@reason-machines/cli-linux-x64 0.2.460 → 0.2.463
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 +2 -2
- package/bin/reason +1 -1
- package/bin/runtime/srt/sandbox-runtime.mjs +40 -40
- package/bin/runtime/srt/vendor/seccomp/x64/apply-seccomp +0 -0
- package/bin/vm-hands/api-7xy672j8.js +2 -0
- package/bin/vm-hands/api-credentials-bbmmmkwx.js +2 -0
- package/bin/vm-hands/connect-cli-2rvwbw01.js +2 -0
- package/bin/vm-hands/credentials-gr9jn270.js +2 -0
- package/bin/vm-hands/{custom-endpoint-device-v3rkzm7q.js → custom-endpoint-device-r2nn1xj9.js} +1 -1
- package/bin/vm-hands/desktop-account-3cc0bhw8.js +2 -0
- package/bin/vm-hands/{device-workspace-vaqjetag.js → device-workspace-s50q53sz.js} +1 -1
- package/bin/vm-hands/hands-worker-source-k8v5kmmw.js +2 -0
- package/bin/vm-hands/{index-ww1zq4h9.js → index-d5n50g8b.js} +1 -1
- package/bin/vm-hands/install-receipt-gvdzhm17.js +2 -0
- package/bin/vm-hands/local-automation-34vdgq8d.js +2 -0
- package/bin/vm-hands/local-capabilities-41n0pspr.js +2 -0
- package/bin/vm-hands/local-desktop-users-qskbh51j.js +2 -0
- package/bin/vm-hands/{local-display-mac-49yz00hp.js → local-display-mac-m77mftqy.js} +1 -1
- package/bin/vm-hands/local-display-session-g81fwns5.js +2 -0
- package/bin/vm-hands/local-display-video-1xd1fqch.js +2 -0
- package/bin/vm-hands/local-managed-process-30k1x92d.js +2 -0
- package/bin/vm-hands/local-pty-session-k6kab3tc.js +2 -0
- package/bin/vm-hands/managed-runtime-hk53v8j5.js +2 -0
- package/bin/vm-hands/{network-contract-g1jewvb5.js → network-contract-y2eybfhn.js} +1 -1
- package/bin/vm-hands/permissions-t3e7bp9x.js +2 -0
- package/bin/vm-hands/{reason-hands-protocol-cebk43jj.js → reason-hands-protocol-r3wtcjed.js} +1 -1
- package/bin/vm-hands/{serve-service-ddds922x.js → serve-service-hr1x43p8.js} +1 -1
- package/bin/vm-hands/{status-q3by8hq6.js → status-h3bk00m3.js} +2 -2
- package/bin/vm-hands/version-qja79041.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-1f25jgyr.js → vm-hands-entry-lite-03d1fhxv.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-75y8022r.js → vm-hands-entry-lite-0yj63trb.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-z599genq.js → vm-hands-entry-lite-1f0v3jb4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8fqrpycx.js → vm-hands-entry-lite-1k16ct2y.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-te16hx2y.js → vm-hands-entry-lite-1y629eqh.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-vsm90vke.js → vm-hands-entry-lite-3krzmhkk.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-3pxmmb7z.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-99y4caf9.js → vm-hands-entry-lite-44qha2rt.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-168m1q57.js → vm-hands-entry-lite-4x8j1xp9.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-43v0ccsr.js → vm-hands-entry-lite-52x189kf.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-eya4kgw8.js → vm-hands-entry-lite-5zdybh8s.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8x5znjnm.js → vm-hands-entry-lite-7ja63pfz.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-qh6hnhtr.js → vm-hands-entry-lite-8qvsnkvv.js} +4 -4
- package/bin/vm-hands/vm-hands-entry-lite-9fzydv1p.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-cmm2ybdr.js → vm-hands-entry-lite-9vv5knh4.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-r3s4j28z.js → vm-hands-entry-lite-abfb6nms.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-26w5ejds.js → vm-hands-entry-lite-b139fhbg.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-wsspeegr.js → vm-hands-entry-lite-b8yapqfn.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-bvb4nvxr.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-rseyh0ej.js → vm-hands-entry-lite-c7ka2d1c.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mdqdbhk1.js → vm-hands-entry-lite-cf1x5cbr.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-e7mr44v7.js → vm-hands-entry-lite-eay4tbg0.js} +15 -15
- package/bin/vm-hands/{vm-hands-entry-lite-6ccgnrgg.js → vm-hands-entry-lite-egax7vw4.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-kgknanhj.js → vm-hands-entry-lite-h6rhk6h1.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-76xb3wgd.js → vm-hands-entry-lite-hzh8fdxx.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-p2zjx5cn.js → vm-hands-entry-lite-jyvmw8b7.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-t7zr2tea.js → vm-hands-entry-lite-k83rkcys.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-2mm1b4qj.js → vm-hands-entry-lite-kz48x6p0.js} +8 -8
- package/bin/vm-hands/{vm-hands-entry-lite-8402gdx0.js → vm-hands-entry-lite-m753n72c.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-6zzn5qbb.js → vm-hands-entry-lite-me5w88km.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-r17x4n1w.js → vm-hands-entry-lite-n1k1njzh.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-9apjqd3s.js → vm-hands-entry-lite-np07qyeq.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-38qt915d.js → vm-hands-entry-lite-r3yp6cr9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-ffn3k8a5.js → vm-hands-entry-lite-rfz60hb3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-pj4vv7c3.js → vm-hands-entry-lite-rzhqftyg.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-rgwm9y7f.js → vm-hands-entry-lite-t0exw1jk.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-n8gng724.js → vm-hands-entry-lite-tn8v3yfj.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-zw5stc7m.js → vm-hands-entry-lite-txd50spx.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-mvsdn8xd.js → vm-hands-entry-lite-vdhgwmmp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-1ts6q468.js → vm-hands-entry-lite-wrvz9jxy.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-pry1an8k.js → vm-hands-entry-lite-x9wy77vd.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-t04rk1xy.js → vm-hands-executor-ksf4ragj.js} +3 -3
- package/bin/vm-hands/{vm-hands-op-runner-tatf8me7.js → vm-hands-op-runner-q5x9gpmt.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-zx8s6rs7.js → vm-hands-runtime-dg696564.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-6hzzjnk7.js +2 -0
- package/bin/vm-hands/worker-sandbox-1g7jheqm.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-7aqwa709.js +0 -2
- package/bin/vm-hands/api-credentials-fh34tvkh.js +0 -2
- package/bin/vm-hands/connect-cli-8vkhdyn7.js +0 -2
- package/bin/vm-hands/credentials-31d5svns.js +0 -2
- package/bin/vm-hands/desktop-account-1k06r449.js +0 -2
- package/bin/vm-hands/hands-worker-source-1y3ffkre.js +0 -2
- package/bin/vm-hands/install-receipt-g4xmdyrg.js +0 -2
- package/bin/vm-hands/local-automation-khtqsw27.js +0 -2
- package/bin/vm-hands/local-capabilities-0v1tmead.js +0 -2
- package/bin/vm-hands/local-desktop-users-xk05xr6n.js +0 -2
- package/bin/vm-hands/local-display-session-ae33d049.js +0 -2
- package/bin/vm-hands/local-display-video-b3hyaefy.js +0 -2
- package/bin/vm-hands/local-managed-process-pnd72aaw.js +0 -2
- package/bin/vm-hands/local-pty-session-hcpz5scq.js +0 -2
- package/bin/vm-hands/managed-runtime-e6ev22c7.js +0 -2
- package/bin/vm-hands/permissions-a7rcytp4.js +0 -2
- package/bin/vm-hands/version-e55vkeaw.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-9h4bfd4w.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-c4jj2s7a.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-rkvhw41t.js +0 -3
- package/bin/vm-hands/worker-preview-readiness-10ex5n3a.js +0 -2
- package/bin/vm-hands/worker-sandbox-wjyfgj98.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_e,ye,we}from"./vm-hands-entry-lite-
|
|
2
|
+
import{_e,ye,we}from"./vm-hands-entry-lite-h6rhk6h1.js";import{De,Ne,Le}from"./vm-hands-entry-lite-vdhgwmmp.js";import{spawn as A}from"child_process";import{randomUUID as s}from"crypto";import{basename as C}from"path";import{fileURLToPath as E}from"url";function S(){let p=C(process.execPath).startsWith("bun");return{command:process.execPath,args:[...p?["--no-env-file",E(new URL("./worker-candidate-entry.ts",import.meta.url))]:[],"worker","__preview-probe"]}}async function fs(p,a,m=S()){if(a.aborted||!["darwin","linux","win32"].includes(process.platform)||process.platform==="win32"&&!ye())return!1;let n=new AbortController,o=()=>n.abort();a.addEventListener("abort",o,{once:!0});let y=setTimeout(o,5000),t=A(m.command,m.args,{cwd:p,...Ne(),stdio:["pipe","pipe","ignore"],env:De()});Le(t);let l=!1,b=new Promise((e)=>t.once("close",()=>{l=!0,e()}));t.on("error",o);let f,w,k=new Promise((e)=>{f=e}),I=new Promise((e)=>{w=e}),v=new Promise((e)=>n.signal.addEventListener("abort",()=>e(null),{once:!0})),i="",g=0,P=!1;t.stdout.setEncoding("utf8"),t.stdout.on("data",(e)=>{if(g+=Buffer.byteLength(e),i+=e,g>512){o();return}while(i.includes(`
|
|
3
3
|
`)){let c=i.indexOf(`
|
|
4
4
|
`),d=i.slice(0,c);i=i.slice(c+1);try{if(!P){let r=JSON.parse(d);if(!r||Object.keys(r).length!==2||!Number.isInteger(r.port)||r.port<1024||r.port>65535||typeof r.token!=="string"||!/^[a-zA-Z0-9_-]{43}$/.test(r.token))throw Error("probe_receipt_invalid");P=!0,f({port:r.port,token:r.token})}else if(d==="ready")w(!0);else o()}catch{o()}}}),b.then(o);let h,u=!1;try{let e=await Promise.race([k,v]);if(!e||!t.pid||n.signal.aborted||a.aborted)return!1;let c=Date.now()+4500,d=s(),r={organizationId:s(),userId:s(),runId:s(),deviceId:s(),rootId:s(),attachmentRevision:0,grantRevision:1,jobId:"readiness",generation:1,fenceId:s(),port:e.port,expiresAtMs:c},L={binding:r,executorLaunchId:d,job:{jobId:r.jobId,state:"running",startedAtMs:Date.now(),finishedAtMs:null,leaseExpiresAtMs:c,exitCode:null,inputSequence:0,output:[],firstCursor:1,nextCursor:0,truncated:!1,process:{pid:t.pid,processGroupId:t.pid,executorLaunchId:d}}},x=we({binding:r,deniedPorts:new Set,readCurrentJob:async()=>!l&&!n.signal.aborted?L:null});h=await _e({binding:r,deviceRelayUrl:`ws://127.0.0.1:${e.port}/device/readiness/${e.token}`,port:x,signal:n.signal}),u=await Promise.race([I,v])===!0&&!n.signal.aborted&&!a.aborted}catch{u=!1}finally{if(clearTimeout(y),a.removeEventListener("abort",o),h?.close(),n.abort(),t.stdin.destroy(),!l)t.kill("SIGKILL");await b}return u&&l}
|
|
5
5
|
export{fs};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ie,De}from"./vm-hands-entry-lite-
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{Ie,De}from"./vm-hands-entry-lite-vdhgwmmp.js";import{request as Ce}from"http";import{pipeline as Ne}from"stream";import{constants as te,createBrotliCompress as $e,createGzip as Me}from"zlib";import{WebSocket as U}from"ws";import{randomBytes as Re,timingSafeEqual as Be}from"crypto";import{createServer as Le}from"net";var p={chunk:32768,upload:1048576,total:536870912,streams:16,queued:512,buffered:262144,relayBuffered:8388608,requestMs:30000,lifetimeMs:600000,authorizationMs:2000,window:8};function Z(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function L(e,t,n=Number.MAX_SAFE_INTEGER){return typeof e==="number"&&Number.isSafeInteger(e)&&e>=t&&e<=n}function pe(e){return typeof e==="string"&&/^[a-zA-Z0-9_-]{1,160}$/.test(e)}function fe(e,t){let n=Buffer.from(e,"latin1");return Buffer.concat([Buffer.from([n.length]),n,t])}function C(e){if(!Z(e)||Object.keys(e).length!==12||![e.organizationId,e.userId,e.runId,e.deviceId,e.rootId,e.jobId,e.fenceId].every(pe)||!L(e.attachmentRevision,0)||!L(e.grantRevision,1)||!L(e.generation,1)||!L(e.port,1024,65535)||!L(e.expiresAtMs,1))throw Error("preview_binding_invalid");return Object.freeze({...e})}function ze(e,t){return Object.keys(e).every((n)=>e[n]===t[n])}function H(e){if(e.length>4096||!e.startsWith("/")||e.startsWith("//")||/[\\\x00-\x20\x7f#]/.test(e))throw Error("preview_path_invalid");let t=decodeURIComponent(e);if(t.startsWith("//")||/[\\\x00-\x1f\x7f]/.test(t))throw Error("preview_path_invalid");return e}function ue(e){return Array.isArray(e)&&e.length<=64&&e.every((t)=>Array.isArray(t)&&t.length===2&&typeof t[0]==="string"&&/^[a-zA-Z0-9-]{1,80}$/.test(t[0])&&typeof t[1]==="string"&&t[1].length<=4096&&!/[\x00-\x1f\x7f]/.test(t[1]))}function z(e,t=p.chunk){if(e.length>Math.ceil(t/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))throw Error("preview_data_invalid");let n=Buffer.from(e,"base64");if(n.length>t)throw Error("preview_data_too_large");return n}function me(e){if(Array.isArray(e))return Buffer.concat(e);if(typeof e==="string")return Buffer.from(e,"utf8");if(e instanceof ArrayBuffer)return Buffer.from(e);return e}function ge(e){if(Buffer.byteLength(e)>p.upload*1.4+300000)throw Error("preview_frame_too_large");let t=JSON.parse(e);if(!Z(t))throw Error("preview_frame_invalid");if(t.type==="hello")return{type:"hello",binding:C(t.binding),...L(t.messages,p.chunk,p.upload)?{messages:t.messages}:{},...L(t.window,1,p.window)?{window:t.window}:{},...t.bytes===!0?{bytes:!0}:{}};if(t.type==="refused"&&typeof t.reason==="string"&&/^[a-z_]{1,32}$/.test(t.reason))return{type:"refused",binding:C(t.binding),reason:t.reason};if(!pe(t.id))throw Error("preview_frame_invalid");if(t.type==="end"||t.type==="cancel"||t.type==="credit")return{type:t.type,id:t.id};if(t.type==="ws"&&typeof t.protocol==="string"&&/^[a-zA-Z0-9._-]{0,100}$/.test(t.protocol))return{type:"ws",id:t.id,protocol:t.protocol};if(t.type==="data"&&typeof t.data==="string"&&typeof t.binary==="boolean")return z(t.data,p.upload),{type:"data",id:t.id,data:t.data,binary:t.binary};if(t.type==="head"&&L(t.status,200,599)&&ue(t.headers))return{type:"head",id:t.id,status:t.status,headers:t.headers};if(t.type==="request"&&typeof t.method==="string"&&/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS)$/.test(t.method)&&typeof t.path==="string"&&ue(t.headers)&&typeof t.body==="string"&&typeof t.upgrade==="boolean")return z(t.body,p.upload),{type:"request",id:t.id,method:t.method,path:H(t.path),headers:t.headers,body:t.body,upgrade:t.upgrade};throw Error("preview_frame_invalid")}function ee(e){let t=[...e],n=new Set(t.filter(([s])=>s.toLowerCase()==="connection").flatMap(([,s])=>s.toLowerCase().split(",").map((i)=>i.trim()))),o=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 t.filter(([s])=>!o.has(s.toLowerCase())&&!n.has(s.toLowerCase())&&!/^(x-forwarded-|x-ara-|sec-websocket-|access-control-)/i.test(s))}async function re(e){let t;try{return await Promise.race([Promise.resolve().then(e).then((n)=>n===!0||(n===!1?!1:void 0),()=>{return}),new Promise((n)=>{t=setTimeout(()=>n(void 0),p.authorizationMs)})])}finally{clearTimeout(t)}}async function Dt(e){return await re(e)===!0}function J(e,t){let n=new URL(e);if(n.username||n.password||n.search||n.hash||!(n.protocol==="wss:"||n.protocol==="ws:"&&["127.0.0.1","[::1]"].includes(n.hostname))||!new RegExp(`^/${t}/[a-zA-Z0-9_-]+/[a-zA-Z0-9_-]{32,}$`).test(n.pathname))throw Error("preview_relay_invalid");return n.href}function at(e){if(!Z(e)||Object.keys(e).length!==2||typeof e.deviceRelayUrl!=="string")throw Error("preview_open_invalid");return{binding:C(e.binding),deviceRelayUrl:J(e.deviceRelayUrl,"device")}}function io(e){if(!Z(e)||Object.keys(e).length!==1||!("binding"in e))throw Error("preview_close_invalid");return{binding:C(e.binding)}}var be="x-preview-connection";async function he(e,t){if(t.aborted)throw Error("preview_closed");let n=Re(32).toString("base64url"),o=new Set,s=!1,i=Le((c)=>{if(s||t.aborted||o.size>=p.streams*2)return c.destroy();o.add(c);let d=new AbortController;c.once("close",()=>{o.delete(c),d.abort()}),c.on("error",()=>c.destroy()),c.setTimeout(2000,()=>c.destroy());let b=Buffer.alloc(0),m=(g)=>{b=Buffer.concat([b,g]);let w=b.indexOf(`\r
|
|
3
3
|
\r
|
|
4
4
|
`);if(w<0){if(b.length>16384)c.destroy();return}if(c.pause(),c.off("data",m),w>16384||b.length>p.upload+16384)return c.destroy();l(b,w).catch(()=>c.destroy())};c.on("data",m);async function l(g,w){let y=g.subarray(0,w).toString("latin1").split(`\r
|
|
5
5
|
`),_=/^(GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS) (\S+) HTTP\/1\.1$/.exec(y.shift()??"");if(!_)throw Error("preview_request_invalid");H(_[2]);let k=!1,O=0,T=[];for(let B of y){let S=/^([a-zA-Z0-9-]+):[ \t]*([^\x00-\x08\x0a-\x1f\x7f]*)$/.exec(B);if(!S)throw Error("preview_header_invalid");if(S[1].toLowerCase()===be){O++;let N=Buffer.from(S[2].trim());k=N.length===n.length&&Be(N,Buffer.from(n))}else if(S[1].toLowerCase()!=="host")T.push(B)}if(!k||O!==1||s||d.signal.aborted)throw Error("preview_connection_denied");let v=await e.connect(d.signal);if(s||d.signal.aborted)throw v.destroy(),Error("preview_closed");o.add(v),v.on("error",()=>c.destroy()),v.once("close",()=>{o.delete(v),c.destroy()}),c.once("close",()=>v.destroy()),c.setTimeout(0);let P=[`${_[1]} ${_[2]} HTTP/1.1`,`Host: 127.0.0.1:${v.remotePort}`,...T,"",""].join(`\r
|
|
6
6
|
`);v.write(Buffer.concat([Buffer.from(P,"latin1"),g.subarray(w+4)])),v.pipe(c),c.pipe(v),c.resume()}});await new Promise((c,d)=>{i.once("error",d),i.listen(0,"127.0.0.1",c)});let a=i.address();if(!a||typeof a==="string")throw i.close(),Error("preview_bind_failed");function u(){if(s)return;s=!0,t.removeEventListener("abort",u);for(let c of o)c.destroy();o.clear(),i.close()}if(t.addEventListener("abort",u,{once:!0}),t.aborted)u();return{port:a.port,headers:{[be]:n},close:u}}var Oe=60000,Fe=1e4,He=5000,Ue=/^(?:text\/(?!event-stream)|application\/(?:(?:x-)?javascript|json|[a-z.+-]*\+json|xml|[a-z.+-]*\+xml|wasm)|image\/svg\+xml)/i;function je(e,t,n,o){let s=(c)=>t.find(([d])=>d.toLowerCase()===c)?.[1],i=(c)=>o.find(([d])=>d.toLowerCase()===c)?.[1],a=Number(i("content-length")??Number.NaN);if(e!=="GET"||n!==200||s("range")!==void 0||i("content-encoding")!==void 0||!Ue.test(i("content-type")??"")||/\bno-transform\b/i.test(i("cache-control")??"")||a<1024)return null;let u=(c)=>new RegExp(`(?:^|,)\\s*${c}\\s*(?:,|$|;\\s*q=(?:1|0?\\.0*[1-9]))`,"i").test(s("accept-encoding")??"");return u("br")?"br":u("gzip")?"gzip":null}function qe(e,t){let n=e.filter(([o])=>o.toLowerCase()==="vary").map(([,o])=>o).join(", ");return[...e.filter(([o])=>!["vary","etag","content-md5"].includes(o.toLowerCase())),...e.filter(([o])=>o.toLowerCase()==="etag").map(([o,s])=>[o,s.startsWith("W/")?s:`W/${s}`]),["Content-Encoding",t],["Vary",n.split(",").some((o)=>/^\s*(?:accept-encoding|\*)\s*$/i.test(o))?n:n?`${n}, Accept-Encoding`:"Accept-Encoding"]]}async function En(e){process.stderr.write(`${JSON.stringify({event:"worker_preview.open_refused",job_id:e.jobId,port:e.port,reason_code:e.reason})}
|
|
7
|
-
`);let t=e.binding,n;try{n=J(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((o)=>{let s=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{s.terminate(),o()},p.authorizationMs*2);s.addEventListener("open",()=>{s.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),s.close(1000,`worker_refused_${e.reason}`)}),s.addEventListener("error",()=>{clearTimeout(i),o()}),s.addEventListener("close",()=>{clearTimeout(i),o()})})}async function Ke(e,t){let n=Date.now()+Fe,o;for(;;){if(!t())return"closed";let s=o??=e.refusal().finally(()=>{o=void 0}),i,a=await Promise.race([s.catch(()=>"port_unproved"),new Promise((u)=>{i=setTimeout(()=>u("port_check_timeout"),p.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((u)=>setTimeout(u,500))}}async function _e(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,o=t.expiresAtMs>Date.now()+p.lifetimeMs+He?"binding_mismatch":await Ke(e.port,n);if(o)throw await En({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:o}),Error("preview_not_authorized",{cause:o});let s=J(e.deviceRelayUrl,"device"),i=await he(e.port,e.signal),a;try{a=new U(s,{followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload*1.4+300000})}catch(f){throw i.close(),f}let u=new Map,c=!1,d=!1,b=0,m=!1,l,g,w,y=new Promise((f)=>{w=f}),_,k,O=new Promise((f,h)=>{_=f,k=h}),T=!1,v=(f)=>{let h=Buffer.isBuffer(f)?f:JSON.stringify(f);if(b+=Buffer.byteLength(h),!n()||d||a.readyState!==U.OPEN)return P(n()?"relay_closed":"expired");if(a.bufferedAmount>p.relayBuffered)return P("relay_backlog");if(b>p.total)return P("quota");a.send(h)};function P(f="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let h of u.values())h.stop();u.clear(),i.close(),a.close(1000,`worker_${f}`),k(Error("preview_closed")),w()}let B=()=>P("aborted"),S=setTimeout(()=>P("pair_timeout"),p.requestMs),N=setInterval(async()=>{if(!n())return P(e.signal.aborted?"aborted":"expired");if(m)return;m=!0;try{let f=l??=Promise.resolve().then(()=>e.port.check()).finally(()=>{l=void 0}),h=await re(()=>f);if(h===!1)return P("port_refused");if(h){g=void 0;return}if(Date.now()-(g??=Date.now())>Oe)return P("port_unknown");for(let E of u.values())E.stop()}finally{m=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())P(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>v({type:"hello",binding:t,messages:p.upload,window:p.window})),a.addEventListener("close",()=>P("relay_closed")),a.addEventListener("error",()=>P("relay_error")),a.addEventListener("message",(f)=>{try{if(!n()||d)return P(e.signal.aborted?"aborted":"expired");if(typeof f.data!=="string")throw Error("preview_frame_invalid");if(b+=Buffer.byteLength(f.data),b>p.total)return P("quota");let h=ge(f.data);if(!c){if(h.type!=="hello"||!ze(t,h.binding))return P("binding_mismatch");c=!0,T=h.bytes===!0,clearTimeout(S),_();return}if(h.type==="hello"||h.type==="refused")return P("invalid_frame");if(h.type==="request"){D(h).catch(()=>P("invalid_request"));return}let E=u.get(h.id);if(!E)return;if(h.type==="cancel"||h.type==="end")E.stop();else if(h.type==="credit"&&E.credit)E.credit();else if(h.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>p.buffered)return E.stop();let I=z(h.data,p.upload);E.ws.send(h.binary?I:I.toString("utf8"))}else P("invalid_frame")}catch{P("invalid_frame")}});async function D(f){if(u.has(f.id)||u.size>=p.streams)return P("stream_limit");if(!n())return P(e.signal.aborted?"aborted":"expired");let h=new AbortController,E,I,q,Y=0,R=(W=!1)=>{if(!u.delete(f.id))return;clearTimeout(E),h.abort(),I?.close(1000,"preview_closed"),q?.(),v({type:W?"end":"cancel",id:f.id})},ie={stop:()=>R(),credit:()=>{Y++,q?.()}};if(u.set(f.id,ie),E=setTimeout(R,p.requestMs),!await It(()=>e.port.check())||!n()||h.signal.aborted)return R();let ae=H(f.path);if(f.upgrade){if(f.method!=="GET"||f.body)return R();let W=f.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${ae}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload}),ie.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),v({type:"ws",id:f.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let K=typeof A.data!=="string",M=me(A.data);if(M.length>p.upload)return R();v({type:"data",id:f.id,data:M.toString("base64"),binary:K})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let Te=z(f.body,p.upload),de=Ce({hostname:"127.0.0.1",port:i.port,path:ae,method:f.method,headers:{...Object.fromEntries(ee(f.headers)),...i.headers,connection:"close"},signal:h.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let K=W.statusCode??502,M=je(f.method,f.headers,K,A),Q=M==="br"?$e({flush:te.BROTLI_OPERATION_FLUSH,params:{[te.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Me({level:6,flush:te.Z_SYNC_FLUSH}):void 0;if(v({type:"head",id:f.id,status:K,headers:ee(M?qe(A,M):A)}),clearTimeout(E),Q)Ne(W,Q,()=>{});for await(let F of Q??W){let ce=Buffer.from(F);for(let G=0;G<ce.length;G+=p.chunk){if(Y===0&&!h.signal.aborted)await new Promise((We)=>{q=We});if(q=void 0,h.signal.aborted)return;Y--;let le=ce.subarray(G,G+p.chunk);v(T?fe(f.id,le):{type:"data",id:f.id,data:le.toString("base64"),binary:!0})}}R(!0)}catch{R()}});de.on("error",()=>R()),de.end(Te)}return await O,{close:P,closed:y}}import{execFile as Ge}from"child_process";import{createRequire as Ze}from"module";import{win32 as V}from"path";var Je=250,Ve=50,Xe=250,Ye=4194304;function Pe(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Qe(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim().split(/\s+/);if(o[0]!=="TCP"||o.length<5)continue;let s=Pe(o[1]),i=Pe(o[2]),a=Number(o.at(-1));if(!s||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:s.address,localPort:s.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function er(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var ke=(e)=>new Promise((t,n)=>Ge(V.join(Ie("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:Ye,encoding:"utf8",windowsHide:!0,env:De()},(o,s)=>o?n(o):t(s)));function ne(e){let t=V.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function rr(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return o===n||o.startsWith(n.endsWith("\\")?n:`${n}\\`)}function xe(e,t,n){let o=e.cwd(n),s=o?ne(o):null;return s&&V.isAbsolute(s)&&rr(t,s)?s:null}var j;function ye(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=Ze(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,o,s;try{o=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,s=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,u=1040,c=568,d=(b,m,l)=>{let g=Buffer.alloc(l);return o.ReadProcessMemory(b,m,n(g),l,null)?g:null};return j={processes(){let b=BigInt(o.CreateToolhelp32Snapshot(a,0));if(b===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let m=Buffer.alloc(c);m.writeUInt32LE(c,0);let l=n(m),g=[];for(let w=o.Process32FirstW(b,l);w;w=o.Process32NextW(b,l)){let y=m.toString("utf16le",44,c),_=y.slice(0,y.includes("\x00")?y.indexOf("\x00"):void 0),k=m.readUInt32LE(8);if(k>0)g.push({pid:k,parentPid:m.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return g}finally{o.CloseHandle(b)}},cwd(b){let m=BigInt(o.OpenProcess(u,0,b));if(m===0n)return null;try{let l=Buffer.alloc(48);if(s.NtQueryInformationProcess(m,0,n(l),l.length,null)!==0)return null;let g=d(m,l.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),w=g?d(m,g+0x38n,16):null,y=w?.readUInt16LE(0)??0;if(!w||y===0||y%2!==0)return null;return d(m,w.readBigUInt64LE(8),y)?.toString("utf16le")??null}finally{o.CloseHandle(m)}}},j}function oe(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function Se(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Qe(n)}async function oo(e,t=ye()){let n=oe(t),o=ne(e),s=[];for(let i of n.processes()){if(s.length>=Je)break;let a=xe(n,o,i.pid);if(a)s.push({pid:i.pid,command:i.command,cwd:V.relative(o,a)||"."})}return{processes:s}}async function so(e,t=ye(),n=ke){let o=oe(t),s=ne(e),i=(await Se(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:er(d)})).sort((d,b)=>d.pid-b.pid||d.port-b.port||(d.address<b.address?-1:d.address>b.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,Ve),u=new Set(a.filter((d)=>xe(o,s,d)!==null));if(u.size===0)return{ports:[]};let c=new Map(o.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>u.has(d.pid)).slice(0,Xe).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function ve(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let s of e)if(!n.has(s.pid)&&n.has(s.parentPid)&&s.pid!==s.parentPid)n.add(s.pid),o=!0}return n}function tr(e,t,n,o){let s=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==o)return[];let a=i.listening&&(s(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),u=!i.listening&&s(i.localAddress)&&s(i.remoteAddress);if(!a&&!u)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:o,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function Ee(e,t,n=ye(),o=ke){let s=oe(n),i=ve(s.processes(),e),a=await Se(o,1000),u=ve(s.processes(),e);return tr(a,new Set([...i].filter((c)=>u.has(c))),e,t)}import{execFile as nr}from"child_process";import{readFile as or,readdir as sr,readlink as ir}from"fs/promises";import{connect as ar}from"net";import{setTimeout as dr}from"timers/promises";var cr={directory:sr,text:(e)=>or(e,"utf8"),link:ir};class se extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new se(e),X="preview_listener_unproved",Ae="00000000000000000000000001000000";async function lr(e,t,n=cr){let o=new Map;for(let a of["tcp","tcp6"]){let u=await n.text(`/proc/net/${a}`);if(u.length>4194304)throw x();for(let c of u.split(`
|
|
7
|
+
`);let t=e.binding,n;try{n=J(e.deviceRelayUrl,"device")}catch{return}if(!t)return;await new Promise((o)=>{let s=new U(n,{followRedirects:!1,perMessageDeflate:!1,maxPayload:4096}),i=setTimeout(()=>{s.terminate(),o()},p.authorizationMs*2);s.addEventListener("open",()=>{s.send(JSON.stringify({type:"refused",binding:t,reason:e.reason})),s.close(1000,`worker_refused_${e.reason}`)}),s.addEventListener("error",()=>{clearTimeout(i),o()}),s.addEventListener("close",()=>{clearTimeout(i),o()})})}async function Ke(e,t){let n=Date.now()+Fe,o;for(;;){if(!t())return"closed";let s=o??=e.refusal().finally(()=>{o=void 0}),i,a=await Promise.race([s.catch(()=>"port_unproved"),new Promise((u)=>{i=setTimeout(()=>u("port_check_timeout"),p.authorizationMs)})]).finally(()=>clearTimeout(i));if(a===null)return null;if(!["listener_unproved","port_check_timeout"].includes(a)||Date.now()+500>=n)return a;await new Promise((u)=>setTimeout(u,500))}}async function _e(e){let t=C(e.binding),n=()=>!e.signal.aborted&&Date.now()<t.expiresAtMs,o=t.expiresAtMs>Date.now()+p.lifetimeMs+He?"binding_mismatch":await Ke(e.port,n);if(o)throw await En({deviceRelayUrl:e.deviceRelayUrl,binding:t,jobId:t.jobId,port:t.port,reason:o}),Error("preview_not_authorized",{cause:o});let s=J(e.deviceRelayUrl,"device"),i=await he(e.port,e.signal),a;try{a=new U(s,{followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload*1.4+300000})}catch(f){throw i.close(),f}let u=new Map,c=!1,d=!1,b=0,m=!1,l,g,w,y=new Promise((f)=>{w=f}),_,k,O=new Promise((f,h)=>{_=f,k=h}),T=!1,v=(f)=>{let h=Buffer.isBuffer(f)?f:JSON.stringify(f);if(b+=Buffer.byteLength(h),!n()||d||a.readyState!==U.OPEN)return P(n()?"relay_closed":"expired");if(a.bufferedAmount>p.relayBuffered)return P("relay_backlog");if(b>p.total)return P("quota");a.send(h)};function P(f="closed"){if(d)return;d=!0,clearInterval(N),clearTimeout(S),e.signal.removeEventListener("abort",B);for(let h of u.values())h.stop();u.clear(),i.close(),a.close(1000,`worker_${f}`),k(Error("preview_closed")),w()}let B=()=>P("aborted"),S=setTimeout(()=>P("pair_timeout"),p.requestMs),N=setInterval(async()=>{if(!n())return P(e.signal.aborted?"aborted":"expired");if(m)return;m=!0;try{let f=l??=Promise.resolve().then(()=>e.port.check()).finally(()=>{l=void 0}),h=await re(()=>f);if(h===!1)return P("port_refused");if(h){g=void 0;return}if(Date.now()-(g??=Date.now())>Oe)return P("port_unknown");for(let E of u.values())E.stop()}finally{m=!1}},1000);if(e.signal.addEventListener("abort",B,{once:!0}),!n())P(e.signal.aborted?"aborted":"expired");a.addEventListener("open",()=>v({type:"hello",binding:t,messages:p.upload,window:p.window})),a.addEventListener("close",()=>P("relay_closed")),a.addEventListener("error",()=>P("relay_error")),a.addEventListener("message",(f)=>{try{if(!n()||d)return P(e.signal.aborted?"aborted":"expired");if(typeof f.data!=="string")throw Error("preview_frame_invalid");if(b+=Buffer.byteLength(f.data),b>p.total)return P("quota");let h=ge(f.data);if(!c){if(h.type!=="hello"||!ze(t,h.binding))return P("binding_mismatch");c=!0,T=h.bytes===!0,clearTimeout(S),_();return}if(h.type==="hello"||h.type==="refused")return P("invalid_frame");if(h.type==="request"){D(h).catch(()=>P("invalid_request"));return}let E=u.get(h.id);if(!E)return;if(h.type==="cancel"||h.type==="end")E.stop();else if(h.type==="credit"&&E.credit)E.credit();else if(h.type==="data"&&E.ws){if(E.ws.readyState!==U.OPEN||E.ws.bufferedAmount>p.buffered)return E.stop();let I=z(h.data,p.upload);E.ws.send(h.binary?I:I.toString("utf8"))}else P("invalid_frame")}catch{P("invalid_frame")}});async function D(f){if(u.has(f.id)||u.size>=p.streams)return P("stream_limit");if(!n())return P(e.signal.aborted?"aborted":"expired");let h=new AbortController,E,I,q,Y=0,R=(W=!1)=>{if(!u.delete(f.id))return;clearTimeout(E),h.abort(),I?.close(1000,"preview_closed"),q?.(),v({type:W?"end":"cancel",id:f.id})},ie={stop:()=>R(),credit:()=>{Y++,q?.()}};if(u.set(f.id,ie),E=setTimeout(R,p.requestMs),!await Dt(()=>e.port.check())||!n()||h.signal.aborted)return R();let ae=H(f.path);if(f.upgrade){if(f.method!=="GET"||f.body)return R();let W=f.headers.find(([A])=>A.toLowerCase()==="sec-websocket-protocol")?.[1].split(",").map((A)=>A.trim());if(W?.some((A)=>!/^[a-zA-Z0-9._-]{1,100}$/.test(A))||(W?.length??0)>8)return R();I=new U(`ws://127.0.0.1:${i.port}${ae}`,W,{headers:i.headers,followRedirects:!1,perMessageDeflate:!1,maxPayload:p.upload}),ie.ws=I,I.binaryType="arraybuffer",I.addEventListener("open",()=>{clearTimeout(E),v({type:"ws",id:f.id,protocol:I.protocol})}),I.addEventListener("message",(A)=>{let K=typeof A.data!=="string",M=me(A.data);if(M.length>p.upload)return R();v({type:"data",id:f.id,data:M.toString("base64"),binary:K})}),I.addEventListener("error",()=>R()),I.addEventListener("close",(A)=>R(A.wasClean));return}let Te=z(f.body,p.upload),de=Ce({hostname:"127.0.0.1",port:i.port,path:ae,method:f.method,headers:{...Object.fromEntries(ee(f.headers)),...i.headers,connection:"close"},signal:h.signal,agent:!1,maxHeaderSize:16384},async(W)=>{try{let A=[];for(let F=0;F<W.rawHeaders.length;F+=2)A.push([W.rawHeaders[F],W.rawHeaders[F+1]]);let K=W.statusCode??502,M=je(f.method,f.headers,K,A),Q=M==="br"?$e({flush:te.BROTLI_OPERATION_FLUSH,params:{[te.BROTLI_PARAM_QUALITY]:5}}):M==="gzip"?Me({level:6,flush:te.Z_SYNC_FLUSH}):void 0;if(v({type:"head",id:f.id,status:K,headers:ee(M?qe(A,M):A)}),clearTimeout(E),Q)Ne(W,Q,()=>{});for await(let F of Q??W){let ce=Buffer.from(F);for(let G=0;G<ce.length;G+=p.chunk){if(Y===0&&!h.signal.aborted)await new Promise((We)=>{q=We});if(q=void 0,h.signal.aborted)return;Y--;let le=ce.subarray(G,G+p.chunk);v(T?fe(f.id,le):{type:"data",id:f.id,data:le.toString("base64"),binary:!0})}}R(!0)}catch{R()}});de.on("error",()=>R()),de.end(Te)}return await O,{close:P,closed:y}}import{execFile as Ge}from"child_process";import{createRequire as Ze}from"module";import{win32 as V}from"path";var Je=250,Ve=50,Xe=250,Ye=4194304;function Pe(e){let t=/^(?:\[([^\]]+)\]|([^:]+)):([0-9]{1,5})$/.exec(e??""),n=Number(t?.[3]);return t&&n<=65535?{address:t[1]??t[2],port:n}:null}function Qe(e){let t=[];for(let n of e.split(/\r?\n/)){let o=n.trim().split(/\s+/);if(o[0]!=="TCP"||o.length<5)continue;let s=Pe(o[1]),i=Pe(o[2]),a=Number(o.at(-1));if(!s||!i||!Number.isSafeInteger(a)||a<0)continue;t.push({pid:a,localAddress:s.address,localPort:s.port,remoteAddress:i.address,remotePort:i.port,listening:i.port===0})}return t}function er(e){if(e.localAddress==="0.0.0.0"||e.localAddress==="::")return`*:${e.localPort}`;return e.localAddress.includes(":")?`[${e.localAddress}]:${e.localPort}`:`${e.localAddress}:${e.localPort}`}var ke=(e)=>new Promise((t,n)=>Ge(V.join(Ie("win32").split(";")[0],"NETSTAT.EXE"),["-ano"],{timeout:e,maxBuffer:Ye,encoding:"utf8",windowsHide:!0,env:De()},(o,s)=>o?n(o):t(s)));function ne(e){let t=V.normalize(e.startsWith("\\\\?\\")?e.slice(4):e);return t.length>3&&t.endsWith("\\")?t.slice(0,-1):t}function rr(e,t){let n=e.toLowerCase(),o=t.toLowerCase();return o===n||o.startsWith(n.endsWith("\\")?n:`${n}\\`)}function xe(e,t,n){let o=e.cwd(n),s=o?ne(o):null;return s&&V.isAbsolute(s)&&rr(t,s)?s:null}var j;function ye(){if(j!==void 0)return j;if(j=null,process.platform!=="win32"||!["x64","arm64"].includes(process.arch))return null;let e;try{e=Ze(import.meta.url)("bun:ffi")}catch{return null}let{FFIType:t,ptr:n}=e,o,s;try{o=e.dlopen("kernel32.dll",{CreateToolhelp32Snapshot:{args:[t.u32,t.u32],returns:t.u64},Process32FirstW:{args:[t.u64,t.ptr],returns:t.i32},Process32NextW:{args:[t.u64,t.ptr],returns:t.i32},OpenProcess:{args:[t.u32,t.i32,t.u32],returns:t.u64},ReadProcessMemory:{args:[t.u64,t.u64,t.ptr,t.u64,t.ptr],returns:t.i32},CloseHandle:{args:[t.u64],returns:t.i32}}).symbols,s=e.dlopen("ntdll.dll",{NtQueryInformationProcess:{args:[t.u64,t.i32,t.ptr,t.u32,t.ptr],returns:t.i32}}).symbols}catch{return null}let i=0xFFFFFFFFFFFFFFFFn,a=2,u=1040,c=568,d=(b,m,l)=>{let g=Buffer.alloc(l);return o.ReadProcessMemory(b,m,n(g),l,null)?g:null};return j={processes(){let b=BigInt(o.CreateToolhelp32Snapshot(a,0));if(b===i)throw new r("process_inspection_failed","Reading this computer's processes did not complete.");try{let m=Buffer.alloc(c);m.writeUInt32LE(c,0);let l=n(m),g=[];for(let w=o.Process32FirstW(b,l);w;w=o.Process32NextW(b,l)){let y=m.toString("utf16le",44,c),_=y.slice(0,y.includes("\x00")?y.indexOf("\x00"):void 0),k=m.readUInt32LE(8);if(k>0)g.push({pid:k,parentPid:m.readUInt32LE(32),command:_.replace(/\.exe$/i,"")||null})}return g}finally{o.CloseHandle(b)}},cwd(b){let m=BigInt(o.OpenProcess(u,0,b));if(m===0n)return null;try{let l=Buffer.alloc(48);if(s.NtQueryInformationProcess(m,0,n(l),l.length,null)!==0)return null;let g=d(m,l.readBigUInt64LE(8)+0x20n,8)?.readBigUInt64LE(0),w=g?d(m,g+0x38n,16):null,y=w?.readUInt16LE(0)??0;if(!w||y===0||y%2!==0)return null;return d(m,w.readBigUInt64LE(8),y)?.toString("utf16le")??null}finally{o.CloseHandle(m)}}},j}function oe(e){if(!e)throw new r("process_inspection_failed","Reading this computer's processes is unavailable.");return e}async function Se(e,t){let n;try{n=await e(t)}catch{throw new r("process_inspection_failed","Reading this computer's ports did not complete.")}return Qe(n)}async function oo(e,t=ye()){let n=oe(t),o=ne(e),s=[];for(let i of n.processes()){if(s.length>=Je)break;let a=xe(n,o,i.pid);if(a)s.push({pid:i.pid,command:i.command,cwd:V.relative(o,a)||"."})}return{processes:s}}async function so(e,t=ye(),n=ke){let o=oe(t),s=ne(e),i=(await Se(n,5000)).filter((d)=>d.listening&&d.pid>0).map((d)=>({pid:d.pid,port:d.localPort,address:er(d)})).sort((d,b)=>d.pid-b.pid||d.port-b.port||(d.address<b.address?-1:d.address>b.address?1:0)),a=[...new Set(i.map((d)=>d.pid))].slice(0,Ve),u=new Set(a.filter((d)=>xe(o,s,d)!==null));if(u.size===0)return{ports:[]};let c=new Map(o.processes().map((d)=>[d.pid,d.command]));return{ports:i.filter((d)=>u.has(d.pid)).slice(0,Xe).map((d)=>({pid:d.pid,command:c.get(d.pid)??null,address:d.address}))}}function ve(e,t){let n=new Set([t]);for(let o=!0;o;){o=!1;for(let s of e)if(!n.has(s.pid)&&n.has(s.parentPid)&&s.pid!==s.parentPid)n.add(s.pid),o=!0}return n}function tr(e,t,n,o){let s=(i)=>i==="127.0.0.1"||i==="::ffff:127.0.0.1"||i==="::1";return e.flatMap((i)=>{if(!t.has(i.pid)||i.localPort!==o)return[];let a=i.listening&&(s(i.localAddress)||["0.0.0.0","::"].includes(i.localAddress)),u=!i.listening&&s(i.localAddress)&&s(i.remoteAddress);if(!a&&!u)return[];let c=`${i.localAddress}:${i.localPort}>${i.remoteAddress}:${i.remotePort}`;return[{pid:i.pid,processGroupId:n,descriptor:String(i.pid),kernelId:c,state:a?"listen":"established",port:o,peerPort:a?null:i.remotePort,host:i.localAddress==="::1"?"::1":"127.0.0.1"}]})}async function Ee(e,t,n=ye(),o=ke){let s=oe(n),i=ve(s.processes(),e),a=await Se(o,1000),u=ve(s.processes(),e);return tr(a,new Set([...i].filter((c)=>u.has(c))),e,t)}import{execFile as nr}from"child_process";import{readFile as or,readdir as sr,readlink as ir}from"fs/promises";import{connect as ar}from"net";import{setTimeout as dr}from"timers/promises";var cr={directory:sr,text:(e)=>or(e,"utf8"),link:ir};class se extends Error{code;constructor(e="port_unproved"){super("preview_port_ownership_unproved");this.code=e}}var x=(e)=>new se(e),X="preview_listener_unproved",Ae="00000000000000000000000001000000";async function lr(e,t,n=cr){let o=new Map;for(let a of["tcp","tcp6"]){let u=await n.text(`/proc/net/${a}`);if(u.length>4194304)throw x();for(let c of u.split(`
|
|
8
8
|
`).slice(1)){let d=c.trim().split(/\s+/);if(d.length<10||!["0A","01"].includes(d[3]))continue;let[b,m]=d[1].split(":"),[l,g]=d[2].split(":");if(Number.parseInt(m,16)!==t)continue;let w=(k)=>k==="0100007F"||k==="0000000000000000FFFF00000100007F"||k===Ae,y=d[3]==="0A";if(!(w(b)||y&&/^0+$/.test(b??"")))continue;if(!y&&!w(l))continue;let _=d[9];if(!/^[1-9][0-9]*$/.test(_))continue;o.set(_,{kernelId:_,port:t,peerPort:y?null:Number.parseInt(g,16),state:y?"listen":"established",host:b===Ae?"::1":"127.0.0.1"})}}let s=await n.directory("/proc");if(s.length>8192)throw x();let i=[];for(let a of s){if(!/^[1-9][0-9]*$/.test(a))continue;try{let u=await n.text(`/proc/${a}/stat`),c=u.slice(u.lastIndexOf(")")+2).trim().split(/\s+/);if(Number(c[2])!==e)continue;let d=await n.directory(`/proc/${a}/fd`);if(d.length>1024)throw x();let b=[];for(let g of d){if(!/^[0-9]+$/.test(g))continue;let w=await n.link(`/proc/${a}/fd/${g}`).catch(()=>""),y=/^socket:\[([0-9]+)\]$/.exec(w)?.[1],_=y?o.get(y):void 0;if(_)b.push({..._,pid:Number(a),processGroupId:e,descriptor:g})}let m=await n.text(`/proc/${a}/stat`),l=m.slice(m.lastIndexOf(")")+2).trim().split(/\s+/);if(c[19]===l[19]&&c[2]===l[2])i.push(...b)}catch(u){if(u instanceof Error&&u.message==="preview_port_ownership_unproved")throw u}}return i}function ur(e,t,n){if(e.length>2097152)throw x();let o=0,s=0,i="",a="",u="",c="",d=[],b=()=>{if(o<1||s!==t||!/^\d+$/.test(i)||!/^0x[0-9a-f]+$/i.test(a))return;let m=c==="LISTEN"&&["*","127.0.0.1","[::ffff:127.0.0.1]","[::1]"].some((g)=>u===`${g}:${n}`),l=new RegExp(`^(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):${n}->(?:127\\.0\\.0\\.1|\\[::ffff:127\\.0\\.0\\.1\\]|\\[::1\\]):([0-9]+)$`).exec(u);if(m||c==="ESTABLISHED"&&l)d.push({pid:o,processGroupId:s,descriptor:i,kernelId:a,state:m?"listen":"established",port:n,peerPort:m?null:Number(l[1]),host:u.startsWith("[::1]:")?"::1":"127.0.0.1"})};for(let m of e.split(/[\0\n]/)){let l=m.slice(1);if(m[0]==="p")b(),o=Number(l),s=0,i=a=u=c="";else if(m[0]==="g")s=Number(l);else if(m[0]==="f")b(),i=l,a=u=c="";else if(m[0]==="d")a=l;else if(m[0]==="n")u=l;else if(m.startsWith("TST="))c=m.slice(4)}return b(),d}async function pr(e,t){if(process.platform==="linux")return lr(e,t);if(process.platform==="win32")return Ee(e,t);if(process.platform!=="darwin")throw x();let n=await new Promise((o,s)=>nr("/usr/sbin/lsof",["-nP","-a","-g",String(e),`-iTCP:${t}`,"-F0pgfdnT"],{timeout:1000,maxBuffer:2097152,encoding:"utf8",env:{PATH:"/usr/bin:/bin",LC_ALL:"C"}},(i,a)=>i?s(x()):o(a)));return ur(n,e,t)}function we(e,t={}){let n=C(e.binding),o=t.inspectSockets??pr,s=t.monotonicNow??(()=>performance.now());async function i(){let l=()=>{if(Date.now()>=n.expiresAtMs)throw x("binding_expired");if(e.deniedPorts.has(n.port))throw x("port_denied")};l();let g=await e.readCurrentJob(),w=g?.job,y=w?.process;if(l(),!g)throw x("server_stopped");if(!ze(n,g.binding)||w?.jobId!==n.jobId)throw x("binding_changed");if(w.state!=="running"||w.finishedAtMs!==null||w.leaseExpiresAtMs<n.expiresAtMs)throw x("job_not_running");if(!y||y.pid<1||y.pid!==y.processGroupId||y.executorLaunchId!==g.executorLaunchId)throw x("process_unproved");return{pid:y.pid,launch:y.executorLaunchId,started:w.startedAtMs}}let a,u;async function c(){let l=await i(),g=await o(l.pid,n.port).catch(()=>{throw Error(X)}),w=await i();if(l.pid!==w.pid||l.launch!==w.launch||l.started!==w.started)throw x("job_restarted");return g}async function d(l){for(;;){if(u&&u.startedAt>=l)return u.sockets;if(a&&a.startedAt>=l)return await a.sockets;if(a){await a.sockets.catch(()=>{});continue}let g={startedAt:s(),sockets:c()};a=g;try{let w=await g.sockets;if(!u||u.startedAt<=g.startedAt)u={startedAt:g.startedAt,sockets:w};return w}finally{if(a===g)a=void 0}}}async function b(l=()=>{},g=s()){l();let w=await d(g);if(l(),Date.now()>=n.expiresAtMs)throw x("binding_expired");if(!w.some((y)=>y.state==="listen"))throw Error(X);return w}async function m(){try{return await b(()=>{},s()-1000),null}catch(l){if(l instanceof Error&&l.message===X)return"listener_unproved";return l instanceof se?l.code:"port_unproved"}}return{refusal:m,async check(){let l=await m();if(l==="listener_unproved")throw Error(X);return l===null},async connect(l){if(l.aborted)throw x();let g=s()+2000,w=new AbortController,y=new Promise((P)=>w.signal.addEventListener("abort",()=>P(null),{once:!0})),_,k=()=>{w.abort(),_?.destroy()},O=setTimeout(k,2000);l.addEventListener("abort",k,{once:!0});let T=()=>{if(w.signal.aborted||l.aborted||s()>=g||_?.destroyed)throw k(),x()};async function v(P){T();let B=await Promise.race([P().then((S)=>({value:S})),y]);if(T(),!B)throw x();return B.value}try{let P=await v(()=>b(T,s()-1000));T();let B=P.some((f)=>f.state==="listen"&&f.host==="127.0.0.1")?"127.0.0.1":"::1",S=ar({host:B,port:n.port,signal:l});_=S,S.once("close",k),await v(()=>new Promise((f,h)=>{S.once("connect",f),S.once("error",h)}));let N=S.localPort;if(!N)throw x();let D=s();while(!(await v(()=>b(T,D))).some((f)=>f.state==="established"&&f.peerPort===N))await v(()=>dr(Math.min(20,Math.max(1,g-s())),void 0,{signal:w.signal})),D=s();return T(),S}catch(P){throw k(),P}finally{clearTimeout(O),l.removeEventListener("abort",k),_?.off("close",k),w.abort()}}}}
|
|
9
|
-
export{p,ze,
|
|
9
|
+
export{p,ze,Dt,at,io,En,_e,ye,oo,so,we};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{E}from"./vm-hands-entry-lite-
|
|
2
|
+
import{E}from"./vm-hands-entry-lite-txd50spx.js";import{fe,Ie,Ne,Le,Me}from"./vm-hands-entry-lite-vdhgwmmp.js";import{spawn as y}from"child_process";import{existsSync as p,mkdirSync as T,readFileSync as _,writeFileSync as A}from"fs";import{homedir as m}from"os";import{basename as H,delimiter as g,join as f,win32 as u}from"path";var Er=process.platform==="win32"?Ie("win32"):"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",P=Er.split(g),R=5000,S=65536,O=new Set(["zsh","bash"]),b=[[".local","bin"],[".bun","bin"],[".cargo","bin"],["go","bin"]],x=(t,e)=>new Promise((n,r)=>{let o;try{o=y(t,[...e],{...Ne(),stdio:["ignore","pipe","ignore"]}),Le(o)}catch(c){r(c);return}let i=[],s=0,a=null,L=(c)=>{a??=Error(c);try{if(o.pid!==void 0)Me(o.pid,"SIGKILL")}catch{}},d=setTimeout(()=>L("login_shell_timeout"),R);o.stdout?.on("data",(c)=>{if(s+=c.length,s>S)L("login_shell_output_too_large");else i.push(c)}),o.once("error",(c)=>{clearTimeout(d),r(c)}),o.once("close",(c)=>{if(clearTimeout(d),a)r(a);else if(c!==0)r(Error("login_shell_exit_nonzero"));else n(Buffer.concat(i).toString("utf8"))})});function w(t){return typeof t==="string"&&t.startsWith("/")&&!t.includes("\x00")&&O.has(H(t))}function h(t){let e=new Set,n=[];for(let r of t){if(e.has(r))continue;e.add(r),n.push(r)}return n}function xr(t,e=process.platform){let n=e==="win32",r=t.split(`
|
|
3
3
|
`).at(-1)??"",o=[];for(let i of r.split(n?";":":")){let s=i.trim();if(n?!u.isAbsolute(s):!s.startsWith("/"))continue;if(s.includes("\x00"))continue;if(E(s))continue;o.push(s)}return h(o)}function vn(t){let e=t?.home??m(),n=t?.directoryExists??p,r=b.map((o)=>f(e,...o)).filter((o)=>{try{return n(o)}catch{return!1}});return h([...r,...process.platform==="win32"?xr(process.env.PATH??process.env.Path??""):[],...P]).join(g)}async function C(t){let e=t?.shell??process.env.SHELL,n=()=>({path:vn({home:t?.home,directoryExists:t?.directoryExists}),source:"fallback"});if(process.platform==="win32"||!w(e))return n();let r;try{r=await(t?.runLoginShell??x)(e,["-lic",'printf %s "$PATH"'])}catch{return n()}if(Buffer.byteLength(r,"utf8")>S)return n();let o=xr(r);if(o.length===0)return n();return{path:h([...o,...P]).join(":"),source:"login_shell"}}function no(t){let e=null;return()=>(e??=C(t),e)}function l(t){if(t===void 0||t.includes("\x00")||Buffer.byteLength(t,"utf8")>32768)return;return t}function He(t){let e=t.source??process.env,n={HOME:t.home,PATH:t.path??Er,TMPDIR:t.temporaryDirectory,SHELL:l(e.SHELL)??"/bin/zsh",LANG:l(e.LANG)??"C.UTF-8",LC_ALL:l(e.LC_ALL)??l(e.LANG)??"C.UTF-8"},r=l(e.LC_CTYPE),o=l(e.TERM),i=l(e.COLORTERM);if(r)n.LC_CTYPE=r;if(o)n.TERM=o;if(i)n.COLORTERM=i;if(process.platform==="win32"){for(let s of I){let a=l(e[s]);if(a)n[s]=a}n.TEMP=n.TMP=t.temporaryDirectory,n.SHELL=fe()??n.SHELL,n.PATH=Sn(n.PATH)}return n}function Sn(t,e=f(m(),".reason","python3")){let n=(i)=>t.split(u.delimiter).filter((s)=>s&&!/[\\/]WindowsApps[\\/]?$/i.test(s)).map((s)=>u.join(s,i)).find((s)=>p(s)),r=n("python.exe");if(n("python3.exe")||!r)return t;let o=`#!/bin/sh
|
|
4
4
|
exec "${r.replaceAll("\\","/")}" "$@"
|
|
5
5
|
`;try{let i=f(e,"python3");if(!p(i)||_(i,"utf8")!==o)T(e,{recursive:!0}),A(i,o)}catch{return t}return[e,t].join(u.delimiter)}var I=["SystemRoot","SystemDrive","windir","ComSpec","PATHEXT","USERPROFILE","USERNAME","USERDOMAIN","APPDATA","LOCALAPPDATA","ProgramData","ProgramFiles","ProgramFiles(x86)","ProgramW6432","CommonProgramFiles","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","OS"];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ie,spawn as E}from"child_process";var fo="h264_ws_v1",mo="video",lt=["smooth","sharp","data_saver","balanced"];var go="video_presets";var L=8388608,S=65536,_o="control",yo="v1",X=200;function Ln(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t,n=(i)=>typeof i==="string"&&i.length>0&&i.length<=X;if(Object.keys(e).length!==2||!n(e.user_id)||!n(e.name))return null;return{user_id:e.user_id,name:e.name}}var wo="windows",bo="v1",D=200,J=(t)=>typeof t==="string"&<.includes(t);function vo(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(Object.keys(e).length!==2||e.format!=="h264_ws_v1"||!J(e.preset))return null;return{format:"h264_ws_v1",preset:e.preset}}var o={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23,resize:24};class l extends Error{constructor(t){super(t);this.name="DisplayVideoProtocolError"}}var Z=new TextEncoder,Q=new TextDecoder("utf-8",{fatal:!0});function p(t,e){if(e.byteLength+1>L)throw new l("message_too_large");let n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,e.byteLength+1),i.setUint8(4,t),n.set(e,5),n}function w(t){let e=Z.encode(t);if(e.byteLength>S)throw new l("text_too_large");return e}function _(t,e){if(!Number.isInteger(t)||t<0||t>65535)throw new l(`invalid_${e}`);return t}function ee(t){if(!Number.isFinite(t))throw new l("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(t)))}function
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ie,spawn as E}from"child_process";var fo="h264_ws_v1",mo="video",lt=["smooth","sharp","data_saver","balanced"];var go="video_presets";var L=8388608,S=65536,_o="control",yo="v1",X=200;function Ln(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t,n=(i)=>typeof i==="string"&&i.length>0&&i.length<=X;if(Object.keys(e).length!==2||!n(e.user_id)||!n(e.name))return null;return{user_id:e.user_id,name:e.name}}var wo="windows",bo="v1",D=200,J=(t)=>typeof t==="string"&<.includes(t);function vo(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(Object.keys(e).length!==2||e.format!=="h264_ws_v1"||!J(e.preset))return null;return{format:"h264_ws_v1",preset:e.preset}}var o={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23,resize:24};class l extends Error{constructor(t){super(t);this.name="DisplayVideoProtocolError"}}var Z=new TextEncoder,Q=new TextDecoder("utf-8",{fatal:!0});function p(t,e){if(e.byteLength+1>L)throw new l("message_too_large");let n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,e.byteLength+1),i.setUint8(4,t),n.set(e,5),n}function w(t){let e=Z.encode(t);if(e.byteLength>S)throw new l("text_too_large");return e}function _(t,e){if(!Number.isInteger(t)||t<0||t>65535)throw new l(`invalid_${e}`);return t}function ee(t){if(!Number.isFinite(t))throw new l("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(t)))}function zt(t){switch(t.type){case"hello":{let e=w(t.codec),n=new Uint8Array(6+e.byteLength),i=new DataView(n.buffer);return i.setUint16(0,_(t.width,"width")),i.setUint16(2,_(t.height,"height")),i.setUint8(4,Math.max(1,Math.min(240,Math.round(t.fps)))),i.setUint8(5,lt.indexOf(t.preset)),n.set(e,6),p(o.hello,n)}case"frame":{let e=new Uint8Array(13+t.data.byteLength),n=new DataView(e.buffer);return n.setUint8(0,t.key?1:0),n.setUint32(1,t.seq>>>0),n.setBigUint64(5,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,13),p(o.frame,e)}case"stats":return p(o.stats,w(JSON.stringify(t.stats)));case"pong":case"ping":{let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.token),p(t.type==="ping"?o.ping:o.pong,e)}case"serverClipboard":return p(o.serverClipboard,w(t.text));case"clientClipboard":return p(o.clientClipboard,w(t.text));case"error":return p(o.error,w(t.code));case"pointer":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint16(0,_(t.x,"x")),n.setUint16(2,_(t.y,"y")),n.setUint8(4,t.buttons&255),p(o.pointer,e)}case"key":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint8(0,t.down?1:0),n.setUint32(1,t.keysym>>>0),p(o.key,e)}case"config":return p(o.config,Uint8Array.of(lt.indexOf(t.preset)));case"keyframeRequest":return p(o.keyframeRequest,new Uint8Array(0));case"audioHello":{let e=w(t.codec),n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,t.sampleRate>>>0),i.setUint8(4,t.channels&255),n.set(e,5),p(o.audioHello,n)}case"audio":{let e=new Uint8Array(8+t.data.byteLength);return new DataView(e.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,8),p(o.audio,e)}case"control":return p(o.control,w(JSON.stringify(t.control)));case"windows":{let e=t.bounds.slice(0,D),n=new Uint8Array(e.length*16),i=new DataView(n.buffer);return e.forEach((s,a)=>{[s.x,s.y,s.width,s.height].forEach((c,d)=>i.setInt32(a*16+d*4,ee(c)))}),p(o.windows,n)}case"audioEnable":return p(o.audioEnable,Uint8Array.of(t.on?1:0));case"resize":{let e=new Uint8Array(4),n=new DataView(e.buffer);return n.setUint16(0,_(t.width,"width")),n.setUint16(2,_(t.height,"height")),p(o.resize,e)}case"ack":{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t.seq>>>0),p(o.ack,e)}}}function M(t){let e=lt[t];if(!e)throw new l("invalid_preset");return e}function y(t,e){if(t.byteLength!==e)throw new l("invalid_length")}function x(t){if(t.byteLength>S)throw new l("text_too_large");try{return Q.decode(t)}catch{throw new l("invalid_text")}}function te(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_stats")}let n=e;if(!n||typeof n!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((s)=>typeof n[s]!=="number"||!Number.isFinite(n[s])))throw new l("invalid_stats");return{fps:n.fps,kbps:n.kbps,dropped:n.dropped,restarts:n.restarts,queued_bytes:n.queued_bytes}}function ne(t){let e;try{e=JSON.parse(x(t))}catch{throw new l("invalid_control")}let n=e;if(!n||typeof n!=="object"||typeof n.you!=="boolean"||typeof n.same_user!=="boolean")throw new l("invalid_control");let i=n.holder===null?null:Ln(n.holder);if(i===null&&n.holder!==null)throw new l("invalid_control");return{holder:i,you:n.you,same_user:n.same_user}}function re(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(t){case o.hello:if(e.byteLength<6)throw new l("invalid_length");return{type:"hello",width:n.getUint16(0),height:n.getUint16(2),fps:n.getUint8(4),preset:M(n.getUint8(5)),codec:x(e.subarray(6))};case o.frame:if(e.byteLength<14)throw new l("invalid_length");if(n.getUint8(0)>1)throw new l("invalid_frame_flags");return{type:"frame",key:n.getUint8(0)===1,seq:n.getUint32(1),captureMicros:Number(n.getBigUint64(5)),data:e.subarray(13)};case o.stats:return{type:"stats",stats:te(e)};case o.ping:case o.pong:return y(e,8),{type:t===o.ping?"ping":"pong",token:n.getFloat64(0)};case o.serverClipboard:return{type:"serverClipboard",text:x(e)};case o.clientClipboard:return{type:"clientClipboard",text:x(e)};case o.error:return{type:"error",code:x(e)};case o.pointer:return y(e,5),{type:"pointer",x:n.getUint16(0),y:n.getUint16(2),buttons:n.getUint8(4)};case o.key:if(y(e,5),n.getUint8(0)>1)throw new l("invalid_key_flags");return{type:"key",down:n.getUint8(0)===1,keysym:n.getUint32(1)};case o.config:return y(e,1),{type:"config",preset:M(n.getUint8(0))};case o.keyframeRequest:return y(e,0),{type:"keyframeRequest"};case o.audioHello:if(e.byteLength<5)throw new l("invalid_length");return{type:"audioHello",sampleRate:n.getUint32(0),channels:n.getUint8(4),codec:x(e.subarray(5))};case o.audio:if(e.byteLength<9)throw new l("invalid_length");return{type:"audio",captureMicros:Number(n.getBigUint64(0)),data:e.subarray(8)};case o.audioEnable:if(y(e,1),n.getUint8(0)>1)throw new l("invalid_audio_flags");return{type:"audioEnable",on:n.getUint8(0)===1};case o.resize:return y(e,4),{type:"resize",width:n.getUint16(0),height:n.getUint16(2)};case o.control:return{type:"control",control:ne(e)};case o.windows:{if(e.byteLength%16!==0||e.byteLength>D*16)throw new l("invalid_length");let i=[];for(let s=0;s<e.byteLength;s+=16)i.push({x:n.getInt32(s),y:n.getInt32(s+4),width:n.getInt32(s+8),height:n.getInt32(s+12)});return{type:"windows",bounds:i}}case o.ack:return y(e,4),{type:"ack",seq:n.getUint32(0)};default:return null}}class Mn{buffer=new Uint8Array(0);push(t){let e=new Uint8Array(this.buffer.byteLength+t.byteLength);e.set(this.buffer),e.set(t,this.buffer.byteLength);let n=[],i=0;while(e.byteLength-i>=4){let s=new DataView(e.buffer,e.byteOffset+i,4).getUint32(0);if(s<1||s>L)throw new l("invalid_message_length");if(e.byteLength-i-4<s)break;let a=e[i+4],c=e.slice(i+5,i+4+s),d=re(a,c);if(d)n.push(d);i+=4+s}return this.buffer=e.slice(i),n}}var Y="/usr/bin/osascript",se=5000,oe=1048576,ae=String.raw`
|
|
3
3
|
ObjC.import("CoreGraphics");
|
|
4
4
|
ObjC.import("ApplicationServices");
|
|
5
5
|
ObjC.import("AppKit");
|
|
@@ -109,4 +109,4 @@ function run() {
|
|
|
109
109
|
`);h>=0;h=f.indexOf(`
|
|
110
110
|
`)){let U=f.slice(0,h);if(f=f.slice(h+1),!U.startsWith("c "))continue;let A=U.slice(2);if(A.length>Math.ceil(S/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(A)){u({reason:"display_protocol"});return}let C=Buffer.from(A,"base64");if(C.byteLength<=S)t.clipboard(C.toString("utf8"));if(a)return}if(f.length>Math.ceil(S/3)*4+2)u({reason:"display_protocol"})}),c.once("error",()=>b("Reason could not watch this Mac's desktop clipboard.")),c.once("exit",()=>{if(!a)b("Reason could not watch this Mac's desktop clipboard.")})};return n.stdout.on("data",(f)=>{if(a||s===null)return;s+=f.toString("utf8");let g=s.indexOf(`
|
|
111
111
|
`);if(g<0){if(s.length>4096)u({reason:"display_protocol"});return}let h=q(s.slice(0,g));if(s=null,!h)u({reason:"display_protocol"});else if(!h.screen||!h.accessibility)b(e.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else z(),t.ready({width:h.width,height:h.height})}),n.stdin.on("error",()=>{return}),n.once("error",()=>b("Reason could not start this Mac's desktop input.")),n.once("exit",()=>{if(s!==null)b("Reason could not start this Mac's desktop input.");else u({reason:"display_closed"})}),{pointer:(f,g,h)=>m(i.pointer(f,g,h)),key:(f,g)=>m(i.key(f,g)),clipboard:(f)=>m([`c ${Buffer.from(f,"utf8").toString("base64")}`]),close(){a=!0,d()}}}
|
|
112
|
-
export{fo,mo,lt,go,S,_o,yo,Ln,wo,bo,vo,
|
|
112
|
+
export{fo,mo,lt,go,S,_o,yo,Ln,wo,bo,vo,zt,Mn,Ge,ut,$n,Bn};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{basename as ln}from"path";var gt=["production","staging"],un="https://api.reasonmachines.com",fn="https://staging-api.reasonmachines.com";var A={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},gn=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function _(n={}){let e=T(n.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(e){if(gt.includes(e))return e;throw Error(`Unknown Reason CLI channel: ${e}`)}let r=ln(n.executablePath??process.execPath).toLowerCase();return gn.has(r)?"staging":"production"}function
|
|
3
|
-
export{gt,_,
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{basename as ln}from"path";var gt=["production","staging"],un="https://api.reasonmachines.com",fn="https://staging-api.reasonmachines.com";var A={production:{api:"https://api.reasonmachines.ai",app:"https://reasonmachines.ai"},staging:{api:"https://staging-api.reasonmachines.ai",app:"https://staging.reasonmachines.ai"}},gn=new Set(["ara-staging","ara-staging.exe","reason-staging","reason-staging.exe"]);function _(n={}){let e=T(n.env??process.env,"REASON_CLI_CHANNEL")?.trim().toLowerCase();if(e){if(gt.includes(e))return e;throw Error(`Unknown Reason CLI channel: ${e}`)}let r=ln(n.executablePath??process.execPath).toLowerCase();return gn.has(r)?"staging":"production"}function er(n){return n==="staging"?fn:un}var U={production:["https://api.ara.so",A.production.api],staging:["https://api-staging.ara.so",A.staging.api]};function Zr(n){let e;try{e=new URL(n).origin}catch{return n}let r=gt.find((t)=>U[t].includes(e));return r?er(r):e}function Oo(n,e){return n===e||Zr(n)===Zr(e)}function Io(n,e){return gt.some((r)=>U[r].includes(n)&&e===er(r))}function Do(n,e){try{let r=new URL(e);return!r.username&&!r.password&&(r.origin===er(n)||r.origin===A[n].api)}catch{return!1}}function ei(n){try{let e=new URL(n).hostname.replace(/^\[|\]$/g,"").toLowerCase();return e==="localhost"||e==="127.0.0.1"||e==="::1"}catch{return!1}}import{randomBytes as J}from"crypto";import{chmodSync as q,closeSync as B,constants as bn,linkSync as V,lstatSync as w,mkdirSync as z,openSync as En,readdirSync as L,readFileSync as Wn,readlinkSync as v,renameSync as S,rmdirSync as Q,symlinkSync as N,unlinkSync as d}from"fs";import{createRequire as Nn}from"module";import{constants as Sn}from"os";import{basename as R,join as l,sep as kn}from"path";import{existsSync as O,lstatSync as j,readdirSync as pn,readFileSync as mn,readlinkSync as dn,realpathSync as yn}from"fs";import{join as m,sep as hn}from"path";function G(n,...e){let r=m(n,"ara"),t=m(n,"reason");if(!Xr(r))return m(t,...e);if(!O(t))return m(r,...e);return O(m(r,...e))&&!O(m(t,...e))?m(r,...e):m(t,...e)}function Xr(n){try{let e=j(n);if(!e.isSymbolicLink())return e.isDirectory();return dn(n)!=="reason"&&O(n)}catch{return!1}}function X(n,e=[]){if(!Xr(n))return!1;let r;try{r=[n,...pn(n,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>m(n,t.name))]}catch{return!1}return r.some((t)=>["connect","connect-once"].filter((i)=>!e.includes(m(t,i))).some((i)=>{let s=m(t,i,"worker.json");try{j(s)}catch{return!1}try{let a=JSON.parse(mn(s,"utf8"))?.stateDirectory;if(typeof a!=="string")return!0;let c=(o,u)=>o===u||o.startsWith(u+hn);return c(a,n)||c(M(a),M(n))}catch{return!0}}))}function M(n){try{return yn(n)}catch{return n}}var P=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),Z=new Set(["local-device.proxy.json"]),Cn=new Set(["local-device.key","local-device.binding"]),W=new Map;function _t(n,e,r){let t=l(n,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(n))return{state:p(t)?.isDirectory()?"kept":"absent"};return vn(t,l(n,"reason"),{linkAlways:!0,kept:(i)=>X(i,r??[]),native:e===void 0?An:()=>e},r!==void 0)}function ke(n,...e){return _t(n),G(n,...e)}var nn="config_rename_unavailable:busy";function vn(n,e,r,t=!1){let i=t?void 0:W.get(n);if(i)return i;let s;try{s=_n(n,e,r)}catch(a){let c=`config_rename_unavailable:${b(a)??"failed"}`;try{return{state:p(n)?.isDirectory()?"kept":"absent",problem:c}}catch{return{state:"kept",problem:c}}}if(!(s.state==="absent"&&r.linkAlways)&&s.problem!==nn&&!(s.state==="kept"&&!s.problem))W.set(n,s);return s}function _n(n,e,r){wn(e,r.native);let t=!1;for(let i=0;i<8;i+=1){let s=p(n);if(s?.isSymbolicLink())return v(n)===R(e)?{state:t?"renamed":"linked"}:{state:"kept"};if(!s){if(D(e))f(()=>d(e),"ENOENT");if(!(t||r.linkAlways)||!x(e))return{state:"absent"};let o=C(e,"link");N(R(e),o);try{f(()=>S(o,n),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{f(()=>d(o),"ENOENT")}continue}if(!s.isDirectory())return{state:"absent"};if(r.kept(n))return K(e),{state:"kept"};let a=r.native();if(!a)return K(e),{state:"kept",problem:"config_rename_unavailable:no_native"};let c=In(a,n);if(!c)return{state:"kept",problem:nn};try{if(w(n).isSymbolicLink())continue;let o=Rn(a,n,e);if(o)return{state:"kept",problem:o};t=!0}finally{c()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function Rn(n,e,r){let t=p(r);if(!t||D(r)){if(!t)N(R(r),r);try{n.exchange(e,r)}catch(o){if(D(r))f(()=>d(r),"ENOENT");return`config_rename_unavailable:${b(o)??"exchange_failed"}`}return null}if(!t.isDirectory())return"config_rename_unavailable:ENOTDIR";if(t.dev!==w(e).dev)return"config_rename_unavailable:EXDEV";let i=[C(r,"probe"),C(r,"probe")];try{N("a",i[0]),N("b",i[1]),n.exchange(i[0],i[1])}catch(o){return`config_rename_unavailable:${b(o)??"exchange_failed"}`}finally{for(let o of i)f(()=>d(o),"ENOENT")}let s=cn(r);for(let o of Cn){let u=p(l(r,o)),g=p(l(e,o));if(u&&g&&u.ino!==g.ino)z(`${s}-replaced`,{mode:448,recursive:!0}),S(l(r,o),l(`${s}-replaced`,o))}let a={linked:new Map,unitsKept:new Set};rn(e,r,"",a);let c=C(r,"rename");N(R(r),c);try{n.exchange(e,c)}catch(o){return f(()=>d(c),"ENOENT"),`config_rename_unavailable:${b(o)??"exchange_failed"}`}return tn(c,r,a,s),null}function en(n){return n===""||!n.includes(kn)}function rn(n,e,r,t){let i=en(r)&&sn(l(e,r),l(n,r));if(i)t.unitsKept.add(r);for(let s of L(l(n,r))){if(i&&(P.has(s)||Z.has(s)))continue;let a=l(r,s),c=l(n,a),o=l(e,a),u=p(c);if(!u)continue;let g=p(o);if(u.isDirectory()){if(!g)f(()=>z(o,{mode:u.mode&4095}),"EEXIST"),q(o,u.mode&4095);if(x(o))rn(n,e,a,t)}else if(!g){if(u.isSymbolicLink())f(()=>N(v(c),o),"EEXIST");else if(f(()=>V(c,o),"EEXIST","ENOENT"))t.linked.set(a,u.ino)}}}function wn(n,e){let r;try{if(!x(n))return;r=L(n)}catch{return}for(let t of r){let i=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(t);if(!i)continue;let s=l(n,t),a=p(s);if(!a)continue;if(!a.isDirectory()){if(!Y(Number(i[2])))f(()=>d(s),"ENOENT");continue}let c=e(),o=null;if(c){try{o=c.lock(s)}catch{continue}if(!o)continue}else if(Y(Number(i[2])))continue;try{let u=C(n,"claim");if(f(()=>S(s,u),"ENOENT"))tn(u,n,null,cn(n))}finally{o?.()}}}function tn(n,e,r,t){for(let[i,s]of r?.linked??[])if(!p(l(n,i))&&p(l(e,i))?.ino===s)f(()=>d(l(e,i)),"ENOENT");if(on(n,e,"",r),f(()=>Q(n),"ENOTEMPTY","EEXIST"))return;S(n,t),q(t,448)}function on(n,e,r,t){let i=en(r)&&(t?t.unitsKept.has(r):sn(l(e,r),l(n,r)));for(let s of L(l(n,r))){let a=l(r,s),c=l(n,a),o=l(e,a),u=w(c),g=p(o);if(g&&u.ino===g.ino&&u.dev===g.dev){d(c);continue}if(u.isFile()&&g?.isFile()&&t?.linked.get(a)===g.ino){S(c,o);continue}if(i&&(P.has(s)||Z.has(s)))continue;if(!g){if(u.isFile()){if(f(()=>V(c,o),"EEXIST"))d(c)}else f(()=>S(c,o),"EEXIST","ENOTEMPTY");continue}if(u.isDirectory()&&g.isDirectory())on(n,e,a,t),f(()=>Q(c),"ENOTEMPTY","EEXIST")}}function sn(n,e){for(let r of P)if(an(l(n,r),l(e,r)))return!0;return!1}function an(n,e){let r=p(n);if(!r)return!1;let t=p(e);if(!t)return!0;if(r.isDirectory()){if(!t.isDirectory())return!0;return L(n).some((i)=>an(l(n,i),l(e,i)))}if(r.isSymbolicLink())return!t.isSymbolicLink()||v(n)!==v(e);return r.ino!==t.ino||r.dev!==t.dev}function K(n){if(D(n))f(()=>d(n),"ENOENT")}function cn(n){return l(n,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${J(3).toString("hex")}`)}function D(n){try{return w(n).isSymbolicLink()&&v(n)===R(n)}catch{return!1}}function x(n){let e=p(n);return e!==null&&e.isDirectory()}function In(n,e){for(let r=0;r<40;r+=1){let t=n.lock(e);if(t)return t;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function C(n,e){return l(n,`.${e}-${process.pid}-${J(6).toString("hex")}`)}function Y(n){if(n===process.pid)return!1;try{return process.kill(n,0),!0}catch(e){return b(e)==="EPERM"}}function p(n){try{return w(n)}catch(e){if(b(e)==="ENOENT"||b(e)==="ENOTDIR")return null;throw e}}function f(n,...e){try{return n(),!0}catch(r){if(e.includes(b(r)??""))return!1;throw r}}function b(n){return n instanceof Error&&"code"in n&&typeof n.code==="string"?n.code:void 0}var k,On=2,Dn=4,Ln=2,Tn=2,H=-100;function An(){if(k!==void 0)return k;if(k=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let n;try{n=Nn(import.meta.url)("bun:ffi")}catch{return null}let e=process.platform==="darwin",r=e?"__error":"__errno_location",t=e?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:i}=n;for(let s of t)try{let a=e?"renamex_np":"renameat2",o=n.dlopen(s,{flock:{args:[i.i32,i.i32],returns:i.i32},[r]:{args:[],returns:i.ptr},[a]:e?{args:[i.ptr,i.ptr,i.u32],returns:i.i32}:{args:[i.i32,i.ptr,i.i32,i.ptr,i.u32],returns:i.i32}}).symbols,u=o[r]();if(u===null)continue;let g=(E)=>{let h=n.read.i32(u),y=Object.entries(Sn.errno).find(([,I])=>I===h)?.[0]??`errno_${h}`;return Object.assign(Error(`${E} failed: ${y}`),{code:y})},F=(E)=>Buffer.from(`${E}\x00`,"utf8");return k={exchange(E,h){let y=F(E),I=F(h);if((e?o[a](n.ptr(y),n.ptr(I),Ln):o[a](H,n.ptr(y),H,n.ptr(I),Tn))!==0)throw g("exchange")},lock(E){let h=En(E,bn.O_RDONLY);if(o.flock(h,On|Dn)===0)return()=>B(h);let y=g("lock");if(B(h),y.code==="EWOULDBLOCK"||y.code==="EAGAIN")return null;throw y}},k}catch{}return null}
|
|
3
|
+
export{gt,_,er,Zr,Oo,Io,Do,ei,Xr,_t,ke};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Yr,Qr,en,
|
|
2
|
+
import{Yr,Qr,en,nr}from"./vm-hands-entry-lite-3krzmhkk.js";import{Eo,xo,P,$r,Br,Un,pt,Hn,Fr,Je,Se,zn,Ze,ne,Xe,Ee,Zt,jr,Ur,Wn}from"./vm-hands-entry-lite-5zdybh8s.js";import{sr}from"./vm-hands-entry-lite-rfz60hb3.js";import{Kt}from"./vm-hands-entry-lite-wrvz9jxy.js";import{ve}from"./vm-hands-entry-lite-txd50spx.js";var r=["cgroup_membership_read_failed","cgroup_v2_membership_absent","cgroup_scope_invalid","cgroup_root_unavailable","cgroup_directory_unavailable","cgroup_limit_read_failed","cgroup_events_read_failed","cgroup_current_read_failed","cgroup_stat_read_failed","boot_id_read_failed","boot_id_invalid","guest_meminfo_read_failed","guest_vmstat_read_failed","memory_counter_invalid","memory_field_missing","memory_capacity_invalid"];var o=String.raw`(function(fs, path) {
|
|
3
3
|
const fail = (message, reasonCode) => { throw Object.assign(Error(message), {reasonCode}); };
|
|
4
4
|
const read = (p, reasonCode, trim=true) => { try { const text=fs.readFileSync(p, "utf8"); return trim?text.trim():text; }
|
|
5
5
|
catch { fail("memory_read", reasonCode); } };
|
|
@@ -309,7 +309,7 @@ function fileOperation(request) {
|
|
|
309
309
|
});
|
|
310
310
|
return { promise, cancel() {} };
|
|
311
311
|
}
|
|
312
|
-
`;var s="a3e39eb55160acfc116fa9871ccc594c68be7a642d2331b24baa707c8f601ec0";import{createHash as I}from"crypto";var H=Object.freeze({"api.ara.so":"api.reasonmachines.com","api.reasonmachines.ai":"api.reasonmachines.com","api-staging.ara.so":"staging-api.reasonmachines.com","staging-api.reasonmachines.ai":"staging-api.reasonmachines.com"});var a=Object.freeze({trailingSlashPattern:/\/+$/.source,keyPrefix:"http.",keySuffix:"/.extraheader",valuePrefix:"Authorization: Bearer "});var c=Object.freeze({tokenEnv:"ARA_GIT_BROKER_TOKEN",reasonTokenEnv:"REASON_GIT_BROKER_TOKEN",urlEnv:"ARA_GIT_BROKER_URL",keyPrefix:"credential.",keySuffix:"/.helper",value:'!f(){ printf "username=%s\\npassword=%s\\n" "ara-run" "${REASON_GIT_BROKER_TOKEN:-$ARA_GIT_BROKER_TOKEN}"; };f'});var
|
|
312
|
+
`;var s="a3e39eb55160acfc116fa9871ccc594c68be7a642d2331b24baa707c8f601ec0";import{createHash as I}from"crypto";var H=Object.freeze({"api.ara.so":"api.reasonmachines.com","api.reasonmachines.ai":"api.reasonmachines.com","api-staging.ara.so":"staging-api.reasonmachines.com","staging-api.reasonmachines.ai":"staging-api.reasonmachines.com"});var a=Object.freeze({trailingSlashPattern:/\/+$/.source,keyPrefix:"http.",keySuffix:"/.extraheader",valuePrefix:"Authorization: Bearer "});var c=Object.freeze({tokenEnv:"ARA_GIT_BROKER_TOKEN",reasonTokenEnv:"REASON_GIT_BROKER_TOKEN",urlEnv:"ARA_GIT_BROKER_URL",keyPrefix:"credential.",keySuffix:"/.helper",value:'!f(){ printf "username=%s\\npassword=%s\\n" "ara-run" "${REASON_GIT_BROKER_TOKEN:-$ARA_GIT_BROKER_TOKEN}"; };f'});var It=/^[A-Za-z_][A-Za-z0-9_]*$/;var h=new Set(["ARA_INFERENCE_TOKEN","AI_GATEWAY_API_KEY","CLOUD_AGENT_AI_GATEWAY_API_KEY","INFERENCE_V2_GATEWAY_API_KEY","VERCEL_AI_GATEWAY_API_KEY","INFERENCE_V2_CONCENTRATE_API_KEY","INFERENCE_V2_OPENAI_API_KEY","INFERENCE_V2_ANTHROPIC_API_KEY","INFERENCE_V2_FINGERPRINT_SECRET","OPENAI_API_KEY","OPENROUTER_API_KEY","ANTHROPIC_API_KEY","CODEX_ACCESS_TOKEN","GITHUB_COPILOT_API_KEY","AZURE_OPENAI_API_KEY","AZURE_OPENAI_CLIENT_SECRET"]),m=new Set(["ARA_OPERATOR_KEY","BL_API_KEY","BLAXEL_API_KEY","NSC_TOKEN","NSC_TOKEN_FILE","NAMESPACE_API_KEY","NAMESPACE_ACCESS_TOKEN","NAMESPACE_TOKEN","NAMESPACE_TOKEN_JSON","NAMESPACE_SANDBOX_TOKEN_JSON","ARA_LOCAL_QA_NAMESPACE_WORKLOAD_TOKEN_FILE","NAMESPACE_SANDBOX_USE_LOCAL_USER_TOKEN","COMPUTE_SERVICE_TOKEN"]),g=["INFISICAL_","NSC_"],_=new Set(["ARA_JOB_ENV","ARA_DELIVERY_BASE_SHA","WORK_ROOT","REPO_DIR","ARA_CONTROL_DIR","ARA_PRESERVE_WORKSPACE","ARA_PINNED_CHECKOUT_REUSE","FOLLOWUP_BRANCH","REPO_URL","TOKENLESS_URL","REPOSITORY_IDENTITY_URL","DEFAULT_BRANCH","BRANCH","BRANCH_GENERATED","BASE_REF","REPO_EMPTY","REPO_WRITABLE","ARA_DELIVERY_BASE_BRANCH","ARA_SERVER_GIT_PUBLICATION","ARA_EMPTY_REPOSITORY_COMMIT","REASON_MODEL","REASON_DELIVERY_BASE_BRANCH","REASON_DELIVERY_BASE_SHA","REASON_EMPTY_REPOSITORY_COMMIT","REASON_SCRATCH_SESSION_ID","REASON_SERVER_GIT_PUBLICATION","REASON_ALLOW_INSTALL_SCRIPTS","SCM_TOKEN","SCM_TOKEN_USER","REASON_OIDC_TOKEN_URL","REASON_OIDC_REQUEST_TOKEN","AWS_CONTAINER_CREDENTIALS_FULL_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN","AWS_CONTAINER_CREDENTIALS_RELATIVE_URI","AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE","BASH_ENV","ENV","BASHOPTS","SHELLOPTS","PS4","IFS","CDPATH","GLOBIGNORE","PROMPT_COMMAND","PATH","HOME","TMPDIR","TMP","TEMP","XDG_CONFIG_HOME","GIT_DIR","GIT_WORK_TREE","GIT_INDEX_FILE","GIT_OBJECT_DIRECTORY","GIT_COMMON_DIR","GIT_NAMESPACE","GIT_CEILING_DIRECTORIES","GIT_DISCOVERY_ACROSS_FILESYSTEM","GIT_SHALLOW_FILE","GIT_ALLOW_PROTOCOL","GIT_PROTOCOL_FROM_USER","GIT_REPLACE_REF_BASE","NODE_OPTIONS","NODE_PATH","NODE_REPL_EXTERNAL_MODULES","CLASSPATH","PYTHONPATH","PYTHONSTARTUP","PYTHONHOME","RUBYOPT","RUBYLIB","PERL5LIB","PERL5OPT","JAVA_TOOL_OPTIONS","_JAVA_OPTIONS","JDK_JAVA_OPTIONS","GEM_PATH","GEM_HOME","GIT_SSH","GIT_SSH_COMMAND","GIT_EXEC_PATH","GIT_TEMPLATE_DIR","GIT_ALTERNATE_OBJECT_DIRECTORIES","GIT_PROXY_COMMAND","GIT_EXTERNAL_DIFF","GIT_PAGER","GIT_EDITOR","GIT_ASKPASS","SSH_ASKPASS","PAGER","EDITOR","TAR_OPTIONS","CURL_HOME","WGETRC","APT_CONFIG","PERLLIB","GIT_GRAFT_FILE","POSIXLY_CORRECT"]),y=["GIT_TRACE","CONTEXT_REPO_","ARA_CHECKPOINT_BOOTSTRAP_","_","ARA_HANDS_","ARA_DEVICE_","ARA_GIT_BROKER_","REASON_HANDS_","REASON_DEVICE_","REASON_GIT_BROKER_","LD_","DYLD_","GIT_CONFIG","BASH_FUNC_"];var t="^(?!(?:"+[...h,...m,..._].join("|")+")$)(?!(?:"+[...g,...y].join("|")+"))"+It.source.slice(1),W=new RegExp(t);var v=["HOME","PWD","OLDPWD","TMPDIR","TMP","TEMP","SHELL","USER","LOGNAME","SCM_TOKEN","SCM_TOKEN_USER","GH_TOKEN","GITHUB_TOKEN","GH_ENTERPRISE_TOKEN","GITHUB_ENTERPRISE_TOKEN","GITLAB_TOKEN"],E=["ARA_HANDS_","ARA_DEVICE_","ARA_GIT_BROKER_","REASON_HANDS_","REASON_DEVICE_","REASON_GIT_BROKER_","BUN_"],S="^(?!(?:"+v.join("|")+")$)(?!(?:"+E.join("|")+"))"+t.slice(1),w="ARA_DELIVERY_BASE_SHA|WORK_ROOT|FOLLOWUP_BRANCH|ARA_PRESERVE_WORKSPACE|ARA_PINNED_CHECKOUT_REUSE|CONTEXT_REPO_[A-Z0-9_]+|REPO_URL|TOKENLESS_URL|REPOSITORY_IDENTITY_URL|DEFAULT_BRANCH|BRANCH|BRANCH_GENERATED|BASE_REF|REPO_EMPTY|REPO_WRITABLE|ARA_DELIVERY_BASE_BRANCH|ARA_SERVER_GIT_PUBLICATION|ARA_EMPTY_REPOSITORY_COMMIT|REASON_MODEL|REASON_DELIVERY_BASE_BRANCH|REASON_DELIVERY_BASE_SHA|REASON_EMPTY_REPOSITORY_COMMIT|REASON_SCRATCH_SESSION_ID|REASON_SERVER_GIT_PUBLICATION|REASON_ALLOW_INSTALL_SCRIPTS",n="^(?:"+w+"|"+S.slice(1,-1)+")$",O=new RegExp(n);function kr(u){return O.test(u)}var st=Object.freeze({tokenPath:"/identity/token",awsPath:"/identity/aws",tokenPattern:/^[A-Za-z0-9_.~-]+$/.source}),V=Object.freeze({variables:256,valueBytes:130816,snapshotBytes:1048576}),Z=Object.freeze({valueChars:16384,snapshotBytes:65536});var l=["set -g history-limit 50000","set -g status off","set -g window-size smallest","set -gq fill-character ' '","set -g escape-time 10","set -g prefix None","set -g prefix2 None","set -g terminal-overrides ',*:smcup@:rmcup@'"];var D=2,R="ara-hands-worker.cjs",d=["/usr/local/go/bin","/opt/node/bin","/usr/local/bin","/usr/sbin","/usr/bin","/sbin","/bin","/usr/local/cargo/bin"],A=d.join(":"),T=["/opt/homebrew/bin",...d].join(":"),k='(platform, linuxPath, macosPath) => platform === "darwin" ? macosPath : linuxPath';var N=String.raw`(function(anchor, pid, native) {
|
|
313
313
|
const token = native.identity(pid);
|
|
314
314
|
const session = native.session(pid);
|
|
315
315
|
if (!native.same(anchor)) throw new Error("pty_session_identity_lost");
|
|
@@ -369,7 +369,7 @@ const GUEST_MEMORY_UNAVAILABLE_REASONS = ${JSON.stringify(r)};
|
|
|
369
369
|
const sampleGuestMemory = ${o};
|
|
370
370
|
const inspectMacPtyMember = ${N};
|
|
371
371
|
const probeLinuxPtyLibrary = ${C};
|
|
372
|
-
const windowsPtyApi = ${
|
|
372
|
+
const windowsPtyApi = ${Kt};
|
|
373
373
|
const LINUX_PTY_EXEC_SOURCE = ${JSON.stringify(x)};
|
|
374
374
|
const CLOSE_CODES = ${JSON.stringify(Ur)};
|
|
375
375
|
const SHA256_RE = /^[0-9a-f]{64}$/;
|
|
@@ -395,7 +395,7 @@ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
|
|
|
395
395
|
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
396
396
|
const WINDOWS = process.platform === "win32";
|
|
397
397
|
// Each Bash leader's tree on Windows, children that outlive it included (shared/windows-job-object.ts).
|
|
398
|
-
const windowsJobs = WINDOWS ? ${
|
|
398
|
+
const windowsJobs = WINDOWS ? ${sr}(require) : null;
|
|
399
399
|
/** Windows has no POSIX owner or mode bits: the user's own profile folders are
|
|
400
400
|
* private by their ACLs, and the worker runs as that ordinary user. */
|
|
401
401
|
function ownedPrivately(stat, mask = 0o077) {
|
|
@@ -577,7 +577,7 @@ function validJobEnvSourcePath() {
|
|
|
577
577
|
if (config.jobEnvSourcePath === undefined || config.jobEnvSourcePath === path.join(config.workRoot, "job.env")) return true;
|
|
578
578
|
// A cloud workspace's job.env is in its Session's root-only control
|
|
579
579
|
// directory (shared/device-workspace.ts), derived from the root alone.
|
|
580
|
-
const cloud = new RegExp(${JSON.stringify(
|
|
580
|
+
const cloud = new RegExp(${JSON.stringify(nr.source)}).exec(config.workRoot);
|
|
581
581
|
if (process.platform === "linux" && cloud) {
|
|
582
582
|
const workspaceId = cloud[3];
|
|
583
583
|
const owner = (new RegExp(${JSON.stringify(Qr.source)}).exec(workspaceId) || [])[1]
|
|
@@ -2347,7 +2347,7 @@ function windowsPtyOperation(request, managed) {
|
|
|
2347
2347
|
try {
|
|
2348
2348
|
if (pty.activeProcesses() > 0) pty.terminate();
|
|
2349
2349
|
for (const startedAt = Date.now(); pty.activeProcesses() > 0;) {
|
|
2350
|
-
if (Date.now() - startedAt > ${
|
|
2350
|
+
if (Date.now() - startedAt > ${Zt}) throw new Error("pty_cleanup_timeout");
|
|
2351
2351
|
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
2352
2352
|
}
|
|
2353
2353
|
pty.close();
|
|
@@ -2795,7 +2795,7 @@ function ptyOperation(request, managed, program = TERMINAL_SHELL) {
|
|
|
2795
2795
|
const { members, empty } = native.session(anchor, device);
|
|
2796
2796
|
try {
|
|
2797
2797
|
if (empty && exitCode !== null && subreaper) break;
|
|
2798
|
-
if (Date.now() - startedAt > ${
|
|
2798
|
+
if (Date.now() - startedAt > ${Zt}) throw new Error("pty_cleanup_timeout");
|
|
2799
2799
|
for (const token of members) {
|
|
2800
2800
|
if (!native.same(anchor)) throw new Error("pty_session_identity_lost");
|
|
2801
2801
|
const id = native.identityKey(token);
|
|
@@ -4177,4 +4177,4 @@ void startJobControl().then(() => {
|
|
|
4177
4177
|
if (validPrivateJob) markReady(); else connect();
|
|
4178
4178
|
}, () => process.exit(45));
|
|
4179
4179
|
`.trimStart();var b=I("sha256").update(Yo,"utf8").digest("hex");
|
|
4180
|
-
export{
|
|
4180
|
+
export{It,kr,st,V,D,R,Yo,b};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-lite-
|
|
2
|
+
import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-lite-k83rkcys.js";import{Kr,Yn,Jr,Qn}from"./vm-hands-entry-lite-abfb6nms.js";import{Zn,Yt,Ro}from"./vm-hands-entry-lite-1y629eqh.js";import{C}from"./vm-hands-entry-lite-vdhgwmmp.js";import{spawnSync as y}from"child_process";import{createHash as ke,randomUUID as Se}from"crypto";import{chmodSync as we,existsSync as P,mkdirSync as $e,readdirSync as Ve,readFileSync as p,renameSync as ye,rmSync as u,statSync as ve,writeFileSync as be}from"fs";import{dirname as We,isAbsolute as q,join as g}from"path";import{spawnSync as de}from"child_process";import{readFileSync as me}from"fs";import{userInfo as D}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function H(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function M(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function K(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[M(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function A(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${D().username}`:D().username}function U(r){let e=A(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
|
|
3
3
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
4
4
|
<RegistrationInfo>
|
|
5
5
|
<Description>${A(r.description)}</Description>
|
|
@@ -42,12 +42,12 @@ import{T}from"./vm-hands-entry-lite-fcvf8md1.js";import{_}from"./vm-hands-entry-
|
|
|
42
42
|
`)}function j(r,e){return["/Create","/TN",r,"/XML",e,"/F"]}function I(r){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}function x(r){return`'*${M(r).replaceAll("'","''")}*'`}function E(r,e){return I(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${x(r)} })`,...e.keepWrapper?[]:["foreach ($w in $wrappers) { Stop-Process -Id $w.ProcessId -Force -ErrorAction SilentlyContinue }"],`foreach ($w in $wrappers) { $all | ? { $_.ParentProcessId -eq $w.ProcessId } | % { taskkill.exe /F ${e.tree?"/T ":""}/PID $_.ProcessId | Out-Null } }`].join(`
|
|
43
43
|
`))}function F(r){return I(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${x(r)} })`,"foreach ($w in $wrappers) { if ($all | ? { $_.ParentProcessId -eq $w.ProcessId -and $_.Name -ne 'conhost.exe' }) { 'running'; exit 0 } }","exit 1"].join(`
|
|
44
44
|
`))}function X(r,e=process.pid){let n=de(C("powershell.exe"),I(["$all = @{}; Get-CimInstance Win32_Process | % { $all[[int]$_.ProcessId] = $_ }",`$p = $all[${Math.trunc(e)}]`,"for ($i = 0; $p -and $i -lt 64; $i++) {",` if ($p.CommandLine -like ${x(r)}) { exit 10 }`," $n = $all[[int]$p.ParentProcessId]"," if (-not $n -or $n.ProcessId -eq $p.ProcessId -or $n.CreationDate -gt $p.CreationDate) { exit 11 }"," $p = $n","}","exit 11"].join(`
|
|
45
|
-
`)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var qr="REASON_WORKER_SERVICE",Ae="worker_identity_unavailable";function xe(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>y(C(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=y(C(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>Ro(r,e),insideService:(e,n)=>Ie(e,process.platform,process.getuid?.(),n)}}function Ie(r,e,n,t=!0){if(process.env[qr]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return p("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return X(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=y("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Ee)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=y("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var Ee=113;class J extends Error{code;constructor(r,e){super(r);this.code=e}}function Kn(r,e){if(!re(r.home,r.platform))throw new J(ee);if(r.platform==="darwin")k(r);let n=Qn(Kr(e,r.home)),t=_({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?Yn(n):null,T(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?g(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):g(r.home,".local","bin",i)];for(let a of s)try{if(a&&q(a)&&ve(a).isFile())return Jr(a)}catch{}throw new J(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var R=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,w=new RegExp(`(\\n\\s*<key>${
|
|
45
|
+
`)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var qr="REASON_WORKER_SERVICE",Ae="worker_identity_unavailable";function xe(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>y(C(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=y(C(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>Ro(r,e),insideService:(e,n)=>Ie(e,process.platform,process.getuid?.(),n)}}function Ie(r,e,n,t=!0){if(process.env[qr]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return p("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return X(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=y("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Ee)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=y("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var Ee=113;class J extends Error{code;constructor(r,e){super(r);this.code=e}}function Kn(r,e){if(!re(r.home,r.platform))throw new J(ee);if(r.platform==="darwin")k(r);let n=Qn(Kr(e,r.home)),t=_({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?Yn(n):null,T(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?g(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):g(r.home,".local","bin",i)];for(let a of s)try{if(a&&q(a)&&ve(a).isFile())return Jr(a)}catch{}throw new J(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var R=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,w=new RegExp(`(\\n\\s*<key>${Yt}</key>\\s*<string>)[^<]*(</string>)`),_e=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Te(r){return r.replaceAll("<","<").replaceAll(">",">").replaceAll(""",'"').replaceAll("'","'").replaceAll("&","&")}function Y(r){let e=[...(R.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Te(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function z(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function h(r){return r.map((e)=>` <string>${d(e)}</string>`).join(`
|
|
46
46
|
`)}function Z(r,e){let n;try{n=p(r,"utf8")}catch{return null}let t=Y(n);if(!t)return null;let i=q(t.launcher)?Jr(t.launcher):t.launcher,{program:s,identity:a}=z(i,t.args,e),o=n.replace(R,(l,c,m,O)=>`${c}${h(s)}
|
|
47
47
|
${O}`);if(!a)o=o.replace(w,"");else if(w.test(o))o=o.replace(w,(l,c,m)=>`${c}${d(a.app)}${m}`);else o=o.replace(_e,(l,c,m)=>`${c}
|
|
48
|
-
<key>${
|
|
48
|
+
<key>${Yt}</key>
|
|
49
49
|
<string>${d(a.app)}</string>${m}`);return o===n?null:o}function Pe(r,e){let n=Z(r,e);if(n!==null)W(r,n)}function Fs(r,e,n){if(e.platform!=="darwin")return!1;let t=Ye(r,e,n);return t!==null&&Z(t.definition,e)!==null}var b="com.reasonmachines.worker.",N="so.reason.worker.",Q=[b,N];function ko(r,e=b){return`${e}connect${r==="production"?"":`.${r}`}`}function js(r,e){return Q.some((n)=>r===ko(e,n))}function Re(r,e,n){if(e==="connect")return ko(r.channel,n);let t=ke("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var ee="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function re(r,e){if(e==="darwin")return{directory:g(r,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:g(r,".config","systemd","user"),suffix:".service"};if(e==="win32")return{directory:H(r),suffix:".xml"};return null}function f(r,e,n,t=b){let i=Re(r,n,t),s=re(e.home,e.platform);if(!s)return null;return{label:i,definition:g(s.directory,`${i}${s.suffix}`),logs:e.platform==="linux"?`journalctl --user -u ${i}.service`:g(r.stateDirectory,"service.log")}}function Ye(r,e,n="serve"){return ne(r,e,n)[0]??null}function ne(r,e,n){return Q.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&P(t.definition))}function te(r,e,n){let t=f(r,e,n,N);return t&&P(t.definition)?t:null}function rs(r,e,n){let t=f(r,e,n),i=te(r,e,n);if(!t||!i||!P(t.definition)||e.insideService?.(i.label))return null;if(!Ce(t,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);return u(i.definition,{force:!0}),"retired"}if(e.platform==="win32")return v(i,e,!0),"retired";return e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Ce(r,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`])===0;if(e.platform==="win32")return e.command("schtasks",["/Query","/TN",r.label])===0;let n=`${r.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",n])===0&&he.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var he=new Set(["active","activating","reloading"]);function Jn(r,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let n=e.read("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(n??"")?.[1]??0)>0}if(e.platform==="win32")return e.read("powershell.exe",F(r.label))?.trim()==="running";return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${r.label}.service`])?.trim()??0)>0}function Us(r){let{config:e,launcher:n,host:t,kind:i}=r,s=f(e,t,i);if(!s)return!1;let a;try{a=t.platform==="win32"?V(s.definition):p(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===se(e,i,s,n);if(t.platform!=="darwin")return a===oe(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(w,"").replace(R,(c,m,O,ue)=>`${m}${o?`${h([o.launcher,...o.args])}
|
|
50
|
-
`:""}${ue}`)===ie(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function L(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function G(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new J("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function ie(r,e,n,t,i,s){let a=L(r,e),o=z(t,a.args,i),l={HOME:i.home,PATH:s,[qr]:n.label,...a.environment,...o.identity?{[
|
|
50
|
+
`:""}${ue}`)===ie(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function L(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function G(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new J("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function ie(r,e,n,t,i,s){let a=L(r,e),o=z(t,a.args,i),l={HOME:i.home,PATH:s,[qr]:n.label,...a.environment,...o.identity?{[Yt]:o.identity.app}:{}};return{identity:o.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
|
|
51
51
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
52
52
|
<plist version="1.0">
|
|
53
53
|
<dict>
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We,co,F,Ve,
|
|
2
|
+
import{We,co,F,Ve,Ft,Tr,x}from"./vm-hands-entry-lite-4x8j1xp9.js";import{K}from"./vm-hands-entry-lite-r3yp6cr9.js";import{ut}from"./vm-hands-entry-lite-jyvmw8b7.js";import{ft}from"./vm-hands-entry-lite-1y629eqh.js";import{Rr}from"./vm-hands-entry-lite-x9wy77vd.js";import{xt,Li}from"./vm-hands-entry-lite-7ja63pfz.js";import{G,qe}from"./vm-hands-entry-lite-0yj63trb.js";import{xe,Kn}from"./vm-hands-entry-lite-m753n72c.js";import{vt}from"./vm-hands-entry-lite-b8yapqfn.js";import{a}from"./vm-hands-entry-lite-cf1x5cbr.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-vdhgwmmp.js";import{spawn as R,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as M,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as U,readFileSync as X,readlinkSync as dt,renameSync as he,rmSync as pt,statSync as mt,writeFileSync as gt}from"fs";import{connect as ht}from"net";import{tmpdir as L,userInfo as we}from"os";import{basename as le,delimiter as wt,dirname as B,join as f}from"path";var z=`import { spawn, execFileSync } from "node:child_process";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { readFileSync, readlinkSync, lstatSync, realpathSync, statSync, mkdtempSync, mkdirSync, chmodSync, writeFileSync, readdirSync, rmSync, openSync, readSync, closeSync, renameSync } from "node:fs";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
@@ -854,7 +854,7 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
|
|
|
854
854
|
process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
|
|
855
855
|
}
|
|
856
856
|
}
|
|
857
|
-
`;import{spawn as Te}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var De="__desktop-call",Me="/usr/bin/setpriv",Ue=27262976,Le=8192,$e=2000;function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],De]}function Ge(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function
|
|
857
|
+
`;import{spawn as Te}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var De="__desktop-call",Me="/usr/bin/setpriv",Ue=27262976,Le=8192,$e=2000;function W(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function Be(e){try{return JSON.parse(e)}catch{return null}}function Fe(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],De]}function Ge(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Mt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{Ge(e)}catch{}let s=n.command??Fe();return new Promise((i,u)=>{let c=(n.spawnProcess??Te)(Me,[`--reuid=${e.uid}`,`--regid=${e.gid}`,"--clear-groups","--no-new-privs","--",...s],{cwd:e.home,detached:!0,stdio:["pipe","pipe","pipe"],env:{HOME:e.home,USER:e.username,LOGNAME:e.username,PATH:"/usr/local/bin:/usr/bin:/bin"}}),d=[],m=0,l="",p=null,g=!1,h,y=(_)=>{try{process.kill(-c.pid,_)}catch{c.kill(_)}},I=(_)=>{p??=_,y("SIGTERM"),h??=setTimeout(()=>y("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(_)=>{if(g)return;g=!0,clearTimeout(h),t.removeEventListener("abort",S),_()};if(c.stdout.on("data",(_)=>{if(m+=_.byteLength,m>Ue)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(_)}),c.stderr.setEncoding("utf8").on("data",(_)=>{l=(l+_).slice(-Le)}),c.stdin.on("error",()=>{}),c.once("error",()=>w(()=>u(p??new r("desktop_delegate_unavailable","Reason could not start its desktop as the desktop account.")))),c.once("close",(_,Ee)=>w(()=>{if(p)return u(p);let b=Be(Buffer.concat(d).toString("utf8"));if(W(b)&&b.ok===!0&&W(b.result))return i(b.result);let O=W(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${_??Ee}${O?"":" with no reply"}`,Y=l.trim().split(`
|
|
858
858
|
`).at(-1)?.slice(-300)??"";if(!O||O.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
|
|
859
|
-
`);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Lt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Kn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>ut(e,o),tile:Rr,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(co,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,_t=18874368,yt=8192,bt=65536,St=55000,kt=60000,Rt=4,It=40000,Ot=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function _e(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==vt||t.kind!=="browser")||JSON.stringify(t).length>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Ot.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Et="__computer-use";function Os(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Ct(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pt=33554432;function Dt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Nt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Dt(await Ct(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(mt(m).size>Pt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Mt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Mt(e.nativeHost,o,{socketDir:Tt(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Ut(e,o,t=a(),n=Bt){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&M(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((h)=>d(h)===l),instance:p,socket:g}))}async function $t(e,o,t=a(),n=Bt){let s=(await Ut(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var q=new Map;function H(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function Wt(e,o){if(await pe(e))return;if(pt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(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");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let h=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let y=lt(u,"a",384);c=ct(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"}}),at(y)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Is(e){await ve(e,!0)}function Ds(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!qt(e.automation))return e.automation;if(!Ft(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function qt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function Ft(e){let o;try{o=dt(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function ve(e,o){xt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...Gt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Et};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await H("bus",()=>Wt(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Gt(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(wt)}}async function Ht(e,o,t){let n=we().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await $t(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;gt(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,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.")),St),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>_t)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(-yt)}),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 Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=Rt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Ns(e,o){let t=_e({call:e});if(!("call"in t))D();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Tn(e,o={}){let t=_e(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??ft)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=await Li(e.runId,e.signal,o.now),p="account"in o?o.account??null:K(),g;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),g=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(p)g=await(o.delegate??Q)(p,t.call,e.signal);else g=await Ae(s,t.call,e.signal,o)}finally{l()}if(i)g=await ie({runId:e.runId,call:t.call,identity:u,output:g,signal:e.signal},c);return fe(g,e.runId,n)}
|
|
860
|
-
export{
|
|
859
|
+
`);if(O)return u(O);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Mt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as je}from"child_process";import{closeSync as Xe,mkdirSync as Ke,openSync as Je}from"fs";import{dirname as E,join as Ye}from"path";import{promisify as ze}from"util";var Ze=ze(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,A=new Map;function T(e,o){let t=A.get(e);if(t?.has(o))return!1;if(!t){if(A.size>=et)A.delete(A.keys().next().value);t=new Set,A.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Kn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>ut(e,o),tile:Rr,installDesktop:tt},te=!1;async function oe(e,o,t){try{await o.open(["-a","Google Chrome",e],t)}catch{t.throwIfAborted(),await o.open([e],t)}}async function ne(e,o,t,n){if(await t.open([Qe[o]],n).catch(()=>{}),e[0]&&!n.aborted)t.tile(E(E(E(e[0]))),o)}async function ot(e,o,t,n,s){for(let i of t){if(!T(e,`grant:${i}`))continue;s.throwIfAborted(),await n.request(o,i).catch(()=>null),await ne(o,i,n,s)}}var rt={name:"open_tab",description:"Open a web page in the user's own Chrome on this Mac. Reason cannot read, screenshot or click in that tab, and no tab_id is returned: browser control needs Reason's Chrome extension. An actual browser call opens its setup page.",inputSchema:{type:"object",properties:{url:{type:"string",description:"An http or https URL."}},required:["url"],additionalProperties:!1}};function re(e){return{code:0,stderr:"",stdout:Buffer.from(JSON.stringify({ok:!0,...e}))}}function nt(e){if(typeof e!=="string")return null;try{let o=new URL(e);return o.protocol==="https:"||o.protocol==="http:"?o.href:null}catch{return null}}async function se(e,o=N){let{call:t,runId:n,signal:s}=e;if(t.kind==="browser"){if(t.operation==="discover")return re({result:{tools:[rt]}});if(t.operation!=="call")throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet. Request a browser operation or connect Chrome from Reason to set it up.")}if(e.desktopMissing&&!te){te=!0;try{o.installDesktop()}catch{}}if(t.kind==="computer"){if(e.identity.length>0&&T(n,"grant:probe")){let c=await o.request(e.identity).catch(()=>null),d=c?[...c.accessibility?[]:["accessibility"],...c.screen?[]:["screen"]]:[];for(let m of d)T(n,`grant:${m}`);for(let m of d)await ne(e.identity,m,o,s)}throw new r("automation_computer_setup_required","Computer use is not set up on this Mac yet; Reason asked macOS for any missing permission.")}if(T(n,"page:chrome-extension"))await oe(co,o,s).catch(()=>{});let i=t.arguments,u=t.operation==="call"&&t.tool==="open_tab"&&i&&typeof i==="object"&&!Array.isArray(i)?nt(i.url):null;if(!u)throw new r("automation_browser_setup_required","Browser control is not set up on this Mac yet; Reason opened its Chrome Web Store page. open_tab still opens pages.");return await oe(u,o,s),re({result:{content:[{type:"text",text:JSON.stringify({opened:u,browser:"the user's Chrome",controllable:!1,note:"Opened for the user to see. Reason cannot read or act in this tab until Reason's Chrome extension is added (its Chrome Web Store page is open)."})}]}})}async function ie(e,o=N){if(e.call.kind!=="computer"||e.call.operation!=="permission_status"||e.output.code!==0||e.identity.length===0)return e.output;let t;try{t=JSON.parse(e.output.stdout.toString("utf8"))}catch{return e.output}if(!t||typeof t!=="object"||Array.isArray(t))return e.output;let n=t.permissions;if(!n||typeof n!=="object")return e.output;let s=n,i=[...s.accessibility==="missing"?["accessibility"]:[],...s.screenRecording==="missing"?["screen"]:[]];if(i.length===0)return e.output;return await ot(e.runId,e.identity,i,o,e.signal),{...e.output,stdout:Buffer.from(JSON.stringify({...t,requested:i}))}}var j=172032,_t=18874368,yt=8192,bt=65536,St=55000,kt=60000,Rt=4,It=40000,Ot=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function D(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function _e(e){let o=Object.keys(e).sort().join(",");if(o==="call"||o==="browser,call"){let t=e.call,n=o==="browser,call";if(!P(t)||t.version!==1||t.kind!=="computer"&&t.kind!=="browser"||n&&(e.browser!==vt||t.kind!=="browser")||JSON.stringify(t).length>bt)D();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Ot.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)D();return{output_id:e.output_id,offset:e.offset}}return D()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Et="__computer-use";function Os(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:"ignore",windowsHide:!0}),u=setTimeout(()=>{i.kill("SIGKILL"),s(-1)},n);i.once("error",()=>{clearTimeout(u),s(-1)}),i.once("exit",(c)=>{clearTimeout(u),s(c??-1)})})}function Ct(e,o,t,n){return new Promise((s)=>{let i=R(e,o,{env:t,stdio:["ignore","pipe","ignore"],windowsHide:!0}),u="";i.stdout.setEncoding("utf8").on("data",(d)=>{u+=d});let c=setTimeout(()=>{i.kill("SIGKILL"),s(null)},n);i.once("error",()=>{clearTimeout(c),s(null)}),i.once("close",(d)=>{clearTimeout(c),s(d===0?u:null)})})}function Tt(e){return v(e)?f(L(),"open-browser-use"):"/tmp/open-browser-use"}function v(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Nt=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pt=33554432;function Dt(e,o){let t;try{t=e===null?null:JSON.parse(e)}catch{return null}let n=P(t)&&P(t.result)?t.result.metadata:null;if(!P(n)||n.extensionId!==o)return null;return typeof n.extensionInstanceId==="string"&&Nt.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return U(c).filter((d)=>d.endsWith(".log")||d.endsWith(".ldb")).map((d)=>f(c,d))}catch{return[]}}),s;try{s=n.some((c)=>c.length>0)?U(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Dt(await Ct(e,["info","--socket",d,"--timeout","2s"],o,5000),t.extensionId);if(m)i.push({instance:m,socket:d})}let u=[];for(let[c,d]of(i.length>0?n:[]).entries())for(let m of d)try{if(mt(m).size>Pt)continue;let l=X(m),p=i.find((g)=>l.includes(g.instance));if(p){u.push({storage:t.storages[c],...p});break}}catch{}return u}async function Ut(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Ut(e.nativeHost,o,{socketDir:Tt(e),extensionId:F,storages:[f(t,"browser-profile","Default","Local Extension Settings",F)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ft){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=U(s)}catch(l){if(l.code==="EPERM")throw new r("browser_use_chrome_access_denied","macOS blocked Reason from reading Chrome's profiles. Allow Full Disk Access for Reason on this Mac and try again.")}let u=(l)=>Number(de.exec(l)?.[2]??-1),c=i.filter((l)=>de.test(l)&&M(f(s,l,"Extensions",We))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",We);return(await be(e,o,{socketDir:n,extensionId:We,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((h)=>d(h)===l),instance:p,socket:g}))}async function $t(e,o,t=a(),n=Ft){let s=(await Lt(e,o,t,n))[0]?.instance;if(!s)throw new r("automation_user_chrome_not_connected","No Chrome profile on this Mac is connected to Reason. Open Chrome with the Reason extension, then try again.");return s}function pe(e){return new Promise((o)=>{let t=ht({path:e}),n=(s)=>{t.destroy(),o(s)};t.setTimeout(1000,()=>n(!1)),t.once("error",()=>n(!1)),t.once("connect",()=>n(!0))})}async function ke(e,o){let t=Date.now()+o;while(Date.now()<t){if(await e())return!0;await new Promise((n)=>setTimeout(n,200))}return!1}var q=new Map;function H(e,o){let t=q.get(e);if(!t)t=o().finally(()=>q.delete(e)),q.set(e,t);return t}async function Bt(e,o){if(await pe(e))return;if(pt(e,{force:!0}),await ye("dbus-daemon",["--session",`--address=unix:path=${e}`,"--fork"],o,1e4)!==0||!await ke(()=>pe(e),5000))throw new r("automation_unavailable","Reason could not start the desktop session bus.")}async function me(e,o,t){let n=e.platform==="darwin-arm64"||v(e)?async()=>await Se(e,o,t)!==null:async()=>await ye(e.nativeHost,["info"],o,5000)===0;if(await n())return;let s=["--profile-directory=Default",`--load-extension=${e.extensionDir}`,"--no-first-run","--no-default-browser-check","--window-size=1280,800","about:blank"],i,u=null,c=0;if(e.platform==="darwin-arm64"){let l=f(t,"browser-profile");G(l);let p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let 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");G(l),st(C("icacls"),[B(e.browser),"/grant","*S-1-15-2-1:(OI)(CI)(RX)","*S-1-15-2-2:(OI)(CI)(RX)"],{stdio:"ignore",windowsHide:!0,timeout:60000});let p=s.filter((g)=>g!=="about:blank").concat("--no-startup-window","--keep-alive-for-test");i=R(e.browser,[`--user-data-dir=${l}`,...p],{detached:!0,stdio:"ignore",env:o})}else{let l=f(o.HOME,".config","google-chrome"),p=f(l,"NativeMessagingHosts");ce(p,{recursive:!0,mode:448});let g=Tr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let h=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let y=lt(u,"a",384);c=ct(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"}}),at(y)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function Is(e){await ve(e,!0)}function Ds(e){return Re(e,Ie(e))}function Re(e,o){return e.platform==="darwin-arm64"||v(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!M(o)||!Wt(e.automation))return e.automation;if(!qt(Re(e,o)))try{he(o,e.automation)}catch{}return M(o)?o:e.automation}function Wt(e){try{return U(e).length===0}catch(o){return o.code==="ENOENT"}}function qt(e){let o;try{o=dt(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function ve(e,o){xt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=we().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||v(e)){let l=v(e)?{...s,...Gt(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Et};if(!o)return l;await H("browser",()=>me(e,l,t));let p=await Se(e,l,t);if(!p)throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.");return{...l,REASON_AUTOMATION_OBU_INSTANCE:p,REASON_AUTOMATION_BACKGROUND_TABS:"1"}}let i=await qe(),u=f(t,"home"),c=f(t,"runtime");G(u),G(c);let d=f(t,"bus"),m={...s,HOME:u,PATH:`${B(e.node)}:/usr/bin:/bin`,DISPLAY:i.display,XAUTHORITY:i.xauthority,XDG_RUNTIME_DIR:c,DBUS_SESSION_BUS_ADDRESS:`unix:path=${d}`,...i.sound?{PULSE_SERVER:Ve(i.sound)}:{}};if(await H("bus",()=>Bt(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Gt(){let e=process.env.SystemRoot??"C:\\Windows",o=Object.fromEntries(["SystemDrive","USERPROFILE","LOCALAPPDATA","APPDATA","ProgramData","ProgramFiles","PATHEXT","ComSpec","USERNAME","USERDOMAIN","COMPUTERNAME","NUMBER_OF_PROCESSORS","PROCESSOR_ARCHITECTURE","PSModuleAnalysisCachePath"].flatMap((n)=>process.env[n]?[[n,process.env[n]]]:[])),t=f(e,"System32");return{...o,SystemRoot:e,windir:e,TEMP:L(),TMP:L(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(wt)}}async function Ht(e,o,t){let n=we().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await $t(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function jt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(L(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!M(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;gt(t,e,{mode:384}),he(t,o)}return[o]}function Oe(e,o,t,n){if(typeof ue!=="string")return Promise.reject(new r("automation_unavailable","This Reason build has no automation runtime."));let s=ue;return new Promise((i,u)=>{let c=R(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,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.")),St),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>_t)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(-yt)}),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 Xt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=Rt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Ae(e,o,t,n={}){let s=await(n.environment??ve)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Oe)(e.node,s,JSON.stringify(o),t)}async function Ns(e,o){let t=_e({call:e});if(!("call"in t))D();let n=x();if(!n?.features.computer||t.call.kind==="browser"&&!n.features.browser)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");return await Ae(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?Xt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Tn(e,o={}){let t=_e(e.payload),n=(o.now??Date.now)();if("output_id"in t){let h=k.get(t.output_id);if(!h||h.runId!==e.runId||h.expiresAt<=n||t.offset>h.bytes.byteLength)throw new r("automation_output_unavailable","Reason automation output expired.");return{chunk:h.bytes.subarray(t.offset,t.offset+j).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??ft)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=await Li(e.runId,e.signal,o.now),p="account"in o?o.account??null:K(),g;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),g=await(o.runtime??Oe)(s.node,h,JSON.stringify(t.call),e.signal)}else if(p)g=await(o.delegate??Q)(p,t.call,e.signal);else g=await Ae(s,t.call,e.signal,o)}finally{l()}if(i)g=await ie({runId:e.runId,call:t.call,identity:u,output:g,signal:e.signal},c);return fe(g,e.runId,n)}
|
|
860
|
+
export{Mt,Pn,Os,Is,Ds,Ns,Tn};
|