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

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 (85) hide show
  1. package/bin/ara +1 -1
  2. package/bin/vm-hands/api-13266c99.js +2 -0
  3. package/bin/vm-hands/api-credentials-q6vq26w0.js +2 -0
  4. package/bin/vm-hands/{ask-relay-7yw62yzw.js → ask-relay-ar561trh.js} +3 -3
  5. package/bin/vm-hands/connect-cli-gjf47h7z.js +2 -0
  6. package/bin/vm-hands/custom-endpoint-device-m1kn3rkk.js +2 -0
  7. package/bin/vm-hands/desktop-account-vfbchnax.js +2 -0
  8. package/bin/vm-hands/{device-workspace-c05vq771.js → device-workspace-nvcschtn.js} +1 -1
  9. package/bin/vm-hands/{hands-worker-source-wfv9csj2.js → hands-worker-source-k9k2vj4y.js} +1 -1
  10. package/bin/vm-hands/{index-80ep9259.js → index-ae8w22py.js} +1 -1
  11. package/bin/vm-hands/{install-receipt-pbfhgaxc.js → install-receipt-4cnygt5g.js} +1 -1
  12. package/bin/vm-hands/local-automation-0j57c21p.js +2 -0
  13. package/bin/vm-hands/local-capabilities-6pqbn5wm.js +2 -0
  14. package/bin/vm-hands/local-desktop-users-nwyzyc05.js +2 -0
  15. package/bin/vm-hands/local-display-mac-ewqyyxk5.js +2 -0
  16. package/bin/vm-hands/local-display-session-a3rr41av.js +2 -0
  17. package/bin/vm-hands/local-pty-session-8k64gfn8.js +2 -0
  18. package/bin/vm-hands/{managed-runtime-vkw66kvt.js → managed-runtime-3fkrr7cf.js} +1 -1
  19. package/bin/vm-hands/{network-contract-zjq3w2n3.js → network-contract-wep9fv9j.js} +1 -1
  20. package/bin/vm-hands/package-pfdm6awy.js +2 -0
  21. package/bin/vm-hands/permissions-d87nq1as.js +2 -0
  22. package/bin/vm-hands/{reason-hands-protocol-aj1zwpk0.js → reason-hands-protocol-78nr9pzf.js} +1 -1
  23. package/bin/vm-hands/serve-service-tzdt63z3.js +2 -0
  24. package/bin/vm-hands/{status-edb6wpzh.js → status-9420cxy5.js} +2 -2
  25. package/bin/vm-hands/version-ss8wa2cx.js +2 -0
  26. package/bin/vm-hands/{vm-hands-entry-lite-1hv536wk.js → vm-hands-entry-lite-01sqtryp.js} +1 -1
  27. package/bin/vm-hands/{vm-hands-entry-lite-62x9nv6n.js → vm-hands-entry-lite-1k23f7ja.js} +3 -3
  28. package/bin/vm-hands/{vm-hands-entry-lite-4xfs7y6w.js → vm-hands-entry-lite-1mrkcz0p.js} +1 -1
  29. package/bin/vm-hands/{vm-hands-entry-lite-dqnhebfx.js → vm-hands-entry-lite-2fpxf6vm.js} +1 -1
  30. package/bin/vm-hands/{vm-hands-entry-lite-jjkkee8q.js → vm-hands-entry-lite-630eqwb4.js} +2 -2
  31. package/bin/vm-hands/{vm-hands-entry-lite-cety9pka.js → vm-hands-entry-lite-7jhh57qs.js} +2 -2
  32. package/bin/vm-hands/{vm-hands-entry-lite-jpkf3569.js → vm-hands-entry-lite-7wgbj1kg.js} +2 -2
  33. package/bin/vm-hands/{vm-hands-entry-lite-qy9xzp2m.js → vm-hands-entry-lite-8a1zycjh.js} +2 -2
  34. package/bin/vm-hands/{vm-hands-entry-lite-t50b2jyp.js → vm-hands-entry-lite-8crh75hs.js} +2 -2
  35. package/bin/vm-hands/{vm-hands-entry-lite-hfq6jjnh.js → vm-hands-entry-lite-arhbwrn1.js} +1 -1
  36. package/bin/vm-hands/{vm-hands-entry-lite-7nk0873d.js → vm-hands-entry-lite-ay6sk3xm.js} +1 -1
  37. package/bin/vm-hands/{vm-hands-entry-lite-cwf21py1.js → vm-hands-entry-lite-bhgsayph.js} +1 -1
  38. package/bin/vm-hands/{vm-hands-entry-lite-vcm4389c.js → vm-hands-entry-lite-cas0c9qd.js} +2 -2
  39. package/bin/vm-hands/{vm-hands-entry-lite-pkjkgy7n.js → vm-hands-entry-lite-cvc79v3m.js} +1 -1
  40. package/bin/vm-hands/{vm-hands-entry-lite-fr2k6eah.js → vm-hands-entry-lite-cvft83sx.js} +2 -2
  41. package/bin/vm-hands/{vm-hands-entry-lite-tf1tkqkw.js → vm-hands-entry-lite-d0f4kbc8.js} +2 -2
  42. package/bin/vm-hands/{vm-hands-entry-lite-e95w4ea8.js → vm-hands-entry-lite-es39m2mg.js} +2 -2
  43. package/bin/vm-hands/{vm-hands-entry-lite-avstvbbc.js → vm-hands-entry-lite-g63y988w.js} +2 -2
  44. package/bin/vm-hands/{vm-hands-entry-lite-0p3438xe.js → vm-hands-entry-lite-gs8cpdfw.js} +2 -2
  45. package/bin/vm-hands/{vm-hands-entry-lite-xhr0m9r0.js → vm-hands-entry-lite-h6qss80e.js} +1 -1
  46. package/bin/vm-hands/{vm-hands-entry-lite-k7fkfytm.js → vm-hands-entry-lite-hzsk6tpw.js} +2 -2
  47. package/bin/vm-hands/{vm-hands-entry-lite-p1nb6n3r.js → vm-hands-entry-lite-jd49j573.js} +2 -2
  48. package/bin/vm-hands/{vm-hands-entry-lite-vfn61qq2.js → vm-hands-entry-lite-m2h8vdr0.js} +2 -2
  49. package/bin/vm-hands/{vm-hands-entry-lite-tbps80f1.js → vm-hands-entry-lite-m57kpdgb.js} +2 -2
  50. package/bin/vm-hands/{vm-hands-entry-lite-kxtjkzzh.js → vm-hands-entry-lite-p24kmysw.js} +1 -1
  51. package/bin/vm-hands/{vm-hands-entry-lite-xj0p1ax7.js → vm-hands-entry-lite-p7hxm3hc.js} +2 -2
  52. package/bin/vm-hands/{vm-hands-entry-lite-hw8vgsmm.js → vm-hands-entry-lite-pby299bv.js} +1 -1
  53. package/bin/vm-hands/{vm-hands-entry-lite-25rpwc1k.js → vm-hands-entry-lite-pcavxb2v.js} +2 -2
  54. package/bin/vm-hands/{vm-hands-entry-lite-0763vz5v.js → vm-hands-entry-lite-pd4gdky1.js} +1 -1
  55. package/bin/vm-hands/{vm-hands-entry-lite-5y2kfnv2.js → vm-hands-entry-lite-pk2xd13q.js} +2 -2
  56. package/bin/vm-hands/{vm-hands-entry-lite-6fvjbwqq.js → vm-hands-entry-lite-qxnzwjrp.js} +1 -1
  57. package/bin/vm-hands/{vm-hands-entry-lite-vb4nyef6.js → vm-hands-entry-lite-rax2e8y2.js} +1 -1
  58. package/bin/vm-hands/{vm-hands-entry-lite-v65nk88n.js → vm-hands-entry-lite-saqwe5sm.js} +2 -2
  59. package/bin/vm-hands/{vm-hands-entry-lite-zn303jrg.js → vm-hands-entry-lite-vebspwdp.js} +1 -1
  60. package/bin/vm-hands/{vm-hands-entry-lite-t5kt2wff.js → vm-hands-entry-lite-wdsk86sk.js} +2 -2
  61. package/bin/vm-hands/{vm-hands-entry-lite-w3cfhkv2.js → vm-hands-entry-lite-y9mpztzd.js} +2 -2
  62. package/bin/vm-hands/{vm-hands-entry-lite-w3xhwb5h.js → vm-hands-entry-lite-zam0fx58.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-3h6qvnbd.js} +1 -1
  65. package/bin/vm-hands/vm-hands-op-runner-awbk4j07.js +2 -0
  66. package/bin/vm-hands/{vm-hands-runtime-1342fjjh.js → vm-hands-runtime-n31ghckd.js} +3 -3
  67. package/bin/vm-hands/worker-sandbox-72e3y7bk.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-op-runner-k2jpqmzw.js +0 -2
  85. package/bin/vm-hands/worker-sandbox-wb5thd4n.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{oi as m,pi as y}from"./vm-hands-entry-lite-4xfs7y6w.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","reason-staging"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
