@reason-machines/cli-linux-x64 0.2.553 → 0.2.555
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/reason +1 -1
- package/bin/vm-hands/api-453kzgb3.js +2 -0
- package/bin/vm-hands/api-credentials-arrtadfe.js +2 -0
- package/bin/vm-hands/connect-cli-33btt5ny.js +2 -0
- package/bin/vm-hands/{desktop-account-d7x4xn27.js → desktop-account-t0afsge2.js} +1 -1
- package/bin/vm-hands/{hands-worker-source-wc8a2nhs.js → hands-worker-source-qj7s9dk5.js} +1 -1
- package/bin/vm-hands/local-automation-5qwy01c7.js +2 -0
- package/bin/vm-hands/local-capabilities-mf5cm434.js +2 -0
- package/bin/vm-hands/{local-desktop-users-tjcpyakd.js → local-desktop-users-5scb9930.js} +1 -1
- package/bin/vm-hands/local-display-mac-pft73te9.js +2 -0
- package/bin/vm-hands/local-display-session-7gvdydea.js +2 -0
- package/bin/vm-hands/local-display-video-vg02ywcz.js +2 -0
- package/bin/vm-hands/local-managed-process-d02r1axd.js +2 -0
- package/bin/vm-hands/local-pty-session-njd0tprg.js +2 -0
- package/bin/vm-hands/{managed-runtime-9p83xxgg.js → managed-runtime-dyea269c.js} +1 -1
- package/bin/vm-hands/permissions-4nhqq4q8.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-g54rtrhd.js +2 -0
- package/bin/vm-hands/{serve-service-83tm7ky3.js → serve-service-5288h5s3.js} +1 -1
- package/bin/vm-hands/{status-mtmtkbbp.js → status-zqw8s5y5.js} +2 -2
- package/bin/vm-hands/version-4nn7abs3.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-645wzfhr.js → vm-hands-entry-lite-0wsr8edk.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-kmtz5h74.js → vm-hands-entry-lite-1yv5qqew.js} +22 -22
- package/bin/vm-hands/{vm-hands-entry-lite-8s4namcq.js → vm-hands-entry-lite-2tbf0swk.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-k9vk84wa.js → vm-hands-entry-lite-2v4zh9ze.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-qdrmhn3f.js → vm-hands-entry-lite-3apb2pjh.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-72nj66ab.js → vm-hands-entry-lite-46pwqvpf.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hq76nmrc.js → vm-hands-entry-lite-99wrj4vv.js} +15 -15
- package/bin/vm-hands/{vm-hands-entry-lite-9azmqs47.js → vm-hands-entry-lite-ak0hd94p.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-6pqfr3w2.js → vm-hands-entry-lite-atv6x5d3.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-e16bhf16.js → vm-hands-entry-lite-b23s6pvp.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-x3ym5t8r.js → vm-hands-entry-lite-b2szp9p8.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-2hfrcr50.js → vm-hands-entry-lite-bpamn7ny.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-0yvkh3bg.js → vm-hands-entry-lite-bs7jaz1j.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-c4zazjyw.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-w29d7ey0.js → vm-hands-entry-lite-dgfx0rbn.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-whfrwyxm.js → vm-hands-entry-lite-f6b0cmq6.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-gezw3967.js → vm-hands-entry-lite-fde30yd5.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-5tnma5qb.js → vm-hands-entry-lite-gje7xvy9.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-hfx1q0b0.js → vm-hands-entry-lite-h1qjggz0.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-y9jarm7q.js → vm-hands-entry-lite-h2rq71rj.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-ycddfgr4.js → vm-hands-entry-lite-mh46pt40.js} +8 -8
- package/bin/vm-hands/{vm-hands-entry-lite-55ja13pk.js → vm-hands-entry-lite-mj7yar3a.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-sb7b4z8t.js → vm-hands-entry-lite-n7bd44rm.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-3dccjjq2.js → vm-hands-entry-lite-pb02nft0.js} +24 -24
- package/bin/vm-hands/{vm-hands-entry-lite-13s0mfpr.js → vm-hands-entry-lite-q2h781jg.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-xe0benev.js → vm-hands-entry-lite-qd46yhvz.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-8hwmhvyx.js → vm-hands-entry-lite-r2qrpjfq.js} +16 -16
- package/bin/vm-hands/{vm-hands-entry-lite-y5hv1gjv.js → vm-hands-entry-lite-ravxhygk.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-t46k8t4n.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-zrkw5syq.js → vm-hands-entry-lite-t87sehfe.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-xrqztkhv.js → vm-hands-entry-lite-wghmyfba.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +1 -1
- package/bin/vm-hands/{vm-hands-executor-n5vw984z.js → vm-hands-executor-ycprx6c1.js} +1 -1
- package/bin/vm-hands/{vm-hands-op-runner-91w40a0z.js → vm-hands-op-runner-f9m5nsa4.js} +1 -1
- package/bin/vm-hands/{vm-hands-runtime-08q76986.js → vm-hands-runtime-a07nhqmd.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-gy36ejp9.js +2 -0
- package/bin/vm-hands/worker-sandbox-f1tfb3y0.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-18f1batz.js +0 -2
- package/bin/vm-hands/api-credentials-6jgf7w9q.js +0 -2
- package/bin/vm-hands/connect-cli-xgbm9xfg.js +0 -2
- package/bin/vm-hands/local-automation-gc28rhzv.js +0 -2
- package/bin/vm-hands/local-capabilities-aa7m3ac6.js +0 -2
- package/bin/vm-hands/local-display-mac-gtp439kc.js +0 -2
- package/bin/vm-hands/local-display-session-wkhda8j7.js +0 -2
- package/bin/vm-hands/local-display-video-14fj7scm.js +0 -2
- package/bin/vm-hands/local-managed-process-hq1x6wqt.js +0 -2
- package/bin/vm-hands/local-pty-session-yr22ryvy.js +0 -2
- package/bin/vm-hands/permissions-5dhys0br.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-k12sw3vm.js +0 -2
- package/bin/vm-hands/version-8z8e46x9.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-r7tb2z3z.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-vn7ag8c7.js +0 -2
- package/bin/vm-hands/worker-preview-readiness-84stxabw.js +0 -2
- package/bin/vm-hands/worker-sandbox-563c5g2f.js +0 -2
- /package/bin/vm-hands/{vm-hands-entry-lite-b6gsggvp.js → vm-hands-entry-lite-tyem93c1.js} +0 -0
|
@@ -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-bpamn7ny.js";import{Oe,Ne,Le}from"./vm-hands-entry-lite-tyem93c1.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 Cs(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:Oe()});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{Cs};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-tyem93c1.js";import{execFileSync as h}from"child_process";import{mkdirSync as k,readdirSync as D,readFileSync as w,rmSync as g,statSync as x,writeFileSync as L}from"fs";import{join as p,sep as y}from"path";import{setTimeout as _}from"timers/promises";var P=3000,u=null;function S(e){return p(e,"users")}function Pt(e){if(u?.root===e.root)return;let o=S(e.root);k(o,{recursive:!0,mode:448}),L(p(o,String(process.pid)),"",{mode:384}),u=e}function Sa(){if(!u)return;g(p(S(u.root),String(process.pid)),{force:!0}),u=null}function m(e){try{return process.kill(e,0),!0}catch(o){return o instanceof Error&&"code"in o&&o.code==="EPERM"}}function E(){let e=process.getuid?.();if(process.platform==="linux")return D("/proc").flatMap((n)=>{if(!/^\d+$/.test(n))return[];try{if(x(`/proc/${n}`).uid!==e)return[];let s=w(`/proc/${n}/cmdline`).toString("utf8").split("\x00").join(" ").trim();return s?[{pid:Number(n),command:s}]:[]}catch{return[]}});if(process.platform==="win32")return h(C("powershell.exe"),["-NoLogo","-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process | ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }'],{encoding:"utf8",maxBuffer:16777216,windowsHide:!0}).split(/\r?\n/).flatMap((s)=>{let l=/^(\d+) (.+)$/.exec(s.trim());return l?[{pid:Number(l[1]),command:l[2]}]:[]});return h("/bin/ps",["-axww","-o","pid=,uid=,command="],{encoding:"utf8",maxBuffer:16777216}).split(`
|
|
3
3
|
`).flatMap((n)=>{let s=/^\s*(\d+)\s+(\d+)\s+(.+)$/.exec(n);return s&&Number(s[2])===e?[{pid:Number(s[1]),command:s[3]}]:[]})}async function Ea(){let e=u;if(!e)return{released:"unused",stopped:0};let o=S(e.root);g(p(o,String(process.pid)),{force:!0}),u=null;let n=!1;for(let t of D(o)){let c=Number(t);if(Number.isSafeInteger(c)&&c>0&&m(c))n=!0;else g(p(o,t),{force:!0})}if(n)return{released:"shared",stopped:0};let s=E().filter((t)=>t.pid!==process.pid&&(t.command.includes(`${e.root}${y}`)||t.command.includes(`${e.automation}${y}`)||t.command.includes(e.extensionDir))),l=(t,c)=>{try{process.kill(t,c)}catch{}};for(let t of s)l(t.pid,"SIGTERM");for(let t=Date.now()+P;Date.now()<t&&s.some((c)=>m(c.pid));)await new Promise((c)=>setTimeout(c,100));for(let t of s)if(m(t.pid))l(t.pid,"SIGKILL");return{released:"stopped",stopped:s.length}}var M=20000,N=30000,O=100,a=new Map,i=null,b=0,f=[];function ji(e){a.set(e,(a.get(e)??0)+1);let o=!1;return()=>{if(o)return;o=!0;let n=(a.get(e)??1)-1;if(n>0){a.set(e,n);return}if(a.delete(e),i?.run===e)i.idleUntil=0}}function T(){return new r("automation_desktop_busy","Another Session, or another agent of this Session, is using this worker's desktop. Retry after it finishes.")}function U(e,o){return i!==null&&i.run!==e&&(i.calls>0||o<i.idleUntil)}async function Hi(e,o,n=Date.now,s="run"){let l=Symbol(e);f.push(l);try{let d=n()+N;for(;;){if(b===0&&!U(e,n())&&(i?.run===e||f[0]===l))break;if(n()>=d)throw T();await _(O,void 0,{signal:o}).catch(()=>o.throwIfAborted())}}finally{f.splice(f.indexOf(l),1)}if(s==="call"&&!(i?.run===e&&(i.calls>0||n()<i.idleUntil))){b+=1;let d=!1;return()=>{if(d)return;d=!0,b-=1}}if(i?.run!==e)i={run:e,calls:0,idleUntil:0};let t=i;t.calls+=1;let c=!1;return()=>{if(c)return;c=!0,t.calls-=1,t.idleUntil=n()+M}}
|
|
4
4
|
export{Pt,Sa,Ea,ji,Hi};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{qn,Wn,Oo,Qt}from"./vm-hands-entry-lite-2v4zh9ze.js";import{Bn,Xe,bo,Fn,jn,Hn,Ur,x}from"./vm-hands-entry-lite-mh46pt40.js";import{Pt}from"./vm-hands-entry-lite-qd46yhvz.js";import{Ir}from"./vm-hands-entry-lite-0wsr8edk.js";import{j}from"./vm-hands-entry-lite-dgfx0rbn.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as ce,spawn as ne}from"child_process";import{randomBytes as he}from"crypto";import{chmodSync as Je,existsSync as ae,lstatSync as Qe,mkdirSync as Se,readFileSync as oe,rmSync as ie,writeFileSync as u}from"fs";import{connect as Te}from"net";import{join as I}from"path";var B=32,Y=76;var m="./desktop-wallpaper-fd8f2wb2.jpg";var v="./dock-browser-y53t41cx.png";var Z="./dock-files-cp52htdw.png";var V="./dock-terminal-1es514yq.png";var z="./grok-wallpaper-71zwn2pj.jpg";var W="./grok-dock-browser-pzw59wnd.png";var U="./grok-dock-files-eckq444x.png";var ee="./grok-dock-terminal-hcpz3e43.png";var re=`# Sets the X root window background and _XROOTPMAP_ID, as feh --bg-fill does.
|
|
3
3
|
# The native Blaxel image ships no feh, hsetroot or compositor, but it does ship
|
|
4
4
|
# python3-gi and libX11. tint2 reads _XROOTPMAP_ID to draw its transparent panel.
|
|
5
5
|
# Usage: DISPLAY=:99 python3 set-root-wallpaper.py IMAGE
|
|
@@ -56,7 +56,7 @@ x.XSetWindowBackgroundPixmap(d, root, pix)
|
|
|
56
56
|
x.XClearWindow(d, root)
|
|
57
57
|
x.XSetCloseDownMode(d, 1) # RetainPermanent: the pixmap outlives this process
|
|
58
58
|
x.XCloseDisplay(d)
|
|
59
|
-
`;function
|
|
59
|
+
`;function Ne(e){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
60
60
|
<openbox_config xmlns="http://openbox.org/3.4/rc">
|
|
61
61
|
<theme><keepBorder>no</keepBorder></theme>
|
|
62
62
|
<applications>
|
|
@@ -64,10 +64,10 @@ x.XCloseDisplay(d)
|
|
|
64
64
|
<application class="Chromium*">
|
|
65
65
|
<decor>no</decor>
|
|
66
66
|
<position force="yes"><x>${B}</x><y>${B}</y></position>
|
|
67
|
-
<size><width>${e.width-B*2}</width><height>${e.height-B-
|
|
67
|
+
<size><width>${e.width-B*2}</width><height>${e.height-B-Y}</height></size>
|
|
68
68
|
</application>
|
|
69
69
|
</applications>
|
|
70
|
-
</openbox_config>`}var
|
|
70
|
+
</openbox_config>`}var ue=`# Remote sandbox dock \u2014 launcher icons only, centred, no panel fill
|
|
71
71
|
panel_items = L
|
|
72
72
|
panel_size = 100% 46
|
|
73
73
|
panel_margin = 0 10
|
|
@@ -88,7 +88,7 @@ launcher_tooltip = 1
|
|
|
88
88
|
launcher_item_app = /tmp/ara-chromium.desktop
|
|
89
89
|
launcher_item_app = /tmp/ara-files.desktop
|
|
90
90
|
launcher_item_app = /tmp/ara-terminal.desktop
|
|
91
|
-
`,De=32,
|
|
91
|
+
`,De=32,Re=`# Remote sandbox dock (grok look) \u2014 small launcher icons only, centred, no panel fill
|
|
92
92
|
panel_items = L
|
|
93
93
|
panel_size = 100% ${De+16}
|
|
94
94
|
panel_margin = 0 0
|
|
@@ -109,7 +109,7 @@ launcher_tooltip = 1
|
|
|
109
109
|
launcher_item_app = /tmp/ara-chromium.desktop
|
|
110
110
|
launcher_item_app = /tmp/ara-files.desktop
|
|
111
111
|
launcher_item_app = /tmp/ara-terminal.desktop
|
|
112
|
-
`,
|
|
112
|
+
`,ge=`corner-radius = 12;
|
|
113
113
|
rounded-corners-exclude = [
|
|
114
114
|
"class_g = 'tint2'",
|
|
115
115
|
"window_type = 'dock'",
|
|
@@ -121,13 +121,13 @@ fading = false;
|
|
|
121
121
|
vsync = false;
|
|
122
122
|
inactive-opacity = 1.0;
|
|
123
123
|
active-opacity = 1.0;
|
|
124
|
-
`,
|
|
124
|
+
`,Ke="/tmp/ara-dock-browser.png",Fe=`[Desktop Entry]
|
|
125
125
|
Name=Chrome
|
|
126
126
|
Exec=chromium --no-sandbox %U
|
|
127
|
-
Icon=${
|
|
127
|
+
Icon=${Ke}
|
|
128
128
|
Type=Application
|
|
129
129
|
Categories=Network;WebBrowser;
|
|
130
|
-
`,
|
|
130
|
+
`,Ce=`[Desktop Entry]
|
|
131
131
|
Name=Terminal
|
|
132
132
|
Exec=bash -c "DISPLAY=:99 xterm -fa DejaVuSansMono -fs 11 -bg black -fg white"
|
|
133
133
|
Icon=/tmp/ara-dock-terminal.png
|
|
@@ -139,12 +139,12 @@ Exec=bash -c "DISPLAY=:99 pcmanfm --no-desktop"
|
|
|
139
139
|
Icon=/tmp/ara-dock-files.png
|
|
140
140
|
Type=Application
|
|
141
141
|
Categories=System;FileManager;
|
|
142
|
-
`;var te={"wallpaper.jpg":
|
|
142
|
+
`;var te={"wallpaper.jpg":m,"dock-browser.png":v,"dock-terminal.png":V,"dock-files.png":Z,"grok-wallpaper.jpg":z,"grok-dock-browser.png":W,"grok-dock-terminal.png":ee,"grok-dock-files.png":U},Ge=re,Oe='set_wallpaper() { if command -v feh >/dev/null 2>&1; then feh --bg-fill "$1"; else python3 "$2" "$1"; fi; }';function de(e){let D=(p)=>p.replaceAll("DISPLAY=:99",`DISPLAY=${e.display}`).replaceAll("/tmp/ara-",`${e.root}/ara-`),s=e.look==="grok",d=new Set(e.absent??[]),t=d.has("files")&&e.filesViewerExec?e.filesViewerExec:null;if(t)d.delete("files");let c=(s?Re:ue).split(`
|
|
143
143
|
`).filter((p)=>!(d.has("terminal")&&p.endsWith("/ara-terminal.desktop"))&&!(d.has("files")&&p.endsWith("/ara-files.desktop"))).join(`
|
|
144
|
-
`),n=(p)=>s?p.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):p,o=t?$e.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):$e,f=s?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":
|
|
145
|
-
`).flatMap((d)=>{let t=d.indexOf("=");return t>0?[[d.slice(0,t),d.slice(t+1)]]:[]})))}catch{return{}}}var se=new Set;async function We(e,D,s){let d=await ze(),t=/^:(\d+)(?:\.\d+)?$/.exec(d.DISPLAY??"")?.[1];if(!t||`:${t}`===
|
|
146
|
-
`),null}var Ie="look";function pe(e){try{return
|
|
147
|
-
`,{mode:384});for(let[i,X]of Object.entries(f.files))
|
|
148
|
-
`);return new Promise((t)=>{let c=ne("/bin/sh",["-c",d],{stdio:"ignore",env:{...s,PATH:"/usr/bin:/bin"}}),n=setTimeout(()=>{c.kill(),t()},
|
|
149
|
-
`),d=s.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of s.slice(d+1)){let n=/^\s+(\d+x\d+)\s/.exec(c);if(!n)break;t.push(n[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:s[d].split(" ")[0],modes:t}}async function rr(e,D,s){if(e.display!==
|
|
144
|
+
`),n=(p)=>s?p.replace("/tmp/ara-dock-","/tmp/ara-grok-dock-"):p,o=t?$e.replace(/^Exec=.*$/m,`Exec=${t}`).replace("Categories=System;FileManager;","Categories=Utility;Viewer;"):$e,f=s?"ara-grok-wallpaper.jpg":"ara-wallpaper.jpg",i={"openbox/rc.xml":Ne(e.screen),"tint2/tint2rc":D(c),"picom/picom.conf":ge,...d.has("terminal")?{}:{"ara-terminal.desktop":D(n(Ce))},...d.has("files")?{}:{"ara-files.desktop":D(n(o))},"ara-chromium.desktop":D(n(Fe)).replace("chromium --no-sandbox %U",e.browserExec),"ara-set-root-wallpaper.py":Ge},X=[...N.slice(0,3),Oe,`[ ! -f "$ROOT/${f}" ] || set_wallpaper "$ROOT/${f}" "$ROOT/ara-set-root-wallpaper.py" || true`,'if alive tint2 && ! cmp -s "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied"; then read -r pid _ <"$ROOT/tint2.pid"; kill -USR1 "$pid" 2>/dev/null || true; fi','cp "$ROOT/tint2/tint2rc" "$ROOT/tint2/applied" 2>/dev/null || true',...N.slice(3)];return{files:i,start:X}}var N=['ticks() { line=$(cat "/proc/$1/stat" 2>/dev/null) || return 1; rest=${line##*) }; case $rest in Z*|X*) return 1;; esac; printf "%s" "$rest" | cut -d " " -f20; }','alive() { [ -f "$ROOT/$1.pid" ] || return 1; read -r pid start <"$ROOT/$1.pid"; current=$(ticks "$pid") || return 1; [ "$current" = "$start" ] && kill -0 "$pid" 2>/dev/null; }','launch() { name=$1; shift; "$@" 9>&- >"$ROOT/$name.log" 2>&1 & pid=$!; start=$(ticks "$pid"); printf "%s %s\\n" "$pid" "$start" >"$ROOT/$name.pid"; }','if [ -f "$ROOT/tint2/tint2rc" ] && ! alive tint2 && command -v tint2 >/dev/null 2>&1; then launch tint2 tint2 -c "$ROOT/tint2/tint2rc"; fi','if [ -f "$ROOT/picom/picom.conf" ] && ! alive picom && command -v picom >/dev/null 2>&1; then launch picom picom --config "$ROOT/picom/picom.conf"; fi'];var ke=43200000,A=":99",_e=60000,P=15000,R={width:1280,height:800},we=/^[A-Za-z0-9._:-]{1,160}$/;function Me(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}var me=["video","viewer","viewer_same_network","viewer_network","look"];function ve(e,D=Date.now()){let s=["relay_url","session_id","expires_at"];if(!Me(e)||s.some((f)=>!(f in e))||Object.keys(e).some((f)=>!s.includes(f)&&!me.includes(f)))throw new r("invalid_display_request","Reason desktop request is malformed.");let d="video"in e?Oo(e.video):void 0,t="viewer"in e?qn(e.viewer):null,c="look"in e?Wn(e.look):null;if(d===null)throw new r("invalid_display_request","Reason desktop video request is invalid.");let n=null;try{n=typeof e.relay_url==="string"?new URL(e.relay_url):null}catch{}if(!n||n.protocol!=="wss:"&&n.protocol!=="ws:"||n.username||n.password)throw new r("invalid_display_request","Reason desktop relay URL is invalid.");if(typeof e.session_id!=="string"||!we.test(e.session_id))throw new r("invalid_display_request","Reason desktop session identity is invalid.");let o=typeof e.expires_at==="string"?Date.parse(e.expires_at):Number.NaN;if(!Number.isFinite(o)||o<=D)throw new r("invalid_display_request","Reason desktop session has already expired.");return{relay_url:e.relay_url,session_id:e.session_id,expires_at:new Date(Math.min(o,D+ke)).toISOString(),...d?{video:d}:{},...t?{viewer:t}:{},...d&&e.viewer_same_network===!0?{viewer_same_network:!0}:{},...c?{look:c}:{}}}function Ft(e=process.platform){return(e==="linux"||e==="darwin"||e==="win32")&&x()?.features.display===!0}async function Vs(){if(process.platform==="win32")return Ft()&&await Ur();if(process.platform!=="darwin")return Ft();return await Ur()}function G(e){Se(e,{recursive:!0,mode:448});let D=Qe(e);if(!D.isDirectory()||D.isSymbolicLink()||process.getuid&&D.uid!==process.getuid())throw new r("display_unavailable","Reason desktop state directory is not private.");Je(e,448)}function Ze(e,D){let s=(t)=>{let c=Buffer.alloc(2);return c.writeUInt16BE(t.length),Buffer.concat([c,t])},d=Buffer.from([255,255]);return Buffer.concat([d,s(Buffer.alloc(0)),s(Buffer.from(e)),s(Buffer.from("MIT-MAGIC-COOKIE-1")),s(D)])}function y(e,D,s=2000){return new Promise((d)=>{let t=Te(e),c="",n=(o)=>{t.destroy(),d(o)};t.setTimeout(s,()=>n(!1)),t.once("error",()=>n(!1)),t.once("close",()=>n(!1)),t.once("connect",()=>{if(!D)n(!0)}),t.on("data",(o)=>{if(c+=o.toString("latin1"),c.length>=4)n(c.startsWith("RFB "))})})}async function Q(e,D){let s=Date.now()+D;while(Date.now()<s){if(await e())return!0;await new Promise((d)=>setTimeout(d,100))}return!1}function g(e,D,s){return new Promise((d)=>{let t=ne(e,D,{detached:!0,stdio:"ignore",env:s});t.once("error",()=>d(-1)),t.once("exit",(c)=>d(c)),t.unref(),setTimeout(()=>d(null),P).unref()})}var J=null;function qe(e=a()){return J??=Ve(e).finally(()=>{J=null}),J}async function Ve(e){let D=x({home:e});if(!D?.xvfb||!D.x11vnc||!D.openbox)throw new r("display_unavailable","Run `reason desktop install` on this machine to enable its desktop.");Pt({root:D.root,automation:D.automation,extensionDir:D.extensionDir});let s=I(D.root,"display");G(s);let d=await We(e,s,D.x11vnc);if(d)return d;let t={display:A,xauthority:I(s,"Xauthority"),rfbSocket:I(s,"rfb.sock")},c=I(s,"pulse"),n=(async()=>{try{G(c)}catch{return null}return await bo(c,D.pulseaudio)})();G(I(s,"home"));let o=S(s,t,D.pulseaudio),f=async()=>({...t,sound:await n});if(await y({path:t.rfbSocket},!0))return be(I(s,"theme"),N,o),await f();if(!ae(t.xauthority))u(t.xauthority,Ze(A.slice(1),he(16)),{mode:384,flag:"wx"});let i=T(I(s,"theme"),t.display,R,e),X={path:`/tmp/.X11-unix/X${A.slice(1)}`};if(!await y(X,!1)){let p=`${R.width}x${R.height}`;if(D.xvnc)ie(t.rfbSocket,{force:!0}),g(D.xvnc,[t.display,"-geometry",p,"-depth","24","-nolisten","tcp","-auth",t.xauthority,"-rfbport","-1","-rfbunixpath",t.rfbSocket,"-SecurityTypes","None","-UseBlacklist=0","-AlwaysShared","-desktop","Reason"],o);else g(D.xvfb,[t.display,"-screen","0",`${p}x24`,"-nolisten","tcp","-auth",t.xauthority],o);if(!await Q(()=>y(X,!1),P)||D.xvnc&&!await Q(()=>y({path:t.rfbSocket},!0),P))throw new r("display_unavailable","Reason could not start the virtual display.");g(D.openbox,["--config-file",i.openboxConfig],o)}if(await k(i,o),!await fe(D.x11vnc,t,s,"x11vnc.log",o))throw new r("display_unavailable","Reason could not start the desktop server.");return await f()}function S(e,D,s){let d={HOME:I(e,"home"),PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:D.display,XAUTHORITY:D.xauthority};if(s)d.PULSE_SERVER=Xe(Bn(I(e,"pulse")));return d}async function fe(e,D,s,d,t){if(await y({path:D.rfbSocket},!0))return!0;ie(D.rfbSocket,{force:!0});let c=await g(e,["-display",D.display,"-auth",D.xauthority,"-rfbport","0","-rfbportv6","-1","-unixsock",D.rfbSocket,"-nopw","-forever","-shared","-noxdamage","-sb","0","-rfbversion","3.7","-quiet","-bg","-o",I(s,d)],t);if(c!==null&&c!==0)return!1;return await Q(()=>y({path:D.rfbSocket},!0),P)}async function ze(){let e=["DISPLAY","XAUTHORITY","WAYLAND_DISPLAY","XDG_SESSION_TYPE"],D=(s)=>Object.fromEntries(e.flatMap((d)=>s[d]?[[d,s[d]]]:[]));if(process.env.DISPLAY)return D(process.env);try{let s=await new Promise((d,t)=>ce("systemctl",["--user","show-environment"],{encoding:"utf8",timeout:2000},(c,n)=>c?t(c):d(n)));return D(Object.fromEntries(s.split(`
|
|
145
|
+
`).flatMap((d)=>{let t=d.indexOf("=");return t>0?[[d.slice(0,t),d.slice(t+1)]]:[]})))}catch{return{}}}var se=new Set;async function We(e,D,s){let d=await ze(),t=/^:(\d+)(?:\.\d+)?$/.exec(d.DISPLAY??"")?.[1];if(!t||`:${t}`===A||d.WAYLAND_DISPLAY||d.XDG_SESSION_TYPE==="wayland")return null;let c={display:`:${t}`,xauthority:d.XAUTHORITY??I(e,".Xauthority"),rfbSocket:I(D,`rfb-${t}.sock`)},n=`${c.display} ${c.xauthority}`;if(se.has(n)||!await y({path:`/tmp/.X11-unix/X${t}`},!1))return null;let o={HOME:e,PATH:"/usr/local/bin:/usr/bin:/bin",DISPLAY:c.display,XAUTHORITY:c.xauthority};if(await fe(s,c,D,`x11vnc-${t}.log`,o))return{...c,sound:null};return se.add(n),process.stderr.write(`Reason worker: your screen ${c.display} could not be served; using the virtual desktop
|
|
146
|
+
`),null}var Ie="look";function pe(e){try{return Wn(oe(I(e,Ie),"utf8").trim())??"reason"}catch{return"reason"}}function T(e,D,s,d,t=pe(e)){let c=`chromium --no-first-run --no-default-browser-check${process.geteuid?.()===0?" --no-sandbox":""} %U`,n=[["terminal","xterm"],["files","pcmanfm"]].filter(([,i])=>!ae(`/usr/bin/${i}`)).map(([i])=>i),o=`${c.replace(/ %U$/,"")} --app=file://${I(d,".reason","workspace")}/`,f=de({root:e,display:D,screen:s,browserExec:c,absent:n,look:t,filesViewerExec:o});for(let i of["","openbox","tint2","picom"])G(I(e,i));u(I(e,Ie),`${t}
|
|
147
|
+
`,{mode:384});for(let[i,X]of Object.entries(f.files))u(I(e,i),X,{mode:384});for(let[i,X]of Object.entries(te))u(I(e,`ara-${i}`),oe(X),{mode:384});return{root:e,openboxConfig:I(e,"openbox","rc.xml"),start:f.start}}function k(e,D){return be(e.root,[...e.start,"openbox --reconfigure >/dev/null 2>&1 || true"],D)}function be(e,D,s){let d=[`ROOT=${JSON.stringify(e)}`,...D].join(`
|
|
148
|
+
`);return new Promise((t)=>{let c=ne("/bin/sh",["-c",d],{stdio:"ignore",env:{...s,PATH:"/usr/bin:/bin"}}),n=setTimeout(()=>{c.kill(),t()},P);c.once("error",()=>{clearTimeout(n),t()}),c.once("exit",()=>{clearTimeout(n),t()})})}var je=2073600,Ue=320;function er(e,D){let s=Math.min(1,Math.sqrt(je/(e.width*e.height))),d=(t,c)=>Math.min(Math.floor(c/8)*8,Math.max(Ue,Math.round(t*s/8)*8));return{width:d(e.width,D.width),height:d(e.height,D.height)}}function _(e,D,s){return new Promise((d)=>ce(e,D,{env:s,encoding:"utf8",timeout:5000},(t,c)=>d(t?null:c)))}function le(e){let D=/current (\d+) x (\d+), maximum (\d+) x (\d+)/.exec(e),s=e.split(`
|
|
149
|
+
`),d=s.findIndex((c)=>/^\S+ connected/.test(c));if(!D||d<0)return null;let t=[];for(let c of s.slice(d+1)){let n=/^\s+(\d+x\d+)\s/.exec(c);if(!n)break;t.push(n[1])}return{current:{width:Number(D[1]),height:Number(D[2])},maximum:{width:Number(D[3]),height:Number(D[4])},output:s[d].split(" ")[0],modes:t}}async function rr(e,D,s){if(e.display!==A)return null;let d={PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority},t=(f)=>_("xrandr",f,d),c=le(await t(["--query"])??"");if(!c||c.maximum.width<=c.current.width&&c.maximum.height<=c.current.height)return null;let n=er(D,c.maximum);if(n.width===c.current.width&&n.height===c.current.height)return{size:n,changed:!1};let o=`${n.width}x${n.height}`;if(!c.modes.includes(o)){if(await t(["--newmode",o,"60",...[n.width,n.width,n.width,n.width,n.height,n.height,n.height,n.height].map(String)]),await t(["--addmode",c.output,o])===null)return null}return s(),await t(["--output",c.output,"--mode",o])===null?null:{size:n,changed:!0}}async function Dr(e,D){let s=a(),d=x({home:s});if(!d)return;let t=I(d.root,"display"),c=S(t,e,d.pulseaudio);await k(T(I(t,"theme"),e.display,D,s),c);let n=D.width-B*2,o=D.height-B-Y;await _("xdotool",["search","--onlyvisible","--class","Chromium","windowsize","%@",String(n),String(o),"windowmove","%@",String(B),String(B)],{...c,PATH:"/usr/bin:/bin"})}var K=Promise.resolve();function $r(e,D,s=()=>{}){let d=K.then(()=>rr(e,D,s));return K=d.then((t)=>t?.changed?Dr(e,t.size):void 0).catch(()=>{}),d.then((t)=>t?.size??null,()=>null)}function tr(e,D){if(e.display!==A)return Promise.resolve();let s=K.then(async()=>{let d=a(),t=x({home:d});if(!t)return;let c=I(t.root,"display"),n=I(c,"theme");if(pe(n)===D)return;let o=S(c,e,t.pulseaudio),f=le(await _("xrandr",["--query"],{PATH:"/usr/bin:/bin",DISPLAY:e.display,XAUTHORITY:e.xauthority})??"");await k(T(n,e.display,f?.current??R,d,D),o)});return K=s.catch(()=>{}),s.catch(()=>{})}async function jt(e,D={}){let s=D.now??Date.now,d=ve(e.payload,s());if(e.signal.throwIfAborted(),!d.video)throw new r("display_video_required","Reason desktops stream as video now; this request came without it.");let t=D.platform??process.platform;if(t!=="linux"&&t!=="darwin"&&t!=="win32")throw new r("display_video_unsupported","This machine does not serve desktop video.");let{video:c,look:n}=d,o=(D.video?.desktop??(t==="darwin"?async()=>Fn:t==="win32"?async()=>jn:async()=>{let f=await qe();if(n)await tr(f,n);return f}))();return await dr(e.signal,d,D,s,(f)=>Hn(f,{request:c,desktop:o,...d.viewer?{viewer:d.viewer}:{},viewerSameNetwork:d.viewer_same_network===!0},{resizeDesktop:$r,...D.video}),(f)=>Qt({type:"error",code:f}))}function dr(e,D,s,d,t,c){let n=d();return new Promise((o,f)=>{let i=null,X=!1,p=!1,w,F,L,q=!1,l=null,E=(b)=>{if(p)return;if(l)b=l.outcome;p=!0,clearTimeout(w),clearTimeout(F),e.removeEventListener("abort",O),L?.close();try{i?.close(1000,"display_session_over")}catch{}if("error"in b){f(b.error);return}o({reason:b.reason,...L?.summary(),duration_ms:Math.max(0,d()-n)})},C=()=>E({error:new r("display_relay_unavailable","Reason could not reach the desktop relay.")}),O=()=>{let b=e.reason;E({error:b instanceof r?b:new r("cancelled","Reason closed the desktop session.")})},M=()=>{if(!l||!i)return;let{outcome:b}=l,H=!("error"in b)?b.reason:b.error instanceof r?b.error.code:"display_unavailable";if(!l.told)try{i.send(c(H))}catch{}E(b)};if(L=t({get done(){return p||l!==null},get open(){return X&&!p&&l===null},get bufferedAmount(){return i?.bufferedAmount??0},send(b){if(p||l||!X||!i)return;try{i.send(b)}catch{E({reason:"relay_closed"})}},end:(b)=>{if(p||l)return;if(!("error"in b)&&q&&X){E(b);return}if(l={outcome:b,told:!("error"in b)&&X},q&&X)M()}}),p){L.close();return}if(e.aborted){O();return}e.addEventListener("abort",O,{once:!0}),w=setTimeout(()=>E({reason:"session_expired"}),Math.max(1,Date.parse(D.expires_at)-d())),F=setTimeout(()=>E({reason:"viewer_absent"}),s.viewerWaitMs??_e);try{i=(s.connect??Ir)(D.relay_url,(s.loadProxy??j)()?.url)}catch{C();return}i.binaryType="arraybuffer",i.onopen=()=>{if(p||!i)return;X=!0,L?.opened()},i.onmessage=(b)=>{if(p)return;let H=b.data,h=H instanceof ArrayBuffer?new Uint8Array(H):ArrayBuffer.isView(H)?new Uint8Array(H.buffer,H.byteOffset,H.byteLength):null;if(!h||h.byteLength===0)return;if(clearTimeout(F),q=!0,l){M();return}L?.received(h)},i.onclose=()=>{if(p)return;if(!X){C();return}E({reason:"relay_closed"})},i.onerror=()=>{if(p||X)return;C()}})}
|
|
150
150
|
export{Ft,Vs,G,qe,jt};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Gi,Ki}from"./vm-hands-entry-lite-
|
|
2
|
+
import{Gi,Ki}from"./vm-hands-entry-lite-ak0hd94p.js";function ks(o=process.platform){if(Gi(),o==="linux"||o==="win32")Ki("strict")}
|
|
3
3
|
export{ks};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-a3p6xz53.js";import{jo}from"./vm-hands-entry-lite-4anjdcth.js";import{Fe,un,Dt,dn}from"./vm-hands-entry-lite-04x5xjt6.js";import{Qn}from"./vm-hands-entry-lite-c4zazjyw.js";import{t,o,d,u,n,gs,W,g,s,i}from"./vm-hands-entry-lite-wzv13c8k.js";var M=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function v(e){let r=typeof e==="string"?M.exec(e):null;return r?{major:Number(r[1]),minor:Number(r[2])}:null}var z=25,x=1e5,j=/^[0-9a-f]{64}$/,L=n({day:t().regex(/^\d{4}-\d{2}-\d{2}$/),sent:o().int().min(0).max(x),received:o().int().min(0).max(x)}),N=20,H=n({name:t().min(1).max(100),address:t().min(1).max(300).optional()}),F=n({name:t().min(1).max(100),agent:t().min(1).max(100)}),Le=n({machine:t().min(1).max(200),person:t().min(1).max(200),team:t().min(1).max(200),team_id:t().min(1).max(200).optional(),workspace:d().optional(),version:t().max(64).optional(),wait_seconds:o().int().min(0).max(z).optional(),message_counts:u(L).max(14).optional().catch(void 0),endpoint:t().regex(j).optional().catch(void 0),hosted:u(H).max(50).optional().catch(void 0)}),B=g("kind",[n({id:t(),kind:i("who"),all:d().optional()}),n({id:t(),kind:i("send"),to:t(),body:t(),from_name:t(),from_agent:t(),wake:d(),reply_to:t().max(100).optional(),notify:d().optional()})]),P=n({job:B.nullable(),retry_after_seconds:o().optional(),hosted:u(F).max(N).optional().catch(void 0)}),G=n({address:t(),person:t(),machine:t(),agent:t(),repo:t().nullable(),branch:t().nullable(),status:t(),since:o().nullable(),doing:t().nullable(),worker:d(),tier:t().max(10).optional()}),J=n({person:t(),machine:t(),online:d()}),K=n({team:t().nullable(),sessions:u(G).max(2000),machines:u(J).max(500),all:d().optional()}),Q=n({address:t().max(300),state:t().max(40),note:t().max(500)}),De=W([n({who:K}),n({sent:n({ids:u(t().max(100)).max(500),recipients:u(t().max(300)).max(500),from:t().max(300),deliveries:u(Q).max(500).optional()})}),n({error:t().min(1).max(2000)})]),V=n({id:t().max(100),from:t().max(300),from_agent:t().max(100).nullable(),to:t().max(300),reply_to:t().max(100).nullable(),body:t().max(64000),sent_at:o()}),Ne=n({messages:u(V).max(100),team:t().min(1).max(200).optional(),team_id:t().min(1).max(200).optional(),workspace:d().optional(),session:t().min(1).max(100).optional().catch(void 0),machine:t().min(1).max(200).optional().catch(void 0)});var I=["run","mcp:read","mcp:write","secrets:read","secrets:write","sessions:read","sessions:debug","devices:read","devices:write","devices:use","ssh:write","knowledge:read","memory:read","memory:write","skills:read","skills:write","repos:read","repos:write","reviews:read","reviews:write","deployment:read","analytics:read","org:read","org:write","attachments:read","attachments:write","guardrails:read","guardrails:write","network:read","network:write","automations:read","automations:write","agent_auth:read"];var sn=I.filter((e)=>e!=="network:read"&&e!=="network:write");class b extends Error{oauthCode;constructor(e,r=null){super(e);this.oauthCode=r;this.name="LoginError"}}function Y(e,r){let a=typeof e.error==="string"?e.error:null,l=typeof e.error_description==="string"?e.error_description:a?a:r;return new b(l,a)}async function X(e,r,a,l){let c=await a(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:r,signal:l}),m=await c.json().catch(()=>({}));if(!c.ok)throw Y(m,`OAuth token request failed (${c.status})`);return m}var Z=1e4;async function ee(e,r={}){let a=r.fetchImpl??fetch,l=await X(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),a,AbortSignal.timeout(Z)).catch((m)=>{if(m instanceof Error&&m.name==="TimeoutError")throw new b("Reason did not answer the login refresh in time. Check the network and retry.");throw m});if(typeof l.access_token!=="string"||typeof l.refresh_token!=="string"||typeof l.expires_in!=="number")throw new b("Reason returned an incomplete refreshed login.");let c={...e,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:new Date(Date.now()+l.expires_in*1000).toISOString(),scopes:typeof l.scope==="string"?l.scope.split(/\s+/).filter(Boolean):e.scopes};return un(c,r.path??Fe()),c}var w=new Map,ne=2000,te=100;function A(e,r){if(!r)return e;if(r.aborted)return Promise.reject(r.reason);return new Promise((a,l)=>{let c=()=>l(r.reason);r.addEventListener("abort",c,{once:!0}),e.then(a,l).finally(()=>r.removeEventListener("abort",c))})}async function ot(e={}){let r=e.path??Fe(),a=Dt(r);if(!a)return null;let l=e.apiOrigin??R(process.env,"REASON_API_URL")?.trim();if(l&&!jo(a.apiOrigin,new URL(l).origin))return null;if(!(Date.parse(a.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&a.accessToken!==e.refused))return a;let m=[r,a.apiOrigin,a.clientId,a.refreshToken].join("\x00"),p=w.get(m);if(p)return A(p,e.signal);let f;return f=ee(a,{fetchImpl:e.fetchImpl,path:r}).catch(async(y)=>{if(!(y instanceof b)||y.oauthCode!=="invalid_grant"&&y.oauthCode!=="invalid_client")throw y;let k=(_)=>_!==null&&(y.oauthCode==="invalid_client"?_.clientId!==a.clientId:_.refreshToken!==a.refreshToken),E=Date.now()+ne;while(!k(Dt(r))&&Date.now()<E)await new Promise((_)=>setTimeout(_,te));if(k(Dt(r)))return ot({fetchImpl:e.fetchImpl,path:r});return dn(r),null}).finally(()=>{if(w.get(m)===f)w.delete(m)}),w.set(m,f),A(f,e.signal)}var se=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:d().nullable()}),oe=n({groups:u(n({selectable:d().optional(),accounts:u(n({source_id:t().min(1),model_ids:u(t().min(1)).optional()}))}))});function re(e){let r=oe.safeParse(e);if(!r.success)return;return r.data.groups.some((a)=>a.selectable!==!1&&a.accounts.some((l)=>l.model_ids===void 0||l.model_ids.length>0))}class D extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,r,a,l,c,m,p){super(a);this.status=e;this.code=r;this.suggestedModel=l;this.retryAfterMs=c;this.resolutionReason=m;this.refusal=p;this.name="ApiError"}static rateLimitDelayMs(e,r){if(!(e instanceof D)||e.status!==429)return null;return Math.min(60000,Math.max(r,e.retryAfterMs??0))}}var ie=["minimal","low","medium","high","xhigh","max"],ae=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:d(),compatible:d().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:u(n({id:t().min(1),label:t()}))}),le=n({devices:u(ae),end_cursor:t().nullish(),has_next_page:d().optional()}),ce=n({id:t().min(1),name:t()}),de=n({items:u(ce)}),me=n({id:t().min(1),name:t(),main:d(),mine:d(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ue=n({items:u(me)}),ge=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:u(t()).default([]),is_enabled:d().default(!0)}),he=n({items:u(ge).default([])}),pe=n({id:t().min(1),kind:t(),enabled:d(),schedule:n({expression:t().nullish(),every_seconds:o().nullish(),next_run_at:t().nullish()}).nullish(),github:n({event:t().nullish(),action:t().nullish(),repo:t().nullish()}).nullish(),last_fired_at:t().nullish()}),T=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:d(),triggers:u(pe).default([])}),fe=n({items:u(T).default([]),end_cursor:t().nullish(),has_next_page:d().optional()}),ye=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:d()}),_e=n({items:u(ye).default([])}),Re=n({status:t(),summary:t().nullish(),category:t().nullish(),outcome:t().nullish(),message_count:o().nullish(),pr_url:t().nullish(),cost_usd:o().nullish(),generated_at:t().nullish()}),C=n({tags:u(t()).default([])}),be=s(["linux","macos"]),U=n({id:t().min(1),name:t().min(1),platform:be.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),we=n({machines:u(U)}),Se=n({machine:U}),ke=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ve=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),O=gs({machine_id:t().min(1),machine_name:t().min(1)}),xe=O.extend({organization_id:t().min(1)}),fn=n({id:t().min(1),name:t().min(1),state:s(["waiting","placed"]),queue_position:o().int().nullable()});var yn=W([n({kind:i("cloud")}),n({kind:s(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function h(e,r,a){let l=e.safeParse(r);if(!l.success)throw new D(502,a,"Reason returned an unexpected response.");return l.data}var Pe=n({error:n({type:t(),message:t()})});function S(e,r,a){let l=Pe.safeParse(r),c=typeof r.error==="string"?r.error:l.success?l.data.error.type:`http_${e}`,m=typeof r.detail==="string"?r.detail:typeof r.message==="string"?r.message:l.success?l.data.error.message:`Reason request failed (${e}${typeof r.error==="string"?` ${r.error}`:""})`,p=c==="github_connection_required"&&typeof r.connect_url==="string"&&/^https?:\/\//.test(r.connect_url)?` Connect it at ${r.connect_url}`:"",f=a===null||a.trim()===""?NaN:Number(a);return new D(e,c,`${m}${p}`,typeof r.suggested_model==="string"?r.suggested_model:void 0,Number.isFinite(f)&&f>=0?f*1000:void 0,typeof r.resolution_reason==="string"?r.resolution_reason:void 0,typeof r.code==="string"?{code:r.code,...typeof r.billing_path==="string"&&/^\/(?![/\\])/.test(r.billing_path)?{billingPath:r.billing_path}:{}}:void 0)}async function Ps(e){let r=await(e.fetchImpl??fetch)(`${e.apiOrigin}/v3/machines/enrollment-tickets`,{method:"POST",headers:{authorization:`Bearer ${e.token}`,accept:"application/json","content-type":"application/json"},body:JSON.stringify(e.body),signal:AbortSignal.timeout(30000),redirect:"error"}),a=await r.json().catch(()=>({}));if(!r.ok)throw S(r.status,a,r.headers.get("retry-after"));return h(xe,a,"invalid_machine_ticket")}var Ie=n({items:u(n({name:t()}))}),Ae=n({name:t(),scope:t(),result:s(["created","updated"]).optional(),warning:n({message:t()}).optional()});class rs{options;credentials;constructor(e,r={}){this.options=r;this.credentials=e}trackEvent(e,r={}){}async request(e,r={}){let{status:a,headers:l,json:c}=await this.exchange(e,r);if(a<200||a>299)throw S(a,c,l.get("retry-after"));return c}async exchange(e,r={},a=!1){let l=this.options.fetchImpl??fetch;if(!a&&r.retryUnauthorized!==!1)await this.renewBeforeExpiry(l,r.signal);let c=await l(`${this.credentials.apiOrigin}/v3${e}`,{method:r.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":Qn,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...r.raw?{"content-type":r.raw.contentType}:r.body===void 0?{}:{"content-type":"application/json"},...r.headers,...r.ifNoneMatch?{"if-none-match":r.ifNoneMatch}:{}},body:r.raw?r.raw.bytes:r.body===void 0?void 0:JSON.stringify(r.body),signal:r.signal,redirect:r.ifNoneMatch?"manual":"error"}),m=await c.json().catch(()=>({}));if(c.status===401&&!a&&r.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let p=await ot({fetchImpl:l,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:r.signal});if(p)return this.credentials=p,this.exchange(e,r,!0)}return{status:c.status,headers:c.headers,json:m}}async renewBeforeExpiry(e,r){let a=this.credentials;if(a.credentialKind==="api_key"||!(Date.parse(a.expiresAt)<=Date.now()+60000))return;let l=await ot({fetchImpl:e,path:this.options.credentialsPath,signal:r}).catch(()=>null);if(l&&l.apiOrigin===a.apiOrigin&&l.orgId===a.orgId&&l.clientId===a.clientId)this.credentials=l}createHeadlessDeviceEnrollmentTicket(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollment-tickets`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}async enrollHeadlessDevice(e){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/enrollments`,{method:"POST",body:e,signal:AbortSignal.timeout(30000),retryUnauthorized:!1})}catch(r){if(r instanceof D&&(r.status===404||r.status===405||r.status===403&&r.code==="endpoint_not_available"))return null;throw r}}addDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(r)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,r=""){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?a:`${a}/${encodeURIComponent(e)}${r}`}async listMachines(){return h(we,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let r=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return h(Se,r,"invalid_machine").machine}async deleteMachine(e){let r=await this.request(this.machinePath(e),{method:"DELETE"});return h(ke,r,"invalid_machine_deletion")}async listSecretNames(e){let r=await this.request(`${this.secretsPath()}?scope=${e}`);return h(Ie,r,"invalid_secret_list").items.map((a)=>a.name)}async setSecret(e){let r=await this.request(this.secretsPath(),{method:"POST",body:e});return h(Ae,r,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let r=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return h(ve,r,"invalid_machine_token")}async createMachineEnrollmentTicket(e,r){let a=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:r,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return h(O,a,"invalid_machine_ticket")}self(e){return this.request("/self",{signal:e})}submitFeedback(e){return this.request("/feedback",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}agentNetwork(e=AbortSignal.timeout(30000)){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{signal:e})}startAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}rotateAgentNetwork(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network`,{method:"PUT",body:e,signal:AbortSignal.timeout(30000)})}async registerNetworkTeam(e){await this.request("/network/teams",{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async claimAgentNetworkRelayJob(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:r});return h(P,a,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:r,signal:AbortSignal.timeout(30000)})}async recordAgentNetworkRelayReplies(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/replies`,{method:"POST",body:e,signal:AbortSignal.timeout(30000)})}async workspaceMembers(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/members/users`,{signal:AbortSignal.timeout(30000)})).items??[]).flatMap((r)=>typeof r.email==="string"?[{email:r.email,role:typeof r.role==="string"?r.role:"member"}]:[])}claimExistingCliPairing(e){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/onboarding/import/pairing/claim-existing`,{method:"POST",body:{pairing_code:e}})}async claudeCodeSignIn(e){return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials`,{retryUnauthorized:!1,signal:e?AbortSignal.any([e,AbortSignal.timeout(15000)]):AbortSignal.timeout(15000)})).claude_code_sign_in===!0}connectAnthropicProvider(e,r,a={}){let l=e.kind==="setup_token"?{setup_token:e.token}:{access_token:e.credential.access,refresh_token:e.credential.refresh,expires_at:new Date(e.credential.expires).toISOString()};return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/provider-credentials/anthropic`,{method:"POST",retryUnauthorized:a.retryUnauthorized,signal:a.signal,body:{...l,...r?{account_key:r}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((r)=>{let a=typeof r.full_name==="string"?r.full_name:typeof r.repo_full_name==="string"?r.repo_full_name:null;if(!a)return[];return[{repo_id:typeof r.repo_id==="string"?r.repo_id:void 0,full_name:a,provider:r.provider==="gitlab"?"gitlab":"github",default_branch:typeof r.default_branch==="string"?r.default_branch:null,private:typeof r.private==="boolean"?r.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),r=de.safeParse(e);if(!r.success)throw new D(502,"invalid_project_list","Reason returned an unexpected project list.");return r.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return h(ue,e,"invalid_reason_list").items}async openReasonConversation(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return h(n({session_id:t().min(1)}),r,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return h(he,e,"invalid_skill_list").items}catch(e){if(e instanceof D&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${r?`?after=${encodeURIComponent(r)}`:""}`),c=le.safeParse(l);if(!c.success)throw new D(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...c.data.devices),r=c.data.has_next_page?c.data.end_cursor??null:null,!r)break}return e}async listModels(){try{let r=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((c)=>c.hidden!==!0),a=r.filter((c)=>c.available!==!1).map(({reasoning_efforts:c,hidden:m,available:p,...f})=>({...f,...Array.isArray(c)?{reasoning_efforts:ie.filter((y)=>c.includes(y))}:{}})),l=new Set(a.map((c)=>c.detail));return{models:a.length>1&&l.size===1?a.map(({detail:c,...m})=>m):a,runnable:a.length>0||r.length===0}}catch(e){if(e instanceof D&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let r=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return v(r.reason_version)?r.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=se.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let r;try{r=re(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:r}}catch(e){if(e instanceof D&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let r=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)r.set("origin",e.origin);r.set("fields",e.fields.join(","));let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${r.toString()}`,{status:l,headers:c,json:m}=await this.exchange(a,e.etag?{ifNoneMatch:e.etag}:{});if(l===304)return null;if(l<200||l>299)throw S(l,m,c.get("retry-after"));return{items:Array.isArray(m.items)?m.items:[],etag:c.get("etag")}}async listSessions(e=50,r,a={}){let l=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:a.status??"active"});if(r)l.set("project_id",r);if(a.origin)l.set("origin",a.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${l.toString()}`)).items??[]}getSession(e,r){let a=r?.fields.length?`?fields=${encodeURIComponent(r.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${a}`)}async prestartSession(e){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return r?.status==="starting"||r?.status==="ready"}async createSession(e){let r=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(r||e.runtimeProfile){let c=await this.request("/deployment");if(r&&(!Array.isArray(c.session_modes)||!c.session_modes.includes(e.mode??"standard")||!Array.isArray(c.workspace_ownerships)||!c.workspace_ownerships.includes(e.workspaceOwnership??"managed")))throw Error("Deployment does not support the requested Session policy; refusing to create a Session.");if(e.runtimeProfile&&(!Array.isArray(c.experimental_runtime_profiles)||!c.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions`,{method:"POST",body:{prompt:e.prompt,...e.attachments?.length?{attachments:e.attachments}:{},...e.mode?{mode:e.mode}:{},...e.workspaceOwnership?{workspace_ownership:e.workspaceOwnership}:{},...e.target?{target:e.target}:{},...e.repo?{repo:e.repo}:{},...e.provider?{provider:e.provider}:{},...e.model?{model:e.model}:{},...e.reasoningEffort?{reasoning_effort:e.reasoningEffort}:{},...e.runtimeProfile?{experimental_runtime_profile:e.runtimeProfile}:{},...e.ref?{ref:e.ref}:{},...e.branch?{branch:e.branch}:{},...e.completionMode?{completion_mode:e.completionMode}:{},...e.env&&Object.keys(e.env).length>0?{env:e.env}:{},...e.clientSessionId?{client_session_id:e.clientSessionId}:{},...e.longRunning?{long_running:{enabled:!0}}:{},...e.spendLimitRcu?{spend_limit_rcu:e.spendLimitRcu}:{},idempotency_key:`cli-${crypto.randomUUID()}`}}),l=await this.getSession(a.session_id);if(r){let c=l.session_policy,m=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!c||c.version!==1||c.mode!==(e.mode??"standard")||c.workspaceOwnership!==(e.workspaceOwnership??"managed")||!c.components||m.some((p)=>c.components[p]!==!0))throw await this.cancelSession(a.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&l.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(a.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return l}async getEvents(e,r=-1,a={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${r}&limit=500${a.waitMs?`&wait_ms=${a.waitMs}`:""}`,a.signal?{signal:a.signal}:{})}catch(l){if(!(l instanceof D)||l.status!==403&&l.status!==404)throw l;return{session:await this.getSession(e),items:[],next_seq:r}}}async getMessages(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${r===void 0?"":`&after_seq=${r}`}`)}async getAttachments(e,r){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${r?`?view=${r}`:""}`)).items??[]}catch(a){if(a instanceof D&&(a.status===403||a.status===404))return[];throw a}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let r=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,a=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,l=[r,a].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${l?` (${l})`:""}. The API server needs an attachment-capable deployment; updating the Agent version alone is not enough. Your image was not sent; retry after the server update.`)}}async sendMessage(e,r,a={}){if(a.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:r,...a.attachments?.length?{attachments:a.attachments}:{},...a.model?{model:a.model}:{},...a.reasoningEffort?{reasoning_effort:a.reasoningEffort}:{},...a.target?{target:a.target}:{},...a.delivery?{delivery:a.delivery}:{}}})}async steerQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(r)}/queued`,{method:"DELETE"})}async getConversation(e){let r=[],a=null;for(let l=0;l<50;l+=1){let c=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${a?`?after=${encodeURIComponent(a)}`:""}`);if(r.push(...c.items??[]),!c.has_next_page||!c.end_cursor)break;a=c.end_cursor}return r}createSharedLink(e,r){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:r.url,...r.label?{label:r.label}:{},...r.expiresInSeconds!==void 0?{expires_in_seconds:r.expiresInSeconds}:{}}})}sessionAction(e,r,a={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${r}`,{method:"POST",body:a})}renameSession(e,r){return this.sessionAction(e,"rename",{title:r||null})}moveSessionToProject(e,r){return this.sessionAction(e,"project",{project_id:r})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,r){return this.sessionAction(e,"rewind",{message_id:r.messageId,content:r.content,request_id:r.requestId})}forkSession(e,r){return this.sessionAction(e,"fork",{...r.message?{message:r.message}:{},client_session_id:r.clientSessionId})}cancelSession(e,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:r.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,r=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`}async archiveSession(e){await this.request(this.sessionPath(e,"/archive"),{method:"POST",body:{}})}async unarchiveSession(e){await this.request(this.sessionPath(e,"/unarchive"),{method:"POST",body:{}})}async deleteSession(e){await this.request(this.sessionPath(e),{method:"DELETE"})}async listSessionTags(e){return h(C,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,r){let a=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:r}});return h(C,a,"invalid_session_tags").tags}async sessionInsight(e,r=!1){let a=await this.request(this.sessionPath(e,r?"/insights/generate":"/insights"),r?{method:"POST",body:{}}:{});return h(Re,a,"invalid_session_insight")}async listAutomations(){let e=[],r=null;for(let a=0;a<20;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${r?`&after=${encodeURIComponent(r)}`:""}`),c=h(fe,l,"invalid_automation_list");if(e.push(...c.items),r=c.has_next_page?c.end_cursor??null:null,!r)break}return e}async createScheduledAutomation(e,r){let a=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,l=h(T,await this.request(a,{method:"POST",body:{name:e.name,instructions:e.instructions,...e.repo?{repo:e.repo.full_name,provider:e.repo.provider}:{}}}),"invalid_automation");try{await this.request(`${a}/${encodeURIComponent(l.id)}/triggers`,{method:"POST",body:r})}catch(c){throw await this.deleteAutomation(l.id).catch(()=>{return}),c}return l}async setAutomationEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:r}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,r){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:r}});return h(n({transcript:t()}),a,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return h(_e,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,r){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:r}})}}
|
|
3
|
+
export{ot,D,Ps,rs};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{Je,wo,U,Xe,Jt,zr,x}from"./vm-hands-entry-lite-mh46pt40.js";import{K}from"./vm-hands-entry-lite-wghmyfba.js";import{ft}from"./vm-hands-entry-lite-2v4zh9ze.js";import{gt}from"./vm-hands-entry-lite-2tbf0swk.js";import{qr}from"./vm-hands-entry-lite-atv6x5d3.js";import{Pt,Hi}from"./vm-hands-entry-lite-qd46yhvz.js";import{G,qe}from"./vm-hands-entry-lite-r2qrpjfq.js";import{xe,Jn}from"./vm-hands-entry-lite-mj7yar3a.js";import{St}from"./vm-hands-entry-lite-07apxfh8.js";import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{C}from"./vm-hands-entry-lite-tyem93c1.js";import{spawn as v,spawnSync as st}from"child_process";import{createHash as it,randomUUID as ge}from"crypto";import{closeSync as at,copyFileSync as ae,existsSync as D,fstatSync as ct,mkdirSync as ce,openSync as lt,readdirSync as L,readFileSync as X,readlinkSync as ut,renameSync as he,rmSync as dt,statSync as pt,writeFileSync as mt}from"fs";import{connect as ht}from"net";import{tmpdir as B,userInfo as _e}from"os";import{basename as le,delimiter as _t,dirname as q,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";
|
|
@@ -950,7 +950,7 @@ if(process.env.REASON_CLOUD_GATEWAY_EXEC === "1") {
|
|
|
950
950
|
process.stdout.write(JSON.stringify(cloudAutomationFailure(error))+"\\n");process.exitCode=1;
|
|
951
951
|
}
|
|
952
952
|
}
|
|
953
|
-
`;import{spawn as Ce}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var Me="__desktop-call",De="/usr/bin/setpriv",Le=27262976,Ue=8192,$e=2000;function
|
|
953
|
+
`;import{spawn as Ce}from"child_process";import{lstatSync as V,readFileSync as Z,rmSync as Ne}from"fs";import{basename as Pe}from"path";var Me="__desktop-call",De="/usr/bin/setpriv",Le=27262976,Ue=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 We(){return[process.execPath,...Pe(process.execPath).startsWith("bun")&&process.argv[1]?[process.argv[1]]:[],Me]}function Fe(e){let o=(i)=>{try{return V(i).uid}catch{return null}},t=V("/tmp/.X11-unix",{throwIfNoEntry:!1});if(!t?.isDirectory()||t.uid!==0)return;let n=["/tmp/.X99-lock","/tmp/.X11-unix/X99"].filter((i)=>{let u=o(i);return u!==null&&u!==e.uid});if(!n.length)return;let s="";try{let i=Z("/tmp/.X99-lock","utf8").trim();if(/^\d+$/.test(i))s=Z(`/proc/${i}/comm`,"utf8").trim()}catch{}if(/^X/.test(s))return;for(let i of n)Ne(i,{force:!0})}function Bt(e,o,t,n={}){if(t.throwIfAborted(),(o.op==="display"||o.op==="automation")&&process.platform==="linux"&&process.getuid?.()===0)try{Fe(e)}catch{}let s=n.command??We();return new Promise((i,u)=>{let c=(n.spawnProcess??Ce)(De,[`--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,y)}catch{c.kill(y)}},I=(y)=>{p??=y,h("SIGTERM"),_??=setTimeout(()=>h("SIGKILL"),$e)},S=()=>I(new r("cancelled","Reason cancelled the desktop operation."));t.addEventListener("abort",S,{once:!0});let w=(y)=>{if(g)return;g=!0,clearTimeout(_),t.removeEventListener("abort",S),y()};if(c.stdout.on("data",(y)=>{if(m+=y.byteLength,m>Le)I(new r("desktop_delegate_failed","Reason's desktop reply is too large."));else d.push(y)}),c.stderr.setEncoding("utf8").on("data",(y)=>{l=(l+y).slice(-Ue)}),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",(y,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 A=W(b)&&b.ok===!1&&typeof b.code==="string"&&typeof b.message==="string"?new r(b.code.slice(0,120),b.message.slice(0,2000)):null,J=`exited ${y??Ee}${A?"":" with no reply"}`,Y=l.trim().split(`
|
|
954
954
|
`).at(-1)?.slice(-300)??"";if(!A||A.code==="desktop_delegate_failed")process.stderr.write(`Reason worker: desktop call ${J}${l?`: ${l.trim().slice(-500)}`:""}
|
|
955
|
-
`);if(A)return u(A);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as Ge,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(Ge),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,O=new Map;function T(e,o){let t=O.get(e);if(t?.has(o))return!1;if(!t){if(O.size>=et)O.delete(O.keys().next().value);t=new Set,O.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=Ye(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Je(t,"a",384);try{let s=je(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{Xe(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>pt(e,o),tile:Ir,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(go,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 H=172032,wt=18874368,yt=8192,bt=65536,xt=55000,kt=60000,vt=4,It=40000,Rt=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function M(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function we(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!==St||t.kind!=="browser")||JSON.stringify(t).length>bt)M();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)M();return{output_id:e.output_id,offset:e.offset}}return M()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Ot="__computer-use";function Us(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=v(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 Et(e,o,t,n){return new Promise((s)=>{let i=v(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 R(e)?f(U(),"open-browser-use"):"/tmp/open-browser-use"}function R(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Mt(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"&&Ct.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return L(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)?L(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Mt(await Et(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>Nt)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 Dt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Dt(e.nativeHost,o,{socketDir:Tt(e),extensionId:j,storages:[f(t,"browser-profile","Default","Local Extension Settings",j)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Ht){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=L(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)&&D(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((_)=>d(_)===l),instance:p,socket:g}))}async function Ut(e,o,t=a(),n=Ht){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 W=new Map;function F(e,o){let t=W.get(e);if(!t)t=o().finally(()=>W.delete(e)),W.set(e,t);return t}async function $t(e,o){if(await pe(e))return;if(dt(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"||R(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 _=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=v("/usr/bin/open",["-g","-n","-a",_,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(R(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=v(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 _=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=v(e.browser,[`--user-data-dir=${l}`,...s,..._,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function zs(e){await Re(e,!0)}function qs(e){return ve(e,Ie(e))}function ve(e,o){return e.platform==="darwin-arm64"||R(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!D(o)||!qt(e.automation))return e.automation;if(!Wt(ve(e,o)))try{he(o,e.automation)}catch{}return D(o)?o:e.automation}function qt(e){try{return L(e).length===0}catch(o){return o.code==="ENOENT"}}function Wt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function Re(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=_e().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||R(e)){let l=R(e)?{...s,...Ft(),HOME:a()}:{...s,HOME:a(),PATH:`${B(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Ot};if(!o)return l;await F("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 F("bus",()=>$t(d,m)),o)await F("browser",()=>me(e,m,t));return m}function Ft(){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:U(),TMP:U(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(_t)}}async function Gt(e,o,t){let n=_e().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 Ut(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(U(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!D(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;ft(t,e,{mode:384}),he(t,o)}return[o]}function Ae(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=v(e,jt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,_=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){v(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>_(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>_(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>wt)_(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",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>h(()=>{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>=vt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Oe(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ae)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=we({call:e});if(!("call"in t))M();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 Oe(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>H?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,H).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=we(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+H).toString("base64")}}let s=(o.components??x)(),i=(o.platform??process.platform)==="darwin",u=i?(o.macIdentity??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Hi(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),_;try{if(m){let h=await(o.userChromeEnvironment??Gt)(s,m,e.signal);e.signal.throwIfAborted(),_=await(o.runtime??Ae)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)_=await(o.delegate??Q)(g,t.call,e.signal);else _=await Oe(s,t.call,e.signal,o)}finally{p()}if(i)_=await ie({runId:e.runId,call:t.call,identity:u,output:_,signal:e.signal},c);return fe(_,e.runId,n)}
|
|
955
|
+
`);if(A)return u(A);u(new r("desktop_delegate_failed",`Reason's desktop operation failed (${J}${Y?`: ${Y}`:""}).`))})),t.aborted)S();c.stdin.end(JSON.stringify(o))})}async function Q(e,o,t,n={}){let s=await Bt(e,{op:"automation",call:o},t,n);if(!Number.isSafeInteger(s.code)||typeof s.stdout!=="string"||typeof s.stderr!=="string")throw new r("desktop_delegate_failed","Reason's desktop reply is malformed.");return{code:s.code,stdout:Buffer.from(s.stdout,"base64"),stderr:s.stderr}}import{execFile as He,spawn as Ge}from"child_process";import{closeSync as je,mkdirSync as Ke,openSync as Ye}from"fs";import{dirname as E,join as ze}from"path";import{promisify as Ve}from"util";var Ze=Ve(He),ee="x-apple.systempreferences:com.apple.preference.security",Qe={accessibility:`${ee}?Privacy_Accessibility`,screen:`${ee}?Privacy_ScreenCapture`},et=64,O=new Map;function T(e,o){let t=O.get(e);if(t?.has(o))return!1;if(!t){if(O.size>=et)O.delete(O.keys().next().value);t=new Set,O.set(e,t)}return t.add(o),!0}function tt(){let e=a(),o=Jn(xe(e),process.env),t=ze(e,".local","share","reason","desktop-install.log");Ke(E(t),{recursive:!0,mode:448});let n=Ye(t,"a",384);try{let s=Ge(o,["desktop","install"],{detached:!0,stdio:["ignore",n,n],env:{...process.env,REASON_DESKTOP_BACKGROUND:"1"}});s.on("error",()=>{return}),s.unref()}finally{je(n)}}var N={open:async(e,o)=>{await Ze("/usr/bin/open",e,{signal:o,timeout:1e4,maxBuffer:8192})},request:(e,o)=>ft(e,o),tile:qr,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(wo,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,wt=18874368,yt=8192,bt=65536,xt=55000,kt=60000,vt=4,It=40000,Rt=/^[0-9a-f-]{36}$/,ue=z,At=ge();function P(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function M(){throw new r("invalid_automation_request","Reason automation request is malformed.")}function we(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!==St||t.kind!=="browser")||JSON.stringify(t).length>bt)M();return{call:t,userChrome:n}}if(o==="offset,output_id"){if(typeof e.output_id!=="string"||!Rt.test(e.output_id)||!Number.isSafeInteger(e.offset)||e.offset<0)M();return{output_id:e.output_id,offset:e.offset}}return M()}function Pn(e=process.platform,o=x){if(e==="darwin")return!0;return(e==="linux"||e==="win32")&&o()?.features.computer===!0}var Ot="__computer-use";function Us(e=x){return e()?.userChrome??{code:"user_chrome_browser_use_missing"}}function ye(e,o,t,n){return new Promise((s)=>{let i=v(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 Et(e,o,t,n){return new Promise((s)=>{let i=v(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 R(e)?f(B(),"open-browser-use"):"/tmp/open-browser-use"}function R(e){return e.platform==="win32-x64"||e.platform==="win32-arm64"}var Ct=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nt=33554432;function Mt(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"&&Ct.test(n.extensionInstanceId)?n.extensionInstanceId:null}async function be(e,o,t){let n=t.storages.map((c)=>{try{return L(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)?L(t.socketDir).filter((c)=>c.endsWith(".sock")):[]}catch{return[]}let i=[];for(let c of s){let d=f(t.socketDir,c),m=Mt(await Et(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(pt(m).size>Nt)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 Dt(e,o,t){return(await be(e,o,t))[0]?.instance??null}function Se(e,o,t){return Dt(e.nativeHost,o,{socketDir:Tt(e),extensionId:U,storages:[f(t,"browser-profile","Default","Local Extension Settings",U)]})}var de=/^(Default|Profile ([0-9]+))$/;async function Lt(e,o,t=a(),n=Jt){let s=f(t,"Library","Application Support","Google","Chrome"),i=[];try{i=L(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)&&D(f(s,l,"Extensions",Je))).sort((l,p)=>u(l)-u(p)),d=(l)=>f(s,l,"Local Extension Settings",Je);return(await be(e,o,{socketDir:n,extensionId:Je,storages:c.map(d)})).map(({storage:l,instance:p,socket:g})=>({profile:c.find((_)=>d(_)===l),instance:p,socket:g}))}async function Ut(e,o,t=a(),n=Jt){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 F=new Map;function H(e,o){let t=F.get(e);if(!t)t=o().finally(()=>F.delete(e)),F.set(e,t);return t}async function $t(e,o){if(await pe(e))return;if(dt(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"||R(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=zr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=e.browser.slice(0,e.browser.indexOf(".app/")+4),h=s.filter((I)=>I!=="about:blank").concat("--no-startup-window","--use-mock-keychain");i=v("/usr/bin/open",["-g","-n","-a",_,"--args",`--user-data-dir=${l}`,...h],{env:o,stdio:"ignore"})}else if(R(e)){let l=f(t,"browser-profile");G(l),st(C("icacls"),[q(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=v(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=zr(e.platform).nativeHostManifests[0];ae(g,f(p,le(g)));let _=process.geteuid?.()===0?["--no-sandbox"]:[];u=f(t,"browser.log");let h=lt(u,"a",384);c=ct(h).size,i=v(e.browser,[`--user-data-dir=${l}`,...s,..._,"--force-renderer-accessibility"],{detached:!0,stdio:["ignore",h,h],env:{...o,ACCESSIBILITY_ENABLED:"1"}}),at(h)}let d=!1;i.once("error",()=>{d=!0}),i.once("exit",(l)=>{d||=l!==0}),i.unref();let m=!1;if(await ke(async()=>d||(m=await n()),It),!m){if(u&&X(u).subarray(c).toString("utf8").includes("No usable sandbox"))throw new r("automation_browser_sandbox_unavailable","Chromium found no usable sandbox on this machine. Run the worker as a non-root user with unprivileged user namespaces enabled, or in a container with seccomp unconfined.");throw new r("automation_browser_unavailable","Reason could not connect the desktop browser.")}}async function zs(e){await Re(e,!0)}function qs(e){return ve(e,Ie(e))}function ve(e,o){return e.platform==="darwin-arm64"||R(e)?f(o,"browser-profile"):f(o,"home",".config","google-chrome")}function Ie(e){let o=f(e.root,"automation");if(!D(o)||!qt(e.automation))return e.automation;if(!Wt(ve(e,o)))try{he(o,e.automation)}catch{}return D(o)?o:e.automation}function qt(e){try{return L(e).length===0}catch(o){return o.code==="ENOENT"}}function Wt(e){let o;try{o=ut(f(e,"SingletonLock"))}catch{return!1}let t=Number(o.slice(o.lastIndexOf("-")+1));if(!Number.isSafeInteger(t)||t<=0)return!0;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}async function Re(e,o){Pt({root:e.root,automation:e.automation,extensionDir:e.extensionDir});let t=Ie(e);G(t);let n=_e().username,s={USER:n,LOGNAME:n,REASON_AUTOMATION_OCU:e.ocu,REASON_AUTOMATION_OBU:e.nativeHost};if(e.platform==="darwin-arm64"||R(e)){let l=R(e)?{...s,...Ft(),HOME:a()}:{...s,HOME:a(),PATH:`${q(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OCU:process.execPath,REASON_AUTOMATION_OCU_SUBCOMMAND:Ot};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:`${q(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:Xe(i.sound)}:{}};if(await H("bus",()=>$t(d,m)),o)await H("browser",()=>me(e,m,t));return m}function Ft(){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:B(),TMP:B(),PATH:[t,f(t,"WindowsPowerShell","v1.0"),e].join(_t)}}async function Ht(e,o,t){let n=_e().username,s={USER:n,LOGNAME:n,HOME:a(),PATH:`${q(e.node)}:/usr/bin:/bin:/usr/sbin:/sbin`,REASON_AUTOMATION_OBU:o,REASON_AUTOMATION_BACKGROUND_TABS:"1"},i=await Ut(o,s);return t.throwIfAborted(),{...s,REASON_AUTOMATION_OBU_INSTANCE:i}}function Gt(e){if(process.platform!=="win32")return["--input-type=module","--eval",e];let o=f(B(),`reason-automation-${it("sha256").update(e).digest("hex").slice(0,16)}.mjs`);if(!D(o)||X(o,"utf8")!==e){let t=`${o}.${process.pid}.tmp`;mt(t,e,{mode:384}),he(t,o)}return[o]}function Ae(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=v(e,Gt(s),{env:{...o,REASON_CLOUD_GATEWAY_EXEC:"1",REASON_AUTOMATION_INLINE_RESULT:"1"},stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:!0}),d=[],m=0,l="",p=null,g=!1,_=(w)=>{if(p??=w,process.platform==="win32"&&c.pid){v(f(process.env.SystemRoot??"C:\\Windows","System32","taskkill.exe"),["/pid",String(c.pid),"/t","/f"],{stdio:"ignore",windowsHide:!0}).once("error",()=>c.kill("SIGKILL"));return}try{process.kill(-c.pid,"SIGKILL")}catch{c.kill("SIGKILL")}},h=(w)=>{if(g)return;g=!0,clearTimeout(I),n.removeEventListener("abort",S),w()},I=setTimeout(()=>_(new r("automation_timed_out","Reason automation did not finish in time.")),xt),S=()=>_(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>wt)_(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",()=>h(()=>u(p??new r("automation_unavailable","Reason could not start the automation runtime.")))),c.once("close",(w)=>h(()=>{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 jt(e,o,t){for(let[s,i]of k)if(i.expiresAt<=t)k.delete(s);while(k.size>=vt)k.delete(k.keys().next().value);let n=ge();return k.set(n,{runId:e,bytes:o,expiresAt:t+kt}),n}async function Oe(e,o,t,n={}){let s=await(n.environment??Re)(e,o.kind==="browser");return t.throwIfAborted(),await(n.runtime??Ae)(e.node,s,JSON.stringify(o),t)}async function Ws(e,o){let t=we({call:e});if(!("call"in t))M();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 Oe(n,t.call,o)}function fe(e,o,t){let n=e.stdout.byteLength>j?jt(o,e.stdout,t):void 0;return{code:e.code,stderr:e.stderr,instance_id:At,output_bytes:e.stdout.byteLength,chunk:e.stdout.subarray(0,j).toString("base64"),...n?{output_id:n}:{}}}async function Rn(e,o={}){let t=we(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??gt)():[],c=o.macSetup??N,d=!s?.features.computer||t.call.kind==="browser"&&!t.userChrome&&!s.features.browser;if(i&&(d||u.length===0||t.call.kind==="browser"&&t.userChrome&&!e.userChrome))return fe(await se({runId:e.runId,call:t.call,identity:u,desktopMissing:d,signal:e.signal},c),e.runId,n);if(!s?.features.computer)throw new r("automation_unavailable","Run `reason desktop install` on this machine to enable computer and browser use.");let m=t.userChrome?e.userChrome:void 0;if(t.userChrome&&!m)throw new r("automation_user_chrome_unavailable","Your own Chrome is not enabled on this computer: run `reason desktop install` on this Mac (and `reason connect --user-chrome on` if you turned it off).");if(t.call.kind==="browser"&&!m&&!s.features.browser)throw new r("automation_browser_not_installed",!s.platform.startsWith("linux")?"Browser use is unavailable on this machine: re-run `reason desktop install`.":"Browser use is unavailable on this machine: install a non-snap Chromium at /usr/bin/chromium, then re-run `reason desktop install`.");e.signal.throwIfAborted();let l=t.call.kind==="browser"&&t.call.operation!=="record_start"&&t.call.operation!=="record_stop",p=await Hi(e.runId,e.signal,o.now,l?"call":"run"),g="account"in o?o.account??null:K(),_;try{if(m){let h=await(o.userChromeEnvironment??Ht)(s,m,e.signal);e.signal.throwIfAborted(),_=await(o.runtime??Ae)(s.node,h,JSON.stringify(t.call),e.signal)}else if(g)_=await(o.delegate??Q)(g,t.call,e.signal);else _=await Oe(s,t.call,e.signal,o)}finally{p()}if(i)_=await ie({runId:e.runId,call:t.call,identity:u,output:_,signal:e.signal},c);return fe(_,e.runId,n)}
|
|
956
956
|
export{Bt,Pn,Us,zs,qs,Ws,Rn};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{a}from"./vm-hands-entry-lite-8dfw96ym.js";import{readFileSync as c}from"fs";import{isAbsolute as l,normalize as i}from"path";var m="REASON_WORKER_DESKTOP_USER",u=null;function p(t,o){for(let s of o.split(`
|
|
3
|
-
`)){let e=s.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!l(n)||i(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function Gs(t={}){let o="value"in t?t.value:process.env[m];if(u=null,o===void 0||o==="")return null;let s=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=s==="linux"&&e===0&&Number.isSafeInteger(n)?p(n,(t.passwd??(()=>c("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function K(){return u}function
|
|
4
|
-
export{Gs,K,
|
|
3
|
+
`)){let e=s.split(":");if(e.length<7||Number(e[2])!==t||!/^\d+$/.test(e[2])||!/^\d+$/.test(e[3]))continue;let n=e[5];if(!/^[a-z_][a-z0-9_-]*$/i.test(e[0])||!l(n)||i(n)!==n||n==="/")return null;return{username:e[0],uid:t,gid:Number(e[3]),home:n}}return null}function Gs(t={}){let o="value"in t?t.value:process.env[m];if(u=null,o===void 0||o==="")return null;let s=t.platform??process.platform,e="euid"in t?t.euid:process.geteuid?.(),n=/^[1-9]\d{0,9}$/.test(o)?Number(o):NaN,r=s==="linux"&&e===0&&Number.isSafeInteger(n)?p(n,(t.passwd??(()=>c("/etc/passwd","utf8")))()):null;if(!r||r.gid===0)throw Error("worker_desktop_user_invalid");return u=r,r}function K(){return u}function zn(){return u?.home??a()}
|
|
4
|
+
export{Gs,K,zn};
|