@reason-machines/cli-linux-x64 0.2.393 → 0.2.394

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 (93) hide show
  1. package/bin/reason +1 -1
  2. package/bin/vm-hands/api-credentials-200ret9z.js +2 -0
  3. package/bin/vm-hands/api-jcccjxss.js +2 -0
  4. package/bin/vm-hands/{ask-relay-q0ysjj22.js → ask-relay-3cek7z3p.js} +3 -3
  5. package/bin/vm-hands/connect-cli-vjrqqwcb.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-3g0rc3wp.js → custom-endpoint-device-qd3zcysz.js} +1 -1
  7. package/bin/vm-hands/desktop-account-r5fsgx43.js +2 -0
  8. package/bin/vm-hands/{device-workspace-35hjc1ff.js → device-workspace-ntckpym4.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-msdkfx9x.js → hands-worker-source-p6530nj7.js} +1 -1
  10. package/bin/vm-hands/{index-m32pjcjr.js → index-z6q2j1e0.js} +1 -1
  11. package/bin/vm-hands/install-receipt-kqayxfsn.js +2 -0
  12. package/bin/vm-hands/local-automation-s04b6p1s.js +2 -0
  13. package/bin/vm-hands/local-capabilities-x34aehzt.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-7kbrnvba.js +2 -0
  15. package/bin/vm-hands/local-display-mac-0k5twcjj.js +2 -0
  16. package/bin/vm-hands/local-display-session-etdwwy0w.js +2 -0
  17. package/bin/vm-hands/local-pty-session-a0fz1f9t.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-bgbzjn5s.js → managed-runtime-3xskn9nc.js} +1 -1
  19. package/bin/vm-hands/{network-contract-3h853c6e.js → network-contract-xgbrevt2.js} +1 -1
  20. package/bin/vm-hands/package-x8ct3epg.js +2 -0
  21. package/bin/vm-hands/permissions-9y5zk8r0.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-mw7ba8vz.js → reason-hands-protocol-90kpyg4s.js} +1 -1
  23. package/bin/vm-hands/{serve-service-qqrsrb6k.js → serve-service-e8xp70yg.js} +1 -1
  24. package/bin/vm-hands/{status-g0yna6nk.js → status-fnnjxbx6.js} +2 -2
  25. package/bin/vm-hands/version-t0b2cxf1.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-180h5amj.js → vm-hands-entry-lite-0nd56w02.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-a1yy1yp3.js → vm-hands-entry-lite-1cs1jy20.js} +2 -2
  28. package/bin/vm-hands/{vm-hands-entry-lite-pjctaaxx.js → vm-hands-entry-lite-1ndnrf11.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-3nr9q3nf.js → vm-hands-entry-lite-29f3m7x2.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-5x04hakp.js → vm-hands-entry-lite-2sx1a43v.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-3ptq7p60.js → vm-hands-entry-lite-34h6rv5c.js} +1 -1
  32. package/bin/vm-hands/{vm-hands-entry-lite-f78n4wqt.js → vm-hands-entry-lite-5d31qv44.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-g87z5eb6.js → vm-hands-entry-lite-69n9q5f1.js} +1 -1
  34. package/bin/vm-hands/{vm-hands-entry-lite-ezahexcb.js → vm-hands-entry-lite-6nj2ejfh.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-3xtndjrw.js → vm-hands-entry-lite-7e41q634.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-y64x380n.js → vm-hands-entry-lite-7f9asswm.js} +2 -2
  37. package/bin/vm-hands/{vm-hands-entry-lite-nnmhnxqs.js → vm-hands-entry-lite-a2wbh54x.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-8e932j3c.js → vm-hands-entry-lite-bgs4zjkf.js} +1 -1
  39. package/bin/vm-hands/{vm-hands-entry-lite-trm3dn8c.js → vm-hands-entry-lite-cfwke54v.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-c7qb87xk.js → vm-hands-entry-lite-ctx006e7.js} +3 -3
  41. package/bin/vm-hands/{vm-hands-entry-lite-88h9vwrv.js → vm-hands-entry-lite-e1cbqqqw.js} +1 -1
  42. package/bin/vm-hands/{vm-hands-entry-lite-r166b92s.js → vm-hands-entry-lite-e4kdpq0t.js} +1 -1
  43. package/bin/vm-hands/{vm-hands-entry-lite-h0keewxv.js → vm-hands-entry-lite-e99ftdr6.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-ksz1k1dh.js → vm-hands-entry-lite-eatqxe5y.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-fb02h1zm.js → vm-hands-entry-lite-ek5r435m.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-atg4z1vg.js → vm-hands-entry-lite-f50vcbjg.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-8pgggvbb.js → vm-hands-entry-lite-f9akybcm.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-9rnba1mg.js → vm-hands-entry-lite-fy8zabtd.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-csecgmaa.js → vm-hands-entry-lite-gk3y60ap.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-1edhwzhg.js → vm-hands-entry-lite-gvstv2dh.js} +2 -2
  51. package/bin/vm-hands/{vm-hands-entry-lite-ebgackey.js → vm-hands-entry-lite-hx4w3r63.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-9gjjvcmz.js → vm-hands-entry-lite-k4erfh5k.js} +1 -1
  53. package/bin/vm-hands/vm-hands-entry-lite-kbjh8x26.js +5 -0
  54. package/bin/vm-hands/{vm-hands-entry-lite-0apahx7m.js → vm-hands-entry-lite-mzsx3wcy.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-n3y7495e.js → vm-hands-entry-lite-ps9gjbs5.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-hfv2tsm9.js → vm-hands-entry-lite-q5h859gg.js} +2 -2
  57. package/bin/vm-hands/{vm-hands-entry-lite-y99g8x7f.js → vm-hands-entry-lite-q62fwa20.js} +1 -1
  58. package/bin/vm-hands/vm-hands-entry-lite-qmzjqwh4.js +105 -0
  59. package/bin/vm-hands/{vm-hands-entry-lite-02zaqpgh.js → vm-hands-entry-lite-qvj5560v.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-t7g13jac.js → vm-hands-entry-lite-r5pq4tkf.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-na1vayq4.js → vm-hands-entry-lite-rdx8pt8v.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-mft9ke08.js → vm-hands-entry-lite-sbn9bmf7.js} +1 -1
  63. package/bin/vm-hands/{vm-hands-entry-lite-p1s0xyc2.js → vm-hands-entry-lite-sjn5yjvx.js} +2 -2
  64. package/bin/vm-hands/{vm-hands-entry-lite-e73s63fb.js → vm-hands-entry-lite-smrymax6.js} +1 -1
  65. package/bin/vm-hands/{vm-hands-entry-lite-yr1n57v6.js → vm-hands-entry-lite-t839nkd2.js} +2 -2
  66. package/bin/vm-hands/{vm-hands-entry-lite-mc3pkj0q.js → vm-hands-entry-lite-v0kpksbf.js} +1 -1
  67. package/bin/vm-hands/{vm-hands-entry-lite-wpcagqfw.js → vm-hands-entry-lite-vqfpryez.js} +1 -1
  68. package/bin/vm-hands/{vm-hands-entry-lite-z4q7mrn5.js → vm-hands-entry-lite-w6wz3jqh.js} +7 -7
  69. package/bin/vm-hands/{vm-hands-entry-lite-0seprnh3.js → vm-hands-entry-lite-xhbjkkk5.js} +1 -1
  70. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  71. package/bin/vm-hands/{vm-hands-executor-mz0bewc9.js → vm-hands-executor-w3w2wkh8.js} +1 -1
  72. package/bin/vm-hands/vm-hands-op-runner-s5ep05ke.js +2 -0
  73. package/bin/vm-hands/{vm-hands-runtime-h39vjxh4.js → vm-hands-runtime-wfjwxqbh.js} +3 -3
  74. package/bin/vm-hands/worker-sandbox-ecjj14h5.js +2 -0
  75. package/package.json +1 -1
  76. package/bin/vm-hands/api-2edgrjpe.js +0 -2
  77. package/bin/vm-hands/api-credentials-1bfy2pqp.js +0 -2
  78. package/bin/vm-hands/connect-cli-9xve38p0.js +0 -2
  79. package/bin/vm-hands/desktop-account-8yf4aqgb.js +0 -2
  80. package/bin/vm-hands/install-receipt-7qanbz38.js +0 -2
  81. package/bin/vm-hands/local-automation-svznxf54.js +0 -2
  82. package/bin/vm-hands/local-capabilities-a2fhpy8v.js +0 -2
  83. package/bin/vm-hands/local-desktop-users-p6n48895.js +0 -2
  84. package/bin/vm-hands/local-display-mac-7havkbhd.js +0 -2
  85. package/bin/vm-hands/local-display-session-42vasad3.js +0 -2
  86. package/bin/vm-hands/local-pty-session-pe20a847.js +0 -2
  87. package/bin/vm-hands/package-04cf0m62.js +0 -2
  88. package/bin/vm-hands/permissions-2ez0eqav.js +0 -2
  89. package/bin/vm-hands/version-5tfam1n3.js +0 -2
  90. package/bin/vm-hands/vm-hands-entry-lite-0z73amf7.js +0 -5
  91. package/bin/vm-hands/vm-hands-entry-lite-vc06etcb.js +0 -105
  92. package/bin/vm-hands/vm-hands-op-runner-6vttwrek.js +0 -2
  93. package/bin/vm-hands/worker-sandbox-nnk7fq89.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-y64x380n.js";import{Dc as p7,Fc as d7,Gc as l7}from"./vm-hands-entry-lite-mc3pkj0q.js";import{Lc as g7}from"./vm-hands-entry-lite-h0keewxv.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-r166b92s.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as t4,bd as e4}from"./vm-hands-entry-lite-180h5amj.js";import{dd as m7}from"./vm-hands-entry-lite-g7h6wjqy.js";import{hd as H2,id as C2,jd as B4,ld as V4,nd as G4,od as X4,sd as U4,ud as Y7}from"./vm-hands-entry-lite-e73s63fb.js";import{Cd as W2,Fd as K9,Od as B9}from"./vm-hands-entry-lite-3xtndjrw.js";import{$e as u6,Ae as n3,Be as O2,Ce as y6,De as r3,Df as i8,Ee as _4,Ef as o8,Fe as P4,Ff as t8,Ge as j0,Gf as e8,Hf as $5,If as J5,Ke as C0,Kf as Z5,Lf as Q5,Mf as K5,Ne as s,Nf as B5,Oe as c1,Of as V5,Pf as G5,Qf as X5,Re as a8,Rf as U5,Sf as F5,Te as n1,Tf as Y5,Ve as h6,We as m6,_e as v6,af as p6,bf as d6,cf as l6,df as s6,ef as c6,ff as n6,gf as r6,hf as a6,if as i6,jf as o6,kf as t6,lf as e6,mf as $7,nf as J7,of as Z7,pf as Q7,rf as K7,sf as B7,tf as V7,uf as G7,vf as X7,wf as U7,xf as F7,ye as g1,ze as E1}from"./vm-hands-entry-lite-02zaqpgh.js";import{Zf as _6,bg as m5,cg as X6,ig as V9,lg as v5,mg as X2}from"./vm-hands-entry-lite-t7g13jac.js";import{og as e7,pg as $9,qg as J9,ug as Z9,xg as Q9}from"./vm-hands-entry-lite-yr1n57v6.js";import{Gg as $8,Ng as S7}from"./vm-hands-entry-lite-n3y7495e.js";import{Sg as Y2}from"./vm-hands-entry-lite-hfv2tsm9.js";import{Yg as u3,jh as W7}from"./vm-hands-entry-lite-a1yy1yp3.js";import{Fi as v7,Gi as u7}from"./vm-hands-entry-lite-c7qb87xk.js";import{Si as A1,Ti as _1,Ui as P1,Vi as T1,Wi as k0}from"./vm-hands-entry-lite-mft9ke08.js";import{mj as b1,nj as j7,oj as r4,pj as a4}from"./vm-hands-entry-lite-5x04hakp.js";import{Aj as k4,rj as v3,tj as B1,zj as y8}from"./vm-hands-entry-lite-3nr9q3nf.js";import{Rj as s7,Sj as c7,Tj as n7,Uj as r7,Wj as a7,Xj as i7,Zj as o7,_j as t7}from"./vm-hands-entry-lite-ebgackey.js";import{jk as V}from"./vm-hands-entry-lite-8pgggvbb.js";import{Ak as N7,Bk as H7,Ck as n4,Dk as l1,tk as z5,uk as c4,zk as z7}from"./vm-hands-entry-lite-fb02h1zm.js";import{Ek as T4}from"./vm-hands-entry-lite-8e932j3c.js";import{Gk as H}from"./vm-hands-entry-lite-g87z5eb6.js";import{Mk as g8}from"./vm-hands-entry-lite-f78n4wqt.js";import{request as _9}from"http";import{request as P9}from"https";import{lookup as T9}from"dns/promises";import{isIP as R9}from"net";async function q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?P9:_9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),g9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(g9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=Y4(Q,J+1);if(K)return K}return null}async function E9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||R9(Q)!==0)return Z;let K;return await Promise.race([T9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function k9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function S9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,Y=0,F=k9(Q.apiKey),X=S9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await q9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await E9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function f9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>f9(Q.path,J));return Z.length===1?Z[0].path:null}var b9=/^[a-f0-9]{64}$/;var D2=32,x9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!x9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!b9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function y9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function h9($){return y9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?h9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),m9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
