@reason-machines/cli-linux-arm64-musl 0.2.327 → 0.2.329
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.
- package/bin/ara +1 -1
- package/bin/vm-hands/connect-cli-tvqpqf33.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-j47avpaq.js → custom-endpoint-device-8yqvpsd7.js} +1 -1
- package/bin/vm-hands/desktop-account-s4629ksd.js +2 -0
- package/bin/vm-hands/{device-workspace-xnyb7zp2.js → device-workspace-pacdp5tv.js} +1 -1
- package/bin/vm-hands/hands-worker-source-fprvxtp8.js +2 -0
- package/bin/vm-hands/{index-752q9pdp.js → index-wx03jedr.js} +1 -1
- package/bin/vm-hands/local-automation-p0ty82xb.js +2 -0
- package/bin/vm-hands/local-capabilities-qyw7cmjt.js +2 -0
- package/bin/vm-hands/local-desktop-users-ktbva6me.js +2 -0
- package/bin/vm-hands/local-display-mac-kbbrwa0y.js +2 -0
- package/bin/vm-hands/local-display-session-dmdw0q7k.js +2 -0
- package/bin/vm-hands/local-pty-session-bnhx083p.js +2 -0
- package/bin/vm-hands/{network-contract-bv7mj5he.js → network-contract-gb6gk8fg.js} +1 -1
- package/bin/vm-hands/package-bzy9agdv.js +2 -0
- package/bin/vm-hands/permissions-14dvc1rh.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-5zt3ys5t.js → reason-hands-protocol-469gmb0h.js} +1 -1
- package/bin/vm-hands/{status-t6acadsj.js → status-ysdt3ep8.js} +2 -2
- package/bin/vm-hands/version-tsq05aw1.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-7t05ea2h.js → vm-hands-entry-lite-0p3hac9d.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-9kasrx18.js → vm-hands-entry-lite-0yghpjef.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ep1me9q3.js → vm-hands-entry-lite-18kr0x4w.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v6tkjqb1.js → vm-hands-entry-lite-40t7d4p5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-cxs89wzv.js → vm-hands-entry-lite-5a0kyaxa.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-psybjyay.js → vm-hands-entry-lite-669hk342.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-6g65w75z.js +5 -0
- package/bin/vm-hands/{vm-hands-entry-lite-yhz6sv35.js → vm-hands-entry-lite-8afzattm.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-n07kxrd1.js → vm-hands-entry-lite-9y8v419y.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-b2wdaq7x.js → vm-hands-entry-lite-abrbc7gf.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cx4z34jh.js → vm-hands-entry-lite-asr8j2d4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mzxhng4z.js → vm-hands-entry-lite-djy0ww6h.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-14t846kp.js → vm-hands-entry-lite-dyqeaqzb.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-472z7kjx.js → vm-hands-entry-lite-henbtxfe.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-22jgncrd.js → vm-hands-entry-lite-jz24p4jj.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-cp1wqjs5.js → vm-hands-entry-lite-kbz9zfha.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ne8kkvk4.js → vm-hands-entry-lite-n5ec0fjy.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qvrnx0vk.js → vm-hands-entry-lite-n8gsyjq7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fq0zr7an.js → vm-hands-entry-lite-nj8bmc9y.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-7jmj7peg.js → vm-hands-entry-lite-nwcza0v8.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-xf6schkk.js → vm-hands-entry-lite-pbnx8z9g.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-q5thp2ap.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-93ejmwqn.js → vm-hands-entry-lite-rd9vsaew.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-t497ewn2.js → vm-hands-entry-lite-rnwjp0tk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-wh0qp1gf.js → vm-hands-entry-lite-sggk0bqc.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-tav4dt92.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-fbbd8e32.js → vm-hands-entry-lite-wtk1v493.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-xbe3dat0.js +181 -0
- package/bin/vm-hands/{vm-hands-entry-lite-mgx65dde.js → vm-hands-entry-lite-xjyd9xvx.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/vm-hands-executor-n2w3v0fs.js +10 -0
- package/bin/vm-hands/vm-hands-op-runner-p2q67yw9.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-jnz4rqxa.js +4 -0
- package/bin/vm-hands/worker-sandbox-bqwkytj2.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/connect-cli-44va9379.js +0 -2
- package/bin/vm-hands/desktop-account-emwzhj61.js +0 -2
- package/bin/vm-hands/hands-worker-source-ea5ywzxx.js +0 -2
- package/bin/vm-hands/local-automation-7cypstyv.js +0 -2
- package/bin/vm-hands/local-capabilities-nywse9m3.js +0 -2
- package/bin/vm-hands/local-desktop-users-rn753h90.js +0 -2
- package/bin/vm-hands/local-display-mac-9qqvjs82.js +0 -2
- package/bin/vm-hands/local-display-session-gtk92n5e.js +0 -2
- package/bin/vm-hands/package-xeh4dp97.js +0 -2
- package/bin/vm-hands/permissions-rgfr52fz.js +0 -2
- package/bin/vm-hands/version-rm84p9qv.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-28ta42wn.js +0 -181
- package/bin/vm-hands/vm-hands-entry-lite-rm0jf774.js +0 -5
- package/bin/vm-hands/vm-hands-executor-2pqe40rp.js +0 -10
- package/bin/vm-hands/vm-hands-op-runner-b484wkc9.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-mew62849.js +0 -4
- package/bin/vm-hands/worker-sandbox-yt11b09s.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ch as c}from"./vm-hands-entry-lite-cp1wqjs5.js";var g={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},g0=Object.values(g),jZ=new Set;function MQ(Q,Z){let $=Q[Z];if($?.trim())return $;let X=Q[g[Z]];if(X?.trim())jZ.add(g[Z]);return X}function KZ(Q,Z){return{[Q]:Z,[g[Q]]:Z}}import{basename as BZ}from"path";var i=["production","staging"],OZ="https://api.reasonmachines.com",kZ="https://staging-api.reasonmachines.com";var l={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},AZ=new Set(["ara-staging","reason-staging"]);function KQ(Q={}){let Z=MQ(Q.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Z){if(i.includes(Z))return Z;throw Error(`Unknown Reason CLI channel: ${Z}`)}let $=BZ(Q.executablePath??process.execPath).toLowerCase();return AZ.has($)?"staging":"production"}function h(Q){return Q==="staging"?kZ:OZ}function y0(Q){return`${h(Q)}/mcp/ara`}var BQ={production:["https://api.ara.so",l.production.api],staging:["https://api-staging.ara.so",l.staging.api]};function jQ(Q){let Z;try{Z=new URL(Q).origin}catch{return Q}let $=i.find((X)=>BQ[X].includes(Z));return $?h($):Z}function p0(Q,Z){return Q===Z||jQ(Q)===jQ(Z)}function OQ(Q,Z){return i.some(($)=>BQ[$].includes(Q)&&Z===h($))}function u0(Q,Z){try{let $=new URL(Z);return!$.username&&!$.password&&($.origin===h(Q)||$.origin===l[Q].api)}catch{return!1}}function d0(Q){try{let Z=new URL(Q).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}import{randomBytes as xQ}from"crypto";import{chmodSync as LQ,closeSync as FQ,constants as _Z,linkSync as bQ,lstatSync as x,mkdirSync as fQ,openSync as NZ,readdirSync as P,readFileSync as TQ,readlinkSync as D,renameSync as N,rmdirSync as CQ,symlinkSync as _,unlinkSync as B}from"fs";import{createRequire as xZ}from"module";import{constants as LZ}from"os";import{basename as f,join as U,sep as bZ}from"path";import{existsSync as m,lstatSync as AQ,readdirSync as PZ,readFileSync as FZ,readlinkSync as TZ,realpathSync as DZ}from"fs";import{join as K,sep as RZ}from"path";function o(Q,...Z){let $=K(Q,"ara"),X=K(Q,"reason");if(!v($))return K(X,...Z);if(!m(X))return K($,...Z);return m(K($,...Z))&&!m(K(X,...Z))?K($,...Z):K(X,...Z)}function v(Q){try{let Z=AQ(Q);if(!Z.isSymbolicLink())return Z.isDirectory();return TZ(Q)!=="reason"&&m(Q)}catch{return!1}}function PQ(Q,Z=[]){if(!v(Q))return!1;let $;try{$=[Q,...PZ(Q,{withFileTypes:!0}).filter((X)=>X.isDirectory()).map((X)=>K(Q,X.name))]}catch{return!1}return $.some((X)=>["connect","connect-once"].filter((z)=>!Z.includes(K(X,z))).some((z)=>{let W=K(X,z,"worker.json");try{AQ(W)}catch{return!1}try{let q=JSON.parse(FZ(W,"utf8"))?.stateDirectory;if(typeof q!=="string")return!0;let V=(J,w)=>J===w||J.startsWith(w+RZ);return V(q,Q)||V(kQ(q),kQ(Q))}catch{return!0}}))}function kQ(Q){try{return DZ(Q)}catch{return Q}}var u=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"]),n=new Set(["local-device.proxy.json"]),fZ=new Set(["local-device.key","local-device.binding"]),DQ=new Map;function r(Q,Z,$){let X=U(Q,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(Q))return{state:G(X)?.isDirectory()?"kept":"absent"};return EQ(X,U(Q,"reason"),{linkAlways:!0,kept:(z)=>PQ(z,$??[]),native:Z===void 0?pQ:()=>Z},$!==void 0)}function SQ(Q,...Z){return r(Q),o(Q,...Z)}function z1(Q,Z=process.platform){let $=U(Q,"Library","Logs");if(Z==="darwin")for(let X of[""," Staging"," Development"])EQ(U($,`Ara${X}`),U($,`Reason${X}`),{linkAlways:!1,kept:()=>!1,native:pQ});return U($,"Reason")}var IQ="config_rename_unavailable:busy";function EQ(Q,Z,$,X=!1){let z=X?void 0:DQ.get(Q);if(z)return z;let W;try{W=CZ(Q,Z,$)}catch(q){let V=`config_rename_unavailable:${A(q)??"failed"}`;try{return{state:G(Q)?.isDirectory()?"kept":"absent",problem:V}}catch{return{state:"kept",problem:V}}}if(!(W.state==="absent"&&$.linkAlways)&&W.problem!==IQ&&!(W.state==="kept"&&!W.problem))DQ.set(Q,W);return W}function CZ(Q,Z,$){IZ(Z,$.native);let X=!1;for(let z=0;z<8;z+=1){let W=G(Q);if(W?.isSymbolicLink())return D(Q)===f(Z)?{state:X?"renamed":"linked"}:{state:"kept"};if(!W){if(p(Z))M(()=>B(Z),"ENOENT");if(!(X||$.linkAlways)||!R(Z))return{state:"absent"};let J=b(Z,"link");_(f(Z),J);try{M(()=>N(J,Q),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{M(()=>B(J),"ENOENT")}continue}if(!W.isDirectory())return{state:"absent"};if($.kept(Q))return RQ(Z),{state:"kept"};let q=$.native();if(!q)return RQ(Z),{state:"kept",problem:"config_rename_unavailable:no_native"};let V=EZ(q,Q);if(!V)return{state:"kept",problem:IQ};try{if(x(Q).isSymbolicLink())continue;let J=SZ(q,Q,Z);if(J)return{state:"kept",problem:J};X=!0}finally{V()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function SZ(Q,Z,$){let X=G($);if(!X||p($)){if(!X)_(f($),$);try{Q.exchange(Z,$)}catch(J){if(p($))M(()=>B($),"ENOENT");return`config_rename_unavailable:${A(J)??"exchange_failed"}`}return null}if(!X.isDirectory())return"config_rename_unavailable:ENOTDIR";if(X.dev!==x(Z).dev)return"config_rename_unavailable:EXDEV";let z=[b($,"probe"),b($,"probe")];try{_("a",z[0]),_("b",z[1]),Q.exchange(z[0],z[1])}catch(J){return`config_rename_unavailable:${A(J)??"exchange_failed"}`}finally{for(let J of z)M(()=>B(J),"ENOENT")}let W=yQ($);for(let J of fZ){let w=G(U($,J)),j=G(U(Z,J));if(w&&j&&w.ino!==j.ino)fQ(`${W}-replaced`,{mode:448,recursive:!0}),N(U($,J),U(`${W}-replaced`,J))}let q={linked:new Map,unitsKept:new Set};gQ(Z,$,"",q);let V=b($,"rename");_(f($),V);try{Q.exchange(Z,V)}catch(J){return M(()=>B(V),"ENOENT"),`config_rename_unavailable:${A(J)??"exchange_failed"}`}return hQ(V,$,q,W),null}function t(Q){return Q===""||!Q.includes(bZ)}function gQ(Q,Z,$,X){let z=t($)&&y(U(Z,$),U(Q,$));if(z)X.unitsKept.add($);for(let W of P(U(Q,$))){if(z&&(u.has(W)||n.has(W)))continue;let q=U($,W),V=U(Q,q),J=U(Z,q),w=G(V);if(!w)continue;let j=G(J);if(w.isDirectory()){if(!j)M(()=>fQ(J,{mode:w.mode&4095}),"EEXIST"),LQ(J,w.mode&4095);if(R(J))gQ(Q,Z,q,X)}else if(!j){if(w.isSymbolicLink())M(()=>_(D(V),J),"EEXIST");else if(M(()=>bQ(V,J),"EEXIST","ENOENT"))X.linked.set(q,w.ino)}}}function IZ(Q,Z){let $;try{if(!R(Q))return;$=P(Q)}catch{return}for(let X of $){let z=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(X);if(!z)continue;let W=U(Q,X),q=G(W);if(!q)continue;if(!q.isDirectory()){if(!_Q(Number(z[2])))M(()=>B(W),"ENOENT");continue}let V=Z(),J=null;if(V){try{J=V.lock(W)}catch{continue}if(!J)continue}else if(_Q(Number(z[2])))continue;try{let w=b(Q,"claim");if(M(()=>N(W,w),"ENOENT"))hQ(w,Q,null,yQ(Q))}finally{J?.()}}}function hQ(Q,Z,$,X){for(let[z,W]of $?.linked??[])if(!G(U(Q,z))&&G(U(Z,z))?.ino===W)M(()=>B(U(Z,z)),"ENOENT");if(mQ(Q,Z,"",$),M(()=>CQ(Q),"ENOTEMPTY","EEXIST"))return;N(Q,X),LQ(X,448)}function mQ(Q,Z,$,X){let z=t($)&&(X?X.unitsKept.has($):y(U(Z,$),U(Q,$)));for(let W of P(U(Q,$))){let q=U($,W),V=U(Q,q),J=U(Z,q),w=x(V),j=G(J);if(j&&w.ino===j.ino&&w.dev===j.dev){B(V);continue}if(w.isFile()&&j?.isFile()&&X?.linked.get(q)===j.ino){N(V,J);continue}if(z&&(u.has(W)||n.has(W)))continue;if(!j){if(w.isFile()){if(M(()=>bQ(V,J),"EEXIST"))B(V)}else M(()=>N(V,J),"EEXIST","ENOTEMPTY");continue}if(w.isDirectory()&&j.isDirectory())mQ(Q,Z,q,X),M(()=>CQ(V),"ENOTEMPTY","EEXIST")}}function W1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=["",...P(Z,{withFileTypes:!0}).filter((z)=>z.isDirectory()&&!z.name.startsWith(".")).map((z)=>z.name)];for(let z of X){let W=U(Z,z),q=U($,z);if(!y(W,q)||!y(q,W))continue;if([...u,...n].some((J)=>a(U(W,J),U(q,J))===!1))return z}return null}function q1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=(z)=>{for(let W of P(U(Z,z))){let q=U(z,W);if(t(z)&&(W==="connect"||W==="connect-once"))continue;let V=x(U(Z,q)),J=G(U($,q));if(!J||V.ino===J.ino&&V.dev===J.dev)continue;if(V.isDirectory()&&J.isDirectory()&&!J.isSymbolicLink()){let w=X(q);if(w!==null)return w}else if(V.isSymbolicLink()||J.isSymbolicLink()){if(!(V.isSymbolicLink()&&J.isSymbolicLink()&&D(U(Z,q))===D(U($,q))))return q}else if(a(U(Z,q),U($,q))!==!0)return q}return null};return X("")}function a(Q,Z){let $=G(Q),X=G(Z);if(!$&&!X)return null;if(!$||!X||$.isDirectory()!==X.isDirectory())return!1;if($.ino===X.ino&&$.dev===X.dev)return!0;if($.isDirectory())return[...new Set([...P(Q),...P(Z)])].every((W)=>a(U(Q,W),U(Z,W))===!0);try{return TQ(Q).equals(TQ(Z))}catch{return!1}}function y(Q,Z){for(let $ of u)if(vQ(U(Q,$),U(Z,$)))return!0;return!1}function vQ(Q,Z){let $=G(Q);if(!$)return!1;let X=G(Z);if(!X)return!0;if($.isDirectory()){if(!X.isDirectory())return!0;return P(Q).some((z)=>vQ(U(Q,z),U(Z,z)))}if($.isSymbolicLink())return!X.isSymbolicLink()||D(Q)!==D(Z);return $.ino!==X.ino||$.dev!==X.dev}function RQ(Q){if(p(Q))M(()=>B(Q),"ENOENT")}function yQ(Q){return U(Q,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${xQ(3).toString("hex")}`)}function p(Q){try{return x(Q).isSymbolicLink()&&D(Q)===f(Q)}catch{return!1}}function R(Q){let Z=G(Q);return Z!==null&&Z.isDirectory()}function EZ(Q,Z){for(let $=0;$<40;$+=1){let X=Q.lock(Z);if(X)return X;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function b(Q,Z){return U(Q,`.${Z}-${process.pid}-${xQ(6).toString("hex")}`)}function _Q(Q){if(Q===process.pid)return!1;try{return process.kill(Q,0),!0}catch(Z){return A(Z)==="EPERM"}}function G(Q){try{return x(Q)}catch(Z){if(A(Z)==="ENOENT"||A(Z)==="ENOTDIR")return null;throw Z}}function M(Q,...Z){try{return Q(),!0}catch($){if(Z.includes(A($)??""))return!1;throw $}}function A(Q){return Q instanceof Error&&"code"in Q&&typeof Q.code==="string"?Q.code:void 0}var L,gZ=2,hZ=4,mZ=2,vZ=2,NQ=-100;function pQ(){if(L!==void 0)return L;if(L=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let Q;try{Q=xZ(import.meta.url)("bun:ffi")}catch{return null}let Z=process.platform==="darwin",$=Z?"__error":"__errno_location",X=Z?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:z}=Q;for(let W of X)try{let q=Z?"renamex_np":"renameat2",J=Q.dlopen(W,{flock:{args:[z.i32,z.i32],returns:z.i32},[$]:{args:[],returns:z.ptr},[q]:Z?{args:[z.ptr,z.ptr,z.u32],returns:z.i32}:{args:[z.i32,z.ptr,z.i32,z.ptr,z.u32],returns:z.i32}}).symbols,w=J[$]();if(w===null)continue;let j=(T)=>{let k=Q.read.i32(w),O=Object.entries(LZ.errno).find(([,E])=>E===k)?.[0]??`errno_${k}`;return Object.assign(Error(`${T} failed: ${O}`),{code:O})},HQ=(T)=>Buffer.from(`${T}\x00`,"utf8");return L={exchange(T,k){let O=HQ(T),E=HQ(k);if((Z?J[q](Q.ptr(O),Q.ptr(E),mZ):J[q](NQ,Q.ptr(O),NQ,Q.ptr(E),vZ))!==0)throw j("exchange")},lock(T){let k=NZ(T,_Z.O_RDONLY);if(J.flock(k,gZ|hZ)===0)return()=>FQ(k);let O=j("lock");if(FQ(k),O.code==="EWOULDBLOCK"||O.code==="EAGAIN")return null;throw O}},L}catch{}return null}import{createHmac as V0,createPublicKey as w0,randomBytes as G0,randomUUID as zZ,verify as H0}from"crypto";import{chmodSync as qQ,existsSync as WZ,mkdirSync as M0,readFileSync as j0,realpathSync as K0,renameSync as B0,statSync as O0,unlinkSync as k0,writeFileSync as A0}from"fs";import{basename as P0,dirname as YQ,isAbsolute as qZ,join as s,resolve as F0}from"path";var Y1=[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 yZ="REASON_DESKTOP_RUNTIME",pZ="REASON_DESKTOP_RUNTIME_CHANNEL",uZ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",dZ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",M1={[yZ]:"ARA_DESKTOP_RUNTIME",[pZ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[uZ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[dZ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function uQ(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as QQ,existsSync as F,mkdirSync as ZQ,readFileSync as lQ,realpathSync as lZ,renameSync as iZ,unlinkSync as $Q,writeFileSync as XQ}from"fs";import{createPrivateKey as oZ,createPublicKey as nZ,generateKeyPairSync as rZ,randomUUID as tZ,sign as aZ}from"crypto";import{createRequire as eZ}from"module";import{homedir as Q0,platform as rQ}from"os";import{dirname as Z0,join as C}from"path";import{existsSync as sZ}from"fs";import{join as cQ}from"path";var e="libara_device_keychain.dylib",dQ="libreason_device_keychain.dylib";class cZ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function sQ(Q){let Z=cQ(Q,dQ);return sZ(Z)?Z:cQ(Q,e)}var iQ=1,$0=16384,S=65536,X0=128,z0=128,tQ=65536;class Y 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 aQ(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 zQ=null;function eQ(){if(!zQ)try{zQ=eZ(import.meta.url)("bun:ffi")}catch{throw new Y("native_boundary_unavailable")}return zQ}function W0(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 q0(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new Y("invalid_credential_record");let Z=Q,$=W0(Z.apiOrigin);if(Z.version!==iQ||!$||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 Y("invalid_credential_record");return{version:iQ,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function J0(Q=process.execPath){let Z=Q;try{Z=lZ(Q)}catch{}return sQ(Z0(Z))}function H(Q){return eQ().ptr(Q)}function Y0(Q){if(!F(Q))throw new Y("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=eQ();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(X){if(X instanceof Y)throw X;throw new Y("native_boundary_unavailable")}}function oQ(Q){return Buffer.from(Q).toString("base64url")}function I(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 QZ(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 ZZ{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=J0(),Z=rQ(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;uQ($)}symbols(){if(this.runtimePlatform!=="darwin")throw new Y("unsupported_platform");this.library??=Y0(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(H(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new Y("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(X0),$=new BigUint64Array(1),X=Q==="load"?this.symbols().ara_device_key_load_public(H(Z),BigInt(Z.byteLength),H($)):this.symbols().ara_device_key_create_fresh_public(H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z!==65)throw new Y("invalid_public_key");let W=oQ(Z.subarray(0,z));if(!I(W))throw new Y("invalid_public_key");return W}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=new Uint8Array(z0),$=new BigUint64Array(1),X=this.symbols().ara_device_key_sign(H(Q),BigInt(Q.byteLength),H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y("proof_sign_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z<1||z>Z.byteLength)throw new Y("invalid_signature");let W=Z.subarray(0,z);if(!QZ(W))throw new Y("invalid_signature");return oQ(W)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(H(Q));if(Z!==0||Q[0]!==1)throw new Y("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(H(Q));if(Z!==0)throw new Y("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(S),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("binding_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_binding");return Q.slice(0,X)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_create(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_update(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(H(Q));if(Z!==0)throw new Y("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array($0),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("legacy_credential_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_credential_record");try{let z=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,X));return q0(JSON.parse(z))}catch(z){if(z instanceof Y)throw z;throw new Y("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(H(Q));if(Z!==0)throw new Y("legacy_credential_delete_failed",Z);return Q[0]===1}}function nQ(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new Y("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),X=Buffer.from(Z.y,"base64url");if($.byteLength!==32||X.byteLength!==32)throw new Y("invalid_public_key");let z=Buffer.concat([Buffer.of(4),$,X]).toString("base64url");if(!I(z))throw new Y("invalid_public_key");return z}function U0(){let Q=process.env.XDG_CONFIG_HOME?.trim()||C(Q0(),".config");r(Q);let Z=C(Q,"ara");return v(Z)?Z:C(Q,"reason")}class $Z{directory;constructor(Q=U0()){this.directory=Q}keyPath(){return C(this.directory,"local-device.key")}bindingPath(){return C(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!F(Q))throw new Y("proof_key_read_failed");try{let Z=lQ(Q,"utf8");return oZ({key:Z,format:"pem"})}catch{throw new Y("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=nZ(Q);return nQ(Z)}createFreshPublicKey(){ZQ(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=rZ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),X=this.keyPath();return XQ(X,$,{mode:384}),QQ(X,384),nQ(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=aZ("sha256",Q,Z)}catch{throw new Y("proof_sign_failed")}if(!QZ($))throw new Y("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!F(Q))return!1;return $Q(Q),!0}loadBinding(){let Q=this.bindingPath();if(!F(Q))return null;try{return new Uint8Array(lQ(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(F(Z))throw new Y("binding_create_failed");XQ(Z,Q,{mode:384}),QQ(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!F(Z))throw new Y("binding_update_failed");let $=`${Z}.${tZ()}`;try{XQ($,Q,{mode:384,flag:"wx"}),QQ($,384),iZ($,Z)}finally{if(F($))$Q($)}}deleteBinding(){let Q=this.bindingPath();if(!F(Q))return!1;return $Q(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function WQ(){return rQ()==="darwin"?new ZZ:new $Z}var UQ=4;var d="macos-keychain-p256-v1",JZ=1,T0=`ARA-DEVICE-BINDING-V1
|
|
2
|
+
import{ph as c}from"./vm-hands-entry-lite-kbz9zfha.js";var g={REASON_API_KEY:"ARA_API_KEY",REASON_API_URL:"ARA_API_URL",REASON_CLI_CHANNEL:"ARA_CLI_CHANNEL",REASON_CLI_LAUNCHER_PATH:"ARA_CLI_LAUNCHER_PATH",REASON_MANAGED_RUNTIME_ROOT:"ARA_MANAGED_RUNTIME_ROOT",REASON_INSTALL_ALIAS_PATH:"ARA_INSTALL_ALIAS_PATH",REASON_INSTALL_DIR:"ARA_INSTALL_DIR",REASON_INSTALL_METHOD:"ARA_INSTALL_METHOD",REASON_INSTALL_PINNED_VERSION:"ARA_INSTALL_PINNED_VERSION",REASON_INSTALL_UPGRADE:"ARA_INSTALL_UPGRADE"},g0=Object.values(g),jZ=new Set;function MQ(Q,Z){let $=Q[Z];if($?.trim())return $;let X=Q[g[Z]];if(X?.trim())jZ.add(g[Z]);return X}function KZ(Q,Z){return{[Q]:Z,[g[Q]]:Z}}import{basename as BZ}from"path";var i=["production","staging"],OZ="https://api.reasonmachines.com",kZ="https://staging-api.reasonmachines.com";var l={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},AZ=new Set(["ara-staging","reason-staging"]);function KQ(Q={}){let Z=MQ(Q.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(Z){if(i.includes(Z))return Z;throw Error(`Unknown Reason CLI channel: ${Z}`)}let $=BZ(Q.executablePath??process.execPath).toLowerCase();return AZ.has($)?"staging":"production"}function h(Q){return Q==="staging"?kZ:OZ}function y0(Q){return`${h(Q)}/mcp/ara`}var BQ={production:["https://api.ara.so",l.production.api],staging:["https://api-staging.ara.so",l.staging.api]};function jQ(Q){let Z;try{Z=new URL(Q).origin}catch{return Q}let $=i.find((X)=>BQ[X].includes(Z));return $?h($):Z}function p0(Q,Z){return Q===Z||jQ(Q)===jQ(Z)}function OQ(Q,Z){return i.some(($)=>BQ[$].includes(Q)&&Z===h($))}function u0(Q,Z){try{let $=new URL(Z);return!$.username&&!$.password&&($.origin===h(Q)||$.origin===l[Q].api)}catch{return!1}}function d0(Q){try{let Z=new URL(Q).hostname.replace(/^\[|\]$/g,"").toLowerCase();return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}import{randomBytes as xQ}from"crypto";import{chmodSync as LQ,closeSync as FQ,constants as _Z,linkSync as bQ,lstatSync as x,mkdirSync as fQ,openSync as NZ,readdirSync as P,readFileSync as TQ,readlinkSync as D,renameSync as N,rmdirSync as CQ,symlinkSync as _,unlinkSync as B}from"fs";import{createRequire as xZ}from"module";import{constants as LZ}from"os";import{basename as f,join as U,sep as bZ}from"path";import{existsSync as m,lstatSync as AQ,readdirSync as PZ,readFileSync as FZ,readlinkSync as TZ,realpathSync as DZ}from"fs";import{join as K,sep as RZ}from"path";function o(Q,...Z){let $=K(Q,"ara"),X=K(Q,"reason");if(!v($))return K(X,...Z);if(!m(X))return K($,...Z);return m(K($,...Z))&&!m(K(X,...Z))?K($,...Z):K(X,...Z)}function v(Q){try{let Z=AQ(Q);if(!Z.isSymbolicLink())return Z.isDirectory();return TZ(Q)!=="reason"&&m(Q)}catch{return!1}}function PQ(Q,Z=[]){if(!v(Q))return!1;let $;try{$=[Q,...PZ(Q,{withFileTypes:!0}).filter((X)=>X.isDirectory()).map((X)=>K(Q,X.name))]}catch{return!1}return $.some((X)=>["connect","connect-once"].filter((z)=>!Z.includes(K(X,z))).some((z)=>{let W=K(X,z,"worker.json");try{AQ(W)}catch{return!1}try{let q=JSON.parse(FZ(W,"utf8"))?.stateDirectory;if(typeof q!=="string")return!0;let V=(J,w)=>J===w||J.startsWith(w+RZ);return V(q,Q)||V(kQ(q),kQ(Q))}catch{return!0}}))}function kQ(Q){try{return DZ(Q)}catch{return Q}}var u=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"]),n=new Set(["local-device.proxy.json"]),fZ=new Set(["local-device.key","local-device.binding"]),DQ=new Map;function r(Q,Z,$){let X=U(Q,"ara");if(/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(Q))return{state:G(X)?.isDirectory()?"kept":"absent"};return EQ(X,U(Q,"reason"),{linkAlways:!0,kept:(z)=>PQ(z,$??[]),native:Z===void 0?pQ:()=>Z},$!==void 0)}function SQ(Q,...Z){return r(Q),o(Q,...Z)}function z1(Q,Z=process.platform){let $=U(Q,"Library","Logs");if(Z==="darwin")for(let X of[""," Staging"," Development"])EQ(U($,`Ara${X}`),U($,`Reason${X}`),{linkAlways:!1,kept:()=>!1,native:pQ});return U($,"Reason")}var IQ="config_rename_unavailable:busy";function EQ(Q,Z,$,X=!1){let z=X?void 0:DQ.get(Q);if(z)return z;let W;try{W=CZ(Q,Z,$)}catch(q){let V=`config_rename_unavailable:${A(q)??"failed"}`;try{return{state:G(Q)?.isDirectory()?"kept":"absent",problem:V}}catch{return{state:"kept",problem:V}}}if(!(W.state==="absent"&&$.linkAlways)&&W.problem!==IQ&&!(W.state==="kept"&&!W.problem))DQ.set(Q,W);return W}function CZ(Q,Z,$){IZ(Z,$.native);let X=!1;for(let z=0;z<8;z+=1){let W=G(Q);if(W?.isSymbolicLink())return D(Q)===f(Z)?{state:X?"renamed":"linked"}:{state:"kept"};if(!W){if(p(Z))M(()=>B(Z),"ENOENT");if(!(X||$.linkAlways)||!R(Z))return{state:"absent"};let J=b(Z,"link");_(f(Z),J);try{M(()=>N(J,Q),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{M(()=>B(J),"ENOENT")}continue}if(!W.isDirectory())return{state:"absent"};if($.kept(Q))return RQ(Z),{state:"kept"};let q=$.native();if(!q)return RQ(Z),{state:"kept",problem:"config_rename_unavailable:no_native"};let V=EZ(q,Q);if(!V)return{state:"kept",problem:IQ};try{if(x(Q).isSymbolicLink())continue;let J=SZ(q,Q,Z);if(J)return{state:"kept",problem:J};X=!0}finally{V()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function SZ(Q,Z,$){let X=G($);if(!X||p($)){if(!X)_(f($),$);try{Q.exchange(Z,$)}catch(J){if(p($))M(()=>B($),"ENOENT");return`config_rename_unavailable:${A(J)??"exchange_failed"}`}return null}if(!X.isDirectory())return"config_rename_unavailable:ENOTDIR";if(X.dev!==x(Z).dev)return"config_rename_unavailable:EXDEV";let z=[b($,"probe"),b($,"probe")];try{_("a",z[0]),_("b",z[1]),Q.exchange(z[0],z[1])}catch(J){return`config_rename_unavailable:${A(J)??"exchange_failed"}`}finally{for(let J of z)M(()=>B(J),"ENOENT")}let W=yQ($);for(let J of fZ){let w=G(U($,J)),j=G(U(Z,J));if(w&&j&&w.ino!==j.ino)fQ(`${W}-replaced`,{mode:448,recursive:!0}),N(U($,J),U(`${W}-replaced`,J))}let q={linked:new Map,unitsKept:new Set};gQ(Z,$,"",q);let V=b($,"rename");_(f($),V);try{Q.exchange(Z,V)}catch(J){return M(()=>B(V),"ENOENT"),`config_rename_unavailable:${A(J)??"exchange_failed"}`}return hQ(V,$,q,W),null}function t(Q){return Q===""||!Q.includes(bZ)}function gQ(Q,Z,$,X){let z=t($)&&y(U(Z,$),U(Q,$));if(z)X.unitsKept.add($);for(let W of P(U(Q,$))){if(z&&(u.has(W)||n.has(W)))continue;let q=U($,W),V=U(Q,q),J=U(Z,q),w=G(V);if(!w)continue;let j=G(J);if(w.isDirectory()){if(!j)M(()=>fQ(J,{mode:w.mode&4095}),"EEXIST"),LQ(J,w.mode&4095);if(R(J))gQ(Q,Z,q,X)}else if(!j){if(w.isSymbolicLink())M(()=>_(D(V),J),"EEXIST");else if(M(()=>bQ(V,J),"EEXIST","ENOENT"))X.linked.set(q,w.ino)}}}function IZ(Q,Z){let $;try{if(!R(Q))return;$=P(Q)}catch{return}for(let X of $){let z=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(X);if(!z)continue;let W=U(Q,X),q=G(W);if(!q)continue;if(!q.isDirectory()){if(!_Q(Number(z[2])))M(()=>B(W),"ENOENT");continue}let V=Z(),J=null;if(V){try{J=V.lock(W)}catch{continue}if(!J)continue}else if(_Q(Number(z[2])))continue;try{let w=b(Q,"claim");if(M(()=>N(W,w),"ENOENT"))hQ(w,Q,null,yQ(Q))}finally{J?.()}}}function hQ(Q,Z,$,X){for(let[z,W]of $?.linked??[])if(!G(U(Q,z))&&G(U(Z,z))?.ino===W)M(()=>B(U(Z,z)),"ENOENT");if(mQ(Q,Z,"",$),M(()=>CQ(Q),"ENOTEMPTY","EEXIST"))return;N(Q,X),LQ(X,448)}function mQ(Q,Z,$,X){let z=t($)&&(X?X.unitsKept.has($):y(U(Z,$),U(Q,$)));for(let W of P(U(Q,$))){let q=U($,W),V=U(Q,q),J=U(Z,q),w=x(V),j=G(J);if(j&&w.ino===j.ino&&w.dev===j.dev){B(V);continue}if(w.isFile()&&j?.isFile()&&X?.linked.get(q)===j.ino){N(V,J);continue}if(z&&(u.has(W)||n.has(W)))continue;if(!j){if(w.isFile()){if(M(()=>bQ(V,J),"EEXIST"))B(V)}else M(()=>N(V,J),"EEXIST","ENOTEMPTY");continue}if(w.isDirectory()&&j.isDirectory())mQ(Q,Z,q,X),M(()=>CQ(V),"ENOTEMPTY","EEXIST")}}function W1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=["",...P(Z,{withFileTypes:!0}).filter((z)=>z.isDirectory()&&!z.name.startsWith(".")).map((z)=>z.name)];for(let z of X){let W=U(Z,z),q=U($,z);if(!y(W,q)||!y(q,W))continue;if([...u,...n].some((J)=>a(U(W,J),U(q,J))===!1))return z}return null}function q1(Q){let Z=U(Q,"ara"),$=U(Q,"reason");if(!R(Z)||!R($))return null;let X=(z)=>{for(let W of P(U(Z,z))){let q=U(z,W);if(t(z)&&(W==="connect"||W==="connect-once"))continue;let V=x(U(Z,q)),J=G(U($,q));if(!J||V.ino===J.ino&&V.dev===J.dev)continue;if(V.isDirectory()&&J.isDirectory()&&!J.isSymbolicLink()){let w=X(q);if(w!==null)return w}else if(V.isSymbolicLink()||J.isSymbolicLink()){if(!(V.isSymbolicLink()&&J.isSymbolicLink()&&D(U(Z,q))===D(U($,q))))return q}else if(a(U(Z,q),U($,q))!==!0)return q}return null};return X("")}function a(Q,Z){let $=G(Q),X=G(Z);if(!$&&!X)return null;if(!$||!X||$.isDirectory()!==X.isDirectory())return!1;if($.ino===X.ino&&$.dev===X.dev)return!0;if($.isDirectory())return[...new Set([...P(Q),...P(Z)])].every((W)=>a(U(Q,W),U(Z,W))===!0);try{return TQ(Q).equals(TQ(Z))}catch{return!1}}function y(Q,Z){for(let $ of u)if(vQ(U(Q,$),U(Z,$)))return!0;return!1}function vQ(Q,Z){let $=G(Q);if(!$)return!1;let X=G(Z);if(!X)return!0;if($.isDirectory()){if(!X.isDirectory())return!0;return P(Q).some((z)=>vQ(U(Q,z),U(Z,z)))}if($.isSymbolicLink())return!X.isSymbolicLink()||D(Q)!==D(Z);return $.ino!==X.ino||$.dev!==X.dev}function RQ(Q){if(p(Q))M(()=>B(Q),"ENOENT")}function yQ(Q){return U(Q,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${xQ(3).toString("hex")}`)}function p(Q){try{return x(Q).isSymbolicLink()&&D(Q)===f(Q)}catch{return!1}}function R(Q){let Z=G(Q);return Z!==null&&Z.isDirectory()}function EZ(Q,Z){for(let $=0;$<40;$+=1){let X=Q.lock(Z);if(X)return X;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function b(Q,Z){return U(Q,`.${Z}-${process.pid}-${xQ(6).toString("hex")}`)}function _Q(Q){if(Q===process.pid)return!1;try{return process.kill(Q,0),!0}catch(Z){return A(Z)==="EPERM"}}function G(Q){try{return x(Q)}catch(Z){if(A(Z)==="ENOENT"||A(Z)==="ENOTDIR")return null;throw Z}}function M(Q,...Z){try{return Q(),!0}catch($){if(Z.includes(A($)??""))return!1;throw $}}function A(Q){return Q instanceof Error&&"code"in Q&&typeof Q.code==="string"?Q.code:void 0}var L,gZ=2,hZ=4,mZ=2,vZ=2,NQ=-100;function pQ(){if(L!==void 0)return L;if(L=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let Q;try{Q=xZ(import.meta.url)("bun:ffi")}catch{return null}let Z=process.platform==="darwin",$=Z?"__error":"__errno_location",X=Z?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:z}=Q;for(let W of X)try{let q=Z?"renamex_np":"renameat2",J=Q.dlopen(W,{flock:{args:[z.i32,z.i32],returns:z.i32},[$]:{args:[],returns:z.ptr},[q]:Z?{args:[z.ptr,z.ptr,z.u32],returns:z.i32}:{args:[z.i32,z.ptr,z.i32,z.ptr,z.u32],returns:z.i32}}).symbols,w=J[$]();if(w===null)continue;let j=(T)=>{let k=Q.read.i32(w),O=Object.entries(LZ.errno).find(([,E])=>E===k)?.[0]??`errno_${k}`;return Object.assign(Error(`${T} failed: ${O}`),{code:O})},HQ=(T)=>Buffer.from(`${T}\x00`,"utf8");return L={exchange(T,k){let O=HQ(T),E=HQ(k);if((Z?J[q](Q.ptr(O),Q.ptr(E),mZ):J[q](NQ,Q.ptr(O),NQ,Q.ptr(E),vZ))!==0)throw j("exchange")},lock(T){let k=NZ(T,_Z.O_RDONLY);if(J.flock(k,gZ|hZ)===0)return()=>FQ(k);let O=j("lock");if(FQ(k),O.code==="EWOULDBLOCK"||O.code==="EAGAIN")return null;throw O}},L}catch{}return null}import{createHmac as V0,createPublicKey as w0,randomBytes as G0,randomUUID as zZ,verify as H0}from"crypto";import{chmodSync as qQ,existsSync as WZ,mkdirSync as M0,readFileSync as j0,realpathSync as K0,renameSync as B0,statSync as O0,unlinkSync as k0,writeFileSync as A0}from"fs";import{basename as P0,dirname as YQ,isAbsolute as qZ,join as s,resolve as F0}from"path";var Y1=[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 yZ="REASON_DESKTOP_RUNTIME",pZ="REASON_DESKTOP_RUNTIME_CHANNEL",uZ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",dZ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",M1={[yZ]:"ARA_DESKTOP_RUNTIME",[pZ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[uZ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[dZ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function uQ(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as QQ,existsSync as F,mkdirSync as ZQ,readFileSync as lQ,realpathSync as lZ,renameSync as iZ,unlinkSync as $Q,writeFileSync as XQ}from"fs";import{createPrivateKey as oZ,createPublicKey as nZ,generateKeyPairSync as rZ,randomUUID as tZ,sign as aZ}from"crypto";import{createRequire as eZ}from"module";import{homedir as Q0,platform as rQ}from"os";import{dirname as Z0,join as C}from"path";import{existsSync as sZ}from"fs";import{join as cQ}from"path";var e="libara_device_keychain.dylib",dQ="libreason_device_keychain.dylib";class cZ extends Error{code;constructor(Q,Z){super(Z);this.code=Q;this.name="ManagedRuntimeError"}}function sQ(Q){let Z=cQ(Q,dQ);return sZ(Z)?Z:cQ(Q,e)}var iQ=1,$0=16384,S=65536,X0=128,z0=128,tQ=65536;class Y 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 aQ(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 zQ=null;function eQ(){if(!zQ)try{zQ=eZ(import.meta.url)("bun:ffi")}catch{throw new Y("native_boundary_unavailable")}return zQ}function W0(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 q0(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new Y("invalid_credential_record");let Z=Q,$=W0(Z.apiOrigin);if(Z.version!==iQ||!$||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 Y("invalid_credential_record");return{version:iQ,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function J0(Q=process.execPath){let Z=Q;try{Z=lZ(Q)}catch{}return sQ(Z0(Z))}function H(Q){return eQ().ptr(Q)}function Y0(Q){if(!F(Q))throw new Y("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=eQ();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(X){if(X instanceof Y)throw X;throw new Y("native_boundary_unavailable")}}function oQ(Q){return Buffer.from(Q).toString("base64url")}function I(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 QZ(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 ZZ{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=J0(),Z=rQ(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;uQ($)}symbols(){if(this.runtimePlatform!=="darwin")throw new Y("unsupported_platform");this.library??=Y0(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(H(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new Y("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(X0),$=new BigUint64Array(1),X=Q==="load"?this.symbols().ara_device_key_load_public(H(Z),BigInt(Z.byteLength),H($)):this.symbols().ara_device_key_create_fresh_public(H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z!==65)throw new Y("invalid_public_key");let W=oQ(Z.subarray(0,z));if(!I(W))throw new Y("invalid_public_key");return W}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=new Uint8Array(z0),$=new BigUint64Array(1),X=this.symbols().ara_device_key_sign(H(Q),BigInt(Q.byteLength),H(Z),BigInt(Z.byteLength),H($));if(X!==0)throw new Y("proof_sign_failed",X);let z=Number($[0]);if(!Number.isSafeInteger(z)||z<1||z>Z.byteLength)throw new Y("invalid_signature");let W=Z.subarray(0,z);if(!QZ(W))throw new Y("invalid_signature");return oQ(W)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(H(Q));if(Z!==0||Q[0]!==1)throw new Y("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(H(Q));if(Z!==0)throw new Y("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(S),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("binding_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_binding");return Q.slice(0,X)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_create(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");let Z=this.symbols().ara_device_binding_update(H(Q),BigInt(Q.byteLength));if(Z!==0)throw new Y("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(H(Q));if(Z!==0)throw new Y("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array($0),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(H(Q),BigInt(Q.byteLength),H(Z));if($===1)return null;if($!==0)throw new Y("legacy_credential_read_failed",$);let X=Number(Z[0]);if(!Number.isSafeInteger(X)||X<1||X>Q.byteLength)throw new Y("invalid_credential_record");try{let z=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,X));return q0(JSON.parse(z))}catch(z){if(z instanceof Y)throw z;throw new Y("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(H(Q));if(Z!==0)throw new Y("legacy_credential_delete_failed",Z);return Q[0]===1}}function nQ(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new Y("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),X=Buffer.from(Z.y,"base64url");if($.byteLength!==32||X.byteLength!==32)throw new Y("invalid_public_key");let z=Buffer.concat([Buffer.of(4),$,X]).toString("base64url");if(!I(z))throw new Y("invalid_public_key");return z}function U0(){let Q=process.env.XDG_CONFIG_HOME?.trim()||C(Q0(),".config");r(Q);let Z=C(Q,"ara");return v(Z)?Z:C(Q,"reason")}class $Z{directory;constructor(Q=U0()){this.directory=Q}keyPath(){return C(this.directory,"local-device.key")}bindingPath(){return C(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!F(Q))throw new Y("proof_key_read_failed");try{let Z=lQ(Q,"utf8");return oZ({key:Z,format:"pem"})}catch{throw new Y("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=nZ(Q);return nQ(Z)}createFreshPublicKey(){ZQ(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=rZ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),X=this.keyPath();return XQ(X,$,{mode:384}),QQ(X,384),nQ(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>tQ)throw new Y("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=aZ("sha256",Q,Z)}catch{throw new Y("proof_sign_failed")}if(!QZ($))throw new Y("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!F(Q))return!1;return $Q(Q),!0}loadBinding(){let Q=this.bindingPath();if(!F(Q))return null;try{return new Uint8Array(lQ(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(F(Z))throw new Y("binding_create_failed");XQ(Z,Q,{mode:384}),QQ(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>S)throw new Y("invalid_binding");ZQ(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!F(Z))throw new Y("binding_update_failed");let $=`${Z}.${tZ()}`;try{XQ($,Q,{mode:384,flag:"wx"}),QQ($,384),iZ($,Z)}finally{if(F($))$Q($)}}deleteBinding(){let Q=this.bindingPath();if(!F(Q))return!1;return $Q(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function WQ(){return rQ()==="darwin"?new ZZ:new $Z}var UQ=4;var d="macos-keychain-p256-v1",JZ=1,T0=`ARA-DEVICE-BINDING-V1
|
|
3
3
|
`;function D0(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function YZ(Q={},Z=c()){let $=KQ({env:{...process.env,...Q}}),X=Q.XDG_CONFIG_HOME?.trim()||s(Z,".config");return SQ(X,...$==="staging"?["staging"]:[])}function VQ(Q={},Z=c()){return s(YZ(Q,Z),"local-device.json")}function UZ(Q={},Z=c()){return s(YZ(Q,Z),"local-daemon.json")}function wQ(Q,Z){M0(YQ(Q),{recursive:!0,mode:448}),qQ(YQ(Q),448);let $=`${Q}.${process.pid}.${zZ()}.tmp`;try{A0($,`${JSON.stringify(Z,null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),qQ($,384),B0($,Q),qQ(Q,384)}finally{if(WZ($))k0($)}return Q}function GQ(Q){if(!WZ(Q))return null;try{return JSON.parse(j0(Q,"utf8"))}catch{return null}}function JQ(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function R0(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let X=$;if(typeof X.id!=="string"||typeof X.label!=="string"||typeof X.path!=="string"||typeof X.pathFingerprint!=="string"||!X.permissions||typeof X.permissions.read!=="boolean"||typeof X.permissions.write!=="boolean"||typeof X.permissions.execute!=="boolean"||typeof X.permissions.discover_environment!=="boolean"||typeof X.permissions.expose_mcp!=="boolean")return null;Z.push({id:X.id,label:X.label,path:X.path,pathFingerprint:X.pathFingerprint,permissions:X.permissions})}return Z}function VZ(Q,Z,$=[]){let X=Object.keys(Q);return Z.every((z)=>Object.hasOwn(Q,z))&&X.every((z)=>Z.includes(z)||$.includes(z))}function _0(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 wZ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=R0(Z.roots),X=_0(Z.apiOrigin);if(!X||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!D0(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:X,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 N0(Q){return{...Q,credentialStorage:d}}function x0(Q){return{version:UQ,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:d}}function GZ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!VZ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=wZ(Z);if(!$||Z.version!==UQ||Z.credentialStorage!==d||!I(Z.devicePublicKey))return null;return{version:UQ,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:d}}function HZ(Q){return new TextEncoder().encode(`${T0}${JSON.stringify(x0(Q))}`)}function L0(Q){let Z=Buffer.from(Q,"base64url");return w0({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function b0(Q,Z){let $={version:JZ,state:Q,signature:Z.sign(HZ(Q))};return new TextEncoder().encode(JSON.stringify($))}function MZ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new Y("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new Y("invalid_binding");let $=Z;if(!VZ($,["version","state","signature"])||$.version!==JZ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new Y("invalid_binding");let X=GZ($.state);if(!X)throw new Y("invalid_binding");let z=!1;try{z=H0("sha256",HZ(X),L0(X.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{z=!1}if(!z)throw new Y("invalid_binding");return X}function f0(Q){let{credentialStorage:Z,...$}=Q;return $}function C0(Q){return Q instanceof Y?aQ(Q):"credential_boundary_failed"}function v1(Q=VQ(),Z={}){let $=GQ(Q),X=Z.proofStore??Z.credentialStore??WQ(),z=X.loadBinding();if(!z){if($&&typeof $==="object"&&!Array.isArray($)&&S0($))return null;if($!==null)throw new Y("invalid_binding");return null}let W=MZ(z),q=X.loadPublicKey();if(X.privateKeyIsNonExtractable(),q!==W.devicePublicKey)throw new Y("invalid_public_key");let V=GZ($);if(Z.repair!==!1&&(!V||JSON.stringify(V)!==JSON.stringify(W)))wQ(Q,W);return f0(W)}function S0(Q){let Z=Q,$=wZ(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 y1(Q,Z=VQ(),$={}){let X=$.proofStore??$.credentialStore??WQ();JQ($,"credential.store_started");try{if(!I(Q.devicePublicKey)||X.loadPublicKey()!==Q.devicePublicKey)throw new Y("invalid_public_key");X.privateKeyIsNonExtractable();let z=N0(Q),W=X.loadBinding();if(W){let V=MZ(W);if(V.devicePublicKey!==Q.devicePublicKey||V.orgId!==Q.orgId||V.deviceId!==Q.deviceId||V.apiOrigin!==Q.apiOrigin&&!OQ(V.apiOrigin,Q.apiOrigin))throw new Y("invalid_binding")}let q=b0(z,X);if(W)X.updateBinding(q);else X.createBinding(q);return wQ(Z,z),JQ($,"credential.store_completed"),Z}catch(z){throw JQ($,"credential.store_failed",C0(z)),z}}function p1(Q=UZ()){let Z=GQ(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;return $}function u1(Q,Z=UZ()){return wQ(Z,Q)}var XZ=1;function I0(Q=VQ()){return s(YQ(Q),"local-device.proxy.json")}function d1(Q=I0()){let Z=GQ(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==XZ||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!qZ($.caFile)))return null;return{version:XZ,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function c1(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=G0(32)){let X=new Set,z=[];for(let W of Q){let q=K0(qZ(W)?W:F0(W));if(!O0(q).isDirectory())throw Error(`Local execution root is not a directory: ${W}`);if(X.has(q))continue;X.add(q),z.push({id:zZ(),label:P0(q)||q,path:q,pathFingerprint:V0("sha256",$).update(q).digest("hex"),permissions:{...Z}})}if(z.length===0)throw Error("At least one explicit local execution root is required.");return z}
|
|
5
|
-
export{MQ as
|
|
5
|
+
export{MQ as Ef,KZ as Ff,i as Gf,KQ as Hf,h as If,y0 as Jf,jQ as Kf,p0 as Lf,OQ as Mf,u0 as Nf,d0 as Of,r as Pf,SQ as Qf,z1 as Rf,W1 as Sf,q1 as Tf,pQ as Uf,cZ as Vf,Y as Wf,J0 as Xf,I as Yf,QZ as Zf,ZZ as _f,$Z as $f,VQ as ag,UZ as bg,v1 as cg,y1 as dg,p1 as eg,u1 as fg,XZ as gg,d1 as hg,c1 as ig};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{hg as m}from"./vm-hands-entry-lite-sggk0bqc.js";import{qg as w}from"./vm-hands-entry-lite-8afzattm.js";import{qh as h}from"./vm-hands-entry-lite-kbz9zfha.js";import{Dh as x}from"./vm-hands-entry-lite-n5ec0fjy.js";import{Wh as Q}from"./vm-hands-entry-lite-40t7d4p5.js";import{existsSync as B,realpathSync as k,statSync as s}from"fs";import{platform as p}from"os";import{isAbsolute as y,sep as d}from"path";var r=43200000,A=w,l=4,u=/^[A-Za-z0-9._:-]{1,160}$/,a=1000;function v(z){return Boolean(z)&&typeof z==="object"&&!Array.isArray(z)}function q(z,H){if(typeof z!=="number"||!Number.isFinite(z)||z<=0)return H;return Math.min(a,Math.max(1,Math.floor(z)))}function n(z,H=Date.now()){let V=["relay_url","session_id","expires_at"],J=new Set([...V,"cols","rows","cwd","workspace"]);if(!v(z)||V.some((L)=>!(L in z))||Object.keys(z).some((L)=>!J.has(L)))throw new Q("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:j,session_id:Y,expires_at:C}=z;if(typeof j!=="string")throw new Q("invalid_pty_request","Reason terminal relay URL is missing.");let D;try{D=new URL(j)}catch{throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.")}if(D.protocol!=="wss:"&&D.protocol!=="ws:"||D.username||D.password)throw new Q("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof Y!=="string"||!u.test(Y))throw new Q("invalid_pty_request","Reason terminal session identity is invalid.");let R=typeof C==="string"?Date.parse(C):Number.NaN;if(!Number.isFinite(R)||R<=H)throw new Q("invalid_pty_request","Reason terminal session has already expired.");if(z.cwd!==void 0&&typeof z.cwd!=="string")throw new Q("invalid_pty_request","Reason terminal working directory is invalid.");let Z=z.workspace===void 0?void 0:x(z.workspace);if(Z===null||Z&&z.cwd!==void 0)throw new Q("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:j,session_id:Y,expires_at:new Date(Math.min(R,H+r)).toISOString(),cols:q(z.cols,80),rows:q(z.rows,24),...z.cwd===void 0?{}:{cwd:z.cwd},...Z?{workspace:Z}:{}}}function o(z,H){return H===z||H.startsWith(z+d)}function U(z,H){if(H===void 0)return z;if(!y(H))throw new Q("pty_cwd_invalid","Reason terminal working directory must be absolute.");let V;try{V=k(H)}catch{throw new Q("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!o(z,V))throw new Q("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!s(V).isDirectory())throw new Q("pty_cwd_invalid","Reason terminal working directory is not a directory.");return V}function t(z=process.env){let H=z.SHELL;if(H&&y(H)&&B(H))return H;for(let V of p()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(B(V))return V;return"/bin/sh"}function e(){let z=globalThis.Bun;if(!z)throw new Q("pty_unavailable","Reason terminals require the Bun runtime.");return z.spawn}function Dz(){return typeof globalThis.Bun<"u"}var zz=(z)=>{let H=e()({cmd:[z.shell,"-i","-l"],cwd:z.cwd,env:{...z.environment,TERM:"xterm-256color"},terminal:{cols:z.cols,rows:z.rows,data:(J,j)=>{z.onData(j)}}}),V=H.terminal;if(!V){try{H.kill()}catch{}throw new Q("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(J)=>V.write(J),resize:(J,j)=>V.resize(J,j),kill:()=>{try{H.kill()}catch{}},exited:H.exited.then((J)=>typeof J==="number"?J:null,()=>null)}},Hz=(z,H)=>{return H===void 0?new WebSocket(z):new WebSocket(z,{proxy:H})},S=new Set;function Jz(z){if(S.size>=l||S.has(z))return null;S.add(z);let H=!1;return()=>{if(H)return;H=!0,S.delete(z)}}async function Kz(z,H={}){let V=H.now??Date.now,J=n(z.payload,V()),j=Jz(z.operationId);if(!j)throw new Q("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let Y=V(),C,D,R;try{let Z=J.workspace?h(z.root,J.workspace):void 0;C=Z?U(B(Z.boundary)?k(Z.boundary):Z.boundary,Z.path):U(z.root,J.cwd),D=H.environment??process.env,R=H.shellPath??t(D)}catch(Z){throw j(),Z}return await new Promise((Z,L)=>{let X=null,W=null,M=!1,f=!1,K=!1,T=null,_=0,b=0,O=[],P=0,g=null,$=(N)=>{if(K)return;if(K=!0,g)clearTimeout(g);z.signal.removeEventListener("abort",I);try{X?.kill()}catch{}try{W?.close(1000,"pty_session_over")}catch{}if(j(),N.kind==="rejected"){L(N.error);return}let G={reason:N.reason,exit_code:T,output_bytes:_,input_bytes:b,duration_ms:Math.max(0,V()-Y)};z.emitEvent("pty.stopped",{...G}).catch(()=>{return}),Z({...G})},I=()=>{let N=z.signal.reason;$({kind:"rejected",error:N instanceof Q?N:new Q("cancelled","Reason closed the terminal session.")})};if(z.signal.aborted){I();return}z.signal.addEventListener("abort",I,{once:!0}),g=setTimeout(()=>$({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(J.expires_at)-V()));let i=(N)=>{if(_+=N.byteLength,!M||!W){if(O.push(N),P+=N.byteLength,P>A)$({kind:"resolved",reason:"output_backpressure"});return}try{W.send(N)}catch{$({kind:"resolved",reason:"relay_closed"});return}if(W.bufferedAmount>A)$({kind:"resolved",reason:"output_backpressure"})};try{X=(H.spawnPty??zz)({shell:R,args:["-i","-l"],cwd:C,cols:J.cols,rows:J.rows,environment:D,onData:(N)=>{if(!K)i(N)}})}catch(N){$({kind:"rejected",error:N instanceof Q?N:new Q("pty_spawn_failed","Reason could not start the terminal shell.")});return}X.exited.then((N)=>{if(K)return;if(T=N,M&&W)try{W.send(JSON.stringify({t:"exit",code:N}))}catch{}$({kind:"resolved",reason:"shell_exited"})});let c=(H.loadProxy??m)()?.url;try{W=(H.connect??Hz)(J.relay_url,c)}catch{$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}W.binaryType="arraybuffer",W.onopen=()=>{if(K||!W)return;M=!0;try{W.send(JSON.stringify({t:"open",cols:J.cols,rows:J.rows}));for(let N of O.splice(0))W.send(N);P=0}catch{$({kind:"resolved",reason:"relay_closed"});return}f=!0,z.emitEvent("pty.ready",{session_id:J.session_id,cols:J.cols,rows:J.rows}).catch(()=>{return})},W.onmessage=(N)=>{if(K||!X)return;let G=N.data;if(typeof G==="string"){let F;try{F=JSON.parse(G)}catch{return}if(!v(F))return;if(F.t==="resize"){try{X.resize(q(F.cols,J.cols),q(F.rows,J.rows))}catch{}return}if(F.t==="close")$({kind:"resolved",reason:"client_closed"});return}let E=G instanceof ArrayBuffer?new Uint8Array(G):ArrayBuffer.isView(G)?new Uint8Array(G.buffer,G.byteOffset,G.byteLength):null;if(!E||E.byteLength===0)return;b+=E.byteLength;try{X.write(E)}catch{}},W.onclose=()=>{if(K)return;if(!f){$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}$({kind:"resolved",reason:"relay_closed"})},W.onerror=()=>{if(K||f)return;$({kind:"rejected",error:new Q("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
|
|
3
|
+
export{r as uf,A as vf,l as wf,n as xf,U as yf,t as zf,Dz as Af,zz as Bf,Hz as Cf,Kz as Df};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{t as d0}from"./vm-hands-entry-lite-
|
|
2
|
+
import{t as d0}from"./vm-hands-entry-lite-pbnx8z9g.js";import{B as l6,C as p6,D as G5,E as B5,F as R7,G as C7,H as v3,I as i5,J as H5,K as _0,L as l$,M as p$,N as S0,O as J2,P as n5,Q as n0,R as M6,S as Z3,T as Z6,X as Q6,ea as x7,fa as E7,ga as S7,ha as w7,ia as u3}from"./vm-hands-entry-lite-nwcza0v8.js";import{$a as K2,Ba as y5,Ca as f5,Da as K5,Ea as V5,Fa as L7,Ga as D7,Ia as u,Ja as e,Ka as s,La as c,Ma as W5,Na as z7,Oa as W$,Ra as V4,Sa as H4,Ta as CJ,Ua as PJ,Va as IJ,Wa as y0,Xa as J0,Ya as g,Za as g3,_a as E$,ab as U0,bb as O7,gb as U6,ib as h8,ka as r7,lb as u2,na as z5,nb as a5,oa as O5,ob as T3,qb as h5,ra as F5,ta as E5,ub as A7,vb as N3,wa as S5}from"./vm-hands-entry-lite-xjyd9xvx.js";import{Db as w5,Eb as b5,Lb as k5}from"./vm-hands-entry-lite-nj8bmc9y.js";import{Qb as N5}from"./vm-hands-entry-lite-rd9vsaew.js";import{Xb as s5}from"./vm-hands-entry-lite-n8gsyjq7.js";import{pc as Y5}from"./vm-hands-entry-lite-abrbc7gf.js";import{Ac as D$,Bc as wJ,Cc as e3,Dc as bJ,Ec as Y4,Fc as F1,Gc as E8,Hc as G4,Lc as t5,Oc as P7,Rc as c6,Sc as s6,tc as i1,uc as G1,vc as I1,wc as L$,xc as HJ,yc as EJ,zc as SJ}from"./vm-hands-entry-lite-0p3hac9d.js";import{Id as X5,Od as $$,Yd as F2,ad as b2,ed as F7,fd as W7}from"./vm-hands-entry-lite-rnwjp0tk.js";import{he as G}from"./vm-hands-entry-lite-669hk342.js";import{ke as xJ,le as o2,oe as I7,re as n$,te as tJ,ue as oJ,ze as J6}from"./vm-hands-entry-lite-xbe3dat0.js";import{Ee as LJ,He as r5,Ie as h3,Ke as U5}from"./vm-hands-entry-lite-henbtxfe.js";import{Xe as r}from"./vm-hands-entry-lite-18kr0x4w.js";import{$f as R4,Ef as k0,Ff as k$,Hf as x0,If as j4,Kf as e0,Lf as z0,Mf as y9,Nf as AJ,Of as RJ,Pf as E2,Qf as q2,Rf as f3,Sf as I8,Tf as x8,Uf as Y$,Vf as v$,Wf as G0,Xf as T2,Yf as y7,Zf as f7,_f as e1,bg as Q3,cg as h1,dg as v0,eg as y$,fg as X3,ig as m1}from"./vm-hands-entry-lite-sggk0bqc.js";import{mg as x5}from"./vm-hands-entry-lite-8afzattm.js";import{mh as Z2,nh as c5}from"./vm-hands-entry-lite-djy0ww6h.js";import{ph as V0,rh as V7}from"./vm-hands-entry-lite-kbz9zfha.js";import{Rh as j7}from"./vm-hands-entry-lite-dyqeaqzb.js";import{Wh as g0}from"./vm-hands-entry-lite-40t7d4p5.js";import{spawn as kJ,spawnSync as $V}from"child_process";import{closeSync as yJ,mkdirSync as JV,openSync as fJ,readdirSync as ZV,realpathSync as B1,rmSync as z$}from"fs";import{hostname as QV}from"os";import{dirname as $9,join as F0,resolve as XV}from"path";var $Z=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function U9($){let J=typeof $==="string"?$Z.exec($):null;return J?{major:Number(J[1]),minor:Number(J[2])}:null}import{createHash as KZ,randomBytes as z9}from"crypto";import{createInterface as VZ}from"readline";import{randomBytes as JZ}from"crypto";import{chmodSync as M9,existsSync as T9,lstatSync as ZZ,mkdirSync as QZ,readFileSync as _9,renameSync as XZ,unlinkSync as F9,writeFileSync as W9}from"fs";import{homedir as YZ}from"os";import{dirname as GZ,join as q9}from"path";function $1($=process.env,J=YZ()){let Z=$.XDG_CONFIG_HOME?.trim()||q9(J,".config"),X=x0({env:$})==="staging"?["staging"]:[];return q9(q2(Z,...X),"credentials.json")}function L9($,J=$1()){return QZ(GZ(J),{recursive:!0,mode:448}),W9(J,`${JSON.stringify($,null,2)}
|
|
3
3
|
`,{mode:384}),M9(J,384),J}function I$($=$1()){if(!T9($))return null;try{let J=_9($,"utf8"),Z=JSON.parse(J);if(typeof Z.apiOrigin!=="string"||typeof Z.clientId!=="string"||typeof Z.accessToken!=="string"||typeof Z.refreshToken!=="string"||typeof Z.expiresAt!=="string"||typeof Z.orgId!=="string"||!Array.isArray(Z.scopes))return null;let Q=new URL(Z.apiOrigin).origin,X=e0(Q);if(X!==Q)BZ($,J,X);return{apiOrigin:X,clientId:Z.clientId,accessToken:Z.accessToken,refreshToken:Z.refreshToken,expiresAt:Z.expiresAt,scopes:Z.scopes.filter((Y)=>typeof Y==="string"),orgId:Z.orgId}}catch{return null}}function BZ($,J,Z){let Q=`${$}.${process.pid}.${JZ(6).toString("hex")}.tmp`;try{let X=ZZ($);if(!X.isFile()||X.uid!==process.geteuid?.())return;let Y=JSON.parse(J);if(W9(Q,`${JSON.stringify({...Y,apiOrigin:Z},null,2)}
|
|
4
4
|
`,{mode:384,flag:"wx"}),M9(Q,384),_9($,"utf8")!==J)throw Error("credentials_changed");XZ(Q,$)}catch{try{F9(Q)}catch{}}}function D9($=$1()){if(!T9($))return!1;return F9($),!0}var j9=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var pV=j9.filter(($)=>$!=="network:read"&&$!=="network:write");class x$ extends Error{oauthCode;constructor($,J=null){super($);this.oauthCode=J;this.name="LoginError"}}function A9(){let $=z9(48).toString("base64url"),J=KZ("sha256").update($).digest("base64url");return{verifier:$,challenge:J,state:z9(32).toString("base64url")}}function HZ($,J){let Z=typeof $.error==="string"?$.error:null,Q=typeof $.error_description==="string"?$.error_description:Z?Z:J;return new x$(Q,Z)}async function NZ($,J,Z,Q){let X=await Z(`${$}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:J,signal:Q}),Y=await X.json().catch(()=>({}));if(!X.ok)throw HZ(Y,`OAuth token request failed (${X.status})`);return Y}var UZ=1e4;async function qZ($,J={}){let Z=J.fetchImpl??fetch,Q=await NZ($.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:$.clientId,refresh_token:$.refreshToken}),Z,AbortSignal.timeout(UZ)).catch((Y)=>{if(Y instanceof Error&&Y.name==="TimeoutError")throw new x$("Reason did not answer the login refresh in time. Check the network and retry.");throw Y});if(typeof Q.access_token!=="string"||typeof Q.refresh_token!=="string"||typeof Q.expires_in!=="number")throw new x$("Reason returned an incomplete refreshed login.");let X={...$,accessToken:Q.access_token,refreshToken:Q.refresh_token,expiresAt:new Date(Date.now()+Q.expires_in*1000).toISOString(),scopes:typeof Q.scope==="string"?Q.scope.split(/\s+/).filter(Boolean):$.scopes};return L9(X,J.path??$1()),X}var M2=new Map;function O9($,J){if(!J)return $;if(J.aborted)return Promise.reject(J.reason);return new Promise((Z,Q)=>{let X=()=>Q(J.reason);J.addEventListener("abort",X,{once:!0}),$.then(Z,Q).finally(()=>J.removeEventListener("abort",X))})}async function k1($={}){let J=$.path??$1(),Z=I$(J);if(!Z)return null;let Q=$.apiOrigin??k0(process.env,"REASON_API_URL")?.trim();if(Q&&!z0(Z.apiOrigin,new URL(Q).origin))return null;let X=Date.parse(Z.expiresAt)<=Date.now()+60000;if(!$.forceRefresh&&!X)return Z;let Y=[J,Z.apiOrigin,Z.clientId,Z.refreshToken].join("\x00"),B=M2.get(Y);if(B)return O9(B,$.signal);let V;return V=qZ(Z,{fetchImpl:$.fetchImpl,path:J}).catch(async(K)=>{if(!(K instanceof x$)||K.oauthCode!=="invalid_grant"&&K.oauthCode!=="invalid_client")throw K;let N=I$(J),q=K.oauthCode==="invalid_client"?N?.clientId!==Z.clientId:N?.refreshToken!==Z.refreshToken;if(N&&q)return k1({fetchImpl:$.fetchImpl,path:J});return D9(J),null}).finally(()=>{if(M2.get(Y)===V)M2.delete(Y)}),M2.set(Y,V),O9(V,$.signal)}function R9($,J){return new Promise((Z)=>{let Q=VZ({input:$}),X=!1,Y=(V)=>{if(X)return;X=!0,J.removeEventListener("abort",B),Q.close(),$.pause(),Z(V)},B=()=>Y(null);J.addEventListener("abort",B,{once:!0}),Q.once("line",(V)=>Y(V)),Q.once("close",()=>Y(null))})}var MZ=G.object({label:G.string(),used_percent:G.number().min(0).max(100).nullable(),resets_at:G.string().nullable(),exhausted:G.boolean().nullable()}),TZ=G.object({groups:G.array(G.object({selectable:G.boolean().optional(),accounts:G.array(G.object({source_id:G.string().min(1),model_ids:G.array(G.string().min(1)).optional()}))}))});function _Z($){let J=TZ.safeParse($);if(!J.success)return;return J.data.groups.some((Z)=>Z.selectable!==!1&&Z.accounts.some((Q)=>Q.model_ids===void 0||Q.model_ids.length>0))}class Y0 extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;constructor($,J,Z,Q,X,Y){super(Z);this.status=$;this.code=J;this.suggestedModel=Q;this.retryAfterMs=X;this.resolutionReason=Y;this.name="ApiError"}static rateLimitDelayMs($,J){if(!($ instanceof Y0)||$.status!==429)return null;return Math.min(60000,Math.max(J,$.retryAfterMs??0))}}var FZ=["minimal","low","medium","high","xhigh","max"],WZ=G.object({id:G.string().min(1),kind:G.string(),name:G.string(),custom_name:G.string().nullish(),status:G.string(),online:G.boolean(),compatible:G.boolean().optional(),compatibility_reason:G.string().nullish(),folder_lane_of:G.string().nullish(),roots:G.array(G.object({id:G.string().min(1),label:G.string()}))}),LZ=G.object({devices:G.array(WZ),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),DZ=G.object({id:G.string().min(1),name:G.string()}),jZ=G.object({items:G.array(DZ)}),zZ=G.object({id:G.string().min(1),name:G.string(),main:G.boolean(),mine:G.boolean(),session_id:G.string().nullish(),appearance:G.object({color:G.string().nullish()}).nullish().catch(null)}),OZ=G.object({items:G.array(zZ)}),AZ=G.object({skill_id:G.string().min(1),name:G.string(),description:G.string().nullish(),activation_keywords:G.array(G.string()).default([]),is_enabled:G.boolean().default(!0)}),RZ=G.object({items:G.array(AZ).default([])}),CZ=G.object({id:G.string().min(1),kind:G.string(),enabled:G.boolean(),schedule:G.object({expression:G.string().nullish(),every_seconds:G.number().nullish(),next_run_at:G.string().nullish()}).nullish(),github:G.object({event:G.string().nullish(),action:G.string().nullish(),repo:G.string().nullish()}).nullish(),last_fired_at:G.string().nullish()}),P9=G.object({id:G.string().min(1),name:G.string().nullish(),instructions:G.string().nullish(),enabled:G.boolean(),triggers:G.array(CZ).default([])}),PZ=G.object({items:G.array(P9).default([]),end_cursor:G.string().nullish(),has_next_page:G.boolean().optional()}),IZ=G.object({id:G.string().min(1),slug:G.string().nullish(),name:G.string(),description:G.string().nullish(),transport:G.string().nullish(),url:G.string().nullish(),enabled:G.boolean()}),xZ=G.object({items:G.array(IZ).default([])}),EZ=G.object({status:G.string(),summary:G.string().nullish(),category:G.string().nullish(),outcome:G.string().nullish(),message_count:G.number().nullish(),pr_url:G.string().nullish(),cost_usd:G.number().nullish(),generated_at:G.string().nullish()}),C9=G.object({tags:G.array(G.string()).default([])}),SZ=G.enum(["linux","macos"]),I9=G.object({id:G.string().min(1),name:G.string().min(1),platform:SZ.nullable(),workers:G.object({total:G.number().int(),online:G.number().int(),busy:G.number().int(),idle:G.number().int()}),sessions:G.object({queued:G.number().int(),running:G.number().int()})}),wZ=G.object({machines:G.array(I9)}),bZ=G.object({machine:I9}),kZ=G.object({deleted:G.literal(!0),revoked_workers:G.number().int(),revoked_tokens:G.number().int()}),yZ=G.object({token:G.object({id:G.string().min(1),machine_id:G.string().min(1),token_prefix:G.string()}),secret:G.string().startsWith("rmt_")}),x9=G.looseObject({machine_id:G.string().min(1),machine_name:G.string().min(1)}),fZ=x9.extend({organization_id:G.string().min(1)}),nV=G.object({id:G.string().min(1),name:G.string().min(1),state:G.enum(["waiting","placed"]),queue_position:G.number().int().nullable()});var rV=G.union([G.object({kind:G.literal("cloud")}),G.object({kind:G.enum(["mac","headless"]),device_id:G.string().min(1),root_id:G.string().min(1)})]);function P0($,J,Z){let Q=$.safeParse(J);if(!Q.success)throw new Y0(502,Z,"Reason returned an unexpected response.");return Q.data}var hZ=G.object({error:G.object({type:G.string(),message:G.string()})});function E9($,J,Z){let Q=hZ.safeParse(J),X=typeof J.error==="string"?J.error:Q.success?Q.data.error.type:`http_${$}`,Y=typeof J.detail==="string"?J.detail:typeof J.message==="string"?J.message:Q.success?Q.data.error.message:`Reason request failed (${$}${typeof J.error==="string"?` ${J.error}`:""})`,B=X==="github_connection_required"&&typeof J.connect_url==="string"&&/^https?:\/\//.test(J.connect_url)?` Connect it at ${J.connect_url}`:"",V=Z===null||Z.trim()===""?NaN:Number(Z);return new Y0($,X,`${Y}${B}`,typeof J.suggested_model==="string"?J.suggested_model:void 0,Number.isFinite(V)&&V>=0?V*1000:void 0,typeof J.resolution_reason==="string"?J.resolution_reason:void 0)}async function S9($){let J=await($.fetchImpl??fetch)(`${$.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${$.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify($.body),signal:AbortSignal.timeout(30000),redirect:"error"}),Z=await J.json().catch(()=>({}));if(!J.ok)throw E9(J.status,Z,J.headers.get("retry-after"));return P0(fZ,Z,"invalid_machine_ticket")}class U1{options;credentials;constructor($,J={}){this.options=J;this.credentials=$}trackEvent($,J={}){}async request($,J={},Z=!1){let Q=this.options.fetchImpl??fetch,X=await Q(`${this.credentials.apiOrigin}/v3${$}`,{method:J.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":"reason-cli","x-reason-agent":"Reason CLI",...J.raw?{"content-type":J.raw.contentType}:J.body===void 0?{}:{"content-type":"application/json"},...J.headers},body:J.raw?J.raw.bytes:J.body===void 0?void 0:JSON.stringify(J.body),signal:J.signal,redirect:"error"}),Y=await X.json().catch(()=>({}));if(X.status===401&&!Z&&J.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let B=await k1({fetchImpl:Q,path:this.options.credentialsPath,forceRefresh:!0,signal:J.signal});if(B)return this.credentials=B,this.request($,J,!0)}if(!X.ok)throw E9(X.status,Y,X.headers.get("retry-after"));return Y}createHeadlessDeviceEnrollmentTicket($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice($){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:$,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(J){if(J instanceof Y0&&(J.status===404||J.status===405||J.status===403&&J.code==="endpoint_not_available"))return null;throw J}}addDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots`,{method:"POST",body:J,signal:AbortSignal.timeout(30000)})}removeDeviceRoot($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent($)}/roots/${encodeURIComponent(J)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath($,J=""){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return $===void 0?Z:`${Z}/${encodeURIComponent($)}${J}`}async listMachines(){return P0(wZ,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine($){let J=await this.request(this.machinePath(),{method:"POST",body:{name:$.name,...$.platform?{platform:$.platform}:{}}});return P0(bZ,J,"invalid_machine").machine}async deleteMachine($){let J=await this.request(this.machinePath($),{method:"DELETE"});return P0(kZ,J,"invalid_machine_deletion")}async createMachineToken($){let J=await this.request(this.machinePath($,"/tokens"),{method:"POST",body:{}});return P0(yZ,J,"invalid_machine_token")}async createMachineEnrollmentTicket($,J){let Z=await this.request(this.machinePath($,"/enrollment-tickets"),{method:"POST",body:J,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return P0(x9,Z,"invalid_machine_ticket")}self($){return this.request("/self",{signal:$})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:$,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:$,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((J)=>typeof J.email==="string"?[{email:J.email,role:typeof J.role==="string"?J.role:"member"}]:[])}claimExistingCliPairing($){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:$}})}connectAnthropicProvider($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:Z.retryUnauthorized,signal:Z.signal,body:{access_token:$.access,refresh_token:$.refresh,expires_at:new Date($.expires).toISOString(),...J?{account_key:J}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((J)=>{let Z=typeof J.full_name==="string"?J.full_name:typeof J.repo_full_name==="string"?J.repo_full_name:null;if(!Z)return[];return[{repo_id:typeof J.repo_id==="string"?J.repo_id:void 0,full_name:Z,provider:J.provider==="gitlab"?"gitlab":"github",default_branch:typeof J.default_branch==="string"?J.default_branch:null,private:typeof J.private==="boolean"?J.private:void 0}]})}async listProjects(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),J=jZ.safeParse($);if(!J.success)throw new Y0(502,"invalid_project_list","Reason returned an unexpected project list.");return J.data.items}async listReasons(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return P0(OZ,$,"invalid_reason_list").items}async openReasonConversation($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent($)}/conversation`,{method:"POST"});return P0(G.object({session_id:G.string().min(1)}),J,"invalid_reason_conversation").session_id}async listSkills(){try{let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return P0(RZ,$,"invalid_skill_list").items}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return[];throw $}}async listDevices(){let $=[],J=null;for(let Z=0;Z<50;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${J?`?after=${encodeURIComponent(J)}`:""}`),X=LZ.safeParse(Q);if(!X.success)throw new Y0(502,"invalid_device_list","Reason returned an unexpected machine list.");if($.push(...X.data.devices),J=X.data.has_next_page?X.data.end_cursor??null:null,!J)break}return $}async listModels(){try{let J=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((X)=>X.hidden!==!0),Z=J.filter((X)=>X.available!==!1).map(({reasoning_efforts:X,hidden:Y,available:B,...V})=>({...V,...Array.isArray(X)?{reasoning_efforts:FZ.filter((K)=>X.includes(K))}:{}})),Q=new Set(Z.map((X)=>X.detail));return{models:Z.length>1&&Q.size===1?Z.map(({detail:X,...Y})=>Y):Z,runnable:Z.length>0||J.length===0}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return{models:[],runnable:!0};throw $}}async getAgentVersion($){try{let J=await this.request("/deployment",{signal:$,retryUnauthorized:!1});return U9(J.reason_version)?J.reason_version:null}catch{return null}}async getUsageQuota(){try{let $=MZ.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!$.success)return null;let J;try{J=_Z(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...$.data,own_inference:J}}catch($){if($ instanceof Y0&&($.status===403||$.status===404))return null;throw $}}async listSessions($=50,J,Z={}){let Q=new URLSearchParams({first:String(Math.min(Math.max($,1),200)),status:Z.status??"active"});if(J)Q.set("project_id",J);if(Z.origin)Q.set("origin",Z.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${Q.toString()}`)).items??[]}getSession($,J){let Z=J?.fields.length?`?fields=${encodeURIComponent(J.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${Z}`)}async prestartSession($){let J=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:$}});return J?.status==="starting"||J?.status==="ready"}async createSession($){let J=$.mode==="ephemeral"||$.workspaceOwnership==="externally-managed";if($.attachments?.length)await this.requireSessionAttachments();if(J||$.runtimeProfile){let X=await this.request("/deployment");if(J&&(!Array.isArray(X.session_modes)||!X.session_modes.includes($.mode??"standard")||!Array.isArray(X.workspace_ownerships)||!X.workspace_ownerships.includes($.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if($.runtimeProfile&&(!Array.isArray(X.experimental_runtime_profiles)||!X.experimental_runtime_profiles.includes($.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:$.prompt,...$.attachments?.length?{attachments:$.attachments}:{},...$.mode?{mode:$.mode}:{},...$.workspaceOwnership?{workspace_ownership:$.workspaceOwnership}:{},...$.target?{target:$.target}:{},...$.repo?{repo:$.repo}:{},...$.provider?{provider:$.provider}:{},...$.model?{model:$.model}:{},...$.reasoningEffort?{reasoning_effort:$.reasoningEffort}:{},...$.runtimeProfile?{experimental_runtime_profile:$.runtimeProfile}:{},...$.ref?{ref:$.ref}:{},...$.branch?{branch:$.branch}:{},...$.completionMode?{completion_mode:$.completionMode}:{},...$.env&&Object.keys($.env).length>0?{env:$.env}:{},...$.clientSessionId?{client_session_id:$.clientSessionId}:{},...$.longRunning?{long_running:{enabled:!0}}:{},...$.spendLimitRcu?{spend_limit_rcu:$.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),Q=await this.getSession(Z.session_id);if(J){let X=Q.session_policy,Y=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!X||X.version!==1||X.mode!==($.mode??"standard")||X.workspaceOwnership!==($.workspaceOwnership??"managed")||!X.components||Y.some((B)=>X.components[B]!==!0))throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if($.runtimeProfile&&Q.experimental_runtime_profile!==$.runtimeProfile)throw await this.cancelSession(Z.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return Q}async getEvents($,J=-1,Z={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/events?after_seq=${J}&limit=500${Z.waitMs?`&wait_ms=${Z.waitMs}`:""}`,Z.signal?{signal:Z.signal}:{})}catch(Q){if(!(Q instanceof Y0)||Q.status!==403&&Q.status!==404)throw Q;return{session:await this.getSession($),items:[],next_seq:J}}}async getMessages($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages?first=500${J===void 0?"":`&after_seq=${J}`}`)}async getAttachments($,J){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/attachments${J?`?view=${J}`:""}`)).items??[]}catch(Z){if(Z instanceof Y0&&(Z.status===403||Z.status===404))return[];throw Z}}async requireSessionAttachments(){let $=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if($.session_attachments!==!0){let J=typeof $.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test($.reason_version)?`Agent ${$.reason_version}`:null,Z=typeof $.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test($.commit_sha)?`server ${$.commit_sha.slice(0,12)}`:null,Q=[J,Z].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${Q?` (${Q})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage($,J,Z={}){if(Z.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages`,{method:"POST",body:{message:J,...Z.attachments?.length?{attachments:Z.attachments}:{},...Z.model?{model:Z.model}:{},...Z.reasoningEffort?{reasoning_effort:Z.reasoningEffort}:{},...Z.target?{target:Z.target}:{},...Z.delivery?{delivery:Z.delivery}:{}}})}async steerQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/messages/${encodeURIComponent(J)}/queued`,{method:"DELETE"})}async getConversation($){let J=[],Z=null;for(let Q=0;Q<50;Q+=1){let X=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/conversation${Z?`?after=${encodeURIComponent(Z)}`:""}`);if(J.push(...X.items??[]),!X.has_next_page||!X.end_cursor)break;Z=X.end_cursor}return J}createSharedLink($,J){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/shared-links`,{method:"POST",body:{url:J.url,...J.label?{label:J.label}:{},...J.expiresInSeconds!==void 0?{expires_in_seconds:J.expiresInSeconds}:{}}})}sessionAction($,J,Z={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/${J}`,{method:"POST",body:Z})}renameSession($,J){return this.sessionAction($,"rename",{title:J||null})}moveSessionToProject($,J){return this.sessionAction($,"project",{project_id:J})}compactSession($){return this.sessionAction($,"compact")}retrySession($){return this.sessionAction($,"retry")}rewindSession($,J){return this.sessionAction($,"rewind",{message_id:J.messageId,content:J.content,request_id:J.requestId})}forkSession($,J){return this.sessionAction($,"fork",{...J.message?{message:J.message}:{},client_session_id:J.clientSessionId})}cancelSession($,J={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}/cancel`,{method:"POST",body:J.mode==="hard"?{mode:"hard"}:{}})}sessionPath($,J=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent($)}${J}`}async archiveSession($){await this.request(this.sessionPath($,"/archive"),{method:"POST",body:{}})}async unarchiveSession($){await this.request(this.sessionPath($,"/unarchive"),{method:"POST",body:{}})}async deleteSession($){await this.request(this.sessionPath($),{method:"DELETE"})}async listSessionTags($){return P0(C9,await this.request(this.sessionPath($,"/tags")),"invalid_session_tags").tags}async appendSessionTags($,J){let Z=await this.request(this.sessionPath($,"/tags"),{method:"POST",body:{tags:J}});return P0(C9,Z,"invalid_session_tags").tags}async sessionInsight($,J=!1){let Z=await this.request(this.sessionPath($,J?"/insights/generate":"/insights"),J?{method:"POST",body:{}}:{});return P0(EZ,Z,"invalid_session_insight")}async listAutomations(){let $=[],J=null;for(let Z=0;Z<20;Z+=1){let Q=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${J?`&after=${encodeURIComponent(J)}`:""}`),X=P0(PZ,Q,"invalid_automation_list");if($.push(...X.items),J=X.has_next_page?X.end_cursor??null:null,!J)break}return $}async createScheduledAutomation($,J){let Z=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,Q=P0(P9,await this.request(Z,{method:"POST",body:{name:$.name,instructions:$.instructions,...$.repo?{repo:$.repo.full_name,provider:$.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${Z}/${encodeURIComponent(Q.id)}/triggers`,{method:"POST",body:J})}catch(X){throw await this.deleteAutomation(Q.id).catch(()=>{return}),X}return Q}async setAutomationEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"PATCH",body:{enabled:J}})}async deleteAutomation($){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent($)}`,{method:"DELETE"})}async transcribe($,J){let Z=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:$,contentType:J}});return P0(G.object({transcript:G.string()}),Z,"invalid_transcript").transcript}async listMcpServers(){let $=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return P0(xZ,$,"invalid_mcp_server_list").items}async setSkillEnabled($,J){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent($)}`,{method:"PUT",body:{is_enabled:J}})}}function y1($,J){let Z=k0($,"REASON_API_URL")?.trim();if(!Z)return j4(J);let Q=new URL(Z);if(Q.protocol!=="https:"&&!(Q.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(Q.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return Q.origin}function mZ($){return k0($,"REASON_API_URL")?.trim()?y1($,"production"):void 0}function z4($){return k0($,"REASON_API_KEY")?.trim()||void 0}async function w9($,J){let Z=$.env??process.env,Q=z4(Z);if(!Q)return($.getCredentials??k1)({apiOrigin:mZ(Z),signal:J});let X=y1(Z,$.channel??x0({env:Z})),Y=await($.fetchImpl??fetch)(X+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+Q,accept:"application/json"},signal:J}),B=await Y.json().catch(()=>({})),V=n0(B)?B:{};if(!Y.ok){let N=typeof V.detail==="string"?V.detail:typeof V.message==="string"?V.message:"API key authentication failed ("+Y.status+")";throw new Y0(Y.status,typeof V.error==="string"?V.error:"api_key_auth_failed",N)}if(typeof V.org_id!=="string"||!V.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let K=Array.isArray(V.scopes)?V.scopes.filter((N)=>typeof N==="string"):[];return{credentialKind:"api_key",apiOrigin:X,accessToken:Q,orgId:V.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:K}}import{createHash as vZ}from"crypto";import{unlinkSync as gZ}from"fs";import{platform as uZ}from"os";import{join as dZ}from"path";var b9=G.discriminatedUnion("store",[G.strictObject({version:G.literal(1),store:G.literal("keychain")}),G.strictObject({version:G.literal(1),store:G.literal("file"),api_key:G.string().min(1).max(4096)})]),f1=($)=>dZ($,"api-key.json");function z1($){let J=vZ("sha256").update(`reason-connect-api-key
|
|
5
5
|
${$}`).digest("hex");return new e1(T2(),uZ(),J)}function O4($,J,Z=z1($)){try{Z.deleteBinding(),Z.createBinding(new TextEncoder().encode(J)),c(f1($),{version:1,store:"keychain"});return}catch(Q){if(!(Q instanceof G0))throw Q}c(f1($),{version:1,store:"file",api_key:J})}function p0($,J=z1($)){if(!u(f1($)))return null;let Z=b9.parse(JSON.parse(s(f1($))));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 G0))throw Q;throw Error("worker_api_key_unreadable")}}function k9($,J=z1($)){if(!u(f1($)))return;if(b9.parse(JSON.parse(s(f1($)))).store==="keychain")try{J.deleteBinding()}catch(Z){if(!(Z instanceof G0))throw Z}gZ(f1($))}async function A4($,J){let Z;try{Z=await w9({env:{REASON_API_KEY:J,REASON_API_URL:$.apiOrigin},fetchImpl:y0($.proxy)})}catch(Q){if(Q instanceof Y0&&(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 BQ,renameSync as KQ,rmSync as v1}from"fs";import{join as M0}from"path";import{createHash as lZ}from"crypto";import{realpathSync as pZ,statSync as cZ,unlinkSync as _2}from"fs";import{platform as sZ}from"os";import{join as f0}from"path";function d($){return{state:f0(g($),"device.json"),control:f0(g($),"control.json"),lock:f0(g($),"lifecycle.lock"),socket:f0(g($),"control.sock"),daemon:f0(g($),"daemon.json"),releaseCheck:f0(g($),"release-check.json"),updateDeferral:f0(g($),"update-deferral.json"),firstHeartbeat:f0(g($),"first-heartbeat.json")}}var aZ=G.object({version:G.literal(1),device_id:G.string().min(1).max(160),offer:G.unknown().optional(),enrollment_ms:G.number().int().nonnegative().max($$).optional()});function f9($,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 C4($,J){let Z=d($).firstHeartbeat;try{if(!u(Z))return null;let Q=aZ.safeParse(JSON.parse(s(Z)));if(_2(Z),!Q.success||Q.data.device_id!==J)return null;let X=F2(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=f0(g($),Q);if(!u(X))return!1;return s(X),!0});return $.lifetime==="persistent"&&Z.join()==="device.json"?P4($):new R4(g($))}function W2($,J){T0($,!0),rZ($);let Z=J??P4($),Q=new R4(g($));try{Z.deleteBinding(),Z.deleteKey(),Z.createFreshPublicKey()}catch(X){if(X instanceof G0)return Q;throw X}return Q.deleteBinding(),Q.deleteKey(),Z}function P4($){return new e1(T2(),sZ(),iZ($))}function iZ($){let J=I4($);return lZ("sha256").update(`reason-worker
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Fe as Aq}from"./vm-hands-entry-lite-henbtxfe.js";import{ef as H,hf as L0,kf as y0,lf as T8,mf as sq,of as $8,rf as iq,tf as nq}from"./vm-hands-entry-lite-jz24p4jj.js";import{Cf as j0}from"./vm-hands-entry-lite-tav4dt92.js";import{hg as U0}from"./vm-hands-entry-lite-sggk0bqc.js";import{oh as Zq}from"./vm-hands-entry-lite-djy0ww6h.js";import{ph as d}from"./vm-hands-entry-lite-kbz9zfha.js";import{Ph as W0}from"./vm-hands-entry-lite-dyqeaqzb.js";import{Wh as M}from"./vm-hands-entry-lite-40t7d4p5.js";import{execFile as tx,spawn as T0}from"child_process";import{randomBytes as ex}from"crypto";import{chmodSync as q1,existsSync as B0,lstatSync as x1,mkdirSync as X1,readFileSync as Q1,rmSync as P1,writeFileSync as o8}from"fs";import{connect as b1}from"net";import{join as _}from"path";var Uq="./desktop-wallpaper-0pjhgyfk.jpg";var Lq="./dock-browser-afp005mt.png";var yq="./dock-files-rywdm96b.png";var jq="./dock-terminal-s41cj1jp.png";var Tq=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
|
+
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
|
+
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
|
+
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
6
|
+
import ctypes, sys
|
|
7
|
+
import gi
|
|
8
|
+
gi.require_version("GdkPixbuf", "2.0")
|
|
9
|
+
from gi.repository import GdkPixbuf
|
|
10
|
+
x = ctypes.cdll.LoadLibrary("libX11.so.6")
|
|
11
|
+
x.XOpenDisplay.restype = ctypes.c_void_p
|
|
12
|
+
x.XOpenDisplay.argtypes = [ctypes.c_char_p]
|
|
13
|
+
d = x.XOpenDisplay(None)
|
|
14
|
+
if not d: sys.exit("no display")
|
|
15
|
+
for name, res, args in [
|
|
16
|
+
("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
|
|
17
|
+
("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
|
|
18
|
+
("XDisplayWidth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
19
|
+
("XDisplayHeight", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
20
|
+
("XDefaultDepth", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
21
|
+
("XDefaultVisual", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
|
|
22
|
+
("XDefaultGC", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_int]),
|
|
23
|
+
("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint, ctypes.c_uint]),
|
|
24
|
+
("XCreateImage", ctypes.c_void_p, [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint, ctypes.c_int, ctypes.c_int, ctypes.c_char_p, ctypes.c_uint, ctypes.c_uint, ctypes.c_int, ctypes.c_int]),
|
|
25
|
+
("XPutImage", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint, ctypes.c_uint]),
|
|
26
|
+
("XInternAtom", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int]),
|
|
27
|
+
("XChangeProperty", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]),
|
|
28
|
+
("XSetWindowBackgroundPixmap", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong]),
|
|
29
|
+
("XClearWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
|
|
30
|
+
("XSetCloseDownMode", ctypes.c_int, [ctypes.c_void_p, ctypes.c_int]),
|
|
31
|
+
("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p]),
|
|
32
|
+
]:
|
|
33
|
+
f = getattr(x, name); f.restype = res; f.argtypes = args
|
|
34
|
+
s = x.XDefaultScreen(d); root = x.XRootWindow(d, s)
|
|
35
|
+
w, h = x.XDisplayWidth(d, s), x.XDisplayHeight(d, s)
|
|
36
|
+
if x.XDefaultDepth(d, s) != 24: sys.exit("unsupported depth")
|
|
37
|
+
# Scale to cover the screen, then crop the centre.
|
|
38
|
+
src = GdkPixbuf.Pixbuf.new_from_file(sys.argv[1])
|
|
39
|
+
k = max(w / src.get_width(), h / src.get_height())
|
|
40
|
+
sw, sh = max(w, round(src.get_width() * k)), max(h, round(src.get_height() * k))
|
|
41
|
+
pb = src.scale_simple(sw, sh, GdkPixbuf.InterpType.BILINEAR).new_subpixbuf((sw - w) // 2, (sh - h) // 2, w, h).copy()
|
|
42
|
+
if pb.get_has_alpha(): pb = pb.composite_color_simple(w, h, GdkPixbuf.InterpType.NEAREST, 255, 1, 0, 0)
|
|
43
|
+
rgb, stride = pb.get_pixels(), pb.get_rowstride()
|
|
44
|
+
bgrx = bytearray(w * h * 4)
|
|
45
|
+
for y in range(h):
|
|
46
|
+
row = rgb[y * stride:y * stride + w * 3]; o = y * w * 4
|
|
47
|
+
bgrx[o:o + w * 4:4] = row[2::3]; bgrx[o + 1:o + w * 4:4] = row[1::3]; bgrx[o + 2:o + w * 4:4] = row[0::3]
|
|
48
|
+
buf = ctypes.create_string_buffer(bytes(bgrx), len(bgrx))
|
|
49
|
+
pix = x.XCreatePixmap(d, root, w, h, 24)
|
|
50
|
+
img = x.XCreateImage(d, x.XDefaultVisual(d, s), 24, 2, 0, buf, w, h, 32, 0) # ZPixmap
|
|
51
|
+
x.XPutImage(d, pix, x.XDefaultGC(d, s), img, 0, 0, 0, 0, w, h)
|
|
52
|
+
ref = ctypes.c_ulong(pix)
|
|
53
|
+
for atom in (b"_XROOTPMAP_ID", b"ESETROOT_PMAP_ID"):
|
|
54
|
+
x.XChangeProperty(d, root, x.XInternAtom(d, atom, 0), 20, 32, 0, ctypes.byref(ref), 1) # XA_PIXMAP, PropModeReplace
|
|
55
|
+
x.XSetWindowBackgroundPixmap(d, root, pix)
|
|
56
|
+
x.XClearWindow(d, root)
|
|
57
|
+
x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
|
|
58
|
+
x.XCloseDisplay(d)
|
|
59
|
+
`;var e=32,Bq=76;function _0(q){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
60
|
+
<openbox_config xmlns="http://openbox.org/3.4/rc">
|
|
61
|
+
<theme><keepBorder>no</keepBorder></theme>
|
|
62
|
+
<applications>
|
|
63
|
+
<!-- Debian Chromium is "Chromium"; Chrome for Testing is "Chromium-browser". -->
|
|
64
|
+
<application class="Chromium*">
|
|
65
|
+
<decor>no</decor>
|
|
66
|
+
<position force="yes"><x>${e}</x><y>${e}</y></position>
|
|
67
|
+
<size><width>${q.width-e*2}</width><height>${q.height-e-Bq}</height></size>
|
|
68
|
+
</application>
|
|
69
|
+
</applications>
|
|
70
|
+
</openbox_config>`}var E0=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
|
|
71
|
+
panel_items = L
|
|
72
|
+
panel_size = 100% 46
|
|
73
|
+
panel_margin = 0 10
|
|
74
|
+
panel_padding = 0 0 10
|
|
75
|
+
panel_position = bottom center horizontal
|
|
76
|
+
panel_shrink = 1
|
|
77
|
+
panel_background_id = 0
|
|
78
|
+
panel_layer = top
|
|
79
|
+
mouse_effects = 1
|
|
80
|
+
mouse_hover_icon_asb = 100 0 12
|
|
81
|
+
mouse_pressed_icon_asb = 100 0 -12
|
|
82
|
+
|
|
83
|
+
launcher_icon_size = 46
|
|
84
|
+
launcher_padding = 0 0 10
|
|
85
|
+
launcher_background_id = 0
|
|
86
|
+
launcher_tooltip = 1
|
|
87
|
+
|
|
88
|
+
launcher_item_app = /tmp/ara-chromium.desktop
|
|
89
|
+
launcher_item_app = /tmp/ara-terminal.desktop
|
|
90
|
+
launcher_item_app = /tmp/ara-files.desktop
|
|
91
|
+
`,O0=`corner-radius = 12;
|
|
92
|
+
rounded-corners-exclude = [
|
|
93
|
+
"class_g = 'tint2'",
|
|
94
|
+
"window_type = 'dock'",
|
|
95
|
+
"window_type = 'desktop'"
|
|
96
|
+
];
|
|
97
|
+
backend = "xrender";
|
|
98
|
+
shadow = false;
|
|
99
|
+
fading = false;
|
|
100
|
+
vsync = false;
|
|
101
|
+
inactive-opacity = 1.0;
|
|
102
|
+
active-opacity = 1.0;
|
|
103
|
+
`,$0="/tmp/ara-dock-browser.png",H0=`[Desktop Entry]
|
|
104
|
+
Name=Chrome
|
|
105
|
+
Exec=chromium --no-sandbox %U
|
|
106
|
+
Icon=${$0}
|
|
107
|
+
Type=Application
|
|
108
|
+
Categories=Network;WebBrowser;
|
|
109
|
+
`,f0=`[Desktop Entry]
|
|
110
|
+
Name=Terminal
|
|
111
|
+
Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
|
|
112
|
+
Icon=/tmp/ara-dock-terminal.png
|
|
113
|
+
Type=Application
|
|
114
|
+
Categories=System;TerminalEmulator;
|
|
115
|
+
`,h0=`[Desktop Entry]
|
|
116
|
+
Name=Files
|
|
117
|
+
Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
|
|
118
|
+
Icon=/tmp/ara-dock-files.png
|
|
119
|
+
Type=Application
|
|
120
|
+
Categories=System;FileManager;
|
|
121
|
+
`;var Dq={"wallpaper.jpg":Uq,"dock-browser.png":Lq,"dock-terminal.png":jq,"dock-files.png":yq},g0=Tq,p0='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function Rq(q){let x=(J)=>J.replaceAll("DISPLAY=:99",`DISPLAY=${q.display}`).replaceAll("/tmp/ara-",`${q.root}/ara-`),X=new Set(q.absent??[]),Q=E0.split(`
|
|
122
|
+
`).filter((J)=>!(X.has("terminal")&&J.endsWith("/ara-terminal.desktop"))&&!(X.has("files")&&J.endsWith("/ara-files.desktop"))).join(`
|
|
123
|
+
`);return{files:{"openbox/rc.xml":_0(q.screen),"tint2/tint2rc":x(Q),"picom/picom.conf":O0,...X.has("terminal")?{}:{"ara-terminal.desktop":x(f0)},...X.has("files")?{}:{"ara-files.desktop":x(h0)},"ara-chromium.desktop":x(H0).replace("chromium --no-sandbox %U",q.browserExec),"ara-set-root-wallpaper.py":g0},start:['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }',p0,'[ ! -f "$ROOT/ara-wallpaper.jpg" ] || set_wallpaper "$ROOT/ara-wallpaper.jpg" "$ROOT/ara-set-root-wallpaper.py" || true','if ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi']}}import{createHash as Gq}from"crypto";import{once as k0}from"events";import{createWriteStream as I0,existsSync as v0,mkdirSync as u0,mkdtempSync as n1,readFileSync as U8,readdirSync as o1,renameSync as c0,realpathSync as l0,rmSync as r0,statSync as H8,writeFileSync as m0}from"fs";import{dirname as f8,join as S}from"path";import{finished as d0}from"stream/promises";var _8="omljlfpmafedpplnpkkahegadhkimdje",f1="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";function p1(q){if(!q||typeof q!=="object"||Array.isArray(q)||!("version"in q)||q.version!==1||!("status"in q))return null;if(q.status==="unavailable")return Object.keys(q).length===2?{version:1,status:"unavailable"}:null;if(q.status!=="connected"||Object.keys(q).length!==5||!("deviceId"in q)||typeof q.deviceId!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(q.deviceId)||!("apiOrigin"in q)||typeof q.apiOrigin!=="string"||q.apiOrigin.length>2048||!("managedRootIds"in q)||!Array.isArray(q.managedRootIds)||q.managedRootIds.length>32)return null;let x=[];for(let X of q.managedRootIds){if(typeof X!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(X))return null;x.push(X)}try{let X=new URL(q.apiOrigin);if(X.origin!==q.apiOrigin||X.username||X.password||!(X.protocol==="https:"||X.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(X.hostname)))return null}catch{return null}return{version:1,status:"connected",deviceId:q.deviceId,apiOrigin:q.apiOrigin,managedRootIds:x}}var g={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},N8={version:"154.0.8037.57",macArm64Sha256:"0e6b3439469c1b8b95b2e89c72ea29f7af00fb2c28a8878358a0b6002b6d3a64",linux64Sha256:"ceee2972074d441ea7c4ba8bcc0eaab77e7e87680f6653d73d3065851fe10302"};var q8={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${g.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${g.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${g.obu.version}/open-browser-use-chrome-extension-${g.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},r="pnbmoicbkopffjjgfgfglopechaiemkp";var a0=["none","standard","all"],E8="22.23.3",s0={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53"},O8={"linux-x64":{ocu:"dist/linux/amd64/open-computer-use",obu:"native/linux-amd64/open-browser-use"},"linux-arm64":{ocu:"dist/linux/arm64/open-computer-use",obu:"native/linux-arm64/open-browser-use"},"darwin-arm64":{ocu:"dist/Open Computer Use.app/Contents/MacOS/OpenComputerUse",obu:"native/darwin-arm64/open-browser-use"}},Fq="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",h8={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},i0={version:h8.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},m="com.ifuryst.open_browser_use.extension",wq="com.reasonmachines.browser_use.extension",Cq="/tmp/reason-browser-use",g8=["tint2","picom","xterm","pcmanfm"],Vq=["fonts-droid-fallback"],Kq=["pulseaudio"],n0=["xvfb","openbox","x11vnc","x11-utils","x11-xserver-utils","xdotool","dbus-x11","at-spi2-core","python3","python3-gi","gir1.2-atspi-2.0","gir1.2-gtk-3.0","fonts-dejavu-core",...Vq,"galculator","chromium","ffmpeg","tmux",...Kq,...g8],o0=new Set([...g8,...Vq,...Kq]),Sq=n0.filter((q)=>q!=="chromium"&&!o0.has(q)),t0=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],W8="/usr/bin/chromium",e0=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function Mq(q=process.platform,x=process.arch){let X=`${q}-${x}`;return X==="linux-x64"||X==="linux-arm64"||X==="darwin-arm64"?X:null}function L8(q){return{node:{version:E8,url:`https://nodejs.org/dist/v${E8}/node-v${E8}-${q}.tar.gz`,sha256:s0[q]},open_computer_use:{version:g.ocu.version,url:q8.ocu.url,sha256:q8.ocu.sha256},open_browser_use:{version:g.obu.version,url:q8.obu.url,sha256:q8.obu.sha256},...q==="darwin-arm64"?{chrome_for_testing:{version:N8.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${N8.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:N8.macArm64Sha256}}:{}}}function qx(q){let x={extension:r};for(let[X,Q]of Object.entries(L8(q)))x[X]=`${Q.version}@${Q.sha256}`;return x}function Yq(q){return S(q,".local","share","reason","desktop")}function zq(q,x=Zq()){let X=Yq(x),Q=(W)=>S(X,W,L8(q)[W]?.version??""),P=Q("open_computer_use"),b=Q("open_browser_use"),J=q==="darwin-arm64",y=S(x,"Library","Application Support"),C=J?S(y,"Google","Chrome","NativeMessagingHosts",`${m}.json`):S(x,".config","google-chrome","NativeMessagingHosts",`${m}.json`);return{root:X,automation:S(f8(X),"automation"),receipt:S(X,"receipt.json"),minimal:k8(x),node:S(Q("node"),"bin","node"),ocuDir:P,ocu:S(P,O8[q].ocu),ocuApp:J?S(P,"dist","Open Computer Use.app"):null,obuDir:b,obu:S(b,"cli","open-browser-use.js"),nativeHost:S(b,O8[q].obu),extensionDir:J?S(y,"OpenBrowserUse","chrome-extension","release"):S(x,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:C,nativeHostManifests:J?[C,S(y,"Google","ChromeForTesting","NativeMessagingHosts",`${m}.json`)]:[S(x,".config","chromium","NativeMessagingHosts",`${m}.json`),S(x,".config","google-chrome-for-testing","NativeMessagingHosts",`${m}.json`)],browser:J?S(Q("chrome_for_testing"),Fq):W8,userChromeHost:J?S(X,"user-chrome","reason-browser-use"):null,userChromeRegistration:J?S(y,"Google","Chrome","NativeMessagingHosts",`${wq}.json`):null,ffmpegDir:S(X,"ffmpeg"),ffmpeg:J?S(X,"ffmpeg",h8.version,"ffmpeg"):null,ffprobe:J?S(X,"ffprobe",i0.version,"ffprobe"):null}}function _q(q){try{let x=JSON.parse(U8(q,"utf8"));if(typeof x!=="object"||x===null)return null;let X=x,Q=X.pins;if(X.schema_version!==1||typeof X.platform!=="string"||typeof Q!=="object"||Q===null||!Object.values(Q).every((P)=>typeof P==="string")||!a0.includes(X.permissions)||!Array.isArray(X.missing_system_packages)||!X.missing_system_packages.every((P)=>typeof P==="string")||typeof X.updated_at!=="string")return null;return{schema_version:1,platform:X.platform,pins:Q,permissions:X.permissions,missing_system_packages:X.missing_system_packages,updated_at:X.updated_at}}catch{return null}}function xx(q,x,X=384){u0(f8(q),{recursive:!0,mode:448});let Q=`${q}.pending.${process.pid}`;m0(Q,x,{mode:X}),c0(Q,q)}function p(q){try{return H8(q).isFile()}catch{return!1}}function Eq(q){try{let x=H8(q);return x.isFile()&&(x.mode&73)!==0}catch{return!1}}function Xx(q){try{return U8(q,"utf8")}catch{return null}}function v(q){for(let x of e0){let X=S(x,q);try{let Q=H8(X);if(Q.isFile()&&(Q.mode&73)!==0)return X}catch{}}return null}function Qx(q){try{let x=JSON.parse(U8(S(q,"package.json"),"utf8"));return typeof x==="object"&&x!==null&&typeof x.version==="string"?x.version:null}catch{return null}}function Px(q,x,X){let Q=L8(X)[q];if(!Q)return!1;if(q==="node")return p(S(x,"bin","node"));if(q==="chrome_for_testing")return p(S(x,Fq));let P=O8[X][q==="open_computer_use"?"ocu":"obu"];return Qx(x)===Q.version&&p(S(x,P))&&(q==="open_computer_use"||p(S(x,"cli","open-browser-use.js")))}function bx(q){return Gq("sha256").update(Buffer.from(q,"base64")).digest("hex").slice(0,32).replace(/./g,(x)=>String.fromCharCode(97+Number.parseInt(x,16)))}function p8(q){try{let x=JSON.parse(U8(q,"utf8"));return typeof x==="object"&&x!==null&&!Array.isArray(x)?x:null}catch{return null}}function Jx(q){let x=p8(S(q.extensionDir,"manifest.json"));return x!==null&&x.version===g.obu.version&&typeof x.key==="string"&&bx(x.key)===r}function Nx(q,x){let X=q?.allowed_origins;return q!==null&&q.name===m&&Array.isArray(X)&&X.length===1&&X[0]===`chrome-extension://${r}/`&&(x===void 0||q.path===x)}function Wx(q){return Jx(q)&&p(q.nativeHost)&&q.nativeHostManifests.every((x)=>Nx(p8(x),q.nativeHost))}function Ux(q){return`#!/bin/sh
|
|
124
|
+
# Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
|
|
125
|
+
obu=${`'${q.replaceAll("'","'\\''")}'`}
|
|
126
|
+
case "$1" in
|
|
127
|
+
chrome-extension://*) exec "$obu" host --socket-dir ${Cq} ;;
|
|
128
|
+
mcp) shift; exec "$obu" mcp --socket-dir ${Cq} "$@" ;;
|
|
129
|
+
esac
|
|
130
|
+
exec "$obu" "$@"
|
|
131
|
+
`}function Lx(q){let x=p8(q),X=x?.allowed_origins;return x!==null&&x.name===wq&&x.type==="stdio"&&Array.isArray(X)&&X.includes(`chrome-extension://${_8}/`)&&typeof x.path==="string"&&Eq(x.path)}function yx(q,x){if(!q.userChromeHost||!q.userChromeRegistration)return null;if(!x||Xx(q.userChromeHost)!==Ux(q.nativeHost)||!Eq(q.userChromeHost))return{code:"user_chrome_browser_use_missing"};return Lx(q.userChromeRegistration)?{host:q.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var jx={display:["display"],computer:["display","system_packages","node","open_computer_use"],browser:["display","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function k(q={}){let x=q.platform===void 0?Mq():q.platform;if(!x)return null;let X=zq(x,q.home),Q=_q(X.receipt),P=qx(x),b=Q!==null&&Q.platform===x&&JSON.stringify(Object.entries(Q.pins).sort())===JSON.stringify(Object.entries(P).sort()),J=[],y=L8(x);for(let N of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let D=y[N];if(!D)continue;let G=Px(N,S(X.root,N,D.version),x),F=Q?.pins[N],O=G&&F===P[N]?"ready":F!==void 0&&F!==P[N]?"outdated":"missing";J.push({name:N,state:O,detail:D.version})}let C=Q?.pins.extension===r&&Wx(X);J.push({name:"browser_extension",state:C?"ready":"missing",detail:r});let W=v("Xvfb"),j=v("x11vnc"),R=v("openbox");if(x!=="darwin-arm64"){J.push(p(W8)?{name:"browser",state:"ready",detail:W8}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${W8}`});let N=W!==null&&j!==null&&R!==null;J.push({name:"display",state:N?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let D=t0.filter((z)=>v(z)===null),G=(Q?.missing_system_packages??Sq).filter((z)=>Sq.includes(z)),F=D.length===0&&G.length===0;J.push(F?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...G,...D])].join(" ")});let O=g8.filter((z)=>v(z)===null);J.push(O.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:O.join(" ")})}let Z=X.ffmpeg&&p(X.ffmpeg)?X.ffmpeg:v("ffmpeg"),B=!Z?null:Z===X.ffmpeg?X.ffprobe:S(f8(l0(Z)),"ffprobe"),Y=b&&J.every((N)=>N.state==="ready"),w=(N)=>b&&J.every((D)=>!jx[N].includes(D.name)||D.state==="ready");return{platform:x,root:X.root,automation:X.automation,ready:Y,features:{display:w("display"),computer:w("computer"),browser:w("browser")},node:X.node,ocu:X.ocu,obu:X.obu,nativeHost:X.nativeHost,extensionDir:X.extensionDir,browser:X.browser,ffmpeg:Z,ffprobe:B&&p(B)?B:null,userChrome:yx(X,b&&["node","open_browser_use"].every((N)=>J.find((D)=>D.name===N)?.state==="ready")),pulseaudio:v("pulseaudio"),xvfb:W,x11vnc:j,openbox:R,components:J}}function Oq(q){return Tx(q)?Aq():[]}function Tx(q){return q?.platform==="darwin-arm64"&&q.ffmpeg===S(q.root,"ffmpeg",h8.version,"ffmpeg")}async function UX(q,x,X,Q=fetch){try{let P=await Q(q,{redirect:"follow"});if(!P.ok||!P.body)throw Error(`download failed (HTTP ${P.status}): ${q}`);let b=Gq("sha256"),J=I0(X,{mode:384});try{let C=P.body.getReader();for(let W=await C.read();!W.done;W=await C.read())if(b.update(W.value),!J.write(W.value))await k0(J,"drain")}finally{J.end(),await d0(J)}let y=b.digest("hex");if(y!==x)throw Error(`digest mismatch for ${q}: expected ${x}, got ${y}`)}catch(P){throw r0(X,{force:!0}),P}}function k8(q){return S(Yq(q),"minimal.json")}function Bx(q=d()){return v0(k8(q))}function LX(q={}){xx(k8(q.home??d()),`${JSON.stringify({version:1,minimal_at:(q.now?.()??new Date).toISOString()})}
|
|
132
|
+
`)}function yX(q={}){let x=q.platform===void 0?Mq():q.platform;if(x===null)return null;let X=q.home??d();if(_q(zq(x,X).receipt)!==null)return"refresh";return Bx(X)?null:"install"}import{execFile as Yx,spawn as d8}from"child_process";import{existsSync as zx}from"fs";import{connect as _x}from"net";function Dx(){let q=new Set,x=null,X=(P)=>({holder:x?.viewer??null,you:x===P,same_user:Boolean(x?.viewer&&P.viewer&&x.viewer.user_id===P.viewer.user_id)}),Q=()=>{for(let P of q)P.notify(X(P))};return{join(P){return q.add(P),P.notify(X(P)),()=>{if(!q.delete(P))return;if(x!==P)return;x=null,Q()}},claim(P){if(x===P||!q.has(P))return;x=P,Q()}}}var $q=Dx();import{spawn as Rx}from"child_process";import{existsSync as Cx}from"fs";import{connect as Sx}from"net";import{join as y8}from"path";var fq="reason_desktop",x8={sampleRate:48000,channels:2,codec:"opus"},Zx=5000,Ax=107,Gx=262144,u8=(q)=>y8(q,"native"),j8=(q)=>`unix:${q}`;function I8(q,x=1000){if(!Cx(q))return Promise.resolve(!1);return new Promise((X)=>{let Q=Sx({path:q}),P=(b)=>{Q.destroy(),X(b)};Q.setTimeout(x,()=>P(!1)),Q.once("error",()=>P(!1)),Q.once("close",()=>P(!1)),Q.once("connect",()=>P(!0))})}async function hq(q,x){if(!x)return null;let X=u8(q);if(Buffer.byteLength(X)>Ax||/["'\\\s]/.test(X))return null;try{if(await I8(X))return X;let Q=Rx(x,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${y8(q,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${X}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${fq} rate=${x8.sampleRate} channels=${x8.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:q,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:q,PULSE_RUNTIME_PATH:y8(q,"runtime"),PULSE_STATE_PATH:y8(q,"state")}}),P=!1;Q.once("error",()=>{P=!0}),Q.once("exit",()=>{P=!0}),Q.unref();let b=Date.now()+Zx;while(Date.now()<b){if(await I8(X))return X;if(P)return await I8(X)?X:null;await new Promise((J)=>setTimeout(J,50))}if(!P)Q.kill("SIGKILL");return null}catch{return null}}function gq(){let{sampleRate:q,channels:x}=x8;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(q),"-channels",String(x),"-fragment_size",String(q*x*2/50),"-i",`${fq}.monitor`,"-vn","-ac",String(x),"-ar",String(q),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var Fx=[79,103,103,83],wx=Buffer.from("OpusHead"),Vx=Buffer.from("OpusTags"),Hq=(q,x)=>q.byteLength>=x.byteLength&&x.every((X,Q)=>q[Q]===X);class v8 extends Error{constructor(q){super(q);this.name="OggProtocolError"}}class c8{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(q){let x=new Uint8Array(this.buffer.byteLength+q.byteLength);x.set(this.buffer),x.set(q,this.buffer.byteLength);let X=[],Q=0;while(x.byteLength-Q>=27){if(Fx.some((Z,B)=>x[Q+B]!==Z)||x[Q+4]!==0)throw new v8("invalid_page");let P=(x[Q+5]&1)!==0,b=x[Q+26];if(x.byteLength-Q<27+b)break;let J=x.subarray(Q+27,Q+27+b),y=J.reduce((Z,B)=>Z+B,0),C=27+b+y;if(x.byteLength-Q<C)break;if(!P&&this.partialBytes>0)this.resetPartial();let W=P&&this.partialBytes===0,j=Q+27+b,R=j;for(let Z of J){if(j+=Z,Z===255)continue;if(this.appendPartial(x.subarray(R,j),W),R=j,!W){let B=this.takePartial();if(B.byteLength>0&&!Hq(B,wx)&&!Hq(B,Vx))X.push(B)}W=!1,this.resetPartial()}if(R<j)this.appendPartial(x.subarray(R,j),W);Q+=C}return this.buffer=x.slice(Q),X}appendPartial(q,x){if(x||q.byteLength===0)return;if(this.partialBytes+=q.byteLength,this.partialBytes>Gx)throw new v8("packet_too_large");this.partial.push(q.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let q=new Uint8Array(this.partialBytes),x=0;for(let X of this.partial)q.set(X,x),x+=X.byteLength;return q}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as Kx}from"child_process";var pq=1048576,Mx=String.raw`
|
|
133
|
+
import gi, json, os, sys
|
|
134
|
+
gi.require_version("Gtk", "3.0")
|
|
135
|
+
from gi.repository import Gtk, Gdk, GLib
|
|
136
|
+
if not Gtk.init_check()[0]:
|
|
137
|
+
sys.exit(1)
|
|
138
|
+
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
|
|
139
|
+
pending = b""
|
|
140
|
+
generation = 0
|
|
141
|
+
def send(value):
|
|
142
|
+
print(json.dumps(value, ensure_ascii=True), flush=True)
|
|
143
|
+
def changed(clipboard, event):
|
|
144
|
+
global generation
|
|
145
|
+
generation += 1
|
|
146
|
+
current = generation
|
|
147
|
+
def received(clipboard, text, unused):
|
|
148
|
+
if current == generation and text is not None and len(text.encode("utf-8")) <= ${H}:
|
|
149
|
+
send({"text": text})
|
|
150
|
+
clipboard.request_text(received, None)
|
|
151
|
+
# No request_text on startup: never share the pre-existing clipboard.
|
|
152
|
+
clipboard.connect("owner-change", changed)
|
|
153
|
+
def input_ready(fd, condition):
|
|
154
|
+
global pending
|
|
155
|
+
chunk = os.read(fd, 65536)
|
|
156
|
+
if not chunk:
|
|
157
|
+
Gtk.main_quit()
|
|
158
|
+
return False
|
|
159
|
+
pending += chunk
|
|
160
|
+
while b"\n" in pending:
|
|
161
|
+
line, pending = pending.split(b"\n", 1)
|
|
162
|
+
text = json.loads(line)
|
|
163
|
+
if not isinstance(text, str) or len(text.encode("utf-8")) > ${H} or "\x00" in text:
|
|
164
|
+
sys.exit(1)
|
|
165
|
+
clipboard.set_text(text, -1)
|
|
166
|
+
send("ack")
|
|
167
|
+
if len(pending) > ${H*6+2}:
|
|
168
|
+
sys.exit(1)
|
|
169
|
+
return True
|
|
170
|
+
GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
|
|
171
|
+
send("ready")
|
|
172
|
+
Gtk.main()
|
|
173
|
+
`;function kq(q,x){let X=Kx("/usr/bin/python3",["-I","-u","-c",Mx],{env:{DISPLAY:q.display,XAUTHORITY:q.xauthority},stdio:["pipe","pipe","ignore"]}),Q=!1,P=!0,b="",J=0,y=[],C=setTimeout(()=>j(),5000),W=()=>{Q=!0,clearTimeout(C),y.length=0,X.kill("SIGKILL")},j=()=>{if(Q)return;W(),x.end({error:new M("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},R=(Z,B=32)=>{if(Q)return;if(!P){Z();return}if(J+=B,J>pq)W(),x.end({reason:"input_backpressure"});else y.push({apply:Z,bytes:B})};return X.stdout.on("data",(Z)=>{if(Q)return;b+=Z.toString("ascii");for(let B=b.indexOf(`
|
|
174
|
+
`);B>=0;B=b.indexOf(`
|
|
175
|
+
`)){let Y=b.slice(0,B);b=b.slice(B+1);let w;try{w=JSON.parse(Y)}catch{j();return}if(w==="ready"||w==="ack"){clearTimeout(C),P=!1;while(!P&&!Q&&y.length){let N=y.shift();J-=N.bytes,N.apply()}}else if(w&&typeof w==="object"&&"text"in w&&typeof w.text==="string"&&Buffer.byteLength(w.text)<=H)x.clipboard(w.text);else{j();return}if(Q)return}if(b.length>H*6+32)j()}),X.stdin.on("error",j),X.once("error",j),X.once("exit",j),{apply:R,write(Z){if(Buffer.byteLength(Z)>H||Z.includes("\x00")){j();return}let B=`${JSON.stringify(Z)}
|
|
176
|
+
`;R(()=>{if(P=!0,C=setTimeout(()=>j(),5000),X.stdin.write(B),X.stdin.writableLength>pq)W(),x.end({reason:"input_backpressure"})},Buffer.byteLength(B))},close:W}}var a={smooth:{fps:60,crf:23,kbps:8000,x264Preset:"ultrafast",threads:2,scale:1},sharp:{fps:30,crf:19,kbps:1e4,x264Preset:"superfast",scale:1},data_saver:{fps:20,crf:28,kbps:2000,x264Preset:"ultrafast",scale:0.75},balanced:{fps:30,crf:23,kbps:4000,x264Preset:"ultrafast",threads:2,scale:1}},Ex="avc1.4D002A",Iq={width:1920,height:1080},Ox=262144,$x=0.2,Hx=250,fx=1e4,hx=1024,l8=1e4,gx=500,px=60,kx=1e4,Ix=1000,vq=1048576,oq={kind:"mac_screen",sound:null},vx,uq=()=>vx??=k()?.ffmpeg??null,a8=(q,x,X)=>d8(q,x,{env:X,stdio:["ignore","pipe","ignore"]}),ux,s8=()=>ux??=Oq(k()),cq=(q,x,X)=>{let[Q,...P]=[...s8(),q];return a8(Q,[...P,...x],X)},lq=()=>P0?.videotoolbox?"h264_videotoolbox":"libx264",cx=()=>Math.round(performance.now()*1000),r8=new Set,rq=!1;function tq(q){if(r8.add(q),q.once("exit",()=>r8.delete(q)),rq)return;rq=!0,process.once("exit",()=>{for(let x of r8)try{x.kill("SIGKILL")}catch{}})}function eq(q){try{q.stdout?.destroy()}catch{}if(q.exitCode!==null||q.signalCode!==null)return;try{q.kill("SIGTERM")}catch{return}let x=setTimeout(()=>{if(q.exitCode===null&&q.signalCode===null)try{q.kill("SIGKILL")}catch{}},gx);q.once("exit",()=>clearTimeout(x))}function lx(q,x,X){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(q),"-video_size",`${x.width}x${x.height}`,"-i",X],size:x}}function rx(q){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(q),"-i","Capture screen 0:none"],size:null}}function mx(q){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(q),"-i","pipe:0"],size:null}}var q0=1700000;function x0(q){return Math.min(1,Math.round(Math.sqrt(q0/(q.width*q.height))*100)/100)}function dx(q,x,X){let Q=d8(X.axe,["stream-video","--udid",X.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,x0(X.size)))],{stdio:["ignore","pipe","ignore"]}),P=d8(q,x,{env:{},stdio:["pipe","pipe","ignore"]});Q.stdout.pipe(P.stdin),P.stdin.on("error",()=>{});let b=()=>{if(Q.exitCode===null&&Q.signalCode===null)Q.kill("SIGTERM")};return P.once("exit",b),P.once("error",b),Q.once("exit",()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")}),Q.once("error",()=>{if(P.exitCode===null&&P.signalCode===null)P.kill("SIGTERM")}),P}function ax(q){let x=Math.min(1,Iq.width/q.width,Iq.height/q.height);return{width:Math.round(q.width*x),height:Math.round(q.height*x)}}function m8(q,x,X,Q="libx264"){let P=a[q],b=(R)=>Math.max(2,Math.floor(R/2)*2),J={width:b(X.width*P.scale),height:b(X.height*P.scale)},y=J.width!==x.size?.width||J.height!==x.size.height,C=Math.max(1,Math.round(P.kbps*2/P.fps)),W=["-g",String(P.fps*px)],j=Q==="h264_videotoolbox"?["-c:v","h264_videotoolbox","-realtime","1","-prio_speed","1","-allow_sw","1","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","nv12",...W,"-b:v",`${P.kbps}k`,"-maxrate",`${P.kbps}k`,"-bufsize",`${C}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",P.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...P.threads?["-threads",String(P.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...W,"-crf",String(P.crf),"-maxrate",`${P.kbps}k`,"-bufsize",`${C}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...x.args,"-an",...y?["-vf",`scale=${J.width}:${J.height}:flags=fast_bilinear`]:[],...j,"-flush_packets","1","-f","h264","pipe:1"]}class X0{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(q,x){if(this.buffer.byteLength===0)this.micros=x;let X=new Uint8Array(this.buffer.byteLength+q.byteLength);X.set(this.buffer),X.set(q,this.buffer.byteLength),this.buffer=X;let Q=[],P=this.scanned;while(P+3<this.buffer.byteLength){if(this.buffer[P]!==0||this.buffer[P+1]!==0||this.buffer[P+2]!==1){P++;continue}let b=this.buffer[P+3]&31,J=P>0&&this.buffer[P-1]===0?P-1:P;if(b===9&&J>0)Q.push({data:this.buffer.slice(0,J),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(J),this.key=!1,this.micros=x,P-=J;if(b===5)this.key=!0;P+=3}return this.scanned=P,Q}}function sx(q,x){let X=_x({path:q}),Q=Buffer.alloc(0),P="version",b=0,J=!1,y=[],C=0,W=!1,j=(N)=>{if(W)return;W=!0,X.destroy(),x.end(N)},R=()=>j({reason:"display_protocol"}),Z=(N)=>{if(W)return;if(!J){if(C+=N.byteLength,C>vq)j({reason:"input_backpressure"});else y.push(N);return}if(X.write(N),X.writableLength>vq)j({reason:"input_backpressure"})},B=(N)=>{Q=Q.subarray(N)},Y=()=>{switch(P){case"version":{if(Q.byteLength<12)return!1;let N=/^RFB (\d{3})\.(\d{3})\n$/.exec(Q.subarray(0,12).toString("latin1"));if(!N||Number(N[1])*1000+Number(N[2])<3007)return R(),!1;return B(12),X.write(`RFB 003.007
|
|
177
|
+
`),P="security",!0}case"security":{if(Q.byteLength<1)return!1;let N=Q[0];if(N===0)return R(),!1;if(Q.byteLength<1+N)return!1;if(!Q.subarray(1,1+N).includes(1))return R(),!1;return B(1+N),X.write(Buffer.from([1,1])),P="init",!0}case"init":{if(Q.byteLength<24)return!1;let N=Q.readUInt32BE(20);if(N>65536)return R(),!1;if(Q.byteLength<24+N)return!1;let D={width:Q.readUInt16BE(0),height:Q.readUInt16BE(2)};if(B(24+N),D.width===0||D.height===0)return R(),!1;P="messages",J=!0;for(let G of y)X.write(G);return y=[],C=0,x.ready(D),!W}case"skip":{let N=Math.min(b,Q.byteLength);if(B(N),b-=N,b>0)return!1;return P="messages",!0}case"messages":{if(Q.byteLength<1)return!1;switch(Q[0]){case 1:{if(Q.byteLength<6)return!1;let N=6+Q.readUInt16BE(4)*6;if(Q.byteLength<N)return!1;return B(N),!0}case 2:return B(1),!0;case 3:{if(Q.byteLength<8)return!1;let N=Q.readUInt32BE(4);if(N>H/2)return B(8),P="skip",b=N,!0;if(Q.byteLength<8+N)return!1;let D=Q.subarray(8,8+N).toString("latin1");return B(8+N),x.clipboard(D),!W}default:return R(),!1}}}},w=!1;return X.once("connect",()=>{w=!0}),X.on("data",(N)=>{if(W)return;Q=Q.byteLength?Buffer.concat([Q,N]):N;while(!W&&Y());}),X.once("error",()=>{if(!w)j({error:new M("display_unavailable","Reason could not reach this machine's desktop server.")})}),X.once("close",()=>j({reason:"display_closed"})),{pointer(N,D,G){let F=Buffer.alloc(6);F.writeUInt8(5,0),F.writeUInt8(G&255,1),F.writeUInt16BE(N,2),F.writeUInt16BE(D,4),Z(F)},key(N,D){let G=Buffer.alloc(8);G.writeUInt8(4,0),G.writeUInt8(N?1:0,1),G.writeUInt32BE(D>>>0,4),Z(G)},clipboard(N){if(Array.from(N).some((F)=>F.codePointAt(0)>255)){j({reason:"clipboard_unicode_unsupported"});return}let D=Buffer.from(N,"latin1"),G=Buffer.alloc(8);G.writeUInt8(6,0),G.writeUInt32BE(D.byteLength,4),Z(Buffer.concat([G,D]))},close(){W=!0,X.destroy()}}}class i8{run=null;viewers=new Set;get running(){return this.run!==null}start(q,x,X,Q){this.viewers.add(q),this.stop();let P;try{P=X()}catch{this.fail();return}tq(P);let b={child:P,splitter:new X0};this.run=b;for(let y of[...this.viewers])y.started(x);P.stdout?.on("data",(y)=>{if(this.run!==b)return;for(let C of b.splitter.push(y,Q()))for(let W of[...this.viewers])W.unit(C)});let J=()=>{if(this.run!==b)return;this.run=null,this.fail()};P.once("exit",J),P.once("error",J)}leave(q){if(!this.viewers.delete(q))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;eq(this.run.child),this.run=null}fail(){for(let q of[...this.viewers])q.failed()}}var mq=new WeakMap;function ix(q){let x=mq.get(q);if(!x)mq.set(q,x=new i8);return x}function Q0(q,x,X={}){let Q=X.micros??cx,P=new sq,b=x.request.preset,J=null,y=null,C=null,W=!1,j=null,R=!1,Z=!1,B=null,Y=0,w=0,N=!1,D=null,G=null,F=0,O=null,z=[],i=0,A=[],f=new Uint32Array(l8+1),I=0,C8=null,S8=0,n=0,Z8=0,qq=0,xq=0,X8=null,A8=0,u={frames:0,bytes:0,since:Q()},c=[],o=0,G8,F8=!1,C0=Q(),E={},l=()=>Math.round((Q()-C0)/1000),Xq=X.control??$q,w8=null,V8=null,$=(L)=>{let U=T8(L);return q.send(U),qq+=U.byteLength,U.byteLength},Q8=(L)=>{if(q.done)return;if(q.open)$({type:"error",code:L});q.end({reason:L})},P8=()=>Math.max(Ox,a[b].kbps*1000/8*$x),b8=()=>Q()/1000,S0=()=>{while(A.length>1&&A[0].atMs<b8()-fx)A.shift();return A[0]?.rttMs??null},Qq=(L)=>{let U=S0();if(U===null||z.length===0)return!1;let T=(U+Hx)*L;return b8()-z[0].sentMs>T||i>T/1000*a[b].kbps*1000/8},Z0=(L)=>{if(F===0)return;let U=Math.min(L,F-1);if(O!==null&&U<=O)return;O=U;let T=b8();while(z.length&&z[0].seq<=U){let V=z.shift();if(i-=V.bytes,V.seq!==U)continue;let K=Math.max(0,T-V.sentMs);while(A.length&&A.at(-1).rttMs>=K)A.pop();A.push({atMs:T,rttMs:K}),f[Math.min(l8,Math.round(K))]++,I++,C8=Math.min(C8??K,K)}},A0=()=>{let L=0;for(let U=0;U<=l8;U++)if(L+=f[U],L*2>=I)return U;return 0},G0=()=>q.bufferedAmount<=P8()/2&&!Qq(0.5),Pq=()=>{F8=!0,c=[],o=0,j?.leave(K8),j=null},bq=(L)=>{if(q.done)return;if(L.key)E.first_key_ms??=l();if(!W){if(!j||c.length===0&&!L.key)return;if(c.push(L),o+=L.data.byteLength,o>P8())Pq();return}if(N){n++;return}if(q.bufferedAmount>P8()||Qq(1)){N=!0,n++,D=setInterval(()=>{if(q.done||!G0())return;if(D)clearInterval(D);D=null,N=!1,Y8()},X.drainPollMs??25);return}if(!R){if(!L.key){n++;return}if($({type:"hello",width:y.width,height:y.height,fps:a[b].fps,preset:b,codec:Ex}),R=!0,E.first_frame_ms??=l(),!Z&&J?.sound)$({type:"audioHello",...x8}),Z=!0}let U=$({type:"frame",key:L.key,seq:F,captureMicros:L.micros,data:L.data});if(z.push({seq:F,sentMs:b8(),bytes:U}),i+=U,z.length>hx)i-=z.shift().bytes;F++,S8++,X8??=L.micros,A8=L.micros,u.frames++,u.bytes+=U},K8={started(L){b=L,R=!1,c=[],o=0},unit:bq,failed:()=>Q8("encoder_failed")},M8=()=>{let L=(X.ffmpeg??uq)();if(!J||!y){Q8("encoder_failed");return}let[U,T]=[J,y],V="kind"in U&&U.kind==="simulator"?U.stream:null;if(!L&&!V){Q8("encoder_failed");return}if(j??="kind"in U&&U.kind==="mac_screen"?ix(X.spawn??cq):new i8,E.encoder_ms===void 0)E.encoder_ms=l(),E.encoder_shared=j.running;j.start(K8,b,()=>{let K=a[b].fps;if(V)return V(K,a[b].kbps,q0);if("kind"in U&&U.kind==="simulator"){let h=Math.min(0.99,x0(U.size)),t={width:U.size.width*h,height:U.size.height*h};return dx(L,m8(b,mx(Math.min(K,30)),t,(X.macEncoder??lq)()),U)}return"kind"in U?(X.spawn??cq)(L,m8(b,rx(K),ax(T),(X.macEncoder??lq)()),{}):(X.spawn??a8)(L,m8(b,lx(K,T,U.display),T),{DISPLAY:U.display,XAUTHORITY:U.xauthority})},Q)},J8=()=>{if(!B)return;eq(B.child),B=null},F0=()=>{let L=(X.ffmpeg??uq)();if(B||q.done||!Z||!J?.sound||!L)return;let U;try{U=(X.spawn??a8)(L,gq(),{PULSE_SERVER:j8(J.sound)})}catch{return}tq(U);let T={child:U,reader:new c8};B=T,U.stdout?.on("data",(K)=>{if(B!==T||q.done)return;let h;try{h=T.reader.push(K)}catch{J8();return}let t=Q();for(let w0 of h){if(q.bufferedAmount>P8()){w++;continue}$({type:"audio",captureMicros:t,data:w0}),Y++}});let V=()=>{if(B===T)J8()};U.once("exit",V),U.once("error",V)},Y8=()=>{if(!j||q.done)return;Z8++,M8()},Jq=()=>{if(q.done||!y)return;if(!W){if(j||F8)return;M8(),G8=setTimeout(()=>{if(!W)Pq()},kx);return}if(clearTimeout(G8),E.encoder_early===void 0){if(E.encoder_early=j!==null,F8)E.hold_lapsed=!0}if(!j)M8();let L=c;c=[],o=0;for(let U of L)bq(U);G??=setInterval(()=>{let U=Q(),T=Math.max(0.001,(U-u.since)/1e6);$({type:"stats",stats:{fps:Math.round(u.frames/T*10)/10,kbps:Math.round(u.bytes*8/1000/T),dropped:n,restarts:Z8,queued_bytes:q.bufferedAmount}}),u={frames:0,bytes:0,since:U}},Ix)};x.desktop.then((L)=>{if(q.done)return;J=L;let U={ready(T){y=T,E.desktop_ms??=l(),Jq()},clipboard(T){if(q.open&&Buffer.byteLength(T)<=H)$({type:"serverClipboard",text:T})},end(T){if("reason"in T&&q.open)$({type:"error",code:T.reason});q.end(T)}};if("kind"in L&&L.kind==="simulator")C=L.input,U.ready(L.points);else if("kind"in L)C=(X.macInput??((T)=>nq(T,s8())))(U);else{let T=(X.linuxClipboard??kq)(L,U),V=sx(L.rfbSocket,{...U,clipboard:(K)=>{if(!T)U.clipboard(K)}});C=T?{pointer:(K,h,t)=>T.apply(()=>V.pointer(K,h,t)),key:(K,h)=>T.apply(()=>V.key(K,h)),clipboard:(K)=>T.write(K),close(){T.close(),V.close()}}:V}Nq()},(L)=>q.end({error:L}));function Nq(){if(V8||!x.viewerSameNetwork||!W||q.done||!J||!("kind"in J)||J.kind!=="mac_screen")return;V8=(X.macWindows??iq)((L)=>{if(q.open)$({type:"windows",bounds:L})})}let Wq={viewer:x.viewer??null,notify(L){if(q.open)$({type:"control",control:L})}},z8=(L)=>{if(!C)return;if(!J||!("kind"in J)||J.kind!=="simulator")Xq.claim(Wq);L(C)};return{opened(){E.relay_ms??=l()},received(L){xq+=L.byteLength;let U;try{U=P.push(L)}catch{Q8("viewer_protocol");return}for(let T of U){if(q.done)return;switch(T.type){case"ping":$({type:"pong",token:T.token});break;case"pointer":z8((V)=>V.pointer(T.x,T.y,T.buttons));break;case"key":z8((V)=>V.key(T.down,T.keysym));break;case"clientClipboard":z8((V)=>V.clipboard(T.text));break;case"config":if(T.preset!==b)b=T.preset,Y8();break;case"keyframeRequest":if(R&&!N)Y8();break;case"ack":Z0(T.seq);break;case"audioEnable":if(T.on)F0();else J8();break;default:break}}if(!W&&!q.done){if(W=!0,E.viewer_ms=l(),x.viewer)w8=Xq.join(Wq);Jq(),Nq()}},close(){if(w8?.(),w8=null,V8?.close(),D)clearInterval(D);if(G)clearInterval(G);clearTimeout(G8),j?.leave(K8),J8(),C?.close()},summary:()=>({output_bytes:qq,input_bytes:xq,video:{preset:b,frames:S8,dropped:n,restarts:Z8,avg_fps:X8!==null&&A8>X8?Math.round((S8-1)/((A8-X8)/1e6)*10)/10:0,min_rtt_ms:Math.round(C8??0),p50_rtt_ms:I?A0():0,audio_packets:Y,audio_dropped:w,connect:E}})}}var dq=null,P0=null,nx=null;function ox(){let q=k();return q?.features.display?q.ffmpeg:null}function b0(q){return dq??=new Promise((x)=>{Yx(q,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(X,Q)=>{let P=(b)=>!X&&new RegExp(`^\\s*V\\S*\\s+${b}\\s`,"m").test(Q);x(P0={x264:P("libx264"),videotoolbox:P("h264_videotoolbox")})})}),dq}var aq=null;function HX(){return aq??=(async()=>{let q=[k()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((X)=>Boolean(X&&zx(X)));if(!q)return null;let x=await b0(q);return x.videotoolbox||x.x264?q:null})(),aq}function J0(q=process.platform,x={}){if(q!=="linux"&&q!=="darwin")return Promise.resolve(!1);let X=(x.ffmpeg??ox)();if(!X)return Promise.resolve(!1);let Q=(x.encoders??b0)(X);if(q==="linux")return Q.then((b)=>b.x264);let P=x.macScreen?x.macScreen():nx??=$8(s8());return Promise.all([Q,P]).then(([b,J])=>(b.x264||b.videotoolbox)&&J?.screen===!0&&J.accessibility)}var J1=43200000,B8=":99",N1=60000,R8=15000,t8={width:1280,height:800},W1=/^[A-Za-z0-9._:-]{1,160}$/;function U1(q){return Boolean(q)&&typeof q==="object"&&!Array.isArray(q)}var L1=["video","viewer","viewer_same_network","viewer_network"];function y1(q,x=Date.now()){let X=["relay_url","session_id","expires_at"];if(!U1(q)||X.some((y)=>!(y in q))||Object.keys(q).some((y)=>!X.includes(y)&&!L1.includes(y)))throw new M("invalid_display_request","Reason desktop request is malformed.");let Q="video"in q?y0(q.video):void 0,P="viewer"in q?L0(q.viewer):null;if(Q===null)throw new M("invalid_display_request","Reason desktop video request is invalid.");let b=null;try{b=typeof q.relay_url==="string"?new URL(q.relay_url):null}catch{}if(!b||b.protocol!=="wss:"&&b.protocol!=="ws:"||b.username||b.password)throw new M("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof q.session_id!=="string"||!W1.test(q.session_id))throw new M("invalid_display_request","Reason desktop session identity is invalid.");let J=typeof q.expires_at==="string"?Date.parse(q.expires_at):Number.NaN;if(!Number.isFinite(J)||J<=x)throw new M("invalid_display_request","Reason desktop session has already expired.");return{relay_url:q.relay_url,session_id:q.session_id,expires_at:new Date(Math.min(J,x+J1)).toISOString(),...Q?{video:Q}:{},...P?{viewer:P}:{},...Q&&q.viewer_same_network===!0?{viewer_same_network:!0}:{}}}function j1(q=process.platform){return(q==="linux"||q==="darwin")&&k()?.features.display===!0}async function nX(){if(process.platform!=="darwin")return j1();return await J0()}function D8(q){X1(q,{recursive:!0,mode:448});let x=x1(q);if(!x.isDirectory()||x.isSymbolicLink()||process.getuid&&x.uid!==process.getuid())throw new M("display_unavailable","Reason desktop state directory is not private.");q1(q,448)}function T1(q,x){let X=(P)=>{let b=Buffer.alloc(2);return b.writeUInt16BE(P.length),Buffer.concat([b,P])},Q=Buffer.from([255,255]);return Buffer.concat([Q,X(Buffer.alloc(0)),X(Buffer.from(q)),X(Buffer.from("MIT-MAGIC-COOKIE-1")),X(x)])}function s(q,x,X=2000){return new Promise((Q)=>{let P=b1(q),b="",J=(y)=>{P.destroy(),Q(y)};P.setTimeout(X,()=>J(!1)),P.once("error",()=>J(!1)),P.once("close",()=>J(!1)),P.once("connect",()=>{if(!x)J(!0)}),P.on("data",(y)=>{if(b+=y.toString("latin1"),b.length>=4)J(b.startsWith("RFB "))})})}async function D0(q,x){let X=Date.now()+x;while(Date.now()<X){if(await q())return!0;await new Promise((Q)=>setTimeout(Q,100))}return!1}function e8(q,x,X){return new Promise((Q)=>{let P=T0(q,x,{detached:!0,stdio:"ignore",env:X});P.once("error",()=>Q(-1)),P.once("exit",(b)=>Q(b)),P.unref(),setTimeout(()=>Q(null),R8).unref()})}var n8=null;function B1(q=d()){return n8??=D1(q).finally(()=>{n8=null}),n8}async function D1(q){let x=k({home:q});if(!x?.xvfb||!x.x11vnc||!x.openbox)throw new M("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");W0({root:x.root,automation:x.automation,extensionDir:x.extensionDir});let X=_(x.root,"display");D8(X);let Q=await C1(q,X,x.x11vnc);if(Q)return Q;let P={display:B8,xauthority:_(X,"Xauthority"),rfbSocket:_(X,"rfb.sock")},b=_(X,"pulse"),J=(async()=>{try{D8(b)}catch{return null}return await hq(b,x.pulseaudio)})(),y=_(X,"home");D8(y);let C={HOME:y,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:P.display,XAUTHORITY:P.xauthority};if(x.pulseaudio)C.PULSE_SERVER=j8(u8(b));let W=async()=>({...P,sound:await J});if(await s({path:P.rfbSocket},!0))return await W();if(!B0(P.xauthority))o8(P.xauthority,T1(B8.slice(1),ex(16)),{mode:384,flag:"wx"});let j=S1(_(X,"theme"),P.display),R={path:`/tmp/.X11-unix/X${B8.slice(1)}`};if(!await s(R,!1)){if(e8(x.xvfb,[P.display,"-screen","0",`${t8.width}x${t8.height}x24`,"-nolisten","tcp","-auth",P.xauthority],C),!await D0(()=>s(R,!1),R8))throw new M("display_unavailable","Reason could not start the virtual display.");e8(x.openbox,["--config-file",j.openboxConfig],C)}if(await Z1(j,C),!await R0(x.x11vnc,P,X,"x11vnc.log",C))throw new M("display_unavailable","Reason could not start the desktop server.");return await W()}async function R0(q,x,X,Q,P){if(await s({path:x.rfbSocket},!0))return!0;P1(x.rfbSocket,{force:!0});let b=await e8(q,["-display",x.display,"-auth",x.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",x.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",_(X,Q)],P);if(b!==null&&b!==0)return!1;return await D0(()=>s({path:x.rfbSocket},!0),R8)}async function R1(){let q=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],x=(X)=>Object.fromEntries(q.flatMap((Q)=>X[Q]?[[Q,X[Q]]]:[]));if(process.env.DISPLAY)return x(process.env);try{let X=await new Promise((Q,P)=>tx("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(b,J)=>b?P(b):Q(J)));return x(Object.fromEntries(X.split(`
|
|
178
|
+
`).flatMap((Q)=>{let P=Q.indexOf("=");return P>0?[[Q.slice(0,P),Q.slice(P+1)]]:[]})))}catch{return{}}}var N0=new Set;async function C1(q,x,X){let Q=await R1(),P=/^:(\d+)(?:\.\d+)?$/.exec(Q.DISPLAY??"")?.[1];if(!P||`:${P}`===B8||Q.WAYLAND_DISPLAY||Q.XDG_SESSION_TYPE==="wayland")return null;let b={display:`:${P}`,xauthority:Q.XAUTHORITY??_(q,".Xauthority"),rfbSocket:_(x,`rfb-${P}.sock`)},J=`${b.display} ${b.xauthority}`;if(N0.has(J)||!await s({path:`/tmp/.X11-unix/X${P}`},!1))return null;let y={HOME:q,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:b.display,XAUTHORITY:b.xauthority};if(await R0(X,b,x,`x11vnc-${P}.log`,y))return{...b,sound:null};return N0.add(J),process.stderr.write(`Reason worker: your screen ${b.display} could not be served; using the virtual desktop
|
|
179
|
+
`),null}function S1(q,x){let X=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,Q=[["terminal","xterm"],["files","pcmanfm"]].filter(([,b])=>!B0(`/usr/bin/${b}`)).map(([b])=>b),P=Rq({root:q,display:x,screen:t8,browserExec:X,absent:Q});for(let b of["","openbox","tint2","picom"])D8(_(q,b));for(let[b,J]of Object.entries(P.files))o8(_(q,b),J,{mode:384});for(let[b,J]of Object.entries(Dq))o8(_(q,`ara-${b}`),Q1(J),{mode:384});return{root:q,openboxConfig:_(q,"openbox","rc.xml"),start:P.start}}async function Z1(q,x){let X=[`ROOT=${JSON.stringify(q.root)}`,...q.start,"openbox --reconfigure >/dev/null 2>&1 || true"].join(`
|
|
180
|
+
`);await new Promise((Q)=>{let P=T0("/bin/sh",["-c",X],{stdio:"ignore",env:{...x,PATH:"/usr/bin:/bin"}}),b=setTimeout(()=>{P.kill(),Q()},R8);P.once("error",()=>{clearTimeout(b),Q()}),P.once("exit",()=>{clearTimeout(b),Q()})})}async function oX(q,x={}){let X=x.now??Date.now,Q=y1(q.payload,X());if(q.signal.throwIfAborted(),!Q.video)throw new M("display_video_required","Reason desktops stream as video now; this request came without it.");let P=x.platform??process.platform;if(P!=="linux"&&P!=="darwin")throw new M("display_video_unsupported","This machine does not serve desktop video.");let b=Q.video,J=(x.video?.desktop??(P==="darwin"?async()=>oq:B1))();return await A1(q.signal,Q,x,X,(y)=>Q0(y,{request:b,desktop:J,...Q.viewer?{viewer:Q.viewer}:{},viewerSameNetwork:Q.viewer_same_network===!0},x.video),(y)=>T8({type:"error",code:y}))}function A1(q,x,X,Q,P,b){let J=Q();return new Promise((y,C)=>{let W=null,j=!1,R=!1,Z,B,Y,w=!1,N=null,D=(A)=>{if(R)return;if(N)A=N;R=!0,clearTimeout(Z),clearTimeout(B),q.removeEventListener("abort",F),Y?.close();try{W?.close(1000,"display_session_over")}catch{}if("error"in A){C(A.error);return}y({reason:A.reason,...Y?.summary(),duration_ms:Math.max(0,Q()-J)})},G=()=>D({error:new M("display_relay_unavailable","Reason could not reach the desktop relay.")}),F=()=>{let A=q.reason;D({error:A instanceof M?A:new M("cancelled","Reason closed the desktop session.")})},O=()=>{if(!N||!W)return;let A=N.error;try{W.send(b(A instanceof M?A.code:"display_unavailable"))}catch{}D(N)};if(Y=P({get done(){return R||N!==null},get open(){return j&&!R&&N===null},get bufferedAmount(){return W?.bufferedAmount??0},send(A){if(R||N||!j||!W)return;try{W.send(A)}catch{D({reason:"relay_closed"})}},end:(A)=>{if(R||N)return;if(!("error"in A)){D(A);return}if(N=A,w&&j)O()}}),R){Y.close();return}if(q.aborted){F();return}q.addEventListener("abort",F,{once:!0}),Z=setTimeout(()=>D({reason:"session_expired"}),Math.max(1,Date.parse(x.expires_at)-Q())),B=setTimeout(()=>D({reason:"viewer_absent"}),X.viewerWaitMs??N1);try{W=(X.connect??j0)(x.relay_url,(X.loadProxy??U0)()?.url)}catch{G();return}W.binaryType="arraybuffer",W.onopen=()=>{if(R||!W)return;j=!0,Y?.opened()},W.onmessage=(A)=>{if(R)return;let f=A.data,I=f instanceof ArrayBuffer?new Uint8Array(f):ArrayBuffer.isView(f)?new Uint8Array(f.buffer,f.byteOffset,f.byteLength):null;if(!I||I.byteLength===0)return;if(clearTimeout(B),w=!0,N){O();return}Y?.received(I)},W.onclose=()=>{if(R)return;if(!j){G();return}D({reason:"relay_closed"})},W.onerror=()=>{if(R||j)return;G()}})}
|
|
181
|
+
export{_8 as ie,f1 as je,p1 as ke,r as le,j8 as me,HX as ne,J0 as oe,Cq as pe,zq as qe,k as re,UX as se,LX as te,yX as ue,J1 as ve,B8 as we,y1 as xe,j1 as ye,nX as ze,D8 as Ae,B1 as Be,oX as Ce};
|