@reason-machines/cli-linux-arm64-musl 0.2.327 → 0.2.329
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ara +1 -1
- package/bin/vm-hands/connect-cli-tvqpqf33.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-j47avpaq.js → custom-endpoint-device-8yqvpsd7.js} +1 -1
- package/bin/vm-hands/desktop-account-s4629ksd.js +2 -0
- package/bin/vm-hands/{device-workspace-xnyb7zp2.js → device-workspace-pacdp5tv.js} +1 -1
- package/bin/vm-hands/hands-worker-source-fprvxtp8.js +2 -0
- package/bin/vm-hands/{index-752q9pdp.js → index-wx03jedr.js} +1 -1
- package/bin/vm-hands/local-automation-p0ty82xb.js +2 -0
- package/bin/vm-hands/local-capabilities-qyw7cmjt.js +2 -0
- package/bin/vm-hands/local-desktop-users-ktbva6me.js +2 -0
- package/bin/vm-hands/local-display-mac-kbbrwa0y.js +2 -0
- package/bin/vm-hands/local-display-session-dmdw0q7k.js +2 -0
- package/bin/vm-hands/local-pty-session-bnhx083p.js +2 -0
- package/bin/vm-hands/{network-contract-bv7mj5he.js → network-contract-gb6gk8fg.js} +1 -1
- package/bin/vm-hands/package-bzy9agdv.js +2 -0
- package/bin/vm-hands/permissions-14dvc1rh.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-5zt3ys5t.js → reason-hands-protocol-469gmb0h.js} +1 -1
- package/bin/vm-hands/{status-t6acadsj.js → status-ysdt3ep8.js} +2 -2
- package/bin/vm-hands/version-tsq05aw1.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-7t05ea2h.js → vm-hands-entry-lite-0p3hac9d.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9kasrx18.js → vm-hands-entry-lite-0yghpjef.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ep1me9q3.js → vm-hands-entry-lite-18kr0x4w.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v6tkjqb1.js → vm-hands-entry-lite-40t7d4p5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cxs89wzv.js → vm-hands-entry-lite-5a0kyaxa.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-psybjyay.js → vm-hands-entry-lite-669hk342.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-6g65w75z.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-yhz6sv35.js → vm-hands-entry-lite-8afzattm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n07kxrd1.js → vm-hands-entry-lite-9y8v419y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b2wdaq7x.js → vm-hands-entry-lite-abrbc7gf.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cx4z34jh.js → vm-hands-entry-lite-asr8j2d4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mzxhng4z.js → vm-hands-entry-lite-djy0ww6h.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-14t846kp.js → vm-hands-entry-lite-dyqeaqzb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-472z7kjx.js → vm-hands-entry-lite-henbtxfe.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-22jgncrd.js → vm-hands-entry-lite-jz24p4jj.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cp1wqjs5.js → vm-hands-entry-lite-kbz9zfha.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ne8kkvk4.js → vm-hands-entry-lite-n5ec0fjy.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qvrnx0vk.js → vm-hands-entry-lite-n8gsyjq7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fq0zr7an.js → vm-hands-entry-lite-nj8bmc9y.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-7jmj7peg.js → vm-hands-entry-lite-nwcza0v8.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-xf6schkk.js → vm-hands-entry-lite-pbnx8z9g.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-q5thp2ap.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-93ejmwqn.js → vm-hands-entry-lite-rd9vsaew.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-t497ewn2.js → vm-hands-entry-lite-rnwjp0tk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-wh0qp1gf.js → vm-hands-entry-lite-sggk0bqc.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-tav4dt92.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-fbbd8e32.js → vm-hands-entry-lite-wtk1v493.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-xbe3dat0.js +181 -0
- package/bin/vm-hands/{vm-hands-entry-lite-mgx65dde.js → vm-hands-entry-lite-xjyd9xvx.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/vm-hands-executor-n2w3v0fs.js +10 -0
- package/bin/vm-hands/vm-hands-op-runner-p2q67yw9.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-jnz4rqxa.js +4 -0
- package/bin/vm-hands/worker-sandbox-bqwkytj2.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-44va9379.js +0 -2
- package/bin/vm-hands/desktop-account-emwzhj61.js +0 -2
- package/bin/vm-hands/hands-worker-source-ea5ywzxx.js +0 -2
- package/bin/vm-hands/local-automation-7cypstyv.js +0 -2
- package/bin/vm-hands/local-capabilities-nywse9m3.js +0 -2
- package/bin/vm-hands/local-desktop-users-rn753h90.js +0 -2
- package/bin/vm-hands/local-display-mac-9qqvjs82.js +0 -2
- package/bin/vm-hands/local-display-session-gtk92n5e.js +0 -2
- package/bin/vm-hands/package-xeh4dp97.js +0 -2
- package/bin/vm-hands/permissions-rgfr52fz.js +0 -2
- package/bin/vm-hands/version-rm84p9qv.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-28ta42wn.js +0 -181
- package/bin/vm-hands/vm-hands-entry-lite-rm0jf774.js +0 -5
- package/bin/vm-hands/vm-hands-executor-2pqe40rp.js +0 -10
- package/bin/vm-hands/vm-hands-op-runner-b484wkc9.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-mew62849.js +0 -4
- package/bin/vm-hands/worker-sandbox-yt11b09s.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$a as J7,Ea as i6,Ga as _4,Ha as R4,Ma as t6,Na as e6,Xa as z4,ab as Z7,bb as h4,cb as m4,eb as Q7,ga as C4,gb as Y8,hb as y0,ia as Y2,ib as m0,ja as H4,jb as r1,ka as D4,la as M4,ma as v6,mb as K7,na as u6,oa as A4,pa as d6,pb as F8,qa as T3,qb as E4,ra as l6,sa as s6,sb as B7,ta as c6,ua as n6,va as T4,wa as r6,xa as a6}from"./vm-hands-entry-lite-mgx65dde.js";import{Ab as r0,Bb as a0,Ib as P0,tb as Z4,ub as y6,vb as h6}from"./vm-hands-entry-lite-fq0zr7an.js";import{Jb as V7,Mb as G7,Ob as U7,Pb as X7}from"./vm-hands-entry-lite-93ejmwqn.js";import{Ub as o6}from"./vm-hands-entry-lite-qvrnx0vk.js";import{Vb as k6,Wb as f6,Xb as b6,Yb as x6,Zb as L0}from"./vm-hands-entry-lite-n07kxrd1.js";import{$b as e1,ac as $2,bc as b3,dc as x3,fc as y3,gc as h3,kc as m3,mc as S6}from"./vm-hands-entry-lite-b2wdaq7x.js";import{Fc as i1,Ic as A7,Rc as T7}from"./vm-hands-entry-lite-7t05ea2h.js";import{$d as f8,Ad as I6,Bd as A6,Cd as T6,Dd as _6,Ed as R6,Gd as P6,Hd as z6,Id as E6,Jd as q6,Kd as g6,Pd as A8,Qd as T8,Rd as _8,Sc as w1,Sd as R8,Tc as K2,Td as P8,Uc as V6,Ud as z8,Vc as A3,Wc as $4,Wd as E8,Xc as J4,Xd as q8,Yc as M0,Yd as g8,Zd as S8,_d as k8,ad as N0,ae as b8,be as x8,ce as y8,dd as d,de as h8,ed as g1,hd as I8,jd as S1,ld as G6,md as U6,nd as X6,od as W6,pd as Y6,qd as F6,rd as N6,sd as C6,td as H6,ud as D6,vd as M6,wd as L6,xd as w6,yd as O6,zd as j6}from"./vm-hands-entry-lite-t497ewn2.js";import{ee as V}from"./vm-hands-entry-lite-psybjyay.js";import{Ae as _7,De as Y5,Ee as c1,fe as L7,ge as w7,he as O7,ie as j7,je as I7,pe as r5,te as W5,ue as g5}from"./vm-hands-entry-lite-28ta42wn.js";import{bf as P4,if as $7}from"./vm-hands-entry-lite-wh0qp1gf.js";import{Af as m6,nf as L3}from"./vm-hands-entry-lite-yhz6sv35.js";import{Fg as W7,Gg as Y7,Hg as F7,Ig as N7,Kg as C7,Lg as H7,Ng as D7,Og as M7}from"./vm-hands-entry-lite-22jgncrd.js";import{ah as a1}from"./vm-hands-entry-lite-mzxhng4z.js";import{ch as I1,dh as p6,eh as j4,fh as I4}from"./vm-hands-entry-lite-cp1wqjs5.js";import{hh as M3,jh as J1,ph as W8,qh as G4}from"./vm-hands-entry-lite-ne8kkvk4.js";import{Oh as H}from"./vm-hands-entry-lite-v6tkjqb1.js";import{Uh as J8}from"./vm-hands-entry-lite-cxs89wzv.js";import{request as n7}from"http";import{request as r7}from"https";import{lookup as a7}from"dns/promises";import{isIP as i7}from"net";async function o7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?r7:n7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:x3},(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 v3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),t7=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function p3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(v3.has(Z))return"custom_endpoint_host_not_found";if(t7.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=p3(Q,J+1);if(K)return K}return null}async function e7($,J){let Z=p3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||i7(Q)!==0)return Z;let K;return await Promise.race([a7(Q).then(()=>!0,(G)=>!v3.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function $9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function J9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let N=K[B-1];Y+=Z.copy(W,Y,0,B-N),B=N}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function u3($){$.signal.throwIfAborted();let J=h3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=m3.parse(await $.credential($.signal));if(!y3(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=$9(Q.apiKey),X=J9(Q.apiKey,Y),N=async(F,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let j=()=>{$.signal.removeEventListener("abort",j),M($.signal.reason)};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted){j();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(F,D)}).then(()=>{$.signal.removeEventListener("abort",j),w()},(O)=>{$.signal.removeEventListener("abort",j),M(O)})})},C=async(F)=>{if(G+=F.length,G>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<F.length;D+=e1){if(W>=b3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await N(`custom_endpoint.chunk.${W++}`,{eof:!1,data:F.subarray(D,D+e1).toString("base64")})}};try{let F=await o7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=F.response,B=F.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let j=K.headers[M];if(typeof j==="string")w[M]=j.replaceAll(Q.apiKey,Y).slice(0,4096)}await N("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let j=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=j.length,U>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(j))}return await C(X(Buffer.alloc(0),!0)),await N(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(F){if($.signal.throwIfAborted(),F instanceof H)throw F;throw new H((K?null:await e7(F,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as d3}from"path";function Z9($,J){return $===d3(J,".ara","workspace")||$===d3(J,".reason","workspace")}function l3($,J){let Z=$.filter((Q)=>Z9(Q.path,J));return Z.length===1?Z[0].path:null}var Q9=/^[a-f0-9]{64}$/;var J2=32,K9=/^\/[^\x00-\x1f\x7f\\]*$/;function D1($){if(typeof $!=="string"||$.length>4096||!K9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function M1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!D1(J.home)||!Array.isArray(J.roots)||J.roots.length>J2)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"||!Q9.test(K)||!D1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as V9}from"child_process";import*as q from"fs";import*as r from"path";import{homedir as G9}from"os";function s3($,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 c3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var n3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function Z2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function r3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function a3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function L1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=r3(J).filter((G)=>!K.has(G));for(let G of $){let U=Z2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,N)=>X.offset-N.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((N)=>Z.secretNames?.(N.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:c3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of n3){let N=a3(X,W).find((C)=>!K.has(C[0]));if(N){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:c3(W,N.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function i3($,J=[]){let Z=r3(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 n3)for(let G of a3(B,K))Q.add(G[0])}return[...Q]}function B9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function o3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+B9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,t3=536870912,Q2=/^[a-f0-9]{40}$/,U9=($,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=V9($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(F)=>{if(U??=Error(F),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),N=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(F)=>{if(W)return;W=!0,clearTimeout(N),Z.signal?.removeEventListener("abort",X),Q({status:F,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,F])}),K.stderr.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,F])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(F)=>C(F)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),X9={command:U9,gh:($,J)=>s3(q,r,$,J),home:G9};function A($){throw Error($)}function W9($,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 Y9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),F9=($)=>JSON.stringify($,(J,Z)=>Y9.has(J)?void 0:Z);function e3($,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 Q4($,J,Z=X9){let Q=w1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=q.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=L1([{path:"github-operation",content:F9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)e3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=Z.gh(K,"git"),W=J.privateDirectory?q.realpathSync(J.privateDirectory):q.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+r.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:r.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},N=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{$4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>K2)A("local_device_gh_response_too_large");let y={};for(let i of k[2].split(/\r?\n/)){let e=i.indexOf(":"),D0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await N(["api","graphql","--hostname","github.com","-f",`query=${J4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>K2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await N(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await N(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await N(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let F=q.realpathSync(J.repoPath);if(F!==K&&!F.startsWith(K+r.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+Z4+")")(),j=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+r.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let i=r.join(F,".ara-local-gh-tmp");if(q.mkdirSync(i,{recursive:!0,mode:448}),q.lstatSync(i).isSymbolicLink()||q.realpathSync(i)!==i)A("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(M(F,i),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:F,TMPDIR:i,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(),e.error||e.status!==0)A("local_device_gh_collection_failed");return e.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),g=async(L,T)=>{let P=r.join(L,".ara-local-gh-tmp");if(q.mkdirSync(P,{recursive:!0,mode:448}),q.lstatSync(P).isSymbolicLink()||q.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...j(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(E,["cat-file","--batch"],[...new Set(L)].join(`
|
|
2
|
+
import{Aa as a6,Ha as i6,Ja as _4,Ka as R4,Pa as t6,Qa as e6,_a as z4,cb as J7,db as Z7,eb as h4,fb as m4,hb as Q7,ja as C4,jb as Y8,kb as y0,la as Y2,lb as m0,ma as H4,mb as r1,na as D4,oa as M4,pa as v6,pb as K7,qa as u6,ra as A4,sa as d6,sb as F8,ta as T3,tb as E4,ua as l6,va as s6,vb as B7,wa as c6,xa as n6,ya as T4,za as r6}from"./vm-hands-entry-lite-xjyd9xvx.js";import{Db as r0,Eb as a0,Lb as P0,wb as Z4,xb as y6,yb as h6}from"./vm-hands-entry-lite-nj8bmc9y.js";import{Mb as V7,Pb as G7,Rb as U7,Sb as X7}from"./vm-hands-entry-lite-rd9vsaew.js";import{Xb as o6}from"./vm-hands-entry-lite-n8gsyjq7.js";import{$b as x6,Yb as k6,Zb as f6,_b as b6,ac as L0}from"./vm-hands-entry-lite-9y8v419y.js";import{cc as e1,dc as $2,ec as b3,gc as x3,ic as y3,jc as h3,nc as m3,pc as S6}from"./vm-hands-entry-lite-abrbc7gf.js";import{Ic as i1,Lc as A7,Uc as T7}from"./vm-hands-entry-lite-0p3hac9d.js";import{$c as M0,$d as g8,Ad as w6,Bd as O6,Cd as j6,Dd as I6,Ed as A6,Fd as T6,Gd as _6,Hd as R6,Jd as P6,Kd as z6,Ld as E6,Md as q6,Nd as g6,Sd as A8,Td as T8,Ud as _8,Vc as w1,Vd as R8,Wc as K2,Wd as P8,Xc as V6,Xd as z8,Yc as A3,Zc as $4,Zd as E8,_c as J4,_d as q8,ae as S8,be as k8,ce as f8,dd as N0,de as b8,ee as x8,fe as y8,gd as d,ge as h8,hd as g1,kd as I8,md as S1,od as G6,pd as U6,qd as X6,rd as W6,sd as Y6,td as F6,ud as N6,vd as C6,wd as H6,xd as D6,yd as M6,zd as L6}from"./vm-hands-entry-lite-rnwjp0tk.js";import{he as V}from"./vm-hands-entry-lite-669hk342.js";import{Be as Y5,Ce as c1,ne as r5,re as W5,se as g5,ye as _7}from"./vm-hands-entry-lite-xbe3dat0.js";import{af as W7,bf as Y7,cf as F7,df as N7,ff as C7,gf as H7,if as D7,jf as M7}from"./vm-hands-entry-lite-jz24p4jj.js";import{Af as j7,Df as I7,uf as L7,vf as w7,wf as O7}from"./vm-hands-entry-lite-tav4dt92.js";import{ag as P4,hg as $7}from"./vm-hands-entry-lite-sggk0bqc.js";import{mg as L3,zg as m6}from"./vm-hands-entry-lite-8afzattm.js";import{nh as a1}from"./vm-hands-entry-lite-djy0ww6h.js";import{ph as I1,qh as p6,rh as j4,sh as I4}from"./vm-hands-entry-lite-kbz9zfha.js";import{Ch as W8,Dh as G4,uh as M3,wh as J1}from"./vm-hands-entry-lite-n5ec0fjy.js";import{Wh as H}from"./vm-hands-entry-lite-40t7d4p5.js";import{ai as J8}from"./vm-hands-entry-lite-5a0kyaxa.js";import{request as n7}from"http";import{request as r7}from"https";import{lookup as a7}from"dns/promises";import{isIP as i7}from"net";async function o7($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?r7:n7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:x3},(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 v3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),t7=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function p3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(v3.has(Z))return"custom_endpoint_host_not_found";if(t7.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=p3(Q,J+1);if(K)return K}return null}async function e7($,J){let Z=p3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||i7(Q)!==0)return Z;let K;return await Promise.race([a7(Q).then(()=>!0,(G)=>!v3.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function $9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function J9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+B),Y=0;for(let X of G){while(B&&Z[B]!==X){let N=K[B-1];Y+=Z.copy(W,Y,0,B-N),B=N}if(Z[B]===X){if(B++,B===Z.length)Y+=Q.copy(W,Y),B=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,B),B=0;return W.subarray(0,Y)}}async function u3($){$.signal.throwIfAborted();let J=h3.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=m3.parse(await $.credential($.signal));if(!y3(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=$9(Q.apiKey),X=J9(Q.apiKey,Y),N=async(F,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let j=()=>{$.signal.removeEventListener("abort",j),M($.signal.reason)};if($.signal.addEventListener("abort",j,{once:!0}),$.signal.aborted){j();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(F,D)}).then(()=>{$.signal.removeEventListener("abort",j),w()},(O)=>{$.signal.removeEventListener("abort",j),M(O)})})},C=async(F)=>{if(G+=F.length,G>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<F.length;D+=e1){if(W>=b3)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await N(`custom_endpoint.chunk.${W++}`,{eof:!1,data:F.subarray(D,D+e1).toString("base64")})}};try{let F=await o7({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=F.response,B=F.close;let D=K.statusCode??500;if(D>=300&&D<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let j=K.headers[M];if(typeof j==="string")w[M]=j.replaceAll(Q.apiKey,Y).slice(0,4096)}await N("custom_endpoint.headers",{status:D,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of K){$.signal.throwIfAborted();let j=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=j.length,U>$2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await C(X(j))}return await C(X(Buffer.alloc(0),!0)),await N(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(F){if($.signal.throwIfAborted(),F instanceof H)throw F;throw new H((K?null:await e7(F,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as d3}from"path";function Z9($,J){return $===d3(J,".ara","workspace")||$===d3(J,".reason","workspace")}function l3($,J){let Z=$.filter((Q)=>Z9(Q.path,J));return Z.length===1?Z[0].path:null}var Q9=/^[a-f0-9]{64}$/;var J2=32,K9=/^\/[^\x00-\x1f\x7f\\]*$/;function D1($){if(typeof $!=="string"||$.length>4096||!K9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function M1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!D1(J.home)||!Array.isArray(J.roots)||J.roots.length>J2)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"||!Q9.test(K)||!D1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}import{spawn as V9}from"child_process";import*as q from"fs";import*as r from"path";import{homedir as G9}from"os";function s3($,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 c3($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var n3=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function Z2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function r3($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function a3($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function L1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=r3(J).filter((G)=>!K.has(G));for(let G of $){let U=Z2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let W=G.content??"",Y=B.map((X)=>({secret:X,offset:W.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,N)=>X.offset-N.offset);if(Y.length>0){let X=[...new Set(Y.flatMap((N)=>Z.secretNames?.(N.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:c3(W,Y[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of n3){let N=a3(X,W).find((C)=>!K.has(C[0]));if(N){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:c3(W,N.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function i3($,J=[]){let Z=r3(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 n3)for(let G of a3(B,K))Q.add(G[0])}return[...Q]}function B9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function o3($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+B9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,t3=536870912,Q2=/^[a-f0-9]{40}$/,U9=($,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=V9($,J,{cwd:Z.cwd,env:Z.env,detached:!0,stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,W=!1,Y=(F)=>{if(U??=Error(F),K.pid)try{process.kill(-K.pid,"SIGKILL")}catch{}},X=()=>Y("cancelled"),N=setTimeout(()=>Y("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let C=(F)=>{if(W)return;W=!0,clearTimeout(N),Z.signal?.removeEventListener("abort",X),Q({status:F,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else B=Buffer.concat([B,F])}),K.stderr.on("data",(F)=>{if(B.length+G.length+F.length>Z.maxBuffer)Y("output_limit");else G=Buffer.concat([G,F])}),K.on("error",()=>{if(Y("spawn_failed"),!K.pid)C(null)}),K.on("close",(F)=>C(F)),K.stdin.on("error",()=>Y("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),X9={command:U9,gh:($,J)=>s3(q,r,$,J),home:G9};function A($){throw Error($)}function W9($,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 Y9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),F9=($)=>JSON.stringify($,(J,Z)=>Y9.has(J)?void 0:Z);function e3($,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 Q4($,J,Z=X9){let Q=w1.parse($);if(!["darwin","linux"].includes(process.platform))A("local_device_gh_platform_unavailable");J.assertCurrent();let K=q.realpathSync(J.root);if(K==="/")A("local_device_gh_root_unavailable");if(!M0(Q)&&!J.forbiddenSecretValues)A("local_device_gh_secret_scope_unavailable");if(!M0(Q)&&J.readOnly)A("local_device_gh_read_only");if(!M0(Q)){let L=L1([{path:"github-operation",content:F9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)e3(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let B=Z.gh(K),G=Z.home(),U=Z.gh(K,"git"),W=J.privateDirectory?q.realpathSync(J.privateDirectory):q.realpathSync(G);if(!M0(Q)&&(!J.privateDirectory||W===K||W.startsWith(K+r.sep)))A("local_device_gh_private_scope_unavailable");let Y={PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:G,GH_CONFIG_DIR:r.join(G,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},X=async(L,T,P=W,k,x=T0)=>{J.assertCurrent();let y=await Z.command(L,T,{cwd:P,env:Y,input:k,maxBuffer:x,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),y.error||y.status!==0)A("local_device_gh_command_failed");return y.stdout},N=async(L)=>(await X(B,L)).toString("utf8").trim(),C=async(L,T="application/vnd.github+json")=>{$4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let P=await Z.command(B,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:W,env:Y,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),P.error&&P.status===null)A("local_device_gh_response_unavailable");let k=P.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!k)A("local_device_gh_response_invalid");let x=Number(k[1]);if(x>=200&&x<300&&P.status!==0)A("local_device_gh_response_unavailable");if(Buffer.byteLength(k[3])>K2)A("local_device_gh_response_too_large");let y={};for(let i of k[2].split(/\r?\n/)){let e=i.indexOf(":"),D0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(D0))y[D0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:x,headers:y,body:x>=200&&x<300?k[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return C(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),P=await N(["api","graphql","--hostname","github.com","-f",`query=${J4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(P)>K2)A("local_device_gh_response_too_large");let k=JSON.parse(P);if(k.errors||k.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||k.data.repository.pullRequest?.number!==Q.number)A("local_device_gh_response_invalid");return{kind:"pr_review_context",body:P}}if(Q.kind==="pr_merge"){let L=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),P=(y)=>y.number===Q.number&&y.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&y.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&y.base?.ref===Q.expectedBaseRef&&y.head?.sha===Q.expectedHeadSha;if(L.status!==200||!P(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())A("local_device_gh_merge_target_changed");await N(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let k=await C(`/repos/${Q.repoFullName}/pulls/${Q.number}`),x=JSON.parse(k.body);if(k.status!==200||!P(x)||x.merged!==!0)A("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)A("local_device_gh_default_branch");let L=await N(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))A("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await N(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)A("local_device_gh_workspace_unavailable");let F=q.realpathSync(J.repoPath);if(F!==K&&!F.startsWith(K+r.sep))A("local_device_gh_workspace_unavailable");let D=`https://github.com/${Q.repoFullName}.git`,w="!'"+B.replace(/'/g,"'\\''")+"' auth git-credential",M=Function("return ("+Z4+")")(),j=(L,T,P)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...P]]:[T,P],O=async(L,T,P,k=T0)=>{let x=L===W||L.startsWith(W+r.sep),y=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...x?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(x)return X(U,y,L,P,k);let i=r.join(F,".ara-local-gh-tmp");if(q.mkdirSync(i,{recursive:!0,mode:448}),q.lstatSync(i).isSymbolicLink()||q.realpathSync(i)!==i)A("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(M(F,i),U,y),{cwd:L,input:P,maxBuffer:k,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:F,TMPDIR:i,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(),e.error||e.status!==0)A("local_device_gh_collection_failed");return e.stdout},R=async(L,T)=>(await O(L,T)).toString("utf8").trim(),g=async(L,T)=>{let P=r.join(L,".ara-local-gh-tmp");if(q.mkdirSync(P,{recursive:!0,mode:448}),q.lstatSync(P).isSymbolicLink()||q.realpathSync(P)!==P)A("local_device_gh_workspace_unavailable");J.assertCurrent();let k=await Z.command(...j(M(L,P),"/bin/sh",["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{PATH:"/usr/bin:/bin:/usr/sbin:/sbin",HOME:L,TMPDIR:P}});if(J.assertCurrent(),k.error||k.status!==0)A("local_device_gh_materialization_failed")},v=async(L)=>{let T=new Map;if(L.length===0)return T;let P=await O(E,["cat-file","--batch"],[...new Set(L)].join(`
|
|
3
3
|
`)+`
|
|
4
4
|
`,T0*8);for(let k=0;k<P.length;){let x=P.indexOf(10,k),[y,i,e]=P.subarray(k,x).toString("utf8").split(" ");if(x<0||!y||i!=="blob"||!/^[0-9]+$/.test(e??""))A("local_device_gh_object_invalid");T.set(y,P.subarray(x+1,x+1+Number(e)).toString("utf8")),k=x+1+Number(e)+1}return T},I=async(L,T,P)=>{let k=r.join(F,".ara-local-gh-tmp"),x=M(F,k)+`
|
|
5
5
|
(allow file-read* file-write* (subpath ${JSON.stringify(F)}))
|
|
@@ -23,7 +23,7 @@ Content-Length: 0\r
|
|
|
23
23
|
\r
|
|
24
24
|
`),x4(W,F,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{B.once("error",W),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as j2,randomUUID as n9}from"crypto";import{closeSync as e0,constants as s,fchownSync as r9,fstatSync as z0,fsyncSync as a9,linkSync as i9,mkdirSync as o9,openSync as Z8,readSync as Q8,unlinkSync as t9,writeSync as e9}from"fs";import{platform as e4}from"os";import{getSystemErrorName as $$}from"util";var u4={type:"string",format:"uuid"},c4=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,T1={type:"string",minLength:1,maxLength:4096,pattern:c4},D2=V.string().min(1).max(4096).regex(new RegExp(c4)),_1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},R1={device_id:u4,root_id:u4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},oK={read:{schema:V.object({..._1,path:D2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...R1,path:T1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({..._1,path:D2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...R1,path:T1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({..._1,command:V.string().min(1).max(16000),cwd:D2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...R1,command:{type:"string",minLength:1,maxLength:16000},cwd:T1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},W0=1073741824,o0=600000,d4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,n4=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${d4}(?:/${d4})*(?![\s\S])`,r4=new RegExp(n4);function a4($){return typeof $==="string"&&$.length>0&&$.length<=4096&&r4.test($)}var M2=V.string().min(1).max(4096).regex(r4),L2={...T1,pattern:n4},i4=V.string().regex(/^[a-f0-9]{64}$/),o4=V.object({kind:V.literal("workspace"),path:M2}).strict(),l9=V.discriminatedUnion("kind",[o4,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:i4}).strict()]),P1=1,t0="cloud_workspace_id",w2="cloud_workspace",O2=1,s9=V.discriminatedUnion("kind",[o4,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(W0),sha256:i4}).strict()]),t4=V.object({source_version:V.literal(P1),source:s9,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[t0]:V.string().min(1).max(160).optional()}).strict(),tK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(P1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var l4=V.object({..._1,timeout_ms:V.number().int().min(1000).max(o0).optional(),source_path:M2,destination_path:M2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),s4={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...R1,timeout_ms:{type:"integer",minimum:1000,maximum:o0},source_path:L2,destination_path:L2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},c9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:L2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},eK=V.union([l4,l4.omit({source_path:!0}).extend({source:l9}).strict()]),$B={...s4,required:["device_id","root_id","destination_path"],properties:{...s4.properties,source:c9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var I2=65536;function u($){throw new H($,$)}function E1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function z1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function J$($,J,Z){let Q;switch(E1($)){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 z1($,J,Q)}function Z$($){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 Q$(){if(e4()==="linux")return{open:(U,W,Y,X=384)=>Z8(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>o9(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>i9(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>t9(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(e4()!=="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=$$(-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 K8($,J){let Z=z0($),Q=z0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)r9(J,Z.uid,Z.gid)}function K$($,J,Z,Q){if(!a4(Z))return u("transfer_path_invalid");let K=Z.split("/"),B=Z8(J,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW);try{for(let G of K.slice(0,-1)){let U;try{U=$.open(B,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW)}catch(W){if(!Q||E1(W)!=="ENOENT")throw W;try{$.mkdir(B,G)}catch(Y){if(E1(Y)!=="EEXIST")throw Y}U=$.open(B,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW),K8(B,U)}e0(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw e0(B),G}}function $8($,J){let Z=z0($,{bigint:!0});if(!Z.isFile()||Z.size>W0)return u("transfer_file_invalid");let Q=j2("sha256"),K=Buffer.alloc(I2),B=0;while(!0){J.throwIfAborted();let U=Q8($,K,0,K.length,B);if(!U)break;if(B+=U,B>W0)return u("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=z0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=Z$($.payload.url),Z=await Q$(),Q,K,B;try{if(Q=K$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);let C=z0(K,{bigint:!0});if(!C.isFile()||C.size>W0)return u("transfer_file_invalid");let F=j2("sha256"),D=0,w=K,M,j=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let I=Buffer.alloc(I2),z=Q8(w,I,0,I.length,D);if(!z){v.close();return}if(D+=z,D>C.size)return u("transfer_source_changed");F.update(I.subarray(0,z)),v.enqueue(I.subarray(0,z))}catch(I){throw M=I,I}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:j,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(C.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return z1(v,$.signal,"transfer_upload_failed")}let O=z0(K,{bigint:!0});if(BigInt(D)!==C.size||O.size!==C.size||O.mtimeNs!==C.mtimeNs||O.ctimeNs!==C.ctimeNs)return u("transfer_source_changed");let R=F.digest("hex"),g=$8(K,$.signal);if(g.size_bytes!==D||g.sha256!==R)return u("transfer_source_changed");return{size_bytes:D,sha256:R,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>W0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK)}catch(C){if(E1(C)!=="ENOENT")throw C}if(W!==void 0){try{let C=$8(W,$.signal);if(C.size_bytes===G&&C.sha256===U)return{...C,outcome:"already_present"}}finally{e0(W)}return u("transfer_destination_exists")}B=`.reason-copy-${n9()}`,K=Z.open(Q.fd,B,s.O_CREAT|s.O_EXCL|s.O_WRONLY|s.O_NOFOLLOW,384),K8(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 z1(C,$.signal,"transfer_download_failed")}let X=j2("sha256"),N=0;try{while(!0){$.signal.throwIfAborted();let C=await Y.read().catch((F)=>z1(F,$.signal,"transfer_download_failed"));if(C.done)break;if(N+=C.value.length,N>G)return u("transfer_size_mismatch");X.update(C.value);for(let F=0;F<C.value.length;)$.signal.throwIfAborted(),F+=e9(K,C.value,F,Math.min(I2,C.value.length-F))}}finally{await Y.cancel().catch(()=>{})}if(N!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return a9(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)e0(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}e0(Q.fd)}}finally{Z.close()}}}}catch(J){return J$(J,$.signal,$.direction)}}import{spawn as V$}from"child_process";import{mkdtempSync as G$,rmSync as U$,writeFileSync as X$}from"fs";import{constants as W$,platform as Y$,tmpdir as F$}from"os";import{join as U8}from"path";import{gunzipSync as B$,gzipSync as WB}from"zlib";var V8=900000,FB=V8+60000,$1=49152,B8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),G8=V.object({version:V.literal(1),script_gzip:B8(163840),stdin_gzip:B8(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(V8)}).strict(),A2=V.string().max($1+256),NB=V.object({exit_code:V.number().int().min(0).max(255),stdout:A2,stderr:A2,combined:A2.optional()}).strict();function T2($){return B$(Buffer.from($,"base64")).toString("utf8")}var N$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",C$=["RUSTUP_HOME","TZ","LC_ALL"],H$=2000,D$=100;function R2(){return Y$()==="linux"&&process.geteuid?.()===0}function _2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
|
|
25
25
|
[reason: ${G} bytes of output omitted]
|
|
26
|
-
`:"")+K.toString("utf8")}}}async function X8($,J){if(!R2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=G8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=T2(Q.script_gzip),B=T2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=G$(U8(F$(),"reason-workspace-setup-"));try{let U=U8(G,"setup.sh");X$(U,K,{mode:384});let W={PATH:N$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let g of C$)if(process.env[g])W[g]=process.env[g];Object.assign(W,Q.env);let Y=V$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=_2($1),N=_2($1),C=_2($1);Y.stdout.on("data",(g)=>{X.push(g),C.push(g)}),Y.stderr.on("data",(g)=>{N.push(g),C.push(g)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let F=(g)=>{try{if(Y.pid)process.kill(-Y.pid,g)}catch{}},D=!1,w,M=()=>{F("SIGTERM"),w??=setTimeout(()=>F("SIGKILL"),H$)},j=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((g,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(I,z)=>g({code:I,signal:z}))}).finally(()=>{clearTimeout(j),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((g)=>{let v=setTimeout(g,D$);Y.once("close",()=>{clearTimeout(v),g()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let R=D?124:O.signal?128+(W$.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,R),stdout:X.text(),stderr:N.text(),...R!==0?{combined:C.text()}:{}}}finally{U$(G,{recursive:!0,force:!0})}}import{chmodSync as M$,mkdtempSync as L$,realpathSync as N8,rmSync as w$}from"fs";import{tmpdir as O$}from"os";import{dirname as j$,join as P2,sep as I$}from"path";function z2($){return F8($,Y8($)!==null).repoPath}function C8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[J1,void 0].map((K)=>j$(W8({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=N8(P2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${I$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function H8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=z2($.runtimeRoot);if(L0(Q)||L0(P2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=L$(P2(O$(),`reason-cloud-copy-${process.pid}-`));try{M$(Z,448);let Q=N8(Z);await E0({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 E0({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{w$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as R7,existsSync as G0,fstatSync as P7,lstatSync as z7,mkdirSync as $Q,mkdtempSync as E7,openSync as q7,readSync as JQ,realpathSync as J0,rmSync as g7,statSync as C1,writeSync as ZQ}from"fs";import{homedir as Y1,platform as l,tmpdir as S7}from"os";import{dirname as F1,isAbsolute as QQ,join as _3,relative as w3,resolve as KQ,sep as BQ}from"path";import{spawn as VQ}from"child_process";import{createHash as P$,randomBytes as z$}from"crypto";var E2=30000,A$=1800000,T$=5000,q1=30000,_$=S1+15000,D8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,R$=[/^\/app\/local-runtime\/operations\/claim$/,D8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(R$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},_$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(T$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(A$,E2*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(g1,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()+E2;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(!D8.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(E2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var S2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function mB($,J={}){let Z=E$($),Q=J.rootPathsSupported===!0?M1($.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 E$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class k1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function q$($){return $===408||$===429||$===500||$===502||$===503||$===504}function g$($){if($ instanceof Y0)return!1;if($ instanceof k1)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 S$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function k$($,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 vB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function M8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function L8($){return P$("sha256").update($??"").digest("hex")}function f$($){return A8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function w8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var b$=20000,x$=1e4,O8=[2000,4000],y$=30000,h$=15000;function j8($){return $?{keepalive:!1}:{}}class g2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class m${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}=T8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??O8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof g2))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new g2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...j8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return _8(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>=b$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,O8[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)()>=x$?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=L8(J),N=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":N.timestamp,"x-device-nonce":N.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":N.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>z$(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(f$({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||!I8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",g1,Q,L8("")),...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&&M8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??k$,W=this.sessionFor($,J.device),Y=Math.max(y$,(J.holdMs??0)+h$),X={fresh:!1},N;for(let C=0;C<G;C+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new k1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let j=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,M,J.useSpareChallenge===!0&&C===0,C===0?J.issuedChallenge:void 0,X),O=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...j,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...j8(X.fresh),signal:M});return await this.parseResponse(O)}catch(j){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw j}finally{clearTimeout(w)}}catch(F){if(N=F,F instanceof k1)X.fresh=!0;if(J.signal?.aborted)throw F;let D=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),w=F instanceof Y0&&q$(F.status),M=g$(F),j=J.transientRetryOwner!=="caller"&&(w||M);if((D||j)&&C+1<G){let O=D?0:S$(C,F,this.proofOptions.retryBaseDelayMs??500);if(O>0)await U(O,J.signal);continue}if(D&&C+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw N??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return R8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return P8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return z8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return E8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return q8(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 g8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});k8(Q)}async localSubscription($,J,Z){return S8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!w8(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,S1))},signal:J.signal});if(B===null)return null;return f8(B,S2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return b8(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)||!w8(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 x8(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(M8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return h8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-j47avpaq.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 y8(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 v$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),Z1=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 f1($,J){if(v$.has($))return!1;if(Z1.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($)||Z1.has($)))return!1;return!0}import{accessSync as p$,constants as u$,existsSync as d$,statSync as l$}from"fs";import{basename as s$,isAbsolute as c$}from"path";var Q1=["-lic"],n$="/bin/zsh",r$=new Set(["zsh","bash"]),m8=20000,k2=60000,a$=65536,i$=64,o$=8192,t$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),e$=["DYLD_","LD_"];function $J($){let J=$.toUpperCase();return t$.has(J)||e$.some((Z)=>J.startsWith(Z))}function v8($=process.env){return!0}function JJ($){if(!c$($)||$.includes("\x00"))return!1;if(!r$.has(s$($)))return!1;try{if(!l$($).isFile())return!1;return p$($,u$.X_OK),!0}catch{return!1}}function q0($=process.env){let J=$.SHELL?.trim();if(J&&JJ(J))return J;return n$}function f2($=process.env){return v8($)&&d$(q0($))}function b2($=process.env){if(!v8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function x2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>a$)throw new H("invalid_payload","command is missing or too large.");return $}function y2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>i$)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")>o$)throw new H("invalid_payload","env entry is invalid or too large.");if($J(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function p8($){let J=$.processEnv??process.env;if(b2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=x2($.command),Q=q0(J),{forwarded:K,ignored:B}=y2($.requestEnv),G=await $.spawn(Q,[...Q1,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:[...Q1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function u8($=process.env){return{transport:"shell",shell:`${q0($)} ${Q1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:k2}}import{readFile as ZJ,readdir as QJ,readlink as KJ,realpath as BJ}from"fs/promises";import{basename as VJ,relative as GJ,sep as UJ}from"path";var w0="/proc",XJ=250,d8=500,WJ=50,YJ=250,FJ=1024,l8=4096,NJ=1,CJ=3,s8=9,HJ="0A",DJ=/^socket:\[(\d+)\]$/,h2={readDirectory:($)=>QJ($),readLink:($)=>KJ($),readTextFile:($)=>ZJ($,"utf8"),realPath:($)=>BJ($)};function n8($,J){return J===$||J.startsWith(`${$}${UJ}`)}function MJ($,J){return GJ($,J)||"."}async function r8($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function a8($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,l8).split(`
|
|
26
|
+
`:"")+K.toString("utf8")}}}async function X8($,J){if(!R2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=G8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=T2(Q.script_gzip),B=T2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=G$(U8(F$(),"reason-workspace-setup-"));try{let U=U8(G,"setup.sh");X$(U,K,{mode:384});let W={PATH:N$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let g of C$)if(process.env[g])W[g]=process.env[g];Object.assign(W,Q.env);let Y=V$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=_2($1),N=_2($1),C=_2($1);Y.stdout.on("data",(g)=>{X.push(g),C.push(g)}),Y.stderr.on("data",(g)=>{N.push(g),C.push(g)}),Y.stdin.on("error",()=>{}),Y.stdin.end(B);let F=(g)=>{try{if(Y.pid)process.kill(-Y.pid,g)}catch{}},D=!1,w,M=()=>{F("SIGTERM"),w??=setTimeout(()=>F("SIGKILL"),H$)},j=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let O=await new Promise((g,v)=>{Y.once("error",()=>v(new H("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(I,z)=>g({code:I,signal:z}))}).finally(()=>{clearTimeout(j),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((g)=>{let v=setTimeout(g,D$);Y.once("close",()=>{clearTimeout(v),g()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let R=D?124:O.signal?128+(W$.signals[O.signal]??0):O.code??1;return{exit_code:Math.min(255,R),stdout:X.text(),stderr:N.text(),...R!==0?{combined:C.text()}:{}}}finally{U$(G,{recursive:!0,force:!0})}}import{chmodSync as M$,mkdtempSync as L$,realpathSync as N8,rmSync as w$}from"fs";import{tmpdir as O$}from"os";import{dirname as j$,join as P2,sep as I$}from"path";function z2($){return F8($,Y8($)!==null).repoPath}function C8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[J1,void 0].map((K)=>j$(W8({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=N8(P2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${I$}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function H8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=z2($.runtimeRoot);if(L0(Q)||L0(P2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=L$(P2(O$(),`reason-cloud-copy-${process.pid}-`));try{M$(Z,448);let Q=N8(Z);await E0({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 E0({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{w$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as R7,existsSync as G0,fstatSync as P7,lstatSync as z7,mkdirSync as $Q,mkdtempSync as E7,openSync as q7,readSync as JQ,realpathSync as J0,rmSync as g7,statSync as C1,writeSync as ZQ}from"fs";import{homedir as Y1,platform as l,tmpdir as S7}from"os";import{dirname as F1,isAbsolute as QQ,join as _3,relative as w3,resolve as KQ,sep as BQ}from"path";import{spawn as VQ}from"child_process";import{createHash as P$,randomBytes as z$}from"crypto";var E2=30000,A$=1800000,T$=5000,q1=30000,_$=S1+15000,D8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,R$=[/^\/app\/local-runtime\/operations\/claim$/,D8];class q2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((W)=>Q.pending.set(K,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(R$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},_$);else{let W=()=>{if(!Q.pending.has(K))return;let Y=this.now()-Q.lastFrameAt;if(Y>=q1)this.drop(Q);else G=setTimeout(W,q1-Y)};G=setTimeout(W,q1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>q1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(T$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(A$,E2*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(g1,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()+E2;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(!D8.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(E2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var S2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function mB($,J={}){let Z=E$($),Q=J.rootPathsSupported===!0?M1($.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 E$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class Y0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class k1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function q$($){return $===408||$===429||$===500||$===502||$===503||$===504}function g$($){if($ instanceof Y0)return!1;if($ instanceof k1)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 S$($,J,Z=500){if(J instanceof Y0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function k$($,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 vB($){return $ instanceof Y0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function M8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function L8($){return P$("sha256").update($??"").digest("hex")}function f$($){return A8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function w8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var b$=20000,x$=1e4,O8=[2000,4000],y$=30000,h$=15000;function j8($){return $?{keepalive:!1}:{}}class g2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class m${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}=T8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new Y0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??O8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof g2))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new g2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...j8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return _8(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>=b$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,O8[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)()>=x$?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=L8(J),N=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":N.timestamp,"x-device-nonce":N.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":N.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>z$(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(f$({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||!I8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new q2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",g1,Q,L8("")),...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&&M8(J.body)>N0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??k$,W=this.sessionFor($,J.device),Y=Math.max(y$,(J.holdMs??0)+h$),X={fresh:!1},N;for(let C=0;C<G;C+=1)try{let F=await W?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(F)return await this.parseResponse(new Response(F.status===204?null:F.body,{status:F.status,headers:F.retryAfter===null?{}:{"retry-after":F.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new k1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let j=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,M,J.useSpareChallenge===!0&&C===0,C===0?J.issuedChallenge:void 0,X),O=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...j,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...j8(X.fresh),signal:M});return await this.parseResponse(O)}catch(j){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw j}finally{clearTimeout(w)}}catch(F){if(N=F,F instanceof k1)X.fresh=!0;if(J.signal?.aborted)throw F;let D=J.device!==void 0&&F instanceof Y0&&F.status===401&&["invalid_device_proof","device_proof_replayed"].includes(F.code),w=F instanceof Y0&&q$(F.status),M=g$(F),j=J.transientRetryOwner!=="caller"&&(w||M);if((D||j)&&C+1<G){let O=D?0:S$(C,F,this.proofOptions.retryBaseDelayMs??500);if(O>0)await U(O,J.signal);continue}if(D&&C+1>=G)throw Error("Reason Device proof retry was exhausted.");throw F}throw N??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return R8(Q)}async enroll($,J,Z,Q){let K=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return P8(K)}async heartbeat($,J,Z,Q){let K=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return z8(K)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return E8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return q8(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 g8(K)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});k8(Q)}async localSubscription($,J,Z){return S8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof Y0&&K.status===404)return null;throw K});if(Q===null)return null;if(!w8(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,S1))},signal:J.signal});if(B===null)return null;return f8(B,S2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof Y0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return b8(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)||!w8(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 x8(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(M8(K)>N0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return h8(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-8yqvpsd7.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 y8(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 v$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),Z1=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 f1($,J){if(v$.has($))return!1;if(Z1.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($)||Z1.has($)))return!1;return!0}import{accessSync as p$,constants as u$,existsSync as d$,statSync as l$}from"fs";import{basename as s$,isAbsolute as c$}from"path";var Q1=["-lic"],n$="/bin/zsh",r$=new Set(["zsh","bash"]),m8=20000,k2=60000,a$=65536,i$=64,o$=8192,t$=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),e$=["DYLD_","LD_"];function $J($){let J=$.toUpperCase();return t$.has(J)||e$.some((Z)=>J.startsWith(Z))}function v8($=process.env){return!0}function JJ($){if(!c$($)||$.includes("\x00"))return!1;if(!r$.has(s$($)))return!1;try{if(!l$($).isFile())return!1;return p$($,u$.X_OK),!0}catch{return!1}}function q0($=process.env){let J=$.SHELL?.trim();if(J&&JJ(J))return J;return n$}function f2($=process.env){return v8($)&&d$(q0($))}function b2($=process.env){if(!v8($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function x2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>a$)throw new H("invalid_payload","command is missing or too large.");return $}function y2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>i$)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")>o$)throw new H("invalid_payload","env entry is invalid or too large.");if($J(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function p8($){let J=$.processEnv??process.env;if(b2(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=x2($.command),Q=q0(J),{forwarded:K,ignored:B}=y2($.requestEnv),G=await $.spawn(Q,[...Q1,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:[...Q1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function u8($=process.env){return{transport:"shell",shell:`${q0($)} ${Q1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:k2}}import{readFile as ZJ,readdir as QJ,readlink as KJ,realpath as BJ}from"fs/promises";import{basename as VJ,relative as GJ,sep as UJ}from"path";var w0="/proc",XJ=250,d8=500,WJ=50,YJ=250,FJ=1024,l8=4096,NJ=1,CJ=3,s8=9,HJ="0A",DJ=/^socket:\[(\d+)\]$/,h2={readDirectory:($)=>QJ($),readLink:($)=>KJ($),readTextFile:($)=>ZJ($,"utf8"),realPath:($)=>BJ($)};function n8($,J){return J===$||J.startsWith(`${$}${UJ}`)}function MJ($,J){return GJ($,J)||"."}async function r8($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function a8($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,l8).split(`
|
|
27
27
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${w0}/${$}/cmdline`)).slice(0,l8).split("\x00",1)[0]?.trim();return Q?VJ(Q):null}catch{return null}}async function i8($,J=h2){let Z;try{Z=await J.readLink(`${w0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function o8($,J=h2){let Z=[];for(let Q of await r8(J)){if(Z.length>=XJ)break;let K=await i8(Q,J);if(!K||!n8($,K))continue;Z.push({pid:Q,command:await a8(Q,J),cwd:MJ($,K)})}return{processes:Z}}function c8($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function LJ($){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 wJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=c8($);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(...c8($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${LJ(Z)}]:${J}`}return null}function OJ($,J){let Z=[];for(let Q of $.split(`
|
|
28
28
|
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=s8)continue;if(K[CJ]?.toUpperCase()!==HJ)continue;let B=K[NJ]??"",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=wJ(B.slice(0,G),U),Y=K[s8];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function jJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=d8)break;let Q;try{Q=await $.readTextFile(`${w0}/net/${Z}`)}catch{continue}J.push(...OJ(Q,d8-J.length))}return J}async function IJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await r8(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${w0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,FJ)){let G;try{G=await J.readLink(`${w0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(DJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function t8($,J=h2){let Z=await jJ(J),Q=await IJ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let N=Q.get(X.inode);if(N===void 0)continue;K.push({pid:N,port:X.port,address:X.address})}K.sort((X,N)=>X.pid-N.pid||X.port-N.port||(X.address<N.address?-1:X.address>N.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,WJ),G=await Promise.all(B.map(async(X)=>[X,await i8(X,J)])),U=new Map(G),W=K.filter((X)=>{let N=U.get(X.pid);return Boolean(N&&n8($,N))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await a8(X,J)])));return{ports:W.slice(0,YJ).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as v2}from"path";var b1=200,AJ=250,TJ=250;async function x1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function m2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var e8="/System/Volumes/Data",_J=["/tmp","/var","/etc"];function p2($){let J=v2.normalize($);if(J.startsWith(`${e8}/`))J=J.slice(e8.length);return _J.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function $5($){return $&&v2.isAbsolute($)?p2($):null}async function J5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=b1){let K=J.slice(Q,Q+b1).join(",");for(let B of await x1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:$5(B.names[0])})}return Z}async function Z5($,J){let Z=p2($),Q=(await x1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=$5(B.names[0]);return G!==null&&m2(Z,G)}).map((B)=>B.pid).slice(0,AJ),K=await J5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&m2(Z,G.cwd)?[{pid:B,command:G.command,cwd:v2.relative(Z,G.cwd)||"."}]:[]})}}async function Q5($,J){let Z=p2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await x1(J,Q),B=await J5(J,K.map((Y)=>Y.pid)),G=K.map((Y)=>Y.pid).filter((Y)=>{let X=B.get(Y)?.cwd;return Boolean(X&&m2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=b1){let X=G.slice(Y,Y+b1).join(",");for(let N of await x1(J,["-a","-p",X,...Q]))for(let C of N.names)if(U.has(`${N.pid} ${C}`))W.push({pid:N.pid,command:N.command,address:C})}return{ports:W.slice(0,TJ)}}import{join as hJ}from"path";import{spawn as SJ}from"child_process";import{randomUUID as kJ}from"crypto";import{chmodSync as V5,lstatSync as G5,mkdirSync as fJ,readdirSync as bJ,statSync as xJ,unlinkSync as yJ}from"fs";import{join as d2}from"path";function K1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}var u2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var y1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var O0=()=>{throw Error("proof_visual_contract_invalid")};class K5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function PJ($){if(!K1($)||$.version!==1)return O0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new K5;if(!K1($.viewport)||!y1($.viewport.width,1,4096)||!y1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>u2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return O0();let J=$.targets.map((Q)=>{if(!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((K)=>!["id","selector"].includes(K)))return O0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return O0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return O0();Z=$.additionalViewports.map((K)=>{if(!K1(K)||!y1(K.width,1,4096)||!Number.isInteger(K.width)||!y1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return O0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return O0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var EJ=["organizationId","userId","sessionId","runId"],qJ=[...EJ,"prUrl","headSha","skillDigest","evidenceKind"],VV=[...qJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var gJ={"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 B5($){return gJ[$].directory}var U5=10485760;function X5($={}){let J=$.directory??B5("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");fJ(J,{recursive:!0,mode:457});let B=G5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");V5(J,457);let G=bJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:xJ(d2(J,M)).mtimeMs})).sort((M,j)=>j.time-M.time);for(let M of G.slice(9))yJ(d2(J,M.name));let U=d2(J,`${kJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??SJ)($.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(U5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,N,C=!1,F=new Promise((M,j)=>{X=M,N=j});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))C=!0,X()});let D=new Promise((M,j)=>{Y.once("error",()=>{N(Error("cloud_browser_recording_unavailable")),j(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(O)=>{try{if(O!==0&&O!==255)throw Error();let R=G5(U);if(!C||!R.isFile()||R.isSymbolicLink()||R.uid!==process.getuid?.()||R.size<128||R.size>U5+65536)throw Error();V5(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{N(Error("cloud_browser_recording_failed")),j(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(K)+5)*1000);D.finally(()=>clearTimeout(w)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await F}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function F5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??W5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=hJ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??Y5)();return B??=X5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:I1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as U3}from"child_process";import{createHash as $Z,randomUUID as JZ}from"crypto";import{existsSync as Q0,mkdirSync as Q3,mkdtempSync as X3,readdirSync as s1,readFileSync as W3,renameSync as ZZ,rmSync as G1,statSync as p1,writeFileSync as QZ}from"fs";import{homedir as Y3,tmpdir as S5}from"os";import{basename as k5,dirname as K3,join as S,relative as f5,resolve as B3,sep as b5}from"path";var a=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),h1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),N5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),s2=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),c2=["home","lock","side_button","siri","apple_pay"],mJ=V.enum(["tree","screenshot","both","none"]),vJ=V.object({...s2.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:mJ.optional(),wait_for:vJ.optional(),timeout:V.number().min(0).max(20).optional()},l2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...s2.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(c2)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),n2=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:a}).strict(),V.object({action:V.literal("shutdown"),device:a}).strict(),V.object({action:V.literal("build"),path:h1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:h1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),steps:V.array(V.lazy(()=>l2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:a.optional(),app_path:h1.optional(),bundle_id:N5.optional(),steps:V.array(V.lazy(()=>l2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:a.optional(),bundle_id:N5}).strict(),V.object({action:V.literal("logs"),device:a.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:a.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:h1.optional()}).strict(),V.object({action:V.literal("chrome"),device:a.optional()}).strict(),V.object({action:V.literal("inspect"),device:a.optional()}).strict(),V.object({action:V.literal("tap"),device:a.optional(),x:Z0.optional(),y:Z0.optional(),...s2.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:a.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:a.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:a.optional(),name:V.enum(c2),...C0}).strict(),V.object({action:V.literal("open_url"),device:a.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:a.optional(),steps:V.array(l2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:a.optional(),mode:V.enum(["light","dark"])}).strict()]),C5=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(),_V=V.object({text:V.string(),error:V.string().optional(),device:C5.optional(),devices:V.array(C5).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 RV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),PV={type:"object",properties:{action:{type:"string",enum:n2.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...c2]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as o2}from"child_process";import{createHash as uJ}from"crypto";import{existsSync as a2,mkdirSync as m1,mkdtempSync as dJ,readdirSync as H5,readFileSync as D5,renameSync as lJ,rmSync as M5,symlinkSync as i2,writeFileSync as B1}from"fs";import{homedir as sJ}from"os";import{dirname as j5,join as b}from"path";import{createInterface as cJ}from"readline";var r2=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
29
29
|
//
|
|
@@ -526,4 +526,4 @@ function run(argv) {
|
|
|
526
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){o5($,G)},close(){clearTimeout(K),Z=null}}}function tZ($,J,Z){return new Promise((Q,K)=>{let B=a5($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function eZ($,J){let Z=pZ(s5(lZ(),"reason-simulator-stream-"));try{let Q=s5(Z,"screen.png");if(await tZ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=uZ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{dZ(Z,{recursive:!0,force:!0})}}async function t5($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!sZ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await x5().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await X1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:B.image.width,height:B.image.height},U=await t2(K),W=U?await v1(K,Z,!0):null,Y=U?null:await r5();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 eZ(Z,$.signal),stream:U?(N,C,F)=>A5(U,Z,Math.min(N,60),F,C):null,input:W?iZ(Z,W):oZ(Z,$.root)};return await c1({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...Y?{ffmpeg:()=>Y}:{}}})}var k7=131072,GQ=131072,UQ=128,f7=8192,R3=30000,P3=15000,XQ=/^[a-z][a-z0-9_]{0,63}$/,WQ=new Set(["jobs.control","fs.read","fs.write"]),e5=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function n1($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function $6($){return $.map(n1).join("/")}function D3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var YQ=[...D3(k6,4).map(($)=>`/(${$.map($6).join("|")})(/|$)`),...D3(f6,4).map(($)=>`/(${$.map($6).join("|")})$`),...D3([...b6],6).map(($)=>`/(${$.map(n1).join("|")})$`),`/${n1(".env")}\\.[^/]+$`,`/[^/]+(${x6.map(n1).join("|")})$`],O3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),b7=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function x7($){return[$.requiredPermission,...$.additionalPermissions??[]]}function FQ($){return V7($)}function j3(){if(l()==="darwin")return G0("/usr/bin/sandbox-exec");if(l()==="linux")return G7();return!1}function J6(){if(l()==="linux")return G0("/proc");if(!j3())return!1;if(l()==="darwin")return G0("/usr/sbin/lsof");return!1}function y7(){return l()==="darwin"?"/bin/zsh":U7()}function I3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function NQ($){if(!I3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>N0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function u0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function o1($,J,Z=f7){let Q=u0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function CQ($,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 N1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function v0($,J){return J===$||J.startsWith(`${$}${BQ}`)}function h0($){if(L0($))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.")}function m($){let J;try{J=J0($.path)}catch(Z){if(process.platform==="darwin"&&J7(Z))throw Z7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!C1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return h0(J),J}function z3($,J="."){if(!J||J.includes("\x00")||QQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");let Z=KQ($,J);if(!v0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function p0($,J=".",Z=!1){let Q=z3($,J),K;try{K=J0(Q)}catch(B){if(p7(B))throw u7();throw new H("path_not_found","Path does not exist.")}if(!v0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)h0(K);return K}function HQ($,J){let Z=z3($,J);if(h0(Z),G0(Z)){let B=J0(Z);if(!v0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(z7(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return h0(B),B}let Q=F1(Z);while(!G0(Q)){let B=F1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=J0(Q);if(!v0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return h0(K),Z}function h7($,J){return w3($,J)||"."}function DQ($,J=k7){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function m7($,J){return{...o6({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 MQ($,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($)}))`]:[],...YQ.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),"(deny network*)"].join(`
|
|
527
527
|
`)}async function E3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,W=!1,Y=!1,X;try{X=VQ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],detached:!0})}catch(w){K(w);return}let N=(w,M)=>{if(Y)return;Y=!0,clearTimeout(D),Z.signal.removeEventListener("abort",F),Q({exitCode:w,signal:M,stdout:B,stderr:G,timedOut:W,truncated:U})},C=(w,M)=>{let j=`${w}${String(M)}`,O=DQ(j);return U||=O.truncated,O.value};X.stdout.on("data",(w)=>{B=C(B,w)}),X.stderr.on("data",(w)=>{G=C(G,w)}),X.once("error",K),X.once("exit",N);let F=()=>{try{X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",F,{once:!0});let D=setTimeout(()=>{W=!0,F()},Z.timeoutMs)})}var Z6=null;function LQ(){return Z6??=X7({scrubEnvironment:m7,spawnCaptured:E3,isProtectedPath:L0}),Z6}var wQ=async($,J,Z)=>{if(l()==="linux")return LQ()($,J,Z);if(l()!=="darwin"||!G0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=E7(_3(S7(),"reason-device-"));try{return await E3("/usr/bin/sandbox-exec",["-p",MQ(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:m7(Z.root,Q)})}finally{g7(Q,{recursive:!0,force:!0})}};function OQ($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>UQ)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")>f7)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function v7($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=m($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??P3,signal:$.signal});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function p7($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var u7=()=>new H("path_unreadable","The path is not readable.");function jQ($){try{return q7($,A0.O_RDONLY)}catch(J){throw p7(J)?u7():J}}function Q6($,J){let Z=m0()?a1():null;return Z?i1(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):IQ($,J)}function IQ($,J){return $==="fs.read"?AQ(J):_Q(J)}async function AQ($){let J=m($.root),Z=p0(J,o1($.payload,"path"));if(!C1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=N1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=N1($.payload.max_bytes,65536,1,k7),B=u0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=jQ(Z),U,W;try{U=P7(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));W=X.subarray(0,X.byteLength?JQ(G,X,0,X.byteLength,Q):0)}finally{R7(G)}let Y=B==="base64"||W.includes(0);return{path:h7(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 TQ($,J){let Z=$==="append"?A0.O_APPEND:A0.O_TRUNC;return A0.O_WRONLY|A0.O_NOFOLLOW|Z|(J?0:A0.O_CREAT|A0.O_EXCL)}async function _Q($){let J=m($.root),Z=o1($.payload,"path"),Q=CQ($.payload,"content",GQ),K=u0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=HQ(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){$Q(F1(B),{recursive:!0,mode:448});let Y=J0(F1(B));if(!v0(J,Y))throw new H("symlink_escape","Write parent escaped root.")}if(!G0(F1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&G0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=G0(B),U=G?z7(B):null,W=q7(B,TQ(K,G),384);try{if(U){let Y=P7(W);if(Y.ino!==U.ino||Y.dev!==U.dev)throw new H("symlink_escape","The write target changed between validation and opening.")}ZQ(W,Q,null,"utf8")}finally{R7(W)}return{path:h7(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function RQ($){let J=m($.root),Z=o1($.payload,"command",65536),Q=p0(J,u0($.payload,"cwd")??".");if(!C1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=N1($.payload.timeout_ms,P3,100,R3);return v7($,y7(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function PQ($){let J=N4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:l()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=m($.root),K=p6(Q,J.data.workspace),B=K.boundary===Q?Q:p0(K.anchor,w3(K.anchor,K.boundary)||"."),G=p0(B,w3(B,K.path)||".");if(!C1(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()+X4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let W=(j)=>$.emit("progress",{process:j});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await A1({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:q0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:W})}}let Y={directory:_3(Z.runtimeDirectory,"processes")},X={deniedPorts:v6([$.apiOrigin])};if($.claim.local_github_authority&&l()==="darwin"){let j=zQ(G);try{return{...await A1({claim:$.claim,root:G,cwd:G,command:J.data.command,mode:"confined",shell:j.shell,prefix:j.prefix,environment:j.environment,expiresAtMs:U,signal:$.signal,emit:W,journals:Y,preview:X})}}finally{j.dispose()}}let N=t6(),C=e6(),F=m0(),D=J.data.egress?r1(F):null;if(J.data.egress&&(D===null||!y0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let w=J.data.egress?await p4(J.data.egress.allowed_domains):null,M=w?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((j)=>`${j}=${w.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
|
|
528
528
|
`):J.data.command;try{return{...await A1({claim:$.claim,root:G,cwd:G,command:M,mode:"host",shell:C,expiresAtMs:U,signal:$.signal,emit:W,...F?{jobsUser:{...F,...D!==null?{modelGid:D}:{}}}:{},environment:{...N.variables,HOME:N.home,PATH:N.path,TMPDIR:N.temporaryDirectory,SHELL:C},journals:Y,preview:X})}}finally{w?.close()}}function zQ($){if(!G0("/usr/bin/sandbox-exec"))throw new H("local_device_gh_confinement_unavailable","This Mac cannot confine a local GitHub Session's dev server.");let J=J0($),Z=J0(E7(_3(J0(S7()),"reason-preview-"))),Q="/bin/bash";return{shell:Q,prefix:["/usr/bin/sandbox-exec","-p",h6(J,Z)],environment:{HOME:Z,PATH:y6,TMPDIR:Z,TMP:Z,TEMP:Z,SHELL:Q,BASH_ENV:"/dev/null",ENV:"/dev/null",OPENSSL_CONF:"/dev/null"},dispose:()=>g7(Z,{recursive:!0,force:!0})}}async function EQ($){b2();let J=m($.root),Z=x2($.payload.command),Q=p0(J,u0($.payload,"cwd")??".");if(!C1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=N1($.payload.timeout_ms,m8,100,k2),{ignored:B}=y2($.payload.env);return await $.emit("progress",{shell:q0(),shell_flags:[...Q1],sandbox:"none",ignored_env:B}),p8({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function qQ($){let J=m($.root),Z=OQ($.payload),Q=Z[0];if(!Q||!b7.has(Q)&&!O3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=O3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=p0(J,u0($.payload,"cwd")??".");return v7($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K,timeoutMs:N1($.payload.timeout_ms,P3,100,R3)})}function d7($,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 gQ($){let J=m($.root);if(l()==="linux")return o8(J);return Z5(J,d7($,J))}async function SQ($){let J=m($.root);if(l()==="linux")return t8(J);return Q5(J,d7($,J))}async function kQ($){let J=$.worker?F5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&q3({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:m($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function fQ($){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}=u6($.payload,$.operationId);return c6({root:m($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:m($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function K6($,J){let Z=m0()?a1():null;return Z?i1(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):bQ(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function bQ($,J){let Z=m(J.root),Q=t0 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?C8(Z,J.payload[t0]):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=t4.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return H8({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=o1(J.payload,"path",4096),G=$==="import"&&Q?z2(K):K;return h0(z3(G,B)),E0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var l7={"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 u3({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>Q6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>Q6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>K6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>K6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>l()==="darwin"&&f2(),execute:PQ},"exec.run":{requiredPermission:"execute",available:j3,execute:RQ},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>f2(),execute:EQ},"git.run":{requiredPermission:"execute",available:()=>j3()&&FQ("git"),execute:qQ},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:J6,execute:gQ},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:J6,execute:SQ},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>l()==="darwin"||Boolean(Q7()),execute:kQ},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:j7,execute:fQ},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:_7,execute:($)=>{let J=a1();return J?i1(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??$7)()},$.signal):c1({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>A7(),execute:($)=>T7({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:U1,execute:($)=>X1({payload:$.payload,root:m($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:i5,execute:($)=>t5({payload:$.payload,root:m($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>n6({root:m($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>l()==="darwin"?G0("/usr/bin/sandbox-exec"):l()==="linux",execute:async($)=>{let J=w1.parse($.payload),Z=A3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!M0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return r6({root:m($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>Q4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>T3({root:m($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>l6({root:m($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>s6({root:m($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:R2,execute:($)=>X8($.payload,$.signal)}};function xQ($,J){try{let Z=l3($,J0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function yQ($,J){try{let Z=J0(J);return $.some((Q)=>Q.path===Z)?Z:void 0}catch{return}}function hQ($,J){try{let Z=J0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function mQ($,J){try{let Z=J0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&v0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function vQ($,J){try{return M1({home:J0(J),roots:$.filter((Z)=>/^[a-f0-9]{64}$/.test(Z.pathFingerprint)&&D1(Z.path)).slice(0,J2).map((Z)=>({path_fingerprint:Z.pathFingerprint,path:Z.path}))})}catch{return}}function GU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||l()==="darwin",K=Q?hQ($,Y1()):void 0,B=!J.worker&&l()==="darwin"?xQ($,Y1()):void 0,G=Q?yQ($,Y1()):void 0,U=!J.worker&&l()==="darwin"?mQ($,Y1()):void 0,W=Q?vQ($,Y1()):void 0,Y=S2.filter((X)=>{if(Z1.has(X)&&!J.worker)return!1;if(J.worker&&!f1(X,J.worker))return!1;let N=l7[X];if(!N)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:N.available?.()??!0)&&$.some((F)=>(!J.worker||X!=="pty.start"||F.permissions.read&&F.permissions.write)&&x7(N).every((D)=>F.permissions[D]))});return{supported_operations:Y,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...W?{root_paths:W}:{},...Y.includes("hands.connect")?{hands_worker_artifact_sha256:P0,hands_worker_entrypoint:a0,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:N0,max_result_bytes:N0,operation_constraints:{...Y.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":V2.parse(J.productionProof)}:{},"exec.run":{transport:"shell",shell:y7(),sandbox:l()==="linux"?"linux_sandbox_runtime":"macos_seatbelt",network:!1,max_timeout_ms:R3},...Y.includes("exec.full")?{"exec.full":u8()}:{},"git.run":{read_only_subcommands:[...b7].sort(),mutating_subcommands:[...O3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:W0,max_timeout_ms:o0,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:W0,max_timeout_ms:o0,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:r0,protocol_version:L3,worker_artifact_sha256:P0,worker_entrypoint:a0,policy_mode:"full_access",policy_version:1,workspace_base:M3,workspace_layout:J1,...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:O7,max_session_ms:L7,max_buffered_output_bytes:w7}}:{},...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:f1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:m6,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!m0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:R6,workspace_base:M3,workspace_layout:J1,browser_state:"optional_headless",desktop:!1,worker_version:r0,protocol_version:L3,...J.worker?.readiness?.["environment.install"]===!0&&Y.includes("environment.install")?{environment_delivery:G6,[W6]:X6}:{},...J.worker?{[F6]:Y6}:{},...J.worker?.handsBrowser?{[M6]:D6}:{},[H6]:C6,[w6]:L6,...y0(J.worker?.executionMode==="unsandboxed")?{[j6]:O6}:{},...y0(J.worker?.executionMode==="unsandboxed")&&r1()!==null?{[A6]:I6}:{},...y0(J.worker?.executionMode==="unsandboxed")&&m0()?{[_6]:T6}:{}}:{},...X==="fs.export"?{cloud_source_version:P1,source_kinds:["workspace","attachment"],[w2]:O2}:{},...X==="fs.import"?{[w2]:O2}:{},...X===U4&&r1()!==null&&y0(J.worker?.executionMode==="unsandboxed")?{[F4]:X2}:{},...X==="tunnel.open"?{carried_jobs:P6}:{},...X==="jobs.control"?{[E6]:z6}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[Y7]:W7,[N7]:F7.join(","),[C7]:H7,[D7]:M7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[q6]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[g6]:!0}:{}}])):{}}}}function q3($,J,Z,Q,K){let B=i6.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 UU($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==U6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((Y)=>Y.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!q3($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let W=T3({root:m(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:W.snapshot_id,installed_revision:W.installed_revision,installed:!0},K),!0}async function XU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==N6)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 d6({operationId:J.operation_id,root:m(W),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function WU($,J,Z){if(J.capability!=="github.local.v1")return B6($,J,Z);try{let Q=await B6($,J,Z);if(Q.status==="succeeded")return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function B6($,J,Z){if(Z1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!f1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=A3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=l7[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let K=$.roots.find((X)=>X.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&I3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&t0 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!q3($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(x7(Q).some((X)=>!K.permissions[X]))return{status:"failed",error_code:"permission_denied"};let B=0,G=async(X,N,C)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:B++,kind:X,capability:J.capability,data:N,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&C?{deliverySignal:C}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||WQ.has(J.capability)||J.capability==="pty.start",W,Y=async(X,N,C)=>{let F=W;W=void 0,await Promise.all([F,G(X,N,C)])};try{if(U)W=G("started"),W.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},N=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(C)=>G("pr-proof.started.v1",C))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:NQ(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??wQ,spawnFullControl:Z.spawnFullControl??E3,emit:U?Y:G,runHandsRelay:Z.runHandsRelay??((C)=>B7(C,X)),runPtySession:Z.runPtySession??I7});if(J.capability==="github.local.v1")V6.parse(N);if(!I3(N))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(N)??"null","utf8")>N0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?Y:G)("completed",{ok:!0}),{status:"succeeded",result:N,error_code:null}}catch(X){let N=Z.signal.reason instanceof H&&e5.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&e5.has(X.code)?X.code:null;if(Z.signal.aborted||N)return{status:"cancelled",...X instanceof n0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":N??"cancelled"};let C=J.capability==="inference.custom.v1"?X instanceof H&&S6(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&XQ.test(X.code)?X.code:"capability_failed",F=J.capability==="hands.connect"&&X instanceof K7?a6(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:C,...F?{expiry_diagnostic:F}:{}}),{status:"failed",error_code:C}}}
|
|
529
|
-
export{N9 as
|
|
529
|
+
export{N9 as B,C9 as C,V4 as D,DK as E,OK as F,uK as G,dK as H,R2 as I,mB as J,Y0 as K,q$ as L,g$ as M,vB as N,m$ as O,q0 as P,K1 as Q,PJ as R,WQ as S,y7 as T,m7 as U,MQ as V,E3 as W,wQ as X,IQ as Y,zQ as Z,bQ as _,l7 as $,xQ as aa,yQ as ba,hQ as ca,mQ as da,vQ as ea,GU as fa,UU as ga,XU as ha,WU as ia};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Nb as j,Ob as q}from"./vm-hands-entry-lite-rd9vsaew.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
|
|
3
3
|
export{y as t};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wh as M}from"./vm-hands-entry-lite-40t7d4p5.js";import{ai as G}from"./vm-hands-entry-lite-5a0kyaxa.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-qyw7cmjt.js"),import("./local-pty-session-bnhx083p.js"),import("./desktop-account-s4629ksd.js"),import("./worker-sandbox-bqwkytj2.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
|
|
3
|
+
export{O as u,C as v,P as w};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{_ as
|
|
2
|
+
import{Tb as D}from"./vm-hands-entry-lite-n8gsyjq7.js";import{Wh as j}from"./vm-hands-entry-lite-40t7d4p5.js";import{statSync as i}from"fs";import{delimiter as n,join as t}from"path";function _(q,z=process.env.PATH??""){if(!q||q.includes("/")||q.includes("\x00"))return!1;return z.split(n).some((G)=>{if(!G)return!1;try{let Q=i(t(G,q));return Q.isFile()&&(Q.mode&73)!==0}catch{return!1}})}import{spawn as r,spawnSync as e}from"child_process";import{existsSync as k,mkdtempSync as E,readFileSync as O,readdirSync as o,realpathSync as qq,rmSync as b,statSync as zq}from"fs";import{platform as y,tmpdir as g}from"os";import{dirname as A,join as Z}from"path";import{fileURLToPath as Gq,pathToFileURL as T}from"url";var Hq=["bwrap","socat","rg"],Jq=2000,v=20000,Qq=3,P=4000,Vq=new Set([".git",".hg",".svn","node_modules"]),Wq=["runAsHostUid","sysrq-trigger"],Yq=Z(A(A(Gq(import.meta.url))),"packages/sandbox-runtime/src/index.ts"),h=!1;function fq(){h=!0}async function u(){let z=h?Z(A(qq(process.execPath)),"runtime","srt"):void 0;if(z&&process.platform==="linux"&&!k(Z(z,"vendor","seccomp",process.arch,"apply-seccomp")))throw Error("packaged_sandbox_runtime_vendor_missing");if(z){let J=O(Z(z,"sandbox-runtime.mjs"),"utf8");for(let Y of Wq)if(!J.includes(Y))throw Error(`packaged_sandbox_runtime_fork_missing:${Y}`)}let H=(await import(z?T(Z(z,"sandbox-runtime.mjs")).href:T(Yq).href)).SandboxManager;if(!H||typeof H.initialize!=="function"||typeof H.wrapWithSandboxArgv!=="function")throw Error("sandbox-runtime does not expose the expected SandboxManager API.");return{SandboxManager:H}}function Zq(q={}){if((q.platformName??y())!=="linux")return!1;let G=q.fileExists??k,Q=q.readFile??((H)=>O(H,"utf8"));for(let H of["/.dockerenv","/run/.containerenv"])try{if(G(H))return!0}catch{}try{return/docker|containerd|kubepods|lxc|libpod/.test(Q("/proc/1/cgroup"))}catch{return!1}}function l(q){return["/bin/true","/usr/bin/true"].find((z)=>q(z))??null}function $q(q,z){return q==="strict"?["--ro-bind","/","/","--unshare-pid","--unshare-user","--cap-drop","ALL","--proc","/proc","--",z]:["--ro-bind","/","/","--unshare-pid","--unshare-user","--bind","/proc","/proc","--",z]}function jq(q,z){try{let G=e("bwrap",$q(q,z),{stdio:"ignore",timeout:Jq});return!G.error&&G.status===0}catch{return!1}}function Bq(q){let z=q.platformName??y();if(z!=="linux")return null;let G=q.hasExecutable??_;if(!Hq.every((V)=>G(V)))return null;let Q=q.fileExists??k,H=l(Q);if(!H)return null;let J=B??(q.containerized??Zq({platformName:z})?"weak":"strict");return(q.probeNamespaces??((V)=>jq(V,H)))(J)?J:null}var L=null,C=!1,K=null,S=null,f=null,B=null,F=null;function M(){throw I("sandbox_mode_conflict"),new j("sandbox_unavailable","Sandbox process policy conflicts with an existing probe or session. Restart the worker.")}function xq(q){if(B!==null&&B!==q||C&&L!==null&&L!==q||F!==null&&F!==q)M();B=q}function I(q){K=q}function c(q){if(K)return!1;if(!C){if(L=Bq(q??{}),C=!0,L&&!q)d()}return L!==null}function Lq(){return c()?L:null}var U=null,w=0;function m(q){if(K)throw new j("sandbox_unavailable","Confined execution is unavailable in this worker process.");if(B&&q.sandboxMode&&B!==q.sandboxMode)M();let z=B??q.sandboxMode??Lq();if(!z)throw new j("sandbox_unavailable","Confined command execution is unavailable on this operating system.");if(F&&F!==z)M();return F=z,U??=(async()=>{let{SandboxManager:G}=await(q.loadSandboxRuntime??u)();return await G.initialize(Iq(z)),G})().catch((G)=>{throw U=null,I(`initialize_failed: ${String(G)}`),G instanceof j?G:new j("sandbox_unavailable","The confined execution sandbox failed to start.")}),U.then((G)=>{if(K)throw new j("sandbox_unavailable","Confined execution became unavailable during sandbox initialization.");return G})}async function Kq(){let q=U;if(U=null,!q)return;try{await(await q).reset()}catch{}}async function d(q={}){if(K)return!1;if(q.loadSandboxRuntime)return x(q.loadSandboxRuntime);if(!c())return!1;return S??=x(u),S}async function x(q){try{let{SandboxManager:z}=await q(),G=z.checkDependencies().errors;if(G.length>0)return I(`dependencies_missing: ${G.join(", ")}`),!1;return!K}catch(z){return I(`load_failed: ${String(z)}`),!1}}async function Rq(q={}){if(!q.loadSandboxRuntime&&!q.sandboxMode){if(!await d())return!1;return f??=R({}),f}return R(q)}async function R(q){let z;try{z=await m(q)}catch{return!1}let G=await Xq(z);if(!G)I("confined_command_failed");if(w===0)await Kq();return G}async function Xq(q){let z=l(k);if(!z)return!1;let G=E(Z(g(),"reason-device-probe-"));try{let{argv:Q}=await q.wrapWithSandboxArgv(a([z]),p(),{filesystem:s({root:G,allowWrite:!1,temporaryDirectory:G,protectedPaths:[]})},void 0,G),[H,...J]=Q;if(!H)return!1;return await Fq(H,J,G)}catch{return!1}finally{try{q.cleanupAfterCommand()}catch{}b(G,{recursive:!0,force:!0})}}function Fq(q,z,G,Q={}){return new Promise((H)=>{let J=!1,Y,V=(X)=>{if(J)return;J=!0,clearTimeout(Y),H(X)},W;try{W=(Q.spawnChild??r)(q,z,{cwd:G,env:{PATH:D,HOME:G,TMPDIR:G},stdio:"ignore"})}catch{V(!1);return}W.once("error",()=>V(!1));let $=(X,N)=>V(X===0&&N===null);if(W.once("exit",$),W.once("close",$),W.exitCode!==null||W.signalCode!==null)$(W.exitCode,W.signalCode);if(J)return;Y=setTimeout(()=>{V(!1);try{W.kill("SIGKILL")}catch{}},Math.min(Q.timeoutMs??v,v))})}function p(q=k){return["/bin/bash","/bin/sh"].find((z)=>q(z))??"/bin/sh"}function a(q){return q.map((z)=>`'${z.replaceAll("'","'\\''")}'`).join(" ")}function Uq(q,z,G=(Q)=>o(Q,{withFileTypes:!0}).filter((H)=>H.isDirectory()||H.isFile()).map((H)=>H.name)){let Q=[],H=[{path:q,depth:0}],J=0;while(H.length>0&&J<P){let Y=H.pop(),V;try{V=G(Y.path)}catch{continue}for(let W of V){if(J+=1,J>P)break;let $=Z(Y.path,W);if(z($)){Q.push($);continue}if(Y.depth+1<Qq&&!Vq.has(W))H.push({path:$,depth:Y.depth+1})}}return Q}function s(q){let z=Z(q.root,".git"),G=[];try{if(zq(z).isDirectory())G=[Z(z,"config"),Z(z,"hooks")]}catch{}return{denyRead:["/home","/root","/tmp","/tmp/.X11-unix",...q.protectedPaths],allowRead:[q.root,q.temporaryDirectory],allowWrite:[...q.allowWrite?[q.root]:[],q.temporaryDirectory],denyWrite:[...q.protectedPaths,...G]}}function Iq(q){return{network:{allowedDomains:[],deniedDomains:[]},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},...q==="weak"?{enableWeakerNestedSandbox:!0}:{}}}function Dq(q){let z=q.createTemporaryDirectory??(()=>E(Z(g(),"reason-device-"))),G=q.removeTemporaryDirectory??((Q)=>b(Q,{recursive:!0,force:!0}));return async(Q,H,J)=>{let Y=await m(q),V=z();w+=1;try{let W;try{W=await Y.wrapWithSandboxArgv(a([Q,...H]),q.shell??p(),{filesystem:s({root:J.root,allowWrite:J.allowWrite,temporaryDirectory:V,protectedPaths:Uq(J.root,q.isProtectedPath)})},J.signal,J.cwd)}catch(N){throw N instanceof j?N:new j("sandbox_unavailable","The confined execution sandbox could not wrap the command.")}let[$,...X]=W.argv;if(!$)throw new j("sandbox_unavailable","The confined execution sandbox produced no command.");return await q.spawnCaptured($,X,{cwd:J.cwd,timeoutMs:J.timeoutMs,signal:J.signal,env:q.scrubEnvironment(J.root,V)})}finally{w-=1;try{Y.cleanupAfterCommand()}catch{}G(V)}}}
|
|
3
|
+
export{_ as Mb,fq as Nb,xq as Ob,c as Pb,Rq as Qb,p as Rb,Dq as Sb};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{he as W}from"./vm-hands-entry-lite-669hk342.js";var E=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),g=W.string().regex(/^[a-f0-9]{40}$/),N=W.number().int().positive(),T=W.string().min(1).max(256),A=W.string().max(60000),q={version:W.literal(1),repoFullName:E},S=W.array(W.string().max(1024).regex(/^Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>$/)).max(500),y=W.strictObject({expectedTrailers:S,missingFromHead:S}),d=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:T.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),a=W.discriminatedUnion("kind",[W.strictObject({...q,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...q,kind:W.literal("pr_review_context"),number:N,after:W.string().min(1).max(1024).optional()}),W.strictObject({...q,kind:W.literal("prepare"),branch:G,baseSha:g,defaultBranch:G}),W.strictObject({...q,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:g,remoteHeadSha:g.nullable(),contributorTrailers:S.optional()}),W.strictObject({...q,kind:W.literal("pr_create"),head:G,base:G,title:T,body:A,draft:W.boolean()}),W.strictObject({...q,kind:W.literal("pr_mutation"),number:N,mutation:d}),W.strictObject({...q,kind:W.literal("pr_merge"),number:N,expectedHeadSha:g,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),I=245760,e=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(I)}),W.strictObject({kind:W.literal("prepare"),headSha:g}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(I)}),W.strictObject({kind:W.literal("publish"),headSha:g,scannedObjectCount:W.number().int().min(0).max(5000),attribution:y.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:N,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:N,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=I,"local_device_gh_result_too_large"),O=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),j=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:O.optional(),contributorRefresh:W.guid().optional(),repoFullName:E.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function C(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function QQ(Q,Z,$={},H="read"){if(C(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return z(Q,Z,$);if(!C(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((K)=>K==="."||K===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((K)=>K.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((K,B)=>{if(B==="per_page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(B==="page"&&/^[1-9][0-9]*$/.test(K)&&Number(K)<=100)return;if(Y==="/pulls"&&B==="state"&&["open","closed","all"].includes(K))return;if(Y==="/pulls"&&B==="sort"&&K==="updated")return;if(Y==="/pulls"&&B==="direction"&&K==="desc")return;if(Y==="/pulls"&&["head","base"].includes(B)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(K))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((B,c)=>{if(c!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(B))throw Error("local_device_gh_header_denied")})}function z(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let H=new URL(Z,"https://api.github.com");if(H.pathname!=="/search/issues"||H.username||H.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;H.searchParams.forEach((X,K)=>{if(K==="q"&&V===null){V=X;return}if(K==="per_page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;if(K==="page"&&/^[1-9][0-9]*$/.test(X)&&Number(X)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,U=V?.toLowerCase()??"";if(U.length>512||!(U+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(U.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((X,K)=>{if(K!=="accept"||X!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var WQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
|
|
3
3
|
repository(owner: $owner, name: $repo) {
|
|
4
4
|
nameWithOwner
|
|
5
5
|
pullRequest(number: $number) {
|
|
@@ -39,4 +39,4 @@ import{ee as W}from"./vm-hands-entry-lite-psybjyay.js";var E=W.string().max(201)
|
|
|
39
39
|
`)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
|
|
40
40
|
`),"utf8")}function D(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function n(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function _(Q){return D(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function s(Q){return D(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&D(Q.payload)}function w(Q){throw Error(Q)}function iQ(Q,Z){let $=D(Q)?Q:{},H=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:H,message:V}}function o(Q){if(!D(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
|
|
41
41
|
`)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function f(Q,Z){if(!D(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==x||!Array.isArray(Q.roots)||!Q.roots.every(_)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:x,roots:Q.roots},auth_scheme:"p256"}}function tQ(Q){return f(Q,!1)}function vQ(Q){let Z=f(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function lQ(Q){if(!D(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...b(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...t(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var i=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function b(Q){return Object.fromEntries(i.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function uQ(Q){if(!D(Q))return;try{return{...o(Q),...b(Q)}}catch{return}}function t(Q){if(!D(Q))return{};let Z={};for(let $ of p){let H=Q[$];if(typeof H==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(H))Z[$]=H}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function aQ(Q){if(!D(Q)||!Array.isArray(Q.roots)||!Q.roots.every(_))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function eQ(Q){if(!D(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function QW(Q){if(!D(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function WW(Q){if(D(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(D(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function ZW(Q){if(!D(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function v(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function $W(Q,Z=k){if(!D(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!L(Q.owner)||!n(Q.capability,Z)||!D(Q.payload)||Q.protocol_version!==x||v(Q.payload)>R||Q.authority!==void 0&&!J(Q.authority)||Q.local_github_authority!==void 0&&!j.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!j.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!m(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!m(Q.recording_authority)||!L(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...J(Q.authority)?{authority:Q.authority}:{},...m(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:j.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&D(Q.environment)&&D(Q.environment.payload)&&J(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:x};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function DW(Q){if(!D(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(s)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function KW(Q){if(!D(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function FW(Q){if(!D(Q)||!D(Q.payload)||!J(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function l(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function wW(Q){if(!D(Q)||!l(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
|
|
42
|
-
export{a as
|
|
42
|
+
export{a as Vc,I as Wc,e as Xc,j as Yc,QQ as Zc,WQ as _c,ZQ as $c,k as ad,x as bd,P as cd,R as dd,wQ as ed,HQ as fd,VQ as gd,YQ as hd,XQ as id,BQ as jd,GQ as kd,qQ as ld,gQ as md,MQ as nd,NQ as od,UQ as pd,jQ as qd,JQ as rd,xQ as sd,IQ as td,SQ as ud,mQ as vd,PQ as wd,CQ as xd,EQ as yd,TQ as zd,AQ as Ad,kQ as Bd,LQ as Cd,_Q as Dd,fQ as Ed,bQ as Fd,cQ as Gd,yQ as Hd,dQ as Id,OQ as Jd,zQ as Kd,RQ as Ld,hQ as Md,pQ as Nd,rQ as Od,nQ as Pd,r as Qd,sQ as Rd,oQ as Sd,iQ as Td,o as Ud,tQ as Vd,vQ as Wd,lQ as Xd,uQ as Yd,aQ as Zd,eQ as _d,QW as $d,WW as ae,ZW as be,$W as ce,DW as de,KW as ee,FW as fe,wW as ge};
|