2
+ import{Ab as P7,Bb as o4,Cb as T7,Db as R7,Kb as q7,Ob as E7,Pb as k7,Zb as J8,bc as f7,cc as b7,dc as Y8,ec as W8,gc as x7,ib as m4,ic as h8,jc as v0,kb as q2,kc as p0,lb as v4,lc as F2,mb as u4,nb as C7,ob as D7,oc as y7,pb as w7,rb as p4,rc as m8,sb as M7,sc as Z8,tb as L7,tc as Q8,ub as i4,uc as k1,vb as O7,wb as a3,wc as h7,xb as I7,yb as A7,zb as _7}from"./vm-hands-entry-lite-7f9asswm.js";import{Dc as p7,Fc as d7,Gc as l7}from"./vm-hands-entry-lite-v0kpksbf.js";import{Lc as g7}from"./vm-hands-entry-lite-e99ftdr6.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-e4kdpq0t.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as t4,bd as e4}from"./vm-hands-entry-lite-0nd56w02.js";import{dd as m7}from"./vm-hands-entry-lite-g7h6wjqy.js";import{hd as H2,id as C2,jd as B4,ld as V4,nd as G4,od as X4,sd as U4,ud as Y7}from"./vm-hands-entry-lite-smrymax6.js";import{Cd as W2,Fd as K9,Od as B9}from"./vm-hands-entry-lite-7e41q634.js";import{Af as U7,Bf as F7,Ce as g1,De as E1,Ee as n3,Fe as O2,Ge as y6,He as r3,Hf as i8,Ie as _4,If as o8,Je as P4,Jf as t8,Ke as j0,Kf as e8,Lf as $5,Mf as J5,Oe as C0,Of as Z5,Pf as Q5,Qf as K5,Re as s,Rf as B5,Se as c1,Sf as V5,Tf as G5,Uf as X5,Ve as a8,Vf as U5,Wf as F5,Xe as n1,Xf as Y5,Ze as h6,_e as m6,cf as v6,df as u6,ef as p6,ff as d6,gf as l6,hf as s6,if as c6,jf as n6,kf as r6,lf as a6,mf as i6,nf as o6,of as t6,pf as e6,qf as $7,rf as J7,sf as Z7,tf as Q7,vf as K7,wf as B7,xf as V7,yf as G7,zf as X7}from"./vm-hands-entry-lite-qvj5560v.js";import{bg as _6,fg as m5,gg as X6,mg as V9,pg as v5,qg as X2}from"./vm-hands-entry-lite-r5pq4tkf.js";import{Bg as Q9,sg as e7,tg as $9,ug as J9,yg as Z9}from"./vm-hands-entry-lite-t839nkd2.js";import{Kg as $8,Rg as S7}from"./vm-hands-entry-lite-ps9gjbs5.js";import{Wg as Y2}from"./vm-hands-entry-lite-q5h859gg.js";import{ah as u3,nh as W7}from"./vm-hands-entry-lite-1cs1jy20.js";import{Ji as v7,Ki as u7}from"./vm-hands-entry-lite-ctx006e7.js";import{Wi as A1,Xi as _1,Yi as P1,Zi as T1,_i as k0}from"./vm-hands-entry-lite-sbn9bmf7.js";import{qj as b1,rj as j7,sj as r4,tj as a4}from"./vm-hands-entry-lite-2sx1a43v.js";import{Dj as y8,Ej as k4,vj as v3,xj as B1}from"./vm-hands-entry-lite-29f3m7x2.js";import{$j as i7,Vj as s7,Wj as c7,Xj as n7,Yj as r7,_j as a7,bk as o7,ck as t7}from"./vm-hands-entry-lite-hx4w3r63.js";import{nk as V}from"./vm-hands-entry-lite-f9akybcm.js";import{Dk as z7,Ek as N7,Fk as H7,Gk as n4,Hk as l1,xk as z5,yk as c4}from"./vm-hands-entry-lite-ek5r435m.js";import{Ik as T4}from"./vm-hands-entry-lite-bgs4zjkf.js";import{Kk as H}from"./vm-hands-entry-lite-69n9q5f1.js";import{Qk as g8}from"./vm-hands-entry-lite-5d31qv44.js";import{request as _9}from"http";import{request as P9}from"https";import{lookup as T9}from"dns/promises";import{isIP as R9}from"net";async function q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?P9:_9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),g9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(g9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=Y4(Q,J+1);if(K)return K}return null}async function E9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||R9(Q)!==0)return Z;let K;return await Promise.race([T9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function k9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function S9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,Y=0,F=k9(Q.apiKey),X=S9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await q9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await E9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function f9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>f9(Q.path,J));return Z.length===1?Z[0].path:null}var b9=/^[a-f0-9]{64}$/;var D2=32,x9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!x9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!b9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function y9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function h9($){return y9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?h9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),m9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
3
3
  return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
4
4
  '(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
5
5
  '(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
@@ -34,7 +34,7 @@ Content-Length: 0\r
34
34
  \r
