@reason-machines/cli-linux-arm64-musl 0.2.370 → 0.2.372

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-af9g18n7.js +2 -0
  3. package/bin/vm-hands/api-credentials-65mrr3tn.js +2 -0
  4. package/bin/vm-hands/{ask-relay-rpjtthmx.js → ask-relay-ymd2qzgp.js} +3 -3
  5. package/bin/vm-hands/connect-cli-qc3wtvs2.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-wmcf39x6.js → custom-endpoint-device-zhpake9f.js} +1 -1
  7. package/bin/vm-hands/desktop-account-5zvgspyw.js +2 -0
  8. package/bin/vm-hands/{device-workspace-05nkwrpp.js → device-workspace-vbcry9d6.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-5wv1djgv.js → hands-worker-source-h0b1j53p.js} +1 -1
  10. package/bin/vm-hands/{index-kf4q2kw5.js → index-bbk6a9sk.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-vaytv1sf.js → install-receipt-7x81ek76.js} +1 -1
  12. package/bin/vm-hands/local-automation-a6jqeh24.js +2 -0
  13. package/bin/vm-hands/local-capabilities-mhszxbtw.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-0hadyvx1.js +2 -0
  15. package/bin/vm-hands/local-display-mac-v1pc7177.js +2 -0
  16. package/bin/vm-hands/local-display-session-n39tx1qm.js +2 -0
  17. package/bin/vm-hands/local-pty-session-hs7rq03x.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-ezr81rm7.js → managed-runtime-jqx6n9c8.js} +1 -1
  19. package/bin/vm-hands/network-contract-zqvt1v0t.js +2 -0
  20. package/bin/vm-hands/package-3cd7cfyv.js +2 -0
  21. package/bin/vm-hands/permissions-yg7dazpa.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-dase3v7x.js → reason-hands-protocol-8fxjynte.js} +1 -1
  23. package/bin/vm-hands/{serve-service-3vafkgbb.js → serve-service-65kzxsrc.js} +1 -1
  24. package/bin/vm-hands/{status-fcvw0v8v.js → status-3wwz3xqm.js} +2 -2
  25. package/bin/vm-hands/version-bsyrze8b.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-2c88t2at.js → vm-hands-entry-lite-00qsbphw.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-w4swepp1.js → vm-hands-entry-lite-1085xsma.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-78mcanwm.js → vm-hands-entry-lite-2jbj99sk.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-sfsgeynk.js → vm-hands-entry-lite-3hbe4em3.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-bnfssh7s.js → vm-hands-entry-lite-3wgag7rz.js} +1 -1
  31. package/bin/vm-hands/{vm-hands-entry-lite-nhfd61cx.js → vm-hands-entry-lite-45j8qwsf.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-67nbqeh3.js → vm-hands-entry-lite-4kfy4zcs.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-rjwk6sfj.js → vm-hands-entry-lite-4m40gwkf.js} +1 -1
  34. package/bin/vm-hands/{vm-hands-entry-lite-qdxaxw06.js → vm-hands-entry-lite-576m681k.js} +3 -3
  35. package/bin/vm-hands/{vm-hands-entry-lite-gzyps3ev.js → vm-hands-entry-lite-5kgvss4p.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-76343s1m.js → vm-hands-entry-lite-70xn5vnc.js} +23 -23
  37. package/bin/vm-hands/{vm-hands-entry-lite-e8skq97c.js → vm-hands-entry-lite-7shpbsw8.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-db4z7ekz.js → vm-hands-entry-lite-9cgm6g8t.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-dq1fdx0j.js → vm-hands-entry-lite-anmv8hp7.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-ngytzkx1.js → vm-hands-entry-lite-bvbfcp1k.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-9fr904x2.js → vm-hands-entry-lite-c01eyep6.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-b775ysr4.js → vm-hands-entry-lite-dcynw6t2.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-vygp7vq8.js → vm-hands-entry-lite-dgxxsdwb.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-7fx4xtf6.js → vm-hands-entry-lite-g036gtem.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-zmf1terc.js → vm-hands-entry-lite-hc3p6r9p.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-y3wncwjd.js → vm-hands-entry-lite-j2q1k9vb.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-d7y6aah1.js → vm-hands-entry-lite-jb2sr2r7.js} +1 -1
  48. package/bin/vm-hands/vm-hands-entry-lite-khjrcwrj.js +5 -0
  49. package/bin/vm-hands/{vm-hands-entry-lite-g576hpce.js → vm-hands-entry-lite-kxdw4myj.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-46zepeny.js → vm-hands-entry-lite-maqkw6pg.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-8sddhaka.js → vm-hands-entry-lite-mh0xecf3.js} +1 -1
  52. package/bin/vm-hands/{vm-hands-entry-lite-va5mj828.js → vm-hands-entry-lite-mrms7y4e.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-y7ne1jra.js → vm-hands-entry-lite-nb5kxm2n.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-bt6esncn.js → vm-hands-entry-lite-nhtb458c.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-5zmn6a7p.js → vm-hands-entry-lite-r6pap1kh.js} +1 -1
  56. package/bin/vm-hands/{vm-hands-entry-lite-mcv6pse6.js → vm-hands-entry-lite-sb9a1jcn.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-vq09as6r.js → vm-hands-entry-lite-vppy988d.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-dh92sc3f.js → vm-hands-entry-lite-xdm9jkgq.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-jxwajwd5.js → vm-hands-entry-lite-y3jxbhxs.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-1fzr8bk1.js → vm-hands-entry-lite-z964akpr.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-dm52srp5.js → vm-hands-entry-lite-za55dtte.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-x9pmwqjd.js → vm-hands-entry-lite-ze9msfq1.js} +2 -2
  63. package/bin/vm-hands/{vm-hands-entry-lite-2fyemnas.js → vm-hands-entry-lite-zfwg7ehq.js} +5 -5
  64. package/bin/vm-hands/{vm-hands-entry-lite-y9wkxydj.js → vm-hands-entry-lite-zh8p7ndn.js} +2 -2
  65. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  66. package/bin/vm-hands/{vm-hands-executor-49tjc3mh.js → vm-hands-executor-y16fdqnj.js} +2 -2
  67. package/bin/vm-hands/vm-hands-op-runner-sb4fa85z.js +2 -0
  68. package/bin/vm-hands/{vm-hands-runtime-2pxyfw0b.js → vm-hands-runtime-vq9kf92k.js} +3 -3
  69. package/bin/vm-hands/worker-sandbox-wpzkvwer.js +2 -0
  70. package/package.json +1 -1
  71. package/bin/vm-hands/api-credentials-ke2v1y5k.js +0 -2
  72. package/bin/vm-hands/api-ewpnfn05.js +0 -2
  73. package/bin/vm-hands/connect-cli-s7pwr65j.js +0 -2
  74. package/bin/vm-hands/desktop-account-cppm1dhr.js +0 -2
  75. package/bin/vm-hands/local-automation-h2x2cx40.js +0 -2
  76. package/bin/vm-hands/local-capabilities-g7vxm7je.js +0 -2
  77. package/bin/vm-hands/local-desktop-users-ejwwkfer.js +0 -2
  78. package/bin/vm-hands/local-display-mac-x0eq4rzq.js +0 -2
  79. package/bin/vm-hands/local-display-session-s6sx0xvh.js +0 -2
  80. package/bin/vm-hands/local-pty-session-pzg7bk32.js +0 -2
  81. package/bin/vm-hands/network-contract-zez17y8t.js +0 -2
  82. package/bin/vm-hands/package-gxv23nam.js +0 -2
  83. package/bin/vm-hands/permissions-4gvq1x6z.js +0 -2
  84. package/bin/vm-hands/version-x0gtqq24.js +0 -2
  85. package/bin/vm-hands/vm-hands-entry-lite-pt633d84.js +0 -5
  86. package/bin/vm-hands/vm-hands-op-runner-bgg6ajgz.js +0 -2
  87. package/bin/vm-hands/worker-sandbox-e4kvy715.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Fb as J7,Hb as f4,Ib as b4,Nb as Q7,Ob as B7,Yb as y4,ac as V7,bc as G7,cc as n4,dc as r4,fc as U7,hb as A4,hc as O8,ic as h0,jb as w2,jc as v0,kb as _4,kc as J2,lb as T4,mb as P4,nb as s6,nc as X7,ob as n6,pb as S4,qb as r6,qc as j8,rb as f3,rc as h4,sb as a6,tb as i6,tc as W7,ub as o6,vb as t6,wb as k4,xb as e6,yb as $7}from"./vm-hands-entry-lite-76343s1m.js";import{wc as H7,yc as C7,zc as D7}from"./vm-hands-entry-lite-b775ysr4.js";import{Ec as Z7}from"./vm-hands-entry-lite-mcv6pse6.js";import{Jc as i0,Kc as o0,Rc as R0}from"./vm-hands-entry-lite-dq1fdx0j.js";import{Sc as V1}from"./vm-hands-entry-lite-g9rvf5qk.js";import{Tc as Y7}from"./vm-hands-entry-lite-hh24bq0d.js";import{$c as s3,Xc as V2,Yc as G2,Zc as l3,bd as c3,cd as n3,gd as r3,id as d6}from"./vm-hands-entry-lite-2c88t2at.js";import{Cd as g7,qd as Q2,td as E7}from"./vm-hands-entry-lite-78mcanwm.js";import{$e as b6,Ae as d,Af as l8,Be as h1,Bf as s8,Cf as c8,Df as n8,Ee as g8,Ge as m1,Ie as D6,Je as M6,Ke as L6,Le as w6,Me as O6,Ne as j6,Oe as I6,Pe as A6,Qe as _6,Re as T6,Se as P6,Te as R6,Ue as z6,Ve as q6,We as E6,Xe as g6,Ye as S6,Ze as k6,_e as f6,bf as x6,cf as y6,df as h6,ef as m6,ff as v6,gf as p6,hf as u6,le as P1,me as R1,ne as S3,nf as S8,oe as F2,of as k8,pe as C6,pf as f8,qe as k3,qf as b8,re as W4,rf as x8,se as Y4,sf as y8,te as L0,uf as h8,vf as m8,wf as v8,xe as H0,xf as p8,yf as u8,zf as d8}from"./vm-hands-entry-lite-2fyemnas.js";import{Jf as Q6,Nf as w5,Of as v5,Uf as S7,Xf as O5,Yf as e1}from"./vm-hands-entry-lite-vq09as6r.js";import{$f as R7,Zf as T7,_f as P7,dg as z7,gg as q7}from"./vm-hands-entry-lite-x9pmwqjd.js";import{pg as x4,wg as K7}from"./vm-hands-entry-lite-vygp7vq8.js";import{Bg as Z2}from"./vm-hands-entry-lite-y9wkxydj.js";import{Gg as R3,Tg as l6}from"./vm-hands-entry-lite-dm52srp5.js";import{ni as F7,oi as N7}from"./vm-hands-entry-lite-qdxaxw06.js";import{Ai as j1,Bi as I1,Ci as A1,Di as _1,Ei as E0}from"./vm-hands-entry-lite-rjwk6sfj.js";import{Wi as E1,Xi as c6,Yi as E4,Zi as g4}from"./vm-hands-entry-lite-9fr904x2.js";import{$i as P3,bj as Q1,hj as w8,ij as D4}from"./vm-hands-entry-lite-db4z7ekz.js";import{Aj as L7,Bj as w7,Cj as O7,Ej as j7,Fj as I7,Hj as A7,Ij as _7,zj as M7}from"./vm-hands-entry-lite-e8skq97c.js";import{Tj as V}from"./vm-hands-entry-lite-zmf1terc.js";import{$j as C}from"./vm-hands-entry-lite-y3wncwjd.js";import{fk as W8}from"./vm-hands-entry-lite-7fx4xtf6.js";import{request as t7}from"http";import{request as e7}from"https";import{lookup as $9}from"dns/promises";import{isIP as J9}from"net";async function Z9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?e7:t7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:s3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var a3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),Q9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function i3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(a3.has(Z))return"custom_endpoint_host_not_found";if(Q9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=i3(Q,J+1);if(B)return B}return null}async function B9($,J){let Z=i3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||J9(Q)!==0)return Z;let B;return await Promise.race([$9(Q).then(()=>!0,(G)=>!a3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?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 V9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function o3($){$.signal.throwIfAborted();let J=n3.safeParse($.payload);if(!J.success)throw new C("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=r3.parse(await $.credential($.signal));if(!c3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new C("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,U=0,W=0,Y=K9(Q.apiKey),X=V9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(P)=>{$.signal.removeEventListener("abort",I),M(P)})})},H=async(N)=>{if(G+=N.length,G>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=V2){if(W>=l3)throw new C("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+V2).toString("base64")})}};try{let N=await Z9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new C("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new C("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=B.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of B){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await H(X(I))}return await H(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof C)throw N;throw new C((B?null:await B9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as t3}from"path";function G9($,J){return $===t3(J,".ara","workspace")||$===t3(J,".reason","workspace")}function e3($,J){let Z=$.filter((Q)=>G9(Q.path,J));return Z.length===1?Z[0].path:null}var U9=/^[a-f0-9]{64}$/;var U2=32,X9=/^\/[^\x00-\x1f\x7f\\]*$/;function w1($){if(typeof $!=="string"||$.length>4096||!X9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!w1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!U9.test(B)||!w1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function W9($){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 Y9($){return W9($)??$.email.toLowerCase()}function X2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?Y9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),F9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...I1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...A1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,..._1.map(($)=>`/[^/]*${n0($)}$`)],$4=`function localGithubSandboxProfile(root, temporary) {
2
+ import{Fb as J7,Hb as f4,Ib as b4,Nb as Q7,Ob as B7,Yb as y4,ac as V7,bc as G7,cc as n4,dc as r4,fc as U7,hb as A4,hc as O8,ic as h0,jb as w2,jc as v0,kb as _4,kc as J2,lb as T4,mb as P4,nb as s6,nc as X7,ob as n6,pb as S4,qb as r6,qc as j8,rb as f3,rc as h4,sb as a6,tb as i6,tc as W7,ub as o6,vb as t6,wb as k4,xb as e6,yb as $7}from"./vm-hands-entry-lite-70xn5vnc.js";import{wc as H7,yc as C7,zc as D7}from"./vm-hands-entry-lite-dcynw6t2.js";import{Ec as Z7}from"./vm-hands-entry-lite-sb9a1jcn.js";import{Jc as i0,Kc as o0,Rc as R0}from"./vm-hands-entry-lite-anmv8hp7.js";import{Sc as V1}from"./vm-hands-entry-lite-g9rvf5qk.js";import{Tc as Y7}from"./vm-hands-entry-lite-hh24bq0d.js";import{$c as s3,Xc as V2,Yc as G2,Zc as l3,bd as c3,cd as n3,gd as r3,id as d6}from"./vm-hands-entry-lite-00qsbphw.js";import{Cd as g7,qd as Q2,td as E7}from"./vm-hands-entry-lite-2jbj99sk.js";import{$e as k6,Ae as d,Af as u8,Be as h1,Bf as d8,Cf as l8,Df as s8,Ee as g8,Ef as c8,Ff as n8,Ge as m1,Ie as D6,Je as M6,Me as L6,Ne as w6,Oe as O6,Pe as j6,Qe as I6,Re as A6,Se as _6,Te as T6,Ue as P6,Ve as R6,We as z6,Xe as q6,Ye as E6,Ze as g6,_e as S6,af as f6,bf as b6,df as x6,ef as y6,ff as h6,gf as m6,hf as v6,if as p6,jf as u6,le as P1,me as R1,ne as S3,oe as F2,pe as C6,pf as S8,qe as k3,qf as k8,re as W4,rf as f8,se as Y4,sf as b8,te as L0,tf as x8,uf as y8,wf as h8,xe as H0,xf as m8,yf as v8,zf as p8}from"./vm-hands-entry-lite-zfwg7ehq.js";import{Lf as Q6,Pf as w5,Qf as v5,Wf as S7,Zf as O5,_f as e1}from"./vm-hands-entry-lite-vppy988d.js";import{$f as T7,ag as P7,bg as R7,fg as z7,ig as q7}from"./vm-hands-entry-lite-ze9msfq1.js";import{rg as x4,yg as K7}from"./vm-hands-entry-lite-dgxxsdwb.js";import{Dg as Z2}from"./vm-hands-entry-lite-zh8p7ndn.js";import{Ig as R3,Vg as l6}from"./vm-hands-entry-lite-za55dtte.js";import{pi as F7,qi as N7}from"./vm-hands-entry-lite-576m681k.js";import{Ci as j1,Di as I1,Ei as A1,Fi as _1,Gi as E0}from"./vm-hands-entry-lite-4m40gwkf.js";import{$i as g4,Yi as E1,Zi as c6,_i as E4}from"./vm-hands-entry-lite-c01eyep6.js";import{bj as P3,dj as Q1,jj as w8,kj as D4}from"./vm-hands-entry-lite-9cgm6g8t.js";import{Bj as M7,Cj as L7,Dj as w7,Ej as O7,Gj as j7,Hj as I7,Jj as A7,Kj as _7}from"./vm-hands-entry-lite-7shpbsw8.js";import{Vj as V}from"./vm-hands-entry-lite-hc3p6r9p.js";import{bk as C}from"./vm-hands-entry-lite-j2q1k9vb.js";import{hk as W8}from"./vm-hands-entry-lite-g036gtem.js";import{request as t7}from"http";import{request as e7}from"https";import{lookup as $9}from"dns/promises";import{isIP as J9}from"net";async function Z9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?e7:t7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:s3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var a3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),Q9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function i3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(a3.has(Z))return"custom_endpoint_host_not_found";if(Q9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=i3(Q,J+1);if(B)return B}return null}async function B9($,J){let Z=i3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||J9(Q)!==0)return Z;let B;return await Promise.race([$9(Q).then(()=>!0,(G)=>!a3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?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 V9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function o3($){$.signal.throwIfAborted();let J=n3.safeParse($.payload);if(!J.success)throw new C("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=r3.parse(await $.credential($.signal));if(!c3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new C("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,U=0,W=0,Y=K9(Q.apiKey),X=V9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((w,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),w()},(P)=>{$.signal.removeEventListener("abort",I),M(P)})})},H=async(N)=>{if(G+=N.length,G>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=V2){if(W>=l3)throw new C("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+V2).toString("base64")})}};try{let N=await Z9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new C("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new C("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let w={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=B.headers[M];if(typeof I==="string")w[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:w});for await(let M of B){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await H(X(I))}return await H(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof C)throw N;throw new C((B?null:await B9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as t3}from"path";function G9($,J){return $===t3(J,".ara","workspace")||$===t3(J,".reason","workspace")}function e3($,J){let Z=$.filter((Q)=>G9(Q.path,J));return Z.length===1?Z[0].path:null}var U9=/^[a-f0-9]{64}$/;var U2=32,X9=/^\/[^\x00-\x1f\x7f\\]*$/;function w1($){if(typeof $!=="string"||$.length>4096||!X9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!w1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!U9.test(B)||!w1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function W9($){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 Y9($){return W9($)??$.email.toLowerCase()}function X2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?Y9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),F9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...I1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...A1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,..._1.map(($)=>`/[^/]*${n0($)}$`)],$4=`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
  `),s4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{K.once("error",W),K.listen(0,"127.0.0.1",()=>U())});let{port:G}=K.address();return{url:`http://127.0.0.1:${G}`,close(){K.close();for(let U of Q)U.destroy()}}}import{createHash as E2,randomUUID as J$}from"crypto";import{closeSync as J1,constants as s,fchownSync as Z$,fstatSync as z0,fsyncSync as Q$,linkSync as B$,mkdirSync as K$,openSync as Y8,readSync as F8,unlinkSync as V$,writeSync as G$}from"fs";import{platform as U8}from"os";import{getSystemErrorName as U$}from"util";var o4={type:"string",format:"uuid"},J8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,g1={type:"string",minLength:1,maxLength:4096,pattern:J8},T2=V.string().min(1).max(4096).regex(new RegExp(J8)),S1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},k1={device_id:o4,root_id:o4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},YK={read:{schema:V.object({...S1,path:T2,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:{...k1,path:g1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...S1,path:T2,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:{...k1,path:g1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...S1,command:V.string().min(1).max(16000),cwd:T2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...k1,command:{type:"string",minLength:1,maxLength:16000},cwd:g1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},Y0=1073741824,e0=600000,t4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,Z8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${t4}(?:/${t4})*(?![\s\S])`,Q8=new RegExp(Z8);function B8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&Q8.test($)}var P2=V.string().min(1).max(4096).regex(Q8),R2={...g1,pattern:Z8},K8=V.string().regex(/^[a-f0-9]{64}$/),V8=V.object({kind:V.literal("workspace"),path:P2}).strict(),t9=V.discriminatedUnion("kind",[V8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:K8}).strict()]),f1=1,$1="cloud_workspace_id",z2="cloud_workspace",q2=1,e9=V.discriminatedUnion("kind",[V8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(Y0),sha256:K8}).strict()]),G8=V.object({source_version:V.literal(f1),source:e9,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(),[$1]:V.string().min(1).max(160).optional()}).strict(),FK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(f1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var e4=V.object({...S1,timeout_ms:V.number().int().min(1000).max(e0).optional(),source_path:P2,destination_path:P2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),$8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...k1,timeout_ms:{type:"integer",minimum:1000,maximum:e0},source_path:R2,destination_path:R2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},$$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:R2},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}]},NK=V.union([e4,e4.omit({source_path:!0}).extend({source:t9}).strict()]),HK={...$8,required:["device_id","root_id","destination_path"],properties:{...$8.properties,source:$$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var g2=65536;function u($){throw new C($,$)}function x1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function b1($,J,Z){if(J.throwIfAborted(),$ instanceof C||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function X$($,J,Z){let Q;switch(x1($)){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 b1($,J,Q)}function W$($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function Y$(){if(U8()==="linux")return{open:(U,W,Y,X=384)=>Y8(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>K$(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>B$(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>V$(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(U8()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),B=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),K=B.symbols.__error();if(K===null)return B.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=U$(-Q.i32(K));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(B.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(B.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(B.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(B.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>B.close()}}function N8($,J){let Z=z0($),Q=z0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)Z$(J,Z.uid,Z.gid)}function F$($,J,Z,Q){if(!B8(Z))return u("transfer_path_invalid");let B=Z.split("/"),K=Y8(J,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW);try{for(let G of B.slice(0,-1)){let U;try{U=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW)}catch(W){if(!Q||x1(W)!=="ENOENT")throw W;try{$.mkdir(K,G)}catch(Y){if(x1(Y)!=="EEXIST")throw Y}U=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW),N8(K,U)}J1(K),K=U}return{fd:K,leaf:B.at(-1)}}catch(G){throw J1(K),G}}function X8($,J){let Z=z0($,{bigint:!0});if(!Z.isFile()||Z.size>Y0)return u("transfer_file_invalid");let Q=E2("sha256"),B=Buffer.alloc(g2),K=0;while(!0){J.throwIfAborted();let U=F8($,B,0,B.length,K);if(!U)break;if(K+=U,K>Y0)return u("transfer_size_exceeded");Q.update(B.subarray(0,U))}let G=z0($,{bigint:!0});if(BigInt(K)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:K,sha256:Q.digest("hex")}}async function q0($){$.signal.throwIfAborted();try{let J=W$($.payload.url),Z=await Y$(),Q,B,K;try{if(Q=F$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){B=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);let H=z0(B,{bigint:!0});if(!H.isFile()||H.size>Y0)return u("transfer_file_invalid");let N=E2("sha256"),D=0,w=B,M,I=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let O=Buffer.alloc(g2),E=F8(w,O,0,O.length,D);if(!E){v.close();return}if(D+=E,D>H.size)return u("transfer_source_changed");N.update(O.subarray(0,E)),v.enqueue(O.subarray(0,E))}catch(O){throw M=O,O}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:I,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(H.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return b1(v,$.signal,"transfer_upload_failed")}let P=z0(B,{bigint:!0});if(BigInt(D)!==H.size||P.size!==H.size||P.mtimeNs!==H.mtimeNs||P.ctimeNs!==H.ctimeNs)return u("transfer_source_changed");let j=N.digest("hex"),_=X8(B,$.signal);if(_.size_bytes!==D||_.sha256!==j)return u("transfer_source_changed");return{size_bytes:D,sha256:j,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>Y0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK)}catch(H){if(x1(H)!=="ENOENT")throw H}if(W!==void 0){try{let H=X8(W,$.signal);if(H.size_bytes===G&&H.sha256===U)return{...H,outcome:"already_present"}}finally{J1(W)}return u("transfer_destination_exists")}K=`.reason-copy-${J$()}`,B=Z.open(Q.fd,K,s.O_CREAT|s.O_EXCL|s.O_WRONLY|s.O_NOFOLLOW,384),N8(Q.fd,B);let Y;try{let H=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!H.ok||!H.body)return u("transfer_download_failed");Y=H.body.getReader()}catch(H){return b1(H,$.signal,"transfer_download_failed")}let X=E2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let H=await Y.read().catch((N)=>b1(N,$.signal,"transfer_download_failed"));if(H.done)break;if(F+=H.value.length,F>G)return u("transfer_size_mismatch");X.update(H.value);for(let N=0;N<H.value.length;)$.signal.throwIfAborted(),N+=G$(B,H.value,N,Math.min(g2,H.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return Q$(B),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,K,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(B!==void 0)J1(B)}finally{try{if(Q){if(K)try{Z.unlink(Q.fd,K)}catch{}J1(Q.fd)}}finally{Z.close()}}}}catch(J){return X$(J,$.signal,$.direction)}}import{spawn as H$}from"child_process";import{mkdtempSync as C$,rmSync as D$,writeFileSync as M$}from"fs";import{constants as L$,platform as w$,tmpdir as O$}from"os";import{join as M8}from"path";import{gunzipSync as N$,gzipSync as _K}from"zlib";var C8=900000,PK=C8+60000,Z1=49152,H8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),D8=V.object({version:V.literal(1),script_gzip:H8(163840),stdin_gzip:H8(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(C8)}).strict(),S2=V.string().max(Z1+256),RK=V.object({exit_code:V.number().int().min(0).max(255),stdout:S2,stderr:S2,combined:S2.optional()}).strict();function k2($){return N$(Buffer.from($,"base64")).toString("utf8")}var j$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",I$=["RUSTUP_HOME","TZ","LC_ALL"],A$=2000,_$=100;function b2(){return w$()==="linux"&&process.geteuid?.()===0}function f2($){let J=Math.floor($/2),Z=[],Q=0,B=Buffer.alloc(0),K=0;return{push(G){K+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)B=Buffer.concat([B,U]).subarray(-J)},text(){let G=K-Q-B.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
36
36
  [reason: ${G} bytes of output omitted]
37
- `:"")+B.toString("utf8")}}}async function L8($,J){if(!b2())throw new C("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new C("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=k2(Q.script_gzip),K=k2(Q.stdin_gzip)}catch{throw new C("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=C$(M8(O$(),"reason-workspace-setup-"));try{let U=M8(G,"setup.sh");M$(U,B,{mode:384});let W={PATH:j$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let _ of I$)if(process.env[_])W[_]=process.env[_];Object.assign(W,Q.env);let Y=H$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=f2(Z1),F=f2(Z1),H=f2(Z1);Y.stdout.on("data",(_)=>{X.push(_),H.push(_)}),Y.stderr.on("data",(_)=>{F.push(_),H.push(_)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(_)=>{try{if(Y.pid)process.kill(-Y.pid,_)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),A$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let P=await new Promise((_,v)=>{Y.once("error",()=>v(new C("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(O,E)=>_({code:O,signal:E}))}).finally(()=>{clearTimeout(I),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((_)=>{let v=setTimeout(_,_$);Y.once("close",()=>{clearTimeout(v),_()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:P.signal?128+(L$.signals[P.signal]??0):P.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:H.text()}:{}}}finally{D$(G,{recursive:!0,force:!0})}}import{chmodSync as T$,mkdtempSync as P$,realpathSync as I8,rmSync as R$}from"fs";import{tmpdir as z$}from"os";import{dirname as q$,join as x2,sep as E$}from"path";function y2($){return j8($,O8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>q$(w8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(x2($,B));break}catch{}if(Q===void 0)throw new C("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${E$}`))throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function _8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=y2($.runtimeRoot);if(E0(Q)||E0(x2(Q,J.path)))throw new C("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=P$(x2(z$(),`reason-cloud-copy-${process.pid}-`));try{T$(Z,448);let Q=I8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let B=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new C("transfer_source_changed","The verified attachment changed before export.");return B}finally{R$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as k7,existsSync as G0,fstatSync as f7,lstatSync as b7,mkdirSync as UQ,mkdtempSync as XQ,openSync as x7,readSync as WQ,realpathSync as U0,rmSync as YQ,statSync as D1,writeSync as FQ}from"fs";import{homedir as N1,platform as n,tmpdir as NQ}from"os";import{dirname as H1,isAbsolute as HQ,join as y7,relative as z3,resolve as CQ,sep as DQ}from"path";import{spawn as MQ}from"child_process";import{createHash as b$,randomBytes as x$}from"crypto";var h2=30000,g$=1800000,S$=5000,y1=30000,k$=m1+15000,T8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,f$=[/^\/app\/local-runtime\/operations\/claim$/,T8];class m2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(f$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},k$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(S$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(g$,h2*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(h1,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()+h2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[B,K]of Q.pending){if(!T8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(h2,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 p2=["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 eK($,J={}){let Z=y$($),Q=J.rootPathsSupported===!0?O1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((B)=>/^[a-f0-9]{64}$/.test(B))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function y$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function h$($){return $===408||$===429||$===500||$===502||$===503||$===504}function m$($){if($ instanceof F0)return!1;if($ instanceof v1)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 v$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function p$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function $V($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return b$("sha256").update($??"").digest("hex")}function u$($){return S8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function z8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var d$=20000,l$=1e4,q8=[2000,4000],s$=30000,c$=15000;function E8($){return $?{keepalive:!1}:{}}class v2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class n${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=k8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??q8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof v2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new v2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return f8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=d$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,q8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=l$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=R8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>x$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(u$({method:$,route:J,timestamp:B,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!g8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new m2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...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&&P8(J.body)>H0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??p$,W=this.sessionFor($,J.device),Y=Math.max(s$,(J.holdMs??0)+c$),X={fresh:!1},F;for(let H=0;H<G;H+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new v1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let I=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&H===0,H===0?J.issuedChallenge:void 0,X),P=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...I,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(X.fresh),signal:M});return await this.parseResponse(P)}catch(I){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw I}finally{clearTimeout(w)}}catch(N){if(F=N,N instanceof v1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),w=N instanceof F0&&h$(N.status),M=m$(N),I=J.transientRetryOwner!=="caller"&&(w||M);if((D||I)&&H+1<G){let P=D?0:v$(H,N,this.proofOptions.retryBaseDelayMs??500);if(P>0)await U(P,J.signal);continue}if(D&&H+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return b8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return x8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return y8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return h8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return m8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return v8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});u8(Q)}async localSubscription($,J,Z){return p8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!z8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return d8(K,p2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return l8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!z8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return s8(Q)}async completeOperation($,J,Z,Q){let B={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(P8(B)>H0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return n8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-wmcf39x6.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let B=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return c8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var r$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=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 p1($,J){if(r$.has($))return!1;if(B1.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($)||B1.has($)))return!1;return!0}import{accessSync as a$,constants as i$,existsSync as o$,statSync as t$}from"fs";import{basename as e$,isAbsolute as $J}from"path";var K1=["-lic"],JJ="/bin/zsh",ZJ=new Set(["zsh","bash"]),r8=20000,u2=60000,QJ=65536,BJ=64,KJ=8192,VJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),GJ=["DYLD_","LD_"];function UJ($){let J=$.toUpperCase();return VJ.has(J)||GJ.some((Z)=>J.startsWith(Z))}function a8($=process.env){return!0}function XJ($){if(!$J($)||$.includes("\x00"))return!1;if(!ZJ.has(e$($)))return!1;try{if(!t$($).isFile())return!1;return a$($,i$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&XJ(J))return J;return JJ}function d2($=process.env){return a8($)&&o$(g0($))}function l2($=process.env){if(!a8($))throw new C("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function s2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>QJ)throw new C("invalid_payload","command is missing or too large.");return $}function c2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new C("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>BJ)throw new C("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>KJ)throw new C("invalid_payload","env entry is invalid or too large.");if(UJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function i8($){let J=$.processEnv??process.env;if(l2(J),$.signal.aborted)throw new C("cancelled","Operation was cancelled.");let Z=s2($.command),Q=g0(J),{forwarded:B,ignored:K}=c2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function o8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:u2}}import{readFile as WJ,readdir as YJ,readlink as FJ,realpath as NJ}from"fs/promises";import{basename as HJ,relative as CJ,sep as DJ}from"path";var w0="/proc",MJ=250,t8=500,LJ=50,wJ=250,OJ=1024,e8=4096,jJ=1,IJ=3,$5=9,AJ="0A",_J=/^socket:\[(\d+)\]$/,n2={readDirectory:($)=>YJ($),readLink:($)=>FJ($),readTextFile:($)=>WJ($,"utf8"),realPath:($)=>NJ($)};function Z5($,J){return J===$||J.startsWith(`${$}${DJ}`)}function TJ($,J){return CJ($,J)||"."}async function Q5($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function B5($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,e8).split(`
37
+ `:"")+B.toString("utf8")}}}async function L8($,J){if(!b2())throw new C("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new C("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=k2(Q.script_gzip),K=k2(Q.stdin_gzip)}catch{throw new C("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=C$(M8(O$(),"reason-workspace-setup-"));try{let U=M8(G,"setup.sh");M$(U,B,{mode:384});let W={PATH:j$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let _ of I$)if(process.env[_])W[_]=process.env[_];Object.assign(W,Q.env);let Y=H$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=f2(Z1),F=f2(Z1),H=f2(Z1);Y.stdout.on("data",(_)=>{X.push(_),H.push(_)}),Y.stderr.on("data",(_)=>{F.push(_),H.push(_)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(_)=>{try{if(Y.pid)process.kill(-Y.pid,_)}catch{}},D=!1,w,M=()=>{N("SIGTERM"),w??=setTimeout(()=>N("SIGKILL"),A$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let P=await new Promise((_,v)=>{Y.once("error",()=>v(new C("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(O,E)=>_({code:O,signal:E}))}).finally(()=>{clearTimeout(I),clearTimeout(w),J.removeEventListener("abort",M)});await new Promise((_)=>{let v=setTimeout(_,_$);Y.once("close",()=>{clearTimeout(v),_()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:P.signal?128+(L$.signals[P.signal]??0):P.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:H.text()}:{}}}finally{D$(G,{recursive:!0,force:!0})}}import{chmodSync as T$,mkdtempSync as P$,realpathSync as I8,rmSync as R$}from"fs";import{tmpdir as z$}from"os";import{dirname as q$,join as x2,sep as E$}from"path";function y2($){return j8($,O8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>q$(w8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(x2($,B));break}catch{}if(Q===void 0)throw new C("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${E$}`))throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function _8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=y2($.runtimeRoot);if(E0(Q)||E0(x2(Q,J.path)))throw new C("protected_path","Credential and secret paths are unavailable to local tasks.");return q0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=P$(x2(z$(),`reason-cloud-copy-${process.pid}-`));try{T$(Z,448);let Q=I8(Z);await q0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let B=await q0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new C("transfer_source_changed","The verified attachment changed before export.");return B}finally{R$(Z,{recursive:!0,force:!0})}}import{constants as A0}from"fs";import{closeSync as k7,existsSync as G0,fstatSync as f7,lstatSync as b7,mkdirSync as UQ,mkdtempSync as XQ,openSync as x7,readSync as WQ,realpathSync as U0,rmSync as YQ,statSync as D1,writeSync as FQ}from"fs";import{homedir as N1,platform as n,tmpdir as NQ}from"os";import{dirname as H1,isAbsolute as HQ,join as y7,relative as z3,resolve as CQ,sep as DQ}from"path";import{spawn as MQ}from"child_process";import{createHash as b$,randomBytes as x$}from"crypto";var h2=30000,g$=1800000,S$=5000,y1=30000,k$=m1+15000,T8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,f$=[/^\/app\/local-runtime\/operations\/claim$/,T8];class m2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(f$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},k$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(S$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(g$,h2*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(h1,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()+h2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[B,K]of Q.pending){if(!T8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(h2,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 p2=["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 eK($,J={}){let Z=y$($),Q=J.rootPathsSupported===!0?O1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((B)=>/^[a-f0-9]{64}$/.test(B))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function y$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function h$($){return $===408||$===429||$===500||$===502||$===503||$===504}function m$($){if($ instanceof F0)return!1;if($ instanceof v1)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 v$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function p$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function $V($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return b$("sha256").update($??"").digest("hex")}function u$($){return S8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function z8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var d$=20000,l$=1e4,q8=[2000,4000],s$=30000,c$=15000;function E8($){return $?{keepalive:!1}:{}}class v2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class n${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=k8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??q8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof v2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new v2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return f8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=d$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,q8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=l$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=R8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>x$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(u$({method:$,route:J,timestamp:B,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!g8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new m2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...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&&P8(J.body)>H0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??p$,W=this.sessionFor($,J.device),Y=Math.max(s$,(J.holdMs??0)+c$),X={fresh:!1},F;for(let H=0;H<G;H+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,w=setTimeout(()=>D.abort(new v1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let I=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&H===0,H===0?J.issuedChallenge:void 0,X),P=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...I,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(X.fresh),signal:M});return await this.parseResponse(P)}catch(I){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw I}finally{clearTimeout(w)}}catch(N){if(F=N,N instanceof v1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),w=N instanceof F0&&h$(N.status),M=m$(N),I=J.transientRetryOwner!=="caller"&&(w||M);if((D||I)&&H+1<G){let P=D?0:v$(H,N,this.proofOptions.retryBaseDelayMs??500);if(P>0)await U(P,J.signal);continue}if(D&&H+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return b8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return x8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return y8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return h8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return m8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return v8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});u8(Q)}async localSubscription($,J,Z){return p8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!z8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return d8(K,p2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return l8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!z8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return s8(Q)}async completeOperation($,J,Z,Q){let B={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(P8(B)>H0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return n8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-zhpake9f.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let B=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return c8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var r$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=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 p1($,J){if(r$.has($))return!1;if(B1.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($)||B1.has($)))return!1;return!0}import{accessSync as a$,constants as i$,existsSync as o$,statSync as t$}from"fs";import{basename as e$,isAbsolute as $J}from"path";var K1=["-lic"],JJ="/bin/zsh",ZJ=new Set(["zsh","bash"]),r8=20000,u2=60000,QJ=65536,BJ=64,KJ=8192,VJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),GJ=["DYLD_","LD_"];function UJ($){let J=$.toUpperCase();return VJ.has(J)||GJ.some((Z)=>J.startsWith(Z))}function a8($=process.env){return!0}function XJ($){if(!$J($)||$.includes("\x00"))return!1;if(!ZJ.has(e$($)))return!1;try{if(!t$($).isFile())return!1;return a$($,i$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&XJ(J))return J;return JJ}function d2($=process.env){return a8($)&&o$(g0($))}function l2($=process.env){if(!a8($))throw new C("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function s2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>QJ)throw new C("invalid_payload","command is missing or too large.");return $}function c2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new C("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>BJ)throw new C("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>KJ)throw new C("invalid_payload","env entry is invalid or too large.");if(UJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function i8($){let J=$.processEnv??process.env;if(l2(J),$.signal.aborted)throw new C("cancelled","Operation was cancelled.");let Z=s2($.command),Q=g0(J),{forwarded:B,ignored:K}=c2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function o8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:u2}}import{readFile as WJ,readdir as YJ,readlink as FJ,realpath as NJ}from"fs/promises";import{basename as HJ,relative as CJ,sep as DJ}from"path";var w0="/proc",MJ=250,t8=500,LJ=50,wJ=250,OJ=1024,e8=4096,jJ=1,IJ=3,$5=9,AJ="0A",_J=/^socket:\[(\d+)\]$/,n2={readDirectory:($)=>YJ($),readLink:($)=>FJ($),readTextFile:($)=>WJ($,"utf8"),realPath:($)=>NJ($)};function Z5($,J){return J===$||J.startsWith(`${$}${DJ}`)}function TJ($,J){return CJ($,J)||"."}async function Q5($){let J;try{J=await $.readDirectory(w0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function B5($,J){try{let Q=(await J.readTextFile(`${w0}/${$}/comm`)).slice(0,e8).split(`
38
38
  `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${w0}/${$}/cmdline`)).slice(0,e8).split("\x00",1)[0]?.trim();return Q?HJ(Q):null}catch{return null}}async function K5($,J=n2){let Z;try{Z=await J.readLink(`${w0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function V5($,J=n2){let Z=[];for(let Q of await Q5(J)){if(Z.length>=MJ)break;let B=await K5(Q,J);if(!B||!Z5($,B))continue;Z.push({pid:Q,command:await B5(Q,J),cwd:TJ($,B)})}return{processes:Z}}function J5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function PJ($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,B=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(B<0)B=W;continue}if(B>=0){let Y=W-B;if(Y>Q)Z=B,Q=Y;B=-1}}let K=J.map((W)=>W.toString(16));if(Q<2)return K.join(":");let G=K.slice(0,Z).join(":"),U=K.slice(Z+Q).join(":");return`${G}::${U}`}function RJ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=J5($);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(...J5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${PJ(Z)}]:${J}`}return null}function zJ($,J){let Z=[];for(let Q of $.split(`
39
39
  `).slice(1)){if(Z.length>=J)break;let B=Q.trim().split(/\s+/);if(B.length<=$5)continue;if(B[IJ]?.toUpperCase()!==AJ)continue;let K=B[jJ]??"",G=K.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(K.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=RJ(K.slice(0,G),U),Y=B[$5];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function qJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=t8)break;let Q;try{Q=await $.readTextFile(`${w0}/net/${Z}`)}catch{continue}J.push(...zJ(Q,t8-J.length))}return J}async function EJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await Q5(J)){if(Z.size>=$.size)break;let B;try{B=await J.readDirectory(`${w0}/${Q}/fd`)}catch{continue}for(let K of B.slice(0,OJ)){let G;try{G=await J.readLink(`${w0}/${Q}/fd/${K}`)}catch{continue}let U=G.match(_J)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function G5($,J=n2){let Z=await qJ(J),Q=await EJ(new Set(Z.map((X)=>X.inode)),J),B=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;B.push({pid:F,port:X.port,address:X.address})}B.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let K=[...new Set(B.map((X)=>X.pid))].slice(0,LJ),G=await Promise.all(K.map(async(X)=>[X,await K5(X,J)])),U=new Map(G),W=B.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&Z5($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await B5(X,J)])));return{ports:W.slice(0,wJ).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as a2}from"path";var u1=200,gJ=250,SJ=250;async function d1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new C("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],B=null;for(let K of Z.stdout.split(/\r?\n/))if(K.startsWith("p")){let G=Number(K.slice(1));if(B=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,B)Q.push(B)}else if(B&&K.startsWith("c"))B.command=K.slice(1)||null;else if(B&&K.startsWith("n"))B.names.push(K.slice(1));return Q}function r2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var U5="/System/Volumes/Data",kJ=["/tmp","/var","/etc"];function i2($){let J=a2.normalize($);if(J.startsWith(`${U5}/`))J=J.slice(U5.length);return kJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function X5($){return $&&a2.isAbsolute($)?i2($):null}async function W5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=u1){let B=J.slice(Q,Q+u1).join(",");for(let K of await d1($,["-a","-p",B,"-d","cwd","-Fpcn"]))Z.set(K.pid,{command:K.command,cwd:X5(K.names[0])})}return Z}async function Y5($,J){let Z=i2($),Q=(await d1(J,["-d","cwd","-Fpn"])).filter((K)=>{let G=X5(K.names[0]);return G!==null&&r2(Z,G)}).map((K)=>K.pid).slice(0,gJ),B=await W5(J,Q);return{processes:Q.flatMap((K)=>{let G=B.get(K);return G?.cwd&&r2(Z,G.cwd)?[{pid:K,command:G.command,cwd:a2.relative(Z,G.cwd)||"."}]:[]})}}async function F5($,J){let Z=i2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],B=await d1(J,Q),K=await W5(J,B.map((Y)=>Y.pid)),G=B.map((Y)=>Y.pid).filter((Y)=>{let X=K.get(Y)?.cwd;return Boolean(X&&r2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(B.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=u1){let X=G.slice(Y,Y+u1).join(",");for(let F of await d1(J,["-a","-p",X,...Q]))for(let H of F.names)if(U.has(`${F.pid} ${H}`))W.push({pid:F.pid,command:F.command,address:H})}return{ports:W.slice(0,SJ)}}import{join as cJ}from"path";import{spawn as vJ}from"child_process";import{randomUUID as pJ}from"crypto";import{chmodSync as C5,lstatSync as D5,mkdirSync as uJ,readdirSync as dJ,statSync as lJ,unlinkSync as sJ}from"fs";import{join as t2}from"path";var o2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var l1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var O0=()=>{throw Error("proof_visual_contract_invalid")};class N5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function bJ($){if(!V1($)||$.version!==1)return O0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new N5;if(!V1($.viewport)||!l1($.viewport.width,1,4096)||!l1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>o2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return O0();let J=$.targets.map((Q)=>{if(!V1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((B)=>!["id","selector"].includes(B)))return O0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return O0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return O0();Z=$.additionalViewports.map((B)=>{if(!V1(B)||!l1(B.width,1,4096)||!Number.isInteger(B.width)||!l1(B.height,1,4096)||!Number.isInteger(B.height)||Object.keys(B).some((K)=>!["width","height"].includes(K)))return O0();return{width:B.width,height:B.height}});let Q=[$.viewport,...Z].map((B)=>`${B.width}x${B.height}`);if(new Set(Q).size!==Q.length)return O0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var yJ=["organizationId","userId","sessionId","runId"],hJ=[...yJ,"prUrl","headSha","skillDigest","evidenceKind"],wV=[...hJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var mJ={"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 H5($){return mJ[$].directory}var M5=10485760;function L5($={}){let J=$.directory??H5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let B=Q?.seconds;if(!Number.isInteger(B)||Number(B)<1||Number(B)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");uJ(J,{recursive:!0,mode:457});let K=D5(J);if(!K.isDirectory()||K.isSymbolicLink()||K.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");C5(J,457);let G=dJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:lJ(t2(J,M)).mtimeMs})).sort((M,I)=>I.time-M.time);for(let M of G.slice(9))sJ(t2(J,M.name));let U=t2(J,`${pJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??vJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(B),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(M5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,H=!1,N=new Promise((M,I)=>{X=M,F=I});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))H=!0,X()});let D=new Promise((M,I)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),I(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(P)=>{try{if(P!==0&&P!==255)throw Error();let j=D5(U);if(!H||!j.isFile()||j.isSymbolicLink()||j.uid!==process.getuid?.()||j.size<128||j.size>M5+65536)throw Error();C5(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),I(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let w=setTimeout(()=>Y.kill("SIGKILL"),(Number(B)+5)*1000);D.finally(()=>clearTimeout(w)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await N}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(B)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function j5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??w5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let B=cJ($.runtimeDirectory,"recordings"),K=null;return{async start(G){let U=await(J.desktop??O5)();return K??=L5({directory:B,display:U.display,ffmpeg:Q,env:{HOME:E1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),K.start(G)},async stop(){if(!K)throw Error("cloud_browser_recording_not_started");return K.stop()},async close(){await K?.close()}}}import{spawn as M3}from"child_process";import{createHash as UZ,randomUUID as XZ}from"crypto";import{existsSync as Q0,mkdirSync as F3,mkdtempSync as L3,readdirSync as t1,readFileSync as w3,renameSync as WZ,rmSync as X1,statSync as r1,writeFileSync as YZ}from"fs";import{homedir as O3,tmpdir as p5}from"os";import{basename as u5,dirname as N3,join as g,relative as d5,resolve as H3,sep as l5}from"path";var i=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),s1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),I5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),$3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),J3=["home","lock","side_button","siri","apple_pay"],nJ=V.enum(["tree","screenshot","both","none"]),rJ=V.object({...$3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:nJ.optional(),wait_for:rJ.optional(),timeout:V.number().min(0).max(20).optional()},e2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...$3.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(J3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),Z3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:i}).strict(),V.object({action:V.literal("shutdown"),device:i}).strict(),V.object({action:V.literal("build"),path:s1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:s1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),steps:V.array(V.lazy(()=>e2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:i.optional(),app_path:s1.optional(),bundle_id:I5.optional(),steps:V.array(V.lazy(()=>e2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:i.optional(),bundle_id:I5}).strict(),V.object({action:V.literal("logs"),device:i.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:i.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:s1.optional()}).strict(),V.object({action:V.literal("chrome"),device:i.optional()}).strict(),V.object({action:V.literal("inspect"),device:i.optional()}).strict(),V.object({action:V.literal("tap"),device:i.optional(),x:Z0.optional(),y:Z0.optional(),...$3.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:i.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:i.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:i.optional(),name:V.enum(J3),...C0}).strict(),V.object({action:V.literal("open_url"),device:i.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:i.optional(),steps:V.array(e2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),A5=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(),hV=V.object({text:V.string(),error:V.string().optional(),device:A5.optional(),devices:V.array(A5).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 mV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),vV={type:"object",properties:{action:{type:"string",enum:Z3.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...J3]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as V3}from"child_process";import{createHash as iJ}from"crypto";import{existsSync as B3,mkdirSync as c1,mkdtempSync as oJ,readdirSync as _5,readFileSync as T5,renameSync as tJ,rmSync as P5,symlinkSync as K3,writeFileSync as G1}from"fs";import{homedir as eJ}from"os";import{dirname as E5,join as f}from"path";import{createInterface as $Z}from"readline";var Q3=`// Reason's simulator host: one warm process per booted iOS Simulator.
40
40
  //
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ij as f}from"./vm-hands-entry-lite-db4z7ekz.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
2
+ import{kj as f}from"./vm-hands-entry-lite-9cgm6g8t.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
3
3
  ...[executor output truncated]`,p=2000,k=1,i=16384,d=32768,y=128,LA=64,s=2097152,H=1,m=16384,c=32768,OA=8388608,n=1000,t=2500,r=2000,zA=t+r,o=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,v=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,l={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},u=new Map(Object.entries(l).map(([x,A])=>[A,x]));function SA(x,A){return A||(u.get(x)??"")}var a=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],e=new Set(a),w=16384,AA=200,xA=2000,WA=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class G extends Error{code;constructor(x){super(x);this.name="HandsProtocolError",this.code=x}}function g(x){return new TextEncoder().encode(x).byteLength}function U(x){return typeof x==="object"&&x!==null&&!Array.isArray(x)}function B(x,A){let W=new Set(A);return Object.keys(x).every((N)=>W.has(N))}function M(x){return typeof x==="string"&&o.test(x)}function Z(x){return Number.isSafeInteger(x)&&Number(x)>=1}function J(x){return typeof x==="string"&&v.test(x)}function C(x){return typeof x==="string"&&x.startsWith("pty-")&&J(x.slice(4))}function z(x){return[x.cols,x.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=n)}function E(x){if(typeof x!=="string"||x.length>Math.ceil(m/3)*4||x.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(x))return-1;let A=x.endsWith("==")?2:x.endsWith("=")?1:0;if(A&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(x[x.length-A-1])&(A===2?15:3))return-1;let N=x.length/4*3-A;return N<=m?N:-1}function S(x){return typeof x==="string"&&/^[0-9a-f]{64}$/.test(x)}function $(x){if(g(x)>b)throw new G("frame_too_large");try{return JSON.parse(x)}catch{throw new G("invalid_json")}}function BA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","tool","input","semanticDigest","lifecycleLeaseId","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||!["bash","repl","resume","read","edit","write","pi_tool"].includes(String(A.tool))||!U(A.input)||A.lifecycleLeaseId!==void 0&&(A.tool!=="bash"||!J(A.lifecycleLeaseId))||A.workspaceBefore!==void 0&&(!(A.tool==="bash"||A.tool==="repl"||A.tool==="pi_tool"&&A.input.tool==="bash")||!U(A.workspaceBefore)||!B(A.workspaceBefore,["script"])||typeof A.workspaceBefore.script!=="string"||A.workspaceBefore.script.length>K))throw new G("invalid_request");let W=U(A.workspaceBefore)&&typeof A.workspaceBefore.script==="string"?{workspaceBefore:{script:A.workspaceBefore.script}}:{};if(A.tool==="bash"){if(!B(A.input,["script","retainBackground","machineSdk"])||typeof A.input.script!=="string"||A.input.script.length>K||A.input.retainBackground!==void 0&&A.input.retainBackground!==!0||A.input.machineSdk!==void 0&&A.input.machineSdk!==!0||A.semanticDigest!==void 0&&!S(A.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"bash",input:{script:A.input.script,...A.input.retainBackground===!0?{retainBackground:!0}:{},...A.input.machineSdk===!0?{machineSdk:!0}:{}},...A.semanticDigest===void 0?{}:{semanticDigest:A.semanticDigest},...A.lifecycleLeaseId===void 0?{}:{lifecycleLeaseId:A.lifecycleLeaseId},...W}}if(A.tool==="resume"){if(A.semanticDigest!==void 0||!B(A.input,["semanticDigest"])||!S(A.input.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"resume",input:{semanticDigest:A.input.semanticDigest}}}if(A.tool==="repl"){if(!B(A.input,["code"])||typeof A.input.code!=="string"||A.input.code.length>K||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"repl",input:{code:A.input.code},...W}}if(A.tool==="pi_tool"){let N=A.semanticDigest===void 0?GA(A.input):null;if(!N)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"pi_tool",input:N,...W}}if(A.tool==="read"){if(!B(A.input,["path","offset","limit"])||typeof A.input.path!=="string"||A.input.path.length<1||A.input.path.length>K||A.semanticDigest!==void 0||A.input.offset!==void 0&&(!Number.isSafeInteger(A.input.offset)||Number(A.input.offset)<1)||A.input.limit!==void 0&&(!Number.isSafeInteger(A.input.limit)||Number(A.input.limit)<1||Number(A.input.limit)>2000))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"read",input:{path:A.input.path,...A.input.offset===void 0?{}:{offset:Number(A.input.offset)},...A.input.limit===void 0?{}:{limit:Number(A.input.limit)}}}}if(A.tool==="edit"){if(!B(A.input,["path","edits"])||typeof A.input.path!=="string"||A.input.path.length<1||!Array.isArray(A.input.edits)||A.input.edits.length<1||A.input.edits.length>128||A.semanticDigest!==void 0)throw new G("invalid_request");let N=A.input.path.length,X=[];for(let V of A.input.edits){if(!U(V)||!B(V,["oldText","newText"])||typeof V.oldText!=="string"||V.oldText.length<1||typeof V.newText!=="string")throw new G("invalid_request");if(N+=V.oldText.length+V.newText.length,N>D)throw new G("invalid_request");X.push({oldText:V.oldText,newText:V.newText})}return{version:I,generation:A.generation,id:A.id,tool:"edit",input:{path:A.input.path,edits:X}}}if(A.tool!=="write"||!B(A.input,["path","content"])||typeof A.input.path!=="string"||A.input.path.length<1||typeof A.input.content!=="string"||A.input.path.length+A.input.content.length>D||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"write",input:{path:A.input.path,content:A.input.content}}}function L(x){return x===void 0||typeof x==="number"&&Number.isFinite(x)}function GA(x){let A=x.args;if(!B(x,["tool","args"])||!U(A))return null;if(x.tool==="bash")return B(A,["command","timeout"])&&typeof A.command==="string"&&A.command.length<=K&&L(A.timeout)?{tool:"bash",args:{command:A.command,...A.timeout===void 0?{}:{timeout:Number(A.timeout)}}}:null;if(typeof A.path!=="string"||A.path.length>K)return null;if(x.tool==="read")return B(A,["path","offset","limit"])&&L(A.offset)&&L(A.limit)?{tool:"read",args:{path:A.path,...A.offset===void 0?{}:{offset:Number(A.offset)},...A.limit===void 0?{}:{limit:Number(A.limit)}}}:null;if(x.tool==="write")return B(A,["path","content"])&&typeof A.content==="string"&&A.path.length+A.content.length<=D?{tool:"write",args:{path:A.path,content:A.content}}:null;if(x.tool!=="edit"||!B(A,["path","edits"])||!Array.isArray(A.edits))return null;let W=A.path.length,N=[];for(let X of A.edits){if(!U(X)||!B(X,["oldText","newText"])||typeof X.oldText!=="string"||typeof X.newText!=="string")return null;if(W+=X.oldText.length+X.newText.length,W>D)return null;N.push({oldText:X.oldText,newText:X.newText})}return{tool:"edit",args:{path:A.path,edits:N}}}function NA(x){if(!U(x))return null;if("thrown"in x)return B(x,["thrown"])&&typeof x.thrown==="string"?{thrown:x.thrown}:null;let A=x.structuredContent;if(!B(x,["content","details","structuredContent","isError"])||!Array.isArray(x.content)||x.isError!==void 0&&x.isError!==!0||A!==void 0&&(!U(A)||!B(A,["output","truncated","full_output_path","exit_code","wall_time_seconds"])||typeof A.output!=="string"||typeof A.truncated!=="boolean"||A.full_output_path!==void 0&&typeof A.full_output_path!=="string"||typeof A.exit_code!=="number"||typeof A.wall_time_seconds!=="number"))return null;let W=[];for(let N of x.content)if(U(N)&&N.type==="text"&&B(N,["type","text"])&&typeof N.text==="string")W.push({type:"text",text:N.text});else if(U(N)&&N.type==="image"&&B(N,["type","data","mimeType"])&&typeof N.data==="string"&&typeof N.mimeType==="string")W.push({type:"image",data:N.data,mimeType:N.mimeType});else return null;return{content:W,...x.details===void 0?{}:{details:x.details},...U(A)?{structuredContent:{output:String(A.output),truncated:A.truncated===!0,...typeof A.full_output_path==="string"?{full_output_path:A.full_output_path}:{},exit_code:Number(A.exit_code),wall_time_seconds:Number(A.wall_time_seconds)}}:{},...x.isError===!0?{isError:!0}:{}}}function UA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","ok","exitCode","stdout","stderr","cwd","error","resumed","browserActions","automaticProgressImage","piToolOutcome","workerElapsedMs","environmentWaitMs","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||typeof A.ok!=="boolean"||!Number.isSafeInteger(A.exitCode)||Number(A.exitCode)<0||Number(A.exitCode)>255||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_||A.cwd!==void 0&&(typeof A.cwd!=="string"||A.cwd.length<1||A.cwd.length>4096||!A.cwd.startsWith("/")||A.cwd.includes("\x00"))||A.error!==void 0&&(typeof A.error!=="string"||A.error.length<1||A.error.length>p||!e.has(A.error))||A.browserActions!==void 0&&!R(A.browserActions)||A.automaticProgressImage!==void 0&&(A.automaticProgressImage!==!0||!A.ok)||A.resumed!==void 0&&A.resumed!==!0||A.workerElapsedMs!==void 0&&(!Number.isSafeInteger(A.workerElapsedMs)||Number(A.workerElapsedMs)<0)||A.environmentWaitMs!==void 0&&(!Number.isSafeInteger(A.environmentWaitMs)||Number(A.environmentWaitMs)<0)||A.workspaceBefore!==void 0&&!h(A.workspaceBefore)||A.ok&&(A.exitCode!==0||A.error!==void 0)||!A.ok&&A.exitCode===0)throw new G("invalid_result");let W=A.piToolOutcome===void 0?void 0:NA(A.piToolOutcome);if(W===null||W&&!A.ok)throw new G("invalid_result");return{version:I,generation:A.generation,id:A.id,ok:A.ok,exitCode:Number(A.exitCode),stdout:A.stdout,stderr:A.stderr,...typeof A.cwd==="string"?{cwd:A.cwd}:{},...A.browserActions!==void 0?{browserActions:R(A.browserActions)}:{},...typeof A.error==="string"?{error:A.error}:{},...A.automaticProgressImage===!0?{automaticProgressImage:!0}:{},...A.resumed===!0?{resumed:!0}:{},...W?{piToolOutcome:W}:{},...A.workerElapsedMs!==void 0?{workerElapsedMs:Number(A.workerElapsedMs)}:{},...A.environmentWaitMs!==void 0?{environmentWaitMs:Number(A.environmentWaitMs)}:{},...h(A.workspaceBefore)?{workspaceBefore:{exitCode:A.workspaceBefore.exitCode,stdout:A.workspaceBefore.stdout,stderr:A.workspaceBefore.stderr}}:{}}}function h(x){return U(x)&&B(x,["exitCode","stdout","stderr"])&&Number.isSafeInteger(x.exitCode)&&Number(x.exitCode)>=0&&Number(x.exitCode)<=255&&typeof x.stdout==="string"&&x.stdout.length<=w&&typeof x.stderr==="string"&&x.stderr.length<=w}function FA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","sequence","stdout","stderr"])||A.type!=="progress"||A.version!==I||!Z(A.generation)||!M(A.id)||!Number.isSafeInteger(A.sequence)||Number(A.sequence)<1||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_)throw new G("invalid_progress");return{type:"progress",version:I,generation:Number(A.generation),id:A.id,sequence:Number(A.sequence),stdout:A.stdout,stderr:A.stderr}}function IA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","requestCancelVersion","managedJobsVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinement","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.type!=="claim"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinement!==void 0&&(!Y(A.piToolsConfinement)||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1)throw new G("invalid_claim");return{type:"claim",version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{},...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...Y(A.piToolsConfinement)?{piToolsConfinement:{template:A.piToolsConfinement.template,quoteDepth:A.piToolsConfinement.quoteDepth}}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{}}}function XA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","workerVersion","workerArtifactSha256","requestCancelVersion","managedJobsVersion","lifecycleVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinementVersion","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.lifecycleVersion!==void 0&&A.lifecycleVersion!==1||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinementVersion!==void 0&&(A.piToolsConfinementVersion!==1||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.type!=="claim_ack"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||!Number.isSafeInteger(A.workerVersion)||Number(A.workerVersion)<1||!S(A.workerArtifactSha256)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k)throw new G("invalid_claim_ack");return{type:"claim_ack",...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.lifecycleVersion===1?{lifecycleVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...A.piToolsConfinementVersion===1?{piToolsConfinementVersion:1}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{},version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,workerVersion:Number(A.workerVersion),workerArtifactSha256:A.workerArtifactSha256,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{}}}function TA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","jobId","action","input"])||A.type!=="job"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobId)||!U(A.input))throw new G("invalid_job_request");let W=A.input,N=Number.isSafeInteger(W.leaseExpiresAtMs)&&Number(W.leaseExpiresAtMs)>0,X=Number.isSafeInteger(W.sequence)&&Number(W.sequence)>=1;if(!(A.action==="start"?W.mode==="pty"?B(W,["mode","cols","rows","leaseExpiresAtMs"])&&C(A.jobId)&&z(W)&&N:B(W,["script","leaseExpiresAtMs"])&&typeof W.script==="string"&&W.script.length<=K&&N:A.action==="inspect"?B(W,["after"])&&Number.isSafeInteger(W.after)&&Number(W.after)>=0:A.action==="input"?"dataBase64"in W?B(W,["sequence","dataBase64"])&&C(A.jobId)&&X&&E(W.dataBase64)>0:B(W,["sequence","data","eof"])&&X&&typeof W.data==="string"&&W.data.length<=i&&typeof W.eof==="boolean":A.action==="resize"?B(W,["sequence","cols","rows"])&&C(A.jobId)&&X&&z(W):A.action==="renew"?B(W,["leaseExpiresAtMs"])&&N:A.action==="cancel"&&B(W,[])))throw new G("invalid_job_request");return A}function MA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","ok","job","error"])||A.type!=="job_result"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_job_result");if(A.ok===!1&&A.job===void 0&&typeof A.error==="string"&&WA.some((F)=>F===A.error))return A;let W=A.job;if(A.ok!==!0||A.error!==void 0||!U(W)||!B(W,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!M(W.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(W.state))||!Number.isSafeInteger(W.startedAtMs)||Number(W.startedAtMs)<1||!Number.isSafeInteger(W.leaseExpiresAtMs)||Number(W.leaseExpiresAtMs)<1||W.finishedAtMs!==null&&(!Number.isSafeInteger(W.finishedAtMs)||Number(W.finishedAtMs)<Number(W.startedAtMs))||W.exitCode!==null&&(!Number.isSafeInteger(W.exitCode)||Number(W.exitCode)<0||Number(W.exitCode)>255)||!Number.isSafeInteger(W.inputSequence)||Number(W.inputSequence)<0||!Number.isSafeInteger(W.firstCursor)||Number(W.firstCursor)<1||!Number.isSafeInteger(W.nextCursor)||Number(W.nextCursor)<Number(W.firstCursor)-1||typeof W.truncated!=="boolean"||!Array.isArray(W.output)||W.output.length>y)throw new G("invalid_job_result");if(W.environmentRevision===void 0!==(W.environmentSnapshotId===void 0)||W.environmentRevision!==void 0&&(!Number.isSafeInteger(W.environmentRevision)||Number(W.environmentRevision)<1||!J(W.environmentSnapshotId)))throw new G("invalid_job_result");let N=Number(W.firstCursor)-1,X=0;for(let F of W.output){if(!U(F)||!B(F,["cursor","stream","text"])||!Number.isSafeInteger(F.cursor)||Number(F.cursor)<=N||Number(F.cursor)>Number(W.nextCursor)||!["stdout","stderr"].includes(String(F.stream))||typeof F.text!=="string")throw new G("invalid_job_result");X+=F.text.length,N=Number(F.cursor)}if(X>d)throw new G("invalid_job_result");let V=W.state==="starting"||W.state==="running";if(V&&(W.finishedAtMs!==null||W.exitCode!==null)||!V&&W.finishedAtMs===null||W.state==="uncertain"&&W.exitCode!==null||W.state==="exited"&&W.exitCode===null||W.state==="cancelled"&&W.exitCode!==130||W.state==="expired"&&W.exitCode!==124)throw new G("invalid_job_result");if(W.process!==void 0){let F=W.process;if(!U(F)||!B(F,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(F.pid)||Number(F.pid)<1||F.processGroupId!==F.pid||!J(F.executorLaunchId)||!["starting","running"].includes(String(W.state)))throw new G("invalid_job_result")}if(W.pty!==void 0){let F=W.pty;if(!U(F)||!B(F,["version","cols","rows","output","cleanup"])||F.version!==H||!C(W.jobId)||!z(F)||W.output.length!==0||!Array.isArray(F.output)||F.output.length>y||(V?F.cleanup!=="pending":W.state==="uncertain"?F.cleanup!=="unconfirmed":F.cleanup!=="confirmed")||W.state==="running"&&(W.process===void 0||W.environmentRevision===void 0))throw new G("invalid_job_result");let T=Number(W.firstCursor)-1,P=0;for(let Q of F.output){if(!U(Q)||!B(Q,["cursor","dataBase64"])||!Number.isSafeInteger(Q.cursor)||Number(Q.cursor)<=T||Number(Q.cursor)>Number(W.nextCursor))throw new G("invalid_job_result");let q=E(Q.dataBase64);if(q<=0||(P+=q)>c)throw new G("invalid_job_result");T=Number(Q.cursor)}}return A}function qA(x){if(g(x)>s)throw new G("frame_too_large");let A=$(x);if(!U(A)||!B(A,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||A.version!==H||![A.sessionId,A.operationId,A.runId].every(M)||![A.deviceId,A.rootId,A.fenceId,A.executorLaunchId].every(J)||!Z(A.generation)||!Number.isSafeInteger(A.rootGrantRevision)||Number(A.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(A.binding))||!Number.isSafeInteger(A.targetRevision)||Number(A.targetRevision)<0||A.binding==="workspace_source"&&A.targetRevision!==0||!U(A.workspace))throw new G("invalid_pty_receipt");if(!f(A.workspace))throw new G("invalid_pty_receipt");let W=MA(JSON.stringify({type:"job_result",version:I,generation:A.generation,id:A.operationId,ok:!0,job:A.job}));if(!W.ok||!W.job.pty||W.job.pty.output.length!==0||W.job.process&&W.job.process.executorLaunchId!==A.executorLaunchId)throw new G("invalid_pty_receipt");return A}function yA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId"])||A.type!=="cancel_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId))throw new G("invalid_cancel_request");return A}function mA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId","status"])||A.type!=="cancel_ack"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId)||!["cancelled","settled","not_found","unsupported","unconfirmed"].includes(String(A.status)))throw new G("invalid_cancel_ack");return A}function wA(x){let A=JSON.stringify(x);return BA(A),A}function hA(x){let A=JSON.stringify(x);return UA(A),A}function fA(x){let A=JSON.stringify(x);return FA(A),A}function kA(x){let A=JSON.stringify(x);return IA(A),A}function HA(x){let A=JSON.stringify(x);return XA(A),A}function O(x){return typeof x==="string"&&x.length>=1&&x.length<=AA&&!x.includes("\x00")}function VA(x){let A=["type","version","generation","id","jobRequestId","verb"];if(x.verb==="help")return B(x,A)?{verb:"help"}:null;if(x.verb==="describe"||x.verb==="namespace")return B(x,[...A,"name"])&&O(x.name)?{verb:x.verb,name:x.name}:null;if(x.verb==="search"){let W=x.args;if(!B(x,[...A,"query","args"])||typeof x.query!=="string"||x.query.trim().length<1||x.query.length>xA)return null;if(W===void 0)return{verb:"search",query:x.query};if(!U(W)||!B(W,["namespace","limit"])||W.namespace!==void 0&&!O(W.namespace)||W.limit!==void 0&&(!Number.isSafeInteger(W.limit)||Number(W.limit)<1||Number(W.limit)>50))return null;return{verb:"search",query:x.query,args:{...typeof W.namespace==="string"?{namespace:W.namespace}:{},...W.limit===void 0?{}:{limit:Number(W.limit)}}}}if(x.verb!=="call"||!B(x,[...A,"name","args"])||!O(x.name)||!U(x.args)||JSON.stringify(x.args).length>K)return null;return{verb:"call",name:x.name,args:x.args}}function gA(x){let A=$(x);if(!U(A)||A.type!=="sdk_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobRequestId))throw new G("invalid_sdk_request");let W=VA(A);if(!W)throw new G("invalid_sdk_request");return{type:"sdk_request",version:I,generation:Number(A.generation),id:A.id,jobRequestId:A.jobRequestId,...W}}function ZA(x){let A=$(x);if(!U(A)||A.type!=="sdk_response"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_sdk_response");let W={type:"sdk_response",version:I,generation:Number(A.generation),id:A.id},N=["type","version","generation","id","ok"];if(A.ok===!0&&B(A,[...N,"result"])&&typeof A.result==="string"&&A.result.length<=_)return{...W,ok:!0,result:A.result};if(A.ok===!1&&B(A,[...N,"error"])&&typeof A.error==="string"&&A.error.length>=1&&A.error.length<=_)return{...W,ok:!1,error:A.error};throw new G("invalid_sdk_response")}function EA(x){let A=JSON.stringify(x);return ZA(A),A}
4
- export{$A as Dg,KA as Eg,QA as Fg,I as Gg,b as Hg,K as Ig,D as Jg,_ as Kg,YA as Lg,p as Mg,k as Ng,i as Og,d as Pg,y as Qg,LA as Rg,s as Sg,H as Tg,m as Ug,c as Vg,OA as Wg,n as Xg,t as Yg,r as Zg,zA as _g,l as $g,SA as ah,a as bh,w as ch,AA as dh,xA as eh,WA as fh,G as gh,M as hh,Z as ih,J as jh,C as kh,S as lh,BA as mh,UA as nh,FA as oh,IA as ph,XA as qh,TA as rh,MA as sh,qA as th,yA as uh,mA as vh,wA as wh,hA as xh,fA as yh,kA as zh,HA as Ah,gA as Bh,ZA as Ch,EA as Dh};
4
+ export{$A as Fg,KA as Gg,QA as Hg,I as Ig,b as Jg,K as Kg,D as Lg,_ as Mg,YA as Ng,p as Og,k as Pg,i as Qg,d as Rg,y as Sg,LA as Tg,s as Ug,H as Vg,m as Wg,c as Xg,OA as Yg,n as Zg,t as _g,r as $g,zA as ah,l as bh,SA as ch,a as dh,w as eh,AA as fh,xA as gh,WA as hh,G as ih,M as jh,Z as kh,J as lh,C as mh,S as nh,BA as oh,UA as ph,FA as qh,IA as rh,XA as sh,TA as th,MA as uh,qA as vh,yA as wh,mA as xh,wA as yh,hA as zh,fA as Ah,kA as Bh,HA as Ch,gA as Dh,ZA as Eh,EA as Fh};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{wg as m}from"./vm-hands-entry-lite-vygp7vq8.js";import{Kg as w}from"./vm-hands-entry-lite-dm52srp5.js";import{Xi as h}from"./vm-hands-entry-lite-9fr904x2.js";import{ij as x}from"./vm-hands-entry-lite-db4z7ekz.js";import{$j as Q}from"./vm-hands-entry-lite-y3wncwjd.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
- export{r as Zf,A as _f,l as $f,n as ag,U as bg,t as cg,Dz as dg,zz as eg,Hz as fg,Kz as gg};
2
+ import{yg as m}from"./vm-hands-entry-lite-dgxxsdwb.js";import{Mg as w}from"./vm-hands-entry-lite-za55dtte.js";import{Zi as h}from"./vm-hands-entry-lite-c01eyep6.js";import{kj as x}from"./vm-hands-entry-lite-9cgm6g8t.js";import{bk as Q}from"./vm-hands-entry-lite-j2q1k9vb.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
3
+ export{r as $f,A as ag,l as bg,n as cg,U as dg,t as eg,Dz as fg,zz as gg,Hz as hg,Kz as ig};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Tj as W}from"./vm-hands-entry-lite-zmf1terc.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
2
+ import{Vj as W}from"./vm-hands-entry-lite-hc3p6r9p.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
3
3
  repository(owner: $owner, name: $repo) {
4
4
  nameWithOwner
5
5
  pullRequest(number: $number) {
@@ -34,9 +34,9 @@ import{Tj as W}from"./vm-hands-entry-lite-zmf1terc.js";var T=W.string().max(201)
34
34
  }
35
35
  }
36
36
  }
37
- }`;function zQ(Q){return Q.kind==="read"||Q.kind==="pr_review_context"}var b=["inspect_project","fs.read","fs.write","fs.search","fs.watch","fs.upload","fs.export","fs.import","fs.download","exec.run","exec.full","process.run.v1","process.full.v1","pty.start","pty.input","pty.resize","pty.close","git.run","process.list","process.signal","ports.list","tunnel.open","tunnel.close","env.discover","setup.run","mcp.discover","mcp.start","mcp.proxy","browser.snapshot","browser.navigate","browser.act","computer.snapshot","computer.act","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.ollama.v1","inference.custom.v1","delegate.devin.copy.v1","delegate.cursor.copy.v1","display.stream.v1","automation.call.v1","preview.serve.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"];var j=2,I="/app/local-runtime",n=262144,HQ="x-reason-relay-host-alias",XQ="v1";function F(Q,Z){return{path:`${I}${Q}`,routerPath:Q,auth:Z}}function g(Q,Z){return{...F(Q,"device_proof"),forOperation($){return F(`/operations/${encodeURIComponent($)}${Z}`,"device_proof")}}}var GQ={register:F("/register","registration_bearer"),enroll:F("/enroll","none"),authChallenge:F("/auth/challenge","none"),identity:F("/identity","device_proof"),heartbeat:F("/heartbeat","device_proof"),rootsSync:F("/roots/sync","device_proof"),disconnect:F("/disconnect","device_proof"),lifecycle:F("/lifecycle","device_proof"),localSubscription:F("/local-subscription","device_proof"),ownerWorkspaces:F("/owner-workspaces","device_proof"),ownerWorkspaceEnrollment:F("/owner-workspaces/enrollment","device_proof"),sessionWorktrees:F("/session-worktrees","device_proof"),operationClaim:F("/operations/claim","device_proof"),operationHeartbeat:g("/operations/:operationId/heartbeat","/heartbeat"),operationEvents:g("/operations/:operationId/events","/events"),operationComplete:g("/operations/:operationId/complete","/complete"),operationEnvironment:g("/operations/:operationId/environment","/environment"),operationEnvironmentAck:g("/operations/:operationId/environment-ack","/environment-ack"),operationCustomEndpointCredential:g("/operations/:operationId/custom-endpoint-credential","/custom-endpoint-credential")},BQ=`${I}/session`,MQ=4096,gQ=5000,o=[/^\/app\/local-runtime\/heartbeat$/,/^\/app\/local-runtime\/operations\/claim$/,/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/(?:heartbeat|events|complete|environment|environment-ack)$/];function qQ(Q){return o.some((Z)=>Z.test(Q))}var NQ="vm_hands_v1",mQ=60000,UQ={unauthenticated:4401,unavailable:4404,overloaded:4429,serviceRestart:1012},jQ="hands_control_v1",xQ="environment.deliver",JQ="claim_v1",SQ="environment_at_claim",IQ="rebind_v1",PQ="resident_rebind",TQ="hands.rebind",CQ="snapshot_v1",AQ="cloud_access",bQ="playwright_v1",EQ="headless_browser",kQ="v1",LQ="job_env_large_values",fQ="srt_root_v1",_Q="hands_confinement",cQ="gid_v1",yQ="model_jobs_egress",dQ="setpriv_v1",OQ="jobs_user",hQ="spawning_attempt_v1",RQ="hands_session_group",rQ="session_cap",pQ="none",nQ="same_launch_v1",oQ="exit_v1",sQ="start_wait",iQ="user_chrome",tQ="cloud_sessions";function S(Q){if(!K(Q)||Object.keys(Q).length!==5||Q.version!==1)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["boot_generation","recording_operation_id","recording_attempt_id"].every(($)=>typeof Q[$]==="string"&&Z.test(Q[$]))&&typeof Q.root_version==="string"&&/^[0-9]{1,20}(?:\.[0-9]{1,6})?$/.test(Q.root_version)}function U(Q){if(!K(Q)||Object.keys(Q).length!==6)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return typeof Q.device_id==="string"&&Z.test(Q.device_id)&&(Q.binding==="workspace_source"||Q.binding==="mcp_control")&&Number.isSafeInteger(Q.target_revision)&&Number(Q.target_revision)>=0&&Number.isSafeInteger(Q.root_grant_revision)&&Number(Q.root_grant_revision)>0&&Number.isSafeInteger(Q.target_generation)&&Number(Q.target_generation)>0&&typeof Q.target_fence_id==="string"&&Z.test(Q.target_fence_id)}var vQ=["lock_acquired","enrollment_started","enrollment_completed","readiness_started","readiness_completed","inventory_completed","control_ready"],lQ=86400000,uQ=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"],s=["production","staging"];function E(Q){if(!K(Q)||Object.keys(Q).length!==3)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["organization_id","user_id","device_id"].every(($)=>Object.hasOwn(Q,$)&&typeof Q[$]==="string"&&Z.test(Q[$])&&Q[$]!=="00000000-0000-0000-0000-000000000000")}var i="DEVICE-PROOF-V2",aQ="ARA-DEVICE-V1";function eQ(Q,Z=i){let $=Q.method.toUpperCase();if(!/^[A-Z]+$/.test($)||!Q.pathAndQuery.startsWith(`${I}/`)||Q.pathAndQuery.includes(`
37
+ }`;function zQ(Q){return Q.kind==="read"||Q.kind==="pr_review_context"}var b=["inspect_project","fs.read","fs.write","fs.search","fs.watch","fs.upload","fs.export","fs.import","fs.download","exec.run","exec.full","process.run.v1","process.full.v1","pty.start","pty.input","pty.resize","pty.close","git.run","process.list","process.signal","ports.list","tunnel.open","tunnel.close","env.discover","setup.run","mcp.discover","mcp.start","mcp.proxy","browser.snapshot","browser.navigate","browser.act","computer.snapshot","computer.act","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.ollama.v1","inference.custom.v1","delegate.devin.copy.v1","delegate.cursor.copy.v1","display.stream.v1","automation.call.v1","preview.serve.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"];var j=2,I="/app/local-runtime",n=262144,HQ="x-reason-relay-host-alias",XQ="v1";function F(Q,Z){return{path:`${I}${Q}`,routerPath:Q,auth:Z}}function g(Q,Z){return{...F(Q,"device_proof"),forOperation($){return F(`/operations/${encodeURIComponent($)}${Z}`,"device_proof")}}}var GQ={register:F("/register","registration_bearer"),enroll:F("/enroll","none"),authChallenge:F("/auth/challenge","none"),identity:F("/identity","device_proof"),heartbeat:F("/heartbeat","device_proof"),rootsSync:F("/roots/sync","device_proof"),disconnect:F("/disconnect","device_proof"),lifecycle:F("/lifecycle","device_proof"),localSubscription:F("/local-subscription","device_proof"),ownerWorkspaces:F("/owner-workspaces","device_proof"),ownerWorkspaceEnrollment:F("/owner-workspaces/enrollment","device_proof"),sessionWorktrees:F("/session-worktrees","device_proof"),operationClaim:F("/operations/claim","device_proof"),operationHeartbeat:g("/operations/:operationId/heartbeat","/heartbeat"),operationEvents:g("/operations/:operationId/events","/events"),operationComplete:g("/operations/:operationId/complete","/complete"),operationEnvironment:g("/operations/:operationId/environment","/environment"),operationEnvironmentAck:g("/operations/:operationId/environment-ack","/environment-ack"),operationCustomEndpointCredential:g("/operations/:operationId/custom-endpoint-credential","/custom-endpoint-credential")},BQ=`${I}/session`,MQ=4096,gQ=5000,o=[/^\/app\/local-runtime\/heartbeat$/,/^\/app\/local-runtime\/operations\/claim$/,/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/(?:heartbeat|events|complete|environment|environment-ack)$/];function qQ(Q){return o.some((Z)=>Z.test(Q))}var NQ="vm_hands_v1",mQ=60000,UQ={unauthenticated:4401,unavailable:4404,overloaded:4429,serviceRestart:1012},jQ="hands_control_v1",xQ="environment.deliver",JQ="vm_hands_workspace_deferred",SQ="vm_hands.workspace_grant",IQ="claim_v1",PQ="environment_at_claim",TQ="rebind_v1",CQ="resident_rebind",AQ="hands.rebind",bQ="snapshot_v1",EQ="cloud_access",kQ="playwright_v1",LQ="headless_browser",fQ="v1",_Q="job_env_large_values",cQ="srt_root_v1",yQ="hands_confinement",dQ="gid_v1",OQ="model_jobs_egress",hQ="setpriv_v1",RQ="jobs_user",rQ="spawning_attempt_v1",pQ="hands_session_group",nQ="session_cap",oQ="none",sQ="same_launch_v1",iQ="exit_v1",tQ="start_wait",vQ="user_chrome",lQ="cloud_sessions";function S(Q){if(!K(Q)||Object.keys(Q).length!==5||Q.version!==1)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["boot_generation","recording_operation_id","recording_attempt_id"].every(($)=>typeof Q[$]==="string"&&Z.test(Q[$]))&&typeof Q.root_version==="string"&&/^[0-9]{1,20}(?:\.[0-9]{1,6})?$/.test(Q.root_version)}function U(Q){if(!K(Q)||Object.keys(Q).length!==6)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return typeof Q.device_id==="string"&&Z.test(Q.device_id)&&(Q.binding==="workspace_source"||Q.binding==="mcp_control")&&Number.isSafeInteger(Q.target_revision)&&Number(Q.target_revision)>=0&&Number.isSafeInteger(Q.root_grant_revision)&&Number(Q.root_grant_revision)>0&&Number.isSafeInteger(Q.target_generation)&&Number(Q.target_generation)>0&&typeof Q.target_fence_id==="string"&&Z.test(Q.target_fence_id)}var uQ=["lock_acquired","enrollment_started","enrollment_completed","readiness_started","readiness_completed","inventory_completed","control_ready"],aQ=86400000,eQ=["service.install_started","service.install_completed","service.install_failed","service.launcher_adopted","service.launcher_conflict","service.started","service.reconnecting","service.reconnected","service.idle_sleep_held","service.idle_sleep_released","service.idle_sleep_failed","service.start_failed","service.stopped","service.exit_failed","service.singleton_rejected","credential.migration_started","credential.migration_completed","credential.migration_failed","credential.store_started","credential.store_completed","credential.store_failed","credential.delete_started","credential.delete_completed","credential.delete_failed","update.check_started","update.not_available","update.download_started","update.downloaded","update.verified","update.activated","update.rollback","update.failed","executor.update.check_started","executor.update.not_available","executor.update.download_started","executor.update.downloaded","executor.update.verified","executor.update.activated","executor.update.rollback","executor.update.failed","identity.refresh_completed","identity.refresh_failed","update.device_moved","update.components_installed","update.deferred","update.deferral_expired","worker.previous_exit","worker.capabilities_withheld","identity.computer_use_unavailable"],s=["production","staging"];function E(Q){if(!K(Q)||Object.keys(Q).length!==3)return!1;let Z=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;return["organization_id","user_id","device_id"].every(($)=>Object.hasOwn(Q,$)&&typeof Q[$]==="string"&&Z.test(Q[$])&&Q[$]!=="00000000-0000-0000-0000-000000000000")}var i="DEVICE-PROOF-V2",QW="ARA-DEVICE-V1";function WW(Q,Z=i){let $=Q.method.toUpperCase();if(!/^[A-Z]+$/.test($)||!Q.pathAndQuery.startsWith(`${I}/`)||Q.pathAndQuery.includes(`
38
38
  `)||!/^[0-9]{1,20}$/.test(Q.timestamp)||!/^[A-Za-z0-9_-]{22,43}$/.test(Q.nonce)||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
39
39
  `)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
40
- `),"utf8")}function K(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function t(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function k(Q){return K(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function v(Q){return K(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&K(Q.payload)}function w(Q){throw Error(Q)}function QW(Q,Z){let $=K(Q)?Q:{},z=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:z,message:V}}function l(Q){if(!K(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
41
- `)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function L(Q,Z){if(!K(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==j||!Array.isArray(Q.roots)||!Q.roots.every(k)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:j,roots:Q.roots},auth_scheme:"p256"}}function WW(Q){return L(Q,!1)}function ZW(Q){let Z=L(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function $W(Q){if(!K(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...a(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var u=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(u.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function KW(Q){if(!K(Q))return;try{return{...l(Q),...f(Q)}}catch{return}}function a(Q){if(!K(Q))return{};let Z={};for(let $ of s){let z=Q[$];if(typeof z==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(z))Z[$]=z}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function DW(Q){if(!K(Q)||!Array.isArray(Q.roots)||!Q.roots.every(k))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function zW(Q){if(!K(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function FW(Q){if(!K(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function wW(Q){if(K(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(K(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function VW(Q){if(!K(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function e(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function YW(Q,Z=b){if(!K(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!E(Q.owner)||!t(Q.capability,Z)||!K(Q.payload)||Q.protocol_version!==j||e(Q.payload)>n||Q.authority!==void 0&&!U(Q.authority)||Q.local_github_authority!==void 0&&!m.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!m.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!E(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...U(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:m.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&K(Q.environment)&&K(Q.environment.payload)&&U(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:j};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function HW(Q){if(!K(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(v)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function XW(Q){if(!K(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function GW(Q){if(!K(Q)||!K(Q.payload)||!U(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function QQ(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function BW(Q){if(!K(Q)||!QQ(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
42
- export{d as le,R as me,ZQ as ne,x as oe,$Q as pe,m as qe,KQ as re,DQ as se,zQ as te,b as ue,j as ve,I as we,n as xe,HQ as ye,XQ as ze,GQ as Ae,BQ as Be,MQ as Ce,gQ as De,qQ as Ee,NQ as Fe,mQ as Ge,UQ as He,jQ as Ie,xQ as Je,JQ as Ke,SQ as Le,IQ as Me,PQ as Ne,TQ as Oe,CQ as Pe,AQ as Qe,bQ as Re,EQ as Se,kQ as Te,LQ as Ue,fQ as Ve,_Q as We,cQ as Xe,yQ as Ye,dQ as Ze,OQ as _e,hQ as $e,RQ as af,rQ as bf,pQ as cf,nQ as df,oQ as ef,sQ as ff,iQ as gf,tQ as hf,vQ as if,lQ as jf,uQ as kf,i as lf,aQ as mf,eQ as nf,QW as of,l as pf,WW as qf,ZW as rf,$W as sf,KW as tf,DW as uf,zW as vf,FW as wf,wW as xf,VW as yf,YW as zf,HW as Af,XW as Bf,GW as Cf,BW as Df};
40
+ `),"utf8")}function K(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function t(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function k(Q){return K(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function v(Q){return K(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&K(Q.payload)}function w(Q){throw Error(Q)}function ZW(Q,Z){let $=K(Q)?Q:{},z=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:z,message:V}}function l(Q){if(!K(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
41
+ `)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function L(Q,Z){if(!K(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==j||!Array.isArray(Q.roots)||!Q.roots.every(k)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:j,roots:Q.roots},auth_scheme:"p256"}}function $W(Q){return L(Q,!1)}function KW(Q){let Z=L(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function DW(Q){if(!K(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...a(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var u=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(u.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function zW(Q){if(!K(Q))return;try{return{...l(Q),...f(Q)}}catch{return}}function a(Q){if(!K(Q))return{};let Z={};for(let $ of s){let z=Q[$];if(typeof z==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(z))Z[$]=z}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function FW(Q){if(!K(Q)||!Array.isArray(Q.roots)||!Q.roots.every(k))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function wW(Q){if(!K(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function VW(Q){if(!K(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function YW(Q){if(K(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(K(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function HW(Q){if(!K(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function e(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function XW(Q,Z=b){if(!K(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!E(Q.owner)||!t(Q.capability,Z)||!K(Q.payload)||Q.protocol_version!==j||e(Q.payload)>n||Q.authority!==void 0&&!U(Q.authority)||Q.local_github_authority!==void 0&&!m.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!m.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!E(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...U(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:m.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&K(Q.environment)&&K(Q.environment.payload)&&U(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:j};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function GW(Q){if(!K(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(v)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function BW(Q){if(!K(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function MW(Q){if(!K(Q)||!K(Q.payload)||!U(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function QQ(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function gW(Q){if(!K(Q)||!QQ(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
42
+ export{d as le,R as me,ZQ as ne,x as oe,$Q as pe,m as qe,KQ as re,DQ as se,zQ as te,b as ue,j as ve,I as we,n as xe,HQ as ye,XQ as ze,GQ as Ae,BQ as Be,MQ as Ce,gQ as De,qQ as Ee,NQ as Fe,mQ as Ge,UQ as He,jQ as Ie,xQ as Je,JQ as Ke,SQ as Le,IQ as Me,PQ as Ne,TQ as Oe,CQ as Pe,AQ as Qe,bQ as Re,EQ as Se,kQ as Te,LQ as Ue,fQ as Ve,_Q as We,cQ as Xe,yQ as Ye,dQ as Ze,OQ as _e,hQ as $e,RQ as af,rQ as bf,pQ as cf,nQ as df,oQ as ef,sQ as ff,iQ as gf,tQ as hf,vQ as if,lQ as jf,uQ as kf,aQ as lf,eQ as mf,i as nf,QW as of,WW as pf,ZW as qf,l as rf,$W as sf,KW as tf,DW as uf,zW as vf,FW as wf,wW as xf,VW as yf,YW as zf,HW as Af,XW as Bf,GW as Cf,BW as Df,MW as Ef,gW as Ff};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Wi as J}from"./vm-hands-entry-lite-9fr904x2.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
2
+ import{Yi as J}from"./vm-hands-entry-lite-c01eyep6.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
3
3
  `)){let j=I.split(":");if(j.length<7||Number(j[2])!==q||!/^\d+$/.test(j[2])||!/^\d+$/.test(j[3]))continue;let x=j[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(j[0])||!M(x)||Q(x)!==x||x==="/")return null;return{username:j[0],uid:q,gid:Number(j[3]),home:x}}return null}function b(q={}){let B="value"in q?q.value:process.env[W];if(G=null,B===void 0||B==="")return null;let I=q.platform??process.platform,j="euid"in q?q.euid:process.geteuid?.(),x=/^[1-9]\d{0,9}$/.test(B)?Number(B):NaN,C=I==="linux"&&j===0&&Number.isSafeInteger(x)?X(x,(q.passwd??(()=>L("/etc/passwd","utf8")))()):null;if(!C||C.gid===0)throw Error("worker_desktop_user_invalid");return G=C,C}function k(){return G}function y(){return G?.home??J()}
4
- export{W as yg,X as zg,b as Ag,k as Bg,y as Cg};
4
+ export{W as Ag,X as Bg,b as Cg,k as Dg,y as Eg};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import"./vm-hands-entry-lite-pt633d84.js";import"./vm-hands-entry-lite-2fyemnas.js";import"./vm-hands-entry-lite-zmf1terc.js";import{fk as A}from"./vm-hands-entry-lite-7fx4xtf6.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-bgg6ajgz.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-2pxyfw0b.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();
2
+ import"./vm-hands-entry-lite-khjrcwrj.js";import"./vm-hands-entry-lite-zfwg7ehq.js";import"./vm-hands-entry-lite-hc3p6r9p.js";import{hk as A}from"./vm-hands-entry-lite-g036gtem.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-sb4fa85z.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-vq9kf92k.js"),z=B(b);if(!z)q("identity_invalid"),await new Promise(()=>{setInterval(()=>{return},1073741824)});await C(z,q),process.exit(0)}K();