@reason-machines/cli-linux-arm64-musl 0.2.364 → 0.2.367

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 (86) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-credentials-5phwd017.js +2 -0
  3. package/bin/vm-hands/api-v98h8tbt.js +2 -0
  4. package/bin/vm-hands/{ask-relay-7yw62yzw.js → ask-relay-99s9r5qx.js} +3 -3
  5. package/bin/vm-hands/connect-cli-9ef3cz0p.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-rzf5q89e.js +2 -0
  7. package/bin/vm-hands/desktop-account-2dtsbtf1.js +2 -0
  8. package/bin/vm-hands/{device-workspace-c05vq771.js → device-workspace-4zmq6vnb.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-wfv9csj2.js → hands-worker-source-s2p9t76m.js} +1 -1
  10. package/bin/vm-hands/{index-80ep9259.js → index-s2jxdd91.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-pbfhgaxc.js → install-receipt-z3jw7v66.js} +1 -1
  12. package/bin/vm-hands/local-automation-kykn3t5n.js +2 -0
  13. package/bin/vm-hands/local-capabilities-emphypye.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-4nz6kmyw.js +2 -0
  15. package/bin/vm-hands/local-display-mac-v9ev5jg4.js +2 -0
  16. package/bin/vm-hands/local-display-session-bgmnyfdn.js +2 -0
  17. package/bin/vm-hands/local-pty-session-c394saph.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-vkw66kvt.js → managed-runtime-8yf32zv3.js} +1 -1
  19. package/bin/vm-hands/{network-contract-zjq3w2n3.js → network-contract-mtrzq59w.js} +1 -1
  20. package/bin/vm-hands/package-08dpakav.js +2 -0
  21. package/bin/vm-hands/permissions-b8k7me17.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-aj1zwpk0.js → reason-hands-protocol-b8c4s9jx.js} +1 -1
  23. package/bin/vm-hands/serve-service-mqkz53dh.js +2 -0
  24. package/bin/vm-hands/{status-edb6wpzh.js → status-gwe4v7q7.js} +2 -2
  25. package/bin/vm-hands/version-bgxwc0n4.js +2 -0
  26. package/bin/vm-hands/vm-hands-entry-lite-0csqb5x1.js +3 -0
  27. package/bin/vm-hands/{vm-hands-entry-lite-0763vz5v.js → vm-hands-entry-lite-0q46m8na.js} +1 -1
  28. package/bin/vm-hands/{vm-hands-entry-lite-tbps80f1.js → vm-hands-entry-lite-0rwpp6hr.js} +2 -2
  29. package/bin/vm-hands/{vm-hands-entry-lite-zn303jrg.js → vm-hands-entry-lite-10sgx6g1.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-hw8vgsmm.js → vm-hands-entry-lite-1c1rxx8v.js} +1 -1
  31. package/bin/vm-hands/{vm-hands-entry-lite-vfn61qq2.js → vm-hands-entry-lite-1yn5vrs6.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-t50b2jyp.js → vm-hands-entry-lite-21856esq.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-vcm4389c.js → vm-hands-entry-lite-3ydgst12.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-1hv536wk.js → vm-hands-entry-lite-44f1pr87.js} +1 -1
  35. package/bin/vm-hands/{vm-hands-entry-lite-fr2k6eah.js → vm-hands-entry-lite-4p6v05yh.js} +2 -2
  36. package/bin/vm-hands/{vm-hands-entry-lite-62x9nv6n.js → vm-hands-entry-lite-4zg490k6.js} +3 -3
  37. package/bin/vm-hands/{vm-hands-entry-lite-w3cfhkv2.js → vm-hands-entry-lite-59napxaf.js} +2 -2
  38. package/bin/vm-hands/{vm-hands-entry-lite-0p3438xe.js → vm-hands-entry-lite-5cmafbnh.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-dqnhebfx.js → vm-hands-entry-lite-5jbnm3bm.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-avstvbbc.js → vm-hands-entry-lite-6gtpyxz7.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-cety9pka.js → vm-hands-entry-lite-6hcx1k08.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-t5kt2wff.js → vm-hands-entry-lite-7cqmn2f8.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-w3xhwb5h.js → vm-hands-entry-lite-c4mk1cwv.js} +1 -1
  44. package/bin/vm-hands/{vm-hands-entry-lite-v65nk88n.js → vm-hands-entry-lite-cgh7q3ss.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-vb4nyef6.js → vm-hands-entry-lite-d12rwjw1.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-kxtjkzzh.js → vm-hands-entry-lite-d2pbd9ky.js} +1 -1
  47. package/bin/vm-hands/{vm-hands-entry-lite-qy9xzp2m.js → vm-hands-entry-lite-dyyhxg5m.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-xj0p1ax7.js → vm-hands-entry-lite-ht2k3g94.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-7nk0873d.js → vm-hands-entry-lite-je3n2wnb.js} +1 -1
  50. package/bin/vm-hands/{vm-hands-entry-lite-cwf21py1.js → vm-hands-entry-lite-jmfb6mqq.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-xhr0m9r0.js → vm-hands-entry-lite-khnx8tzk.js} +1 -1
  52. package/bin/vm-hands/{vm-hands-entry-lite-5y2kfnv2.js → vm-hands-entry-lite-mq8bw5c9.js} +2 -2
  53. package/bin/vm-hands/{vm-hands-entry-lite-k7fkfytm.js → vm-hands-entry-lite-p30699xy.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-4xfs7y6w.js → vm-hands-entry-lite-peqmq6j6.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-tf1tkqkw.js → vm-hands-entry-lite-pp4mnye8.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-jjkkee8q.js → vm-hands-entry-lite-q01t7ykc.js} +2 -2
  57. package/bin/vm-hands/{vm-hands-entry-lite-e95w4ea8.js → vm-hands-entry-lite-qdb917g9.js} +2 -2
  58. package/bin/vm-hands/{vm-hands-entry-lite-6fvjbwqq.js → vm-hands-entry-lite-smhq7c4x.js} +1 -1
  59. package/bin/vm-hands/{vm-hands-entry-lite-p1nb6n3r.js → vm-hands-entry-lite-thskh018.js} +2 -2
  60. package/bin/vm-hands/{vm-hands-entry-lite-25rpwc1k.js → vm-hands-entry-lite-wmd391jw.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-pkjkgy7n.js → vm-hands-entry-lite-xy8xmzjw.js} +1 -1
  62. package/bin/vm-hands/{vm-hands-entry-lite-hfq6jjnh.js → vm-hands-entry-lite-zg9a3kv5.js} +1 -1
  63. package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
  64. package/bin/vm-hands/{vm-hands-executor-8s1c63v3.js → vm-hands-executor-frexe1jn.js} +1 -1
  65. package/bin/vm-hands/vm-hands-op-runner-aekwp51s.js +2 -0
  66. package/bin/vm-hands/{vm-hands-runtime-1342fjjh.js → vm-hands-runtime-90my200c.js} +3 -3
  67. package/bin/vm-hands/worker-sandbox-bjwykp0q.js +2 -0
  68. package/package.json +1 -1
  69. package/bin/vm-hands/api-credentials-vtpssnm1.js +0 -2
  70. package/bin/vm-hands/api-dvwzjwmh.js +0 -2
  71. package/bin/vm-hands/connect-cli-9v34nh0s.js +0 -2
  72. package/bin/vm-hands/custom-endpoint-device-8v87dhjx.js +0 -2
  73. package/bin/vm-hands/desktop-account-q57958y1.js +0 -2
  74. package/bin/vm-hands/local-automation-cbajffkk.js +0 -2
  75. package/bin/vm-hands/local-capabilities-q6g78bqk.js +0 -2
  76. package/bin/vm-hands/local-desktop-users-m7rexsex.js +0 -2
  77. package/bin/vm-hands/local-display-mac-9de01n3r.js +0 -2
  78. package/bin/vm-hands/local-display-session-1np79m1h.js +0 -2
  79. package/bin/vm-hands/local-pty-session-e7j0kj19.js +0 -2
  80. package/bin/vm-hands/package-44a3p8yk.js +0 -2
  81. package/bin/vm-hands/permissions-0apqx19h.js +0 -2
  82. package/bin/vm-hands/serve-service-g3410yvm.js +0 -2
  83. package/bin/vm-hands/version-q2x36es9.js +0 -2
  84. package/bin/vm-hands/vm-hands-entry-lite-jpkf3569.js +0 -3
  85. package/bin/vm-hands/vm-hands-op-runner-k2jpqmzw.js +0 -2
  86. package/bin/vm-hands/worker-sandbox-wb5thd4n.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Fb as J7,Hb as f4,Ib as b4,Nb as Q7,Ob as B7,Yb as y4,ac as V7,bc as G7,cc as n4,dc as r4,fc as U7,hb as A4,hc as O8,ic as h0,jb as L2,jc as v0,kb as _4,kc as J2,lb as T4,mb as P4,nb as s6,nc as X7,ob as n6,pb as S4,qb as r6,qc as j8,rb as f3,rc as h4,sb as a6,tb as i6,tc as W7,ub as o6,vb as t6,wb as k4,xb as e6,yb as $7}from"./vm-hands-entry-lite-v65nk88n.js";import{wc as F7,yc as N7,zc as H7}from"./vm-hands-entry-lite-cwf21py1.js";import{Ec as Z7}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as i0,Kc as o0,Rc as z0}from"./vm-hands-entry-lite-xhr0m9r0.js";import{Sc as j1,Tc as I1,Uc as A1,Vc as _1,Wc as L0}from"./vm-hands-entry-lite-f4gvypnx.js";import{Xc as V1}from"./vm-hands-entry-lite-wry37am5.js";import{Yc as Y7}from"./vm-hands-entry-lite-wej1p1ry.js";import{ad as V2,bd as G2,cd as l3,ed as s3,gd as c3,hd as n3,ld as r3,nd as d6}from"./vm-hands-entry-lite-jpkf3569.js";import{Fd as q7,td as Q2,wd as z7}from"./vm-hands-entry-lite-e95w4ea8.js";import{$e as S6,Ae as H0,Af as p8,Bf as u8,Cf as d8,De as d,Df as l8,Ee as h1,Ef as s8,Ff as c8,Gf as n8,He as g8,Je as m1,Le as D6,Me as M6,Ne as w6,Oe as L6,Pe as O6,Qe as j6,Re as I6,Se as A6,Te as _6,Ue as T6,Ve as P6,We as R6,Xe as z6,Ye as q6,Ze as E6,_e as g6,af as k6,bf as f6,cf as b6,ef as x6,ff as y6,gf as h6,hf as m6,if as v6,jf as p6,kf as u6,oe as P1,pe as R1,qe as S3,qf as S8,re as F2,rf as k8,se as C6,sf as f8,te as k3,tf as b8,ue as W4,uf as x8,ve as Y4,vf as y8,we as w0,xf as h8,yf as m8,zf as v8}from"./vm-hands-entry-lite-fr2k6eah.js";import{$f as e1,Mf as Q6,Qf as L5,Rf as v5,Xf as E7,_f as O5}from"./vm-hands-entry-lite-t5kt2wff.js";import{ag as A7,bg as _7,cg as T7,gg as P7,jg as R7}from"./vm-hands-entry-lite-qy9xzp2m.js";import{sg as x4,zg as K7}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Eg as Z2}from"./vm-hands-entry-lite-5y2kfnv2.js";import{Jg as R3,Wg as l6}from"./vm-hands-entry-lite-vcm4389c.js";import{Si as E1,Ti as c6,Ui as E4,Vi as g4}from"./vm-hands-entry-lite-tbps80f1.js";import{Xi as P3,Zi as Q1,dj as L8,ej as D4}from"./vm-hands-entry-lite-dqnhebfx.js";import{Aj as L7,Bj as O7,Dj as j7,Ej as I7,vj as C7,wj as D7,xj as M7,yj as w7}from"./vm-hands-entry-lite-avstvbbc.js";import{Pj as V}from"./vm-hands-entry-lite-k7fkfytm.js";import{Xj as C}from"./vm-hands-entry-lite-kxtjkzzh.js";import{bk as W8}from"./vm-hands-entry-lite-hw8vgsmm.js";import{request as i7}from"http";import{request as o7}from"https";import{lookup as t7}from"dns/promises";import{isIP as e7}from"net";async function $9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?o7:i7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:s3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var a3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),J9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function i3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(a3.has(Z))return"custom_endpoint_host_not_found";if(J9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=i3(Q,J+1);if(B)return B}return null}async function Z9($,J){let Z=i3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||e7(Q)!==0)return Z;let B;return await Promise.race([t7(Q).then(()=>!0,(G)=>!a3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?Z:"custom_endpoint_host_not_found"}function Q9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function B9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function o3($){$.signal.throwIfAborted();let J=n3.safeParse($.payload);if(!J.success)throw new C("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=r3.parse(await $.credential($.signal));if(!c3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new C("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,U=0,W=0,Y=Q9(Q.apiKey),X=B9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((L,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),L()},(P)=>{$.signal.removeEventListener("abort",I),M(P)})})},H=async(N)=>{if(G+=N.length,G>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=V2){if(W>=l3)throw new C("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+V2).toString("base64")})}};try{let N=await $9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new C("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new C("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let L={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=B.headers[M];if(typeof I==="string")L[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:L});for await(let M of B){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await H(X(I))}return await H(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof C)throw N;throw new C((B?null:await Z9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as t3}from"path";function K9($,J){return $===t3(J,".ara","workspace")||$===t3(J,".reason","workspace")}function e3($,J){let Z=$.filter((Q)=>K9(Q.path,J));return Z.length===1?Z[0].path:null}var V9=/^[a-f0-9]{64}$/;var U2=32,G9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!G9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!V9.test(B)||!L1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function U9($){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 X9($){return U9($)??$.email.toLowerCase()}function X2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?X9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),W9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...I1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...A1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,..._1.map(($)=>`/[^/]*${n0($)}$`)],$4=`function localGithubSandboxProfile(root, temporary) {
2
+ import{Fb as J7,Hb as f4,Ib as b4,Nb as Q7,Ob as B7,Yb as y4,ac as V7,bc as G7,cc as n4,dc as r4,fc as U7,hb as A4,hc as O8,ic as h0,jb as L2,jc as v0,kb as _4,kc as J2,lb as T4,mb as P4,nb as s6,nc as X7,ob as n6,pb as S4,qb as r6,qc as j8,rb as f3,rc as h4,sb as a6,tb as i6,tc as W7,ub as o6,vb as t6,wb as k4,xb as e6,yb as $7}from"./vm-hands-entry-lite-cgh7q3ss.js";import{wc as F7,yc as N7,zc as H7}from"./vm-hands-entry-lite-jmfb6mqq.js";import{Ec as Z7}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as i0,Kc as o0,Rc as z0}from"./vm-hands-entry-lite-khnx8tzk.js";import{Sc as j1,Tc as I1,Uc as A1,Vc as _1,Wc as L0}from"./vm-hands-entry-lite-f4gvypnx.js";import{Xc as V1}from"./vm-hands-entry-lite-wry37am5.js";import{Yc as Y7}from"./vm-hands-entry-lite-wej1p1ry.js";import{ad as V2,bd as G2,cd as l3,ed as s3,gd as c3,hd as n3,ld as r3,nd as d6}from"./vm-hands-entry-lite-0csqb5x1.js";import{Hd as q7,vd as Q2,yd as z7}from"./vm-hands-entry-lite-qdb917g9.js";import{$e as E6,Af as m8,Bf as v8,Ce as H0,Cf as p8,Df as u8,Ef as d8,Fe as d,Ff as l8,Ge as h1,Gf as s8,Hf as c8,If as n8,Je as g8,Le as m1,Ne as D6,Oe as M6,Pe as w6,Qe as L6,Re as O6,Se as j6,Te as I6,Ue as A6,Ve as _6,We as T6,Xe as P6,Ye as R6,Ze as z6,_e as q6,af as g6,bf as S6,cf as k6,df as f6,ef as b6,gf as x6,hf as y6,if as h6,jf as m6,kf as v6,lf as p6,mf as u6,qe as P1,re as R1,se as S3,sf as S8,te as F2,tf as k8,ue as C6,uf as f8,ve as k3,vf as b8,we as W4,wf as x8,xe as Y4,xf as y8,ye as w0,zf as h8}from"./vm-hands-entry-lite-4p6v05yh.js";import{Of as Q6,Sf as L5,Tf as v5,Zf as E7,ag as O5,bg as e1}from"./vm-hands-entry-lite-7cqmn2f8.js";import{cg as A7,dg as _7,eg as T7,ig as P7,lg as R7}from"./vm-hands-entry-lite-dyyhxg5m.js";import{Bg as K7,ug as x4}from"./vm-hands-entry-lite-ht2k3g94.js";import{Gg as Z2}from"./vm-hands-entry-lite-mq8bw5c9.js";import{Lg as R3,Yg as l6}from"./vm-hands-entry-lite-3ydgst12.js";import{Ui as E1,Vi as c6,Wi as E4,Xi as g4}from"./vm-hands-entry-lite-0rwpp6hr.js";import{$i as Q1,Zi as P3,fj as L8,gj as D4}from"./vm-hands-entry-lite-5jbnm3bm.js";import{Aj as w7,Cj as L7,Dj as O7,Fj as j7,Gj as I7,xj as C7,yj as D7,zj as M7}from"./vm-hands-entry-lite-6gtpyxz7.js";import{Rj as V}from"./vm-hands-entry-lite-p30699xy.js";import{Zj as C}from"./vm-hands-entry-lite-d2pbd9ky.js";import{dk as W8}from"./vm-hands-entry-lite-1c1rxx8v.js";import{request as i7}from"http";import{request as o7}from"https";import{lookup as t7}from"dns/promises";import{isIP as e7}from"net";async function $9($){let J=new URL($.url);return await new Promise((Z,Q)=>{let B=(J.protocol==="https:"?o7:i7)(J,{method:"POST",headers:{...$.headers,"accept-encoding":"identity"},signal:$.signal,timeout:s3},(K)=>Z({response:K,close:()=>{K.destroy(),B.destroy(),K.socket?.destroy()}}));B.once("error",Q),B.once("timeout",()=>B.destroy(Object.assign(Error("custom_endpoint_timeout"),{code:"ETIMEDOUT"}))),B.end($.body)})}var a3=new Set(["ENOTFOUND","EAI_AGAIN","EAI_NONAME","EAI_NODATA","EAI_FAIL","DNSException"]),J9=new Set(["ECONNREFUSED","ETIMEDOUT","ECONNRESET","EHOSTUNREACH","ENETUNREACH","EHOSTDOWN","ENETDOWN","EPIPE","ECONNABORTED","EADDRNOTAVAIL","ConnectionRefused","ConnectionClosed","ConnectionTimedOut","Timeout"]);function i3($,J=0){if(!$||typeof $!=="object"||J>3)return null;let Z=$.code;if(typeof Z==="string"){if(a3.has(Z))return"custom_endpoint_host_not_found";if(J9.has(Z))return"custom_endpoint_connection_failed";if(/^(?:ERR_TLS_|ERR_SSL_|CERT_|UNABLE_TO_(?:GET|VERIFY|DECRYPT)|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|HOSTNAME_MISMATCH|EPROTO$)/.test(Z))return"custom_endpoint_tls_failed"}for(let Q of[...$ instanceof AggregateError?$.errors:[],$.cause]){let B=i3(Q,J+1);if(B)return B}return null}async function Z9($,J){let Z=i3($),Q=new URL(J).hostname.replace(/^\[|\]$/g,"");if(Z!==null&&Z!=="custom_endpoint_connection_failed"||e7(Q)!==0)return Z;let B;return await Promise.race([t7(Q).then(()=>!0,(G)=>!a3.has(String(G?.code))),new Promise((G)=>{B=setTimeout(()=>G(!0),5000)})]).finally(()=>clearTimeout(B))?Z:"custom_endpoint_host_not_found"}function Q9($){for(let J=42;;J++){if(J===127)J=256;let Z=String.fromCodePoint(J);if(!$.includes(Z))return Z}}function B9($,J){let Z=Buffer.from($),Q=Buffer.from(J),B=new Uint32Array(Z.length);for(let G=1,U=0;G<Z.length;G++){while(U&&Z[G]!==Z[U])U=B[U-1];if(Z[G]===Z[U])U++;B[G]=U}let K=0;return(G,U=!1)=>{let W=Buffer.allocUnsafe(G.length*Q.length+K),Y=0;for(let X of G){while(K&&Z[K]!==X){let F=B[K-1];Y+=Z.copy(W,Y,0,K-F),K=F}if(Z[K]===X){if(K++,K===Z.length)Y+=Q.copy(W,Y),K=0}else W[Y++]=X}if(U)Y+=Z.copy(W,Y,0,K),K=0;return W.subarray(0,Y)}}async function o3($){$.signal.throwIfAborted();let J=n3.safeParse($.payload);if(!J.success)throw new C("custom_endpoint_invalid_request","Invalid local model request.");let Z=J.data,Q=r3.parse(await $.credential($.signal));if(!c3(Z,{baseUrl:Z.baseUrl,api:Q.api,execution:"device"}))throw new C("custom_endpoint_invalid_request","The request does not match the configured API.");$.signal.throwIfAborted();let B,K,G=0,U=0,W=0,Y=Q9(Q.apiKey),X=B9(Q.apiKey,Y),F=async(N,D)=>{$.signal.throwIfAborted(),await new Promise((L,M)=>{let I=()=>{$.signal.removeEventListener("abort",I),M($.signal.reason)};if($.signal.addEventListener("abort",I,{once:!0}),$.signal.aborted){I();return}Promise.resolve().then(()=>{return $.signal.throwIfAborted(),$.emit(N,D)}).then(()=>{$.signal.removeEventListener("abort",I),L()},(P)=>{$.signal.removeEventListener("abort",I),M(P)})})},H=async(N)=>{if(G+=N.length,G>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");for(let D=0;D<N.length;D+=V2){if(W>=l3)throw new C("custom_endpoint_response_too_large","Local model response exceeds the chunk limit.");await F(`custom_endpoint.chunk.${W++}`,{eof:!1,data:N.subarray(D,D+V2).toString("base64")})}};try{let N=await $9({url:Z.url,body:Z.body,signal:$.signal,headers:{...Z.headers,...Q.api==="anthropic-messages"?{"x-api-key":Q.apiKey}:{authorization:`Bearer ${Q.apiKey}`}}});B=N.response,K=N.close;let D=B.statusCode??500;if(D>=300&&D<400)throw new C("custom_endpoint_redirect_refused","Local model redirects are not followed.");if(B.headers["content-encoding"]&&B.headers["content-encoding"]!=="identity")throw new C("custom_endpoint_encoding_unsupported","The local server must honor identity encoding.");let L={};for(let M of["content-type","retry-after","x-request-id","request-id"]){let I=B.headers[M];if(typeof I==="string")L[M]=I.replaceAll(Q.apiKey,Y).slice(0,4096)}await F("custom_endpoint.headers",{status:D,statusText:(B.statusMessage??"").replaceAll(Q.apiKey,Y).slice(0,256),headers:L});for await(let M of B){$.signal.throwIfAborted();let I=Buffer.isBuffer(M)?M:Buffer.from(M);if(U+=I.length,U>G2)throw new C("custom_endpoint_response_too_large","Local model response exceeds the transport limit.");await H(X(I))}return await H(X(Buffer.alloc(0),!0)),await F(`custom_endpoint.chunk.${W}`,{eof:!0}),{bytes:G,chunks:W}}catch(N){if($.signal.throwIfAborted(),N instanceof C)throw N;throw new C((B?null:await Z9(N,Z.url))??"custom_endpoint_request_failed","The local model server could not complete the request.")}finally{K?.()}}import{join as t3}from"path";function K9($,J){return $===t3(J,".ara","workspace")||$===t3(J,".reason","workspace")}function e3($,J){let Z=$.filter((Q)=>K9(Q.path,J));return Z.length===1?Z[0].path:null}var V9=/^[a-f0-9]{64}$/;var U2=32,G9=/^\/[^\x00-\x1f\x7f\\]*$/;function L1($){if(typeof $!=="string"||$.length>4096||!G9.test($))return!1;if($==="/")return!0;return $.split("/").slice(1).every((J)=>J!==""&&J!=="."&&J!=="..")}function O1($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(!L1(J.home)||!Array.isArray(J.roots)||J.roots.length>U2)return;let Z=[];for(let Q of J.roots){if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let{path_fingerprint:B,path:K}=Q;if(typeof B!=="string"||!V9.test(B)||!L1(K))return;Z.push({path_fingerprint:B,path:K})}return{home:J.home,roots:Z}}function U9($){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 X9($){return U9($)??$.email.toLowerCase()}function X2($){let J=/^Co-authored-by:\s*([^<>\r\n]+) <([^<>\s]+)>$/i.exec($.trim());return J?X9({name:J[1],email:J[2]}):$.trim().toLowerCase()}var n0=($)=>$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/[a-z]/gi,(J)=>`[${J.toLowerCase()}${J.toUpperCase()}]`),W9=[...j1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...I1.map(($)=>`/(${$.map(n0).join("/")})(/|$)`),...[...A1].map(($)=>`/(${n0($)})$`),`/${n0(".env.")}[^/]*$`,..._1.map(($)=>`/[^/]*${n0($)}$`)],$4=`function localGithubSandboxProfile(root, temporary) {
3
3
  return ['(version 1)','(deny default)','(import "system.sb")','(allow process-exec process-fork)',
4
4
  '(allow file-read* (subpath "/bin") (subpath "/sbin") (subpath "/usr/bin") (subpath "/usr/sbin") (subpath "/usr/libexec") (subpath "/usr/share") (subpath "/private/var/select") (literal "/private/var/db/xcode_select_link"))',
5
5
  '(allow file-read-metadata (path-ancestors "/opt/homebrew/bin") (path-ancestors "/usr/local/bin") (path-ancestors "/Library/Developer/CommandLineTools"))',
@@ -34,7 +34,7 @@ Content-Length: 0\r
34
34
  \r
35
35
  `),s4(W,N,Y)})().catch(()=>W.destroy())}),await new Promise((U,W)=>{K.once("error",W),K.listen(0,"127.0.0.1",()=>U())});let{port:G}=K.address();return{url:`http://127.0.0.1:${G}`,close(){K.close();for(let U of Q)U.destroy()}}}import{createHash as E2,randomUUID as e9}from"crypto";import{closeSync as J1,constants as s,fchownSync as $$,fstatSync as q0,fsyncSync as J$,linkSync as Z$,mkdirSync as Q$,openSync as Y8,readSync as F8,unlinkSync as B$,writeSync as K$}from"fs";import{platform as U8}from"os";import{getSystemErrorName as V$}from"util";var o4={type:"string",format:"uuid"},J8=String.raw`^(?![\\/])(?![A-Za-z]:[\\/])(?!.*(?:^|[\\/])\.\.(?:[\\/]|$))(?!.*\u0000)(?=.*\S)[\s\S]+$`,g1={type:"string",minLength:1,maxLength:4096,pattern:J8},T2=V.string().min(1).max(4096).regex(new RegExp(J8)),S1={device_id:V.string().uuid(),root_id:V.string().uuid(),timeout_ms:V.number().int().min(1000).max(60000).optional()},k1={device_id:o4,root_id:o4,timeout_ms:{type:"integer",minimum:1000,maximum:60000}},XK={read:{schema:V.object({...S1,path:T2,offset:V.number().int().min(0).optional(),max_bytes:V.number().int().min(1).max(131072).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path"],properties:{...k1,path:g1,offset:{type:"integer",minimum:0},max_bytes:{type:"integer",minimum:1,maximum:131072}},additionalProperties:!1}},write:{schema:V.object({...S1,path:T2,content:V.string().max(131072),mode:V.enum(["overwrite","append"]).optional(),create_parents:V.boolean().optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","path","content"],properties:{...k1,path:g1,content:{type:"string",maxLength:131072},mode:{type:"string",enum:["overwrite","append"]},create_parents:{type:"boolean"}},additionalProperties:!1}},exec:{schema:V.object({...S1,command:V.string().min(1).max(16000),cwd:T2.optional(),mode:V.enum(["confined","host"]).optional()}).strict(),inputSchema:{type:"object",required:["device_id","root_id","command"],properties:{...k1,command:{type:"string",minLength:1,maxLength:16000},cwd:g1,mode:{type:"string",enum:["confined","host"],description:"Defaults to host: the existing permitted login shell with OS/account access, requiring execute and environment-discovery permission. Request confined explicitly for a scrubbed shell without network."}},additionalProperties:!1}}},Y0=1073741824,e0=600000,t4=String.raw`(?!\.{1,2}(?:/|(?![\s\S])))[^/\\\u0000]+`,Z8=String.raw`^(?![A-Za-z]:/)(?=[\s\S]*\S)${t4}(?:/${t4})*(?![\s\S])`,Q8=new RegExp(Z8);function B8($){return typeof $==="string"&&$.length>0&&$.length<=4096&&Q8.test($)}var P2=V.string().min(1).max(4096).regex(Q8),R2={...g1,pattern:Z8},K8=V.string().regex(/^[a-f0-9]{64}$/),V8=V.object({kind:V.literal("workspace"),path:P2}).strict(),i9=V.discriminatedUnion("kind",[V8,V.object({kind:V.literal("attachment"),attachment_id:V.string().min(1).max(120),sha256:K8}).strict()]),f1=1,$1="cloud_workspace_id",z2="cloud_workspace",q2=1,o9=V.discriminatedUnion("kind",[V8,V.object({kind:V.literal("attachment"),download_url:V.string().min(1).max(16384),size_bytes:V.number().int().min(0).max(Y0),sha256:K8}).strict()]),G8=V.object({source_version:V.literal(f1),source:o9,url:V.string().min(1).max(16384),transfer_cloud_scope:V.object({sandboxId:V.string().min(1).max(256),revision:V.number().int().nonnegative(),brainFence:V.string().uuid()}).strict().optional(),[$1]:V.string().min(1).max(160).optional()}).strict(),WK=V.object({ready:V.literal(!0),cloud_source_version:V.literal(f1),source_kinds:V.array(V.enum(["workspace","attachment"]))});var e4=V.object({...S1,timeout_ms:V.number().int().min(1000).max(e0).optional(),source_path:P2,destination_path:P2,idempotency_key:V.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/).optional()}).strict(),$8={type:"object",required:["device_id","root_id","source_path","destination_path"],properties:{...k1,timeout_ms:{type:"integer",minimum:1000,maximum:e0},source_path:R2,destination_path:R2,idempotency_key:{type:"string",minLength:1,maxLength:160,pattern:"^[A-Za-z0-9._:-]+$"}},additionalProperties:!1},t9={oneOf:[{type:"object",required:["kind","path"],properties:{kind:{type:"string",const:"workspace"},path:R2},additionalProperties:!1},{type:"object",required:["kind","attachment_id","sha256"],properties:{kind:{type:"string",const:"attachment"},attachment_id:{type:"string",minLength:1,maxLength:120},sha256:{type:"string",pattern:"^[a-f0-9]{64}$"}},additionalProperties:!1}]},YK=V.union([e4,e4.omit({source_path:!0}).extend({source:i9}).strict()]),FK={...$8,required:["device_id","root_id","destination_path"],properties:{...$8.properties,source:t9},oneOf:[{required:["source_path"],not:{required:["source"]}},{required:["source"],not:{required:["source_path"]}}]};var g2=65536;function u($){throw new C($,$)}function x1($){return typeof $==="object"&&$!==null&&"code"in $&&typeof $.code==="string"?$.code:void 0}function b1($,J,Z){if(J.throwIfAborted(),$ instanceof C||$ instanceof Error&&$.name==="AbortError")throw $;return u(Z)}function G$($,J,Z){let Q;switch(x1($)){case"ENOENT":Q=Z==="export"?"transfer_source_missing":"transfer_path_unavailable";break;case"EACCES":case"EPERM":case"EROFS":Q="transfer_permission_denied";break;case"ELOOP":case"ENOTDIR":Q="transfer_path_unsafe";break;case"EEXIST":Q="transfer_destination_exists";break;default:Q="transfer_path_unavailable"}return b1($,J,Q)}function U$($){if(typeof $!=="string"||$.length>16384)return u("transfer_url_invalid");let J;try{J=new URL($)}catch{return u("transfer_url_invalid")}if(J.protocol!=="https:"||J.username||J.password||J.hash)return u("transfer_url_invalid");return J.href}async function X$(){if(U8()==="linux")return{open:(U,W,Y,X=384)=>Y8(`/proc/self/fd/${U}/${W}`,Y,X),mkdir:(U,W)=>Q$(`/proc/self/fd/${U}/${W}`,{mode:448}),link:(U,W,Y)=>Z$(`/proc/self/fd/${U}/${W}`,`/proc/self/fd/${U}/${Y}`),unlink:(U,W)=>B$(`/proc/self/fd/${U}/${W}`),close:()=>{}};if(U8()!=="darwin")return u("transfer_platform_unsupported");let{dlopen:$,FFIType:J,ptr:Z,read:Q}=await import("bun:ffi"),B=$("/usr/lib/libSystem.B.dylib",{__error:{args:[],returns:J.ptr},openat:{args:[J.i32,J.ptr,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32,J.i32],returns:J.i32},mkdirat:{args:[J.i32,J.ptr,J.i32],returns:J.i32},linkat:{args:[J.i32,J.ptr,J.i32,J.ptr,J.i32],returns:J.i32},unlinkat:{args:[J.i32,J.ptr,J.i32],returns:J.i32}}),K=B.symbols.__error();if(K===null)return B.close(),u("transfer_path_unavailable");let G=(U)=>{if(U<0){let W=V$(-Q.i32(K));throw Object.assign(Error("transfer_path_unavailable"),{code:W})}return U};return{open:(U,W,Y,X=384)=>G(B.symbols.openat(U,Z(Buffer.from(`${W}\x00`)),Y,X,0,0,0,0,X)),mkdir:(U,W)=>{G(B.symbols.mkdirat(U,Z(Buffer.from(`${W}\x00`)),448))},link:(U,W,Y)=>{G(B.symbols.linkat(U,Z(Buffer.from(`${W}\x00`)),U,Z(Buffer.from(`${Y}\x00`)),0))},unlink:(U,W)=>{G(B.symbols.unlinkat(U,Z(Buffer.from(`${W}\x00`)),0))},close:()=>B.close()}}function N8($,J){let Z=q0($),Q=q0(J);if(Q.uid!==Z.uid||Q.gid!==Z.gid)$$(J,Z.uid,Z.gid)}function W$($,J,Z,Q){if(!B8(Z))return u("transfer_path_invalid");let B=Z.split("/"),K=Y8(J,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW);try{for(let G of B.slice(0,-1)){let U;try{U=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW)}catch(W){if(!Q||x1(W)!=="ENOENT")throw W;try{$.mkdir(K,G)}catch(Y){if(x1(Y)!=="EEXIST")throw Y}U=$.open(K,G,s.O_RDONLY|s.O_DIRECTORY|s.O_NOFOLLOW),N8(K,U)}J1(K),K=U}return{fd:K,leaf:B.at(-1)}}catch(G){throw J1(K),G}}function X8($,J){let Z=q0($,{bigint:!0});if(!Z.isFile()||Z.size>Y0)return u("transfer_file_invalid");let Q=E2("sha256"),B=Buffer.alloc(g2),K=0;while(!0){J.throwIfAborted();let U=F8($,B,0,B.length,K);if(!U)break;if(K+=U,K>Y0)return u("transfer_size_exceeded");Q.update(B.subarray(0,U))}let G=q0($,{bigint:!0});if(BigInt(K)!==Z.size||G.size!==Z.size||G.mtimeNs!==Z.mtimeNs||G.ctimeNs!==Z.ctimeNs)return u("transfer_source_changed");return{size_bytes:K,sha256:Q.digest("hex")}}async function E0($){$.signal.throwIfAborted();try{let J=U$($.payload.url),Z=await X$(),Q,B,K;try{if(Q=W$(Z,$.root,$.path,$.direction==="import"),$.direction==="export"){B=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK);let H=q0(B,{bigint:!0});if(!H.isFile()||H.size>Y0)return u("transfer_file_invalid");let N=E2("sha256"),D=0,L=B,M,I=new ReadableStream({pull(v){try{$.signal.throwIfAborted();let O=Buffer.alloc(g2),E=F8(L,O,0,O.length,D);if(!E){v.close();return}if(D+=E,D>H.size)return u("transfer_source_changed");N.update(O.subarray(0,E)),v.enqueue(O.subarray(0,E))}catch(O){throw M=O,O}}});try{let v=await($.fetchImpl??fetch)(J,Object.assign({method:"PUT",body:I,redirect:"error",signal:$.signal,headers:{"content-type":"application/octet-stream","content-length":String(H.size)}},{duplex:"half"}));if(M!==void 0)throw M;if(!v.ok)return u("transfer_upload_failed");await v.body?.cancel()}catch(v){if(M!==void 0)throw M;return b1(v,$.signal,"transfer_upload_failed")}let P=q0(B,{bigint:!0});if(BigInt(D)!==H.size||P.size!==H.size||P.mtimeNs!==H.mtimeNs||P.ctimeNs!==H.ctimeNs)return u("transfer_source_changed");let j=N.digest("hex"),_=X8(B,$.signal);if(_.size_bytes!==D||_.sha256!==j)return u("transfer_source_changed");return{size_bytes:D,sha256:j,outcome:"copied"}}let G=$.payload.size_bytes,U=$.payload.sha256;if(typeof G!=="number"||!Number.isSafeInteger(G)||G<0||G>Y0||typeof U!=="string"||!/^[a-f0-9]{64}$/.test(U))return u("transfer_receipt_invalid");let W;try{W=Z.open(Q.fd,Q.leaf,s.O_RDONLY|s.O_NOFOLLOW|s.O_NONBLOCK)}catch(H){if(x1(H)!=="ENOENT")throw H}if(W!==void 0){try{let H=X8(W,$.signal);if(H.size_bytes===G&&H.sha256===U)return{...H,outcome:"already_present"}}finally{J1(W)}return u("transfer_destination_exists")}K=`.reason-copy-${e9()}`,B=Z.open(Q.fd,K,s.O_CREAT|s.O_EXCL|s.O_WRONLY|s.O_NOFOLLOW,384),N8(Q.fd,B);let Y;try{let H=await($.fetchImpl??fetch)(J,{redirect:"error",signal:$.signal});if(!H.ok||!H.body)return u("transfer_download_failed");Y=H.body.getReader()}catch(H){return b1(H,$.signal,"transfer_download_failed")}let X=E2("sha256"),F=0;try{while(!0){$.signal.throwIfAborted();let H=await Y.read().catch((N)=>b1(N,$.signal,"transfer_download_failed"));if(H.done)break;if(F+=H.value.length,F>G)return u("transfer_size_mismatch");X.update(H.value);for(let N=0;N<H.value.length;)$.signal.throwIfAborted(),N+=K$(B,H.value,N,Math.min(g2,H.value.length-N))}}finally{await Y.cancel().catch(()=>{})}if(F!==G||X.digest("hex")!==U)return u("transfer_hash_mismatch");return J$(B),await $.beforeCommit?.(),$.signal.throwIfAborted(),Z.link(Q.fd,K,Q.leaf),{size_bytes:G,sha256:U,outcome:"copied"}}finally{try{if(B!==void 0)J1(B)}finally{try{if(Q){if(K)try{Z.unlink(Q.fd,K)}catch{}J1(Q.fd)}}finally{Z.close()}}}}catch(J){return G$(J,$.signal,$.direction)}}import{spawn as F$}from"child_process";import{mkdtempSync as N$,rmSync as H$,writeFileSync as C$}from"fs";import{constants as D$,platform as M$,tmpdir as w$}from"os";import{join as M8}from"path";import{gunzipSync as Y$,gzipSync as IK}from"zlib";var C8=900000,_K=C8+60000,Z1=49152,H8=($)=>V.string().min(1).max($).regex(/^[A-Za-z0-9+/]+=*$/),D8=V.object({version:V.literal(1),script_gzip:H8(163840),stdin_gzip:H8(65536),cwd:V.string().min(1).max(4096).startsWith("/"),env:V.record(V.string().regex(/^[A-Z_][A-Z0-9_]{0,63}$/),V.string().max(4096)).refine(($)=>Object.keys($).length<=16,"too many variables"),timeout_ms:V.number().int().min(1000).max(C8)}).strict(),S2=V.string().max(Z1+256),TK=V.object({exit_code:V.number().int().min(0).max(255),stdout:S2,stderr:S2,combined:S2.optional()}).strict();function k2($){return Y$(Buffer.from($,"base64")).toString("utf8")}var L$="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",O$=["RUSTUP_HOME","TZ","LC_ALL"],j$=2000,I$=100;function b2(){return M$()==="linux"&&process.geteuid?.()===0}function f2($){let J=Math.floor($/2),Z=[],Q=0,B=Buffer.alloc(0),K=0;return{push(G){K+=G.length;let U=G;if(Q<J){let W=U.subarray(0,J-Q);Z.push(W),Q+=W.length,U=U.subarray(W.length)}if(U.length)B=Buffer.concat([B,U]).subarray(-J)},text(){let G=K-Q-B.length;return Buffer.concat(Z).toString("utf8")+(G>0?`
36
36
  [reason: ${G} bytes of output omitted]
37
- `:"")+B.toString("utf8")}}}async function w8($,J){if(!b2())throw new C("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new C("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=k2(Q.script_gzip),K=k2(Q.stdin_gzip)}catch{throw new C("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=N$(M8(w$(),"reason-workspace-setup-"));try{let U=M8(G,"setup.sh");C$(U,B,{mode:384});let W={PATH:L$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let _ of O$)if(process.env[_])W[_]=process.env[_];Object.assign(W,Q.env);let Y=F$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=f2(Z1),F=f2(Z1),H=f2(Z1);Y.stdout.on("data",(_)=>{X.push(_),H.push(_)}),Y.stderr.on("data",(_)=>{F.push(_),H.push(_)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(_)=>{try{if(Y.pid)process.kill(-Y.pid,_)}catch{}},D=!1,L,M=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),j$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let P=await new Promise((_,v)=>{Y.once("error",()=>v(new C("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(O,E)=>_({code:O,signal:E}))}).finally(()=>{clearTimeout(I),clearTimeout(L),J.removeEventListener("abort",M)});await new Promise((_)=>{let v=setTimeout(_,I$);Y.once("close",()=>{clearTimeout(v),_()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:P.signal?128+(D$.signals[P.signal]??0):P.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:H.text()}:{}}}finally{H$(G,{recursive:!0,force:!0})}}import{chmodSync as A$,mkdtempSync as _$,realpathSync as I8,rmSync as T$}from"fs";import{tmpdir as P$}from"os";import{dirname as R$,join as x2,sep as z$}from"path";function y2($){return j8($,O8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>R$(L8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(x2($,B));break}catch{}if(Q===void 0)throw new C("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${z$}`))throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function _8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=y2($.runtimeRoot);if(L0(Q)||L0(x2(Q,J.path)))throw new C("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=_$(x2(P$(),`reason-cloud-copy-${process.pid}-`));try{A$(Z,448);let Q=I8(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 B=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new C("transfer_source_changed","The verified attachment changed before export.");return B}finally{T$(Z,{recursive:!0,force:!0})}}import{constants as _0}from"fs";import{closeSync as g7,existsSync as G0,fstatSync as S7,lstatSync as k7,mkdirSync as VQ,mkdtempSync as GQ,openSync as f7,readSync as UQ,realpathSync as U0,rmSync as XQ,statSync as D1,writeSync as WQ}from"fs";import{homedir as N1,platform as n,tmpdir as YQ}from"os";import{dirname as H1,isAbsolute as FQ,join as b7,relative as z3,resolve as NQ,sep as HQ}from"path";import{spawn as CQ}from"child_process";import{createHash as k$,randomBytes as f$}from"crypto";var h2=30000,q$=1800000,E$=5000,y1=30000,g$=m1+15000,T8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,S$=[/^\/app\/local-runtime\/operations\/claim$/,T8];class m2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(S$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},g$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(E$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(q$,h2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(h1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+h2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[B,K]of Q.pending){if(!T8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(h2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var p2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function oK($,J={}){let Z=b$($),Q=J.rootPathsSupported===!0?O1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((B)=>/^[a-f0-9]{64}$/.test(B))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function b$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function x$($){return $===408||$===429||$===500||$===502||$===503||$===504}function y$($){if($ instanceof F0)return!1;if($ instanceof v1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function h$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function m$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function tK($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return k$("sha256").update($??"").digest("hex")}function v$($){return S8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function z8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var p$=20000,u$=1e4,q8=[2000,4000],d$=30000,l$=15000;function E8($){return $?{keepalive:!1}:{}}class v2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class s${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=k8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??q8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof v2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new v2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return f8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=p$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,q8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=u$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=R8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>f$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(v$({method:$,route:J,timestamp:B,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!g8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new m2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&P8(J.body)>H0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??m$,W=this.sessionFor($,J.device),Y=Math.max(d$,(J.holdMs??0)+l$),X={fresh:!1},F;for(let H=0;H<G;H+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,L=setTimeout(()=>D.abort(new v1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let I=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&H===0,H===0?J.issuedChallenge:void 0,X),P=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...I,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(X.fresh),signal:M});return await this.parseResponse(P)}catch(I){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw I}finally{clearTimeout(L)}}catch(N){if(F=N,N instanceof v1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),L=N instanceof F0&&x$(N.status),M=y$(N),I=J.transientRetryOwner!=="caller"&&(L||M);if((D||I)&&H+1<G){let P=D?0:h$(H,N,this.proofOptions.retryBaseDelayMs??500);if(P>0)await U(P,J.signal);continue}if(D&&H+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return b8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return x8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return y8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return h8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return m8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return v8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});u8(Q)}async localSubscription($,J,Z){return p8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!z8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return d8(K,p2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return l8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!z8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return s8(Q)}async completeOperation($,J,Z,Q){let B={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(P8(B)>H0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return n8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-8v87dhjx.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let B=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return c8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var c$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function p1($,J){if(c$.has($))return!1;if(B1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||B1.has($)))return!1;return!0}import{accessSync as n$,constants as r$,existsSync as a$,statSync as i$}from"fs";import{basename as o$,isAbsolute as t$}from"path";var K1=["-lic"],e$="/bin/zsh",$J=new Set(["zsh","bash"]),r8=20000,u2=60000,JJ=65536,ZJ=64,QJ=8192,BJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),KJ=["DYLD_","LD_"];function VJ($){let J=$.toUpperCase();return BJ.has(J)||KJ.some((Z)=>J.startsWith(Z))}function a8($=process.env){return!0}function GJ($){if(!t$($)||$.includes("\x00"))return!1;if(!$J.has(o$($)))return!1;try{if(!i$($).isFile())return!1;return n$($,r$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&GJ(J))return J;return e$}function d2($=process.env){return a8($)&&a$(g0($))}function l2($=process.env){if(!a8($))throw new C("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function s2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>JJ)throw new C("invalid_payload","command is missing or too large.");return $}function c2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new C("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>ZJ)throw new C("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>QJ)throw new C("invalid_payload","env entry is invalid or too large.");if(VJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function i8($){let J=$.processEnv??process.env;if(l2(J),$.signal.aborted)throw new C("cancelled","Operation was cancelled.");let Z=s2($.command),Q=g0(J),{forwarded:B,ignored:K}=c2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function o8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:u2}}import{readFile as UJ,readdir as XJ,readlink as WJ,realpath as YJ}from"fs/promises";import{basename as FJ,relative as NJ,sep as HJ}from"path";var O0="/proc",CJ=250,t8=500,DJ=50,MJ=250,wJ=1024,e8=4096,LJ=1,OJ=3,$5=9,jJ="0A",IJ=/^socket:\[(\d+)\]$/,n2={readDirectory:($)=>XJ($),readLink:($)=>WJ($),readTextFile:($)=>UJ($,"utf8"),realPath:($)=>YJ($)};function Z5($,J){return J===$||J.startsWith(`${$}${HJ}`)}function AJ($,J){return NJ($,J)||"."}async function Q5($){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 B5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,e8).split(`
37
+ `:"")+B.toString("utf8")}}}async function w8($,J){if(!b2())throw new C("workspace_setup_requires_root","Workspace setup runs only on a root Linux worker.");let Z=D8.safeParse($);if(!Z.success)throw new C("invalid_request","Reason sent an invalid workspace setup.");let Q=Z.data,B,K;try{B=k2(Q.script_gzip),K=k2(Q.stdin_gzip)}catch{throw new C("invalid_request","Reason sent an unreadable workspace setup.")}J.throwIfAborted();let G=N$(M8(w$(),"reason-workspace-setup-"));try{let U=M8(G,"setup.sh");C$(U,B,{mode:384});let W={PATH:L$,LANG:"C.UTF-8",HOME:"/root",USER:"root",LOGNAME:"root",SHELL:"/bin/bash",TMPDIR:"/tmp"};for(let _ of O$)if(process.env[_])W[_]=process.env[_];Object.assign(W,Q.env);let Y=F$("/bin/bash",[U],{cwd:Q.cwd,env:W,detached:!0,stdio:["pipe","pipe","pipe"]}),X=f2(Z1),F=f2(Z1),H=f2(Z1);Y.stdout.on("data",(_)=>{X.push(_),H.push(_)}),Y.stderr.on("data",(_)=>{F.push(_),H.push(_)}),Y.stdin.on("error",()=>{}),Y.stdin.end(K);let N=(_)=>{try{if(Y.pid)process.kill(-Y.pid,_)}catch{}},D=!1,L,M=()=>{N("SIGTERM"),L??=setTimeout(()=>N("SIGKILL"),j$)},I=setTimeout(()=>{D=!0,M()},Q.timeout_ms);J.addEventListener("abort",M,{once:!0});let P=await new Promise((_,v)=>{Y.once("error",()=>v(new C("workspace_setup_start_failed","The workspace setup did not start."))),Y.once("exit",(O,E)=>_({code:O,signal:E}))}).finally(()=>{clearTimeout(I),clearTimeout(L),J.removeEventListener("abort",M)});await new Promise((_)=>{let v=setTimeout(_,I$);Y.once("close",()=>{clearTimeout(v),_()})}),Y.stdout.destroy(),Y.stderr.destroy(),J.throwIfAborted();let j=D?124:P.signal?128+(D$.signals[P.signal]??0):P.code??1;return{exit_code:Math.min(255,j),stdout:X.text(),stderr:F.text(),...j!==0?{combined:H.text()}:{}}}finally{H$(G,{recursive:!0,force:!0})}}import{chmodSync as A$,mkdtempSync as _$,realpathSync as I8,rmSync as T$}from"fs";import{tmpdir as P$}from"os";import{dirname as R$,join as x2,sep as z$}from"path";function y2($){return j8($,O8($)!==null).repoPath}function A8($,J){let Z;try{if(typeof J!=="string")throw Error("invalid");Z=[Q1,void 0].map((B)=>R$(L8({kind:"managed",workspaceId:J,...B?{layout:B}:{}})))}catch{throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is invalid.")}let Q;for(let B of Z)try{Q=I8(x2($,B));break}catch{}if(Q===void 0)throw new C("cloud_copy_workspace_unavailable","The Session workspace is not on this computer.");if(!Q.startsWith(`${$}${z$}`))throw new C("cloud_copy_workspace_invalid","The Cloud copy workspace is outside this worker's root.");return Q}async function _8($){$.signal.throwIfAborted();let J=$.source;if(J.kind==="workspace"){let Q=y2($.runtimeRoot);if(L0(Q)||L0(x2(Q,J.path)))throw new C("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=_$(x2(P$(),`reason-cloud-copy-${process.pid}-`));try{A$(Z,448);let Q=I8(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 B=await E0({direction:"export",root:Q,path:"source",payload:{url:$.url},signal:$.signal,fetchImpl:$.fetchImpl});if(B.size_bytes!==J.size_bytes||B.sha256!==J.sha256)throw new C("transfer_source_changed","The verified attachment changed before export.");return B}finally{T$(Z,{recursive:!0,force:!0})}}import{constants as _0}from"fs";import{closeSync as g7,existsSync as G0,fstatSync as S7,lstatSync as k7,mkdirSync as VQ,mkdtempSync as GQ,openSync as f7,readSync as UQ,realpathSync as U0,rmSync as XQ,statSync as D1,writeSync as WQ}from"fs";import{homedir as N1,platform as n,tmpdir as YQ}from"os";import{dirname as H1,isAbsolute as FQ,join as b7,relative as z3,resolve as NQ,sep as HQ}from"path";import{spawn as CQ}from"child_process";import{createHash as k$,randomBytes as f$}from"crypto";var h2=30000,q$=1800000,E$=5000,y1=30000,g$=m1+15000,T8=/^\/app\/local-runtime\/operations\/[0-9a-fA-F-]{36}\/heartbeat$/,S$=[/^\/app\/local-runtime\/operations\/claim$/,T8];class m2{options;current=null;connecting=null;retryAt=0;failures=0;nextId=0;closed=!1;reconnectTimer=null;constructor($){this.options=$}now(){return(this.options.now??Date.now)()}jitter($){return Math.floor((this.options.random??Math.random)()*$)}async request($,J,Z){Z?.throwIfAborted();let Q=this.current;if(!Q)return this.connect(),null;if(Q.pending.size>=Q.maxInFlight)return null;let B=String(++this.nextId),K=new Promise((W)=>Q.pending.set(B,{path:$,resolve:W}));if(!this.send(Q,{t:"req",id:B,path:$,body:J}))return Q.pending.delete(B),null;let G;if(S$.some((W)=>W.test($)))G=setTimeout(()=>{if(Q.pending.has(B))this.drop(Q)},g$);else{let W=()=>{if(!Q.pending.has(B))return;let Y=this.now()-Q.lastFrameAt;if(Y>=y1)this.drop(Q);else G=setTimeout(W,y1-Y)};G=setTimeout(W,y1)}if(K.finally(()=>clearTimeout(G)),!Z)return await K;let U=new Promise((W,Y)=>{let X=()=>{if(Q.pending.delete(B),clearTimeout(G),this.send(Q,{t:"abort",id:B}),this.now()-Q.lastFrameAt>y1)this.drop(Q);Y(Z.reason)};if(Z.aborted)X();else Z.addEventListener("abort",X,{once:!0}),K.finally(()=>Z.removeEventListener("abort",X))});return await Promise.race([K,U])}cadence(){return this.current?.cadence??null}close(){if(this.closed=!0,this.reconnectTimer)clearTimeout(this.reconnectTimer);for(let $ of[this.current,this.connecting])if($)this.drop($)}send($,J){try{return $.socket.send(JSON.stringify(J)),!0}catch{return this.drop($),!1}}drop($){if($.dropped)return;$.dropped=!0,this.settle($);try{$.socket.close()}catch{}}settle($){for(let J of $.pending.values())J.resolve(null);if($.pending.clear(),this.current===$)this.current=null,this.retryAt=Math.max(this.retryAt,this.now()+this.jitter(E$));if(this.connecting===$){this.connecting=null,this.failures+=1;let J=Math.min(q$,h2*2**Math.min(this.failures-1,10));this.retryAt=Math.max(this.retryAt,this.now()+J/2+this.jitter(J/2))}}connect(){if(this.closed||this.connecting||this.now()<this.retryAt)return;let $=this.options.WebSocket??globalThis.WebSocket;if(!$){this.retryAt=Number.POSITIVE_INFINITY;return}let J=new URL(h1,this.options.apiOrigin);J.protocol=J.protocol==="https:"?"wss:":"ws:",J.searchParams.set("device_id",this.options.deviceId);let Z;try{Z=new $(J.toString())}catch{this.failures+=1,this.retryAt=this.now()+h2;return}let Q={socket:Z,pending:new Map,maxInFlight:0,cadence:null,lastFrameAt:this.now(),dropped:!1};this.connecting=Q,Z.onmessage=(B)=>this.receive(Q,B.data),Z.onclose=()=>this.settle(Q),Z.onerror=()=>this.settle(Q)}receive($,J){if(typeof J!=="string")return;let Z;try{Z=JSON.parse(J)}catch{return}if($.lastFrameAt=this.now(),Z.t==="res"){let Q=$.pending.get(Z.id);$.pending.delete(Z.id),Q?.resolve({status:Z.status,body:Z.body,retryAfter:Z.retry_after??null});return}if(Z.t==="challenge"&&this.connecting===$){let Q;try{Q=this.options.signHello(Z.challenge)}catch{this.drop($);return}this.send($,{t:"hello",...Q});return}if(Z.t==="ready"&&this.connecting===$){this.connecting=null,this.failures=0,$.maxInFlight=Math.max(1,Math.min(Z.max_in_flight,1000)),$.cadence=Z.cadence??null;let Q=this.current;if(this.current=$,Q){for(let[B,K]of Q.pending){if(!T8.test(K.path))continue;Q.pending.delete(B),this.send(Q,{t:"abort",id:B}),K.resolve(null)}if(Q.pending.size===0)this.drop(Q)}return}if(Z.t==="fallback"){this.retryAt=this.now()+Math.max(h2,Math.min(Z.retry_after_ms,86400000)),this.drop($);return}if(Z.t==="reconnect"&&this.current===$&&!this.reconnectTimer)this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.retryAt=0,this.connect()},Math.max(0,Math.min(Z.after_ms,60000)))}}var p2=["fs.read","fs.write","fs.export","fs.import","exec.run","exec.full","process.run.v1","process.full.v1","preview.serve.v1","pty.start","git.run","process.list","ports.list","computer.use","browser.use","browser.recording.v1","browser.pr-proof.v1","hands.connect","jobs.control","environment.install","github.local.v1","inference.custom.v1","display.stream.v1","automation.call.v1","simulator.call.v1","simulator.stream.v1","tunnel.open","tunnel.close","workspace.setup.v1"];function oK($,J={}){let Z=b$($),Q=J.rootPathsSupported===!0?O1($.root_paths):void 0;return{supported_operations:[...$.supported_operations],...J.accountRootMetadataSupported===!0&&typeof $.account_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.account_root_fingerprint)?{account_root_fingerprint:$.account_root_fingerprint}:{},...J.workspaceRootMetadataSupported===!0&&typeof $.workspace_root_fingerprint==="string"&&/^[a-f0-9]{64}$/.test($.workspace_root_fingerprint)?{workspace_root_fingerprint:$.workspace_root_fingerprint}:{},...J.accountRootPathSupported===!0&&typeof $.account_root_path==="string"&&$.account_root_path.startsWith("/")&&$.account_root_path.length<=4096?{account_root_path:$.account_root_path}:{},...J.homeContainedRootsSupported===!0&&Array.isArray($.home_contained_root_fingerprints)&&$.home_contained_root_fingerprints.length<=32&&$.home_contained_root_fingerprints.every((B)=>/^[a-f0-9]{64}$/.test(B))?{home_contained_root_fingerprints:[...$.home_contained_root_fingerprints]}:{},...Q?{root_paths:Q}:{},...Object.keys(Z).length?{operation_constraints:Z}:{},...$.hands_worker_artifact_sha256&&$.hands_worker_entrypoint?{hands_worker_artifact_sha256:$.hands_worker_artifact_sha256,hands_worker_entrypoint:$.hands_worker_entrypoint}:{},...$.hands_slots!==void 0?{hands_slots:$.hands_slots}:{}}}function b$($){let J=(Q)=>Q===null||typeof Q==="boolean"||typeof Q==="number"&&Number.isFinite(Q)||typeof Q==="string"&&Q.length<=512,Z={};for(let Q of $.supported_operations){let B=$.operation_constraints?.[Q];if(!B||typeof B!=="object"||Array.isArray(B))continue;if(!("ready"in B)||typeof B.ready!=="boolean")continue;let K={};for(let[G,U]of Object.entries(B).slice(0,32)){if(!G.length||G.length>64||["__proto__","constructor","prototype"].includes(G))continue;if(J(U)||Array.isArray(U)&&U.length<=64&&U.every(J))K[G]=U}if(Object.keys(K).length)Z[Q]=K}return Z}class F0 extends Error{status;code;retryAfter;constructor($,J,Z,Q=null){super(Z);this.status=$;this.code=J;this.retryAfter=Q;this.name="LocalRuntimeHttpError"}}class v1 extends Error{timeoutMs;constructor($){super(`Reason Device request did not answer within ${$}ms.`);this.timeoutMs=$;this.name="LocalRuntimeRequestTimeoutError"}}function x$($){return $===408||$===429||$===500||$===502||$===503||$===504}function y$($){if($ instanceof F0)return!1;if($ instanceof v1)return!0;if(!($ instanceof Error))return!1;if($.name==="AbortError")return!1;if($ instanceof TypeError&&$.message.toLowerCase().includes("fetch failed"))return!0;for(let J of[$,$.cause])if(J&&typeof J==="object"&&"code"in J){let Z=String(J.code);if(["ECONNRESET","ECONNREFUSED","ETIMEDOUT","EHOSTUNREACH","ENOTFOUND","EAI_AGAIN","ConnectionClosed","ConnectionRefused","UND_ERR_SOCKET","UND_ERR_CONNECT_TIMEOUT"].includes(Z))return!0}return!1}function h$($,J,Z=500){if(J instanceof F0&&J.retryAfter){let K=parseFloat(J.retryAfter);if(Number.isFinite(K)&&K>0)return Math.min(K*1000,1e4)}let Q=Z*2**$,B=Math.floor(Math.random()*200);return Math.min(Q+B,5000)}async function m$($,J){if(J?.aborted)throw J.reason??new DOMException("The operation was aborted.","AbortError");await new Promise((Z,Q)=>{let B=()=>{clearTimeout(K),Q(J?.reason??new DOMException("The operation was aborted.","AbortError"))},K=setTimeout(()=>{J?.removeEventListener("abort",B),Z()},$);J?.addEventListener("abort",B,{once:!0})})}function tK($){return $ instanceof F0&&$.status===401&&($.code==="device_revoked"||$.code==="invalid_device_credential")}function P8($){return Buffer.byteLength(JSON.stringify($)??"null","utf8")}function R8($){return k$("sha256").update($??"").digest("hex")}function v$($){return S8({method:$.method,pathAndQuery:$.route,timestamp:$.timestamp,nonce:$.nonce,challenge:$.challenge,bodySha256:$.bodySha256})}function z8($){return Boolean($)&&typeof $==="object"&&!Array.isArray($)}var p$=20000,u$=1e4,q8=[2000,4000],d$=30000,l$=15000;function E8($){return $?{keepalive:!1}:{}}class v2 extends Error{constructor($){super(`Reason Device proof challenge did not answer within ${$}ms.`)}}class s${fetchImpl;proofStore;proofOptions;apiOrigin;spareChallenge=null;sessions=new Map;sessionsClosed=!1;constructor($,J=fetch,Z,Q={}){this.fetchImpl=J;this.proofStore=Z;this.proofOptions=Q;let B=new URL($);if(B.protocol!=="https:"&&B.hostname!=="127.0.0.1"&&B.hostname!=="localhost"&&B.hostname!=="[::1]"&&B.hostname!=="::1")throw Error("Reason Device API must use HTTPS, except for localhost development.");this.apiOrigin=B.origin}async parseResponse($){if($.status===204)return null;let J=await $.json().catch(()=>({}));if(!$.ok){let{code:Z,message:Q}=k8(J,$.status),B=$.headers?.get?.("retry-after")??null;throw new F0($.status,Z,Q,B)}return J}async challenge($,J,Z={fresh:!1}){let Q=this.proofOptions.challengeAttemptTimeoutsMs??q8;for(let B of Q)try{return await this.challengeAttempt($,J,B,Z.fresh)}catch(K){if(J?.aborted||!(K instanceof v2))throw K;Z.fresh=!0}return await this.challengeAttempt($,J,null,Z.fresh)}async challengeAttempt($,J,Z,Q=!1){let B=JSON.stringify({device_id:$}),K=Z===null?null:new AbortController,G=K&&Z!==null?setTimeout(()=>K.abort(new v2(Z)),Z):null;try{let U=await this.fetchImpl(`${this.apiOrigin}${d.authChallenge.path}`,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:B,...E8(Q),signal:K?J?AbortSignal.any([J,K.signal]):K.signal:J});return f8(await this.parseResponse(U))}catch(U){if(!J?.aborted&&K?.signal.aborted)throw K.signal.reason;throw U}finally{if(G)clearTimeout(G)}}async takeSpareChallenge($){let J=this.spareChallenge;if(this.spareChallenge=null,!J||J.deviceId!==$)return null;let Z=await J.challenge,Q=(this.proofOptions.now??Date.now)();return Z&&Date.parse(Z.expires_at)-Q>=p$?Z:null}refillSpareChallenge($){let J=this.challengeAttempt($,void 0,q8[0]??2000).catch(()=>null);this.spareChallenge={deviceId:$,challenge:J}}async proofHeaders($,J,Z,Q,B=!1,K,G){let U=K&&Date.parse(K.expires_at)-(this.proofOptions.now??Date.now)()>=u$?K:null,W=!U&&B?await this.takeSpareChallenge(Z.deviceId):null,Y=U??W??await this.challenge(Z.deviceId,Q,G);if(B)this.refillSpareChallenge(Z.deviceId);let X=R8(J),F=this.signProof("POST",$,Y.challenge,X);return{"x-device-id":Z.deviceId,"x-device-timestamp":F.timestamp,"x-device-nonce":F.nonce,"x-device-challenge":Y.challenge,"x-device-body-sha256":X,"x-device-signature":F.signature}}signProof($,J,Z,Q){let B=String(Math.trunc((this.proofOptions.now??Date.now)())),K=(this.proofOptions.nonce??(()=>f$(24)))();if(K.byteLength<16||K.byteLength>32)throw Error("Invalid Reason Device proof nonce.");let G=Buffer.from(K).toString("base64url"),U=this.proofStore.sign(v$({method:$,route:J,timestamp:B,nonce:G,challenge:Z,bodySha256:Q}));if(!/^[A-Za-z0-9_-]{8,128}$/.test(U))throw Error("Reason Device proof boundary returned an invalid signature.");return{timestamp:B,nonce:G,signature:U}}sessionFor($,J){if(!this.proofOptions.deviceSession||this.sessionsClosed||!J||!g8($.path))return null;let Z=this.sessions.get(J.deviceId);if(!Z)Z=new m2({apiOrigin:this.apiOrigin,deviceId:J.deviceId,signHello:(Q)=>this.signProof("GET",h1,Q,R8("")),...this.proofOptions.webSocket?{WebSocket:this.proofOptions.webSocket}:{},...this.proofOptions.now?{now:this.proofOptions.now}:{}}),this.sessions.set(J.deviceId,Z);return Z}sessionCadence($){let J=this.proofOptions.deviceSession&&!this.sessionsClosed?this.sessions.get($.deviceId)?.cadence()??null:null;return J?{presenceIntervalMs:J.presence_interval_ms,claimWaitMs:J.claim_wait_ms}:null}close(){this.sessionsClosed=!0;for(let $ of this.sessions.values())$.close();this.sessions.clear()}async request($,J){if(J.body!==void 0&&P8(J.body)>H0)throw Error("Reason Device request exceeds the 256 KB protocol limit.");if(J.authorization!==void 0&&J.device!==void 0)throw Error("Reason Device request cannot combine bearer and proof authentication.");let Z=J.authorization!==void 0,Q=J.device!==void 0;if(!($.auth==="none"?!Z&&!Q:$.auth==="registration_bearer"?Z&&!Q:Z!==Q))throw Error(`Reason Device request used invalid authentication for ${$.path}.`);let K=J.body===void 0?void 0:JSON.stringify(J.body),G=this.proofOptions.maxAttempts??4,U=this.proofOptions.sleep??m$,W=this.sessionFor($,J.device),Y=Math.max(d$,(J.holdMs??0)+l$),X={fresh:!1},F;for(let H=0;H<G;H+=1)try{let N=await W?.request($.path,J.sessionBody===void 0?K??"":JSON.stringify(J.sessionBody),J.signal)??null;if(N)return await this.parseResponse(new Response(N.status===204?null:N.body,{status:N.status,headers:N.retryAfter===null?{}:{"retry-after":N.retryAfter}}));let D=new AbortController,L=setTimeout(()=>D.abort(new v1(Y)),Y),M=J.signal?AbortSignal.any([J.signal,D.signal]):D.signal;try{let I=J.device===void 0?{}:await this.proofHeaders($.path,K,J.device,M,J.useSpareChallenge===!0&&H===0,H===0?J.issuedChallenge:void 0,X),P=await this.fetchImpl(`${this.apiOrigin}${$.path}`,{method:"POST",redirect:"error",headers:{...J.authorization===void 0?{}:{authorization:`Bearer ${J.authorization}`},...I,accept:"application/json",...J.body===void 0?{}:{"content-type":"application/json"}},body:K,...E8(X.fresh),signal:M});return await this.parseResponse(P)}catch(I){if(!J.signal?.aborted&&D.signal.aborted)throw D.signal.reason;throw I}finally{clearTimeout(L)}}catch(N){if(F=N,N instanceof v1)X.fresh=!0;if(J.signal?.aborted)throw N;let D=J.device!==void 0&&N instanceof F0&&N.status===401&&["invalid_device_proof","device_proof_replayed"].includes(N.code),L=N instanceof F0&&x$(N.status),M=y$(N),I=J.transientRetryOwner!=="caller"&&(L||M);if((D||I)&&H+1<G){let P=D?0:h$(H,N,this.proofOptions.retryBaseDelayMs??500);if(P>0)await U(P,J.signal);continue}if(D&&H+1>=G)throw Error("Reason Device proof retry was exhausted.");throw N}throw F??Error("Reason Device request failed.")}async register($,J,Z){let Q=await this.request(d.register,{authorization:$,body:J,signal:Z});return b8(Q)}async enroll($,J,Z,Q){let B=await this.request(d.enroll,{body:{...Z,enrollment_ticket:$,code_verifier:J},signal:Q});return x8(B)}async heartbeat($,J,Z,Q){let B=await this.request(d.heartbeat,{device:$,body:J,signal:Z,...Q?{issuedChallenge:Q}:{}});return y8(B)}async syncRoots($,J,Z){let Q=await this.request(d.rootsSync,{device:$,body:{roots:J},signal:Z});return h8(Q)}async identity($,J){let Z=await this.request(d.identity,{device:$,signal:J});return m8(Z)}async disconnect($,J,Z,Q=[]){let B=await this.request(d.disconnect,{device:$,body:Z?{successor_device_id:Z,...Q.length?{successor_roots:Q}:{}}:{},signal:J});return v8(B)}async deviceLifecycle($,J,Z){let Q=await this.request(d.lifecycle,{device:$,body:J,signal:Z});u8(Q)}async localSubscription($,J,Z){return p8(await this.request(d.localSubscription,{device:$,body:J,signal:Z}))}async ownerWorkspaces($,J){let Q=(await this.request(d.ownerWorkspaces,{device:$,body:{},signal:J}))?.organizations;if(!Array.isArray(Q))throw Error("Reason returned an invalid workspace list.");return Q.flatMap((B)=>{let K=B;return typeof K?.id==="string"?[{id:K.id,...typeof K.name==="string"&&K.name.trim()?{name:K.name.trim()}:{},blocked:K.blocked===!0}]:[]})}async ownerWorkspaceEnrollment($,J,Z){return this.request(d.ownerWorkspaceEnrollment,{device:$,body:J,signal:Z})}async liveSessionWorktrees($,J,Z){let Q=await this.request(d.sessionWorktrees,{device:$,body:{worktree_ids:[...J]},signal:Z}).catch((B)=>{if(B instanceof F0&&B.status===404)return null;throw B});if(Q===null)return null;if(!z8(Q)||!Array.isArray(Q.live)||!Q.live.every((B)=>typeof B==="string"&&J.includes(B)))throw Error("Reason returned an invalid Session worktree answer.");return Q.live}async claimOperation($,J={}){let Z=Math.max(J.waitMs??25000,0),Q=(G)=>({wait_ms:Math.min(Z,G),...J.instanceGeneration===void 0?{}:{instance_generation:J.instanceGeneration}}),B=this.sessionCadence($)?.claimWaitMs,K=await this.request(d.operationClaim,{device:$,body:Q(30000),holdMs:Math.min(Z,30000),...B===void 0?{}:{sessionBody:Q(Math.min(B,m1))},signal:J.signal});if(K===null)return null;return d8(K,p2)}async operationHeartbeat($,J,Z={}){let Q=(G)=>this.request(d.operationHeartbeat.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z.controlAckSeq===void 0?{}:{control_ack_seq:Z.controlAckSeq},...G?{client_retry_count:Z.clientRetryCount}:{},...G&&Z.waitMs!==void 0?{wait_ms:Math.min(Math.max(Z.waitMs,0),30000)}:{}},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...G&&Z.waitMs!==void 0?{holdMs:Math.min(Math.max(Z.waitMs,0),30000)}:{}}),B=(Z.clientRetryCount??0)>0||Z.waitMs!==void 0,K;try{K=await Q(B)}catch(G){if(!B||!(G instanceof F0)||G.status!==400||G.code!=="invalid_operation_heartbeat")throw G;K=await Q(!1)}return l8(K)}async operationEvents($,J,Z){if(!Number.isInteger(Z.eventSeqStart)||Z.eventSeqStart<0||Z.events.length<1||Z.events.length>100||Z.events.some((B)=>!/^[A-Za-z0-9._:-]{1,64}$/.test(B.kind)||!z8(B.payload)))throw Error("Invalid Reason Device operation event batch.");let Q=await this.request(d.operationEvents.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,event_seq_start:Z.eventSeqStart,events:Z.events},signal:Z.signal,transientRetryOwner:Z.transientRetryOwner,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return s8(Q)}async completeOperation($,J,Z,Q){let B={attempt_id:J.attempt_id,attempt_token:J.attempt_token,status:Z.status,...Z.result===void 0?{}:{result:Z.result},...Z.error_code?{error_code:Z.error_code}:{}};if(P8(B)>H0)throw Error("Reason Device operation result exceeds the 256 KB protocol limit.");let K=await this.request(d.operationComplete.forOperation(J.operation_id),{device:$,body:B,signal:Q});return n8(K)}async operationCustomEndpointCredential($,J,Z){let{CustomEndpointDeviceCredentialSchema:Q}=await import("./custom-endpoint-device-rzf5q89e.js");return Q.parse(await this.request(d.operationCustomEndpointCredential.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token},signal:Z}))}async operationEnvironment($,J,Z,Q){let B=await this.request(d.operationEnvironment.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,snapshot_id:Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}});return c8(B)}async acknowledgeOperationEnvironment($,J,Z,Q){await this.request(d.operationEnvironmentAck.forOperation(J.operation_id),{device:$,body:{attempt_id:J.attempt_id,attempt_token:J.attempt_token,...Z},signal:Q,...this.proofOptions.prefetchEventChallenges===!0?{useSpareChallenge:!0}:{}})}}var c$=new Set(["process.run.v1","process.full.v1","computer.use","browser.use"]),B1=new Set(["jobs.control","environment.install","tunnel.open","tunnel.close","display.stream.v1","automation.call.v1","workspace.setup.v1","simulator.call.v1","simulator.stream.v1"]);function p1($,J){if(c$.has($))return!1;if(B1.has($)&&!J.runtimeDirectory)return!1;if(($==="inference.custom.v1"||$==="preview.serve.v1"||$==="simulator.call.v1"||$==="simulator.stream.v1")&&(J.executionMode!=="unsandboxed"||!J.runtimeDirectory))return!1;if(J.executionMode!=="unsandboxed"&&(["exec.full","hands.connect","pty.start","browser.pr-proof.v1"].includes($)||B1.has($)))return!1;return!0}import{accessSync as n$,constants as r$,existsSync as a$,statSync as i$}from"fs";import{basename as o$,isAbsolute as t$}from"path";var K1=["-lic"],e$="/bin/zsh",$J=new Set(["zsh","bash"]),r8=20000,u2=60000,JJ=65536,ZJ=64,QJ=8192,BJ=new Set(["NODE_OPTIONS","PATH","ZDOTDIR","BASH_ENV","ENV"]),KJ=["DYLD_","LD_"];function VJ($){let J=$.toUpperCase();return BJ.has(J)||KJ.some((Z)=>J.startsWith(Z))}function a8($=process.env){return!0}function GJ($){if(!t$($)||$.includes("\x00"))return!1;if(!$J.has(o$($)))return!1;try{if(!i$($).isFile())return!1;return n$($,r$.X_OK),!0}catch{return!1}}function g0($=process.env){let J=$.SHELL?.trim();if(J&&GJ(J))return J;return e$}function d2($=process.env){return a8($)&&a$(g0($))}function l2($=process.env){if(!a8($))throw new C("full_control_disabled","Full-control execution is unavailable on this Reason Device.")}function s2($){if(typeof $!=="string"||$.length===0||$.includes("\x00")||Buffer.byteLength($,"utf8")>JJ)throw new C("invalid_payload","command is missing or too large.");return $}function c2($){if($===void 0||$===null)return{forwarded:{},ignored:[]};if(typeof $!=="object"||Array.isArray($))throw new C("invalid_payload","env must be an object of strings.");let J=Object.entries($);if(J.length>ZJ)throw new C("invalid_payload","env has too many entries.");let Z={},Q=[];for(let[B,K]of J){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(B)||typeof K!=="string"||K.includes("\x00")||Buffer.byteLength(K,"utf8")>QJ)throw new C("invalid_payload","env entry is invalid or too large.");if(VJ(B)){Q.push(B);continue}Z[B]=K}return{forwarded:Z,ignored:Q}}async function i8($){let J=$.processEnv??process.env;if(l2(J),$.signal.aborted)throw new C("cancelled","Operation was cancelled.");let Z=s2($.command),Q=g0(J),{forwarded:B,ignored:K}=c2($.requestEnv),G=await $.spawn(Q,[...K1,Z],{cwd:$.cwd,timeoutMs:$.timeoutMs,signal:$.signal,env:{...J,...B}});return{exit_code:G.exitCode,signal:G.signal,stdout:G.stdout,stderr:G.stderr,timed_out:G.timedOut,truncated:G.truncated,shell:Q,shell_flags:[...K1],login:!0,interactive:!0,sandbox:"none",ignored_env:K}}function o8($=process.env){return{transport:"shell",shell:`${g0($)} ${K1.join(" ")}`,login_shell:!0,interactive_shell:!0,rc_files_loaded:!0,sandbox:"none",network:!0,environment:"inherited",privilege:"user",sudo:"argv_exact_nopasswd_only",activation:"explicit_device_grant",max_timeout_ms:u2}}import{readFile as UJ,readdir as XJ,readlink as WJ,realpath as YJ}from"fs/promises";import{basename as FJ,relative as NJ,sep as HJ}from"path";var O0="/proc",CJ=250,t8=500,DJ=50,MJ=250,wJ=1024,e8=4096,LJ=1,OJ=3,$5=9,jJ="0A",IJ=/^socket:\[(\d+)\]$/,n2={readDirectory:($)=>XJ($),readLink:($)=>WJ($),readTextFile:($)=>UJ($,"utf8"),realPath:($)=>YJ($)};function Z5($,J){return J===$||J.startsWith(`${$}${HJ}`)}function AJ($,J){return NJ($,J)||"."}async function Q5($){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 B5($,J){try{let Q=(await J.readTextFile(`${O0}/${$}/comm`)).slice(0,e8).split(`
38
38
  `,1)[0]?.trim();if(Q)return Q}catch{}try{let Q=(await J.readTextFile(`${O0}/${$}/cmdline`)).slice(0,e8).split("\x00",1)[0]?.trim();return Q?FJ(Q):null}catch{return null}}async function K5($,J=n2){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 V5($,J=n2){let Z=[];for(let Q of await Q5(J)){if(Z.length>=CJ)break;let B=await K5(Q,J);if(!B||!Z5($,B))continue;Z.push({pid:Q,command:await B5(Q,J),cwd:AJ($,B)})}return{processes:Z}}function J5($){let J=[];for(let Z=0;Z<8;Z+=2)J.unshift(Number.parseInt($.slice(Z,Z+2),16));return J}function _J($){let J=[];for(let W=0;W<16;W+=2)J.push($[W]<<8|$[W+1]);if(J.slice(0,5).every((W)=>W===0)&&J[5]===65535)return`::ffff:${$.slice(12).join(".")}`;let Z=-1,Q=0,B=-1;for(let W=0;W<=J.length;W+=1){if(W<J.length&&J[W]===0){if(B<0)B=W;continue}if(B>=0){let Y=W-B;if(Y>Q)Z=B,Q=Y;B=-1}}let K=J.map((W)=>W.toString(16));if(Q<2)return K.join(":");let G=K.slice(0,Z).join(":"),U=K.slice(Z+Q).join(":");return`${G}::${U}`}function TJ($,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`[${_J(Z)}]:${J}`}return null}function PJ($,J){let Z=[];for(let Q of $.split(`
39
39
  `).slice(1)){if(Z.length>=J)break;let B=Q.trim().split(/\s+/);if(B.length<=$5)continue;if(B[OJ]?.toUpperCase()!==jJ)continue;let K=B[LJ]??"",G=K.lastIndexOf(":");if(G<0)continue;let U=Number.parseInt(K.slice(G+1),16);if(!Number.isInteger(U)||U<=0||U>65535)continue;let W=TJ(K.slice(0,G),U),Y=B[$5];if(!W||!Y||!/^[0-9]+$/.test(Y))continue;Z.push({inode:Y,port:U,address:W})}return Z}async function RJ($){let J=[];for(let Z of["tcp","tcp6"]){if(J.length>=t8)break;let Q;try{Q=await $.readTextFile(`${O0}/net/${Z}`)}catch{continue}J.push(...PJ(Q,t8-J.length))}return J}async function zJ($,J){let Z=new Map;if($.size===0)return Z;for(let Q of await Q5(J)){if(Z.size>=$.size)break;let B;try{B=await J.readDirectory(`${O0}/${Q}/fd`)}catch{continue}for(let K of B.slice(0,wJ)){let G;try{G=await J.readLink(`${O0}/${Q}/fd/${K}`)}catch{continue}let U=G.match(IJ)?.[1];if(!U||!$.has(U)||Z.has(U))continue;Z.set(U,Q)}}return Z}async function G5($,J=n2){let Z=await RJ(J),Q=await zJ(new Set(Z.map((X)=>X.inode)),J),B=[];for(let X of Z){let F=Q.get(X.inode);if(F===void 0)continue;B.push({pid:F,port:X.port,address:X.address})}B.sort((X,F)=>X.pid-F.pid||X.port-F.port||(X.address<F.address?-1:X.address>F.address?1:0));let K=[...new Set(B.map((X)=>X.pid))].slice(0,DJ),G=await Promise.all(K.map(async(X)=>[X,await K5(X,J)])),U=new Map(G),W=B.filter((X)=>{let F=U.get(X.pid);return Boolean(F&&Z5($,F))}),Y=new Map(await Promise.all([...new Set(W.map((X)=>X.pid))].map(async(X)=>[X,await B5(X,J)])));return{ports:W.slice(0,MJ).map((X)=>({pid:X.pid,command:Y.get(X.pid)??null,address:X.address}))}}import{posix as a2}from"path";var u1=200,qJ=250,EJ=250;async function d1($,J){let Z=await $(J);if(Z.timedOut||Z.truncated||Z.exitCode!==0&&Z.exitCode!==1)throw new C("process_inspection_failed","Reading this Mac's processes did not complete.");let Q=[],B=null;for(let K of Z.stdout.split(/\r?\n/))if(K.startsWith("p")){let G=Number(K.slice(1));if(B=Number.isInteger(G)&&G>0?{pid:G,command:null,names:[]}:null,B)Q.push(B)}else if(B&&K.startsWith("c"))B.command=K.slice(1)||null;else if(B&&K.startsWith("n"))B.names.push(K.slice(1));return Q}function r2($,J){return J===$||J.startsWith($==="/"?$:`${$}/`)}var U5="/System/Volumes/Data",gJ=["/tmp","/var","/etc"];function i2($){let J=a2.normalize($);if(J.startsWith(`${U5}/`))J=J.slice(U5.length);return gJ.find((Q)=>J===Q||J.startsWith(`${Q}/`))?`/private${J}`:J}function X5($){return $&&a2.isAbsolute($)?i2($):null}async function W5($,J){let Z=new Map;for(let Q=0;Q<J.length;Q+=u1){let B=J.slice(Q,Q+u1).join(",");for(let K of await d1($,["-a","-p",B,"-d","cwd","-Fpcn"]))Z.set(K.pid,{command:K.command,cwd:X5(K.names[0])})}return Z}async function Y5($,J){let Z=i2($),Q=(await d1(J,["-d","cwd","-Fpn"])).filter((K)=>{let G=X5(K.names[0]);return G!==null&&r2(Z,G)}).map((K)=>K.pid).slice(0,qJ),B=await W5(J,Q);return{processes:Q.flatMap((K)=>{let G=B.get(K);return G?.cwd&&r2(Z,G.cwd)?[{pid:K,command:G.command,cwd:a2.relative(Z,G.cwd)||"."}]:[]})}}async function F5($,J){let Z=i2($),Q=["-nP","-iTCP","-sTCP:LISTEN","-Fpcn"],B=await d1(J,Q),K=await W5(J,B.map((Y)=>Y.pid)),G=B.map((Y)=>Y.pid).filter((Y)=>{let X=K.get(Y)?.cwd;return Boolean(X&&r2(Z,X))});if(G.length===0)return{ports:[]};let U=new Set(B.flatMap((Y)=>Y.names.map((X)=>`${Y.pid} ${X}`))),W=[];for(let Y=0;Y<G.length;Y+=u1){let X=G.slice(Y,Y+u1).join(",");for(let F of await d1(J,["-a","-p",X,...Q]))for(let H of F.names)if(U.has(`${F.pid} ${H}`))W.push({pid:F.pid,command:F.command,address:H})}return{ports:W.slice(0,EJ)}}import{join as lJ}from"path";import{spawn as hJ}from"child_process";import{randomUUID as mJ}from"crypto";import{chmodSync as C5,lstatSync as D5,mkdirSync as vJ,readdirSync as pJ,statSync as uJ,unlinkSync as dJ}from"fs";import{join as t2}from"path";var o2={targets:24,assets:128,sourceFiles:2000,sourceBytes:20000000,outputBytes:20000000};var l1=($,J=0,Z=1e6)=>typeof $==="number"&&Number.isFinite($)&&$>=J&&$<=Z;var j0=()=>{throw Error("proof_visual_contract_invalid")};class N5 extends Error{constructor(){super("proof_visual_contract_invalid")}}function kJ($){if(!V1($)||$.version!==1)return j0();if(typeof $.route!=="string"||!$.route.startsWith("/")||$.route.length>512||/[\x00-\x20\x7f\\?#%]/.test($.route)||$.route.startsWith("//"))throw new N5;if(!V1($.viewport)||!l1($.viewport.width,1,4096)||!l1($.viewport.height,1,4096)||!Array.isArray($.targets)||$.targets.length<1||$.targets.length>o2.targets||Object.keys($).some((Q)=>!["version","route","viewport","targets","additionalViewports"].includes(Q)))return j0();let J=$.targets.map((Q)=>{if(!V1(Q)||typeof Q.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(Q.id)||typeof Q.selector!=="string"||!Q.selector.trim()||Q.selector.length>256||/[\x00-\x1f\x7f]/.test(Q.selector)||Object.keys(Q).some((B)=>!["id","selector"].includes(B)))return j0();return{id:Q.id,selector:Q.selector}});if(new Set(J.map((Q)=>Q.id)).size!==J.length)return j0();let Z;if($.additionalViewports!==void 0){if(!Array.isArray($.additionalViewports)||$.additionalViewports.length<1||$.additionalViewports.length>3)return j0();Z=$.additionalViewports.map((B)=>{if(!V1(B)||!l1(B.width,1,4096)||!Number.isInteger(B.width)||!l1(B.height,1,4096)||!Number.isInteger(B.height)||Object.keys(B).some((K)=>!["width","height"].includes(K)))return j0();return{width:B.width,height:B.height}});let Q=[$.viewport,...Z].map((B)=>`${B.width}x${B.height}`);if(new Set(Q).size!==Q.length)return j0()}return{version:1,route:$.route,viewport:{width:$.viewport.width,height:$.viewport.height},targets:J,...Z?{additionalViewports:Z}:{}}}var bJ=["organizationId","userId","sessionId","runId"],xJ=[...bJ,"prUrl","headSha","skillDigest","evidenceKind"],MV=[...xJ,"contextId","preparedAt","captureId","startedAt","finishedAt","sha256","kind","visualPlan","visualObservation"];var yJ={"image/png":{kind:"image",directory:"/tmp/ara-public-screenshots",extension:"png",maxBytes:8388608},"video/webm":{kind:"video",directory:"/tmp/ara-public-recordings",extension:"webm",maxBytes:10551296}};function H5($){return yJ[$].directory}var M5=10485760;function w5($={}){let J=$.directory??H5("video/webm"),Z=null;return{async start(Q){if(Z)throw Error("cloud_browser_recording_active");let B=Q?.seconds;if(!Number.isInteger(B)||Number(B)<1||Number(B)>15||!Q||Object.keys(Q).some((M)=>M!=="seconds"))throw Error("cloud_browser_recording_seconds_1_to_15_required");vJ(J,{recursive:!0,mode:457});let K=D5(J);if(!K.isDirectory()||K.isSymbolicLink()||K.uid!==process.getuid?.())throw Error("cloud_browser_recording_directory_invalid");C5(J,457);let G=pJ(J).filter((M)=>/^[a-f0-9-]{36}\.webm$/.test(M)).map((M)=>({name:M,time:uJ(t2(J,M)).mtimeMs})).sort((M,I)=>I.time-M.time);for(let M of G.slice(9))dJ(t2(J,M.name));let U=t2(J,`${mJ()}.webm`),W=["-f","x11grab","-framerate","12","-i",$.display??":99"],Y=($.spawn??hJ)($.ffmpeg??"ffmpeg",["-nostdin","-hide_banner","-loglevel","error","-y",...W,"-t",String(B),"-vf","scale=1280:-2","-c:v","libvpx","-deadline","realtime","-b:v","700k","-an","-fs",String(M5),"-progress","pipe:1",U],{stdio:["ignore","pipe","ignore"],...$.env?{env:$.env}:{}}),X,F,H=!1,N=new Promise((M,I)=>{X=M,F=I});Y.stdout.on("data",(M)=>{if(/frame=\s*[1-9]/.test(String(M)))H=!0,X()});let D=new Promise((M,I)=>{Y.once("error",()=>{F(Error("cloud_browser_recording_unavailable")),I(Error("cloud_browser_recording_unavailable"))}),Y.once("exit",(P)=>{try{if(P!==0&&P!==255)throw Error();let j=D5(U);if(!H||!j.isFile()||j.isSymbolicLink()||j.uid!==process.getuid?.()||j.size<128||j.size>M5+65536)throw Error();C5(U,420),X(),M({path:U,mimeType:"video/webm"})}catch{F(Error("cloud_browser_recording_failed")),I(Error("cloud_browser_recording_failed"))}})});D.catch(()=>{});let L=setTimeout(()=>Y.kill("SIGKILL"),(Number(B)+5)*1000);D.finally(()=>clearTimeout(L)).catch(()=>{}),Z={done:D,stop:()=>{return Y.kill("SIGINT"),D}};try{await N}catch(M){throw Z=null,M}return{recording:!0,seconds:Number(B)}},async stop(){if(!Z)throw Error("cloud_browser_recording_not_started");let Q=Z;return Z=null,Q.stop()},async close(){if(Z)await this.stop().catch(()=>{})}}}function j5($,J={}){if($.executionMode!=="unsandboxed"||!$.runtimeDirectory||(J.platform??process.platform)!=="linux")return null;let Z=(J.components??L5)(),Q=Z?.features.display?Z.ffmpeg:null;if(!Q)return null;let B=lJ($.runtimeDirectory,"recordings"),K=null;return{async start(G){let U=await(J.desktop??O5)();return K??=w5({directory:B,display:U.display,ffmpeg:Q,env:{HOME:E1(),PATH:"/usr/local/bin:/usr/bin:/bin",XAUTHORITY:U.xauthority},...J.spawn?{spawn:J.spawn}:{}}),K.start(G)},async stop(){if(!K)throw Error("cloud_browser_recording_not_started");return K.stop()},async close(){await K?.close()}}}import{spawn as M3}from"child_process";import{createHash as VZ,randomUUID as GZ}from"crypto";import{existsSync as Q0,mkdirSync as F3,mkdtempSync as w3,readdirSync as t1,readFileSync as L3,renameSync as UZ,rmSync as X1,statSync as r1,writeFileSync as XZ}from"fs";import{homedir as O3,tmpdir as p5}from"os";import{basename as u5,dirname as N3,join as g,relative as d5,resolve as H3,sep as l5}from"path";var i=V.string().min(1).max(200),Z0=V.number().finite().min(0).max(1e4),s1=V.string().min(1).max(4096).refine(($)=>!$.includes("\x00")),I5=V.string().regex(/^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/),$3=V.object({id:V.string().min(1).max(500).optional(),label:V.string().min(1).max(500).optional()}).strict(),J3=["home","lock","side_button","siri","apple_pay"],sJ=V.enum(["tree","screenshot","both","none"]),cJ=V.object({...$3.shape,gone:V.boolean().optional()}).strict().refine(($)=>Boolean($.id||$.label),"wait_for needs an id or label"),C0={observe:sJ.optional(),wait_for:cJ.optional(),timeout:V.number().min(0).max(20).optional()},e2=V.discriminatedUnion("action",[V.object({action:V.literal("tap"),x:Z0.optional(),y:Z0.optional(),...$3.shape,duration:V.number().min(0).max(10).optional()}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional()}).strict(),V.object({action:V.literal("type"),text:V.string().min(1).max(4000)}).strict(),V.object({action:V.literal("button"),name:V.enum(J3)}).strict(),V.object({action:V.literal("sleep"),seconds:V.number().min(0).max(10)}).strict()]),Z3=V.discriminatedUnion("action",[V.object({action:V.literal("devices")}).strict(),V.object({action:V.literal("boot"),device:i}).strict(),V.object({action:V.literal("shutdown"),device:i}).strict(),V.object({action:V.literal("build"),path:s1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("run"),path:s1.optional(),scheme:V.string().min(1).max(200).optional(),configuration:V.string().min(1).max(100).optional(),device:i.optional(),steps:V.array(V.lazy(()=>e2)).max(30).optional(),...C0}).strict(),V.object({action:V.literal("build_status"),build_id:V.string().regex(/^build-[0-9a-z-]{4,64}$/),device:i.optional(),wait:V.boolean().optional()}).strict(),V.object({action:V.literal("launch"),device:i.optional(),app_path:s1.optional(),bundle_id:I5.optional(),steps:V.array(V.lazy(()=>e2)).max(30).optional(),...C0}).strict().refine(($)=>Boolean($.app_path)!==Boolean($.bundle_id),"pass exactly one of app_path or bundle_id"),V.object({action:V.literal("terminate"),device:i.optional(),bundle_id:I5}).strict(),V.object({action:V.literal("logs"),device:i.optional(),after:V.number().int().min(0).optional()}).strict(),V.object({action:V.literal("screenshot"),device:i.optional(),scale:V.union([V.literal(1),V.literal(2)]).optional(),save_path:s1.optional()}).strict(),V.object({action:V.literal("chrome"),device:i.optional()}).strict(),V.object({action:V.literal("inspect"),device:i.optional()}).strict(),V.object({action:V.literal("tap"),device:i.optional(),x:Z0.optional(),y:Z0.optional(),...$3.shape,duration:V.number().min(0).max(10).optional(),...C0}).strict().refine(($)=>$.x!==void 0&&$.y!==void 0||Boolean($.id||$.label),"pass x and y, or an id or label"),V.object({action:V.literal("swipe"),device:i.optional(),x:Z0,y:Z0,x2:Z0,y2:Z0,duration:V.number().min(0.05).max(5).optional(),...C0}).strict(),V.object({action:V.literal("type"),device:i.optional(),text:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("button"),device:i.optional(),name:V.enum(J3),...C0}).strict(),V.object({action:V.literal("open_url"),device:i.optional(),url:V.string().min(1).max(4000),...C0}).strict(),V.object({action:V.literal("steps"),device:i.optional(),steps:V.array(e2).min(1).max(30),...C0}).strict(),V.object({action:V.literal("appearance"),device:i.optional(),mode:V.enum(["light","dark"])}).strict()]),A5=V.object({udid:V.string(),name:V.string(),runtime:V.string(),state:V.enum(["booted","shutdown","booting","shutting_down"]),kind:V.enum(["iphone","ipad","other"])}).strict(),xV=V.object({text:V.string(),error:V.string().optional(),device:A5.optional(),devices:V.array(A5).optional(),image:V.object({mime:V.literal("image/jpeg"),data:V.string(),width:V.number(),height:V.number()}).strict().optional(),build:V.object({id:V.string(),status:V.enum(["running","succeeded","failed"]),app_path:V.string().optional(),bundle_id:V.string().optional(),errors:V.array(V.string()),log_tail:V.string(),elapsed_ms:V.number()}).strict().optional(),logs:V.object({lines:V.array(V.string()),next:V.number()}).strict().optional(),screen:V.string().optional(),chrome:V.object({identifier:V.string(),screen:V.object({width:V.number(),height:V.number()}).strict(),inset:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),padding:V.object({top:V.number(),left:V.number(),bottom:V.number(),right:V.number()}).strict(),screen_mask:V.string().optional(),pieces:V.record(V.enum(["topLeft","top","topRight","right","bottomRight","bottom","bottomLeft","left"]),V.object({image:V.string(),width:V.number(),height:V.number()}).strict()),buttons:V.array(V.object({name:V.string(),image:V.string(),x:V.number(),y:V.number(),width:V.number(),height:V.number()}).strict())}).strict().optional()}).strict();var yV=V.object({device_id:V.uuid().optional(),root_id:V.uuid().optional()}),hV={type:"object",properties:{action:{type:"string",enum:Z3.options.map(($)=>$.shape.action.value).filter(($)=>$!=="chrome")},device_id:{type:"string",format:"uuid",description:"Reason machine id from devices.list; omit for the machine this Session runs on."},root_id:{type:"string",format:"uuid"},device:{type:"string",description:"Simulator UDID or exact name; omit for the booted one."},path:{type:"string",description:"build or run: a .xcodeproj, .xcworkspace, or a folder holding one (project.yml is generated with XcodeGen), absolute or relative to the Session's folder. Omit it when the folder holds one app project."},scheme:{type:"string"},configuration:{type:"string"},build_id:{type:"string"},app_path:{type:"string",description:"launch: the built .app from build_status."},bundle_id:{type:"string"},after:{type:"integer",minimum:0,description:"logs: only lines after this sequence number."},x:{type:"number"},y:{type:"number"},x2:{type:"number"},y2:{type:"number"},id:{type:"string",description:"tap: accessibility identifier from inspect."},label:{type:"string",description:"tap: accessibility label from inspect."},duration:{type:"number",description:"tap: seconds held (above 0.5 is a long press); swipe: seconds."},text:{type:"string"},name:{type:"string",enum:[...J3]},url:{type:"string"},mode:{type:"string",enum:["light","dark"]},steps:{type:"array",maxItems:30,description:"steps (or launch): run in order in one call (after launch, once the app is up). Each item is {action:'tap', id|label|x,y} | {action:'swipe', x,y,x2,y2} | {action:'type', text} | {action:'button', name} | {action:'sleep', seconds}. Taps by id or label wait for their element to appear.",items:{type:"object"}},observe:{type:"string",enum:["tree","screenshot","both","none"],description:"After tap, swipe, type, button, open_url, launch or steps: what to return about the settled screen. Default tree (the accessibility tree, so no separate inspect is needed); screenshot or both to see it."},wait_for:{type:"object",description:"After the action, wait until this element is on screen: {id} or {label}; add gone:true to wait for it to disappear.",properties:{id:{type:"string"},label:{type:"string"},gone:{type:"boolean"}},additionalProperties:!1},timeout:{type:"number",description:"Seconds to wait for wait_for (default 5, max 20)."},wait:{type:"boolean",description:"build or build_status: wait for the build to finish (up to ~45 s) instead of returning at once."},save_path:{type:"string",description:"screenshot: also save the full-resolution PNG at this path (absolute or relative to the Session's folder), for example to show the user."}},required:["action"],additionalProperties:!1};import{spawn as V3}from"child_process";import{createHash as rJ}from"crypto";import{existsSync as B3,mkdirSync as c1,mkdtempSync as aJ,readdirSync as _5,readFileSync as T5,renameSync as iJ,rmSync as P5,symlinkSync as K3,writeFileSync as G1}from"fs";import{homedir as oJ}from"os";import{dirname as E5,join as f}from"path";import{createInterface as tJ}from"readline";var Q3=`// Reason's simulator host: one warm process per booted iOS Simulator.
40
40
  //
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{uj as $}from"./vm-hands-entry-lite-w3cfhkv2.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
- export{O as qj,Z as rj,S as sj,k as tj};
2
+ import{wj as $}from"./vm-hands-entry-lite-59napxaf.js";var O=$.version,Z=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;function S(B,D){if(!Z.test(B)||!Z.test(D))throw Error("cannot compare invalid CLI versions");let J=(q)=>{let y=q.indexOf("-");return y===-1?[q,void 0]:[q.slice(0,y),q.slice(y+1)]},[j,F]=J(B),[w,G]=J(D),K=j.split(".").map(BigInt),M=w.split(".").map(BigInt);for(let q=0;q<3;q+=1){if(K[q]===M[q])continue;return K[q]<M[q]?-1:1}if(F===void 0||G===void 0){if(F===G)return 0;return F===void 0?1:-1}let Q=F.split("."),U=G.split("."),A=Math.max(Q.length,U.length);for(let q=0;q<A;q+=1){let y=Q[q],z=U[q];if(y===void 0||z===void 0){if(y===z)return 0;return y===void 0?-1:1}if(y===z)continue;let H=/^\d+$/.test(y),W=/^\d+$/.test(z);if(H&&W){let X=BigInt(y),Y=BigInt(z);if(X===Y)continue;return X<Y?-1:1}if(H!==W)return H?-1:1;return y<z?-1:1}return 0}function k(B,D){return D?`cli ${B} \xB7 agent ${D}`:`cli ${B}`}
3
+ export{O as sj,Z as tj,S as uj,k as vj};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{ej as f}from"./vm-hands-entry-lite-dqnhebfx.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
2
+ import{gj as f}from"./vm-hands-entry-lite-5jbnm3bm.js";var j=["Click browser element","Double click browser element","Type text","Clear browser field","Press key","Scroll browser element into view","Drag on computer","Select browser option","Check browser control","Uncheck browser control","Hover browser element","Focus browser element","Open browser page","Reload browser page","Go back in browser","Go forward in browser","Take browser screenshot"],$A=32;function R(x){if(!Array.isArray(x)||x.length>32||!x.every((A)=>typeof A==="string"&&j.includes(A)))return;return x.slice()}var KA="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",QA=262144;function Y(x){if(!x||typeof x!=="object"||Array.isArray(x))return!1;let A=x,W=Object.keys(A);return W.length===2&&W.includes("template")&&W.includes("quoteDepth")&&typeof A.template==="string"&&A.template.length<=262144&&!A.template.includes("\x00")&&A.template.split("__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__").length===2&&(A.quoteDepth===1||A.quoteDepth===2||A.quoteDepth===3)}var I=2,b=33554432,K=200000,D=4000000,_=240000,YA=`
3
3
  ...[executor output truncated]`,p=2000,k=1,i=16384,d=32768,y=128,LA=64,s=2097152,H=1,m=16384,c=32768,OA=8388608,n=1000,t=2500,r=2000,zA=t+r,o=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,v=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,l={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},u=new Map(Object.entries(l).map(([x,A])=>[A,x]));function SA(x,A){return A||(u.get(x)??"")}var a=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],e=new Set(a),w=16384,AA=200,xA=2000,WA=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class G extends Error{code;constructor(x){super(x);this.name="HandsProtocolError",this.code=x}}function g(x){return new TextEncoder().encode(x).byteLength}function U(x){return typeof x==="object"&&x!==null&&!Array.isArray(x)}function B(x,A){let W=new Set(A);return Object.keys(x).every((N)=>W.has(N))}function M(x){return typeof x==="string"&&o.test(x)}function Z(x){return Number.isSafeInteger(x)&&Number(x)>=1}function J(x){return typeof x==="string"&&v.test(x)}function C(x){return typeof x==="string"&&x.startsWith("pty-")&&J(x.slice(4))}function z(x){return[x.cols,x.rows].every((A)=>Number.isSafeInteger(A)&&Number(A)>=1&&Number(A)<=n)}function E(x){if(typeof x!=="string"||x.length>Math.ceil(m/3)*4||x.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(x))return-1;let A=x.endsWith("==")?2:x.endsWith("=")?1:0;if(A&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(x[x.length-A-1])&(A===2?15:3))return-1;let N=x.length/4*3-A;return N<=m?N:-1}function S(x){return typeof x==="string"&&/^[0-9a-f]{64}$/.test(x)}function $(x){if(g(x)>b)throw new G("frame_too_large");try{return JSON.parse(x)}catch{throw new G("invalid_json")}}function BA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","tool","input","semanticDigest","lifecycleLeaseId","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||!["bash","repl","resume","read","edit","write","pi_tool"].includes(String(A.tool))||!U(A.input)||A.lifecycleLeaseId!==void 0&&(A.tool!=="bash"||!J(A.lifecycleLeaseId))||A.workspaceBefore!==void 0&&(!(A.tool==="bash"||A.tool==="repl"||A.tool==="pi_tool"&&A.input.tool==="bash")||!U(A.workspaceBefore)||!B(A.workspaceBefore,["script"])||typeof A.workspaceBefore.script!=="string"||A.workspaceBefore.script.length>K))throw new G("invalid_request");let W=U(A.workspaceBefore)&&typeof A.workspaceBefore.script==="string"?{workspaceBefore:{script:A.workspaceBefore.script}}:{};if(A.tool==="bash"){if(!B(A.input,["script","retainBackground","machineSdk"])||typeof A.input.script!=="string"||A.input.script.length>K||A.input.retainBackground!==void 0&&A.input.retainBackground!==!0||A.input.machineSdk!==void 0&&A.input.machineSdk!==!0||A.semanticDigest!==void 0&&!S(A.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"bash",input:{script:A.input.script,...A.input.retainBackground===!0?{retainBackground:!0}:{},...A.input.machineSdk===!0?{machineSdk:!0}:{}},...A.semanticDigest===void 0?{}:{semanticDigest:A.semanticDigest},...A.lifecycleLeaseId===void 0?{}:{lifecycleLeaseId:A.lifecycleLeaseId},...W}}if(A.tool==="resume"){if(A.semanticDigest!==void 0||!B(A.input,["semanticDigest"])||!S(A.input.semanticDigest))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"resume",input:{semanticDigest:A.input.semanticDigest}}}if(A.tool==="repl"){if(!B(A.input,["code"])||typeof A.input.code!=="string"||A.input.code.length>K||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"repl",input:{code:A.input.code},...W}}if(A.tool==="pi_tool"){let N=A.semanticDigest===void 0?GA(A.input):null;if(!N)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"pi_tool",input:N,...W}}if(A.tool==="read"){if(!B(A.input,["path","offset","limit"])||typeof A.input.path!=="string"||A.input.path.length<1||A.input.path.length>K||A.semanticDigest!==void 0||A.input.offset!==void 0&&(!Number.isSafeInteger(A.input.offset)||Number(A.input.offset)<1)||A.input.limit!==void 0&&(!Number.isSafeInteger(A.input.limit)||Number(A.input.limit)<1||Number(A.input.limit)>2000))throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"read",input:{path:A.input.path,...A.input.offset===void 0?{}:{offset:Number(A.input.offset)},...A.input.limit===void 0?{}:{limit:Number(A.input.limit)}}}}if(A.tool==="edit"){if(!B(A.input,["path","edits"])||typeof A.input.path!=="string"||A.input.path.length<1||!Array.isArray(A.input.edits)||A.input.edits.length<1||A.input.edits.length>128||A.semanticDigest!==void 0)throw new G("invalid_request");let N=A.input.path.length,X=[];for(let V of A.input.edits){if(!U(V)||!B(V,["oldText","newText"])||typeof V.oldText!=="string"||V.oldText.length<1||typeof V.newText!=="string")throw new G("invalid_request");if(N+=V.oldText.length+V.newText.length,N>D)throw new G("invalid_request");X.push({oldText:V.oldText,newText:V.newText})}return{version:I,generation:A.generation,id:A.id,tool:"edit",input:{path:A.input.path,edits:X}}}if(A.tool!=="write"||!B(A.input,["path","content"])||typeof A.input.path!=="string"||A.input.path.length<1||typeof A.input.content!=="string"||A.input.path.length+A.input.content.length>D||A.semanticDigest!==void 0)throw new G("invalid_request");return{version:I,generation:A.generation,id:A.id,tool:"write",input:{path:A.input.path,content:A.input.content}}}function L(x){return x===void 0||typeof x==="number"&&Number.isFinite(x)}function GA(x){let A=x.args;if(!B(x,["tool","args"])||!U(A))return null;if(x.tool==="bash")return B(A,["command","timeout"])&&typeof A.command==="string"&&A.command.length<=K&&L(A.timeout)?{tool:"bash",args:{command:A.command,...A.timeout===void 0?{}:{timeout:Number(A.timeout)}}}:null;if(typeof A.path!=="string"||A.path.length>K)return null;if(x.tool==="read")return B(A,["path","offset","limit"])&&L(A.offset)&&L(A.limit)?{tool:"read",args:{path:A.path,...A.offset===void 0?{}:{offset:Number(A.offset)},...A.limit===void 0?{}:{limit:Number(A.limit)}}}:null;if(x.tool==="write")return B(A,["path","content"])&&typeof A.content==="string"&&A.path.length+A.content.length<=D?{tool:"write",args:{path:A.path,content:A.content}}:null;if(x.tool!=="edit"||!B(A,["path","edits"])||!Array.isArray(A.edits))return null;let W=A.path.length,N=[];for(let X of A.edits){if(!U(X)||!B(X,["oldText","newText"])||typeof X.oldText!=="string"||typeof X.newText!=="string")return null;if(W+=X.oldText.length+X.newText.length,W>D)return null;N.push({oldText:X.oldText,newText:X.newText})}return{tool:"edit",args:{path:A.path,edits:N}}}function NA(x){if(!U(x))return null;if("thrown"in x)return B(x,["thrown"])&&typeof x.thrown==="string"?{thrown:x.thrown}:null;let A=x.structuredContent;if(!B(x,["content","details","structuredContent","isError"])||!Array.isArray(x.content)||x.isError!==void 0&&x.isError!==!0||A!==void 0&&(!U(A)||!B(A,["output","truncated","full_output_path","exit_code","wall_time_seconds"])||typeof A.output!=="string"||typeof A.truncated!=="boolean"||A.full_output_path!==void 0&&typeof A.full_output_path!=="string"||typeof A.exit_code!=="number"||typeof A.wall_time_seconds!=="number"))return null;let W=[];for(let N of x.content)if(U(N)&&N.type==="text"&&B(N,["type","text"])&&typeof N.text==="string")W.push({type:"text",text:N.text});else if(U(N)&&N.type==="image"&&B(N,["type","data","mimeType"])&&typeof N.data==="string"&&typeof N.mimeType==="string")W.push({type:"image",data:N.data,mimeType:N.mimeType});else return null;return{content:W,...x.details===void 0?{}:{details:x.details},...U(A)?{structuredContent:{output:String(A.output),truncated:A.truncated===!0,...typeof A.full_output_path==="string"?{full_output_path:A.full_output_path}:{},exit_code:Number(A.exit_code),wall_time_seconds:Number(A.wall_time_seconds)}}:{},...x.isError===!0?{isError:!0}:{}}}function UA(x){let A=$(x);if(!U(A)||!B(A,["version","generation","id","ok","exitCode","stdout","stderr","cwd","error","resumed","browserActions","automaticProgressImage","piToolOutcome","workerElapsedMs","environmentWaitMs","workspaceBefore"])||A.version!==I||!Z(A.generation)||!M(A.id)||typeof A.ok!=="boolean"||!Number.isSafeInteger(A.exitCode)||Number(A.exitCode)<0||Number(A.exitCode)>255||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_||A.cwd!==void 0&&(typeof A.cwd!=="string"||A.cwd.length<1||A.cwd.length>4096||!A.cwd.startsWith("/")||A.cwd.includes("\x00"))||A.error!==void 0&&(typeof A.error!=="string"||A.error.length<1||A.error.length>p||!e.has(A.error))||A.browserActions!==void 0&&!R(A.browserActions)||A.automaticProgressImage!==void 0&&(A.automaticProgressImage!==!0||!A.ok)||A.resumed!==void 0&&A.resumed!==!0||A.workerElapsedMs!==void 0&&(!Number.isSafeInteger(A.workerElapsedMs)||Number(A.workerElapsedMs)<0)||A.environmentWaitMs!==void 0&&(!Number.isSafeInteger(A.environmentWaitMs)||Number(A.environmentWaitMs)<0)||A.workspaceBefore!==void 0&&!h(A.workspaceBefore)||A.ok&&(A.exitCode!==0||A.error!==void 0)||!A.ok&&A.exitCode===0)throw new G("invalid_result");let W=A.piToolOutcome===void 0?void 0:NA(A.piToolOutcome);if(W===null||W&&!A.ok)throw new G("invalid_result");return{version:I,generation:A.generation,id:A.id,ok:A.ok,exitCode:Number(A.exitCode),stdout:A.stdout,stderr:A.stderr,...typeof A.cwd==="string"?{cwd:A.cwd}:{},...A.browserActions!==void 0?{browserActions:R(A.browserActions)}:{},...typeof A.error==="string"?{error:A.error}:{},...A.automaticProgressImage===!0?{automaticProgressImage:!0}:{},...A.resumed===!0?{resumed:!0}:{},...W?{piToolOutcome:W}:{},...A.workerElapsedMs!==void 0?{workerElapsedMs:Number(A.workerElapsedMs)}:{},...A.environmentWaitMs!==void 0?{environmentWaitMs:Number(A.environmentWaitMs)}:{},...h(A.workspaceBefore)?{workspaceBefore:{exitCode:A.workspaceBefore.exitCode,stdout:A.workspaceBefore.stdout,stderr:A.workspaceBefore.stderr}}:{}}}function h(x){return U(x)&&B(x,["exitCode","stdout","stderr"])&&Number.isSafeInteger(x.exitCode)&&Number(x.exitCode)>=0&&Number(x.exitCode)<=255&&typeof x.stdout==="string"&&x.stdout.length<=w&&typeof x.stderr==="string"&&x.stderr.length<=w}function FA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","sequence","stdout","stderr"])||A.type!=="progress"||A.version!==I||!Z(A.generation)||!M(A.id)||!Number.isSafeInteger(A.sequence)||Number(A.sequence)<1||typeof A.stdout!=="string"||A.stdout.length>_||typeof A.stderr!=="string"||A.stderr.length>_)throw new G("invalid_progress");return{type:"progress",version:I,generation:Number(A.generation),id:A.id,sequence:Number(A.sequence),stdout:A.stdout,stderr:A.stderr}}function IA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","requestCancelVersion","managedJobsVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinement","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.type!=="claim"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinement!==void 0&&(!Y(A.piToolsConfinement)||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1)throw new G("invalid_claim");return{type:"claim",version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{},...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...Y(A.piToolsConfinement)?{piToolsConfinement:{template:A.piToolsConfinement.template,quoteDepth:A.piToolsConfinement.quoteDepth}}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{}}}function XA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","fenceId","executorLaunchId","workerVersion","workerArtifactSha256","requestCancelVersion","managedJobsVersion","lifecycleVersion","browserRunEnvelopeVersion","terminalCleanupVersion","guestMemoryVersion","guestMemoryDiagnosticsVersion","piToolsVersion","piToolsConfinementVersion","backgroundBashVersion","machineSdkVersion","executionTimingVersion","environmentWaitVersion","workspaceBeforeVersion"])||A.lifecycleVersion!==void 0&&A.lifecycleVersion!==1||A.workspaceBeforeVersion!==void 0&&A.workspaceBeforeVersion!==1||A.piToolsVersion!==void 0&&A.piToolsVersion!==1||A.piToolsConfinementVersion!==void 0&&(A.piToolsConfinementVersion!==1||A.piToolsVersion!==1)||A.backgroundBashVersion!==void 0&&A.backgroundBashVersion!==1||A.machineSdkVersion!==void 0&&A.machineSdkVersion!==1||A.executionTimingVersion!==void 0&&A.executionTimingVersion!==1||A.environmentWaitVersion!==void 0&&(A.environmentWaitVersion!==1||A.executionTimingVersion!==1)||A.guestMemoryVersion!==void 0&&A.guestMemoryVersion!==1||A.guestMemoryDiagnosticsVersion!==void 0&&(A.guestMemoryDiagnosticsVersion!==1||A.guestMemoryVersion!==1)||A.terminalCleanupVersion!==void 0&&A.terminalCleanupVersion!==1||A.browserRunEnvelopeVersion!==void 0&&A.browserRunEnvelopeVersion!==1||A.type!=="claim_ack"||A.version!==I||!Z(A.generation)||!J(A.fenceId)||!J(A.executorLaunchId)||!Number.isSafeInteger(A.workerVersion)||Number(A.workerVersion)<1||!S(A.workerArtifactSha256)||A.requestCancelVersion!==void 0&&A.requestCancelVersion!==1||A.managedJobsVersion!==void 0&&A.managedJobsVersion!==k)throw new G("invalid_claim_ack");return{type:"claim_ack",...A.guestMemoryVersion===1?{guestMemoryVersion:1}:{},...A.guestMemoryDiagnosticsVersion===1?{guestMemoryDiagnosticsVersion:1}:{},...A.terminalCleanupVersion===1?{terminalCleanupVersion:1}:{},...A.browserRunEnvelopeVersion===1?{browserRunEnvelopeVersion:1}:{},...A.lifecycleVersion===1?{lifecycleVersion:1}:{},...A.piToolsVersion===1?{piToolsVersion:1}:{},...A.piToolsConfinementVersion===1?{piToolsConfinementVersion:1}:{},...A.backgroundBashVersion===1?{backgroundBashVersion:1}:{},...A.machineSdkVersion===1?{machineSdkVersion:1}:{},...A.executionTimingVersion===1?{executionTimingVersion:1}:{},...A.environmentWaitVersion===1?{environmentWaitVersion:1}:{},...A.workspaceBeforeVersion===1?{workspaceBeforeVersion:1}:{},version:I,generation:A.generation,fenceId:A.fenceId,executorLaunchId:A.executorLaunchId,workerVersion:Number(A.workerVersion),workerArtifactSha256:A.workerArtifactSha256,...A.requestCancelVersion===1?{requestCancelVersion:1}:{},...A.managedJobsVersion===1?{managedJobsVersion:1}:{}}}function TA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","jobId","action","input"])||A.type!=="job"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobId)||!U(A.input))throw new G("invalid_job_request");let W=A.input,N=Number.isSafeInteger(W.leaseExpiresAtMs)&&Number(W.leaseExpiresAtMs)>0,X=Number.isSafeInteger(W.sequence)&&Number(W.sequence)>=1;if(!(A.action==="start"?W.mode==="pty"?B(W,["mode","cols","rows","leaseExpiresAtMs"])&&C(A.jobId)&&z(W)&&N:B(W,["script","leaseExpiresAtMs"])&&typeof W.script==="string"&&W.script.length<=K&&N:A.action==="inspect"?B(W,["after"])&&Number.isSafeInteger(W.after)&&Number(W.after)>=0:A.action==="input"?"dataBase64"in W?B(W,["sequence","dataBase64"])&&C(A.jobId)&&X&&E(W.dataBase64)>0:B(W,["sequence","data","eof"])&&X&&typeof W.data==="string"&&W.data.length<=i&&typeof W.eof==="boolean":A.action==="resize"?B(W,["sequence","cols","rows"])&&C(A.jobId)&&X&&z(W):A.action==="renew"?B(W,["leaseExpiresAtMs"])&&N:A.action==="cancel"&&B(W,[])))throw new G("invalid_job_request");return A}function MA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","ok","job","error"])||A.type!=="job_result"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_job_result");if(A.ok===!1&&A.job===void 0&&typeof A.error==="string"&&WA.some((F)=>F===A.error))return A;let W=A.job;if(A.ok!==!0||A.error!==void 0||!U(W)||!B(W,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!M(W.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(W.state))||!Number.isSafeInteger(W.startedAtMs)||Number(W.startedAtMs)<1||!Number.isSafeInteger(W.leaseExpiresAtMs)||Number(W.leaseExpiresAtMs)<1||W.finishedAtMs!==null&&(!Number.isSafeInteger(W.finishedAtMs)||Number(W.finishedAtMs)<Number(W.startedAtMs))||W.exitCode!==null&&(!Number.isSafeInteger(W.exitCode)||Number(W.exitCode)<0||Number(W.exitCode)>255)||!Number.isSafeInteger(W.inputSequence)||Number(W.inputSequence)<0||!Number.isSafeInteger(W.firstCursor)||Number(W.firstCursor)<1||!Number.isSafeInteger(W.nextCursor)||Number(W.nextCursor)<Number(W.firstCursor)-1||typeof W.truncated!=="boolean"||!Array.isArray(W.output)||W.output.length>y)throw new G("invalid_job_result");if(W.environmentRevision===void 0!==(W.environmentSnapshotId===void 0)||W.environmentRevision!==void 0&&(!Number.isSafeInteger(W.environmentRevision)||Number(W.environmentRevision)<1||!J(W.environmentSnapshotId)))throw new G("invalid_job_result");let N=Number(W.firstCursor)-1,X=0;for(let F of W.output){if(!U(F)||!B(F,["cursor","stream","text"])||!Number.isSafeInteger(F.cursor)||Number(F.cursor)<=N||Number(F.cursor)>Number(W.nextCursor)||!["stdout","stderr"].includes(String(F.stream))||typeof F.text!=="string")throw new G("invalid_job_result");X+=F.text.length,N=Number(F.cursor)}if(X>d)throw new G("invalid_job_result");let V=W.state==="starting"||W.state==="running";if(V&&(W.finishedAtMs!==null||W.exitCode!==null)||!V&&W.finishedAtMs===null||W.state==="uncertain"&&W.exitCode!==null||W.state==="exited"&&W.exitCode===null||W.state==="cancelled"&&W.exitCode!==130||W.state==="expired"&&W.exitCode!==124)throw new G("invalid_job_result");if(W.process!==void 0){let F=W.process;if(!U(F)||!B(F,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(F.pid)||Number(F.pid)<1||F.processGroupId!==F.pid||!J(F.executorLaunchId)||!["starting","running"].includes(String(W.state)))throw new G("invalid_job_result")}if(W.pty!==void 0){let F=W.pty;if(!U(F)||!B(F,["version","cols","rows","output","cleanup"])||F.version!==H||!C(W.jobId)||!z(F)||W.output.length!==0||!Array.isArray(F.output)||F.output.length>y||(V?F.cleanup!=="pending":W.state==="uncertain"?F.cleanup!=="unconfirmed":F.cleanup!=="confirmed")||W.state==="running"&&(W.process===void 0||W.environmentRevision===void 0))throw new G("invalid_job_result");let T=Number(W.firstCursor)-1,P=0;for(let Q of F.output){if(!U(Q)||!B(Q,["cursor","dataBase64"])||!Number.isSafeInteger(Q.cursor)||Number(Q.cursor)<=T||Number(Q.cursor)>Number(W.nextCursor))throw new G("invalid_job_result");let q=E(Q.dataBase64);if(q<=0||(P+=q)>c)throw new G("invalid_job_result");T=Number(Q.cursor)}}return A}function qA(x){if(g(x)>s)throw new G("frame_too_large");let A=$(x);if(!U(A)||!B(A,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||A.version!==H||![A.sessionId,A.operationId,A.runId].every(M)||![A.deviceId,A.rootId,A.fenceId,A.executorLaunchId].every(J)||!Z(A.generation)||!Number.isSafeInteger(A.rootGrantRevision)||Number(A.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(A.binding))||!Number.isSafeInteger(A.targetRevision)||Number(A.targetRevision)<0||A.binding==="workspace_source"&&A.targetRevision!==0||!U(A.workspace))throw new G("invalid_pty_receipt");if(!f(A.workspace))throw new G("invalid_pty_receipt");let W=MA(JSON.stringify({type:"job_result",version:I,generation:A.generation,id:A.operationId,ok:!0,job:A.job}));if(!W.ok||!W.job.pty||W.job.pty.output.length!==0||W.job.process&&W.job.process.executorLaunchId!==A.executorLaunchId)throw new G("invalid_pty_receipt");return A}function yA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId"])||A.type!=="cancel_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId))throw new G("invalid_cancel_request");return A}function mA(x){let A=$(x);if(!U(A)||!B(A,["type","version","generation","id","targetId","status"])||A.type!=="cancel_ack"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.targetId)||!["cancelled","settled","not_found","unsupported","unconfirmed"].includes(String(A.status)))throw new G("invalid_cancel_ack");return A}function wA(x){let A=JSON.stringify(x);return BA(A),A}function hA(x){let A=JSON.stringify(x);return UA(A),A}function fA(x){let A=JSON.stringify(x);return FA(A),A}function kA(x){let A=JSON.stringify(x);return IA(A),A}function HA(x){let A=JSON.stringify(x);return XA(A),A}function O(x){return typeof x==="string"&&x.length>=1&&x.length<=AA&&!x.includes("\x00")}function VA(x){let A=["type","version","generation","id","jobRequestId","verb"];if(x.verb==="help")return B(x,A)?{verb:"help"}:null;if(x.verb==="describe"||x.verb==="namespace")return B(x,[...A,"name"])&&O(x.name)?{verb:x.verb,name:x.name}:null;if(x.verb==="search"){let W=x.args;if(!B(x,[...A,"query","args"])||typeof x.query!=="string"||x.query.trim().length<1||x.query.length>xA)return null;if(W===void 0)return{verb:"search",query:x.query};if(!U(W)||!B(W,["namespace","limit"])||W.namespace!==void 0&&!O(W.namespace)||W.limit!==void 0&&(!Number.isSafeInteger(W.limit)||Number(W.limit)<1||Number(W.limit)>50))return null;return{verb:"search",query:x.query,args:{...typeof W.namespace==="string"?{namespace:W.namespace}:{},...W.limit===void 0?{}:{limit:Number(W.limit)}}}}if(x.verb!=="call"||!B(x,[...A,"name","args"])||!O(x.name)||!U(x.args)||JSON.stringify(x.args).length>K)return null;return{verb:"call",name:x.name,args:x.args}}function gA(x){let A=$(x);if(!U(A)||A.type!=="sdk_request"||A.version!==I||!Z(A.generation)||!M(A.id)||!M(A.jobRequestId))throw new G("invalid_sdk_request");let W=VA(A);if(!W)throw new G("invalid_sdk_request");return{type:"sdk_request",version:I,generation:Number(A.generation),id:A.id,jobRequestId:A.jobRequestId,...W}}function ZA(x){let A=$(x);if(!U(A)||A.type!=="sdk_response"||A.version!==I||!Z(A.generation)||!M(A.id))throw new G("invalid_sdk_response");let W={type:"sdk_response",version:I,generation:Number(A.generation),id:A.id},N=["type","version","generation","id","ok"];if(A.ok===!0&&B(A,[...N,"result"])&&typeof A.result==="string"&&A.result.length<=_)return{...W,ok:!0,result:A.result};if(A.ok===!1&&B(A,[...N,"error"])&&typeof A.error==="string"&&A.error.length>=1&&A.error.length<=_)return{...W,ok:!1,error:A.error};throw new G("invalid_sdk_response")}function EA(x){let A=JSON.stringify(x);return ZA(A),A}