35
35
  `),U8(Y,N,F)})().catch(()=>Y.destroy())}),await new Promise((U,Y)=>{B.once("error",Y),B.listen(0,"127.0.0.1",()=>U())});let{port:G}=B.address();return{url:`http://127.0.0.1:${G}`,close(){B.close();for(let U of Q)U.destroy()}}}import{createHash as l2,randomUUID as k$}from"crypto";import{closeSync as p1,constants as J0,fchownSync as S$,fstatSync as L0,fsyncSync as f$,linkSync as P8,lstatSync as v2,mkdirSync as T8,openSync as v1,readSync as E8,realpathSync as u2,unlinkSync as R8,writeSync as b$}from"fs";import{isAbsolute as x$,join as y$,relative as h$,sep as m$}from"path";import{platform as p2}from"os";import{getSystemErrorName as v$}from"util";var H8={type:"string",format:"uuid"},M8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,x1={type:"string",minLength:1,maxLength:4096,pattern:M8},b2=V.string().min(1).max(4096).regex(new RegExp(M8)),y1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},h1={device_id:H8,root_id:H8,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},iB={read:{schema:V.object({...y1,path:b2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...h1,path:x1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...y1,path:b2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...h1,path:x1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...y1,command:V.string().min(1).max(16000),cwd:b2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...h1,command:{type:"string",minLength:1,maxLength:16000},cwd:x1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},z0=1073741824,Z1=600000,C8=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,j8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${C8}(?:/${C8})*(?![\s\S])`,L8=new RegExp(j8);function O8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&L8.test($)}var x2=V.string().min(1).max(4096).regex(L8),y2={...x1,pattern:j8},I8=V.string().regex(/^[a-f0-9]{64}$/),A8=V.object({kind:V.literal("workspace"),path:x2}).strict(),q$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:I8}).strict()]),m1=1,Q1="cloud_workspace_id",h2="cloud_workspace",m2=1,g$=V.discriminatedUnion("kind",[A8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(z0),sha256:I8}).strict()]),_8=V.object({source_version:V.literal(m1),source:g$,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[Q1]:V.string().min(1).max(160).optional()}).strict(),oB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(m1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var D8=V.object({...y1,timeout_ms:V.number().int().min(1000).max(Z1).optional(),source_path:x2,destination_path:x2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),w8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...h1,timeout_ms:{type:"integer",minimum:1000,maximum:Z1},source_path:y2,destination_path:y2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},E$={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:y2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},tB=V.union([D8,D8.omit({source_path:!0}).extend({source:q$}).strict()]),eB={...w8,required:["device_id","root_id","destination_path"],properties:{...w8.properties,source:E$},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var s2=65536;function l($){throw new H($,$)}function d1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function u1($,J,Z){if(J.throwIfAborted(),$ instanceof H||$ instanceof Error&&$.name==="AbortError")throw $;return l(Z)}function u$($,J,Z){let Q;switch(d1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return u1($,J,Q)}function p$($){if(typeof $!=="string"||$.length>16384)return l("transfer_url_invalid");let J;try{J=new URL($)}catch{return l("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return l("transfer_url_invalid");return J.href}var d2=J0.O_RDONLY|J0.O_DIRECTORY|J0.O_NOFOLLOW;async function d$(){if(p2()==="win32"){let F=new Map,X,W=-1,z=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(D)=>{let j=h$(X,D);return j===""||j!==".."&&!j.startsWith(`..${m$}`)&&!x$(j)},C=(D)=>{let j=v2(D);if(j.isSymbolicLink())throw z();if(!j.isDirectory())throw Object.assign(Error("transfer_path_unsafe"),{code:"ENOTDIR"});let O=u2(D);if(X??=O,!N(O))throw z();return F.set(W,{path:D,real:O}),W--},M=(D)=>{let j=F.get(D);if(u2(j.path)!==j.real)throw z();return j.path},w=(D,j)=>{if(l1(j))throw Object.assign(Error("transfer_path_invalid"),{code:"ENOTDIR"});return y$(F.get(D).path,j)};return{root:C,openDirectory:(D,j)=>C(w(D,j)),open:(D,j,O,A=384)=>{let b=w(D,j);if(v2(b,{throwIfNoEntry:!1})?.isSymbolicLink())throw z();M(D);let I=v1(b,O,A);try{let R=L0(I),P=v2(b);if(P.isSymbolicLink()||R.ino!==P.ino||R.dev!==P.dev||!N(u2(b)))throw z()}catch(R){throw p1(I),R}return I},mkdir:(D,j)=>{let O=w(D,j);M(D),T8(O)},link:(D,j,O)=>{let A=w(D,j),b=w(D,O);M(D),P8(A,b)},unlink:(D,j)=>R8(w(D,j)),closeDirectory:(D)=>{F.delete(D)},inherit:()=>{},close:()=>{}}}let $={root:(F)=>v1(F,d2),closeDirectory:p1,inherit:l$};if(p2()==="linux")return{...$,openDirectory:(F,X)=>v1(`/proc/self/fd/${F}/${X}`,d2),open:(F,X,W,z=384)=>v1(`/proc/self/fd/${F}/${X}`,W,z),mkdir:(F,X)=>T8(`/proc/self/fd/${F}/${X}`,{mode:448}),link:(F,X,W)=>P8(`/proc/self/fd/${F}/${X}`,`/proc/self/fd/${F}/${W}`),unlink:(F,X)=>R8(`/proc/self/fd/${F}/${X}`),close:()=>{}};if(p2()!=="darwin")return l("transfer_platform_unsupported");let{dlopen:J,FFIType:Z,ptr:Q,read:K}=await import("bun:ffi"),B=J("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:Z.ptr},openat:{args:[Z.i32,Z.ptr,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32,Z.i32],returns:Z.i32},mkdirat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32},linkat:{args:[Z.i32,Z.ptr,Z.i32,Z.ptr,Z.i32],returns:Z.i32},unlinkat:{args:[Z.i32,Z.ptr,Z.i32],returns:Z.i32}}),G=B.symbols.__error();if(G===null)return B.close(),l("transfer_path_unavailable");let U=(F)=>{if(F<0){let X=v$(-K.i32(G));throw Object.assign(Error("transfer_path_unavailable"),{code:X})}return F},Y=(F,X,W,z=384)=>U(B.symbols.openat(F,Q(Buffer.from(`${X}\x00`)),W,z,0,0,0,0,z));return{...$,openDirectory:(F,X)=>Y(F,X,d2),open:Y,mkdir:(F,X)=>{U(B.symbols.mkdirat(F,Q(Buffer.from(`${X}\x00`)),448))},link:(F,X,W)=>{U(B.symbols.linkat(F,Q(Buffer.from(`${X}\x00`)),F,Q(Buffer.from(`${W}\x00`)),0))},unlink:(F,X)=>{U(B.symbols.unlinkat(F,Q(Buffer.from(`${X}\x00`)),0))},close:()=>B.close()}}function l$($,J){let Z=L0($),Q=L0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)S$(J,Z.uid,Z.gid)}function s$($,J,Z,Q){if(!O8(Z))return l("transfer_path_invalid");let K=Z.split("/"),B=$.root(J);try{for(let G of K.slice(0,-1)){let U;try{U=$.openDirectory(B,G)}catch(Y){if(!Q||d1(Y)!=="ENOENT")throw Y;try{$.mkdir(B,G)}catch(F){if(d1(F)!=="EEXIST")throw F}U=$.openDirectory(B,G),$.inherit(B,U)}$.closeDirectory(B),B=U}return{fd:B,leaf:K.at(-1)}}catch(G){throw $.closeDirectory(B),G}}function q8($,J){let Z=L0($,{bigint:!0});if(!Z.isFile()||Z.size>z0)return l("transfer_file_invalid");let Q=l2("sha256"),K=Buffer.alloc(s2),B=0;while(!0){J.throwIfAborted();let U=E8($,K,0,K.length,B);if(!U)break;if(B+=U,B>z0)return l("transfer_size_exceeded");Q.update(K.subarray(0,U))}let G=L0($,{bigint:!0});if(BigInt(B)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return l("transfer_source_changed");return{size_bytes:B,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=p$($.payload.url),Z=await d$(),Q,K,B;try{if(Q=s$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){K=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK);let z=L0(K,{bigint:!0});if(!z.isFile()||z.size>z0)return l("transfer_file_invalid");let N=l2("sha256"),C=0,M=K,w,D=new ReadableStream({pull(b){try{$.signal.throwIfAborted();let I=Buffer.alloc(s2),R=E8(M,I,0,I.length,C);if(!R){b.close();return}if(C+=R,C>z.size)return l("transfer_source_changed");N.update(I.subarray(0,R)),b.enqueue(I.subarray(0,R))}catch(I){throw w=I,I}}});try{let b=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:D,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(z.size)}},{duplex:"half"}));if(w!==void 0)throw w;if(!b.ok)return l("transfer_upload_failed");await b.body?.cancel()}catch(b){if(w!==void 0)throw w;return u1(b,$.signal,"transfer_upload_failed")}let j=L0(K,{bigint:!0});if(BigInt(C)!==z.size||j.size!==z.size||j.mtimeNs!==z.mtimeNs||j.ctimeNs!==z.ctimeNs)return l("transfer_source_changed");let O=N.digest("hex"),A=q8(K,$.signal);if(A.size_bytes!==C||A.sha256!==O)return l("transfer_source_changed");return{size_bytes:C,sha256:O,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>z0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return l("transfer_receipt_invalid");let Y;try{Y=Z.open(Q.fd,Q.leaf,J0.O_RDONLY|J0.O_NOFOLLOW|J0.O_NONBLOCK)}catch(z){if(d1(z)!=="ENOENT")throw z}if(Y!==void 0){try{let z=q8(Y,$.signal);if(z.size_bytes===G&&z.sha256===U)return{...z,outcome:"already_present"}}finally{p1(Y)}return l("transfer_destination_exists")}B=`.reason-copy-${k$()}`,K=Z.open(Q.fd,B,J0.O_CREAT|J0.O_EXCL|J0.O_WRONLY|J0.O_NOFOLLOW,384),Z.inherit(Q.fd,K);let F;try{let z=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!z.ok||!z.body)return l("transfer_download_failed");F=z.body.getReader()}catch(z){return u1(z,$.signal,"transfer_download_failed")}let X=l2("sha256"),W=0;try{while(!0){$.signal.throwIfAborted();let z=await F.read().catch((N)=>u1(N,$.signal,"transfer_download_failed"));if(z.done)break;if(W+=z.value.length,W>G)return l("transfer_size_mismatch");X.update(z.value);for(let N=0;N<z.value.length;)$.signal.throwIfAborted(),N+=b$(K,z.value,N,Math.min(s2,z.value.length-N))}}finally{await F.cancel().catch(()=>{})}if(W!==G||X.digest("hex")!==U)return l("transfer_hash_mismatch");return f$(K),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,B,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(K!==void 0)p1(K)}finally{try{if(Q){if(B)try{Z.unlink(Q.fd,B)}catch{}Z.closeDirectory(Q.fd)}}finally{Z.close()}}}}catch(J){return u$(J,$.signal,$.direction)}}import{spawn as n$}from"child_process";import{mkdtempSync as r$,rmSync as a$,writeFileSync as i$}from"fs";import{constants as o$,platform as t$,tmpdir as e$}from"os";import{join as b8}from"path";import{gunzipSync as c$,gzipSync as YV}from"zlib";var S8=900000,zV=S8+60000,K1=49152,k8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),f8=V.object({version:V.literal(1),script_gzip:k8(163840),stdin_gzip:k8(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max(S8)}).strict(),c2=V.string().max(K1+256),NV=V.object({exit_code:V.number().int().min(0).max(255),stdout:c2,stderr:c2,combined:c2.optional()}).strict();function n2($){return c$(Buffer.from($,"base64")).toString("utf8")}var $J="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",JJ=["RUSTUP_HOME","TZ","LC_ALL"],ZJ=2000,QJ=100;function a2(){return t$()==="linux"&&process.geteuid?.()===0}function r2($){let J=Math.floor($/2),Z=[],Q=0,K=Buffer.alloc(0),B=0;return{push(G){B+=G.length;let U=G;if(Q<J){let Y=U.subarray(0,J-Q);Z.push(Y),Q+=Y.length,U=U.subarray(Y.length)}if(U.length)K=Buffer.concat([K,U]).subarray(-J)},text(){let G=B-Q-K.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
