@reason-machines/cli-linux-arm64-musl 0.2.387 → 0.2.389

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 (97) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-2edgrjpe.js +2 -0
  3. package/bin/vm-hands/api-credentials-1bfy2pqp.js +2 -0
  4. package/bin/vm-hands/{ask-relay-xa9bffq4.js → ask-relay-72awrbwx.js} +3 -3
  5. package/bin/vm-hands/connect-cli-rss8z5bk.js +2 -0
  6. package/bin/vm-hands/{custom-endpoint-device-bm94e9r0.js → custom-endpoint-device-3g0rc3wp.js} +1 -1
  7. package/bin/vm-hands/desktop-account-8yf4aqgb.js +2 -0
  8. package/bin/vm-hands/{device-workspace-0xsj5ykf.js → device-workspace-35hjc1ff.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-azdrrhsz.js → hands-worker-source-msdkfx9x.js} +1 -1
  10. package/bin/vm-hands/{index-7f2kwwen.js → index-m32pjcjr.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-3xyx3rdd.js → install-receipt-7qanbz38.js} +1 -1
  12. package/bin/vm-hands/local-automation-gb4jmhmg.js +2 -0
  13. package/bin/vm-hands/local-capabilities-gtdp4pz0.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-p6n48895.js +2 -0
  15. package/bin/vm-hands/local-display-mac-7havkbhd.js +2 -0
  16. package/bin/vm-hands/local-display-session-yz5szy3t.js +2 -0
  17. package/bin/vm-hands/local-pty-session-8ny1n2fv.js +2 -0
  18. package/bin/vm-hands/managed-runtime-gyd32324.js +2 -0
  19. package/bin/vm-hands/network-contract-3h853c6e.js +2 -0
  20. package/bin/vm-hands/package-04cf0m62.js +2 -0
  21. package/bin/vm-hands/permissions-6pfayzkx.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-7d7xj1h3.js → reason-hands-protocol-mw7ba8vz.js} +1 -1
  23. package/bin/vm-hands/serve-service-mcnkk9hs.js +2 -0
  24. package/bin/vm-hands/{status-qm9cztrx.js → status-s1g9gt1e.js} +2 -2
  25. package/bin/vm-hands/version-cta9ffcc.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-xrthfx3q.js → vm-hands-entry-lite-00800vjk.js} +2 -2
  27. package/bin/vm-hands/{vm-hands-entry-lite-5n4vsm6b.js → vm-hands-entry-lite-02zaqpgh.js} +5 -5
  28. package/bin/vm-hands/{vm-hands-entry-lite-8fj07njx.js → vm-hands-entry-lite-0seprnh3.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-qnnfvm5r.js → vm-hands-entry-lite-0z73amf7.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-h8dbw0c7.js → vm-hands-entry-lite-180h5amj.js} +1 -1
  31. package/bin/vm-hands/{vm-hands-entry-lite-4g9dqrgy.js → vm-hands-entry-lite-2yx44ayr.js} +34 -34
  32. package/bin/vm-hands/{vm-hands-entry-lite-pk3q774c.js → vm-hands-entry-lite-3nr9q3nf.js} +1 -1
  33. package/bin/vm-hands/{vm-hands-entry-lite-9cmfthkq.js → vm-hands-entry-lite-3ptq7p60.js} +1 -1
  34. package/bin/vm-hands/{vm-hands-entry-lite-fyvgav60.js → vm-hands-entry-lite-5x04hakp.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-6wsa0qrb.js → vm-hands-entry-lite-73akm1q1.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-f5230h6t.js → vm-hands-entry-lite-88h9vwrv.js} +1 -1
  37. package/bin/vm-hands/vm-hands-entry-lite-8e932j3c.js +3 -0
  38. package/bin/vm-hands/{vm-hands-entry-lite-zjfr0zh8.js → vm-hands-entry-lite-8pgggvbb.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-ew076kpd.js → vm-hands-entry-lite-8q63t2c0.js} +2 -2
  40. package/bin/vm-hands/{vm-hands-entry-lite-ammr3xbc.js → vm-hands-entry-lite-a1yy1yp3.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-j8q0pdsq.js → vm-hands-entry-lite-a8pdf1yx.js} +2 -2
  42. package/bin/vm-hands/vm-hands-entry-lite-adpzn7fe.js +3 -0
  43. package/bin/vm-hands/{vm-hands-entry-lite-hnsm5t36.js → vm-hands-entry-lite-atg4z1vg.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-y2s2w174.js → vm-hands-entry-lite-bwpay74g.js} +1 -1
  45. package/bin/vm-hands/{vm-hands-entry-lite-e2mjbqmr.js → vm-hands-entry-lite-csecgmaa.js} +2 -2
  46. package/bin/vm-hands/{vm-hands-entry-lite-xq8bkqrd.js → vm-hands-entry-lite-dbcsvq0f.js} +2 -2
  47. package/bin/vm-hands/{vm-hands-entry-lite-rpn0frzb.js → vm-hands-entry-lite-e73s63fb.js} +1 -1
  48. package/bin/vm-hands/{vm-hands-entry-lite-1gxktkpe.js → vm-hands-entry-lite-ebgackey.js} +2 -2
  49. package/bin/vm-hands/vm-hands-entry-lite-ezahexcb.js +5 -0
  50. package/bin/vm-hands/{vm-hands-entry-lite-d00dg3ys.js → vm-hands-entry-lite-f5v3wap5.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-2t0vcvd8.js → vm-hands-entry-lite-f78n4wqt.js} +1 -1
  52. package/bin/vm-hands/vm-hands-entry-lite-fb02h1zm.js +3 -0
  53. package/bin/vm-hands/{vm-hands-entry-lite-51hmj6am.js → vm-hands-entry-lite-g87z5eb6.js} +1 -1
  54. package/bin/vm-hands/{vm-hands-entry-lite-qef2ndkd.js → vm-hands-entry-lite-h0keewxv.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-fb5dzy9x.js → vm-hands-entry-lite-hfv2tsm9.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-2j141pnw.js → vm-hands-entry-lite-jt9fmk7y.js} +2 -2
  57. package/bin/vm-hands/{vm-hands-entry-lite-ma001vzh.js → vm-hands-entry-lite-ksz1k1dh.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-ejm5er3h.js → vm-hands-entry-lite-mc3pkj0q.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-sex82vb1.js → vm-hands-entry-lite-mft9ke08.js} +1 -1
  60. package/bin/vm-hands/{vm-hands-entry-lite-f7f1zb7s.js → vm-hands-entry-lite-nq5np26e.js} +1 -1
  61. package/bin/vm-hands/{vm-hands-entry-lite-rd0ak4ye.js → vm-hands-entry-lite-p1s0xyc2.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-mn64e4pt.js → vm-hands-entry-lite-r166b92s.js} +1 -1
  63. package/bin/vm-hands/{vm-hands-entry-lite-f02906k8.js → vm-hands-entry-lite-trm3dn8c.js} +1 -1
  64. package/bin/vm-hands/{vm-hands-entry-lite-7a01dgje.js → vm-hands-entry-lite-vvv3m6wy.js} +3 -3
  65. package/bin/vm-hands/{vm-hands-entry-lite-w7havvz8.js → vm-hands-entry-lite-w4tyr264.js} +1 -1
  66. package/bin/vm-hands/{vm-hands-entry-lite-vj9h1knv.js → vm-hands-entry-lite-w844s03h.js} +2 -2
  67. package/bin/vm-hands/{vm-hands-entry-lite-2e18tm6w.js → vm-hands-entry-lite-wpcagqfw.js} +1 -1
  68. package/bin/vm-hands/{vm-hands-entry-lite-wc6skbhf.js → vm-hands-entry-lite-wxzh22y4.js} +2 -2
  69. package/bin/vm-hands/{vm-hands-entry-lite-9w5vs9zv.js → vm-hands-entry-lite-y99g8x7f.js} +1 -1
  70. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  71. package/bin/vm-hands/{vm-hands-executor-d8wkv51n.js → vm-hands-executor-22jnr9y7.js} +1 -1
  72. package/bin/vm-hands/vm-hands-op-runner-dcweybjn.js +2 -0
  73. package/bin/vm-hands/vm-hands-runtime-bt8pe8cm.js +4 -0
  74. package/bin/vm-hands/worker-sandbox-nnk7fq89.js +2 -0
  75. package/package.json +1 -1
  76. package/bin/vm-hands/api-credentials-xppmbg0m.js +0 -2
  77. package/bin/vm-hands/api-xmpbsm6b.js +0 -2
  78. package/bin/vm-hands/connect-cli-c1ex48w5.js +0 -2
  79. package/bin/vm-hands/desktop-account-3tnm4z5w.js +0 -2
  80. package/bin/vm-hands/local-automation-06tkbypc.js +0 -2
  81. package/bin/vm-hands/local-capabilities-cktbbszh.js +0 -2
  82. package/bin/vm-hands/local-desktop-users-ajb81vjm.js +0 -2
  83. package/bin/vm-hands/local-display-mac-9h6btvvq.js +0 -2
  84. package/bin/vm-hands/local-display-session-9d20yat4.js +0 -2
  85. package/bin/vm-hands/local-pty-session-cjas515w.js +0 -2
  86. package/bin/vm-hands/managed-runtime-pjemjmd9.js +0 -2
  87. package/bin/vm-hands/network-contract-dsw79qkc.js +0 -2
  88. package/bin/vm-hands/package-smk3nqjs.js +0 -2
  89. package/bin/vm-hands/permissions-qrfwt9ez.js +0 -2
  90. package/bin/vm-hands/serve-service-403dqjk9.js +0 -2
  91. package/bin/vm-hands/version-gyns0vgm.js +0 -2
  92. package/bin/vm-hands/vm-hands-entry-lite-dh5gwmyf.js +0 -3
  93. package/bin/vm-hands/vm-hands-entry-lite-e0gdt6r5.js +0 -5
  94. package/bin/vm-hands/vm-hands-entry-lite-r8qg3wp1.js +0 -3
  95. package/bin/vm-hands/vm-hands-op-runner-4m334z7c.js +0 -2
  96. package/bin/vm-hands/vm-hands-runtime-6ajffhfb.js +0 -4
  97. package/bin/vm-hands/worker-sandbox-tgqbmy6b.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Ab as _7,Bb as i4,Cb as P7,Db as T7,Kb as R7,Ob as g7,Pb as E7,Zb as $8,bc as S7,cc as f7,dc as F8,ec as Y8,gc as b7,ib as h4,ic as y8,jc as v0,kb as q2,kc as p0,lb as m4,lc as F2,mb as v4,nb as H7,ob as C7,oc as x7,pb as D7,rb as u4,rc as h8,sb as w7,sc as J8,tb as j7,tc as Z8,ub as a4,uc as k1,vb as L7,wb as a3,wc as y7,xb as O7,yb as I7,zb as A7}from"./vm-hands-entry-lite-xq8bkqrd.js";import{Dc as u7,Fc as p7,Gc as d7}from"./vm-hands-entry-lite-ejm5er3h.js";import{Lc as q7}from"./vm-hands-entry-lite-qef2ndkd.js";import{Rc as e0,Sc as $1,Zc as g0}from"./vm-hands-entry-lite-mn64e4pt.js";import{_c as X1}from"./vm-hands-entry-lite-rtt2w6c6.js";import{ad as o4,bd as t4}from"./vm-hands-entry-lite-h8dbw0c7.js";import{dd as h7}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 F7}from"./vm-hands-entry-lite-rpn0frzb.js";import{Cd as W2,Fd as Q9,Od as K9}from"./vm-hands-entry-lite-d00dg3ys.js";import{$e as u6,Ae as n3,Be as O2,Ce as x6,Cf as a8,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,Jf 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 r8,Rf as U5,Sf as F5,Te as n1,Ve as y6,We as h6,Ze 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,qf as Q7,rf as K7,sf as B7,tf as V7,uf as G7,vf as X7,wf as U7,ye as g1,ze as E1}from"./vm-hands-entry-lite-5n4vsm6b.js";import{Yf as A6,ag as h5,bg as G6,hg as B9,kg as m5,lg as X2}from"./vm-hands-entry-lite-vj9h1knv.js";import{ng as t7,og as e7,pg as $9,tg as J9,wg as Z9}from"./vm-hands-entry-lite-dh5gwmyf.js";import{Fg as e4,Mg as k7}from"./vm-hands-entry-lite-xrthfx3q.js";import{Rg as Y2}from"./vm-hands-entry-lite-fb5dzy9x.js";import{Xg as u3,ih as Y7}from"./vm-hands-entry-lite-ammr3xbc.js";import{Ei as m7,Fi as v7}from"./vm-hands-entry-lite-7a01dgje.js";import{Ri as A1,Si as _1,Ti as P1,Ui as T1,Vi as k0}from"./vm-hands-entry-lite-sex82vb1.js";import{lj as b1,mj as M7,nj as n4,oj as r4}from"./vm-hands-entry-lite-fyvgav60.js";import{qj as v3,sj as B1,yj as x8,zj as E4}from"./vm-hands-entry-lite-pk3q774c.js";import{Qj as l7,Rj as s7,Sj as c7,Tj as n7,Vj as r7,Wj as a7,Yj as i7,Zj as o7}from"./vm-hands-entry-lite-1gxktkpe.js";import{ik as V}from"./vm-hands-entry-lite-zjfr0zh8.js";import{Ak as N7,Bk as c4,Ck as l1,sk as W5,tk as s4,yk as W7,zk as z7}from"./vm-hands-entry-lite-r8qg3wp1.js";import{Ek as H}from"./vm-hands-entry-lite-51hmj6am.js";import{Kk as q8}from"./vm-hands-entry-lite-2t0vcvd8.js";import{request as A9}from"http";import{request as _9}from"https";import{lookup as P9}from"dns/promises";import{isIP as T9}from"net";async function R9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?_9:A9)(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"]),q9=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(q9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=Y4(Q,J+1);if(K)return K}return null}async function g9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||T9(Q)!==0)return Z;let K;return await Promise.race([P9(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 E9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function k9($,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=E9(Q.apiKey),X=k9(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 R9({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 g9(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 S9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>S9(Q.path,J));return Z.length===1?Z[0].path:null}var f9=/^[a-f0-9]{64}$/;var D2=32,b9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!b9.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"||!f9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function x9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function y9($){return x9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?y9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),h9=[...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-dbcsvq0f.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-f5v3wap5.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-w844s03h.js";import{og as e7,pg as $9,qg as J9,ug as Z9,xg as Q9}from"./vm-hands-entry-lite-adpzn7fe.js";import{Gg as $8,Ng as S7}from"./vm-hands-entry-lite-00800vjk.js";import{Sg as Y2}from"./vm-hands-entry-lite-hfv2tsm9.js";import{Yg as u3,jh as W7}from"./vm-hands-entry-lite-a1yy1yp3.js";import{Fi as v7,Gi as u7}from"./vm-hands-entry-lite-vvv3m6wy.js";import{Si as A1,Ti as _1,Ui as P1,Vi as T1,Wi as k0}from"./vm-hands-entry-lite-mft9ke08.js";import{mj as b1,nj as j7,oj as r4,pj as a4}from"./vm-hands-entry-lite-5x04hakp.js";import{Aj as k4,rj as v3,tj as B1,zj as y8}from"./vm-hands-entry-lite-3nr9q3nf.js";import{Rj as s7,Sj as c7,Tj as n7,Uj as r7,Wj as a7,Xj as i7,Zj as o7,_j as t7}from"./vm-hands-entry-lite-ebgackey.js";import{jk as V}from"./vm-hands-entry-lite-8pgggvbb.js";import{Ak as N7,Bk as H7,Ck as n4,Dk as l1,tk as z5,uk as c4,zk as z7}from"./vm-hands-entry-lite-fb02h1zm.js";import{Ek as T4}from"./vm-hands-entry-lite-8e932j3c.js";import{Gk as H}from"./vm-hands-entry-lite-g87z5eb6.js";import{Mk as g8}from"./vm-hands-entry-lite-f78n4wqt.js";import{request as _9}from"http";import{request as P9}from"https";import{lookup as T9}from"dns/promises";import{isIP as R9}from"net";async function q9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let K=(J.protocol==="https:"?P9:_9)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:V4},(B)=>Z({response:B,close:()=>{B.destroy(),K.destroy(),B.socket?.destroy()}}));K.once("error",Q),K.once("timeout",()=>K.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),K.end($.body)})}var F4=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),g9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function Y4($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(F4.has(Z))return"custom_endpoint_host_not_found";if(g9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let K=Y4(Q,J+1);if(K)return K}return null}async function E9($,J){let Z=Y4($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||R9(Q)!==0)return Z;let K;return await Promise.race([T9(Q).then(()=>!0,(G)=>!F4.has(String(G?.code))),new Promise((G)=>{K=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(K))?Z:"custom_endpoint_host_not_found"}function k9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function S9($,J){let Z=Buffer.from($),Q=Buffer.from(J),K=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=K[U-1];if(Z[G]===Z[U])U++;K[G]=U}let B=0;return(G,U=!1)=>{let Y=Buffer.allocUnsafe(G.length*Q.length+B),F=0;for(let X of G){while(B&&Z[B]!==X){let W=K[B-1];F+=Z.copy(Y,F,0,B-W),B=W}if(Z[B]===X){if(B++,B===Z.length)F+=Q.copy(Y,F),B=0}else Y[F++]=X}if(U)F+=Z.copy(Y,F,0,B),B=0;return Y.subarray(0,F)}}async function W4($){$.signal.throwIfAborted();let J=X4.safeParse($.payload);if(!J.success)throw new H("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=U4.parse(await $.credential($.signal));if(!G4(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new H("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let K,B,G=0,U=0,Y=0,F=k9(Q.apiKey),X=S9(Q.apiKey,F),W=async(N,C)=>{$.signal.throwIfAborted(),await new Promise((M,w)=>{let D=()=>{$.signal.removeEventListener("abort",D),w($.signal.reason)};if($.signal.addEventListener("abort",D,{once:!0}),$.signal.aborted){D();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,C)}).then(()=>{$.signal.removeEventListener("abort",D),M()},(j)=>{$.signal.removeEventListener("abort",D),w(j)})})},z=async(N)=>{if(G+=N.length,G>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let C=0;C<N.length;C+=H2){if(Y>=B4)throw new H("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await W(`custom_endpoint.chunk.${Y++}`,{eof:!1,data:N.subarray(C,C+H2).toString("base64")})}};try{let N=await q9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});K=N.response,B=N.close;let C=K.statusCode??500;if(C>=300&&C<400)throw new H("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(K.headers["content-encoding"]&&K.headers["content-encoding"]!=="identity")throw new H("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let M={};for(let w of["content-type","retry-after","x-request-id","request-id"]){let D=K.headers[w];if(typeof D==="string")M[w]=D.replaceAll(Q.apiKey,F).slice(0,4096)}await W("custom_endpoint.headers",{status:C,statusText:(K.statusMessage??"").replaceAll(Q.apiKey,F).slice(0,256),headers:M});for await(let w of K){$.signal.throwIfAborted();let D=Buffer.isBuffer(w)?w:Buffer.from(w);if(U+=D.length,U>C2)throw new H("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await z(X(D))}return await z(X(Buffer.alloc(0),!0)),await W(`custom_endpoint.chunk.${Y}`,{eof:!0}),{bytes:G,chunks:Y}}catch(N){if($.signal.throwIfAborted(),N instanceof H)throw N;throw new H((K?null:await E9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{B?.()}}import{join as z4}from"path";function f9($,J){return $===z4(J,".ara","workspace")||$===z4(J,".reason","workspace")}function N4($,J){let Z=$.filter((Q)=>f9(Q.path,J));return Z.length===1?Z[0].path:null}var b9=/^[a-f0-9]{64}$/;var D2=32,x9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!x9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($,J){let Z=J==="win32"?/^([A-Za-z]):[\\/]*(.*)$/.exec($):null;if(!Z)return $;let Q=Z[2].split(/[\\/]+/).filter(Boolean).join("/");return`/${Z[1].toUpperCase()}:${Q?`/${Q}`:""}`}function I1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>D2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:K,path:B}=Q;if(typeof K!=="string"||!b9.test(K)||!L1(B))return;Z.push({path_fingerprint:K,path:B})}return{home:J.home,roots:Z}}function y9($){let J=/^Reason contributor (rc_[0-9a-f]{32})$/.exec($.name)?.[1];return $.email.toLowerCase()==="343777287+reason-contributors@users.noreply.github.com"&&J?J:void 0}function h9($){return y9($)??$.email.toLowerCase()}function w2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?h9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var r0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),m9=[...A1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),..._1.map(($)=>`/(${$.map(r0).join("/")})(/|$)`),...[...P1].map(($)=>`/(${r0($)})$`),`/${r0(".env.")}[^/]*$`,...T1.map(($)=>`/[^/]*${r0($)}$`)],H4=`function localGithubSandboxProfile(root, temporary) {
3
3
  return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
4
4
  '(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
5
5
  '(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
@@ -8,9 +8,9 @@ import{Ab as _7,Bb as i4,Cb as P7,Db as T7,Kb as R7,Ob as g7,Pb as E7,Zb as $8,b
8
8
  '(allow file-read-metadata (path-ancestors '+JSON.stringify(root)+') (path-ancestors '+JSON.stringify(temporary)+'))',
9
9
  '(deny file-read* file-write* (subpath "/opt/homebrew/etc") (subpath "/usr/local/etc") (literal "/private/etc/master.passwd"))',
10
10
  '(deny file-write* (subpath "/opt/homebrew") (subpath "/usr/local") (subpath "/Library/Developer") (subpath "/cores"))',
11
- ...${JSON.stringify(h9)}.map(pattern => '(deny file-read* file-write* (regex #"'+pattern+'"))'),
11
+ ...${JSON.stringify(m9)}.map(pattern => '(deny file-read* file-write* (regex #"'+pattern+'"))'),
12
12
  '(deny network*)','(deny mach-lookup)','(deny process-info*)','(allow process-info* (target same-sandbox))','(allow process-info-listpids)','(allow file-read-metadata (subpath "/dev"))','(deny signal)','(allow signal (target same-sandbox))'].join('\\n');
13
- }`;import{spawn as v9,spawnSync as u9}from"child_process";import*as g from"fs";import*as y from"path";import{homedir as p9}from"os";function C4($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z);if(process.platform==="win32"){let G=(U)=>U.toLowerCase()===K.toLowerCase()||U.toLowerCase().startsWith(K.toLowerCase()+J.sep);for(let U of new Set([process.env.ProgramW6432,process.env.ProgramFiles])){if(!U)continue;try{let Y=$.realpathSync(Q==="gh"?`${U}\\GitHub CLI\\gh.exe`:`${U}\\Git\\cmd\\git.exe`);if(!G(Y)&&Y.toLowerCase().startsWith(U.toLowerCase()+"\\")&&$.statSync(Y).isFile())return Y}catch{}}throw Error("local_device_gh_unavailable")}let B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((F)=>U.startsWith(F)))continue;let Y=$.statSync(U);if(!Y.isFile()||(Y.mode&18)!==0||![0,process.getuid()].includes(Y.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function D4($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var w4=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function M2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function M4($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function j4($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function R1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=M4(J).filter((G)=>!K.has(G));for(let G of $){let U=M2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let Y=G.content??"",F=B.map((X)=>({secret:X,offset:Y.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,W)=>X.offset-W.offset);if(F.length>0){let X=[...new Set(F.flatMap((W)=>Z.secretNames?.(W.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:D4(Y,F[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of w4){let W=j4(X,Y).find((z)=>!K.has(z[0]));if(W){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:D4(Y,W.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function L4($,J=[]){let Z=M4(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of w4)for(let G of j4(B,K))Q.add(G[0])}return[...Q]}function m9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function O4($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+m9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,U0=process.platform==="win32",i0=process.env.SystemRoot??"C:\\Windows",d9=($)=>U0?u9(y.win32.join(i0,"System32","taskkill.exe"),["/PID",String($),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-$,"SIGKILL"),a0=U0?[y.win32.join(i0,"System32"),i0].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",q1=U0?{SystemRoot:i0,WINDIR:i0}:{},l9=($)=>U0?y.win32.resolve($,"..","..","bin","sh.exe"):"/bin/sh",I4=536870912,j2=/^[a-f0-9]{40}$/,s9=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=v9($,J,{cwd:Z.cwd,env:Z.env,...U0?{windowsHide:!0}:{detached:!0},stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,Y=!1,F=(N)=>{if(U??=Error(N),K.pid)try{d9(K.pid)}catch{}},X=()=>F("cancelled"),W=setTimeout(()=>F("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let z=(N)=>{if(Y)return;Y=!0,clearTimeout(W),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)F("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)F("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(F("spawn_failed"),!K.pid)z(null)}),K.on("close",(N)=>z(N)),K.stdin.on("error",()=>F("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),c9={command:s9,gh:($,J)=>C4(g,y,$,J),home:p9};function _($){throw Error($)}function L2($,J){let[Z,Q]=U0?[$.toLowerCase(),J.toLowerCase()]:[$,J];return Q===Z||Q.startsWith(Z+y.sep)}function n9($,J){let Z=new Set($.split(/\r?\n/).map(w2));return J.filter((Q)=>{let K=w2(Q);if(Z.has(K))return!1;return Z.add(K),!0})}var r9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),a9=($)=>JSON.stringify($,(J,Z)=>r9.has(J)?void 0:Z);function A4($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");_(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function T4($,J,Z=c9){let Q=g1.parse($),K="local_device_gh_prepare_setup";try{if(!["darwin","linux","win32"].includes(process.platform))_("local_device_gh_platform_unavailable");J.assertCurrent();let B=g.realpathSync(J.root);if(B===y.parse(B).root)_("local_device_gh_root_unavailable");if(!j0(Q)&&!J.forbiddenSecretValues)_("local_device_gh_secret_scope_unavailable");if(!j0(Q)&&J.readOnly)_("local_device_gh_read_only");if(!j0(Q)){let L=R1([{path:"github-operation",content:a9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)A4(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let G=Z.gh(B),U=Z.home(),Y=Z.gh(B,"git"),F=J.privateDirectory?g.realpathSync(J.privateDirectory):g.realpathSync(U);if(!j0(Q)&&(!J.privateDirectory||L2(B,F)))_("local_device_gh_private_scope_unavailable");let X={...q1,PATH:U0?[y.dirname(Y),a0].join(";"):a0,HOME:U,GH_CONFIG_DIR:U0&&process.env.APPDATA?y.join(process.env.APPDATA,"GitHub CLI"):y.join(U,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:U0?"":"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},W=async(L,T,q=F,S,h=T0)=>{J.assertCurrent();let m=await Z.command(L,T,{cwd:q,env:X,input:S,maxBuffer:h,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),m.error||m.status!==0)_("local_device_gh_command_failed");return m.stdout},z=async(L)=>(await W(G,L)).toString("utf8").trim(),N=async(L,T="application/vnd.github+json")=>{_4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let q=await Z.command(G,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:F,env:X,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),q.error&&q.status===null)_("local_device_gh_response_unavailable");let S=q.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!S)_("local_device_gh_response_invalid");let h=Number(S[1]);if(h>=200&&h<300&&q.status!==0)_("local_device_gh_response_unavailable");if(Buffer.byteLength(S[3])>O2)_("local_device_gh_response_too_large");let m={};for(let i of S[2].split(/\r?\n/)){let e=i.indexOf(":"),M0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(M0))m[M0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:h,headers:m,body:h>=200&&h<300?S[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return N(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),q=await z(["api","graphql","--hostname","github.com","-f",`query=${P4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(q)>O2)_("local_device_gh_response_too_large");let S=JSON.parse(q);if(S.errors||S.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||S.data.repository.pullRequest?.number!==Q.number)_("local_device_gh_response_invalid");return{kind:"pr_review_context",body:q}}if(Q.kind==="pr_merge"){let L=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),q=(m)=>m.number===Q.number&&m.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&m.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&m.base?.ref===Q.expectedBaseRef&&m.head?.sha===Q.expectedHeadSha;if(L.status!==200||!q(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())_("local_device_gh_merge_target_changed");await z(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let S=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),h=JSON.parse(S.body);if(S.status!==200||!q(h)||h.merged!==!0)_("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)_("local_device_gh_default_branch");let L=await z(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))_("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await z(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)_("local_device_gh_workspace_unavailable");let C=g.realpathSync(J.repoPath);if(!L2(B,C))_("local_device_gh_workspace_unavailable");let M=`https://github.com/${Q.repoFullName}.git`,w="!'"+(U0?G.replace(/\\/g,"/"):G).replace(/'/g,"'\\''")+"' auth git-credential",D=Function("return ("+H4+")")(),j=(L,T,q)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...q]]:[T,q],O=async(L,T,q,S=T0)=>{let h=L2(F,L),m=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...h?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(h)return W(Y,m,L,q,S);let i=y.join(C,".ara-local-gh-tmp");if(g.mkdirSync(i,{recursive:!0,mode:448}),g.lstatSync(i).isSymbolicLink()||g.realpathSync(i)!==i)_("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(D(C,i),Y,m),{cwd:L,input:q,maxBuffer:S,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:C,TMPDIR:i,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),e.error||e.status!==0)_("local_device_gh_collection_failed");return e.stdout},A=async(L,T)=>(await O(L,T)).toString("utf8").trim(),b=async(L,T)=>{let q=y.join(L,".ara-local-gh-tmp");if(g.mkdirSync(q,{recursive:!0,mode:448}),g.lstatSync(q).isSymbolicLink()||g.realpathSync(q)!==q)_("local_device_gh_workspace_unavailable");J.assertCurrent();let S=await Z.command(...j(D(L,q),l9(Y),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:L,TMPDIR:q}});if(J.assertCurrent(),S.error||S.status!==0)_("local_device_gh_materialization_failed")},I=async(L)=>{let T=new Map;if(L.length===0)return T;let q=await O(p,["cat-file","--batch"],[...new Set(L)].join(`
13
+ }`;import{spawn as u9,spawnSync as p9}from"child_process";import*as g from"fs";import*as y from"path";import{homedir as d9}from"os";function C4($,J,Z,Q="gh"){if(!["gh","git"].includes(Q))throw Error("local_device_gh_unavailable");let K=$.realpathSync(Z);if(process.platform==="win32"){let G=(U)=>U.toLowerCase()===K.toLowerCase()||U.toLowerCase().startsWith(K.toLowerCase()+J.sep);for(let U of new Set([process.env.ProgramW6432,process.env.ProgramFiles])){if(!U)continue;try{let Y=$.realpathSync(Q==="gh"?`${U}\\GitHub CLI\\gh.exe`:`${U}\\Git\\cmd\\git.exe`);if(!G(Y)&&Y.toLowerCase().startsWith(U.toLowerCase()+"\\")&&$.statSync(Y).isFile())return Y}catch{}}throw Error("local_device_gh_unavailable")}let B=Q==="git"&&process.platform==="darwin"?"/Library/Developer/CommandLineTools/usr/bin/git":"/usr/bin/"+Q;for(let G of["/opt/homebrew/bin/"+Q,"/usr/local/bin/"+Q,B])try{let U=$.realpathSync(G);if(U===K||U.startsWith(K+J.sep)||!["/opt/homebrew/","/usr/local/","/usr/bin/",...Q==="git"?["/Library/Developer/CommandLineTools/"]:[]].some((F)=>U.startsWith(F)))continue;let Y=$.statSync(U);if(!Y.isFile()||(Y.mode&18)!==0||![0,process.getuid()].includes(Y.uid))continue;return $.accessSync(U,$.constants.X_OK),U}catch{continue}throw Error("local_device_gh_unavailable")}function D4($,J){let Z=1;for(let Q=0;Q<J;Q+=1)if($.charCodeAt(Q)===10)Z+=1;return Z}var w4=[{name:"private_key",regex:/-----BEGIN\s+(?:[A-Z0-9_-]+\s+)?PRIVATE\s+KEY-----/i},{name:"github_pat",regex:/\bgh[pousr]_[A-Za-z0-9_]{36,}\b/},{name:"github_fine_grained_pat",regex:/\bgithub_pat_[A-Za-z0-9_]{36,}\b/},{name:"gitlab_pat",regex:/\bglpat-[0-9a-zA-Z_-]{20,}\b/},{name:"slack_token",regex:/\bxox[baprs]-[0-9]{10,}-[0-9]{10,}-[0-9a-zA-Z]{24}\b/},{name:"stripe_live_key",regex:/\b[sr]k_live_[0-9a-zA-Z]{24,}\b/},{name:"bearer_jwt",regex:/\bBearer\s+ey[A-Za-z0-9_-]{20,}\.ey[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{20,}\b/}];function M2($){let J=$.trim().replaceAll("\\","/");if(!J)return{valid:!1,reason:"empty_path"};if(J.startsWith("/"))return{valid:!1,reason:"absolute_path_forbidden"};if(J.split("/").includes("..")||J.includes("../")||J.endsWith("/.."))return{valid:!1,reason:"path_traversal_forbidden"};if(J===".git"||J.startsWith(".git/")||J.includes("/.git/"))return{valid:!1,reason:"git_directory_entry_forbidden"};return{valid:!0}}function M4($){return[...new Set($.map((J)=>J.trim()).filter((J)=>J.length>=8))]}function j4($,J){return[...J.matchAll(new RegExp($.regex.source,`${$.regex.flags}g`))]}function R1($,J=[],Z={}){let Q=[],K=Z.published??new Set,B=M4(J).filter((G)=>!K.has(G));for(let G of $){let U=M2(G.path);if(!U.valid){Q.push({path:G.path,reason:U.reason??"invalid_path"});continue}let Y=G.content??"",F=B.map((X)=>({secret:X,offset:Y.indexOf(X)})).filter((X)=>X.offset>=0).sort((X,W)=>X.offset-W.offset);if(F.length>0){let X=[...new Set(F.flatMap((W)=>Z.secretNames?.(W.secret)??[]))];Q.push({path:G.path,reason:"literal_secret_detected",ruleId:"forbidden_secret_value",line:D4(Y,F[0].offset),...X.length>0?{secretNames:X}:{}})}for(let X of w4){let W=j4(X,Y).find((z)=>!K.has(z[0]));if(W){Q.push({path:G.path,reason:`credential_pattern_detected: ${X.name}`,pattern:X.name,ruleId:X.name,line:D4(Y,W.index)});break}}}return{clean:Q.length===0,violations:Q,scannedObjectCount:$.length}}function L4($,J=[]){let Z=M4(J),Q=new Set;for(let{content:K}of $){for(let B of Z)if(K.includes(B))Q.add(B);for(let B of w4)for(let G of j4(B,K))Q.add(G[0])}return[...Q]}function v9($,J){let Z=0;for(let Q=$.indexOf(J);Q>=0;Q=$.indexOf(J,Q+J.length))Z+=1;return Z}function O4($,J,Z){let Q=(K,B)=>K.reduce((G,U)=>G+v9(U,B),0);return new Set($.filter((K)=>Q(J,K)<=Q(Z,K)))}var T0=4194304,U0=process.platform==="win32",i0=process.env.SystemRoot??"C:\\Windows",l9=($)=>U0?p9(y.win32.join(i0,"System32","taskkill.exe"),["/PID",String($),"/T","/F"],{stdio:"ignore",windowsHide:!0}):process.kill(-$,"SIGKILL"),a0=U0?[y.win32.join(i0,"System32"),i0].join(";"):"/usr/bin:/bin:/usr/sbin:/sbin",q1=U0?{SystemRoot:i0,WINDIR:i0}:{},s9=($)=>U0?y.win32.resolve($,"..","..","bin","sh.exe"):"/bin/sh",I4=536870912,j2=/^[a-f0-9]{40}$/,c9=($,J,Z)=>new Promise((Q)=>{if(Z.signal?.aborted){Q({status:null,error:Error("cancelled"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let K;try{K=u9($,J,{cwd:Z.cwd,env:Z.env,...U0?{windowsHide:!0}:{detached:!0},stdio:["pipe","pipe","pipe"]})}catch{Q({status:null,error:Error("spawn_failed"),stdout:Buffer.alloc(0),stderr:Buffer.alloc(0)});return}let B=Buffer.alloc(0),G=Buffer.alloc(0),U,Y=!1,F=(N)=>{if(U??=Error(N),K.pid)try{l9(K.pid)}catch{}},X=()=>F("cancelled"),W=setTimeout(()=>F("timeout"),Z.timeout);Z.signal?.addEventListener("abort",X,{once:!0});let z=(N)=>{if(Y)return;Y=!0,clearTimeout(W),Z.signal?.removeEventListener("abort",X),Q({status:N,stdout:B,stderr:G,...U?{error:U}:{}})};if(K.stdout.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)F("output_limit");else B=Buffer.concat([B,N])}),K.stderr.on("data",(N)=>{if(B.length+G.length+N.length>Z.maxBuffer)F("output_limit");else G=Buffer.concat([G,N])}),K.on("error",()=>{if(F("spawn_failed"),!K.pid)z(null)}),K.on("close",(N)=>z(N)),K.stdin.on("error",()=>F("input_failed")),K.stdin.end(Z.input),Z.signal?.aborted)X()}),n9={command:c9,gh:($,J)=>C4(g,y,$,J),home:d9};function _($){throw Error($)}function L2($,J){let[Z,Q]=U0?[$.toLowerCase(),J.toLowerCase()]:[$,J];return Q===Z||Q.startsWith(Z+y.sep)}function r9($,J){let Z=new Set($.split(/\r?\n/).map(w2));return J.filter((Q)=>{let K=w2(Q);if(Z.has(K))return!1;return Z.add(K),!0})}var a9=new Set(["repoFullName","branch","head","base","defaultBranch","expectedBaseRef","baseSha","remoteHeadSha","expectedHeadSha"]),i9=($)=>JSON.stringify($,(J,Z)=>a9.has(J)?void 0:Z);function A4($,J,Z){let Q=[...new Set($.map((B)=>`${J(B.path)}${B.line?`:${B.line}`:""} (${B.reason==="literal_secret_detected"?`value of ${B.secretNames?.length?B.secretNames.slice(0,3).join(", "):"a session variable"}`:`${B.ruleId??"credential"} credential`})`))].slice(0,10),K=$.some((B)=>B.reason==="literal_secret_detected");_(`local_device_gh_secret_scan_failed: the change adds text matching a secret that the base does not already contain: ${Q.join("; ")}. Nothing was sent. ${Z}${K?" If the line is ordinary code, that variable's value is too generic to tell apart from code: tell the person which variable matched so they can change its value.":""}`)}async function R4($,J,Z=n9){let Q=g1.parse($),K="local_device_gh_prepare_setup";try{if(!["darwin","linux","win32"].includes(process.platform))_("local_device_gh_platform_unavailable");J.assertCurrent();let B=g.realpathSync(J.root);if(B===y.parse(B).root)_("local_device_gh_root_unavailable");if(!j0(Q)&&!J.forbiddenSecretValues)_("local_device_gh_secret_scope_unavailable");if(!j0(Q)&&J.readOnly)_("local_device_gh_read_only");if(!j0(Q)){let L=R1([{path:"github-operation",content:i9(Q)}],J.forbiddenSecretValues,J.secretNames?{secretNames:J.secretNames}:{});if(!L.clean)A4(L.violations,()=>`the ${Q.kind} request text`,"Remove it from the pull request text and try again.")}let G=Z.gh(B),U=Z.home(),Y=Z.gh(B,"git"),F=J.privateDirectory?g.realpathSync(J.privateDirectory):g.realpathSync(U);if(!j0(Q)&&(!J.privateDirectory||L2(B,F)))_("local_device_gh_private_scope_unavailable");let X={...q1,PATH:U0?[y.dirname(Y),a0].join(";"):a0,HOME:U,GH_CONFIG_DIR:U0&&process.env.APPDATA?y.join(process.env.APPDATA,"GitHub CLI"):y.join(U,".config","gh"),GH_PROMPT_DISABLED:"1",GH_PAGER:U0?"":"/bin/cat",GH_HOST:"github.com",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1",...process.platform==="linux"?Object.fromEntries(["DBUS_SESSION_BUS_ADDRESS","XDG_RUNTIME_DIR"].flatMap((L)=>process.env[L]?[[L,process.env[L]]]:[])):{}},W=async(L,T,q=F,S,h=T0)=>{J.assertCurrent();let m=await Z.command(L,T,{cwd:q,env:X,input:S,maxBuffer:h,timeout:Math.max(1,Math.min(60000,(J.deadlineMs??Date.now()+60000)-Date.now())),signal:J.signal});if(J.assertCurrent(),m.error||m.status!==0)_("local_device_gh_command_failed");return m.stdout},z=async(L)=>(await W(G,L)).toString("utf8").trim(),N=async(L,T="application/vnd.github+json")=>{_4(Q.repoFullName,L,{headers:{accept:T}}),J.assertCurrent();let q=await Z.command(G,["api","--hostname","github.com","--method","GET","--include","-H",`Accept: ${T}`,L],{cwd:F,env:X,maxBuffer:T0,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal});if(J.assertCurrent(),q.error&&q.status===null)_("local_device_gh_response_unavailable");let S=q.stdout.toString("utf8").match(/^HTTP\/[^ ]+ ([0-9]{3})[^\r\n]*\r?\n([\s\S]*?)\r?\n\r?\n([\s\S]*)$/);if(!S)_("local_device_gh_response_invalid");let h=Number(S[1]);if(h>=200&&h<300&&q.status!==0)_("local_device_gh_response_unavailable");if(Buffer.byteLength(S[3])>O2)_("local_device_gh_response_too_large");let m={};for(let i of S[2].split(/\r?\n/)){let e=i.indexOf(":"),M0=i.slice(0,e).toLowerCase();if(["link","content-type"].includes(M0))m[M0]=i.slice(e+1).trim().slice(0,8192)}return{kind:"read",status:h,headers:m,body:h>=200&&h<300?S[3]:JSON.stringify({message:"local_device_gh_request_failed"})}};if(Q.kind==="read")return N(Q.path,Q.accept);if(Q.kind==="pr_review_context"){let[L,T]=Q.repoFullName.split("/"),q=await z(["api","graphql","--hostname","github.com","-f",`query=${P4}`,"-f",`owner=${L}`,"-f",`repo=${T}`,"-F",`number=${Q.number}`,...Q.after?["-f",`after=${Q.after}`]:[]]);if(Buffer.byteLength(q)>O2)_("local_device_gh_response_too_large");let S=JSON.parse(q);if(S.errors||S.data?.repository?.nameWithOwner?.toLowerCase()!==Q.repoFullName.toLowerCase()||S.data.repository.pullRequest?.number!==Q.number)_("local_device_gh_response_invalid");return{kind:"pr_review_context",body:q}}if(Q.kind==="pr_merge"){let L=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),T=JSON.parse(L.body),q=(m)=>m.number===Q.number&&m.html_url===`https://github.com/${Q.repoFullName}/pull/${Q.number}`&&m.base?.repo?.full_name?.toLowerCase()===Q.repoFullName.toLowerCase()&&m.base?.ref===Q.expectedBaseRef&&m.head?.sha===Q.expectedHeadSha;if(L.status!==200||!q(T)||T.state!=="open"||T.draft!==!1||T.head?.sha!==Q.expectedHeadSha||T.base?.repo?.full_name?.toLowerCase()!==Q.repoFullName.toLowerCase())_("local_device_gh_merge_target_changed");await z(["pr","merge",String(Q.number),`--repo=${Q.repoFullName}`,`--${Q.method}`,"--match-head-commit",Q.expectedHeadSha,...Q.commitBody!==void 0&&Q.method!=="rebase"?[`--body=${Q.commitBody}`]:[]]);let S=await N(`/repos/${Q.repoFullName}/pulls/${Q.number}`),h=JSON.parse(S.body);if(S.status!==200||!q(h)||h.merged!==!0)_("local_device_gh_merge_unconfirmed");return{kind:"pr_merge",number:Q.number,merged:!0}}if(Q.kind==="pr_create"){if(Q.head===Q.base)_("local_device_gh_default_branch");let L=await z(["pr","create","--repo",Q.repoFullName,"--head",Q.head,"--base",Q.base,`--title=${Q.title}`,`--body=${Q.body}`,...Q.draft?["--draft"]:[]]);if(!new RegExp("^https://github\\.com/"+Q.repoFullName.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")+"/pull/[1-9][0-9]*$").test(L))_("local_device_gh_mutation_unconfirmed");return{kind:"pr_create",url:L}}if(Q.kind==="pr_mutation"){let L=Q.mutation,T=L.action==="edit"?["edit",...L.title!==void 0?[`--title=${L.title}`]:[],...L.body!==void 0?[`--body=${L.body}`]:[],...L.base?[`--base=${L.base}`]:[]]:L.action==="metadata"?["edit",`--${L.change}-${L.field}=${L.value}`]:L.action==="ready"?["ready"]:L.action==="draft"?["ready","--undo"]:["close"];return await z(["pr",...T,String(Q.number),"--repo",Q.repoFullName]),{kind:"pr_mutation",number:Q.number,applied:!0}}if(!J.repoPath)_("local_device_gh_workspace_unavailable");let C=g.realpathSync(J.repoPath);if(!L2(B,C))_("local_device_gh_workspace_unavailable");let M=`https://github.com/${Q.repoFullName}.git`,w="!'"+(U0?G.replace(/\\/g,"/"):G).replace(/'/g,"'\\''")+"' auth git-credential",D=T4(H4),j=(L,T,q)=>process.platform==="darwin"?["/usr/bin/sandbox-exec",["-p",L,T,...q]]:[T,q],O=async(L,T,q,S=T0)=>{let h=L2(F,L),m=["-c","core.hooksPath=/dev/null","-c","core.fsmonitor=false","-c","credential.helper=","-c","http.extraheader=",...h?["-c",`credential.https://github.com.helper=${w}`]:[],"-c","protocol.ext.allow=never","-c","protocol.file.allow=never","-c","protocol.ssh.allow=never",...T];if(h)return W(Y,m,L,q,S);let i=y.join(C,".ara-local-gh-tmp");if(g.mkdirSync(i,{recursive:!0,mode:448}),g.lstatSync(i).isSymbolicLink()||g.realpathSync(i)!==i)_("local_device_gh_workspace_unavailable");J.assertCurrent();let e=await Z.command(...j(D(C,i),Y,m),{cwd:L,input:q,maxBuffer:S,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:C,TMPDIR:i,GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_SYSTEM:"/dev/null",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_NO_REPLACE_OBJECTS:"1",GIT_LFS_SKIP_SMUDGE:"1"}});if(J.assertCurrent(),e.error||e.status!==0)_("local_device_gh_collection_failed");return e.stdout},A=async(L,T)=>(await O(L,T)).toString("utf8").trim(),b=async(L,T)=>{let q=y.join(L,".ara-local-gh-tmp");if(g.mkdirSync(q,{recursive:!0,mode:448}),g.lstatSync(q).isSymbolicLink()||g.realpathSync(q)!==q)_("local_device_gh_workspace_unavailable");J.assertCurrent();let S=await Z.command(...j(D(L,q),s9(Y),["-c",'printf "%s\\n" "$1" > .git/shallow',"sh",T]),{cwd:L,maxBuffer:65536,timeout:Math.max(1,Math.min(25000,(J.deadlineMs??Date.now()+25000)-Date.now())),signal:J.signal,env:{...q1,PATH:a0,HOME:L,TMPDIR:q}});if(J.assertCurrent(),S.error||S.status!==0)_("local_device_gh_materialization_failed")},I=async(L)=>{let T=new Map;if(L.length===0)return T;let q=await O(p,["cat-file","--batch"],[...new Set(L)].join(`
14
14
  `)+`
15
15
  `,T0*8);for(let S=0;S<q.length;){let h=q.indexOf(10,S),[m,i,e]=q.subarray(S,h).toString("utf8").split(" ");if(h<0||!m||i!=="blob"||!/^[0-9]+$/.test(e??""))_("local_device_gh_object_invalid");T.set(m,q.subarray(h+1,h+1+Number(e)).toString("utf8")),S=h+1+Number(e)+1}return T},R=async(L,T,q)=>{let S=y.join(C,".ara-local-gh-tmp"),h=D(C,S)+`
16
16
  (allow file-read* file-write* (subpath ${JSON.stringify(C)}))
@@ -21,22 +21,22 @@ import{Ab as _7,Bb as i4,Cb as P7,Db as T7,Kb as R7,Ob as g7,Pb as E7,Zb as $8,b
21
21
  `)].filter(Boolean);if(h.some((d)=>!j2.test(d)))_("local_device_gh_object_invalid");let m=await O(C,["pack-objects","--stdout"],[...new Set(h)].join(`
22
22
  `)+`
23
23
  `,I4);if(g.writeFileSync(y.join(p,"shallow"),Q.baseSha+`
24
- `,{flag:"wx",mode:384}),await O(p,["index-pack","--strict","--stdin"],m,65536),await O(p,["merge-base","--is-ancestor",Q.baseSha,T]),Q.remoteHeadSha)await O(p,["merge-base","--is-ancestor",Q.remoteHeadSha,T]);let i=await O(p,["show","-s","--format=%B",T]),e=(await O(p,["interpret-trailers","--parse"],i)).toString("utf8"),M0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:n9(e,Q.contributorTrailers)}:void 0,s0=(await A(p,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
25
- `).filter(Boolean);if(s0.length>5000)_("local_device_gh_collection_too_large");let c0=[],J4=0;for(let d of s0){if(!j2.test(d))_("local_device_gh_object_invalid");let B0=await A(p,["cat-file","-t",d]);if(!["blob","commit","tree"].includes(B0))_("local_device_gh_object_invalid");let $0=await O(p,["cat-file",B0,d]);if(J4+=$0.length,J4>T0)_("local_device_gh_collection_too_large");if(B0==="tree"){let Y0=0;while(Y0<$0.length){let H0=$0.indexOf(32,Y0),t=$0.indexOf(0,H0+1);if(H0<Y0||t<=H0||t+21>$0.length)_("local_device_gh_object_invalid");let V0=$0.subarray(H0+1,t).toString("utf8");if(V0.includes("/")||!M2(V0).valid)_("local_device_gh_object_invalid");Y0=t+21}}c0.push({path:`object-${d}`,content:$0.toString("utf8")})}let Z4=J.secretNames?{secretNames:J.secretNames}:{},n0=R1(c0,J.forbiddenSecretValues,Z4),Q4=new Map;if(!n0.clean)try{let d=(await O(p,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,T])).toString("utf8").split("\x00"),B0=[],$0=[];for(let r=0;r+1<d.length;r+=2){let[,O9,I9,N2,j1]=d[r].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!N2||!j1)continue;if(O9!=="160000"&&!/^0+$/.test(N2))B0.push(N2);if(I9!=="160000"&&!/^0+$/.test(j1))$0.push(j1),Q4.set(`object-${j1}`,d[r+1])}let Y0=await I([...B0,...$0]),H0=new Set(n0.violations.map((r)=>r.path)),t=L4(c0.filter((r)=>H0.has(r.path)),J.forbiddenSecretValues),V0=O4(t,$0.map((r)=>Y0.get(r)??""),B0.map((r)=>Y0.get(r)??""));if(V0.size>0)n0=R1(c0,J.forbiddenSecretValues,{...Z4,published:V0})}catch{}if(!n0.clean)A4(n0.violations,(d)=>Q4.get(d)??`an object in the pushed history (${d})`,"Remove it from the files and commit again; a commit or message in the pushed history that holds it must be amended before this branch can be pushed.");await O(p,["push","--no-recurse-submodules",M,`${T}:refs/heads/${Q.branch}`]);let K4=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(K4.status!==200||JSON.parse(K4.body).object?.sha!==T)_("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:T,scannedObjectCount:c0.length,...M0?{attribution:M0}:{}}}catch(L){throw M1=!0,L}finally{try{g.rmSync(p,{recursive:!0,force:!0})}catch(L){if(!M1||Q.kind!=="prepare")throw K=null,L}}}catch(B){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&K&&!J.signal?.aborted)throw new E1(K);throw B}}var R0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),I2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},i9=V.object({...I2,version:V.literal(2),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!1),source_bound:V.literal(!1),profiles:V.array(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),o9=V.object({...I2,version:V.literal(3),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!0),source_bound:V.literal(!1),max_seconds:V.literal(15),profiles:V.array(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),A2=V.union([i9,o9]),QB=V.union([V.object({...I2,version:V.literal(1),development_only:V.literal(!0),profile:R0.shape.profile,extension_instance_id:R0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),A2]);import{randomUUID as E2}from"crypto";import{spawn as Y$}from"child_process";import{existsSync as k2,lstatSync as Q8,mkdirSync as W$,readFileSync as z$,realpathSync as S1,rmSync as N$,writeFileSync as H$}from"fs";import{dirname as C$,join as W0,relative as D$,sep as w$}from"path";var t9=["process.run.v1","process.full.v1"],e9=600000,$$=1800000,J$=20000,R4="process.cancel.v1",q4=V.object({action:V.literal("start"),request_id:V.string().uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),cwd:V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")&&!$.startsWith("/")&&!$.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:V.enum(["host","confined"]).default("host"),timeout_ms:V.number().int().min(1000).max($$).default(e9).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),_2={device_id:V.string().uuid(),root_id:V.string().uuid()},Z$=V.discriminatedUnion("action",[q4.extend(_2),V.object({..._2,action:V.literal("inspect"),process_id:V.string().uuid(),after:V.number().int().min(0).default(0),wait_ms:V.number().int().min(0).max(J$).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),V.object({..._2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),VB=V.toJSONSchema(Z$,{io:"input"}),GB=q4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),o0=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:V.number().int().nullable(),first_cursor:V.number().int().min(0),next_cursor:V.number().int().min(0),truncated:V.boolean(),observed_at:V.iso.datetime(),output:V.array(V.object({cursor:V.number().int().min(1),stream:V.enum(["stdout","stderr"]),text:V.string().max(32768)}).strict()).max(128)}).strict().refine(($)=>{if(Buffer.byteLength(JSON.stringify($))>1e5||$.next_cursor<$.first_cursor-1)return!1;if(($.state==="starting"||$.state==="running"||$.state==="uncertain")&&$.exit_code!==null)return!1;if($.state==="exited"&&($.exit_code===null||$.exit_code<0||$.exit_code>255))return!1;if($.state==="cancelled"&&$.exit_code!==130||$.state==="expired"&&$.exit_code!==124)return!1;let Z=$.first_cursor-1;for(let Q of $.output){if(Q.cursor<=Z||Q.cursor>$.next_cursor)return!1;Z=Q.cursor}return!0});function g4($){return t9.includes($)}var XB=V.object({operation_constraints:V.record(V.string(),V.unknown())}),UB=V.object({ready:V.literal(!0),version:V.literal(1),execution_mode:V.enum(["host","confined"]),max_timeout_ms:V.number().int().min(1000).optional()});var Q$=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["queued","cancelled_before_start","not_started"]),exit_code:V.null(),output:V.array(V.never()).length(0),first_cursor:V.literal(0),next_cursor:V.literal(0),truncated:V.literal(!1),cancellation_requested:V.literal(!1),reason_code:V.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),K$=V.object({...o0.shape,state:V.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:V.iso.datetime().optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:V.boolean(),reason_code:V.string().nullable().optional(),execution_authority:V.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:V.object({cause:V.literal("brain_generation_changed"),terminal_confirmed:V.boolean(),next_step:V.enum(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:o0.shape.state.or(V.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),FB=V.toJSONSchema(K$),YB=V.union([o0,Q$.refine(($)=>$.state==="cancelled_before_start")]),P2=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["exited","cancelled","expired"]),exit_code:V.number().int().min(0).max(255),observed_at:V.iso.datetime()}).strict().refine(($)=>($.state!=="cancelled"||$.exit_code===130)&&($.state!=="expired"||$.exit_code===124)),B$=V.object({process_terminal_observation:P2}).strict();function WB($,J){let Z=B$.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var k4="preview.serve.v1",S4=43200000;var CB=3,f4="preview.open.v1",b4=1,T2="gid_proxy_v1",x4="egress",R2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,V$=V.object({version:V.literal(T2),allowed_domains:V.array(V.string().max(260).regex(R2)).max(1024)}).strict(),G$=V.custom(($)=>E4($)!==null,"invalid workspace"),X$=V.object({version:V.literal(1),request_id:V.uuid(),session_id:V.uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),port:V.number().int().min(1024).max(65535),workspace:G$,egress:V$.optional()}).strict(),y4=X$.extend({expires_at:V.iso.datetime()}).strict();var U$=4,F$=5000;function g2($,J,Z){let Q=null;try{Q=q2($)}catch{}m4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function p4($){let J=new Map;return{open(Z){let Q=(X)=>g2(Z,$.claim.operation_id,X),K;try{K=q2(Z)}catch{return Q("binding_invalid")}let{binding:B,deviceRelayUrl:G}=K,U=$.claim.owner;if(!U||B.organizationId!==U.organization_id||B.userId!==U.user_id||B.deviceId!==U.device_id||B.rootId!==$.claim.root_id||B.jobId!==$.claim.operation_id||B.fenceId!==$.claim.operation_id||B.generation!==b4||B.expiresAtMs>Math.min(Date.now()+h4.lifetimeMs+F$,$.expiresAtMs))return Q("binding_mismatch");if(B.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(B.port)?.abort(),J.delete(B.port),J.size>=U$)return Q("preview_capacity");let Y=new AbortController;J.set(B.port,Y);let F=u4({binding:B,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(Y.signal.aborted)return null;let X=await $.inspect();return X?{binding:B,executorLaunchId:$.executorLaunchId,job:X}:null}});v4({binding:B,deviceRelayUrl:G,port:F,signal:Y.signal}).then((X)=>X.closed,(X)=>{let W=X instanceof Error?X.message:"preview_failed";if(W!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:B.jobId,port:B.port,reason_code:W})}
26
- `)}).finally(()=>{if(J.get(B.port)===Y)J.delete(B.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class t0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var K8=256,f1=new Map,B8="preview.serve.v1",q0=new Map;function V8($){let J=q0.get($.operation_id);if(J){if(J.claim!==$)throw G0("process_authority_lost");return J}if(q0.size>=K8)throw G0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return q0.set($.operation_id,Z),Z}function d4($){return{version:1,process_id:$,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var l4=($)=>new Promise((J)=>setTimeout(J,$)),G0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function M$($=b1(),J=j$()){let Z=C$(e4({},$)),Q=D$(n4($),Z),[K,...B]=Q.split(w$);return{directory:W0(J,Q,"processes"),previous:[W0(Z,"processes"),...K==="reason"?[W0(J,"ara",...B,"processes")]:[]]}}function j$(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=r4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function S2($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw G0("process_authority_lost");let J=V8($.claim);if(J.executing)throw G0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",d4($.claim.operation_id);J.phase="starting";let Z=$.journals??M$();W$(Z.directory,{recursive:!0,mode:448});let Q=a4({runtimeDirectory:S1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((I)=>k2(I)).map((I)=>S1(I)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:K8});try{for(let I of[$.root,$.cwd])if(!$8(S1(I),Q.journalDirectory))throw new H("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(I){throw Q.disposeSocket(),I}let K=Q8(Q.journalDirectory),B=$.claim.capability===B8,G=()=>f1.set($.claim.operation_id,{path:Q.journalDirectory,ino:K.ino,dev:K.dev,anyCompletion:B}),U=Q.launchDirectory,Y=W0(U,"config.json"),F={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:e0,protocolVersion:2,workerArtifactSha256:g0,workerEntrypoint:$1,targetGeneration:1,fenceId:E2(),...process.platform==="win32"?{bashExecutable:s4()}:{},workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:W0(U,"unused.env"),replSocketPath:W0(U,"unused.sock"),readyPath:W0(U,"ready.json"),directTerminalReceiptPath:W0(U,"terminal.json"),launchId:E2(),expiresAtMs:$.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Q.journalDirectory,scopeId:Q.scopeId},jobControlSocketPath:Q.socketPath,...$.prefix?{bashCommandPrefix:$.prefix}:{},...$.jobsUser?{jobsUser:$.jobsUser}:{}},X;try{H$(Y,JSON.stringify(F),{mode:384});let I=J8({configPath:Y,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(Y,F)??Y$(I.command,I.args,{...I.options,env:$.environment,stdio:[Z8,"ignore","ignore"]})}catch(I){throw Q.disposeSocket(),I}let W=!1,z=new Promise((I,R)=>{X.once("exit",(P)=>{W=!0,I(P)}),X.once("error",(P)=>{W=!0,R(P)})});z.catch(()=>{});let N={root:$.root,runId:$.claim.run_id,scopeId:Q.scopeId,socketPath:Q.socketPath,generation:1,fenceId:F.fenceId,executorLaunchId:F.launchId,expiresAtMs:F.expiresAtMs},C=async(I)=>{let R=await i4(N,{type:"job",version:2,generation:1,id:E2(),jobId:$.claim.operation_id,...I==="start"?{action:I,input:{script:$.command,leaseExpiresAtMs:$.expiresAtMs}}:I==="inspect"?{action:I,input:{after:0}}:I==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:I,input:{}}},new AbortController().signal);if(!R.ok)throw G0(R.error);return R.job},M=!1,w=!1,D,j=()=>{M=!0,k1(X,"SIGTERM")};$.signal.addEventListener("abort",j,{once:!0});let O,A=0,b=async(I)=>{let R=[...I.output],P={version:1,process_id:$.claim.operation_id,state:I.state,exit_code:I.exitCode,first_cursor:I.firstCursor,next_cursor:I.nextCursor,truncated:I.truncated,output:R,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(P))>90000&&R.length)R.shift(),P.truncated=!0,P.first_cursor=R[0]?.cursor??P.next_cursor+1;O=o0.parse(P),await $.emit(O),A=Date.now()};try{let I=Math.min(Date.now()+1e4,$.expiresAtMs);while(!k2(F.readyPath)){if(W)throw new H("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if($.signal.aborted||Date.now()>=I)throw G0("process_start_unconfirmed");await l4(25)}let R=JSON.parse(z$(F.readyPath,"utf8"));if(R.launchId!==F.launchId||R.fenceId!==F.fenceId||R.workerArtifactSha256!==g0)throw G0();if($.signal.throwIfAborted(),J.cancelRequested)return d4($.claim.operation_id);let P;try{w=!0,P=await C("start")}catch(c){if(!(c instanceof H)||c.code!=="hands_job_result_unknown")throw c;P=await C("inspect")}if(J.phase="running",J.cancel=async()=>{await C("cancel")},B&&$.preview)J.tunnels=p4({claim:$.claim,executorLaunchId:F.launchId,expiresAtMs:$.expiresAtMs,deniedPorts:$.preview.deniedPorts,inspect:async()=>J.phase==="running"&&!W?await C("probe"):null});if(J.cancelRequested)await J.cancel(),P=await C("inspect");for(;;){if(!["starting","running"].includes(P.state))J.phase="settling",J.cancel=void 0;if(!O||O.state!==P.state||O.next_cursor!==P.nextCursor&&Date.now()-A>=5000)await b(P);if(!["starting","running"].includes(P.state))break;if($.signal.aborted||W)throw G0();await l4(1000);try{P=await C("inspect"),D=void 0}catch(c){if(!(c instanceof H)||c.code!=="hands_job_result_unknown"||$.signal.aborted||W||Date.now()-(D??=Date.now())>120000)throw c}}if(!O||O.state==="uncertain")throw G0();return O}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",j),!W&&!M)k1(X,"SIGTERM");let I,R=await Promise.race([z.then((P)=>({code:P})),new Promise((P)=>{I=setTimeout(()=>P(null),6000)})]).finally(()=>{clearTimeout(I)});if(!R){try{k1(X,"SIGKILL")}catch{}try{await z}finally{if(W)Q.disposeSocket()}throw G0("process_cleanup_unconfirmed")}try{if((M||$.signal.aborted)&&R.code===0&&w){o4(U);let P=JSON.parse(t4(F.directTerminalReceiptPath)),c=P2.safeParse(P.observation);if(Object.keys(P).length===4&&P.launch_id===F.launchId&&P.fence_id===F.fenceId&&P.scope_id===Q.scopeId&&c.success&&c.data.process_id===$.claim.operation_id){if(B)G();throw new t0(c.data)}}}catch(P){if(P instanceof t0)throw P}finally{if(W)Q.disposeSocket()}if(R.code!==0&&!M&&w)throw G0("process_cleanup_unconfirmed");if(!M&&R.code===0&&(O&&["exited","cancelled","expired"].includes(O.state)||!w&&J.cancelRequested)||B&&R.code===0&&!w)G()}}async function mB($,J){if(J.kind===f4&&$.capability===B8){let K=q0.get($.operation_id);if(K?.claim===$&&K.tunnels)K.tunnels.open(J.payload);else g2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==R4||!g4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=q0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=V8($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function vB($,J){q0.delete($);let Z=f1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return f1.delete($),!1;try{let Q=Q8(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||!c4(Q)||S1(Z.path)!==Z.path||k2(W0(Z.path,"owner.lock")))return!1;return N$(Z.path,{recursive:!0}),f1.delete($),!0}catch{return!1}}import{createServer as L$,request as O$}from"http";import{connect as I$,isIP as A$}from"net";var W8=120000,_$=15000;function P$($,J,Z){let Q=F8(J).toLowerCase().replace(/\.$/,"");if(!Q||A$(Q))return!1;return $.some((K)=>{if(!R2.test(K))return!1;let B=K.lastIndexOf(":"),G=B>0?K.slice(0,B):K;if(B>0&&Number(K.slice(B+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function T$($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,K=Z?Number(Z[2]):J;return Q&&K>=1&&K<=65535?{host:Q,port:K}:null}async function f2($,J,Z){if(!P$(Z,$,J))return null;let Q=await Y8($);return Q.ok?Q.addresses[0]:null}function J1($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
24
+ `,{flag:"wx",mode:384}),await O(p,["index-pack","--strict","--stdin"],m,65536),await O(p,["merge-base","--is-ancestor",Q.baseSha,T]),Q.remoteHeadSha)await O(p,["merge-base","--is-ancestor",Q.remoteHeadSha,T]);let i=await O(p,["show","-s","--format=%B",T]),e=(await O(p,["interpret-trailers","--parse"],i)).toString("utf8"),M0=Q.contributorTrailers?{expectedTrailers:Q.contributorTrailers,missingFromHead:r9(e,Q.contributorTrailers)}:void 0,s0=(await A(p,["rev-list","--objects","--no-object-names",T,"--not",Q.baseSha,...Q.remoteHeadSha?[Q.remoteHeadSha]:[]])).split(`
25
+ `).filter(Boolean);if(s0.length>5000)_("local_device_gh_collection_too_large");let c0=[],J4=0;for(let d of s0){if(!j2.test(d))_("local_device_gh_object_invalid");let B0=await A(p,["cat-file","-t",d]);if(!["blob","commit","tree"].includes(B0))_("local_device_gh_object_invalid");let $0=await O(p,["cat-file",B0,d]);if(J4+=$0.length,J4>T0)_("local_device_gh_collection_too_large");if(B0==="tree"){let Y0=0;while(Y0<$0.length){let H0=$0.indexOf(32,Y0),t=$0.indexOf(0,H0+1);if(H0<Y0||t<=H0||t+21>$0.length)_("local_device_gh_object_invalid");let V0=$0.subarray(H0+1,t).toString("utf8");if(V0.includes("/")||!M2(V0).valid)_("local_device_gh_object_invalid");Y0=t+21}}c0.push({path:`object-${d}`,content:$0.toString("utf8")})}let Z4=J.secretNames?{secretNames:J.secretNames}:{},n0=R1(c0,J.forbiddenSecretValues,Z4),Q4=new Map;if(!n0.clean)try{let d=(await O(p,["diff","--no-renames","--no-abbrev","--raw","-z",Q.baseSha,T])).toString("utf8").split("\x00"),B0=[],$0=[];for(let r=0;r+1<d.length;r+=2){let[,I9,A9,N2,j1]=d[r].slice(1).match(/^([0-7]{6}) ([0-7]{6}) ([0-9a-f]{40}) ([0-9a-f]{40}) /)??[];if(!N2||!j1)continue;if(I9!=="160000"&&!/^0+$/.test(N2))B0.push(N2);if(A9!=="160000"&&!/^0+$/.test(j1))$0.push(j1),Q4.set(`object-${j1}`,d[r+1])}let Y0=await I([...B0,...$0]),H0=new Set(n0.violations.map((r)=>r.path)),t=L4(c0.filter((r)=>H0.has(r.path)),J.forbiddenSecretValues),V0=O4(t,$0.map((r)=>Y0.get(r)??""),B0.map((r)=>Y0.get(r)??""));if(V0.size>0)n0=R1(c0,J.forbiddenSecretValues,{...Z4,published:V0})}catch{}if(!n0.clean)A4(n0.violations,(d)=>Q4.get(d)??`an object in the pushed history (${d})`,"Remove it from the files and commit again; a commit or message in the pushed history that holds it must be amended before this branch can be pushed.");await O(p,["push","--no-recurse-submodules",M,`${T}:refs/heads/${Q.branch}`]);let K4=await N(`/repos/${Q.repoFullName}/git/ref/heads/${encodeURIComponent(Q.branch)}`);if(K4.status!==200||JSON.parse(K4.body).object?.sha!==T)_("local_device_gh_push_unconfirmed");return{kind:"publish",headSha:T,scannedObjectCount:c0.length,...M0?{attribution:M0}:{}}}catch(L){throw M1=!0,L}finally{try{g.rmSync(p,{recursive:!0,force:!0})}catch(L){if(!M1||Q.kind!=="prepare")throw K=null,L}}}catch(B){if(Q.kind==="prepare"&&Q.diagnosticsVersion===1&&K&&!J.signal?.aborted)throw new E1(K);throw B}}var R0=V.object({profile:V.string().regex(/^(Default|Profile [0-9]+)$/),extension_instance_id:V.string().min(1).max(1024)}).strict(),I2={ready:V.literal(!0),boot_generation:V.string().uuid(),proof_ready:V.literal(!1),result:V.literal("metadata_only")},o9=V.object({...I2,version:V.literal(2),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!1),source_bound:V.literal(!1),profiles:V.array(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),t9=V.object({...I2,version:V.literal(3),development_only:V.literal(!1),image:V.literal(!0),video:V.literal(!0),source_bound:V.literal(!1),max_seconds:V.literal(15),profiles:V.array(R0.shape.profile).min(1).max(16),extension_instance_ids:V.array(R0.shape.extension_instance_id.max(512)).min(1).max(16)}).strict().refine(($)=>new Set($.profiles).size===$.profiles.length&&$.profiles.length===$.extension_instance_ids.length),A2=V.union([o9,t9]),BB=V.union([V.object({...I2,version:V.literal(1),development_only:V.literal(!0),profile:R0.shape.profile,extension_instance_id:R0.shape.extension_instance_id,max_seconds:V.literal(15)}).strict(),A2]);import{randomUUID as E2}from"crypto";import{spawn as W$}from"child_process";import{existsSync as k2,lstatSync as K8,mkdirSync as z$,readFileSync as N$,realpathSync as S1,rmSync as H$,writeFileSync as C$}from"fs";import{dirname as D$,join as W0,relative as w$,sep as M$}from"path";var e9=["process.run.v1","process.full.v1"],$$=600000,J$=1800000,Z$=20000,q4="process.cancel.v1",g4=V.object({action:V.literal("start"),request_id:V.string().uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),cwd:V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")&&!$.startsWith("/")&&!$.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:V.enum(["host","confined"]).default("host"),timeout_ms:V.number().int().min(1000).max(J$).default($$).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),_2={device_id:V.string().uuid(),root_id:V.string().uuid()},Q$=V.discriminatedUnion("action",[g4.extend(_2),V.object({..._2,action:V.literal("inspect"),process_id:V.string().uuid(),after:V.number().int().min(0).default(0),wait_ms:V.number().int().min(0).max(Z$).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),V.object({..._2,action:V.literal("cancel"),process_id:V.string().uuid()}).strict()]),XB=V.toJSONSchema(Q$,{io:"input"}),UB=g4.extend({process_brain_fence:V.string().uuid(),process_expires_at:V.iso.datetime()}).strict(),o0=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:V.number().int().nullable(),first_cursor:V.number().int().min(0),next_cursor:V.number().int().min(0),truncated:V.boolean(),observed_at:V.iso.datetime(),output:V.array(V.object({cursor:V.number().int().min(1),stream:V.enum(["stdout","stderr"]),text:V.string().max(32768)}).strict()).max(128)}).strict().refine(($)=>{if(Buffer.byteLength(JSON.stringify($))>1e5||$.next_cursor<$.first_cursor-1)return!1;if(($.state==="starting"||$.state==="running"||$.state==="uncertain")&&$.exit_code!==null)return!1;if($.state==="exited"&&($.exit_code===null||$.exit_code<0||$.exit_code>255))return!1;if($.state==="cancelled"&&$.exit_code!==130||$.state==="expired"&&$.exit_code!==124)return!1;let Z=$.first_cursor-1;for(let Q of $.output){if(Q.cursor<=Z||Q.cursor>$.next_cursor)return!1;Z=Q.cursor}return!0});function E4($){return e9.includes($)}var FB=V.object({operation_constraints:V.record(V.string(),V.unknown())}),YB=V.object({ready:V.literal(!0),version:V.literal(1),execution_mode:V.enum(["host","confined"]),max_timeout_ms:V.number().int().min(1000).optional()});var K$=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["queued","cancelled_before_start","not_started"]),exit_code:V.null(),output:V.array(V.never()).length(0),first_cursor:V.literal(0),next_cursor:V.literal(0),truncated:V.literal(!1),cancellation_requested:V.literal(!1),reason_code:V.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),B$=V.object({...o0.shape,state:V.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:V.iso.datetime().optional(),expires_at:V.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:V.boolean(),reason_code:V.string().nullable().optional(),execution_authority:V.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:V.object({cause:V.literal("brain_generation_changed"),terminal_confirmed:V.boolean(),next_step:V.enum(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:o0.shape.state.or(V.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),WB=V.toJSONSchema(B$),zB=V.union([o0,K$.refine(($)=>$.state==="cancelled_before_start")]),P2=V.object({version:V.literal(1),process_id:V.string().uuid(),state:V.enum(["exited","cancelled","expired"]),exit_code:V.number().int().min(0).max(255),observed_at:V.iso.datetime()}).strict().refine(($)=>($.state!=="cancelled"||$.exit_code===130)&&($.state!=="expired"||$.exit_code===124)),V$=V.object({process_terminal_observation:P2}).strict();function NB($,J){let Z=V$.safeParse($);return Z.success&&Z.data.process_terminal_observation.process_id===J?Z.data:null}var S4="preview.serve.v1",f4=43200000;var wB=3,b4="preview.open.v1",x4=1,T2="gid_proxy_v1",y4="egress",R2=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,G$=V.object({version:V.literal(T2),allowed_domains:V.array(V.string().max(260).regex(R2)).max(1024)}).strict(),X$=V.custom(($)=>k4($)!==null,"invalid workspace"),U$=V.object({version:V.literal(1),request_id:V.uuid(),session_id:V.uuid(),command:V.string().min(1).max(16000).refine(($)=>!$.includes("\x00")),port:V.number().int().min(1024).max(65535),workspace:X$,egress:G$.optional()}).strict(),h4=U$.extend({expires_at:V.iso.datetime()}).strict();var F$=4,Y$=5000;function g2($,J,Z){let Q=null;try{Q=q2($)}catch{}v4({deviceRelayUrl:Q?.deviceRelayUrl??"",binding:Q?.binding??null,jobId:J,port:Q?.binding.port??0,reason:Q?Z:"binding_invalid"})}function d4($){let J=new Map;return{open(Z){let Q=(X)=>g2(Z,$.claim.operation_id,X),K;try{K=q2(Z)}catch{return Q("binding_invalid")}let{binding:B,deviceRelayUrl:G}=K,U=$.claim.owner;if(!U||B.organizationId!==U.organization_id||B.userId!==U.user_id||B.deviceId!==U.device_id||B.rootId!==$.claim.root_id||B.jobId!==$.claim.operation_id||B.fenceId!==$.claim.operation_id||B.generation!==x4||B.expiresAtMs>Math.min(Date.now()+m4.lifetimeMs+Y$,$.expiresAtMs))return Q("binding_mismatch");if(B.expiresAtMs<=Date.now())return Q("binding_expired");if(J.get(B.port)?.abort(),J.delete(B.port),J.size>=F$)return Q("preview_capacity");let Y=new AbortController;J.set(B.port,Y);let F=p4({binding:B,deniedPorts:$.deniedPorts,readCurrentJob:async()=>{if(Y.signal.aborted)return null;let X=await $.inspect();return X?{binding:B,executorLaunchId:$.executorLaunchId,job:X}:null}});u4({binding:B,deviceRelayUrl:G,port:F,signal:Y.signal}).then((X)=>X.closed,(X)=>{let W=X instanceof Error?X.message:"preview_failed";if(W!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:B.jobId,port:B.port,reason_code:W})}
26
+ `)}).finally(()=>{if(J.get(B.port)===Y)J.delete(B.port)})},dispose(){for(let Z of J.values())Z.abort();J.clear()}}}class t0 extends H{observation;constructor($){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=$}}var B8=256,f1=new Map,V8="preview.serve.v1",q0=new Map;function G8($){let J=q0.get($.operation_id);if(J){if(J.claim!==$)throw G0("process_authority_lost");return J}if(q0.size>=B8)throw G0("process_journal_capacity");let Z={claim:$,executing:!1,cancelRequested:!1,phase:"pending"};return q0.set($.operation_id,Z),Z}function l4($){return{version:1,process_id:$,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var s4=($)=>new Promise((J)=>setTimeout(J,$)),G0=($="process_outcome_uncertain")=>new H($,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function j$($=b1(),J=L$()){let Z=D$($8({},$)),Q=w$(r4($),Z),[K,...B]=Q.split(M$);return{directory:W0(J,Q,"processes"),previous:[W0(Z,"processes"),...K==="reason"?[W0(J,"ara",...B,"processes")]:[]]}}function L$(){if(process.platform!=="darwin")throw new H("process_unavailable","Managed Mac process execution is unavailable.");let $=a4();if(!$)throw new H("process_unavailable","The private per-user process directory is unavailable.");return $}async function S2($){if(!$.claim.owner||$.signal.aborted||$.expiresAtMs<=Date.now())throw G0("process_authority_lost");let J=G8($.claim);if(J.executing)throw G0("process_busy");if(J.executing=!0,J.cancelRequested)return J.phase="settling",l4($.claim.operation_id);J.phase="starting";let Z=$.journals??j$();z$(Z.directory,{recursive:!0,mode:448});let Q=i4({runtimeDirectory:S1(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter((I)=>k2(I)).map((I)=>S1(I)),root:$.root,runId:JSON.stringify([$.claim.owner,$.claim.run_id,$.claim.root_id,$.claim.operation_id]),maxScopes:B8});try{for(let I of[$.root,$.cwd])if(!J8(S1(I),Q.journalDirectory))throw new H("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch(I){throw Q.disposeSocket(),I}let K=K8(Q.journalDirectory),B=$.claim.capability===V8,G=()=>f1.set($.claim.operation_id,{path:Q.journalDirectory,ino:K.ino,dev:K.dev,anyCompletion:B}),U=Q.launchDirectory,Y=W0(U,"config.json"),F={url:"",transport:"local_job_ipc",directShell:{mode:$.mode,executable:$.shell,jobId:$.claim.operation_id},workerVersion:e0,protocolVersion:2,workerArtifactSha256:g0,workerEntrypoint:$1,targetGeneration:1,fenceId:E2(),...process.platform==="win32"?{bashExecutable:c4()}:{},workRoot:$.root,workspaceAliasPath:$.root,repoPath:$.cwd,jobEnvPath:W0(U,"unused.env"),replSocketPath:W0(U,"unused.sock"),readyPath:W0(U,"ready.json"),directTerminalReceiptPath:W0(U,"terminal.json"),launchId:E2(),expiresAtMs:$.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Q.journalDirectory,scopeId:Q.scopeId},jobControlSocketPath:Q.socketPath,...$.prefix?{bashCommandPrefix:$.prefix}:{},...$.jobsUser?{jobsUser:$.jobsUser}:{}},X;try{C$(Y,JSON.stringify(F),{mode:384});let I=Z8({configPath:Y,root:$.cwd,grantedRoot:$.root,workRoot:$.root,temporaryDirectory:U});X=$.spawnWorker?.(Y,F)??W$(I.command,I.args,{...I.options,env:$.environment,stdio:[Q8,"ignore","ignore"]})}catch(I){throw Q.disposeSocket(),I}let W=!1,z=new Promise((I,R)=>{X.once("exit",(P)=>{W=!0,I(P)}),X.once("error",(P)=>{W=!0,R(P)})});z.catch(()=>{});let N={root:$.root,runId:$.claim.run_id,scopeId:Q.scopeId,socketPath:Q.socketPath,generation:1,fenceId:F.fenceId,executorLaunchId:F.launchId,expiresAtMs:F.expiresAtMs},C=async(I)=>{let R=await o4(N,{type:"job",version:2,generation:1,id:E2(),jobId:$.claim.operation_id,...I==="start"?{action:I,input:{script:$.command,leaseExpiresAtMs:$.expiresAtMs}}:I==="inspect"?{action:I,input:{after:0}}:I==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:I,input:{}}},new AbortController().signal);if(!R.ok)throw G0(R.error);return R.job},M=!1,w=!1,D,j=()=>{M=!0,k1(X,"SIGTERM")};$.signal.addEventListener("abort",j,{once:!0});let O,A=0,b=async(I)=>{let R=[...I.output],P={version:1,process_id:$.claim.operation_id,state:I.state,exit_code:I.exitCode,first_cursor:I.firstCursor,next_cursor:I.nextCursor,truncated:I.truncated,output:R,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(P))>90000&&R.length)R.shift(),P.truncated=!0,P.first_cursor=R[0]?.cursor??P.next_cursor+1;O=o0.parse(P),await $.emit(O),A=Date.now()};try{let I=Math.min(Date.now()+1e4,$.expiresAtMs);while(!k2(F.readyPath)){if(W)throw new H("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if($.signal.aborted||Date.now()>=I)throw G0("process_start_unconfirmed");await s4(25)}let R=JSON.parse(N$(F.readyPath,"utf8"));if(R.launchId!==F.launchId||R.fenceId!==F.fenceId||R.workerArtifactSha256!==g0)throw G0();if($.signal.throwIfAborted(),J.cancelRequested)return l4($.claim.operation_id);let P;try{w=!0,P=await C("start")}catch(c){if(!(c instanceof H)||c.code!=="hands_job_result_unknown")throw c;P=await C("inspect")}if(J.phase="running",J.cancel=async()=>{await C("cancel")},B&&$.preview)J.tunnels=d4({claim:$.claim,executorLaunchId:F.launchId,expiresAtMs:$.expiresAtMs,deniedPorts:$.preview.deniedPorts,inspect:async()=>J.phase==="running"&&!W?await C("probe"):null});if(J.cancelRequested)await J.cancel(),P=await C("inspect");for(;;){if(!["starting","running"].includes(P.state))J.phase="settling",J.cancel=void 0;if(!O||O.state!==P.state||O.next_cursor!==P.nextCursor&&Date.now()-A>=5000)await b(P);if(!["starting","running"].includes(P.state))break;if($.signal.aborted||W)throw G0();await s4(1000);try{P=await C("inspect"),D=void 0}catch(c){if(!(c instanceof H)||c.code!=="hands_job_result_unknown"||$.signal.aborted||W||Date.now()-(D??=Date.now())>120000)throw c}}if(!O||O.state==="uncertain")throw G0();return O}finally{if(J.phase="settling",J.cancel=void 0,J.tunnels?.dispose(),J.tunnels=void 0,await J.cancelInFlight?.catch(()=>{}),$.signal.removeEventListener("abort",j),!W&&!M)k1(X,"SIGTERM");let I,R=await Promise.race([z.then((P)=>({code:P})),new Promise((P)=>{I=setTimeout(()=>P(null),6000)})]).finally(()=>{clearTimeout(I)});if(!R){try{k1(X,"SIGKILL")}catch{}try{await z}finally{if(W)Q.disposeSocket()}throw G0("process_cleanup_unconfirmed")}try{if((M||$.signal.aborted)&&R.code===0&&w){t4(U);let P=JSON.parse(e4(F.directTerminalReceiptPath)),c=P2.safeParse(P.observation);if(Object.keys(P).length===4&&P.launch_id===F.launchId&&P.fence_id===F.fenceId&&P.scope_id===Q.scopeId&&c.success&&c.data.process_id===$.claim.operation_id){if(B)G();throw new t0(c.data)}}}catch(P){if(P instanceof t0)throw P}finally{if(W)Q.disposeSocket()}if(R.code!==0&&!M&&w)throw G0("process_cleanup_unconfirmed");if(!M&&R.code===0&&(O&&["exited","cancelled","expired"].includes(O.state)||!w&&J.cancelRequested)||B&&R.code===0&&!w)G()}}async function uB($,J){if(J.kind===b4&&$.capability===V8){let K=q0.get($.operation_id);if(K?.claim===$&&K.tunnels)K.tunnels.open(J.payload);else g2(J.payload,$.operation_id,"server_not_running");return!0}if(J.kind!==q4||!E4($.capability)||!$.owner||J.payload.process_id!==$.operation_id)return!1;let Z=q0.get($.operation_id);if(Z&&Z.claim!==$)return!1;let Q=G8($);if(Q.cancelRequested=!0,Q.phase==="running"&&Q.cancel)Q.cancelInFlight??=Q.cancel(),await Q.cancelInFlight;return!0}function pB($,J){q0.delete($);let Z=f1.get($);if(!Z||J!=="succeeded"&&!Z.anyCompletion)return f1.delete($),!1;try{let Q=K8(Z.path);if(!Q.isDirectory()||Q.isSymbolicLink()||Q.ino!==Z.ino||Q.dev!==Z.dev||!n4(Q)||S1(Z.path)!==Z.path||k2(W0(Z.path,"owner.lock")))return!1;return H$(Z.path,{recursive:!0}),f1.delete($),!0}catch{return!1}}import{createServer as O$,request as I$}from"http";import{connect as A$,isIP as _$}from"net";var z8=120000,P$=15000;function T$($,J,Z){let Q=Y8(J).toLowerCase().replace(/\.$/,"");if(!Q||_$(Q))return!1;return $.some((K)=>{if(!R2.test(K))return!1;let B=K.lastIndexOf(":"),G=B>0?K.slice(0,B):K;if(B>0&&Number(K.slice(B+1))!==Z)return!1;return G.startsWith("*.")?Q.endsWith(G.slice(1)):Q===G})}function R$($,J){let Z=/^\[?([^\]]+?)\]?:([0-9]{1,5})$/.exec($),Q=Z?Z[1]:$,K=Z?Number(Z[2]):J;return Q&&K>=1&&K<=65535?{host:Q,port:K}:null}async function f2($,J,Z){if(!T$(Z,$,J))return null;let Q=await W8($);return Q.ok?Q.addresses[0]:null}function J1($,J){$.end(`HTTP/1.1 ${J} ${J===403?"Forbidden":"Bad Gateway"}\r
27
27
  Connection: close\r
28
28
  Content-Length: 0\r
29
29
  \r
30
- `)}function G8($,J){return new Promise((Z,Q)=>{let K=I$({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),_$);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(G)=>{clearTimeout(B),Q(G)})})}function X8($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(W8,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function U8($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function z8($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=L$((U,Y)=>{(async()=>{let F;try{F=new URL(U.url??"")}catch{F=new URL("invalid:")}let X=Number(F.port||80),W=F.protocol==="http:"?await f2(F.hostname,X,Z):null;if(!W){J(),Y.writeHead(403,{connection:"close"}).end();return}let z=O$({host:W,port:X,method:U.method,path:`${F.pathname}${F.search}`,headers:U8(U.headers,F.host),agent:!1,timeout:W8},(N)=>{Y.writeHead(N.statusCode??502,N.headers),N.pipe(Y)});z.on("timeout",()=>z.destroy()),z.on("error",()=>{if(!Y.headersSent)Y.writeHead(502);Y.end()}),Y.on("close",()=>z.destroy()),U.pipe(z)})().catch(()=>{if(!Y.headersSent)Y.writeHead(502);Y.end()})});B.on("connection",K),B.on("connect",(U,Y,F)=>{K(Y),Y.on("error",()=>Y.destroy()),(async()=>{let X=T$(U.url??"",443),W=X?await f2(X.host,X.port,Z):null;if(!X||!W){J(),J1(Y,403);return}let z=await G8(W,X.port).catch(()=>null);if(!z){J1(Y,502);return}if(Y.destroyed){z.destroy();return}K(z),Y.write(`HTTP/1.1 200 Connection Established\r
30
+ `)}function X8($,J){return new Promise((Z,Q)=>{let K=A$({host:$,port:J}),B=setTimeout(()=>K.destroy(Error("connect_timeout")),P$);K.once("connect",()=>{clearTimeout(B),Z(K)}),K.once("error",(G)=>{clearTimeout(B),Q(G)})})}function U8($,J,Z){for(let Q of[$,J])Q.on("error",()=>{$.destroy(),J.destroy()}),Q.on("close",()=>{$.destroy(),J.destroy()});if(J.setTimeout(z8,()=>J.destroy()),Z.length)J.write(Z);$.pipe(J).pipe($)}function F8($,J){let Z={...$,host:J};return delete Z["proxy-authorization"],delete Z["proxy-connection"],Z}async function N8($,J=()=>{}){let Z=[...$],Q=new Set,K=(U)=>{Q.add(U),U.once("close",()=>Q.delete(U))},B=O$((U,Y)=>{(async()=>{let F;try{F=new URL(U.url??"")}catch{F=new URL("invalid:")}let X=Number(F.port||80),W=F.protocol==="http:"?await f2(F.hostname,X,Z):null;if(!W){J(),Y.writeHead(403,{connection:"close"}).end();return}let z=I$({host:W,port:X,method:U.method,path:`${F.pathname}${F.search}`,headers:F8(U.headers,F.host),agent:!1,timeout:z8},(N)=>{Y.writeHead(N.statusCode??502,N.headers),N.pipe(Y)});z.on("timeout",()=>z.destroy()),z.on("error",()=>{if(!Y.headersSent)Y.writeHead(502);Y.end()}),Y.on("close",()=>z.destroy()),U.pipe(z)})().catch(()=>{if(!Y.headersSent)Y.writeHead(502);Y.end()})});B.on("connection",K),B.on("connect",(U,Y,F)=>{K(Y),Y.on("error",()=>Y.destroy()),(async()=>{let X=R$(U.url??"",443),W=X?await f2(X.host,X.port,Z):null;if(!X||!W){J(),J1(Y,403);return}let z=await X8(W,X.port).catch(()=>null);if(!z){J1(Y,502);return}if(Y.destroyed){z.destroy();return}K(z),Y.write(`HTTP/1.1 200 Connection Established\r
31
31
  \r
32
- `),X8(Y,z,F)})().catch(()=>Y.destroy())}),B.on("upgrade",(U,Y,F)=>{K(Y),Y.on("error",()=>Y.destroy()),(async()=>{let X;try{X=new URL(U.url??"")}catch{J1(Y,403);return}let W=Number(X.port||80),z=["http:","ws:"].includes(X.protocol)?await f2(X.hostname,W,Z):null;if(!z){J(),J1(Y,403);return}let N=await G8(z,W).catch(()=>null);if(!N){J1(Y,502);return}K(N);let C=U8(U.headers,X.host),M=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[w,D]of Object.entries(C))for(let j of Array.isArray(D)?D:D===void 0?[]:[D])M.push(`${w}: ${j}`);N.write(`${M.join(`\r
32
+ `),U8(Y,z,F)})().catch(()=>Y.destroy())}),B.on("upgrade",(U,Y,F)=>{K(Y),Y.on("error",()=>Y.destroy()),(async()=>{let X;try{X=new URL(U.url??"")}catch{J1(Y,403);return}let W=Number(X.port||80),z=["http:","ws:"].includes(X.protocol)?await f2(X.hostname,W,Z):null;if(!z){J(),J1(Y,403);return}let N=await X8(z,W).catch(()=>null);if(!N){J1(Y,502);return}K(N);let C=F8(U.headers,X.host),M=[`${U.method} ${X.pathname}${X.search} HTTP/1.1`];for(let[w,D]of Object.entries(C))for(let j of Array.isArray(D)?D:D===void 0?[]:[D])M.push(`${w}: ${j}`);N.write(`${M.join(`\r
33
33
  `)}\r
34
34
  \r
35
- `),X8(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 E$}from"crypto";import{closeSync as p1,constants as J0,fchownSync as k$,fstatSync as L0,fsyncSync as S$,linkSync as _8,lstatSync as v2,mkdirSync as P8,openSync as v1,readSync as g8,realpathSync as u2,unlinkSync as T8,writeSync as f$}from"fs";import{isAbsolute as b$,join as x$,relative as y$,sep as h$}from"path";import{platform as p2}from"os";import{getSystemErrorName as m$}from"util";var N8={type:"string",format:"uuid"},w8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,x1={type:"string",minLength:1,maxLength:4096,pattern:w8},b2=V.string().min(1).max(4096).regex(new RegExp(w8)),y1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},h1={device_id:N8,root_id:N8,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},rB={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,H8=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,M8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${H8}(?:/${H8})*(?![\s\S])`,j8=new RegExp(M8);function L8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&j8.test($)}var x2=V.string().min(1).max(4096).regex(j8),y2={...x1,pattern:M8},O8=V.string().regex(/^[a-f0-9]{64}$/),I8=V.object({kind:V.literal("workspace"),path:x2}).strict(),R$=V.discriminatedUnion("kind",[I8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:O8}).strict()]),m1=1,Q1="cloud_workspace_id",h2="cloud_workspace",m2=1,q$=V.discriminatedUnion("kind",[I8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(z0),sha256:O8}).strict()]),A8=V.object({source_version:V.literal(m1),source:q$,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(),aB=V.object({ready:V.literal(!0),cloud_source_version:V.literal(m1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var C8=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(),D8={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},g$={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}]},iB=V.union([C8,C8.omit({source_path:!0}).extend({source:R$}).strict()]),oB={...D8,required:["device_id","root_id","destination_path"],properties:{...D8.properties,source:g$},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 v$($,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 u$($){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 p$(){if(p2()==="win32"){let F=new Map,X,W=-1,z=()=>Object.assign(Error("transfer_path_unsafe"),{code:"ELOOP"}),N=(D)=>{let j=y$(X,D);return j===""||j!==".."&&!j.startsWith(`..${h$}`)&&!b$(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 x$(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),P8(O)},link:(D,j,O)=>{let A=w(D,j),b=w(D,O);M(D),_8(A,b)},unlink:(D,j)=>T8(w(D,j)),closeDirectory:(D)=>{F.delete(D)},inherit:()=>{},close:()=>{}}}let $={root:(F)=>v1(F,d2),closeDirectory:p1,inherit:d$};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)=>P8(`/proc/self/fd/${F}/${X}`,{mode:448}),link:(F,X,W)=>_8(`/proc/self/fd/${F}/${X}`,`/proc/self/fd/${F}/${W}`),unlink:(F,X)=>T8(`/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=m$(-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 d$($,J){let Z=L0($),Q=L0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)k$(J,Z.uid,Z.gid)}function l$($,J,Z,Q){if(!L8(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 R8($,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=g8($,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=u$($.payload.url),Z=await p$(),Q,K,B;try{if(Q=l$(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=g8(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=R8(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=R8(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-${E$()}`,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+=f$(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 S$(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 v$(J,$.signal,$.direction)}}import{spawn as c$}from"child_process";import{mkdtempSync as n$,rmSync as r$,writeFileSync as a$}from"fs";import{constants as i$,platform as o$,tmpdir as t$}from"os";import{join as f8}from"path";import{gunzipSync as s$,gzipSync as UV}from"zlib";var k8=900000,YV=k8+60000,K1=49152,E8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),S8=V.object({version:V.literal(1),script_gzip:E8(163840),stdin_gzip:E8(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(k8)}).strict(),c2=V.string().max(K1+256),WV=V.object({exit_code:V.number().int().min(0).max(255),stdout:c2,stderr:c2,combined:c2.optional()}).strict();function n2($){return s$(Buffer.from($,"base64")).toString("utf8")}var e$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",$J=["RUSTUP_HOME","TZ","LC_ALL"],JJ=2000,ZJ=100;function a2(){return o$()==="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?`
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 b8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=S8.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=n$(f8(t$(),"reason-workspace-setup-"));try{let U=f8(G,"setup.sh");a$(U,K,{mode:384});let Y={PATH:e$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of $J)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=c$("/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"),JJ)},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,ZJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(i$.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{r$(G,{recursive:!0,force:!0})}}import{chmodSync as QJ,mkdtempSync as KJ,realpathSync as m8,rmSync as BJ}from"fs";import{tmpdir as VJ}from"os";import{dirname as GJ,join as i2,sep as XJ}from"path";function o2($){return h8($,y8($)!==null).repoPath}function v8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>GJ(x8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=m8(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(`${$}${XJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function u8($){$.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=KJ(i2(VJ(),`reason-cloud-copy-${process.pid}-`));try{QJ(Z,448);let Q=m8(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{BJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as V9,existsSync as F0,fstatSync as G9,ftruncateSync as dQ,lstatSync as p3,mkdirSync as lQ,mkdtempSync as sQ,openSync as X9,readSync as cQ,realpathSync as X0,rmSync as nQ,statSync as w1,writeSync as rQ}from"fs";import{homedir as H1,platform as E,tmpdir as aQ}from"os";import{dirname as C1,isAbsolute as iQ,join as U9,relative as d3,resolve as oQ,sep as tQ}from"path";import{spawn as eQ}from"child_process";import{createHash as zJ,randomBytes as NJ}from"crypto";var t2=30000,UJ=1800000,FJ=5000,s1=30000,YJ=n1+15000,p8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,WJ=[/^\/app\/local-runtime\/operations\/claim$/,p8];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(WJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},YJ);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(FJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(UJ,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(!p8.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 hV($,J={}){let Z=HJ($),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 HJ($){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 CJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function DJ($){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 wJ($,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 MJ($,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 mV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function d8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function l8($){return zJ("sha256").update($??"").digest("hex")}function jJ($){return a8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function s8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var LJ=20000,OJ=1e4,c8=[2000,4000],IJ=30000,AJ=15000;function n8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class _J{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}=i8(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??c8;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,...n8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return o8(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>=LJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,c8[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)()>=OJ?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=l8(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??(()=>NJ(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(jJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!r8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,l8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&d8(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??MJ,Y=this.sessionFor($,J.device),F=Math.max(IJ,(J.holdMs??0)+AJ),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,...n8(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&&CJ(N.status),w=DJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:wJ(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 t8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return e8(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return $5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return J5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Z5(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 Q5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});B5(Q)}async localSubscription($,J,Z){return K5(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(!s8(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 V5(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 G5(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)||!s8(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 X5(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(d8(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 F5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-bm94e9r0.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 U5(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 PJ=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(PJ.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 TJ,constants as RJ,existsSync as qJ,statSync as gJ}from"fs";import{basename as EJ,isAbsolute as kJ}from"path";var G1=["-lic"],Y5="/bin/zsh",SJ=new Set(["zsh","bash"]),z5=20000,Z3=60000,fJ=65536,bJ=64,xJ=8192,yJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),hJ=["DYLD_","LD_"];function mJ($){let J=$.toUpperCase();return yJ.has(J)||hJ.some((Z)=>J.startsWith(Z))}function N5($=process.env){return!0}function vJ($){if(!kJ($)||$.includes("\x00"))return!1;if(!SJ.has(EJ($)))return!1;try{if(!gJ($).isFile())return!1;return TJ($,RJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return W5()??Y5;let J=$.SHELL?.trim();if(J&&vJ(J))return J;return Y5}function Q3($=process.env){return N5($)&&qJ(S0($))}function K3($=process.env){if(!N5($))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")>fJ)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>bJ)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")>xJ)throw new H("invalid_payload","env entry is invalid or too large.");if(mJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function H5($){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 C5($=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 uJ,readdir as pJ,readlink as dJ,realpath as lJ}from"fs/promises";import{basename as sJ,relative as cJ,sep as nJ}from"path";var O0="/proc",rJ=250,D5=500,aJ=50,iJ=250,oJ=1024,w5=4096,tJ=1,eJ=3,M5=9,$Z="0A",JZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>pJ($),readLink:($)=>dJ($),readTextFile:($)=>uJ($,"utf8"),realPath:($)=>lJ($)};function L5($,J){return J===$||J.startsWith(`${$}${nJ}`)}function ZZ($,J){return cJ($,J)||"."}async function O5($){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 I5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,w5).split(`
38
- `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,w5).split("\x00",1)[0]?.trim();return Q?sJ(Q):null}catch{return null}}async function A5($,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 _5($,J=G3){let Z=[];for(let Q of await O5(J)){if(Z.length>=rJ)break;let K=await A5(Q,J);if(!K||!L5($,K))continue;Z.push({pid:Q,command:await I5(Q,J),cwd:ZZ($,K)})}return{processes:Z}}function j5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function QZ($){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 KZ($,J){if(/^[0-9A-Fa-f]{8}$/.test($)){let Z=j5($);if(Z.every((Q)=>Q===0))return`*:${J}`;return`${Z.join(".")}:${J}`}if(/^[0-9A-Fa-f]{32}$/.test($)){let Z=[];for(let Q=0;Q<4;Q+=1)Z.push(...j5($.slice(Q*8,Q*8+8)));if(Z.every((Q)=>Q===0))return`*:${J}`;return`[${QZ(Z)}]:${J}`}return null}function BZ($,J){let Z=[];for(let Q of $.split(`
39
- `).slice(1)){if(Z.length>=J)break;let K=Q.trim().split(/\s+/);if(K.length<=M5)continue;if(K[eJ]?.toUpperCase()!==$Z)continue;let B=K[tJ]??"",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=KZ(B.slice(0,G),U),F=K[M5];if(!Y||!F||!/^[0-9]+$/.test(F))continue;Z.push({inode:F,port:U,address:Y})}return Z}async function VZ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=D5)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...BZ(Q,D5-J.length))}return J}async function GZ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await O5(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,oJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${B}`)}catch{continue}let U=G.match(JZ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function P5($,J=G3){let Z=await VZ(J),Q=await GZ(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,aJ),G=await Promise.all(B.map(async(X)=>[X,await A5(X,J)])),U=new Map(G),Y=K.filter((X)=>{let W=U.get(X.pid);return Boolean(W&&L5($,W))}),F=new Map(await Promise.all([...new Set(Y.map((X)=>X.pid))].map(async(X)=>[X,await I5(X,J)])));return{ports:Y.slice(0,iJ).map((X)=>({pid:X.pid,command:F.get(X.pid)??null,address:X.address}))}}import{posix as U3}from"path";var i1=200,XZ=250,UZ=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 T5="/System/Volumes/Data",FZ=["/tmp","/var","/etc"];function F3($){let J=U3.normalize($);if(J.startsWith(`${T5}/`))J=J.slice(T5.length);return FZ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function R5($){return $&&U3.isAbsolute($)?F3($):null}async function q5($,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:R5(B.names[0])})}return Z}async function g5($,J){let Z=F3($),Q=(await o1(J,["-d","cwd","-Fpn"])).filter((B)=>{let G=R5(B.names[0]);return G!==null&&X3(Z,G)}).map((B)=>B.pid).slice(0,XZ),K=await q5(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 E5($,J){let Z=F3($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],K=await o1(J,Q),B=await q5(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,UZ)}}import{join as IZ}from"path";import{spawn as DZ}from"child_process";import{randomUUID as wZ}from"crypto";import{chmodSync as f5,lstatSync as b5,mkdirSync as MZ,readdirSync as jZ,statSync as LZ,unlinkSync as OZ}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 k5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function WZ($){if(!X1($)||$.version!==1)return I0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new k5;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 NZ=["organizationId","userId","sessionId","runId"],HZ=[...NZ,"prUrl","headSha","skillDigest","evidenceKind"],BG=[...HZ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var CZ={"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 S5($){return CZ[$].directory}var x5=10485760;function y5($={}){let J=$.directory??S5("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");MZ(J,{recursive:!0,mode:457});let B=b5(J);if(!B.isDirectory()||B.isSymbolicLink()||B.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");f5(J,457);let G=jZ(J).filter((w)=>/^[a-f0-9-]{36}\.webm$/.test(w)).map((w)=>({name:w,time:LZ(W3(J,w)).mtimeMs})).sort((w,D)=>D.time-w.time);for(let w of G.slice(9))OZ(W3(J,w.name));let U=W3(J,`${wZ()}.webm`),Y=["-f","x11grab","-framerate","12","-i",$.display??":99"],F=($.spawn??DZ)($.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(x5),"-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=b5(U);if(!z||!O.isFile()||O.isSymbolicLink()||O.uid!==process.getuid?.()||O.size<128||O.size>x5+65536)throw Error();f5(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 v5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??h5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let K=IZ($.runtimeDirectory,"recordings"),B=null;return{async start(G){let U=await(J.desktop??m5)();return B??=y5({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 dZ,randomUUID as lZ}from"crypto";import{existsSync as Q0,mkdirSync as P3,mkdtempSync as k3,readdirSync as G2,readFileSync as S3,renameSync as sZ,rmSync as Y1,statSync as Q2,writeFileSync as cZ}from"fs";import{homedir as f3,tmpdir as X6}from"os";import{basename as U6,dirname as T3,join as k,relative as F6,resolve as R3,sep as Y6}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")),u5=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"],AZ=V.enum(["tree","screenshot","both","none"]),_Z=V.object({...N3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),D0={observe:AZ.optional(),wait_for:_Z.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:u5.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:u5}).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()]),p5=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(),AG=V.object({text:V.string(),error:V.string().optional(),device:p5.optional(),devices:V.array(p5).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 _G=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."}},l5=C3.options.map(($)=>$.shape).filter(($)=>$.action.value!=="chrome"),PZ={tap:[{required:["x","y"]},{required:["id"]},{required:["label"]}],launch:[{required:["app_path"],without:["bundle_id"]},{required:["bundle_id"],without:["app_path"]}]},d5=new Set;function TZ($,J){let{description:Z,...Q}=$==="steps"&&J==="steps"?{...$2.steps,minItems:1}:$2[$];if(Z===void 0||d5.has($))return Q;return d5.add($),{...Q,description:Z}}var RZ=l5.flatMap(($)=>{let J=$.action.value,Z=Object.keys($).filter((K)=>Object.hasOwn($2,K)),Q=Z.filter((K)=>!$[K].safeParse(void 0).success);return(PZ[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,TZ(B,J)])]),required:["action",...Q,...K.required],additionalProperties:!1}))}),qZ={type:"object",properties:{action:{type:"string",enum:l5.map(($)=>$.action.value)},...$2},required:["action"],additionalProperties:!1},PG={...qZ,anyOf:RZ};import{spawn as j3}from"child_process";import{createHash as EZ}from"crypto";import{existsSync as w3,mkdirSync as J2,mkdtempSync as kZ,readdirSync as s5,readFileSync as c5,renameSync as SZ,rmSync as n5,symlinkSync as M3,writeFileSync as U1}from"fs";import{homedir as fZ}from"os";import{dirname as o5,join as x}from"path";import{createInterface as bZ}from"readline";var D3=`// Reason's simulator host: one warm process per booted iOS Simulator.
37
+ `:"")+K.toString("utf8")}}}async function x8($,J){if(!a2())throw new H("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=f8.safeParse($);if(!Z.success)throw new H("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,K,B;try{K=n2(Q.script_gzip),B=n2(Q.stdin_gzip)}catch{throw new H("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=r$(b8(e$(),"reason-workspace-setup-"));try{let U=b8(G,"setup.sh");i$(U,K,{mode:384});let Y={PATH:$J,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let A of JJ)if(process.env[A])Y[A]=process.env[A];Object.assign(Y,Q.env);let F=n$("/bin/bash",[U],{cwd:Q.cwd,env:Y,detached:!0,stdio:["pipe","pipe","pipe"]}),X=r2(K1),W=r2(K1),z=r2(K1);F.stdout.on("data",(A)=>{X.push(A),z.push(A)}),F.stderr.on("data",(A)=>{W.push(A),z.push(A)}),F.stdin.on("error",()=>{}),F.stdin.end(B);let N=(A)=>{try{if(F.pid)process.kill(-F.pid,A)}catch{}},C=!1,M,w=()=>{N("SIGTERM"),M??=setTimeout(()=>N("SIGKILL"),ZJ)},D=setTimeout(()=>{C=!0,w()},Q.timeout_ms);J.addEventListener("abort",w,{once:!0});let j=await new Promise((A,b)=>{F.once("error",()=>b(new H("workspace_setup_start_failed","The workspace setup did not start."))),F.once("exit",(I,R)=>A({code:I,signal:R}))}).finally(()=>{clearTimeout(D),clearTimeout(M),J.removeEventListener("abort",w)});await new Promise((A)=>{let b=setTimeout(A,QJ);F.once("close",()=>{clearTimeout(b),A()})}),F.stdout.destroy(),F.stderr.destroy(),J.throwIfAborted();let O=C?124:j.signal?128+(o$.signals[j.signal]??0):j.code??1;return{exit_code:Math.min(255,O),stdout:X.text(),stderr:W.text(),...O!==0?{combined:z.text()}:{}}}finally{a$(G,{recursive:!0,force:!0})}}import{chmodSync as KJ,mkdtempSync as BJ,realpathSync as v8,rmSync as VJ}from"fs";import{tmpdir as GJ}from"os";import{dirname as XJ,join as i2,sep as UJ}from"path";function o2($){return m8($,h8($)!==null).repoPath}function u8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[B1,void 0].map((K)=>XJ(y8({kind:"managed",workspaceId:J,...K?{layout:K}:{}})))}catch{throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let K of Z)try{Q=v8(i2($,K));break}catch{}if(Q===void 0)throw new H("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${UJ}`))throw new H("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function p8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=o2($.runtimeRoot);if(k0(Q)||k0(i2(Q,J.path)))throw new H("protected_path","Credential and secret paths are unavailable to local tasks.");return E0({direction:"export",root:Q,path:J.path,payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl})}let Z=BJ(i2(GJ(),`reason-cloud-copy-${process.pid}-`));try{KJ(Z,448);let Q=v8(Z);await E0({direction:"import",root:Q,path:"source",payload:{url:J.download_url,size_bytes:J.size_bytes,sha256:J.sha256},signal:$.signal,fetchImpl:$.fetchImpl});let K=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(K.size_bytes!==J.size_bytes||K.sha256!==J.sha256)throw new H("transfer_source_changed","The verified attachment changed before export.");return K}finally{VJ(Z,{recursive:!0,force:!0})}}import{constants as K0}from"fs";import{closeSync as G9,existsSync as F0,fstatSync as X9,ftruncateSync as lQ,lstatSync as p3,mkdirSync as sQ,mkdtempSync as cQ,openSync as U9,readSync as nQ,realpathSync as X0,rmSync as rQ,statSync as w1,writeSync as aQ}from"fs";import{homedir as H1,platform as E,tmpdir as iQ}from"os";import{dirname as C1,isAbsolute as oQ,join as F9,relative as d3,resolve as tQ,sep as eQ}from"path";import{spawn as $K}from"child_process";import{createHash as NJ,randomBytes as HJ}from"crypto";var t2=30000,FJ=1800000,YJ=5000,s1=30000,WJ=n1+15000,d8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,zJ=[/^\/app\/local-runtime\/operations\/claim$/,d8];class e2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let K=String(++this.nextId),B=new Promise((Y)=>Q.pending.set(K,{path:$,resolve:Y}));if(!this.send(Q,{t:"req",id:K,path:$,body:J}))return Q.pending.delete(K),null;let G;if(zJ.some((Y)=>Y.test($)))G=setTimeout(()=>{if(Q.pending.has(K))this.drop(Q)},WJ);else{let Y=()=>{if(!Q.pending.has(K))return;let F=this.now()-Q.lastFrameAt;if(F>=s1)this.drop(Q);else G=setTimeout(Y,s1-F)};G=setTimeout(Y,s1)}if(B.finally(()=>clearTimeout(G)),!Z)return await B;let U=new Promise((Y,F)=>{let X=()=>{if(Q.pending.delete(K),clearTimeout(G),this.send(Q,{t:"abort",id:K}),this.now()-Q.lastFrameAt>s1)this.drop(Q);F(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),B.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([B,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(YJ));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(FJ,t2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(c1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+t2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(K)=>this.receive(Q,K.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[K,B]of Q.pending){if(!d8.test(B.path))continue;Q.pending.delete(K),this.send(Q,{t:"abort",id:K}),B.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(t2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var J3=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function vV($,J={}){let Z=CJ($),Q=J.rootPathsSupported===!0?I1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((K)=>/^[a-f0-9]{64}$/.test(K))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function CJ($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let K=$.operation_constraints?.[Q];if(!K||typeof K!=="object"||Array.isArray(K))continue;if(!("ready"in K)||typeof K.ready!=="boolean")continue;let B={};for(let[G,U]of Object.entries(K).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))B[G]=U}if(Object.keys(B).length)Z[Q]=B}return Z}class N0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class r1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function DJ($){return $===408||$===429||$===500||$===502||$===503||$===504}function wJ($){if($ instanceof N0)return!1;if($ instanceof r1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function MJ($,J,Z=500){if(J instanceof N0&&J.retryAfter){let B=parseFloat(J.retryAfter);if(Number.isFinite(B)&&B>0)return Math.min(B*1000,1e4)}let Q=Z*2**$,K=Math.floor(Math.random()*200);return Math.min(Q+K,5000)}async function jJ($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let K=()=>{clearTimeout(B),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},B=setTimeout(()=>{J?.removeEventListener("abort",K),Z()},$);J?.addEventListener("abort",K,{once:!0})})}function uV($){return $ instanceof N0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function l8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function s8($){return NJ("sha256").update($??"").digest("hex")}function LJ($){return i8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function c8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var OJ=20000,IJ=1e4,n8=[2000,4000],AJ=30000,_J=15000;function r8($){return $?{keepalive:!1}:{}}class $3 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class PJ{fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let K=new URL($);if(K.protocol!=="https:"&&K.hostname!=="127.0.0.1"&&K.hostname!=="localhost"&&K.hostname!=="[::1]"&&K.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=K.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=o8(J,$.status),K=$.headers?.get?.("retry-after")??null;throw new N0($.status,Z,Q,K)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??n8;for(let K of Q)try{return await this.challengeAttempt($,J,K,Z.fresh)}catch(B){if(J?.aborted||!(B instanceof $3))throw B;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let K=JSON.stringify({device_id:$}),B=Z===null?null:new AbortController,G=B&&Z!==null?setTimeout(()=>B.abort(new $3(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${s.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:K,...r8(Q),signal:B?J?AbortSignal.any([J,B.signal]):B.signal:J});return t8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&B?.signal.aborted)throw B.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=OJ?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,n8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,K=!1,B,G){let U=B&&Date.parse(B.expires_at)-(this.proofOptions.now??Date.now)()>=IJ?B:null,Y=!U&&K?await this.takeSpareChallenge(Z.deviceId):null,F=U??Y??await this.challenge(Z.deviceId,Q,G);if(K)this.refillSpareChallenge(Z.deviceId);let X=s8(J),W=this.signProof("POST",$,F.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":W.timestamp,"x-device-nonce":W.nonce,"x-device-challenge":F.challenge,"x-device-body-sha256":X,"x-device-signature":W.signature}}signProof($,J,Z,Q){let K=String(Math.trunc((this.proofOptions.now??Date.now)())),B=(this.proofOptions.nonce??(()=>HJ(24)))();if(B.byteLength<16||B.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(B).toString("base64url"),U=this.proofStore.sign(LJ({method:$,route:J,timestamp:K,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:K,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!a8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new e2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",c1,Q,s8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&l8(J.body)>C0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let B=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??jJ,Y=this.sessionFor($,J.device),F=Math.max(AJ,(J.holdMs??0)+_J),X={fresh:!1},W;for(let z=0;z<G;z+=1)try{let N=await Y?.request($.path,J.sessionBody===void 0?B??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let C=new AbortController,M=setTimeout(()=>C.abort(new r1(F)),F),w=J.signal?AbortSignal.any([J.signal,C.signal]):C.signal;try{let D=J.device===void 0?{}:await this.proofHeaders($.path,B,J.device,w,J.useSpareChallenge===!0&&z===0,z===0?J.issuedChallenge:void 0,X),j=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...D,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:B,...r8(X.fresh),signal:w});return await this.parseResponse(j)}catch(D){if(!J.signal?.aborted&&C.signal.aborted)throw C.signal.reason;throw D}finally{clearTimeout(M)}}catch(N){if(W=N,N instanceof r1)X.fresh=!0;if(J.signal?.aborted)throw N;let C=J.device!==void 0&&N instanceof N0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),M=N instanceof N0&&DJ(N.status),w=wJ(N),D=J.transientRetryOwner!=="caller"&&(M||w);if((C||D)&&z+1<G){let j=C?0:MJ(z,N,this.proofOptions.retryBaseDelayMs??500);if(j>0)await U(j,J.signal);continue}if(C&&z+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw W??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(s.register,{authorization:$,body:J,signal:Z});return e8(Q)}async enroll($,J,Z,Q){let K=await this.request(s.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return $5(K)}async heartbeat($,J,Z,Q){let K=await this.request(s.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return J5(K)}async syncRoots($,J,Z){let Q=await this.request(s.rootsSync,{device:$,body:{roots:J},signal:Z});return Z5(Q)}async identity($,J){let Z=await this.request(s.identity,{device:$,signal:J});return Q5(Z)}async disconnect($,J,Z,Q=[]){let K=await this.request(s.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return K5(K)}async deviceLifecycle($,J,Z){let Q=await this.request(s.lifecycle,{device:$,body:J,signal:Z});V5(Q)}async localSubscription($,J,Z){return B5(await this.request(s.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(s.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((K)=>{let B=K;return typeof B?.id==="string"?[{id:B.id,...typeof B.name==="string"&&B.name.trim()?{name:B.name.trim()}:{},blocked:B.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(s.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(s.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((K)=>{if(K instanceof N0&&K.status===404)return null;throw K});if(Q===null)return null;if(!c8(Q)||!Array.isArray(Q.live)||!Q.live.every((K)=>typeof K==="string"&&J.includes(K)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),K=this.sessionCadence($)?.claimWaitMs,B=await this.request(s.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...K===void 0?{}:{sessionBody:Q(Math.min(K,n1))},signal:J.signal});if(B===null)return null;return G5(B,J3)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(s.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),K=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,B;try{B=await Q(K)}catch(G){if(!K||!(G instanceof N0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;B=await Q(!1)}return X5(B)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((K)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(K.kind)||!c8(K.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(s.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return U5(Q)}async completeOperation($,J,Z,Q){let K={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(l8(K)>C0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let B=await this.request(s.operationComplete.forOperation(J.operation_id),{device:$,body:K,signal:Q});return Y5(B)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-3g0rc3wp.js");return Q.parse(await this.request(s.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let K=await this.request(s.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return F5(K)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(s.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var TJ=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),V1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function a1($,J){if(TJ.has($))return!1;if(V1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||V1.has($)))return!1;return!0}import{accessSync as RJ,constants as qJ,existsSync as gJ,statSync as EJ}from"fs";import{basename as kJ,isAbsolute as SJ}from"path";var G1=["-lic"],W5="/bin/zsh",fJ=new Set(["zsh","bash"]),N5=20000,Z3=60000,bJ=65536,xJ=64,yJ=8192,hJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),mJ=["DYLD_","LD_"];function vJ($){let J=$.toUpperCase();return hJ.has(J)||mJ.some((Z)=>J.startsWith(Z))}function H5($=process.env){return!0}function uJ($){if(!SJ($)||$.includes("\x00"))return!1;if(!fJ.has(kJ($)))return!1;try{if(!EJ($).isFile())return!1;return RJ($,qJ.X_OK),!0}catch{return!1}}function S0($=process.env){if(process.platform==="win32")return z5()??W5;let J=$.SHELL?.trim();if(J&&uJ(J))return J;return W5}function Q3($=process.env){return H5($)&&gJ(S0($))}function K3($=process.env){if(!H5($))throw new H("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function B3($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>bJ)throw new H("invalid_payload","command is missing or too large.");return $}function V3($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new H("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>xJ)throw new H("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[K,B]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(K)||typeof B!=="string"||B.includes("\x00")||Buffer.byteLength(B,"utf8")>yJ)throw new H("invalid_payload","env entry is invalid or too large.");if(vJ(K)){Q.push(K);continue}Z[K]=B}return{forwarded:Z,ignored:Q}}async function C5($){let J=$.processEnv??process.env;if(K3(J),$.signal.aborted)throw new H("cancelled","Operation was cancelled.");let Z=B3($.command),Q=S0(J),{forwarded:K,ignored:B}=V3($.requestEnv),G=await $.spawn(Q,[...G1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...K}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...G1],login:!0,interactive:!0,sandbox:"none",ignored_env:B}}function D5($=process.env){return{transport:"shell",shell:`${S0($)} ${G1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:Z3}}import{readFile as pJ,readdir as dJ,readlink as lJ,realpath as sJ}from"fs/promises";import{basename as cJ,relative as nJ,sep as rJ}from"path";var O0="/proc",aJ=250,w5=500,iJ=50,oJ=250,tJ=1024,M5=4096,eJ=1,$Z=3,j5=9,JZ="0A",ZZ=/^socket:\[(\d+)\]$/,G3={readDirectory:($)=>dJ($),readLink:($)=>lJ($),readTextFile:($)=>pJ($,"utf8"),realPath:($)=>sJ($)};function O5($,J){return J===$||J.startsWith(`${$}${rJ}`)}function QZ($,J){return nJ($,J)||"."}async function I5($){let J;try{J=await $.readDirectory(O0)}catch{return[]}return J.filter((Z)=>/^[0-9]+$/.test(Z)).map((Z)=>Number(Z)).filter((Z)=>Number.isSafeInteger(Z)&&Z>0).sort((Z,Q)=>Z-Q)}async function A5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,M5).split(`
38
+ `,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
+ `).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
  //
41
41
  // Built on the Mac on first use (cli/simulator-host.ts) against the MIT
42
42
  // FBSimulatorControl frameworks that the pinned AXe ships, so loading
@@ -495,33 +495,33 @@ case "stream":
495
495
  default:
496
496
  fail("usage: simulator-host serve|stream <udid> ...")
497
497
  }
498
- `;var r5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",xZ=180000,yZ=15000,hZ=30000,mZ=600000,vZ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
498
+ `;var a5=process.arch==="arm64"?"arm64-apple-macos":"x86_64-apple-macos",yZ=180000,hZ=15000,mZ=30000,vZ=600000,uZ=["SimDevice","SimDeviceSet","SimDeviceType","SimRuntime"].map(($)=>`@interface ${$} : NSObject
499
499
  @end
500
- `).join("");function a5($,J,Z){return new Promise((Q)=>{let K=j3($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),B="";K.stdout.on("data",(G)=>{B+=G}),K.stderr.on("data",(G)=>{B+=G}),K.once("error",(G)=>Q({code:-1,output:String(G)})),K.once("close",(G)=>Q({code:G??-1,output:B}))})}var i5=new Map;function L3($){let J=x(o5($),"Frameworks"),Z=i5.get(J);if(!Z)i5.set(J,Z=uZ(J));return Z}async function uZ($){if(process.platform!=="darwin"||!w3(x($,"FBSimulatorControl.framework")))return null;let J=await a5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=EZ("sha256").update(D3).update(J.output).update($).digest("hex").slice(0,16),Q=x(fZ(),".local","share","reason","simulator","host"),K=x(Q,Z,"simulator-host");if(w3(K))return K;J2(Q,{recursive:!0,mode:448});let B=kZ(x(Q,".staging-"));try{let G=x(B,"Frameworks"),U=x(G,"FBSimulatorControl.framework"),Y=x(U,"Modules","FBSimulatorControl.swiftmodule");J2(Y,{recursive:!0});for(let M of s5($))if(M!=="FBSimulatorControl.framework")M3(x($,M),x(G,M));let F=x($,"FBSimulatorControl.framework");M3(x(F,"FBSimulatorControl"),x(U,"FBSimulatorControl")),M3(x(F,"Headers"),x(U,"Headers")),U1(x(U,"Modules","module.modulemap"),c5(x(F,"Modules","module.modulemap")));let X=c5(x(F,"Modules","FBSimulatorControl.swiftmodule",`${r5}.swiftinterface`),"utf8");U1(x(Y,`${r5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let W=x(B,"include","CoreSimulator");J2(W,{recursive:!0}),U1(x(W,"module.modulemap"),`module CoreSimulator {
500
+ `).join("");function i5($,J,Z){return new Promise((Q)=>{let K=j3($,J,{stdio:["ignore","pipe","pipe"],timeout:Z}),B="";K.stdout.on("data",(G)=>{B+=G}),K.stderr.on("data",(G)=>{B+=G}),K.once("error",(G)=>Q({code:-1,output:String(G)})),K.once("close",(G)=>Q({code:G??-1,output:B}))})}var o5=new Map;function L3($){let J=x(t5($),"Frameworks"),Z=o5.get(J);if(!Z)o5.set(J,Z=pZ(J));return Z}async function pZ($){if(process.platform!=="darwin"||!w3(x($,"FBSimulatorControl.framework")))return null;let J=await i5("xcrun",["swiftc","--version"],30000);if(J.code!==0)return null;let Z=kZ("sha256").update(D3).update(J.output).update($).digest("hex").slice(0,16),Q=x(bZ(),".local","share","reason","simulator","host"),K=x(Q,Z,"simulator-host");if(w3(K))return K;J2(Q,{recursive:!0,mode:448});let B=SZ(x(Q,".staging-"));try{let G=x(B,"Frameworks"),U=x(G,"FBSimulatorControl.framework"),Y=x(U,"Modules","FBSimulatorControl.swiftmodule");J2(Y,{recursive:!0});for(let M of c5($))if(M!=="FBSimulatorControl.framework")M3(x($,M),x(G,M));let F=x($,"FBSimulatorControl.framework");M3(x(F,"FBSimulatorControl"),x(U,"FBSimulatorControl")),M3(x(F,"Headers"),x(U,"Headers")),U1(x(U,"Modules","module.modulemap"),n5(x(F,"Modules","module.modulemap")));let X=n5(x(F,"Modules","FBSimulatorControl.swiftmodule",`${a5}.swiftinterface`),"utf8");U1(x(Y,`${a5}.swiftinterface`),X.replace(/FBSimulatorControl\.(?=[A-Za-z_])/g,"").replace(/IOSurface\.IOSurface/g,"IOSurface"));let W=x(B,"include","CoreSimulator");J2(W,{recursive:!0}),U1(x(W,"module.modulemap"),`module CoreSimulator {
501
501
  header "CoreSimulator.h"
502
502
  export *
503
503
  }
504
504
  `),U1(x(W,"CoreSimulator.h"),`#import <Foundation/Foundation.h>
505
- ${vZ}`);let z=x(B,"main.swift");U1(z,D3);let N=x(B,"simulator-host"),C=await a5("xcrun",["swiftc","-O","-F",G,"-I",x(B,"include"),"-module-cache-path",x(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,z,"-o",N],xZ);if(C.code!==0||!w3(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
505
+ ${uZ}`);let z=x(B,"main.swift");U1(z,D3);let N=x(B,"simulator-host"),C=await i5("xcrun",["swiftc","-O","-F",G,"-I",x(B,"include"),"-module-cache-path",x(B,"cache"),"-Xlinker","-rpath","-Xlinker",$,z,"-o",N],yZ);if(C.code!==0||!w3(N))return process.stderr.write(`Reason: the simulator host did not build; simulator actions use AXe.
506
506
  ${C.output.slice(-2000)}
507
- `),null;J2(o5(K),{recursive:!0}),SZ(N,K);for(let M of s5(Q))if(M!==Z&&!M.startsWith(".staging-"))n5(x(Q,M),{recursive:!0,force:!0});return K}catch{return null}finally{n5(B,{recursive:!0,force:!0})}}class F1 extends Error{}class b0 extends Error{}class t5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;bZ({input:$.stdout}).on("line",(Q)=>{let K;try{K=JSON.parse(Q)}catch{return}let B=this.pending.get(Number(K.id));if(!B)return;if(this.pending.delete(Number(K.id)),clearTimeout(B.timer),K.ok===!0)B.resolve(K);else B.reject(new F1(String(K.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new b0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let K=setTimeout(()=>{this.pending.delete(J),Q(new b0("The simulator host did not answer.")),this.close()},hZ);this.pending.set(J,{resolve:Z,reject:Q,timer:K}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
508
- `)})}close(){if(this.child.exitCode===null&&this.child.signalCode===null)this.child.kill("SIGTERM");this.end()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>this.close(),mZ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new b0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var f0=new Map;async function Z2($,J,Z=!1){let Q=f0.get(J);if(!Q){let K={started:pZ($,J)};f0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&f0.get(J)===K)f0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function pZ($,J){let Z=await L3($);if(!Z)return null;let Q=j3(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),yZ);Q.stdout.once("data",(Y)=>{clearTimeout(U),G(String(Y).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(U),G(!1)}),Q.once("error",()=>{clearTimeout(U),G(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let B=new t5(Q,()=>{let G=f0.get(J);if(G&&(G.host===B||G.host===void 0))f0.delete(J)});return B}function e5($,J,Z,Q,K){return j3($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var x0={version:"1.8.0",url:"https://github.com/cameroncooke/AXe/releases/download/v1.8.0/AXe-macOS-v1.8.0-universal.tar.gz",sha256:"7b76340b72e90d0f211bc7c4636f15009076eff07acef2f2b632b175debd8834"},nZ=50000,rZ=112640,aZ=174080,O3=2,iZ=60000,oZ=2000,tZ=300,eZ=40,$Q=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function m0($,J,Z={}){return new Promise((Q,K)=>{let B=E3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],U=[];B.stdout.on("data",(F)=>G.push(F)),B.stderr.on("data",(F)=>U.push(F));let Y=setTimeout(()=>B.kill("SIGKILL"),Z.timeoutMs??nZ);B.on("error",(F)=>{clearTimeout(Y),K(F)}),B.on("close",(F)=>{clearTimeout(Y),Q({code:F??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function f($,J){throw new H($,J)}async function n($,J,Z,Q={}){let K=await m0($,J,Q);if(K.code!==0)f("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function W1(){return process.platform==="darwin"&&Q0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Q0("/usr/bin/xcrun")}var I3=null;function A0(){return k(f3(),".local","share","reason","simulator","axe")}function b3(){let $=k(A0(),x0.version,"axe");if(Q0($))return Promise.resolve($);return I3??=(async()=>{P3(A0(),{recursive:!0,mode:448});let J=k3(k(A0(),".staging-"));try{let Z=k(J,"axe.tgz");await G6(x0.url,x0.sha256,Z);let Q=k(J,"tree");if(P3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!Q0(k(Q,"axe"))||!Q0(k(Q,"Frameworks")))f("simulator_axe_missing","The AXe archive has an unexpected layout.");Y1(k(A0(),x0.version),{recursive:!0,force:!0}),sZ(Q,k(A0(),x0.version));for(let K of G2(A0()))if(K!==x0.version&&!K.startsWith(".staging-"))Y1(k(A0(),K),{recursive:!0,force:!0});return $}finally{Y1(J,{recursive:!0,force:!0}),I3=null}})(),I3}var W6=b3;async function z6($){let J=await b3().catch(()=>null);return J?Z2(J,$.udid).catch(()=>null):null}async function K2($,J,Z){let Q=await b3().catch(()=>f("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await m0(Q,[...$,"--udid",J]);if(K.code===0)return K.stdout;let B=(K.stderr||K.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(B))f("simulator_element_not_found",B.slice(-500));return f("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function JQ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function ZQ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function x3(){let J=JSON.parse(await n("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,K]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let B of K){if(B.isAvailable===!1)continue;let G=B.name.toLowerCase();if(B.deviceTypeIdentifier)q3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:JQ(Q),state:ZQ(B.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,K)=>Number(K.state==="booted")-Number(Q.state==="booted")||K.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(K.name))}var q3=new Map,g3=null;async function o($,J){let Z=await x3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)f("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let K=Z.filter((B)=>B.state==="booted");if(Q=K.find((B)=>B.udid===g3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)f("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")f("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return g3=Q.udid,Q}function v($){return`${$.name} (${$.runtime})`}async function QQ($){if($.state!=="booted"){let J=await m0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))f("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await n("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return g3=$.udid,{...$,state:"booted"}}function y3($,J){let Z=R3($,J),Q=F6($,Z);if(Q.startsWith("..")||Q.startsWith(Y6)||R3($,Q)!==Z)f("simulator_path_outside_root",`${J} is outside this machine's granted folder (${$}). Pass a path inside it, or one relative to it.`);return Z}var $6=4,KQ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function BQ($){let J=[],Z=(Q,K)=>{let B;try{B=G2(Q)}catch{return}if(B.includes("project.yml")||B.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=$6)return;for(let G of B.sort()){if(G.startsWith(".")||KQ.has(G))continue;let U=k(Q,G);try{if(Q2(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)f("simulator_project_not_found",`No Xcode project or project.yml within ${$6} folders of ${$}; pass path.`);return f("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>F6($,Q)||".").join(", ")}.`)}var h0=new Map;async function VQ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:T3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:T3($)};if(!Q2($).isDirectory())f("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>G2($).filter((B)=>B.endsWith(K)).sort();if(Q0(k($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>Q0("/opt/homebrew/bin/xcodegen")?n("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(K));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:k($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:k($,Q),dir:$};return f("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function N6($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function GQ($){let J=(await N6($))[0];if(!J)f("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function XQ($){let J=[],Z=new Set;return $.forEach((Q,K)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let B=$.slice(K+1,K+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...B].join(`
509
- `).slice(0,800))}),J}async function UQ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await N6(Z).catch(()=>[]);if(B.length)$.log.push(`error: this project's schemes are: ${B.join(", ")}`)}$.status="failed";return}let Q=k($.productsDir,`${$.configuration}-iphonesimulator`),K=Q0(Q)?G2(Q).filter((B)=>B.endsWith(".app")).map((B)=>k(Q,B)).sort((B,G)=>Q2(G).mtimeMs-Q2(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await D6($.appPath).catch(()=>{return});if($.status=$.appPath?"succeeded":"failed",!$.appPath)$.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function J6($,J){let Z=$.path?y3(J,$.path):BQ(J),Q=await VQ(Z),K=$.scheme??await GQ(Q),B=$.configuration??"Debug",G=await o($.device,{booted:!1}).catch(()=>null),U=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",Y=dZ("sha256").update(Q.path).digest("hex").slice(0,16),F=k(f3(),"Library","Caches","reason","simulator-builds",Y),X={id:`build-${lZ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:k(F,"Build","Products"),configuration:B};h0.set(X.id,X);for(let[C,M]of h0)if(h0.size>20&&M.status!=="running")h0.delete(C);let W=E3("xcodebuild",[Q.flag,Q.path,"-scheme",K,"-configuration",B,"-destination",U,"-derivedDataPath",F,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),z="",N=(C)=>{let M=(z+C.toString("utf8")).split(`
510
- `);if(z=M.pop()??"",X.log.push(...M),X.log.length>5000)X.log.splice(0,X.log.length-5000)};return W.stdout.on("data",N),W.stderr.on("data",N),W.on("error",(C)=>{X.log.push(`error: ${C.message}`),X.status="failed",X.ended=Date.now()}),W.on("close",(C)=>{if(z)X.log.push(z);UQ(X,C??-1,Q)}),{text:`Build ${X.id} started: ${K} (${B}) for ${G?v(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:H6(X)}}function H6($){return{id:$.id,status:$.status,errors:XQ($.log),log_tail:$.log.slice(-eZ).join(`
511
- `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var FQ=45000,YQ=30000;async function A3($,J=FQ){let Z=Date.now()+J;while(h0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=C6($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function C6($){let J=h0.get($);if(!J)f("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=H6(J);return{text:J.status==="running"?`Build ${$} is running (${Math.round(Z.elapsed_ms/1000)} s).`:J.status==="succeeded"?`Build ${$} succeeded: ${J.appPath}. Launch it with app_path.`:`Build ${$} failed with ${Z.errors.length} error(s).`,build:Z}}async function D6($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",k($,"Info.plist")],"Reading the bundle id")).trim()}var w0=new Map;function WQ($,J){w0.get($.udid)?.stop();let Z=E3("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",$.udid,J],{stdio:["ignore","pipe","pipe"]}),Q={udid:$.udid,bundleId:J,lines:[],first:0,stop:()=>Z.kill("SIGTERM")};w0.set($.udid,Q);let K="",B=(G)=>{let U=(K+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
512
- `);K=U.pop()??"",Q.lines.push(...U);let Y=Q.lines.length-oZ;if(Y>0)Q.lines.splice(0,Y),Q.first+=Y};return Z.stdout.on("data",B),Z.stderr.on("data",B),new Promise((G)=>{let U=setTimeout(()=>G(null),15000),Y=()=>{let F=Q.lines.concat(K).join(`
513
- `).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(F)clearTimeout(U),G(Number(F))};Z.stdout.on("data",Y),Z.on("close",()=>{clearTimeout(U),G(null)})})}async function zQ($,J){let Z=await o($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=NQ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,B],`Installing ${U6(B)}`),Q=await D6(B)}if($.bundle_id){if((await m0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)f("simulator_app_not_installed",`${$.bundle_id} is not installed on ${v(Z)}.`)}let K=await WQ(Z,Q);if(K===null){let B=w0.get(Z.udid)?.lines.slice(-20).join(`
507
+ `),null;J2(t5(K),{recursive:!0}),fZ(N,K);for(let M of c5(Q))if(M!==Z&&!M.startsWith(".staging-"))r5(x(Q,M),{recursive:!0,force:!0});return K}catch{return null}finally{r5(B,{recursive:!0,force:!0})}}class F1 extends Error{}class b0 extends Error{}class e5{child;onGone;nextId=1;pending=new Map;idle;gone=!1;constructor($,J){this.child=$;this.onGone=J;xZ({input:$.stdout}).on("line",(Q)=>{let K;try{K=JSON.parse(Q)}catch{return}let B=this.pending.get(Number(K.id));if(!B)return;if(this.pending.delete(Number(K.id)),clearTimeout(B.timer),K.ok===!0)B.resolve(K);else B.reject(new F1(String(K.error??"The simulator refused the action.")))}),$.once("exit",()=>this.end()),$.once("error",()=>this.end()),this.touch()}call($){if(this.gone)return Promise.reject(new b0("The simulator host has exited."));this.touch();let J=this.nextId++;return new Promise((Z,Q)=>{let K=setTimeout(()=>{this.pending.delete(J),Q(new b0("The simulator host did not answer.")),this.close()},mZ);this.pending.set(J,{resolve:Z,reject:Q,timer:K}),this.child.stdin.write(`${JSON.stringify({id:J,...$})}
508
+ `)})}close(){if(this.child.exitCode===null&&this.child.signalCode===null)this.child.kill("SIGTERM");this.end()}touch(){clearTimeout(this.idle),this.idle=setTimeout(()=>this.close(),vZ),this.idle.unref?.()}end(){if(this.gone)return;this.gone=!0,clearTimeout(this.idle);for(let $ of this.pending.values())clearTimeout($.timer),$.reject(new b0("The simulator host has exited."));this.pending.clear(),this.onGone()}}var f0=new Map;async function Z2($,J,Z=!1){let Q=f0.get(J);if(!Q){let K={started:dZ($,J)};f0.set(J,Q=K),K.started.then((B)=>{if(K.host=B,!B&&f0.get(J)===K)f0.delete(J)})}if(Q.host!==void 0)return Q.host;return Z?Q.started:null}async function dZ($,J){let Z=await L3($);if(!Z)return null;let Q=j3(Z,["serve",J],{stdio:["pipe","pipe","ignore"]});if(!await new Promise((G)=>{let U=setTimeout(()=>G(!1),hZ);Q.stdout.once("data",(Y)=>{clearTimeout(U),G(String(Y).includes('"ready":true'))}),Q.once("exit",()=>{clearTimeout(U),G(!1)}),Q.once("error",()=>{clearTimeout(U),G(!1)})})){if(Q.exitCode===null)Q.kill("SIGTERM");return null}let B=new e5(Q,()=>{let G=f0.get(J);if(G&&(G.host===B||G.host===void 0))f0.delete(J)});return B}function $6($,J,Z,Q,K){return j3($,["stream",J,String(Z),String(Math.round(Q)),String(K)],{stdio:["pipe","pipe","ignore"]})}var x0={version:"1.8.0",url:"https://github.com/cameroncooke/AXe/releases/download/v1.8.0/AXe-macOS-v1.8.0-universal.tar.gz",sha256:"7b76340b72e90d0f211bc7c4636f15009076eff07acef2f2b632b175debd8834"},rZ=50000,aZ=112640,iZ=174080,O3=2,oZ=60000,tZ=2000,eZ=300,$Q=40,JQ=new Set(["file:","javascript:","data:","vbscript:","blob:"]);function m0($,J,Z={}){return new Promise((Q,K)=>{let B=E3($,J,{cwd:Z.cwd,stdio:["ignore","pipe","pipe"],signal:Z.signal}),G=[],U=[];B.stdout.on("data",(F)=>G.push(F)),B.stderr.on("data",(F)=>U.push(F));let Y=setTimeout(()=>B.kill("SIGKILL"),Z.timeoutMs??rZ);B.on("error",(F)=>{clearTimeout(Y),K(F)}),B.on("close",(F)=>{clearTimeout(Y),Q({code:F??-1,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(U).toString("utf8")})})})}function f($,J){throw new H($,J)}async function n($,J,Z,Q={}){let K=await m0($,J,Q);if(K.code!==0)f("simulator_command_failed",`${Z} failed: ${(K.stderr||K.stdout).trim().slice(-1500)}`);return K.stdout}function W1(){return process.platform==="darwin"&&Q0("/Library/Developer/PrivateFrameworks/CoreSimulator.framework")&&Q0("/usr/bin/xcrun")}var I3=null;function A0(){return k(f3(),".local","share","reason","simulator","axe")}function b3(){let $=k(A0(),x0.version,"axe");if(Q0($))return Promise.resolve($);return I3??=(async()=>{P3(A0(),{recursive:!0,mode:448});let J=k3(k(A0(),".staging-"));try{let Z=k(J,"axe.tgz");await X6(x0.url,x0.sha256,Z);let Q=k(J,"tree");if(P3(Q),await n("tar",["-xzf",Z,"-C",Q],"Extracting AXe"),!Q0(k(Q,"axe"))||!Q0(k(Q,"Frameworks")))f("simulator_axe_missing","The AXe archive has an unexpected layout.");Y1(k(A0(),x0.version),{recursive:!0,force:!0}),cZ(Q,k(A0(),x0.version));for(let K of G2(A0()))if(K!==x0.version&&!K.startsWith(".staging-"))Y1(k(A0(),K),{recursive:!0,force:!0});return $}finally{Y1(J,{recursive:!0,force:!0}),I3=null}})(),I3}var z6=b3;async function N6($){let J=await b3().catch(()=>null);return J?Z2(J,$.udid).catch(()=>null):null}async function K2($,J,Z){let Q=await b3().catch(()=>f("simulator_axe_missing","AXe could not be installed on this Mac.")),K=await m0(Q,[...$,"--udid",J]);if(K.code===0)return K.stdout;let B=(K.stderr||K.stdout).trim();if(/no (matching |accessibility )?element|element not found|could not find|no elements? match/i.test(B))f("simulator_element_not_found",B.slice(-500));return f("simulator_command_failed",`${Z} failed: ${B.slice(-1500)}`)}function ZQ($){let J=$.match(/SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/);return J?`${J[1]} ${J[2]}.${J[3]}${J[4]?`.${J[4]}`:""}`:$}function QQ($){switch($){case"Booted":return"booted";case"Booting":return"booting";case"Shutting Down":return"shutting_down";default:return"shutdown"}}async function x3(){let J=JSON.parse(await n("xcrun",["simctl","list","devices","available","-j"],"Listing simulators")).devices??{},Z=[];for(let[Q,K]of Object.entries(J)){if(!Q.includes("SimRuntime.iOS"))continue;for(let B of K){if(B.isAvailable===!1)continue;let G=B.name.toLowerCase();if(B.deviceTypeIdentifier)q3.set(B.udid,B.deviceTypeIdentifier);Z.push({udid:B.udid,name:B.name,runtime:ZQ(Q),state:QQ(B.state),kind:G.includes("iphone")?"iphone":G.includes("ipad")?"ipad":"other"})}}return Z.sort((Q,K)=>Number(K.state==="booted")-Number(Q.state==="booted")||K.runtime.localeCompare(Q.runtime,void 0,{numeric:!0})||Q.name.localeCompare(K.name))}var q3=new Map,g3=null;async function o($,J){let Z=await x3(),Q;if($){let K=Z.filter((B)=>B.udid===$||B.name===$);if(Q=K.find((B)=>B.state==="booted")??K[0],!Q)f("simulator_device_not_found",`No simulator named "${$}". Call devices to list them.`)}else{let K=Z.filter((B)=>B.state==="booted");if(Q=K.find((B)=>B.udid===g3)??K.find((B)=>B.kind==="iphone")??K[0],!Q)f("simulator_not_booted","No simulator is booted. Call devices, then boot one.")}if(J.booted&&Q.state!=="booted")f("simulator_not_booted",`${Q.name} is not booted. Boot it first.`);return g3=Q.udid,Q}function v($){return`${$.name} (${$.runtime})`}async function KQ($){if($.state!=="booted"){let J=await m0("xcrun",["simctl","boot",$.udid]);if(J.code!==0&&!/current state: Booted/i.test(J.stderr))f("simulator_command_failed",`Booting ${$.name} failed: ${J.stderr.trim().slice(-1000)}`);await n("xcrun",["simctl","bootstatus",$.udid,"-b"],`Waiting for ${$.name} to boot`,{timeoutMs:45000})}return g3=$.udid,{...$,state:"booted"}}function y3($,J){let Z=R3($,J),Q=Y6($,Z);if(Q.startsWith("..")||Q.startsWith(W6)||R3($,Q)!==Z)f("simulator_path_outside_root",`${J} is outside this machine's granted folder (${$}). Pass a path inside it, or one relative to it.`);return Z}var J6=4,BQ=new Set(["node_modules","Pods","DerivedData","build","Carthage","vendor"]);function VQ($){let J=[],Z=(Q,K)=>{let B;try{B=G2(Q)}catch{return}if(B.includes("project.yml")||B.some((G)=>G.endsWith(".xcworkspace")||G.endsWith(".xcodeproj"))){J.push(Q);return}if(K>=J6)return;for(let G of B.sort()){if(G.startsWith(".")||BQ.has(G))continue;let U=k(Q,G);try{if(Q2(U).isDirectory())Z(U,K+1)}catch{}}};if(Z($,0),J.length===1)return J[0];if(!J.length)f("simulator_project_not_found",`No Xcode project or project.yml within ${J6} folders of ${$}; pass path.`);return f("simulator_project_not_found",`${$} holds several Xcode projects; pass path as one of: ${J.map((Q)=>Y6($,Q)||".").join(", ")}.`)}var h0=new Map;async function GQ($){if($.endsWith(".xcworkspace"))return{flag:"-workspace",path:$,dir:T3($)};if($.endsWith(".xcodeproj"))return{flag:"-project",path:$,dir:T3($)};if(!Q2($).isDirectory())f("simulator_project_not_found",`${$} is not a project, workspace or folder.`);let J=(K)=>G2($).filter((B)=>B.endsWith(K)).sort();if(Q0(k($,"project.yml")))await n("xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}).catch((K)=>Q0("/opt/homebrew/bin/xcodegen")?n("/opt/homebrew/bin/xcodegen",["generate","--quiet"],"xcodegen generate",{cwd:$,timeoutMs:45000}):Promise.reject(K));let Z=J(".xcworkspace")[0];if(Z)return{flag:"-workspace",path:k($,Z),dir:$};let Q=J(".xcodeproj")[0];if(Q)return{flag:"-project",path:k($,Q),dir:$};return f("simulator_project_not_found",`No .xcodeproj or .xcworkspace in ${$}.`)}async function H6($){let J=JSON.parse(await n("xcodebuild",["-list","-json",$.flag,$.path],"Listing schemes"));return J.workspace?.schemes??J.project?.schemes??[]}async function XQ($){let J=(await H6($))[0];if(!J)f("simulator_build_no_scheme",`${$.path} has no schemes; pass scheme.`);return J}function UQ($){let J=[],Z=new Set;return $.forEach((Q,K)=>{if(J.length>=20||!/(^|\s)error: /.test(Q)||Q.startsWith("note:")||Z.has(Q))return;Z.add(Q);let B=$.slice(K+1,K+3).filter((G)=>G.trim()!==""&&!/(^|\s)(error|warning|note): /.test(G));J.push([Q,...B].join(`
509
+ `).slice(0,800))}),J}async function FQ($,J,Z){if($.ended=Date.now(),J!==0){if($.log.some((B)=>B.includes("does not contain a scheme named"))){let B=await H6(Z).catch(()=>[]);if(B.length)$.log.push(`error: this project's schemes are: ${B.join(", ")}`)}$.status="failed";return}let Q=k($.productsDir,`${$.configuration}-iphonesimulator`),K=Q0(Q)?G2(Q).filter((B)=>B.endsWith(".app")).map((B)=>k(Q,B)).sort((B,G)=>Q2(G).mtimeMs-Q2(B).mtimeMs):[];if($.appPath=K[0],$.appPath)$.bundleId=await w6($.appPath).catch(()=>{return});if($.status=$.appPath?"succeeded":"failed",!$.appPath)$.log.push("error: the build succeeded but produced no .app for the iOS Simulator")}async function Z6($,J){let Z=$.path?y3(J,$.path):VQ(J),Q=await GQ(Z),K=$.scheme??await XQ(Q),B=$.configuration??"Debug",G=await o($.device,{booted:!1}).catch(()=>null),U=G?`platform=iOS Simulator,id=${G.udid}`:"generic/platform=iOS Simulator",Y=lZ("sha256").update(Q.path).digest("hex").slice(0,16),F=k(f3(),"Library","Caches","reason","simulator-builds",Y),X={id:`build-${sZ().slice(0,8)}`,status:"running",started:Date.now(),log:[],productsDir:k(F,"Build","Products"),configuration:B};h0.set(X.id,X);for(let[C,M]of h0)if(h0.size>20&&M.status!=="running")h0.delete(C);let W=E3("xcodebuild",[Q.flag,Q.path,"-scheme",K,"-configuration",B,"-destination",U,"-derivedDataPath",F,"-skipMacroValidation","build"],{cwd:Q.dir,stdio:["ignore","pipe","pipe"]}),z="",N=(C)=>{let M=(z+C.toString("utf8")).split(`
510
+ `);if(z=M.pop()??"",X.log.push(...M),X.log.length>5000)X.log.splice(0,X.log.length-5000)};return W.stdout.on("data",N),W.stderr.on("data",N),W.on("error",(C)=>{X.log.push(`error: ${C.message}`),X.status="failed",X.ended=Date.now()}),W.on("close",(C)=>{if(z)X.log.push(z);FQ(X,C??-1,Q)}),{text:`Build ${X.id} started: ${K} (${B}) for ${G?v(G):"the iOS Simulator"}. Poll build_status with this build_id; a first build can take minutes, later ones are incremental.`,build:C6(X)}}function C6($){return{id:$.id,status:$.status,errors:UQ($.log),log_tail:$.log.slice(-$Q).join(`
511
+ `).slice(-4000),elapsed_ms:($.ended??Date.now())-$.started,...$.appPath?{app_path:$.appPath}:{},...$.bundleId?{bundle_id:$.bundleId}:{}}}var YQ=45000,WQ=30000;async function A3($,J=YQ){let Z=Date.now()+J;while(h0.get($)?.status==="running"&&Date.now()<Z)await Bun.sleep(500);let Q=D6($);return Q.build?.status==="running"?{...Q,text:`${Q.text} Still running: call build_status with wait again.`}:Q}function D6($){let J=h0.get($);if(!J)f("simulator_build_not_found",`No build ${$} on this Mac (a worker restart forgets builds); start a new one.`);let Z=C6(J);return{text:J.status==="running"?`Build ${$} is running (${Math.round(Z.elapsed_ms/1000)} s).`:J.status==="succeeded"?`Build ${$} succeeded: ${J.appPath}. Launch it with app_path.`:`Build ${$} failed with ${Z.errors.length} error(s).`,build:Z}}async function w6($){return(await n("plutil",["-extract","CFBundleIdentifier","raw","-o","-",k($,"Info.plist")],"Reading the bundle id")).trim()}var w0=new Map;function zQ($,J){w0.get($.udid)?.stop();let Z=E3("script",["-q","/dev/null","xcrun","simctl","launch","--console-pty","--terminate-running-process",$.udid,J],{stdio:["ignore","pipe","pipe"]}),Q={udid:$.udid,bundleId:J,lines:[],first:0,stop:()=>Z.kill("SIGTERM")};w0.set($.udid,Q);let K="",B=(G)=>{let U=(K+G.toString("utf8").replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\r]/g,"")).split(`
512
+ `);K=U.pop()??"",Q.lines.push(...U);let Y=Q.lines.length-tZ;if(Y>0)Q.lines.splice(0,Y),Q.first+=Y};return Z.stdout.on("data",B),Z.stderr.on("data",B),new Promise((G)=>{let U=setTimeout(()=>G(null),15000),Y=()=>{let F=Q.lines.concat(K).join(`
513
+ `).match(new RegExp(`${J.replace(/\./g,"\\.")}: (\\d+)`))?.[1];if(F)clearTimeout(U),G(Number(F))};Z.stdout.on("data",Y),Z.on("close",()=>{clearTimeout(U),G(null)})})}async function NQ($,J){let Z=await o($.device,{booted:!0}),Q=$.bundle_id;if($.app_path){let B=HQ(J,$.app_path);await n("xcrun",["simctl","install",Z.udid,B],`Installing ${F6(B)}`),Q=await w6(B)}if($.bundle_id){if((await m0("xcrun",["simctl","get_app_container",Z.udid,$.bundle_id])).code!==0)f("simulator_app_not_installed",`${$.bundle_id} is not installed on ${v(Z)}.`)}let K=await zQ(Z,Q);if(K===null){let B=w0.get(Z.udid)?.lines.slice(-20).join(`
514
514
  `)??"";f("simulator_launch_failed",`${Q} did not start on ${v(Z)}.${B?`
515
- ${B}`:""}`)}return{text:`Launched ${Q} on ${v(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function NQ($,J){let Z=R3(J),Q=k(f3(),"Library","Caches","reason","simulator-builds")+Y6;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:y3($,Z)}function HQ($,J){let Z=w0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${v($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-tZ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${v($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var B2=new Map;function Z6($,...J){let Z=B2.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)f("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function Q6($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function h3($,J=1,Z){let Q=k3(k(X6(),"reason-sim-"));try{let K=k(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){P3(T3(Z),{recursive:!0});let N=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),C=Number(N.match(/pixelWidth: (\d+)/)?.[1]),M=Number(N.match(/pixelHeight: (\d+)/)?.[1]),w=2/Q6($,C);await n("sips",["-z",String(Math.round(M*w)),String(Math.round(C*w)),K,"--out",Z],"Saving the screenshot")}let B=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),G=Number(B.match(/pixelWidth: (\d+)/)?.[1]),U=Number(B.match(/pixelHeight: (\d+)/)?.[1]),Y=Q6($,G),F=Math.round(G/Y),X=Math.round(U/Y);B2.set($.udid,{width:F,height:X});let W=Buffer.alloc(0),z=J===2?aZ:rZ;for(let N of[70,50,35]){let C=k(Q,`screen-${N}.jpg`);if(await n("sips",["-z",String(X*J),String(F*J),"-s","format","jpeg","-s","formatOptions",String(N),K,"--out",C],"Encoding the screenshot"),W=S3(C),W.byteLength<=z)break}return{text:`Screenshot of ${v($)} at ${F}x${X} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:W.toString("base64"),width:F,height:X}}}finally{Y1(Q,{recursive:!0,force:!0})}}async function CQ($){let J=await z6($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return K2(["describe-ui"],$.udid,"Reading the accessibility tree")}async function V2($){let J=JSON.parse(await CQ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(K,B,G="")=>{let U=(K.role??K.type??"?").replace(/^AX/,""),Y=K.AXLabel||K.title||"",F=K.AXValue?` value="${String(K.AXValue).slice(0,120)}"`:"",X=K.AXUniqueId?` id=${K.AXUniqueId}`:"";if(K.AXUniqueId)Z.ids.add(K.AXUniqueId);if(Y)Z.labels.add(Y);let W=K.frame;if(U==="Application"&&W&&!Z.bounds)Z.bounds={width:W.width,height:W.height};if(W&&W.width>0&&W.height>0&&(K.AXUniqueId||K.AXLabel))Z.targets.push({...K.AXUniqueId?{id:K.AXUniqueId.trim()}:{},...K.AXLabel?{label:K.AXLabel.trim()}:{},role:U,frame:W});let z=Boolean(Y||X||F||!["Group","Other"].includes(U));if(z){let N=`${" ".repeat(Math.min(B,12))}${U} "${Y.slice(0,160)}"${X}${F}`+(W?` (${Math.round(W.x)},${Math.round(W.y)} ${Math.round(W.width)}x${Math.round(W.height)})`:"")+(K.enabled===!1?" disabled":"");Z.lines.push(N);let C=U==="Image"&&!X,M=(U==="StaticText"||U==="Image")&&!X&&Y!==""&&G.includes(Y);if(!C&&!M)Z.compact.push(N)}for(let N of K.children??[])Q(N,z?B+1:B,Y||G)};for(let K of J)Q(K,0);return Z}function w6($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
515
+ ${B}`:""}`)}return{text:`Launched ${Q} on ${v(Z)} (pid ${K}). Its console is captured; read it with logs.`,device:Z}}function HQ($,J){let Z=R3(J),Q=k(f3(),"Library","Caches","reason","simulator-builds")+W6;return Z.startsWith(Q)&&Z.endsWith(".app")?Z:y3($,Z)}function CQ($,J){let Z=w0.get($.udid);if(!Z)return{text:`No app launched by Reason is running on ${v($)}; launch one to capture its capture.`,logs:{lines:[],next:0}};let Q=Math.max(J??0,Z.first,Z.first+Z.lines.length-eZ),K=Z.lines.slice(Q-Z.first).map((B)=>B.slice(0,2000));return{text:`${K.length} console line(s) from ${Z.bundleId} on ${v($)}.`,logs:{lines:K,next:Z.first+Z.lines.length}}}var B2=new Map;function Q6($,...J){let Z=B2.get($.udid);if(!Z)return;for(let[Q,K]of J)if(Q>Z.width||K>Z.height)f("simulator_point_off_screen",`(${Q}, ${K}) is off ${$.name}'s ${Z.width}x${Z.height}-point screen.`)}function K6($,J){if($.kind==="ipad")return 2;return J===750||J===828||J===640?2:3}async function h3($,J=1,Z){let Q=k3(k(U6(),"reason-sim-"));try{let K=k(Q,"screen.png");if(await n("xcrun",["simctl","io",$.udid,"screenshot","--type=png",K],"Taking a screenshot"),Z){P3(T3(Z),{recursive:!0});let N=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),C=Number(N.match(/pixelWidth: (\d+)/)?.[1]),M=Number(N.match(/pixelHeight: (\d+)/)?.[1]),w=2/K6($,C);await n("sips",["-z",String(Math.round(M*w)),String(Math.round(C*w)),K,"--out",Z],"Saving the screenshot")}let B=await n("sips",["-g","pixelWidth","-g","pixelHeight",K],"Reading the screenshot size"),G=Number(B.match(/pixelWidth: (\d+)/)?.[1]),U=Number(B.match(/pixelHeight: (\d+)/)?.[1]),Y=K6($,G),F=Math.round(G/Y),X=Math.round(U/Y);B2.set($.udid,{width:F,height:X});let W=Buffer.alloc(0),z=J===2?iZ:aZ;for(let N of[70,50,35]){let C=k(Q,`screen-${N}.jpg`);if(await n("sips",["-z",String(X*J),String(F*J),"-s","format","jpeg","-s","formatOptions",String(N),K,"--out",C],"Encoding the screenshot"),W=S3(C),W.byteLength<=z)break}return{text:`Screenshot of ${v($)} at ${F}x${X} points: image pixels are tap coordinates.`+(Z?` Saved at ${Z}.`:""),device:$,image:{mime:"image/jpeg",data:W.toString("base64"),width:F,height:X}}}finally{Y1(Q,{recursive:!0,force:!0})}}async function DQ($){let J=await N6($);if(J)try{return String((await J.call({op:"tree"})).tree)}catch{}return K2(["describe-ui"],$.udid,"Reading the accessibility tree")}async function V2($){let J=JSON.parse(await DQ($)),Z={lines:[],compact:[],ids:new Set,labels:new Set,targets:[]},Q=(K,B,G="")=>{let U=(K.role??K.type??"?").replace(/^AX/,""),Y=K.AXLabel||K.title||"",F=K.AXValue?` value="${String(K.AXValue).slice(0,120)}"`:"",X=K.AXUniqueId?` id=${K.AXUniqueId}`:"";if(K.AXUniqueId)Z.ids.add(K.AXUniqueId);if(Y)Z.labels.add(Y);let W=K.frame;if(U==="Application"&&W&&!Z.bounds)Z.bounds={width:W.width,height:W.height};if(W&&W.width>0&&W.height>0&&(K.AXUniqueId||K.AXLabel))Z.targets.push({...K.AXUniqueId?{id:K.AXUniqueId.trim()}:{},...K.AXLabel?{label:K.AXLabel.trim()}:{},role:U,frame:W});let z=Boolean(Y||X||F||!["Group","Other"].includes(U));if(z){let N=`${" ".repeat(Math.min(B,12))}${U} "${Y.slice(0,160)}"${X}${F}`+(W?` (${Math.round(W.x)},${Math.round(W.y)} ${Math.round(W.width)}x${Math.round(W.height)})`:"")+(K.enabled===!1?" disabled":"");Z.lines.push(N);let C=U==="Image"&&!X,M=(U==="StaticText"||U==="Image")&&!X&&Y!==""&&G.includes(Y);if(!C&&!M)Z.compact.push(N)}for(let N of K.children??[])Q(N,z?B+1:B,Y||G)};for(let K of J)Q(K,0);return Z}function M6($,J,Z=!1){let Q=(Z?$.compact:$.lines).join(`
516
516
  `);return Q.length>J?`${Q.slice(0,J)}
517
- \u2026 (truncated)`:Q}async function DQ($){let J=await V2($);return{text:`Accessibility tree of ${v($)} (frames in points; tap by id or label):
518
- ${w6(J,iZ)}`,device:$}}var wQ=450,MQ=1e4;function jQ($,J){let Z=J.id?$.ids.has(J.id):[...$.labels].some((Q)=>Q===J.label||Q.includes(J.label));return J.gone?!Z:Z}async function _0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let K=null,B="";if(J.wait_for){let U=Date.now()+(J.timeout??5)*1000,Y=J.wait_for,F=Y.id?`id ${Y.id}`:`"${Y.label}"`;for(;;){if(K=await V2($),jQ(K,Y)){B=` ${F} is ${Y.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){B=Y.gone?` Waited ${J.timeout??5} s: ${F} is still on screen.`:` Waited ${J.timeout??5} s: ${F} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(wQ);let G={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await V2($),G.screen=w6(K,MQ,!0),G.text+=`
517
+ \u2026 (truncated)`:Q}async function wQ($){let J=await V2($);return{text:`Accessibility tree of ${v($)} (frames in points; tap by id or label):
518
+ ${M6(J,oZ)}`,device:$}}var MQ=450,jQ=1e4;function LQ($,J){let Z=J.id?$.ids.has(J.id):[...$.labels].some((Q)=>Q===J.label||Q.includes(J.label));return J.gone?!Z:Z}async function _0($,J,Z){let Q=J.observe??"tree";if(Q==="none"&&!J.wait_for)return Z;let K=null,B="";if(J.wait_for){let U=Date.now()+(J.timeout??5)*1000,Y=J.wait_for,F=Y.id?`id ${Y.id}`:`"${Y.label}"`;for(;;){if(K=await V2($),LQ(K,Y)){B=` ${F} is ${Y.gone?"gone":"on screen"}.`;break}if(Date.now()>=U){B=Y.gone?` Waited ${J.timeout??5} s: ${F} is still on screen.`:` Waited ${J.timeout??5} s: ${F} is not in the visible accessibility tree. Lists only build their visible rows, so check the screen below: it may be open with that element further down (scroll to it), or wait for something at its top.`;break}await Bun.sleep(250)}}else await Bun.sleep(MQ);let G={...Z,text:`${Z.text}${B}`};if(Q==="tree"||Q==="both")K??=await V2($),G.screen=M6(K,jQ,!0),G.text+=`
519
519
  Screen now:
520
- ${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await h3($);G.image=U.image}return G}function K6($){return`'${$.replace(/'/g,"'\\''")}'`}function LQ($){switch($.action){case"tap":if($.x!==void 0&&$.y!==void 0)return $.duration?`touch -x ${$.x} -y ${$.y} --down --up --delay ${$.duration}`:`tap -x ${$.x} -y ${$.y}`;return $.id?`tap --id ${K6($.id)}`:`tap --label ${K6($.label)}`;case"swipe":return`swipe --start-x ${$.x} --start-y ${$.y} --end-x ${$.x2} --end-y ${$.y2} --duration ${$.duration??0.3}`;case"button":return`button ${$.name.replace("_","-")}`;case"sleep":return`sleep ${$.seconds}`}}var M6=0.35,OQ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function IQ($,J){let Z=$.targets.filter((F)=>J.id!==void 0?F.id===J.id.trim():F.label===J.label?.trim()),Q=(F)=>({x:F.frame.x+F.frame.width/2,y:F.frame.y+F.frame.height/2}),K=$.bounds,B=K?Z.filter((F)=>{let{x:X,y:W}=Q(F);return X>=0&&W>=0&&X<=K.width&&W<=K.height}):Z,G=B.length?B:Z,U=G.filter((F)=>OQ.has(F.role)),Y=(U.length?U:G)[0];return Y?Q(Y):null}async function AQ($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let G=IQ(await V2($),J);if(G)return G;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return f("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
520
+ ${G.screen}`;if(Q==="screenshot"||Q==="both"){let U=await h3($);G.image=U.image}return G}function B6($){return`'${$.replace(/'/g,"'\\''")}'`}function OQ($){switch($.action){case"tap":if($.x!==void 0&&$.y!==void 0)return $.duration?`touch -x ${$.x} -y ${$.y} --down --up --delay ${$.duration}`:`tap -x ${$.x} -y ${$.y}`;return $.id?`tap --id ${B6($.id)}`:`tap --label ${B6($.label)}`;case"swipe":return`swipe --start-x ${$.x} --start-y ${$.y} --end-x ${$.x2} --end-y ${$.y2} --duration ${$.duration??0.3}`;case"button":return`button ${$.name.replace("_","-")}`;case"sleep":return`sleep ${$.seconds}`}}var j6=0.35,IQ=new Set(["Button","Link","Cell","MenuItem","Switch","Toggle","CheckBox","PopUpButton","TextField","SecureTextField","SearchField","TextArea","Slider","Tab","RadioButton"]);function AQ($,J){let Z=$.targets.filter((F)=>J.id!==void 0?F.id===J.id.trim():F.label===J.label?.trim()),Q=(F)=>({x:F.frame.x+F.frame.width/2,y:F.frame.y+F.frame.height/2}),K=$.bounds,B=K?Z.filter((F)=>{let{x:X,y:W}=Q(F);return X>=0&&W>=0&&X<=K.width&&W<=K.height}):Z,G=B.length?B:Z,U=G.filter((F)=>IQ.has(F.role)),Y=(U.length?U:G)[0];return Y?Q(Y):null}async function _Q($,J,Z,Q,K){let B=Date.now()+Z*1000;for(;;){let G=AQ(await V2($),J);if(G)return G;if(Date.now()>=B){let U=J.id!==void 0?`--id '${J.id}'`:`--label '${J.label}'`;return f("simulator_element_not_found",`Error: Step ${Q} failed: [tap]
521
521
  No accessibility element matched ${U}. Make sure the app is on the expected screen, then inspect it and prefer an id when there is one.
522
- (${Q-1} of ${K} steps had completed.)`)}await Bun.sleep(250)}}async function y0($,J,Z){let Q=await z6($);if(!Q)return B6($,J,Z);for(let[K,B]of J.entries()){try{switch(B.action){case"tap":{let U=B.x!==void 0&&B.y!==void 0?{x:B.x,y:B.y}:await AQ($,B,Z,K+1,J.length);await Q.call(B.duration?{op:"tap",...U,duration:B.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:B.x,y:B.y,x2:B.x2,y2:B.y2,duration:B.duration??0.3});break;case"button":await Q.call({op:"button",name:B.name});break;case"type":await Q.call({op:"text",text:B.text}).catch((U)=>U instanceof F1?K2(["type",B.text],$.udid,`Step ${K+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(B.seconds*1000);break}}catch(U){if(U instanceof b0)return await B6($,J.slice(K),Z),`Ran ${J.length} step(s) on ${v($)}.`;if(U instanceof F1)f("simulator_command_failed",`Step ${K+1} failed: ${U.message}
523
- (${K} of ${J.length} steps had completed.)`);throw U}let G=J[K+1];if(B.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(M6*1000)}return`Ran ${J.length} step(s) on ${v($)}.`}async function B6($,J,Z){let Q=[],K=[],B=0,G=0,U=async()=>{if(Q.length===0)return;let Y=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let F of Q)Y.push("--step",F);try{await K2(Y,$.udid,`Steps ${G+1}-${G+B}`)}catch(F){if(F instanceof H){let X=F.message.replace(/Step (\d+) failed/,(W,z)=>{let N=K[Number(z)-1];return N?`Step ${N} failed`:W});f(F.code,`${X}
524
- (${G} of ${J.length} steps had completed before this batch.)`)}throw F}G+=B,Q=[],K=[],B=0};for(let[Y,F]of J.entries()){if(F.action==="type"){await U(),await K2(["type",F.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(LQ(F)),B+=1,K.push(Y+1);let X=J[Y+1];if(F.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${M6}`),K.push(Y+1)}return await U(),`Ran ${J.length} step(s) on ${v($)}.`}var _Q=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],V6=new Map,PQ=`ObjC.import("AppKit");
522
+ (${Q-1} of ${K} steps had completed.)`)}await Bun.sleep(250)}}async function y0($,J,Z){let Q=await N6($);if(!Q)return V6($,J,Z);for(let[K,B]of J.entries()){try{switch(B.action){case"tap":{let U=B.x!==void 0&&B.y!==void 0?{x:B.x,y:B.y}:await _Q($,B,Z,K+1,J.length);await Q.call(B.duration?{op:"tap",...U,duration:B.duration}:{op:"tap",...U});break}case"swipe":await Q.call({op:"swipe",x:B.x,y:B.y,x2:B.x2,y2:B.y2,duration:B.duration??0.3});break;case"button":await Q.call({op:"button",name:B.name});break;case"type":await Q.call({op:"text",text:B.text}).catch((U)=>U instanceof F1?K2(["type",B.text],$.udid,`Step ${K+1} (typing)`):Promise.reject(U));break;case"sleep":await Bun.sleep(B.seconds*1000);break}}catch(U){if(U instanceof b0)return await V6($,J.slice(K),Z),`Ran ${J.length} step(s) on ${v($)}.`;if(U instanceof F1)f("simulator_command_failed",`Step ${K+1} failed: ${U.message}
523
+ (${K} of ${J.length} steps had completed.)`);throw U}let G=J[K+1];if(B.action!=="sleep"&&G&&G.action!=="sleep")await Bun.sleep(j6*1000)}return`Ran ${J.length} step(s) on ${v($)}.`}async function V6($,J,Z){let Q=[],K=[],B=0,G=0,U=async()=>{if(Q.length===0)return;let Y=["batch","--ax-cache","perStep","--wait-timeout",String(Z)];for(let F of Q)Y.push("--step",F);try{await K2(Y,$.udid,`Steps ${G+1}-${G+B}`)}catch(F){if(F instanceof H){let X=F.message.replace(/Step (\d+) failed/,(W,z)=>{let N=K[Number(z)-1];return N?`Step ${N} failed`:W});f(F.code,`${X}
524
+ (${G} of ${J.length} steps had completed before this batch.)`)}throw F}G+=B,Q=[],K=[],B=0};for(let[Y,F]of J.entries()){if(F.action==="type"){await U(),await K2(["type",F.text],$.udid,`Step ${G+1} (typing)`),G+=1;continue}Q.push(OQ(F)),B+=1,K.push(Y+1);let X=J[Y+1];if(F.action!=="sleep"&&X&&X.action!=="sleep")Q.push(`sleep ${j6}`),K.push(Y+1)}return await U(),`Ran ${J.length} step(s) on ${v($)}.`}var PQ=["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"],G6=new Map,TQ=`ObjC.import("AppKit");
525
525
  function run(argv) {
526
526
  const [input, output, width, height] = argv;
527
527
  const w = Number(width), h = Number(height);
@@ -533,8 +533,8 @@ function run(argv) {
533
533
  image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, w, h), $.NSZeroRect, $.NSCompositingOperationCopy, 1);
534
534
  $.NSGraphicsContext.restoreGraphicsState;
535
535
  rep.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(output, true);
536
- }`;async function _3($,J,Z){let Q=await n("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),K=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),B=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)K=K*Z/B,B=Z;let G=k3(k(X6(),"reason-chrome-"));try{let U=k(G,"render.js"),Y=k(G,"out.png");if(cZ(U,PQ),await n("osascript",["-l","JavaScript",U,$,Y,String(Math.max(1,Math.round(K*J))),String(Math.max(1,Math.round(B*J)))],"Rendering the frame"),!Q0(Y))f("simulator_command_failed",`Rendering ${U6($)} produced no image.`);return{image:S3(Y).toString("base64"),width:K,height:B}}finally{Y1(G,{recursive:!0,force:!0})}}async function TQ($){if(!q3.has($.udid))await x3();let J=q3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)f("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function RQ($){let J=await TQ($),Z=B2.get($.udid)??($.state==="booted"?(await h3($),B2.get($.udid)):void 0);if(!Z)f("simulator_not_booted",`${$.name} is not booted.`);let Q=V6.get(J);if(Q)return{text:`Frame of ${v($)}.`,device:$,chrome:Q};let K=k(J,"Contents","Resources"),B=JSON.parse(await n("plutil",["-convert","json","-o","-",k(K,"profile.plist")],"Reading the device profile")),G=B.framebufferMask?k(K,`${B.framebufferMask}.pdf`):null,U=G&&Q0(G)?await _3(G,O3,Z.height):null,Y=B.chromeIdentifier?.split(".").pop(),F=Y?k("/Library/Developer/DeviceKit/Chrome",`${Y}.devicechrome`,"Contents","Resources"):"";if(!Y||!Q0(k(F,"chrome.json")))f("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(S3(k(F,"chrome.json"),"utf8")),W={};for(let j of _Q){let O=X.images[j];if(!O)f("simulator_command_failed",`${$.name}'s frame has no ${j} piece.`);W[j]=await _3(k(F,`${O}.pdf`),O3)}let{sizing:z}=X.images,N={top:z.topHeight,left:z.leftWidth,bottom:z.bottomHeight,right:z.rightWidth},C=Z.width+N.left+N.right,M=Z.height+N.top+N.bottom,w=[];for(let j of X.inputs??[]){let O=k(F,`${j.image}.pdf`);if(!Q0(O))continue;let A=await _3(O,O3),{x:b,y:I}=j.offsets.normal,R=(c,p,M1)=>c<0?p+c-M1:c,P=j.anchor==="left"?{x:b-A.width,y:R(I,M,A.height)}:j.anchor==="right"?{x:C+b,y:R(I,M,A.height)}:j.anchor==="top"?{x:R(b,C,A.width),y:I-A.height}:{x:R(b,C,A.width),y:M+I};w.push({name:j.name,image:A.image,...P,width:A.width,height:A.height})}let D={identifier:X.identifier,screen:{width:Z.width,height:Z.height},inset:N,padding:X.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:W,buttons:w,...U?{screen_mask:U.image}:{}};return V6.set(J,D),{text:`Frame of ${v($)}.`,device:$,chrome:D}}var qQ=new Set(["simulator_command_failed","simulator_launch_failed","simulator_point_off_screen","simulator_build_no_scheme","simulator_element_not_found","simulator_path_outside_root","simulator_project_not_found"]);async function z1($){try{return await j6($)}catch(J){if(J instanceof H&&qQ.has(J.code))return{text:J.message,error:J.code};throw J}}async function j6($){if(!W1())f("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=C3.safeParse($.payload);if(!J.success)f("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await x3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(v).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await QQ(await o(Z.device,{booted:!1}));return{text:`${v(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await o(Z.device,{booted:!1});w0.get(Q.udid)?.stop(),w0.delete(Q.udid);let K=await m0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))f("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${v(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await J6(Z,$.root);return Z.wait&&Q.build?A3(Q.build.id):Q}case"build_status":return Z.wait?A3(Z.build_id):C6(Z.build_id);case"run":{let Q=await J6({...Z,action:"build"},$.root),K=await A3(Q.build.id,YQ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await j6({root:$.root,payload:{action:"launch",app_path:K.build.app_path,...Z.device?{device:Z.device}:{},...Z.steps?{steps:Z.steps}:{},...Z.observe?{observe:Z.observe}:{},...Z.wait_for?{wait_for:Z.wait_for}:{},...Z.timeout!==void 0?{timeout:Z.timeout}:{}}});return{...B,text:`Built in ${Math.round(K.build.elapsed_ms/1000)} s. ${B.text}`,build:K.build}}case"launch":{let Q=await zQ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await y0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return _0(Q.device,Z,Q)}case"steps":{let Q=await o(Z.device,{booted:!0});return _0(Q,Z,{text:await y0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await o(Z.device,{booted:!0});if(w0.get(Q.udid)?.bundleId===Z.bundle_id)w0.get(Q.udid)?.stop();return await m0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${v(Q)}.`,device:Q}}case"logs":return HQ(await o(Z.device,{booted:!1}),Z.after);case"screenshot":return h3(await o(Z.device,{booted:!0}),Z.scale,Z.save_path?y3($.root,Z.save_path):void 0);case"chrome":return RQ(await o(Z.device,{booted:!1}));case"inspect":return DQ(await o(Z.device,{booted:!0}));case"tap":{let Q=await o(Z.device,{booted:!0}),K=Z.x!==void 0&&Z.y!==void 0;if(K)Z6(Q,[Z.x,Z.y]);await y0(Q,[K?{action:"tap",x:Z.x,y:Z.y,...Z.duration&&Z.duration>0?{duration:Z.duration}:{}}:Z.id?{action:"tap",id:Z.id}:{action:"tap",label:Z.label}],3);let B=K?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return _0(Q,Z,{text:`Tapped ${B} on ${v(Q)}.`,device:Q})}case"swipe":{let Q=await o(Z.device,{booted:!0});return Z6(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await y0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),_0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${v(Q)}.`,device:Q})}case"type":{let Q=await o(Z.device,{booted:!0});return await y0(Q,[{action:"type",text:Z.text}],3),_0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${v(Q)}.`,device:Q})}case"button":{let Q=await o(Z.device,{booted:!0});return await y0(Q,[{action:"button",name:Z.name}],3),_0(Q,Z,{text:`Pressed ${Z.name} on ${v(Q)}.`,device:Q})}case"open_url":{let Q=await o(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{f("simulator_invalid_request","open_url needs an absolute URL.")}if($Q.has(K.protocol))f("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),_0(Q,Z,{text:`Opened ${K.href} on ${v(Q)}.`,device:Q})}case"appearance":{let Q=await o(Z.device,{booted:!0});return await n("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${v(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as gQ,readFileSync as EQ,rmSync as kQ}from"fs";import{tmpdir as SQ}from"os";import{join as L6}from"path";import{spawn as _6}from"child_process";var fQ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,N1=1,bQ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],O6=60,xQ=8,P6=W1;var I6={65293:40,65421:40,65307:41,65288:42,65289:43,65535:76,65360:74,65367:77,65365:75,65366:78,65361:80,65362:82,65363:79,65364:81,65505:225,65506:229,65507:224,65508:228,65513:226,65514:230,65515:227,65516:231,65511:227,65512:231,65509:57},yQ=(()=>{let $={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((Z,Q)=>{$[Z]=4+Q,$[Z.toUpperCase()]=4+Q}),"1234567890".split("").forEach((Z,Q)=>{$[Z]=30+Q}),"!@#$%^&*()".split("").forEach((Z,Q)=>{$[Z]=30+Q});let J=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[Z,Q,K]of J)$[Z]=K,$[Q]=K;return $})();function hQ($){if(I6[$]!==void 0)return I6[$];return $>=32&&$<=126?yQ[String.fromCharCode($)]??null:null}function T6($,J){let Z=_6("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function mQ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,G,U){let Y=(U&N1)!==0;if(Y&&!(Z&N1))K({op:"touch",phase:"down",x:B,y:G});else if(Y&&(B!==Q.x||G!==Q.y))K({op:"touch",phase:"move",x:B,y:G});else if(!Y&&Z&N1)K({op:"touch",phase:"up",x:B,y:G});for(let F of bQ)if(U&F.bit&&!(Z&F.bit))K({op:"swipe",x:B,y:G,x2:B+F.dx*O6,y2:G+F.dy*O6,duration:0.08});Z=U,Q={x:B,y:G}},key(B,G){let U=hQ(G);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){T6($,B)},close(){if(Z&N1)K({op:"touch",phase:"up",...Q});Z=0}}}function vQ($,J){let Z=null,Q="",K,B=(G)=>{z1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,Y){let F=(Y&N1)!==0;if(F&&!Z)Z={x:G,y:U,at:Date.now()};if(!F&&Z){let X=(Date.now()-Z.at)/1000;if(Math.hypot(G-Z.x,U-Z.y)>xQ)B({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:U,duration:Math.min(Math.max(X,0.05),1)});else B({action:"tap",x:Z.x,y:Z.y,...X>0.5?{duration:Math.min(X,10)}:{}});Z=null}},key(G,U){if(!G)return;let Y=U===65293?`
537
- `:U>=32&&U<=126?String.fromCharCode(U):null;if(Y===null)return;Q+=Y,clearTimeout(K),K=setTimeout(()=>{let F=Q;Q="",B({action:"type",text:F})},250)},clipboard(G){T6($,G)},close(){clearTimeout(K),Z=null}}}function uQ($,J,Z){return new Promise((Q,K)=>{let B=_6($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function pQ($,J){let Z=gQ(L6(SQ(),"reason-simulator-stream-"));try{let Q=L6(Z,"screen.png");if(await uQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=EQ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{kQ(Z,{recursive:!0,force:!0})}}async function R6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!fQ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await W6().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await z1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:B.image.width,height:B.image.height},U=await L3(K),Y=U?await Z2(K,Z,!0):null,F=U?null:await A6();if(!U&&!F)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let X={kind:"simulator",udid:Z,axe:K,points:G,sound:null,size:U?G:await pQ(Z,$.signal),stream:U?(W,z,N)=>e5(U,Z,Math.min(W,60),N,z):null,input:Y?mQ(Z,Y):vQ(Z,$.root)};return await X2({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...F?{ffmpeg:()=>F}:{}}})}var F9=131072,$K=131072,JK=128,Y9=8192,i3=30000,o3=15000,ZK=/^[a-z][a-z0-9_]{0,63}$/,QK=new Set(["jobs.control","fs.read","fs.write"]),q6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function U2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function g6($){return $.map(U2).join("/")}function m3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var KK=[...m3(A1,4).map(($)=>`/(${$.map(g6).join("|")})(/|$)`),...m3(_1,4).map(($)=>`/(${$.map(g6).join("|")})$`),...m3([...P1],6).map(($)=>`/(${$.map(U2).join("|")})$`),`/${U2(".env")}\\.[^/]+$`,`/[^/]+(${T1.map(U2).join("|")})$`],l3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),W9=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function z9($){return[$.requiredPermission,...$.additionalPermissions??[]]}function BK($){return h7($)}function s3(){if(E()==="darwin")return F0("/usr/bin/sandbox-exec");if(E()==="linux"||E()==="win32")return u7();return!1}function E6(){if(E()==="linux")return F0("/proc");if(E()==="win32")return H7()!==null;if(!s3())return!1;if(E()==="darwin")return F0("/usr/sbin/lsof");return!1}function N9(){return E()==="darwin"?"/bin/zsh":p7()}function c3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function VK($){if(!c3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>C0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function l0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function z2($,J,Z=Y9){let Q=l0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function GK($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function D1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function P0($,J){if(E()==="win32")[$,J]=[$.toLowerCase(),J.toLowerCase()];return J===$||J.startsWith(`${$}${tQ}`)}function u0($){if(m7($))throw new H("protected_path","This path is on Reason's credential denylist. The Mac's owner can allow it with `reason permissions protected allow <path>` or Request permission in Files.")}function u($){let J;try{J=X0($.path)}catch(Z){if(process.platform==="darwin"&&S7(Z))throw f7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!w1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return u0(J),J}function t3($,J="."){if(!J||J.includes("\x00")||iQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");if(E()==="win32"&&J.split(/[\\/]/).some(l1))throw new H("invalid_path","Windows reserves this file name.");let Z=oQ($,J);if(!P0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function d0($,J=".",Z=!1){let Q=t3($,J),K;try{K=X0(Q)}catch(B){if(w9(B))throw M9();throw new H("path_not_found","Path does not exist.")}if(!P0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)u0(K);return K}function XK($,J){let Z=t3($,J);if(u0(Z),F0(Z)){let B=X0(Z);if(!P0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(p3(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return u0(B),B}let Q=C1(Z);while(!F0(Q)){let B=C1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=X0(Q);if(!P0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return u0(K),Z}function H9($,J){return d3($,J)||"."}function UK($,J=F9){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function C9($,J){return{...q7({home:$,temporaryDirectory:J}),ZDOTDIR:J,BASH_ENV:"/dev/null",ENV:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}function FK($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...KK.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),...v7($,Z),"(deny network*)"].join(`
538
- `)}async function e3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,Y=!1,F=!1,X;try{X=eQ($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],...W7()}),z7(X)}catch(M){K(M);return}let W=(M,w)=>{if(F)return;F=!0,clearTimeout(C),Z.signal.removeEventListener("abort",N),Q({exitCode:M,signal:w,stdout:B,stderr:G,timedOut:Y,truncated:U})},z=(M,w)=>{let D=`${M}${String(w)}`,j=UK(D);return U||=j.truncated,j.value};X.stdout.on("data",(M)=>{B=z(B,M)}),X.stderr.on("data",(M)=>{G=z(G,M)}),X.once("error",K),X.once("exit",W);let N=()=>{try{if(E()==="win32"&&X.pid)N7(X.pid);else X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",N,{once:!0});let C=setTimeout(()=>{Y=!0,N()},Z.timeoutMs)})}var k6=null;function YK(){return k6??=d7({scrubEnvironment:C9,spawnCaptured:e3,isProtectedPath:k0}),k6}var WK=async($,J,Z)=>{if(E()==="linux"||E()==="win32")return YK()($,J,Z);if(E()!=="darwin"||!F0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=sQ(U9(aQ(),"reason-device-"));try{return await e3("/usr/bin/sandbox-exec",["-p",FK(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:C9(Z.root,Q)})}finally{nQ(Q,{recursive:!0,force:!0})}};function zK($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>JK)throw new H("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>Y9)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function D9($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=u($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??o3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function w9($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var M9=()=>new H("path_unreadable","The path is not readable.");function NK($){try{return X9($,K0.O_RDONLY)}catch(J){throw w9(J)?M9():J}}function S6($,J){let Z=p0()?Y2():null;return Z?W2(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):HK($,J)}function HK($,J){return $==="fs.read"?CK(J):wK(J)}async function CK($){let J=u($.root),Z=d0(J,z2($.payload,"path"));if(!w1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=D1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=D1($.payload.max_bytes,65536,1,F9),B=l0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=NK(Z),U,Y;try{U=G9(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));Y=X.subarray(0,X.byteLength?cQ(G,X,0,X.byteLength,Q):0)}finally{V9(G)}let F=B==="base64"||Y.includes(0);return{path:H9(J,Z),content:F?Y.toString("base64"):Y.toString("utf8"),encoding:F?"base64":"utf8",offset:Q,bytes:Y.byteLength,size:U,truncated:Q+Y.byteLength<U}}function DK($,J,Z=E()){let Q=$==="append"?K0.O_APPEND:K0.O_TRUNC;if(Z==="win32")return J?K0.O_WRONLY|($==="append"?K0.O_APPEND:0):K0.O_WRONLY|K0.O_CREAT|K0.O_EXCL;return K0.O_WRONLY|K0.O_NOFOLLOW|Q|(J?0:K0.O_CREAT|K0.O_EXCL)}async function wK($){let J=u($.root),Z=z2($.payload,"path"),Q=GK($.payload,"content",$K),K=l0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=XK(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){lQ(C1(B),{recursive:!0,mode:448});let F=X0(C1(B));if(!P0(J,F))throw new H("symlink_escape","Write parent escaped root.")}if(!F0(C1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&F0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=F0(B),U=G?p3(B):null,Y=X9(B,DK(K,G),384);try{let F=G9(Y),X=U??(E()==="win32"?p3(B):null);if(X&&(F.ino!==X.ino||F.dev!==X.dev||E()==="win32"&&!P0(J,X0(B))))throw new H("symlink_escape","The write target changed between validation and opening.");if(E()==="win32"&&U&&K!=="append")dQ(Y,0);rQ(Y,Q,null,"utf8")}finally{V9(Y)}return{path:H9(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function MK($){let J=u($.root),Z=z2($.payload,"command",65536),Q=d0(J,l0($.payload,"cwd")??".");if(!w1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=D1($.payload.timeout_ms,o3,100,i3);return D9($,N9(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function jK($){let J=y4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:E()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=u($.root),K=M7(Q,J.data.workspace),B=K.boundary===Q?Q:d0(K.anchor,d3(K.anchor,K.boundary)||"."),G=d0(B,d3(B,K.path)||".");if(!w1(G).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+S4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let Y=(D)=>$.emit("progress",{process:D});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await S2({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:S0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:Y})}}let F={directory:U9(Z.runtimeDirectory,"processes")},X={deniedPorts:w7([$.apiOrigin])},W=g7(),z=E7(),N=p0(),C=J.data.egress?F2(N):null;if(J.data.egress&&(C===null||!v0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let M=J.data.egress?await z8(J.data.egress.allowed_domains):null,w=M?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((D)=>`${D}=${M.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
539
- `):J.data.command;try{return{...await S2({claim:$.claim,root:G,cwd:G,command:w,mode:"host",shell:z,expiresAtMs:U,signal:$.signal,emit:Y,...N?{jobsUser:{...N,...C!==null?{modelGid:C}:{}}}:{},environment:{...W.variables,HOME:W.home,PATH:W.path,TMPDIR:W.temporaryDirectory,SHELL:z},journals:F,preview:X})}}finally{M?.close()}}async function LK($){K3();let J=u($.root),Z=B3($.payload.command),Q=d0(J,l0($.payload,"cwd")??".");if(!w1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=D1($.payload.timeout_ms,z5,100,Z3),{ignored:B}=V3($.payload.env);return await $.emit("progress",{shell:S0(),shell_flags:[...G1],sandbox:"none",ignored_env:B}),H5({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function OK($){let J=u($.root),Z=zK($.payload),Q=Z[0];if(!Q||!W9.has(Q)&&!l3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=l3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=d0(J,l0($.payload,"cwd")??".");return D9($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K||process.platform==="win32"&&$.root.permissions.write,timeoutMs:D1($.payload.timeout_ms,o3,100,i3)})}function j9($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");return Q}}async function IK($){let J=u($.root);if(E()==="linux")return _5(J);if(E()==="win32")return C7(J);return g5(J,j9($,J))}async function AK($){let J=u($.root);if(E()==="linux")return P5(J);if(E()==="win32")return D7(J);return E5(J,j9($,J))}async function _K($){let J=$.worker?v5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&$4({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},...$.worker.ownComputer?{ownComputer:!0}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:u($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function PK($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new H("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=j7($.payload,$.operationId);return A7({root:u($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:u($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function f6($,J){let Z=p0()?Y2():null;return Z?W2(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):TK(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function TK($,J){let Z=u(J.root),Q=Q1 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let K=Q?v8(Z,J.payload[Q1]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new H("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let U=A8.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return u8({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=z2(J.payload,"path",4096),G=$==="import"&&Q?o2(K):K;return u0(t3(G,B)),E0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var L9={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new H("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return W4({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>S6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>S6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>f6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>f6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>E()==="darwin"&&Q3(),execute:jK},"exec.run":{requiredPermission:"execute",available:s3,execute:MK},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Q3(),execute:LK},"git.run":{requiredPermission:"execute",available:()=>s3()&&BK("git"),execute:OK},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:E6,execute:IK},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:E6,execute:AK},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>E()==="darwin"||Boolean(b7()),execute:_K},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:J9,execute:PK},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:B9,execute:($)=>{let J=Y2();return J?W2(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??k7)()},$.signal):X2({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>Q9(),execute:($)=>K9({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:W1,execute:($)=>z1({payload:$.payload,root:u($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:P6,execute:($)=>R6({payload:$.payload,root:u($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>_7({root:u($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>E()==="darwin"?F0("/usr/bin/sandbox-exec"):E()==="linux"||E()==="win32",execute:async($)=>{let J=g1.parse($.payload),Z=r3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!j0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return P7({root:u($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>T4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>a3({root:u($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>O7({root:u($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>I7({root:u($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:a2,execute:($)=>b8($.payload,$.signal)}};function RK($,J){try{let Z=N4($,X0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function qK($,J){try{let Z=X0(J);return $.some((Q)=>Q.path===Z)?O1(Z,E()):void 0}catch{return}}function gK($,J){try{let Z=X0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function EK($,J){try{let Z=X0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&P0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function kK($,J,Z=E()){try{return I1({home:O1(X0(J),Z),roots:$.map((Q)=>({path_fingerprint:Q.pathFingerprint,path:O1(Q.path,Z)})).filter((Q)=>/^[a-f0-9]{64}$/.test(Q.path_fingerprint)&&L1(Q.path)).slice(0,D2)})}catch{return}}function XU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||E()==="darwin",K=Q?gK($,H1()):void 0,B=!J.worker&&E()==="darwin"?RK($,H1()):void 0,G=Q?qK($,H1()):void 0,U=!J.worker&&E()==="darwin"?EK($,H1()):void 0,Y=Q?kK($,H1()):void 0,F=J3.filter((X)=>{if(V1.has(X)&&!J.worker)return!1;if(J.worker&&!a1(X,J.worker))return!1;let W=L9[X];if(!W)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:W.available?.()??!0)&&$.some((N)=>(!J.worker||X!=="pty.start"||N.permissions.read&&N.permissions.write)&&z9(W).every((C)=>N.permissions[C]))});return{supported_operations:F,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...Y?{root_paths:Y}:{},...F.includes("hands.connect")?{hands_worker_artifact_sha256:g0,hands_worker_entrypoint:$1,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:C0,max_result_bytes:C0,operation_constraints:{...F.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":A2.parse(J.productionProof)}:{},...F.includes("exec.run")?{"exec.run":{transport:"shell",shell:N9(),sandbox:E()==="linux"?"linux_sandbox_runtime":E()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:i3}}:{},...F.includes("exec.full")?{"exec.full":C5()}:{},"git.run":{read_only_subcommands:[...W9].sort(),mutating_subcommands:[...l3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:z0,max_timeout_ms:Z1,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:z0,max_timeout_ms:Z1,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:e0,protocol_version:u3,worker_artifact_sha256:g0,worker_entrypoint:$1,policy_mode:"full_access",policy_version:1,workspace_base:v3,workspace_layout:B1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":E()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...F.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:$9,max_session_ms:t7,max_buffered_output_bytes:e7}}:{},...J.worker?Object.fromEntries(F.filter((X)=>X!=="browser.pr-proof.v1").map((X)=>[X,{ready:J.worker?.readiness?.[X]===!0,...J.worker?.readiness?.[X]!==!0&&J.worker?.probing?.includes(X)?{probing:!0}:{},execution_mode:a1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:Y7,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!p0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:Z7,...J.worker?.ownComputer?{[Q7]:K7}:{},workspace_base:v3,workspace_layout:B1,browser_state:"optional_headless",desktop:!1,worker_version:e0,protocol_version:u3,...J.worker?.readiness?.["environment.install"]===!0&&F.includes("environment.install")?{environment_delivery:y6,[v6]:m6}:{},...J.worker?{[p6]:u6}:{},...J.worker?.handsBrowser?{[n6]:c6}:{},[s6]:l6,[a6]:r6,...v0(J.worker?.executionMode==="unsandboxed")?{[o6]:i6}:{},...v0(J.worker?.executionMode==="unsandboxed")&&F2()!==null?{[e6]:t6}:{},...v0(J.worker?.executionMode==="unsandboxed")&&p0()?{[J7]:$7}:{}}:{},...X==="fs.export"?{cloud_source_version:m1,source_kinds:["workspace","attachment"],[h2]:m2}:{},...X==="fs.import"?{[h2]:m2}:{},...X===k4&&F2()!==null&&v0(J.worker?.executionMode==="unsandboxed")?{[x4]:T2}:{},...X==="tunnel.open"?{carried_jobs:B7}:{},...X==="jobs.control"?{[G7]:V7}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[s7]:l7,[n7]:c7.join(","),[r7]:a7,[i7]:o7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[X7]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[U7]:!0}:{}}])):{}}}}function $4($,J,Z,Q,K){let B=R7.safeParse(Q);return B.success&&K!==void 0&&K.device_id===$.deviceId&&B.data.device_id===$.deviceId&&B.data.root_id===J&&B.data.run_id===Z&&B.data.binding.kind===K.binding&&B.data.binding.target_revision===K.target_revision&&B.data.binding.root_grant_revision===K.root_grant_revision&&B.data.binding.target_generation===K.target_generation&&B.data.binding.target_fence_id===K.target_fence_id}async function UU($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==h6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((F)=>F.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!$4($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let Y=a3({root:u(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:Y.snapshot_id,installed_revision:Y.installed_revision,installed:!0},K),!0}async function FU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==d6)return!1;let{version:K,run_id:B,target_generation:G,target_fence_id:U}=Z.payload;if(K!==1||Object.keys(Z.payload).length!==4||typeof B!=="string"||typeof G!=="number"||typeof U!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let Y=$.roots.find((F)=>F.id===J.root_id);if(!Y)throw new H("root_not_granted","The Hands root is no longer granted.");return await L7({operationId:J.operation_id,root:u(Y),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function YU($,J,Z){if(J.capability!=="github.local.v1")return b6($,J,Z);try{let Q=await b6($,J,Z);if(Q.status==="succeeded"||n3(J.payload,Q.status,Q.error_code))return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function b6($,J,Z){if(V1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!a1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=r3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=L9[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let K=$.roots.find((X)=>X.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&c3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&Q1 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!$4($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(z9(Q).some((X)=>!K.permissions[X]))return{status:"failed",error_code:"permission_denied"};let B=0,G=async(X,W,z)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:B++,kind:X,capability:J.capability,data:W,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&z?{deliverySignal:z}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||QK.has(J.capability)||J.capability==="pty.start",Y,F=async(X,W,z)=>{let N=Y;Y=void 0,await Promise.all([N,G(X,W,z)])};try{if(U)Y=G("started"),Y.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},W=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(z)=>G("pr-proof.started.v1",z))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:VK(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:X,runCommand:Z.runCommand??WK,spawnFullControl:Z.spawnFullControl??e3,emit:U?F:G,runHandsRelay:Z.runHandsRelay??((z)=>y7(z,X)),runPtySession:Z.runPtySession??Z9});if(J.capability==="github.local.v1")x6.parse(W);if(!c3(W))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(W)??"null","utf8")>C0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?F:G)("completed",{ok:!0}),{status:"succeeded",result:W,error_code:null}}catch(X){let W=Z.signal.reason instanceof H&&q6.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&q6.has(X.code)?X.code:null;if(Z.signal.aborted||W)return{status:"cancelled",...X instanceof t0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":W??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&X instanceof Error&&"code"in X&&["EACCES","EPERM"].includes(String(X.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let z=J.capability==="inference.custom.v1"?X instanceof H&&F7(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?X instanceof E1&&n3(J.payload,"failed",X.code)?X.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&ZK.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof x7?T7(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:z,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:z}}}
540
- export{i9 as Ba,o9 as Ca,g4 as Da,WB as Ea,CB as Fa,mB as Ga,vB as Ha,a2 as Ia,hV as Ja,N0 as Ka,CJ as La,DJ as Ma,mV as Na,_J as Oa,S0 as Pa,WZ as Qa,QK as Ra,N9 as Sa,C9 as Ta,FK as Ua,e3 as Va,WK as Wa,HK as Xa,DK as Ya,TK as Za,L9 as _a,RK as $a,qK as ab,gK as bb,EK as cb,kK as db,XU as eb,UU as fb,FU as gb,YU as hb};
536
+ }`;async function _3($,J,Z){let Q=await n("sips",["-g","pixelWidth","-g","pixelHeight",$],"Reading the frame size"),K=Number(Q.match(/pixelWidth: ([\d.]+)/)?.[1]),B=Number(Q.match(/pixelHeight: ([\d.]+)/)?.[1]);if(Z!==void 0)K=K*Z/B,B=Z;let G=k3(k(U6(),"reason-chrome-"));try{let U=k(G,"render.js"),Y=k(G,"out.png");if(nZ(U,TQ),await n("osascript",["-l","JavaScript",U,$,Y,String(Math.max(1,Math.round(K*J))),String(Math.max(1,Math.round(B*J)))],"Rendering the frame"),!Q0(Y))f("simulator_command_failed",`Rendering ${F6($)} produced no image.`);return{image:S3(Y).toString("base64"),width:K,height:B}}finally{Y1(G,{recursive:!0,force:!0})}}async function RQ($){if(!q3.has($.udid))await x3();let J=q3.get($.udid),Q=JSON.parse(await n("xcrun",["simctl","list","devicetypes","-j"],"Listing device types")).devicetypes?.find((K)=>K.identifier===J)?.bundlePath;if(!Q)f("simulator_command_failed",`No device type bundle for ${$.name}.`);return Q}async function qQ($){let J=await RQ($),Z=B2.get($.udid)??($.state==="booted"?(await h3($),B2.get($.udid)):void 0);if(!Z)f("simulator_not_booted",`${$.name} is not booted.`);let Q=G6.get(J);if(Q)return{text:`Frame of ${v($)}.`,device:$,chrome:Q};let K=k(J,"Contents","Resources"),B=JSON.parse(await n("plutil",["-convert","json","-o","-",k(K,"profile.plist")],"Reading the device profile")),G=B.framebufferMask?k(K,`${B.framebufferMask}.pdf`):null,U=G&&Q0(G)?await _3(G,O3,Z.height):null,Y=B.chromeIdentifier?.split(".").pop(),F=Y?k("/Library/Developer/DeviceKit/Chrome",`${Y}.devicechrome`,"Contents","Resources"):"";if(!Y||!Q0(k(F,"chrome.json")))f("simulator_command_failed",`${$.name} has no device frame in this Xcode.`);let X=JSON.parse(S3(k(F,"chrome.json"),"utf8")),W={};for(let j of PQ){let O=X.images[j];if(!O)f("simulator_command_failed",`${$.name}'s frame has no ${j} piece.`);W[j]=await _3(k(F,`${O}.pdf`),O3)}let{sizing:z}=X.images,N={top:z.topHeight,left:z.leftWidth,bottom:z.bottomHeight,right:z.rightWidth},C=Z.width+N.left+N.right,M=Z.height+N.top+N.bottom,w=[];for(let j of X.inputs??[]){let O=k(F,`${j.image}.pdf`);if(!Q0(O))continue;let A=await _3(O,O3),{x:b,y:I}=j.offsets.normal,R=(c,p,M1)=>c<0?p+c-M1:c,P=j.anchor==="left"?{x:b-A.width,y:R(I,M,A.height)}:j.anchor==="right"?{x:C+b,y:R(I,M,A.height)}:j.anchor==="top"?{x:R(b,C,A.width),y:I-A.height}:{x:R(b,C,A.width),y:M+I};w.push({name:j.name,image:A.image,...P,width:A.width,height:A.height})}let D={identifier:X.identifier,screen:{width:Z.width,height:Z.height},inset:N,padding:X.images.devicePadding??{top:0,left:0,bottom:0,right:0},pieces:W,buttons:w,...U?{screen_mask:U.image}:{}};return G6.set(J,D),{text:`Frame of ${v($)}.`,device:$,chrome:D}}var gQ=new Set(["simulator_command_failed","simulator_launch_failed","simulator_point_off_screen","simulator_build_no_scheme","simulator_element_not_found","simulator_path_outside_root","simulator_project_not_found"]);async function z1($){try{return await L6($)}catch(J){if(J instanceof H&&gQ.has(J.code))return{text:J.message,error:J.code};throw J}}async function L6($){if(!W1())f("simulator_xcode_missing","Xcode's iOS Simulator is not available on this Mac.");let J=C3.safeParse($.payload);if(!J.success)f("simulator_invalid_request",J.error.issues.map((Q)=>Q.message).join("; "));let Z=J.data;switch(Z.action){case"devices":{let Q=await x3(),K=Q.filter((B)=>B.state==="booted");return{text:`${K.length} booted (${K.map(v).join(", ")||"none"}), ${Q.length} available.`,devices:Q}}case"boot":{let Q=await KQ(await o(Z.device,{booted:!1}));return{text:`${v(Q)} is booted.`,device:Q}}case"shutdown":{let Q=await o(Z.device,{booted:!1});w0.get(Q.udid)?.stop(),w0.delete(Q.udid);let K=await m0("xcrun",["simctl","shutdown",Q.udid]);if(K.code!==0&&!/current state: Shutdown/i.test(K.stderr))f("simulator_command_failed",K.stderr.trim().slice(-1000));return{text:`${v(Q)} is shut down.`,device:{...Q,state:"shutdown"}}}case"build":{let Q=await Z6(Z,$.root);return Z.wait&&Q.build?A3(Q.build.id):Q}case"build_status":return Z.wait?A3(Z.build_id):D6(Z.build_id);case"run":{let Q=await Z6({...Z,action:"build"},$.root),K=await A3(Q.build.id,WQ);if(K.build?.status!=="succeeded"||!K.build.app_path)return K;let B=await L6({root:$.root,payload:{action:"launch",app_path:K.build.app_path,...Z.device?{device:Z.device}:{},...Z.steps?{steps:Z.steps}:{},...Z.observe?{observe:Z.observe}:{},...Z.wait_for?{wait_for:Z.wait_for}:{},...Z.timeout!==void 0?{timeout:Z.timeout}:{}}});return{...B,text:`Built in ${Math.round(K.build.elapsed_ms/1000)} s. ${B.text}`,build:K.build}}case"launch":{let Q=await NQ(Z,$.root);if(!Q.device)return Q;if(Z.steps?.length)Q.text+=` ${await y0(Q.device,Z.steps,Z.timeout??8)}`;else if(!Z.wait_for)await Bun.sleep(1000);return _0(Q.device,Z,Q)}case"steps":{let Q=await o(Z.device,{booted:!0});return _0(Q,Z,{text:await y0(Q,Z.steps,Z.timeout??5),device:Q})}case"terminate":{let Q=await o(Z.device,{booted:!0});if(w0.get(Q.udid)?.bundleId===Z.bundle_id)w0.get(Q.udid)?.stop();return await m0("xcrun",["simctl","terminate",Q.udid,Z.bundle_id]),{text:`Terminated ${Z.bundle_id} on ${v(Q)}.`,device:Q}}case"logs":return CQ(await o(Z.device,{booted:!1}),Z.after);case"screenshot":return h3(await o(Z.device,{booted:!0}),Z.scale,Z.save_path?y3($.root,Z.save_path):void 0);case"chrome":return qQ(await o(Z.device,{booted:!1}));case"inspect":return wQ(await o(Z.device,{booted:!0}));case"tap":{let Q=await o(Z.device,{booted:!0}),K=Z.x!==void 0&&Z.y!==void 0;if(K)Q6(Q,[Z.x,Z.y]);await y0(Q,[K?{action:"tap",x:Z.x,y:Z.y,...Z.duration&&Z.duration>0?{duration:Z.duration}:{}}:Z.id?{action:"tap",id:Z.id}:{action:"tap",label:Z.label}],3);let B=K?`(${Z.x}, ${Z.y})`:Z.id?`id ${Z.id}`:`"${Z.label}"`;return _0(Q,Z,{text:`Tapped ${B} on ${v(Q)}.`,device:Q})}case"swipe":{let Q=await o(Z.device,{booted:!0});return Q6(Q,[Z.x,Z.y],[Z.x2,Z.y2]),await y0(Q,[{action:"swipe",x:Z.x,y:Z.y,x2:Z.x2,y2:Z.y2,...Z.duration!==void 0?{duration:Z.duration}:{}}],3),_0(Q,Z,{text:`Swiped (${Z.x}, ${Z.y}) \u2192 (${Z.x2}, ${Z.y2}) on ${v(Q)}.`,device:Q})}case"type":{let Q=await o(Z.device,{booted:!0});return await y0(Q,[{action:"type",text:Z.text}],3),_0(Q,Z,{text:`Typed ${Z.text.length} character(s) on ${v(Q)}.`,device:Q})}case"button":{let Q=await o(Z.device,{booted:!0});return await y0(Q,[{action:"button",name:Z.name}],3),_0(Q,Z,{text:`Pressed ${Z.name} on ${v(Q)}.`,device:Q})}case"open_url":{let Q=await o(Z.device,{booted:!0}),K;try{K=new URL(Z.url)}catch{f("simulator_invalid_request","open_url needs an absolute URL.")}if(JQ.has(K.protocol))f("simulator_invalid_request",`${K.protocol} URLs are not allowed.`);return await n("xcrun",["simctl","openurl",Q.udid,K.href],"Opening the URL"),_0(Q,Z,{text:`Opened ${K.href} on ${v(Q)}.`,device:Q})}case"appearance":{let Q=await o(Z.device,{booted:!0});return await n("xcrun",["simctl","ui",Q.udid,"appearance",Z.mode],"Setting the appearance"),{text:`${v(Q)} is in ${Z.mode} mode.`,device:Q}}}}import{mkdtempSync as EQ,readFileSync as kQ,rmSync as SQ}from"fs";import{tmpdir as fQ}from"os";import{join as O6}from"path";import{spawn as P6}from"child_process";var bQ=/^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i,N1=1,xQ=[{bit:8,dx:0,dy:1},{bit:16,dx:0,dy:-1},{bit:32,dx:1,dy:0},{bit:64,dx:-1,dy:0}],I6=60,yQ=8,T6=W1;var A6={65293:40,65421:40,65307:41,65288:42,65289:43,65535:76,65360:74,65367:77,65365:75,65366:78,65361:80,65362:82,65363:79,65364:81,65505:225,65506:229,65507:224,65508:228,65513:226,65514:230,65515:227,65516:231,65511:227,65512:231,65509:57},hQ=(()=>{let $={" ":44};"abcdefghijklmnopqrstuvwxyz".split("").forEach((Z,Q)=>{$[Z]=4+Q,$[Z.toUpperCase()]=4+Q}),"1234567890".split("").forEach((Z,Q)=>{$[Z]=30+Q}),"!@#$%^&*()".split("").forEach((Z,Q)=>{$[Z]=30+Q});let J=[["-","_",45],["=","+",46],["[","{",47],["]","}",48],["\\","|",49],[";",":",51],["'",'"',52],["`","~",53],[",","<",54],[".",">",55],["/","?",56]];for(let[Z,Q,K]of J)$[Z]=K,$[Q]=K;return $})();function mQ($){if(A6[$]!==void 0)return A6[$];return $>=32&&$<=126?hQ[String.fromCharCode($)]??null:null}function R6($,J){let Z=P6("xcrun",["simctl","pbcopy",$],{stdio:["pipe","ignore","ignore"]});Z.once("error",()=>{}),Z.stdin.end(J)}function vQ($,J){let Z=0,Q={x:0,y:0},K=(B)=>{J.call(B).catch(()=>{})};return{pointer(B,G,U){let Y=(U&N1)!==0;if(Y&&!(Z&N1))K({op:"touch",phase:"down",x:B,y:G});else if(Y&&(B!==Q.x||G!==Q.y))K({op:"touch",phase:"move",x:B,y:G});else if(!Y&&Z&N1)K({op:"touch",phase:"up",x:B,y:G});for(let F of xQ)if(U&F.bit&&!(Z&F.bit))K({op:"swipe",x:B,y:G,x2:B+F.dx*I6,y2:G+F.dy*I6,duration:0.08});Z=U,Q={x:B,y:G}},key(B,G){let U=mQ(G);if(U!==null)K({op:"key",usage:U,down:B})},clipboard(B){R6($,B)},close(){if(Z&N1)K({op:"touch",phase:"up",...Q});Z=0}}}function uQ($,J){let Z=null,Q="",K,B=(G)=>{z1({payload:{...G,device:$,observe:"none"},root:J}).catch(()=>{})};return{pointer(G,U,Y){let F=(Y&N1)!==0;if(F&&!Z)Z={x:G,y:U,at:Date.now()};if(!F&&Z){let X=(Date.now()-Z.at)/1000;if(Math.hypot(G-Z.x,U-Z.y)>yQ)B({action:"swipe",x:Z.x,y:Z.y,x2:G,y2:U,duration:Math.min(Math.max(X,0.05),1)});else B({action:"tap",x:Z.x,y:Z.y,...X>0.5?{duration:Math.min(X,10)}:{}});Z=null}},key(G,U){if(!G)return;let Y=U===65293?`
537
+ `:U>=32&&U<=126?String.fromCharCode(U):null;if(Y===null)return;Q+=Y,clearTimeout(K),K=setTimeout(()=>{let F=Q;Q="",B({action:"type",text:F})},250)},clipboard(G){R6($,G)},close(){clearTimeout(K),Z=null}}}function pQ($,J,Z){return new Promise((Q,K)=>{let B=P6($,J,{stdio:"ignore",signal:Z});B.once("error",K),B.once("exit",(G)=>Q(G??-1))})}async function dQ($,J){let Z=EQ(O6(fQ(),"reason-simulator-stream-"));try{let Q=O6(Z,"screen.png");if(await pQ("xcrun",["simctl","io",$,"screenshot","--type=png",Q],J)!==0)throw new H("simulator_not_booted","That simulator is not booted.");let K=kQ(Q).subarray(16,24);return{width:K.readUInt32BE(0),height:K.readUInt32BE(4)}}finally{SQ(Z,{recursive:!0,force:!0})}}async function q6($,J={}){let{udid:Z,...Q}=$.payload;if(typeof Z!=="string"||!bQ.test(Z)||!Q.video)throw new H("invalid_display_request","Reason simulator stream request is malformed.");let K=await z6().catch(()=>{throw new H("simulator_axe_missing","AXe could not be installed on this Mac.")}),B=await z1({payload:{action:"screenshot",device:Z},root:$.root});if(B.error||!B.image)throw new H("simulator_not_booted","That simulator is not booted.");let G={width:B.image.width,height:B.image.height},U=await L3(K),Y=U?await Z2(K,Z,!0):null,F=U?null:await _6();if(!U&&!F)throw new H("display_video_unsupported","This Mac can build neither the simulator host nor find an H.264 ffmpeg.");let X={kind:"simulator",udid:Z,axe:K,points:G,sound:null,size:U?G:await dQ(Z,$.signal),stream:U?(W,z,N)=>$6(U,Z,Math.min(W,60),N,z):null,input:Y?vQ(Z,Y):uQ(Z,$.root)};return await X2({payload:Q,signal:$.signal},{...J,video:{desktop:async()=>X,...F?{ffmpeg:()=>F}:{}}})}var Y9=131072,JK=131072,ZK=128,W9=8192,i3=30000,o3=15000,QK=/^[a-z][a-z0-9_]{0,63}$/,KK=new Set(["jobs.control","fs.read","fs.write"]),g6=new Set(["cancelled","run_finished","run_cancelled","driver_handoff","driver_stopped"]);function U2($){return $.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`)}function E6($){return $.map(U2).join("/")}function m3($,J){let Z=[];for(let Q=0;Q<$.length;Q+=J)Z.push($.slice(Q,Q+J));return Z}var BK=[...m3(A1,4).map(($)=>`/(${$.map(E6).join("|")})(/|$)`),...m3(_1,4).map(($)=>`/(${$.map(E6).join("|")})$`),...m3([...P1],6).map(($)=>`/(${$.map(U2).join("|")})$`),`/${U2(".env")}\\.[^/]+$`,`/[^/]+(${T1.map(U2).join("|")})$`],l3=new Set(["add","am","apply","branch","checkout","cherry-pick","clean","commit","merge","mv","rebase","remote","reset","restore","revert","rm","stash","switch","tag"]),z9=new Set(["blame","diff","for-each-ref","grep","log","ls-files","rev-list","rev-parse","shortlog","show","status"]);function N9($){return[$.requiredPermission,...$.additionalPermissions??[]]}function VK($){return m7($)}function s3(){if(E()==="darwin")return F0("/usr/bin/sandbox-exec");if(E()==="linux"||E()==="win32")return p7();return!1}function k6(){if(E()==="linux")return F0("/proc");if(E()==="win32")return C7()!==null;if(!s3())return!1;if(E()==="darwin")return F0("/usr/sbin/lsof");return!1}function H9(){return E()==="darwin"?"/bin/zsh":d7()}function c3($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}function GK($){if(!c3($))throw new H("invalid_payload","Operation payload must be an object.");if(Buffer.byteLength(JSON.stringify($),"utf8")>C0)throw new H("payload_too_large","Operation payload exceeds 256 KB.");return $}function l0($,J){let Z=$[J];if(Z===void 0||Z===null)return;if(typeof Z!=="string")throw new H("invalid_payload",`${J} must be a string.`);return Z}function z2($,J,Z=W9){let Q=l0($,J);if(!Q||Buffer.byteLength(Q,"utf8")>Z||Q.includes("\x00"))throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function XK($,J,Z){let Q=$[J];if(typeof Q!=="string"||Q.includes("\x00")||Buffer.byteLength(Q,"utf8")>Z)throw new H("invalid_payload",`${J} is missing or too large.`);return Q}function D1($,J,Z,Q){if($===void 0||$===null)return J;if(typeof $!=="number"||!Number.isInteger($))throw new H("invalid_payload","Expected a bounded integer.");return Math.min(Math.max($,Z),Q)}function P0($,J){if(E()==="win32")[$,J]=[$.toLowerCase(),J.toLowerCase()];return J===$||J.startsWith(`${$}${eQ}`)}function u0($){if(v7($))throw new H("protected_path","This path is on Reason's credential denylist. The Mac's owner can allow it with `reason permissions protected allow <path>` or Request permission in Files.")}function u($){let J;try{J=X0($.path)}catch(Z){if(process.platform==="darwin"&&f7(Z))throw b7($.path);throw new H("root_unavailable","The granted root is unavailable.")}if(J!==$.path||!w1(J).isDirectory())throw new H("root_changed","The granted root changed after registration.");return u0(J),J}function t3($,J="."){if(!J||J.includes("\x00")||oQ(J))throw new H("path_outside_root","Paths must be relative to the granted root.");if(E()==="win32"&&J.split(/[\\/]/).some(l1))throw new H("invalid_path","Windows reserves this file name.");let Z=tQ($,J);if(!P0($,Z))throw new H("path_outside_root","Path escapes the granted root.");return Z}function d0($,J=".",Z=!1){let Q=t3($,J),K;try{K=X0(Q)}catch(B){if(M9(B))throw j9();throw new H("path_not_found","Path does not exist.")}if(!P0($,K))throw new H("symlink_escape","Path resolves outside the granted root.");if(!Z)u0(K);return K}function UK($,J){let Z=t3($,J);if(u0(Z),F0(Z)){let B=X0(Z);if(!P0($,B))throw new H("symlink_escape","Write target resolves outside the granted root.");if(p3(Z).isSymbolicLink())throw new H("symlink_escape","Writing through a symlink is not allowed.");return u0(B),B}let Q=C1(Z);while(!F0(Q)){let B=C1(Q);if(B===Q)throw new H("path_outside_root","No safe write parent.");Q=B}let K=X0(Q);if(!P0($,K))throw new H("symlink_escape","Write parent resolves outside the granted root.");return u0(K),Z}function C9($,J){return d3($,J)||"."}function FK($,J=Y9){let Z=Buffer.from($,"utf8");if(Z.byteLength<=J)return{value:$,truncated:!1};return{value:Z.subarray(0,J).toString("utf8"),truncated:!0}}function D9($,J){return{...g7({home:$,temporaryDirectory:J}),ZDOTDIR:J,BASH_ENV:"/dev/null",ENV:"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_CONFIG_GLOBAL:"/dev/null",GIT_TERMINAL_PROMPT:"0",GIT_OPTIONAL_LOCKS:"0"}}function YK($,J,Z,Q=!1){return["(version 1)","(deny default)",'(import "system.sb")',"(allow process*)",'(allow file-read* (subpath "/opt/homebrew") (subpath "/usr/local"))',...Q?['(allow file-read* (subpath "/dev"))']:[],`(allow file-read* (subpath ${JSON.stringify($)}))`,`(allow file-read* file-write* (subpath ${JSON.stringify(J)}))`,...Z?[`(allow file-write* (subpath ${JSON.stringify($)}))`]:[],...BK.map((K)=>`(deny file-read* file-write* (regex #"${K}"))`),...u7($,Z),"(deny network*)"].join(`
538
+ `)}async function e3($,J,Z){return new Promise((Q,K)=>{let B="",G="",U=!1,Y=!1,F=!1,X;try{X=$K($,J,{cwd:Z.cwd,env:Z.env,shell:!1,stdio:["ignore","pipe","pipe"],...z7()}),N7(X)}catch(M){K(M);return}let W=(M,w)=>{if(F)return;F=!0,clearTimeout(C),Z.signal.removeEventListener("abort",N),Q({exitCode:M,signal:w,stdout:B,stderr:G,timedOut:Y,truncated:U})},z=(M,w)=>{let D=`${M}${String(w)}`,j=FK(D);return U||=j.truncated,j.value};X.stdout.on("data",(M)=>{B=z(B,M)}),X.stderr.on("data",(M)=>{G=z(G,M)}),X.once("error",K),X.once("exit",W);let N=()=>{try{if(E()==="win32"&&X.pid)H7(X.pid);else X.kill("SIGTERM")}catch{}};Z.signal.addEventListener("abort",N,{once:!0});let C=setTimeout(()=>{Y=!0,N()},Z.timeoutMs)})}var S6=null;function WK(){return S6??=l7({scrubEnvironment:D9,spawnCaptured:e3,isProtectedPath:k0}),S6}var zK=async($,J,Z)=>{if(E()==="linux"||E()==="win32")return WK()($,J,Z);if(E()!=="darwin"||!F0("/usr/bin/sandbox-exec"))throw new H("sandbox_unavailable","Confined command execution is unavailable on this operating system.");let Q=cQ(F9(iQ(),"reason-device-"));try{return await e3("/usr/bin/sandbox-exec",["-p",YK(Z.root,Q,Z.allowWrite,Z.allowProcessInspection===!0),$,...J],{cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,env:D9(Z.root,Q)})}finally{rQ(Q,{recursive:!0,force:!0})}};function NK($){let J=$.args;if(J===void 0)return[];if(!Array.isArray(J)||J.length>ZK)throw new H("invalid_payload","args must be a bounded string array.");return J.map((Z)=>{if(typeof Z!=="string"||Z.includes("\x00")||Buffer.byteLength(Z,"utf8")>W9)throw new H("invalid_payload","Command argument is invalid or too large.");return Z})}async function w9($,J,Z,Q={}){if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");let K=u($.root),B=Q.cwd??K,G=await $.runCommand(J,Z,{cwd:B,root:K,allowWrite:Q.allowWrite===!0,timeoutMs:Q.timeoutMs??o3,signal:$.signal});if(G.exitCode!==0&&/permission denied|operation not permitted|EACCES|EPERM/i.test(G.stderr))await $.emit("permission.denied",{operation:"bash",provenance:$.worker?.executionMode==="unsandboxed"?"os_permission_unknown":"sandbox_policy"});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated}}function M9($){let J=$ instanceof Error&&"code"in $?$.code:null;return J==="EACCES"||J==="EPERM"}var j9=()=>new H("path_unreadable","The path is not readable.");function HK($){try{return U9($,K0.O_RDONLY)}catch(J){throw M9(J)?j9():J}}function f6($,J){let Z=p0()?Y2():null;return Z?W2(Z,{op:"fs",capability:$,root:J.root,payload:J.payload},J.signal).then((Q)=>Q.value):CK($,J)}function CK($,J){return $==="fs.read"?DK(J):MK(J)}async function DK($){let J=u($.root),Z=d0(J,z2($.payload,"path"));if(!w1(Z).isFile())throw new H("not_a_file","Read target is not a file.");let Q=D1($.payload.offset,0,0,Number.MAX_SAFE_INTEGER),K=D1($.payload.max_bytes,65536,1,Y9),B=l0($.payload,"encoding");if(B!==void 0&&B!=="base64")throw new H("invalid_payload","encoding must be base64.");let G=HK(Z),U,Y;try{U=X9(G).size;let X=Buffer.alloc(Math.max(0,Math.min(K,U-Q)));Y=X.subarray(0,X.byteLength?nQ(G,X,0,X.byteLength,Q):0)}finally{G9(G)}let F=B==="base64"||Y.includes(0);return{path:C9(J,Z),content:F?Y.toString("base64"):Y.toString("utf8"),encoding:F?"base64":"utf8",offset:Q,bytes:Y.byteLength,size:U,truncated:Q+Y.byteLength<U}}function wK($,J,Z=E()){let Q=$==="append"?K0.O_APPEND:K0.O_TRUNC;if(Z==="win32")return J?K0.O_WRONLY|($==="append"?K0.O_APPEND:0):K0.O_WRONLY|K0.O_CREAT|K0.O_EXCL;return K0.O_WRONLY|K0.O_NOFOLLOW|Q|(J?0:K0.O_CREAT|K0.O_EXCL)}async function MK($){let J=u($.root),Z=z2($.payload,"path"),Q=XK($.payload,"content",JK),K=l0($.payload,"mode")??"overwrite";if(!["create","overwrite","append"].includes(K))throw new H("invalid_payload","mode must be create, overwrite, or append.");let B=UK(J,Z);if($.payload.create_parents===!0||$.payload.create_directories===!0){sQ(C1(B),{recursive:!0,mode:448});let F=X0(C1(B));if(!P0(J,F))throw new H("symlink_escape","Write parent escaped root.")}if(!F0(C1(B)))throw new H("path_not_found","Write parent does not exist.");if(K==="create"&&F0(B))throw new H("path_exists","Create mode will not overwrite an existing file.");let G=F0(B),U=G?p3(B):null,Y=U9(B,wK(K,G),384);try{let F=X9(Y),X=U??(E()==="win32"?p3(B):null);if(X&&(F.ino!==X.ino||F.dev!==X.dev||E()==="win32"&&!P0(J,X0(B))))throw new H("symlink_escape","The write target changed between validation and opening.");if(E()==="win32"&&U&&K!=="append")lQ(Y,0);aQ(Y,Q,null,"utf8")}finally{G9(Y)}return{path:C9(J,B),bytes_written:Buffer.byteLength(Q,"utf8"),mode:K}}async function jK($){let J=u($.root),Z=z2($.payload,"command",65536),Q=d0(J,l0($.payload,"cwd")??".");if(!w1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=D1($.payload.timeout_ms,o3,100,i3);return w9($,H9(),["-lc",Z],{cwd:Q,allowWrite:$.root.permissions.write,timeoutMs:K})}async function LK($){let J=h4.safeParse($.payload),Z=$.worker;if(!J.success||!$.claimOwner||(Z?!Z.runtimeDirectory:E()!=="darwin"))throw new H("preview_unavailable","Preview servers are unavailable on this computer.");let Q=u($.root),K=j7(Q,J.data.workspace),B=K.boundary===Q?Q:d0(K.anchor,d3(K.anchor,K.boundary)||"."),G=d0(B,d3(B,K.path)||".");if(!w1(G).isDirectory())throw new H("invalid_cwd","The Session checkout is not a directory.");let U=Math.min(Date.parse(J.data.expires_at),Date.now()+f4);if(!(U>Date.now()))throw new H("process_authority_lost","The preview server lease is unavailable.");let Y=(D)=>$.emit("progress",{process:D});if(!Z?.runtimeDirectory){if($.claim.local_github_authority)throw new H("local_device_gh_confinement_unavailable","Only a worker runs a local GitHub Session's dev server.");return{...await S2({claim:$.claim,root:B,cwd:G,command:J.data.command,mode:"host",shell:S0(),environment:process.env,expiresAtMs:U,signal:$.signal,emit:Y})}}let F={directory:F9(Z.runtimeDirectory,"processes")},X={deniedPorts:M7([$.apiOrigin])},W=E7(),z=k7(),N=p0(),C=J.data.egress?F2(N):null;if(J.data.egress&&(C===null||!v0(Z.executionMode==="unsandboxed")))throw new H("preview_egress_unavailable","This computer cannot hold a dev server to the run's network allowlist; no command was dispatched.");let M=J.data.egress?await N8(J.data.egress.allowed_domains):null,w=M?[`export ${["HTTP_PROXY","HTTPS_PROXY","http_proxy","https_proxy"].map((D)=>`${D}=${M.url}`).join(" ")}`,"export NO_PROXY=localhost,127.0.0.1,::1 no_proxy=localhost,127.0.0.1,::1 NODE_USE_ENV_PROXY=1",J.data.command].join(`
539
+ `):J.data.command;try{return{...await S2({claim:$.claim,root:G,cwd:G,command:w,mode:"host",shell:z,expiresAtMs:U,signal:$.signal,emit:Y,...N?{jobsUser:{...N,...C!==null?{modelGid:C}:{}}}:{},environment:{...W.variables,HOME:W.home,PATH:W.path,TMPDIR:W.temporaryDirectory,SHELL:z},journals:F,preview:X})}}finally{M?.close()}}async function OK($){K3();let J=u($.root),Z=B3($.payload.command),Q=d0(J,l0($.payload,"cwd")??".");if(!w1(Q).isDirectory())throw new H("invalid_cwd","cwd is not a directory.");let K=D1($.payload.timeout_ms,N5,100,Z3),{ignored:B}=V3($.payload.env);return await $.emit("progress",{shell:S0(),shell_flags:[...G1],sandbox:"none",ignored_env:B}),C5({command:Z,cwd:Q,timeoutMs:K,signal:$.signal,spawn:$.spawnFullControl,requestEnv:$.payload.env})}async function IK($){let J=u($.root),Z=NK($.payload),Q=Z[0];if(!Q||!z9.has(Q)&&!l3.has(Q))throw new H("git_command_not_allowed","Git subcommand is not in the Device allowlist.");if(Z.some((G)=>G==="-C"||G==="-c"||G.startsWith("--git-dir")||G.startsWith("--work-tree")||G.startsWith("--config-env")||G.startsWith("--exec-path")))throw new H("git_argument_not_allowed","Git path/config overrides are not allowed.");let K=l3.has(Q);if(K&&!$.root.permissions.write)throw new H("permission_denied","Mutating Git commands require the write grant.");let B=d0(J,l0($.payload,"cwd")??".");return w9($,"git",["-c","core.hooksPath=/dev/null","-c","credential.helper=",...Z],{cwd:B,allowWrite:K||process.platform==="win32"&&$.root.permissions.write,timeoutMs:D1($.payload.timeout_ms,o3,100,i3)})}function L9($,J){return async(Z)=>{let Q=await $.runCommand("/usr/sbin/lsof",Z,{cwd:J,root:J,allowWrite:!1,allowProcessInspection:!0,timeoutMs:1e4,signal:$.signal});if($.signal.aborted)throw new H("cancelled","Operation was cancelled.");return Q}}async function AK($){let J=u($.root);if(E()==="linux")return P5(J);if(E()==="win32")return D7(J);return E5(J,L9($,J))}async function _K($){let J=u($.root);if(E()==="linux")return T5(J);if(E()==="win32")return w7(J);return k5(J,L9($,J))}async function PK($){let J=$.worker?u5($.worker):null,Z=$.claim.environment;delete $.claim.environment;let Q=$.worker&&Z&&$4({deviceId:$.deviceId},$.root.id,$.runId,Z.payload,Z.authority)?Z.payload:void 0;return $.runHandsRelay({...$.claimedAtMs===void 0?{}:{claimedAtMs:$.claimedAtMs},claimOwner:$.claimOwner,...Q?{claimEnvironment:Q}:{},localGithubConfinement:Boolean($.claim.local_github_authority),...$.worker?{headless:!0,runtimeDirectory:$.worker.runtimeDirectory,...$.worker.handsSlots?{handsSlots:$.worker.handsSlots}:{},...$.worker.ownComputer?{ownComputer:!0}:{},hostExecution:$.worker.executionMode==="unsandboxed",...$.worker.executionMode==="unsandboxed"&&$.worker.readiness?.["pty.start"]===!0?{managedPty:{version:1,startupVerified:!0}}:{},deviceIdentity:{deviceId:$.deviceId,rootId:$.root.id,apiOrigin:$.apiOrigin},...J?{desktopRecording:J}:{}}:{},root:u($.root),runId:$.runId,operationId:$.operationId,attemptId:$.attemptId,payload:$.payload,signal:$.signal,emitEvent:(K,B,G)=>$.emit(K,B,G)})}async function TK($){if($.worker){if(!$.root.permissions.read||!$.root.permissions.write)throw new H("permission_denied","Bound Hands terminals require the workspace read/write grants.");let{workspace:J,session:Z}=L7($.payload,$.operationId);return _7({root:u($.root),runId:$.runId,deviceId:$.deviceId,rootId:$.root.id,workspace:J,session:Z,owner:$.claimOwner,authority:$.claimAuthority,signal:$.signal,emit:(Q,K)=>$.emit(Q,K)})}return $.runPtySession({root:u($.root),runId:$.runId,operationId:$.operationId,payload:$.payload,signal:$.signal,emitEvent:(J,Z)=>$.emit(J,Z)})}function b6($,J){let Z=p0()?Y2():null;return Z?W2(Z,{op:"transfer",direction:J,root:$.root,payload:$.payload,worker:Boolean($.worker)},$.signal).then((Q)=>Q.value):RK(J,{root:$.root,payload:$.payload,signal:$.signal,worker:Boolean($.worker),fetchImpl:$.fetchImpl,beforeCommit:()=>$.emit("progress",{phase:"file_transfer_verified"})})}async function RK($,J){let Z=u(J.root),Q=Q1 in J.payload;if(Q&&!J.worker)throw new H("cloud_copy_workspace_invalid","Only a worker resolves a Cloud copy workspace.");let K=Q?u8(Z,J.payload[Q1]):Z;if("source"in J.payload||"source_version"in J.payload){if($!=="export"||!Q)throw new H("cloud_copy_source_unsupported","Explicit sources require the private Cloud exporter.");let U=_8.safeParse(J.payload);if(!U.success)throw new H("invalid_payload","Invalid Cloud export request.");return p8({runtimeRoot:K,source:U.data.source,url:U.data.url,signal:J.signal,fetchImpl:J.fetchImpl})}let B=z2(J.payload,"path",4096),G=$==="import"&&Q?o2(K):K;return u0(t3(G,B)),E0({direction:$,root:G,path:B,payload:J.payload,signal:J.signal,fetchImpl:J.fetchImpl,beforeCommit:J.beforeCommit})}var O9={"inference.custom.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],execute:($)=>{if(!$.customEndpointCredential||!$.claimOwner)throw new H("custom_endpoint_credential_unavailable","Local model credentials require a signed Device claim.");return W4({payload:$.payload,signal:$.signal,credential:$.customEndpointCredential,emit:(J,Z)=>$.emit(J,Z,$.signal)})}},"fs.read":{requiredPermission:"read",execute:($)=>f6("fs.read",$)},"fs.write":{requiredPermission:"write",execute:($)=>f6("fs.write",$)},"fs.export":{requiredPermission:"read",execute:($)=>b6($,"export")},"fs.import":{requiredPermission:"write",execute:($)=>b6($,"import")},"preview.serve.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>E()==="darwin"&&Q3(),execute:LK},"exec.run":{requiredPermission:"execute",available:s3,execute:jK},"exec.full":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:()=>Q3(),execute:OK},"git.run":{requiredPermission:"execute",available:()=>s3()&&VK("git"),execute:IK},"process.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:k6,execute:AK},"ports.list":{requiredPermission:"read",additionalPermissions:["discover_environment"],available:k6,execute:_K},"hands.connect":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>E()==="darwin"||Boolean(x7()),execute:PK},"pty.start":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:Z9,execute:TK},"display.stream.v1":{requiredPermission:"execute",additionalPermissions:["discover_environment"],available:V9,execute:($)=>{let J=Y2();return J?W2(J,{op:"display",payload:$.payload,proxy:($.relay.loadProxy??S7)()},$.signal):X2({payload:$.payload,signal:$.signal},$.relay)}},"automation.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:()=>K9(),execute:($)=>B9({runId:$.runId,payload:$.payload,signal:$.signal,...$.worker?.userChrome?{userChrome:$.worker.userChrome}:{}})},"simulator.call.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:W1,execute:($)=>z1({payload:$.payload,root:u($.root)})},"simulator.stream.v1":{requiredPermission:"execute",additionalPermissions:["read","discover_environment"],available:T6,execute:($)=>q6({payload:$.payload,root:u($.root),signal:$.signal},$.relay)},"jobs.control":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],available:()=>!0,execute:($)=>P7({root:u($.root),runId:$.runId,payload:$.payload,signal:$.signal})},"github.local.v1":{requiredPermission:"read",additionalPermissions:["execute","discover_environment"],available:()=>E()==="darwin"?F0("/usr/bin/sandbox-exec"):E()==="linux"||E()==="win32",execute:async($)=>{let J=g1.parse($.payload),Z=r3.parse($.claim.local_github_authority);if(Z.userId!==$.claimOwner?.user_id||Z.deviceId!==$.deviceId||Z.rootId!==$.root.id||Z.runId!==$.runId||Z.repoFullName!==J.repoFullName||!Z.readOnly&&!$.root.permissions.write||!j0(J)&&(Z.readOnly||Z.generation===null&&!(J.kind==="pr_merge"&&Z.merge?.source==="human")&&!(J.kind==="pr_mutation"&&Z.contributorRefresh)))throw Error("local_device_gh_authority_changed");return T7({root:u($.root),runId:$.runId,request:J,authority:Z,signal:$.signal,leaseUntil:$.claim.lease_until},(Q)=>R4(J,Q))}},"environment.install":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:async($)=>a3({root:u($.root),runId:$.runId,payload:$.payload})},"browser.pr-proof.v1":{requiredPermission:"read",additionalPermissions:["execute"],available:()=>!1,execute:async($)=>{if(!$.proveMac)throw new H("capability_unsupported","PR proof host is not installed.");return $.proveMac()}},"tunnel.open":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>I7({root:u($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"tunnel.close":{requiredPermission:"execute",additionalPermissions:["read","write","discover_environment"],execute:($)=>A7({root:u($.root),runId:$.runId,owner:$.claimOwner,payload:$.payload,signal:$.signal})},"workspace.setup.v1":{requiredPermission:"execute",additionalPermissions:["read","write"],available:a2,execute:($)=>x8($.payload,$.signal)}};function qK($,J){try{let Z=N4($,X0(J)),Q=Z?$.find((K)=>K.path===Z):void 0;return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function gK($,J){try{let Z=X0(J);return $.some((Q)=>Q.path===Z)?O1(Z,E()):void 0}catch{return}}function EK($,J){try{let Z=X0(J),Q=$.find((K)=>K.path===Z);return Q&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)?Q.pathFingerprint:void 0}catch{return}}function kK($,J){try{let Z=X0(J);if(!$.some((Q)=>Q.path===Z))return;return $.filter((Q)=>Q.path!==Z&&P0(Z,Q.path)&&/^[a-f0-9]{64}$/.test(Q.pathFingerprint)).map((Q)=>Q.pathFingerprint)}catch{return}}function SK($,J,Z=E()){try{return I1({home:O1(X0(J),Z),roots:$.map((Q)=>({path_fingerprint:Q.pathFingerprint,path:O1(Q.path,Z)})).filter((Q)=>/^[a-f0-9]{64}$/.test(Q.path_fingerprint)&&L1(Q.path)).slice(0,D2)})}catch{return}}function FU($,J={}){let Z=J.worker?J.worker.handsSlots??1:J.handsSlots===1?1:void 0,Q=Boolean(J.worker)||E()==="darwin",K=Q?EK($,H1()):void 0,B=!J.worker&&E()==="darwin"?qK($,H1()):void 0,G=Q?gK($,H1()):void 0,U=!J.worker&&E()==="darwin"?kK($,H1()):void 0,Y=Q?SK($,H1()):void 0,F=J3.filter((X)=>{if(V1.has(X)&&!J.worker)return!1;if(J.worker&&!a1(X,J.worker))return!1;let W=O9[X];if(!W)return!1;return(X==="hands.connect"&&(J.terminalOnlyHands===!0||Boolean(J.worker))||(X==="pty.start"||X==="preview.serve.v1")&&Boolean(J.worker)||X==="browser.pr-proof.v1"&&Boolean(J.productionProof)?!0:W.available?.()??!0)&&$.some((N)=>(!J.worker||X!=="pty.start"||N.permissions.read&&N.permissions.write)&&N9(W).every((C)=>N.permissions[C]))});return{supported_operations:F,...K?{account_root_fingerprint:K}:{},...B?{workspace_root_fingerprint:B}:{},...G?{account_root_path:G}:{},...U?{home_contained_root_fingerprints:U}:{},...Y?{root_paths:Y}:{},...F.includes("hands.connect")?{hands_worker_artifact_sha256:g0,hands_worker_entrypoint:$1,...Z?{hands_slots:Z}:{}}:{},max_payload_bytes:C0,max_result_bytes:C0,operation_constraints:{...F.includes("browser.pr-proof.v1")&&J.productionProof?{"browser.pr-proof.v1":A2.parse(J.productionProof)}:{},...F.includes("exec.run")?{"exec.run":{transport:"shell",shell:H9(),sandbox:E()==="linux"?"linux_sandbox_runtime":E()==="win32"?"windows_srt":"macos_seatbelt",network:!1,max_timeout_ms:i3}}:{},...F.includes("exec.full")?{"exec.full":D5()}:{},"git.run":{read_only_subcommands:[...z9].sort(),mutating_subcommands:[...l3].sort(),push:!1,credential_helpers:!1},"fs.export":{transport:"https_signed_url",max_bytes:z0,max_timeout_ms:Z1,result:"sha256_and_size"},"fs.import":{transport:"https_signed_url",max_bytes:z0,max_timeout_ms:Z1,atomic:!0,overwrite:!1},"hands.connect":{transport:"wss_relay",worker:"ara_hands",worker_version:e0,protocol_version:u3,worker_artifact_sha256:g0,worker_entrypoint:$1,policy_mode:"full_access",policy_version:1,workspace_base:v3,workspace_layout:B1,...Z?{slots:Z}:{},browser_state:J.worker?"optional_headless":J.terminalOnlyHands===!0?"disabled_terminal_only":E()==="darwin"?"optional_isolated_per_session":"isolated_per_session",max_session_ms:43200000},...F.includes("pty.start")?{"pty.start":{transport:"wss_relay",shell:"login_shell",resize:!0,slots:J9,max_session_ms:e7,max_buffered_output_bytes:$9}}:{},...J.worker?Object.fromEntries(F.filter((X)=>X!=="browser.pr-proof.v1").map((X)=>[X,{ready:J.worker?.readiness?.[X]===!0,...J.worker?.readiness?.[X]!==!0&&J.worker?.probing?.includes(X)?{probing:!0}:{},execution_mode:a1(X,{...J.worker,executionMode:"sandboxed"})?"confined":"host",...X==="pty.start"?{transport:"wss_relay",worker:"ara_hands",shell:"bound_job",protocol_version:W7,environment:"private_snapshot",receipt:"metadata_only",...J.worker?.persistentTerminals&&!p0()?{persistent_terminals:!0}:{}}:{},...X==="github.local.v1"?{contributor_attribution:2,prepare_diagnostics:1,...J.worker?.githubSignedIn!==void 0?{gh_authenticated:J.worker.githubSignedIn}:{}}:{},...X==="hands.connect"?{transport:"wss_relay",worker:"ara_hands",slots:Z,session_group:Q7,...J.worker?.ownComputer?{[K7]:B7}:{},workspace_base:v3,workspace_layout:B1,browser_state:"optional_headless",desktop:!1,worker_version:e0,protocol_version:u3,...J.worker?.readiness?.["environment.install"]===!0&&F.includes("environment.install")?{environment_delivery:h6,[u6]:v6}:{},...J.worker?{[d6]:p6}:{},...J.worker?.handsBrowser?{[r6]:n6}:{},[c6]:s6,[i6]:a6,...v0(J.worker?.executionMode==="unsandboxed")?{[t6]:o6}:{},...v0(J.worker?.executionMode==="unsandboxed")&&F2()!==null?{[$7]:e6}:{},...v0(J.worker?.executionMode==="unsandboxed")&&p0()?{[Z7]:J7}:{}}:{},...X==="fs.export"?{cloud_source_version:m1,source_kinds:["workspace","attachment"],[h2]:m2}:{},...X==="fs.import"?{[h2]:m2}:{},...X===S4&&F2()!==null&&v0(J.worker?.executionMode==="unsandboxed")?{[y4]:T2}:{},...X==="tunnel.open"?{carried_jobs:V7}:{},...X==="jobs.control"?{[X7]:G7}:{},...X==="display.stream.v1"&&J.worker?.displayVideo?{[c7]:s7,[r7]:n7.join(","),[a7]:i7,[o7]:t7}:{},...X==="automation.call.v1"&&J.worker?.userChrome?{[U7]:!0}:{},...X==="automation.call.v1"&&J.worker?.cloudSessions?{[F7]:!0}:{}}])):{}}}}function $4($,J,Z,Q,K){let B=q7.safeParse(Q);return B.success&&K!==void 0&&K.device_id===$.deviceId&&B.data.device_id===$.deviceId&&B.data.root_id===J&&B.data.run_id===Z&&B.data.binding.kind===K.binding&&B.data.binding.target_revision===K.target_revision&&B.data.binding.root_grant_revision===K.root_grant_revision&&B.data.binding.target_generation===K.target_generation&&B.data.binding.target_fence_id===K.target_fence_id}async function YU($,J,Z,Q,K){if(J.capability!=="hands.connect"||Z.kind!==m6||!Q.operationEnvironment||!Q.acknowledgeOperationEnvironment)return!1;let B=Z.payload.snapshot_id;if(Z.payload.version!==1||typeof B!=="string"||Object.keys(Z.payload).length!==2)throw new H("environment_unavailable","Reason sent an invalid environment delivery.");let G=$.roots.find((F)=>F.id===J.root_id);if(!G)throw new H("root_not_granted","The Hands root is no longer granted.");let U=await Q.operationEnvironment($,J,B,K);if(!$4($,G.id,J.run_id,U.payload,U.authority)||U.payload.snapshot_id!==B)throw new H("environment_unavailable","The delivered environment does not match this Hands.");let Y=a3({root:u(G),operationId:J.operation_id,payload:U.payload});return await Q.acknowledgeOperationEnvironment($,J,{snapshot_id:Y.snapshot_id,installed_revision:Y.installed_revision,installed:!0},K),!0}async function WU($,J,Z,Q){if(J.capability!=="hands.connect"||Z.kind!==l6)return!1;let{version:K,run_id:B,target_generation:G,target_fence_id:U}=Z.payload;if(K!==1||Object.keys(Z.payload).length!==4||typeof B!=="string"||typeof G!=="number"||typeof U!=="string")throw new H("hands_rebind_unavailable","Reason sent an invalid Hands rebind.");let Y=$.roots.find((F)=>F.id===J.root_id);if(!Y)throw new H("root_not_granted","The Hands root is no longer granted.");return await O7({operationId:J.operation_id,root:u(Y),runId:B,targetGeneration:G,fenceId:U,...Q?{signal:Q}:{}}),!0}async function zU($,J,Z){if(J.capability!=="github.local.v1")return x6($,J,Z);try{let Q=await x6($,J,Z);if(Q.status==="succeeded"||n3(J.payload,Q.status,Q.error_code))return Q;return{status:Q.status,error_code:Q.status==="cancelled"?"operation_cancelled":"local_github_unavailable"}}catch{return{status:Z.signal.aborted?"cancelled":"failed",error_code:Z.signal.aborted?"operation_cancelled":"local_github_unavailable"}}}async function x6($,J,Z){if(V1.has(J.capability)&&!Z.worker)return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&!a1(J.capability,Z.worker))return{status:"failed",error_code:"capability_not_granted"};if(Z.worker&&Z.worker.readiness?.[J.capability]!==!0)return{status:"failed",error_code:"capability_unavailable"};if(J.local_github_authority){let X=r3.safeParse(J.local_github_authority);if(!X.success||X.data.deviceId!==$.deviceId||X.data.rootId!==J.root_id||X.data.runId!==J.run_id||X.data.userId!==J.owner?.user_id||!["github.local.v1","hands.connect","environment.install","jobs.control","preview.serve.v1"].includes(J.capability))return{status:"failed",error_code:"local_device_gh_capability_denied"}}let Q=O9[J.capability];if(!Q)return{status:"failed",error_code:"capability_unsupported"};if(Q.available&&!Q.available()&&!(["hands.connect","pty.start","preview.serve.v1"].includes(J.capability)&&Z.worker)&&!Z.runCommand&&!Z.runHandsRelay&&!Z.spawnFullControl&&!Z.runPtySession&&!(J.capability==="browser.pr-proof.v1"&&Z.proveMac))return{status:"failed",error_code:"capability_unavailable"};if(J.protocol_version!==2)return{status:"failed",error_code:"protocol_unsupported"};let K=$.roots.find((X)=>X.id===J.root_id);if(!K)return{status:"failed",error_code:"root_not_granted"};if((J.capability==="fs.export"||J.capability==="fs.import")&&c3(J.payload)&&(("source"in J.payload)||("source_version"in J.payload))){let X=Boolean(Z.worker||$.worker)&&Q1 in J.payload;if(J.capability!=="fs.export"||!X)return{status:"failed",error_code:"cloud_copy_source_unsupported"}}if(J.owner&&(J.owner.device_id!==$.deviceId||J.owner.organization_id!==$.orgId))return{status:"failed",error_code:"capability_not_granted"};if((J.capability==="tunnel.open"||J.capability==="tunnel.close")&&!J.owner)return{status:"failed",error_code:"preview_unavailable"};if(J.capability==="environment.install"&&!$4($,K.id,J.run_id,J.payload,J.authority))return{status:"failed",error_code:"environment_unavailable"};if(N9(Q).some((X)=>!K.permissions[X]))return{status:"failed",error_code:"permission_denied"};let B=0,G=async(X,W,z)=>{if(["environment.install","github.local.v1"].includes(J.capability)||J.capability==="inference.custom.v1"&&(X==="started"||X==="completed"))return;await Z.emit?.({sequence:B++,kind:X,capability:J.capability,data:W,...(X==="hands.reconnected"||J.capability==="inference.custom.v1")&&z?{deliverySignal:z}:{}})},U=J.capability==="hands.connect"||J.capability==="display.stream.v1"||J.capability==="simulator.stream.v1"||KK.has(J.capability)||J.capability==="pty.start",Y,F=async(X,W,z)=>{let N=Y;Y=void 0,await Promise.all([N,G(X,W,z)])};try{if(U)Y=G("started"),Y.catch(()=>{return});else await G("started");let X={...Z.proxy===void 0?{}:{loadProxy:()=>Z.proxy??null},...Z.handsLaunch?.takePrespawnedWorker?{takePrespawnedWorker:Z.handsLaunch.takePrespawnedWorker}:{},...Z.handsLaunch?.adoptSpawnedWorker?{adoptSpawnedWorker:Z.handsLaunch.adoptSpawnedWorker}:{}},W=await Q.execute({...Z.proveMac?{proveMac:()=>Z.proveMac(J,Z.signal,(z)=>G("pr-proof.started.v1",z))}:{},claim:J,worker:Z.worker,claimOwner:J.owner,claimAuthority:J.authority,organizationId:$.orgId,deviceId:$.deviceId,apiOrigin:$.apiOrigin,root:K,payload:GK(J.payload),runId:J.run_id,operationId:J.operation_id,attemptId:J.attempt_id,...Z.handsLaunch?{claimedAtMs:Z.handsLaunch.claimedAtMs}:{},signal:Z.signal,...Z.customEndpointCredential?{customEndpointCredential:Z.customEndpointCredential}:{},fetchImpl:Z.fetchImpl??fetch,relay:X,runCommand:Z.runCommand??zK,spawnFullControl:Z.spawnFullControl??e3,emit:U?F:G,runHandsRelay:Z.runHandsRelay??((z)=>h7(z,X)),runPtySession:Z.runPtySession??Q9});if(J.capability==="github.local.v1")y6.parse(W);if(!c3(W))throw new H("invalid_result","Operation result must be a JSON object.");if(Buffer.byteLength(JSON.stringify(W)??"null","utf8")>C0)throw new H("result_too_large","Operation result exceeds 256 KB.");return await(U?F:G)("completed",{ok:!0}),{status:"succeeded",result:W,error_code:null}}catch(X){let W=Z.signal.reason instanceof H&&g6.has(Z.signal.reason.code)?Z.signal.reason.code:X instanceof H&&g6.has(X.code)?X.code:null;if(Z.signal.aborted||W)return{status:"cancelled",...X instanceof t0?{result:{process_terminal_observation:X.observation}}:{},error_code:["environment.install","github.local.v1","inference.custom.v1"].includes(J.capability)?"operation_cancelled":W??"cancelled"};if(["fs.read","fs.write"].includes(J.capability)&&X instanceof Error&&"code"in X&&["EACCES","EPERM"].includes(String(X.code)))await G("permission.denied",{operation:J.capability==="fs.read"?"read":"write",provenance:"os_permission_unknown"});let z=J.capability==="inference.custom.v1"?X instanceof H&&Y7(X.code)?X.code:"custom_endpoint_unavailable":J.capability==="github.local.v1"?X instanceof E1&&n3(J.payload,"failed",X.code)?X.code:"local_github_unavailable":J.capability==="environment.install"?"environment_install_failed":X instanceof H&&QK.test(X.code)?X.code:"capability_failed",N=J.capability==="hands.connect"&&X instanceof y7?R7(X.expiryDiagnostic):null;return await G("completed",{ok:!1,error_code:z,...N?{expiry_diagnostic:N}:{}}),{status:"failed",error_code:z}}}
540
+ export{o9 as Ba,t9 as Ca,E4 as Da,NB as Ea,wB as Fa,uB as Ga,pB as Ha,a2 as Ia,vV as Ja,N0 as Ka,DJ as La,wJ as Ma,uV as Na,PJ as Oa,S0 as Pa,zZ as Qa,KK as Ra,H9 as Sa,D9 as Ta,YK as Ua,e3 as Va,zK as Wa,CK as Xa,wK as Ya,RK as Za,O9 as _a,qK as $a,gK as ab,EK as bb,kK as cb,SK as db,FU as eb,YU as fb,WU as gb,zU as hb};