@reason-machines/cli-linux-x64 0.2.415 → 0.2.419
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 +7 -8
- package/bin/reason +2 -2
- package/bin/runtime/srt/sandbox-runtime.mjs +52 -52
- package/bin/vm-hands/api-credentials-s4897qxy.js +2 -0
- package/bin/vm-hands/api-m73x3da5.js +2 -0
- package/bin/vm-hands/ask-relay-4kwcx2b7.js +8 -0
- package/bin/vm-hands/connect-cli-34b18gjs.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-j012b4bd.js +2 -0
- package/bin/vm-hands/desktop-account-0q0arpzk.js +2 -0
- package/bin/vm-hands/device-workspace-3jxhs54b.js +2 -0
- package/bin/vm-hands/hands-worker-source-y64axsw3.js +2 -0
- package/bin/vm-hands/index-194s4vz0.js +12818 -0
- package/bin/vm-hands/install-receipt-1g68b446.js +2 -0
- package/bin/vm-hands/local-automation-k2w46hn2.js +2 -0
- package/bin/vm-hands/local-capabilities-tdzbqmrb.js +2 -0
- package/bin/vm-hands/local-desktop-users-6thzvydd.js +2 -0
- package/bin/vm-hands/local-display-mac-59ma7sxa.js +2 -0
- package/bin/vm-hands/local-display-session-4833qq7h.js +2 -0
- package/bin/vm-hands/local-display-video-c1143mz6.js +2 -0
- package/bin/vm-hands/local-managed-process-mr0zpk7c.js +2 -0
- package/bin/vm-hands/local-pty-session-bwarwpsd.js +2 -0
- package/bin/vm-hands/managed-runtime-vz1wqwwg.js +2 -0
- package/bin/vm-hands/network-contract-gprc37sw.js +2 -0
- package/bin/vm-hands/package-ej9snd47.js +2 -0
- package/bin/vm-hands/permissions-7sfghef4.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-jsrkawe2.js +2 -0
- package/bin/vm-hands/serve-service-kngyzh74.js +2 -0
- package/bin/vm-hands/status-jz29fb95.js +96 -0
- package/bin/vm-hands/version-g29vt13t.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-0h4qmgm2.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-0k13wmzm.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-1exfjv79.js +52 -0
- package/bin/vm-hands/vm-hands-entry-lite-26q3hbdc.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-28s7v15d.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-2m5dwrdf.js +6 -0
- package/bin/vm-hands/vm-hands-entry-lite-37hvds7z.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-3rqdzqhk.js +112 -0
- package/bin/vm-hands/vm-hands-entry-lite-4gh5kfr4.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-t7an5zg2.js → vm-hands-entry-lite-4k4h9rcq.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-6nwbqg37.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-m11j0f9q.js → vm-hands-entry-lite-6y6pz2yw.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-714wspqb.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-7zk0r3p9.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-9qep7pka.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-bdhjpv7g.js → vm-hands-entry-lite-agsp101y.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-am6kj1n1.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-as1tkffn.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-bxt4n1nj.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-c2g3wmkp.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-d2w8tghq.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-d98m00b8.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-daxcxjze.js +344 -0
- package/bin/vm-hands/vm-hands-entry-lite-dcnyve97.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-e1b89x66.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-ej5ffjck.js +105 -0
- package/bin/vm-hands/vm-hands-entry-lite-ejkba2nk.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-f3wh0dza.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-f5xb489y.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-feybcq63.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-fpp2bs9y.js +452 -0
- package/bin/vm-hands/{vm-hands-entry-lite-qxchbbew.js → vm-hands-entry-lite-fzkfajew.js} +9 -5
- package/bin/vm-hands/vm-hands-entry-lite-gt497d5x.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-gxper06w.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-j2ng164q.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-jp9q2vsx.js +127 -0
- package/bin/vm-hands/vm-hands-entry-lite-magmzx9c.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-ntx8fdyq.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-pfzczmaa.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-pkc4ry5x.js +539 -0
- package/bin/vm-hands/vm-hands-entry-lite-pp7jfqzr.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-q8wkrzer.js +66 -0
- package/bin/vm-hands/vm-hands-entry-lite-s823n1q9.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-s9xf5z69.js +7 -0
- package/bin/vm-hands/vm-hands-entry-lite-tchc7z17.js +128 -0
- package/bin/vm-hands/vm-hands-entry-lite-tytfs183.js +42 -0
- package/bin/vm-hands/vm-hands-entry-lite-v4jtxgaj.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-vgpt2n1v.js +11 -0
- package/bin/vm-hands/{vm-hands-entry-lite-9c95p6n9.js → vm-hands-entry-lite-vsa7t6m9.js} +54 -54
- package/bin/vm-hands/vm-hands-entry-lite-xp3qzxk5.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -3
- package/bin/vm-hands/vm-hands-executor-epyhpjv3.js +11 -0
- package/bin/vm-hands/vm-hands-op-runner-fn1qph82.js +2 -0
- package/bin/vm-hands/vm-hands-runtime-8vt9etvv.js +4 -0
- package/bin/vm-hands/worker-preview-readiness-yfjgban2.js +2 -0
- package/bin/vm-hands/worker-sandbox-z0t69av8.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-cjv8m2zy.js +0 -2
- package/bin/vm-hands/api-credentials-m5akr9fv.js +0 -2
- package/bin/vm-hands/connect-cli-d60gmgnx.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-dkqb4rqy.js +0 -2
- package/bin/vm-hands/desktop-account-5v7x0ajx.js +0 -2
- package/bin/vm-hands/device-workspace-p9q9dckg.js +0 -2
- package/bin/vm-hands/fsevents-ekt70rcc.js +0 -2
- package/bin/vm-hands/hands-worker-source-cgrpm21b.js +0 -2
- package/bin/vm-hands/index-k8kcz8a3.js +0 -12818
- package/bin/vm-hands/install-receipt-7vt2y2vh.js +0 -2
- package/bin/vm-hands/local-automation-4htjhv65.js +0 -2
- package/bin/vm-hands/local-capabilities-c04tbapa.js +0 -2
- package/bin/vm-hands/local-desktop-users-q886k0mm.js +0 -2
- package/bin/vm-hands/local-display-mac-w85956f1.js +0 -2
- package/bin/vm-hands/local-display-session-pkz7a5q9.js +0 -2
- package/bin/vm-hands/local-pty-session-5f50sqq0.js +0 -2
- package/bin/vm-hands/managed-runtime-ppypxbh9.js +0 -2
- package/bin/vm-hands/network-contract-9x9kc5vv.js +0 -2
- package/bin/vm-hands/package-78fkast4.js +0 -2
- package/bin/vm-hands/permissions-xt02c6dh.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-2tnghj3b.js +0 -2
- package/bin/vm-hands/serve-service-wanptaqv.js +0 -2
- package/bin/vm-hands/status-gt7c4ke0.js +0 -10
- package/bin/vm-hands/version-bq5j7cqg.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-09m2cdkw.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-0xrsph3r.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-1cwqa4jr.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-1rrb66r9.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-1rtkf2xm.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-22kfyvnk.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-2hvbgp1n.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-2wgdvb15.js +0 -14
- package/bin/vm-hands/vm-hands-entry-lite-2wvsyggd.js +0 -540
- package/bin/vm-hands/vm-hands-entry-lite-463m6ejk.js +0 -458
- package/bin/vm-hands/vm-hands-entry-lite-6aeea05q.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-88swf2qr.js +0 -6
- package/bin/vm-hands/vm-hands-entry-lite-89z488gz.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-8ns59paz.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-8t9xssf9.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-907pa7f9.js +0 -65
- package/bin/vm-hands/vm-hands-entry-lite-9ay6f56v.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ab2m9erf.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-b885gwfh.js +0 -7
- package/bin/vm-hands/vm-hands-entry-lite-cc2tgsqp.js +0 -105
- package/bin/vm-hands/vm-hands-entry-lite-ckv17tn8.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-eqgj4acy.js +0 -112
- package/bin/vm-hands/vm-hands-entry-lite-ewwx4fr3.js +0 -250
- package/bin/vm-hands/vm-hands-entry-lite-f5e3dbgk.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-grtycq6y.js +0 -52
- package/bin/vm-hands/vm-hands-entry-lite-gvwdy3rf.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-hj8n59y9.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-k278g9kj.js +0 -42
- package/bin/vm-hands/vm-hands-entry-lite-kq0qmsw8.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-pgb514h0.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-pmcz7j7t.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-q0k6kx6d.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-qq9w7wq6.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-qy9xg6em.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-qysyf65v.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-rwxbhwky.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-txn44020.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-vrqzr15t.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-zg36myyf.js +0 -5
- package/bin/vm-hands/vm-hands-executor-7k9z9988.js +0 -11
- package/bin/vm-hands/vm-hands-op-runner-n8p81rwm.js +0 -2
- package/bin/vm-hands/vm-hands-runtime-bqsz7h0h.js +0 -4
- package/bin/vm-hands/worker-sandbox-smqj3mbe.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{le as ae,ne}from"./vm-hands-entry-lite-ej5ffjck.js";import{$f as be}from"./vm-hands-entry-lite-tytfs183.js";import{Cg as O,Dg as Te}from"./vm-hands-entry-lite-tchc7z17.js";import{Gg as C,Hg as ie,Ig as M,Lg as Oe,Sg as j,Tg as K,Ug as v}from"./vm-hands-entry-lite-jp9q2vsx.js";import{Di as xe}from"./vm-hands-entry-lite-28s7v15d.js";import{oj as se}from"./vm-hands-entry-lite-1exfjv79.js";import{Sj as J}from"./vm-hands-entry-lite-0h4qmgm2.js";import{Yj as x}from"./vm-hands-entry-lite-6nwbqg37.js";import{Pk as Se,Qk as oe}from"./vm-hands-entry-lite-3rqdzqhk.js";import{Wk as Ie,al as Ne}from"./vm-hands-entry-lite-v4jtxgaj.js";import{hl as ye}from"./vm-hands-entry-lite-gxper06w.js";import{ql as p}from"./vm-hands-entry-lite-magmzx9c.js";import{spawn as S,spawnSync as pt}from"child_process";import{createHash as ft,randomUUID as ve}from"crypto";import{closeSync as mt,copyFileSync as de,existsSync as q,fstatSync as _t,mkdirSync as pe,openSync as ht,readdirSync as D,readFileSync as Y,readlinkSync as wt,renameSync as Re,rmSync as gt,statSync as bt,writeFileSync as xt}from"fs";import{connect as St}from"net";import{tmpdir as F,userInfo as $e}from"os";import{basename as fe,delimiter as yt,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";
|
|
@@ -849,7 +849,11 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
|
|
|
849
849
|
process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
|
|
850
850
|
}
|
|
851
851
|
}
|
|
852
|
-
`;import{spawn as
|
|
853
|
-
`).at(-1)?.slice(-300)??"";if(!
|
|
854
|
-
`);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${X}${J?`: ${J}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function z(e,o,t,n={}){let s=await kt(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 qe,spawn as We}from"child_process";import{closeSync as Fe,mkdirSync as Ge,openSync as He}from"fs";import{dirname as E,join as je}from"path";import{promisify as Ke}from"util";var Xe=Ke(qe),Z="x-apple.systempreferences:com.apple.preference.security",Je={accessibility:`${Z}?Privacy_Accessibility`,screen:`${Z}?Privacy_ScreenCapture`},Ye=64,A=new Map;function C(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=Ye)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function ze(){let e=a(),o=Cn(be(e),process.env),t=je(e,".local","share","reason","desktop-install.log");Ge(E(t),{recursive:!0,mode:448});let n=He(t,"a",384);try{let s=We(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Fe(n)}}var T={open:async(e,o)=>{await Xe("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>st(e,o),tile:Br,installDesktop:ze},Q=!1;async function ee(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function oe(e,o,t,n){if(await t.open([Je[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function Ve(e,o,t,n,s){for(let i of t){if(!C(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await oe(o,i,n,s)}}var Ze={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 te(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function et(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 re(e,o=T){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return te({result:{tools:[Ze]}});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&&!Q){Q=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&C(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)C(n,`grant:${m}`);for(let m of d)await oe(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(C(n,"page:chrome-extension"))await ee(Fi,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?et(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 ee(u,o,s),te({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 ne(e,o=T){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 Ve(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,ft=18874368,wt=8192,_t=65536,yt=55000,bt=60000,St=4,xt=40000,Rt=/^[0-9a-f-]{36}$/,ce=Y,It=me();function N(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function he(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!N(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==ht||t.kind!=="browser")||JSON.stringify(t).length>_t)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function mn(e=process.platform,o=P){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var vt="__computer-use";function ss(e=P){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function we(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 Ot(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 At(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 Et=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Tt=33554432;function Nt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=N(t)&&N(t.result)?t.result.metadata:null;if(!N(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Et.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function _e(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=Nt(await Ot(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(ut(m).size>Tt)continue;let l=K(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Pt(e,o,t){return(await _e(e,o,t))[0]?.instance??null}function ye(e,o,t){return Pt(e.nativeHost,o,{socketDir:At(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var le=/^(Default|Profile ([0-9]+))$/;async function Dt(e,o,t=a(),n=Ct){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(le.exec(l)?.[2]??-1),c=i.filter((l)=>le.test(l)&&M(f(s,l,"Extensions",$e))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",$e);return(await _e(e,o,{socketDir:n,extensionId:$e,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((h)=>d(h)===l),instance:p,socket:g}))}async function Mt(e,o,t=a(),n=Ct){let s=(await Dt(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 ue(e){return new Promise((o)=>{let t=pt({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 Se(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 W=new Map;function H(e,o){let t=W.get(e);if(!t)t=o().finally(()=>W.delete(e)),W.set(e,t);return t}async function Ut(e,o){if(await ue(e))return;if(lt(e,{force:!0}),await we("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await Se(()=>ue(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function de(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await ye(e,o,t)!==null:async()=>await we(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");V(l);let p=f(l,"NativeMessagingHosts");ie(p,{recursive:!0,mode:448});let g=yr(e.platform).nativeHostManifests[0];se(g,f(p,ae(g)));let h=e.browser.slice(0,e.browser.indexOf(".app/")+4),y=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=R("/usr/bin/open",["-g","-n","-a",h,"--args",`--user-data-dir=${l}`,...y],{env:o,stdio:"ignore"})}else if(v(e)){let l=f(t,"browser-profile");V(l),tt(x("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");ie(p,{recursive:!0,mode:448});let g=yr(e.platform).nativeHostManifests[0];se(g,f(p,ae(g)));let h=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let y=it(u,"a",384);c=nt(y).size,i=R(e.browser,[`--user-data-dir=${l}`,...s,...h,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",y,y],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),rt(y)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await Se(async()=>d||(m=await n()),xt),!m){if(u&&K(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 as(e){await Re(e,!0)}function cs(e){return xe(e,ke(e))}function xe(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function ke(e){let o=f(e.root,"automation");if(!M(o)||!Lt(e.automation))return e.automation;if(!$t(xe(e,o)))try{fe(o,e.automation)}catch{}return M(o)?o:e.automation}function Lt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function $t(e){let o;try{o=ct(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 Re(e,o){gt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=ke(e);V(t);let n=ge().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,...Bt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:vt};if(!o)return l;await H("browser",()=>de(e,l,t));let p=await ye(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 Be(),u=f(t,"home"),c=f(t,"runtime");V(u),V(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:Qe(i.sound)}:{}};if(await H("bus",()=>Ut(d,m)),o)await H("browser",()=>de(e,m,t));return m}function Bt(){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(mt)}}async function qt(e,o,t){let n=ge().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 Mt(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function Wt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${ot("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||K(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;dt(t,e,{mode:384}),fe(t,o)}return[o]}function Ie(e,o,t,n){if(typeof ce!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ce;return new Promise((i,u)=>{let c=R(e,Wt(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,h=(w)=>{if(p??=w,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")}},y=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>h(new r("automation_timed_out","Reason automation did not finish in time.")),yt),S=()=>h(new r("cancelled","Reason cancelled the automation call."));if(n.addEventListener("abort",S,{once:!0}),c.stdout.on("data",(w)=>{if(m+=w.byteLength,m>ft)h(new r("automation_output_too_large","Reason automation output is too large."));else d.push(w)}),c.stderr.setEncoding("utf8").on("data",(w)=>{l=(l+w).slice(-wt)}),c.stdin.on("error",()=>{}),c.once("error",()=>y(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>y(()=>{if(p)u(p);else i({code:w??1,stdout:Buffer.concat(d),stderr:l})})),n.aborted)S();c.stdin.end(t)})}var k=new Map;function Ft(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=St)k.delete(k.keys().next().value);let n=me();return k.set(n,{runId:e,bytes:o,expiresAt:t+bt}),n}async function ve(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ie)(e.node,s,JSON.stringify(o),t)}async function ls(e,o){let t=he({call:e});if(!("call"in t))D();let n=P();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 ve(n,t.call,o)}function pe(e,o,t){let n=e.stdout.byteLength>j?Ft(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:It,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function gn(e,o={}){let t=he(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??P)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??at)():[],c=o.macSetup??T,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 pe(await re({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=await _i(e.runId,e.signal,o.now),p="account"in o?o.account??null:G(),g;try{if(m){let h=await(o.userChromeEnvironment??qt)(s,m,e.signal);e.signal.throwIfAborted(),g=await(o.runtime??Ie)(s.node,h,JSON.stringify(t.call),e.signal)}else if(p)g=await(o.delegate??z)(p,t.call,e.signal);else g=await ve(s,t.call,e.signal,o)}finally{l()}if(i)g=await ne({runId:e.runId,call:t.call,identity:u,output:g,signal:e.signal},c);return pe(g,e.runId,n)}
|
|
855
|
-
|
|
852
|
+
`;import{spawn as Ge}from"child_process";import{basename as Me}from"path";var Ke="__desktop-call",ze="/usr/bin/setpriv",Je=27262976,je=8192,Ye=2000;function U(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Xe(e){try{return JSON.parse(e)}catch{return null}}function Ve(){return[process.execPath,...Me(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Ke]}function Ze(e,r,t,i={}){t.throwIfAborted();let o=i.command??Ve();return new Promise((s,c)=>{let a=(i.spawnProcess??Ge)(ze,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...o],{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"}}),l=[],d=0,n="",u=null,m=!1,_,g=(w)=>{try{process.kill(-a.pid,w)}catch{a.kill(w)}},N=(w)=>{u??=w,g("SIGTERM"),_??=setTimeout(()=>g("SIGKILL"),Ye)},y=()=>N(new p("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",y,{once:!0});let h=(w)=>{if(m)return;m=!0,clearTimeout(_),t.removeEventListener("abort",y),w()};if(a.stdout.on("data",(w)=>{if(d+=w.byteLength,d>Je)N(new p("desktop_delegate_failed","Reason's desktop reply is too large."));else l.push(w)}),a.stderr.setEncoding("utf8").on("data",(w)=>{n=(n+w).slice(-je)}),a.stdin.on("error",()=>{}),a.once("error",()=>h(()=>c(u??new p("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),a.once("close",(w,Ue)=>h(()=>{if(u)return c(u);let b=Xe(Buffer.concat(l).toString("utf8"));if(U(b)&&b.ok===!0&&U(b.result))return s(b.result);let R=U(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new p(b.code.slice(0,120),b.message.slice(0,2000)):null,X=`exited ${w??Ue}${R?"":" with no reply"}`,V=n.trim().split(`
|
|
853
|
+
`).at(-1)?.slice(-300)??"";if(!R||R.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${X}${n?`: ${n.trim().slice(-500)}`:""}
|
|
854
|
+
`);if(R)return c(R);c(new p("desktop_delegate_failed",`Reason's desktop operation failed (${X}${V?`: ${V}`:""}).`))})),t.aborted)y();a.stdin.end(JSON.stringify(r))})}async function H(e,r,t,i={}){let o=await Ze(e,{op:"automation",call:r},t,i);if(!Number.isSafeInteger(o.code)||typeof o.stdout!=="string"||typeof o.stderr!=="string")throw new p("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:o.code,stdout:Buffer.from(o.stdout,"base64"),stderr:o.stderr}}import{execFile as He,spawn as Qe}from"child_process";import{closeSync as et,mkdirSync as tt,openSync as rt}from"fs";import{dirname as A,join as it}from"path";import{promisify as ot}from"util";var st=ot(He),Q="x-apple.systempreferences:com.apple.preference.security",at={accessibility:`${Q}?Privacy_Accessibility`,screen:`${Q}?Privacy_ScreenCapture`},nt=64,$=new Map;function k(e,r){let t=$.get(e);if(t?.has(r))return!1;if(!t){if($.size>=nt)$.delete($.keys().next().value);t=new Set,$.set(e,t)}return t.add(r),!0}function ct(){let e=x(),r=ne(ae(e),process.env),t=it(e,".local","share","reason","desktop-install.log");tt(A(t),{recursive:!0,mode:448});let i=rt(t,"a",384);try{let o=Qe(r,["desktop","install"],{detached:!0,stdio:["ignore",i,i],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});o.on("error",()=>{return}),o.unref()}finally{et(i)}}var P={open:async(e,r)=>{await st("/usr/bin/open",e,{signal:r,timeout:1e4,maxBuffer:8192})},request:(e,r)=>oe(e,r),tile:se,installDesktop:ct},ee=!1;async function te(e,r,t){try{await r.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await r.open([e],t)}}async function ce(e,r,t,i){if(await t.open([at[r]],i).catch(()=>{}),e[0]&&!i.aborted)t.tile(A(A(A(e[0]))),r)}async function lt(e,r,t,i,o){for(let s of t){if(!k(e,`grant:${s}`))continue;o.throwIfAborted(),await i.request(r,s).catch(()=>null),await ce(r,s,i,o)}}var ut={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 dt(e){if(typeof e!=="string")return null;try{let r=new URL(e);return r.protocol==="https:"||r.protocol==="http:"?r.href:null}catch{return null}}async function le(e,r=P){let{call:t,runId:i,signal:o}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[ut]}});if(t.operation!=="call")throw new p("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&&!ee){ee=!0;try{r.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&k(i,"grant:probe")){let a=await r.request(e.identity).catch(()=>null),l=a?[...a.accessibility?[]:["accessibility"],...a.screen?[]:["screen"]]:[];for(let d of l)k(i,`grant:${d}`);for(let d of l)await ce(e.identity,d,r,o)}throw new p("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(k(i,"page:chrome-extension"))await te(ie,r,o).catch(()=>{});let s=t.arguments,c=t.operation==="call"&&t.tool==="open_tab"&&s&&typeof s==="object"&&!Array.isArray(s)?dt(s.url):null;if(!c)throw new p("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 te(c,r,o),re({result:{content:[{type:"text",text:JSON.stringify({opened:c,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 ue(e,r=P){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 i=t.permissions;if(!i||typeof i!=="object")return e.output;let o=i,s=[...o.accessibility==="missing"?["accessibility"]:[],...o.screenRecording==="missing"?["screen"]:[]];if(s.length===0)return e.output;return await lt(e.runId,e.identity,s,r,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:s}))}}var z=172032,It=18874368,Nt=8192,Ot=65536,Tt=55000,vt=60000,Rt=4,$t=40000,At=/^[0-9a-f-]{36}$/,me=Z,kt=ve();function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function E(){throw new p("invalid_automation_request","Reason automation request is malformed.")}function Ae(e){let r=Object.keys(e).sort().join(",");if(r==="call"||r==="browser,call"){let t=e.call,i=r==="browser,call";if(!W(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||i&&(e.browser!==be||t.kind!=="browser")||JSON.stringify(t).length>Ot)E();return{call:t,userChrome:i}}if(r==="offset,output_id"){if(typeof e.output_id!=="string"||!At.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)E();return{output_id:e.output_id,offset:e.offset}}return E()}function Wr(e=process.platform,r=v){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&r()?.features.computer===!0}var Pt="__computer-use";function Ct(e){let r=(t)=>t?"granted":"missing";return`Permissions: accessibility=${r(e.accessibility)}, screenRecording=${r(e.screen)}
|
|
855
|
+
`}function Wt(e,r,t,i={stdin:process.stdin,stdout:process.stdout}){return new Promise((o)=>{let s=S(e,r,{env:t,stdio:["pipe","pipe","inherit"]}),c=(n)=>{s.kill(n)},a=["SIGTERM","SIGINT","SIGHUP"];for(let n of a)process.on(n,c);i.stdin.pipe(s.stdin),s.stdin.on("error",()=>{return}),s.stdout.pipe(i.stdout,{end:!1});let l=!1,d=(n)=>{if(l)return;l=!0;for(let u of a)process.off(u,c);i.stdin.unpipe(s.stdin),i.stdout.write("",()=>o(n))};s.once("error",()=>d(127)),s.once("close",(n)=>d(n??1))})}async function Er(e,r={}){let t=r.stderr??process.stderr,i=(r.identity??J)(),o=(r.components??v)();if(i.length===0||o?.platform!=="darwin-arm64")return t.write(`Reason computer use: Reason's background identity cannot run Open Computer Use here (computer_use_identity_unavailable)
|
|
856
|
+
`),1;if(e.length===1&&e[0]==="doctor"){let a=await(r.grants??Se)(i);if(!a)return t.write(`Reason computer use: Reason's permissions could not be read (computer_use_permission_status_unavailable)
|
|
857
|
+
`),1;return(r.stdout??process.stdout).write(Ct(a)),0}if(e.length!==1||e[0]!=="mcp")return t.write(`Usage: reason __computer-use mcp|doctor
|
|
858
|
+
`),2;let[s,...c]=i;return(r.run??Wt)(s,[...c,o.ocu,"mcp"],{...process.env,OPEN_COMPUTER_USE_DISABLE_APP_AGENT_PROXY:"1"})}function qr(e=v){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ke(e,r,t,i){return new Promise((o)=>{let s=S(e,r,{env:t,stdio:"ignore",windowsHide:!0}),c=setTimeout(()=>{s.kill("SIGKILL"),o(-1)},i);s.once("error",()=>{clearTimeout(c),o(-1)}),s.once("exit",(a)=>{clearTimeout(c),o(a??-1)})})}function Et(e,r,t,i){return new Promise((o)=>{let s=S(e,r,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),c="";s.stdout.setEncoding("utf8").on("data",(l)=>{c+=l});let a=setTimeout(()=>{s.kill("SIGKILL"),o(null)},i);s.once("error",()=>{clearTimeout(a),o(null)}),s.once("close",(l)=>{clearTimeout(a),o(l===0?c:null)})})}function qt(e){return T(e)?f(F(),"open-browser-use"):"/tmp/open-browser-use"}function T(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Dt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ft=33554432;function Bt(e,r){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let i=W(t)&&W(t.result)?t.result.metadata:null;if(!W(i)||i.extensionId!==r)return null;return typeof i.extensionInstanceId==="string"&&Dt.test(i.extensionInstanceId)?i.extensionInstanceId:null}async function Pe(e,r,t){let i=t.storages.map((a)=>{try{return D(a).filter((l)=>l.endsWith(".log")||l.endsWith(".ldb")).map((l)=>f(a,l))}catch{return[]}}),o;try{o=i.some((a)=>a.length>0)?D(t.socketDir).filter((a)=>a.endsWith(".sock")):[]}catch{return[]}let s=[];for(let a of o){let l=f(t.socketDir,a),d=Bt(await Et(e,["info","--socket",l,"--timeout","2s"],r,5000),t.extensionId);if(d)s.push({instance:d,socket:l})}let c=[];for(let[a,l]of(s.length>0?i:[]).entries())for(let d of l)try{if(bt(d).size>Ft)continue;let n=Y(d),u=s.find((m)=>n.includes(m.instance));if(u){c.push({storage:t.storages[a],...u});break}}catch{}return c}async function Ut(e,r,t){return(await Pe(e,r,t))[0]?.instance??null}function Ce(e,r,t){return Ut(e.nativeHost,r,{socketDir:qt(e),extensionId:M,storages:[f(t,"browser-profile","Default","Local Extension Settings",M)]})}var _e=/^(Default|Profile ([0-9]+))$/;async function Lt(e,r,t=x(),i=j){let o=f(t,"Library","Application Support","Google","Chrome"),s=[];try{s=D(o)}catch(n){if(n.code==="EPERM")throw new p("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 c=(n)=>Number(_e.exec(n)?.[2]??-1),a=s.filter((n)=>_e.test(n)&&q(f(o,n,"Extensions",C))).sort((n,u)=>c(n)-c(u)),l=(n)=>f(o,n,"Local Extension Settings",C);return(await Pe(e,r,{socketDir:i,extensionId:C,storages:a.map(l)})).map(({storage:n,instance:u,socket:m})=>({profile:a.find((_)=>l(_)===n),instance:u,socket:m}))}async function Gt(e,r,t=x(),i=j){let o=(await Lt(e,r,t,i))[0]?.instance;if(!o)throw new p("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 o}function he(e){return new Promise((r)=>{let t=St({path:e}),i=(o)=>{t.destroy(),r(o)};t.setTimeout(1000,()=>i(!1)),t.once("error",()=>i(!1)),t.once("connect",()=>i(!0))})}async function We(e,r){let t=Date.now()+r;while(Date.now()<t){if(await e())return!0;await new Promise((i)=>setTimeout(i,200))}return!1}var L=new Map;function G(e,r){let t=L.get(e);if(!t)t=r().finally(()=>L.delete(e)),L.set(e,t);return t}async function Mt(e,r){if(await he(e))return;if(gt(e,{force:!0}),await ke("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],r,1e4)!==0||!await We(()=>he(e),5000))throw new p("automation_unavailable","Reason could not start the desktop session bus.")}async function we(e,r,t){let i=e.platform==="darwin-arm64"||T(e)?async()=>await Ce(e,r,t)!==null:async()=>await ke(e.nativeHost,["info"],r,5000)===0;if(await i())return;let o=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],s,c=null,a=0;if(e.platform==="darwin-arm64"){let n=f(t,"browser-profile");O(n);let u=f(n,"NativeMessagingHosts");pe(u,{recursive:!0,mode:448});let m=K(e.platform).nativeHostManifests[0];de(m,f(u,fe(m)));let _=e.browser.slice(0,e.browser.indexOf(".app/")+4),g=o.filter((N)=>N!=="about:blank").concat("--no-startup-window","--use-mock-keychain");s=S("/usr/bin/open",["-g","-n","-a",_,"--args",`--user-data-dir=${n}`,...g],{env:r,stdio:"ignore"})}else if(T(e)){let n=f(t,"browser-profile");O(n),pt(ye("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 u=o.filter((m)=>m!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");s=S(e.browser,[`--user-data-dir=${n}`,...u],{detached:!0,stdio:"ignore",env:r})}else{let n=f(r.HOME,".config","google-chrome"),u=f(n,"NativeMessagingHosts");pe(u,{recursive:!0,mode:448});let m=K(e.platform).nativeHostManifests[0];de(m,f(u,fe(m)));let _=process.geteuid?.()===0?["--no-sandbox"]:[];c=f(t,"browser.log");let g=ht(c,"a",384);a=_t(g).size,s=S(e.browser,[`--user-data-dir=${n}`,...o,..._,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",g,g],env:{...r,ACCESSIBILITY_ENABLED:"1"}}),mt(g)}let l=!1;s.once("error",()=>{l=!0}),s.once("exit",(n)=>{l||=n!==0}),s.unref();let d=!1;if(await We(async()=>l||(d=await i()),$t),!d){if(c&&Y(c).subarray(a).toString("utf8").includes("No usable sandbox"))throw new p("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 p("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Dr(e){await De(e,!0)}function Fr(e){return Ee(e,qe(e))}function Ee(e,r){return e.platform==="darwin-arm64"||T(e)?f(r,"browser-profile"):f(r,"home",".config","google-chrome")}function qe(e){let r=f(e.root,"automation");if(!q(r)||!Kt(e.automation))return e.automation;if(!zt(Ee(e,r)))try{Re(r,e.automation)}catch{}return q(r)?r:e.automation}function Kt(e){try{return D(e).length===0}catch(r){return r.code==="ENOENT"}}function zt(e){let r;try{r=wt(f(e,"SingletonLock"))}catch{return!1}let t=Number(r.slice(r.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(i){return i.code==="EPERM"}}async function De(e,r){Ie({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=qe(e);O(t);let i=$e().username,o={USER:i,LOGNAME:i,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||T(e)){let n=T(e)?{...o,...Jt(),HOME:x()}:{...o,HOME:x(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Pt};if(!r)return n;await G("browser",()=>we(e,n,t));let u=await Ce(e,n,t);if(!u)throw new p("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...n,REASON_AUTOMATION_OBU_INSTANCE:u,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let s=await Te(),c=f(t,"home"),a=f(t,"runtime");O(c),O(a);let l=f(t,"bus"),d={...o,HOME:c,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:s.display,XAUTHORITY:s.xauthority,XDG_RUNTIME_DIR:a,DBUS_SESSION_BUS_ADDRESS:`unix:path=${l}`,...s.sound?{PULSE_SERVER:Oe(s.sound)}:{}};if(await G("bus",()=>Mt(l,d)),r)await G("browser",()=>we(e,d,t));return d}function Jt(){let e=process.env.SystemRoot??"C:\\Windows",r=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((i)=>process.env[i]?[[i,process.env[i]]]:[])),t=f(e,"System32");return{...r,SystemRoot:e,windir:e,TEMP:F(),TMP:F(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(yt)}}async function jt(e,r,t){let i=$e().username,o={USER:i,LOGNAME:i,HOME:x(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:r,REASON_AUTOMATION_BACKGROUND_TABS:"1"},s=await Gt(r,o);return t.throwIfAborted(),{...o,REASON_AUTOMATION_OBU_INSTANCE:s}}function Yt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let r=f(F(),`reason-automation-${ft("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!q(r)||Y(r,"utf8")!==e){let t=`${r}.${process.pid}.tmp`;xt(t,e,{mode:384}),Re(t,r)}return[r]}function Fe(e,r,t,i){if(typeof me!=="string")return Promise.reject(new p("automation_unavailable","This Reason build has no automation runtime."));let o=me;return new Promise((s,c)=>{let a=S(e,Yt(o),{env:{...r,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),l=[],d=0,n="",u=null,m=!1,_=(h)=>{if(u??=h,process.platform==="win32"&&a.pid){S(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(a.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>a.kill("SIGKILL"));return}try{process.kill(-a.pid,"SIGKILL")}catch{a.kill("SIGKILL")}},g=(h)=>{if(m)return;m=!0,clearTimeout(N),i.removeEventListener("abort",y),h()},N=setTimeout(()=>_(new p("automation_timed_out","Reason automation did not finish in time.")),Tt),y=()=>_(new p("cancelled","Reason cancelled the automation call."));if(i.addEventListener("abort",y,{once:!0}),a.stdout.on("data",(h)=>{if(d+=h.byteLength,d>It)_(new p("automation_output_too_large","Reason automation output is too large."));else l.push(h)}),a.stderr.setEncoding("utf8").on("data",(h)=>{n=(n+h).slice(-Nt)}),a.stdin.on("error",()=>{}),a.once("error",()=>g(()=>c(u??new p("automation_unavailable","Reason could not start the automation runtime.")))),a.once("close",(h)=>g(()=>{if(u)c(u);else s({code:h??1,stdout:Buffer.concat(l),stderr:n})})),i.aborted)y();a.stdin.end(t)})}var I=new Map;function Xt(e,r,t){for(let[o,s]of I)if(s.expiresAt<=t)I.delete(o);while(I.size>=Rt)I.delete(I.keys().next().value);let i=ve();return I.set(i,{runId:e,bytes:r,expiresAt:t+vt}),i}async function Be(e,r,t,i={}){let o=await(i.environment??De)(e,r.kind==="browser");return t.throwIfAborted(),await(i.runtime??Fe)(e.node,o,JSON.stringify(r),t)}async function Br(e,r){let t=Ae({call:e});if(!("call"in t))E();let i=v();if(!i?.features.computer||t.call.kind==="browser"&&!i.features.browser)throw new p("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Be(i,t.call,r)}function ge(e,r,t){let i=e.stdout.byteLength>z?Xt(r,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:kt,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,z).toString("base64"),...i?{output_id:i}:{}}}async function Ur(e,r={}){let t=Ae(e.payload),i=(r.now??Date.now)();if("output_id"in t){let _=I.get(t.output_id);if(!_||_.runId!==e.runId||_.expiresAt<=i||t.offset>_.bytes.byteLength)throw new p("automation_output_unavailable","Reason automation output expired.");return{chunk:_.bytes.subarray(t.offset,t.offset+z).toString("base64")}}let o=(r.components??v)(),s=(r.platform??process.platform)==="darwin",c=s?(r.macIdentity??J)():[],a=r.macSetup??P,l=!o?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!o.features.browser;if(s&&(l||c.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return ge(await le({runId:e.runId,call:t.call,identity:c,desktopMissing:l,signal:e.signal},a),e.runId,i);if(!o?.features.computer)throw new p("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let d=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!d)throw new p("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"&&!d&&!o.features.browser)throw new p("automation_browser_not_installed",!o.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 n=await Ne(e.runId,e.signal,r.now),u="account"in r?r.account??null:xe(),m;try{if(d){let _=await(r.userChromeEnvironment??jt)(o,d,e.signal);e.signal.throwIfAborted(),m=await(r.runtime??Fe)(o.node,_,JSON.stringify(t.call),e.signal)}else if(u)m=await(r.delegate??H)(u,t.call,e.signal);else m=await Be(o,t.call,e.signal,r)}finally{n()}if(s)m=await ue({runId:e.runId,call:t.call,identity:c,output:m,signal:e.signal},a);return ge(m,e.runId,i)}
|
|
859
|
+
export{Ze as Xd,z as Yd,Ae as Zd,Wr as _d,Wt as $d,Er as ae,qr as be,Lt as ce,Gt as de,Dr as ee,Fr as fe,Br as ge,Ur as he};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ol as M}from"./vm-hands-entry-lite-6y6pz2yw.js";import{pl as D}from"./vm-hands-entry-lite-0k13wmzm.js";import{execFileSync as A}from"child_process";import{realpathSync as U,statSync as F}from"fs";import{tmpdir as j}from"os";import{createRequire as I}from"module";import{win32 as Z}from"path";var J=["/bin/bash","/usr/bin/bash"],u="Git Bash was not found. Install Git for Windows (https://git-scm.com/download/win), then run `reason connect`.";function k(K){try{return F(K).isFile()}catch{return!1}}var q=(K)=>[Z.join(K,"bin","bash.exe"),Z.join(K,"usr","bin","bash.exe")];function O(K,Q){let L=Z.normalize(K).toLowerCase(),Y=(Q.SystemRoot??Q.SYSTEMROOT??"C:\\Windows").toLowerCase();return L.startsWith(Z.join(Y,"system32").toLowerCase()+"\\")||L.startsWith(Z.join(Y,"sysnative").toLowerCase()+"\\")||L.includes("\\windowsapps\\")}function C(K=process.env,Q=k){let L=[];for(let Y of(K.PATH??K.Path??"").split(";"))if(Y&&Z.isAbsolute(Y))L.push(Z.join(Y,"git.exe"));for(let Y of[K.ProgramW6432,K.ProgramFiles,K["ProgramFiles(x86)"]])if(Y)L.push(Z.join(Y,"Git","cmd","git.exe"));if(K.LOCALAPPDATA)L.push(Z.join(K.LOCALAPPDATA,"Programs","Git","cmd","git.exe"));return L.find(Q)??null}var T;function w(K=process.platform){if(K!=="win32")return"git";return T??=C(),T}function P(K){let Q=process.platform==="win32"?C(K):"git";if(!Q)return null;try{return A(Q,["--exec-path"],{encoding:"utf8",timeout:5000,windowsHide:!0,stdio:["ignore","pipe","ignore"],env:K}).trim()||null}catch{return null}}function G(K=process.env,Q=P,L=k){let Y=[],H=Q(K);if(H)Y.push(...q(Z.resolve(H,"..","..","..")));for(let $ of[K.ProgramW6432,K.ProgramFiles,K["ProgramFiles(x86)"]])if($)Y.push(...q(Z.join($,"Git")));if(K.LOCALAPPDATA)Y.push(...q(Z.join(K.LOCALAPPDATA,"Programs","Git")));for(let $ of(K.PATH??K.Path??"").split(";"))if($&&Z.isAbsolute($))Y.push(Z.join($,"bash.exe"));return Y.find(($)=>!O($,K)&&L($))??null}var z;function W(K=process.platform){if(K!=="win32")return J.find(k)??null;return z??=G(),z}function f(K=process.platform){let Q=W(K);if(!Q)throw Error(K==="win32"?u:"bash_unavailable");return Q}function h(K=process.platform){return U(K==="win32"?j():"/tmp")}function X(K=process.platform,Q=process.env){if(K!=="win32")return"/usr/bin:/bin";let L=Q.SystemRoot??Q.SYSTEMROOT??"C:\\Windows";return[Z.join(L,"System32"),L,Z.join(L,"System32","Wbem"),Z.join(L,"System32","WindowsPowerShell","v1.0")].join(";")}function _(K,Q=process.platform){if(Q!=="win32"||/[\\/]/.test(K))return K;let L=/\.exe$/i.test(K)?K:`${K}.exe`,Y=X(Q).split(";");return Z.join(L.toLowerCase()==="powershell.exe"?Y[3]:Y[0],L)}function v(K=process.platform,Q=process.env){if(K!=="win32")return{PATH:X(K)};let L=Q.SystemRoot??Q.SYSTEMROOT??"C:\\Windows";return{PATH:X(K,Q),SystemRoot:L,WINDIR:L}}function c(K=process.platform){return K==="win32"?{windowsHide:!0}:{detached:!0}}var V;function N(){if(V===void 0)V=D(M)(I(import.meta.url));return V}function p(K,Q=process.platform){let L=K.pid;if(Q!=="win32"||L===void 0)return;let Y=N();if(Y?.track(L))K.once("close",()=>Y.release(L))}function l(K,Q="SIGTERM",L=process.platform){if(L!=="win32"){process.kill(-K,Q);return}if(Q===0){process.kill(K,0);return}if(N()?.terminate(K))return;A(_("taskkill",L),["/PID",String(K),"/T","/F"],{stdio:"ignore",timeout:1e4,windowsHide:!0})}function d(K,Q=63,L=process.platform){return L==="win32"||K.uid===process.getuid?.()&&(K.mode&Q)===0}var x=/^(?:con|prn|aux|nul|com[0-9\u00b9\u00b2\u00b3]|lpt[0-9\u00b9\u00b2\u00b3]|conin\$|conout\$)(?:\..*)?$|:|[. ]$/i;function s(K){return K!=="."&&K!==".."&&x.test(K)}
|
|
3
|
+
export{u as bl,w as cl,W as dl,f as el,h as fl,X as gl,_ as hl,v as il,c as jl,p as kl,l as ll,d as ml,s as nl};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{gl as WJ,il as LJ}from"./vm-hands-entry-lite-gxper06w.js";import{ql as t}from"./vm-hands-entry-lite-magmzx9c.js";import{request as IJ}from"http";import{pipeline as wJ}from"stream";import{constants as QJ,createBrotliCompress as gJ,createGzip as mJ}from"zlib";import{WebSocket as v}from"ws";import{randomBytes as hJ,timingSafeEqual as yJ}from"crypto";import{createServer as bJ}from"net";var A={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function n(J){return J!==null&&typeof J==="object"&&!Array.isArray(J)}function y(J,X,Z=Number.MAX_SAFE_INTEGER){return typeof J==="number"&&Number.isSafeInteger(J)&&J>=X&&J<=Z}function xJ(J){return typeof J==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(J)}function NJ(J,X){let Z=Buffer.from(J,"latin1");return Buffer.concat([Buffer.from([Z.length]),Z,X])}function b(J){if(!n(J)||Object.keys(J).length!==12||![J.organizationId,J.userId,J.runId,J.deviceId,J.rootId,J.jobId,J.fenceId].every(xJ)||!y(J.attachmentRevision,0)||!y(J.grantRevision,1)||!y(J.generation,1)||!y(J.port,1024,65535)||!y(J.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...J})}function o(J,X){return Object.keys(J).every((Z)=>J[Z]===X[Z])}function k(J){if(J.length>4096||!J.startsWith("/")||J.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(J))throw Error("preview_path_invalid");let X=decodeURIComponent(J);if(X.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(X))throw Error("preview_path_invalid");return J}function qJ(J){return Array.isArray(J)&&J.length<=64&&J.every((X)=>Array.isArray(X)&&X.length===2&&typeof X[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(X[0])&&typeof X[1]==="string"&&X[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(X[1]))}function f(J,X=A.chunk){if(J.length>Math.ceil(X/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(J))throw Error("preview_data_invalid");let Z=Buffer.from(J,"base64");if(Z.length>X)throw Error("preview_data_too_large");return Z}function OJ(J){if(Array.isArray(J))return Buffer.concat(J);if(typeof J==="string")return Buffer.from(J,"utf8");if(J instanceof ArrayBuffer)return Buffer.from(J);return J}function jJ(J){if(Buffer.byteLength(J)>A.upload*1.4+300000)throw Error("preview_frame_too_large");let X=JSON.parse(J);if(!n(X))throw Error("preview_frame_invalid");if(X.type==="hello")return{type:"hello",binding:b(X.binding),...y(X.messages,A.chunk,A.upload)?{messages:X.messages}:{},...y(X.window,1,A.window)?{window:X.window}:{},...X.bytes===!0?{bytes:!0}:{}};if(X.type==="refused"&&typeof X.reason==="string"&&/^[a-z_]{1,32}$/.test(X.reason))return{type:"refused",binding:b(X.binding),reason:X.reason};if(!xJ(X.id))throw Error("preview_frame_invalid");if(X.type==="end"||X.type==="cancel"||X.type==="credit")return{type:X.type,id:X.id};if(X.type==="ws"&&typeof X.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(X.protocol))return{type:"ws",id:X.id,protocol:X.protocol};if(X.type==="data"&&typeof X.data==="string"&&typeof X.binary==="boolean")return f(X.data,A.upload),{type:"data",id:X.id,data:X.data,binary:X.binary};if(X.type==="head"&&y(X.status,200,599)&&qJ(X.headers))return{type:"head",id:X.id,status:X.status,headers:X.headers};if(X.type==="request"&&typeof X.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(X.method)&&typeof X.path==="string"&&qJ(X.headers)&&typeof X.body==="string"&&typeof X.upgrade==="boolean")return f(X.body,A.upload),{type:"request",id:X.id,method:X.method,path:k(X.path),headers:X.headers,body:X.body,upgrade:X.upgrade};throw Error("preview_frame_invalid")}function ZJ(J){let X=[...J],Z=new Set(X.filter(([$])=>$.toLowerCase()==="connection").flatMap(([,$])=>$.toLowerCase().split(",").map((Y)=>Y.trim()))),Q=new Set(["authorization","proxy-authorization","cookie","set-cookie","host","origin","referer","connection","upgrade","keep-alive","transfer-encoding","te","trailer","content-length","forwarded","alt-svc","service-worker-allowed","clear-site-data","refresh"]);return X.filter(([$])=>!Q.has($.toLowerCase())&&!Z.has($.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test($))}async function $J(J){let X;try{return await Promise.race([Promise.resolve().then(J).then((Z)=>Z===!0||(Z===!1?!1:void 0),()=>{return}),new Promise((Z)=>{X=setTimeout(()=>Z(void 0),A.authorizationMs)})])}finally{clearTimeout(X)}}async function CJ(J){return await $J(J)===!0}function a(J,X){let Z=new URL(J);if(Z.username||Z.password||Z.search||Z.hash||!(Z.protocol==="wss:"||Z.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(Z.hostname))||!new RegExp(`^/${X}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(Z.pathname))throw Error("preview_relay_invalid");return Z.href}function UX(J){if(!n(J)||Object.keys(J).length!==2||typeof J.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:b(J.binding),deviceRelayUrl:a(J.deviceRelayUrl,"device")}}function qX(J){if(!n(J)||Object.keys(J).length!==1||!("binding"in J))throw Error("preview_close_invalid");return{binding:b(J.binding)}}var AJ="x-preview-connection";async function BJ(J,X){if(X.aborted)throw Error("preview_closed");let Z=hJ(32).toString("base64url"),Q=new Set,$=!1,Y=bJ((F)=>{if($||X.aborted||Q.size>=A.streams*2)return F.destroy();Q.add(F);let K=new AbortController;F.once("close",()=>{Q.delete(F),K.abort()}),F.on("error",()=>F.destroy()),F.setTimeout(2000,()=>F.destroy());let N=Buffer.alloc(0),q=(x)=>{N=Buffer.concat([N,x]);let U=N.indexOf(`\r
|
|
3
|
+
\r
|
|
4
|
+
`);if(U<0){if(N.length>16384)F.destroy();return}if(F.pause(),F.off("data",q),U>16384||N.length>A.upload+16384)return F.destroy();D(N,U).catch(()=>F.destroy())};F.on("data",q);async function D(x,U){let O=x.subarray(0,U).toString("latin1").split(`\r
|
|
5
|
+
`),T=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(O.shift()??"");if(!T)throw Error("preview_request_invalid");k(T[2]);let V=!1,g=0,S=[];for(let h of O){let L=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(h);if(!L)throw Error("preview_header_invalid");if(L[1].toLowerCase()===AJ){g++;let I=Buffer.from(L[2].trim());V=I.length===Z.length&&yJ(I,Buffer.from(Z))}else if(L[1].toLowerCase()!=="host")S.push(h)}if(!V||g!==1||$||K.signal.aborted)throw Error("preview_connection_denied");let B=await J.connect(K.signal);if($||K.signal.aborted)throw B.destroy(),Error("preview_closed");Q.add(B),B.on("error",()=>F.destroy()),B.once("close",()=>{Q.delete(B),F.destroy()}),F.once("close",()=>B.destroy()),F.setTimeout(0);let C=[`${T[1]} ${T[2]} HTTP/1.1`,`Host: 127.0.0.1:${B.remotePort}`,...S,"",""].join(`\r
|
|
6
|
+
`);B.write(Buffer.concat([Buffer.from(C,"latin1"),x.subarray(U+4)])),B.pipe(F),F.pipe(B),F.resume()}});await new Promise((F,K)=>{Y.once("error",K),Y.listen(0,"127.0.0.1",F)});let G=Y.address();if(!G||typeof G==="string")throw Y.close(),Error("preview_bind_failed");function H(){if($)return;$=!0,X.removeEventListener("abort",H);for(let F of Q)F.destroy();Q.clear(),Y.close()}if(X.addEventListener("abort",H,{once:!0}),X.aborted)H();return{port:G.port,headers:{[AJ]:Z},close:H}}var fJ=60000,kJ=1e4,vJ=5000,uJ=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function pJ(J,X,Z,Q){let $=(F)=>X.find(([K])=>K.toLowerCase()===F)?.[1],Y=(F)=>Q.find(([K])=>K.toLowerCase()===F)?.[1],G=Number(Y("content-length")??Number.NaN);if(J!=="GET"||Z!==200||$("range")!==void 0||Y("content-encoding")!==void 0||!uJ.test(Y("content-type")??"")||/\bno-transform\b/i.test(Y("cache-control")??"")||G<1024)return null;let H=(F)=>new RegExp(`(?:^|,)\\s*${F}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test($("accept-encoding")??"");return H("br")?"br":H("gzip")?"gzip":null}function dJ(J,X){let Z=J.filter(([Q])=>Q.toLowerCase()==="vary").map(([,Q])=>Q).join(", ");return[...J.filter(([Q])=>!["vary","etag","content-md5"].includes(Q.toLowerCase())),...J.filter(([Q])=>Q.toLowerCase()==="etag").map(([Q,$])=>[Q,$.startsWith("W/")?$:`W/${$}`]),["Content-Encoding",X],["Vary",Z.split(",").some((Q)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(Q))?Z:Z?`${Z}, Accept-Encoding`:"Accept-Encoding"]]}async function cJ(J){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:J.jobId,port:J.port,reason_code:J.reason})}
|
|
7
|
+
`);let X=J.binding,Z;try{Z=a(J.deviceRelayUrl,"device")}catch{return}if(!X)return;await new Promise((Q)=>{let $=new v(Z,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),Y=setTimeout(()=>{$.terminate(),Q()},A.authorizationMs*2);$.addEventListener("open",()=>{$.send(JSON.stringify({type:"refused",binding:X,reason:J.reason})),$.close(1000,`worker_refused_${J.reason}`)}),$.addEventListener("error",()=>{clearTimeout(Y),Q()}),$.addEventListener("close",()=>{clearTimeout(Y),Q()})})}async function lJ(J,X){let Z=Date.now()+kJ,Q;for(;;){if(!X())return"closed";let $=Q??=J.refusal().finally(()=>{Q=void 0}),Y,G=await Promise.race([$.catch(()=>"port_unproved"),new Promise((H)=>{Y=setTimeout(()=>H("port_check_timeout"),A.authorizationMs)})]).finally(()=>clearTimeout(Y));if(G===null)return null;if(!["listener_unproved","port_check_timeout"].includes(G)||Date.now()+500>=Z)return G;await new Promise((H)=>setTimeout(H,500))}}async function MX(J){let X=b(J.binding),Z=()=>!J.signal.aborted&&Date.now()<X.expiresAtMs,Q=X.expiresAtMs>Date.now()+A.lifetimeMs+vJ?"binding_mismatch":await lJ(J.port,Z);if(Q)throw await cJ({deviceRelayUrl:J.deviceRelayUrl,binding:X,jobId:X.jobId,port:X.port,reason:Q}),Error("preview_not_authorized",{cause:Q});let $=a(J.deviceRelayUrl,"device"),Y=await BJ(J.port,J.signal),G;try{G=new v($,{followRedirects:!1,perMessageDeflate:!1,maxPayload:A.upload*1.4+300000})}catch(z){throw Y.close(),z}let H=new Map,F=!1,K=!1,N=0,q=!1,D,x,U,O=new Promise((z)=>{U=z}),T,V,g=new Promise((z,j)=>{T=z,V=j}),S=!1,B=(z)=>{let j=Buffer.isBuffer(z)?z:JSON.stringify(z);if(N+=Buffer.byteLength(j),!Z()||K||G.readyState!==v.OPEN)return C(Z()?"relay_closed":"expired");if(G.bufferedAmount>A.relayBuffered)return C("relay_backlog");if(N>A.total)return C("quota");G.send(j)};function C(z="closed"){if(K)return;K=!0,clearInterval(I),clearTimeout(L),J.signal.removeEventListener("abort",h);for(let j of H.values())j.stop();H.clear(),Y.close(),G.close(1000,`worker_${z}`),V(Error("preview_closed")),U()}let h=()=>C("aborted"),L=setTimeout(()=>C("pair_timeout"),A.requestMs),I=setInterval(async()=>{if(!Z())return C(J.signal.aborted?"aborted":"expired");if(q)return;q=!0;try{let z=D??=Promise.resolve().then(()=>J.port.check()).finally(()=>{D=void 0}),j=await $J(()=>z);if(j===!1)return C("port_refused");if(j){x=void 0;return}if(Date.now()-(x??=Date.now())>fJ)return C("port_unknown");for(let M of H.values())M.stop()}finally{q=!1}},1000);if(J.signal.addEventListener("abort",h,{once:!0}),!Z())C(J.signal.aborted?"aborted":"expired");G.addEventListener("open",()=>B({type:"hello",binding:X,messages:A.upload,window:A.window})),G.addEventListener("close",()=>C("relay_closed")),G.addEventListener("error",()=>C("relay_error")),G.addEventListener("message",(z)=>{try{if(!Z()||K)return C(J.signal.aborted?"aborted":"expired");if(typeof z.data!=="string")throw Error("preview_frame_invalid");if(N+=Buffer.byteLength(z.data),N>A.total)return C("quota");let j=jJ(z.data);if(!F){if(j.type!=="hello"||!o(X,j.binding))return C("binding_mismatch");F=!0,S=j.bytes===!0,clearTimeout(L),T();return}if(j.type==="hello"||j.type==="refused")return C("invalid_frame");if(j.type==="request"){d(j).catch(()=>C("invalid_request"));return}let M=H.get(j.id);if(!M)return;if(j.type==="cancel"||j.type==="end")M.stop();else if(j.type==="credit"&&M.credit)M.credit();else if(j.type==="data"&&M.ws){if(M.ws.readyState!==v.OPEN||M.ws.bufferedAmount>A.buffered)return M.stop();let R=f(j.data,A.upload);M.ws.send(j.binary?R:R.toString("utf8"))}else C("invalid_frame")}catch{C("invalid_frame")}});async function d(z){if(H.has(z.id)||H.size>=A.streams)return C("stream_limit");if(!Z())return C(J.signal.aborted?"aborted":"expired");let j=new AbortController,M,R,c,JJ=0,E=(P=!1)=>{if(!H.delete(z.id))return;clearTimeout(M),j.abort(),R?.close(1000,"preview_closed"),c?.(),B({type:P?"end":"cancel",id:z.id})},FJ={stop:()=>E(),credit:()=>{JJ++,c?.()}};if(H.set(z.id,FJ),M=setTimeout(E,A.requestMs),!await CJ(()=>J.port.check())||!Z()||j.signal.aborted)return E();let HJ=k(z.path);if(z.upgrade){if(z.method!=="GET"||z.body)return E();let P=z.headers.find(([_])=>_.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((_)=>_.trim());if(P?.some((_)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(_))||(P?.length??0)>8)return E();R=new v(`ws://127.0.0.1:${Y.port}${HJ}`,P,{headers:Y.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:A.upload}),FJ.ws=R,R.binaryType="arraybuffer",R.addEventListener("open",()=>{clearTimeout(M),B({type:"ws",id:z.id,protocol:R.protocol})}),R.addEventListener("message",(_)=>{let l=typeof _.data!=="string",w=OJ(_.data);if(w.length>A.upload)return E();B({type:"data",id:z.id,data:w.toString("base64"),binary:l})}),R.addEventListener("error",()=>E()),R.addEventListener("close",(_)=>E(_.wasClean));return}let PJ=f(z.body,A.upload),DJ=IJ({hostname:"127.0.0.1",port:Y.port,path:HJ,method:z.method,headers:{...Object.fromEntries(ZJ(z.headers)),...Y.headers,connection:"close"},signal:j.signal,agent:!1,maxHeaderSize:16384},async(P)=>{try{let _=[];for(let m=0;m<P.rawHeaders.length;m+=2)_.push([P.rawHeaders[m],P.rawHeaders[m+1]]);let l=P.statusCode??502,w=pJ(z.method,z.headers,l,_),XJ=w==="br"?gJ({flush:QJ.BROTLI_OPERATION_FLUSH,params:{[QJ.BROTLI_PARAM_QUALITY]:5}}):w==="gzip"?mJ({level:6,flush:QJ.Z_SYNC_FLUSH}):void 0;if(B({type:"head",id:z.id,status:l,headers:ZJ(w?dJ(_,w):_)}),clearTimeout(M),XJ)wJ(P,XJ,()=>{});for await(let m of XJ??P){let zJ=Buffer.from(m);for(let i=0;i<zJ.length;i+=A.chunk){if(JJ===0&&!j.signal.aborted)await new Promise((EJ)=>{c=EJ});if(c=void 0,j.signal.aborted)return;JJ--;let UJ=zJ.subarray(i,i+A.chunk);B(S?NJ(z.id,UJ):{type:"data",id:z.id,data:UJ.toString("base64"),binary:!0})}}E(!0)}catch{E()}});DJ.on("error",()=>E()),DJ.end(PJ)}return await g,{close:C,closed:O}}import{execFile as iJ}from"child_process";import{createRequire as nJ}from"module";import{win32 as r}from"path";var oJ=250,aJ=50,tJ=250,rJ=4194304;function TJ(J){let X=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(J??""),Z=Number(X?.[3]);return X&&Z<=65535?{address:X[1]??X[2],port:Z}:null}function sJ(J){let X=[];for(let Z of J.split(/\r?\n/)){let Q=Z.trim().split(/\s+/);if(Q[0]!=="TCP"||Q.length<5)continue;let $=TJ(Q[1]),Y=TJ(Q[2]),G=Number(Q.at(-1));if(!$||!Y||!Number.isSafeInteger(G)||G<0)continue;X.push({pid:G,localAddress:$.address,localPort:$.port,remoteAddress:Y.address,remotePort:Y.port,listening:Y.port===0})}return X}function eJ(J){if(J.localAddress==="0.0.0.0"||J.localAddress==="::")return`*:${J.localPort}`;return J.localAddress.includes(":")?`[${J.localAddress}]:${J.localPort}`:`${J.localAddress}:${J.localPort}`}var YJ=(J)=>new Promise((X,Z)=>iJ(r.join(WJ("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:J,maxBuffer:rJ,encoding:"utf8",windowsHide:!0,env:LJ()},(Q,$)=>Q?Z(Q):X($)));function p(J){let X=r.normalize(J.startsWith("\\\\?\\")?J.slice(4):J);return X.length>3&&X.endsWith("\\")?X.slice(0,-1):X}function JX(J,X){let Z=J.toLowerCase(),Q=X.toLowerCase();return Q===Z||Q.startsWith(Z.endsWith("\\")?Z:`${Z}\\`)}function MJ(J,X,Z){let Q=J.cwd(Z),$=Q?p(Q):null;return $&&r.isAbsolute($)&&JX(X,$)?$:null}var u;function s(){if(u!==void 0)return u;if(u=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let J;try{J=nJ(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:X,ptr:Z}=J,Q,$;try{Q=J.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[X.u32,X.u32],returns:X.u64},Process32FirstW:{args:[X.u64,X.ptr],returns:X.i32},Process32NextW:{args:[X.u64,X.ptr],returns:X.i32},OpenProcess:{args:[X.u32,X.i32,X.u32],returns:X.u64},ReadProcessMemory:{args:[X.u64,X.u64,X.ptr,X.u64,X.ptr],returns:X.i32},CloseHandle:{args:[X.u64],returns:X.i32}}).symbols,$=J.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[X.u64,X.i32,X.ptr,X.u32,X.ptr],returns:X.i32}}).symbols}catch{return null}let Y=0xFFFF_FFFF_FFFF_FFFFn,G=2,H=1040,F=568,K=(N,q,D)=>{let x=Buffer.alloc(D);return Q.ReadProcessMemory(N,q,Z(x),D,null)?x:null};return u={processes(){let N=BigInt(Q.CreateToolhelp32Snapshot(G,0));if(N===Y)throw new t("process_inspection_failed","Reading this computer's processes did not complete.");try{let q=Buffer.alloc(F);q.writeUInt32LE(F,0);let D=Z(q),x=[];for(let U=Q.Process32FirstW(N,D);U;U=Q.Process32NextW(N,D)){let O=q.toString("utf16le",44,F),T=O.slice(0,O.includes("\x00")?O.indexOf("\x00"):void 0),V=q.readUInt32LE(8);if(V>0)x.push({pid:V,parentPid:q.readUInt32LE(32),command:T.replace(/\.exe$/i,"")||null})}return x}finally{Q.CloseHandle(N)}},cwd(N){let q=BigInt(Q.OpenProcess(H,0,N));if(q===0n)return null;try{let D=Buffer.alloc(48);if($.NtQueryInformationProcess(q,0,Z(D),D.length,null)!==0)return null;let x=K(q,D.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),U=x?K(q,x+0x38n,16):null,O=U?.readUInt16LE(0)??0;if(!U||O===0||O%2!==0)return null;return K(q,U.readBigUInt64LE(8),O)?.toString("utf16le")??null}finally{Q.CloseHandle(q)}}},u}function GJ(J){if(!J)throw new t("process_inspection_failed","Reading this computer's processes is unavailable.");return J}async function _J(J,X){let Z;try{Z=await J(X)}catch{throw new t("process_inspection_failed","Reading this computer's ports did not complete.")}return sJ(Z)}async function yX(J,X=s()){let Z=GJ(X),Q=p(J),$=[];for(let Y of Z.processes()){if($.length>=oJ)break;let G=MJ(Z,Q,Y.pid);if(G)$.push({pid:Y.pid,command:Y.command,cwd:r.relative(Q,G)||"."})}return{processes:$}}async function bX(J,X=s(),Z=YJ){let Q=GJ(X),$=p(J),Y=(await _J(Z,5000)).filter((K)=>K.listening&&K.pid>0).map((K)=>({pid:K.pid,port:K.localPort,address:eJ(K)})).sort((K,N)=>K.pid-N.pid||K.port-N.port||(K.address<N.address?-1:K.address>N.address?1:0)),G=[...new Set(Y.map((K)=>K.pid))].slice(0,aJ),H=new Set(G.filter((K)=>MJ(Q,$,K)!==null));if(H.size===0)return{ports:[]};let F=new Map(Q.processes().map((K)=>[K.pid,K.command]));return{ports:Y.filter((K)=>H.has(K.pid)).slice(0,tJ).map((K)=>({pid:K.pid,command:F.get(K.pid)??null,address:K.address}))}}function VJ(J,X){let Z=new Set([X]);for(let Q=!0;Q;){Q=!1;for(let $ of J)if(!Z.has($.pid)&&Z.has($.parentPid)&&$.pid!==$.parentPid)Z.add($.pid),Q=!0}return Z}function XX(J,X,Z,Q){let $=(Y)=>Y==="127.0.0.1"||Y==="::ffff:127.0.0.1"||Y==="::1";return J.flatMap((Y)=>{if(!X.has(Y.pid)||Y.localPort!==Q)return[];let G=Y.listening&&($(Y.localAddress)||["0.0.0.0","::"].includes(Y.localAddress)),H=!Y.listening&&$(Y.localAddress)&&$(Y.remoteAddress);if(!G&&!H)return[];let F=`${Y.localAddress}:${Y.localPort}>${Y.remoteAddress}:${Y.remotePort}`;return[{pid:Y.pid,processGroupId:Z,descriptor:String(Y.pid),kernelId:F,state:G?"listen":"established",port:Q,peerPort:G?null:Y.remotePort,host:Y.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function SJ(J,X,Z=s(),Q=YJ){let $=GJ(Z),Y=VJ($.processes(),J),G=await _J(Q,1000),H=VJ($.processes(),J);return XX(G,new Set([...Y].filter((F)=>H.has(F))),J,X)}async function IX(J,X=s(),Z=YJ){if(!X||J.aborted)return!1;let Q=X.processes().some((H)=>H.pid===process.pid),$=X.cwd(process.pid),Y=$!==null&&p($).toLowerCase()===p(process.cwd()).toLowerCase(),G=await Z(5000).then((H)=>/^\s*TCP\s/m.test(H),()=>!1);return Q&&Y&&G&&!J.aborted}import{execFile as ZX}from"child_process";import{readFile as $X,readdir as QX,readlink as YX}from"fs/promises";import{connect as GX}from"net";import{setTimeout as KX}from"timers/promises";var FX={directory:QX,text:(J)=>$X(J,"utf8"),link:YX};class KJ extends Error{code;constructor(J="port_unproved"){super("preview_port_ownership_unproved");this.code=J}}var W=(J)=>new KJ(J),e="preview_listener_unproved",RJ="00000000000000000000000001000000";async function HX(J,X,Z=FX){let Q=new Map;for(let G of["tcp","tcp6"]){let H=await Z.text(`/proc/net/${G}`);if(H.length>4194304)throw W();for(let F of H.split(`
|
|
8
|
+
`).slice(1)){let K=F.trim().split(/\s+/);if(K.length<10||!["0A","01"].includes(K[3]))continue;let[N,q]=K[1].split(":"),[D,x]=K[2].split(":");if(Number.parseInt(q,16)!==X)continue;let U=(V)=>V==="0100007F"||V==="0000000000000000FFFF00000100007F"||V===RJ,O=K[3]==="0A";if(!(U(N)||O&&/^0+$/.test(N??"")))continue;if(!O&&!U(D))continue;let T=K[9];if(!/^[1-9][0-9]*$/.test(T))continue;Q.set(T,{kernelId:T,port:X,peerPort:O?null:Number.parseInt(x,16),state:O?"listen":"established",host:N===RJ?"::1":"127.0.0.1"})}}let $=await Z.directory("/proc");if($.length>8192)throw W();let Y=[];for(let G of $){if(!/^[1-9][0-9]*$/.test(G))continue;try{let H=await Z.text(`/proc/${G}/stat`),F=H.slice(H.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(F[2])!==J)continue;let K=await Z.directory(`/proc/${G}/fd`);if(K.length>1024)throw W();let N=[];for(let x of K){if(!/^[0-9]+$/.test(x))continue;let U=await Z.link(`/proc/${G}/fd/${x}`).catch(()=>""),O=/^socket:\[([0-9]+)\]$/.exec(U)?.[1],T=O?Q.get(O):void 0;if(T)N.push({...T,pid:Number(G),processGroupId:J,descriptor:x})}let q=await Z.text(`/proc/${G}/stat`),D=q.slice(q.lastIndexOf(")")+2).trim().split(/\s+/);if(F[19]===D[19]&&F[2]===D[2])Y.push(...N)}catch(H){if(H instanceof Error&&H.message==="preview_port_ownership_unproved")throw H}}return Y}function DX(J,X,Z){if(J.length>2097152)throw W();let Q=0,$=0,Y="",G="",H="",F="",K=[],N=()=>{if(Q<1||$!==X||!/^\d+$/.test(Y)||!/^0x[0-9a-f]+$/i.test(G))return;let q=F==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((x)=>H===`${x}:${Z}`),D=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${Z}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(H);if(q||F==="ESTABLISHED"&&D)K.push({pid:Q,processGroupId:$,descriptor:Y,kernelId:G,state:q?"listen":"established",port:Z,peerPort:q?null:Number(D[1]),host:H.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let q of J.split(/[\0\n]/)){let D=q.slice(1);if(q[0]==="p")N(),Q=Number(D),$=0,Y=G=H=F="";else if(q[0]==="g")$=Number(D);else if(q[0]==="f")N(),Y=D,G=H=F="";else if(q[0]==="d")G=D;else if(q[0]==="n")H=D;else if(q.startsWith("TST="))F=q.slice(4)}return N(),K}async function zX(J,X){if(process.platform==="linux")return HX(J,X);if(process.platform==="win32")return SJ(J,X);if(process.platform!=="darwin")throw W();let Z=await new Promise((Q,$)=>ZX("/usr/sbin/lsof",["-nP","-a","-g",String(J),`-iTCP:${X}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(Y,G)=>Y?$(W()):Q(G)));return DX(Z,J,X)}function pX(J,X={}){let Z=b(J.binding),Q=X.inspectSockets??zX,$=X.monotonicNow??(()=>performance.now());async function Y(){let D=()=>{if(Date.now()>=Z.expiresAtMs)throw W("binding_expired");if(J.deniedPorts.has(Z.port))throw W("port_denied")};D();let x=await J.readCurrentJob(),U=x?.job,O=U?.process;if(D(),!x)throw W("server_stopped");if(!o(Z,x.binding)||U?.jobId!==Z.jobId)throw W("binding_changed");if(U.state!=="running"||U.finishedAtMs!==null||U.leaseExpiresAtMs<Z.expiresAtMs)throw W("job_not_running");if(!O||O.pid<1||O.pid!==O.processGroupId||O.executorLaunchId!==x.executorLaunchId)throw W("process_unproved");return{pid:O.pid,launch:O.executorLaunchId,started:U.startedAtMs}}let G,H;async function F(){let D=await Y(),x=await Q(D.pid,Z.port).catch(()=>{throw Error(e)}),U=await Y();if(D.pid!==U.pid||D.launch!==U.launch||D.started!==U.started)throw W("job_restarted");return x}async function K(D){for(;;){if(H&&H.startedAt>=D)return H.sockets;if(G&&G.startedAt>=D)return await G.sockets;if(G){await G.sockets.catch(()=>{});continue}let x={startedAt:$(),sockets:F()};G=x;try{let U=await x.sockets;if(!H||H.startedAt<=x.startedAt)H={startedAt:x.startedAt,sockets:U};return U}finally{if(G===x)G=void 0}}}async function N(D=()=>{},x=$()){D();let U=await K(x);if(D(),Date.now()>=Z.expiresAtMs)throw W("binding_expired");if(!U.some((O)=>O.state==="listen"))throw Error(e);return U}async function q(){try{return await N(()=>{},$()-1000),null}catch(D){if(D instanceof Error&&D.message===e)return"listener_unproved";return D instanceof KJ?D.code:"port_unproved"}}return{refusal:q,async check(){let D=await q();if(D==="listener_unproved")throw Error(e);return D===null},async connect(D){if(D.aborted)throw W();let x=$()+2000,U=new AbortController,O=new Promise((C)=>U.signal.addEventListener("abort",()=>C(null),{once:!0})),T,V=()=>{U.abort(),T?.destroy()},g=setTimeout(V,2000);D.addEventListener("abort",V,{once:!0});let S=()=>{if(U.signal.aborted||D.aborted||$()>=x||T?.destroyed)throw V(),W()};async function B(C){S();let h=await Promise.race([C().then((L)=>({value:L})),O]);if(S(),!h)throw W();return h.value}try{let C=await B(()=>N(S,$()-1000));S();let h=C.some((z)=>z.state==="listen"&&z.host==="127.0.0.1")?"127.0.0.1":"::1",L=GX({host:h,port:Z.port,signal:D});T=L,L.once("close",V),await B(()=>new Promise((z,j)=>{L.once("connect",z),L.once("error",j)}));let I=L.localPort;if(!I)throw W();let d=$();while(!(await B(()=>N(S,d))).some((z)=>z.state==="established"&&z.peerPort===I))await B(()=>KX(Math.min(20,Math.max(1,x-$())),void 0,{signal:U.signal})),d=$();return S(),L}catch(C){throw V(),C}finally{clearTimeout(g),D.removeEventListener("abort",V),T?.off("close",V),U.abort()}}}}
|
|
9
|
+
export{A as ad,o as bd,jJ as cd,CJ as dd,UX as ed,qX as fd,cJ as gd,MX as hd,s as id,yX as jd,bX as kd,IX as ld,pX as md};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ei as MJ}from"./vm-hands-entry-lite-28s7v15d.js";import{Rj as OJ}from"./vm-hands-entry-lite-0h4qmgm2.js";import{Yj as G$}from"./vm-hands-entry-lite-6nwbqg37.js";import{Fk as M,Mk as QQ,Nk as ZQ,Pk as f$,Sk as qQ,Uk as zQ}from"./vm-hands-entry-lite-3rqdzqhk.js";import{ql as c}from"./vm-hands-entry-lite-magmzx9c.js";import{execFile as N0,spawn as s$}from"child_process";import{existsSync as R0}from"fs";import{connect as I0}from"net";function NQ(){let $=new Set,J=null,Q=(q)=>({holder:J?.viewer??null,you:J===q,same_user:Boolean(J?.viewer&&q.viewer&&J.viewer.user_id===q.viewer.user_id)}),Z=()=>{for(let q of $)q.notify(Q(q))};return{join(q){return $.add(q),q.notify(Q(q)),()=>{if(!$.delete(q))return;if(J!==q)return;J=null,Z()}},claim(q){if(J===q||!$.has(q))return;J=q,Z()}}}var HJ=NQ();import{createHash as AJ}from"crypto";import{once as vQ}from"events";import{createWriteStream as bQ,existsSync as _Q,mkdirSync as gQ,mkdtempSync as C4,readFileSync as H$,readdirSync as F4,renameSync as SQ,realpathSync as yQ,rmSync as EQ,statSync as h$,writeFileSync as fQ}from"fs";import{delimiter as N4,dirname as u$,join as U}from"path";import{finished as hQ}from"stream/promises";var k$="omljlfpmafedpplnpkkahegadhkimdje",o0="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";function t0($){if(!$||typeof $!=="object"||Array.isArray($)||!("version"in $)||$.version!==1||!("status"in $))return null;if($.status==="unavailable")return Object.keys($).length===2?{version:1,status:"unavailable"}:null;if($.status!=="connected"||Object.keys($).length!==5||!("deviceId"in $)||typeof $.deviceId!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test($.deviceId)||!("apiOrigin"in $)||typeof $.apiOrigin!=="string"||$.apiOrigin.length>2048||!("managedRootIds"in $)||!Array.isArray($.managedRootIds)||$.managedRootIds.length>32)return null;let J=[];for(let Q of $.managedRootIds){if(typeof Q!=="string"||!/^[A-Za-z0-9._:-]{1,160}$/.test(Q))return null;J.push(Q)}try{let Q=new URL($.apiOrigin);if(Q.origin!==$.apiOrigin||Q.username||Q.password||!(Q.protocol==="https:"||Q.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(Q.hostname)))return null}catch{return null}return{version:1,status:"connected",deviceId:$.deviceId,apiOrigin:$.apiOrigin,managedRootIds:J}}var v={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"}},E={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var o={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${v.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${v.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${v.obu.version}/open-browser-use-chrome-extension-${v.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},l="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as b$}from"child_process";import{createRequire as RQ}from"module";import{join as IQ}from"path";var PQ=30000,xQ=1048576;function _$(){return process.env.SystemRoot??"C:\\Windows"}function MQ(){return IQ(_$(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var OQ=String.raw`
|
|
3
|
+
$ErrorActionPreference = "Stop"
|
|
4
|
+
Add-Type -TypeDefinition @"
|
|
5
|
+
using System;
|
|
6
|
+
using System.Runtime.InteropServices;
|
|
7
|
+
public static class ReasonInput {
|
|
8
|
+
[StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
9
|
+
[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
10
|
+
[StructLayout(LayoutKind.Explicit)] public struct UNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
|
|
11
|
+
[StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public UNION u; }
|
|
12
|
+
[DllImport("user32.dll")] static extern uint SendInput(uint count, INPUT[] inputs, int size);
|
|
13
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
|
14
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
|
|
15
|
+
[DllImport("user32.dll")] static extern uint MapVirtualKey(uint code, uint type);
|
|
16
|
+
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
|
|
17
|
+
static void Send(INPUT input) { SendInput(1, new INPUT[] { input }, Marshal.SizeOf(typeof(INPUT))); }
|
|
18
|
+
public static void Mouse(uint flags, int x, int y, int data) {
|
|
19
|
+
INPUT input = new INPUT(); input.type = 0;
|
|
20
|
+
input.u.mi.dx = x; input.u.mi.dy = y; input.u.mi.mouseData = data; input.u.mi.dwFlags = flags; Send(input);
|
|
21
|
+
}
|
|
22
|
+
public static void Key(ushort vk, ushort unit, uint flags) {
|
|
23
|
+
INPUT input = new INPUT(); input.type = 1;
|
|
24
|
+
input.u.ki.wVk = vk; input.u.ki.wScan = vk != 0 ? (ushort)MapVirtualKey(vk, 0) : unit; input.u.ki.dwFlags = flags; Send(input);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
"@
|
|
28
|
+
[void][ReasonInput]::SetProcessDPIAware()
|
|
29
|
+
$width = [ReasonInput]::GetSystemMetrics(0)
|
|
30
|
+
$height = [ReasonInput]::GetSystemMetrics(1)
|
|
31
|
+
$session = [Diagnostics.Process]::GetCurrentProcess().SessionId
|
|
32
|
+
[Console]::Out.WriteLine('{"session":' + $session + ',"width":' + $width + ',"height":' + $height + '}')
|
|
33
|
+
[Console]::Out.Flush()
|
|
34
|
+
$mode = "__MODE__"
|
|
35
|
+
if ($mode -eq "probe") { exit 0 }
|
|
36
|
+
if ($mode -eq "clipboard") {
|
|
37
|
+
# Only changes made during this pairing: never export the initial clipboard.
|
|
38
|
+
$parent = Get-Process -Id __PARENT__
|
|
39
|
+
$last = [ReasonInput]::GetClipboardSequenceNumber()
|
|
40
|
+
while (-not $parent.HasExited) {
|
|
41
|
+
Start-Sleep -Milliseconds 100
|
|
42
|
+
$count = [ReasonInput]::GetClipboardSequenceNumber()
|
|
43
|
+
if ($count -eq $last) { continue }
|
|
44
|
+
$last = $count
|
|
45
|
+
try { $text = Get-Clipboard -Raw } catch { continue }
|
|
46
|
+
if (-not $text) { continue }
|
|
47
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes($text)
|
|
48
|
+
if ($bytes.Length -gt __MAX_TEXT_BYTES__) { continue }
|
|
49
|
+
[Console]::Out.WriteLine("c " + [Convert]::ToBase64String($bytes))
|
|
50
|
+
[Console]::Out.Flush()
|
|
51
|
+
}
|
|
52
|
+
exit 0
|
|
53
|
+
}
|
|
54
|
+
$scaleX = 65535.0 / [Math]::Max(1, $width - 1)
|
|
55
|
+
$scaleY = 65535.0 / [Math]::Max(1, $height - 1)
|
|
56
|
+
while ($null -ne ($line = [Console]::In.ReadLine())) {
|
|
57
|
+
$n = $line.Split(" ")
|
|
58
|
+
try {
|
|
59
|
+
switch ($n[0]) {
|
|
60
|
+
"p" { [ReasonInput]::Mouse(0x8001, [int]([int]$n[1] * $scaleX), [int]([int]$n[2] * $scaleY), 0) }
|
|
61
|
+
"b" { [ReasonInput]::Mouse([uint32]$n[1], 0, 0, [int]$n[2]) }
|
|
62
|
+
"k" { [ReasonInput]::Key([uint16]$n[1], [uint16]$n[2], [uint32]$n[3]) }
|
|
63
|
+
"c" { Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($n[1]))) }
|
|
64
|
+
}
|
|
65
|
+
} catch { [Console]::Error.WriteLine("input: $_") }
|
|
66
|
+
}
|
|
67
|
+
`;function g$($){let J=OQ.replace("__MODE__",$).replace("__PARENT__",String(process.pid)).replace("__MAX_TEXT_BYTES__",String(M));return[MQ(),["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(J,"utf16le").toString("base64")]]}var AQ=["USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP","PSModuleAnalysisCachePath"];function S$(){let $=AQ.flatMap((J)=>process.env[J]?[[J,process.env[J]]]:[]);return{...Object.fromEntries($),SystemRoot:_$(),windir:_$()}}function CJ($){let J;try{J=JSON.parse($)}catch{return null}if(!J||typeof J!=="object")return null;let Q=J,Z=(q,z)=>typeof q==="number"&&Number.isSafeInteger(q)&&q>=z;return Z(Q.session,0)&&Z(Q.width,1)&&Z(Q.height,1)?{session:Q.session,width:Q.width,height:Q.height}:null}function FJ(){return new Promise(($)=>{let J=b$(...g$("probe"),{env:S$(),stdio:["ignore","pipe","ignore"],windowsHide:!0}),Q="",Z=setTimeout(()=>{J.kill("SIGKILL"),$(null)},PQ);J.stdout.setEncoding("utf8").on("data",(q)=>{Q+=q}),J.once("error",()=>{clearTimeout(Z),$(null)}),J.once("close",()=>{clearTimeout(Z),$(CJ(Q.split(/\r?\n/)[0]??""))})})}var s;function DJ(){if(s!==void 0)return s;if(process.platform!=="win32")return s=!1;try{let $=RQ(import.meta.url)("bun:ffi"),{symbols:J}=$.dlopen("kernel32.dll",{GetCurrentProcessId:{args:[],returns:$.FFIType.u32},ProcessIdToSessionId:{args:[$.FFIType.u32,$.FFIType.ptr],returns:$.FFIType.i32}}),Q=new Uint32Array(1);return s=J.ProcessIdToSessionId(J.GetCurrentProcessId(),Q)!==0&&Q[0]>0}catch{return s=!1}}var XJ=[{bit:1,down:2,up:4},{bit:2,down:32,up:64},{bit:4,down:8,up:16}],jJ=2048,KJ=4096,wQ=[[8,jJ,120],[16,jJ,-120],[32,KJ,-120],[64,KJ,120]],BJ=1,v$=2,TQ=4,kQ=new Set([65505,65506]),LJ=new Set([65507,65508,65511,65512,65513,65514,65027,65515,65516]),UJ=new Map([[65505,[160,!1]],[65506,[161,!1]],[65507,[162,!1]],[65508,[163,!0]],[65511,[164,!1]],[65512,[165,!0]],[65513,[164,!1]],[65514,[165,!0]],[65027,[165,!0]],[65515,[91,!0]],[65516,[92,!0]],[65288,[8,!1]],[65289,[9,!1]],[65056,[9,!1]],[65293,[13,!1]],[65307,[27,!1]],[65535,[46,!0]],[65379,[45,!0]],[65360,[36,!0]],[65367,[35,!0]],[65365,[33,!0]],[65366,[34,!0]],[65361,[37,!0]],[65362,[38,!0]],[65363,[39,!0]],[65364,[40,!0]],[65383,[93,!0]],[65509,[20,!1]],[65299,[19,!1]],[65300,[145,!1]],[65377,[44,!0]],[65407,[144,!0]],[32,[32,!1]],[65421,[13,!0]],[65408,[32,!1]],[65450,[106,!1]],[65451,[107,!1]],[65452,[108,!1]],[65453,[109,!1]],[65454,[110,!1]],[65455,[111,!0]],[65429,[36,!1]],[65430,[37,!1]],[65431,[38,!1]],[65432,[39,!1]],[65433,[40,!1]],[65434,[33,!1]],[65435,[34,!1]],[65436,[35,!1]],[65438,[45,!1]],[65439,[46,!1]],...Array.from({length:10},($,J)=>[65456+J,[96+J,!1]]),...Array.from({length:24},($,J)=>[65470+J,[112+J,!1]])]);class NJ{x=-1;y=-1;mask=0;held=new Set;pressed=new Set;pointer($,J,Q){let Z=[];if($!==this.x||J!==this.y)this.x=$,this.y=J,Z.push(`p ${$} ${J}`);for(let q of XJ){let z=(this.mask&q.bit)!==0,W=(Q&q.bit)!==0;if(z!==W)Z.push(`b ${W?q.down:q.up} 0`)}for(let[q,z,W]of wQ)if(!(this.mask&q)&&Q&q)Z.push(`b ${z} ${W}`);return this.mask=Q,Z}key($,J){let Q=$?0:v$;if(kQ.has(J)||LJ.has(J))if($)this.held.add(J);else this.held.delete(J);let Z=UJ.get(J);if(Z)return[`k ${Z[0]} 0 ${Q|(Z[1]?BJ:0)}`];let q=J<256?J:(J&4278190080)===16777216?J&16777215:0,z=String.fromCharCode(q),W=[...this.held].some((C)=>LJ.has(C)),H=/^[A-Za-z0-9]$/.test(z)?z.toUpperCase().charCodeAt(0):0;if(H&&($?W:this.pressed.has(H))){if($)this.pressed.add(H);else this.pressed.delete(H);return[`k ${H} 0 ${Q}`]}if(q<33||q>=127&&q<160||q>65535||q>=55296&&q<57344)return[];return[`k 0 ${q} ${Q|TQ}`]}release(){let $=XJ.filter((J)=>this.mask&J.bit).map((J)=>`b ${J.up} 0`);for(let J of this.pressed)$.push(`k ${J} 0 ${v$}`);for(let J of this.held){let[Q,Z]=UJ.get(J);$.push(`k ${Q} 0 ${v$|(Z?BJ:0)}`)}return this.mask=0,this.pressed.clear(),this.held.clear(),$}}function RJ($){let J=b$(...g$("input"),{env:S$(),stdio:["pipe","pipe","ignore"],windowsHide:!0}),Q=new NJ,Z="",q=!1,z=null,W=()=>{if(z?.kill("SIGKILL"),J.exitCode!==null||J.signalCode!==null)return;J.stdin.end(Q.release().map((X)=>`${X}
|
|
68
|
+
`).join("")),setTimeout(()=>J.kill("SIGKILL"),2000).unref()},H=(X)=>{if(q)return;q=!0,W(),$.end(X)},C=(X)=>H({error:new c("display_unavailable",X)}),L=(X)=>{if(q||X.length===0)return;if(J.stdin.write(X.map((F)=>`${F}
|
|
69
|
+
`).join("")),J.stdin.writableLength>xQ)H({reason:"input_backpressure"})},B=()=>{z=b$(...g$("clipboard"),{env:S$(),stdio:["ignore","pipe","ignore"],windowsHide:!0});let X="";z.stdout?.on("data",(F)=>{if(q)return;X+=F.toString("ascii");for(let j=X.indexOf(`
|
|
70
|
+
`);j>=0;j=X.indexOf(`
|
|
71
|
+
`)){let T=X.slice(0,j).replace(/\r$/,"");if(X=X.slice(j+1),!T.startsWith("c "))continue;let I=T.slice(2);if(I.length>Math.ceil(M/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(I)){H({reason:"display_protocol"});return}let V=Buffer.from(I,"base64");if(V.byteLength<=M)$.clipboard(V.toString("utf8"));if(q)return}if(X.length>Math.ceil(M/3)*4+4)H({reason:"display_protocol"})}),z.once("error",()=>C("Reason could not watch this computer's desktop clipboard.")),z.once("exit",()=>{if(!q)C("Reason could not watch this computer's desktop clipboard.")})};return J.stdout.on("data",(X)=>{if(q||Z===null)return;Z+=X.toString("utf8");let F=Z.indexOf(`
|
|
72
|
+
`);if(F<0){if(Z.length>4096)H({reason:"display_protocol"});return}let j=CJ(Z.slice(0,F).trim());if(Z=null,!j)H({reason:"display_protocol"});else if(j.session===0)C("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else B(),$.ready({width:j.width,height:j.height})}),J.stdin.on("error",()=>{return}),J.once("error",()=>C("Reason could not start this computer's desktop input.")),J.once("exit",()=>{if(Z!==null)C("Reason could not start this computer's desktop input.");else H({reason:"display_closed"})}),{pointer:(X,F,j)=>L(Q.pointer(X,F,j)),key:(X,F)=>L(Q.key(X,F)),clipboard:(X)=>L([`c ${Buffer.from(X,"utf8").toString("base64")}`]),close(){q=!0,W()}}}var uQ=["none","standard","all"],Y$="22.23.3",mQ={"linux-x64":"1084aa36196bba4c3a5e69a1ee388a6e4ff729dad09445fbcd434b28fe3c24af","linux-arm64":"5ced2d48d1d7198739b7f86804de0171aefb6823b684b12341d3321afc3cb0b2","darwin-arm64":"23b25245dcfb9af7262f8ff142e9e2e0af025368117329e7a7458a51e5922f53","win32-x64":"2b0ff57b049cda1bbcea2240eec20467018713c1efe1f7360c2681859b90ed71","win32-arm64":"33dad22e4cef5ee8f9fbb1b0d037fdacd0e56d12a4580f0d63f68b894deab535"},y$={"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"}},wJ="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",TJ="chrome-win64/chrome.exe",d={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},lQ={version:d.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},E$={version:d.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${d.version}/ffmpeg-${d.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},IJ=`ffmpeg-${E$.version}-essentials_build/bin`,f="com.ifuryst.open_browser_use.extension",kJ="com.reasonmachines.browser_use.extension",PJ="/tmp/reason-browser-use",m$=["tint2","picom","xterm","pcmanfm"],vJ=["fonts-droid-fallback"],bJ=["pulseaudio"],_J=["tigervnc-standalone-server"],cQ=["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",...vJ,"galculator","chromium","ffmpeg","tmux",...bJ,..._J,...m$],dQ=new Set([...m$,...vJ,...bJ,..._J]),xJ=cQ.filter(($)=>$!=="chromium"&&!dQ.has($)),pQ=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],V$="/usr/bin/chromium",iQ=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function gJ($=process.platform,J=process.arch){let Q=`${$}-${J}`;return Q==="linux-x64"||Q==="linux-arm64"||Q==="darwin-arm64"||Q==="win32-x64"||Q==="win32-arm64"?Q:null}function p($){return $==="win32-x64"||$==="win32-arm64"}function l$($){return p($)?`node-v${Y$}-${$.replace("win32","win")}`:`node-v${Y$}-${$}`}function X$($){return{node:{version:Y$,url:`https://nodejs.org/dist/v${Y$}/${l$($)}${p($)?".zip":".tar.gz"}`,sha256:mQ[$]},open_computer_use:{version:v.ocu.version,url:o.ocu.url,sha256:o.ocu.sha256},open_browser_use:{version:v.obu.version,url:o.obu.url,sha256:o.obu.sha256},...$==="darwin-arm64"?{chrome_for_testing:{version:E.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${E.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:E.macArm64Sha256}}:p($)?{chrome_for_testing:{version:E.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${E.version}/win64/chrome-win64.zip`,sha256:E.win64Sha256}}:{}}}function rQ($){let J={extension:l};for(let[Q,Z]of Object.entries(X$($)))J[Q]=`${Z.version}@${Z.sha256}`;return J}function SJ($){return U($,".local","share","reason","desktop")}function yJ($,J=MJ()){let Q=SJ(J),Z=(X)=>U(Q,X,X$($)[X]?.version??""),q=Z("open_computer_use"),z=Z("open_browser_use"),W=$==="darwin-arm64",H=p($),C=U(J,"Library","Application Support"),L=U(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:U(J,"AppData","Local"),"OpenBrowserUse"),B=W?U(C,"Google","Chrome","NativeMessagingHosts",`${f}.json`):H?U(L,"NativeMessagingHosts",`${f}.json`):U(J,".config","google-chrome","NativeMessagingHosts",`${f}.json`);return{root:Q,automation:U(u$(Q),"automation"),receipt:U(Q,"receipt.json"),minimal:d$(J),node:H?U(Z("node"),l$($),"node.exe"):U(Z("node"),"bin","node"),ocuDir:q,ocu:U(q,y$[$].ocu),ocuApp:W?U(q,"dist","Open Computer Use.app"):null,obuDir:z,obu:U(z,"cli","open-browser-use.js"),nativeHost:U(z,y$[$].obu),extensionDir:W?U(C,"OpenBrowserUse","chrome-extension","release"):H?U(L,"chrome-extension","release"):U(J,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:B,nativeHostManifests:W?[B,U(C,"Google","ChromeForTesting","NativeMessagingHosts",`${f}.json`)]:H?[B]:[U(J,".config","chromium","NativeMessagingHosts",`${f}.json`),U(J,".config","google-chrome-for-testing","NativeMessagingHosts",`${f}.json`)],browser:W?U(Z("chrome_for_testing"),wJ):H?U(Z("chrome_for_testing"),TJ):V$,userChromeHost:W?U(Q,"user-chrome","reason-browser-use"):null,userChromeRegistration:W?U(C,"Google","Chrome","NativeMessagingHosts",`${kJ}.json`):null,ffmpegDir:U(Q,"ffmpeg"),ffmpeg:W?U(Q,"ffmpeg",d.version,"ffmpeg"):H?U(Q,"ffmpeg",E$.version,IJ,"ffmpeg.exe"):null,ffprobe:W?U(Q,"ffprobe",lQ.version,"ffprobe"):H?U(Q,"ffmpeg",E$.version,IJ,"ffprobe.exe"):null}}function EJ($){try{let J=JSON.parse(H$($,"utf8"));if(typeof J!=="object"||J===null)return null;let Q=J,Z=Q.pins;if(Q.schema_version!==1||typeof Q.platform!=="string"||typeof Z!=="object"||Z===null||!Object.values(Z).every((q)=>typeof q==="string")||!uQ.includes(Q.permissions)||!Array.isArray(Q.missing_system_packages)||!Q.missing_system_packages.every((q)=>typeof q==="string")||typeof Q.updated_at!=="string")return null;return{schema_version:1,platform:Q.platform,pins:Z,permissions:Q.permissions,missing_system_packages:Q.missing_system_packages,updated_at:Q.updated_at}}catch{return null}}function aQ($,J,Q=384){gQ(u$($),{recursive:!0,mode:448});let Z=`${$}.pending.${process.pid}`;fQ(Z,J,{mode:Q}),SQ(Z,$)}function b($){try{return h$($).isFile()}catch{return!1}}function fJ($){try{let J=h$($);return J.isFile()&&(J.mode&73)!==0}catch{return!1}}function oQ($){try{return H$($,"utf8")}catch{return null}}function S($){for(let J of iQ){let Q=U(J,$);try{let Z=h$(Q);if(Z.isFile()&&(Z.mode&73)!==0)return Q}catch{}}return null}function sQ($){try{let J=JSON.parse(H$(U($,"package.json"),"utf8"));return typeof J==="object"&&J!==null&&typeof J.version==="string"?J.version:null}catch{return null}}function nQ($,J,Q){let Z=X$(Q)[$];if(!Z)return!1;let q=p(Q);if($==="node")return b(q?U(J,l$(Q),"node.exe"):U(J,"bin","node"));if($==="chrome_for_testing")return b(U(J,q?TJ:wJ));let z=y$[Q][$==="open_computer_use"?"ocu":"obu"];return sQ(J)===Z.version&&b(U(J,z))&&($==="open_computer_use"||b(U(J,"cli","open-browser-use.js")))}function tQ($){return AJ("sha256").update(Buffer.from($,"base64")).digest("hex").slice(0,32).replace(/./g,(J)=>String.fromCharCode(97+Number.parseInt(J,16)))}function c$($){try{let J=JSON.parse(H$($,"utf8"));return typeof J==="object"&&J!==null&&!Array.isArray(J)?J:null}catch{return null}}function eQ($){let J=c$(U($.extensionDir,"manifest.json"));return J!==null&&J.version===v.obu.version&&typeof J.key==="string"&&tQ(J.key)===l}function $0($,J){let Q=$?.allowed_origins;return $!==null&&$.name===f&&Array.isArray(Q)&&Q.length===1&&Q[0]===`chrome-extension://${l}/`&&(J===void 0||$.path===J)}function J0($){return eQ($)&&b($.nativeHost)&&$.nativeHostManifests.every((J)=>$0(c$(J),$.nativeHost))}function Q0($){return`#!/bin/sh
|
|
73
|
+
# Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
|
|
74
|
+
obu=${`'${$.replaceAll("'","'\\''")}'`}
|
|
75
|
+
case "$1" in
|
|
76
|
+
chrome-extension://*) exec "$obu" host --socket-dir ${PJ} ;;
|
|
77
|
+
mcp) shift; exec "$obu" mcp --socket-dir ${PJ} "$@" ;;
|
|
78
|
+
esac
|
|
79
|
+
exec "$obu" "$@"
|
|
80
|
+
`}function Z0($){let J=c$($),Q=J?.allowed_origins;return J!==null&&J.name===kJ&&J.type==="stdio"&&Array.isArray(Q)&&Q.includes(`chrome-extension://${k$}/`)&&typeof J.path==="string"&&fJ(J.path)}function q0($,J){if(!$.userChromeHost||!$.userChromeRegistration)return null;if(!J||oQ($.userChromeHost)!==Q0($.nativeHost)||!fJ($.userChromeHost))return{code:"user_chrome_browser_use_missing"};return Z0($.userChromeRegistration)?{host:$.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var z0={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 n($={}){let J=$.platform===void 0?gJ():$.platform;if(!J)return null;let Q=yJ(J,$.home),Z=EJ(Q.receipt),q=rQ(J),z=Z!==null&&Z.platform===J&&JSON.stringify(Object.entries(Z.pins).sort())===JSON.stringify(Object.entries(q).sort()),W=[],H=X$(J);for(let V of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let D=H[V];if(!D)continue;let R=nQ(V,U(Q.root,V,D.version),J),P=Z?.pins[V],_=R&&P===q[V]?"ready":P!==void 0&&P!==q[V]?"outdated":"missing";W.push({name:V,state:_,detail:D.version})}let C=Z?.pins.extension===l&&J0(Q);W.push({name:"browser_extension",state:C?"ready":"missing",detail:l});let L=S("Xvfb"),B=S("x11vnc"),X=S("openbox");if(p(J))W.push(DJ()?{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"}),W.push(Q.ffmpeg&&b(Q.ffmpeg)?{name:"desktop_video",state:"ready",detail:Q.ffmpeg}:{name:"desktop_video",state:"missing",detail:"run `reason desktop install` for desktop video"});else if(J!=="darwin-arm64"){W.push(b(V$)?{name:"browser",state:"ready",detail:V$}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${V$}`});let V=L!==null&&B!==null&&X!==null;W.push({name:"display",state:V?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let D=pQ.filter((O)=>S(O)===null),R=(Z?.missing_system_packages??xJ).filter((O)=>xJ.includes(O)),P=D.length===0&&R.length===0;W.push(P?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...R,...D])].join(" ")});let _=m$.filter((O)=>S(O)===null);W.push(_.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:_.join(" ")})}let F=Q.ffmpeg&&b(Q.ffmpeg)?Q.ffmpeg:S("ffmpeg"),j=!F?null:F===Q.ffmpeg?Q.ffprobe:U(u$(yQ(F)),"ffprobe"),T=z&&W.every((V)=>V.state==="ready"),I=(V)=>z&&W.every((D)=>!z0[V].includes(D.name)||D.state==="ready");return{platform:J,root:Q.root,automation:Q.automation,ready:T,features:{display:I("display"),computer:I("computer"),browser:I("browser")},node:Q.node,ocu:Q.ocu,obu:Q.obu,nativeHost:Q.nativeHost,extensionDir:Q.extensionDir,browser:Q.browser,ffmpeg:F,ffprobe:j&&b(j)?j:null,userChrome:q0(Q,z&&["node","open_browser_use"].every((V)=>W.find((D)=>D.name===V)?.state==="ready")),pulseaudio:S("pulseaudio"),xvnc:S("Xvnc"),xvfb:L,x11vnc:B,openbox:X,components:W}}function hJ($){return W0($)?OJ():[]}function W0($){return $?.platform==="darwin-arm64"&&$.ffmpeg===U($.root,"ffmpeg",d.version,"ffmpeg")}async function b4($,J,Q,Z=fetch){try{let q=await Z($,{redirect:"follow"});if(!q.ok||!q.body)throw Error(`download failed (HTTP ${q.status}): ${$}`);let z=AJ("sha256"),W=bQ(Q,{mode:384});try{let C=q.body.getReader();for(let L=await C.read();!L.done;L=await C.read())if(z.update(L.value),!W.write(L.value))await vQ(W,"drain")}finally{W.end(),await hQ(W)}let H=z.digest("hex");if(H!==J)throw Error(`digest mismatch for ${$}: expected ${J}, got ${H}`)}catch(q){throw EQ(Q,{force:!0}),q}}function d$($){return U(SJ($),"minimal.json")}function V0($=G$()){return _Q(d$($))}function _4($={}){aQ(d$($.home??G$()),`${JSON.stringify({version:1,minimal_at:($.now?.()??new Date).toISOString()})}
|
|
81
|
+
`)}function g4($={}){let J=$.platform===void 0?gJ():$.platform;if(J===null)return null;let Q=$.home??G$();if(EJ(yJ(J,Q).receipt)!==null)return"refresh";return V0(Q)?null:"install"}import{spawn as Y0}from"child_process";import{existsSync as G0}from"fs";import{connect as H0}from"net";import{join as j$}from"path";var mJ="reason_desktop",t={sampleRate:48000,channels:2,codec:"opus"},X0=5000,j0=107,K0=262144,B0=($)=>j$($,"native"),lJ=($)=>`unix:${$}`;function p$($,J=1000){if(!G0($))return Promise.resolve(!1);return new Promise((Q)=>{let Z=H0({path:$}),q=(z)=>{Z.destroy(),Q(z)};Z.setTimeout(J,()=>q(!1)),Z.once("error",()=>q(!1)),Z.once("close",()=>q(!1)),Z.once("connect",()=>q(!0))})}async function u4($,J){if(!J)return null;let Q=B0($);if(Buffer.byteLength(Q)>j0||/["'\\\s]/.test(Q))return null;try{if(await p$(Q))return Q;let Z=Y0(J,["--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:${j$($,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${Q}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${mJ} rate=${t.sampleRate} channels=${t.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:$,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:$,PULSE_RUNTIME_PATH:j$($,"runtime"),PULSE_STATE_PATH:j$($,"state")}}),q=!1;Z.once("error",()=>{q=!0}),Z.once("exit",()=>{q=!0}),Z.unref();let z=Date.now()+X0;while(Date.now()<z){if(await p$(Q))return Q;if(q)return await p$(Q)?Q:null;await new Promise((W)=>setTimeout(W,50))}if(!q)Z.kill("SIGKILL");return null}catch{return null}}function cJ(){let{sampleRate:$,channels:J}=t;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String($),"-channels",String(J),"-fragment_size",String($*J*2/50),"-i",`${mJ}.monitor`,"-vn","-ac",String(J),"-ar",String($),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var L0=[79,103,103,83],U0=Buffer.from("OpusHead"),C0=Buffer.from("OpusTags"),uJ=($,J)=>$.byteLength>=J.byteLength&&J.every((Q,Z)=>$[Z]===Q);class i$ extends Error{constructor($){super($);this.name="OggProtocolError"}}class r${buffer=new Uint8Array(0);partial=[];partialBytes=0;push($){let J=new Uint8Array(this.buffer.byteLength+$.byteLength);J.set(this.buffer),J.set($,this.buffer.byteLength);let Q=[],Z=0;while(J.byteLength-Z>=27){if(L0.some((F,j)=>J[Z+j]!==F)||J[Z+4]!==0)throw new i$("invalid_page");let q=(J[Z+5]&1)!==0,z=J[Z+26];if(J.byteLength-Z<27+z)break;let W=J.subarray(Z+27,Z+27+z),H=W.reduce((F,j)=>F+j,0),C=27+z+H;if(J.byteLength-Z<C)break;if(!q&&this.partialBytes>0)this.resetPartial();let L=q&&this.partialBytes===0,B=Z+27+z,X=B;for(let F of W){if(B+=F,F===255)continue;if(this.appendPartial(J.subarray(X,B),L),X=B,!L){let j=this.takePartial();if(j.byteLength>0&&!uJ(j,U0)&&!uJ(j,C0))Q.push(j)}L=!1,this.resetPartial()}if(X<B)this.appendPartial(J.subarray(X,B),L);Z+=C}return this.buffer=J.slice(Z),Q}appendPartial($,J){if(J||$.byteLength===0)return;if(this.partialBytes+=$.byteLength,this.partialBytes>K0)throw new i$("packet_too_large");this.partial.push($.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let $=new Uint8Array(this.partialBytes),J=0;for(let Q of this.partial)$.set(Q,J),J+=Q.byteLength;return $}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as F0}from"child_process";var dJ=1048576,D0=String.raw`
|
|
82
|
+
import gi, json, os, sys
|
|
83
|
+
gi.require_version("Gtk", "3.0")
|
|
84
|
+
from gi.repository import Gtk, Gdk, GLib
|
|
85
|
+
if not Gtk.init_check()[0]:
|
|
86
|
+
sys.exit(1)
|
|
87
|
+
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
|
|
88
|
+
pending = b""
|
|
89
|
+
generation = 0
|
|
90
|
+
def send(value):
|
|
91
|
+
print(json.dumps(value, ensure_ascii=True), flush=True)
|
|
92
|
+
def changed(clipboard, event):
|
|
93
|
+
global generation
|
|
94
|
+
generation += 1
|
|
95
|
+
current = generation
|
|
96
|
+
def received(clipboard, text, unused):
|
|
97
|
+
if current == generation and text is not None and len(text.encode("utf-8")) <= ${M}:
|
|
98
|
+
send({"text": text})
|
|
99
|
+
clipboard.request_text(received, None)
|
|
100
|
+
# No request_text on startup: never share the pre-existing clipboard.
|
|
101
|
+
clipboard.connect("owner-change", changed)
|
|
102
|
+
def input_ready(fd, condition):
|
|
103
|
+
global pending
|
|
104
|
+
chunk = os.read(fd, 65536)
|
|
105
|
+
if not chunk:
|
|
106
|
+
Gtk.main_quit()
|
|
107
|
+
return False
|
|
108
|
+
pending += chunk
|
|
109
|
+
while b"\n" in pending:
|
|
110
|
+
line, pending = pending.split(b"\n", 1)
|
|
111
|
+
text = json.loads(line)
|
|
112
|
+
if not isinstance(text, str) or len(text.encode("utf-8")) > ${M} or "\x00" in text:
|
|
113
|
+
sys.exit(1)
|
|
114
|
+
clipboard.set_text(text, -1)
|
|
115
|
+
send("ack")
|
|
116
|
+
if len(pending) > ${M*6+2}:
|
|
117
|
+
sys.exit(1)
|
|
118
|
+
return True
|
|
119
|
+
GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
|
|
120
|
+
send("ready")
|
|
121
|
+
Gtk.main()
|
|
122
|
+
`;function pJ($,J){let Q=F0("/usr/bin/python3",["-I","-u","-c",D0],{env:{DISPLAY:$.display,XAUTHORITY:$.xauthority},stdio:["pipe","pipe","ignore"]}),Z=!1,q=!0,z="",W=0,H=[],C=setTimeout(()=>B(),5000),L=()=>{Z=!0,clearTimeout(C),H.length=0,Q.kill("SIGKILL")},B=()=>{if(Z)return;L(),J.end({error:new c("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},X=(F,j=32)=>{if(Z)return;if(!q){F();return}if(W+=j,W>dJ)L(),J.end({reason:"input_backpressure"});else H.push({apply:F,bytes:j})};return Q.stdout.on("data",(F)=>{if(Z)return;z+=F.toString("ascii");for(let j=z.indexOf(`
|
|
123
|
+
`);j>=0;j=z.indexOf(`
|
|
124
|
+
`)){let T=z.slice(0,j);z=z.slice(j+1);let I;try{I=JSON.parse(T)}catch{B();return}if(I==="ready"||I==="ack"){clearTimeout(C),q=!1;while(!q&&!Z&&H.length){let V=H.shift();W-=V.bytes,V.apply()}}else if(I&&typeof I==="object"&&"text"in I&&typeof I.text==="string"&&Buffer.byteLength(I.text)<=M)J.clipboard(I.text);else{B();return}if(Z)return}if(z.length>M*6+32)B()}),Q.stdin.on("error",B),Q.once("error",B),Q.once("exit",B),{apply:X,write(F){if(Buffer.byteLength(F)>M||F.includes("\x00")){B();return}let j=`${JSON.stringify(F)}
|
|
125
|
+
`;X(()=>{if(q=!0,C=setTimeout(()=>B(),5000),Q.stdin.write(j),Q.stdin.writableLength>dJ)L(),J.end({reason:"input_backpressure"})},Buffer.byteLength(j))},close:L}}var i={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}},P0="avc1.4D002A",iJ={width:1920,height:1080},x0=262144,M0=0.2,O0=250,A0=1e4,w0=1024,a$=1e4,T0=500,k0=60,v0=1e4,b0=1000,rJ=1048576,_0=-223,g0=-308,Z8={kind:"mac_screen",sound:null},q8={kind:"windows_screen",sound:null},S0,aJ=()=>S0??=n()?.ffmpeg??null,B$=($,J,Q)=>s$($,J,{env:Q,stdio:["ignore","pipe","ignore"],windowsHide:!0}),y0,n$=()=>y0??=hJ(n()),oJ=($,J,Q)=>{let[Z,...q]=[...n$(),$];return B$(Z,[...q,...J],Q)},sJ=()=>XQ?.videotoolbox?"h264_videotoolbox":"libx264",E0=()=>Math.round(performance.now()*1000),o$=new Set,nJ=!1;function WQ($){if(o$.add($),$.once("exit",()=>o$.delete($)),nJ)return;nJ=!0,process.once("exit",()=>{for(let J of o$)try{J.kill("SIGKILL")}catch{}})}function VQ($){try{$.stdout?.destroy()}catch{}if($.exitCode!==null||$.signalCode!==null)return;try{$.kill("SIGTERM")}catch{return}let J=setTimeout(()=>{if($.exitCode===null&&$.signalCode===null)try{$.kill("SIGKILL")}catch{}},T0);$.once("exit",()=>clearTimeout(J))}function f0($,J,Q){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String($),"-video_size",`${J.width}x${J.height}`,"-i",Q],size:J}}function h0($){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String($),"-i","Capture screen 0:none"],size:null}}function u0($,J){return{args:["-f","gdigrab","-draw_mouse","1","-framerate",String($),"-offset_x","0","-offset_y","0","-video_size",`${J.width}x${J.height}`,"-i","desktop"],size:J}}function m0($){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String($),"-i","pipe:0"],size:null}}var YQ=1700000;function GQ($){return Math.min(1,Math.round(Math.sqrt(YQ/($.width*$.height))*100)/100)}function l0($,J,Q){let Z=s$(Q.axe,["stream-video","--udid",Q.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,GQ(Q.size)))],{stdio:["ignore","pipe","ignore"]}),q=s$($,J,{env:{},stdio:["pipe","pipe","ignore"]});Z.stdout.pipe(q.stdin),q.stdin.on("error",()=>{});let z=()=>{if(Z.exitCode===null&&Z.signalCode===null)Z.kill("SIGTERM")};return q.once("exit",z),q.once("error",z),Z.once("exit",()=>{if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}),Z.once("error",()=>{if(q.exitCode===null&&q.signalCode===null)q.kill("SIGTERM")}),q}function tJ($){let J=Math.min(1,iJ.width/$.width,iJ.height/$.height);return{width:Math.round($.width*J),height:Math.round($.height*J)}}function K$($,J,Q,Z="libx264"){let q=i[$],z=(X)=>Math.max(2,Math.floor(X/2)*2),W={width:z(Q.width*q.scale),height:z(Q.height*q.scale)},H=W.width!==J.size?.width||W.height!==J.size.height,C=Math.max(1,Math.round(q.kbps*2/q.fps)),L=["-g",String(q.fps*k0)],B=Z==="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",...L,"-b:v",`${q.kbps}k`,"-maxrate",`${q.kbps}k`,"-bufsize",`${C}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",q.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...q.threads?["-threads",String(q.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...L,"-crf",String(q.crf),"-maxrate",`${q.kbps}k`,"-bufsize",`${C}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...J.args,"-an",...H?["-vf",`scale=${W.width}:${W.height}:flags=fast_bilinear`]:[],...B,"-flush_packets","1","-f","h264","pipe:1"]}class HQ{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push($,J){if(this.buffer.byteLength===0)this.micros=J;let Q=new Uint8Array(this.buffer.byteLength+$.byteLength);Q.set(this.buffer),Q.set($,this.buffer.byteLength),this.buffer=Q;let Z=[],q=this.scanned;while(q+3<this.buffer.byteLength){if(this.buffer[q]!==0||this.buffer[q+1]!==0||this.buffer[q+2]!==1){q++;continue}let z=this.buffer[q+3]&31,W=q>0&&this.buffer[q-1]===0?q-1:q;if(z===9&&W>0)Z.push({data:this.buffer.slice(0,W),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(W),this.key=!1,this.micros=J,q-=W;if(z===5)this.key=!0;q+=3}return this.scanned=q,Z}}function c0($,J){let Q=I0({path:$}),Z=Buffer.alloc(0),q="version",z=0,W=!1,H=[],C=0,L=!1,B=(V)=>{if(L)return;L=!0,Q.destroy(),J.end(V)},X=()=>B({reason:"display_protocol"}),F=(V)=>{if(L)return;if(!W){if(C+=V.byteLength,C>rJ)B({reason:"input_backpressure"});else H.push(V);return}if(Q.write(V),Q.writableLength>rJ)B({reason:"input_backpressure"})},j=(V)=>{Z=Z.subarray(V)},T=()=>{switch(q){case"version":{if(Z.byteLength<12)return!1;let V=/^RFB (\d{3})\.(\d{3})\n$/.exec(Z.subarray(0,12).toString("latin1"));if(!V||Number(V[1])*1000+Number(V[2])<3007)return X(),!1;return j(12),Q.write(`RFB 003.007
|
|
126
|
+
`),q="security",!0}case"security":{if(Z.byteLength<1)return!1;let V=Z[0];if(V===0)return X(),!1;if(Z.byteLength<1+V)return!1;if(!Z.subarray(1,1+V).includes(1))return X(),!1;return j(1+V),Q.write(Buffer.from([1,1])),q="init",!0}case"init":{if(Z.byteLength<24)return!1;let V=Z.readUInt32BE(20);if(V>65536)return X(),!1;if(Z.byteLength<24+V)return!1;let D={width:Z.readUInt16BE(0),height:Z.readUInt16BE(2)};if(j(24+V),D.width===0||D.height===0)return X(),!1;q="messages";let R=Buffer.alloc(12);R.writeUInt8(2,0),R.writeUInt16BE(2,2),R.writeInt32BE(g0,4),R.writeInt32BE(_0,8),Q.write(R),W=!0;for(let P of H)Q.write(P);return H=[],C=0,J.ready(D),!L}case"skip":{let V=Math.min(z,Z.byteLength);if(j(V),z-=V,z>0)return!1;return q="messages",!0}case"messages":{if(Z.byteLength<1)return!1;switch(Z[0]){case 1:{if(Z.byteLength<6)return!1;let V=6+Z.readUInt16BE(4)*6;if(Z.byteLength<V)return!1;return j(V),!0}case 2:return j(1),!0;case 3:{if(Z.byteLength<8)return!1;let V=Z.readUInt32BE(4);if(V>M/2)return j(8),q="skip",z=V,!0;if(Z.byteLength<8+V)return!1;let D=Z.subarray(8,8+V).toString("latin1");return j(8+V),J.clipboard(D),!L}default:return X(),!1}}}},I=!1;return Q.once("connect",()=>{I=!0}),Q.on("data",(V)=>{if(L)return;Z=Z.byteLength?Buffer.concat([Z,V]):V;while(!L&&T());}),Q.once("error",()=>{if(!I)B({error:new c("display_unavailable","Reason could not reach this machine's desktop server.")})}),Q.once("close",()=>B({reason:"display_closed"})),{pointer(V,D,R){let P=Buffer.alloc(6);P.writeUInt8(5,0),P.writeUInt8(R&255,1),P.writeUInt16BE(V,2),P.writeUInt16BE(D,4),F(P)},key(V,D){let R=Buffer.alloc(8);R.writeUInt8(4,0),R.writeUInt8(V?1:0,1),R.writeUInt32BE(D>>>0,4),F(R)},clipboard(V){if(Array.from(V).some((P)=>P.codePointAt(0)>255)){B({reason:"clipboard_unicode_unsupported"});return}let D=Buffer.from(V,"latin1"),R=Buffer.alloc(8);R.writeUInt8(6,0),R.writeUInt32BE(D.byteLength,4),F(Buffer.concat([R,D]))},close(){L=!0,Q.destroy()}}}class t${run=null;viewers=new Set;get running(){return this.run!==null}start($,J,Q,Z){this.viewers.add($),this.stop();let q;try{q=Q()}catch{this.fail();return}WQ(q);let z={child:q,splitter:new HQ};this.run=z;for(let H of[...this.viewers])H.started(J);q.stdout?.on("data",(H)=>{if(this.run!==z)return;for(let C of z.splitter.push(H,Z()))for(let L of[...this.viewers])L.unit(C)});let W=()=>{if(this.run!==z)return;this.run=null,this.fail()};q.once("exit",W),q.once("error",W)}leave($){if(!this.viewers.delete($))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;VQ(this.run.child),this.run=null}fail(){for(let $ of[...this.viewers])$.failed()}}var eJ=new WeakMap;function d0($){let J=eJ.get($);if(!J)eJ.set($,J=new t$);return J}var e=new Map;function z8($,J,Q={}){let Z=Q.micros??E0,q=new ZQ,z=J.request.preset,W=null,H=null,C=null,L=!1,B=null,X=!1,F=!1,j=null,T=0,I=0,V=!1,D=null,R=null,P=0,_=null,O=[],$$=0,g=[],e$=new Uint32Array(a$+1),L$=0,U$=null,C$=0,r=0,F$=0,$J=0,JJ=0,J$=null,D$=0,h={frames:0,bytes:0,since:Z()},u=[],a=0,N$,R$=!1,KQ=Z(),w={},m=()=>Math.round((Z()-KQ)/1000),QJ=Q.control??HJ,I$=null,P$=null,ZJ=0,x$=!1,qJ={pause(){if(!B?.running)return;B.stop(),x$=!0},adopt(Y){let G=Y!==null&&(Y.width!==H?.width||Y.height!==H?.height);if(G)H=Y;if(!G&&!x$)return;if(x$=!1,B)W$();else A$()}},BQ=(Y)=>{if(!Q.resizeDesktop||!W||"kind"in W||$.done)return;let G=W.display,K=()=>[...e.get(G)??[]];ZJ++,Q.resizeDesktop(W,Y,()=>{for(let N of K())N.pause()}).then((N)=>{for(let x of K())x.adopt(N)})},k=(Y)=>{let G=QQ(Y);return $.send(G),$J+=G.byteLength,G.byteLength},Q$=(Y)=>{if($.done)return;if($.open)k({type:"error",code:Y});$.end({reason:Y})},Z$=()=>Math.max(x0,i[z].kbps*1000/8*M0),q$=()=>Z()/1000,LQ=()=>{while(g.length>1&&g[0].atMs<q$()-A0)g.shift();return g[0]?.rttMs??null},zJ=(Y)=>{let G=LQ();if(G===null||O.length===0)return!1;let K=(G+O0)*Y;return q$()-O[0].sentMs>K||$$>K/1000*i[z].kbps*1000/8},UQ=(Y)=>{if(P===0)return;let G=Math.min(Y,P-1);if(_!==null&&G<=_)return;_=G;let K=q$();while(O.length&&O[0].seq<=G){let N=O.shift();if($$-=N.bytes,N.seq!==G)continue;let x=Math.max(0,K-N.sentMs);while(g.length&&g.at(-1).rttMs>=x)g.pop();g.push({atMs:K,rttMs:x}),e$[Math.min(a$,Math.round(x))]++,L$++,U$=Math.min(U$??x,x)}},CQ=()=>{let Y=0;for(let G=0;G<=a$;G++)if(Y+=e$[G],Y*2>=L$)return G;return 0},FQ=()=>$.bufferedAmount<=Z$()/2&&!zJ(0.5),WJ=()=>{R$=!0,u=[],a=0,B?.leave(M$),B=null},VJ=(Y)=>{if($.done)return;if(Y.key)w.first_key_ms??=m();if(!L){if(!B||u.length===0&&!Y.key)return;if(u.push(Y),a+=Y.data.byteLength,a>Z$())WJ();return}if(V){r++;return}if($.bufferedAmount>Z$()||zJ(1)){V=!0,r++,D=setInterval(()=>{if($.done||!FQ())return;if(D)clearInterval(D);D=null,V=!1,W$()},Q.drainPollMs??25);return}if(!X){if(!Y.key){r++;return}if(k({type:"hello",width:H.width,height:H.height,fps:i[z].fps,preset:z,codec:P0}),X=!0,w.first_frame_ms??=m(),!F&&W?.sound)k({type:"audioHello",...t}),F=!0}let G=k({type:"frame",key:Y.key,seq:P,captureMicros:Y.micros,data:Y.data});if(O.push({seq:P,sentMs:q$(),bytes:G}),$$+=G,O.length>w0)$$-=O.shift().bytes;P++,C$++,J$??=Y.micros,D$=Y.micros,h.frames++,h.bytes+=G},M$={started(Y){z=Y,X=!1,u=[],a=0},unit:VJ,failed:()=>Q$("encoder_failed")},O$=()=>{let Y=(Q.ffmpeg??aJ)();if(!W||!H){Q$("encoder_failed");return}let[G,K]=[W,H],N="kind"in G&&G.kind==="simulator"?G.stream:null;if(!Y&&!N){Q$("encoder_failed");return}if(B??="kind"in G&&G.kind==="mac_screen"?d0(Q.spawn??oJ):new t$,w.encoder_ms===void 0)w.encoder_ms=m(),w.encoder_shared=B.running;B.start(M$,z,()=>{let x=i[z].fps;if(N)return N(x,i[z].kbps,YQ);if("kind"in G&&G.kind==="simulator"){let A=Math.min(0.99,GQ(G.size)),y={width:G.size.width*A,height:G.size.height*A};return l0(Y,K$(z,m0(Math.min(x,30)),y,(Q.macEncoder??sJ)()),G)}if("kind"in G&&G.kind==="windows_screen")return(Q.spawn??B$)(Y,K$(z,u0(x,K),tJ(K)),{SystemRoot:process.env.SystemRoot??"C:\\Windows"});return"kind"in G?(Q.spawn??oJ)(Y,K$(z,h0(x),tJ(K),(Q.macEncoder??sJ)()),{}):(Q.spawn??B$)(Y,K$(z,f0(x,K,G.display),K),{DISPLAY:G.display,XAUTHORITY:G.xauthority})},Z)},z$=()=>{if(!j)return;VQ(j.child),j=null},DQ=()=>{let Y=(Q.ffmpeg??aJ)();if(j||$.done||!F||!W?.sound||!Y)return;let G;try{G=(Q.spawn??B$)(Y,cJ(),{PULSE_SERVER:lJ(W.sound)})}catch{return}WQ(G);let K={child:G,reader:new r$};j=K,G.stdout?.on("data",(x)=>{if(j!==K||$.done)return;let A;try{A=K.reader.push(x)}catch{z$();return}let y=Z();for(let T$ of A){if($.bufferedAmount>Z$()){I++;continue}k({type:"audio",captureMicros:y,data:T$}),T++}});let N=()=>{if(j===K)z$()};G.once("exit",N),G.once("error",N)},W$=()=>{if(!B||$.done)return;F$++,O$()},A$=()=>{if($.done||!H)return;if(!L){if(B||R$)return;O$(),N$=setTimeout(()=>{if(!L)WJ()},v0);return}if(clearTimeout(N$),w.encoder_early===void 0){if(w.encoder_early=B!==null,R$)w.hold_lapsed=!0}if(!B)O$();let Y=u;u=[],a=0;for(let G of Y)VJ(G);R??=setInterval(()=>{let G=Z(),K=Math.max(0.001,(G-h.since)/1e6);k({type:"stats",stats:{fps:Math.round(h.frames/K*10)/10,kbps:Math.round(h.bytes*8/1000/K),dropped:r,restarts:F$,queued_bytes:$.bufferedAmount}}),h={frames:0,bytes:0,since:G}},b0)};J.desktop.then((Y)=>{if($.done)return;W=Y;let G={ready(K){H=K,w.desktop_ms??=m(),A$()},clipboard(K){if($.open&&Buffer.byteLength(K)<=M)k({type:"serverClipboard",text:K})},end(K){if("reason"in K&&$.open)k({type:"error",code:K.reason});$.end(K)}};if("kind"in Y&&Y.kind==="simulator")C=Y.input,G.ready(Y.points);else if("kind"in Y&&Y.kind==="windows_screen")C=(Q.windowsInput??RJ)(G);else if("kind"in Y)C=(Q.macInput??((K)=>zQ(K,n$())))(G);else{let K=e.get(Y.display);if(!K)e.set(Y.display,K=new Set);K.add(qJ);let N=(Q.linuxClipboard??pJ)(Y,G),x=c0(Y.rfbSocket,{...G,clipboard:(A)=>{if(!N)G.clipboard(A)}});C=N?{pointer:(A,y,T$)=>N.apply(()=>x.pointer(A,y,T$)),key:(A,y)=>N.apply(()=>x.key(A,y)),clipboard:(A)=>N.write(A),close(){N.close(),x.close()}}:x}YJ()},(Y)=>$.end({error:Y}));function YJ(){if(P$||!J.viewerSameNetwork||!L||$.done||!W||!("kind"in W)||W.kind!=="mac_screen")return;P$=(Q.macWindows??qQ)((Y)=>{if($.open)k({type:"windows",bounds:Y})})}let GJ={viewer:J.viewer??null,notify(Y){if($.open)k({type:"control",control:Y})}},w$=(Y)=>{if(!C)return;if(!W||!("kind"in W)||W.kind!=="simulator")QJ.claim(GJ);Y(C)};return{opened(){w.relay_ms??=m()},received(Y){JJ+=Y.byteLength;let G;try{G=q.push(Y)}catch{Q$("viewer_protocol");return}for(let K of G){if($.done)return;switch(K.type){case"ping":k({type:"pong",token:K.token});break;case"pointer":w$((N)=>N.pointer(K.x,K.y,K.buttons));break;case"key":w$((N)=>N.key(K.down,K.keysym));break;case"clientClipboard":w$((N)=>N.clipboard(K.text));break;case"config":if(K.preset!==z)z=K.preset,W$();break;case"keyframeRequest":if(X&&!V)W$();break;case"ack":UQ(K.seq);break;case"audioEnable":if(K.on)DQ();else z$();break;case"resize":BQ({width:K.width,height:K.height});break;default:break}}if(!L&&!$.done){if(L=!0,w.viewer_ms=m(),J.viewer)I$=QJ.join(GJ);A$(),YJ()}},close(){if(W&&!("kind"in W)){let Y=e.get(W.display);if(Y?.delete(qJ),Y?.size===0)e.delete(W.display)}if(I$?.(),I$=null,P$?.close(),D)clearInterval(D);if(R)clearInterval(R);clearTimeout(N$),B?.leave(M$),z$(),C?.close()},summary:()=>({output_bytes:$J,input_bytes:JJ,video:{preset:z,frames:C$,dropped:r,restarts:F$,avg_fps:J$!==null&&D$>J$?Math.round((C$-1)/((D$-J$)/1e6)*10)/10:0,min_rtt_ms:Math.round(U$??0),p50_rtt_ms:L$?CQ():0,audio_packets:T,audio_dropped:I,resizes:ZJ,connect:w}})}}var $Q=null,XQ=null,p0=null,i0=null;function r0(){let $=n();return $?.features.display?$.ffmpeg:null}function jQ($){return $Q??=new Promise((J)=>{N0($,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(Q,Z)=>{let q=(z)=>!Q&&new RegExp(`^\\s*V\\S*\\s+${z}\\s`,"m").test(Z);J(XQ={x264:q("libx264"),videotoolbox:q("h264_videotoolbox")})})}),$Q}var JQ=null;function W8(){return JQ??=(async()=>{let $=[n()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((Q)=>Boolean(Q&&R0(Q)));if(!$)return null;let J=await jQ($);return J.videotoolbox||J.x264?$:null})(),JQ}function V8($=process.platform,J={}){if($!=="linux"&&$!=="darwin"&&$!=="win32")return Promise.resolve(!1);let Q=(J.ffmpeg??r0)();if(!Q)return Promise.resolve(!1);let Z=(J.encoders??jQ)(Q);if($==="linux")return Z.then((z)=>z.x264);if($==="win32"){let z=J.windowsScreen?J.windowsScreen():i0??=FJ();return Promise.all([Z,z]).then(([W,H])=>W.x264&&(H?.session??0)>0)}let q=J.macScreen?J.macScreen():p0??=f$(n$());return Promise.all([Z,q]).then(([z,W])=>(z.x264||z.videotoolbox)&&W?.screen===!0&&W.accessibility)}
|
|
127
|
+
export{k$ as Gg,o0 as Hg,l as Ig,t0 as Jg,B0 as Kg,lJ as Lg,u4 as Mg,Z8 as Ng,q8 as Og,z8 as Pg,W8 as Qg,V8 as Rg,PJ as Sg,yJ as Tg,n as Ug,b4 as Vg,_4 as Wg,g4 as Xg};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Wi as v}from"./vm-hands-entry-lite-xp3qzxk5.js";import{Yi as r,cj as o,fj as g,gj as h,hj as a}from"./vm-hands-entry-lite-26q3hbdc.js";import{Yj as V}from"./vm-hands-entry-lite-6nwbqg37.js";import{Vk as U}from"./vm-hands-entry-lite-q8wkrzer.js";import{createHmac as mQ,createPublicKey as CQ,randomBytes as LQ,randomUUID as t,verify as EQ}from"crypto";import{chmodSync as _,existsSync as e,mkdirSync as IQ,readFileSync as gQ,realpathSync as hQ,renameSync as vQ,statSync as yQ,unlinkSync as uQ,writeFileSync as pQ}from"fs";import{basename as cQ,dirname as F,isAbsolute as QQ,join as A,resolve as lQ}from"path";var WZ=[Object.freeze({family:"ara",channel:"stable",applicationId:"so.ara.desktop"}),Object.freeze({family:"ara",channel:"staging",applicationId:"so.ara.desktop.staging"}),Object.freeze({family:"reason",channel:"stable",applicationId:"com.reasonmachines.desktop"}),Object.freeze({family:"reason",channel:"staging",applicationId:"com.reasonmachines.desktop.staging"})];var zQ="REASON_DESKTOP_RUNTIME",UQ="REASON_DESKTOP_RUNTIME_CHANNEL",JQ="REASON_DESKTOP_RUNTIME_INSTANCE_ID",MQ="REASON_DESKTOP_RUNTIME_WORKSPACE_SCOPE",zZ={[zQ]:"ARA_DESKTOP_RUNTIME",[UQ]:"ARA_DESKTOP_RUNTIME_CHANNEL",[JQ]:"ARA_DESKTOP_RUNTIME_INSTANCE_ID",[MQ]:"ARA_DESKTOP_RUNTIME_WORKSPACE_SCOPE"};function m(Q){if(Q===void 0)return;if(!/^[a-f0-9]{64}$/.test(Q))throw Error("Invalid desktop workspace scope.");return Q}import{chmodSync as N,existsSync as z,mkdirSync as O,readFileSync as C,realpathSync as xQ,renameSync as wQ,unlinkSync as R,writeFileSync as f}from"fs";import{createPrivateKey as KQ,createPublicKey as VQ,generateKeyPairSync as AQ,randomUUID as NQ,sign as OQ}from"crypto";import{createRequire as RQ}from"module";import{homedir as fQ,platform as y}from"os";import{dirname as kQ,join as J}from"path";var L=1,BQ=16384,M=65536,_Q=128,TQ=128,u=65536;class q extends Error{code;nativeStatus;constructor(Q,Z){super(`Reason Device proof boundary failed (${Q}).${Z===void 0?"":` Native status: ${Z}.`}`);this.code=Q;this.nativeStatus=Z;this.name="LocalCredentialBoundaryError"}}function p(Q){if(Q.code==="proof_key_read_failed"&&Q.nativeStatus===-25300)return"proof_key_missing";switch(Q.nativeStatus){case-25308:return"keychain_interaction_required";case-25293:return"keychain_access_denied";case-25291:return"keychain_unavailable";default:return Q.code}}var k=null;function c(){if(!k)try{k=RQ(import.meta.url)("bun:ffi")}catch{throw new q("native_boundary_unavailable")}return k}function FQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost"&&Z.hostname!=="[::1]"&&Z.hostname!=="::1")return null;return Z.origin}catch{return null}}function PQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))throw new q("invalid_credential_record");let Z=Q,$=FQ(Z.apiOrigin);if(Z.version!==L||!$||typeof Z.orgId!=="string"||Z.orgId.length<1||Z.orgId.length>160||typeof Z.deviceId!=="string"||Z.deviceId.length<1||Z.deviceId.length>160||typeof Z.credential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.credential)||Z.credential.length>4096)throw new q("invalid_credential_record");return{version:L,apiOrigin:$,orgId:Z.orgId,deviceId:Z.deviceId,credential:Z.credential}}function DQ(Q=process.execPath){let Z=Q;try{Z=xQ(Q)}catch{}return v(kQ(Z))}function j(Q){return c().ptr(Q)}function bQ(Q){if(!z(Q))throw new q("native_boundary_unavailable");let{dlopen:Z,FFIType:$}=c();try{return Z(Q,{ara_device_configure_scope:{args:[$.ptr,$.u64],returns:$.i32},ara_device_key_load_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_create_fresh_public:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_sign:{args:[$.ptr,$.u64,$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_key_is_non_extractable:{args:[$.ptr],returns:$.i32},ara_device_key_delete:{args:[$.ptr],returns:$.i32},ara_device_binding_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_binding_create:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_update:{args:[$.ptr,$.u64],returns:$.i32},ara_device_binding_delete:{args:[$.ptr],returns:$.i32},ara_device_keychain_read:{args:[$.ptr,$.u64,$.ptr],returns:$.i32},ara_device_keychain_delete:{args:[$.ptr],returns:$.i32}})}catch(W){if(W instanceof q)throw W;throw new q("native_boundary_unavailable")}}function E(Q){return Buffer.from(Q).toString("base64url")}function x(Q){if(typeof Q!=="string"||!/^[A-Za-z0-9_-]{87}$/.test(Q))return!1;try{let Z=Buffer.from(Q,"base64url");return Z.byteLength===65&&Z[0]===4}catch{return!1}}function l(Q){if(Q.byteLength<8||Q.byteLength>72||Q[0]!==48)return!1;let Z=Q[1];return Z!==void 0&&Z<128&&Z+2===Q.byteLength}class d{libraryPath;runtimePlatform;workspaceScope;library=null;constructor(Q=DQ(),Z=y(),$){this.libraryPath=Q;this.runtimePlatform=Z;this.workspaceScope=$;m($)}symbols(){if(this.runtimePlatform!=="darwin")throw new q("unsupported_platform");this.library??=bQ(this.libraryPath);let Q=new TextEncoder().encode(this.workspaceScope??""),Z=this.library.symbols.ara_device_configure_scope(j(Q.length?Q:new Uint8Array(1)),BigInt(Q.length));if(Z!==0)throw new q("native_boundary_unavailable",Z);return this.library.symbols}publicKey(Q){let Z=new Uint8Array(_Q),$=new BigUint64Array(1),W=Q==="load"?this.symbols().ara_device_key_load_public(j(Z),BigInt(Z.byteLength),j($)):this.symbols().ara_device_key_create_fresh_public(j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q(Q==="load"?"proof_key_read_failed":"proof_key_generation_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X!==65)throw new q("invalid_public_key");let Y=E(Z.subarray(0,X));if(!x(Y))throw new q("invalid_public_key");return Y}loadPublicKey(){return this.publicKey("load")}createFreshPublicKey(){return this.publicKey("create_fresh")}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=new Uint8Array(TQ),$=new BigUint64Array(1),W=this.symbols().ara_device_key_sign(j(Q),BigInt(Q.byteLength),j(Z),BigInt(Z.byteLength),j($));if(W!==0)throw new q("proof_sign_failed",W);let X=Number($[0]);if(!Number.isSafeInteger(X)||X<1||X>Z.byteLength)throw new q("invalid_signature");let Y=Z.subarray(0,X);if(!l(Y))throw new q("invalid_signature");return E(Y)}privateKeyIsNonExtractable(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_is_non_extractable(j(Q));if(Z!==0||Q[0]!==1)throw new q("proof_key_read_failed",Z);return!0}deleteKey(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_key_delete(j(Q));if(Z!==0)throw new q("proof_key_delete_failed",Z);return Q[0]===1}loadBinding(){let Q=new Uint8Array(M),Z=new BigUint64Array(1),$=this.symbols().ara_device_binding_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("binding_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_binding");return Q.slice(0,W)}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_create(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_create_failed",Z)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");let Z=this.symbols().ara_device_binding_update(j(Q),BigInt(Q.byteLength));if(Z!==0)throw new q("binding_update_failed",Z)}deleteBinding(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_binding_delete(j(Q));if(Z!==0)throw new q("binding_delete_failed",Z);return Q[0]===1}loadLegacyCredential(){let Q=new Uint8Array(BQ),Z=new BigUint64Array(1),$=this.symbols().ara_device_keychain_read(j(Q),BigInt(Q.byteLength),j(Z));if($===1)return null;if($!==0)throw new q("legacy_credential_read_failed",$);let W=Number(Z[0]);if(!Number.isSafeInteger(W)||W<1||W>Q.byteLength)throw new q("invalid_credential_record");try{let X=new TextDecoder("utf-8",{fatal:!0}).decode(Q.subarray(0,W));return PQ(JSON.parse(X))}catch(X){if(X instanceof q)throw X;throw new q("invalid_credential_record")}}deleteLegacyCredential(){let Q=new Uint8Array(1),Z=this.symbols().ara_device_keychain_delete(j(Q));if(Z!==0)throw new q("legacy_credential_delete_failed",Z);return Q[0]===1}}function I(Q){let Z=Q.export({format:"jwk"});if(Z.crv!=="P-256"||typeof Z.x!=="string"||typeof Z.y!=="string")throw new q("invalid_public_key");let $=Buffer.from(Z.x,"base64url"),W=Buffer.from(Z.y,"base64url");if($.byteLength!==32||W.byteLength!==32)throw new q("invalid_public_key");let X=Buffer.concat([Buffer.of(4),$,W]).toString("base64url");if(!x(X))throw new q("invalid_public_key");return X}function SQ(){let Q=process.env.XDG_CONFIG_HOME?.trim()||J(fQ(),".config");h(Q);let Z=J(Q,"ara");return g(Z)?Z:J(Q,"reason")}class i{directory;constructor(Q=SQ()){this.directory=Q}keyPath(){return J(this.directory,"local-device.key")}bindingPath(){return J(this.directory,"local-device.binding")}loadPrivateKeyObject(){let Q=this.keyPath();if(!z(Q))throw new q("proof_key_read_failed");try{let Z=C(Q,"utf8");return KQ({key:Z,format:"pem"})}catch{throw new q("proof_key_read_failed")}}loadPublicKey(){let Q=this.loadPrivateKeyObject(),Z=VQ(Q);return I(Z)}createFreshPublicKey(){O(this.directory,{recursive:!0,mode:448});let{privateKey:Q,publicKey:Z}=AQ("ec",{namedCurve:"P-256"}),$=Q.export({type:"pkcs8",format:"pem"}),W=this.keyPath();return f(W,$,{mode:384}),N(W,384),I(Z)}sign(Q){if(Q.byteLength<1||Q.byteLength>u)throw new q("proof_sign_failed");let Z=this.loadPrivateKeyObject(),$;try{$=OQ("sha256",Q,Z)}catch{throw new q("proof_sign_failed")}if(!l($))throw new q("invalid_signature");return $.toString("base64url")}privateKeyIsNonExtractable(){return!1}deleteKey(){let Q=this.keyPath();if(!z(Q))return!1;return R(Q),!0}loadBinding(){let Q=this.bindingPath();if(!z(Q))return null;try{return new Uint8Array(C(Q))}catch{return null}}createBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(z(Z))throw new q("binding_create_failed");f(Z,Q,{mode:384}),N(Z,384)}updateBinding(Q){if(Q.byteLength<1||Q.byteLength>M)throw new q("invalid_binding");O(this.directory,{recursive:!0,mode:448});let Z=this.bindingPath();if(!z(Z))throw new q("binding_update_failed");let $=`${Z}.${NQ()}`;try{f($,Q,{mode:384,flag:"wx"}),N($,384),wQ($,Z)}finally{if(z($))R($)}}deleteBinding(){let Q=this.bindingPath();if(!z(Q))return!1;return R(Q),!0}loadLegacyCredential(){return null}deleteLegacyCredential(){return!1}}function B(){return y()==="darwin"?new d:new i}var w=U.string().min(1).max(160).regex(/^[A-Za-z0-9._:-]+$/),s=U.object({id:w,kind:U.literal("permission_denied"),operation:U.enum(["bash","read","write","edit"]),provenance:U.enum(["sandbox_policy","os_permission_unknown"]),occurredAt:U.string().datetime(),expiresAt:U.string().datetime(),sessionId:w,deviceId:w,organizationId:w}).strict();var P=4;var K="macos-keychain-p256-v1",ZQ=1,dQ=`ARA-DEVICE-BINDING-V1
|
|
3
|
+
`;function iQ(Q){return Q===void 0||typeof Q==="number"&&Number.isInteger(Q)&&Q>=1&&Q<=4}function $Q(Q,Z=Date.now()){let $=s.safeParse(Q);if(!$.success)return!1;let W=$.data,X=typeof W.occurredAt==="string"?Date.parse(W.occurredAt):NaN,Y=typeof W.expiresAt==="string"?Date.parse(W.expiresAt):NaN;return W.kind==="permission_denied"&&["bash","read","write","edit"].includes(W.operation)&&["sandbox_policy","os_permission_unknown"].includes(W.provenance)&&Number.isFinite(X)&&X<=Z&&Y>Z&&Y>X&&Y-X<=600000}function LZ(Q,Z,$=Date.now()){if(!Q||!Z||Q.state!=="connected"||Q.deviceId!==Z.deviceId)return null;let W=Date.parse(Q.lastHeartbeatAt??""),X=Q.permissionRecovery;if(!($-W>=0&&$-W<30000)||!$Q(X,$)||X.deviceId!==Z.deviceId||X.organizationId!==Z.orgId)return null;try{process.kill(Q.pid,0)}catch{return null}return X}function WQ(Q={},Z=V()){let $=r({env:{...process.env,...Q}}),W=Q.XDG_CONFIG_HOME?.trim()||A(Z,".config");return a(W,...$==="staging"?["staging"]:[])}function D(Q={},Z=V()){return A(WQ(Q,Z),"local-device.json")}function qQ(Q={},Z=V()){return A(WQ(Q,Z),"local-daemon.json")}function b(Q,Z){IQ(F(Q),{recursive:!0,mode:448}),_(F(Q),448);let $=`${Q}.${process.pid}.${t()}.tmp`;try{pQ($,`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,{mode:384,flag:"wx"}),_($,384),vQ($,Q),_(Q,384)}finally{if(e($))uQ($)}return Q}function S(Q){if(!e(Q))return null;try{return JSON.parse(gQ(Q,"utf8"))}catch{return null}}function T(Q,Z,$){try{Q.onCredentialLifecycle?.({event:Z,...$?{reasonCode:$}:{}})}catch{}}function sQ(Q){if(!Array.isArray(Q))return null;let Z=[];for(let $ of Q){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||typeof W.label!=="string"||typeof W.path!=="string"||typeof W.pathFingerprint!=="string"||!W.permissions||typeof W.permissions.read!=="boolean"||typeof W.permissions.write!=="boolean"||typeof W.permissions.execute!=="boolean"||typeof W.permissions.discover_environment!=="boolean"||typeof W.permissions.expose_mcp!=="boolean")return null;Z.push({id:W.id,label:W.label,path:W.path,pathFingerprint:W.pathFingerprint,permissions:W.permissions})}return Z}function XQ(Q,Z,$=[]){let W=Object.keys(Q);return Z.every((X)=>Object.hasOwn(Q,X))&&W.every((X)=>Z.includes(X)||$.includes(X))}function nQ(Q){if(typeof Q!=="string")return null;try{let Z=new URL(Q);if(Z.protocol!=="https:"&&Z.hostname!=="127.0.0.1"&&Z.hostname!=="localhost")return null;return Z.origin}catch{return null}}function YQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q,$=sQ(Z.roots),W=nQ(Z.apiOrigin);if(!W||typeof Z.orgId!=="string"||typeof Z.deviceId!=="string"||typeof Z.displayName!=="string"||typeof Z.registeredAt!=="string"||!iQ(Z.handsSlots)||Z.worker!==void 0&&(!Z.worker||!/^[a-f0-9]{64}$/.test(Z.worker.configDigest)||!["persistent","ephemeral"].includes(Z.worker.lifetime)||!Number.isFinite(Date.parse(Z.worker.expiresAt)))||!$)return null;return{apiOrigin:W,orgId:Z.orgId,deviceId:Z.deviceId,displayName:Z.displayName,registeredAt:Z.registeredAt,...Z.handsSlots!==void 0?{handsSlots:Z.handsSlots}:{},...Z.worker!==void 0?{worker:Z.worker}:{},roots:$}}function rQ(Q){return{...Q,credentialStorage:K}}function oQ(Q){return{version:P,apiOrigin:Q.apiOrigin,orgId:Q.orgId,deviceId:Q.deviceId,devicePublicKey:Q.devicePublicKey,displayName:Q.displayName,registeredAt:Q.registeredAt,...Q.handsSlots!==void 0?{handsSlots:Q.handsSlots}:{},...Q.worker!==void 0?{worker:Q.worker}:{},roots:Q.roots.map((Z)=>({id:Z.id,label:Z.label,path:Z.path,pathFingerprint:Z.pathFingerprint,permissions:{read:Z.permissions.read,write:Z.permissions.write,execute:Z.permissions.execute,discover_environment:Z.permissions.discover_environment,expose_mcp:Z.permissions.expose_mcp}})),credentialStorage:K}}function jQ(Q){if(!Q||typeof Q!=="object"||Array.isArray(Q))return null;let Z=Q;if(!XQ(Z,["version","apiOrigin","orgId","deviceId","devicePublicKey","displayName","registeredAt","roots","credentialStorage"],["handsSlots","worker"]))return null;let $=YQ(Z);if(!$||Z.version!==P||Z.credentialStorage!==K||!x(Z.devicePublicKey))return null;return{version:P,...$,devicePublicKey:Z.devicePublicKey,credentialStorage:K}}function GQ(Q){return new TextEncoder().encode(`${dQ}${JSON.stringify(oQ(Q))}`)}function aQ(Q){let Z=Buffer.from(Q,"base64url");return CQ({format:"jwk",key:{kty:"EC",crv:"P-256",x:Z.subarray(1,33).toString("base64url"),y:Z.subarray(33,65).toString("base64url")}})}function tQ(Q,Z){let $={version:ZQ,state:Q,signature:Z.sign(GQ(Q))};return new TextEncoder().encode(JSON.stringify($))}function HQ(Q){let Z;try{Z=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(Q))}catch{throw new q("invalid_binding")}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw new q("invalid_binding");let $=Z;if(!XQ($,["version","state","signature"])||$.version!==ZQ||typeof $.signature!=="string"||!/^[A-Za-z0-9_-]{10,128}$/.test($.signature))throw new q("invalid_binding");let W=jQ($.state);if(!W)throw new q("invalid_binding");let X=!1;try{X=EQ("sha256",GQ(W),aQ(W.devicePublicKey),Buffer.from($.signature,"base64url"))}catch{X=!1}if(!X)throw new q("invalid_binding");return W}function eQ(Q){let{credentialStorage:Z,...$}=Q;return $}function QZ(Q){return Q instanceof q?p(Q):"credential_boundary_failed"}function EZ(Q=D(),Z={}){let $=S(Q),W=Z.proofStore??Z.credentialStore??B(),X=W.loadBinding();if(!X){if($&&typeof $==="object"&&!Array.isArray($)&&ZZ($))return null;if($!==null)throw new q("invalid_binding");return null}let Y=HQ(X),G=W.loadPublicKey();if(W.privateKeyIsNonExtractable(),G!==Y.devicePublicKey)throw new q("invalid_public_key");let H=jQ($);if(Z.repair!==!1&&(!H||JSON.stringify(H)!==JSON.stringify(Y)))b(Q,Y);return eQ(Y)}function ZZ(Q){let Z=Q,$=YQ(Q);if(!$)return null;if(Z.version===2){if(typeof Z.deviceCredential!=="string"||!/^(?:reason|ara)_dev_/.test(Z.deviceCredential)||Z.deviceCredential.length>4096)return null;return{state:$,credentialSource:"plaintext-v2"}}if(Z.version!==3||Z.credentialStorage!=="macos-keychain-v1"||"deviceCredential"in Z)return null;return{state:$,credentialSource:"keychain-v3"}}function IZ(Q,Z=D(),$={}){let W=$.proofStore??$.credentialStore??B();T($,"credential.store_started");try{if(!x(Q.devicePublicKey)||W.loadPublicKey()!==Q.devicePublicKey)throw new q("invalid_public_key");W.privateKeyIsNonExtractable();let X=rQ(Q),Y=W.loadBinding();if(Y){let H=HQ(Y);if(H.devicePublicKey!==Q.devicePublicKey||H.orgId!==Q.orgId||H.deviceId!==Q.deviceId||H.apiOrigin!==Q.apiOrigin&&!o(H.apiOrigin,Q.apiOrigin))throw new q("invalid_binding")}let G=tQ(X,W);if(Y)W.updateBinding(G);else W.createBinding(G);return b(Z,X),T($,"credential.store_completed"),Z}catch(X){throw T($,"credential.store_failed",QZ(X)),X}}function gZ(Q=qQ()){let Z=S(Q);if(!Z||typeof Z!=="object")return null;let $=Z;if($.version!==1||typeof $.pid!=="number"||!Number.isInteger($.pid)||!["starting","connected","stopped","error"].includes($.state??"")||typeof $.startedAt!=="string"||$.lastHeartbeatAt!==void 0&&typeof $.lastHeartbeatAt!=="string"||$.lastUsedAt!==void 0&&typeof $.lastUsedAt!=="string"||$.organizationId!==void 0&&typeof $.organizationId!=="string"||$.organizationName!==void 0&&typeof $.organizationName!=="string"||$.organizationSlug!==void 0&&typeof $.organizationSlug!=="string"||$.error!==void 0&&typeof $.error!=="string"||$.reconnectingSince!==void 0&&typeof $.reconnectingSince!=="string"||$.workspace!==void 0&&typeof $.workspace!=="string")return null;if($.permissionRecovery!==void 0&&!$Q($.permissionRecovery))delete $.permissionRecovery;return $}function hZ(Q,Z=qQ()){return b(Z,Q)}var n=1;function $Z(Q=D()){return A(F(Q),"local-device.proxy.json")}function vZ(Q=$Z()){let Z=S(Q);if(!Z||typeof Z!=="object"||Array.isArray(Z))return null;let $=Z;if($.version!==n||typeof $.url!=="string"||$.url.length===0||$.caFile!==void 0&&(typeof $.caFile!=="string"||!QQ($.caFile)))return null;return{version:n,url:$.url,...$.caFile?{caFile:$.caFile}:{}}}function yZ(Q,Z={read:!0,write:!1,execute:!1,discover_environment:!1,expose_mcp:!1},$=LQ(32)){let W=new Set,X=[];for(let Y of Q){let G=hQ(QQ(Y)?Y:lQ(Y));if(!yQ(G).isDirectory())throw Error(`Local execution root is not a directory: ${Y}`);if(W.has(G))continue;W.add(G),X.push({id:t(),label:cQ(G)||G,path:G,pathFingerprint:mQ("sha256",$).update(G).digest("hex"),permissions:{...Z}})}if(X.length===0)throw Error("At least one explicit local execution root is required.");return X}
|
|
5
|
+
export{q as hh,DQ as ih,x as jh,l as kh,d as lh,i as mh,$Q as nh,LZ as oh,D as ph,qQ as qh,EZ as rh,IZ as sh,gZ as th,hZ as uh,n as vh,vZ as wh,yZ as xh};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Kc as GB,Lc as HB,Mc as _,Ub as KB,Zb as CB,ec as LB}from"./vm-hands-entry-lite-fpp2bs9y.js";import{$c as g,Tc as UB,Uc as VB}from"./vm-hands-entry-lite-vsa7t6m9.js";import{ad as u,ed as f,gd as r,hd as a,md as n}from"./vm-hands-entry-lite-j2ng164q.js";import{yd as XB,zd as FB}from"./vm-hands-entry-lite-f5xb489y.js";import{ph as $B}from"./vm-hands-entry-lite-ntx8fdyq.js";import{$j as QB,Yj as BB,_j as JB}from"./vm-hands-entry-lite-6nwbqg37.js";import{kk as s}from"./vm-hands-entry-lite-feybcq63.js";import{Vk as J}from"./vm-hands-entry-lite-q8wkrzer.js";import{el as YB,ml as ZB}from"./vm-hands-entry-lite-gxper06w.js";import{ql as T}from"./vm-hands-entry-lite-magmzx9c.js";import{randomUUID as j}from"crypto";import{spawn as hB}from"child_process";import{existsSync as h,lstatSync as MB,mkdirSync as mB,readFileSync as yB,realpathSync as R,rmSync as bB,writeFileSync as dB}from"fs";import{dirname as vB,join as O,relative as cB,sep as lB}from"path";var qB=["process.run.v1","process.full.v1"],kB=600000,xB=1800000,DB=20000,v="process.cancel.v1",c=J.object({action:J.literal("start"),request_id:J.string().uuid(),command:J.string().min(1).max(16000).refine((B)=>!B.includes("\x00")),cwd:J.string().min(1).max(4096).refine((B)=>!B.includes("\x00")&&!B.startsWith("/")&&!B.split(/[\\/]/).includes("..")).describe("Path relative to the granted device root; omit to use that root. Must not start with /, contain a .. path segment, or contain a NUL character.").optional(),mode:J.enum(["host","confined"]).default("host"),timeout_ms:J.number().int().min(1000).max(xB).default(kB).describe("Absolute process budget including queue and startup time. Defaults to ten minutes; longer explicit requests require the selected root's advertised max_timeout_ms. Retrying never renews the deadline.")}).strict(),I={device_id:J.string().uuid(),root_id:J.string().uuid()},AB=J.discriminatedUnion("action",[c.extend(I),J.object({...I,action:J.literal("inspect"),process_id:J.string().uuid(),after:J.number().int().min(0).default(0),wait_ms:J.number().int().min(0).max(DB).default(0).describe("Wait for new output or a state change, bounded by this call's wait budget. Expiring this wait does not cancel the process or extend its deadline.")}).strict(),J.object({...I,action:J.literal("cancel"),process_id:J.string().uuid()}).strict()]),uB=J.toJSONSchema(AB,{io:"input"}),rB=c.extend({process_brain_fence:J.string().uuid(),process_expires_at:J.iso.datetime()}).strict(),D=J.object({version:J.literal(1),process_id:J.string().uuid(),state:J.enum(["starting","running","exited","cancelled","expired","uncertain"]),exit_code:J.number().int().nullable(),first_cursor:J.number().int().min(0),next_cursor:J.number().int().min(0),truncated:J.boolean(),observed_at:J.iso.datetime(),output:J.array(J.object({cursor:J.number().int().min(1),stream:J.enum(["stdout","stderr"]),text:J.string().max(32768)}).strict()).max(128)}).strict().refine((B)=>{if(Buffer.byteLength(JSON.stringify(B))>1e5||B.next_cursor<B.first_cursor-1)return!1;if((B.state==="starting"||B.state==="running"||B.state==="uncertain")&&B.exit_code!==null)return!1;if(B.state==="exited"&&(B.exit_code===null||B.exit_code<0||B.exit_code>255))return!1;if(B.state==="cancelled"&&B.exit_code!==130||B.state==="expired"&&B.exit_code!==124)return!1;let Z=B.first_cursor-1;for(let Y of B.output){if(Y.cursor<=Z||Y.cursor>B.next_cursor)return!1;Z=Y.cursor}return!0});function l(B){return qB.includes(B)}var aB=J.object({operation_constraints:J.record(J.string(),J.unknown())}),nB=J.object({ready:J.literal(!0),version:J.literal(1),execution_mode:J.enum(["host","confined"]),max_timeout_ms:J.number().int().min(1000).optional()});var _B=J.object({version:J.literal(1),process_id:J.string().uuid(),state:J.enum(["queued","cancelled_before_start","not_started"]),exit_code:J.null(),output:J.array(J.never()).length(0),first_cursor:J.literal(0),next_cursor:J.literal(0),truncated:J.literal(!1),cancellation_requested:J.literal(!1),reason_code:J.enum(["cancelled_before_start","process_journal_capacity","path_not_found","process_timeout_unsupported"]).optional(),expires_at:J.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it.")}).strict(),RB=J.object({...D.shape,state:J.enum(["queued","starting","running","exited","cancelled","expired","uncertain","cancelled_before_start","not_started"]),observed_at:J.iso.datetime().optional(),expires_at:J.iso.datetime().optional().describe("Accepted absolute process deadline. Reading, waiting and retrying do not extend it."),cancellation_requested:J.boolean(),reason_code:J.string().nullable().optional(),execution_authority:J.literal("lost").optional().describe("Historical receipt only; the current Brain cannot control this older-generation process."),recovery:J.object({cause:J.literal("brain_generation_changed"),terminal_confirmed:J.boolean(),next_step:J.enum(["inspect_until_terminal","reconcile_effects_before_new_intent"])}).strict().optional().describe("Historical process recovery only. An unconfirmed outcome forbids replay. A confirmed terminal observation proves the old process stopped, not that its command had no effects. Reconcile the result; only restart still-needed, safely repeatable work with a new request_id and current authority. Respect user cancellation."),last_observed_state:D.shape.state.or(J.literal("cancelled_before_start")).nullable().optional().describe("Last saved observation before authority was lost; a running observation does not establish current child liveness.")}).strict(),iB=J.toJSONSchema(RB),tB=J.union([D,_B.refine((B)=>B.state==="cancelled_before_start")]),S=J.object({version:J.literal(1),process_id:J.string().uuid(),state:J.enum(["exited","cancelled","expired"]),exit_code:J.number().int().min(0).max(255),observed_at:J.iso.datetime()}).strict().refine((B)=>(B.state!=="cancelled"||B.exit_code===130)&&(B.state!=="expired"||B.exit_code===124)),PB=J.object({process_terminal_observation:S}).strict();function eB(B,Q){let Z=PB.safeParse(B);return Z.success&&Z.data.process_terminal_observation.process_id===Q?Z.data:null}var YJ="preview.serve.v1",ZJ=43200000;var $J=3,p="preview.open.v1",o=1,EB="gid_proxy_v1",XJ="egress",IB=/^(?:\*\.)?[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?(?::[1-9][0-9]{0,4})?$/,SB=J.object({version:J.literal(EB),allowed_domains:J.array(J.string().max(260).regex(IB)).max(1024)}).strict(),fB=J.custom((B)=>s(B)!==null,"invalid workspace"),wB=J.object({version:J.literal(1),request_id:J.uuid(),session_id:J.uuid(),command:J.string().min(1).max(16000).refine((B)=>!B.includes("\x00")),port:J.number().int().min(1024).max(65535),workspace:fB,egress:SB.optional()}).strict(),FJ=wB.extend({expires_at:J.iso.datetime()}).strict();var jB=4,gB=5000;function w(B,Q,Z){let Y=null;try{Y=f(B)}catch{}r({deviceRelayUrl:Y?.deviceRelayUrl??"",binding:Y?.binding??null,jobId:Q,port:Y?.binding.port??0,reason:Y?Z:"binding_invalid"})}function i(B){let Q=new Map;return{open(Z){let Y=(C)=>w(Z,B.claim.operation_id,C),G;try{G=f(Z)}catch{return Y("binding_invalid")}let{binding:F,deviceRelayUrl:A}=G,U=B.claim.owner;if(!U||F.organizationId!==U.organization_id||F.userId!==U.user_id||F.deviceId!==U.device_id||F.rootId!==B.claim.root_id||F.jobId!==B.claim.operation_id||F.fenceId!==B.claim.operation_id||F.generation!==o||F.expiresAtMs>Math.min(Date.now()+u.lifetimeMs+gB,B.expiresAtMs))return Y("binding_mismatch");if(F.expiresAtMs<=Date.now())return Y("binding_expired");if(Q.get(F.port)?.abort(),Q.delete(F.port),Q.size>=jB)return Y("preview_capacity");let z=new AbortController;Q.set(F.port,z);let L=n({binding:F,deniedPorts:B.deniedPorts,readCurrentJob:async()=>{if(z.signal.aborted)return null;let C=await B.inspect();return C?{binding:F,executorLaunchId:B.executorLaunchId,job:C}:null}});a({binding:F,deviceRelayUrl:A,port:L,signal:z.signal}).then((C)=>C.closed,(C)=>{let V=C instanceof Error?C.message:"preview_failed";if(V!=="preview_not_authorized")process.stderr.write(`${JSON.stringify({event:"worker_preview.open_failed",job_id:F.jobId,port:F.port,reason_code:V})}
|
|
3
|
+
`)}).finally(()=>{if(Q.get(F.port)===z)Q.delete(F.port)})},dispose(){for(let Z of Q.values())Z.abort();Q.clear()}}}class m extends T{observation;constructor(B){super("process_authority_lost","Process authority was lost; the owned process group has stopped.");this.observation=B}}var NB=256,P=new Map,OB="preview.serve.v1",q=new Map;function TB(B){let Q=q.get(B.operation_id);if(Q){if(Q.claim!==B)throw M("process_authority_lost");return Q}if(q.size>=NB)throw M("process_journal_capacity");let Z={claim:B,executing:!1,cancelRequested:!1,phase:"pending"};return q.set(B.operation_id,Z),Z}function t(B){return{version:1,process_id:B,state:"cancelled_before_start",exit_code:null,output:[],first_cursor:0,next_cursor:0,truncated:!1,cancellation_requested:!1,reason_code:"cancelled_before_start"}}var e=(B)=>new Promise((Q)=>setTimeout(Q,B)),M=(B="process_outcome_uncertain")=>new T(B,"The managed process outcome could not be confirmed; inspect its saved receipt before starting another intent.");function sB(B=BB(),Q=pB()){let Z=vB($B({},B)),Y=cB(JB(B),Z),[G,...F]=Y.split(lB);return{directory:O(Q,Y,"processes"),previous:[O(Z,"processes"),...G==="reason"?[O(Q,"ara",...F,"processes")]:[]]}}function pB(){if(process.platform!=="darwin")throw new T("process_unavailable","Managed Mac process execution is unavailable.");let B=QB();if(!B)throw new T("process_unavailable","The private per-user process directory is unavailable.");return B}async function IJ(B){if(!B.claim.owner||B.signal.aborted||B.expiresAtMs<=Date.now())throw M("process_authority_lost");let Q=TB(B.claim);if(Q.executing)throw M("process_busy");if(Q.executing=!0,Q.cancelRequested)return Q.phase="settling",t(B.claim.operation_id);Q.phase="starting";let Z=B.journals??sB();mB(Z.directory,{recursive:!0,mode:448});let Y=CB({runtimeDirectory:R(Z.directory),previousRuntimeDirectories:(Z.previous??[]).filter(($)=>h($)).map(($)=>R($)),root:B.root,runId:JSON.stringify([B.claim.owner,B.claim.run_id,B.claim.root_id,B.claim.operation_id]),maxScopes:NB});try{for(let $ of[B.root,B.cwd])if(!KB(R($),Y.journalDirectory))throw new T("process_journal_inside_workspace","The selected root contains the private process journal. Select an existing narrower granted workspace root outside the journal; no command was dispatched.")}catch($){throw Y.disposeSocket(),$}let G=MB(Y.journalDirectory),F=B.claim.capability===OB,A=()=>P.set(B.claim.operation_id,{path:Y.journalDirectory,ino:G.ino,dev:G.dev,anyCompletion:F}),U=Y.launchDirectory,z=O(U,"config.json"),L={url:"",transport:"local_job_ipc",directShell:{mode:B.mode,executable:B.shell,jobId:B.claim.operation_id},workerVersion:UB,protocolVersion:2,workerArtifactSha256:g,workerEntrypoint:VB,targetGeneration:1,fenceId:j(),...process.platform==="win32"?{bashExecutable:YB()}:{},workRoot:B.root,workspaceAliasPath:B.root,repoPath:B.cwd,jobEnvPath:O(U,"unused.env"),replSocketPath:O(U,"unused.sock"),readyPath:O(U,"ready.json"),directTerminalReceiptPath:O(U,"terminal.json"),launchId:j(),expiresAtMs:B.expiresAtMs+5000,bashTimeoutMs:60000,replTimeoutMs:1000,allowedTools:["bash"],managedJobs:{journalDirectory:Y.journalDirectory,scopeId:Y.scopeId},jobControlSocketPath:Y.socketPath,...B.prefix?{bashCommandPrefix:B.prefix}:{},...B.jobsUser?{jobsUser:B.jobsUser}:{}},C;try{dB(z,JSON.stringify(L),{mode:384});let $=GB({configPath:z,root:B.cwd,grantedRoot:B.root,workRoot:B.root,temporaryDirectory:U});C=B.spawnWorker?.(z,L)??hB($.command,$.args,{...$.options,env:B.environment,stdio:[HB,"ignore","ignore"]})}catch($){throw Y.disposeSocket(),$}let V=!1,E=new Promise(($,K)=>{C.once("exit",(X)=>{V=!0,$(X)}),C.once("error",(X)=>{V=!0,K(X)})});E.catch(()=>{});let zB={root:B.root,runId:B.claim.run_id,scopeId:Y.scopeId,socketPath:Y.socketPath,generation:1,fenceId:L.fenceId,executorLaunchId:L.launchId,expiresAtMs:L.expiresAtMs},W=async($)=>{let K=await LB(zB,{type:"job",version:2,generation:1,id:j(),jobId:B.claim.operation_id,...$==="start"?{action:$,input:{script:B.command,leaseExpiresAtMs:B.expiresAtMs}}:$==="inspect"?{action:$,input:{after:0}}:$==="probe"?{action:"inspect",input:{after:Number.MAX_SAFE_INTEGER}}:{action:$,input:{}}},new AbortController().signal);if(!K.ok)throw M(K.error);return K.job},k=!1,x=!1,y,b=()=>{k=!0,_(C,"SIGTERM")};B.signal.addEventListener("abort",b,{once:!0});let N,d=0,WB=async($)=>{let K=[...$.output],X={version:1,process_id:B.claim.operation_id,state:$.state,exit_code:$.exitCode,first_cursor:$.firstCursor,next_cursor:$.nextCursor,truncated:$.truncated,output:K,observed_at:new Date().toISOString()};while(Buffer.byteLength(JSON.stringify(X))>90000&&K.length)K.shift(),X.truncated=!0,X.first_cursor=K[0]?.cursor??X.next_cursor+1;N=D.parse(X),await B.emit(N),d=Date.now()};try{let $=Math.min(Date.now()+1e4,B.expiresAtMs);while(!h(L.readyPath)){if(V)throw new T("process_start_failed","The managed process supervisor exited before accepting a command; no command was dispatched.");if(B.signal.aborted||Date.now()>=$)throw M("process_start_unconfirmed");await e(25)}let K=JSON.parse(yB(L.readyPath,"utf8"));if(K.launchId!==L.launchId||K.fenceId!==L.fenceId||K.workerArtifactSha256!==g)throw M();if(B.signal.throwIfAborted(),Q.cancelRequested)return t(B.claim.operation_id);let X;try{x=!0,X=await W("start")}catch(H){if(!(H instanceof T)||H.code!=="hands_job_result_unknown")throw H;X=await W("inspect")}if(Q.phase="running",Q.cancel=async()=>{await W("cancel")},F&&B.preview)Q.tunnels=i({claim:B.claim,executorLaunchId:L.launchId,expiresAtMs:B.expiresAtMs,deniedPorts:B.preview.deniedPorts,inspect:async()=>Q.phase==="running"&&!V?await W("probe"):null});if(Q.cancelRequested)await Q.cancel(),X=await W("inspect");for(;;){if(!["starting","running"].includes(X.state))Q.phase="settling",Q.cancel=void 0;if(!N||N.state!==X.state||N.next_cursor!==X.nextCursor&&Date.now()-d>=5000)await WB(X);if(!["starting","running"].includes(X.state))break;if(B.signal.aborted||V)throw M();await e(1000);try{X=await W("inspect"),y=void 0}catch(H){if(!(H instanceof T)||H.code!=="hands_job_result_unknown"||B.signal.aborted||V||Date.now()-(y??=Date.now())>120000)throw H}}if(!N||N.state==="uncertain")throw M();return N}finally{if(Q.phase="settling",Q.cancel=void 0,Q.tunnels?.dispose(),Q.tunnels=void 0,await Q.cancelInFlight?.catch(()=>{}),B.signal.removeEventListener("abort",b),!V&&!k)_(C,"SIGTERM");let $,K=await Promise.race([E.then((X)=>({code:X})),new Promise((X)=>{$=setTimeout(()=>X(null),6000)})]).finally(()=>{clearTimeout($)});if(!K){try{_(C,"SIGKILL")}catch{}try{await E}finally{if(V)Y.disposeSocket()}throw M("process_cleanup_unconfirmed")}try{if((k||B.signal.aborted)&&K.code===0&&x){XB(U);let X=JSON.parse(FB(L.directTerminalReceiptPath)),H=S.safeParse(X.observation);if(Object.keys(X).length===4&&X.launch_id===L.launchId&&X.fence_id===L.fenceId&&X.scope_id===Y.scopeId&&H.success&&H.data.process_id===B.claim.operation_id){if(F)A();throw new m(H.data)}}}catch(X){if(X instanceof m)throw X}finally{if(V)Y.disposeSocket()}if(K.code!==0&&!k&&x)throw M("process_cleanup_unconfirmed");if(!k&&K.code===0&&(N&&["exited","cancelled","expired"].includes(N.state)||!x&&Q.cancelRequested)||F&&K.code===0&&!x)A()}}async function SJ(B,Q){if(Q.kind===p&&B.capability===OB){let G=q.get(B.operation_id);if(G?.claim===B&&G.tunnels)G.tunnels.open(Q.payload);else w(Q.payload,B.operation_id,"server_not_running");return!0}if(Q.kind!==v||!l(B.capability)||!B.owner||Q.payload.process_id!==B.operation_id)return!1;let Z=q.get(B.operation_id);if(Z&&Z.claim!==B)return!1;let Y=TB(B);if(Y.cancelRequested=!0,Y.phase==="running"&&Y.cancel)Y.cancelInFlight??=Y.cancel(),await Y.cancelInFlight;return!0}function fJ(B,Q){q.delete(B);let Z=P.get(B);if(!Z||Q!=="succeeded"&&!Z.anyCompletion)return P.delete(B),!1;try{let Y=MB(Z.path);if(!Y.isDirectory()||Y.isSymbolicLink()||Y.ino!==Z.ino||Y.dev!==Z.dev||!ZB(Y)||R(Z.path)!==Z.path||h(O(Z.path,"owner.lock")))return!1;return bB(Z.path,{recursive:!0}),P.delete(B),!0}catch{return!1}}
|
|
4
|
+
export{l as wb,eB as xb,YJ as yb,ZJ as zb,$J as Ab,EB as Bb,XJ as Cb,IB as Db,FJ as Eb,m as Fb,NB as Gb,sB as Hb,IJ as Ib,SJ as Jb,fJ as Kb};
|