- export{f as Zh,mJ as _h,yJ as $h,j as ai,sJ as bi,p as ci,cJ as di,lJ as ei,iJ as fi,rJ as gi,r as hi,jJ as ii,qQ as ji,BQ as ki,YQ as li,WQ as mi,LJ as ni};
2
+ import{pi as m,qi as y}from"./vm-hands-entry-lite-1mrkcz0p.js";import{basename as UJ}from"path";var f=["production","staging"],DJ="https://api.reasonmachines.com",EJ="https://staging-api.reasonmachines.com";var u={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},GJ=new Set(["ara-staging","reason-staging"]);function mJ(J={}){let Q=m(J.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Q){if(f.includes(Q))return Q;throw Error(`Unknown Reason CLI channel: ${Q}`)}let V=UJ(J.executablePath??process.execPath).toLowerCase();return GJ.has(V)?"staging":"production"}function yJ(J,Q){return{...J,...y("REASON_CLI_CHANNEL",Q)}}function j(J){return J==="staging"?EJ:DJ}function sJ(J){return`${j(J)}/mcp/ara`}var s={production:["https://api.ara.so",u.production.api],staging:["https://api-staging.ara.so",u.staging.api]};function p(J){let Q;try{Q=new URL(J).origin}catch{return J}let V=f.find((Z)=>s[Z].includes(Q));return V?j(V):Q}function cJ(J,Q){return J===Q||p(J)===p(Q)}function lJ(J,Q){return f.some((V)=>s[V].includes(J)&&Q===j(V))}function iJ(J,Q){try{let V=new URL(Q);return!V.username&&!V.password&&(V.origin===j(J)||V.origin===u[J].api)}catch{return!1}}function rJ(J){try{let Q=new URL(J).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}import{randomBytes as VJ}from"crypto";import{chmodSync as ZJ,closeSync as a,constants as _J,linkSync as $J,lstatSync as k,mkdirSync as XJ,openSync as kJ,readdirSync as P,readFileSync as t,readlinkSync as R,renameSync as _,rmdirSync as KJ,symlinkSync as A,unlinkSync as U}from"fs";import{createRequire as CJ}from"module";import{constants as FJ}from"os";import{basename as O,join as K,sep as OJ}from"path";import{existsSync as I,lstatSync as l,readdirSync as PJ,readFileSync as HJ,readlinkSync as RJ,realpathSync as TJ}from"fs";import{join as L,sep as AJ}from"path";function i(J,...Q){let V=L(J,"ara"),Z=L(J,"reason");if(!r(V))return L(Z,...Q);if(!I(Z))return L(V,...Q);return I(L(V,...Q))&&!I(L(Z,...Q))?L(V,...Q):L(Z,...Q)}function r(J){try{let Q=l(J);if(!Q.isSymbolicLink())return Q.isDirectory();return RJ(J)!=="reason"&&I(J)}catch{return!1}}function o(J,Q=[]){if(!r(J))return!1;let V;try{V=[J,...PJ(J,{withFileTypes:!0}).filter((Z)=>Z.isDirectory()).map((Z)=>L(J,Z.name))]}catch{return!1}return V.some((Z)=>["connect","connect-once"].filter(($)=>!Q.includes(L(Z,$))).some(($)=>{let M=L(Z,$,"worker.json");try{l(M)}catch{return!1}try{let z=JSON.parse(HJ(M,"utf8"))?.stateDirectory;if(typeof z!=="string")return!0;let q=(X,B)=>X===B||X.startsWith(B+AJ);return q(z,J)||q(c(z),c(J))}catch{return!0}}))}function c(J){try{return TJ(J)}catch{return J}}var S=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),x=new Set(["local-device.proxy.json"]),bJ=new Set(["local-device.key","local-device.binding"]),n=new Map;function jJ(J,Q,V){let Z=K(J,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(J))return{state:Y(Z)?.isDirectory()?"kept":"absent"};return zJ(Z,K(J,"reason"),{linkAlways:!0,kept:($)=>o($,V??[]),native:Q===void 0?LJ:()=>Q},V!==void 0)}function qQ(J,...Q){return jJ(J),i(J,...Q)}function BQ(J,Q=process.platform){let V=K(J,"Library","Logs");if(Q==="darwin")for(let Z of[""," Staging"," Development"])zJ(K(V,`Ara${Z}`),K(V,`Reason${Z}`),{linkAlways:!1,kept:()=>!1,native:LJ});return K(V,"Reason")}var MJ="config_rename_unavailable:busy";function zJ(J,Q,V,Z=!1){let $=Z?void 0:n.get(J);if($)return $;let M;try{M=IJ(J,Q,V)}catch(z){let q=`config_rename_unavailable:${G(z)??"failed"}`;try{return{state:Y(J)?.isDirectory()?"kept":"absent",problem:q}}catch{return{state:"kept",problem:q}}}if(!(M.state==="absent"&&V.linkAlways)&&M.problem!==MJ&&!(M.state==="kept"&&!M.problem))n.set(J,M);return M}function IJ(J,Q,V){vJ(Q,V.native);let Z=!1;for(let $=0;$<8;$+=1){let M=Y(J);if(M?.isSymbolicLink())return R(J)===O(Q)?{state:Z?"renamed":"linked"}:{state:"kept"};if(!M){if(v(Q))W(()=>U(Q),"ENOENT");if(!(Z||V.linkAlways)||!T(Q))return{state:"absent"};let X=F(Q,"link");A(O(Q),X);try{W(()=>_(X,J),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{W(()=>U(X),"ENOENT")}continue}if(!M.isDirectory())return{state:"absent"};if(V.kept(J))return e(Q),{state:"kept"};let z=V.native();if(!z)return e(Q),{state:"kept",problem:"config_rename_unavailable:no_native"};let q=SJ(z,J);if(!q)return{state:"kept",problem:MJ};try{if(k(J).isSymbolicLink())continue;let X=NJ(z,J,Q);if(X)return{state:"kept",problem:X};Z=!0}finally{q()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function NJ(J,Q,V){let Z=Y(V);if(!Z||v(V)){if(!Z)A(O(V),V);try{J.exchange(Q,V)}catch(X){if(v(V))W(()=>U(V),"ENOENT");return`config_rename_unavailable:${G(X)??"exchange_failed"}`}return null}if(!Z.isDirectory())return"config_rename_unavailable:ENOTDIR";if(Z.dev!==k(Q).dev)return"config_rename_unavailable:EXDEV";let $=[F(V,"probe"),F(V,"probe")];try{A("a",$[0]),A("b",$[1]),J.exchange($[0],$[1])}catch(X){return`config_rename_unavailable:${G(X)??"exchange_failed"}`}finally{for(let X of $)W(()=>U(X),"ENOENT")}let M=wJ(V);for(let X of bJ){let B=Y(K(V,X)),w=Y(K(Q,X));if(B&&w&&B.ino!==w.ino)XJ(`${M}-replaced`,{mode:448,recursive:!0}),_(K(V,X),K(`${M}-replaced`,X))}let z={linked:new Map,unitsKept:new Set};qJ(Q,V,"",z);let q=F(V,"rename");A(O(V),q);try{J.exchange(Q,q)}catch(X){return W(()=>U(q),"ENOENT"),`config_rename_unavailable:${G(X)??"exchange_failed"}`}return BJ(q,V,z,M),null}function g(J){return J===""||!J.includes(OJ)}function qJ(J,Q,V,Z){let $=g(V)&&N(K(Q,V),K(J,V));if($)Z.unitsKept.add(V);for(let M of P(K(J,V))){if($&&(S.has(M)||x.has(M)))continue;let z=K(V,M),q=K(J,z),X=K(Q,z),B=Y(q);if(!B)continue;let w=Y(X);if(B.isDirectory()){if(!w)W(()=>XJ(X,{mode:B.mode&4095}),"EEXIST"),ZJ(X,B.mode&4095);if(T(X))qJ(J,Q,z,Z)}else if(!w){if(B.isSymbolicLink())W(()=>A(R(q),X),"EEXIST");else if(W(()=>$J(q,X),"EEXIST","ENOENT"))Z.linked.set(z,B.ino)}}}function vJ(J,Q){let V;try{if(!T(J))return;V=P(J)}catch{return}for(let Z of V){let $=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(Z);if(!$)continue;let M=K(J,Z),z=Y(M);if(!z)continue;if(!z.isDirectory()){if(!JJ(Number($[2])))W(()=>U(M),"ENOENT");continue}let q=Q(),X=null;if(q){try{X=q.lock(M)}catch{continue}if(!X)continue}else if(JJ(Number($[2])))continue;try{let B=F(J,"claim");if(W(()=>_(M,B),"ENOENT"))BJ(B,J,null,wJ(J))}finally{X?.()}}}function BJ(J,Q,V,Z){for(let[$,M]of V?.linked??[])if(!Y(K(J,$))&&Y(K(Q,$))?.ino===M)W(()=>U(K(Q,$)),"ENOENT");if(YJ(J,Q,"",V),W(()=>KJ(J),"ENOTEMPTY","EEXIST"))return;_(J,Z),ZJ(Z,448)}function YJ(J,Q,V,Z){let $=g(V)&&(Z?Z.unitsKept.has(V):N(K(Q,V),K(J,V)));for(let M of P(K(J,V))){let z=K(V,M),q=K(J,z),X=K(Q,z),B=k(q),w=Y(X);if(w&&B.ino===w.ino&&B.dev===w.dev){U(q);continue}if(B.isFile()&&w?.isFile()&&Z?.linked.get(z)===w.ino){_(q,X);continue}if($&&(S.has(M)||x.has(M)))continue;if(!w){if(B.isFile()){if(W(()=>$J(q,X),"EEXIST"))U(q)}else W(()=>_(q,X),"EEXIST","ENOTEMPTY");continue}if(B.isDirectory()&&w.isDirectory())YJ(J,Q,z,Z),W(()=>KJ(q),"ENOTEMPTY","EEXIST")}}function YQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=["",...P(Q,{withFileTypes:!0}).filter(($)=>$.isDirectory()&&!$.name.startsWith(".")).map(($)=>$.name)];for(let $ of Z){let M=K(Q,$),z=K(V,$);if(!N(M,z)||!N(z,M))continue;if([...S,...x].some((X)=>h(K(M,X),K(z,X))===!1))return $}return null}function WQ(J){let Q=K(J,"ara"),V=K(J,"reason");if(!T(Q)||!T(V))return null;let Z=($)=>{for(let M of P(K(Q,$))){let z=K($,M);if(g($)&&(M==="connect"||M==="connect-once"))continue;let q=k(K(Q,z)),X=Y(K(V,z));if(!X||q.ino===X.ino&&q.dev===X.dev)continue;if(q.isDirectory()&&X.isDirectory()&&!X.isSymbolicLink()){let B=Z(z);if(B!==null)return B}else if(q.isSymbolicLink()||X.isSymbolicLink()){if(!(q.isSymbolicLink()&&X.isSymbolicLink()&&R(K(Q,z))===R(K(V,z))))return z}else if(h(K(Q,z),K(V,z))!==!0)return z}return null};return Z("")}function h(J,Q){let V=Y(J),Z=Y(Q);if(!V&&!Z)return null;if(!V||!Z||V.isDirectory()!==Z.isDirectory())return!1;if(V.ino===Z.ino&&V.dev===Z.dev)return!0;if(V.isDirectory())return[...new Set([...P(J),...P(Q)])].every((M)=>h(K(J,M),K(Q,M))===!0);try{return t(J).equals(t(Q))}catch{return!1}}function N(J,Q){for(let V of S)if(WJ(K(J,V),K(Q,V)))return!0;return!1}function WJ(J,Q){let V=Y(J);if(!V)return!1;let Z=Y(Q);if(!Z)return!0;if(V.isDirectory()){if(!Z.isDirectory())return!0;return P(J).some(($)=>WJ(K(J,$),K(Q,$)))}if(V.isSymbolicLink())return!Z.isSymbolicLink()||R(J)!==R(Q);return V.ino!==Z.ino||V.dev!==Z.dev}function e(J){if(v(J))W(()=>U(J),"ENOENT")}function wJ(J){return K(J,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${VJ(3).toString("hex")}`)}function v(J){try{return k(J).isSymbolicLink()&&R(J)===O(J)}catch{return!1}}function T(J){let Q=Y(J);return Q!==null&&Q.isDirectory()}function SJ(J,Q){for(let V=0;V<40;V+=1){let Z=J.lock(Q);if(Z)return Z;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function F(J,Q){return K(J,`.${Q}-${process.pid}-${VJ(6).toString("hex")}`)}function JJ(J){if(J===process.pid)return!1;try{return process.kill(J,0),!0}catch(Q){return G(Q)==="EPERM"}}function Y(J){try{return k(J)}catch(Q){if(G(Q)==="ENOENT"||G(Q)==="ENOTDIR")return null;throw Q}}function W(J,...Q){try{return J(),!0}catch(V){if(Q.includes(G(V)??""))return!1;throw V}}function G(J){return J instanceof Error&&"code"in J&&typeof J.code==="string"?J.code:void 0}var C,uJ=2,fJ=4,xJ=2,gJ=2,QJ=-100;function LJ(){if(C!==void 0)return C;if(C=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let J;try{J=CJ(import.meta.url)("bun:ffi")}catch{return null}let Q=process.platform==="darwin",V=Q?"__error":"__errno_location",Z=Q?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:$}=J;for(let M of Z)try{let z=Q?"renamex_np":"renameat2",X=J.dlopen(M,{flock:{args:[$.i32,$.i32],returns:$.i32},[V]:{args:[],returns:$.ptr},[z]:Q?{args:[$.ptr,$.ptr,$.u32],returns:$.i32}:{args:[$.i32,$.ptr,$.i32,$.ptr,$.u32],returns:$.i32}}).symbols,B=X[V]();if(B===null)continue;let w=(H)=>{let E=J.read.i32(B),D=Object.entries(FJ.errno).find(([,b])=>b===E)?.[0]??`errno_${E}`;return Object.assign(Error(`${H} failed: ${D}`),{code:D})},d=(H)=>Buffer.from(`${H}\x00`,"utf8");return C={exchange(H,E){let D=d(H),b=d(E);if((Q?X[z](J.ptr(D),J.ptr(b),xJ):X[z](QJ,J.ptr(D),QJ,J.ptr(b),gJ))!==0)throw w("exchange")},lock(H){let E=kJ(H,_J.O_RDONLY);if(X.flock(E,uJ|fJ)===0)return()=>a(E);let D=w("lock");if(a(E),D.code==="EWOULDBLOCK"||D.code==="EAGAIN")return null;throw D}},C}catch{}return null}
3
+ export{f as _h,mJ as $h,yJ as ai,j as bi,sJ as ci,p as di,cJ as ei,lJ as fi,iJ as gi,rJ as hi,r as ii,jJ as ji,qQ as ki,BQ as li,YQ as mi,WQ as ni,LJ as oi};
@@ -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-saqwe5sm.js";import{wc as F7,yc as N7,zc as H7}from"./vm-hands-entry-lite-bhgsayph.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-h6qss80e.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-7wgbj1kg.js";import{Gd as q7,ud as Q2,xd as z7}from"./vm-hands-entry-lite-es39m2mg.js";import{$e as g6,Af as v8,Be as H0,Bf as p8,Cf as u8,Df as d8,Ee as d,Ef as l8,Fe as h1,Ff as s8,Gf as c8,Hf as n8,Ie as g8,Ke as m1,Me as D6,Ne as M6,Oe as w6,Pe as L6,Qe as O6,Re as j6,Se as I6,Te as A6,Ue as _6,Ve as T6,We as P6,Xe as R6,Ye as z6,Ze as q6,_e as E6,af as S6,bf as k6,cf as f6,df as b6,ff as x6,gf as y6,hf as h6,if as m6,jf as v6,kf as p6,lf as u6,pe as P1,qe as R1,re as S3,rf as S8,se as F2,sf as k8,te as C6,tf as f8,ue as k3,uf as b8,ve as W4,vf as x8,we as Y4,wf as y8,xe as w0,yf as h8,zf as m8}from"./vm-hands-entry-lite-cvft83sx.js";import{$f as O5,Nf as Q6,Rf as L5,Sf as v5,Yf as E7,ag as e1}from"./vm-hands-entry-lite-wdsk86sk.js";import{bg as A7,cg as _7,dg as T7,hg as P7,kg as R7}from"./vm-hands-entry-lite-8a1zycjh.js";import{Ag as K7,tg as x4}from"./vm-hands-entry-lite-p7hxm3hc.js";import{Fg as Z2}from"./vm-hands-entry-lite-pk2xd13q.js";import{Kg as R3,Xg as l6}from"./vm-hands-entry-lite-cas0c9qd.js";import{Ti as E1,Ui as c6,Vi as E4,Wi as g4}from"./vm-hands-entry-lite-m57kpdgb.js";import{Yi as P3,_i as Q1,ej as L8,fj as D4}from"./vm-hands-entry-lite-2fpxf6vm.js";import{Bj as L7,Cj as O7,Ej as j7,Fj as I7,wj as C7,xj as D7,yj as M7,zj as w7}from"./vm-hands-entry-lite-g63y988w.js";import{Qj as V}from"./vm-hands-entry-lite-hzsk6tpw.js";import{Yj as C}from"./vm-hands-entry-lite-p24kmysw.js";import{ck as W8}from"./vm-hands-entry-lite-pby299bv.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-m1kn3rkk.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{$i as X,bj as Y,dj as Z}from"./vm-hands-entry-lite-dqnhebfx.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
- export{Q as Si,O as Ti,_ as Ui,b as Vi,g as Wi};
2
+ import{aj as X,cj as Y,ej as Z}from"./vm-hands-entry-lite-2fpxf6vm.js";import{execFileSync as z}from"child_process";import{existsSync as V,realpathSync as M}from"fs";import{userInfo as D}from"os";import{isAbsolute as $,join as C,normalize as F,parse as K}from"path";function Q(){let q=F(D().homedir);if(!$(q)||q===K(q).root)throw Error("Could not resolve the canonical macOS user home.");return q}function O(q,B,J=Q()){let L=Z(B);if(B.kind==="managed"&&B.base){let G=M(J);return{anchor:G,boundary:C(G,B.base),path:C(G,L)}}if(B.kind==="root"&&Y(B.path)){let G=M(J);return{anchor:G,boundary:C(G,X),path:C(G,L)}}return{anchor:q,boundary:q,path:C(q,L)}}function _(q=Q()){return C(q,".config")}function b(){if(process.platform!=="darwin")return null;try{let q=z("/usr/bin/getconf",["DARWIN_USER_DIR"],{encoding:"utf8",timeout:5000}).trim();return $(q)?M(q):null}catch{return null}}function g(q=Q()){let B=C(q,"Library","Application Support","Ara"),J=C(q,"Library","Application Support","Reason");return V(B)&&!V(J)?B:J}
3
+ export{Q as Ti,O as Ui,_ as Vi,b as Wi,g as Xi};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  class o extends Error{code;constructor(a,r){super(r);this.code=a;this.name="LocalCapabilityError"}}
3
- export{o as Xj};
3
+ export{o as Yj};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Yh as v}from"./vm-hands-entry-lite-1hv536wk.js";import{_h as r,ei as o,hi as g,ii as h,ji as a}from"./vm-hands-entry-lite-p1nb6n3r.js";import{Si as V}from"./vm-hands-entry-lite-tbps80f1.js";import{Pj as U}from"./vm-hands-entry-lite-k7fkfytm.js";import{createHmac as mQ,createPublicKey as CQ,randomBytes as LQ,randomUUID as t,verify as EQ}from"crypto";import{chmodSync as _,existsSync as e,mkdirSync as IQ,readFileSync as gQ,realpathSync as hQ,renameSync as vQ,statSync as yQ,unlinkSync as uQ,writeFileSync as pQ}from"fs";import{basename as cQ,dirname as F,isAbsolute as QQ,join as A,resolve as lQ}from"path";var WZ=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var zQ="REASON_DESKTOP_RUNTIME",UQ="REASON_DESKTOP_RUNTIME_CHANNEL",JQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",zZ={[zQ]:"ARA_DESKTOP_RUNTIME",[UQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[JQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function m(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as N,existsSync as z,mkdirSync as O,readFileSync as C,realpathSync as xQ,renameSync as wQ,unlinkSync as R,writeFileSync as f}from"fs";import{createPrivateKey as KQ,createPublicKey as VQ,generateKeyPairSync as AQ,randomUUID as NQ,sign as OQ}from"crypto";import{createRequire as RQ}from"module";import{homedir as fQ,platform as y}from"os";import{dirname as kQ,join as J}from"path";var L=1,BQ=16384,M=65536,_Q=128,TQ=128,u=65536;class q extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function p(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var k=null;function c(){if(!k)try{k=RQ(import.meta.url)("bun:ffi")}catch{throw new q("native_boundary_unavailable")}return k}function FQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function PQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new q("invalid_credential_record");let Z=Q,$=FQ(Z.apiOrigin);if(Z.version!==L||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new q("invalid_credential_record");return{version:L,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function DQ(Q=process.execPath){let Z=Q;try{Z=xQ(Q)}catch{}return v(kQ(Z))}function j(Q){return c().ptr(Q)}function bQ(Q){if(!z(Q))throw new q("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=c();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(W){if(W instanceof q)throw W;throw new q("native_boundary_unavailable")}}function E(Q){return Buffer.from(Q).toString("base64url")}function x(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function l(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class d{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=DQ(),Z=y(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;m($)}symbols(){if(this.runtimePlatform!=="darwin")throw new q("unsupported_platform");this.library??=bQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(j(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new q("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(_Q),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(j(Z),BigInt(Z.byteLength),j($)):this.symbols().ara_device_key_create_fresh_public(j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X!==65)throw new q("invalid_public_key");let Y=E(Z.subarray(0,X));if(!x(Y))throw new q("invalid_public_key");return Y}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=new Uint8Array(TQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(j(Q),BigInt(Q.byteLength),j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q("proof_sign_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X<1||X>Z.byteLength)throw new q("invalid_signature");let Y=Z.subarray(0,X);if(!l(Y))throw new q("invalid_signature");return E(Y)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(j(Q));if(Z!==0||Q[0]!==1)throw new q("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(j(Q));if(Z!==0)throw new q("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(M),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_create(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_update(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(j(Q));if(Z!==0)throw new q("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(BQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_credential_record");try{let X=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return PQ(JSON.parse(X))}catch(X){if(X instanceof q)throw X;throw new q("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(j(Q));if(Z!==0)throw new q("legacy_credential_delete_failed",Z);return Q[0]===1}}function I(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new q("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new q("invalid_public_key");let X=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(X))throw new q("invalid_public_key");return X}function SQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||J(fQ(),".config");h(Q);let Z=J(Q,"ara");return g(Z)?Z:J(Q,"reason")}class i{directory;constructor(Q=SQ()){this.directory=Q}keyPath(){return J(this.directory,"local-device.key")}bindingPath(){return J(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!z(Q))throw new q("proof_key_read_failed");try{let Z=C(Q,"utf8");return KQ({key:Z,format:"pem"})}catch{throw new q("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=VQ(Q);return I(Z)}createFreshPublicKey(){O(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return f(W,$,{mode:384}),N(W,384),I(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=OQ("sha256",Q,Z)}catch{throw new q("proof_sign_failed")}if(!l($))throw new q("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!z(Q))return!1;return R(Q),!0}loadBinding(){let Q=this.bindingPath();if(!z(Q))return null;try{return new Uint8Array(C(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(z(Z))throw new q("binding_create_failed");f(Z,Q,{mode:384}),N(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!z(Z))throw new q("binding_update_failed");let $=`${Z}.${NQ()}`;try{f($,Q,{mode:384,flag:"wx"}),N($,384),wQ($,Z)}finally{if(z($))R($)}}deleteBinding(){let Q=this.bindingPath();if(!z(Q))return!1;return R(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function B(){return y()==="darwin"?new d:new i}var w=U.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),s=U.object({id:w,kind:U.literal("permission_denied"),operation:U.enum(["bash","read","write","edit"]),provenance:U.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:U.string().datetime(),expiresAt:U.string().datetime(),sessionId:w,deviceId:w,organizationId:w}).strict();var P=4;var K="macos-keychain-p256-v1",ZQ=1,dQ=`ARA-DEVICE-BINDING-V1
2
+ import{Zh as v}from"./vm-hands-entry-lite-01sqtryp.js";import{$h as r,fi as o,ii as g,ji as h,ki as a}from"./vm-hands-entry-lite-jd49j573.js";import{Ti as V}from"./vm-hands-entry-lite-m57kpdgb.js";import{Qj as U}from"./vm-hands-entry-lite-hzsk6tpw.js";import{createHmac as mQ,createPublicKey as CQ,randomBytes as LQ,randomUUID as t,verify as EQ}from"crypto";import{chmodSync as _,existsSync as e,mkdirSync as IQ,readFileSync as gQ,realpathSync as hQ,renameSync as vQ,statSync as yQ,unlinkSync as uQ,writeFileSync as pQ}from"fs";import{basename as cQ,dirname as F,isAbsolute as QQ,join as A,resolve as lQ}from"path";var WZ=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var zQ="REASON_DESKTOP_RUNTIME",UQ="REASON_DESKTOP_RUNTIME_CHANNEL",JQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",zZ={[zQ]:"ARA_DESKTOP_RUNTIME",[UQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[JQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function m(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as N,existsSync as z,mkdirSync as O,readFileSync as C,realpathSync as xQ,renameSync as wQ,unlinkSync as R,writeFileSync as f}from"fs";import{createPrivateKey as KQ,createPublicKey as VQ,generateKeyPairSync as AQ,randomUUID as NQ,sign as OQ}from"crypto";import{createRequire as RQ}from"module";import{homedir as fQ,platform as y}from"os";import{dirname as kQ,join as J}from"path";var L=1,BQ=16384,M=65536,_Q=128,TQ=128,u=65536;class q extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function p(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var k=null;function c(){if(!k)try{k=RQ(import.meta.url)("bun:ffi")}catch{throw new q("native_boundary_unavailable")}return k}function FQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function PQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new q("invalid_credential_record");let Z=Q,$=FQ(Z.apiOrigin);if(Z.version!==L||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new q("invalid_credential_record");return{version:L,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function DQ(Q=process.execPath){let Z=Q;try{Z=xQ(Q)}catch{}return v(kQ(Z))}function j(Q){return c().ptr(Q)}function bQ(Q){if(!z(Q))throw new q("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=c();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(W){if(W instanceof q)throw W;throw new q("native_boundary_unavailable")}}function E(Q){return Buffer.from(Q).toString("base64url")}function x(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function l(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class d{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=DQ(),Z=y(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;m($)}symbols(){if(this.runtimePlatform!=="darwin")throw new q("unsupported_platform");this.library??=bQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(j(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new q("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(_Q),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(j(Z),BigInt(Z.byteLength),j($)):this.symbols().ara_device_key_create_fresh_public(j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X!==65)throw new q("invalid_public_key");let Y=E(Z.subarray(0,X));if(!x(Y))throw new q("invalid_public_key");return Y}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=new Uint8Array(TQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(j(Q),BigInt(Q.byteLength),j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q("proof_sign_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X<1||X>Z.byteLength)throw new q("invalid_signature");let Y=Z.subarray(0,X);if(!l(Y))throw new q("invalid_signature");return E(Y)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(j(Q));if(Z!==0||Q[0]!==1)throw new q("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(j(Q));if(Z!==0)throw new q("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(M),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_create(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_update(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(j(Q));if(Z!==0)throw new q("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(BQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_credential_record");try{let X=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return PQ(JSON.parse(X))}catch(X){if(X instanceof q)throw X;throw new q("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(j(Q));if(Z!==0)throw new q("legacy_credential_delete_failed",Z);return Q[0]===1}}function I(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new q("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new q("invalid_public_key");let X=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(X))throw new q("invalid_public_key");return X}function SQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||J(fQ(),".config");h(Q);let Z=J(Q,"ara");return g(Z)?Z:J(Q,"reason")}class i{directory;constructor(Q=SQ()){this.directory=Q}keyPath(){return J(this.directory,"local-device.key")}bindingPath(){return J(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!z(Q))throw new q("proof_key_read_failed");try{let Z=C(Q,"utf8");return KQ({key:Z,format:"pem"})}catch{throw new q("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=VQ(Q);return I(Z)}createFreshPublicKey(){O(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return f(W,$,{mode:384}),N(W,384),I(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=OQ("sha256",Q,Z)}catch{throw new q("proof_sign_failed")}if(!l($))throw new q("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!z(Q))return!1;return R(Q),!0}loadBinding(){let Q=this.bindingPath();if(!z(Q))return null;try{return new Uint8Array(C(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(z(Z))throw new q("binding_create_failed");f(Z,Q,{mode:384}),N(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!z(Z))throw new q("binding_update_failed");let $=`${Z}.${NQ()}`;try{f($,Q,{mode:384,flag:"wx"}),N($,384),wQ($,Z)}finally{if(z($))R($)}}deleteBinding(){let Q=this.bindingPath();if(!z(Q))return!1;return R(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function B(){return y()==="darwin"?new d:new i}var w=U.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),s=U.object({id:w,kind:U.literal("permission_denied"),operation:U.enum(["bash","read","write","edit"]),provenance:U.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:U.string().datetime(),expiresAt:U.string().datetime(),sessionId:w,deviceId:w,organizationId:w}).strict();var P=4;var K="macos-keychain-p256-v1",ZQ=1,dQ=`ARA-DEVICE-BINDING-V1
3
3
  `;function iQ(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function $Q(Q,Z=Date.now()){let $=s.safeParse(Q);if(!$.success)return!1;let W=$.data,X=typeof W.occurredAt==="string"?Date.parse(W.occurredAt):NaN,Y=typeof W.expiresAt==="string"?Date.parse(W.expiresAt):NaN;return W.kind==="permission_denied"&&["bash","read","write","edit"].includes(W.operation)&&["sandbox_policy","os_permission_unknown"].includes(W.provenance)&&Number.isFinite(X)&&X<=Z&&Y>Z&&Y>X&&Y-X<=600000}function LZ(Q,Z,$=Date.now()){if(!Q||!Z||Q.state!=="connected"||Q.deviceId!==Z.deviceId)return null;let W=Date.parse(Q.lastHeartbeatAt??""),X=Q.permissionRecovery;if(!($-W>=0&&$-W<30000)||!$Q(X,$)||X.deviceId!==Z.deviceId||X.organizationId!==Z.orgId)return null;try{process.kill(Q.pid,0)}catch{return null}return X}function WQ(Q={},Z=V()){let $=r({env:{...process.env,...Q}}),W=Q.XDG_CONFIG_HOME?.trim()||A(Z,".config");return a(W,...$==="staging"?["staging"]:[])}function D(Q={},Z=V()){return A(WQ(Q,Z),"local-device.json")}function qQ(Q={},Z=V()){return A(WQ(Q,Z),"local-daemon.json")}function b(Q,Z){IQ(F(Q),{recursive:!0,mode:448}),_(F(Q),448);let $=`${Q}.${process.pid}.${t()}.tmp`;try{pQ($,`${JSON.stringify(Z,null,2)}
4
4
  `,{mode:384,flag:"wx"}),_($,384),vQ($,Q),_(Q,384)}finally{if(e($))uQ($)}return Q}function S(Q){if(!e(Q))return null;try{return JSON.parse(gQ(Q,"utf8"))}catch{return null}}function T(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function sQ(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||typeof W.label!=="string"||typeof W.path!=="string"||typeof W.pathFingerprint!=="string"||!W.permissions||typeof W.permissions.read!=="boolean"||typeof W.permissions.write!=="boolean"||typeof W.permissions.execute!=="boolean"||typeof W.permissions.discover_environment!=="boolean"||typeof W.permissions.expose_mcp!=="boolean")return null;Z.push({id:W.id,label:W.label,path:W.path,pathFingerprint:W.pathFingerprint,permissions:W.permissions})}return Z}function XQ(Q,Z,$=[]){let W=Object.keys(Q);return Z.every((X)=>Object.hasOwn(Q,X))&&W.every((X)=>Z.includes(X)||$.includes(X))}function nQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost")return null;return Z.origin}catch{return null}}function YQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=sQ(Z.roots),W=nQ(Z.apiOrigin);if(!W||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!iQ(Z.handsSlots)||Z.worker!==void 0&&(!Z.worker||!/^[a-f0-9]{64}$/.test(Z.worker.configDigest)||!["persistent","ephemeral"].includes(Z.worker.lifetime)||!Number.isFinite(Date.parse(Z.worker.expiresAt)))||!$)return null;return{apiOrigin:W,orgId:Z.orgId,deviceId:Z.deviceId,displayName:Z.displayName,registeredAt:Z.registeredAt,...Z.handsSlots!==void 0?{handsSlots:Z.handsSlots}:{},...Z.worker!==void 0?{worker:Z.worker}:{},roots:$}}function rQ(Q){return{...Q,credentialStorage:K}}function oQ(Q){return{version:P,apiOrigin:Q.apiOrigin,orgId:Q.orgId,deviceId:Q.deviceId,devicePublicKey:Q.devicePublicKey,displayName:Q.displayName,registeredAt:Q.registeredAt,...Q.handsSlots!==void 0?{handsSlots:Q.handsSlots}:{},...Q.worker!==void 0?{worker:Q.worker}:{},roots:Q.roots.map((Z)=>({id:Z.id,label:Z.label,path:Z.path,pathFingerprint:Z.pathFingerprint,permissions:{read:Z.permissions.read,write:Z.permissions.write,execute:Z.permissions.execute,discover_environment:Z.permissions.discover_environment,expose_mcp:Z.permissions.expose_mcp}})),credentialStorage:K}}function jQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!XQ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=YQ(Z);if(!$||Z.version!==P||Z.credentialStorage!==K||!x(Z.devicePublicKey))return null;return{version:P,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:K}}function GQ(Q){return new TextEncoder().encode(`${dQ}${JSON.stringify(oQ(Q))}`)}function aQ(Q){let Z=Buffer.from(Q,"base64url");return CQ({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function tQ(Q,Z){let $={version:ZQ,state:Q,signature:Z.sign(GQ(Q))};return new TextEncoder().encode(JSON.stringify($))}function HQ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new q("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new q("invalid_binding");let $=Z;if(!XQ($,["version","state","signature"])||$.version!==ZQ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new q("invalid_binding");let W=jQ($.state);if(!W)throw new q("invalid_binding");let X=!1;try{X=EQ("sha256",GQ(W),aQ(W.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{X=!1}if(!X)throw new q("invalid_binding");return W}function eQ(Q){let{credentialStorage:Z,...$}=Q;return $}function QZ(Q){return Q instanceof q?p(Q):"credential_boundary_failed"}function EZ(Q=D(),Z={}){let $=S(Q),W=Z.proofStore??Z.credentialStore??B(),X=W.loadBinding();if(!X){if($&&typeof $==="object"&&!Array.isArray($)&&ZZ($))return null;if($!==null)throw new q("invalid_binding");return null}let Y=HQ(X),G=W.loadPublicKey();if(W.privateKeyIsNonExtractable(),G!==Y.devicePublicKey)throw new q("invalid_public_key");let H=jQ($);if(Z.repair!==!1&&(!H||JSON.stringify(H)!==JSON.stringify(Y)))b(Q,Y);return eQ(Y)}function ZZ(Q){let Z=Q,$=YQ(Q);if(!$)return null;if(Z.version===2){if(typeof Z.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.deviceCredential)||Z.deviceCredential.length>4096)return null;return{state:$,credentialSource:"plaintext-v2"}}if(Z.version!==3||Z.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in Z)return null;return{state:$,credentialSource:"keychain-v3"}}function IZ(Q,Z=D(),$={}){let W=$.proofStore??$.credentialStore??B();T($,"credential.store_started");try{if(!x(Q.devicePublicKey)||W.loadPublicKey()!==Q.devicePublicKey)throw new q("invalid_public_key");W.privateKeyIsNonExtractable();let X=rQ(Q),Y=W.loadBinding();if(Y){let H=HQ(Y);if(H.devicePublicKey!==Q.devicePublicKey||H.orgId!==Q.orgId||H.deviceId!==Q.deviceId||H.apiOrigin!==Q.apiOrigin&&!o(H.apiOrigin,Q.apiOrigin))throw new q("invalid_binding")}let G=tQ(X,W);if(Y)W.updateBinding(G);else W.createBinding(G);return b(Z,X),T($,"credential.store_completed"),Z}catch(X){throw T($,"credential.store_failed",QZ(X)),X}}function gZ(Q=qQ()){let Z=S(Q);if(!Z||typeof Z!=="object")return null;let $=Z;if($.version!==1||typeof $.pid!=="number"||!Number.isInteger($.pid)||!["starting","connected","stopped","error"].includes($.state??"")||typeof $.startedAt!=="string"||$.lastHeartbeatAt!==void 0&&typeof $.lastHeartbeatAt!=="string"||$.lastUsedAt!==void 0&&typeof $.lastUsedAt!=="string"||$.organizationId!==void 0&&typeof $.organizationId!=="string"||$.organizationName!==void 0&&typeof $.organizationName!=="string"||$.organizationSlug!==void 0&&typeof $.organizationSlug!=="string"||$.error!==void 0&&typeof $.error!=="string"||$.reconnectingSince!==void 0&&typeof $.reconnectingSince!=="string"||$.workspace!==void 0&&typeof $.workspace!=="string")return null;if($.permissionRecovery!==void 0&&!$Q($.permissionRecovery))delete $.permissionRecovery;return $}function hZ(Q,Z=qQ()){return b(Z,Q)}var n=1;function $Z(Q=D()){return A(F(Q),"local-device.proxy.json")}function vZ(Q=$Z()){let Z=S(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==n||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!QQ($.caFile)))return null;return{version:n,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function yZ(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=LQ(32)){let W=new Set,X=[];for(let Y of Q){let G=hQ(QQ(Y)?Y:lQ(Y));if(!yQ(G).isDirectory())throw Error(`Local execution root is not a directory: ${Y}`);if(W.has(G))continue;W.add(G),X.push({id:t(),label:cQ(G)||G,path:G,pathFingerprint:mQ("sha256",$).update(G).digest("hex"),permissions:{...Z}})}if(X.length===0)throw Error("At least one explicit local execution root is required.");return X}
5
- export{q as kg,DQ as lg,x as mg,l as ng,d as og,i as pg,$Q as qg,LZ as rg,D as sg,qQ as tg,EZ as ug,IZ as vg,gZ as wg,hZ as xg,n as yg,vZ as zg,yZ as Ag};
5
+ export{q as lg,DQ as mg,x as ng,l as og,d as pg,i as qg,$Q as rg,LZ as sg,D as tg,qQ as ug,EZ as vg,IZ as wg,gZ as xg,hZ as yg,n as zg,vZ as Ag,yZ as Bg};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
2
  var n=Object.create;var{getPrototypeOf:o,defineProperty:e,getOwnPropertyNames:k,getOwnPropertyDescriptor:p}=Object,l=Object.prototype.hasOwnProperty;function m(a){return this[a]}var q,r,u=(a,b,c)=>{var d=a!=null&&typeof a==="object";if(d){var h=b?q??=new WeakMap:r??=new WeakMap,i=h.get(a);if(i)return i}c=a!=null?n(o(a)):{};let f=b||!a||!a.__esModule?e(c,"default",{value:a,enumerable:!0}):c;for(let g of k(a))if(!l.call(f,g))e(f,g,{get:m.bind(a,g),enumerable:!0});if(d)h.set(a,f);return f},v=(a)=>{var b=(j??=new WeakMap).get(a),c;if(b)return b;if(b=e({},"__esModule",{value:!0}),a&&typeof a==="object"||typeof a==="function"){for(var d of k(a))if(!l.call(b,d))e(b,d,{get:m.bind(a,d),enumerable:!(c=p(a,d))||c.enumerable})}return j.set(a,b),b},j,w=(a,b)=>()=>(b||a((b={exports:{}}).exports,b),b.exports);var s=(a)=>a;function t(a,b){this[a]=s.bind(null,b)}var x=(a,b)=>{for(var c in b)e(a,c,{get:b[c],enumerable:!0,configurable:!0,set:t.bind(b,c)})};var y=(a,b)=>()=>(a&&(b=a(a=0)),b);var z=import.meta.require;
3
- export{u as Yj,v as Zj,w as _j,x as $j,y as ak,z as bk};
3
+ export{u as Zj,v as _j,w as $j,x as ak,y as bk,z as ck};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{r as v0}from"./vm-hands-entry-lite-0763vz5v.js";import{v as n1,x as x6,y as c9}from"./vm-hands-entry-lite-hfq6jjnh.js";import{A as X2,B as E6,C as $4,D as J4,E as V6,F as m0,J as G6,K as A$}from"./vm-hands-entry-lite-zn303jrg.js";import{V as g2,oa as e0,ra as u1,ta as VJ}from"./vm-hands-entry-lite-w3xhwb5h.js";import{Ba as f5,Ca as m5,Da as e4,Ea as $8,Fa as DJ,Ga as WJ,Ha as _9,Ia as d8,Ja as Q8,Ka as L0,La as I1,Ma as C1,Na as I0,Oa as g1,Pa as p8,Qa as B5,Ra as f3,Sa as t8,Wa as r8,cb as AJ,db as RJ,eb as PJ,fb as IJ,gb as D9}from"./vm-hands-entry-lite-vfn61qq2.js";import{$b as _J,Ab as x8,Bb as J8,Cb as Z8,Db as MJ,Eb as TJ,Gb as u,Hb as e,Ib as s,Jb as c,Kb as H8,Lb as FJ,Mb as N1,Pb as t2,Qb as r2,Rb as R6,Sb as P6,Tb as I6,Ub as S0,Vb as J0,Wb as g,Xb as j9,Yb as j1,Zb as i1,_b as N0,ec as V5,gc as S4,ib as cJ,jc as I2,lb as L8,lc as u8,mb as F8,mc as i3,oc as S8,pb as U8,rb as A8,sc as jJ,tc as l3,ub as R8,zb as E8}from"./vm-hands-entry-lite-v65nk88n.js";import{xc as X8}from"./vm-hands-entry-lite-cwf21py1.js";import{Ec as g8}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as P8,Kc as I8,Rc as C8}from"./vm-hands-entry-lite-xhr0m9r0.js";import{Xc as H$}from"./vm-hands-entry-lite-wry37am5.js";import{nd as o4}from"./vm-hands-entry-lite-jpkf3569.js";import{Cd as v5,Dd as g5,wd as c8,zd as OJ}from"./vm-hands-entry-lite-e95w4ea8.js";import{Gd as p$,Id as Q$,Jd as R$,Kd as U1,Md as B6,Nd as S6,Od as b6,Qd as H1,Rd as w6,Sd as b9,Td as y6,Ud as s2,Vd as M$,Wd as A4,Xd as a2}from"./vm-hands-entry-lite-tf1tkqkw.js";import{Be as HJ,Ce as qJ,df as r4,lf as J6,mf as n$,wf as Z2,xe as L2}from"./vm-hands-entry-lite-fr2k6eah.js";import{Jf as C6,Kf as m2,Nf as zJ,Qf as w1,Sf as o6,Tf as e6,Yf as n8}from"./vm-hands-entry-lite-t5kt2wff.js";import{Ag as w$,kg as V0,lg as $2,mg as xJ,ng as SJ,og as i$,pg as N3,qg as z2,rg as K4,tg as A2,ug as b$,vg as k0,wg as t$,xg as R2}from"./vm-hands-entry-lite-xj0p1ax7.js";import{Dg as d1,Eg as v8}from"./vm-hands-entry-lite-5y2kfnv2.js";import{Jg as z8}from"./vm-hands-entry-lite-vcm4389c.js";import{_h as Z$,ci as W$,di as P0,ei as i9,fi as O6,gi as z6,ii as q2,ji as A6,ki as T9,li as O4,mi as z4,ni as r$}from"./vm-hands-entry-lite-p1nb6n3r.js";import{oi as v1,pi as z1}from"./vm-hands-entry-lite-4xfs7y6w.js";import{Fi as F6,Ni as l8,Oi as L9,Qi as Y8}from"./vm-hands-entry-lite-0p3438xe.js";import{Si as H0,Ui as QJ}from"./vm-hands-entry-lite-tbps80f1.js";import{qj as r}from"./vm-hands-entry-lite-t50b2jyp.js";import{Pj as K}from"./vm-hands-entry-lite-k7fkfytm.js";import{Sj as LJ}from"./vm-hands-entry-lite-jjkkee8q.js";import{Xj as h0}from"./vm-hands-entry-lite-kxtjkzzh.js";import{bk as aV}from"./vm-hands-entry-lite-hw8vgsmm.js";import{spawn as k6,spawnSync as iV}from"child_process";import{closeSync as h6,mkdirSync as nV,openSync as f6,readdirSync as tV,realpathSync as X$,rmSync as M1}from"fs";import{hostname as rV}from"os";import{dirname as w9,join as F0,resolve as oV}from"path";import{createHash as J7}from"crypto";import{unlinkSync as Z7}from"fs";import{platform as Q7}from"os";import{join as X7}from"path";var s9=K.discriminatedUnion("store",[K.strictObject({version:K.literal(1),store:K.literal("keychain")}),K.strictObject({version:K.literal(1),store:K.literal("file"),api_key:K.string().min(1).max(4096)})]),S$=($)=>X7($,"api-key.json");function F$($){let J=J7("sha256").update(`reason-connect-api-key
2
+ import{r as v0}from"./vm-hands-entry-lite-pd4gdky1.js";import{v as n1,x as x6,y as c9}from"./vm-hands-entry-lite-arhbwrn1.js";import{A as X2,B as E6,C as $4,D as J4,E as V6,F as m0,J as G6,K as A$}from"./vm-hands-entry-lite-vebspwdp.js";import{V as g2,oa as e0,ra as u1,ta as VJ}from"./vm-hands-entry-lite-zam0fx58.js";import{Ba as f5,Ca as m5,Da as e4,Ea as $8,Fa as DJ,Ga as WJ,Ha as _9,Ia as d8,Ja as Q8,Ka as L0,La as I1,Ma as C1,Na as I0,Oa as g1,Pa as p8,Qa as B5,Ra as f3,Sa as t8,Wa as r8,cb as AJ,db as RJ,eb as PJ,fb as IJ,gb as D9}from"./vm-hands-entry-lite-m2h8vdr0.js";import{$b as _J,Ab as x8,Bb as J8,Cb as Z8,Db as MJ,Eb as TJ,Gb as u,Hb as e,Ib as s,Jb as c,Kb as H8,Lb as FJ,Mb as N1,Pb as t2,Qb as r2,Rb as R6,Sb as P6,Tb as I6,Ub as S0,Vb as J0,Wb as g,Xb as j9,Yb as j1,Zb as i1,_b as N0,ec as V5,gc as S4,ib as cJ,jc as I2,lb as L8,lc as u8,mb as F8,mc as i3,oc as S8,pb as U8,rb as A8,sc as jJ,tc as l3,ub as R8,zb as E8}from"./vm-hands-entry-lite-saqwe5sm.js";import{xc as X8}from"./vm-hands-entry-lite-bhgsayph.js";import{Ec as g8}from"./vm-hands-entry-lite-gxjxx1r2.js";import{Jc as P8,Kc as I8,Rc as C8}from"./vm-hands-entry-lite-h6qss80e.js";import{Xc as H$}from"./vm-hands-entry-lite-wry37am5.js";import{nd as o4}from"./vm-hands-entry-lite-7wgbj1kg.js";import{Ad as OJ,Dd as v5,Ed as g5,xd as c8}from"./vm-hands-entry-lite-es39m2mg.js";import{Hd as p$,Jd as Q$,Kd as R$,Ld as U1,Nd as B6,Od as S6,Pd as b6,Rd as H1,Sd as w6,Td as b9,Ud as y6,Vd as s2,Wd as M$,Xd as A4,Yd as a2}from"./vm-hands-entry-lite-d0f4kbc8.js";import{Ce as HJ,De as qJ,ef as r4,mf as J6,nf as n$,xf as Z2,ye as L2}from"./vm-hands-entry-lite-cvft83sx.js";import{Kf as C6,Lf as m2,Of as zJ,Rf as w1,Tf as o6,Uf as e6,Zf as n8}from"./vm-hands-entry-lite-wdsk86sk.js";import{Bg as w$,lg as V0,mg as $2,ng as xJ,og as SJ,pg as i$,qg as N3,rg as z2,sg as K4,ug as A2,vg as b$,wg as k0,xg as t$,yg as R2}from"./vm-hands-entry-lite-p7hxm3hc.js";import{Eg as d1,Fg as v8}from"./vm-hands-entry-lite-pk2xd13q.js";import{Kg as z8}from"./vm-hands-entry-lite-cas0c9qd.js";import{$h as Z$,di as W$,ei as P0,fi as i9,gi as O6,hi as z6,ji as q2,ki as A6,li as T9,mi as O4,ni as z4,oi as r$}from"./vm-hands-entry-lite-jd49j573.js";import{pi as v1,qi as z1}from"./vm-hands-entry-lite-1mrkcz0p.js";import{Gi as F6,Oi as l8,Pi as L9,Ri as Y8}from"./vm-hands-entry-lite-gs8cpdfw.js";import{Ti as H0,Vi as QJ}from"./vm-hands-entry-lite-m57kpdgb.js";import{rj as r}from"./vm-hands-entry-lite-8crh75hs.js";import{Qj as K}from"./vm-hands-entry-lite-hzsk6tpw.js";import{Tj as LJ}from"./vm-hands-entry-lite-630eqwb4.js";import{Yj as h0}from"./vm-hands-entry-lite-p24kmysw.js";import{ck as aV}from"./vm-hands-entry-lite-pby299bv.js";import{spawn as k6,spawnSync as iV}from"child_process";import{closeSync as h6,mkdirSync as nV,openSync as f6,readdirSync as tV,realpathSync as X$,rmSync as M1}from"fs";import{hostname as rV}from"os";import{dirname as w9,join as F0,resolve as oV}from"path";import{createHash as J7}from"crypto";import{unlinkSync as Z7}from"fs";import{platform as Q7}from"os";import{join as X7}from"path";var s9=K.discriminatedUnion("store",[K.strictObject({version:K.literal(1),store:K.literal("keychain")}),K.strictObject({version:K.literal(1),store:K.literal("file"),api_key:K.string().min(1).max(4096)})]),S$=($)=>X7($,"api-key.json");function F$($){let J=J7("sha256").update(`reason-connect-api-key
3
3
  ${$}`).digest("hex");return new i$($2(),Q7(),J)}function B3($,J,Z=F$($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(S$($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof V0))throw Q}c(S$($),{version:1,store:"file",api_key:J})}function d0($,J=F$($)){if(!u(S$($)))return null;let Z=s9.parse(JSON.parse(s(S$($))));if(Z.store==="file")return Z.api_key;try{let Q=J.loadBinding();return Q?new TextDecoder().decode(Q):null}catch(Q){if(!(Q instanceof V0))throw Q;throw Error("worker_api_key_unreadable")}}function a9($,J=F$($)){if(!u(S$($)))return;if(s9.parse(JSON.parse(s(S$($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof V0))throw Z}Z7(S$($))}async function K3($,J){let Z;try{Z=await c9({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:S0($.proxy)})}catch(Q){if(Q instanceof m0&&(Q.status===401||Q.status===403))throw Error("worker_api_key_rejected");throw Q}if(!Z)throw Error("worker_api_key_rejected");if(!Z.scopes.includes("devices:write"))throw Error("worker_api_key_devices_write_required");return Z}import{readdirSync as z7,renameSync as A7,rmSync as y$}from"fs";import{join as q0}from"path";import{createHash as Y7}from"crypto";import{realpathSync as V7,statSync as G7,unlinkSync as J2}from"fs";import{platform as B7}from"os";import{join as b0}from"path";function d($){return{state:b0(g($),"device.json"),control:b0(g($),"control.json"),lock:b0(g($),"lifecycle.lock"),socket:b0(g($),"control.sock"),daemon:b0(g($),"daemon.json"),releaseCheck:b0(g($),"release-check.json"),updateDeferral:b0(g($),"update-deferral.json"),firstHeartbeat:b0(g($),"first-heartbeat.json")}}var K7=K.object({version:K.literal(1),device_id:K.string().min(1).max(160),offer:K.unknown().optional(),enrollment_ms:K.number().int().nonnegative().max(n$).optional()});function n9($,J,Z){e(g($),!0),c(d($).firstHeartbeat,{version:1,device_id:J,...Z.offer?{offer:Z.offer}:{},...Z.enrollmentMs!==void 0?{enrollment_ms:Z.enrollmentMs}:{}})}function U3($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=K7.safeParse(JSON.parse(s(Z)));if(J2(Z),!Q.success||Q.data.device_id!==J)return null;let X=Z2(Q.data.offer);return{...X?{offer:X}:{},...Q.data.enrollment_ms!==void 0?{enrollmentMs:Q.data.enrollment_ms}:{}}}catch{return null}}function T0($,J=!1){e(g($),J);let Z=["local-device.key","local-device.binding","device.json"].filter((Q)=>{let X=b0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?H3($):new N3(g($))}function Q2($,J){T0($,!0),H7($);let Z=J??H3($),Q=new N3(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof V0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function H3($){return new i$($2(),B7(),N7($))}function N7($){let J=q3($);return Y7("sha256").update(`reason-worker
4
4
  ${J?.directory??g($)}`).digest("hex")}function D1($,J){c(b0(g($),W1),{version:1,directory:q3($)?.directory??g($),devicePublicKey:J})}var W1="keychain-scope.json";function t9($){return u(b0(g($),W1))}var U7=K.strictObject({version:K.literal(1),directory:K.string().min(1),devicePublicKey:K.string().min(1)});function q3($){let J=b0(g($),W1);if(!u(J))return null;let Z=U7.safeParse(JSON.parse(s(J))),Q=d($).state;if(!Z.success||!u(Q))return null;return JSON.parse(s(Q))?.devicePublicKey===Z.data.devicePublicKey?Z.data:null}function H7($){let J=b0(g($),W1);if(!u(J))return;if(q3($))try{let Z=H3($);Z.deleteBinding(),Z.deleteKey()}catch(Z){if(!(Z instanceof V0))throw Z}J2(J)}function K$($){let J=V7($.workspaceRoot);if(J!==$.workspaceRoot||!G7(J).isDirectory()||!j1(J,$.stateDirectory))throw Error("worker_workspace_not_canonical_or_overlaps_state")}function o($){if(!u(g($)))return null;let J=b$(d($).state,{proofStore:T0($),repair:!1}),Z=J!==null&&i9($.apiOrigin,J.apiOrigin),Q=Z?[N0($),N0({...$,apiOrigin:J.apiOrigin})]:[N0($)];if(J&&(!Q.includes(J.worker?.configDigest??"")||J.worker.lifetime!==$.lifetime||J.apiOrigin!==$.apiOrigin&&!Z||J.roots.length>32||J.roots[0]?.path!==$.workspaceRoot||J.handsSlots!==$.slots))throw Error("worker_config_binding_mismatch");return J}var r9=K.strictObject({version:K.literal(1),drained:K.boolean(),revoked:K.boolean()});function $0($){let J=d($).control;return u(J)?r9.parse(JSON.parse(s(J))):{version:1,drained:!1,revoked:!1}}function R0($,J){c(d($).control,r9.parse(J))}function w0($){let J=T0($);J.deleteBinding(),J.deleteKey();let Z=b0(g($),W1);if(u(Z))J2(Z);let Q=d($).state;if(u(Q))J2(Q)}var q7=K.strictObject({read:K.boolean(),write:K.boolean(),execute:K.boolean(),discover_environment:K.boolean(),expose_mcp:K.literal(!1)}),M3=K.strictObject({version:K.literal(1),organization_id:K.string().min(1).max(160),enrollment_ticket:K.string().min(1).max(4096),code_verifier:K.string().regex(/^[A-Za-z0-9._~-]{43,128}$/),root_fingerprint_key:K.string().regex(/^[a-f0-9]{64}$/),root:K.strictObject({path_fingerprint:K.string().regex(/^[a-f0-9]{64}$/),permissions:q7,execution_mode:K.enum(["confined","host"]).default("confined")}),folders:K.array(K.strictObject({path_fingerprint:K.string().regex(/^[a-f0-9]{64}$/)})).min(1).max(31).optional()}),M7=K.object({device_id:K.string().min(1).max(160),organization_id:K.string().min(1).max(160),auth_scheme:K.literal("p256"),protocol_version:K.literal(2),roots:K.array(K.object({id:K.string().min(1),label:K.string(),path_fingerprint:K.string()})).min(1).max(32),headless:K.object({lifecycle:K.enum(["persistent","ephemeral"]),expires_at:K.iso.datetime({offset:!0})}),first_heartbeat:K.unknown().optional()}),T3=30000;class r0 extends Error{deviceRemoved;constructor($){super("worker_enrollment_rejected");this.deviceRemoved=$}}async function T7($,J,Z=fetch){let Q=await Z(`${$}/app/local-runtime/enroll`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J),redirect:"error",signal:AbortSignal.timeout(T3)});if(!Q.ok){let X=Q.status===409?await Q.json().catch(()=>null):null;throw new r0(X?.error==="device_revoked")}return Q.json()}async function L3($,J,Z,Q){v0();let X=M3.parse(JSON.parse(s(J)));return o0($,X,Z,Q)}async function o0($,J,Z,Q=(Y,V)=>T7(Y,V,S0($.proxy)),X=performance.now()){let Y=e9($,J,Z),V=await Q($.apiOrigin,{...Y.request,enrollment_ticket:J.enrollment_ticket,code_verifier:J.code_verifier});return Y.receipt(V,X)}async function o9($,J,Z,Q,X=performance.now()){let Y=e9($,J,Z),V=await Q(Y.request,J.code_verifier);return V===null?null:Y.receipt(V,X)}function e9($,J,Z){if(v0(),J.root.execution_mode!==$.executionMode)throw Error("worker_enrollment_mode_mismatch");let Q=w$([$.workspaceRoot],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(Q.path!==$.workspaceRoot||Q.pathFingerprint!==J.root.path_fingerprint)throw Error("worker_enrollment_root_mismatch");let X=($.folders??[]).map((B,U)=>{let M=w$([B],J.root.permissions,Buffer.from(J.root_fingerprint_key,"hex"))[0];if(M.path!==B||M.pathFingerprint!==J.folders?.[U]?.path_fingerprint)throw Error("worker_enrollment_root_mismatch");return M});if((J.folders?.length??0)!==X.length)throw Error("worker_enrollment_root_mismatch");let Y=[{...Q,label:"workspace"},...X],V;try{V=Z.loadPublicKey()}catch{V=Z.createFreshPublicKey()}return{request:{device_public_key:V,name:$.name,os:process.platform,architecture:process.arch,reason_runtime_version:r,bridge_version:r,protocol_version:2,capabilities:{supported_operations:[]},roots:Y.map((B)=>({label:B.label,path_fingerprint:B.pathFingerprint,permissions:J.root.permissions}))},receipt(B,U){let M=M7.parse(B);if(M.organization_id!==J.organization_id||M.roots.length!==Y.length||M.roots.some((H,q)=>H.path_fingerprint!==Y[q].pathFingerprint)||M.headless.lifecycle!==$.lifetime||Date.parse(M.headless.expires_at)<=Date.now())throw Error("worker_enrollment_receipt_mismatch");let G=Z2(M.first_heartbeat);try{n9($,M.device_id,{...G?{offer:G}:{},enrollmentMs:Math.min(n$,Math.max(0,Math.round(performance.now()-U)))})}catch{}return{version:4,apiOrigin:$.apiOrigin,orgId:M.organization_id,deviceId:M.device_id,devicePublicKey:V,displayName:$.name,registeredAt:new Date().toISOString(),handsSlots:$.slots,worker:{configDigest:N0($),lifetime:$.lifetime,expiresAt:M.headless.expires_at},roots:M.roots.map((H,q)=>({id:H.id,label:H.label,path:Y[q].path,pathFingerprint:H.path_fingerprint,permissions:J.root.permissions}))}}}}import{randomBytes as L7,randomUUID as F7}from"crypto";import{unlinkSync as _7}from"fs";import{join as j7}from"path";var Z4=K.strictObject({version:K.literal(1),install_id:K.uuid(),fingerprint_key:K.string().regex(/^[a-f0-9]{64}$/)}),D7=K.object({enrollment_ticket:K.string().min(1).max(4096),expires_at:K.iso.datetime({offset:!0}),device_kind:K.literal("headless"),lifecycle:K.enum(["persistent","ephemeral"]),device_expires_at:K.iso.datetime({offset:!0})});function F3($){return D7.parse($)}var W7=K.object({credentialKind:K.enum(["oauth","api_key"]).optional(),apiOrigin:K.url(),clientId:K.string(),accessToken:K.string().min(1).max(32768),refreshToken:K.string().max(32768),expiresAt:K.iso.datetime({offset:!0}),scopes:K.array(K.string().max(128)).max(128),orgId:K.string().min(1).max(160)});function _$($){return X2(z1("REASON_CLI_CHANNEL",$.channel),H0())}async function j$($,J=_$($)){if(!u(J))return null;let Z=W7.parse(JSON.parse(s(J)));if(!P0(Z.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(Z.credentialKind==="api_key")return Date.parse(Z.expiresAt)>Date.now()?Z:null;let Q=S0($.proxy),X=Object.assign((V,N)=>Q(V,{...N,redirect:"error",signal:AbortSignal.timeout(30000)}),{preconnect:fetch.preconnect}),Y=await J4({path:J,fetchImpl:X});if(Y&&!P0(Y.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");return Y}async function Q4($,J,Z){if(!P0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Q=D$($);return Q.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(Q.request))}async function X4($,J,Z,Q,X){let Y=performance.now();if(!P0(J.apiOrigin,$.apiOrigin))throw Error("worker_session_origin_mismatch");if(!J.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let V=D$($),N=X?void 0:Z.enrollHeadlessDevice?.bind(Z);if(N){let B=await o9($,V.direct(J.orgId),Q,(U,M)=>N({approval:V.request,code_verifier:M,registration:U}).catch((G)=>{throw O7(G)}),Y);if(B)return B}return o0($,V.complete(J.orgId,await Z.createHeadlessDeviceEnrollmentTicket(V.request)),Q,X,Y)}function O7($){if(!($ instanceof m0))return $;if($.status===409)return new r0($.code==="device_revoked");if($.status===410||$.status===401&&$.code==="invalid_enrollment_ticket"||$.status===403&&$.code==="grant_exceeded"||$.status===400&&$.code==="invalid_device_enrollment")return new r0(!1);return $}var O1=($)=>j7(g($),"enrollment-install.json");function Y4($){if(u(O1($)))_7(O1($))}function D$($,{stored:J=!0}={}){v0();let Z=O1($),Q=J&&u(Z)?Z4.parse(JSON.parse(s(Z))):{version:1,install_id:F7(),fingerprint_key:L7(32).toString("hex")};if(J&&!u(Z))c(Z,Q);let X={read:!0,write:!0,execute:!0,discover_environment:!0,expose_mcp:!1},Y=Buffer.from(Q.fingerprint_key,"hex"),V=w$([$.workspaceRoot],X,Y)[0];if(V.path!==$.workspaceRoot)throw Error("worker_workspace_not_canonical_or_overlaps_state");let N=($.folders??[]).map((G)=>{let H=w$([G],X,Y)[0];if(H.path!==G)throw Error("worker_workspace_not_canonical_or_overlaps_state");return{path_fingerprint:H.pathFingerprint}}),B=$4(),U={install_id:Q.install_id,code_challenge:B.challenge,lifecycle:$.lifetime,roots:[V.pathFingerprint,...N.map((G)=>G.path_fingerprint)].map((G)=>({path_fingerprint:G,permissions:X,execution_mode:$.executionMode}))},M=(G)=>({version:1,organization_id:G,code_verifier:B.verifier,root_fingerprint_key:Q.fingerprint_key,root:{path_fingerprint:V.pathFingerprint,permissions:X,execution_mode:$.executionMode},...N.length?{folders:N}:{}});return{request:U,saveInstall(G){e(g(G),!0),c(O1(G),Q)},complete(G,H){let q=F3(H);if(q.lifecycle!==$.lifetime||Date.parse(q.expires_at)<=Date.now()||Date.parse(q.device_expires_at)<=Date.now())throw Error("worker_ticket_receipt_mismatch");return{...M(G),enrollment_ticket:q.enrollment_ticket}},direct:M}}function V4($,J,Z){let Q=O1($);if(!u(Q))throw Error("worker_folders_unavailable");let X=Z4.parse(JSON.parse(s(Q)));return w$([J],Z,Buffer.from(X.fingerprint_key,"hex"))[0]}var Y2=8,N4=600000,U4=15000,G4=new Set(["device_revoked","invalid_device_credential"]),V2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,N$=($)=>q0(g($),"workspaces"),H4="account.json",_3=($)=>u(q0($,H4));function y0($){let J;try{J=z7(N$($))}catch{return[]}return J.filter((Z)=>V2.test(Z)).sort().map((Z)=>{let Q=q0(N$($),Z),X=q0(Q,"worker.json"),Y=null;try{let V=J0.safeParse(JSON.parse(s(X)));if(V.success&&V.data.stateDirectory===Q)Y=V.data}catch{}return{organizationId:Z,directory:Q,configPath:X,config:Y,account:_3(Q)}})}function G2($,J){let Z=J.toLowerCase();if(!V2.test(Z))throw Error("worker_workspace_id_invalid");let Q=J0.parse({...$,stateDirectory:q0(N$($),Z)});return e(Q.stateDirectory,!0),c(q0(Q.stateDirectory,H4),{version:1}),{config:Q,configPath:q0(Q.stateDirectory,"worker.json")}}function B2($,J){try{let{config:Z,configPath:Q}=G2($,J);e(g(Z),!0),R0(Z,{version:1,drained:!0,revoked:!0}),c(Q,Z)}catch{}}function A1($,J){let Z=J.toLowerCase(),Q=null;try{Q=o($)?.orgId.toLowerCase()??null}catch{}return Q===Z||y0($).some((X)=>!X.account&&X.config!==null&&X.organizationId===Z)}var j3=["device.json","local-device.key","local-device.binding","keychain-scope.json","control.json","enrollment-install.json","first-heartbeat.json"];function B4($,J){let Z=o($);if(!Z?.worker)throw Error("worker_identity_missing");D1($,Z.devicePublicKey),e(g(J),!0);for(let Y of j3)y$(q0(g(J),Y),{force:!0});for(let Y of j3){let V=q0(g($),Y);if(u(V))A7(V,q0(g(J),Y))}let Q=T0(J),X=b$(d(J).state,{proofStore:Q,repair:!1});if(!X?.worker)throw Error("worker_identity_missing");k0({...X,worker:{...X.worker,configDigest:N0(J)}},d(J).state,{proofStore:Q})}function D3($){for(let J of y0($)){if(J.account)continue;try{if(J.config&&u(d(J.config).state))w0(J.config)}catch{}y$(J.directory,{recursive:!0,force:!0})}y$(O3($),{force:!0})}function K2($,{prefer:J,keep:Z,live:Q=!1}){let X=Date.now(),Y=(G)=>Number(Date.parse(G.worker?.expiresAt??"")>X+60000),N=y0($).flatMap((G)=>{if(!G.account||!G.config)return[];try{if($0(G.config).revoked)return[];let H=o(G.config);return H&&H.orgId.toLowerCase()===G.organizationId&&(!Q||Y(H))?[{...G,config:G.config,state:H}]:[]}catch{return[]}}).sort((G,H)=>Number(H.organizationId===J)-Number(G.organizationId===J)||Y(H.state)-Y(G.state))[0];if(!N)return null;let B=null;try{B=$0($).revoked?null:o($)}catch{}let U=B?.orgId.toLowerCase()??"";if(Z&&B&&V2.test(U)&&U!==N.organizationId){let G=G2($,U);B4($,G.config),c(G.configPath,G.config)}else if(u(g($))){try{if(u(d($).state))w0($)}catch{}for(let G of j3)y$(q0(g($),G),{force:!0})}D3($);let M=J0.parse({...N.config,stateDirectory:$.stateDirectory});return B4(N.config,M),c(q0($.stateDirectory,"worker.json"),M),y$(N.directory,{recursive:!0,force:!0}),M}var W3={before($){for(let{config:J}of y0($))try{let Z=J?o(J):null;if(J&&Z)D1(J,Z.devicePublicKey)}catch{}},after($,J){for(let{organizationId:Z,directory:Q,configPath:X,config:Y}of y0(J)){if(Y)continue;try{let V=J0.parse(JSON.parse(s(X)));if(V.stateDirectory!==q0(N$($),Z))continue;let N=J0.parse({...V,stateDirectory:Q}),B=T0(N),U=b$(d(N).state,{proofStore:B,repair:!1});if(U?.worker?.configDigest===N0(V))k0({...U,worker:{...U.worker,configDigest:N0(N)}},d(N).state,{proofStore:B});c(X,N)}catch{}}}},O3=($)=>q0(N$($),"listed.json");function q4($){try{let J=JSON.parse(s(O3($))),Z=J.names&&typeof J.names==="object"&&!Array.isArray(J.names)?Object.fromEntries(Object.entries(J.names).filter((Q)=>typeof Q[1]==="string")):{};return{listed:J.listed===!0,reason:J.reason==="sign_in"?"sign_in":null,blocked:Array.isArray(J.blocked)?J.blocked.filter((Q)=>typeof Q==="string"):[],names:Z}}catch{return null}}function M4($,J){let Z=y0($),Q=Z.filter((B)=>B.account),X=Z.filter((B)=>!B.account),Y=q4($),V=Y&&!Y.listed?Y.reason:null,N=V||X.length===0&&Y&&!Y.listed?[]:X;if(Q.length===0&&N.length===0&&(V||Y&&!Y.listed))return{workspaces:null,off:V};return{off:V,workspaces:[...Q,...N].map(({organizationId:B,config:U,account:M})=>{let G=!1,H=null,q=!1,T=null;try{G=U?$0(U).revoked:!1,H=U&&!G?o(U):null;let L=U?t$(d(U).daemon):null;q=J&&!!H&&L?.state==="connected",T=q?K4(L,H):null}catch{}return{...T?{permission_recovery:T}:{},organization_id:B,device_id:H?.deviceId??null,name:Y?.names?.[B]??null,root:H?.roots[0]?{id:H.roots[0].id,permissions:H.roots[0].permissions}:null,state:G?"removed":q?"connected":"not_running",blocked:!M&&!G&&!q&&(Y?.blocked.includes(B)??!1),...M?{account:!0}:{}}})}}function T4($){let{config:J,state:Z,client:Q,signal:X}=$,Y=$.log??(()=>{return}),V=new Map,N=null,B=!1,U=q4(J)??{listed:!1,reason:null,blocked:[]},M=(_)=>{let{folders:D,...R}=J,E=Z.roots.slice(1).map((P)=>P.path);return J0.parse({...R,...E.length?{folders:E}:{},stateDirectory:q0(N$(J),_)})},G=async(_)=>{let D=V.get(_);if(!D)return;D.controller.abort(),await D.done},H=(_,D=!1)=>{let R=new AbortController,E=()=>R.abort();if(X.addEventListener("abort",E,{once:!0}),X.aborted)R.abort();let P={..._,controller:R,claims:0,done:Promise.resolve(),account:D};P.done=$.serve(_,R.signal,(I)=>{P.claims=I}).then(()=>{return},(I)=>{if(D&&I instanceof L0&&I.status===401&&G4.has(I.code)){try{R0(_.config,{version:1,drained:!0,revoked:!0})}catch{}Y(`Reason worker: workspace ${_.organizationId} (another account's) no longer accepts this computer (${I.code}); run \`reason connect\` signed in as that account to connect it again
5
5
  `)}else if(I instanceof L0&&I.status===401&&G4.has(I.code)){try{w0(_.config)}catch{}Y(`Reason worker: workspace ${_.organizationId} no longer accepts this computer
@@ -309,7 +309,7 @@ Usage:
309
309
  `),host:Z.host}),N=_4({...V,log:(q)=>Q.stderr.write(`${q}
310
310
  `)}),{configPath:B}=N,U=N.saved;if(!U)return Q.stderr.write("Reason: this computer has no saved connection. Run `reason connect`.\n"),0;let M=(q,T)=>{let L=Z3(Z.home,Z.channel),j;try{let O=null;try{O=T.keep?null:o(U)?.orgId.toLowerCase()??null}catch{}if(j=K2(U,{prefer:t1(Z.home,Z.channel,U),...T}),j&&O)B2(j,O)}finally{L()}if(!j)return!1;U=j;let W="";try{W=` (workspace ${o(j)?.orgId??"unknown"})`}catch{}return Q.stderr.write(`Reason: ${q}; this computer goes on running Sessions for its other Reason account${W}.
311
311
  `),!0};if($0(U).revoked&&!M("this computer's connection was removed from Reason",{keep:!1}))return Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0;if(U.executionMode==="confined"||!q1(U)){let q=d0(U.stateDirectory)??void 0,T=q?null:t1(Z.home,Z.channel,U);if(!q&&!(T&&A1(U,T)))M("this computer's connection expired and its account is not signed in here",{keep:!0,live:!0})}let G=U.executionMode==="confined";if(G||!q1(U)){let q=d0(U.stateDirectory)??void 0;if(Q.stderr.write(G?u6:`Reason: this computer's connection expired; renewing it with ${q?"its API key":"your login"}\u2026
312
- `),await y9(J0.parse({...U,executionMode:"host"}),B,Q,X,q)!==0)return Q.stderr.write(q?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let H=new AbortController;if(!X.runWorker)import("./ask-relay-7yw62yzw.js").then(({runBackgroundAskRelay:q})=>q(H.signal,(T)=>Q.stderr.write(`${T}
312
+ `),await y9(J0.parse({...U,executionMode:"host"}),B,Q,X,q)!==0)return Q.stderr.write(q?"Reason: could not renew this computer's connection. Run `reason connect --api-key KEY` with a valid key.\n":"Reason: could not renew this computer's connection. Run `reason login`, then `reason connect`.\n"),0}let H=new AbortController;if(!X.runWorker)import("./ask-relay-ar561trh.js").then(({runBackgroundAskRelay:q})=>q(H.signal,(T)=>Q.stderr.write(`${T}
313
313
  `))).catch(()=>{});try{for(;;){let q=d0(U.stateDirectory)===null?{ownerWorkspaces:X.worker?.ownerWorkspaces??{}}:{},T=X.runWorker?null:l2({stateDirectory:U.stateDirectory}),L=!1,j;try{j=await(X.runWorker??q$)(["start","--config",B],{deferOptionalLanes:!0,...X.worker,...q,ownComputer:!0,io:{stdout:Q.stdout,stderr:Q.stderr},onDeviceRevoked:()=>{L=!0}})}finally{T?.stop()}if(!L)return j;if(!M("this computer's connection was removed from Reason",{keep:!1}))break}return e2(Z.home,Z.channel,!0),Q.stderr.write("Reason: this computer was removed from Reason. Run `reason connect` to connect it again.\n"),0}finally{H.abort()}}async function VG($,J,Z){let{io:Q,options:X,home:Y,channel:V,environment:N}=Z;if(J&&await(X.controlWorker??K0)(J,"status").catch(()=>null))throw new l("This computer is already connected in the background (see `reason status`). Run `reason disconnect` first to connect it only while a command runs.");let B=g0(Y,V,!0),U=p6({parsed:$,saved:J,stateDirectory:B,lifetime:"ephemeral",home:Y,channel:V,options:X,environment:N}),M=l6(U,Z.apiKey??(J?d0(J.stateDirectory)??void 0:void 0)),G=F0(B,"worker.json");return e(B,!0),c(G,M),Q.stdout.write(x9(`Reason: connecting "${M.name}" while this command runs`,M,Z.host.platform,["Connecting\u2026"])),(X.runWorker??q$)(["start","--config",G],{...k9(X.worker,Z.apiKey),ownComputer:!0,io:{stdout:Q.stdout,stderr:n2(Q.stderr)},onStartup:(H)=>{if(H==="ready")Q.stdout.write(`Connected. Start Sessions on "${M.name}" from Reason. Press Ctrl-C to stop.
314
314
  `);X.worker?.onStartup?.(H)}})}function GG($,J,Z,Q){if(Z.platform!=="darwin")throw new l("--keep-awake is for macOS.");if(!J)throw new l("This computer is not connected to Reason. Run reason connect first.");e(g(J),!0),x4(d(J).daemon,$);let X=M2(d(J).daemon)==="battery_and_ac";return Q.stdout.write(`Keep awake: ${X?"on (this Mac stays awake while it runs Sessions)":"off"}
315
315
  `),0}var BG=K.object({root:K.object({id:K.string().min(1).max(160),label:K.string().max(160),path_fingerprint:K.string()})});async function c6($,J,Z,Q){let X=await(k9(Q.worker,Z).enrollmentCredentials??j$)($,_$($));if(!X)throw Error("worker_session_login_required");if(!X.scopes.includes("devices:write"))throw Error("worker_devices_write_scope_required");let Y=Q.folderApi?.(X)??new A$(X,{credentialsPath:_$($),fetchImpl:S0($.proxy)}),V=(N)=>N instanceof m0&&N.status===404&&!["device_not_found","root_not_found"].includes(N.code);return{add:async(N)=>{let B=V4($,N,{...J.roots[0].permissions,expose_mcp:!1}),U=await Y.addDeviceRoot(J.deviceId,{path_fingerprint:B.pathFingerprint,label:B.label,permissions:{...B.permissions,expose_mcp:!1}}).catch((G)=>{if(V(G))throw Error("worker_folders_unavailable");if(G instanceof m0&&G.code==="root_limit_reached")throw new l("This computer already has the most folders Reason allows (32).");throw G}),M=BG.parse(U).root;if(M.path_fingerprint!==B.pathFingerprint)throw Error("worker_enrollment_receipt_mismatch");return{...B,id:M.id,label:M.label}},remove:async(N)=>{await Y.removeDeviceRoot(J.deviceId,N).catch((B)=>{if(V(B))throw Error("worker_folders_unavailable");if(!(B instanceof m0&&B.code==="root_not_found"))throw B})}}}function s6($,J,Z){k0({...J,roots:Z,handsSlots:$.slots,worker:{...J.worker,configDigest:N0($)}},d($).state,{proofStore:T0($)})}async function a6($,J,Z,Q){let{io:X,options:Y,host:V}=Q,N=J&&!Q.apiKey&&d0(J.stateDirectory)===null?t1(Q.home,Q.channel,J):null,B=J&&N&&P$(J)&&!A1(J,N)?y0(J).find((P)=>P.account&&P.organizationId===N)??null:void 0;if(B===null)throw new l("This computer is not connected for your account. Run reason connect first.");let U=B?B.config:J,M=B?B.configPath:Z,G=U&&P$(U)&&!$0(U).revoked?o(U):null;if(!J||!U||!G||U.lifetime!=="persistent")throw new l("This computer is not connected to Reason. Run reason connect first.");let H=$.addFolder!==void 0,q=H?$.addFolder:$.removeFolder,T=Y.cwd??process.cwd(),L;try{L=i2(T,q)}catch(P){if(H)throw new l(P instanceof Error?P.message:String(P));L=oV(T,q)}if(L===U.workspaceRoot)throw new l(`${L} is this computer's main folder. To use another one, run reason connect --folder PATH.`);let j=U.folders??[],W=G.roots.slice(1).find((P)=>P.path===L);if(!H&&!W&&!j.includes(L))throw new l(`${L} is not one of this computer's folders.`);if(H&&!j1(L,U.stateDirectory))throw new l(`${L} holds Reason's own settings.`);if(H&&!W&&j.length>=31)throw new l("This computer already has the most folders Reason allows (32).");let O=Q.apiKey??d0(U.stateDirectory)??void 0,F=await c6(U,G,O,Y),z=G.roots.filter((P)=>P.path!==L);if(H)z=[...z,await F.add(L)];else if(W)await F.remove(W.id);s6(U,G,z);let _=H?[...j.filter((P)=>P!==L),L]:j.filter((P)=>P!==L),{folders:D,...R}=U;if(c(M,J0.parse({...R,..._.length?{folders:_}:{}})),!await(Y.controlWorker??K0)(J,"reload_roots").then(()=>!0,()=>!1))M$(J,V,"connect");return X.stdout.write(H?`Added ${L}. Sessions on "${U.name}" may run in it.
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{uc as j,vc as q}from"./vm-hands-entry-lite-cwf21py1.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
2
+ import{uc as j,vc as q}from"./vm-hands-entry-lite-bhgsayph.js";function y(v=process.platform){if(j(),v==="linux")q("strict")}
3
3
  export{y as r};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{Si as J}from"./vm-hands-entry-lite-tbps80f1.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
2
+ import{Ti as J}from"./vm-hands-entry-lite-m57kpdgb.js";import{readFileSync as L}from"fs";import{isAbsolute as M,normalize as Q}from"path";var W="REASON_WORKER_DESKTOP_USER",G=null;function X(q,B){for(let I of B.split(`
3
3
  `)){let j=I.split(":");if(j.length<7||Number(j[2])!==q||!/^\d+$/.test(j[2])||!/^\d+$/.test(j[3]))continue;let x=j[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(j[0])||!M(x)||Q(x)!==x||x==="/")return null;return{username:j[0],uid:q,gid:Number(j[3]),home:x}}return null}function b(q={}){let B="value"in q?q.value:process.env[W];if(G=null,B===void 0||B==="")return null;let I=q.platform??process.platform,j="euid"in q?q.euid:process.geteuid?.(),x=/^[1-9]\d{0,9}$/.test(B)?Number(B):NaN,C=I==="linux"&&j===0&&Number.isSafeInteger(x)?X(x,(q.passwd??(()=>L("/etc/passwd","utf8")))()):null;if(!C||C.gid===0)throw Error("worker_desktop_user_invalid");return G=C,C}function k(){return G}function y(){return G?.home??J()}
4
- export{W as Bg,X as Cg,b as Dg,k as Eg,y as Fg};
4
+ export{W as Cg,X as Dg,b as Eg,k as Fg,y as Gg};