4
- export{$A as Gg,KA as Hg,QA as Ig,I as Jg,b as Kg,K as Lg,D as Mg,_ as Ng,YA as Og,p as Pg,k as Qg,i as Rg,d as Sg,y as Tg,LA as Ug,s as Vg,H as Wg,m as Xg,c as Yg,OA as Zg,n as _g,t as $g,r as ah,zA as bh,l as ch,SA as dh,a as eh,w as fh,AA as gh,xA as hh,WA as ih,G as jh,M as kh,Z as lh,J as mh,C as nh,S as oh,BA as ph,UA as qh,FA as rh,IA as sh,XA as th,TA as uh,MA as vh,qA as wh,yA as xh,mA as yh,wA as zh,hA as Ah,fA as Bh,kA as Ch,HA as Dh,gA as Eh,ZA as Fh,EA as Gh};
4
+ export{$A as Ig,KA as Jg,QA as Kg,I as Lg,b as Mg,K as Ng,D as Og,_ as Pg,YA as Qg,p as Rg,k as Sg,i as Tg,d as Ug,y as Vg,LA as Wg,s as Xg,H as Yg,m as Zg,c as _g,OA as $g,n as ah,t as bh,r as ch,zA as dh,l as eh,SA as fh,a as gh,w as hh,AA as ih,xA as jh,WA as kh,G as lh,M as mh,Z as nh,J as oh,C as ph,S as qh,BA as rh,UA as sh,FA as th,IA as uh,XA as vh,TA as wh,MA as xh,qA as yh,yA as zh,mA as Ah,wA as Bh,hA as Ch,fA as Dh,kA as Eh,HA as Fh,gA as Gh,ZA as Hh,EA as Ih};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  import{createHash as f,createPublicKey as V,verify as G}from"crypto";var H="libara_device_keychain.dylib",Y="libreason_device_keychain.dylib",k=1,x=2,h=536870912,p=262144;var U=["darwin-arm64","darwin-x64"];class J extends Error{code;constructor(z,F){super(F);this.code=z;this.name="ManagedRuntimeError"}}var C=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/,N=/^[a-f0-9]{64}$/;function X(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function $(z,F,Q=[]){let Z=new Set([...F,...Q]);return F.every((W)=>(W in z))&&Object.keys(z).every((W)=>Z.has(W))}function B(z){return typeof z==="string"&&C.test(z)}function O(z){return typeof z==="string"&&!Number.isNaN(Date.parse(z))&&new Date(z).toISOString()===z}function c(z){return U.includes(z)}function I(z,F){if(!B(z)||!c(F))throw new J("invalid_release_asset","Invalid managed runtime release asset.");return`ara-runtime-v${z}-${F}`}function m(z,F){return`${I(z,F)}-${H}`}var R="managed-runtime-identity.json",D="reason-macos-background-identity-v1";function q(z){if(z===null)return"null";if(typeof z==="string"||typeof z==="boolean")return JSON.stringify(z);if(typeof z==="number"){if(!Number.isFinite(z))throw new J("invalid_manifest","Manifest numbers must be finite.");return JSON.stringify(z)}if(Array.isArray(z))return`[${z.map((F)=>q(F)).join(",")}]`;if(X(z))return`{${Object.keys(z).sort().map((F)=>`${JSON.stringify(F)}:${q(z[F])}`).join(",")}}`;throw new J("invalid_manifest","Manifest contains an unsupported value.")}function j(z){if(!X(z)||!$(z,["url","sha256","size_bytes"])||typeof z.url!=="string"||typeof z.sha256!=="string"||!N.test(z.sha256)||typeof z.size_bytes!=="number"||!Number.isSafeInteger(z.size_bytes)||z.size_bytes<=0||z.size_bytes>h)throw new J("invalid_manifest","Manifest contains an invalid runtime artifact.");let F;try{F=new URL(z.url)}catch{throw new J("invalid_manifest","Runtime artifact URL is invalid.")}if(F.protocol!=="https:"||F.username||F.password||F.hash)throw new J("invalid_manifest","Runtime artifact URL must be an HTTPS URL without credentials or a fragment.");return{url:F.toString(),sha256:z.sha256,size_bytes:z.size_bytes}}function b(z){if(!X(z)||!$(z,["broker","credential_library"]))throw new J("invalid_manifest","Manifest must bind the broker and credential library as one runtime.");return{broker:j(z.broker),credential_library:j(z.credential_library)}}function K(z){if(!X(z)||!$(z,["schema_version","version","published_at","artifacts"])||z.schema_version!==x||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Managed Reason runtime manifest is invalid.");return{schema_version:x,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":b(z.artifacts["darwin-arm64"]),"darwin-x64":b(z.artifacts["darwin-x64"])}}}function _(z){if(!X(z)||!$(z,["schema_version","version","published_at","artifacts"])||z.schema_version!==k||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Legacy managed runtime manifest is invalid.");return{schema_version:k,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":j(z.artifacts["darwin-arm64"]),"darwin-x64":j(z.artifacts["darwin-x64"])}}}function M(z){if(!X(z)||!$(z,["schema","version","published_at","artifacts"])||z.schema!==D||!B(z.version)||!O(z.published_at)||!X(z.artifacts)||!$(z.artifacts,[...U]))throw new J("invalid_manifest","Reason background identity manifest is invalid.");return{schema:D,version:z.version,published_at:z.published_at,artifacts:{"darwin-arm64":j(z.artifacts["darwin-arm64"]),"darwin-x64":j(z.artifacts["darwin-x64"])}}}function S(z){if(typeof z!=="string"||!/^[A-Za-z0-9+/]+={0,2}$/.test(z))throw new J("invalid_signature","Runtime manifest signature is invalid.");let F=Buffer.from(z,"base64");if(F.length!==64||F.toString("base64")!==z)throw new J("invalid_signature","Runtime manifest signature is invalid.");return F}function L(z){let F=z;if(typeof z==="string")try{F=JSON.parse(z)}catch{throw new J("invalid_manifest","Managed Reason runtime manifest is not valid JSON.")}if(!X(F)||!$(F,["key_id","manifest","signature"])||typeof F.key_id!=="string"||!/^[A-Za-z0-9._-]{1,80}$/.test(F.key_id)||typeof F.signature!=="string")throw new J("invalid_manifest","Signed managed Reason runtime manifest is invalid.");return F}function o(z,F){let Q=L(z),Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Runtime manifest was signed by an unknown key.");let W=K(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Runtime manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Runtime manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function E(z,F){let Q=L(z),Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Background identity manifest was signed by an unknown key.");let W=M(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Background identity manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Background identity manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function d(z,F){let Q=z;if(typeof z==="string")try{Q=JSON.parse(z)}catch{throw new J("invalid_manifest","Legacy managed runtime manifest is not valid JSON.")}if(!X(Q)||!$(Q,["key_id","manifest","signature"])||typeof Q.key_id!=="string"||!/^[A-Za-z0-9._-]{1,80}$/.test(Q.key_id)||typeof Q.signature!=="string")throw new J("invalid_manifest","Signed legacy managed runtime manifest is invalid.");let Z=F[Q.key_id];if(!Z)throw new J("untrusted_key","Legacy runtime manifest was signed by an unknown key.");let W=_(Q.manifest),w=S(Q.signature),P=!1;try{P=G(null,Buffer.from(q(W)),V(Z),w)}catch{throw new J("invalid_signature","Legacy runtime manifest signature could not be verified.")}if(!P)throw new J("invalid_signature","Legacy runtime manifest signature did not match.");return{key_id:Q.key_id,manifest:W,signature:Q.signature}}function A(z){return f("sha256").update(z).digest("hex")}function i(z,F){if(z.byteLength!==F.size_bytes)throw new J("artifact_size_mismatch","Runtime artifact size did not match its manifest.");if(A(z)!==F.sha256)throw new J("artifact_checksum_mismatch","Runtime artifact checksum did not match its manifest.")}import{existsSync as y}from"fs";import{join as T}from"path";function v(z){let F=T(z,Y);return y(F)?F:T(z,H)}
3
- export{H as Hh,Y as Ih,k as Jh,x as Kh,h as Lh,p as Mh,U as Nh,J as Oh,I as Ph,m as Qh,R as Rh,q as Sh,o as Th,E as Uh,d as Vh,A as Wh,i as Xh,v as Yh};
3
+ export{H as Jh,Y as Kh,k as Lh,x as Mh,h as Nh,p as Oh,U as Ph,J as Qh,I as Rh,m as Sh,R as Th,q as Uh,o as Vh,E as Wh,d as Xh,A as Yh,i as Zh,v as _h};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Pj as W}from"./vm-hands-entry-lite-k7fkfytm.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
2
+ import{Rj as W}from"./vm-hands-entry-lite-p30699xy.js";var T=W.string().max(201).regex(/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/).refine((Q)=>Q.split("/").every((Z)=>Z!=="."&&Z!=="..")),G=W.string().min(1).max(255).regex(/^[A-Za-z0-9_][A-Za-z0-9_./-]*$/).refine((Q)=>!Q.includes("..")&&!Q.includes("//")&&!Q.endsWith("/")&&!Q.endsWith(".lock")),M=W.string().regex(/^[a-f0-9]{40}$/),q=W.number().int().positive(),C=W.string().min(1).max(256),A=W.string().max(60000),B={version:W.literal(1),repoFullName:T},J=W.array(W.string().max(1024).regex(/^(?:Co-authored-by: [^<>\r\n\x00]+ <[^<>\s]+@[^<>\s]+>|Reason-Contributor-ID: rc_[a-f0-9]{32})$/)).max(1000),c=W.strictObject({expectedTrailers:J,missingFromHead:J}),y=W.discriminatedUnion("action",[W.strictObject({action:W.literal("edit"),title:C.optional(),body:A.optional(),base:G.optional()}),W.strictObject({action:W.enum(["ready","draft","close"])}),W.strictObject({action:W.literal("metadata"),field:W.enum(["reviewer","assignee","label"]),change:W.enum(["add","remove"]),value:W.string().min(1).max(100).refine((Q)=>!/[\r\n\0]/.test(Q))})]),d=W.discriminatedUnion("kind",[W.strictObject({...B,kind:W.literal("read"),path:W.string().min(1).max(2048),accept:W.enum(["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"]).optional()}),W.strictObject({...B,kind:W.literal("pr_review_context"),number:q,after:W.string().min(1).max(1024).optional()}),W.strictObject({...B,kind:W.literal("prepare"),branch:G,baseSha:M,defaultBranch:G,diagnosticsVersion:W.literal(1).optional()}),W.strictObject({...B,kind:W.literal("publish"),branch:G,defaultBranch:G,baseSha:M,remoteHeadSha:M.nullable(),contributorTrailers:J.optional()}),W.strictObject({...B,kind:W.literal("pr_create"),head:G,base:G,title:C,body:A,draft:W.boolean()}),W.strictObject({...B,kind:W.literal("pr_mutation"),number:q,mutation:y}),W.strictObject({...B,kind:W.literal("pr_merge"),number:q,expectedHeadSha:M,expectedBaseRef:G,method:W.enum(["merge","squash","rebase"]),commitBody:W.string().max(65536).optional()})]),O=["local_device_gh_prepare_setup","local_device_gh_prepare_metadata","local_device_gh_prepare_private_init","local_device_gh_prepare_fetch","local_device_gh_prepare_base_mismatch","local_device_gh_prepare_checkout_validation","local_device_gh_prepare_checkout_init","local_device_gh_prepare_materialization"];function h(Q){return O.some((Z)=>Z===Q)}class R extends Error{code;constructor(Q){super(Q);this.code=Q}}function ZQ(Q,Z,$){let z=d.safeParse(Q);return Z==="failed"&&z.success&&z.data.kind==="prepare"&&z.data.diagnosticsVersion===1&&h($)}var x=245760,$Q=W.discriminatedUnion("kind",[W.strictObject({kind:W.literal("pr_review_context"),body:W.string().max(x)}),W.strictObject({kind:W.literal("prepare"),headSha:M}),W.strictObject({kind:W.literal("read"),status:W.number().int().min(200).max(599),headers:W.record(W.string(),W.string().max(8192)).refine((Q)=>Object.keys(Q).every((Z)=>Z==="link"||Z==="content-type")),body:W.string().max(x)}),W.strictObject({kind:W.literal("publish"),headSha:M,scannedObjectCount:W.number().int().min(0).max(5000),attribution:c.optional()}),W.strictObject({kind:W.literal("pr_create"),url:W.string().max(1024).regex(/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]*$/)}),W.strictObject({kind:W.literal("pr_mutation"),number:q,applied:W.literal(!0)}),W.strictObject({kind:W.literal("pr_merge"),number:q,merged:W.literal(!0)})]).refine((Q)=>new TextEncoder().encode(JSON.stringify(Q)).byteLength<=x,"local_device_gh_result_too_large"),r=W.strictObject({source:W.enum(["agent","human"]),operationId:W.uuid()}),m=W.strictObject({version:W.literal(1),userId:W.guid(),deviceId:W.guid(),rootId:W.guid(),runId:W.guid(),merge:r.optional(),contributorRefresh:W.guid().optional(),repoFullName:T.nullable(),rootRevision:W.string().regex(/^[1-9][0-9]*$/),readOnly:W.boolean(),generation:W.number().int().positive().nullable(),fenceId:W.guid().nullable()}).refine((Q)=>Q.generation===null===(Q.fenceId===null));function P(Q){return/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(Q)&&Q.split("/").every((Z)=>Z!=="."&&Z!=="..")}function KQ(Q,Z,$={},z="read"){if(P(Q)&&(Z==="/search/issues"||Z.startsWith("/search/issues?")))return p(Q,Z,$);if(!P(Q)||!Z.startsWith(`/repos/${Q}/`)&&Z!==`/repos/${Q}`)throw Error("local_device_gh_repository_mismatch");if(/[\\#\u0000-\u001f]/.test(Z)||/%(?:2e|5c|00)/i.test(Z))throw Error("local_device_gh_path_denied");let V=new URL(Z,"https://api.github.com");if(V.pathname!==Z.split("?")[0]||V.username||V.password)throw Error("local_device_gh_path_denied");let Y;try{Y=decodeURIComponent(V.pathname.slice(`/repos/${Q}`.length))}catch{throw Error("local_device_gh_path_denied")}if(Y.includes("%")||Y.split("/").some((D)=>D==="."||D===".."))throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");if(![/^$/,/^\/commits$/,/^\/pulls$/,/^\/pulls\/[1-9][0-9]*(?:\/(?:commits|files|reviews|comments))?$/,/^\/issues\/[1-9][0-9]*(?:\/comments)?$/,/^\/issues\/comments\/[1-9][0-9]*\/reactions$/,/^\/commits\/[A-Za-z0-9_./-]+(?:\/(?:check-runs|status))?$/,/^\/check-runs\/[1-9][0-9]*(?:\/annotations)?$/,/^\/branches\/[A-Za-z0-9_./-]+$/,/^\/git\/ref\/heads\/[A-Za-z0-9_./-]+$/,/^\/compare\/[A-Za-z0-9_./-]+\.\.\.[A-Za-z0-9_./-]+$/].some((D)=>D.test(Y)))throw Error("local_device_gh_path_denied");if(V.searchParams.forEach((D,X)=>{if(X==="per_page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(X==="page"&&/^[1-9][0-9]*$/.test(D)&&Number(D)<=100)return;if(Y==="/pulls"&&X==="state"&&["open","closed","all"].includes(D))return;if(Y==="/pulls"&&X==="sort"&&D==="updated")return;if(Y==="/pulls"&&X==="direction"&&D==="desc")return;if(Y==="/pulls"&&["head","base"].includes(X)&&/^[A-Za-z0-9_./:-]{1,255}$/.test(D))return;throw Error("local_device_gh_query_denied")}),$.headers)new Headers($.headers).forEach((X,_)=>{if(_!=="accept"||!["application/vnd.github+json","application/vnd.github.full+json","application/vnd.github.v3.diff"].includes(X))throw Error("local_device_gh_header_denied")})}function p(Q,Z,$){if(/[\\#\u0000-\u001f]/.test(Z))throw Error("local_device_gh_path_denied");let z=new URL(Z,"https://api.github.com");if(z.pathname!=="/search/issues"||z.username||z.password)throw Error("local_device_gh_path_denied");if(($.method??"GET").toUpperCase()!=="GET"||$.body!=null)throw Error("local_device_gh_mutation_not_admitted");let V=null;z.searchParams.forEach((H,D)=>{if(D==="q"&&V===null){V=H;return}if(D==="per_page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;if(D==="page"&&/^[1-9][0-9]*$/.test(H)&&Number(H)<=100)return;throw Error("local_device_gh_query_denied")});let Y=`repo:${Q.toLowerCase()} `,N=V?.toLowerCase()??"";if(N.length>512||!(N+" ").startsWith(Y)||/(?:^|\s)(?:repo|org|user):/.test(N.slice(Y.length)))throw Error("local_device_gh_query_denied");if($.headers)new Headers($.headers).forEach((H,D)=>{if(D!=="accept"||H!=="application/vnd.github+json")throw Error("local_device_gh_header_denied")})}var DQ=`query PullRequestReviewContext($owner: String!, $repo: String!, $number: Int!, $after: String) {
3
3
  repository(owner: $owner, name: $repo) {
4
4
  nameWithOwner
5
5
  pullRequest(number: $number) {
@@ -39,4 +39,4 @@ import{Pj as W}from"./vm-hands-entry-lite-k7fkfytm.js";var T=W.string().max(201)
39
39
  `)||!/^[a-f0-9]{64}$/.test(Q.bodySha256))throw Error("Invalid Reason Device proof input.");return Buffer.from([Z,$,Q.pathAndQuery,Q.timestamp,Q.nonce,Q.challenge,Q.bodySha256].join(`
40
40
  `),"utf8")}function K(Q){return Boolean(Q)&&typeof Q==="object"&&!Array.isArray(Q)}function t(Q,Z){return typeof Q==="string"&&Z.some(($)=>$===Q)}function k(Q){return K(Q)&&typeof Q.id==="string"&&typeof Q.label==="string"&&typeof Q.path_fingerprint==="string"}function v(Q){return K(Q)&&Number.isInteger(Q.seq)&&Number(Q.seq)>=0&&typeof Q.kind==="string"&&/^[A-Za-z0-9._:-]{1,64}$/.test(Q.kind)&&K(Q.payload)}function w(Q){throw Error(Q)}function QW(Q,Z){let $=K(Q)?Q:{},z=typeof $.error==="string"?$.error:`http_${Z}`,V=typeof $.detail==="string"?$.detail:typeof $.message==="string"?$.message:`Reason Device request failed (${Z})`;return{code:z,message:V}}function l(Q){if(!K(Q)||typeof Q.challenge!=="string"||Q.challenge.length<16||Q.challenge.length>1024||Q.challenge.includes(`
41
41
  `)||typeof Q.expires_at!=="string"||!Number.isFinite(Date.parse(Q.expires_at)))w("Reason returned an invalid Device proof challenge.");return{challenge:Q.challenge,expires_at:Q.expires_at}}function L(Q,Z){if(!K(Q)||typeof Q.device_id!=="string"||Q.auth_scheme!=="p256"||Q.organization_id!==void 0&&typeof Q.organization_id!=="string"||Q.protocol_version!==j||!Array.isArray(Q.roots)||!Q.roots.every(k)||Z&&typeof Q.organization_id!=="string"||Q.device_credential!==void 0)w(Z?"Reason returned an invalid Device enrollment.":"Reason returned an invalid Device registration.");return{...{device_id:Q.device_id,...typeof Q.organization_id==="string"?{organization_id:Q.organization_id}:{},protocol_version:j,roots:Q.roots},auth_scheme:"p256"}}function WW(Q){return L(Q,!1)}function ZW(Q){let Z=L(Q,!0);if(typeof Z.organization_id!=="string")return w("Reason returned an invalid Device enrollment.");return{...Z,organization_id:Z.organization_id}}function $W(Q){if(!K(Q)||typeof Q.server_time!=="string"||typeof Q.drain!=="boolean")return w("Reason returned an invalid Device heartbeat.");return{server_time:Q.server_time,drain:Q.drain,...f(Q),...typeof Q.update_policy==="string"||Q.update_policy===null?{update_policy:Q.update_policy}:{},...typeof Q.supported_protocol_version==="number"?{supported_protocol_version:Q.supported_protocol_version}:{},...a(Q.latest_cli_versions),...Q.hands_prespawn===!0?{hands_prespawn:!0}:{}}}var u=["account_root_metadata_supported","workspace_root_metadata_supported","account_root_path_supported","home_contained_roots_supported","root_paths_supported","startup_supported"];function f(Q){return Object.fromEntries(u.filter((Z)=>Q[Z]===!0).map((Z)=>[Z,!0]))}function KW(Q){if(!K(Q))return;try{return{...l(Q),...f(Q)}}catch{return}}function a(Q){if(!K(Q))return{};let Z={};for(let $ of s){let z=Q[$];if(typeof z==="string"&&/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/.test(z))Z[$]=z}return Object.keys(Z).length>0?{latest_cli_versions:Z}:{}}function DW(Q){if(!K(Q)||!Array.isArray(Q.roots)||!Q.roots.every(k))return w("Reason returned an invalid Device root sync.");return{roots:Q.roots}}function zW(Q){if(!K(Q)||Q.user_id!==void 0&&typeof Q.user_id!=="string"||typeof Q.organization_id!=="string"||typeof Q.organization_name!=="string"||typeof Q.organization_slug!=="string")return w("Reason returned an invalid Device identity.");return{...typeof Q.user_id==="string"?{user_id:Q.user_id}:{},organization_id:Q.organization_id,organization_name:Q.organization_name,organization_slug:Q.organization_slug}}function FW(Q){if(!K(Q)||Q.disconnected!==!0)return w("Reason did not disconnect this Device.");let Z=Q.sessions_moved;return typeof Z==="number"&&Number.isSafeInteger(Z)&&Z>=0?{disconnected:!0,sessions_moved:Z}:{disconnected:!0}}function wW(Q){if(K(Q)&&Q.ok===!0&&typeof Q.expires==="number")return{ok:!0,expires:Q.expires};if(K(Q)&&Q.ok===!1&&typeof Q.error==="string")return{ok:!1,error:Q.error};return w("Reason did not answer the local login hand-over.")}function VW(Q){if(!K(Q)||Q.accepted!==!0)return w("Reason did not accept the Device lifecycle event.");return{accepted:!0}}function e(Q){return Buffer.byteLength(JSON.stringify(Q),"utf8")}function YW(Q,Z=b){if(!K(Q)||typeof Q.operation_id!=="string"||typeof Q.attempt_id!=="string"||typeof Q.attempt_token!=="string"||!/^(?:reason|ara)_attempt_/.test(Q.attempt_token)||typeof Q.lease_until!=="string"||typeof Q.run_id!=="string"||typeof Q.root_id!=="string"||Q.owner!==void 0&&!E(Q.owner)||!t(Q.capability,Z)||!K(Q.payload)||Q.protocol_version!==j||e(Q.payload)>n||Q.authority!==void 0&&!U(Q.authority)||Q.local_github_authority!==void 0&&!m.safeParse(Q.local_github_authority).success||Q.capability==="github.local.v1"&&!m.safeParse(Q.local_github_authority).success||Q.recording_authority!==void 0&&!S(Q.recording_authority)||Q.capability==="browser.recording.v1"&&(!S(Q.recording_authority)||!E(Q.owner))||Q.capability!=="browser.recording.v1"&&Q.recording_authority!==void 0)return w("Reason returned an invalid Device operation claim.");let $={operation_id:Q.operation_id,attempt_id:Q.attempt_id,attempt_token:Q.attempt_token,lease_until:Q.lease_until,run_id:Q.run_id,root_id:Q.root_id,capability:Q.capability,payload:Q.payload,...U(Q.authority)?{authority:Q.authority}:{},...S(Q.recording_authority)?{recording_authority:Object.freeze({...Q.recording_authority})}:{},...Q.local_github_authority!==void 0?{local_github_authority:m.parse(Q.local_github_authority)}:{},...Q.capability==="hands.connect"&&K(Q.environment)&&K(Q.environment.payload)&&U(Q.environment.authority)?{environment:{payload:Q.environment.payload,authority:Q.environment.authority}}:{},protocol_version:j};if(Q.owner!==void 0)$.owner=Object.freeze({...Q.owner});return $}function HW(Q){if(!K(Q)||typeof Q.lease_until!=="string"||!Array.isArray(Q.controls)||!Q.controls.every(v)||!Number.isInteger(Q.next_control_seq)||Number(Q.next_control_seq)<0)return w("Reason returned an invalid Device operation heartbeat.");return{lease_until:Q.lease_until,controls:Q.controls,next_control_seq:Number(Q.next_control_seq)}}function XW(Q){if(!K(Q)||!Number.isInteger(Q.next_event_seq)||Number(Q.next_event_seq)<0||typeof Q.duplicate!=="boolean"||!Number.isInteger(Q.accepted_count)||Number(Q.accepted_count)<0)return w("Reason returned an invalid Device operation event result.");return{next_event_seq:Number(Q.next_event_seq),duplicate:Q.duplicate,accepted_count:Number(Q.accepted_count)}}function GW(Q){if(!K(Q)||!K(Q.payload)||!U(Q.authority))return w("Reason returned an invalid Device environment delivery.");return{payload:Q.payload,authority:Q.authority}}function QQ(Q){return Q==="succeeded"||Q==="failed"||Q==="cancelled"||Q==="expired"}function BW(Q){if(!K(Q)||!QQ(Q.status)||typeof Q.idempotent!=="boolean")return w("Reason returned an invalid Device operation completion.");return{status:Q.status,idempotent:Q.idempotent}}
42
- export{d as oe,R as pe,ZQ as qe,x as re,$Q as se,m as te,KQ as ue,DQ as ve,zQ as we,b as xe,j as ye,I as ze,n as Ae,HQ as Be,XQ as Ce,GQ as De,BQ as Ee,MQ as Fe,gQ as Ge,qQ as He,NQ as Ie,mQ as Je,UQ as Ke,jQ as Le,xQ as Me,JQ as Ne,SQ as Oe,IQ as Pe,PQ as Qe,TQ as Re,CQ as Se,AQ as Te,bQ as Ue,EQ as Ve,kQ as We,LQ as Xe,fQ as Ye,_Q as Ze,cQ as _e,yQ as $e,dQ as af,OQ as bf,hQ as cf,RQ as df,rQ as ef,pQ as ff,nQ as gf,oQ as hf,sQ as if,iQ as jf,tQ as kf,vQ as lf,lQ as mf,uQ as nf,i as of,aQ as pf,eQ as qf,QW as rf,l as sf,WW as tf,ZW as uf,$W as vf,KW as wf,DW as xf,zW as yf,FW as zf,wW as Af,VW as Bf,YW as Cf,HW as Df,XW as Ef,GW as Ff,BW as Gf};
42
+ export{d as qe,R as re,ZQ as se,x as te,$Q as ue,m as ve,KQ as we,DQ as xe,zQ as ye,b as ze,j as Ae,I as Be,n as Ce,HQ as De,XQ as Ee,GQ as Fe,BQ as Ge,MQ as He,gQ as Ie,qQ as Je,NQ as Ke,mQ as Le,UQ as Me,jQ as Ne,xQ as Oe,JQ as Pe,SQ as Qe,IQ as Re,PQ as Se,TQ as Te,CQ as Ue,AQ as Ve,bQ as We,EQ as Xe,kQ as Ye,LQ as Ze,fQ as _e,_Q as $e,cQ as af,yQ as bf,dQ as cf,OQ as df,hQ as ef,RQ as ff,rQ as gf,pQ as hf,nQ as if,oQ as jf,sQ as kf,iQ as lf,tQ as mf,vQ as nf,lQ as of,uQ as pf,i as qf,aQ as rf,eQ as sf,QW as tf,l as uf,WW as vf,ZW as wf,$W as xf,KW as yf,DW as zf,zW as Af,FW as Bf,wW as Cf,VW as Df,YW as Ef,HW as Ff,XW as Gf,GW as Hf,BW as If};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Di as v,Gi as _,Ii as w,Mi as S,Ni as x}from"./vm-hands-entry-lite-0p3438xe.js";import{Si as I}from"./vm-hands-entry-lite-tbps80f1.js";import{qj as O}from"./vm-hands-entry-lite-t50b2jyp.js";import{Jj as L,Kj as T}from"./vm-hands-entry-lite-avstvbbc.js";import{bk as G}from"./vm-hands-entry-lite-hw8vgsmm.js";import{spawnSync as l}from"child_process";import{dirname as B}from"path";import{spawn as y}from"child_process";import{accessSync as c,constants as g}from"fs";import{basename as h,join as m}from"path";var j=null;function U(q){if(j===q)j=null;if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}var C=(q,z)=>{if(j)U(j);let J=m(q,v);try{c(J,g.X_OK)}catch{return()=>{}}let F;try{F=y(J,["--app",q,"--name",h(q,".app"),"--permission",z==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return F.on("error",()=>{if(j===F)j=null}),F.once("exit",()=>{if(j===F)j=null}),F.unref(),j=F,()=>U(F)};var M=`Reason permissions
2
+ import{Fi as v,Ii as _,Ki as w,Oi as S,Pi as x}from"./vm-hands-entry-lite-5cmafbnh.js";import{Ui as I}from"./vm-hands-entry-lite-0rwpp6hr.js";import{sj as O}from"./vm-hands-entry-lite-21856esq.js";import{Lj as L,Mj as T}from"./vm-hands-entry-lite-6gtpyxz7.js";import{dk as G}from"./vm-hands-entry-lite-1c1rxx8v.js";import{spawnSync as l}from"child_process";import{dirname as B}from"path";import{spawn as y}from"child_process";import{accessSync as c,constants as g}from"fs";import{basename as h,join as m}from"path";var j=null;function U(q){if(j===q)j=null;if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}var C=(q,z)=>{if(j)U(j);let J=m(q,v);try{c(J,g.X_OK)}catch{return()=>{}}let F;try{F=y(J,["--app",q,"--name",h(q,".app"),"--permission",z==="screen"?"screen_recording":"accessibility"],{detached:!0,stdio:"ignore"})}catch{return()=>{}}return F.on("error",()=>{if(j===F)j=null}),F.once("exit",()=>{if(j===F)j=null}),F.unref(),j=F,()=>U(F)};var M=`Reason permissions
3
3
 
4
4
  Usage:
5
5
  reason permissions [--json]
@@ -14,7 +14,7 @@ The macOS privacy permissions of this computer's Reason worker:
14
14
  allow asks for each missing one, or the one named. macOS cannot ask for Full
15
15
  Disk Access: allow disk opens its pane, shows the file to add in Finder and
16
16
  waits until the worker has it.
17
- `,D="x-apple.systempreferences:com.apple.preference.security",a="curl -fsSL https://reasonmachines.com/install.sh | bash",d=180000,n=2000,E=["screen","accessibility","disk"],N={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${D}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${D}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${D}?Privacy_AllFiles`}};function k(q){return q.executable}function p(q,z){if(q==="computer_use_identity_missing")return`Reason's background identity is not installed (${q}); reinstall Reason: ${a}`;if(q==="computer_use_identity_outdated")return`Reason's background identity is outdated (${w(z)??"unknown"}; this CLI is ${O}) (${q}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${q}); run the installed \`reason\``}function s(q=I()){let z=S(q);if(z.length>0)return{state:"ready",path:B(B(B(z[0]))),prefix:z};let J=x(z,q)??"computer_use_identity_unavailable";return{state:J,path:_(q),detail:p(J,q)}}function u(){return{identity:()=>s(),grants:(q)=>L(q),request:(q,z)=>T(q,z),worker:async()=>(await import("./status-edb6wpzh.js")).connectionMacState(),open:(q)=>{l("/usr/bin/open",q,{stdio:"ignore",timeout:1e4})},tile:C,restartConnection:async()=>(await import("./connect-cli-9v34nh0s.js")).restartConnection(),sleep:(q)=>new Promise((z)=>setTimeout(z,q)),now:()=>Date.now()}}function P(q,z,J){if(q.state!=="ready"||!z)return"unknown";return z[J]?"granted":"missing"}async function b(q){let z=q.identity(),J=z.state==="ready"?await q.grants(z.prefix):null,F=await q.worker(),X=F?k(F):null,Q=!X||F?.full_disk_access==="unknown"?"unknown":F?.full_disk_access==="granted"?"granted":"missing",$=(K,H,Z)=>{let{label:R,purpose:W,level:V}=N[K];return{id:K,label:R,purpose:W,level:V,state:H,holder:Z}};return{identity:{state:z.state,path:z.path,detail:z.state==="ready"?null:z.detail},worker_detail:X?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[$("screen",P(z,J,"screen"),z.path),$("accessibility",P(z,J,"accessibility"),z.path),$("disk",Q,X)]}}function Rq(q){let z=q.identity.state==="ready"?null:q.identity.state,J=q.permissions.filter((Q)=>Q.state==="granted").length,F=[...z?[z]:[],...q.permissions.filter((Q)=>Q.state!=="granted"&&!(z&&Q.id!=="disk")).map((Q)=>`${Q.label} ${Q.state}`)],X=!z&&q.permissions.some((Q)=>Q.state==="missing");return`Permissions: ${J} of ${q.permissions.length}${F.length>0?` (${F.join(", ")})`:""}`+(X?" \u2014 reason permissions allow":F.length>0?" \u2014 reason permissions":"")}function t(q){let z=[];if(q.identity.detail)z.push(q.identity.detail);z.push(`Reason: ${q.identity.path}`);let J=q.permissions.find((F)=>F.id==="disk");z.push(J?.holder?`Worker: ${J.holder}`:`Worker: ${q.worker_detail}`),z.push("");for(let F of q.permissions){let X=`${F.label}${F.level==="recommended"?" (recommended)":""}`;z.push(` ${F.id.padEnd(13)} ${F.state.padEnd(7)} ${X}: ${F.purpose}`)}if(q.permissions.some((F)=>F.state==="missing"))z.push("","Allow the missing ones: reason permissions allow");return`${z.join(`
17
+ `,D="x-apple.systempreferences:com.apple.preference.security",a="curl -fsSL https://reasonmachines.com/install.sh | bash",d=180000,n=2000,E=["screen","accessibility","disk"],N={screen:{label:"Screen & System Audio Recording",purpose:"desktop video, computer-use screenshots",level:"required",pane:`${D}?Privacy_ScreenCapture`},accessibility:{label:"Accessibility",purpose:"computer-use clicks and typing, desktop input",level:"required",pane:`${D}?Privacy_Accessibility`},disk:{label:"Full Disk Access",purpose:"Sessions in Desktop, Documents, Downloads, iCloud Drive and Mail",level:"recommended",pane:`${D}?Privacy_AllFiles`}};function k(q){return q.executable}function p(q,z){if(q==="computer_use_identity_missing")return`Reason's background identity is not installed (${q}); reinstall Reason: ${a}`;if(q==="computer_use_identity_outdated")return`Reason's background identity is outdated (${w(z)??"unknown"}; this CLI is ${O}) (${q}); \`reason update\` installs this release's`;return`Reason's background identity cannot run computer use for this CLI (${q}); run the installed \`reason\``}function s(q=I()){let z=S(q);if(z.length>0)return{state:"ready",path:B(B(B(z[0]))),prefix:z};let J=x(z,q)??"computer_use_identity_unavailable";return{state:J,path:_(q),detail:p(J,q)}}function u(){return{identity:()=>s(),grants:(q)=>L(q),request:(q,z)=>T(q,z),worker:async()=>(await import("./status-gwe4v7q7.js")).connectionMacState(),open:(q)=>{l("/usr/bin/open",q,{stdio:"ignore",timeout:1e4})},tile:C,restartConnection:async()=>(await import("./connect-cli-9ef3cz0p.js")).restartConnection(),sleep:(q)=>new Promise((z)=>setTimeout(z,q)),now:()=>Date.now()}}function P(q,z,J){if(q.state!=="ready"||!z)return"unknown";return z[J]?"granted":"missing"}async function b(q){let z=q.identity(),J=z.state==="ready"?await q.grants(z.prefix):null,F=await q.worker(),X=F?k(F):null,Q=!X||F?.full_disk_access==="unknown"?"unknown":F?.full_disk_access==="granted"?"granted":"missing",$=(K,H,Z)=>{let{label:R,purpose:W,level:V}=N[K];return{id:K,label:R,purpose:W,level:V,state:H,holder:Z}};return{identity:{state:z.state,path:z.path,detail:z.state==="ready"?null:z.detail},worker_detail:X?null:"Full Disk Access is read from this computer's running worker; `reason connect` starts it.",permissions:[$("screen",P(z,J,"screen"),z.path),$("accessibility",P(z,J,"accessibility"),z.path),$("disk",Q,X)]}}function Rq(q){let z=q.identity.state==="ready"?null:q.identity.state,J=q.permissions.filter((Q)=>Q.state==="granted").length,F=[...z?[z]:[],...q.permissions.filter((Q)=>Q.state!=="granted"&&!(z&&Q.id!=="disk")).map((Q)=>`${Q.label} ${Q.state}`)],X=!z&&q.permissions.some((Q)=>Q.state==="missing");return`Permissions: ${J} of ${q.permissions.length}${F.length>0?` (${F.join(", ")})`:""}`+(X?" \u2014 reason permissions allow":F.length>0?" \u2014 reason permissions":"")}function t(q){let z=[];if(q.identity.detail)z.push(q.identity.detail);z.push(`Reason: ${q.identity.path}`);let J=q.permissions.find((F)=>F.id==="disk");z.push(J?.holder?`Worker: ${J.holder}`:`Worker: ${q.worker_detail}`),z.push("");for(let F of q.permissions){let X=`${F.label}${F.level==="recommended"?" (recommended)":""}`;z.push(` ${F.id.padEnd(13)} ${F.state.padEnd(7)} ${X}: ${F.purpose}`)}if(q.permissions.some((F)=>F.state==="missing"))z.push("","Allow the missing ones: reason permissions allow");return`${z.join(`
18
18
  `)}
19
19
  `}async function A(q,z){let J=z.now()+d;for(;;){if(await q())return!0;if(z.now()>=J)return!1;await z.sleep(n)}}async function o(q,z){let J=z.host??u(),{io:F}=z,X=await b(J),Q=X.permissions.filter((Z)=>q.includes(Z.id)&&Z.state!=="granted");if(Q.length===0)return F.stdout.write(`Reason permissions: ${q.map((Z)=>N[Z].label).join(", ")} already allowed.
20
20
  `),0;let $=!1,K=!1,H=J.identity();for(let Z of Q){let{label:R,pane:W}=N[Z.id];if(Z.id!=="disk"){if(H.state!=="ready"){if(!$)F.stderr.write(`Reason permissions: ${H.detail}
@@ -34,4 +34,4 @@ ${M}`),1;if(F.command==="help")return J.stdout.write(M),0;let X=z.platform??proc
34
34
  `:`Reason permissions: macOS privacy permissions do not apply on this computer.
35
35
  `),0;let Q=z.host??u();if(F.command==="allow")return o(F.ids,{io:J,wait:!0,host:Q});let $=await b(Q);return J.stdout.write(F.json?`${JSON.stringify({platform:X,applicable:!0,...$},null,2)}
36
36
  `:t($)),0}
37
- export{C as qi,M as ri,E as si,k as ti,s as ui,b as vi,Rq as wi,t as xi,o as yi,i as zi,Vq as Ai};
37
+ export{C as si,M as ti,E as ui,k as vi,s as wi,b as xi,Rq as yi,t as zi,o as Ai,i as Bi,Vq as Ci};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- var r={name:"github-native-engineer-device-worker-production",version:"0.2.364",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
3
- export{r as uj};
2
+ var r={name:"github-native-engineer-device-worker-production",version:"0.2.367",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@anthropic-ai/sandbox-runtime":"^0.0.73","@earendil-works/pi-tui":"1.0.0","@modelcontextprotocol/sdk":"^1.29.0","@reason/runtime-distribution":"workspace:*","playwright-core":"1.60.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"1.20.0","basic-ftp":"6.2.1","@grpc/grpc-js":"1.14.5",browserslist:"4.28.8","engine.io":"6.6.7","fast-uri":"3.1.8",hono:"^4.13.7","ip-address":"10.7.1",nanoid:"3.3.18",dompurify:"3.4.13",postcss:"8.5.23",qs:"6.16.0","shell-quote":"1.11.0","socket.io-parser":"4.2.7",tmp:"0.2.7",toml:"4.2.0",undici:"8.10.2",ws:"^8.21.0","js-yaml":"4.3.2","@modelcontextprotocol/sdk":"1.31.0","proxy-addr":"2.0.8","source-map-js":"1.2.2"}};
3
+ export{r as wj};