@reason-machines/cli-linux-x64 0.2.388 → 0.2.390
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 +2 -2
- package/bin/vm-hands/api-2edgrjpe.js +2 -0
- package/bin/vm-hands/api-credentials-1bfy2pqp.js +2 -0
- package/bin/vm-hands/{ask-relay-rpekz0vc.js → ask-relay-fhcfxc8e.js} +3 -3
- package/bin/vm-hands/connect-cli-9aczr82r.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-baqm3872.js → custom-endpoint-device-3g0rc3wp.js} +1 -1
- package/bin/vm-hands/desktop-account-8yf4aqgb.js +2 -0
- package/bin/vm-hands/{device-workspace-0kk5ef85.js → device-workspace-35hjc1ff.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-mshf7c6v.js → hands-worker-source-msdkfx9x.js} +1 -1
- package/bin/vm-hands/{index-cvnymkkb.js → index-m32pjcjr.js} +1 -1
- package/bin/vm-hands/{install-receipt-352cy8vj.js → install-receipt-7qanbz38.js} +1 -1
- package/bin/vm-hands/local-automation-dcqf14d4.js +2 -0
- package/bin/vm-hands/local-capabilities-pv3gr2hy.js +2 -0
- package/bin/vm-hands/local-desktop-users-p6n48895.js +2 -0
- package/bin/vm-hands/local-display-mac-7havkbhd.js +2 -0
- package/bin/vm-hands/local-display-session-gnx1pp3w.js +2 -0
- package/bin/vm-hands/local-pty-session-8ny1n2fv.js +2 -0
- package/bin/vm-hands/{managed-runtime-wzk0q157.js → managed-runtime-7zsf50b5.js} +1 -1
- package/bin/vm-hands/network-contract-3h853c6e.js +2 -0
- package/bin/vm-hands/package-04cf0m62.js +2 -0
- package/bin/vm-hands/permissions-dsmaj350.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-z95pxxbh.js → reason-hands-protocol-mw7ba8vz.js} +1 -1
- package/bin/vm-hands/{serve-service-d2q1pdxh.js → serve-service-qax96kty.js} +1 -1
- package/bin/vm-hands/{status-x8g58cxm.js → status-1v4paztv.js} +2 -2
- package/bin/vm-hands/version-8eeqhkse.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jx3w1z5q.js → vm-hands-entry-lite-00800vjk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v2ptg6br.js → vm-hands-entry-lite-02zaqpgh.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-zr8gf6nd.js → vm-hands-entry-lite-0seprnh3.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qnnfvm5r.js → vm-hands-entry-lite-0z73amf7.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y55f8dyw.js → vm-hands-entry-lite-180h5amj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-pk3q774c.js → vm-hands-entry-lite-3nr9q3nf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b1ygrkbq.js → vm-hands-entry-lite-3ptq7p60.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fyvgav60.js → vm-hands-entry-lite-5x04hakp.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-yzaz1e8r.js → vm-hands-entry-lite-6t0a7k6v.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-zs3jsffv.js → vm-hands-entry-lite-7s9z3tdn.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-stbfyev7.js → vm-hands-entry-lite-88h9vwrv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-f89wk20p.js → vm-hands-entry-lite-8e932j3c.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-e05sgnwe.js → vm-hands-entry-lite-8pgggvbb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ammr3xbc.js → vm-hands-entry-lite-a1yy1yp3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-289qftes.js → vm-hands-entry-lite-adpzn7fe.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mbs7d7ye.js → vm-hands-entry-lite-atg4z1vg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y2s2w174.js → vm-hands-entry-lite-bwpay74g.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-e2mjbqmr.js → vm-hands-entry-lite-csecgmaa.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-spccx392.js → vm-hands-entry-lite-e73s63fb.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-p6g561rq.js → vm-hands-entry-lite-ebgackey.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-d7cvwy3k.js → vm-hands-entry-lite-ecsgqm1s.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-ezahexcb.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-grjkhbf2.js → vm-hands-entry-lite-f78n4wqt.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-te0p47ak.js → vm-hands-entry-lite-fb02h1zm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fw5ztpwn.js → vm-hands-entry-lite-g87z5eb6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6shgavn0.js → vm-hands-entry-lite-gq3bzj7d.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-s7k376cz.js → vm-hands-entry-lite-h0keewxv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-fb5dzy9x.js → vm-hands-entry-lite-hfv2tsm9.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3vb4he21.js → vm-hands-entry-lite-hp0ccw3e.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-jjgqsan6.js → vm-hands-entry-lite-jsbgswhd.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-ma001vzh.js → vm-hands-entry-lite-ksz1k1dh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kb981w39.js → vm-hands-entry-lite-mc3pkj0q.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sex82vb1.js → vm-hands-entry-lite-mft9ke08.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-9fc26f9c.js → vm-hands-entry-lite-n11e88ty.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-sb7n76g7.js → vm-hands-entry-lite-p1s0xyc2.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n25efwqt.js → vm-hands-entry-lite-r166b92s.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6tv7j3ej.js → vm-hands-entry-lite-rnmy7f5e.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-sv8bb7jq.js → vm-hands-entry-lite-rxg5nf73.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-nf0avf46.js → vm-hands-entry-lite-t6dxxwc8.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-30rnhzfj.js → vm-hands-entry-lite-trm3dn8c.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-r7czqrtj.js → vm-hands-entry-lite-wjwwzxej.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-2e18tm6w.js → vm-hands-entry-lite-wpcagqfw.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-nr1narzb.js → vm-hands-entry-lite-y99g8x7f.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-axe84b1n.js → vm-hands-entry-lite-zd5pw8gj.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-j4q5snaz.js → vm-hands-executor-zsepc201.js} +1 -1
- package/bin/vm-hands/vm-hands-op-runner-sfhzq9bc.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-r0y0c22t.js +4 -0
- package/bin/vm-hands/worker-sandbox-nnk7fq89.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-9jsc2wk3.js +0 -2
- package/bin/vm-hands/api-credentials-jhaxk9e6.js +0 -2
- package/bin/vm-hands/connect-cli-xk4wx40j.js +0 -2
- package/bin/vm-hands/desktop-account-374pyd2h.js +0 -2
- package/bin/vm-hands/local-automation-fqf1yxn8.js +0 -2
- package/bin/vm-hands/local-capabilities-0xqv6w37.js +0 -2
- package/bin/vm-hands/local-desktop-users-39d8h875.js +0 -2
- package/bin/vm-hands/local-display-mac-yt4tpb96.js +0 -2
- package/bin/vm-hands/local-display-session-12q3s3p1.js +0 -2
- package/bin/vm-hands/local-pty-session-142rrpf9.js +0 -2
- package/bin/vm-hands/network-contract-m55ndrgk.js +0 -2
- package/bin/vm-hands/package-k4xz7vcr.js +0 -2
- package/bin/vm-hands/permissions-zajmtjzs.js +0 -2
- package/bin/vm-hands/version-55234k7v.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-wzqzjd6f.js +0 -5
- package/bin/vm-hands/vm-hands-op-runner-btwvjt4p.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-gw2wdm13.js +0 -4
- package/bin/vm-hands/worker-sandbox-r41yz175.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-6t0a7k6v.js";import{Dc as p7,Fc as d7,Gc as l7}from"./vm-hands-entry-lite-mc3pkj0q.js";import{Lc as g7}from"./vm-hands-entry-lite-h0keewxv.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-r166b92s.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as t4,bd as e4}from"./vm-hands-entry-lite-180h5amj.js";import{dd as m7}from"./vm-hands-entry-lite-g7h6wjqy.js";import{hd as H2,id as C2,jd as B4,ld as V4,nd as G4,od as X4,sd as U4,ud as Y7}from"./vm-hands-entry-lite-e73s63fb.js";import{Cd as W2,Fd as K9,Od as B9}from"./vm-hands-entry-lite-t6dxxwc8.js";import{$e as u6,Ae as n3,Be as O2,Ce as y6,De as r3,Df as i8,Ee as _4,Ef as o8,Fe as P4,Ff as t8,Ge as j0,Gf as e8,Hf as $5,If as J5,Ke as C0,Kf as Z5,Lf as Q5,Mf as K5,Ne as s,Nf as B5,Oe as c1,Of as V5,Pf as G5,Qf as X5,Re as a8,Rf as U5,Sf as F5,Te as n1,Tf as Y5,Ve as h6,We as m6,_e as v6,af as p6,bf as d6,cf as l6,df as s6,ef as c6,ff as n6,gf as r6,hf as a6,if as i6,jf as o6,kf as t6,lf as e6,mf as $7,nf as J7,of as Z7,pf as Q7,rf as K7,sf as B7,tf as V7,uf as G7,vf as X7,wf as U7,xf as F7,ye as g1,ze as E1}from"./vm-hands-entry-lite-02zaqpgh.js";import{Zf as _6,bg as m5,cg as X6,ig as V9,lg as v5,mg as X2}from"./vm-hands-entry-lite-zd5pw8gj.js";import{og as e7,pg as $9,qg as J9,ug as Z9,xg as Q9}from"./vm-hands-entry-lite-adpzn7fe.js";import{Gg as $8,Ng as S7}from"./vm-hands-entry-lite-00800vjk.js";import{Sg as Y2}from"./vm-hands-entry-lite-hfv2tsm9.js";import{Yg as u3,jh as W7}from"./vm-hands-entry-lite-a1yy1yp3.js";import{Fi as v7,Gi as u7}from"./vm-hands-entry-lite-jsbgswhd.js";import{Si as A1,Ti as _1,Ui as P1,Vi as T1,Wi as k0}from"./vm-hands-entry-lite-mft9ke08.js";import{mj as b1,nj as j7,oj as r4,pj as a4}from"./vm-hands-entry-lite-5x04hakp.js";import{Aj as k4,rj as v3,tj as B1,zj as y8}from"./vm-hands-entry-lite-3nr9q3nf.js";import{Rj as s7,Sj as c7,Tj as n7,Uj as r7,Wj as a7,Xj as i7,Zj as o7,_j as t7}from"./vm-hands-entry-lite-ebgackey.js";import{jk as V}from"./vm-hands-entry-lite-8pgggvbb.js";import{Ak as N7,Bk as H7,Ck as n4,Dk as l1,tk as z5,uk as c4,zk as z7}from"./vm-hands-entry-lite-fb02h1zm.js";import{Ek as T4}from"./vm-hands-entry-lite-8e932j3c.js";import{Gk as H}from"./vm-hands-entry-lite-g87z5eb6.js";import{Mk as g8}from"./vm-hands-entry-lite-f78n4wqt.js";import{request as _9}from"http";import{request as P9}from"https";import{lookup as T9}from"dns/promises";import{isIP as R9}from"net";async function q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?P9:_9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(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 F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),g9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(g9.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=Y4(Q,J+1);if(K)return K}return null}async function E9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||R9(Q)!==0)return Z;let K;return await Promise.race([T9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function k9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function S9($,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 Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(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,Y=0,F=k9(Q.apiKey),X=S9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await q9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<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 M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await E9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function f9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>f9(Q.path,J));return Z.length===1?Z[0].path:null}var b9=/^[a-f0-9]{64}$/;var D2=32,x9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!x9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)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"||!b9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function y9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function h9($){return y9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?h9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),m9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
|
|
3
3
|
return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
|
|
4
4
|
'(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
|
|
5
5
|
'(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
|
|
@@ -34,7 +34,7 @@ Content-Length: 0\r
|
|
|
34
34
|
\r
|
|
35
35
|
`),U8(Y,N,F)})().catch(()=>Y.destroy())}),await new Promise((U,Y)=>{B.once("error",Y),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 l2,randomUUID as k$}from"crypto";import{closeSync as p1,constants as J0,fchownSync as S$,fstatSync as L0,fsyncSync as f$,linkSync as P8,lstatSync as v2,mkdirSync as T8,openSync as v1,readSync as E8,realpathSync as u2,unlinkSync as R8,writeSync as b$}from"fs";import{isAbsolute as x$,join as y$,relative as h$,sep as m$}from"path";import{platform as p2}from"os";import{getSystemErrorName as v$}from"util";var H8={type:"string",format:"uuid"},M8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,x1={type:"string",minLength:1,maxLength:4096,pattern:M8},b2=V.string().min(1).max(4096).regex(new RegExp(M8)),y1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},h1={device_id:H8,root_id:H8,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},iB={read:{schema:V.object({...y1,path:b2,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:{...h1,path:x1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...y1,path:b2,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:{...h1,path:x1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...y1,command:V.string().min(1).max(16000),cwd:b2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...h1,command:{type:"string",minLength:1,maxLength:16000},cwd:x1,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}}},z0=1073741824,Z1=600000,C8=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,j8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${C8}(?:/${C8})*(?![\s\S])`,L8=new RegExp(j8);function O8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&L8.test($)}var x2=V.string().min(1).max(4096).regex(L8),y2={...x1,pattern:j8},I8=V.string().regex(/^[a-f0-9]{64}$/),A8=V.object({kind:V.literal("workspace"),path:x2}).strict(),q$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:I8}).strict()]),m1=1,Q1="cloud_workspace_id",h2="cloud_workspace",m2=1,g$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(z0),sha256:I8}).strict()]),_8=V.object({source_version:V.literal(m1),source:g$,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(),[Q1]:V.string().min(1).max(160).optional()}).strict(),oB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(m1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var D8=V.object({...y1,timeout_ms:V.number().int().min(1000).max(Z1).optional(),source_path:x2,destination_path:x2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),w8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...h1,timeout_ms:{type:"integer",minimum:1000,maximum:Z1},source_path:y2,destination_path:y2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},E$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:y2},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}]},tB=V.union([D8,D8.omit({source_path:!0}).extend({source:q$}).strict()]),eB={...w8,required:["device_id","root_id","destination_path"],properties:{...w8.properties,source:E$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var s2=65536;function l($){throw new H($,$)}function d1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function u1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return l(Z)}function u$($,J,Z){let Q;switch(d1($)){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 u1($,J,Q)}function p$($){if(typeof $!=="string"||$.length>16384)return l("transfer_url_invalid");let J;try{J=new URL($)}catch{return l("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return l("transfer_url_invalid");return J.href}var d2=J0.O_RDONLY|J0.O_DIRECTORY|J0.O_NOFOLLOW;async function d$(){if(p2()==="win32"){let F=new Map,X,W=-1,z=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(D)=>{let j=h$(X,D);return j===""||j!==".."&&!j.startsWith(`..${m$}`)&&!x$(j)},C=(D)=>{let j=v2(D);if(j.isSymbolicLink())throw z();if(!j.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let O=u2(D);if(X??=O,!N(O))throw z();return F.set(W,{path:D,real:O}),W--},M=(D)=>{let j=F.get(D);if(u2(j.path)!==j.real)throw z();return j.path},w=(D,j)=>{if(l1(j))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return y$(F.get(D).path,j)};return{root:C,openDirectory:(D,j)=>C(w(D,j)),open:(D,j,O,A=384)=>{let b=w(D,j);if(v2(b,{throwIfNoEntry:!1})?.isSymbolicLink())throw z();M(D);let I=v1(b,O,A);try{let R=L0(I),P=v2(b);if(P.isSymbolicLink()||R.ino!==P.ino||R.dev!==P.dev||!N(u2(b)))throw z()}catch(R){throw p1(I),R}return I},mkdir:(D,j)=>{let O=w(D,j);M(D),T8(O)},link:(D,j,O)=>{let A=w(D,j),b=w(D,O);M(D),P8(A,b)},unlink:(D,j)=>R8(w(D,j)),closeDirectory:(D)=>{F.delete(D)},inherit:()=>{},close:()=>{}}}let $={root:(F)=>v1(F,d2),closeDirectory:p1,inherit:l$};if(p2()==="linux")return{...$,openDirectory:(F,X)=>v1(`/proc/self/fd/${F}/${X}`,d2),open:(F,X,W,z=384)=>v1(`/proc/self/fd/${F}/${X}`,W,z),mkdir:(F,X)=>T8(`/proc/self/fd/${F}/${X}`,{mode:448}),link:(F,X,W)=>P8(`/proc/self/fd/${F}/${X}`,`/proc/self/fd/${F}/${W}`),unlink:(F,X)=>R8(`/proc/self/fd/${F}/${X}`),close:()=>{}};if(p2()!=="darwin")return l("transfer_platform_unsupported");let{dlopen:J,FFIType:Z,ptr:Q,read:K}=await import("bun:ffi"),B=J("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:Z.ptr},openat:{args:[Z.i32,Z.ptr,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32],returns:Z.i32},mkdirat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32},linkat:{args:[Z.i32,Z.ptr,Z.i32,Z.ptr,Z.i32],returns:Z.i32},unlinkat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32}}),G=B.symbols.__error();if(G===null)return B.close(),l("transfer_path_unavailable");let U=(F)=>{if(F<0){let X=v$(-K.i32(G));throw Object.assign(Error("transfer_path_unavailable"),{code:X})}return F},Y=(F,X,W,z=384)=>U(B.symbols.openat(F,Q(Buffer.from(`${X}\x00`)),W,z,0,0,0,0,z));return{...$,openDirectory:(F,X)=>Y(F,X,d2),open:Y,mkdir:(F,X)=>{U(B.symbols.mkdirat(F,Q(Buffer.from(`${X}\x00`)),448))},link:(F,X,W)=>{U(B.symbols.linkat(F,Q(Buffer.from(`${X}\x00`)),F,Q(Buffer.from(`${W}\x00`)),0))},unlink:(F,X)=>{U(B.symbols.unlinkat(F,Q(Buffer.from(`${X}\x00`)),0))},close:()=>B.close()}}function l$($,J){let Z=L0($),Q=L0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)S$(J,Z.uid,Z.gid)}function s$($,J,Z,Q){if(!O8(Z))return l("transfer_path_invalid");let K=Z.split("/"),B=$.root(J);try{for(let G of K.slice(0,-1)){let U;try{U=$.openDirectory(B,G)}catch(Y){if(!Q||d1(Y)!=="ENOENT")throw Y;try{$.mkdir(B,G)}catch(F){if(d1(F)!=="EEXIST")throw F}U=$.openDirectory(B,G),$.inherit(B,U)}$.closeDirectory(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw $.closeDirectory(B),G}}function q8($,J){let Z=L0($,{bigint:!0});if(!Z.isFile()||Z.size>z0)return l("transfer_file_invalid");let Q=l2("sha256"),K=Buffer.alloc(s2),B=0;while(!0){J.throwIfAborted();let U=E8($,K,0,K.length,B);if(!U)break;if(B+=U,B>z0)return l("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=L0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return l("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=p$($.payload.url),Z=await d$(),Q,K,B;try{if(Q=s$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK);let z=L0(K,{bigint:!0});if(!z.isFile()||z.size>z0)return l("transfer_file_invalid");let N=l2("sha256"),C=0,M=K,w,D=new ReadableStream({pull(b){try{$.signal.throwIfAborted();let I=Buffer.alloc(s2),R=E8(M,I,0,I.length,C);if(!R){b.close();return}if(C+=R,C>z.size)return l("transfer_source_changed");N.update(I.subarray(0,R)),b.enqueue(I.subarray(0,R))}catch(I){throw w=I,I}}});try{let b=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:D,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(z.size)}},{duplex:"half"}));if(w!==void 0)throw w;if(!b.ok)return l("transfer_upload_failed");await b.body?.cancel()}catch(b){if(w!==void 0)throw w;return u1(b,$.signal,"transfer_upload_failed")}let j=L0(K,{bigint:!0});if(BigInt(C)!==z.size||j.size!==z.size||j.mtimeNs!==z.mtimeNs||j.ctimeNs!==z.ctimeNs)return l("transfer_source_changed");let O=N.digest("hex"),A=q8(K,$.signal);if(A.size_bytes!==C||A.sha256!==O)return l("transfer_source_changed");return{size_bytes:C,sha256:O,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>z0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return l("transfer_receipt_invalid");let Y;try{Y=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK)}catch(z){if(d1(z)!=="ENOENT")throw z}if(Y!==void 0){try{let z=q8(Y,$.signal);if(z.size_bytes===G&&z.sha256===U)return{...z,outcome:"already_present"}}finally{p1(Y)}return l("transfer_destination_exists")}B=`.reason-copy-${k$()}`,K=Z.open(Q.fd,B,J0.O_CREAT|J0.O_EXCL|J0.O_WRONLY|J0.O_NOFOLLOW,384),Z.inherit(Q.fd,K);let F;try{let z=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!z.ok||!z.body)return l("transfer_download_failed");F=z.body.getReader()}catch(z){return u1(z,$.signal,"transfer_download_failed")}let X=l2("sha256"),W=0;try{while(!0){$.signal.throwIfAborted();let z=await F.read().catch((N)=>u1(N,$.signal,"transfer_download_failed"));if(z.done)break;if(W+=z.value.length,W>G)return l("transfer_size_mismatch");X.update(z.value);for(let N=0;N<z.value.length;)$.signal.throwIfAborted(),N+=b$(K,z.value,N,Math.min(s2,z.value.length-N))}}finally{await F.cancel().catch(()=>{})}if(W!==G||X.digest("hex")!==U)return l("transfer_hash_mismatch");return f$(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)p1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}Z.closeDirectory(Q.fd)}}finally{Z.close()}}}}catch(J){return u$(J,$.signal,$.direction)}}import{spawn as n$}from"child_process";import{mkdtempSync as r$,rmSync as a$,writeFileSync as i$}from"fs";import{constants as o$,platform as t$,tmpdir as e$}from"os";import{join as b8}from"path";import{gunzipSync as c$,gzipSync as YV}from"zlib";var S8=900000,zV=S8+60000,K1=49152,k8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),f8=V.object({version:V.literal(1),script_gzip:k8(163840),stdin_gzip:k8(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(S8)}).strict(),c2=V.string().max(K1+256),NV=V.object({exit_code:V.number().int().min(0).max(255),stdout:c2,stderr:c2,combined:c2.optional()}).strict();function n2($){return c$(Buffer.from($,"base64")).toString("utf8")}var $J="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",JJ=["RUSTUP_HOME","TZ","LC_ALL"],ZJ=2000,QJ=100;function a2(){return t$()==="linux"&&process.geteuid?.()===0}function r2($){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 Y=U.subarray(0,J-Q);Z.push(Y),Q+=Y.length,U=U.subarray(Y.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?`
|
|
36
36
|
[reason: ${G} bytes of output omitted]
|
|
37
|
-
`:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({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=v8(i2($,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(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(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=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(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{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(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(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*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(c1,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()+t2;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(t2,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 J3=["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 vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.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 CJ($){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 N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)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 MJ($,J,Z=500){if(J instanceof N0&&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 jJ($,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 uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{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}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))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 $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(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>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[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)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(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(LJ({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||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...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&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.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(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.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 N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.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 U5(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(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-baqm3872.js");return Q.parse(await this.request(s.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(s.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 F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.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 TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=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 a1($,J){if(TJ.has($))return!1;if(V1.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($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){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>xJ)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")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,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:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.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:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
|
|
37
|
+
`:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({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=v8(i2($,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(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(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=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(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{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(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(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*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(c1,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()+t2;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(t2,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 J3=["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 vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.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 CJ($){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 N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)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 MJ($,J,Z=500){if(J instanceof N0&&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 jJ($,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 uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{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}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))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 $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(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>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[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)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(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(LJ({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||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...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&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.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(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.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 N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.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 U5(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(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-3g0rc3wp.js");return Q.parse(await this.request(s.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(s.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 F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.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 TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=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 a1($,J){if(TJ.has($))return!1;if(V1.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($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){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>xJ)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")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,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:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.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:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
|
|
38
38
|
`,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,M5).split("\x00",1)[0]?.trim();return Q?cJ(Q):null}catch{return null}}async function _5($,J=G3){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function P5($,J=G3){let Z=[];for(let Q of await I5(J)){if(Z.length>=aJ)break;let K=await _5(Q,J);if(!K||!O5($,K))continue;Z.push({pid:Q,command:await A5(Q,J),cwd:QZ($,K)})}return{processes:Z}}function L5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function KZ($){let J=[];for(let Y=0;Y<16;Y+=2)J.push($[Y]<<8|$[Y+1]);if(J.slice(0,5).every((Y)=>Y===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let Y=0;Y<=J.length;Y+=1){if(Y<J.length&&J[Y]===0){if(K<0)K=Y;continue}if(K>=0){let F=Y-K;if(F>Q)Z=K,Q=F;K=-1}}let B=J.map((Y)=>Y.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 BZ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=L5($);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(...L5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${KZ(Z)}]:${J}`}return null}function VZ($,J){let Z=[];for(let Q of $.split(`
|
|
39
39
|
`).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=j5)continue;if(K[$Z]?.toUpperCase()!==JZ)continue;let B=K[eJ]??"",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 Y=BZ(B.slice(0,G),U),F=K[j5];if(!Y||!F||!/^[0-9]+$/.test(F))continue;Z.push({inode:F,port:U,address:Y})}return Z}async function GZ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=w5)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...VZ(Q,w5-J.length))}return J}async function XZ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await I5(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,tJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(ZZ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function T5($,J=G3){let Z=await GZ(J),Q=await XZ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let W=Q.get(X.inode);if(W===void 0)continue;K.push({pid:W,port:X.port,address:X.address})}K.sort((X,W)=>X.pid-W.pid||X.port-W.port||(X.address<W.address?-1:X.address>W.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,iJ),G=await Promise.all(B.map(async(X)=>[X,await _5(X,J)])),U=new Map(G),Y=K.filter((X)=>{let W=U.get(X.pid);return Boolean(W&&O5($,W))}),F=new Map(await Promise.all([...new Set(Y.map((X)=>X.pid))].map(async(X)=>[X,await A5(X,J)])));return{ports:Y.slice(0,oJ).map((X)=>({pid:X.pid,command:F.get(X.pid)??null,address:X.address}))}}import{posix as U3}from"path";var i1=200,UZ=250,FZ=250;async function o1($,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 X3($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var R5="/System/Volumes/Data",YZ=["/tmp","/var","/etc"];function F3($){let J=U3.normalize($);if(J.startsWith(`${R5}/`))J=J.slice(R5.length);return YZ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function q5($){return $&&U3.isAbsolute($)?F3($):null}async function g5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=i1){let K=J.slice(Q,Q+i1).join(",");for(let B of await o1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:q5(B.names[0])})}return Z}async function E5($,J){let Z=F3($),Q=(await o1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=q5(B.names[0]);return G!==null&&X3(Z,G)}).map((B)=>B.pid).slice(0,UZ),K=await g5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&X3(Z,G.cwd)?[{pid:B,command:G.command,cwd:U3.relative(Z,G.cwd)||"."}]:[]})}}async function k5($,J){let Z=F3($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await o1(J,Q),B=await g5(J,K.map((F)=>F.pid)),G=K.map((F)=>F.pid).filter((F)=>{let X=B.get(F)?.cwd;return Boolean(X&&X3(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((F)=>F.names.map((X)=>`${F.pid} ${X}`))),Y=[];for(let F=0;F<G.length;F+=i1){let X=G.slice(F,F+i1).join(",");for(let W of await o1(J,["-a","-p",X,...Q]))for(let z of W.names)if(U.has(`${W.pid} ${z}`))Y.push({pid:W.pid,command:W.command,address:z})}return{ports:Y.slice(0,FZ)}}import{join as AZ}from"path";import{spawn as wZ}from"child_process";import{randomUUID as MZ}from"crypto";import{chmodSync as b5,lstatSync as x5,mkdirSync as jZ,readdirSync as LZ,statSync as OZ,unlinkSync as IZ}from"fs";import{join as W3}from"path";var Y3={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var t1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var I0=()=>{throw Error("proof_visual_contract_invalid")};class S5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function zZ($){if(!X1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new S5;if(!X1($.viewport)||!t1($.viewport.width,1,4096)||!t1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>Y3.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return I0();let J=$.targets.map((Q)=>{if(!X1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return I0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return I0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return I0();Z=$.additionalViewports.map((K)=>{if(!X1(K)||!t1(K.width,1,4096)||!Number.isInteger(K.width)||!t1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return I0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return I0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var HZ=["organizationId","userId","sessionId","runId"],CZ=[...HZ,"prUrl","headSha","skillDigest","evidenceKind"],GG=[...CZ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DZ={"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 f5($){return DZ[$].directory}var y5=10485760;function h5($={}){let J=$.directory??f5("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((w)=>w!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");jZ(J,{recursive:!0,mode:457});let B=x5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");b5(J,457);let G=LZ(J).filter((w)=>/^[a-f0-9-]{36}\.webm$/.test(w)).map((w)=>({name:w,time:OZ(W3(J,w)).mtimeMs})).sort((w,D)=>D.time-w.time);for(let w of G.slice(9))IZ(W3(J,w.name));let U=W3(J,`${MZ()}.webm`),Y=["-f","x11grab","-framerate","12","-i",$.display??":99"],F=($.spawn??wZ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...Y,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(y5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,W,z=!1,N=new Promise((w,D)=>{X=w,W=D});F.stdout.on("data",(w)=>{if(/frame=\s*[1-9]/.test(String(w)))z=!0,X()});let C=new Promise((w,D)=>{F.once("error",()=>{W(Error("cloud_browser_recording_unavailable")),D(Error("cloud_browser_recording_unavailable"))}),F.once("exit",(j)=>{try{if(j!==0&&j!==255)throw Error();let O=x5(U);if(!z||!O.isFile()||O.isSymbolicLink()||O.uid!==process.getuid?.()||O.size<128||O.size>y5+65536)throw Error();b5(U,420),X(),w({path:U,mimeType:"video/webm"})}catch{W(Error("cloud_browser_recording_failed")),D(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let M=setTimeout(()=>F.kill("SIGKILL"),(Number(K)+5)*1000);C.finally(()=>clearTimeout(M)).catch(()=>{}),Z={done:C,stop:()=>{return F.kill("SIGINT"),C}};try{await N}catch(w){throw Z=null,w}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 u5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??m5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AZ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??v5)();return B??=h5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:b1(),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 E3}from"child_process";import{createHash as lZ,randomUUID as sZ}from"crypto";import{existsSync as Q0,mkdirSync as P3,mkdtempSync as k3,readdirSync as G2,readFileSync as S3,renameSync as cZ,rmSync as Y1,statSync as Q2,writeFileSync as nZ}from"fs";import{homedir as f3,tmpdir as U6}from"os";import{basename as F6,dirname as T3,join as k,relative as Y6,resolve as R3,sep as W6}from"path";var a=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),e1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),p5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),N3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),H3=["home","lock","side_button","siri","apple_pay"],_Z=V.enum(["tree","screenshot","both","none"]),PZ=V.object({...N3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),D0={observe:_Z.optional(),wait_for:PZ.optional(),timeout:V.number().min(0).max(20).optional()},z3=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...N3.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(H3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),C3=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:e1.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:e1.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(()=>z3)).max(30).optional(),...D0}).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:e1.optional(),bundle_id:p5.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).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:p5}).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:e1.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(),...N3.shape,duration:V.number().min(0).max(10).optional(),...D0}).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(),...D0}).strict(),V.object({action:V.literal("type"),device:a.optional(),text:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("button"),device:a.optional(),name:V.enum(H3),...D0}).strict(),V.object({action:V.literal("open_url"),device:a.optional(),url:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("steps"),device:a.optional(),steps:V.array(z3).min(1).max(30),...D0}).strict(),V.object({action:V.literal("appearance"),device:a.optional(),mode:V.enum(["light","dark"])}).strict()]),d5=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(),PG=V.object({text:V.string(),error:V.string().optional(),device:d5.optional(),devices:V.array(d5).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 TG=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),$2={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. Required for boot and shutdown; for other actions omit it 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",description:"build_status (required): the build_id a build or run returned."},app_path:{type:"string",description:"launch: the built .app from build_status (or pass bundle_id instead)."},bundle_id:{type:"string",description:"terminate (required); launch: an installed app's bundle id instead of app_path."},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number",description:"tap (with y, unless id or label is given) or swipe (required): start point in device points."},y:{type:"number"},x2:{type:"number",description:"swipe (required, with y2): end point in device points."},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect (instead of x and y)."},label:{type:"string",description:"tap: accessibility label from inspect (instead of x and y)."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string",description:"type (required): the text to type."},name:{type:"string",enum:[...H3],description:"button (required)."},url:{type:"string",description:"open_url (required): the URL or deep link."},mode:{type:"string",enum:["light","dark"],description:"appearance (required)."},steps:{type:"array",maxItems:30,description:"steps (required, at least one) or launch and run: 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."}},s5=C3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),TZ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},l5=new Set;function RZ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...$2.steps,minItems:1}:$2[$];if(Z===void 0||l5.has($))return Q;return l5.add($),{...Q,description:Z}}var qZ=s5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn($2,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(TZ[J]??[{required:[]}]).map((K)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((B)=>!K.without?.includes(B)).map((B)=>[B,RZ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),gZ={type:"object",properties:{action:{type:"string",enum:s5.map(($)=>$.action.value)},...$2},required:["action"],additionalProperties:!1},RG={...gZ,anyOf:qZ};import{spawn as j3}from"child_process";import{createHash as kZ}from"crypto";import{existsSync as w3,mkdirSync as J2,mkdtempSync as SZ,readdirSync as c5,readFileSync as n5,renameSync as fZ,rmSync as r5,symlinkSync as M3,writeFileSync as U1}from"fs";import{homedir as bZ}from"os";import{dirname as t5,join as x}from"path";import{createInterface as xZ}from"readline";var D3=`// Reason's simulator host: one warm process per booted iOS Simulator.
|
|
40
40
|
//
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sd as ae,Ud as ne}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Sd as ae,Ud as ne}from"./vm-hands-entry-lite-gq3bzj7d.js";import{wf as be}from"./vm-hands-entry-lite-02zaqpgh.js";import{$f as Y,Uf as C,Vf as ie,Xf as M,Yf as Oe,ag as z,bg as v,kg as O,lg as Be}from"./vm-hands-entry-lite-zd5pw8gj.js";import{Sg as Se}from"./vm-hands-entry-lite-hfv2tsm9.js";import{Hi as se}from"./vm-hands-entry-lite-jsbgswhd.js";import{gj as J}from"./vm-hands-entry-lite-rnmy7f5e.js";import{mj as x}from"./vm-hands-entry-lite-5x04hakp.js";import{dk as Ne,ek as oe}from"./vm-hands-entry-lite-ebgackey.js";import{kk as ye,qk as Ie}from"./vm-hands-entry-lite-p1s0xyc2.js";import{xk as xe}from"./vm-hands-entry-lite-fb02h1zm.js";import{Gk as p}from"./vm-hands-entry-lite-g87z5eb6.js";import{spawn as S,spawnSync as pt}from"child_process";import{createHash as ft,randomUUID as Te}from"crypto";import{closeSync as mt,copyFileSync as de,existsSync as q,fstatSync as _t,mkdirSync as pe,openSync as ht,readdirSync as D,readFileSync as j,readlinkSync as wt,renameSync as ve,rmSync as gt,statSync as bt,writeFileSync as xt}from"fs";import{connect as St}from"net";import{tmpdir as F,userInfo as Re}from"os";import{basename as fe,delimiter as yt,dirname as B,join as f}from"path";var Z=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{wa as f}from"./vm-hands-entry-lite-
|
|
2
|
+
import{wa as f}from"./vm-hands-entry-lite-3ptq7p60.js";import{ni as K,ri as U,si as y,yi as T}from"./vm-hands-entry-lite-csecgmaa.js";import{Di as v}from"./vm-hands-entry-lite-ksz1k1dh.js";import{jk as $}from"./vm-hands-entry-lite-8pgggvbb.js";var u=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function _(x){let w=typeof x==="string"?u.exec(x):null;return w?{major:Number(w[1]),minor:Number(w[2])}:null}import{createHash as s,randomBytes as j}from"crypto";import{createInterface as o}from"readline";import{randomBytes as d}from"crypto";import{chmodSync as q,existsSync as C,lstatSync as l,mkdirSync as a,readFileSync as b,renameSync as p,unlinkSync as O,writeFileSync as L}from"fs";import{homedir as t}from"os";import{dirname as i,join as F}from"path";function B(x=process.env,w=t()){let H=x.XDG_CONFIG_HOME?.trim()||F(w,".config"),J=K({env:x})==="staging"?["staging"]:[];return F(T(H,...J),"credentials.json")}function A(x,w=B()){return a(i(w),{recursive:!0,mode:448}),L(w,`${JSON.stringify(x,null,2)}
|
|
3
3
|
`,{mode:384}),q(w,384),w}function M(x=B()){if(!C(x))return null;try{let w=b(x,"utf8"),H=JSON.parse(w);if(typeof H.apiOrigin!=="string"||typeof H.clientId!=="string"||typeof H.accessToken!=="string"||typeof H.refreshToken!=="string"||typeof H.expiresAt!=="string"||typeof H.orgId!=="string"||!Array.isArray(H.scopes))return null;let G=new URL(H.apiOrigin).origin,J=U(G);if(J!==G)n(x,w,J);return{apiOrigin:J,clientId:H.clientId,accessToken:H.accessToken,refreshToken:H.refreshToken,expiresAt:H.expiresAt,scopes:H.scopes.filter((Q)=>typeof Q==="string"),orgId:H.orgId}}catch{return null}}function n(x,w,H){let G=`${x}.${process.pid}.${d(6).toString("hex")}.tmp`;try{let J=l(x);if(!J.isFile()||process.platform!=="win32"&&J.uid!==process.geteuid?.())return;let Q=JSON.parse(w);if(L(G,`${JSON.stringify({...Q,apiOrigin:H},null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),q(G,384),b(x,"utf8")!==w)throw Error("credentials_changed");p(G,x)}catch{try{O(G)}catch{}}}function R(x=B()){if(!C(x))return!1;return O(x),!0}var S=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var o0=S.filter((x)=>x!=="network:read"&&x!=="network:write");class D extends Error{oauthCode;constructor(x,w=null){super(x);this.oauthCode=w;this.name="LoginError"}}function r0(){let x=j(48).toString("base64url"),w=s("sha256").update(x).digest("base64url");return{verifier:x,challenge:w,state:j(32).toString("base64url")}}function r(x,w){let H=typeof x.error==="string"?x.error:null,G=typeof x.error_description==="string"?x.error_description:H?H:w;return new D(G,H)}async function e(x,w,H,G){let J=await H(`${x}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:w,signal:G}),Q=await J.json().catch(()=>({}));if(!J.ok)throw r(Q,`OAuth token request failed (${J.status})`);return Q}var x0=1e4;async function w0(x,w={}){let H=w.fetchImpl??fetch,G=await e(x.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:x.clientId,refresh_token:x.refreshToken}),H,AbortSignal.timeout(x0)).catch((Q)=>{if(Q instanceof Error&&Q.name==="TimeoutError")throw new D("Reason did not answer the login refresh in time. Check the network and retry.");throw Q});if(typeof G.access_token!=="string"||typeof G.refresh_token!=="string"||typeof G.expires_in!=="number")throw new D("Reason returned an incomplete refreshed login.");let J={...x,accessToken:G.access_token,refreshToken:G.refresh_token,expiresAt:new Date(Date.now()+G.expires_in*1000).toISOString(),scopes:typeof G.scope==="string"?G.scope.split(/\s+/).filter(Boolean):x.scopes};return A(J,w.path??B()),J}var z=new Map;function k(x,w){if(!w)return x;if(w.aborted)return Promise.reject(w.reason);return new Promise((H,G)=>{let J=()=>G(w.reason);w.addEventListener("abort",J,{once:!0}),x.then(H,G).finally(()=>w.removeEventListener("abort",J))})}async function P(x={}){let w=x.path??B(),H=M(w);if(!H)return null;let G=x.apiOrigin??v(process.env,"REASON_API_URL")?.trim();if(G&&!y(H.apiOrigin,new URL(G).origin))return null;let J=Date.parse(H.expiresAt)<=Date.now()+60000;if(!x.forceRefresh&&!J)return H;let Q=[w,H.apiOrigin,H.clientId,H.refreshToken].join("\x00"),V=z.get(Q);if(V)return k(V,x.signal);let Z;return Z=w0(H,{fetchImpl:x.fetchImpl,path:w}).catch(async(Y)=>{if(!(Y instanceof D)||Y.oauthCode!=="invalid_grant"&&Y.oauthCode!=="invalid_client")throw Y;let N=M(w),c=Y.oauthCode==="invalid_client"?N?.clientId!==H.clientId:N?.refreshToken!==H.refreshToken;if(N&&c)return P({fetchImpl:x.fetchImpl,path:w});return R(w),null}).finally(()=>{if(z.get(Q)===Z)z.delete(Q)}),z.set(Q,Z),k(Z,x.signal)}function e0(x,w){return new Promise((H)=>{let G=o({input:x}),J=!1,Q=(Z)=>{if(J)return;J=!0,w.removeEventListener("abort",V),G.close(),x.pause(),H(Z)},V=()=>Q(null);w.addEventListener("abort",V,{once:!0}),G.once("line",(Z)=>Q(Z)),G.once("close",()=>Q(null))})}var $0=$.object({label:$.string(),used_percent:$.number().min(0).max(100).nullable(),resets_at:$.string().nullable(),exhausted:$.boolean().nullable()}),H0=$.object({groups:$.array($.object({selectable:$.boolean().optional(),accounts:$.array($.object({source_id:$.string().min(1),model_ids:$.array($.string().min(1)).optional()}))}))});function G0(x){let w=H0.safeParse(x);if(!w.success)return;return w.data.groups.some((H)=>H.selectable!==!1&&H.accounts.some((G)=>G.model_ids===void 0||G.model_ids.length>0))}class X extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor(x,w,H,G,J,Q){super(H);this.status=x;this.code=w;this.suggestedModel=G;this.retryAfterMs=J;this.resolutionReason=Q;this.name="ApiError"}static rateLimitDelayMs(x,w){if(!(x instanceof X)||x.status!==429)return null;return Math.min(60000,Math.max(w,x.retryAfterMs??0))}}var J0=["minimal","low","medium","high","xhigh","max"],Q0=$.object({id:$.string().min(1),kind:$.string(),name:$.string(),custom_name:$.string().nullish(),status:$.string(),online:$.boolean(),compatible:$.boolean().optional(),compatibility_reason:$.string().nullish(),folder_lane_of:$.string().nullish(),roots:$.array($.object({id:$.string().min(1),label:$.string()}))}),W0=$.object({devices:$.array(Q0),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),Z0=$.object({id:$.string().min(1),name:$.string()}),V0=$.object({items:$.array(Z0)}),X0=$.object({id:$.string().min(1),name:$.string(),main:$.boolean(),mine:$.boolean(),session_id:$.string().nullish(),appearance:$.object({color:$.string().nullish()}).nullish().catch(null)}),Y0=$.object({items:$.array(X0)}),B0=$.object({skill_id:$.string().min(1),name:$.string(),description:$.string().nullish(),activation_keywords:$.array($.string()).default([]),is_enabled:$.boolean().default(!0)}),D0=$.object({items:$.array(B0).default([])}),z0=$.object({id:$.string().min(1),kind:$.string(),enabled:$.boolean(),schedule:$.object({expression:$.string().nullish(),every_seconds:$.number().nullish(),next_run_at:$.string().nullish()}).nullish(),github:$.object({event:$.string().nullish(),action:$.string().nullish(),repo:$.string().nullish()}).nullish(),last_fired_at:$.string().nullish()}),h=$.object({id:$.string().min(1),name:$.string().nullish(),instructions:$.string().nullish(),enabled:$.boolean(),triggers:$.array(z0).default([])}),N0=$.object({items:$.array(h).default([]),end_cursor:$.string().nullish(),has_next_page:$.boolean().optional()}),K0=$.object({id:$.string().min(1),slug:$.string().nullish(),name:$.string(),description:$.string().nullish(),transport:$.string().nullish(),url:$.string().nullish(),enabled:$.boolean()}),M0=$.object({items:$.array(K0).default([])}),P0=$.object({status:$.string(),summary:$.string().nullish(),category:$.string().nullish(),outcome:$.string().nullish(),message_count:$.number().nullish(),pr_url:$.string().nullish(),cost_usd:$.number().nullish(),generated_at:$.string().nullish()}),E=$.object({tags:$.array($.string()).default([])}),_0=$.enum(["linux","macos"]),I=$.object({id:$.string().min(1),name:$.string().min(1),platform:_0.nullable(),workers:$.object({total:$.number().int(),online:$.number().int(),busy:$.number().int(),idle:$.number().int()}),sessions:$.object({queued:$.number().int(),running:$.number().int()})}),F0=$.object({machines:$.array(I)}),U0=$.object({machine:I}),T0=$.object({deleted:$.literal(!0),revoked_workers:$.number().int(),revoked_tokens:$.number().int()}),q0=$.object({token:$.object({id:$.string().min(1),machine_id:$.string().min(1),token_prefix:$.string()}),secret:$.string().startsWith("rmt_")}),m=$.looseObject({machine_id:$.string().min(1),machine_name:$.string().min(1)}),C0=m.extend({organization_id:$.string().min(1)}),b0=$.object({id:$.string().min(1),name:$.string().min(1),state:$.enum(["waiting","placed"]),queue_position:$.number().int().nullable()});function J1(x){let w=b0.safeParse(x.machine);return w.success?w.data:null}var O0=$.union([$.object({kind:$.literal("cloud")}),$.object({kind:$.enum(["mac","headless"]),device_id:$.string().min(1),root_id:$.string().min(1)})]);function Q1(x){let w=O0.safeParse(x.runs_on);return w.success?w.data:null}function W(x,w,H){let G=x.safeParse(w);if(!G.success)throw new X(502,H,"Reason returned an unexpected response.");return G.data}var L0=$.object({error:$.object({type:$.string(),message:$.string()})});function g(x,w,H){let G=L0.safeParse(w),J=typeof w.error==="string"?w.error:G.success?G.data.error.type:`http_${x}`,Q=typeof w.detail==="string"?w.detail:typeof w.message==="string"?w.message:G.success?G.data.error.message:`Reason request failed (${x}${typeof w.error==="string"?` ${w.error}`:""})`,V=J==="github_connection_required"&&typeof w.connect_url==="string"&&/^https?:\/\//.test(w.connect_url)?` Connect it at ${w.connect_url}`:"",Z=H===null||H.trim()===""?NaN:Number(H);return new X(x,J,`${Q}${V}`,typeof w.suggested_model==="string"?w.suggested_model:void 0,Number.isFinite(Z)&&Z>=0?Z*1000:void 0,typeof w.resolution_reason==="string"?w.resolution_reason:void 0)}async function W1(x){let w=await(x.fetchImpl??fetch)(`${x.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${x.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(x.body),signal:AbortSignal.timeout(30000),redirect:"error"}),H=await w.json().catch(()=>({}));if(!w.ok)throw g(w.status,H,w.headers.get("retry-after"));return W(C0,H,"invalid_machine_ticket")}class A0{options;credentials;constructor(x,w={}){this.options=w;this.credentials=x}trackEvent(x,w={}){}async request(x,w={},H=!1){let G=this.options.fetchImpl??fetch,J=await G(`${this.credentials.apiOrigin}/v3${x}`,{method:w.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...w.raw?{"content-type":w.raw.contentType}:w.body===void 0?{}:{"content-type":"application/json"},...w.headers},body:w.raw?w.raw.bytes:w.body===void 0?void 0:JSON.stringify(w.body),signal:w.signal,redirect:"error"}),Q=await J.json().catch(()=>({}));if(J.status===401&&!H&&w.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let V=await P({fetchImpl:G,path:this.options.credentialsPath,forceRefresh:!0,signal:w.signal});if(V)return this.credentials=V,this.request(x,w,!0)}if(!J.ok)throw g(J.status,Q,J.headers.get("retry-after"));return Q}createHeadlessDeviceEnrollmentTicket(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(x){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:x,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(w){if(w instanceof X&&(w.status===404||w.status===405||w.status===403&&w.code==="endpoint_not_available"))return null;throw w}}addDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(x)}/roots/${encodeURIComponent(w)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(x,w=""){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return x===void 0?H:`${H}/${encodeURIComponent(x)}${w}`}async listMachines(){return W(F0,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(x){let w=await this.request(this.machinePath(),{method:"POST",body:{name:x.name,...x.platform?{platform:x.platform}:{}}});return W(U0,w,"invalid_machine").machine}async deleteMachine(x){let w=await this.request(this.machinePath(x),{method:"DELETE"});return W(T0,w,"invalid_machine_deletion")}async createMachineToken(x){let w=await this.request(this.machinePath(x,"/tokens"),{method:"POST",body:{}});return W(q0,w,"invalid_machine_token")}async createMachineEnrollmentTicket(x,w){let H=await this.request(this.machinePath(x,"/enrollment-tickets"),{method:"POST",body:w,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return W(m,H,"invalid_machine_ticket")}self(x){return this.request("/self",{signal:x})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:x,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:x,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:x,signal:w});return W(f,H,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(x)}`,{method:"POST",body:w,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:{messages:x},signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((w)=>typeof w.email==="string"?[{email:w.email,role:typeof w.role==="string"?w.role:"member"}]:[])}claimExistingCliPairing(x){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:x}})}async claudeCodeSignIn(x){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:x?AbortSignal.any([x,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(x,w,H={}){let G=x.kind==="setup_token"?{setup_token:x.token}:{access_token:x.credential.access,refresh_token:x.credential.refresh,expires_at:new Date(x.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:H.retryUnauthorized,signal:H.signal,body:{...G,...w?{account_key:w}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((w)=>{let H=typeof w.full_name==="string"?w.full_name:typeof w.repo_full_name==="string"?w.repo_full_name:null;if(!H)return[];return[{repo_id:typeof w.repo_id==="string"?w.repo_id:void 0,full_name:H,provider:w.provider==="gitlab"?"gitlab":"github",default_branch:typeof w.default_branch==="string"?w.default_branch:null,private:typeof w.private==="boolean"?w.private:void 0}]})}async listProjects(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),w=V0.safeParse(x);if(!w.success)throw new X(502,"invalid_project_list","Reason returned an unexpected project list.");return w.data.items}async listReasons(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return W(Y0,x,"invalid_reason_list").items}async openReasonConversation(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(x)}/conversation`,{method:"POST"});return W($.object({session_id:$.string().min(1)}),w,"invalid_reason_conversation").session_id}async listSkills(){try{let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return W(D0,x,"invalid_skill_list").items}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return[];throw x}}async listDevices(){let x=[],w=null;for(let H=0;H<50;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${w?`?after=${encodeURIComponent(w)}`:""}`),J=W0.safeParse(G);if(!J.success)throw new X(502,"invalid_device_list","Reason returned an unexpected machine list.");if(x.push(...J.data.devices),w=J.data.has_next_page?J.data.end_cursor??null:null,!w)break}return x}async listModels(){try{let w=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((J)=>J.hidden!==!0),H=w.filter((J)=>J.available!==!1).map(({reasoning_efforts:J,hidden:Q,available:V,...Z})=>({...Z,...Array.isArray(J)?{reasoning_efforts:J0.filter((Y)=>J.includes(Y))}:{}})),G=new Set(H.map((J)=>J.detail));return{models:H.length>1&&G.size===1?H.map(({detail:J,...Q})=>Q):H,runnable:H.length>0||w.length===0}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return{models:[],runnable:!0};throw x}}async getAgentVersion(x){try{let w=await this.request("/deployment",{signal:x,retryUnauthorized:!1});return _(w.reason_version)?w.reason_version:null}catch{return null}}async getUsageQuota(){try{let x=$0.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!x.success)return null;let w;try{w=G0(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...x.data,own_inference:w}}catch(x){if(x instanceof X&&(x.status===403||x.status===404))return null;throw x}}async listSessions(x=50,w,H={}){let G=new URLSearchParams({first:String(Math.min(Math.max(x,1),200)),status:H.status??"active"});if(w)G.set("project_id",w);if(H.origin)G.set("origin",H.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${G.toString()}`)).items??[]}getSession(x,w){let H=w?.fields.length?`?fields=${encodeURIComponent(w.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${H}`)}async prestartSession(x){let w=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:x}});return w?.status==="starting"||w?.status==="ready"}async createSession(x){let w=x.mode==="ephemeral"||x.workspaceOwnership==="externally-managed";if(x.attachments?.length)await this.requireSessionAttachments();if(w||x.runtimeProfile){let J=await this.request("/deployment");if(w&&(!Array.isArray(J.session_modes)||!J.session_modes.includes(x.mode??"standard")||!Array.isArray(J.workspace_ownerships)||!J.workspace_ownerships.includes(x.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(x.runtimeProfile&&(!Array.isArray(J.experimental_runtime_profiles)||!J.experimental_runtime_profiles.includes(x.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:x.prompt,...x.attachments?.length?{attachments:x.attachments}:{},...x.mode?{mode:x.mode}:{},...x.workspaceOwnership?{workspace_ownership:x.workspaceOwnership}:{},...x.target?{target:x.target}:{},...x.repo?{repo:x.repo}:{},...x.provider?{provider:x.provider}:{},...x.model?{model:x.model}:{},...x.reasoningEffort?{reasoning_effort:x.reasoningEffort}:{},...x.runtimeProfile?{experimental_runtime_profile:x.runtimeProfile}:{},...x.ref?{ref:x.ref}:{},...x.branch?{branch:x.branch}:{},...x.completionMode?{completion_mode:x.completionMode}:{},...x.env&&Object.keys(x.env).length>0?{env:x.env}:{},...x.clientSessionId?{client_session_id:x.clientSessionId}:{},...x.longRunning?{long_running:{enabled:!0}}:{},...x.spendLimitRcu?{spend_limit_rcu:x.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),G=await this.getSession(H.session_id);if(w){let J=G.session_policy,Q=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!J||J.version!==1||J.mode!==(x.mode??"standard")||J.workspaceOwnership!==(x.workspaceOwnership??"managed")||!J.components||Q.some((V)=>J.components[V]!==!0))throw await this.cancelSession(H.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(x.runtimeProfile&&G.experimental_runtime_profile!==x.runtimeProfile)throw await this.cancelSession(H.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return G}async getEvents(x,w=-1,H={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/events?after_seq=${w}&limit=500${H.waitMs?`&wait_ms=${H.waitMs}`:""}`,H.signal?{signal:H.signal}:{})}catch(G){if(!(G instanceof X)||G.status!==403&&G.status!==404)throw G;return{session:await this.getSession(x),items:[],next_seq:w}}}async getMessages(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages?first=500${w===void 0?"":`&after_seq=${w}`}`)}async getAttachments(x,w){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/attachments${w?`?view=${w}`:""}`)).items??[]}catch(H){if(H instanceof X&&(H.status===403||H.status===404))return[];throw H}}async requireSessionAttachments(){let x=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(x.session_attachments!==!0){let w=typeof x.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(x.reason_version)?`Agent ${x.reason_version}`:null,H=typeof x.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(x.commit_sha)?`server ${x.commit_sha.slice(0,12)}`:null,G=[w,H].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${G?` (${G})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(x,w,H={}){if(H.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages`,{method:"POST",body:{message:w,...H.attachments?.length?{attachments:H.attachments}:{},...H.model?{model:H.model}:{},...H.reasoningEffort?{reasoning_effort:H.reasoningEffort}:{},...H.target?{target:H.target}:{},...H.delivery?{delivery:H.delivery}:{}}})}async steerQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/messages/${encodeURIComponent(w)}/queued`,{method:"DELETE"})}async getConversation(x){let w=[],H=null;for(let G=0;G<50;G+=1){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/conversation${H?`?after=${encodeURIComponent(H)}`:""}`);if(w.push(...J.items??[]),!J.has_next_page||!J.end_cursor)break;H=J.end_cursor}return w}createSharedLink(x,w){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/shared-links`,{method:"POST",body:{url:w.url,...w.label?{label:w.label}:{},...w.expiresInSeconds!==void 0?{expires_in_seconds:w.expiresInSeconds}:{}}})}sessionAction(x,w,H={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/${w}`,{method:"POST",body:H})}renameSession(x,w){return this.sessionAction(x,"rename",{title:w||null})}moveSessionToProject(x,w){return this.sessionAction(x,"project",{project_id:w})}compactSession(x){return this.sessionAction(x,"compact")}retrySession(x){return this.sessionAction(x,"retry")}rewindSession(x,w){return this.sessionAction(x,"rewind",{message_id:w.messageId,content:w.content,request_id:w.requestId})}forkSession(x,w){return this.sessionAction(x,"fork",{...w.message?{message:w.message}:{},client_session_id:w.clientSessionId})}cancelSession(x,w={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}/cancel`,{method:"POST",body:w.mode==="hard"?{mode:"hard"}:{}})}sessionPath(x,w=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(x)}${w}`}async archiveSession(x){await this.request(this.sessionPath(x,"/archive"),{method:"POST",body:{}})}async unarchiveSession(x){await this.request(this.sessionPath(x,"/unarchive"),{method:"POST",body:{}})}async deleteSession(x){await this.request(this.sessionPath(x),{method:"DELETE"})}async listSessionTags(x){return W(E,await this.request(this.sessionPath(x,"/tags")),"invalid_session_tags").tags}async appendSessionTags(x,w){let H=await this.request(this.sessionPath(x,"/tags"),{method:"POST",body:{tags:w}});return W(E,H,"invalid_session_tags").tags}async sessionInsight(x,w=!1){let H=await this.request(this.sessionPath(x,w?"/insights/generate":"/insights"),w?{method:"POST",body:{}}:{});return W(P0,H,"invalid_session_insight")}async listAutomations(){let x=[],w=null;for(let H=0;H<20;H+=1){let G=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${w?`&after=${encodeURIComponent(w)}`:""}`),J=W(N0,G,"invalid_automation_list");if(x.push(...J.items),w=J.has_next_page?J.end_cursor??null:null,!w)break}return x}async createScheduledAutomation(x,w){let H=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,G=W(h,await this.request(H,{method:"POST",body:{name:x.name,instructions:x.instructions,...x.repo?{repo:x.repo.full_name,provider:x.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${H}/${encodeURIComponent(G.id)}/triggers`,{method:"POST",body:w})}catch(J){throw await this.deleteAutomation(G.id).catch(()=>{return}),J}return G}async setAutomationEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"PATCH",body:{enabled:w}})}async deleteAutomation(x){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(x)}`,{method:"DELETE"})}async transcribe(x,w){let H=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:x,contentType:w}});return W($.object({transcript:$.string()}),H,"invalid_transcript").transcript}async listMcpServers(){let x=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return W(M0,x,"invalid_mcp_server_list").items}async setSkillEnabled(x,w){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(x)}`,{method:"PUT",body:{is_enabled:w}})}}
|
|
5
5
|
export{B as A,M as B,r0 as C,P as D,e0 as E,X as F,J0 as G,J1 as H,Q1 as I,W1 as J,A0 as K};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
3
|
-
export{O as
|
|
2
|
+
import{Qj as $}from"./vm-hands-entry-lite-ecsgqm1s.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
|
|
3
|
+
export{O as Mj,Z as Nj,S as Oj,k as Pj};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Jk as e}from"./vm-hands-entry-lite-f78n4wqt.js";var i=e((o,t)=>{t.exports={name:"playwright-core",version:"1.60.0",description:"A high-level API to automate web browsers",repository:{type:"git",url:"git+https://github.com/microsoft/playwright.git"},homepage:"https://playwright.dev",engines:{node:">=18"},author:{name:"Microsoft Corporation"},license:"Apache-2.0",exports:{".":{types:"./index.d.ts",import:"./index.mjs",require:"./index.js",default:"./index.js"},"./package.json":"./package.json","./lib/bootstrap":"./lib/bootstrap.js","./lib/coreBundle":"./lib/coreBundle.js","./lib/utilsBundle":"./lib/utilsBundle.js","./lib/tools/cli-client/program":"./lib/tools/cli-client/program.js"},bin:{"playwright-core":"cli.js"},types:"types/types.d.ts"}});
|
|
3
3
|
export{i as Aa};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{wg as k0}from"./vm-hands-entry-lite-adpzn7fe.js";import{Ng as f0}from"./vm-hands-entry-lite-00800vjk.js";import{Tg as uq}from"./vm-hands-entry-lite-hfv2tsm9.js";import{fj as cq}from"./vm-hands-entry-lite-rnmy7f5e.js";import{mj as i}from"./vm-hands-entry-lite-5x04hakp.js";import{$j as h0,Vj as _,Yj as g0,ak as G8,bk as y0,dk as l8,gk as G0,ik as A0}from"./vm-hands-entry-lite-ebgackey.js";import{kk as H0}from"./vm-hands-entry-lite-p1s0xyc2.js";import{Gk as K}from"./vm-hands-entry-lite-g87z5eb6.js";import{execFile as f1,spawn as I0}from"child_process";import{randomBytes as g1}from"crypto";import{chmodSync as h1,existsSync as p0,lstatSync as k1,mkdirSync as I1,readFileSync as p1,rmSync as v1,writeFileSync as Wq}from"fs";import{connect as u1}from"net";import{join as $}from"path";var Gq="./desktop-wallpaper-0pjhgyfk.jpg";var Aq="./dock-browser-afp005mt.png";var Sq="./dock-files-rywdm96b.png";var Vq="./dock-terminal-s41cj1jp.png";var Fq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -248,4 +248,4 @@ Gtk.main()
|
|
|
248
248
|
`).flatMap((P)=>{let X=P.indexOf("=");return X>0?[[P.slice(0,X),P.slice(X+1)]]:[]})))}catch{return{}}}var E0=new Set;async function t1(q,x,Q){let P=await o1(),X=/^:(\d+)(?:\.\d+)?$/.exec(P.DISPLAY??"")?.[1];if(!X||`:${X}`===A8||P.WAYLAND_DISPLAY||P.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${X}`,xauthority:P.XAUTHORITY??$(q,".Xauthority"),rfbSocket:$(x,`rfb-${X}.sock`)},J=`${b.display} ${b.xauthority}`;if(E0.has(J)||!await o({path:`/tmp/.X11-unix/X${X}`},!1))return null;let N={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await u0(Q,b,x,`x11vnc-${X}.log`,N))return{...b,sound:null};return E0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
|
|
249
249
|
`),null}function e1(q,x){let Q=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,P=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!p0(`/usr/bin/${b}`)).map(([b])=>b),X=Mq({root:q,display:x,screen:Nq,browserExec:Q,absent:P});for(let b of["","openbox","tint2","picom"])S8($(q,b));for(let[b,J]of Object.entries(X.files))Wq($(q,b),J,{mode:384});for(let[b,J]of Object.entries(zq))Wq($(q,`ara-${b}`),p1(J),{mode:384});return{root:q,openboxConfig:$(q,"openbox","rc.xml"),start:X.start}}async function q9(q,x){let Q=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
|
|
250
250
|
`);await new Promise((P)=>{let X=I0("/bin/sh",["-c",Q],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{X.kill(),P()},V8);X.once("error",()=>{clearTimeout(b),P()}),X.once("exit",()=>{clearTimeout(b),P()})})}async function uQ(q,x={}){let Q=x.now??Date.now,P=a1(q.payload,Q());if(q.signal.throwIfAborted(),!P.video)throw new K("display_video_required","Reason desktops stream as video now; this request came without it.");let X=x.platform??process.platform;if(X!=="linux"&&X!=="darwin"&&X!=="win32")throw new K("display_video_unsupported","This machine does not serve desktop video.");let b=P.video,J=(x.video?.desktop??(X==="darwin"?async()=>S0:X==="win32"?async()=>V0:i1))();return await x9(q.signal,P,x,Q,(N)=>w0(N,{request:b,desktop:J,...P.viewer?{viewer:P.viewer}:{},viewerSameNetwork:P.viewer_same_network===!0},x.video),(N)=>G8({type:"error",code:N}))}function x9(q,x,Q,P,X,b){let J=P();return new Promise((N,T)=>{let L=null,C=!1,U=!1,y,R,Y,S=!1,W=null,G=(A)=>{if(U)return;if(W)A=W;U=!0,clearTimeout(y),clearTimeout(R),q.removeEventListener("abort",F),Y?.close();try{L?.close(1000,"display_session_over")}catch{}if("error"in A){T(A.error);return}N({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,P()-J)})},V=()=>G({error:new K("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;G({error:A instanceof K?A:new K("cancelled","Reason closed the desktop session.")})},E=()=>{if(!W||!L)return;let A=W.error;try{L.send(b(A instanceof K?A.code:"display_unavailable"))}catch{}G(W)};if(Y=X({get done(){return U||W!==null},get open(){return C&&!U&&W===null},get bufferedAmount(){return L?.bufferedAmount??0},send(A){if(U||W||!C||!L)return;try{L.send(A)}catch{G({reason:"relay_closed"})}},end:(A)=>{if(U||W)return;if(!("error"in A)){G(A);return}if(W=A,S&&C)E()}}),U){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),y=setTimeout(()=>G({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-P())),R=setTimeout(()=>G({reason:"viewer_absent"}),Q.viewerWaitMs??l1);try{L=(Q.connect??k0)(x.relay_url,(Q.loadProxy??f0)()?.url)}catch{V();return}L.binaryType="arraybuffer",L.onopen=()=>{if(U||!L)return;C=!0,Y?.opened()},L.onmessage=(A)=>{if(U)return;let f=A.data,p=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!p||p.byteLength===0)return;if(clearTimeout(R),S=!0,W){E();return}Y?.received(p)},L.onclose=()=>{if(U)return;if(!C){V();return}G({reason:"relay_closed"})},L.onerror=()=>{if(U||C)return;V()}})}
|
|
251
|
-
export{g8 as
|
|
251
|
+
export{g8 as Uf,D9 as Vf,y9 as Wf,d as Xf,T8 as Yf,FQ as Zf,bq as _f,pq as $f,oq as ag,I as bg,t9 as cg,e9 as dg,qQ as eg,c1 as fg,A8 as gg,a1 as hg,O0 as ig,vQ as jg,S8 as kg,i1 as lg,uQ as mg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./vm-hands-entry-lite-
|
|
2
|
+
import"./vm-hands-entry-lite-ezahexcb.js";import"./vm-hands-entry-lite-02zaqpgh.js";import"./vm-hands-entry-lite-8pgggvbb.js";import{Mk as A}from"./vm-hands-entry-lite-f78n4wqt.js";import{readFileSync as J}from"fs";var G=performance.now();delete process.env.BUN_BE_BUN;var q=(j,b={})=>console.log(JSON.stringify({stage:j,ms:Math.round(performance.now()),...b}));async function K(){if(process.argv.includes("--vm-hands-op-runner")){let{runVmHandsOpRunner:D}=await import("./vm-hands-op-runner-sfhzq9bc.js");await D();return}q("parsed",{t0:Math.round(G)});let j="";try{j=J(3,"utf8")}catch{}q("fd3_read",{bytes:j.length});let b=null;if(j.trim())try{b=JSON.parse(j)}catch{b=null}if(!b||typeof b!=="object"||Array.isArray(b))q(j.trim()?"identity_invalid":"identity_free"),await new Promise(()=>{setInterval(()=>{return},1073741824)});let{parseVmHandsInit:B,runVmHands:C}=await import("./vm-hands-runtime-r0y0c22t.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{s as wq}from"./vm-hands-entry-lite-
|
|
2
|
+
import{s as wq}from"./vm-hands-entry-lite-hp0ccw3e.js";import{Mb as Nq,qc as Aq,wb as jq,wc as Rq}from"./vm-hands-entry-lite-6t0a7k6v.js";import"./vm-hands-entry-lite-h0keewxv.js";import"./vm-hands-entry-lite-r166b92s.js";import"./vm-hands-entry-lite-180h5amj.js";import"./vm-hands-entry-lite-02zaqpgh.js";import"./vm-hands-entry-lite-00800vjk.js";import"./vm-hands-entry-lite-hfv2tsm9.js";import"./vm-hands-entry-lite-wpcagqfw.js";import"./vm-hands-entry-lite-a1yy1yp3.js";import"./vm-hands-entry-lite-bwpay74g.js";import"./vm-hands-entry-lite-csecgmaa.js";import"./vm-hands-entry-lite-ksz1k1dh.js";import"./vm-hands-entry-lite-mft9ke08.js";import"./vm-hands-entry-lite-5x04hakp.js";import"./vm-hands-entry-lite-3nr9q3nf.js";import"./vm-hands-entry-lite-ecsgqm1s.js";import"./vm-hands-entry-lite-8pgggvbb.js";import"./vm-hands-entry-lite-p1s0xyc2.js";import"./vm-hands-entry-lite-fb02h1zm.js";import"./vm-hands-entry-lite-8e932j3c.js";import"./vm-hands-entry-lite-88h9vwrv.js";import"./vm-hands-entry-lite-g87z5eb6.js";import"./vm-hands-entry-lite-f78n4wqt.js";import{spawn as gq}from"child_process";import{chmodSync as Sq,chownSync as Eq,existsSync as l,lstatSync as e,mkdirSync as r,mkdtempSync as yq,readdirSync as s,readFileSync as I,realpathSync as mq,rmdirSync as qq,rmSync as uq,writeFileSync as y}from"fs";import{join as L}from"path";import{readFileSync as Wq,readlinkSync as Gq}from"fs";import{relative as _q}from"path";var Jq=16;function Yq(X){return X.replace(/\\([0-7]{3})/g,($,W)=>String.fromCharCode(Number.parseInt(W,8)))}function hq(X){let $=[];for(let W of X.split(`
|
|
3
3
|
`)){let q=W.split(" ");if(q.length<10||!/^\d+:\d+$/.test(q[2]))continue;$.push({device:q[2],root:Yq(q[3]),mountPoint:Yq(q[4])})}return $}function kq(X,$,W){let q=X.replace(/\/+$/,"")||"/",J=(F)=>q==="/"||F===q||F.startsWith(`${q}/`),G=(F)=>new Map(hq(F).filter((R)=>J(R.mountPoint)).map((R)=>[`${R.mountPoint}\x00${R.device}\x00${R.root}`,R.mountPoint])),Y=G($),A=G(W),j=(F)=>_q(q,F)||".",f=[...Y].filter(([F])=>!A.has(F)).map(([,F])=>j(F)),O=[...A].filter(([F])=>!Y.has(F)).map(([,F])=>j(F));return{missing:f,extra:O,referenceCount:Y.size,ownCount:A.size}}function Kq(X,$,W,q="/proc"){let J,G,Y=null;try{J=Wq(`${q}/1/mountinfo`,"utf8"),G=Wq(`${q}/self/mountinfo`,"utf8")}catch(R){let v=R&&typeof R==="object"&&"code"in R&&typeof R.code==="string"?R.code:"unreadable";$("vm_hands.mount_check_unavailable",{code:v});return}try{Y=Gq(`${q}/1/ns/mnt`)===Gq(`${q}/self/ns/mnt`)}catch{}let{missing:A,extra:j,referenceCount:f,ownCount:O}=kq(X,J,G),F={reference_count:f,own_count:O,missing_count:A.length,extra_count:j.length,same_namespace:Y};if(j.length)$("vm_hands.mount_extra",{...F,extra:j.slice(0,Jq)});if(A.length)throw $("vm_hands.mount_mismatch",{...F,missing:A.slice(0,Jq)}),W(`${A.length} mount(s) under the Session root are missing from vm-hands' namespace`)}var Pq="/sys/fs/cgroup/reason-payload",H="vm-hands",lq="/run/ara-srt/fallbacks.jsonl",E="/reason-person",Xq=5000,cq=1e4,Bq="__VM_HANDS_PROOF_DIR__",pq="__VM_HANDS_PROBE_NONCE__";class D extends Error{code;constructor(X,$){super($);this.code=X}}function aq(X,$){if(!/^[0-9a-f-]{36}$/i.test($))throw new D("vm_hands_bind_invalid","bad bind id");return L(X,H,`b-${$.toLowerCase()}`)}var tq=5000,Iq=(X)=>`'${X.replaceAll("'","'\\''")}'`;function JX(X){let $=X.cgroup??Pq,W=X.init.layout.payload_uid,q=X.log??(()=>{}),J=new Map,G=new Map,Y=0,A=()=>{try{let Z=I("/run/ara-srt/starts.jsonl","utf8"),z=Z.slice(Y>Z.length?0:Y).split(`
|
|
4
4
|
`).filter(Boolean);Y=Z.length;let K=z.map((U)=>{try{return Number(JSON.parse(U).elapsed_ms)||0}catch{return 0}});if(K.length)q("vm_hands.srt_server_starts",{count:K.length,elapsed_ms:K.slice(0,8)})}catch{}},j=null,f=!1,O=X.srtCgroup??"/sys/fs/cgroup/reason-srt",F=()=>{j??=Uq()},R=0,v=()=>{try{let Z=I(lq,"utf8"),z=Z.slice(R>Z.length?0:R);R=Z.length;let K=z.split(`
|
|
5
5
|
`).filter(Boolean).slice(0,1000);if(!K.length)return null;let U={},T=0;for(let N of K)try{let M=JSON.parse(N),B=typeof M.code==="string"&&/^[a-z_]{1,40}$/.test(M.code)?M.code:"other";if(U[B]=(U[B]??0)+1,typeof M.elapsed_ms==="number")T=Math.max(T,M.elapsed_ms)}catch{U.unparsed=(U.unparsed??0)+1}return q("vm_hands.srt_fallbacks",{count:K.length,codes:U,max_elapsed_ms:T}),{count:K.length,codes:U,max_elapsed_ms:T}}catch{return null}},P=!1,m=(Z,z,K)=>{if(P)throw Error("vm_hands_pool_held");return vq(Z,z,K)},i=(Z)=>(z,K,U)=>gq("/bin/sh",["-c",`echo $$ > ${Iq(L(Z,"cgroup.procs"))} || exit 125; exec "$@"`,"vm-hands-join",z,...K],U),vq=i(L($,H)),u=L($,H,"probe"),g=(Z)=>aq($,Z),bq=(Z)=>{let z=g(Z);try{r(z,{mode:493})}catch(K){if(!(K&&typeof K==="object"&&("code"in K)&&K.code==="EEXIST"))throw new D("vm_hands_bind_failed","bind cgroup")}return z},xq=(Z)=>{try{qq(g(Z))}catch{}},x=X.prespawn?Nq({spawnProcess:m,...X.relayDependencies?.sourceEntrypoint?{sourceEntrypoint:X.relayDependencies.sourceEntrypoint}:{},log:(Z,z)=>q(Z,z??{})}):null;x?.arm();let n=x?setInterval(()=>{x.arm()},tq):null;n?.unref?.();async function c(Z){let z=J.get(Z);if(J.delete(Z),!z)return;z.abort.abort(),await z.done}return{bindCgroup:g,async startExecutor(Z){if(F(),G.set(Z.bindId,Uq()),f=!0,!Z.claim)throw new D("vm_hands_bind_invalid","an executor needs the claim it serves");await c(Z.bindId);let{claim:z,bindId:K}=Z,U=bq(K),T=z.owner;if(!T||typeof T.device_id!=="string"||typeof z.root_id!=="string")throw new D("vm_hands_bind_invalid","claim without its owner Device or root");let N=new AbortController,M,B,V=new Promise((Q,w)=>{M=Q,B=w}),_,C=new Promise((Q)=>{_=Q}),S=Rq({headless:!0,hostExecution:!0,runtimeDirectory:X.runtimeDirectory,deviceIdentity:{deviceId:T.device_id,rootId:z.root_id,apiOrigin:X.apiOrigin},claimOwner:z.owner,root:X.root,runId:z.run_id,operationId:z.operation_id,attemptId:z.attempt_id,payload:Object.fromEntries(Object.entries(z.payload).filter(([Q])=>!Q.startsWith("vm_hands_"))),signal:N.signal,...Z.workspaceGrant?{workspaceGrant:Z.workspaceGrant}:{},emitEvent:async(Q,w)=>{if(Q==="hands.ready"){M(w);return}if(Q==="hands.started"||Q==="hands.stopped"||Q==="hands.failed")return;await X.forward(K,Q,w)}},{...X.relayDependencies,spawnWorker:(Q)=>i(U)(Q.command,Q.args,Q.options),...x?{takePrespawnedWorker:(Q)=>{let w=x.take(Q);if(!w?.pid)return w;try{return y(L(U,"cgroup.procs"),String(w.pid)),w}catch{try{w.kill("SIGKILL")}catch{}return null}},adoptSpawnedWorker:x.adopt}:{}}).then(()=>{_("executor_stopped")},(Q)=>{let w=Q&&typeof Q==="object"&&"code"in Q?String(Q.code):"executor_failed";B(new D(w,Q instanceof Error?Q.message:String(Q))),_(w)}).finally(()=>B(new D("vm_hands_executor_exited","executor ended before it was ready")));J.set(K,{abort:N,done:S,exited:C,operationId:z.operation_id,runId:z.run_id,expiresAtMs:Date.parse(String(z.payload.expires_at??""))||0});let h=await V,p=h.executor_launch_id;if(typeof p!=="string")throw new D("vm_hands_bind_failed","executor ready without a launch id");return{launchId:p,readyData:h,applied:{hands_confinement:typeof z.payload.hands_confinement==="string"?z.payload.hands_confinement:null,browser_egress:z.payload.browser_egress??null}}},takeSrtFallbacks:v,executorExited(Z){return J.get(Z)?.exited??new Promise(()=>{})},freezeBind(Z){let z=g(Z);if(l(L(z,"cgroup.freeze")))y(L(z,"cgroup.freeze"),"1")},async killAndVerifyPayload(Z){let z=new Set(Z?.keep??[]);if(z.size||Z?.own)return Hq(Z?.bindId??null,z,Z?.own===!0);P=!0;let K=Tq();try{await Mq();let U=Promise.all([...J.keys()].map((B)=>c(B).catch(()=>{return})));A();let T=Date.now()+Xq;await a($,T,"payload"),await U;let N=(f||X.srtWarmLate?.()===!0)&&l(L(O,"cgroup.events"));if(N)await a(O,T,"srt");let M=$q(W).filter((B)=>!b(B,E));if(j!==null){let B=Zq(j).filter((V)=>V!==process.pid&&!b(V,E));if(B.length)throw q("vm_hands.kill_strays",{strays:t(B)}),new D("vm_hands_kill_unverified",`${B.length} process(es) the run started survived it`);j=null}if(f=!1,N)X.onSrtReset?.();if(M.length)throw q("vm_hands.kill_survivors",{pids:M.slice(0,16)}),new D("vm_hands_kill_unverified",`${M.length} payload-uid process(es) outside the payload cgroup`);G.clear();for(let B of zq())try{qq(L($,H,B))}catch{}}finally{P=!1,K()}if(x)setTimeout(()=>{if(!J.size)x.arm()},100).unref?.()},async killProbe(){let Z=Date.now()+Xq;if(l(L(u,"cgroup.events"))){await a(u,Z,"probe");try{qq(u)}catch{}}let z=Qq(process.pid);if(z===null)throw new D("vm_hands_kill_unverified","agent start time unreadable");await dq($,z,Z);let K=(T)=>{let N=Qq(T);return N!==null&&N<=z},U=$q(W).filter((T)=>K(T)&&!b(T,E));if(U.length)throw q("vm_hands.kill_survivors",{pids:U.slice(0,16),at:"attest"}),new D("vm_hands_kill_unverified",`${U.length} payload-uid process(es) from before this agent`);if(j!==null){let T=[$,L($,H)].map((B)=>B.replace(/^\/sys\/fs\/cgroup/,"")),N=O.replace(/^\/sys\/fs\/cgroup/,""),M=Zq(j).filter((B)=>B!==process.pid&&!b(B,E)&&!b(B,"/reason-vm-hands")&&!b(B,N)&&!T.some((V)=>Lq(B,V)));if(M.length&&f)throw q("vm_hands.kill_strays",{strays:t(M),at:"attest"}),new D("vm_hands_kill_unverified",`${M.length} process(es) the run started survived it`);if(M.length)q("vm_hands.attest_concurrent",{processes:t(M),count:M.length});j=null}},async runProbe({nonce:Z,script:z}){if(F(),!z.includes(Bq))throw new D("vm_hands_probe_failed","probe names no proof directory");let K=X.proofParent??"/tmp/reason-vm-hands-proof";r(K,{mode:457,recursive:!0});let U=e(K);if(U.isSymbolicLink()||!U.isDirectory()||U.uid!==(process.getuid?.()??-1)||(U.mode&4095)!==457)throw new D("vm_hands_probe_failed","proof parent is not root's 0711 directory");let T=yq(L(K,"p-")),N=!1;try{if(!/^[A-Za-z0-9/._-]+$/.test(T)||!/^[A-Za-z0-9_-]{1,128}$/.test(Z))throw new D("vm_hands_probe_failed","proof directory path or nonce");Eq(T,W,W),Sq(T,448);let M=e(T).ino;try{r(u,{mode:493})}catch(C){if(!(C&&typeof C==="object"&&("code"in C)&&C.code==="EEXIST"))throw new D("vm_hands_probe_failed","probe cgroup")}let B=i(u)("/bin/bash",["-c",z.replaceAll(Bq,T).replaceAll(pq,Z)],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:["ignore","pipe","ignore"]}),V="";B.stdout?.on("data",(C)=>{if(V.length<16384)V+=C.toString("utf8").slice(0,16384-V.length)});let _=await new Promise((C)=>{let S=setTimeout(()=>{N=!0,B.kill("SIGKILL"),C(124)},cq);B.once("error",()=>{clearTimeout(S),C(127)}),B.once("close",(h)=>{clearTimeout(S),C(h??1)})});return q("vm_hands.probe",{nonce_len:Z.length,exit_code:_}),{exitCode:_,markers:V,proofDirInode:M}}finally{if(!N)uq(T,{recursive:!0,force:!0})}},restatLayout(){let{session_root:Z,alias:z}=X.init.layout,K="invalid";try{Aq(Z),K="0:0:755"}catch{}let U=!1,T=-1;try{let N=e(z);T=N.uid,U=K==="0:0:755"&&z===L(Z,"repo")&&!N.isSymbolicLink()&&N.isDirectory()&&mq(z)===z&&N.uid===W}catch{}return{root_mode:K,alias_ok:U,owner_uid:T}},verifyMounts(){Kq(X.init.layout.session_root,q,(Z)=>new D("vm_hands_mount_mismatch",Z))},installEnvironment(Z,z){let K=J.get(Z);if(!K)throw new D("environment_unavailable","no executor owns an environment");return jq({root:X.root,operationId:K.operationId,payload:z}).installed_revision},async stop(){if(n)clearInterval(n);x?.close(),await Promise.all([...J.keys()].map((Z)=>c(Z)))}};function zq(){try{return s(L($,H),{withFileTypes:!0}).filter((Z)=>Z.isDirectory()&&/^b-[0-9a-f-]{36}$/.test(Z.name)).map((Z)=>Z.name)}catch{return[]}}async function Hq(Z,z,K=!1){let U=new Set([...z].map((N)=>N.toLowerCase())),T=Tq();try{await Mq();let N=Date.now()+Xq,M=new Set(zq().filter((Q)=>!U.has(Q.slice(2))).map((Q)=>Q.slice(2)));if(Z)M.add(Z.toLowerCase());let B=null;for(let Q of M){let w=c(Q).catch(()=>{return}),o=G.get(Q);if(o!==void 0)B=B===null?o:Math.min(B,o);if(l(L(g(Q),"cgroup.events")))await a(g(Q),N,"bind");await w}let V=[...U].map((Q)=>g(Q).replace(/^\/sys\/fs\/cgroup/,"")),_=[$,L($,H)].map((Q)=>Q.replace(/^\/sys\/fs\/cgroup/,"")),C=O.replace(/^\/sys\/fs\/cgroup/,""),S=(Q)=>b(Q,E)||V.some((w)=>b(Q,w)),h=K?[]:$q(W).filter((Q)=>!S(Q));if(h.length)throw q("vm_hands.kill_survivors",{pids:h.slice(0,16),beside:U.size}),new D("vm_hands_kill_unverified",`${h.length} payload-uid process(es) outside a live bind`);let p=(Q)=>!S(Q)&&!b(Q,"/reason-vm-hands")&&!b(Q,C)&&!_.some((w)=>Lq(Q,w));if(B!==null){let Q=Zq(B).filter((w)=>w!==process.pid&&p(w));if(Q.length)throw q("vm_hands.kill_strays",{strays:t(Q),beside:U.size}),new D("vm_hands_kill_unverified",`${Q.length} process(es) the run started survived it`)}for(let Q of M)G.delete(Q),xq(Q)}finally{T()}}}function Qq(X,$="/proc"){try{let W=I(L($,String(X),"stat"),"utf8"),q=Number(W.slice(W.lastIndexOf(")")+2).split(" ")[19]);return Number.isFinite(q)?q:null}catch{return null}}function Cq(X,$="/proc"){try{let W=I(L($,String(X),"stat"),"utf8"),q=Number(W.slice(W.lastIndexOf(")")+2).split(" ")[1]);return Number.isFinite(q)?q:null}catch{return null}}async function dq(X,$,W){try{y(L(X,"cgroup.freeze"),"1")}catch(q){throw new D("vm_hands_kill_unverified",`payload cgroup.freeze: ${q instanceof Error?q.message:String(q)}`)}try{for(;;){let q=Oq(X).filter((G)=>fq(G,X)),J=new Set(q.filter((G)=>{let Y=Qq(G);return Y!==null&&Y<=$}));for(let G=!0;G;){G=!1;for(let Y of q){if(J.has(Y))continue;let A=Cq(Y);if(A!==null&&J.has(A))J.add(Y),G=!0}}if(J.size===0)return;if(Date.now()>W)throw new D("vm_hands_kill_unverified",`${J.size} previous-boot process(es) survived`);for(let G of J)try{process.kill(G,"SIGKILL")}catch{}await new Promise((G)=>setTimeout(G,10))}}finally{try{y(L(X,"cgroup.freeze"),"0")}catch{}}}function Lq(X,$,W="/proc"){try{return I(L(W,String(X),"cgroup"),"utf8").split(`
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{xa as m,ya as l,za as s}from"./vm-hands-entry-lite-ezahexcb.js";import{Ie as k}from"./vm-hands-entry-lite-02zaqpgh.js";import"./vm-hands-entry-lite-8pgggvbb.js";import{Mk as F}from"./vm-hands-entry-lite-f78n4wqt.js";import{spawn as t}from"child_process";import{createHash as e}from"crypto";import{lstatSync as x,mkdirSync as d,readFileSync as c,statSync as jj,writeFileSync as o}from"fs";var P="/run/reason-vm-hands",R="/run/reason-vm-hands/env",h="/home/runner/.reason/workspace",qj=/^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/,S="/sys/fs/cgroup/reason-srt",y="/usr/local/bin/ara-srt-exec",Jj=65536,Qj=21600000;function Zj(Q,j="/run/ara-srt"){try{if((process.getuid?.()??-1)!==0)return;d(j,{recursive:!0,mode:448});let q=x(j);if(!q.isDirectory()||q.uid!==0||(q.mode&63)!==0){Q("srt_base_keyed_skipped",{reason:"socket_dir_unsafe"});return}o(`${j}/base-keyed`,`1
|
|
3
|
+
`,{mode:420}),Q("srt_base_keyed",{})}catch{Q("srt_base_keyed_skipped",{reason:"error"})}}function p(Q,j){let q=(G)=>{return j("srt_warm_skipped",{reason:G}),Promise.resolve()};if(typeof Q.srt_base_settings!=="string")return q("no_settings");let Z=Buffer.from(Q.srt_base_settings,"base64");if(Z.length===0||Z.length>Jj||Z.toString("base64")!==Q.srt_base_settings)return q("settings_invalid");try{let G=x(S);if(!G.isDirectory()||G.uid!==0||(G.mode&18)!==0)return q("cgroup_unsafe");for(let[U,g]of[[y,!1],["/usr/local/bin",!0]]){let L=x(U);if((g?!L.isDirectory():!L.isFile())||L.uid!==0||(L.mode&18)!==0)return q("srt_exec_unsafe")}}catch{return q("cgroup_or_exec_missing")}if((process.getuid?.()??-1)!==0)return q("not_root");let X=performance.now(),z=e("sha256").update(Z).digest("hex"),N=`${P}/srt-base-settings.json`;try{o(N,Z,{mode:384,flag:"w"})}catch{return q("settings_write")}let W=t("/bin/sh",["-c",`echo $$ > ${S}/cgroup.procs || exit 125; exec "$@"`,"vm-hands-srt",y,"--settings",N,"--idle-ms",String(Qj),"--","/bin/true"],{cwd:"/",env:{PATH:"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"},stdio:"ignore"});return new Promise((G)=>{W.once("error",()=>{j("srt_warm_failed",{reason:"spawn"}),G()}),W.once("close",(U)=>{j(U===0?"srt_warm_done":"srt_warm_failed",{exit_code:U,warm_ms:Math.round(performance.now()-X),settings_sha256:z}),G()})})}var u=3000;function Nj(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let j=Q,q=j.layout,Z=j.device_key,X=j.credential;return typeof j.workspace_id==="string"&&Number.isSafeInteger(j.instance_generation)&&typeof j.api_origin==="string"&&qj.test(j.api_origin)&&typeof j.manifest_digest==="string"&&!!X&&typeof X.key_id==="string"&&Number.isSafeInteger(X.expires_at_ms)&&typeof X.signature==="string"&&!!q&&typeof q.session_root==="string"&&typeof q.alias==="string"&&Number.isSafeInteger(q.payload_uid)&&typeof q.kind==="string"&&!!Z&&typeof Z.pkcs8==="string"&&typeof Z.spki==="string"?j:null}function v(Q){d(Q,{recursive:!0,mode:448});let j=jj(Q);if(!j.isDirectory()||(j.mode&63)!==0||j.uid!==(process.getuid?.()??-1))throw Error(`vm_hands_runtime_directory_unsafe: ${Q}`)}async function $j(Q){let[{CLI_VERSION:j},q,Z,X]=await Promise.all([import("./version-8eeqhkse.js"),import("./hands-worker-source-msdkfx9x.js"),import("./network-contract-3h853c6e.js"),import("./device-workspace-35hjc1ff.js")]),{REASON_HANDS_PROTOCOL_VERSION:z}=await import("./reason-hands-protocol-mw7ba8vz.js");return{reason_runtime_version:j,bridge_version:j,protocol_version:k,execution_eligible:!0,instance_generation:Q.instance_generation,capabilities:{supported_operations:["hands.connect"],hands_worker_artifact_sha256:q.REASON_HANDS_WORKER_ARTIFACT_SHA256,hands_worker_entrypoint:q.REASON_HANDS_WORKER_ENTRYPOINT,hands_slots:1,max_payload_bytes:Z.LOCAL_OPERATION_MAX_BYTES,max_result_bytes:Z.LOCAL_OPERATION_MAX_BYTES,operation_constraints:{"hands.connect":{ready:!0,execution_mode:"host",transport:"wss_relay",worker:"ara_hands",slots:1,session_group:Z.HANDS_SESSION_GROUP,worker_version:q.REASON_HANDS_WORKER_VERSION,protocol_version:z,worker_artifact_sha256:q.REASON_HANDS_WORKER_ARTIFACT_SHA256,worker_entrypoint:q.REASON_HANDS_WORKER_ENTRYPOINT,policy_mode:"full_access",policy_version:1,workspace_base:X.REASON_WORKSPACE_BASE,workspace_layout:X.SESSION_WORKSPACE_LAYOUT,browser_state:"optional_headless",desktop:!1,max_session_ms:43200000,environment_delivery:Z.HANDS_ENVIRONMENT_DELIVERY,[Z.HANDS_ENVIRONMENT_AT_CLAIM_KEY]:Z.HANDS_ENVIRONMENT_AT_CLAIM,[Z.HANDS_CLOUD_ACCESS_KEY]:Z.HANDS_CLOUD_ACCESS,[Z.HANDS_LARGE_ENVIRONMENT_KEY]:Z.HANDS_LARGE_ENVIRONMENT,[Z.HANDS_CONFINEMENT_KEY]:Z.HANDS_CONFINEMENT,[Z.HANDS_JOBS_USER_KEY]:Z.HANDS_JOBS_USER,vm_hands:"v1"}}}}}var C=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.list","ports.list","pty.start","jobs.control","automation.call.v1"],Xj=new Set(["pty.start","jobs.control"]);function zj(Q,j){let q=j([{id:"vm-hands",label:"workspace",path:h,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}],{worker:{executionMode:"unsandboxed",readiness:Object.fromEntries(C.map((z)=>[z,!0]))}}),Z=Q.capabilities,X={...Z.operation_constraints};for(let z of C)X[z]={...q.operation_constraints?.[z]??{},ready:!0,execution_mode:q.operation_constraints?.[z]?.execution_mode??"host"};return{...Q,capabilities:{...Z,supported_operations:["hands.connect",...C],operation_constraints:X}}}function Gj(Q){for(let j of c("/etc/passwd","utf8").split(`
|
|
4
|
+
`)){let q=j.split(":");if(q.length>=4&&Number(q[2])===Q&&/^\d+$/.test(q[3]??"")&&Number(q[3])>0)return Number(q[3])}throw Error("vm_hands_payload_account_unavailable")}function Fj(Q,j){let q=j.owner;if(!q||typeof q.organization_id!=="string"||typeof q.device_id!=="string"||typeof j.root_id!=="string")return null;return{version:4,apiOrigin:Q.api_origin,orgId:q.organization_id,deviceId:q.device_id,devicePublicKey:"",displayName:"vm-hands",registeredAt:new Date(0).toISOString(),handsSlots:1,roots:[{id:j.root_id,label:"workspace",path:h,pathFingerprint:"0".repeat(64),permissions:{read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1}}]}}function Kj(Q=process.platform,j="/proc/self/oom_score_adj"){if(Q!=="linux")return null;let q;try{q=c(j,"utf8").trim()}catch{return{value:"unreadable"}}if(!/^-?\d+$/.test(q))return{value:"unreadable"};let Z=Number(q);return Z<0?{value:Z}:null}async function Wj(Q,j){let q=Kj();if(q)j("vm_hands.oom_protected",{code:"vm_hands_oom_protected",value:q.value}),await new Promise(()=>{setInterval(()=>{return},1073741824)});v(P),v(R),Zj(j);let Z=p(Q,j),X=!1,z=async()=>{if(!await Promise.race([Z.then(()=>!0),new Promise(($)=>setTimeout(()=>$(!1),u).unref?.())]))X=!0,j("srt_warm_late",{wait_ms:u})},[{configureDesktopAccount:N},{configureWorkerSandbox:W}]=await Promise.all([import("./desktop-account-8yf4aqgb.js"),import("./worker-sandbox-nnk7fq89.js")]);W();try{N({value:String(Q.layout.payload_uid)})}catch{j("payload_account_unavailable"),await new Promise(()=>{setInterval(()=>{return},1073741824)})}let G=new AbortController;for(let J of["SIGTERM","SIGINT"])process.on(J,()=>G.abort());let U=new Map,g,L=new Promise((J)=>{g=J}),A=L.then(()=>import("./vm-hands-executor-zsepc201.js")).then(({createVmHandsExecutor:J})=>{let $=J({init:Q,root:h,runtimeDirectory:P,apiOrigin:Q.api_origin,prespawn:!0,onSrtReset:()=>{X=!1,Z=p(Q,j)},srtWarmLate:()=>X,forward:(Y,K,H)=>U.get(Y)?.(K,H)??Promise.reject(Error("vm_hands_not_bound")),log:(Y,K)=>j(Y,K)});return j("executor_loaded"),$}),D=(J)=>async(...$)=>(await A)[J](...$),f=null;A.then((J)=>{f=($)=>J.executorExited($)});let M={startExecutor:async(...J)=>{return await z(),D("startExecutor")(...J)},killAndVerifyPayload:D("killAndVerifyPayload"),killProbe:D("killProbe"),runProbe:async(...J)=>{return await z(),D("runProbe")(...J)},restatLayout:()=>{throw Error("replaced below")},verifyMounts:()=>{throw Error("replaced below")},installEnvironment:()=>{throw Error("replaced below")},executorExited:(J)=>f?f(J):new Promise(()=>{}),takeSrtFallbacks:()=>null};A.then((J)=>{M.restatLayout=()=>J.restatLayout(),M.verifyMounts=()=>J.verifyMounts(),M.installEnvironment=($,Y)=>J.installEnvironment($,Y),M.freezeBind=($)=>J.freezeBind($),M.takeSrtFallbacks=()=>J.takeSrtFallbacks?.()??null});let n=await m(Q),r=new l(Q,n,M,{envRoot:R}),b=$j(Q),E=null,a=Promise.all([b,import("./local-capabilities-pv3gr2hy.js")]).then(([J,$])=>{E=zj(J,$.capabilityInventoryForRoots),j("device_ops_loaded")}).catch((J)=>j("device_ops_unavailable",{error:J instanceof Error?J.name:"error"})),w=L.then(()=>import("./vm-hands-executor-zsepc201.js")).then(({createVmHandsOpRunners:J,vmHandsBindCgroup:$,VM_HANDS_PAYLOAD_CGROUP:Y})=>J({payloadUid:Q.layout.payload_uid,payloadGid:Gj(Q.layout.payload_uid),bindCgroup:(K)=>$(Y,K),log:(K,H)=>j(K,H)})).catch(()=>null);w.then((J)=>J?.warm("person")),j("agent_ready"),await s({apiOrigin:Q.api_origin,agent:r,signal:G.signal,heartbeat:async()=>E??await b,executeOp:async({kind:J,claim:$,bindId:Y,signal:K,emit:H})=>{let T=Fj(Q,$);if(!T)return{status:"failed",error_code:"vm_hands_bind_invalid"};let _={executionMode:"unsandboxed",runtimeDirectory:P,readiness:Object.fromEntries(C.map((B)=>[B,!0]))},I=(B)=>{let V=typeof B.kind==="string"?B.kind:"";if(V)H({kind:V,...B.data&&typeof B.data==="object"?{data:B.data}:{}})};if($.capability==="exec.full"&&J!=="person")return{status:"failed",error_code:"capability_not_granted"};if($.capability==="automation.call.v1"&&J!=="model")return{status:"failed",error_code:"capability_not_granted"};let i=$.capability==="pty.start"&&J==="person"&&!$.authority;if(Xj.has(String($.capability))&&!i){let{executeLocalOperation:B}=await import("./local-capabilities-pv3gr2hy.js");return B(T,$,{worker:_,signal:K,emit:(V)=>I(V)})}let O=await w;if(!O)return{status:"failed",error_code:"vm_hands_payload_account_unavailable"};return O.run(J,{id:String($.attempt_id),claim:$,state:T,worker:_},I,K,Y)},readyData:({launchId:J})=>({executor_launch_id:J}),log:(J,$)=>{if(J==="vm_hands.registered"||J==="vm_hands.reconnected")g();j(J,$)},onTurn:(J,$)=>{if($)U.set(J,$);else U.delete(J)}}),await(await A).stop(),(await w)?.stop()}export{Kj as vmHandsOomProtection,p as startBaseSrtServer,Wj as runVmHands,Nj as parseVmHandsInit,$j as heartbeatBody,Zj as enableBaseKeyedSrt};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{r as a}from"./vm-hands-entry-lite-0seprnh3.js";import"./vm-hands-entry-lite-mc3pkj0q.js";import"./vm-hands-entry-lite-h0keewxv.js";import"./vm-hands-entry-lite-g7h6wjqy.js";import"./vm-hands-entry-lite-mft9ke08.js";import"./vm-hands-entry-lite-fb02h1zm.js";import"./vm-hands-entry-lite-8e932j3c.js";import"./vm-hands-entry-lite-88h9vwrv.js";import"./vm-hands-entry-lite-g87z5eb6.js";import"./vm-hands-entry-lite-f78n4wqt.js";export{a as configureWorkerSandbox};
|
package/package.json
CHANGED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{F as a,G as b,H as c,I as d,J as e,K as f}from"./vm-hands-entry-lite-30rnhzfj.js";import"./vm-hands-entry-lite-b1ygrkbq.js";import"./vm-hands-entry-lite-e2mjbqmr.js";import"./vm-hands-entry-lite-ma001vzh.js";import"./vm-hands-entry-lite-fyvgav60.js";import"./vm-hands-entry-lite-pk3q774c.js";import"./vm-hands-entry-lite-e05sgnwe.js";import"./vm-hands-entry-lite-te0p47ak.js";import"./vm-hands-entry-lite-f89wk20p.js";import"./vm-hands-entry-lite-stbfyev7.js";import"./vm-hands-entry-lite-grjkhbf2.js";export{d as sessionPlace,c as sessionMachine,e as createMachineEnrollmentTicketWithToken,f as ReasonApi,b as REASONING_EFFORTS,a as ApiError};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{v as a,w as b,x as c,y as d,z as e}from"./vm-hands-entry-lite-mbs7d7ye.js";import"./vm-hands-entry-lite-30rnhzfj.js";import"./vm-hands-entry-lite-b1ygrkbq.js";import"./vm-hands-entry-lite-rtt2w6c6.js";import"./vm-hands-entry-lite-e2mjbqmr.js";import"./vm-hands-entry-lite-ma001vzh.js";import"./vm-hands-entry-lite-fyvgav60.js";import"./vm-hands-entry-lite-pk3q774c.js";import"./vm-hands-entry-lite-e05sgnwe.js";import"./vm-hands-entry-lite-te0p47ak.js";import"./vm-hands-entry-lite-f89wk20p.js";import"./vm-hands-entry-lite-stbfyev7.js";import"./vm-hands-entry-lite-grjkhbf2.js";export{d as resolveApiCredentials,e as requireApiCredentials,b as explicitApiOrigin,c as environmentApiKey,a as apiOriginFromEnvironment};
|