@reason-machines/cli-linux-x64 0.2.509 → 0.2.512
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/THIRD_PARTY_NOTICES.txt +0 -50
- package/bin/reason +2 -2
- package/bin/vm-hands/api-credentials-tsbx6cpa.js +2 -0
- package/bin/vm-hands/api-nwnptsbc.js +2 -0
- package/bin/vm-hands/connect-cli-ymqe88y2.js +2 -0
- package/bin/vm-hands/credentials-pgsb4v9j.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-57hkdy1z.js +2 -0
- package/bin/vm-hands/desktop-account-j6fjngt1.js +2 -0
- package/bin/vm-hands/device-workspace-qjyzphga.js +2 -0
- package/bin/vm-hands/{fsevents-x66t2ncp.js → fsevents-sw63c1nr.js} +1 -1
- package/bin/vm-hands/hands-worker-source-xjbrgfar.js +2 -0
- package/bin/vm-hands/{index-rdm4a3y7.js → index-j4gb3cze.js} +10 -10
- package/bin/vm-hands/install-receipt-y7exc4wh.js +2 -0
- package/bin/vm-hands/local-automation-ta2k7hz3.js +2 -0
- package/bin/vm-hands/local-capabilities-8xm0j4yv.js +2 -0
- package/bin/vm-hands/local-desktop-users-q0391ha1.js +2 -0
- package/bin/vm-hands/local-display-mac-7pg0n3zs.js +2 -0
- package/bin/vm-hands/local-display-session-36ypnvvr.js +2 -0
- package/bin/vm-hands/local-display-video-xaxjazsp.js +2 -0
- package/bin/vm-hands/local-managed-process-c1pd7k4g.js +2 -0
- package/bin/vm-hands/local-pty-session-q06ff8yk.js +2 -0
- package/bin/vm-hands/managed-runtime-cf3m8ygn.js +2 -0
- package/bin/vm-hands/network-contract-6mkf58vs.js +2 -0
- package/bin/vm-hands/package-sng72tm1.js +2 -0
- package/bin/vm-hands/permissions-mtp3nv7w.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-zf7bpqwe.js +2 -0
- package/bin/vm-hands/serve-service-612sfna9.js +2 -0
- package/bin/vm-hands/status-vc1z4d4q.js +10 -0
- package/bin/vm-hands/version-3fc9wwez.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-kkfefpq6.js → vm-hands-entry-lite-024t90qh.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-12r5xwkb.js → vm-hands-entry-lite-08fnapbd.js} +10 -10
- package/bin/vm-hands/{vm-hands-entry-lite-7777m86y.js → vm-hands-entry-lite-0gj3p9tg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-y2khvb5c.js → vm-hands-entry-lite-0sh835na.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-5gevvgec.js → vm-hands-entry-lite-1ek3r3w9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-c67nmnex.js → vm-hands-entry-lite-1zd088yv.js} +25 -25
- package/bin/vm-hands/{vm-hands-entry-lite-bw9g69x1.js → vm-hands-entry-lite-21pw3ra3.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-38g65s5x.js → vm-hands-entry-lite-39qv4sqt.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-8pgdcdsm.js → vm-hands-entry-lite-3p7zk3yt.js} +4 -4
- package/bin/vm-hands/vm-hands-entry-lite-42117xc5.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-yg9zb1nr.js → vm-hands-entry-lite-55mpsgz3.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-4kp6abst.js → vm-hands-entry-lite-58yq5qb3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-w1958mev.js → vm-hands-entry-lite-5np5k3wb.js} +4 -4
- package/bin/vm-hands/vm-hands-entry-lite-60pnam39.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-64b6nx6h.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-txd50spx.js → vm-hands-entry-lite-70hq7mrs.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-fzbqk2qx.js → vm-hands-entry-lite-7p4qsm5s.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-4483nna7.js → vm-hands-entry-lite-8z4k86tg.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-t8c42p62.js → vm-hands-entry-lite-ac708gr9.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-bqqfmgaz.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-np07qyeq.js → vm-hands-entry-lite-ckezse0f.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hqm76r37.js → vm-hands-entry-lite-dcrz19xf.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-3c5n0wm3.js → vm-hands-entry-lite-fa71c1fj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-t6f1f51j.js → vm-hands-entry-lite-fqas8pts.js} +9 -9
- package/bin/vm-hands/{vm-hands-entry-lite-1kkqgavp.js → vm-hands-entry-lite-h2j0q0en.js} +20 -20
- package/bin/vm-hands/{vm-hands-entry-lite-eabever7.js → vm-hands-entry-lite-k1wghndy.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-18cpkdc1.js → vm-hands-entry-lite-kjznqmwj.js} +39 -39
- package/bin/vm-hands/{vm-hands-entry-lite-cswyn85b.js → vm-hands-entry-lite-m7pkmatv.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rzpg99eh.js → vm-hands-entry-lite-pn8e1xf9.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-hyv23rd9.js → vm-hands-entry-lite-psjcmgj8.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-f62fvme8.js → vm-hands-entry-lite-pwmvq53c.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-vph99v9r.js → vm-hands-entry-lite-qz74j563.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-w2n56kvf.js → vm-hands-entry-lite-qzcac2mf.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-p62aaxk9.js → vm-hands-entry-lite-s3tt2trs.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-rfz60hb3.js → vm-hands-entry-lite-s85p7tqp.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-pdn0nt11.js → vm-hands-entry-lite-svd5v9dr.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-as5c1hre.js → vm-hands-entry-lite-tarerak1.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-wrvz9jxy.js → vm-hands-entry-lite-td73npv3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-3zeavsfr.js → vm-hands-entry-lite-vs47bs09.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-vwxg4fhe.js +42 -0
- package/bin/vm-hands/{vm-hands-entry-lite-nqdstx24.js → vm-hands-entry-lite-wp0d65yx.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-tvgb94jk.js → vm-hands-entry-lite-wx1fmrbs.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-51y3fyms.js → vm-hands-entry-lite-xynhzesa.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-x1b0sm48.js → vm-hands-entry-lite-ymqb2927.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-f5501hn3.js → vm-hands-entry-lite-zc8fsn2e.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-6ex6edrw.js → vm-hands-executor-yk90fyff.js} +3 -3
- package/bin/vm-hands/vm-hands-op-runner-545vwzvp.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-c68t42yc.js → vm-hands-runtime-wr0m4gny.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-6kk98y4k.js +2 -0
- package/bin/vm-hands/worker-sandbox-j6cmex8e.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-87hn92f0.js +0 -2
- package/bin/vm-hands/api-yg04rftf.js +0 -2
- package/bin/vm-hands/connect-cli-f1hg3trw.js +0 -2
- package/bin/vm-hands/credentials-zsgek373.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-0a5wjyh6.js +0 -2
- package/bin/vm-hands/desktop-account-ythxv2x5.js +0 -2
- package/bin/vm-hands/device-workspace-pt07525s.js +0 -2
- package/bin/vm-hands/hands-worker-source-5sk272dx.js +0 -2
- package/bin/vm-hands/install-receipt-d5489knb.js +0 -2
- package/bin/vm-hands/local-automation-627gg3ya.js +0 -2
- package/bin/vm-hands/local-capabilities-1tap81zp.js +0 -2
- package/bin/vm-hands/local-desktop-users-gham2z3k.js +0 -2
- package/bin/vm-hands/local-display-mac-fnp3317m.js +0 -2
- package/bin/vm-hands/local-display-session-q2vbnpr2.js +0 -2
- package/bin/vm-hands/local-display-video-4kcndnqg.js +0 -2
- package/bin/vm-hands/local-managed-process-nzpq335j.js +0 -2
- package/bin/vm-hands/local-pty-session-7yr8cm6d.js +0 -2
- package/bin/vm-hands/managed-runtime-ptn52m9d.js +0 -2
- package/bin/vm-hands/network-contract-cvqgd243.js +0 -2
- package/bin/vm-hands/package-datdmd5r.js +0 -2
- package/bin/vm-hands/permissions-xp4389xm.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-8fgk2s53.js +0 -2
- package/bin/vm-hands/serve-service-5q4prte5.js +0 -2
- package/bin/vm-hands/status-dqabww8t.js +0 -10
- package/bin/vm-hands/version-q9df1yye.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-439wxzv9.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-h3r57pgb.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-js4cr7bc.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-t5r1sy9z.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-vx0ht58w.js +0 -42
- package/bin/vm-hands/vm-hands-op-runner-p3h06gcq.js +0 -2
- package/bin/vm-hands/worker-preview-readiness-5myda114.js +0 -2
- package/bin/vm-hands/worker-sandbox-phfz1pj5.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We,
|
|
2
|
+
import{We,fo,F,Ve,Ut,Rr,x}from"./vm-hands-entry-lite-fqas8pts.js";import{K}from"./vm-hands-entry-lite-wx1fmrbs.js";import{dt}from"./vm-hands-entry-lite-k1wghndy.js";import{mt}from"./vm-hands-entry-lite-55mpsgz3.js";import{Or}from"./vm-hands-entry-lite-xynhzesa.js";import{At,ji}from"./vm-hands-entry-lite-024t90qh.js";import{G,qe}from"./vm-hands-entry-lite-pn8e1xf9.js";import{xe,Kn}from"./vm-hands-entry-lite-08fnapbd.js";import{vt}from"./vm-hands-entry-lite-vwxg4fhe.js";import{a}from"./vm-hands-entry-lite-0sh835na.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-qz74j563.js";import{spawn as R,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as M,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as U,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as pt,statSync as ft,writeFileSync as gt}from"fs";import{connect as ht}from"net";import{tmpdir as L,userInfo as we}from"os";import{basename as le,delimiter as wt,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -854,7 +854,7 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
|
|
|
854
854
|
process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
|
-
`;import{spawn as Te}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var De="__desktop-call",Me="/usr/bin/setpriv",Ue=27262976,Le=8192,$e=2000;function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],De]}function Ge(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function
|
|
857
|
+
`;import{spawn as Te}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var De="__desktop-call",Me="/usr/bin/setpriv",Ue=27262976,Le=8192,$e=2000;function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],De]}function Ge(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Bt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{Ge(e)}catch{}let s=n.command??Fe();return new Promise((i,u)=>{let c=(n.spawnProcess??Te)(Me,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,w,h=(y)=>{try{process.kill(-c.pid,y)}catch{c.kill(y)}},I=(y)=>{p??=y,h("SIGTERM"),w??=setTimeout(()=>h("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let _=(y)=>{if(g)return;g=!0,clearTimeout(w),t.removeEventListener("abort",S),y()};if(c.stdout.on("data",(y)=>{if(m+=y.byteLength,m>Ue)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(y)}),c.stderr.setEncoding("utf8").on("data",(y)=>{l=(l+y).slice(-Le)}),c.stdin.on("error",()=>{}),c.once("error",()=>_(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(y,Ee)=>_(()=>{if(p)return u(p);let b=Be(Buffer.concat(d).toString("utf8"));if(W(b)&&b.ok===!0&&W(b.result))return i(b.result);let O=W(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${y??Ee}${O?"":" with no reply"}`,Y=l.trim().split(`
|
|
858
858
|
`).at(-1)?.slice(-300)??"";if(!O||O.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
|
|
859
|
-
`);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Mt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>dt(e,o),tile:Rr,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(uo,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,_t=18874368,yt=8192,bt=65536,St=55000,kt=60000,Rt=4,It=40000,Ot=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function _e(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==vt||t.kind!=="browser")||JSON.stringify(t).length>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Ot.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Tn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Et="__computer-use";function Ms(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Ct(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pt=33554432;function Dt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Nt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Dt(await Ct(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(ft(m).size>Pt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Ut(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Ut(e.nativeHost,o,{socketDir:Tt(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ft){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&M(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((w)=>d(w)===l),instance:p,socket:g}))}async function $t(e,o,t=a(),n=Ft){let s=(await Lt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var q=new Map;function H(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function Bt(e,o){if(await pe(e))return;if(pt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",w,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...w,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function $s(e){await ve(e,!0)}function Bs(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!Wt(e.automation))return e.automation;if(!qt(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function Wt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function qt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function ve(e,o){xt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...Gt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Et};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await H("bus",()=>Bt(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Gt(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(wt)}}async function Ht(e,o,t){let n=we().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await $t(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;gt(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,w=(_)=>{if(p??=_,process.platform==="win32"&&c.pid){R(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(_)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),_()},I=setTimeout(()=>w(new r("automation_timed_out","Reason automation did not finish in time.")),St),S=()=>w(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>_t)w(new r("automation_output_too_large","Reason automation output is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(_)=>h(()=>{if(p)u(p);else i({code:_??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=Rt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Fs(e,o){let t=_e({call:e});if(!("call"in t))D();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=_e(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??mt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await $i(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),w;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),w=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)w=await(o.delegate??Q)(g,t.call,e.signal);else w=await Ae(s,t.call,e.signal,o)}finally{p()}if(i)w=await ie({runId:e.runId,call:t.call,identity:u,output:w,signal:e.signal},c);return fe(w,e.runId,n)}
|
|
860
|
-
export{
|
|
859
|
+
`);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Kn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>dt(e,o),tile:Or,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(fo,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,_t=18874368,yt=8192,bt=65536,St=55000,xt=60000,kt=4,Rt=40000,It=/^[0-9a-f-]{36}$/,ue=z,Ot=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function _e(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==vt||t.kind!=="browser")||JSON.stringify(t).length>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!It.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Et="__computer-use";function Fs(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Ct(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pt=33554432;function Dt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Nt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Dt(await Ct(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(ft(m).size>Pt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Mt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Mt(e.nativeHost,o,{socketDir:Tt(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ut){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&M(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((w)=>d(w)===l),instance:p,socket:g}))}async function $t(e,o,t=a(),n=Ut){let s=(await Lt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var q=new Map;function H(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function Wt(e,o){if(await pe(e))return;if(pt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Rr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",w,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Rr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let w=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...w,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),Rt),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function js(e){await ve(e,!0)}function Us(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!qt(e.automation))return e.automation;if(!Ft(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function qt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function Ft(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function ve(e,o){At({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...Gt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Et};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await H("bus",()=>Wt(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Gt(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(wt)}}async function Ht(e,o,t){let n=we().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await $t(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;gt(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,w=(_)=>{if(p??=_,process.platform==="win32"&&c.pid){R(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(_)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),_()},I=setTimeout(()=>w(new r("automation_timed_out","Reason automation did not finish in time.")),St),S=()=>w(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>_t)w(new r("automation_output_too_large","Reason automation output is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-yt)}),c.stdin.on("error",()=>{}),c.once("error",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(_)=>h(()=>{if(p)u(p);else i({code:_??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=kt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+xt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Hs(e,o){let t=_e({call:e});if(!("call"in t))D();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:Ot,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Tn(e,o={}){let t=_e(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??mt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await ji(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),w;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),w=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)w=await(o.delegate??Q)(g,t.call,e.signal);else w=await Ae(s,t.call,e.signal,o)}finally{p()}if(i)w=await ie({runId:e.runId,call:t.call,identity:u,output:w,signal:e.signal},c);return fe(w,e.runId,n)}
|
|
860
|
+
export{Bt,Pn,Fs,js,Us,Hs,Tn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
export{
|
|
2
|
+
var tr={name:"github-native-engineer-device-worker-production",version:"0.2.512",private:!0,type:"module",engines:{node:">=22",bun:">=1.3.0"},workspaces:["../../packages/runtime-distribution"],dependencies:{"@agentclientprotocol/sdk":"1.9.0","@anthropic-ai/sandbox-runtime":"^0.0.80","@earendil-works/pi-tui":"1.0.0","@reason/runtime-distribution":"workspace:*",diff:"8.0.4","open-browser-use-sdk":"0.1.42","playwright-core":"1.60.0",toml:"4.2.0",zod:"^4.4.3"},overrides:{"@hono/node-server":"^1.19.15","@earendil-works/pi-agent-core":"1.0.0","@earendil-works/pi-ai":"1.0.0","@earendil-works/pi-coding-agent":"1.0.0","@earendil-works/chord":"1.0.0","@earendil-works/pi-codemode":"1.0.0","@earendil-works/pi-mcp":"1.0.0","@earendil-works/pi-telemetry":"1.0.0","@earendil-works/pi-tui":"1.0.0","brace-expansion":"2.1.7",axios:"^1.20.0","basic-ftp":"^6.2.1","@grpc/grpc-js":"^1.14.5",browserslist:"^4.28.8","engine.io":"^6.6.7","fast-uri":"^3.1.8",hono:"^4.13.7","ip-address":"^10.7.1",nanoid:"^3.3.18",dompurify:"^3.4.17",postcss:"^8.5.23",qs:"^6.16.0","shell-quote":"^1.11.0","socket.io-parser":"^4.2.7",tmp:"^0.2.7",toml:"^4.2.0",undici:"^8.10.2",ws:"^8.21.0","js-yaml":"^4.3.2","@modelcontextprotocol/sdk":"^1.31.0","proxy-addr":"^2.0.8","source-map-js":"^1.2.2"}};
|
|
3
|
+
export{tr};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{Mo}from"./vm-hands-entry-lite-wp0d65yx.js";import{Fe,un,It,dn}from"./vm-hands-entry-lite-pwmvq53c.js";import{Yn}from"./vm-hands-entry-lite-42117xc5.js";import{t,o,d,u,i,hs,W,g,s,n}from"./vm-hands-entry-lite-qzcac2mf.js";var q=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(e){let r=typeof e==="string"?q.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var j=25,v=1e5,L=/^[0-9a-f]{64}$/,N=i({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(v),received:o().int().min(0).max(v)}),Te=i({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(j).optional(),message_counts:u(N).max(14).optional().catch(void 0),endpoint:t().regex(L).optional().catch(void 0)}),D=g("kind",[i({id:t(),kind:n("who"),all:d().optional()}),i({id:t(),kind:n("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),x=i({job:D.nullable(),retry_after_seconds:o().optional()}),H=i({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),F=i({person:t(),machine:t(),online:d()}),B=i({team:t().nullable(),sessions:u(H).max(2000),machines:u(F).max(500),all:d().optional()}),G=i({address:t().max(300),state:t().max(40),note:t().max(500)}),$e=W([i({who:B}),i({sent:i({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(G).max(500).optional()})}),i({error:t().min(1).max(2000)})]),J=i({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ue=i({messages:u(J).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional()});var P=["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 We=P.filter((e)=>e!=="network:read"&&e!=="network:write");class R extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Q(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new R(l,a)}async function K(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Q(m,`OAuth token request failed (${c.status})`);return m}var V=1e4;async function Y(e,r={}){let a=r.fetchImpl??fetch,l=await K(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(V)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new R("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new R("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return un(c,r.path??Fe()),c}var b=new Map,X=2000,Z=100;function C(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function Ot(e={}){let r=e.path??Fe(),a=It(r);if(!a)return null;let l=e.apiOrigin??T(process.env,"REASON_API_URL")?.trim();if(l&&!Mo(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=b.get(m);if(p)return C(p,e.signal);let f;return f=Y(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof R)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let S=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),E=Date.now()+X;while(!S(It(r))&&Date.now()<E)await new Promise((_)=>setTimeout(_,Z));if(S(It(r)))return Ot({fetchImpl:e.fetchImpl,path:r});return dn(r),null}).finally(()=>{if(b.get(m)===f)b.delete(m)}),b.set(m,f),C(f,e.signal)}var ee=i({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),ne=i({groups:u(i({selectable:d().optional(),accounts:u(i({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function te(e){let r=ne.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class I extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,r,a,l,c,m,p){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.refusal=p;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof I)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var se=["minimal","low","medium","high","xhigh","max"],oe=i({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(i({id:t().min(1),label:t()}))}),re=i({devices:u(oe),end_cursor:t().nullish(),has_next_page:d().optional()}),ie=i({id:t().min(1),name:t()}),ae=i({items:u(ie)}),le=i({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:i({color:t().nullish()}).nullish().catch(null)}),ce=i({items:u(le)}),de=i({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),ue=i({items:u(de).default([])}),me=i({id:t().min(1),kind:t(),enabled:d(),schedule:i({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:i({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),U=i({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(me).default([])}),ge=i({items:u(U).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),he=i({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),pe=i({items:u(he).default([])}),fe=i({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),A=i({tags:u(t()).default([])}),ye=s(["linux","macos"]),O=i({id:t().min(1),name:t().min(1),platform:ye.nullable(),workers:i({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:i({queued:o().int(),running:o().int()})}),_e=i({machines:u(O)}),Re=i({machine:O}),be=i({deleted:n(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),we=i({token:i({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),M=hs({machine_id:t().min(1),machine_name:t().min(1)}),Se=M.extend({organization_id:t().min(1)}),on=i({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var rn=W([i({kind:n("cloud")}),i({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new I(502,a,"Reason returned an unexpected response.");return l.data}var ke=i({error:i({type:t(),message:t()})});function w(e,r,a){let l=ke.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new I(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0,typeof r.code==="string"?{code:r.code,...typeof r.billing_path==="string"&&/^\/(?![/\\])/.test(r.billing_path)?{billingPath:r.billing_path}:{}}:void 0)}async function ks(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw w(r.status,a,r.headers.get("retry-after"));return h(Se,a,"invalid_machine_ticket")}class Qo{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw w(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch,c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Yn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await Ot({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof I&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(_e,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Re,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(be,r,"invalid_machine_deletion")}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(we,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(M,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:AbortSignal.timeout(30000)})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(x,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=ae.safeParse(e);if(!r.success)throw new I(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ce,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(i({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(ue,e,"invalid_skill_list").items}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=re.safeParse(l);if(!c.success)throw new I(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:se.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return k(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=ee.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=te(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof I&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw w(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof I)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof I&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. 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(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(A,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(A,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(fe,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(ge,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(U,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(i({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(pe,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
3
|
+
export{Ot,I,ks,Qo};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{statSync as f}from"fs";import{delimiter as l,join as d}from"path";function
|
|
3
|
-
export{
|
|
2
|
+
import{statSync as f}from"fs";import{delimiter as l,join as d}from"path";function $t(e,o=process.env.PATH??"",i=process.env,u=process.platform){let r=u==="win32",a=e.includes("/")||r&&e.includes("\\");if(!e||a||e.includes("\x00"))return!1;let c=r?["",...(i.PATHEXT??".EXE;.CMD;.BAT;.COM").split(";")]:[""];return o.split(l).some((t)=>{if(!t)return!1;return c.some((n)=>{if(n===void 0)return!1;try{let s=f(d(t,`${e}${n}`));if(!s.isFile())return!1;return r||(s.mode&73)!==0}catch{return!1}})})}
|
|
3
|
+
export{$t};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{E}from"./vm-hands-entry-lite-
|
|
3
|
-
`).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(E(s))continue;o.push(s)}return h(o)}function
|
|
2
|
+
import{E}from"./vm-hands-entry-lite-70hq7mrs.js";import{fe,Ie,Ne,Le,Me}from"./vm-hands-entry-lite-qz74j563.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var Cr=process.platform==="win32"?Ie("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=Cr.split(g),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Ne(),stdio:["ignore","pipe","ignore"]}),Le(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)Me(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function Ar(t,e=process.platform){let n=e==="win32",r=t.split(`
|
|
3
|
+
`).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(E(s))continue;o.push(s)}return h(o)}function xn(t){let e=t?.home??m(),n=t?.directoryExists??p,r=b.map((o)=>f(e,...o)).filter((o)=>{try{return n(o)}catch{return!1}});return h([...r,...process.platform==="win32"?Ar(process.env.PATH??process.env.Path??""):[],...P]).join(g)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:xn({home:t?.home,directoryExists:t?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!w(e))return n();let r;try{r=await(t?.runLoginShell??x)(e,["-lic",'printf %s "$PATH"'])}catch{return n()}if(Buffer.byteLength(r,"utf8")>S)return n();let o=Ar(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function co(t){let e=null;return()=>(e??=C(t),e)}function l(t){if(t===void 0||t.includes("\x00")||Buffer.byteLength(t,"utf8")>32768)return;return t}function He(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??Cr,TMPDIR:t.temporaryDirectory,SHELL:l(e.SHELL)??"/bin/zsh",LANG:l(e.LANG)??"C.UTF-8",LC_ALL:l(e.LC_ALL)??l(e.LANG)??"C.UTF-8"},r=l(e.LC_CTYPE),o=l(e.TERM),i=l(e.COLORTERM);if(r)n.LC_CTYPE=r;if(o)n.TERM=o;if(i)n.COLORTERM=i;if(process.platform==="win32"){for(let s of I){let a=l(e[s]);if(a)n[s]=a}n.TEMP=n.TMP=t.temporaryDirectory,n.SHELL=fe()??n.SHELL,n.PATH=kn(n.PATH)}return n}function kn(t,e=f(m(),".reason","python3")){let n=(i)=>t.split(u.delimiter).filter((s)=>s&&!/[\\/]WindowsApps[\\/]?$/i.test(s)).map((s)=>u.join(s,i)).find((s)=>p(s)),r=n("python.exe");if(n("python3.exe")||!r)return t;let o=`#!/bin/sh
|
|
4
4
|
exec "${r.replaceAll("\\","/")}" "$@"
|
|
5
5
|
`;try{let i=f(e,"python3");if(!p(i)||_(i,"utf8")!==o)T(e,{recursive:!0}),A(i,o)}catch{return t}return[e,t].join(u.delimiter)}var I=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
|
|
6
|
-
export{
|
|
6
|
+
export{Cr,Ar,xn,co,He,kn};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Ot,I}from"./vm-hands-entry-lite-bqqfmgaz.js";import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_,rr}from"./vm-hands-entry-lite-wp0d65yx.js";import{be}from"./vm-hands-entry-lite-yretc2th.js";function Ui(e,i){let t=T(e,"REASON_API_URL")?.trim();if(!t)return rr(i);let n=new URL(t);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&["127.0.0.1","localhost","::1"].includes(n.hostname)))throw Error("REASON_API_URL must use HTTPS (HTTP is allowed only for loopback development).");return n.origin}function Xo(e){return T(e,"REASON_API_URL")?.trim()?Ui(e,"production"):void 0}function Yo(e){return T(e,"REASON_API_KEY")?.trim()||void 0}async function xs(e,i){let t=e.env??process.env,n=Yo(t);if(!n)return(e.getCredentials??Ot)({apiOrigin:Xo(t),signal:i});let a=Ui(t,e.channel??_({env:t})),o=await(e.fetchImpl??fetch)(a+"/v3/self",{redirect:"error",headers:{authorization:"Bearer "+n,accept:"application/json"},signal:i}),p=await o.json().catch(()=>({})),r=be(p)?p:{};if(!o.ok){let s=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:"API key authentication failed ("+o.status+")";throw new I(o.status,typeof r.error==="string"?r.error:"api_key_auth_failed",s)}if(typeof r.org_id!=="string"||!r.org_id)throw Error("The API key in the environment did not resolve to a Workspace.");let l=Array.isArray(r.scopes)?r.scopes.filter((s)=>typeof s==="string"):[];return{credentialKind:"api_key",apiOrigin:a,accessToken:n,orgId:r.org_id,clientId:"api-key",refreshToken:"",expiresAt:"",scopes:l}}export{Ui,Xo,Yo,xs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S,
|
|
2
|
+
import{S,Wt,$n,Ge,Bn,Fn}from"./vm-hands-entry-lite-k1wghndy.js";import{Xn}from"./vm-hands-entry-lite-55mpsgz3.js";import{Ln}from"./vm-hands-entry-lite-wx1fmrbs.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ys,spawn as qe}from"child_process";import{existsSync as ws}from"fs";import{connect as xs}from"net";function pn(){let e=new Set,t=null,n=(s)=>({holder:t?.viewer??null,you:t===s,same_user:Boolean(t?.viewer&&s.viewer&&t.viewer.user_id===s.viewer.user_id)}),o=()=>{for(let s of e)s.notify(n(s))};return{join(s){return e.add(s),s.notify(n(s)),()=>{if(!e.delete(s))return;if(t!==s)return;t=null,o()}},claim(s){if(t===s||!e.has(s))return;t=s,o()}}}var ut=pn();import{createHash as St}from"crypto";import{once as Sn}from"events";import{createWriteStream as vn,existsSync as mr,mkdirSync as gr,mkdtempSync as hr,readFileSync as le,readdirSync as br,renameSync as yr,realpathSync as En,rmSync as Pn,statSync as Ne,writeFileSync as wr}from"fs";import{delimiter as _r,dirname as vt,join as b}from"path";import{finished as Cn}from"stream/promises";var We="omljlfpmafedpplnpkkahegadhkimdje",fo="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var O={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"}},H={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${O.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${O.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${O.obu.version}/open-browser-use-chrome-extension-${O.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},F="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Me}from"child_process";import{createRequire as fn}from"module";import{join as mn}from"path";var gn=30000,hn=1048576;function Te(){return process.env.SystemRoot??"C:\\Windows"}function bn(){return mn(Te(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var yn=String.raw`
|
|
3
3
|
$ErrorActionPreference = "Stop"
|
|
4
4
|
Add-Type -TypeDefinition @"
|
|
5
5
|
using System;
|
|
@@ -69,15 +69,15 @@ while ($null -ne ($line = [Console]::In.ReadLine())) {
|
|
|
69
69
|
`).join("")),t.stdin.writableLength>hn)d({reason:"input_backpressure"})},g=()=>{i=Me(...Oe("clipboard"),{env:Ae(),stdio:["ignore","pipe","ignore"],windowsHide:!0});let p="";i.stdout?.on("data",(w)=>{if(s)return;p+=w.toString("ascii");for(let f=p.indexOf(`
|
|
70
70
|
`);f>=0;f=p.indexOf(`
|
|
71
71
|
`)){let M=p.slice(0,f).replace(/\r$/,"");if(p=p.slice(f+1),!M.startsWith("c "))continue;let E=M.slice(2);if(E.length>Math.ceil(S/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(E)){d({reason:"display_protocol"});return}let c=Buffer.from(E,"base64");if(c.byteLength<=S)e.clipboard(c.toString("utf8"));if(s)return}if(p.length>Math.ceil(S/3)*4+4)d({reason:"display_protocol"})}),i.once("error",()=>y("Reason could not watch this computer's desktop clipboard.")),i.once("exit",()=>{if(!s)y("Reason could not watch this computer's desktop clipboard.")})};return t.stdout.on("data",(p)=>{if(s||o===null)return;o+=p.toString("utf8");let w=o.indexOf(`
|
|
72
|
-
`);if(w<0){if(o.length>4096)d({reason:"display_protocol"});return}let f=ht(o.slice(0,w).trim());if(o=null,!f)d({reason:"display_protocol"});else if(f.session===0)y("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else g(),e.ready({width:f.width,height:f.height})}),t.stdin.on("error",()=>{return}),t.once("error",()=>y("Reason could not start this computer's desktop input.")),t.once("exit",()=>{if(o!==null)y("Reason could not start this computer's desktop input.");else d({reason:"display_closed"})}),{pointer:(p,w,f)=>h(n.pointer(p,w,f)),key:(p,w)=>h(n.key(p,w)),clipboard:(p)=>h([`c ${Buffer.from(p,"utf8").toString("base64")}`]),close(){s=!0,a()}}}var
|
|
72
|
+
`);if(w<0){if(o.length>4096)d({reason:"display_protocol"});return}let f=ht(o.slice(0,w).trim());if(o=null,!f)d({reason:"display_protocol"});else if(f.session===0)y("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else g(),e.ready({width:f.width,height:f.height})}),t.stdin.on("error",()=>{return}),t.once("error",()=>y("Reason could not start this computer's desktop input.")),t.once("exit",()=>{if(o!==null)y("Reason could not start this computer's desktop input.");else d({reason:"display_closed"})}),{pointer:(p,w,f)=>h(n.pointer(p,w,f)),key:(p,w)=>h(n.key(p,w)),clipboard:(p)=>h([`c ${Buffer.from(p,"utf8").toString("base64")}`]),close(){s=!0,a()}}}var Mn=["none","standard","all"],ue="22.23.3",Tn={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53","win32-x64":"2b0ff57b049cda1bbcea2240eec20467018713c1efe1f7360c2681859b90ed71","win32-arm64":"33dad22e4cef5ee8f9fbb1b0d037fdacd0e56d12a4580f0d63f68b894deab535"},$e={"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"},"win32-x64":{ocu:"dist/windows/amd64/open-computer-use.exe",obu:"native/windows-amd64/open-browser-use.exe"},"win32-arm64":{ocu:"dist/windows/arm64/open-computer-use.exe",obu:"native/windows-arm64/open-browser-use.exe"}},Et="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",Dt="chrome-win64/chrome.exe",W={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},An={version:W.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},Le={version:W.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${W.version}/ffmpeg-${W.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},_t=`ffmpeg-${Le.version}-essentials_build/bin`,z="com.ifuryst.open_browser_use.extension",It="com.reasonmachines.browser_use.extension",Ut="/tmp/reason-browser-use",Ue=["tint2","picom","xterm","pcmanfm"],Pt=["fonts-droid-fallback"],Ct=["pulseaudio"],Rt=["tigervnc-standalone-server"],Un=["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",...Pt,"galculator","chromium","ffmpeg","tmux",...Ct,...Rt,...Ue],Hn=new Set([...Ue,...Pt,...Ct,...Rt]),kt=Un.filter((e)=>e!=="chromium"&&!Hn.has(e)),zn=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],ce="/usr/bin/chromium",jn=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function Gn(e=process.platform,t=process.arch){let n=`${e}-${t}`;return n==="linux-x64"||n==="linux-arm64"||n==="darwin-arm64"||n==="win32-x64"||n==="win32-arm64"?n:null}function K(e){return e==="win32-x64"||e==="win32-arm64"}function Be(e){return K(e)?`node-v${ue}-${e.replace("win32","win")}`:`node-v${ue}-${e}`}function de(e){return{node:{version:ue,url:`https://nodejs.org/dist/v${ue}/${Be(e)}${K(e)?".zip":".tar.gz"}`,sha256:Tn[e]},open_computer_use:{version:O.ocu.version,url:J.ocu.url,sha256:J.ocu.sha256},open_browser_use:{version:O.obu.version,url:J.obu.url,sha256:J.obu.sha256},...e==="darwin-arm64"?{chrome_for_testing:{version:H.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${H.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:H.macArm64Sha256}}:K(e)?{chrome_for_testing:{version:H.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${H.version}/win64/chrome-win64.zip`,sha256:H.win64Sha256}}:{}}}function Vn(e){let t={extension:F};for(let[n,o]of Object.entries(de(e)))t[n]=`${o.version}@${o.sha256}`;return t}function Mt(e){return b(e,".local","share","reason","desktop")}function Rr(e,t=Ln()){let n=Mt(t),o=(p)=>b(n,p,de(e)[p]?.version??""),s=o("open_computer_use"),i=o("open_browser_use"),a=e==="darwin-arm64",d=K(e),y=b(t,"Library","Application Support"),h=b(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:b(t,"AppData","Local"),"OpenBrowserUse"),g=a?b(y,"Google","Chrome","NativeMessagingHosts",`${z}.json`):d?b(h,"NativeMessagingHosts",`${z}.json`):b(t,".config","google-chrome","NativeMessagingHosts",`${z}.json`);return{root:n,automation:b(vt(n),"automation"),receipt:b(n,"receipt.json"),minimal:is(t),node:d?b(o("node"),Be(e),"node.exe"):b(o("node"),"bin","node"),ocuDir:s,ocu:b(s,$e[e].ocu),ocuApp:a?b(s,"dist","Open Computer Use.app"):null,obuDir:i,obu:b(i,"cli","open-browser-use.js"),nativeHost:b(i,$e[e].obu),extensionDir:a?b(y,"OpenBrowserUse","chrome-extension","release"):d?b(h,"chrome-extension","release"):b(t,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:g,nativeHostManifests:a?[g,b(y,"Google","ChromeForTesting","NativeMessagingHosts",`${z}.json`)]:d?[g]:[b(t,".config","chromium","NativeMessagingHosts",`${z}.json`),b(t,".config","google-chrome-for-testing","NativeMessagingHosts",`${z}.json`)],browser:a?b(o("chrome_for_testing"),Et):d?b(o("chrome_for_testing"),Dt):ce,userChromeHost:a?b(n,"user-chrome","reason-browser-use"):null,userChromeRegistration:a?b(y,"Google","Chrome","NativeMessagingHosts",`${It}.json`):null,ffmpegDir:b(n,"ffmpeg"),ffmpeg:a?b(n,"ffmpeg",W.version,"ffmpeg"):d?b(n,"ffmpeg",Le.version,_t,"ffmpeg.exe"):null,ffprobe:a?b(n,"ffprobe",An.version,"ffprobe"):d?b(n,"ffmpeg",Le.version,_t,"ffprobe.exe"):null}}function Wn(e){try{let t=JSON.parse(le(e,"utf8"));if(typeof t!=="object"||t===null)return null;let n=t,o=n.pins;if(n.schema_version!==1||typeof n.platform!=="string"||typeof o!=="object"||o===null||!Object.values(o).every((s)=>typeof s==="string")||!Mn.includes(n.permissions)||!Array.isArray(n.missing_system_packages)||!n.missing_system_packages.every((s)=>typeof s==="string")||typeof n.updated_at!=="string")return null;return{schema_version:1,platform:n.platform,pins:o,permissions:n.permissions,missing_system_packages:n.missing_system_packages,updated_at:n.updated_at}}catch{return null}}function A(e){try{return Ne(e).isFile()}catch{return!1}}function Tt(e){try{let t=Ne(e);return t.isFile()&&(t.mode&73)!==0}catch{return!1}}function Kn(e){try{return le(e,"utf8")}catch{return null}}function U(e){for(let t of jn){let n=b(t,e);try{let o=Ne(n);if(o.isFile()&&(o.mode&73)!==0)return n}catch{}}return null}function qn(e){try{let t=JSON.parse(le(b(e,"package.json"),"utf8"));return typeof t==="object"&&t!==null&&typeof t.version==="string"?t.version:null}catch{return null}}function Yn(e,t,n){let o=de(n)[e];if(!o)return!1;let s=K(n);if(e==="node")return A(s?b(t,Be(n),"node.exe"):b(t,"bin","node"));if(e==="chrome_for_testing")return A(b(t,s?Dt:Et));let i=$e[n][e==="open_computer_use"?"ocu":"obu"];return qn(t)===o.version&&A(b(t,i))&&(e==="open_computer_use"||A(b(t,"cli","open-browser-use.js")))}function Jn(e){return St("sha256").update(Buffer.from(e,"base64")).digest("hex").slice(0,32).replace(/./g,(t)=>String.fromCharCode(97+Number.parseInt(t,16)))}function He(e){try{let t=JSON.parse(le(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Zn(e){let t=He(b(e.extensionDir,"manifest.json"));return t!==null&&t.version===O.obu.version&&typeof t.key==="string"&&Jn(t.key)===F}function Qn(e,t){let n=e?.allowed_origins;return e!==null&&e.name===z&&Array.isArray(n)&&n.length===1&&n[0]===`chrome-extension://${F}/`&&(t===void 0||e.path===t)}function es(e){return Zn(e)&&A(e.nativeHost)&&e.nativeHostManifests.every((t)=>Qn(He(t),e.nativeHost))}function ts(e){return`#!/bin/sh
|
|
73
73
|
# Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
|
|
74
74
|
obu=${`'${e.replaceAll("'","'\\''")}'`}
|
|
75
75
|
case "$1" in
|
|
76
|
-
chrome-extension://*) exec "$obu" host --socket-dir ${
|
|
77
|
-
mcp) shift; exec "$obu" mcp --socket-dir ${
|
|
76
|
+
chrome-extension://*) exec "$obu" host --socket-dir ${Ut} ;;
|
|
77
|
+
mcp) shift; exec "$obu" mcp --socket-dir ${Ut} "$@" ;;
|
|
78
78
|
esac
|
|
79
79
|
exec "$obu" "$@"
|
|
80
|
-
`}function ns(e){let t=He(e),n=t?.allowed_origins;return t!==null&&t.name===It&&t.type==="stdio"&&Array.isArray(n)&&n.includes(`chrome-extension://${We}/`)&&typeof t.path==="string"&&Tt(t.path)}function ss(e,t){if(!e.userChromeHost||!e.userChromeRegistration)return null;if(!t||Kn(e.userChromeHost)!==ts(e.nativeHost)||!Tt(e.userChromeHost))return{code:"user_chrome_browser_use_missing"};return ns(e.userChromeRegistration)?{host:e.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var rs={display:["display","desktop_session","desktop_video"],computer:["display","desktop_session","system_packages","node","open_computer_use"],browser:["display","desktop_session","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function x(e={}){let t=e.platform===void 0?Gn():e.platform;if(!t)return null;let n=
|
|
80
|
+
`}function ns(e){let t=He(e),n=t?.allowed_origins;return t!==null&&t.name===It&&t.type==="stdio"&&Array.isArray(n)&&n.includes(`chrome-extension://${We}/`)&&typeof t.path==="string"&&Tt(t.path)}function ss(e,t){if(!e.userChromeHost||!e.userChromeRegistration)return null;if(!t||Kn(e.userChromeHost)!==ts(e.nativeHost)||!Tt(e.userChromeHost))return{code:"user_chrome_browser_use_missing"};return ns(e.userChromeRegistration)?{host:e.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var rs={display:["display","desktop_session","desktop_video"],computer:["display","desktop_session","system_packages","node","open_computer_use"],browser:["display","desktop_session","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function x(e={}){let t=e.platform===void 0?Gn():e.platform;if(!t)return null;let n=Rr(t,e.home),o=Wn(n.receipt),s=Vn(t),i=o!==null&&o.platform===t&&JSON.stringify(Object.entries(o.pins).sort())===JSON.stringify(Object.entries(s).sort()),a=[],d=de(t);for(let c of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let _=d[c];if(!_)continue;let v=Yn(c,b(n.root,c,_.version),t),D=o?.pins[c],L=v&&D===s[c]?"ready":D!==void 0&&D!==s[c]?"outdated":"missing";a.push({name:c,state:L,detail:_.version})}let y=o?.pins.extension===F&&es(n);a.push({name:"browser_extension",state:y?"ready":"missing",detail:F});let h=U("Xvfb"),g=U("x11vnc"),p=U("openbox");if(K(t))a.push(yt()?{name:"desktop_session",state:"ready",detail:"signed-in desktop session"}:{name:"desktop_session",state:"missing",detail:"run the worker in the signed-in desktop session, not as a service"}),a.push(n.ffmpeg&&A(n.ffmpeg)?{name:"desktop_video",state:"ready",detail:n.ffmpeg}:{name:"desktop_video",state:"missing",detail:"run `reason desktop install` for desktop video"});else if(t!=="darwin-arm64"){a.push(A(ce)?{name:"browser",state:"ready",detail:ce}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${ce}`});let c=h!==null&&g!==null&&p!==null;a.push({name:"display",state:c?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let _=zn.filter((P)=>U(P)===null),v=(o?.missing_system_packages??kt).filter((P)=>kt.includes(P)),D=_.length===0&&v.length===0;a.push(D?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...v,..._])].join(" ")});let L=Ue.filter((P)=>U(P)===null);a.push(L.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:L.join(" ")})}let w=n.ffmpeg&&A(n.ffmpeg)?n.ffmpeg:U("ffmpeg"),f=!w?null:w===n.ffmpeg?n.ffprobe:b(vt(En(w)),"ffprobe"),M=i&&a.every((c)=>c.state==="ready"),E=(c)=>i&&a.every((_)=>!rs[c].includes(_.name)||_.state==="ready");return{platform:t,root:n.root,automation:n.automation,ready:M,features:{display:E("display"),computer:E("computer"),browser:E("browser")},node:n.node,ocu:n.ocu,obu:n.obu,nativeHost:n.nativeHost,extensionDir:n.extensionDir,browser:n.browser,ffmpeg:w,ffprobe:f&&A(f)?f:null,userChrome:ss(n,i&&["node","open_browser_use"].every((c)=>a.find((_)=>_.name===c)?.state==="ready")),pulseaudio:U("pulseaudio"),xvnc:U("Xvnc"),xvfb:h,x11vnc:g,openbox:p,components:a}}function Ot(e){return os(e)?Xn():[]}function os(e){return e?.platform==="darwin-arm64"&&e.ffmpeg===b(e.root,"ffmpeg",W.version,"ffmpeg")}async function go(e,t,n,o=fetch){try{let s=await o(e,{redirect:"follow"});if(!s.ok||!s.body)throw Error(`download failed (HTTP ${s.status}): ${e}`);let i=St("sha256"),a=vn(n,{mode:384});try{let y=s.body.getReader();for(let h=await y.read();!h.done;h=await y.read())if(i.update(h.value),!a.write(h.value))await Sn(a,"drain")}finally{a.end(),await Cn(a)}let d=i.digest("hex");if(d!==t)throw Error(`digest mismatch for ${e}: expected ${t}, got ${d}`)}catch(s){throw Pn(n,{force:!0}),s}}function is(e){return b(Mt(e),"minimal.json")}import{spawn as as}from"child_process";import{existsSync as cs}from"fs";import{connect as us}from"net";import{join as pe}from"path";var $t="reason_desktop",Q={sampleRate:48000,channels:2,codec:"opus"},ls=5000,ds=107,ps=262144,Rn=(e)=>pe(e,"native"),Ve=(e)=>`unix:${e}`;function Fe(e,t=1000){if(!cs(e))return Promise.resolve(!1);return new Promise((n)=>{let o=us({path:e}),s=(i)=>{o.destroy(),n(i)};o.setTimeout(t,()=>s(!1)),o.once("error",()=>s(!1)),o.once("close",()=>s(!1)),o.once("connect",()=>s(!0))})}async function mo(e,t){if(!t)return null;let n=Rn(e);if(Buffer.byteLength(n)>ds||/["'\\\s]/.test(n))return null;try{if(await Fe(n))return n;let o=as(t,["--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:${pe(e,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${n}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${$t} rate=${Q.sampleRate} channels=${Q.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:e,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:e,PULSE_RUNTIME_PATH:pe(e,"runtime"),PULSE_STATE_PATH:pe(e,"state")}}),s=!1;o.once("error",()=>{s=!0}),o.once("exit",()=>{s=!0}),o.unref();let i=Date.now()+ls;while(Date.now()<i){if(await Fe(n))return n;if(s)return await Fe(n)?n:null;await new Promise((a)=>setTimeout(a,50))}if(!s)o.kill("SIGKILL");return null}catch{return null}}function Lt(){let{sampleRate:e,channels:t}=Q;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(e),"-channels",String(t),"-fragment_size",String(e*t*2/50),"-i",`${$t}.monitor`,"-vn","-ac",String(t),"-ar",String(e),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var fs=[79,103,103,83],ms=Buffer.from("OpusHead"),gs=Buffer.from("OpusTags"),At=(e,t)=>e.byteLength>=t.byteLength&&t.every((n,o)=>e[o]===n);class ze extends Error{constructor(e){super(e);this.name="OggProtocolError"}}class je{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(e){let t=new Uint8Array(this.buffer.byteLength+e.byteLength);t.set(this.buffer),t.set(e,this.buffer.byteLength);let n=[],o=0;while(t.byteLength-o>=27){if(fs.some((w,f)=>t[o+f]!==w)||t[o+4]!==0)throw new ze("invalid_page");let s=(t[o+5]&1)!==0,i=t[o+26];if(t.byteLength-o<27+i)break;let a=t.subarray(o+27,o+27+i),d=a.reduce((w,f)=>w+f,0),y=27+i+d;if(t.byteLength-o<y)break;if(!s&&this.partialBytes>0)this.resetPartial();let h=s&&this.partialBytes===0,g=o+27+i,p=g;for(let w of a){if(g+=w,w===255)continue;if(this.appendPartial(t.subarray(p,g),h),p=g,!h){let f=this.takePartial();if(f.byteLength>0&&!At(f,ms)&&!At(f,gs))n.push(f)}h=!1,this.resetPartial()}if(p<g)this.appendPartial(t.subarray(p,g),h);o+=y}return this.buffer=t.slice(o),n}appendPartial(e,t){if(t||e.byteLength===0)return;if(this.partialBytes+=e.byteLength,this.partialBytes>ps)throw new ze("packet_too_large");this.partial.push(e.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let e=new Uint8Array(this.partialBytes),t=0;for(let n of this.partial)e.set(n,t),t+=n.byteLength;return e}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as hs}from"child_process";var Nt=1048576,bs=String.raw`
|
|
81
81
|
import gi, json, os, sys
|
|
82
82
|
gi.require_version("Gtk", "3.0")
|
|
83
83
|
from gi.repository import Gtk, Gdk, GLib
|
|
@@ -118,9 +118,9 @@ def input_ready(fd, condition):
|
|
|
118
118
|
GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
|
|
119
119
|
send("ready")
|
|
120
120
|
Gtk.main()
|
|
121
|
-
`;function
|
|
121
|
+
`;function Bt(e,t){let n=hs("/usr/bin/python3",["-I","-u","-c",bs],{env:{DISPLAY:e.display,XAUTHORITY:e.xauthority},stdio:["pipe","pipe","ignore"]}),o=!1,s=!0,i="",a=0,d=[],y=setTimeout(()=>g(),5000),h=()=>{o=!0,clearTimeout(y),d.length=0,n.kill("SIGKILL")},g=()=>{if(o)return;h(),t.end({error:new r("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},p=(w,f=32)=>{if(o)return;if(!s){w();return}if(a+=f,a>Nt)h(),t.end({reason:"input_backpressure"});else d.push({apply:w,bytes:f})};return n.stdout.on("data",(w)=>{if(o)return;i+=w.toString("ascii");for(let f=i.indexOf(`
|
|
122
122
|
`);f>=0;f=i.indexOf(`
|
|
123
123
|
`)){let M=i.slice(0,f);i=i.slice(f+1);let E;try{E=JSON.parse(M)}catch{g();return}if(E==="ready"||E==="ack"){clearTimeout(y),s=!1;while(!s&&!o&&d.length){let c=d.shift();a-=c.bytes,c.apply()}}else if(E&&typeof E==="object"&&"text"in E&&typeof E.text==="string"&&Buffer.byteLength(E.text)<=S)t.clipboard(E.text);else{g();return}if(o)return}if(i.length>S*6+32)g()}),n.stdin.on("error",g),n.once("error",g),n.once("exit",g),{apply:p,write(w){if(Buffer.byteLength(w)>S||w.includes("\x00")){g();return}let f=`${JSON.stringify(w)}
|
|
124
|
-
`;p(()=>{if(s=!0,y=setTimeout(()=>g(),5000),n.stdin.write(f),n.stdin.writableLength>Nt)h(),t.end({reason:"input_backpressure"})},Buffer.byteLength(f))},close:h}}var X={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}},_s="avc1.4D002A",
|
|
125
|
-
`),s="security",!0}case"security":{if(o.byteLength<1)return!1;let c=o[0];if(c===0)return p(),!1;if(o.byteLength<1+c)return!1;if(!o.subarray(1,1+c).includes(1))return p(),!1;return f(1+c),n.write(Buffer.from([1,1])),s="init",!0}case"init":{if(o.byteLength<24)return!1;let c=o.readUInt32BE(20);if(c>65536)return p(),!1;if(o.byteLength<24+c)return!1;let _={width:o.readUInt16BE(0),height:o.readUInt16BE(2)};if(f(24+c),_.width===0||_.height===0)return p(),!1;s="messages";let v=Buffer.alloc(12);v.writeUInt8(2,0),v.writeUInt16BE(2,2),v.writeInt32BE(Ts,4),v.writeInt32BE(Ms,8),n.write(v),a=!0;for(let D of d)n.write(D);return d=[],y=0,t.ready(_),!h}case"skip":{let c=Math.min(i,o.byteLength);if(f(c),i-=c,i>0)return!1;return s="messages",!0}case"messages":{if(o.byteLength<1)return!1;switch(o[0]){case 1:{if(o.byteLength<6)return!1;let c=6+o.readUInt16BE(4)*6;if(o.byteLength<c)return!1;return f(c),!0}case 2:return f(1),!0;case 3:{if(o.byteLength<8)return!1;let c=o.readUInt32BE(4);if(c>S/2)return f(8),s="skip",i=c,!0;if(o.byteLength<8+c)return!1;let _=o.subarray(8,8+c).toString("latin1");return f(8+c),t.clipboard(_),!h}default:return p(),!1}}}},E=!1;return n.once("connect",()=>{E=!0}),n.on("data",(c)=>{if(h)return;o=o.byteLength?Buffer.concat([o,c]):c;while(!h&&M());}),n.once("error",()=>{if(!E)g({error:new r("display_unavailable","Reason could not reach this machine's desktop server.")})}),n.once("close",()=>g({reason:"display_closed"})),{pointer(c,_,v){let D=Buffer.alloc(6);D.writeUInt8(5,0),D.writeUInt8(v&255,1),D.writeUInt16BE(c,2),D.writeUInt16BE(_,4),w(D)},key(c,_){let v=Buffer.alloc(8);v.writeUInt8(4,0),v.writeUInt8(c?1:0,1),v.writeUInt32BE(_>>>0,4),w(v)},clipboard(c){if(Array.from(c).some((D)=>D.codePointAt(0)>255)){g({reason:"clipboard_unicode_unsupported"});return}let _=Buffer.from(c,"latin1"),v=Buffer.alloc(8);v.writeUInt8(6,0),v.writeUInt32BE(_.byteLength,4),w(Buffer.concat([v,_]))},close(){h=!0,n.destroy()}}}class Je{run=null;viewers=new Set;get running(){return this.run!==null}start(e,t,n,o){this.viewers.add(e),this.stop();let s;try{s=n()}catch{this.fail();return}Jt(s);let i={child:s,splitter:new tn};this.run=i;for(let d of[...this.viewers])d.started(t);s.stdout?.on("data",(d)=>{if(this.run!==i)return;for(let y of i.splitter.push(d,o()))for(let h of[...this.viewers])h.unit(y)});let a=()=>{if(this.run!==i)return;this.run=null,this.fail()};s.once("exit",a),s.once("error",a)}leave(e){if(!this.viewers.delete(e))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;Zt(this.run.child),this.run=null}fail(){for(let e of[...this.viewers])e.failed()}}var Xt=new WeakMap;function zs(e){let t=Xt.get(e);if(!t)Xt.set(e,t=new Je);return t}var ee=new Map;function Nn(e,t,n={}){let o=n.micros??$s,s=new Bn,i=t.request.preset,a=null,d=null,y=null,h=!1,g=null,p=!1,w=!1,f=null,M=0,E=0,c=!1,_=null,v=null,D=0,L=null,P=[],te=0,N=[],Ze=new Uint32Array(Ke+1),ge=0,he=null,be=0,q=0,ye=0,Qe=0,et=0,ne=null,we=0,j={frames:0,bytes:0,since:o()},G=[],Y=0,xe,_e=!1,rn=o(),R={},V=()=>Math.round((o()-rn)/1000),tt=n.control??ut,ke=null,Se=null,nt=0,ve=!1,st={pause(){if(!g?.running)return;g.stop(),ve=!0},adopt(u){let l=u!==null&&(u.width!==d?.width||u.height!==d?.height);if(l)d=u;if(!l&&!ve)return;if(ve=!1,g)ae();else Ie()}},on=(u)=>{if(!n.resizeDesktop||!a||"kind"in a||e.done)return;let l=a.display,m=()=>[...ee.get(l)??[]];nt++,n.resizeDesktop(a,u,()=>{for(let k of m())k.pause()}).then((k)=>{for(let I of m())I.adopt(k)})},T=(u)=>{let l=zt(u);return e.send(l),Qe+=l.byteLength,l.byteLength},se=(u)=>{if(e.done)return;if(e.open)T({type:"error",code:u});e.end({reason:u})},re=()=>Math.max(ks,X[i].kbps*1000/8*Ss),oe=()=>o()/1000,an=()=>{while(N.length>1&&N[0].atMs<oe()-Es)N.shift();return N[0]?.rttMs??null},rt=(u)=>{let l=an();if(l===null||P.length===0)return!1;let m=(l+vs)*u;return oe()-P[0].sentMs>m||te>m/1000*X[i].kbps*1000/8},cn=(u)=>{if(D===0)return;let l=Math.min(u,D-1);if(L!==null&&l<=L)return;L=l;let m=oe();while(P.length&&P[0].seq<=l){let k=P.shift();if(te-=k.bytes,k.seq!==l)continue;let I=Math.max(0,m-k.sentMs);while(N.length&&N.at(-1).rttMs>=I)N.pop();N.push({atMs:m,rttMs:I}),Ze[Math.min(Ke,Math.round(I))]++,ge++,he=Math.min(he??I,I)}},un=()=>{let u=0;for(let l=0;l<=Ke;l++)if(u+=Ze[l],u*2>=ge)return l;return 0},ln=()=>e.bufferedAmount<=re()/2&&!rt(0.5),ot=()=>{_e=!0,G=[],Y=0,g?.leave(Ee),g=null},it=(u)=>{if(e.done)return;if(u.key)R.first_key_ms??=V();if(!h){if(!g||G.length===0&&!u.key)return;if(G.push(u),Y+=u.data.byteLength,Y>re())ot();return}if(c){q++;return}if(e.bufferedAmount>re()||rt(1)){c=!0,q++,_=setInterval(()=>{if(e.done||!ln())return;if(_)clearInterval(_);_=null,c=!1,ae()},n.drainPollMs??25);return}if(!p){if(!u.key){q++;return}if(T({type:"hello",width:d.width,height:d.height,fps:X[i].fps,preset:i,codec:_s}),p=!0,R.first_frame_ms??=V(),!w&&a?.sound)T({type:"audioHello",...Q}),w=!0}let l=T({type:"frame",key:u.key,seq:D,captureMicros:u.micros,data:u.data});if(P.push({seq:D,sentMs:oe(),bytes:l}),te+=l,P.length>Ds)te-=P.shift().bytes;D++,be++,ne??=u.micros,we=u.micros,j.frames++,j.bytes+=l},Ee={started(u){i=u,p=!1,G=[],Y=0},unit:it,failed:()=>se("encoder_failed")},De=()=>{let u=(n.ffmpeg??jt)();if(!a||!d){se("encoder_failed");return}let[l,m]=[a,d],k="kind"in l&&l.kind==="simulator"?l.stream:null;if(!u&&!k){se("encoder_failed");return}if(g??="kind"in l&&l.kind==="mac_screen"?zs(n.spawn??Gt):new Je,R.encoder_ms===void 0)R.encoder_ms=V(),R.encoder_shared=g.running;g.start(Ee,i,()=>{let I=X[i].fps;if(k)return k(I,X[i].kbps,Qt);if("kind"in l&&l.kind==="simulator"){let C=Math.min(0.99,en(l.size)),B={width:l.size.width*C,height:l.size.height*C};return Hs(u,fe(i,Bs(Math.min(I,30)),B,(n.macEncoder??Vt)()),l)}if("kind"in l&&l.kind==="windows_screen")return(n.spawn??me)(u,fe(i,Us(I,m),Kt(m)),{SystemRoot:process.env.SystemRoot??"C:\\Windows"});return"kind"in l?(n.spawn??Gt)(u,fe(i,Ns(I),Kt(m),(n.macEncoder??Vt)()),{}):(n.spawn??me)(u,fe(i,Ls(I,m,l.display),m),{DISPLAY:l.display,XAUTHORITY:l.xauthority})},o)},ie=()=>{if(!f)return;Zt(f.child),f=null},dn=()=>{let u=(n.ffmpeg??jt)();if(f||e.done||!w||!a?.sound||!u)return;let l;try{l=(n.spawn??me)(u,Lt(),{PULSE_SERVER:Ve(a.sound)})}catch{return}Jt(l);let m={child:l,reader:new je};f=m,l.stdout?.on("data",(I)=>{if(f!==m||e.done)return;let C;try{C=m.reader.push(I)}catch{ie();return}let B=o();for(let Ce of C){if(e.bufferedAmount>re()){E++;continue}T({type:"audio",captureMicros:B,data:Ce}),M++}});let k=()=>{if(f===m)ie()};l.once("exit",k),l.once("error",k)},ae=()=>{if(!g||e.done)return;ye++,De()},Ie=()=>{if(e.done||!d)return;if(!h){if(g||_e)return;De(),xe=setTimeout(()=>{if(!h)ot()},Cs);return}if(clearTimeout(xe),R.encoder_early===void 0){if(R.encoder_early=g!==null,_e)R.hold_lapsed=!0}if(!g)De();let u=G;G=[],Y=0;for(let l of u)it(l);v??=setInterval(()=>{let l=o(),m=Math.max(0.001,(l-j.since)/1e6);T({type:"stats",stats:{fps:Math.round(j.frames/m*10)/10,kbps:Math.round(j.bytes*8/1000/m),dropped:q,restarts:ye,queued_bytes:e.bufferedAmount}}),j={frames:0,bytes:0,since:l}},Rs)};t.desktop.then((u)=>{if(e.done)return;a=u;let l={ready(m){d=m,R.desktop_ms??=V(),Ie()},clipboard(m){if(e.open&&Buffer.byteLength(m)<=S)T({type:"serverClipboard",text:m})},end(m){if("reason"in m&&e.open)T({type:"error",code:m.reason});e.end(m)}};if("kind"in u&&u.kind==="simulator")y=u.input,l.ready(u.points);else if("kind"in u&&u.kind==="windows_screen")y=(n.windowsInput??xt)(l);else if("kind"in u)y=(n.macInput??((m)=>jn(m,Ye())))(l);else{let m=ee.get(u.display);if(!m)ee.set(u.display,m=new Set);m.add(st);let k=(n.linuxClipboard??Ut)(u,l),I=Fs(u.rfbSocket,{...l,clipboard:(C)=>{if(!k)l.clipboard(C)}});y=k?{pointer:(C,B,Ce)=>k.apply(()=>I.pointer(C,B,Ce)),key:(C,B)=>k.apply(()=>I.key(C,B)),clipboard:(C)=>k.write(C),close(){k.close(),I.close()}}:I}at()},(u)=>e.end({error:u}));function at(){if(Se||!t.viewerSameNetwork||!h||e.done||!a||!("kind"in a)||a.kind!=="mac_screen")return;Se=(n.macWindows??Fn)((u)=>{if(e.open)T({type:"windows",bounds:u})})}let ct={viewer:t.viewer??null,notify(u){if(e.open)T({type:"control",control:u})}},Pe=(u)=>{if(!y)return;if(!a||!("kind"in a)||a.kind!=="simulator")tt.claim(ct);u(y)};return{opened(){R.relay_ms??=V()},received(u){et+=u.byteLength;let l;try{l=s.push(u)}catch{se("viewer_protocol");return}for(let m of l){if(e.done)return;switch(m.type){case"ping":T({type:"pong",token:m.token});break;case"pointer":Pe((k)=>k.pointer(m.x,m.y,m.buttons));break;case"key":Pe((k)=>k.key(m.down,m.keysym));break;case"clientClipboard":Pe((k)=>k.clipboard(m.text));break;case"config":if(m.preset!==i)i=m.preset,ae();break;case"keyframeRequest":if(p&&!c)ae();break;case"ack":cn(m.seq);break;case"audioEnable":if(m.on)dn();else ie();break;case"resize":on({width:m.width,height:m.height});break;default:break}}if(!h&&!e.done){if(h=!0,R.viewer_ms=V(),t.viewer)ke=tt.join(ct);Ie(),at()}},close(){if(a&&!("kind"in a)){let u=ee.get(a.display);if(u?.delete(st),u?.size===0)ee.delete(a.display)}if(ke?.(),ke=null,Se?.close(),_)clearInterval(_);if(v)clearInterval(v);clearTimeout(xe),g?.leave(Ee),ie(),y?.close()},summary:()=>({output_bytes:Qe,input_bytes:et,video:{preset:i,frames:be,dropped:q,restarts:ye,avg_fps:ne!==null&&we>ne?Math.round((be-1)/((we-ne)/1e6)*10)/10:0,min_rtt_ms:Math.round(he??0),p50_rtt_ms:ge?un():0,audio_packets:M,audio_dropped:E,resizes:nt,connect:R}})}}var qt=null,nn=null,js=null,Gs=null;function Vs(){let e=x();return e?.features.display?e.ffmpeg:null}function sn(e){return qt??=new Promise((t)=>{ys(e,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(n,o)=>{let s=(i)=>!n&&new RegExp(`^\\s*V\\S*\\s+${i}\\s`,"m").test(o);t(nn={x264:s("libx264"),videotoolbox:s("h264_videotoolbox")})})}),qt}var Yt=null;function Ln(){return Yt??=(async()=>{let e=[x()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((n)=>Boolean(n&&ws(n)));if(!e)return null;let t=await sn(e);return t.videotoolbox||t.x264?e:null})(),Yt}function Pr(e=process.platform,t={}){if(e!=="linux"&&e!=="darwin"&&e!=="win32")return Promise.resolve(!1);let n=(t.ffmpeg??Vs)();if(!n)return Promise.resolve(!1);let o=(t.encoders??sn)(n);if(e==="linux")return o.then((i)=>i.x264);if(e==="win32"){let i=t.windowsScreen?t.windowsScreen():Gs??=bt();return Promise.all([o,i]).then(([a,d])=>a.x264&&(d?.session??0)>0)}let s=t.macScreen?t.macScreen():js??=Ge(Ye());return Promise.all([o,s]).then(([i,a])=>(i.x264||i.videotoolbox)&&a?.screen===!0&&a.accessibility)}
|
|
126
|
-
export{We,
|
|
124
|
+
`;p(()=>{if(s=!0,y=setTimeout(()=>g(),5000),n.stdin.write(f),n.stdin.writableLength>Nt)h(),t.end({reason:"input_backpressure"})},Buffer.byteLength(f))},close:h}}var X={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}},_s="avc1.4D002A",Ht={width:1920,height:1080},ks=262144,Ss=0.2,vs=250,Es=1e4,Ds=1024,Ke=1e4,Is=500,Ps=60,Cs=1e4,Rs=1000,Ft=1048576,Ms=-223,Ts=-308,On={kind:"mac_screen",sound:null},In={kind:"windows_screen",sound:null},Os,zt=()=>Os??=x()?.ffmpeg??null,me=(e,t,n)=>qe(e,t,{env:n,stdio:["ignore","pipe","ignore"],windowsHide:!0}),As,Ye=()=>As??=Ot(x()),jt=(e,t,n)=>{let[o,...s]=[...Ye(),e];return me(o,[...s,...t],n)},Gt=()=>nn?.videotoolbox?"h264_videotoolbox":"libx264",$s=()=>Math.round(performance.now()*1000),Xe=new Set,Vt=!1;function Jt(e){if(Xe.add(e),e.once("exit",()=>Xe.delete(e)),Vt)return;Vt=!0,process.once("exit",()=>{for(let t of Xe)try{t.kill("SIGKILL")}catch{}})}function Zt(e){try{e.stdout?.destroy()}catch{}if(e.exitCode!==null||e.signalCode!==null)return;try{e.kill("SIGTERM")}catch{return}let t=setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{e.kill("SIGKILL")}catch{}},Is);e.once("exit",()=>clearTimeout(t))}function Ls(e,t,n){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(e),"-video_size",`${t.width}x${t.height}`,"-i",n],size:t}}function Ns(e){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(e),"-i","Capture screen 0:none"],size:null}}function Us(e,t){return{args:["-f","gdigrab","-draw_mouse","1","-framerate",String(e),"-offset_x","0","-offset_y","0","-video_size",`${t.width}x${t.height}`,"-i","desktop"],size:t}}function Bs(e){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(e),"-i","pipe:0"],size:null}}var Qt=1700000;function en(e){return Math.min(1,Math.round(Math.sqrt(Qt/(e.width*e.height))*100)/100)}function Hs(e,t,n){let o=qe(n.axe,["stream-video","--udid",n.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,en(n.size)))],{stdio:["ignore","pipe","ignore"]}),s=qe(e,t,{env:{},stdio:["pipe","pipe","ignore"]});o.stdout.pipe(s.stdin),s.stdin.on("error",()=>{});let i=()=>{if(o.exitCode===null&&o.signalCode===null)o.kill("SIGTERM")};return s.once("exit",i),s.once("error",i),o.once("exit",()=>{if(s.exitCode===null&&s.signalCode===null)s.kill("SIGTERM")}),o.once("error",()=>{if(s.exitCode===null&&s.signalCode===null)s.kill("SIGTERM")}),s}function Kt(e){let t=Math.min(1,Ht.width/e.width,Ht.height/e.height);return{width:Math.round(e.width*t),height:Math.round(e.height*t)}}function fe(e,t,n,o="libx264"){let s=X[e],i=(p)=>Math.max(2,Math.floor(p/2)*2),a={width:i(n.width*s.scale),height:i(n.height*s.scale)},d=a.width!==t.size?.width||a.height!==t.size.height,y=Math.max(1,Math.round(s.kbps*2/s.fps)),h=["-g",String(s.fps*Ps)],g=o==="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",...h,"-b:v",`${s.kbps}k`,"-maxrate",`${s.kbps}k`,"-bufsize",`${y}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",s.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...s.threads?["-threads",String(s.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...h,"-crf",String(s.crf),"-maxrate",`${s.kbps}k`,"-bufsize",`${y}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...t.args,"-an",...d?["-vf",`scale=${a.width}:${a.height}:flags=fast_bilinear`]:[],...g,"-flush_packets","1","-f","h264","pipe:1"]}class tn{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(e,t){if(this.buffer.byteLength===0)this.micros=t;let n=new Uint8Array(this.buffer.byteLength+e.byteLength);n.set(this.buffer),n.set(e,this.buffer.byteLength),this.buffer=n;let o=[],s=this.scanned;while(s+3<this.buffer.byteLength){if(this.buffer[s]!==0||this.buffer[s+1]!==0||this.buffer[s+2]!==1){s++;continue}let i=this.buffer[s+3]&31,a=s>0&&this.buffer[s-1]===0?s-1:s;if(i===9&&a>0)o.push({data:this.buffer.slice(0,a),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(a),this.key=!1,this.micros=t,s-=a;if(i===5)this.key=!0;s+=3}return this.scanned=s,o}}function Fs(e,t){let n=xs({path:e}),o=Buffer.alloc(0),s="version",i=0,a=!1,d=[],y=0,h=!1,g=(c)=>{if(h)return;h=!0,n.destroy(),t.end(c)},p=()=>g({reason:"display_protocol"}),w=(c)=>{if(h)return;if(!a){if(y+=c.byteLength,y>Ft)g({reason:"input_backpressure"});else d.push(c);return}if(n.write(c),n.writableLength>Ft)g({reason:"input_backpressure"})},f=(c)=>{o=o.subarray(c)},M=()=>{switch(s){case"version":{if(o.byteLength<12)return!1;let c=/^RFB (\d{3})\.(\d{3})\n$/.exec(o.subarray(0,12).toString("latin1"));if(!c||Number(c[1])*1000+Number(c[2])<3007)return p(),!1;return f(12),n.write(`RFB 003.007
|
|
125
|
+
`),s="security",!0}case"security":{if(o.byteLength<1)return!1;let c=o[0];if(c===0)return p(),!1;if(o.byteLength<1+c)return!1;if(!o.subarray(1,1+c).includes(1))return p(),!1;return f(1+c),n.write(Buffer.from([1,1])),s="init",!0}case"init":{if(o.byteLength<24)return!1;let c=o.readUInt32BE(20);if(c>65536)return p(),!1;if(o.byteLength<24+c)return!1;let _={width:o.readUInt16BE(0),height:o.readUInt16BE(2)};if(f(24+c),_.width===0||_.height===0)return p(),!1;s="messages";let v=Buffer.alloc(12);v.writeUInt8(2,0),v.writeUInt16BE(2,2),v.writeInt32BE(Ts,4),v.writeInt32BE(Ms,8),n.write(v),a=!0;for(let D of d)n.write(D);return d=[],y=0,t.ready(_),!h}case"skip":{let c=Math.min(i,o.byteLength);if(f(c),i-=c,i>0)return!1;return s="messages",!0}case"messages":{if(o.byteLength<1)return!1;switch(o[0]){case 1:{if(o.byteLength<6)return!1;let c=6+o.readUInt16BE(4)*6;if(o.byteLength<c)return!1;return f(c),!0}case 2:return f(1),!0;case 3:{if(o.byteLength<8)return!1;let c=o.readUInt32BE(4);if(c>S/2)return f(8),s="skip",i=c,!0;if(o.byteLength<8+c)return!1;let _=o.subarray(8,8+c).toString("latin1");return f(8+c),t.clipboard(_),!h}default:return p(),!1}}}},E=!1;return n.once("connect",()=>{E=!0}),n.on("data",(c)=>{if(h)return;o=o.byteLength?Buffer.concat([o,c]):c;while(!h&&M());}),n.once("error",()=>{if(!E)g({error:new r("display_unavailable","Reason could not reach this machine's desktop server.")})}),n.once("close",()=>g({reason:"display_closed"})),{pointer(c,_,v){let D=Buffer.alloc(6);D.writeUInt8(5,0),D.writeUInt8(v&255,1),D.writeUInt16BE(c,2),D.writeUInt16BE(_,4),w(D)},key(c,_){let v=Buffer.alloc(8);v.writeUInt8(4,0),v.writeUInt8(c?1:0,1),v.writeUInt32BE(_>>>0,4),w(v)},clipboard(c){if(Array.from(c).some((D)=>D.codePointAt(0)>255)){g({reason:"clipboard_unicode_unsupported"});return}let _=Buffer.from(c,"latin1"),v=Buffer.alloc(8);v.writeUInt8(6,0),v.writeUInt32BE(_.byteLength,4),w(Buffer.concat([v,_]))},close(){h=!0,n.destroy()}}}class Je{run=null;viewers=new Set;get running(){return this.run!==null}start(e,t,n,o){this.viewers.add(e),this.stop();let s;try{s=n()}catch{this.fail();return}Jt(s);let i={child:s,splitter:new tn};this.run=i;for(let d of[...this.viewers])d.started(t);s.stdout?.on("data",(d)=>{if(this.run!==i)return;for(let y of i.splitter.push(d,o()))for(let h of[...this.viewers])h.unit(y)});let a=()=>{if(this.run!==i)return;this.run=null,this.fail()};s.once("exit",a),s.once("error",a)}leave(e){if(!this.viewers.delete(e))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;Zt(this.run.child),this.run=null}fail(){for(let e of[...this.viewers])e.failed()}}var Xt=new WeakMap;function zs(e){let t=Xt.get(e);if(!t)Xt.set(e,t=new Je);return t}var ee=new Map;function Dn(e,t,n={}){let o=n.micros??$s,s=new $n,i=t.request.preset,a=null,d=null,y=null,h=!1,g=null,p=!1,w=!1,f=null,M=0,E=0,c=!1,_=null,v=null,D=0,L=null,P=[],te=0,N=[],Ze=new Uint32Array(Ke+1),ge=0,he=null,be=0,q=0,ye=0,Qe=0,et=0,ne=null,we=0,j={frames:0,bytes:0,since:o()},G=[],Y=0,xe,_e=!1,rn=o(),R={},V=()=>Math.round((o()-rn)/1000),tt=n.control??ut,ke=null,Se=null,nt=0,ve=!1,st={pause(){if(!g?.running)return;g.stop(),ve=!0},adopt(u){let l=u!==null&&(u.width!==d?.width||u.height!==d?.height);if(l)d=u;if(!l&&!ve)return;if(ve=!1,g)ae();else Ie()}},on=(u)=>{if(!n.resizeDesktop||!a||"kind"in a||e.done)return;let l=a.display,m=()=>[...ee.get(l)??[]];nt++,n.resizeDesktop(a,u,()=>{for(let k of m())k.pause()}).then((k)=>{for(let I of m())I.adopt(k)})},T=(u)=>{let l=Wt(u);return e.send(l),Qe+=l.byteLength,l.byteLength},se=(u)=>{if(e.done)return;if(e.open)T({type:"error",code:u});e.end({reason:u})},re=()=>Math.max(ks,X[i].kbps*1000/8*Ss),oe=()=>o()/1000,an=()=>{while(N.length>1&&N[0].atMs<oe()-Es)N.shift();return N[0]?.rttMs??null},rt=(u)=>{let l=an();if(l===null||P.length===0)return!1;let m=(l+vs)*u;return oe()-P[0].sentMs>m||te>m/1000*X[i].kbps*1000/8},cn=(u)=>{if(D===0)return;let l=Math.min(u,D-1);if(L!==null&&l<=L)return;L=l;let m=oe();while(P.length&&P[0].seq<=l){let k=P.shift();if(te-=k.bytes,k.seq!==l)continue;let I=Math.max(0,m-k.sentMs);while(N.length&&N.at(-1).rttMs>=I)N.pop();N.push({atMs:m,rttMs:I}),Ze[Math.min(Ke,Math.round(I))]++,ge++,he=Math.min(he??I,I)}},un=()=>{let u=0;for(let l=0;l<=Ke;l++)if(u+=Ze[l],u*2>=ge)return l;return 0},ln=()=>e.bufferedAmount<=re()/2&&!rt(0.5),ot=()=>{_e=!0,G=[],Y=0,g?.leave(Ee),g=null},it=(u)=>{if(e.done)return;if(u.key)R.first_key_ms??=V();if(!h){if(!g||G.length===0&&!u.key)return;if(G.push(u),Y+=u.data.byteLength,Y>re())ot();return}if(c){q++;return}if(e.bufferedAmount>re()||rt(1)){c=!0,q++,_=setInterval(()=>{if(e.done||!ln())return;if(_)clearInterval(_);_=null,c=!1,ae()},n.drainPollMs??25);return}if(!p){if(!u.key){q++;return}if(T({type:"hello",width:d.width,height:d.height,fps:X[i].fps,preset:i,codec:_s}),p=!0,R.first_frame_ms??=V(),!w&&a?.sound)T({type:"audioHello",...Q}),w=!0}let l=T({type:"frame",key:u.key,seq:D,captureMicros:u.micros,data:u.data});if(P.push({seq:D,sentMs:oe(),bytes:l}),te+=l,P.length>Ds)te-=P.shift().bytes;D++,be++,ne??=u.micros,we=u.micros,j.frames++,j.bytes+=l},Ee={started(u){i=u,p=!1,G=[],Y=0},unit:it,failed:()=>se("encoder_failed")},De=()=>{let u=(n.ffmpeg??zt)();if(!a||!d){se("encoder_failed");return}let[l,m]=[a,d],k="kind"in l&&l.kind==="simulator"?l.stream:null;if(!u&&!k){se("encoder_failed");return}if(g??="kind"in l&&l.kind==="mac_screen"?zs(n.spawn??jt):new Je,R.encoder_ms===void 0)R.encoder_ms=V(),R.encoder_shared=g.running;g.start(Ee,i,()=>{let I=X[i].fps;if(k)return k(I,X[i].kbps,Qt);if("kind"in l&&l.kind==="simulator"){let C=Math.min(0.99,en(l.size)),B={width:l.size.width*C,height:l.size.height*C};return Hs(u,fe(i,Bs(Math.min(I,30)),B,(n.macEncoder??Gt)()),l)}if("kind"in l&&l.kind==="windows_screen")return(n.spawn??me)(u,fe(i,Us(I,m),Kt(m)),{SystemRoot:process.env.SystemRoot??"C:\\Windows"});return"kind"in l?(n.spawn??jt)(u,fe(i,Ns(I),Kt(m),(n.macEncoder??Gt)()),{}):(n.spawn??me)(u,fe(i,Ls(I,m,l.display),m),{DISPLAY:l.display,XAUTHORITY:l.xauthority})},o)},ie=()=>{if(!f)return;Zt(f.child),f=null},dn=()=>{let u=(n.ffmpeg??zt)();if(f||e.done||!w||!a?.sound||!u)return;let l;try{l=(n.spawn??me)(u,Lt(),{PULSE_SERVER:Ve(a.sound)})}catch{return}Jt(l);let m={child:l,reader:new je};f=m,l.stdout?.on("data",(I)=>{if(f!==m||e.done)return;let C;try{C=m.reader.push(I)}catch{ie();return}let B=o();for(let Ce of C){if(e.bufferedAmount>re()){E++;continue}T({type:"audio",captureMicros:B,data:Ce}),M++}});let k=()=>{if(f===m)ie()};l.once("exit",k),l.once("error",k)},ae=()=>{if(!g||e.done)return;ye++,De()},Ie=()=>{if(e.done||!d)return;if(!h){if(g||_e)return;De(),xe=setTimeout(()=>{if(!h)ot()},Cs);return}if(clearTimeout(xe),R.encoder_early===void 0){if(R.encoder_early=g!==null,_e)R.hold_lapsed=!0}if(!g)De();let u=G;G=[],Y=0;for(let l of u)it(l);v??=setInterval(()=>{let l=o(),m=Math.max(0.001,(l-j.since)/1e6);T({type:"stats",stats:{fps:Math.round(j.frames/m*10)/10,kbps:Math.round(j.bytes*8/1000/m),dropped:q,restarts:ye,queued_bytes:e.bufferedAmount}}),j={frames:0,bytes:0,since:l}},Rs)};t.desktop.then((u)=>{if(e.done)return;a=u;let l={ready(m){d=m,R.desktop_ms??=V(),Ie()},clipboard(m){if(e.open&&Buffer.byteLength(m)<=S)T({type:"serverClipboard",text:m})},end(m){if("reason"in m&&e.open)T({type:"error",code:m.reason});e.end(m)}};if("kind"in u&&u.kind==="simulator")y=u.input,l.ready(u.points);else if("kind"in u&&u.kind==="windows_screen")y=(n.windowsInput??xt)(l);else if("kind"in u)y=(n.macInput??((m)=>Fn(m,Ye())))(l);else{let m=ee.get(u.display);if(!m)ee.set(u.display,m=new Set);m.add(st);let k=(n.linuxClipboard??Bt)(u,l),I=Fs(u.rfbSocket,{...l,clipboard:(C)=>{if(!k)l.clipboard(C)}});y=k?{pointer:(C,B,Ce)=>k.apply(()=>I.pointer(C,B,Ce)),key:(C,B)=>k.apply(()=>I.key(C,B)),clipboard:(C)=>k.write(C),close(){k.close(),I.close()}}:I}at()},(u)=>e.end({error:u}));function at(){if(Se||!t.viewerSameNetwork||!h||e.done||!a||!("kind"in a)||a.kind!=="mac_screen")return;Se=(n.macWindows??Bn)((u)=>{if(e.open)T({type:"windows",bounds:u})})}let ct={viewer:t.viewer??null,notify(u){if(e.open)T({type:"control",control:u})}},Pe=(u)=>{if(!y)return;if(!a||!("kind"in a)||a.kind!=="simulator")tt.claim(ct);u(y)};return{opened(){R.relay_ms??=V()},received(u){et+=u.byteLength;let l;try{l=s.push(u)}catch{se("viewer_protocol");return}for(let m of l){if(e.done)return;switch(m.type){case"ping":T({type:"pong",token:m.token});break;case"pointer":Pe((k)=>k.pointer(m.x,m.y,m.buttons));break;case"key":Pe((k)=>k.key(m.down,m.keysym));break;case"clientClipboard":Pe((k)=>k.clipboard(m.text));break;case"config":if(m.preset!==i)i=m.preset,ae();break;case"keyframeRequest":if(p&&!c)ae();break;case"ack":cn(m.seq);break;case"audioEnable":if(m.on)dn();else ie();break;case"resize":on({width:m.width,height:m.height});break;default:break}}if(!h&&!e.done){if(h=!0,R.viewer_ms=V(),t.viewer)ke=tt.join(ct);Ie(),at()}},close(){if(a&&!("kind"in a)){let u=ee.get(a.display);if(u?.delete(st),u?.size===0)ee.delete(a.display)}if(ke?.(),ke=null,Se?.close(),_)clearInterval(_);if(v)clearInterval(v);clearTimeout(xe),g?.leave(Ee),ie(),y?.close()},summary:()=>({output_bytes:Qe,input_bytes:et,video:{preset:i,frames:be,dropped:q,restarts:ye,avg_fps:ne!==null&&we>ne?Math.round((be-1)/((we-ne)/1e6)*10)/10:0,min_rtt_ms:Math.round(he??0),p50_rtt_ms:ge?un():0,audio_packets:M,audio_dropped:E,resizes:nt,connect:R}})}}var qt=null,nn=null,js=null,Gs=null;function Vs(){let e=x();return e?.features.display?e.ffmpeg:null}function sn(e){return qt??=new Promise((t)=>{ys(e,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(n,o)=>{let s=(i)=>!n&&new RegExp(`^\\s*V\\S*\\s+${i}\\s`,"m").test(o);t(nn={x264:s("libx264"),videotoolbox:s("h264_videotoolbox")})})}),qt}var Yt=null;function Nn(){return Yt??=(async()=>{let e=[x()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((n)=>Boolean(n&&ws(n)));if(!e)return null;let t=await sn(e);return t.videotoolbox||t.x264?e:null})(),Yt}function Tr(e=process.platform,t={}){if(e!=="linux"&&e!=="darwin"&&e!=="win32")return Promise.resolve(!1);let n=(t.ffmpeg??Vs)();if(!n)return Promise.resolve(!1);let o=(t.encoders??sn)(n);if(e==="linux")return o.then((i)=>i.x264);if(e==="win32"){let i=t.windowsScreen?t.windowsScreen():Gs??=bt();return Promise.all([o,i]).then(([a,d])=>a.x264&&(d?.session??0)>0)}let s=t.macScreen?t.macScreen():js??=Ge(Ye());return Promise.all([o,s]).then(([i,a])=>(i.x264||i.videotoolbox)&&a?.screen===!0&&a.accessibility)}
|
|
126
|
+
export{We,fo,F,Rn,Ve,mo,On,In,Dn,Nn,Tr,Ut,Rr,x,go};
|