36
36
  [reason: ${G} bytes of output omitted]
37
- `:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-3g0rc3wp.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
37
+ `:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-qd3zcysz.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
38
38
  `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,M5).split("\x00",1)[0]?.trim();return Q?cJ(Q):null}catch{return null}}async function _5($,J=G3){let Z;try{Z=await J.readLink(`${O0}/${$}/cwd`)}catch{return null}if(!Z)return null;try{return await J.realPath(Z)}catch{return null}}async function P5($,J=G3){let Z=[];for(let Q of await I5(J)){if(Z.length>=aJ)break;let K=await _5(Q,J);if(!K||!O5($,K))continue;Z.push({pid:Q,command:await A5(Q,J),cwd:QZ($,K)})}return{processes:Z}}function L5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function KZ($){let J=[];for(let Y=0;Y<16;Y+=2)J.push($[Y]<<8|$[Y+1]);if(J.slice(0,5).every((Y)=>Y===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,K=-1;for(let Y=0;Y<=J.length;Y+=1){if(Y<J.length&&J[Y]===0){if(K<0)K=Y;continue}if(K>=0){let F=Y-K;if(F>Q)Z=K,Q=F;K=-1}}let B=J.map((Y)=>Y.toString(16));if(Q<2)return B.join(":");let G=B.slice(0,Z).join(":"),U=B.slice(Z+Q).join(":");return`${G}::${U}`}function BZ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=L5($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...L5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${KZ(Z)}]:${J}`}return null}function VZ($,J){let Z=[];for(let Q of $.split(`
39
39
  `).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=j5)continue;if(K[$Z]?.toUpperCase()!==JZ)continue;let B=K[eJ]??"",G=B.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(B.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let Y=BZ(B.slice(0,G),U),F=K[j5];if(!Y||!F||!/^[0-9]+$/.test(F))continue;Z.push({inode:F,port:U,address:Y})}return Z}async function GZ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=w5)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...VZ(Q,w5-J.length))}return J}async function XZ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await I5(J)){if(Z.size>=$.size)break;let K;try{K=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let B of K.slice(0,tJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(ZZ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function T5($,J=G3){let Z=await GZ(J),Q=await XZ(new Set(Z.map((X)=>X.inode)),J),K=[];for(let X of Z){let W=Q.get(X.inode);if(W===void 0)continue;K.push({pid:W,port:X.port,address:X.address})}K.sort((X,W)=>X.pid-W.pid||X.port-W.port||(X.address<W.address?-1:X.address>W.address?1:0));let B=[...new Set(K.map((X)=>X.pid))].slice(0,iJ),G=await Promise.all(B.map(async(X)=>[X,await _5(X,J)])),U=new Map(G),Y=K.filter((X)=>{let W=U.get(X.pid);return Boolean(W&&O5($,W))}),F=new Map(await Promise.all([...new Set(Y.map((X)=>X.pid))].map(async(X)=>[X,await A5(X,J)])));return{ports:Y.slice(0,oJ).map((X)=>({pid:X.pid,command:F.get(X.pid)??null,address:X.address}))}}import{posix as U3}from"path";var i1=200,UZ=250,FZ=250;async function o1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new H("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],K=null;for(let B of Z.stdout.split(/\r?\n/))if(B.startsWith("p")){let G=Number(B.slice(1));if(K=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,K)Q.push(K)}else if(K&&B.startsWith("c"))K.command=B.slice(1)||null;else if(K&&B.startsWith("n"))K.names.push(B.slice(1));return Q}function X3($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var R5="/System/Volumes/Data",YZ=["/tmp","/var","/etc"];function F3($){let J=U3.normalize($);if(J.startsWith(`${R5}/`))J=J.slice(R5.length);return YZ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function q5($){return $&&U3.isAbsolute($)?F3($):null}async function g5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=i1){let K=J.slice(Q,Q+i1).join(",");for(let B of await o1($,["-a","-p",K,"-d","cwd","-Fpcn"]))Z.set(B.pid,{command:B.command,cwd:q5(B.names[0])})}return Z}async function E5($,J){let Z=F3($),Q=(await o1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=q5(B.names[0]);return G!==null&&X3(Z,G)}).map((B)=>B.pid).slice(0,UZ),K=await g5(J,Q);return{processes:Q.flatMap((B)=>{let G=K.get(B);return G?.cwd&&X3(Z,G.cwd)?[{pid:B,command:G.command,cwd:U3.relative(Z,G.cwd)||"."}]:[]})}}async function k5($,J){let Z=F3($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await o1(J,Q),B=await g5(J,K.map((F)=>F.pid)),G=K.map((F)=>F.pid).filter((F)=>{let X=B.get(F)?.cwd;return Boolean(X&&X3(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(K.flatMap((F)=>F.names.map((X)=>`${F.pid} ${X}`))),Y=[];for(let F=0;F<G.length;F+=i1){let X=G.slice(F,F+i1).join(",");for(let W of await o1(J,["-a","-p",X,...Q]))for(let z of W.names)if(U.has(`${W.pid} ${z}`))Y.push({pid:W.pid,command:W.command,address:z})}return{ports:Y.slice(0,FZ)}}import{join as AZ}from"path";import{spawn as wZ}from"child_process";import{randomUUID as MZ}from"crypto";import{chmodSync as b5,lstatSync as x5,mkdirSync as jZ,readdirSync as LZ,statSync as OZ,unlinkSync as IZ}from"fs";import{join as W3}from"path";var Y3={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var t1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var I0=()=>{throw Error("proof_visual_contract_invalid")};class S5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function zZ($){if(!X1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new S5;if(!X1($.viewport)||!t1($.viewport.width,1,4096)||!t1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>Y3.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return I0();let J=$.targets.map((Q)=>{if(!X1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((K)=>!["id","selector"].includes(K)))return I0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return I0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return I0();Z=$.additionalViewports.map((K)=>{if(!X1(K)||!t1(K.width,1,4096)||!Number.isInteger(K.width)||!t1(K.height,1,4096)||!Number.isInteger(K.height)||Object.keys(K).some((B)=>!["width","height"].includes(B)))return I0();return{width:K.width,height:K.height}});let Q=[$.viewport,...Z].map((K)=>`${K.width}x${K.height}`);if(new Set(Q).size!==Q.length)return I0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var HZ=["organizationId","userId","sessionId","runId"],CZ=[...HZ,"prUrl","headSha","skillDigest","evidenceKind"],GG=[...CZ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var DZ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function f5($){return DZ[$].directory}var y5=10485760;function h5($={}){let J=$.directory??f5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let K=Q?.seconds;if(!Number.isInteger(K)||Number(K)<1||Number(K)>15||!Q||Object.keys(Q).some((w)=>w!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");jZ(J,{recursive:!0,mode:457});let B=x5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");b5(J,457);let G=LZ(J).filter((w)=>/^[a-f0-9-]{36}\.webm$/.test(w)).map((w)=>({name:w,time:OZ(W3(J,w)).mtimeMs})).sort((w,D)=>D.time-w.time);for(let w of G.slice(9))IZ(W3(J,w.name));let U=W3(J,`${MZ()}.webm`),Y=["-f","x11grab","-framerate","12","-i",$.display??":99"],F=($.spawn??wZ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...Y,"-t",String(K),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(y5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,W,z=!1,N=new Promise((w,D)=>{X=w,W=D});F.stdout.on("data",(w)=>{if(/frame=\s*[1-9]/.test(String(w)))z=!0,X()});let C=new Promise((w,D)=>{F.once("error",()=>{W(Error("cloud_browser_recording_unavailable")),D(Error("cloud_browser_recording_unavailable"))}),F.once("exit",(j)=>{try{if(j!==0&&j!==255)throw Error();let O=x5(U);if(!z||!O.isFile()||O.isSymbolicLink()||O.uid!==process.getuid?.()||O.size<128||O.size>y5+65536)throw Error();b5(U,420),X(),w({path:U,mimeType:"video/webm"})}catch{W(Error("cloud_browser_recording_failed")),D(Error("cloud_browser_recording_failed"))}})});C.catch(()=>{});let M=setTimeout(()=>F.kill("SIGKILL"),(Number(K)+5)*1000);C.finally(()=>clearTimeout(M)).catch(()=>{}),Z={done:C,stop:()=>{return F.kill("SIGINT"),C}};try{await N}catch(w){throw Z=null,w}return{recording:!0,seconds:Number(K)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function u5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??m5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=AZ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??v5)();return B??=h5({directory:K,display:U.display,ffmpeg:Q,env:{HOME:b1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),B.start(G)},async stop(){if(!B)throw Error("cloud_browser_recording_not_started");return B.stop()},async close(){await B?.close()}}}import{spawn as E3}from"child_process";import{createHash as lZ,randomUUID as sZ}from"crypto";import{existsSync as Q0,mkdirSync as P3,mkdtempSync as k3,readdirSync as G2,readFileSync as S3,renameSync as cZ,rmSync as Y1,statSync as Q2,writeFileSync as nZ}from"fs";import{homedir as f3,tmpdir as U6}from"os";import{basename as F6,dirname as T3,join as k,relative as Y6,resolve as R3,sep as W6}from"path";var a=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),e1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),p5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),N3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),H3=["home","lock","side_button","siri","apple_pay"],_Z=V.enum(["tree","screenshot","both","none"]),PZ=V.object({...N3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),D0={observe:_Z.optional(),wait_for:PZ.optional(),timeout:V.number().min(0).max(20).optional()},z3=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(H3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),C3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:a}).strict(),V.object({action:V.literal("shutdown"),device:a}).strict(),V.object({action:V.literal("build"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:e1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:a.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:a.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:a.optional(),app_path:e1.optional(),bundle_id:p5.optional(),steps:V.array(V.lazy(()=>z3)).max(30).optional(),...D0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:a.optional(),bundle_id:p5}).strict(),V.object({action:V.literal("logs"),device:a.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:a.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:e1.optional()}).strict(),V.object({action:V.literal("chrome"),device:a.optional()}).strict(),V.object({action:V.literal("inspect"),device:a.optional()}).strict(),V.object({action:V.literal("tap"),device:a.optional(),x:Z0.optional(),y:Z0.optional(),...N3.shape,duration:V.number().min(0).max(10).optional(),...D0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:a.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...D0}).strict(),V.object({action:V.literal("type"),device:a.optional(),text:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("button"),device:a.optional(),name:V.enum(H3),...D0}).strict(),V.object({action:V.literal("open_url"),device:a.optional(),url:V.string().min(1).max(4000),...D0}).strict(),V.object({action:V.literal("steps"),device:a.optional(),steps:V.array(z3).min(1).max(30),...D0}).strict(),V.object({action:V.literal("appearance"),device:a.optional(),mode:V.enum(["light","dark"])}).strict()]),d5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),PG=V.object({text:V.string(),error:V.string().optional(),device:d5.optional(),devices:V.array(d5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var TG=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),$2={device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name. Required for boot and shutdown; for other actions omit it for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string",description:"build_status (required): the build_id a build or run returned."},app_path:{type:"string",description:"launch: the built .app from build_status (or pass bundle_id instead)."},bundle_id:{type:"string",description:"terminate (required); launch: an installed app's bundle id instead of app_path."},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number",description:"tap (with y, unless id or label is given) or swipe (required): start point in device points."},y:{type:"number"},x2:{type:"number",description:"swipe (required, with y2): end point in device points."},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect (instead of x and y)."},label:{type:"string",description:"tap: accessibility label from inspect (instead of x and y)."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string",description:"type (required): the text to type."},name:{type:"string",enum:[...H3],description:"button (required)."},url:{type:"string",description:"open_url (required): the URL or deep link."},mode:{type:"string",enum:["light","dark"],description:"appearance (required)."},steps:{type:"array",maxItems:30,description:"steps (required, at least one) or launch and run: run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},s5=C3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),TZ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},l5=new Set;function RZ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...$2.steps,minItems:1}:$2[$];if(Z===void 0||l5.has($))return Q;return l5.add($),{...Q,description:Z}}var qZ=s5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn($2,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(TZ[J]??[{required:[]}]).map((K)=>({type:"object",properties:Object.fromEntries([["action",{type:"string",const:J}],...["device_id","root_id",...Z].filter((B)=>!K.without?.includes(B)).map((B)=>[B,RZ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),gZ={type:"object",properties:{action:{type:"string",enum:s5.map(($)=>$.action.value)},...$2},required:["action"],additionalProperties:!1},RG={...gZ,anyOf:qZ};import{spawn as j3}from"child_process";import{createHash as kZ}from"crypto";import{existsSync as w3,mkdirSync as J2,mkdtempSync as SZ,readdirSync as c5,readFileSync as n5,renameSync as fZ,rmSync as r5,symlinkSync as M3,writeFileSync as U1}from"fs";import{homedir as bZ}from"os";import{dirname as t5,join as x}from"path";import{createInterface as xZ}from"readline";var D3=`// Reason's simulator host: one warm process per booted iOS Simulator.
40
40
  //
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Di as m,Ei as y}from"./vm-hands-entry-lite-ksz1k1dh.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){if(Q==="win32")return K(J,"AppData","Local","Reason","Logs");let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
- export{f as mi,mJ as ni,yJ as oi,j as pi,sJ as qi,p as ri,cJ as si,lJ as ti,iJ as ui,rJ as vi,r as wi,jJ as xi,qQ as yi,BQ as zi,YQ as Ai,WQ as Bi,LJ as Ci};
2
+ import{Hi as m,Ii as y}from"./vm-hands-entry-lite-eatqxe5y.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){if(Q==="win32")return K(J,"AppData","Local","Reason","Logs");let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
+ export{f as qi,mJ as ri,yJ as si,j as ti,sJ as ui,p as vi,cJ as wi,lJ as xi,iJ as yi,rJ as zi,r as Ai,jJ as Bi,qQ as Ci,BQ as Di,YQ as Ei,WQ as Fi,LJ as Gi};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Qj as $}from"./vm-hands-entry-lite-nnmhnxqs.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
- export{O as Mj,Z as Nj,S as Oj,k as Pj};
2
+ import{Uj as $}from"./vm-hands-entry-lite-a2wbh54x.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
+ export{O as Qj,Z as Rj,S as Sj,k as Tj};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Gk as l}from"./vm-hands-entry-lite-g87z5eb6.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
2
+ import{Kk as l}from"./vm-hands-entry-lite-69n9q5f1.js";import{execFile as zj,spawn as I}from"child_process";var Cj="h264_ws_v1",kj="video",h=["smooth","sharp","data_saver","balanced"];var Yj="video_presets";var V=8388608,Y=65536,Lj="control",Aj="v1",d=200;function s(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q,J=(Q)=>typeof Q==="string"&&Q.length>0&&Q.length<=d;if(Object.keys(j).length!==2||!J(j.user_id)||!J(j.name))return null;return{user_id:j.user_id,name:j.name}}var xj="windows",Mj="v1",A=200,o=(q)=>typeof q==="string"&&h.includes(q);function fj(q){if(!q||typeof q!=="object"||Array.isArray(q))return null;let j=q;if(Object.keys(j).length!==2||j.format!=="h264_ws_v1"||!o(j.preset))return null;return{format:"h264_ws_v1",preset:j.preset}}var $={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23};class U extends Error{constructor(q){super(q);this.name="DisplayVideoProtocolError"}}var e=new TextEncoder,jj=new TextDecoder("utf-8",{fatal:!0});function H(q,j){if(j.byteLength+1>V)throw new U("message_too_large");let J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,j.byteLength+1),Q.setUint8(4,q),J.set(j,5),J}function R(q){let j=e.encode(q);if(j.byteLength>Y)throw new U("text_too_large");return j}function f(q,j){if(!Number.isInteger(q)||q<0||q>65535)throw new U(`invalid_${j}`);return q}function qj(q){if(!Number.isFinite(q))throw new U("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(q)))}function hj(q){switch(q.type){case"hello":{let j=R(q.codec),J=new Uint8Array(6+j.byteLength),Q=new DataView(J.buffer);return Q.setUint16(0,f(q.width,"width")),Q.setUint16(2,f(q.height,"height")),Q.setUint8(4,Math.max(1,Math.min(240,Math.round(q.fps)))),Q.setUint8(5,h.indexOf(q.preset)),J.set(j,6),H($.hello,J)}case"frame":{let j=new Uint8Array(13+q.data.byteLength),J=new DataView(j.buffer);return J.setUint8(0,q.key?1:0),J.setUint32(1,q.seq>>>0),J.setBigUint64(5,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,13),H($.frame,j)}case"stats":return H($.stats,R(JSON.stringify(q.stats)));case"pong":case"ping":{let j=new Uint8Array(8);return new DataView(j.buffer).setFloat64(0,q.token),H(q.type==="ping"?$.ping:$.pong,j)}case"serverClipboard":return H($.serverClipboard,R(q.text));case"clientClipboard":return H($.clientClipboard,R(q.text));case"error":return H($.error,R(q.code));case"pointer":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint16(0,f(q.x,"x")),J.setUint16(2,f(q.y,"y")),J.setUint8(4,q.buttons&255),H($.pointer,j)}case"key":{let j=new Uint8Array(5),J=new DataView(j.buffer);return J.setUint8(0,q.down?1:0),J.setUint32(1,q.keysym>>>0),H($.key,j)}case"config":return H($.config,Uint8Array.of(h.indexOf(q.preset)));case"keyframeRequest":return H($.keyframeRequest,new Uint8Array(0));case"audioHello":{let j=R(q.codec),J=new Uint8Array(5+j.byteLength),Q=new DataView(J.buffer);return Q.setUint32(0,q.sampleRate>>>0),Q.setUint8(4,q.channels&255),J.set(j,5),H($.audioHello,J)}case"audio":{let j=new Uint8Array(8+q.data.byteLength);return new DataView(j.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(q.captureMicros)))),j.set(q.data,8),H($.audio,j)}case"control":return H($.control,R(JSON.stringify(q.control)));case"windows":{let j=q.bounds.slice(0,A),J=new Uint8Array(j.length*16),Q=new DataView(J.buffer);return j.forEach((Z,z)=>{[Z.x,Z.y,Z.width,Z.height].forEach((G,F)=>Q.setInt32(z*16+F*4,qj(G)))}),H($.windows,J)}case"audioEnable":return H($.audioEnable,Uint8Array.of(q.on?1:0));case"ack":{let j=new Uint8Array(4);return new DataView(j.buffer).setUint32(0,q.seq>>>0),H($.ack,j)}}}function T(q){let j=h[q];if(!j)throw new U("invalid_preset");return j}function C(q,j){if(q.byteLength!==j)throw new U("invalid_length")}function k(q){if(q.byteLength>Y)throw new U("text_too_large");try{return jj.decode(q)}catch{throw new U("invalid_text")}}function Jj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_stats")}let J=j;if(!J||typeof J!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((Z)=>typeof J[Z]!=="number"||!Number.isFinite(J[Z])))throw new U("invalid_stats");return{fps:J.fps,kbps:J.kbps,dropped:J.dropped,restarts:J.restarts,queued_bytes:J.queued_bytes}}function Qj(q){let j;try{j=JSON.parse(k(q))}catch{throw new U("invalid_control")}let J=j;if(!J||typeof J!=="object"||typeof J.you!=="boolean"||typeof J.same_user!=="boolean")throw new U("invalid_control");let Q=J.holder===null?null:s(J.holder);if(Q===null&&J.holder!==null)throw new U("invalid_control");return{holder:Q,you:J.you,same_user:J.same_user}}function Zj(q,j){let J=new DataView(j.buffer,j.byteOffset,j.byteLength);switch(q){case $.hello:if(j.byteLength<6)throw new U("invalid_length");return{type:"hello",width:J.getUint16(0),height:J.getUint16(2),fps:J.getUint8(4),preset:T(J.getUint8(5)),codec:k(j.subarray(6))};case $.frame:if(j.byteLength<14)throw new U("invalid_length");if(J.getUint8(0)>1)throw new U("invalid_frame_flags");return{type:"frame",key:J.getUint8(0)===1,seq:J.getUint32(1),captureMicros:Number(J.getBigUint64(5)),data:j.subarray(13)};case $.stats:return{type:"stats",stats:Jj(j)};case $.ping:case $.pong:return C(j,8),{type:q===$.ping?"ping":"pong",token:J.getFloat64(0)};case $.serverClipboard:return{type:"serverClipboard",text:k(j)};case $.clientClipboard:return{type:"clientClipboard",text:k(j)};case $.error:return{type:"error",code:k(j)};case $.pointer:return C(j,5),{type:"pointer",x:J.getUint16(0),y:J.getUint16(2),buttons:J.getUint8(4)};case $.key:if(C(j,5),J.getUint8(0)>1)throw new U("invalid_key_flags");return{type:"key",down:J.getUint8(0)===1,keysym:J.getUint32(1)};case $.config:return C(j,1),{type:"config",preset:T(J.getUint8(0))};case $.keyframeRequest:return C(j,0),{type:"keyframeRequest"};case $.audioHello:if(j.byteLength<5)throw new U("invalid_length");return{type:"audioHello",sampleRate:J.getUint32(0),channels:J.getUint8(4),codec:k(j.subarray(5))};case $.audio:if(j.byteLength<9)throw new U("invalid_length");return{type:"audio",captureMicros:Number(J.getBigUint64(0)),data:j.subarray(8)};case $.audioEnable:if(C(j,1),J.getUint8(0)>1)throw new U("invalid_audio_flags");return{type:"audioEnable",on:J.getUint8(0)===1};case $.control:return{type:"control",control:Qj(j)};case $.windows:{if(j.byteLength%16!==0||j.byteLength>A*16)throw new U("invalid_length");let Q=[];for(let Z=0;Z<j.byteLength;Z+=16)Q.push({x:J.getInt32(Z),y:J.getInt32(Z+4),width:J.getInt32(Z+8),height:J.getInt32(Z+12)});return{type:"windows",bounds:Q}}case $.ack:return C(j,4),{type:"ack",seq:J.getUint32(0)};default:return null}}class $j{buffer=new Uint8Array(0);push(q){let j=new Uint8Array(this.buffer.byteLength+q.byteLength);j.set(this.buffer),j.set(q,this.buffer.byteLength);let J=[],Q=0;while(j.byteLength-Q>=4){let Z=new DataView(j.buffer,j.byteOffset+Q,4).getUint32(0);if(Z<1||Z>V)throw new U("invalid_message_length");if(j.byteLength-Q-4<Z)break;let z=j[Q+4],G=j.slice(Q+5,Q+4+Z),F=Zj(z,G);if(F)J.push(F);Q+=4+Z}return this.buffer=j.slice(Q),J}}var t="/usr/bin/osascript",Gj=5000,Kj=1048576,Uj=String.raw`
3
3
  ObjC.import("CoreGraphics");
4
4
  ObjC.import("ApplicationServices");
5
5
  ObjC.import("AppKit");
@@ -109,4 +109,4 @@ function run() {
109
109
  `);X>=0;X=B.indexOf(`
110
110
  `)){let S=B.slice(0,X);if(B=B.slice(X+1),!S.startsWith("c "))continue;let O=S.slice(2);if(O.length>Math.ceil(Y/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(O)){K({reason:"display_protocol"});return}let _=Buffer.from(O,"base64");if(_.byteLength<=Y)q.clipboard(_.toString("utf8"));if(z)return}if(B.length>Math.ceil(Y/3)*4+2)K({reason:"display_protocol"})}),G.once("error",()=>W("Reason could not watch this Mac's desktop clipboard.")),G.once("exit",()=>{if(!z)W("Reason could not watch this Mac's desktop clipboard.")})};return J.stdout.on("data",(B)=>{if(z||Z===null)return;Z+=B.toString("utf8");let N=Z.indexOf(`
111
111
  `);if(N<0){if(Z.length>4096)K({reason:"display_protocol"});return}let X=y(Z.slice(0,N));if(Z=null,!X)K({reason:"display_protocol"});else if(!X.screen||!X.accessibility)W(j.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else i(),q.ready({width:X.width,height:X.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>W("Reason could not start this Mac's desktop input.")),J.once("exit",()=>{if(Z!==null)W("Reason could not start this Mac's desktop input.");else K({reason:"display_closed"})}),{pointer:(B,N,X)=>L(Q.pointer(B,N,X)),key:(B,N)=>L(Q.key(B,N)),clipboard:(B)=>L([`c ${Buffer.from(B,"utf8").toString("base64")}`]),close(){z=!0,F()}}}
112
- export{Cj as Rj,kj as Sj,h as Tj,Yj as Uj,Y as Vj,Lj as Wj,Aj as Xj,s as Yj,xj as Zj,Mj as _j,fj as $j,hj as ak,$j as bk,y as ck,Sj as dk,_j as ek,Hj as fk,Tj as gk,a as hk,Vj as ik};
112
+ export{Cj as Vj,kj as Wj,h as Xj,Yj,Y as Zj,Lj as _j,Aj as $j,s as ak,xj as bk,Mj as ck,fj as dk,hj as ek,$j as fk,y as gk,Sj as hk,_j as ik,Hj as jk,Tj as kk,a as lk,Vj as mk};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import{createHash as f,createPublicKey as V,verify as G}from"crypto";var Y="libara_device_keychain.dylib",H="libreason_device_keychain.dylib",k=1,x=2,h=536870912,R=262144;var U=["darwin-arm64","darwin-x64"];class J extends Error{code;constructor(z,F){super(F);this.code=z;this.name="ManagedRuntimeError"}}var C=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,N=/^[a-f0-9]{64}$/;function X(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function $(z,F,Q=[]){let Z=new Set([...F,...Q]);return F.every((W)=>(W in z))&&Object.keys(z).every((W)=>Z.has(W))}function B(z){return typeof z==="string"&&C.test(z)}function O(z){return typeof z==="string"&&!Number.isNaN(Date.parse(z))&&new Date(z).toISOString()===z}function I(z){return U.includes(z)}function c(z,F){if(!B(z)||!I(F))throw new J("invalid_release_asset","Invalid managed runtime release asset.")}function K(z,F){return c(z,F),`reason-runtime-v${z}-${F}`}function g(z,F){return`${K(z,F)}-${H}`}var o="managed-runtime-identity.json",D="reason-macos-background-identity-v1";function q(z){if(z===null)return"null";if(typeof z==="string"||typeof z==="boolean")return JSON.stringify(z);if(typeof z==="number"){if(!Number.isFinite(z))throw new J("invalid_manifest","Manifest numbers must be finite.");return JSON.stringify(z)}if(Array.isArray(z))return`[${z.map((F)=>q(F)).join(",")}]`;if(X(z))return`{${Object.keys(z).sort().map((F)=>`${JSON.stringify(F)}:${q(z[F])}`).join(",")}}`;throw new J("invalid_manifest","Manifest contains an unsupported value.")}function j(z){if(!X(z)||!$(z,["url","sha256","size_bytes"])||typeof z.url!=="string"||typeof z.sha256!=="string"||!N.test(z.sha256)||typeof z.size_bytes!=="number"||!Number.isSafeInteger(z.size_bytes)||z.size_bytes<=0||z.size_bytes>h)throw new J("invalid_manifest","Manifest contains an invalid runtime artifact.");let F;try{F=new URL(z.url)}catch{throw new J("invalid_manifest","Runtime artifact URL is invalid.")}if(F.protocol!=="https:"||F.username||F.password||F.hash)throw new J("invalid_manifest","Runtime artifact URL must be an HTTPS URL without credentials or a fragment.");return{url:F.toString(),sha256:z.sha256,size_bytes:z.size_bytes}}function b(z){if(!X(z)||!$(z,["broker","credential_library"]))throw new J("invalid_manifest","Manifest must bind the broker and credential library as one runtime.");return{broker:j(z.broker),credential_library:j(z.credential_library)}}function _(z){if(!X(z)||!$(z,["schema_version","version","published_at","artifacts"])||z.schema_version!==x||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Managed Reason runtime manifest is invalid.");return{schema_version:x,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":b(z.artifacts["darwin-arm64"]),"darwin-x64":b(z.artifacts["darwin-x64"])}}}function M(z){if(!X(z)||!$(z,["schema_version","version","published_at","artifacts"])||z.schema_version!==k||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Legacy managed runtime manifest is invalid.");return{schema_version:k,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":j(z.artifacts["darwin-arm64"]),"darwin-x64":j(z.artifacts["darwin-x64"])}}}function A(z){if(!X(z)||!$(z,["schema","version","published_at","artifacts"])||z.schema!==D||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Reason background identity manifest is invalid.");return{schema:D,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":j(z.artifacts["darwin-arm64"]),"darwin-x64":j(z.artifacts["darwin-x64"])}}}function S(z){if(typeof z!=="string"||!/^[A-Za-z0-9+/]+={0,2}$/.test(z))throw new J("invalid_signature","Runtime manifest signature is invalid.");let F=Buffer.from(z,"base64");if(F.length!==64||F.toString("base64")!==z)throw new J("invalid_signature","Runtime manifest signature is invalid.");return F}function L(z){let F=z;if(typeof z==="string")try{F=JSON.parse(z)}catch{throw new J("invalid_manifest","Managed Reason runtime manifest is not valid JSON.")}if(!X(F)||!$(F,["key_id","manifest","signature"])||typeof F.key_id!=="string"||!/^[A-Za-z0-9._-]{1,80}$/.test(F.key_id)||typeof F.signature!=="string")throw new J("invalid_manifest","Signed managed Reason runtime manifest is invalid.");return F}function E(z,F){let Q=L(z),Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Runtime manifest was signed by an unknown key.");let W=_(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Runtime manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Runtime manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function d(z,F){let Q=L(z),Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Background identity manifest was signed by an unknown key.");let W=A(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Background identity manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Background identity manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function i(z,F){let Q=z;if(typeof z==="string")try{Q=JSON.parse(z)}catch{throw new J("invalid_manifest","Legacy managed runtime manifest is not valid JSON.")}if(!X(Q)||!$(Q,["key_id","manifest","signature"])||typeof Q.key_id!=="string"||!/^[A-Za-z0-9._-]{1,80}$/.test(Q.key_id)||typeof Q.signature!=="string")throw new J("invalid_manifest","Signed legacy managed runtime manifest is invalid.");let Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Legacy runtime manifest was signed by an unknown key.");let W=M(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Legacy runtime manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Legacy runtime manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function y(z){return f("sha256").update(z).digest("hex")}function n(z,F){if(z.byteLength!==F.size_bytes)throw new J("artifact_size_mismatch","Runtime artifact size did not match its manifest.");if(y(z)!==F.sha256)throw new J("artifact_checksum_mismatch","Runtime artifact checksum did not match its manifest.")}import{existsSync as p}from"fs";import{join as T}from"path";function r(z){let F=T(z,H);return p(F)?F:T(z,Y)}
3
- export{Y as Wh,H as Xh,k as Yh,x as Zh,h as _h,R as $h,U as ai,J as bi,K as ci,g as di,o as ei,q as fi,E as gi,d as hi,i as ii,y as ji,n as ki,r as li};
3
+ export{Y as _h,H as $h,k as ai,x as bi,h as ci,R as di,U as ei,J as fi,K as gi,g as hi,o as ii,q as ji,E as ki,d as li,i as mi,y as ni,n as oi,r as pi};
@@ -0,0 +1,5 @@
1
+ // @bun
2
+ import{Bi as m,qi as A,ri as y,si as p}from"./vm-hands-entry-lite-gk3y60ap.js";import{Hi as u}from"./vm-hands-entry-lite-eatqxe5y.js";import{randomUUID as d}from"crypto";import{chmodSync as c,existsSync as n,mkdirSync as YJ,readlinkSync as GJ,readFileSync as OJ,renameSync as VJ,unlinkSync as FJ,writeFileSync as HJ}from"fs";import{homedir as v}from"os";import{basename as C,dirname as H,isAbsolute as g,join as N,normalize as a,relative as TJ,resolve as zJ}from"path";import{unlinkSync as XJ}from"fs";import{dirname as ZJ,join as $J}from"path";function jJ(J){return $J(ZJ(J),"future-device-grant.json")}function l(J){try{XJ(jJ(J))}catch(Q){if(!(Q instanceof Error&&("code"in Q)&&Q.code==="ENOENT"))throw Q}}var z=3,BJ=1,SJ=2,D=1,i=1,r="Reason may read and write files and run commands in this signed-in OS account, subject to saved restrictions and operating system permissions.",E="Reason may later execute on this computer inside a Reason sandbox, limited to folders explicitly attached by the user.",_J=[E,"Ara may later execute on this computer inside an Ara sandbox, limited to folders explicitly attached by the user."];function t(J){return typeof J==="string"&&_J.includes(J)}var IJ=["future_device","updates_only","cli_only"];function h(J){return typeof J==="string"&&IJ.some((Q)=>Q===J)}function LJ(J=process.env,Q=v()){return J.XDG_CONFIG_HOME?.trim()||N(Q,".config")}function K(J=process.env,Q=v()){let U=y({env:J}),W=LJ(J,Q);return N(W,m(W).state==="kept"?"ara":"reason",...U==="staging"?["staging"]:[],"installation.json")}function G(J){return typeof J==="string"&&J.trim().length>0}var NJ=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function AJ(J){return typeof J==="string"&&NJ.test(J)}function M(J){return G(J)&&g(J)&&a(J)===J}function e(J){if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return M(Q.path)&&(Q.role==="launcher"&&(Q.kind==="file"||Q.kind==="symlink")||Q.role==="worker_root"&&Q.kind==="directory"||Q.role==="alias"&&Q.kind==="symlink"&&M(Q.target))}function JJ(J){return J==="staging"?["reason-staging","ara-staging"]:["reason","ara"]}var gJ=/^\.(?:reason|ara)(?:-staging)?-worker-/,hJ=["reason","ara"];function oJ(J){let Q=J.owned_paths.filter((W)=>W.role==="launcher").map((W)=>W.path),[U]=JJ(J.channel);return Q.find((W)=>C(W)===U)??Q[0]??null}function o(J){let[Q,U]=JJ(J.channel==="staging"?"staging":"production"),W=[[Q,U],[U,Q]];return J.owned_paths?.every((X)=>X.role!=="alias"||J.installer==="shell"&&W.some(([$,j])=>X.path===N(J.install_dir,$)&&X.target===N(J.install_dir,j))&&J.owned_paths?.some(($)=>$.role==="launcher"&&$.path===X.target))??!1}function w(J,Q){try{return zJ(H(J),GJ(J))===Q}catch{return!1}}function sJ(J){let Q=C(J),U=Q==="ara"?"reason":Q==="ara-staging"?"reason-staging":null;if(!U)return J;let W=N(H(J),U);return w(W,J)||w(J,W)?W:J}function f(J,Q){let U=TJ(J,Q);return U.length>0&&!U.startsWith("..")&&!g(U)}function QJ(J){if(J===null)return!0;if(!J||typeof J!=="object"||Array.isArray(J))return!1;let Q=J;return(Q.kind==="shell_profile"||Q.kind==="windows_user_path")&&G(Q.location)&&G(Q.value)&&(typeof Q.added_by_installer==="boolean"||typeof Q.added_by_ara==="boolean")&&(Q.added_by_installer===void 0||typeof Q.added_by_installer==="boolean")&&(Q.added_by_ara===void 0||typeof Q.added_by_ara==="boolean")}function q(J){return J.added_by_installer??J.added_by_ara??!1}function UJ(J,Q){if(Q===null)return J==="cli_only";if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;let U=Q;if(U.version!==D||!G(U.recorded_at))return!1;if(J==="future_device")return U.decision==="authorized"&&t(U.scope);return U.scope===null&&U.decision===(J==="updates_only"?"ask":"disabled")}function DJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==BJ||!A.includes(Q.channel)||Q.install_method!=="curl"||Q.installer!=="shell"&&Q.installer!=="powershell"||!G(Q.installed_at)||!G(Q.version)||!G(Q.target)||!M(Q.install_dir)||!Array.isArray(Q.owned_paths)||!Q.owned_paths.every(e)||!Q.owned_paths.every((U)=>f(Q.install_dir,U.path))||!o(Q)||!QJ(Q.path_entry))return null;return{...Q,schema_version:z,installation_id:null,background_mode:"cli_only",device_consent:null}}function KJ(J){if(!J||typeof J!=="object"||Array.isArray(J))return null;let Q=J;if(Q.schema_version!==SJ||!WJ(Q)||!h(Q.background_mode)||!UJ(Q.background_mode,Q.device_consent))return null;return{...Q,schema_version:z,installation_id:null}}function WJ(J){return A.includes(J.channel)&&(J.install_method==="curl"&&(J.installer==="shell"||J.installer==="powershell")||J.install_method==="desktop"&&J.installer==="desktop"&&Array.isArray(J.owned_paths)&&J.owned_paths.length===0&&J.path_entry===null)&&G(J.installed_at)&&G(J.version)&&G(J.target)&&M(J.install_dir)&&Array.isArray(J.owned_paths)&&J.owned_paths.every(e)&&J.owned_paths.every((Q)=>f(J.install_dir,Q.path))&&o(J)&&QJ(J.path_entry)}function RJ(J){let Q=DJ(J);if(Q)return Q;let U=KJ(J);if(U)return U;if(!J||typeof J!=="object"||Array.isArray(J))return null;let W=J;if(W.schema_version!==z||!AJ(W.installation_id)||!WJ(W)||!h(W.background_mode)||!UJ(W.background_mode,W.device_consent)||W.desktop_account_access!==void 0&&(W.desktop_account_access===null||typeof W.desktop_account_access!=="object"||Array.isArray(W.desktop_account_access)||W.desktop_account_access.version!==i||W.desktop_account_access.scope!==r||!G(W.desktop_account_access.recorded_at)||!Number.isFinite(Date.parse(W.desktop_account_access.recorded_at))))return null;return W}function k(J=K()){if(!n(J))return null;try{return RJ(JSON.parse(OJ(J,"utf8")))}catch{return null}}function b(J){return Boolean(J?.installation_id&&J.background_mode==="future_device"&&J.device_consent?.version===D&&J.device_consent.decision==="authorized"&&t(J.device_consent.scope))}function s(J,Q){let U=k(Q);if(!(b(U)&&b(J)&&U.installation_id===J.installation_id&&U.channel===J.channel))l(Q);YJ(H(Q),{recursive:!0,mode:448}),c(H(Q),448);let X=`${Q}.${process.pid}.${d()}.tmp`;try{HJ(X,`${JSON.stringify(J,null,2)}
3
+ `,{mode:384,flag:"wx"}),c(X,384),VJ(X,Q)}finally{if(n(X))FJ(X)}let $=H(Q),j=C($)==="staging"?H($):$;if(C(j)==="reason")m(H(j));return J}function qJ(J=K(),Q=new Date){let U=k(J);if(!U?.installation_id)throw Error("Reason installation ownership is missing; reinstall the current CLI before enabling Device execution");if(b(U))return U;let W={...U,background_mode:"future_device",device_consent:{version:D,decision:"authorized",scope:E,recorded_at:Q.toISOString()}};return delete W.desktop_account_access,s(W,J)}function lJ(J,Q=K(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=L(J.installDir,"install directory"),X=k(Q);if(X?.installation_id&&!J.accountAccess)return qJ(Q,U);return s({...X??{schema_version:z,channel:J.channel,install_method:"desktop",installer:"desktop",installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:[],path_entry:null},schema_version:z,installation_id:X?.installation_id??d(),background_mode:"future_device",...J.accountAccess?{desktop_account_access:{version:i,scope:r,recorded_at:U.toISOString()}}:{},device_consent:{version:D,decision:"authorized",scope:E,recorded_at:U.toISOString()}},Q)}function CJ(J,Q){return J.kind===Q.kind&&J.location===Q.location&&J.value===Q.value}function L(J,Q){let U=a(J);if(!g(U))throw Error(`${Q} must be an absolute path`);return U}function MJ(J,Q=K(),U=new Date){if(!A.includes(J.channel))throw Error("invalid installation channel");if(!J.version.trim())throw Error("installation version is required");if(!J.target.trim())throw Error("installation target is required");let W=L(J.install_dir,"install directory"),X=k(Q),$=J.backgroundMode??"preserve",j=$==="preserve"?X?.background_mode??"cli_only":$,T=X?.channel===J.channel&&b(X)&&j==="future_device",B=$==="preserve"&&!X||X?.channel===J.channel&&($==="preserve"||T),O={path:L(J.launcherPath,"launcher path"),kind:J.launcherKind,role:"launcher"};if(!f(W,O.path))throw Error("launcher path must be inside the install directory");let S=(J.workerRoots??[]).map((Y)=>L(Y,"worker root"));if(S.some((Y)=>!f(W,Y)))throw Error("worker root must be inside the install directory");let _=[];if(J.aliasPath){let Y={path:L(J.aliasPath,"alias path"),kind:"symlink",role:"alias",target:O.path};if(!o({installer:J.installer,channel:J.channel,install_dir:W,owned_paths:[O,Y]})||!w(Y.path,Y.target))throw Error("alias must be the channel's symlink to its canonical launcher");_.push(Y)}let R=[...X?.channel===J.channel&&X.install_dir===W?X.owned_paths:[],O,..._,...S.map((Y)=>({path:Y,kind:"directory",role:"worker_root"}))],P=Array.from(new Map(R.map((Y)=>[Y.path,Y])).values()),Z=J.pathEntry??null,F=Z?X?.path_entry&&CJ(Z,X.path_entry)?{...Z,added_by_installer:q(Z)||q(X.path_entry),added_by_ara:q(Z)||q(X.path_entry)}:Z:X?.path_entry??null,I={schema_version:z,installation_id:X?.installation_id??d(),channel:J.channel,install_method:"curl",installer:J.installer,installed_at:U.toISOString(),version:J.version.trim(),target:J.target.trim(),install_dir:W,owned_paths:P,path_entry:F,background_mode:j,device_consent:B?X?.device_consent??null:{version:D,decision:j==="future_device"?"authorized":j==="updates_only"?"ask":"disabled",scope:j==="future_device"?E:null,recorded_at:U.toISOString()},...T&&X.desktop_account_access?{desktop_account_access:X.desktop_account_access}:{}};return s(I,Q)}function x(J,Q){let U=J.indexOf(Q);if(U===-1)return;let W=J[U+1];if(!W||W.startsWith("--"))throw Error(`${Q} needs a value`);return W}function V(J,Q){let U=x(J,Q);if(!U)throw Error(`${Q} is required`);return U}function cJ(J,Q={}){let U=Q.io??{stdout:process.stdout,stderr:process.stderr};try{let W=new Set(["--channel","--installer","--version","--target","--install-dir","--launcher-path","--launcher-kind","--worker-root","--path-kind","--path-location","--path-value","--background-mode"]);for(let Z=0;Z<J.length;Z+=1){let F=J[Z];if(F==="--path-added")continue;if(!W.has(F))throw Error(`unknown option: ${F}`);if(Z+=1,Z>=J.length)throw Error(`${F} needs a value`)}let X=Q.env??process.env,$=V(J,"--channel"),j=y({env:X,executablePath:Q.executablePath});if($!==j)throw Error(`installer channel ${$} does not match running ${j} CLI`);let T=V(J,"--installer");if(T!=="shell"&&T!=="powershell")throw Error("--installer must be shell or powershell");let B=V(J,"--launcher-kind");if(B!=="file"&&B!=="symlink")throw Error("--launcher-kind must be file or symlink");let O=x(J,"--path-kind"),S=null;if(O){if(O!=="shell_profile"&&O!=="windows_user_path")throw Error("--path-kind must be shell_profile or windows_user_path");S={kind:O,location:V(J,"--path-location"),value:V(J,"--path-value"),added_by_installer:J.includes("--path-added"),added_by_ara:J.includes("--path-added")}}else if(J.includes("--path-location")||J.includes("--path-value")||J.includes("--path-added"))throw Error("path entry flags require --path-kind");let _={channel:j,install_method:"curl",installer:T,version:V(J,"--version"),target:V(J,"--target"),install_dir:V(J,"--install-dir"),launcherPath:V(J,"--launcher-path"),launcherKind:B,workerRoots:J.flatMap((Z,F)=>{if(Z!=="--worker-root")return[];let I=J[F+1];if(!I||I.startsWith("--"))throw Error("--worker-root needs a value");return[I]}),pathEntry:S,backgroundMode:(()=>{let Z=x(J,"--background-mode")??"preserve";if(Z!=="preserve"&&!h(Z))throw Error("--background-mode must be future_device, updates_only, cli_only, or preserve");return Z})()},R=u(X,"REASON_INSTALL_ALIAS_PATH");if(R)_.aliasPath=R;let P=K(p(X,j),Q.home??v());return(Q.writeReceipt??MJ)(_,P,Q.now?.()??new Date),0}catch(W){return U.stderr.write(`Reason installer receipt: ${W instanceof Error?W.message:String(W)}
4
+ `),1}}
5
+ export{z as ge,D as he,i as ie,r as je,E as ke,IJ as le,LJ as me,K as ne,JJ as oe,gJ as pe,hJ as qe,oJ as re,w as se,sJ as te,q as ue,RJ as ve,k as we,b as xe,qJ as ye,lJ as ze,MJ as Ae,cJ as Be};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Gk as M}from"./vm-hands-entry-lite-g87z5eb6.js";import{Mk as G}from"./vm-hands-entry-lite-f78n4wqt.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-a2fhpy8v.js"),import("./local-pty-session-pe20a847.js"),import("./desktop-account-8yf4aqgb.js"),import("./worker-sandbox-nnk7fq89.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
2
+ import{Kk as M}from"./vm-hands-entry-lite-69n9q5f1.js";import{Qk as G}from"./vm-hands-entry-lite-5d31qv44.js";import{readdirSync as D,readFileSync as I}from"fs";import{userInfo as A}from"os";var O="--vm-hands-op-runner-kind=person";function x(q){let Q=new Set([q]),K=[];try{K=D("/proc")}catch{}for(let z of K){if(!/^\d+$/.test(z))continue;try{let X=I(`/proc/${z}/stat`,"utf8");if(Number(X.slice(X.lastIndexOf(")")+2).split(" ")[3])===q)Q.add(Number(z))}catch{}}for(let z of Q)try{process.kill(z,"SIGKILL")}catch{}}var C=(q)=>{let Q=globalThis.Bun;if(!Q)throw new M("pty_unavailable","Reason terminals require the Bun runtime.");let K=Q.spawn({cmd:[q.shell,...q.args],cwd:q.cwd,env:{...q.environment,TERM:"xterm-256color"},terminal:{cols:q.cols,rows:q.rows,data:(J,Y)=>q.onData(Y)}}),z=K.terminal,X=()=>{x(K.pid);try{z?.close()}catch{}};if(!z)throw X(),new M("pty_unavailable","Reason could not allocate a pseudo-terminal.");return{write:(J)=>z.write(J),resize:(J,Y)=>z.resize(J,Y),kill:X,exited:K.exited.then((J)=>typeof J==="number"?J:null,()=>null)}};function L(){let q=(()=>{try{return A().username}catch{return}})();return{PATH:process.env.PATH,HOME:process.env.HOME,SHELL:process.env.SHELL,LANG:"C.UTF-8",...q?{USER:q,LOGNAME:q}:{}}}async function P(){let[{executeLocalOperation:q,spawnCaptured:Q},{runLocalPtySession:K},{configureDesktopAccount:z},{configureWorkerSandbox:X}]=await Promise.all([import("./local-capabilities-x34aehzt.js"),import("./local-pty-session-a0fz1f9t.js"),import("./desktop-account-r5fsgx43.js"),import("./worker-sandbox-ecjj14h5.js")]);X();let T=process.argv.includes(O),J=($,j,F)=>Q($,j[0]==="-lic"?["-lc",...j.slice(1)]:j,F),Y=(process.geteuid?.()??0)!==0,H=new Map,Z=($)=>{try{process.send?.($)}catch{}};process.on("message",($)=>{let j=$;if(j?.t==="cancel"){H.get(j.id)?.abort();return}if(j?.t!=="op")return;if(!Y){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"vm_hands_payload_account_unavailable"}});return}let F=j.claim.capability;if(F==="pty.start"&&!T){Z({t:"done",id:j.id,completion:{status:"failed",error_code:"capability_not_granted"}});return}let U=new AbortController;H.set(j.id,U);let V=F==="pty.start"?{runPtySession:(B)=>K(B,{spawnPty:C,environment:L(),loadProxy:()=>null})}:{worker:j.worker,...F==="exec.full"?{spawnFullControl:J}:{}};q(j.state,j.claim,{...V,signal:U.signal,emit:(B)=>{let{deliverySignal:N,...W}=B;Z({t:"event",id:j.id,event:W})}}).then((B)=>Z({t:"done",id:j.id,completion:B}),(B)=>Z({t:"done",id:j.id,completion:{status:"failed",error_code:B&&typeof B==="object"&&"code"in B&&typeof B.code==="string"?B.code:"vm_hands_op_failed"}})).finally(()=>H.delete(j.id))}),process.on("disconnect",()=>process.exit(0)),await new Promise(()=>{})}
3
3
  export{O as s,C as t,P as u};