@reason-machines/cli-linux-arm64 0.2.559 → 0.2.561
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/agent-network-kk36zca7.js +2 -0
- package/bin/vm-hands/api-credentials-mtfdk175.js +2 -0
- package/bin/vm-hands/api-w6w7vfp3.js +2 -0
- package/bin/vm-hands/ask-relay-xx0rzpch.js +5 -0
- package/bin/vm-hands/connect-cli-dmwph620.js +2 -0
- package/bin/vm-hands/credentials-s7ps7y6s.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-3xnrp33e.js +2 -0
- package/bin/vm-hands/desktop-account-eg8thn79.js +2 -0
- package/bin/vm-hands/device-workspace-h5rsecq8.js +2 -0
- package/bin/vm-hands/{fsevents-fev1pxw2.js → fsevents-vxv56sp5.js} +1 -1
- package/bin/vm-hands/hands-worker-source-vk664w8p.js +2 -0
- package/bin/vm-hands/{index-j6wffzfd.js → index-03p9c17x.js} +106 -106
- package/bin/vm-hands/install-receipt-j04hdw1k.js +2 -0
- package/bin/vm-hands/local-automation-vvt9d9xb.js +2 -0
- package/bin/vm-hands/local-capabilities-pwv76ns5.js +2 -0
- package/bin/vm-hands/local-desktop-users-sq4trh07.js +2 -0
- package/bin/vm-hands/local-display-mac-yxcxvg2z.js +2 -0
- package/bin/vm-hands/local-display-session-axh9mfdk.js +2 -0
- package/bin/vm-hands/local-display-video-pxhztqk7.js +2 -0
- package/bin/vm-hands/local-managed-process-4mgqn7tg.js +2 -0
- package/bin/vm-hands/local-pty-session-edd8ttf9.js +2 -0
- package/bin/vm-hands/managed-runtime-pcagtyfz.js +2 -0
- package/bin/vm-hands/network-auto-update-wkzb91qz.js +3 -0
- package/bin/vm-hands/network-contract-8mxtma3w.js +2 -0
- package/bin/vm-hands/network-sign-in-61gmpmaa.js +3 -0
- package/bin/vm-hands/package-vwvzjtn0.js +2 -0
- package/bin/vm-hands/permissions-348prrcx.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-1nkpw1v3.js +2 -0
- package/bin/vm-hands/serve-service-3dkyznay.js +2 -0
- package/bin/vm-hands/status-khqk4cjw.js +96 -0
- package/bin/vm-hands/version-c1hen0wn.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-0wb1n769.js +9 -0
- package/bin/vm-hands/{vm-hands-entry-lite-506b6pcz.js → vm-hands-entry-lite-2dak7e1h.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-a3p6xz53.js → vm-hands-entry-lite-2rgf8866.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-52qz0n30.js +7 -0
- package/bin/vm-hands/vm-hands-entry-lite-57ajjwmh.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-5y4phfv1.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-6jxshhps.js +9 -0
- package/bin/vm-hands/vm-hands-entry-lite-71ebge0c.js +42 -0
- package/bin/vm-hands/vm-hands-entry-lite-7pfhwxn5.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-84mc1f7h.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-8xv6c0rm.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-9g52kxyj.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-8rmbdm6c.js → vm-hands-entry-lite-9yfmkd1f.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-a6ss0ges.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-a7bf7xr7.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-ab1pq3xg.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-bj3w2ven.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-q1yvw4xz.js → vm-hands-entry-lite-e3fn8ys2.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-gxpw14jv.js +11 -0
- package/bin/vm-hands/vm-hands-entry-lite-h7nk2848.js +539 -0
- package/bin/vm-hands/vm-hands-entry-lite-hjjbjpd7.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-hn9pq7zj.js +127 -0
- package/bin/vm-hands/vm-hands-entry-lite-hs6sdn60.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-ht6hzkgj.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-hxfxs7r9.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-2v4zh9ze.js → vm-hands-entry-lite-j10cw3d9.js} +9 -9
- package/bin/vm-hands/vm-hands-entry-lite-jgk5z8zc.js +10 -0
- package/bin/vm-hands/vm-hands-entry-lite-jpvmkce5.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-k5ytpgzz.js +65 -0
- package/bin/vm-hands/{vm-hands-entry-lite-s85p7tqp.js → vm-hands-entry-lite-krpqqx12.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-m1we91g4.js +105 -0
- package/bin/vm-hands/{vm-hands-entry-lite-q2h781jg.js → vm-hands-entry-lite-ms99mzp0.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-nn6zcvmp.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-46pwqvpf.js → vm-hands-entry-lite-ptycjmkc.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-pxtycfdv.js +5 -0
- package/bin/vm-hands/vm-hands-entry-lite-q9djb28r.js +4 -0
- package/bin/vm-hands/vm-hands-entry-lite-q9s1e2y1.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-pzj5s203.js → vm-hands-entry-lite-qf990rxw.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-sy7dcccg.js +2 -0
- package/bin/vm-hands/vm-hands-entry-lite-tcmye5ny.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-1yv5qqew.js → vm-hands-entry-lite-v4hr9x9h.js} +45 -45
- package/bin/vm-hands/vm-hands-entry-lite-vdv4nm5f.js +3 -0
- package/bin/vm-hands/vm-hands-entry-lite-vkhacd00.js +452 -0
- package/bin/vm-hands/vm-hands-entry-lite-wcgm41jq.js +52 -0
- package/bin/vm-hands/vm-hands-entry-lite-weqam12f.js +6 -0
- package/bin/vm-hands/{vm-hands-entry-lite-jrce7v4r.js → vm-hands-entry-lite-xvccy3z4.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-y3nz20wb.js +345 -0
- package/bin/vm-hands/vm-hands-entry-lite-yvws5zpx.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-qd46yhvz.js → vm-hands-entry-lite-z0ht62s4.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-z213y4pj.js +150 -0
- package/bin/vm-hands/vm-hands-entry-lite-zawytz09.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-h2rq71rj.js → vm-hands-entry-lite-zh6ncdjn.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/{vm-hands-executor-p2jvbq5w.js → vm-hands-executor-csdtg7kj.js} +8 -8
- package/bin/vm-hands/vm-hands-op-runner-z7tsd84c.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-889hfy4p.js → vm-hands-runtime-1qxf96z7.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-06tygyjs.js +2 -0
- package/bin/vm-hands/worker-sandbox-e1cpkzfz.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/api-credentials-x30e4ezb.js +0 -2
- package/bin/vm-hands/api-y6v8wdsq.js +0 -2
- package/bin/vm-hands/connect-cli-32wrv6sw.js +0 -2
- package/bin/vm-hands/credentials-sbza33ac.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-mydksbg8.js +0 -2
- package/bin/vm-hands/desktop-account-t0afsge2.js +0 -2
- package/bin/vm-hands/device-workspace-b534qy2c.js +0 -2
- package/bin/vm-hands/hands-worker-source-qj7s9dk5.js +0 -2
- package/bin/vm-hands/install-receipt-zv1bjbgh.js +0 -2
- package/bin/vm-hands/local-automation-pwwqrnt7.js +0 -2
- package/bin/vm-hands/local-capabilities-scnpxe96.js +0 -2
- package/bin/vm-hands/local-desktop-users-5scb9930.js +0 -2
- package/bin/vm-hands/local-display-mac-pft73te9.js +0 -2
- package/bin/vm-hands/local-display-session-9362hqsn.js +0 -2
- package/bin/vm-hands/local-display-video-dndhr5v1.js +0 -2
- package/bin/vm-hands/local-managed-process-zm639p1g.js +0 -2
- package/bin/vm-hands/local-pty-session-njd0tprg.js +0 -2
- package/bin/vm-hands/managed-runtime-cqkw2mtn.js +0 -2
- package/bin/vm-hands/network-contract-kx0hz3wt.js +0 -2
- package/bin/vm-hands/package-way7qesn.js +0 -2
- package/bin/vm-hands/permissions-jxycbgay.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-g54rtrhd.js +0 -2
- package/bin/vm-hands/serve-service-byvya1ym.js +0 -2
- package/bin/vm-hands/status-f1k1qmck.js +0 -10
- package/bin/vm-hands/version-czwf27v3.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-04x5xjt6.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-07apxfh8.js +0 -42
- package/bin/vm-hands/vm-hands-entry-lite-0wsr8edk.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-1tgxze8w.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-2twtpxmp.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-3gbf905c.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-48rphbjm.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-4anjdcth.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-73f4cgkf.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-8dfw96ym.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ak0hd94p.js +0 -7
- package/bin/vm-hands/vm-hands-entry-lite-bpamn7ny.js +0 -9
- package/bin/vm-hands/vm-hands-entry-lite-dgfx0rbn.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-ecz6fzds.js +0 -126
- package/bin/vm-hands/vm-hands-entry-lite-frd7e74y.js +0 -5
- package/bin/vm-hands/vm-hands-entry-lite-fxzadxz4.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-gje7xvy9.js +0 -6
- package/bin/vm-hands/vm-hands-entry-lite-h1qjggz0.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-j3fw7x65.js +0 -14
- package/bin/vm-hands/vm-hands-entry-lite-jydpev8e.js +0 -452
- package/bin/vm-hands/vm-hands-entry-lite-k84zsash.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-kf2jgke1.js +0 -150
- package/bin/vm-hands/vm-hands-entry-lite-m0gsez4t.js +0 -539
- package/bin/vm-hands/vm-hands-entry-lite-n7bd44rm.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-p5ny1pw4.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-qcktp8d9.js +0 -52
- package/bin/vm-hands/vm-hands-entry-lite-ravxhygk.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-s0rx4fm8.js +0 -105
- package/bin/vm-hands/vm-hands-entry-lite-tyem93c1.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-vj7xzb3y.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-wghmyfba.js +0 -4
- package/bin/vm-hands/vm-hands-entry-lite-wzv13c8k.js +0 -65
- package/bin/vm-hands/vm-hands-entry-lite-yptpy066.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-yretc2th.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-zf0h0qjy.js +0 -2
- package/bin/vm-hands/vm-hands-op-runner-2bfbyj4e.js +0 -2
- package/bin/vm-hands/worker-preview-readiness-gy36ejp9.js +0 -2
- package/bin/vm-hands/worker-sandbox-f1tfb3y0.js +0 -2
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{w}from"./vm-hands-entry-lite-q9s1e2y1.js";import{existsSync as T,mkdirSync as k,readFileSync as d,rmSync as y,writeFileSync as b}from"fs";import{homedir as l,hostname as M}from"os";import{dirname as N,join as h}from"path";function f(t){let e=t.trim().slice(t.trim().indexOf("#")+1),o=["rn1-","tincan1"].find((a)=>e.startsWith(a));if(!o)return null;let n=Buffer.from(e.slice(o.length),"base64url"),r=32,i=(a)=>(r+=a,r<=n.length),m=()=>{let a=n[r];if(a===void 0||!i(1))return!1;if(a!==255)return i(a);let s=n[r];return s!==void 0&&i(1)&&i(s)};if(n.length<32||!m()||!m()||!m())return null;let u=n[r];if(u===void 0||!i(1))return null;for(let a=0;a<u;a+=1){let s=n[r];if(!i(1)||!i(s===4?4:s===6?16:Number.NaN)||!i(2))return null}let g=[];for(;r+32<=n.length;r+=32)g.push(n.subarray(r,r+32).toString("hex"));return{team:n.subarray(0,16).toString("hex"),name:n.subarray(33,33+n[32]).toString("utf8"),secret:n.subarray(16,32).toString("hex"),machines:g}}var p=(t)=>h(t,".reason","ask.json");function A(t){try{let e=JSON.parse(d(p(t),"utf8"));if(typeof e.orgId!=="string"||typeof e.team!=="string")return null;let o=e.pendingRotation;return{orgId:e.orgId,team:e.team,...typeof e.checkedAt==="number"?{checkedAt:e.checkedAt}:{},...o&&typeof o.link==="string"&&typeof o.team==="string"&&typeof o.replaces==="string"?{pendingRotation:o}:{}}}catch{return null}}var c=(t)=>{let e=w();return h(t,".reason",e==="production"?"network-team.json":`network-team.${e}.json`)};function ma(t=l()){return c(t).replace(/\.json$/,"-login.json")}function ga(t=l()){try{let e=JSON.parse(d(c(t),"utf8"));return typeof e.team==="string"?{team:e.team,setupDone:e.setupDone===!0,registered:typeof e.registered==="string"?e.registered:null,account:typeof e.account==="string"?e.account:null}:null}catch{return null}}function _a(t,e=l()){k(N(c(e)),{recursive:!0}),b(c(e),`${JSON.stringify(t)}
|
|
3
|
+
`,{mode:384}),y(p(e),{force:!0})}function Ur(t=l()){let e=A(t);return e?{orgId:e.orgId,team:e.team}:null}function zr(t){let e=f(t);return e&&e.machines.length>0?{teamId:e.team,teamName:e.name,secret:e.secret}:null}
|
|
4
|
+
export{ma,ga,_a,Ur,zr};
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{O,Rn,ns,Xt,is,os}from"./vm-hands-entry-lite-j10cw3d9.js";import{ls}from"./vm-hands-entry-lite-6jxshhps.js";import{Ko}from"./vm-hands-entry-lite-q9djb28r.js";import{s}from"./vm-hands-entry-lite-zawytz09.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as _s,spawn as qe}from"child_process";import{existsSync as ks}from"fs";import{connect as vs}from"net";function gn(){let e=new Set,t=null,n=(i)=>({holder:t?.viewer??null,you:t===i,same_user:Boolean(t?.viewer&&i.viewer&&t.viewer.user_id===i.viewer.user_id)}),o=()=>{for(let i of e)i.notify(n(i))};return{join(i){return e.add(i),i.notify(n(i)),()=>{if(!e.delete(i))return;if(t!==i)return;t=null,o()}},claim(i){if(t===i||!e.has(i))return;t=i,o()}}}var ut=gn();import{createHash as vt}from"crypto";import{once as Pn}from"events";import{createWriteStream as Cn,existsSync as Mn,mkdirSync as Tn,mkdtempSync as hr,readFileSync as de,readdirSync as br,renameSync as On,realpathSync as An,rmSync as $n,statSync as Ue,writeFileSync as Ln}from"fs";import{delimiter as wr,dirname as Be,join as y}from"path";import{finished as Nn}from"stream/promises";var Gt="omljlfpmafedpplnpkkahegadhkimdje",lc="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var A={ocu:{repository:"https://github.com/iFurySt/open-codex-computer-use.git",revision:"386a260d1ab8b690adbbb27f7471595cf0c2b752",version:"0.3.5"},obu:{repository:"https://github.com/iFurySt/open-browser-use.git",revision:"ac015846df75928fbcf0f3a0f3ba3a210ce1a507",version:"0.1.42"}},F={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var J={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${A.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${A.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${A.obu.version}/open-browser-use-chrome-extension-${A.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},le="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as Te}from"child_process";import{createRequire as hn}from"module";import{join as bn}from"path";var xn=30000,_n=1048576;function Oe(){return process.env.SystemRoot??"C:\\Windows"}function kn(){return bn(Oe(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var vn=String.raw`
|
|
3
|
+
$ErrorActionPreference = "Stop"
|
|
4
|
+
Add-Type -TypeDefinition @"
|
|
5
|
+
using System;
|
|
6
|
+
using System.Runtime.InteropServices;
|
|
7
|
+
public static class ReasonInput {
|
|
8
|
+
[StructLayout(LayoutKind.Sequential)] public struct MOUSEINPUT { public int dx; public int dy; public int mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
9
|
+
[StructLayout(LayoutKind.Sequential)] public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
|
|
10
|
+
[StructLayout(LayoutKind.Explicit)] public struct UNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
|
|
11
|
+
[StructLayout(LayoutKind.Sequential)] public struct INPUT { public uint type; public UNION u; }
|
|
12
|
+
[DllImport("user32.dll")] static extern uint SendInput(uint count, INPUT[] inputs, int size);
|
|
13
|
+
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
|
|
14
|
+
[DllImport("user32.dll")] public static extern int GetSystemMetrics(int index);
|
|
15
|
+
[DllImport("user32.dll")] static extern uint MapVirtualKey(uint code, uint type);
|
|
16
|
+
[DllImport("user32.dll")] public static extern uint GetClipboardSequenceNumber();
|
|
17
|
+
static void Send(INPUT input) { SendInput(1, new INPUT[] { input }, Marshal.SizeOf(typeof(INPUT))); }
|
|
18
|
+
public static void Mouse(uint flags, int x, int y, int data) {
|
|
19
|
+
INPUT input = new INPUT(); input.type = 0;
|
|
20
|
+
input.u.mi.dx = x; input.u.mi.dy = y; input.u.mi.mouseData = data; input.u.mi.dwFlags = flags; Send(input);
|
|
21
|
+
}
|
|
22
|
+
public static void Key(ushort vk, ushort unit, uint flags) {
|
|
23
|
+
INPUT input = new INPUT(); input.type = 1;
|
|
24
|
+
input.u.ki.wVk = vk; input.u.ki.wScan = vk != 0 ? (ushort)MapVirtualKey(vk, 0) : unit; input.u.ki.dwFlags = flags; Send(input);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
"@
|
|
28
|
+
[void][ReasonInput]::SetProcessDPIAware()
|
|
29
|
+
$width = [ReasonInput]::GetSystemMetrics(0)
|
|
30
|
+
$height = [ReasonInput]::GetSystemMetrics(1)
|
|
31
|
+
$session = [Diagnostics.Process]::GetCurrentProcess().SessionId
|
|
32
|
+
[Console]::Out.WriteLine('{"session":' + $session + ',"width":' + $width + ',"height":' + $height + '}')
|
|
33
|
+
[Console]::Out.Flush()
|
|
34
|
+
$mode = "__MODE__"
|
|
35
|
+
if ($mode -eq "probe") { exit 0 }
|
|
36
|
+
if ($mode -eq "clipboard") {
|
|
37
|
+
# Only changes made during this pairing: never export the initial clipboard.
|
|
38
|
+
$parent = Get-Process -Id __PARENT__
|
|
39
|
+
$last = [ReasonInput]::GetClipboardSequenceNumber()
|
|
40
|
+
while (-not $parent.HasExited) {
|
|
41
|
+
Start-Sleep -Milliseconds 100
|
|
42
|
+
$count = [ReasonInput]::GetClipboardSequenceNumber()
|
|
43
|
+
if ($count -eq $last) { continue }
|
|
44
|
+
$last = $count
|
|
45
|
+
try { $text = Get-Clipboard -Raw } catch { continue }
|
|
46
|
+
if (-not $text) { continue }
|
|
47
|
+
$bytes = [Text.Encoding]::UTF8.GetBytes($text)
|
|
48
|
+
if ($bytes.Length -gt __MAX_TEXT_BYTES__) { continue }
|
|
49
|
+
[Console]::Out.WriteLine("c " + [Convert]::ToBase64String($bytes))
|
|
50
|
+
[Console]::Out.Flush()
|
|
51
|
+
}
|
|
52
|
+
exit 0
|
|
53
|
+
}
|
|
54
|
+
$scaleX = 65535.0 / [Math]::Max(1, $width - 1)
|
|
55
|
+
$scaleY = 65535.0 / [Math]::Max(1, $height - 1)
|
|
56
|
+
while ($null -ne ($line = [Console]::In.ReadLine())) {
|
|
57
|
+
$n = $line.Split(" ")
|
|
58
|
+
try {
|
|
59
|
+
switch ($n[0]) {
|
|
60
|
+
"p" { [ReasonInput]::Mouse(0x8001, [int]([int]$n[1] * $scaleX), [int]([int]$n[2] * $scaleY), 0) }
|
|
61
|
+
"b" { [ReasonInput]::Mouse([uint32]$n[1], 0, 0, [int]$n[2]) }
|
|
62
|
+
"k" { [ReasonInput]::Key([uint16]$n[1], [uint16]$n[2], [uint32]$n[3]) }
|
|
63
|
+
"c" { Set-Clipboard -Value ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($n[1]))) }
|
|
64
|
+
}
|
|
65
|
+
} catch { [Console]::Error.WriteLine("input: $_") }
|
|
66
|
+
}
|
|
67
|
+
`;function Ae(e){let t=vn.replace("__MODE__",e).replace("__PARENT__",String(process.pid)).replace("__MAX_TEXT_BYTES__",String(O));return[kn(),["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(t,"utf16le").toString("base64")]]}var Sn=["USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP","PSModuleAnalysisCachePath"];function $e(){let e=Sn.flatMap((t)=>process.env[t]?[[t,process.env[t]]]:[]);return{...Object.fromEntries(e),SystemRoot:Oe(),windir:Oe()}}function ht(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!=="object")return null;let n=t,o=(i,a)=>typeof i==="number"&&Number.isSafeInteger(i)&&i>=a;return o(n.session,0)&&o(n.width,1)&&o(n.height,1)?{session:n.session,width:n.width,height:n.height}:null}function bt(){return new Promise((e)=>{let t=Te(...Ae("probe"),{env:$e(),stdio:["ignore","pipe","ignore"],windowsHide:!0}),n="",o=setTimeout(()=>{t.kill("SIGKILL"),e(null)},xn);t.stdout.setEncoding("utf8").on("data",(i)=>{n+=i}),t.once("error",()=>{clearTimeout(o),e(null)}),t.once("close",()=>{clearTimeout(o),e(ht(n.split(/\r?\n/)[0]??""))})})}var Z;function yt(){if(Z!==void 0)return Z;if(process.platform!=="win32")return Z=!1;try{let e=hn(import.meta.url)("bun:ffi"),{symbols:t}=e.dlopen("kernel32.dll",{GetCurrentProcessId:{args:[],returns:e.FFIType.u32},ProcessIdToSessionId:{args:[e.FFIType.u32,e.FFIType.ptr],returns:e.FFIType.i32}}),n=new Uint32Array(1);return Z=t.ProcessIdToSessionId(t.GetCurrentProcessId(),n)!==0&&n[0]>0}catch{return Z=!1}}var lt=[{bit:1,down:2,up:4},{bit:2,down:32,up:64},{bit:4,down:8,up:16}],dt=2048,pt=4096,En=[[8,dt,120],[16,dt,-120],[32,pt,-120],[64,pt,120]],ft=1,Me=2,Dn=4,In=new Set([65505,65506]),mt=new Set([65507,65508,65511,65512,65513,65514,65027,65515,65516]),gt=new Map([[65505,[160,!1]],[65506,[161,!1]],[65507,[162,!1]],[65508,[163,!0]],[65511,[164,!1]],[65512,[165,!0]],[65513,[164,!1]],[65514,[165,!0]],[65027,[165,!0]],[65515,[91,!0]],[65516,[92,!0]],[65288,[8,!1]],[65289,[9,!1]],[65056,[9,!1]],[65293,[13,!1]],[65307,[27,!1]],[65535,[46,!0]],[65379,[45,!0]],[65360,[36,!0]],[65367,[35,!0]],[65365,[33,!0]],[65366,[34,!0]],[65361,[37,!0]],[65362,[38,!0]],[65363,[39,!0]],[65364,[40,!0]],[65383,[93,!0]],[65509,[20,!1]],[65299,[19,!1]],[65300,[145,!1]],[65377,[44,!0]],[65407,[144,!0]],[32,[32,!1]],[65421,[13,!0]],[65408,[32,!1]],[65450,[106,!1]],[65451,[107,!1]],[65452,[108,!1]],[65453,[109,!1]],[65454,[110,!1]],[65455,[111,!0]],[65429,[36,!1]],[65430,[37,!1]],[65431,[38,!1]],[65432,[39,!1]],[65433,[40,!1]],[65434,[33,!1]],[65435,[34,!1]],[65436,[35,!1]],[65438,[45,!1]],[65439,[46,!1]],...Array.from({length:10},(e,t)=>[65456+t,[96+t,!1]]),...Array.from({length:24},(e,t)=>[65470+t,[112+t,!1]])]);class wt{x=-1;y=-1;mask=0;held=new Set;pressed=new Set;pointer(e,t,n){let o=[];if(e!==this.x||t!==this.y)this.x=e,this.y=t,o.push(`p ${e} ${t}`);for(let i of lt){let a=(this.mask&i.bit)!==0,c=(n&i.bit)!==0;if(a!==c)o.push(`b ${c?i.down:i.up} 0`)}for(let[i,a,c]of En)if(!(this.mask&i)&&n&i)o.push(`b ${a} ${c}`);return this.mask=n,o}key(e,t){let n=e?0:Me;if(In.has(t)||mt.has(t))if(e)this.held.add(t);else this.held.delete(t);let o=gt.get(t);if(o)return[`k ${o[0]} 0 ${n|(o[1]?ft:0)}`];let i=t<256?t:(t&4278190080)===16777216?t&16777215:0,a=String.fromCharCode(i),c=[...this.held].some((w)=>mt.has(w)),p=/^[A-Za-z0-9]$/.test(a)?a.toUpperCase().charCodeAt(0):0;if(p&&(e?c:this.pressed.has(p))){if(e)this.pressed.add(p);else this.pressed.delete(p);return[`k ${p} 0 ${n}`]}if(i<33||i>=127&&i<160||i>65535||i>=55296&&i<57344)return[];return[`k 0 ${i} ${n|Dn}`]}release(){let e=lt.filter((t)=>this.mask&t.bit).map((t)=>`b ${t.up} 0`);for(let t of this.pressed)e.push(`k ${t} 0 ${Me}`);for(let t of this.held){let[n,o]=gt.get(t);e.push(`k ${n} 0 ${Me|(o?ft:0)}`)}return this.mask=0,this.pressed.clear(),this.held.clear(),e}}function xt(e){let t=Te(...Ae("input"),{env:$e(),stdio:["pipe","pipe","ignore"],windowsHide:!0}),n=new wt,o="",i=!1,a=null,c=()=>{if(a?.kill("SIGKILL"),t.exitCode!==null||t.signalCode!==null)return;t.stdin.end(n.release().map((f)=>`${f}
|
|
68
|
+
`).join("")),setTimeout(()=>t.kill("SIGKILL"),2000).unref()},p=(f)=>{if(i)return;i=!0,c(),e.end(f)},w=(f)=>p({error:new r("display_unavailable",f)}),b=(f)=>{if(i||f.length===0)return;if(t.stdin.write(f.map((x)=>`${x}
|
|
69
|
+
`).join("")),t.stdin.writableLength>_n)p({reason:"input_backpressure"})},h=()=>{a=Te(...Ae("clipboard"),{env:$e(),stdio:["ignore","pipe","ignore"],windowsHide:!0});let f="";a.stdout?.on("data",(x)=>{if(i)return;f+=x.toString("ascii");for(let m=f.indexOf(`
|
|
70
|
+
`);m>=0;m=f.indexOf(`
|
|
71
|
+
`)){let R=f.slice(0,m).replace(/\r$/,"");if(f=f.slice(m+1),!R.startsWith("c "))continue;let S=R.slice(2);if(S.length>Math.ceil(O/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(S)){p({reason:"display_protocol"});return}let u=Buffer.from(S,"base64");if(u.byteLength<=O)e.clipboard(u.toString("utf8"));if(i)return}if(f.length>Math.ceil(O/3)*4+4)p({reason:"display_protocol"})}),a.once("error",()=>w("Reason could not watch this computer's desktop clipboard.")),a.once("exit",()=>{if(!i)w("Reason could not watch this computer's desktop clipboard.")})};return t.stdout.on("data",(f)=>{if(i||o===null)return;o+=f.toString("utf8");let x=o.indexOf(`
|
|
72
|
+
`);if(x<0){if(o.length>4096)p({reason:"display_protocol"});return}let m=ht(o.slice(0,x).trim());if(o=null,!m)p({reason:"display_protocol"});else if(m.session===0)w("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else h(),e.ready({width:m.width,height:m.height})}),t.stdin.on("error",()=>{return}),t.once("error",()=>w("Reason could not start this computer's desktop input.")),t.once("exit",()=>{if(o!==null)w("Reason could not start this computer's desktop input.");else p({reason:"display_closed"})}),{pointer:(f,x,m)=>b(n.pointer(f,x,m)),key:(f,x)=>b(n.key(f,x)),clipboard:(f)=>b([`c ${Buffer.from(f,"utf8").toString("base64")}`]),close(){i=!0,c()}}}var Un=["none","standard","all"],ue="22.23.4",Bn={"linux-x64":"b8492284c76a54baf58d61668dd0e41ee0fc98adabf9503d30f05d08f55b4406","linux-arm64":"f7a1e486dbc8b286847815b477d4fb5e9fb963ed4489c3e1588853d685f589f9","darwin-arm64":"c9e1dbc748b33ed2d14f42445191ecaf14c56259c7a9a26d0042c49ec2b66428","win32-x64":"cbc74b5e0982c9dbb41525fd8fb5dcd32fbee237863f7829072f4639a1ce5f20","win32-arm64":"a8b8cd79cbbb3062435f449591d98dd63730bbbf30ce2d7cc3a6376c236cb111"},Le={"linux-x64":{ocu:"dist/linux/amd64/open-computer-use",obu:"native/linux-amd64/open-browser-use"},"linux-arm64":{ocu:"dist/linux/arm64/open-computer-use",obu:"native/linux-arm64/open-browser-use"},"darwin-arm64":{ocu:"dist/Open Computer Use.app/Contents/MacOS/OpenComputerUse",obu:"native/darwin-arm64/open-browser-use"},"win32-x64":{ocu:"dist/windows/amd64/open-computer-use.exe",obu:"native/windows-amd64/open-browser-use.exe"},"win32-arm64":{ocu:"dist/windows/arm64/open-computer-use.exe",obu:"native/windows-arm64/open-browser-use.exe"}},St="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",Et="chrome-win64/chrome.exe",W={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},Hn={version:W.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},Ne={version:W.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${W.version}/ffmpeg-${W.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},_t=`ffmpeg-${Ne.version}-essentials_build/bin`,z="com.ifuryst.open_browser_use.extension",Dt="com.reasonmachines.browser_use.extension",yn="/tmp/reason-browser-use",He=["tint2","picom","xterm","pcmanfm"],It=["fonts-droid-fallback"],Pt=["pulseaudio"],Ct=["tigervnc-standalone-server"],Fn=["xvfb","openbox","x11vnc","x11-utils","x11-xserver-utils","xdotool","dbus-x11","at-spi2-core","python3","python3-gi","gir1.2-atspi-2.0","gir1.2-gtk-3.0","fonts-dejavu-core",...It,"galculator","chromium","ffmpeg","tmux",...Pt,...Ct,...He],zn=new Set([...He,...It,...Pt,...Ct]),kt=Fn.filter((e)=>e!=="chromium"&&!zn.has(e)),jn=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],ce="/usr/bin/chromium",Vn=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function Rt(e=process.platform,t=process.arch){let n=`${e}-${t}`;return n==="linux-x64"||n==="linux-arm64"||n==="darwin-arm64"||n==="win32-x64"||n==="win32-arm64"?n:null}function K(e){return e==="win32-x64"||e==="win32-arm64"}function Fe(e){return K(e)?`node-v${ue}-${e.replace("win32","win")}`:`node-v${ue}-${e}`}function pe(e){return{node:{version:ue,url:`https://nodejs.org/dist/v${ue}/${Fe(e)}${K(e)?".zip":".tar.gz"}`,sha256:Bn[e]},open_computer_use:{version:A.ocu.version,url:J.ocu.url,sha256:J.ocu.sha256},open_browser_use:{version:A.obu.version,url:J.obu.url,sha256:J.obu.sha256},...e==="darwin-arm64"?{chrome_for_testing:{version:F.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${F.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:F.macArm64Sha256}}:K(e)?{chrome_for_testing:{version:F.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${F.version}/win64/chrome-win64.zip`,sha256:F.win64Sha256}}:{}}}function Gn(e){let t={extension:le};for(let[n,o]of Object.entries(pe(e)))t[n]=`${o.version}@${o.sha256}`;return t}function Mt(e){return y(e,".local","share","reason","desktop")}function wn(e,t=Ko()){let n=Mt(t),o=(f)=>y(n,f,pe(e)[f]?.version??""),i=o("open_computer_use"),a=o("open_browser_use"),c=e==="darwin-arm64",p=K(e),w=y(t,"Library","Application Support"),b=y(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:y(t,"AppData","Local"),"OpenBrowserUse"),h=c?y(w,"Google","Chrome","NativeMessagingHosts",`${z}.json`):p?y(b,"NativeMessagingHosts",`${z}.json`):y(t,".config","google-chrome","NativeMessagingHosts",`${z}.json`);return{root:n,automation:y(Be(n),"automation"),receipt:y(n,"receipt.json"),minimal:je(t),node:p?y(o("node"),Fe(e),"node.exe"):y(o("node"),"bin","node"),ocuDir:i,ocu:y(i,Le[e].ocu),ocuApp:c?y(i,"dist","Open Computer Use.app"):null,obuDir:a,obu:y(a,"cli","open-browser-use.js"),nativeHost:y(a,Le[e].obu),extensionDir:c?y(w,"OpenBrowserUse","chrome-extension","release"):p?y(b,"chrome-extension","release"):y(t,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:h,nativeHostManifests:c?[h,y(w,"Google","ChromeForTesting","NativeMessagingHosts",`${z}.json`)]:p?[h]:[y(t,".config","chromium","NativeMessagingHosts",`${z}.json`),y(t,".config","google-chrome-for-testing","NativeMessagingHosts",`${z}.json`)],browser:c?y(o("chrome_for_testing"),St):p?y(o("chrome_for_testing"),Et):ce,userChromeHost:c?y(n,"user-chrome","reason-browser-use"):null,userChromeRegistration:c?y(w,"Google","Chrome","NativeMessagingHosts",`${Dt}.json`):null,ffmpegDir:y(n,"ffmpeg"),ffmpeg:c?y(n,"ffmpeg",W.version,"ffmpeg"):p?y(n,"ffmpeg",Ne.version,_t,"ffmpeg.exe"):null,ffprobe:c?y(n,"ffprobe",Hn.version,"ffprobe"):p?y(n,"ffmpeg",Ne.version,_t,"ffprobe.exe"):null}}function Tt(e){try{let t=JSON.parse(de(e,"utf8"));if(typeof t!=="object"||t===null)return null;let n=t,o=n.pins;if(n.schema_version!==1||typeof n.platform!=="string"||typeof o!=="object"||o===null||!Object.values(o).every((i)=>typeof i==="string")||!Un.includes(n.permissions)||!Array.isArray(n.missing_system_packages)||!n.missing_system_packages.every((i)=>typeof i==="string")||typeof n.updated_at!=="string")return null;return{schema_version:1,platform:n.platform,pins:o,permissions:n.permissions,missing_system_packages:n.missing_system_packages,updated_at:n.updated_at}}catch{return null}}function Wn(e,t,n=384){Tn(Be(e),{recursive:!0,mode:448});let o=`${e}.pending.${process.pid}`;Ln(o,t,{mode:n}),On(o,e)}function L(e){try{return Ue(e).isFile()}catch{return!1}}function Ot(e){try{let t=Ue(e);return t.isFile()&&(t.mode&73)!==0}catch{return!1}}function Kn(e){try{return de(e,"utf8")}catch{return null}}function B(e){for(let t of Vn){let n=y(t,e);try{let o=Ue(n);if(o.isFile()&&(o.mode&73)!==0)return n}catch{}}return null}function Xn(e){try{let t=JSON.parse(de(y(e,"package.json"),"utf8"));return typeof t==="object"&&t!==null&&typeof t.version==="string"?t.version:null}catch{return null}}function qn(e,t,n){let o=pe(n)[e];if(!o)return!1;let i=K(n);if(e==="node")return L(i?y(t,Fe(n),"node.exe"):y(t,"bin","node"));if(e==="chrome_for_testing")return L(y(t,i?Et:St));let a=Le[n][e==="open_computer_use"?"ocu":"obu"];return Xn(t)===o.version&&L(y(t,a))&&(e==="open_computer_use"||L(y(t,"cli","open-browser-use.js")))}function Yn(e){return vt("sha256").update(Buffer.from(e,"base64")).digest("hex").slice(0,32).replace(/./g,(t)=>String.fromCharCode(97+Number.parseInt(t,16)))}function ze(e){try{let t=JSON.parse(de(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Jn(e){let t=ze(y(e.extensionDir,"manifest.json"));return t!==null&&t.version===A.obu.version&&typeof t.key==="string"&&Yn(t.key)===le}function Zn(e,t){let n=e?.allowed_origins;return e!==null&&e.name===z&&Array.isArray(n)&&n.length===1&&n[0]===`chrome-extension://${le}/`&&(t===void 0||e.path===t)}function Qn(e){return Jn(e)&&L(e.nativeHost)&&e.nativeHostManifests.every((t)=>Zn(ze(t),e.nativeHost))}function es(e){return`#!/bin/sh
|
|
73
|
+
# Reason's Chrome extension host (reason desktop install): Open Browser Use on Reason's socket directory.
|
|
74
|
+
obu=${`'${e.replaceAll("'","'\\''")}'`}
|
|
75
|
+
case "$1" in
|
|
76
|
+
chrome-extension://*) exec "$obu" host --socket-dir ${yn} ;;
|
|
77
|
+
mcp) shift; exec "$obu" mcp --socket-dir ${yn} "$@" ;;
|
|
78
|
+
esac
|
|
79
|
+
exec "$obu" "$@"
|
|
80
|
+
`}function ts(e){let t=ze(e),n=t?.allowed_origins;return t!==null&&t.name===Dt&&t.type==="stdio"&&Array.isArray(n)&&n.includes(`chrome-extension://${Gt}/`)&&typeof t.path==="string"&&Ot(t.path)}function ss(e,t){if(!e.userChromeHost||!e.userChromeRegistration)return null;if(!t||Kn(e.userChromeHost)!==es(e.nativeHost)||!Ot(e.userChromeHost))return{code:"user_chrome_browser_use_missing"};return ts(e.userChromeRegistration)?{host:e.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var rs={display:["display","desktop_session","desktop_video"],computer:["display","desktop_session","system_packages","node","open_computer_use"],browser:["display","desktop_session","system_packages","node","open_computer_use","open_browser_use","browser_extension","browser","chrome_for_testing"]};function T(e={}){let t=e.platform===void 0?Rt():e.platform;if(!t)return null;let n=wn(t,e.home),o=Tt(n.receipt),i=Gn(t),a=o!==null&&o.platform===t&&JSON.stringify(Object.entries(o.pins).sort())===JSON.stringify(Object.entries(i).sort()),c=[],p=pe(t);for(let u of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let _=p[u];if(!_)continue;let v=qn(u,y(n.root,u,_.version),t),E=o?.pins[u],N=v&&E===i[u]?"ready":E!==void 0&&E!==i[u]?"outdated":"missing";c.push({name:u,state:N,detail:_.version})}let w=o?.pins.extension===le&&Qn(n);c.push({name:"browser_extension",state:w?"ready":"missing",detail:le});let b=B("Xvfb"),h=B("x11vnc"),f=B("openbox");if(K(t))c.push(yt()?{name:"desktop_session",state:"ready",detail:"signed-in desktop session"}:{name:"desktop_session",state:"missing",detail:"run the worker in the signed-in desktop session, not as a service"}),c.push(n.ffmpeg&&L(n.ffmpeg)?{name:"desktop_video",state:"ready",detail:n.ffmpeg}:{name:"desktop_video",state:"missing",detail:"run `reason desktop install` for desktop video"});else if(t!=="darwin-arm64"){c.push(L(ce)?{name:"browser",state:"ready",detail:ce}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${ce}`});let u=b!==null&&h!==null&&f!==null;c.push({name:"display",state:u?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let _=jn.filter((I)=>B(I)===null),v=(o?.missing_system_packages??kt).filter((I)=>kt.includes(I)),E=_.length===0&&v.length===0;c.push(E?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...v,..._])].join(" ")});let N=He.filter((I)=>B(I)===null);c.push(N.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:N.join(" ")})}let x=n.ffmpeg&&L(n.ffmpeg)?n.ffmpeg:B("ffmpeg"),m=!x?null:x===n.ffmpeg?n.ffprobe:y(Be(An(x)),"ffprobe"),R=a&&c.every((u)=>u.state==="ready"),S=(u)=>a&&c.every((_)=>!rs[u].includes(_.name)||_.state==="ready");return{platform:t,root:n.root,automation:n.automation,ready:R,features:{display:S("display"),computer:S("computer"),browser:S("browser")},node:n.node,ocu:n.ocu,obu:n.obu,nativeHost:n.nativeHost,extensionDir:n.extensionDir,browser:n.browser,ffmpeg:x,ffprobe:m&&L(m)?m:null,userChrome:ss(n,a&&["node","open_browser_use"].every((u)=>c.find((_)=>_.name===u)?.state==="ready")),pulseaudio:B("pulseaudio"),xvnc:B("Xvnc"),xvfb:b,x11vnc:h,openbox:f,components:c}}function At(e){return as(e)?ls():[]}function as(e){return e?.platform==="darwin-arm64"&&e.ffmpeg===y(e.root,"ffmpeg",W.version,"ffmpeg")}async function dc(e,t,n,o=fetch){try{let i=await o(e,{redirect:"follow"});if(!i.ok||!i.body)throw Error(`download failed (HTTP ${i.status}): ${e}`);let a=vt("sha256"),c=Cn(n,{mode:384});try{let w=i.body.getReader();for(let b=await w.read();!b.done;b=await w.read())if(a.update(b.value),!c.write(b.value))await Pn(c,"drain")}finally{c.end(),await Nn(c)}let p=a.digest("hex");if(p!==t)throw Error(`digest mismatch for ${e}: expected ${t}, got ${p}`)}catch(i){throw $n(n,{force:!0}),i}}function je(e){return y(Mt(e),"minimal.json")}function cs(e=s()){return Mn(je(e))}function pc(e={}){Wn(je(e.home??s()),`${JSON.stringify({version:1,minimal_at:(e.now?.()??new Date).toISOString()})}
|
|
81
|
+
`)}function hc(e={}){let t=e.platform===void 0?Rt():e.platform;if(t===null)return null;let n=e.home??s();if(Tt(wn(t,n).receipt)!==null)return"refresh";return cs(n)?null:"install"}import{spawn as us}from"child_process";import{existsSync as ds}from"fs";import{connect as ps}from"net";import{join as fe}from"path";var Lt="reason_desktop",Q={sampleRate:48000,channels:2,codec:"opus"},fs=5000,ms=107,gs=262144,zo=(e)=>fe(e,"native"),Kt=(e)=>`unix:${e}`;function Ve(e,t=1000){if(!ds(e))return Promise.resolve(!1);return new Promise((n)=>{let o=ps({path:e}),i=(a)=>{o.destroy(),n(a)};o.setTimeout(t,()=>i(!1)),o.once("error",()=>i(!1)),o.once("close",()=>i(!1)),o.once("connect",()=>i(!0))})}async function uc(e,t){if(!t)return null;let n=zo(e);if(Buffer.byteLength(n)>ms||/["'\\\s]/.test(n))return null;try{if(await Ve(n))return n;let o=us(t,["--daemonize=no","--system=no","--use-pid-file=no","--exit-idle-time=-1","--disallow-exit=yes","--realtime=no","--high-priority=no","--disallow-module-loading=yes","--log-level=warning",`--log-target=file:${fe(e,"pulseaudio.log")}`,"-n",`--load=module-native-protocol-unix socket="${n}" auth-anonymous=1 auth-cookie-enabled=0`,`--load=module-null-sink sink_name=${Lt} rate=${Q.sampleRate} channels=${Q.channels} sink_properties=device.description=Reason_desktop`],{detached:!0,stdio:"ignore",env:{HOME:e,PATH:"/usr/bin:/bin",XDG_RUNTIME_DIR:e,PULSE_RUNTIME_PATH:fe(e,"runtime"),PULSE_STATE_PATH:fe(e,"state")}}),i=!1;o.once("error",()=>{i=!0}),o.once("exit",()=>{i=!0}),o.unref();let a=Date.now()+fs;while(Date.now()<a){if(await Ve(n))return n;if(i)return await Ve(n)?n:null;await new Promise((c)=>setTimeout(c,50))}if(!i)o.kill("SIGKILL");return null}catch{return null}}function Nt(){let{sampleRate:e,channels:t}=Q;return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer","-f","pulse","-sample_rate",String(e),"-channels",String(t),"-fragment_size",String(e*t*2/50),"-i",`${Lt}.monitor`,"-vn","-ac",String(t),"-ar",String(e),"-c:a","libopus","-b:a","64k","-application","lowdelay","-frame_duration","20","-flush_packets","1","-page_duration","20000","-f","ogg","pipe:1"]}var hs=[79,103,103,83],bs=Buffer.from("OpusHead"),ys=Buffer.from("OpusTags"),$t=(e,t)=>e.byteLength>=t.byteLength&&t.every((n,o)=>e[o]===n);class Ge extends Error{constructor(e){super(e);this.name="OggProtocolError"}}class We{buffer=new Uint8Array(0);partial=[];partialBytes=0;push(e){let t=new Uint8Array(this.buffer.byteLength+e.byteLength);t.set(this.buffer),t.set(e,this.buffer.byteLength);let n=[],o=0;while(t.byteLength-o>=27){if(hs.some((x,m)=>t[o+m]!==x)||t[o+4]!==0)throw new Ge("invalid_page");let i=(t[o+5]&1)!==0,a=t[o+26];if(t.byteLength-o<27+a)break;let c=t.subarray(o+27,o+27+a),p=c.reduce((x,m)=>x+m,0),w=27+a+p;if(t.byteLength-o<w)break;if(!i&&this.partialBytes>0)this.resetPartial();let b=i&&this.partialBytes===0,h=o+27+a,f=h;for(let x of c){if(h+=x,x===255)continue;if(this.appendPartial(t.subarray(f,h),b),f=h,!b){let m=this.takePartial();if(m.byteLength>0&&!$t(m,bs)&&!$t(m,ys))n.push(m)}b=!1,this.resetPartial()}if(f<h)this.appendPartial(t.subarray(f,h),b);o+=w}return this.buffer=t.slice(o),n}appendPartial(e,t){if(t||e.byteLength===0)return;if(this.partialBytes+=e.byteLength,this.partialBytes>gs)throw new Ge("packet_too_large");this.partial.push(e.slice())}takePartial(){if(this.partial.length===1)return this.partial[0];let e=new Uint8Array(this.partialBytes),t=0;for(let n of this.partial)e.set(n,t),t+=n.byteLength;return e}resetPartial(){this.partial=[],this.partialBytes=0}}import{spawn as ws}from"child_process";var Ut=1048576,xs=String.raw`
|
|
82
|
+
import gi, json, os, sys
|
|
83
|
+
gi.require_version("Gtk", "3.0")
|
|
84
|
+
from gi.repository import Gtk, Gdk, GLib
|
|
85
|
+
if not Gtk.init_check()[0]:
|
|
86
|
+
sys.exit(1)
|
|
87
|
+
clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
|
|
88
|
+
pending = b""
|
|
89
|
+
generation = 0
|
|
90
|
+
def send(value):
|
|
91
|
+
print(json.dumps(value, ensure_ascii=True), flush=True)
|
|
92
|
+
def changed(clipboard, event):
|
|
93
|
+
global generation
|
|
94
|
+
generation += 1
|
|
95
|
+
current = generation
|
|
96
|
+
def received(clipboard, text, unused):
|
|
97
|
+
if current == generation and text is not None and len(text.encode("utf-8")) <= ${O}:
|
|
98
|
+
send({"text": text})
|
|
99
|
+
clipboard.request_text(received, None)
|
|
100
|
+
# No request_text on startup: never share the pre-existing clipboard.
|
|
101
|
+
clipboard.connect("owner-change", changed)
|
|
102
|
+
def input_ready(fd, condition):
|
|
103
|
+
global pending
|
|
104
|
+
chunk = os.read(fd, 65536)
|
|
105
|
+
if not chunk:
|
|
106
|
+
Gtk.main_quit()
|
|
107
|
+
return False
|
|
108
|
+
pending += chunk
|
|
109
|
+
while b"\n" in pending:
|
|
110
|
+
line, pending = pending.split(b"\n", 1)
|
|
111
|
+
text = json.loads(line)
|
|
112
|
+
if not isinstance(text, str) or len(text.encode("utf-8")) > ${O} or "\x00" in text:
|
|
113
|
+
sys.exit(1)
|
|
114
|
+
clipboard.set_text(text, -1)
|
|
115
|
+
send("ack")
|
|
116
|
+
if len(pending) > ${O*6+2}:
|
|
117
|
+
sys.exit(1)
|
|
118
|
+
return True
|
|
119
|
+
GLib.io_add_watch(0, GLib.IO_IN | GLib.IO_HUP, input_ready)
|
|
120
|
+
send("ready")
|
|
121
|
+
Gtk.main()
|
|
122
|
+
`;function Bt(e,t){let n=ws("/usr/bin/python3",["-I","-u","-c",xs],{env:{DISPLAY:e.display,XAUTHORITY:e.xauthority},stdio:["pipe","pipe","ignore"]}),o=!1,i=!0,a="",c=0,p=[],w=setTimeout(()=>h(),5000),b=()=>{o=!0,clearTimeout(w),p.length=0,n.kill("SIGKILL")},h=()=>{if(o)return;b(),t.end({error:new r("display_unavailable","Reason could not start this Linux desktop's UTF-8 clipboard.")})},f=(x,m=32)=>{if(o)return;if(!i){x();return}if(c+=m,c>Ut)b(),t.end({reason:"input_backpressure"});else p.push({apply:x,bytes:m})};return n.stdout.on("data",(x)=>{if(o)return;a+=x.toString("ascii");for(let m=a.indexOf(`
|
|
123
|
+
`);m>=0;m=a.indexOf(`
|
|
124
|
+
`)){let R=a.slice(0,m);a=a.slice(m+1);let S;try{S=JSON.parse(R)}catch{h();return}if(S==="ready"||S==="ack"){clearTimeout(w),i=!1;while(!i&&!o&&p.length){let u=p.shift();c-=u.bytes,u.apply()}}else if(S&&typeof S==="object"&&"text"in S&&typeof S.text==="string"&&Buffer.byteLength(S.text)<=O)t.clipboard(S.text);else{h();return}if(o)return}if(a.length>O*6+32)h()}),n.stdin.on("error",h),n.once("error",h),n.once("exit",h),{apply:f,write(x){if(Buffer.byteLength(x)>O||x.includes("\x00")){h();return}let m=`${JSON.stringify(x)}
|
|
125
|
+
`;f(()=>{if(i=!0,w=setTimeout(()=>h(),5000),n.stdin.write(m),n.stdin.writableLength>Ut)b(),t.end({reason:"input_backpressure"})},Buffer.byteLength(m))},close:b}}var X={smooth:{fps:60,crf:23,kbps:8000,x264Preset:"ultrafast",threads:2,scale:1},sharp:{fps:30,crf:19,kbps:1e4,x264Preset:"superfast",scale:1},data_saver:{fps:20,crf:28,kbps:2000,x264Preset:"ultrafast",scale:0.75},balanced:{fps:30,crf:23,kbps:4000,x264Preset:"ultrafast",threads:2,scale:1}},Ss="avc1.4D002A",Ht={width:1920,height:1080},Es=262144,Ds=0.2,Is=250,Ps=1e4,Cs=1024,Ke=1e4,Rs=500,Ms=60,Ts=1e4,Os=1000,Ft=1048576,As=-223,$s=-308,qo={kind:"mac_screen",sound:null},Wo={kind:"windows_screen",sound:null},Ls,zt=()=>Ls??=T()?.ffmpeg??null,ge=(e,t,n)=>qe(e,t,{env:n,stdio:["ignore","pipe","ignore"],windowsHide:!0}),Ns,Ye=()=>Ns??=At(T()),jt=(e,t,n)=>{let[o,...i]=[...Ye(),e];return ge(o,[...i,...t],n)},Vt=()=>on?.videotoolbox?"h264_videotoolbox":"libx264",Us=()=>Math.round(performance.now()*1000),Xe=new Set,Wt=!1;function en(e){if(Xe.add(e),e.once("exit",()=>Xe.delete(e)),Wt)return;Wt=!0,process.once("exit",()=>{for(let t of Xe)try{t.kill("SIGKILL")}catch{}})}function tn(e){try{e.stdout?.destroy()}catch{}if(e.exitCode!==null||e.signalCode!==null)return;try{e.kill("SIGTERM")}catch{return}let t=setTimeout(()=>{if(e.exitCode===null&&e.signalCode===null)try{e.kill("SIGKILL")}catch{}},Rs);e.once("exit",()=>clearTimeout(t))}function Bs(e,t,n){return{args:["-f","x11grab","-draw_mouse","1","-framerate",String(e),"-video_size",`${t.width}x${t.height}`,"-i",n],size:t}}function Hs(e){return{args:["-f","avfoundation","-capture_cursor","1","-pixel_format","nv12","-framerate",String(e),"-i","Capture screen 0:none"],size:null}}function Fs(e,t){return{args:["-f","gdigrab","-draw_mouse","1","-framerate",String(e),"-offset_x","0","-offset_y","0","-video_size",`${t.width}x${t.height}`,"-i","desktop"],size:t}}function zs(e){return{args:["-probesize","32","-analyzeduration","0","-f","image2pipe","-c:v","mjpeg","-framerate",String(e),"-i","pipe:0"],size:null}}var nn=1700000;function sn(e){return Math.min(1,Math.round(Math.sqrt(nn/(e.width*e.height))*100)/100)}function js(e,t,n){let o=qe(n.axe,["stream-video","--udid",n.udid,"--format","ffmpeg","--fps","30","--quality","85","--scale",String(Math.min(0.99,sn(n.size)))],{stdio:["ignore","pipe","ignore"]}),i=qe(e,t,{env:{},stdio:["pipe","pipe","ignore"]});o.stdout.pipe(i.stdin),i.stdin.on("error",()=>{});let a=()=>{if(o.exitCode===null&&o.signalCode===null)o.kill("SIGTERM")};return i.once("exit",a),i.once("error",a),o.once("exit",()=>{if(i.exitCode===null&&i.signalCode===null)i.kill("SIGTERM")}),o.once("error",()=>{if(i.exitCode===null&&i.signalCode===null)i.kill("SIGTERM")}),i}function qt(e){let t=Math.min(1,Ht.width/e.width,Ht.height/e.height);return{width:Math.round(e.width*t),height:Math.round(e.height*t)}}function me(e,t,n,o="libx264"){let i=X[e],a=(f)=>Math.max(2,Math.floor(f/2)*2),c={width:a(n.width*i.scale),height:a(n.height*i.scale)},p=c.width!==t.size?.width||c.height!==t.size.height,w=Math.max(1,Math.round(i.kbps*2/i.fps)),b=["-g",String(i.fps*Ms)],h=o==="h264_videotoolbox"?["-c:v","h264_videotoolbox","-realtime","1","-prio_speed","1","-allow_sw","1","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","nv12",...b,"-b:v",`${i.kbps}k`,"-maxrate",`${i.kbps}k`,"-bufsize",`${w}k`,"-bsf:v","h264_metadata=aud=insert"]:["-c:v","libx264","-preset",i.x264Preset,"-tune","zerolatency","-profile:v","main","-level","4.2","-bf","0","-pix_fmt","yuv420p",...i.threads?["-threads",String(i.threads)]:[],"-x264-params","aud=1:repeat-headers=1",...b,"-crf",String(i.crf),"-maxrate",`${i.kbps}k`,"-bufsize",`${w}k`];return["-hide_banner","-loglevel","error","-nostdin","-fflags","nobuffer",...t.args,"-an",...p?["-vf",`scale=${c.width}:${c.height}:flags=fast_bilinear`]:[],...h,"-flush_packets","1","-f","h264","pipe:1"]}class rn{buffer=new Uint8Array(0);scanned=0;key=!1;micros=0;push(e,t){if(this.buffer.byteLength===0)this.micros=t;let n=new Uint8Array(this.buffer.byteLength+e.byteLength);n.set(this.buffer),n.set(e,this.buffer.byteLength),this.buffer=n;let o=[],i=this.scanned;while(i+3<this.buffer.byteLength){if(this.buffer[i]!==0||this.buffer[i+1]!==0||this.buffer[i+2]!==1){i++;continue}let a=this.buffer[i+3]&31,c=i>0&&this.buffer[i-1]===0?i-1:i;if(a===9&&c>0)o.push({data:this.buffer.slice(0,c),key:this.key,micros:this.micros}),this.buffer=this.buffer.subarray(c),this.key=!1,this.micros=t,i-=c;if(a===5)this.key=!0;i+=3}return this.scanned=i,o}}function Vs(e,t){let n=vs({path:e}),o=Buffer.alloc(0),i="version",a=0,c=!1,p=[],w=0,b=!1,h=(u)=>{if(b)return;b=!0,n.destroy(),t.end(u)},f=()=>h({reason:"display_protocol"}),x=(u)=>{if(b)return;if(!c){if(w+=u.byteLength,w>Ft)h({reason:"input_backpressure"});else p.push(u);return}if(n.write(u),n.writableLength>Ft)h({reason:"input_backpressure"})},m=(u)=>{o=o.subarray(u)},R=()=>{switch(i){case"version":{if(o.byteLength<12)return!1;let u=/^RFB (\d{3})\.(\d{3})\n$/.exec(o.subarray(0,12).toString("latin1"));if(!u||Number(u[1])*1000+Number(u[2])<3007)return f(),!1;return m(12),n.write(`RFB 003.007
|
|
126
|
+
`),i="security",!0}case"security":{if(o.byteLength<1)return!1;let u=o[0];if(u===0)return f(),!1;if(o.byteLength<1+u)return!1;if(!o.subarray(1,1+u).includes(1))return f(),!1;return m(1+u),n.write(Buffer.from([1,1])),i="init",!0}case"init":{if(o.byteLength<24)return!1;let u=o.readUInt32BE(20);if(u>65536)return f(),!1;if(o.byteLength<24+u)return!1;let _={width:o.readUInt16BE(0),height:o.readUInt16BE(2)};if(m(24+u),_.width===0||_.height===0)return f(),!1;i="messages";let v=Buffer.alloc(12);v.writeUInt8(2,0),v.writeUInt16BE(2,2),v.writeInt32BE($s,4),v.writeInt32BE(As,8),n.write(v),c=!0;for(let E of p)n.write(E);return p=[],w=0,t.ready(_),!b}case"skip":{let u=Math.min(a,o.byteLength);if(m(u),a-=u,a>0)return!1;return i="messages",!0}case"messages":{if(o.byteLength<1)return!1;switch(o[0]){case 1:{if(o.byteLength<6)return!1;let u=6+o.readUInt16BE(4)*6;if(o.byteLength<u)return!1;return m(u),!0}case 2:return m(1),!0;case 3:{if(o.byteLength<8)return!1;let u=o.readUInt32BE(4);if(u>O/2)return m(8),i="skip",a=u,!0;if(o.byteLength<8+u)return!1;let _=o.subarray(8,8+u).toString("latin1");return m(8+u),t.clipboard(_),!b}default:return f(),!1}}}},S=!1;return n.once("connect",()=>{S=!0}),n.on("data",(u)=>{if(b)return;o=o.byteLength?Buffer.concat([o,u]):u;while(!b&&R());}),n.once("error",()=>{if(!S)h({error:new r("display_unavailable","Reason could not reach this machine's desktop server.")})}),n.once("close",()=>h({reason:"display_closed"})),{pointer(u,_,v){let E=Buffer.alloc(6);E.writeUInt8(5,0),E.writeUInt8(v&255,1),E.writeUInt16BE(u,2),E.writeUInt16BE(_,4),x(E)},key(u,_){let v=Buffer.alloc(8);v.writeUInt8(4,0),v.writeUInt8(u?1:0,1),v.writeUInt32BE(_>>>0,4),x(v)},clipboard(u){if(Array.from(u).some((E)=>E.codePointAt(0)>255)){h({reason:"clipboard_unicode_unsupported"});return}let _=Buffer.from(u,"latin1"),v=Buffer.alloc(8);v.writeUInt8(6,0),v.writeUInt32BE(_.byteLength,4),x(Buffer.concat([v,_]))},close(){b=!0,n.destroy()}}}class Je{run=null;viewers=new Set;get running(){return this.run!==null}start(e,t,n,o){this.viewers.add(e),this.stop();let i;try{i=n()}catch{this.fail();return}en(i);let a={child:i,splitter:new rn};this.run=a;for(let p of[...this.viewers])p.started(t);i.stdout?.on("data",(p)=>{if(this.run!==a)return;for(let w of a.splitter.push(p,o()))for(let b of[...this.viewers])b.unit(w)});let c=()=>{if(this.run!==a)return;this.run=null,this.fail()};i.once("exit",c),i.once("error",c)}leave(e){if(!this.viewers.delete(e))return;if(this.viewers.size===0)this.stop()}stop(){if(!this.run)return;tn(this.run.child),this.run=null}fail(){for(let e of[...this.viewers])e.failed()}}var Yt=new WeakMap;function Gs(e){let t=Yt.get(e);if(!t)Yt.set(e,t=new Je);return t}var ee=new Map;function Vo(e,t,n={}){let o=n.micros??Us,i=new ns,a=t.request.preset,c=null,p=null,w=null,b=!1,h=null,f=!1,x=!1,m=null,R=0,S=0,u=!1,_=null,v=null,E=0,N=null,I=[],te=0,U=[],Ze=new Uint32Array(Ke+1),he=0,be=null,ye=0,q=0,we=0,Qe=0,et=0,ne=null,xe=0,j={frames:0,bytes:0,since:o()},V=[],Y=0,_e,ke=!1,cn=o(),C={},G=()=>Math.round((o()-cn)/1000),tt=n.control??ut,ve=null,Se=null,nt=0,Ee=!1,st={pause(){if(!h?.running)return;h.stop(),Ee=!0},adopt(l){let d=l!==null&&(l.width!==p?.width||l.height!==p?.height);if(d)p=l;if(!d&&!Ee)return;if(Ee=!1,h)ae();else Pe()}},un=(l)=>{if(!n.resizeDesktop||!c||"kind"in c||e.done)return;let d=c.display,g=()=>[...ee.get(d)??[]];nt++,n.resizeDesktop(c,l,()=>{for(let k of g())k.pause()}).then((k)=>{for(let D of g())D.adopt(k)})},M=(l)=>{let d=Rn(l);return e.send(d),Qe+=d.byteLength,d.byteLength},se=(l)=>{if(e.done)return;if(e.open)M({type:"error",code:l});e.end({reason:l})},re=()=>Math.max(Es,X[a].kbps*1000/8*Ds),oe=()=>o()/1000,ln=()=>{while(U.length>1&&U[0].atMs<oe()-Ps)U.shift();return U[0]?.rttMs??null},rt=(l)=>{let d=ln();if(d===null||I.length===0)return!1;let g=(d+Is)*l;return oe()-I[0].sentMs>g||te>g/1000*X[a].kbps*1000/8},dn=(l)=>{if(E===0)return;let d=Math.min(l,E-1);if(N!==null&&d<=N)return;N=d;let g=oe();while(I.length&&I[0].seq<=d){let k=I.shift();if(te-=k.bytes,k.seq!==d)continue;let D=Math.max(0,g-k.sentMs);while(U.length&&U.at(-1).rttMs>=D)U.pop();U.push({atMs:g,rttMs:D}),Ze[Math.min(Ke,Math.round(D))]++,he++,be=Math.min(be??D,D)}},pn=()=>{let l=0;for(let d=0;d<=Ke;d++)if(l+=Ze[d],l*2>=he)return d;return 0},fn=()=>e.bufferedAmount<=re()/2&&!rt(0.5),ot=()=>{ke=!0,V=[],Y=0,h?.leave(De),h=null},it=(l)=>{if(e.done)return;if(l.key)C.first_key_ms??=G();if(!b){if(!h||V.length===0&&!l.key)return;if(V.push(l),Y+=l.data.byteLength,Y>re())ot();return}if(u){q++;return}if(e.bufferedAmount>re()||rt(1)){u=!0,q++,_=setInterval(()=>{if(e.done||!fn())return;if(_)clearInterval(_);_=null,u=!1,ae()},n.drainPollMs??25);return}if(!f){if(!l.key){q++;return}if(M({type:"hello",width:p.width,height:p.height,fps:X[a].fps,preset:a,codec:Ss}),f=!0,C.first_frame_ms??=G(),!x&&c?.sound)M({type:"audioHello",...Q}),x=!0}let d=M({type:"frame",key:l.key,seq:E,captureMicros:l.micros,data:l.data});if(I.push({seq:E,sentMs:oe(),bytes:d}),te+=d,I.length>Cs)te-=I.shift().bytes;E++,ye++,ne??=l.micros,xe=l.micros,j.frames++,j.bytes+=d},De={started(l){a=l,f=!1,V=[],Y=0},unit:it,failed:()=>se("encoder_failed")},Ie=()=>{let l=(n.ffmpeg??zt)();if(!c||!p){se("encoder_failed");return}let[d,g]=[c,p],k="kind"in d&&d.kind==="simulator"?d.stream:null;if(!l&&!k){se("encoder_failed");return}if(h??="kind"in d&&d.kind==="mac_screen"?Gs(n.spawn??jt):new Je,C.encoder_ms===void 0)C.encoder_ms=G(),C.encoder_shared=h.running;h.start(De,a,()=>{let D=X[a].fps;if(k)return k(D,X[a].kbps,nn);if("kind"in d&&d.kind==="simulator"){let P=Math.min(0.99,sn(d.size)),H={width:d.size.width*P,height:d.size.height*P};return js(l,me(a,zs(Math.min(D,30)),H,(n.macEncoder??Vt)()),d)}if("kind"in d&&d.kind==="windows_screen")return(n.spawn??ge)(l,me(a,Fs(D,g),qt(g)),{SystemRoot:process.env.SystemRoot??"C:\\Windows"});return"kind"in d?(n.spawn??jt)(l,me(a,Hs(D),qt(g),(n.macEncoder??Vt)()),{}):(n.spawn??ge)(l,me(a,Bs(D,g,d.display),g),{DISPLAY:d.display,XAUTHORITY:d.xauthority})},o)},ie=()=>{if(!m)return;tn(m.child),m=null},mn=()=>{let l=(n.ffmpeg??zt)();if(m||e.done||!x||!c?.sound||!l)return;let d;try{d=(n.spawn??ge)(l,Nt(),{PULSE_SERVER:Kt(c.sound)})}catch{return}en(d);let g={child:d,reader:new We};m=g,d.stdout?.on("data",(D)=>{if(m!==g||e.done)return;let P;try{P=g.reader.push(D)}catch{ie();return}let H=o();for(let Re of P){if(e.bufferedAmount>re()){S++;continue}M({type:"audio",captureMicros:H,data:Re}),R++}});let k=()=>{if(m===g)ie()};d.once("exit",k),d.once("error",k)},ae=()=>{if(!h||e.done)return;we++,Ie()},Pe=()=>{if(e.done||!p)return;if(!b){if(h||ke)return;Ie(),_e=setTimeout(()=>{if(!b)ot()},Ts);return}if(clearTimeout(_e),C.encoder_early===void 0){if(C.encoder_early=h!==null,ke)C.hold_lapsed=!0}if(!h)Ie();let l=V;V=[],Y=0;for(let d of l)it(d);v??=setInterval(()=>{let d=o(),g=Math.max(0.001,(d-j.since)/1e6);M({type:"stats",stats:{fps:Math.round(j.frames/g*10)/10,kbps:Math.round(j.bytes*8/1000/g),dropped:q,restarts:we,queued_bytes:e.bufferedAmount}}),j={frames:0,bytes:0,since:d}},Os)};t.desktop.then((l)=>{if(e.done)return;c=l;let d={ready(g){p=g,C.desktop_ms??=G(),Pe()},clipboard(g){if(e.open&&Buffer.byteLength(g)<=O)M({type:"serverClipboard",text:g})},end(g){if("reason"in g&&e.open)M({type:"error",code:g.reason});e.end(g)}};if("kind"in l&&l.kind==="simulator")w=l.input,d.ready(l.points);else if("kind"in l&&l.kind==="windows_screen")w=(n.windowsInput??xt)(d);else if("kind"in l)w=(n.macInput??((g)=>os(g,Ye())))(d);else{let g=ee.get(l.display);if(!g)ee.set(l.display,g=new Set);g.add(st);let k=(n.linuxClipboard??Bt)(l,d),D=Vs(l.rfbSocket,{...d,clipboard:(P)=>{if(!k)d.clipboard(P)}});w=k?{pointer:(P,H,Re)=>k.apply(()=>D.pointer(P,H,Re)),key:(P,H)=>k.apply(()=>D.key(P,H)),clipboard:(P)=>k.write(P),close(){k.close(),D.close()}}:D}at()},(l)=>e.end({error:l}));function at(){if(Se||!t.viewerSameNetwork||!b||e.done||!c||!("kind"in c)||c.kind!=="mac_screen")return;Se=(n.macWindows??is)((l)=>{if(e.open)M({type:"windows",bounds:l})})}let ct={viewer:t.viewer??null,notify(l){if(e.open)M({type:"control",control:l})}},Ce=(l)=>{if(!w)return;if(!c||!("kind"in c)||c.kind!=="simulator")tt.claim(ct);l(w)};return{opened(){C.relay_ms??=G()},received(l){et+=l.byteLength;let d;try{d=i.push(l)}catch{se("viewer_protocol");return}for(let g of d){if(e.done)return;switch(g.type){case"ping":M({type:"pong",token:g.token});break;case"pointer":Ce((k)=>k.pointer(g.x,g.y,g.buttons));break;case"key":Ce((k)=>k.key(g.down,g.keysym));break;case"clientClipboard":Ce((k)=>k.clipboard(g.text));break;case"config":if(g.preset!==a)a=g.preset,ae();break;case"keyframeRequest":if(f&&!u)ae();break;case"ack":dn(g.seq);break;case"audioEnable":if(g.on)mn();else ie();break;case"resize":un({width:g.width,height:g.height});break;default:break}}if(!b&&!e.done){if(b=!0,C.viewer_ms=G(),t.viewer)ve=tt.join(ct);Pe(),at()}},close(){if(c&&!("kind"in c)){let l=ee.get(c.display);if(l?.delete(st),l?.size===0)ee.delete(c.display)}if(ve?.(),ve=null,Se?.close(),_)clearInterval(_);if(v)clearInterval(v);clearTimeout(_e),h?.leave(De),ie(),w?.close()},summary:()=>({output_bytes:Qe,input_bytes:et,video:{preset:a,frames:ye,dropped:q,restarts:we,avg_fps:ne!==null&&xe>ne?Math.round((ye-1)/((xe-ne)/1e6)*10)/10:0,min_rtt_ms:Math.round(be??0),p50_rtt_ms:he?pn():0,audio_packets:R,audio_dropped:S,resizes:nt,connect:C}})}}var Zt=null,on=null,Ws=null,Ks=null;function Xs(){let e=T();return e?.features.display?e.ffmpeg:null}function an(e){return Zt??=new Promise((t)=>{_s(e,["-hide_banner","-encoders"],{env:{},timeout:5000,killSignal:"SIGKILL",maxBuffer:1048576,encoding:"utf8"},(n,o)=>{let i=(a)=>!n&&new RegExp(`^\\s*V\\S*\\s+${a}\\s`,"m").test(o);t(on={x264:i("libx264"),videotoolbox:i("h264_videotoolbox")})})}),Zt}var Qt=null;function Go(){return Qt??=(async()=>{let e=[T()?.ffmpeg,"/opt/homebrew/bin/ffmpeg","/usr/local/bin/ffmpeg"].find((n)=>Boolean(n&&ks(n)));if(!e)return null;let t=await an(e);return t.videotoolbox||t.x264?e:null})(),Qt}function Jt(e=process.platform,t={}){if(e!=="linux"&&e!=="darwin"&&e!=="win32")return Promise.resolve(!1);let n=(t.ffmpeg??Xs)();if(!n)return Promise.resolve(!1);let o=(t.encoders??an)(n);if(e==="linux")return o.then((a)=>a.x264);if(e==="win32"){let a=t.windowsScreen?t.windowsScreen():Ks??=bt();return Promise.all([o,a]).then(([c,p])=>c.x264&&(p?.session??0)>0)}let i=t.macScreen?t.macScreen():Ws??=Xt(Ye());return Promise.all([o,i]).then(([a,c])=>(a.x264||a.videotoolbox)&&c?.screen===!0&&c.accessibility)}
|
|
127
|
+
export{Gt,lc,le,zo,Kt,uc,qo,Wo,Vo,Go,Jt,yn,wn,T,dc,pc,hc};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{randomBytes as z}from"crypto";import{chmodSync as H,closeSync as B,constants as yn,linkSync as Q,lstatSync as w,mkdirSync as Z,openSync as dn,readdirSync as E,readFileSync as Y,readlinkSync as v,renameSync as D,rmdirSync as x,symlinkSync as h,unlinkSync as g}from"fs";import{createRequire as gn}from"module";import{constants as pn}from"os";import{basename as O,join as s,sep as bn}from"path";import{existsSync as R,lstatSync as U,readdirSync as an,readFileSync as ln,readlinkSync as un,realpathSync as fn}from"fs";import{join as d,sep as mn}from"path";function K(n,...r){let e=d(n,"ara"),t=d(n,"reason");if(!Ni(e))return d(t,...r);if(!R(t))return d(e,...r);return R(d(e,...r))&&!R(d(t,...r))?d(e,...r):d(t,...r)}function Ni(n){try{let r=U(n);if(!r.isSymbolicLink())return r.isDirectory();return un(n)!=="reason"&&R(n)}catch{return!1}}function W(n,r=[]){if(!Ni(n))return!1;let e;try{e=[n,...an(n,{withFileTypes:!0}).filter((t)=>t.isDirectory()).map((t)=>d(n,t.name))]}catch{return!1}return e.some((t)=>["connect","connect-once"].filter((i)=>!r.includes(d(t,i))).some((i)=>{let c=d(t,i,"worker.json");try{U(c)}catch{return!1}try{let a=JSON.parse(ln(c,"utf8"))?.stateDirectory;if(typeof a!=="string")return!0;let l=(o,u)=>o===u||o.startsWith(u+mn);return l(a,n)||l(X(a),X(n))}catch{return!0}}))}function X(n){try{return fn(n)}catch{return n}}var j=new Set(["credentials.json","local-device.json","local-device.revoked.json","local-device.auth-migration.json","local-device.json.registration-pending.json","local-daemon.json","local-daemon.json.workspaces.json","local-root-fingerprint-key.json","instances","workspaces"]),F=new Set(["local-device.proxy.json"]),kn=new Set(["local-device.key","local-device.binding"]),q=new Map;function De(n,r,e){let t=s(n,"ara");if(process.platform==="win32"||/[/\\]\.reason-ssh[/\\][^/\\]+[/\\]installer-home[/\\]\.config$/.test(n))return{state:f(t)?.isDirectory()?"kept":"absent"};return rn(t,s(n,"reason"),{linkAlways:!0,kept:(i)=>W(i,e??[]),native:r===void 0?wt:()=>r},e!==void 0)}function yt(n,...r){return De(n),K(n,...r)}function es(n,r=process.platform){if(r==="win32")return s(n,"AppData","Local","Reason","Logs");let e=s(n,"Library","Logs");if(r==="darwin")for(let t of[""," Staging"," Development"])rn(s(e,`Ara${t}`),s(e,`Reason${t}`),{linkAlways:!1,kept:()=>!1,native:wt});return s(e,"Reason")}var nn="config_rename_unavailable:busy";function rn(n,r,e,t=!1){let i=t?void 0:q.get(n);if(i)return i;let c;try{c=En(n,r,e)}catch(a){let l=`config_rename_unavailable:${k(a)??"failed"}`;try{return{state:f(n)?.isDirectory()?"kept":"absent",problem:l}}catch{return{state:"kept",problem:l}}}if(!(c.state==="absent"&&e.linkAlways)&&c.problem!==nn&&!(c.state==="kept"&&!c.problem))q.set(n,c);return c}function En(n,r,e){vn(r,e.native);let t=!1;for(let i=0;i<8;i+=1){let c=f(n);if(c?.isSymbolicLink())return v(n)===O(r)?{state:t?"renamed":"linked"}:{state:"kept"};if(!c){if(A(r))m(()=>g(r),"ENOENT");if(!(t||e.linkAlways)||!N(r))return{state:"absent"};let o=_(r,"link");h(O(r),o);try{m(()=>D(o,n),"EISDIR","ENOTEMPTY","EEXIST","ENOTDIR")}finally{m(()=>g(o),"ENOENT")}continue}if(!c.isDirectory())return{state:"absent"};if(e.kept(n))return G(r),{state:"kept"};let a=e.native();if(!a)return G(r),{state:"kept",problem:"config_rename_unavailable:no_native"};let l=Nn(a,n);if(!l)return{state:"kept",problem:nn};try{if(w(n).isSymbolicLink())continue;let o=Sn(a,n,r);if(o)return{state:"kept",problem:o};t=!0}finally{l()}}throw Object.assign(Error("legacy directory rename did not settle"),{code:"unsettled"})}function Sn(n,r,e){let t=f(e);if(!t||A(e)){if(!t)h(O(e),e);try{n.exchange(r,e)}catch(o){if(A(e))m(()=>g(e),"ENOENT");return`config_rename_unavailable:${k(o)??"exchange_failed"}`}return null}if(!t.isDirectory())return"config_rename_unavailable:ENOTDIR";if(t.dev!==w(r).dev)return"config_rename_unavailable:EXDEV";let i=[_(e,"probe"),_(e,"probe")];try{h("a",i[0]),h("b",i[1]),n.exchange(i[0],i[1])}catch(o){return`config_rename_unavailable:${k(o)??"exchange_failed"}`}finally{for(let o of i)m(()=>g(o),"ENOENT")}let c=cn(e);for(let o of kn){let u=f(s(e,o)),y=f(s(r,o));if(u&&y&&u.ino!==y.ino)Z(`${c}-replaced`,{mode:448,recursive:!0}),D(s(e,o),s(`${c}-replaced`,o))}let a={linked:new Map,unitsKept:new Set};en(r,e,"",a);let l=_(e,"rename");h(O(e),l);try{n.exchange(r,l)}catch(o){return m(()=>g(l),"ENOENT"),`config_rename_unavailable:${k(o)??"exchange_failed"}`}return tn(l,e,a,c),null}function M(n){return n===""||!n.includes(bn)}function en(n,r,e,t){let i=M(e)&&I(s(r,e),s(n,e));if(i)t.unitsKept.add(e);for(let c of E(s(n,e))){if(i&&(j.has(c)||F.has(c)))continue;let a=s(e,c),l=s(n,a),o=s(r,a),u=f(l);if(!u)continue;let y=f(o);if(u.isDirectory()){if(!y)m(()=>Z(o,{mode:u.mode&4095}),"EEXIST"),H(o,u.mode&4095);if(N(o))en(n,r,a,t)}else if(!y){if(u.isSymbolicLink())m(()=>h(v(l),o),"EEXIST");else if(m(()=>Q(l,o),"EEXIST","ENOENT"))t.linked.set(a,u.ino)}}}function vn(n,r){let e;try{if(!N(n))return;e=E(n)}catch{return}for(let t of e){let i=/^\.(rename|link|probe|claim)-(\d+)-[0-9a-f]+$/.exec(t);if(!i)continue;let c=s(n,t),a=f(c);if(!a)continue;if(!a.isDirectory()){if(!J(Number(i[2])))m(()=>g(c),"ENOENT");continue}let l=r(),o=null;if(l){try{o=l.lock(c)}catch{continue}if(!o)continue}else if(J(Number(i[2])))continue;try{let u=_(n,"claim");if(m(()=>D(c,u),"ENOENT"))tn(u,n,null,cn(n))}finally{o?.()}}}function tn(n,r,e,t){for(let[i,c]of e?.linked??[])if(!f(s(n,i))&&f(s(r,i))?.ino===c)m(()=>g(s(r,i)),"ENOENT");if(on(n,r,"",e),m(()=>x(n),"ENOTEMPTY","EEXIST"))return;D(n,t),H(t,448)}function on(n,r,e,t){let i=M(e)&&(t?t.unitsKept.has(e):I(s(r,e),s(n,e)));for(let c of E(s(n,e))){let a=s(e,c),l=s(n,a),o=s(r,a),u=w(l),y=f(o);if(y&&u.ino===y.ino&&u.dev===y.dev){g(l);continue}if(u.isFile()&&y?.isFile()&&t?.linked.get(a)===y.ino){D(l,o);continue}if(i&&(j.has(c)||F.has(c)))continue;if(!y){if(u.isFile()){if(m(()=>Q(l,o),"EEXIST"))g(l)}else m(()=>D(l,o),"EEXIST","ENOTEMPTY");continue}if(u.isDirectory()&&y.isDirectory())on(n,r,a,t),m(()=>x(l),"ENOTEMPTY","EEXIST")}}function mc(n){let r=s(n,"ara"),e=s(n,"reason");if(!N(r)||!N(e))return null;let t=["",...E(r,{withFileTypes:!0}).filter((i)=>i.isDirectory()&&!i.name.startsWith(".")).map((i)=>i.name)];for(let i of t){let c=s(r,i),a=s(e,i);if(!I(c,a)||!I(a,c))continue;if([...j,...F].some((o)=>P(s(c,o),s(a,o))===!1))return i}return null}function gc(n){let r=s(n,"ara"),e=s(n,"reason");if(!N(r)||!N(e))return null;let t=(i)=>{for(let c of E(s(r,i))){let a=s(i,c);if(M(i)&&(c==="connect"||c==="connect-once"))continue;let l=w(s(r,a)),o=f(s(e,a));if(!o||l.ino===o.ino&&l.dev===o.dev)continue;if(l.isDirectory()&&o.isDirectory()&&!o.isSymbolicLink()){let u=t(a);if(u!==null)return u}else if(l.isSymbolicLink()||o.isSymbolicLink()){if(!(l.isSymbolicLink()&&o.isSymbolicLink()&&v(s(r,a))===v(s(e,a))))return a}else if(P(s(r,a),s(e,a))!==!0)return a}return null};return t("")}function P(n,r){let e=f(n),t=f(r);if(!e&&!t)return null;if(!e||!t||e.isDirectory()!==t.isDirectory())return!1;if(e.ino===t.ino&&e.dev===t.dev)return!0;if(e.isDirectory())return[...new Set([...E(n),...E(r)])].every((c)=>P(s(n,c),s(r,c))===!0);try{return Y(n).equals(Y(r))}catch{return!1}}function I(n,r){for(let e of j)if(sn(s(n,e),s(r,e)))return!0;return!1}function sn(n,r){let e=f(n);if(!e)return!1;let t=f(r);if(!t)return!0;if(e.isDirectory()){if(!t.isDirectory())return!0;return E(n).some((i)=>sn(s(n,i),s(r,i)))}if(e.isSymbolicLink())return!t.isSymbolicLink()||v(n)!==v(r);return e.ino!==t.ino||e.dev!==t.dev}function G(n){if(A(n))m(()=>g(n),"ENOENT")}function cn(n){return s(n,`.pre-rename-${new Date().toISOString().replace(/[:.]/g,"-")}-${z(3).toString("hex")}`)}function A(n){try{return w(n).isSymbolicLink()&&v(n)===O(n)}catch{return!1}}function N(n){let r=f(n);return r!==null&&r.isDirectory()}function Nn(n,r){for(let e=0;e<40;e+=1){let t=n.lock(r);if(t)return t;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,50)}return null}function _(n,r){return s(n,`.${r}-${process.pid}-${z(6).toString("hex")}`)}function J(n){if(n===process.pid)return!1;try{return process.kill(n,0),!0}catch(r){return k(r)==="EPERM"}}function f(n){try{return w(n)}catch(r){if(k(r)==="ENOENT"||k(r)==="ENOTDIR")return null;throw r}}function m(n,...r){try{return n(),!0}catch(e){if(r.includes(k(e)??""))return!1;throw e}}function k(n){return n instanceof Error&&"code"in n&&typeof n.code==="string"?n.code:void 0}var T,hn=2,Dn=4,wn=2,Tn=2,V=-100;function wt(){if(T!==void 0)return T;if(T=null,process.platform!=="linux"&&process.platform!=="darwin")return null;let n;try{n=gn(import.meta.url)("bun:ffi")}catch{return null}let r=process.platform==="darwin",e=r?"__error":"__errno_location",t=r?["/usr/lib/libSystem.B.dylib"]:["libc.so.6",`libc.musl-${process.arch==="arm64"?"aarch64":"x86_64"}.so.1`],{FFIType:i}=n;for(let c of t)try{let a=r?"renamex_np":"renameat2",o=n.dlopen(c,{flock:{args:[i.i32,i.i32],returns:i.i32},[e]:{args:[],returns:i.ptr},[a]:r?{args:[i.ptr,i.ptr,i.u32],returns:i.i32}:{args:[i.i32,i.ptr,i.i32,i.ptr,i.u32],returns:i.i32}}).symbols,u=o[e]();if(u===null)continue;let y=(S)=>{let b=n.read.i32(u),p=Object.entries(pn.errno).find(([,L])=>L===b)?.[0]??`errno_${b}`;return Object.assign(Error(`${S} failed: ${p}`),{code:p})},C=(S)=>Buffer.from(`${S}\x00`,"utf8");return T={exchange(S,b){let p=C(S),L=C(b);if((r?o[a](n.ptr(p),n.ptr(L),wn):o[a](V,n.ptr(p),V,n.ptr(L),Tn))!==0)throw y("exchange")},lock(S){let b=dn(S,yn.O_RDONLY);if(o.flock(b,hn|Dn)===0)return()=>B(b);let p=y("lock");if(B(b),p.code==="EWOULDBLOCK"||p.code==="EAGAIN")return null;throw p}},T}catch{}return null}
|
|
3
|
+
export{Ni,De,yt,es,mc,gc,wt};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ba}from"./vm-hands-entry-lite-84mc1f7h.js";import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{W}from"./vm-hands-entry-lite-q9s1e2y1.js";import{Q,ro,ve,no}from"./vm-hands-entry-lite-a7bf7xr7.js";import{xr}from"./vm-hands-entry-lite-bj3w2ven.js";import{t,o,_,d,n,rl,we,c,i}from"./vm-hands-entry-lite-k5ytpgzz.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function S(e){let s=typeof e==="string"?E.exec(e):null;return s?{major:Number(s[1]),minor:Number(s[2])}:null}import{createHash as q,randomBytes as v}from"crypto";import{createInterface as M}from"readline";var k=["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 Ge=k.filter((e)=>e!=="network:read"&&e!=="network:write");class y extends Error{oauthCode;constructor(e,s=null){super(e);this.oauthCode=s;this.name="LoginError"}}function ya(){let e=v(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:v(32).toString("base64url")}}function z(e,s){let r=typeof e.error==="string"?e.error:null,a=typeof e.error_description==="string"?e.error_description:r?r:s;return new y(a,r)}async function L(e,s,r,a){let l=await r(`${e}/mcp/oauth/token`,{method:"POST",redirect:"error",headers:{"content-type":"application/x-www-form-urlencoded"},body:s,signal:a}),u=await l.json().catch(()=>({}));if(!l.ok)throw z(u,`OAuth token request failed (${l.status})`);return u}var j=1e4;async function D(e,s={}){let r=s.fetchImpl??fetch,a=await L(e.apiOrigin,new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken}),r,AbortSignal.timeout(j)).catch((u)=>{if(u instanceof Error&&u.name==="TimeoutError")throw new y("Reason did not answer the login refresh in time. Check the network and retry.");throw u});if(typeof a.access_token!=="string"||typeof a.refresh_token!=="string"||typeof a.expires_in!=="number")throw new y("Reason returned an incomplete refreshed login.");let l={...e,accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:new Date(Date.now()+a.expires_in*1000).toISOString(),scopes:typeof a.scope==="string"?a.scope.split(/\s+/).filter(Boolean):e.scopes};return ro(l,s.path??Q()),l}var R=new Map,N=2000,H=100;function I(e,s){if(!s)return e;if(s.aborted)return Promise.reject(s.reason);return new Promise((r,a)=>{let l=()=>a(s.reason);s.addEventListener("abort",l,{once:!0}),e.then(r,a).finally(()=>s.removeEventListener("abort",l))})}async function be(e={}){let s=e.path??Q(),r=ve(s);if(!r)return null;let a=e.apiOrigin??P(process.env,"REASON_API_URL")?.trim();if(a&&!W(r.apiOrigin,new URL(a).origin))return null;if(!(Date.parse(r.expiresAt)<=Date.now()+60000)&&(!e.forceRefresh||e.refused!==void 0&&r.accessToken!==e.refused))return r;let u=[s,r.apiOrigin,r.clientId,r.refreshToken].join("\x00"),g=R.get(u);if(g)return I(g,e.signal);let h;return h=D(r,{fetchImpl:e.fetchImpl,path:s}).catch(async(p)=>{if(!(p instanceof y)||p.oauthCode!=="invalid_grant"&&p.oauthCode!=="invalid_client")throw p;let b=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!b(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(b(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return no(s),null}).finally(()=>{if(R.get(u)===h)R.delete(u)}),R.set(u,h),I(h,e.signal)}function wa(e,s){return new Promise((r)=>{let a=M({input:e}),l=!1,u=(h)=>{if(l)return;l=!0,s.removeEventListener("abort",g),a.close(),e.pause(),r(h)},g=()=>u(null);s.addEventListener("abort",g,{once:!0}),a.once("line",(h)=>u(h)),a.once("close",()=>u(null))})}var F=n({label:t(),used_percent:o().min(0).max(100).nullable(),resets_at:t().nullable(),exhausted:_().nullable()}),B=n({groups:d(n({selectable:_().optional(),accounts:d(n({source_id:t().min(1),model_ids:d(t().min(1)).optional()}))}))});function G(e){let s=B.safeParse(e);if(!s.success)return;return s.data.groups.some((r)=>r.selectable!==!1&&r.accounts.some((a)=>a.model_ids===void 0||a.model_ids.length>0))}class C extends Error{status;code;suggestedModel;retryAfterMs;resolutionReason;refusal;constructor(e,s,r,a,l,u,g){super(r);this.status=e;this.code=s;this.suggestedModel=a;this.retryAfterMs=l;this.resolutionReason=u;this.refusal=g;this.name="ApiError"}static rateLimitDelayMs(e,s){if(!(e instanceof C)||e.status!==429)return null;return Math.min(60000,Math.max(s,e.retryAfterMs??0))}}var J=["minimal","low","medium","high","xhigh","max"],K=n({id:t().min(1),kind:t(),name:t(),custom_name:t().nullish(),status:t(),online:_(),compatible:_().optional(),compatibility_reason:t().nullish(),folder_lane_of:t().nullish(),roots:d(n({id:t().min(1),label:t()}))}),V=n({devices:d(K),end_cursor:t().nullish(),has_next_page:_().optional()}),Y=n({id:t().min(1),name:t()}),Z=n({items:d(Y)}),X=n({id:t().min(1),name:t(),main:_(),mine:_(),session_id:t().nullish(),appearance:n({color:t().nullish()}).nullish().catch(null)}),ee=n({items:d(X)}),ne=n({skill_id:t().min(1),name:t(),description:t().nullish(),activation_keywords:d(t()).default([]),is_enabled:_().default(!0)}),te=n({items:d(ne).default([])}),se=n({id:t().min(1),kind:t(),enabled:_(),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()}),A=n({id:t().min(1),name:t().nullish(),instructions:t().nullish(),enabled:_(),triggers:d(se).default([])}),oe=n({items:d(A).default([]),end_cursor:t().nullish(),has_next_page:_().optional()}),re=n({id:t().min(1),slug:t().nullish(),name:t(),description:t().nullish(),transport:t().nullish(),url:t().nullish(),enabled:_()}),ie=n({items:d(re).default([])}),ae=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()}),x=n({tags:d(t()).default([])}),le=c(["linux","macos"]),T=n({id:t().min(1),name:t().min(1),platform:le.nullable(),workers:n({total:o().int(),online:o().int(),busy:o().int(),idle:o().int()}),sessions:n({queued:o().int(),running:o().int()})}),ce=n({machines:d(T)}),de=n({machine:T}),ue=n({deleted:i(!0),revoked_workers:o().int(),revoked_tokens:o().int()}),ge=n({token:n({id:t().min(1),machine_id:t().min(1),token_prefix:t()}),secret:t().startsWith("rmt_")}),U=rl({machine_id:t().min(1),machine_name:t().min(1)}),he=U.extend({organization_id:t().min(1)}),tn=n({id:t().min(1),name:t().min(1),state:c(["waiting","placed"]),queue_position:o().int().nullable()});var sn=we([n({kind:i("cloud")}),n({kind:c(["mac","headless"]),device_id:t().min(1),root_id:t().min(1)})]);function m(e,s,r){let a=e.safeParse(s);if(!a.success)throw new C(502,r,"Reason returned an unexpected response.");return a.data}var pe=n({error:n({type:t(),message:t()})});function w(e,s,r){let a=pe.safeParse(s),l=typeof s.error==="string"?s.error:a.success?a.data.error.type:`http_${e}`,u=typeof s.detail==="string"?s.detail:typeof s.message==="string"?s.message:a.success?a.data.error.message:`Reason request failed (${e}${typeof s.error==="string"?` ${s.error}`:""})`,g=l==="github_connection_required"&&typeof s.connect_url==="string"&&/^https?:\/\//.test(s.connect_url)?` Connect it at ${s.connect_url}`:"",h=r===null||r.trim()===""?NaN:Number(r);return new C(e,l,`${u}${g}`,typeof s.suggested_model==="string"?s.suggested_model:void 0,Number.isFinite(h)&&h>=0?h*1000:void 0,typeof s.resolution_reason==="string"?s.resolution_reason:void 0,typeof s.code==="string"?{code:s.code,...typeof s.billing_path==="string"&&/^\/(?![/\\])/.test(s.billing_path)?{billingPath:s.billing_path}:{}}:void 0)}async function eo(e){let s=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"}),r=await s.json().catch(()=>({}));if(!s.ok)throw w(s.status,r,s.headers.get("retry-after"));return m(he,r,"invalid_machine_ticket")}var fe=n({items:d(n({name:t()}))}),_e=n({name:t(),scope:t(),result:c(["created","updated"]).optional(),warning:n({message:t()}).optional()});class me{options;credentials;constructor(e,s={}){this.options=s;this.credentials=e}trackEvent(e,s={}){}async request(e,s={}){let{status:r,headers:a,json:l}=await this.exchange(e,s);if(r<200||r>299)throw w(r,l,a.get("retry-after"));return l}async exchange(e,s={},r=!1){let a=this.options.fetchImpl??fetch;if(!r&&s.retryUnauthorized!==!1)await this.renewBeforeExpiry(a,s.signal);let l=await a(`${this.credentials.apiOrigin}/v3${e}`,{method:s.method??"GET",headers:{authorization:`Bearer ${this.credentials.accessToken}`,accept:"application/json","user-agent":xr,"x-reason-agent":"Reason CLI","x-client-surface":this.options.clientSurface??"direct_cli",...s.raw?{"content-type":s.raw.contentType}:s.body===void 0?{}:{"content-type":"application/json"},...s.headers,...s.ifNoneMatch?{"if-none-match":s.ifNoneMatch}:{}},body:s.raw?s.raw.bytes:s.body===void 0?void 0:JSON.stringify(s.body),signal:s.signal,redirect:s.ifNoneMatch?"manual":"error"}),u=await l.json().catch(()=>({}));if(l.status===401&&!r&&s.retryUnauthorized!==!1&&this.credentials.credentialKind!=="api_key"){let g=await be({fetchImpl:a,path:this.options.credentialsPath,forceRefresh:!0,refused:this.credentials.accessToken,signal:s.signal});if(g)return this.credentials=g,this.exchange(e,s,!0)}return{status:l.status,headers:l.headers,json:u}}async renewBeforeExpiry(e,s){let r=this.credentials;if(r.credentialKind==="api_key"||!(Date.parse(r.expiresAt)<=Date.now()+60000))return;let a=await be({fetchImpl:e,path:this.options.credentialsPath,signal:s}).catch(()=>null);if(a&&a.apiOrigin===r.apiOrigin&&a.orgId===r.orgId&&a.clientId===r.clientId)this.credentials=a}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(s){if(s instanceof C&&(s.status===404||s.status===405||s.status===403&&s.code==="endpoint_not_available"))return null;throw s}}addDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots`,{method:"POST",body:s,signal:AbortSignal.timeout(30000)})}removeDeviceRoot(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices/${encodeURIComponent(e)}/roots/${encodeURIComponent(s)}`,{method:"DELETE",signal:AbortSignal.timeout(30000)})}machinePath(e,s=""){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/machines`;return e===void 0?r:`${r}/${encodeURIComponent(e)}${s}`}async listMachines(){return m(ce,await this.request(this.machinePath()),"invalid_machine_list").machines}async createMachine(e){let s=await this.request(this.machinePath(),{method:"POST",body:{name:e.name,...e.platform?{platform:e.platform}:{}}});return m(de,s,"invalid_machine").machine}async deleteMachine(e){let s=await this.request(this.machinePath(e),{method:"DELETE"});return m(ue,s,"invalid_machine_deletion")}async listSecretNames(e){let s=await this.request(`${this.secretsPath()}?scope=${e}`);return m(fe,s,"invalid_secret_list").items.map((r)=>r.name)}async setSecret(e){let s=await this.request(this.secretsPath(),{method:"POST",body:e});return m(_e,s,"invalid_secret_write")}secretsPath(){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/secrets`}async createMachineToken(e){let s=await this.request(this.machinePath(e,"/tokens"),{method:"POST",body:{}});return m(ge,s,"invalid_machine_token")}async createMachineEnrollmentTicket(e,s){let r=await this.request(this.machinePath(e,"/enrollment-tickets"),{method:"POST",body:s,signal:AbortSignal.timeout(30000),retryUnauthorized:!1});return m(U,r,"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,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/claim`,{method:"POST",body:e,signal:s});return m(ba,r,"invalid_agent_network_job")}async completeAgentNetworkRelayJob(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-network/relay/jobs/${encodeURIComponent(e)}`,{method:"POST",body:s,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((s)=>typeof s.email==="string"?[{email:s.email,role:typeof s.role==="string"?s.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,s,r={}){let a=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:r.retryUnauthorized,signal:r.signal,body:{...a,...s?{account_key:s}:{}}})}async listRepositories(){return((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/repositories`)).items??[]).flatMap((s)=>{let r=typeof s.full_name==="string"?s.full_name:typeof s.repo_full_name==="string"?s.repo_full_name:null;if(!r)return[];return[{repo_id:typeof s.repo_id==="string"?s.repo_id:void 0,full_name:r,provider:s.provider==="gitlab"?"gitlab":"github",default_branch:typeof s.default_branch==="string"?s.default_branch:null,private:typeof s.private==="boolean"?s.private:void 0}]})}async listProjects(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/projects`),s=Z.safeParse(e);if(!s.success)throw new C(502,"invalid_project_list","Reason returned an unexpected project list.");return s.data.items}async listReasons(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons`);return m(ee,e,"invalid_reason_list").items}async openReasonConversation(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/reasons/${encodeURIComponent(e)}/conversation`,{method:"POST"});return m(n({session_id:t().min(1)}),s,"invalid_reason_conversation").session_id}async listSkills(){try{let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills`);return m(te,e,"invalid_skill_list").items}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return[];throw e}}async listDevices(){let e=[],s=null;for(let r=0;r<50;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/devices${s?`?after=${encodeURIComponent(s)}`:""}`),l=V.safeParse(a);if(!l.success)throw new C(502,"invalid_device_list","Reason returned an unexpected machine list.");if(e.push(...l.data.devices),s=l.data.has_next_page?l.data.end_cursor??null:null,!s)break}return e}async listModels(){try{let s=((await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`)).models??[]).filter((l)=>l.hidden!==!0),r=s.filter((l)=>l.available!==!1).map(({reasoning_efforts:l,hidden:u,available:g,...h})=>({...h,...Array.isArray(l)?{reasoning_efforts:J.filter((p)=>l.includes(p))}:{}})),a=new Set(r.map((l)=>l.detail));return{models:r.length>1&&a.size===1?r.map(({detail:l,...u})=>u):r,runnable:r.length>0||s.length===0}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return{models:[],runnable:!0};throw e}}async getAgentVersion(e){try{let s=await this.request("/deployment",{signal:e,retryUnauthorized:!1});return S(s.reason_version)?s.reason_version:null}catch{return null}}async getUsageQuota(){try{let e=F.safeParse(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/usage/quota`));if(!e.success)return null;let s;try{s=G(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/agent-auth/models`))}catch{}return{...e.data,own_inference:s}}catch(e){if(e instanceof C&&(e.status===403||e.status===404))return null;throw e}}async listSessionFields(e){let s=new URLSearchParams({first:String(Math.min(Math.max(e.first,1),200)),status:e.status??"active"});if(e.origin)s.set("origin",e.origin);s.set("fields",e.fields.join(","));let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${s.toString()}`,{status:a,headers:l,json:u}=await this.exchange(r,e.etag?{ifNoneMatch:e.etag}:{});if(a===304)return null;if(a<200||a>299)throw w(a,u,l.get("retry-after"));return{items:Array.isArray(u.items)?u.items:[],etag:l.get("etag")}}async listSessions(e=50,s,r={}){let a=new URLSearchParams({first:String(Math.min(Math.max(e,1),200)),status:r.status??"active"});if(s)a.set("project_id",s);if(r.origin)a.set("origin",r.origin);return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions?${a.toString()}`)).items??[]}getSession(e,s){let r=s?.fields.length?`?fields=${encodeURIComponent(s.fields.join(","))}`:"";return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${r}`)}async prestartSession(e){let s=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/prestart`,{method:"POST",body:{client_session_id:e}});return s?.status==="starting"||s?.status==="ready"}async createSession(e){let s=e.mode==="ephemeral"||e.workspaceOwnership==="externally-managed";if(e.attachments?.length)await this.requireSessionAttachments();if(s||e.runtimeProfile){let l=await this.request("/deployment");if(s&&(!Array.isArray(l.session_modes)||!l.session_modes.includes(e.mode??"standard")||!Array.isArray(l.workspace_ownerships)||!l.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(l.experimental_runtime_profiles)||!l.experimental_runtime_profiles.includes(e.runtimeProfile)))throw Error("Deployment does not support the requested runtime profile; refusing to create a Session.")}let r=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()}`}}),a=await this.getSession(r.session_id);if(s){let l=a.session_policy,u=["memoryRead","memoryWrite","skills","inheritedInstructions","integrations","secretInjection"];if(!l||l.version!==1||l.mode!==(e.mode??"standard")||l.workspaceOwnership!==(e.workspaceOwnership??"managed")||!l.components||u.some((g)=>l.components[g]!==!0))throw await this.cancelSession(r.session_id),Error("Server did not attest the requested Session policy; cancellation requested.")}if(e.runtimeProfile&&a.experimental_runtime_profile!==e.runtimeProfile)throw await this.cancelSession(r.session_id),Error("Server did not attest the requested runtime profile; cancellation requested.");return a}async getEvents(e,s=-1,r={}){try{return await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/events?after_seq=${s}&limit=500${r.waitMs?`&wait_ms=${r.waitMs}`:""}`,r.signal?{signal:r.signal}:{})}catch(a){if(!(a instanceof C)||a.status!==403&&a.status!==404)throw a;return{session:await this.getSession(e),items:[],next_seq:s}}}async getMessages(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages?first=500${s===void 0?"":`&after_seq=${s}`}`)}async getAttachments(e,s){try{return(await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/attachments${s?`?view=${s}`:""}`)).items??[]}catch(r){if(r instanceof C&&(r.status===403||r.status===404))return[];throw r}}async requireSessionAttachments(){let e=await this.request("/deployment",{headers:{"cache-control":"no-cache"}});if(e.session_attachments!==!0){let s=typeof e.reason_version==="string"&&/^\d+\.\d+(?:\.\d+)?$/.test(e.reason_version)?`Agent ${e.reason_version}`:null,r=typeof e.commit_sha==="string"&&/^[a-f0-9]{40,64}$/i.test(e.commit_sha)?`server ${e.commit_sha.slice(0,12)}`:null,a=[s,r].filter(Boolean).join(", ");throw Error(`This server does not support Session image attachments: ${new URL(this.credentials.apiOrigin).host}${a?` (${a})`:""}. 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,s,r={}){if(r.attachments?.length)await this.requireSessionAttachments();return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages`,{method:"POST",body:{message:s,...r.attachments?.length?{attachments:r.attachments}:{},...r.model?{model:r.model}:{},...r.reasoningEffort?{reasoning_effort:r.reasoningEffort}:{},...r.target?{target:r.target}:{},...r.delivery?{delivery:r.delivery}:{}}})}async steerQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/steer`,{method:"POST",body:{}})}async withdrawQueuedMessage(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/messages/${encodeURIComponent(s)}/queued`,{method:"DELETE"})}async getConversation(e){let s=[],r=null;for(let a=0;a<50;a+=1){let l=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/conversation${r?`?after=${encodeURIComponent(r)}`:""}`);if(s.push(...l.items??[]),!l.has_next_page||!l.end_cursor)break;r=l.end_cursor}return s}createSharedLink(e,s){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/shared-links`,{method:"POST",body:{url:s.url,...s.label?{label:s.label}:{},...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}})}sessionAction(e,s,r={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/${s}`,{method:"POST",body:r})}renameSession(e,s){return this.sessionAction(e,"rename",{title:s||null})}moveSessionToProject(e,s){return this.sessionAction(e,"project",{project_id:s})}compactSession(e){return this.sessionAction(e,"compact")}retrySession(e){return this.sessionAction(e,"retry")}rewindSession(e,s){return this.sessionAction(e,"rewind",{message_id:s.messageId,content:s.content,request_id:s.requestId})}forkSession(e,s){return this.sessionAction(e,"fork",{...s.message?{message:s.message}:{},client_session_id:s.clientSessionId})}cancelSession(e,s={}){return this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}/cancel`,{method:"POST",body:s.mode==="hard"?{mode:"hard"}:{}})}sessionPath(e,s=""){return`/organizations/${encodeURIComponent(this.credentials.orgId)}/sessions/${encodeURIComponent(e)}${s}`}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 m(x,await this.request(this.sessionPath(e,"/tags")),"invalid_session_tags").tags}async appendSessionTags(e,s){let r=await this.request(this.sessionPath(e,"/tags"),{method:"POST",body:{tags:s}});return m(x,r,"invalid_session_tags").tags}async sessionInsight(e,s=!1){let r=await this.request(this.sessionPath(e,s?"/insights/generate":"/insights"),s?{method:"POST",body:{}}:{});return m(ae,r,"invalid_session_insight")}async listAutomations(){let e=[],s=null;for(let r=0;r<20;r+=1){let a=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations?first=100${s?`&after=${encodeURIComponent(s)}`:""}`),l=m(oe,a,"invalid_automation_list");if(e.push(...l.items),s=l.has_next_page?l.end_cursor??null:null,!s)break}return e}async createScheduledAutomation(e,s){let r=`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations`,a=m(A,await this.request(r,{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(`${r}/${encodeURIComponent(a.id)}/triggers`,{method:"POST",body:s})}catch(l){throw await this.deleteAutomation(a.id).catch(()=>{return}),l}return a}async setAutomationEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"PATCH",body:{enabled:s}})}async deleteAutomation(e){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/automations/${encodeURIComponent(e)}`,{method:"DELETE"})}async transcribe(e,s){let r=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/transcribe`,{method:"POST",raw:{bytes:e,contentType:s}});return m(n({transcript:t()}),r,"invalid_transcript").transcript}async listMcpServers(){let e=await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/mcp-servers`);return m(ie,e,"invalid_mcp_server_list").items}async setSkillEnabled(e,s){await this.request(`/organizations/${encodeURIComponent(this.credentials.orgId)}/skills/${encodeURIComponent(e)}`,{method:"PUT",body:{is_enabled:s}})}}
|
|
3
|
+
export{ya,be,wa,C,eo,me};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{te}from"./vm-hands-entry-lite-9g52kxyj.js";import{_r}from"./vm-hands-entry-lite-jpvmkce5.js";import{dn}from"./vm-hands-entry-lite-zh6ncdjn.js";import{Se}from"./vm-hands-entry-lite-pxtycfdv.js";import{Ve}from"./vm-hands-entry-lite-zawytz09.js";import{Dt}from"./vm-hands-entry-lite-ab1pq3xg.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{existsSync as D,realpathSync as W,statSync as J}from"fs";import{platform as h}from"os";import{isAbsolute as q,sep as X}from"path";import{existsSync as F}from"fs";import{createRequire as H}from"module";var k=Dt(dn)(()=>H(import.meta.url)("bun:ffi"),F);function fi(){return process.platform==="win32"&&typeof globalThis.Bun<"u"&&k.available()}function E(e=process.env){return k.defaultShell(e)}function C(e){return k.shellArgs(e)}function M(e){let n=k.spawn({...e,env:e.environment});return n.exited.then(()=>n.close()),{write:(o)=>n.write(o),resize:(o,t)=>n.resize(o,t),kill:()=>n.close(),exited:n.exited}}var mi=43200000,an=_r,gi=4,Y=/^[A-Za-z0-9._:-]{1,160}$/,K=1000;function z(e){return Boolean(e)&&typeof e==="object"&&!Array.isArray(e)}function P(e,n){if(typeof e!=="number"||!Number.isFinite(e)||e<=0)return n;return Math.min(K,Math.max(1,Math.floor(e)))}function G(e,n=Date.now()){let o=["relay_url","session_id","expires_at"],t=new Set([...o,"cols","rows","cwd","workspace"]);if(!z(e)||o.some((b)=>!(b in e))||Object.keys(e).some((b)=>!t.has(b)))throw new r("invalid_pty_request","Reason terminal request is malformed.");let{relay_url:c,session_id:m,expires_at:g}=e;if(typeof c!=="string")throw new r("invalid_pty_request","Reason terminal relay URL is missing.");let d;try{d=new URL(c)}catch{throw new r("invalid_pty_request","Reason terminal relay URL is invalid.")}if(d.protocol!=="wss:"&&d.protocol!=="ws:"||d.username||d.password)throw new r("invalid_pty_request","Reason terminal relay URL is invalid.");if(typeof m!=="string"||!Y.test(m))throw new r("invalid_pty_request","Reason terminal session identity is invalid.");let p=typeof g==="string"?Date.parse(g):Number.NaN;if(!Number.isFinite(p)||p<=n)throw new r("invalid_pty_request","Reason terminal session has already expired.");if(e.cwd!==void 0&&typeof e.cwd!=="string")throw new r("invalid_pty_request","Reason terminal working directory is invalid.");let a=e.workspace===void 0?void 0:te(e.workspace);if(a===null||a&&e.cwd!==void 0)throw new r("invalid_pty_request","Reason terminal workspace is invalid.");return{relay_url:c,session_id:m,expires_at:new Date(Math.min(p,n+mi)).toISOString(),cols:P(e.cols,80),rows:P(e.rows,24),...e.cwd===void 0?{}:{cwd:e.cwd},...a?{workspace:a}:{}}}function Q(e,n){if(h()==="win32")[e,n]=[e.toLowerCase(),n.toLowerCase()];return n===e||n.startsWith(e+X)}function N(e,n){if(n===void 0)return e;if(!q(n))throw new r("pty_cwd_invalid","Reason terminal working directory must be absolute.");let o;try{o=W(n)}catch{throw new r("pty_cwd_invalid","Reason terminal working directory does not exist.")}if(!Q(e,o))throw new r("pty_cwd_outside_root","Reason terminal working directory escapes the granted root.");if(!J(o).isDirectory())throw new r("pty_cwd_invalid","Reason terminal working directory is not a directory.");return o}function Yc(e=process.env){if(h()==="win32")return E(e);let n=e.SHELL;if(n&&q(n)&&D(n))return n;for(let o of h()==="darwin"?["/bin/zsh","/bin/bash","/bin/sh"]:["/bin/bash","/bin/sh"])if(D(o))return o;return"/bin/sh"}function V(){let e=globalThis.Bun;if(!e)throw new r("pty_unavailable","Reason terminals require the Bun runtime.");return e.spawn}function Lo(){if(h()==="win32")return fi();return typeof globalThis.Bun<"u"}var Z=(e)=>{if(h()==="win32")try{return M({...e,file:e.shell,args:C(e.shell),environment:{...e.environment,TERM:"xterm-256color"}})}catch{throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}let n=V()({cmd:[e.shell,"-i","-l"],cwd:e.cwd,env:{...e.environment,TERM:"xterm-256color"},terminal:{cols:e.cols,rows:e.rows,data:(t,c)=>{e.onData(c)}}}),o=n.terminal;if(!o){try{n.kill()}catch{}throw new r("pty_unavailable","Reason could not allocate a pseudo-terminal.")}return{write:(t)=>o.write(t),resize:(t,c)=>o.resize(t,c),kill:()=>{try{n.kill()}catch{}},exited:n.exited.then((t)=>typeof t==="number"?t:null,()=>null)}},_i=(e,n)=>n===void 0?new WebSocket(e):new WebSocket(e,{proxy:n}),v=new Set;function ee(e){if(v.size>=gi||v.has(e))return null;v.add(e);let n=!1;return()=>{if(n)return;n=!0,v.delete(e)}}async function $o(e,n={}){let o=n.now??Date.now,t=G(e.payload,o()),c=ee(e.operationId);if(!c)throw new r("pty_slot_busy","This Reason Device already runs the maximum number of terminals.");let m=o(),g,d,p;try{let a=t.workspace?Ve(e.root,t.workspace):void 0;g=a?N(D(a.boundary)?W(a.boundary):a.boundary,a.path):N(e.root,t.cwd),d=n.environment??process.env,p=n.shellPath??Yc(d)}catch(a){throw c(),a}return await new Promise((a,b)=>{let w=null,i=null,S=!1,x=!1,y=!1,T=null,U=0,B=0,O=[],R=0,A=null,l=(s)=>{if(y)return;if(y=!0,A)clearTimeout(A);e.signal.removeEventListener("abort",L);try{w?.kill()}catch{}try{i?.close(1000,"pty_session_over")}catch{}if(c(),s.kind==="rejected"){b(s.error);return}let u={reason:s.reason,exit_code:T,output_bytes:U,input_bytes:B,duration_ms:Math.max(0,o()-m)};e.emitEvent("pty.stopped",{...u}).catch(()=>{return}),a({...u})},L=()=>{let s=e.signal.reason;l({kind:"rejected",error:s instanceof r?s:new r("cancelled","Reason closed the terminal session.")})};if(e.signal.aborted){L();return}e.signal.addEventListener("abort",L,{once:!0}),A=setTimeout(()=>l({kind:"resolved",reason:"session_expired"}),Math.max(1,Date.parse(t.expires_at)-o()));let I=(s)=>{if(U+=s.byteLength,!S||!i){if(O.push(s),R+=s.byteLength,R>an)l({kind:"resolved",reason:"output_backpressure"});return}try{i.send(s)}catch{l({kind:"resolved",reason:"relay_closed"});return}if(i.bufferedAmount>an)l({kind:"resolved",reason:"output_backpressure"})};try{w=(n.spawnPty??Z)({shell:p,args:["-i","-l"],cwd:g,cols:t.cols,rows:t.rows,environment:d,onData:(s)=>{if(!y)I(s)}})}catch(s){l({kind:"rejected",error:s instanceof r?s:new r("pty_spawn_failed","Reason could not start the terminal shell.")});return}w.exited.then((s)=>{if(y)return;if(T=s,S&&i)try{i.send(JSON.stringify({t:"exit",code:s}))}catch{}l({kind:"resolved",reason:"shell_exited"})});let j=(n.loadProxy??Se)()?.url;try{i=(n.connect??_i)(t.relay_url,j)}catch{l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}i.binaryType="arraybuffer",i.onopen=()=>{if(y||!i)return;S=!0;try{i.send(JSON.stringify({t:"open",cols:t.cols,rows:t.rows}));for(let s of O.splice(0))i.send(s);R=0}catch{l({kind:"resolved",reason:"relay_closed"});return}x=!0,e.emitEvent("pty.ready",{session_id:t.session_id,cols:t.cols,rows:t.rows}).catch(()=>{return})},i.onmessage=(s)=>{if(y||!w)return;let u=s.data;if(typeof u==="string"){let f;try{f=JSON.parse(u)}catch{return}if(!z(f))return;if(f.t==="resize"){try{w.resize(P(f.cols,t.cols),P(f.rows,t.rows))}catch{}return}if(f.t==="close")l({kind:"resolved",reason:"client_closed"});return}let _=u instanceof ArrayBuffer?new Uint8Array(u):ArrayBuffer.isView(u)?new Uint8Array(u.buffer,u.byteOffset,u.byteLength):null;if(!_||_.byteLength===0)return;B+=_.byteLength;try{w.write(_)}catch{}},i.onclose=()=>{if(y)return;if(!x){l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")});return}l({kind:"resolved",reason:"relay_closed"})},i.onerror=()=>{if(y||x)return;l({kind:"rejected",error:new r("pty_relay_unavailable","Reason could not reach the terminal relay.")})}})}
|
|
3
|
+
export{fi,mi,an,gi,Yc,Lo,_i,$o};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as E}from"child_process";var
|
|
2
|
+
import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{execFile as se,spawn as E}from"child_process";var vc="h264_ws_v1",Sc="video",Sr=["smooth","sharp","data_saver","balanced"];var Ec="video_presets";var M=8388608,O=65536,kc="control",xc="v1",X=200;function ts(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t,n=(i)=>typeof i==="string"&&i.length>0&&i.length<=X;if(Object.keys(e).length!==2||!n(e.user_id)||!n(e.name))return null;return{user_id:e.user_id,name:e.name}}var Cc="windows",Ac="v1",Pc="look",Rc="v1",J=["reason","grok"];function rs(t){return typeof t==="string"&&J.includes(t)?t:null}var _=200,Z=(t)=>typeof t==="string"&&Sr.includes(t);function Tc(t){if(!t||typeof t!=="object"||Array.isArray(t))return null;let e=t;if(Object.keys(e).length!==2||e.format!=="h264_ws_v1"||!Z(e.preset))return null;return{format:"h264_ws_v1",preset:e.preset}}var o={hello:1,frame:2,stats:3,pong:4,serverClipboard:5,error:6,audioHello:7,audio:8,control:9,windows:10,pointer:16,key:17,config:18,ping:19,clientClipboard:20,keyframeRequest:21,ack:22,audioEnable:23,resize:24};class l extends Error{constructor(t){super(t);this.name="DisplayVideoProtocolError"}}var Q=new TextEncoder,ee=new TextDecoder("utf-8",{fatal:!0});function p(t,e){if(e.byteLength+1>M)throw new l("message_too_large");let n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,e.byteLength+1),i.setUint8(4,t),n.set(e,5),n}function w(t){let e=Q.encode(t);if(e.byteLength>O)throw new l("text_too_large");return e}function m(t,e){if(!Number.isInteger(t)||t<0||t>65535)throw new l(`invalid_${e}`);return t}function te(t){if(!Number.isFinite(t))throw new l("invalid_window");return Math.max(-2147483648,Math.min(2147483647,Math.round(t)))}function Rn(t){switch(t.type){case"hello":{let e=w(t.codec),n=new Uint8Array(6+e.byteLength),i=new DataView(n.buffer);return i.setUint16(0,m(t.width,"width")),i.setUint16(2,m(t.height,"height")),i.setUint8(4,Math.max(1,Math.min(240,Math.round(t.fps)))),i.setUint8(5,Sr.indexOf(t.preset)),n.set(e,6),p(o.hello,n)}case"frame":{let e=new Uint8Array(13+t.data.byteLength),n=new DataView(e.buffer);return n.setUint8(0,t.key?1:0),n.setUint32(1,t.seq>>>0),n.setBigUint64(5,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,13),p(o.frame,e)}case"stats":return p(o.stats,w(JSON.stringify(t.stats)));case"pong":case"ping":{let e=new Uint8Array(8);return new DataView(e.buffer).setFloat64(0,t.token),p(t.type==="ping"?o.ping:o.pong,e)}case"serverClipboard":return p(o.serverClipboard,w(t.text));case"clientClipboard":return p(o.clientClipboard,w(t.text));case"error":return p(o.error,w(t.code));case"pointer":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint16(0,m(t.x,"x")),n.setUint16(2,m(t.y,"y")),n.setUint8(4,t.buttons&255),p(o.pointer,e)}case"key":{let e=new Uint8Array(5),n=new DataView(e.buffer);return n.setUint8(0,t.down?1:0),n.setUint32(1,t.keysym>>>0),p(o.key,e)}case"config":return p(o.config,Uint8Array.of(Sr.indexOf(t.preset)));case"keyframeRequest":return p(o.keyframeRequest,new Uint8Array(0));case"audioHello":{let e=w(t.codec),n=new Uint8Array(5+e.byteLength),i=new DataView(n.buffer);return i.setUint32(0,t.sampleRate>>>0),i.setUint8(4,t.channels&255),n.set(e,5),p(o.audioHello,n)}case"audio":{let e=new Uint8Array(8+t.data.byteLength);return new DataView(e.buffer).setBigUint64(0,BigInt(Math.max(0,Math.floor(t.captureMicros)))),e.set(t.data,8),p(o.audio,e)}case"control":return p(o.control,w(JSON.stringify(t.control)));case"windows":{let e=t.bounds.slice(0,_),n=new Uint8Array(e.length*16),i=new DataView(n.buffer);return e.forEach((s,a)=>{[s.x,s.y,s.width,s.height].forEach((c,d)=>i.setInt32(a*16+d*4,te(c)))}),p(o.windows,n)}case"audioEnable":return p(o.audioEnable,Uint8Array.of(t.on?1:0));case"resize":{let e=new Uint8Array(4),n=new DataView(e.buffer);return n.setUint16(0,m(t.width,"width")),n.setUint16(2,m(t.height,"height")),p(o.resize,e)}case"ack":{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t.seq>>>0),p(o.ack,e)}}}function L(t){let e=Sr[t];if(!e)throw new l("invalid_preset");return e}function y(t,e){if(t.byteLength!==e)throw new l("invalid_length")}function S(t){if(t.byteLength>O)throw new l("text_too_large");try{return ee.decode(t)}catch{throw new l("invalid_text")}}function ne(t){let e;try{e=JSON.parse(S(t))}catch{throw new l("invalid_stats")}let n=e;if(!n||typeof n!=="object"||["fps","kbps","dropped","restarts","queued_bytes"].some((s)=>typeof n[s]!=="number"||!Number.isFinite(n[s])))throw new l("invalid_stats");return{fps:n.fps,kbps:n.kbps,dropped:n.dropped,restarts:n.restarts,queued_bytes:n.queued_bytes}}function re(t){let e;try{e=JSON.parse(S(t))}catch{throw new l("invalid_control")}let n=e;if(!n||typeof n!=="object"||typeof n.you!=="boolean"||typeof n.same_user!=="boolean")throw new l("invalid_control");let i=n.holder===null?null:ts(n.holder);if(i===null&&n.holder!==null)throw new l("invalid_control");return{holder:i,you:n.you,same_user:n.same_user}}function ie(t,e){let n=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(t){case o.hello:if(e.byteLength<6)throw new l("invalid_length");return{type:"hello",width:n.getUint16(0),height:n.getUint16(2),fps:n.getUint8(4),preset:L(n.getUint8(5)),codec:S(e.subarray(6))};case o.frame:if(e.byteLength<14)throw new l("invalid_length");if(n.getUint8(0)>1)throw new l("invalid_frame_flags");return{type:"frame",key:n.getUint8(0)===1,seq:n.getUint32(1),captureMicros:Number(n.getBigUint64(5)),data:e.subarray(13)};case o.stats:return{type:"stats",stats:ne(e)};case o.ping:case o.pong:return y(e,8),{type:t===o.ping?"ping":"pong",token:n.getFloat64(0)};case o.serverClipboard:return{type:"serverClipboard",text:S(e)};case o.clientClipboard:return{type:"clientClipboard",text:S(e)};case o.error:return{type:"error",code:S(e)};case o.pointer:return y(e,5),{type:"pointer",x:n.getUint16(0),y:n.getUint16(2),buttons:n.getUint8(4)};case o.key:if(y(e,5),n.getUint8(0)>1)throw new l("invalid_key_flags");return{type:"key",down:n.getUint8(0)===1,keysym:n.getUint32(1)};case o.config:return y(e,1),{type:"config",preset:L(n.getUint8(0))};case o.keyframeRequest:return y(e,0),{type:"keyframeRequest"};case o.audioHello:if(e.byteLength<5)throw new l("invalid_length");return{type:"audioHello",sampleRate:n.getUint32(0),channels:n.getUint8(4),codec:S(e.subarray(5))};case o.audio:if(e.byteLength<9)throw new l("invalid_length");return{type:"audio",captureMicros:Number(n.getBigUint64(0)),data:e.subarray(8)};case o.audioEnable:if(y(e,1),n.getUint8(0)>1)throw new l("invalid_audio_flags");return{type:"audioEnable",on:n.getUint8(0)===1};case o.resize:return y(e,4),{type:"resize",width:n.getUint16(0),height:n.getUint16(2)};case o.control:return{type:"control",control:re(e)};case o.windows:{if(e.byteLength%16!==0||e.byteLength>_*16)throw new l("invalid_length");let i=[];for(let s=0;s<e.byteLength;s+=16)i.push({x:n.getInt32(s),y:n.getInt32(s+4),width:n.getInt32(s+8),height:n.getInt32(s+12)});return{type:"windows",bounds:i}}case o.ack:return y(e,4),{type:"ack",seq:n.getUint32(0)};default:return null}}class ns{buffer=new Uint8Array(0);push(t){let e=new Uint8Array(this.buffer.byteLength+t.byteLength);e.set(this.buffer),e.set(t,this.buffer.byteLength);let n=[],i=0;while(e.byteLength-i>=4){let s=new DataView(e.buffer,e.byteOffset+i,4).getUint32(0);if(s<1||s>M)throw new l("invalid_message_length");if(e.byteLength-i-4<s)break;let a=e[i+4],c=e.slice(i+5,i+4+s),d=ie(a,c);if(d)n.push(d);i+=4+s}return this.buffer=e.slice(i),n}}var j="/usr/bin/osascript",oe=5000,ae=1048576,ce=String.raw`
|
|
3
3
|
ObjC.import("CoreGraphics");
|
|
4
4
|
ObjC.import("ApplicationServices");
|
|
5
5
|
ObjC.import("AppKit");
|
|
@@ -29,7 +29,7 @@ function run(argv) {
|
|
|
29
29
|
const text = clipboard.stringForType($.NSPasteboardTypeString);
|
|
30
30
|
if (!text) continue;
|
|
31
31
|
const bytes = text.dataUsingEncoding($.NSUTF8StringEncoding);
|
|
32
|
-
if (Number(bytes.length) > ${
|
|
32
|
+
if (Number(bytes.length) > ${O}) continue;
|
|
33
33
|
stdout.writeData($("c " + bytes.base64EncodedStringWithOptions(0).js + "\n").dataUsingEncoding($.NSUTF8StringEncoding));
|
|
34
34
|
}
|
|
35
35
|
return;
|
|
@@ -70,7 +70,7 @@ function run(argv) {
|
|
|
70
70
|
}
|
|
71
71
|
}
|
|
72
72
|
`;function q(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!=="object")return null;let n=e,i=(c)=>typeof c==="number"&&Number.isFinite(c)?Math.min(65535,Math.round(c)):0;if(typeof n.screen!=="boolean"||typeof n.accessibility!=="boolean")return null;let s=i(n.width),a=i(n.height);return s>0&&a>0?{screen:n.screen,accessibility:n.accessibility,width:s,height:a}:null}function v(t,...e){let[n,...i]=[...t,j,"-l","JavaScript","-e",ce,...e];return[n,i]}function H(t,...e){return new Promise((n)=>{se(...v(t,...e),{env:{},timeout:oe,killSignal:"SIGKILL",maxBuffer:65536,encoding:"utf8"},(i,s)=>n(i?null:q(s.split(`
|
|
73
|
-
`)[0]??"")))})}function
|
|
73
|
+
`)[0]??"")))})}function Xt(t=[]){return H(t,"probe")}function Er(t,e){return H(t,"request",...e?[e]:[])}var N=2,ue=8,le=String.raw`
|
|
74
74
|
ObjC.import("CoreGraphics");
|
|
75
75
|
ObjC.import("Foundation");
|
|
76
76
|
ObjC.bindFunction("getppid", ["int", []]);
|
|
@@ -84,7 +84,7 @@ function run() {
|
|
|
84
84
|
const list = ObjC.castRefToObject($.CGWindowListCopyWindowInfo($.kCGWindowListOptionOnScreenOnly | $.kCGWindowListExcludeDesktopElements, 0));
|
|
85
85
|
const bounds = [];
|
|
86
86
|
const count = Number(list.count);
|
|
87
|
-
for (let i = 0; i < count && bounds.length < ${
|
|
87
|
+
for (let i = 0; i < count && bounds.length < ${_}; i++) {
|
|
88
88
|
const window = list.objectAtIndex(i);
|
|
89
89
|
if (Number(window.objectForKey("kCGWindowLayer").js) !== 0) continue;
|
|
90
90
|
const b = window.objectForKey("kCGWindowBounds");
|
|
@@ -101,12 +101,12 @@ function run() {
|
|
|
101
101
|
$.NSThread.sleepForTimeInterval(wait);
|
|
102
102
|
}
|
|
103
103
|
}
|
|
104
|
-
`;function de(t){let e;try{e=JSON.parse(t)}catch{return null}if(!Array.isArray(e))return null;let n=[];for(let i of e.slice(0,
|
|
104
|
+
`;function de(t){let e;try{e=JSON.parse(t)}catch{return null}if(!Array.isArray(e))return null;let n=[];for(let i of e.slice(0,_)){if(!Array.isArray(i)||i.length!==4||!i.every((u)=>typeof u==="number"&&Number.isFinite(u)))return null;let[s,a,c,d]=i.map(Math.round);if(c>0&&d>0)n.push({x:s,y:a,width:c,height:d})}return n}function is(t){let e=Date.now(),n=0,i=!1,s=(u,b={})=>{try{process.stderr.write(`${JSON.stringify({event:"display.windows_helper",state:u,...b})}
|
|
105
105
|
`)}catch{}},a=(u,b={})=>{if(i)return;i=!0,s(u,{updates:n,duration_ms:Date.now()-e,...b})},c=E(j,["-l","JavaScript","-e",le],{env:{},stdio:["ignore","pipe","ignore"]});s("started");let d="";return c.stdout.on("data",(u)=>{if(i)return;d+=u.toString("utf8");for(let b=d.indexOf(`
|
|
106
106
|
`);b>=0;b=d.indexOf(`
|
|
107
|
-
`)){let
|
|
107
|
+
`)){let x=de(d.slice(0,b));if(d=d.slice(b+1),x)n++,t(x)}if(d.length>65536)d=""}),c.once("error",(u)=>a("failed",{code:u.code??"spawn_failed"})),c.once("exit",(u,b)=>a("failed",{code:"exited",exit_code:u,signal:b})),{close(){a("stopped"),c.kill("SIGKILL")}}}var T=5,R=[{bit:1,button:0,down:1,up:2,drag:6},{bit:4,button:1,down:3,up:4,drag:7},{bit:2,button:2,down:25,up:26,drag:27}],fe=[[8,1,0],[16,-1,0],[32,0,1],[64,0,-1]],P=50,pe=500,V=4,I=131072,W=262144,D=524288,F=1048576,B=new Map([[65505,[56,I]],[65506,[60,I]],[65507,[59,W]],[65508,[62,W]],[65511,[58,D]],[65512,[61,D]],[65513,[58,D]],[65514,[61,D]],[65027,[61,D]],[65515,[55,F]],[65516,[54,F]]]),be=new Map([[65288,51],[65289,48],[65056,48],[65293,36],[65307,53],[65535,117],[65509,57],[65360,115],[65361,123],[65362,126],[65363,124],[65364,125],[65365,116],[65366,121],[65367,119],[65379,114],[65386,114],[65291,71],[65408,49],[65421,76],[65429,115],[65430,123],[65431,126],[65432,124],[65433,125],[65434,116],[65435,121],[65436,119],[65437,71],[65438,114],[65439,117],[65450,67],[65451,69],[65452,65],[65453,78],[65454,65],[65455,75],[65469,81],...[82,83,84,85,86,87,88,89,91,92].map((t,e)=>[65456+e,t]),...[122,120,99,118,96,97,98,100,101,109,103,111,105,107,113,106,64,79,80,90].map((t,e)=>[65470+e,t])]),G="asdfhgzxcv\x00bqweryt123465=97-80]ou[ip\x00lj'k;\\,/nm.\x00 `",Y='~!@#$%^&*()_+{}|:"<>?',he="`1234567890-=[]\\;',./",k=new Map;for(let t=0;t<G.length;t++){let e=G[t];if(e==="\x00")continue;if(k.set(e.charCodeAt(0),[t,!1]),e>="a"&&e<="z")k.set(e.toUpperCase().charCodeAt(0),[t,!0])}for(let t=0;t<Y.length;t++)k.set(Y.charCodeAt(t),[k.get(he.charCodeAt(t))[0],!0]);class K{now;x=-1;y=-1;mask=0;clicks=0;lastDown=null;held=new Set;constructor(t=()=>performance.now()){this.now=t}flags(){let t=0;for(let e of this.held)t|=B.get(e)[1];return t}mouse(t,e){return`m ${t} ${this.x} ${this.y} ${e} ${t===T?0:this.clicks} ${this.flags()}`}pointer(t,e,n){let i=[];if(t!==this.x||e!==this.y){this.x=t,this.y=e;let s=R.find((a)=>this.mask&a.bit);i.push(s?this.mouse(s.drag,s.button):this.mouse(T,0))}for(let s of R){let a=(this.mask&s.bit)!==0,c=(n&s.bit)!==0;if(!a&&c){let d=this.now(),u=this.lastDown;this.clicks=u&&u.button===s.button&&d-u.at<=pe&&Math.abs(t-u.x)<=V&&Math.abs(e-u.y)<=V?this.clicks+1:1,this.lastDown={button:s.button,at:d,x:t,y:e},i.push(this.mouse(s.down,s.button))}else if(a&&!c)i.push(this.mouse(s.up,s.button))}for(let[s,a,c]of fe)if(!(this.mask&s)&&n&s)i.push(`w ${a*P} ${c*P} ${this.flags()}`);return this.mask=n,i}key(t,e){let n=t?1:0,i=B.get(e);if(i){if(t)this.held.add(e);else this.held.delete(e);return[`k ${i[0]} ${n} ${this.flags()}`]}let s=be.get(e);if(s!==void 0)return[`k ${s} ${n} ${this.flags()}`];let a=e<256?e:(e&4278190080)===16777216?e&16777215:0,c=k.get(a);if(c)return[`k ${c[0]} ${n} ${this.flags()|(c[1]?I:0)}`];if(a<160||a>65535||a>=55296&&a<57344)return[];return[`u ${n} ${a} ${this.flags()}`]}}function os(t,e=[]){let n=E(...v(e),{env:{},stdio:["pipe","pipe","ignore"]}),i=new K,s="",a=!1,c=null,d=()=>{n.kill("SIGKILL"),c?.kill("SIGKILL")},u=(f)=>{if(a)return;a=!0,d(),t.end(f)},b=(f)=>u({error:new r("display_unavailable",f)}),x=(f)=>{if(a||f.length===0)return;if(n.stdin.write(f.map((g)=>`${g}
|
|
108
108
|
`).join("")),n.stdin.writableLength>ae)u({reason:"input_backpressure"})},z=()=>{c=E(...v(e,"clipboard"),{env:{},stdio:["ignore","pipe","ignore"]});let f="";c.stdout?.on("data",(g)=>{if(a)return;f+=g.toString("ascii");for(let h=f.indexOf(`
|
|
109
109
|
`);h>=0;h=f.indexOf(`
|
|
110
|
-
`)){let U=f.slice(0,h);if(f=f.slice(h+1),!U.startsWith("c "))continue;let A=U.slice(2);if(A.length>Math.ceil(
|
|
111
|
-
`);if(g<0){if(s.length>4096)u({reason:"display_protocol"});return}let h=q(s.slice(0,g));if(s=null,!h)u({reason:"display_protocol"});else if(!h.screen||!h.accessibility)b(e.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else z(),t.ready({width:h.width,height:h.height})}),n.stdin.on("error",()=>{return}),n.once("error",()=>b("Reason could not start this Mac's desktop input.")),n.once("exit",()=>{if(s!==null)b("Reason could not start this Mac's desktop input.");else u({reason:"display_closed"})}),{pointer:(f,g,h)=>
|
|
112
|
-
export{
|
|
110
|
+
`)){let U=f.slice(0,h);if(f=f.slice(h+1),!U.startsWith("c "))continue;let A=U.slice(2);if(A.length>Math.ceil(O/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(A)){u({reason:"display_protocol"});return}let C=Buffer.from(A,"base64");if(C.byteLength<=O)t.clipboard(C.toString("utf8"));if(a)return}if(f.length>Math.ceil(O/3)*4+2)u({reason:"display_protocol"})}),c.once("error",()=>b("Reason could not watch this Mac's desktop clipboard.")),c.once("exit",()=>{if(!a)b("Reason could not watch this Mac's desktop clipboard.")})};return n.stdout.on("data",(f)=>{if(a||s===null)return;s+=f.toString("utf8");let g=s.indexOf(`
|
|
111
|
+
`);if(g<0){if(s.length>4096)u({reason:"display_protocol"});return}let h=q(s.slice(0,g));if(s=null,!h)u({reason:"display_protocol"});else if(!h.screen||!h.accessibility)b(e.length>0?"Reason's background worker needs Screen Recording and Accessibility on this Mac (its own Reason entry in System Settings > Privacy & Security, not the Reason app's): run `reason permissions allow` on this Mac.":"Allow Screen Recording and Accessibility for this Mac's Reason worker, then restart it.");else z(),t.ready({width:h.width,height:h.height})}),n.stdin.on("error",()=>{return}),n.once("error",()=>b("Reason could not start this Mac's desktop input.")),n.once("exit",()=>{if(s!==null)b("Reason could not start this Mac's desktop input.");else u({reason:"display_closed"})}),{pointer:(f,g,h)=>x(i.pointer(f,g,h)),key:(f,g)=>x(i.key(f,g)),clipboard:(f)=>x([`c ${Buffer.from(f,"utf8").toString("base64")}`]),close(){a=!0,d()}}}
|
|
112
|
+
export{vc,Sc,Sr,Ec,O,kc,xc,ts,Cc,Ac,Pc,Rc,rs,Tc,Rn,ns,Xt,Er,is,os};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{to}from"./vm-hands-entry-lite-84mc1f7h.js";import{spawnSync as p}from"child_process";import{createHash as de}from"crypto";import{chmodSync as ge,closeSync as pe,existsSync as w,linkSync as fe,lstatSync as me,mkdirSync as Q,mkdtempSync as he,openSync as we,readdirSync as ye,readFileSync as Ee,readSync as ke,realpathSync as Ne,renameSync as E,rmSync as k,statSync as Y,symlinkSync as W,writeFileSync as I}from"fs";import{connect as Se}from"net";import{homedir as m}from"os";import{basename as Z,dirname as R,join as u}from"path";import{inflateRawSync as be}from"zlib";var oe=new Set(["<","\u02C2","\u1438","\u2039","\u3008","\u276C","\u276E","\u2770","\u16B2","\u2D66","\uD800\uDF2D","\uD81A\uDEEC","\uD834\uDE36","\u27E8","\u27EA","\u29FC","\u3008","\u300A","\uFE64","\uFF1C"]),D=(e)=>e===" "||e==="\t"||e===`
|
|
3
|
+
`||e==="\f"||e==="\r",ie=(e)=>e.length===1&&e>="!"&&e<="~",G=(e)=>e.length===1&&/[A-Za-z]/.test(e);function J(e){let n=Array.from(e),t=(r)=>{let s=r+Math.min(n.length-r,64),o=r;while(o<s&&(D(n[o])||n[o]==="/"))o+=1;let i=o-r,a=[];while(o<s&&!D(n[o])&&n[o]!==">"&&n[o]!=="\uFF1E")a.push(n[o++]);return i+a.length===s-r&&n.length-r>64||!a.every(ie)||ae(a)};return n.map((r,s)=>oe.has(r)&&t(s+1)?"[":r).join("")}function ae(e){let n=1;for(let t of e){let r=t==="0"?"o":t==="3"?"e":t==="4"||t==="@"?"a":t==="5"||t==="$"?"s":G(t)?t.toLowerCase():t,s="reason".indexOf(r),o=s<0?0:1<<s;if(n=1|(G(t)?0:n)|(n&o)<<1,n&64)return!0}return!1}var ce=/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g;function U(e){return J(e.replace(ce," ").replace(/[\u2028\u2029]/g," "))}var le=["CLAUDECODE","CLAUDE_CODE_SESSION_ID","CODEX_THREAD_ID","CODEX_SESSION_ID","GROK_SESSION_ID","GROK_WORKSPACE_ROOT","GEMINI_CLI","CURSOR_AGENT","OPENCODE","COPILOT_CLI","COPILOT_AGENT_SESSION_ID","AI_AGENT"];function ue(e=process.env,n=Boolean(process.stderr.isTTY)){let t=le.some((r)=>e[r]!==void 0)||Object.keys(e).some((r)=>r.startsWith("CODEX_SANDBOX"))||Boolean(e.REASON_NETWORK_AGENT)||Boolean(e.TINCAN_AGENT);return n&&!t}function Fe(e,n=ue()){return n?e:U(e)}class Ce extends Error{}var f="reason-network",g="0.12.10",_e={"aarch64-apple-darwin":"fd3e6eccf76aa3f3cdcbe516bb2e0885bc9416e89378d858c5d96e58a37a2996","x86_64-apple-darwin":"68a224c4e51ec91c4754fdda2724de0e72ba3f27b687b2466a7c7d5e492ad72c","aarch64-unknown-linux-musl":"ca6177ba2ac3fc2d1ca0a06953cb33ee09ab6d83f5b957bee54339b41b6672b4","x86_64-unknown-linux-musl":"d872f3e96066ed717cc775f9c580a2ab68feace60e06427ff216cec985f2115a","aarch64-pc-windows-msvc":"67b4f3f9c3f7e69e285eef863009fa014195b1c91a4e8b1abca81f1a085e55ed","x86_64-pc-windows-msvc":"9fad0c86fdc56e7b837b7c98960f685dd63721f4e6be5a172f8198eee82e5869"},Re="https://reasonmachines.com/cli/engine",N="REASON_AGENT_NETWORK_BIN";function ve(e=process.platform,n=process.arch){let t=n==="arm64"?"aarch64":n==="x64"?"x86_64":null,r=e==="darwin"?"apple-darwin":e==="linux"?"unknown-linux-musl":e==="win32"?"pc-windows-msvc":null;return t&&r?`${t}-${r}`:null}function ee(e){return`${f}-${e}${e.endsWith("-windows-msvc")?".zip":".tar.gz"}`}function xe(e){let n=_e[e];return n?{url:`${Re}/${g}/${ee(e)}`,sha256:n}:null}function A(e){let n=p(e,["--version"],{encoding:"utf8",timeout:5000}),[t,r]=n.status===0?n.stdout.trim().split(/\s+/):[];return t===f?r??null:null}function _(e,n){let t=e.split(".").map(Number),r=n.split(".").map(Number);for(let s=0;s<3;s+=1)if((t[s]??0)!==(r[s]??0))return(t[s]??0)>(r[s]??0);return!0}function S(e=m(),n=process.platform){return u(e,".reason","bin",`${f}${n==="win32"?".exe":""}`)}var v=process.platform==="win32"?`~\\.local\\bin\\${f}.exe`:`~/.local/bin/${f}`;async function Te(e=process.env,n=()=>{}){if(e[N])return e[N];let t=S(),r=T(),s=r?.path===t&&y(t)===r.fingerprint?r:null,o=s?.kept,i=M(e)?null:$e(o);if(s?.version===g&&!i)return t;let a=w(t)?A(t):null;if(i){let c=A(i.path),d=a&&_(a,g)?a:g;if(!c||!_(d,c)){if(c)n(`Reason Network: ${v} (${c}) is newer than the version \`reason network\` keeps up to date (${d}), so it was left as it is.`);o=i.fingerprint,i=null}}if(s?.version===g&&!i)return F(t,o);if(!a||!_(a,g))await ne(t);let l=p(t,["setup",...M(e)?["--no-service"]:[]],{env:await C(e),encoding:"utf8",timeout:60000});if(l.status!==0){let c=b((l.stderr||l.stdout||"").trim().split(`
|
|
4
|
+
`).pop()??"");if(s)return B(m(),{...s,fingerprint:y(t)??s.fingerprint,...o?{kept:o}:{}}),n(i?`Reason Network: couldn't move your agents off ${v}${c?` (${c})`:""}; they keep using it. Run reason network to try again.`:`Reason Network: couldn't finish setting up on this computer${c?` (${c})`:""}. Run reason network to try again.`),t;throw new Ce(`Couldn't connect this computer's agents to the network${c?` (${c})`:""}. Run reason network to try again.`)}if(i)o=Pe(i,t,n);return F(t,o),p(t,["stop"],{env:e,stdio:"ignore",timeout:15000}),t}function $e(e){let n=u(m(),".local","bin",Z(S())),t;try{t=me(n)}catch{return null}let r=`${t.size}:${t.mtimeMs}:${t.ino}`;if(!t.isFile()||r===e)return null;try{let s=Y(S());if(s.ino===t.ino&&s.dev===t.dev)return null}catch{}try{let s=Buffer.alloc(2),o=we(n,"r");try{ke(o,s,0,2,0)}finally{pe(o)}if(s.toString("latin1")==="#!")return null}catch{return null}return{path:n,fingerprint:r}}function Pe(e,n,t){let r=`${e.path}.reason-${process.pid}`;try{if(k(r,{force:!0}),process.platform==="win32"){try{W(n,r,"file")}catch{fe(n,r)}te(r,e.path,"win32")}else W(n,r),E(r,e.path);t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date (${v} points to it). Restart a running agent to pick it up.`);return}catch(s){return k(r,{force:!0}),t(`Reason Network: your agents on this computer now use the version \`reason network\` keeps up to date, but ${v} couldn't be pointed to it (${s instanceof Error?s.message:String(s)}). Remove that copy so it can't take them back.`),e.fingerprint}}async function al(e={}){let n=e.env??process.env,t=e.home??m(),r=S(t),s=T(t);if(n[N]||s?.path!==r||y(r)!==s.fingerprint)return!1;if(s.version===g)return!1;let o=A(r);if(o&&_(o,g))return!1;return await ne(r),B(t,{...s,fingerprint:y(r)??""}),e.beforeRestart?.(),p(r,["stop"],{env:n,stdio:"ignore",timeout:15000}),!0}async function C(e){if(e[j])return e;try{let{defaultWorkerServiceHost:n,workerServiceLauncher:t}=await import("./serve-service-3dkyznay.js");return{...e,[j]:t(n(m()),e)}}catch{return e}}var j="REASON_NETWORK_REASON_BIN";function M(e=process.env){return Boolean(e.REASON_NETWORK_NO_SERVICE||e.TINCAN_NO_SERVICE)}var L=(e)=>u(e,".reason","ask-engine.json");function y(e){try{let n=Y(e);return`${n.size}:${n.mtimeMs}:${n.ino}`}catch{return null}}function cl(e=m()){return T(e)?.version??null}function T(e=m()){try{let n=JSON.parse(Ee(L(e),"utf8"));if(typeof n.path!=="string"||typeof n.fingerprint!=="string"||typeof n.version!=="string")return null;return{path:n.path,fingerprint:n.fingerprint,version:n.version,...typeof n.kept==="string"?{kept:n.kept}:{}}}catch{return null}}function B(e,n){Q(R(L(e)),{recursive:!0}),I(L(e),JSON.stringify(n))}function F(e,n){let t=y(e);if(t)B(m(),{path:e,fingerprint:t,version:g,...n?{kept:n}:{}});return e}async function ne(e){let n=ve(),t=n?xe(n):null;if(!n||!t)throw new Ce(`Reason Network runs on macOS, Linux and Windows (arm64 or x64); this is ${process.platform} ${process.arch}.`);let{url:r,sha256:s}=t,o;try{let a=await fetch(r,{signal:AbortSignal.timeout(120000)});if(!a.ok)throw Error(`HTTP ${a.status}`);o=Buffer.from(await a.arrayBuffer())}catch(a){let l=a instanceof Error&&a.name==="TimeoutError"?"no download within 2 minutes":a instanceof Error?a.message.replace(/\.$/,""):String(a);throw new Ce(`Couldn't download Reason Network from ${new URL(r).host} (${l}). Check the connection and run reason network again.`)}if(de("sha256").update(o).digest("hex")!==s)throw new Ce("The Reason Network download didn't match its checksum, so it wasn't installed.");Oe(o,n,e)}var H="Couldn't unpack the Reason Network download.";function Oe(e,n,t,r=process.platform){Q(R(t),{recursive:!0});let s=he(u(R(t),".reason-engine-"));try{let o=u(s,f);if(ee(n).endsWith(".zip"))o=u(s,`${f}.exe`),I(o,Ie(e,`${f}.exe`));else{I(u(s,"engine.tar.gz"),e);let i=p("tar",["--no-same-owner","-xzf",u(s,"engine.tar.gz"),"-C",s],{encoding:"utf8"});if(i.status!==0||!w(o)){let a=(i.stderr??"").trim().split(`
|
|
5
|
+
`).slice(-3).join("; "),l=i.error?`tar failed: ${i.error.message}`:i.signal?`tar was stopped by ${i.signal}`:i.status!==0?`tar exited ${i.status}${a?`: ${a}`:""}`:`no ${f} in it`;throw new Ce(`Couldn't unpack the Reason Network download (${l}).`)}}ge(o,493),te(o,t,r)}finally{k(s,{recursive:!0,force:!0})}}function Ie(e,n){let t=e.lastIndexOf(Buffer.from("PK\x05\x06","latin1"));if(t<0||t+22>e.length)throw new Ce(H);let r=e.readUInt32LE(t+16);for(let s=e.readUInt16LE(t+10);s>0;s-=1){if(r+46>e.length||e.readUInt32LE(r)!==33639248)break;let o=e.readUInt16LE(r+28);if(e.toString("utf8",r+46,r+46+o)===n){let i=e.readUInt16LE(r+10),a=e.readUInt32LE(r+20),l=e.readUInt32LE(r+24),c=e.readUInt32LE(r+42);if(c+30>e.length||e.readUInt32LE(c)!==67324752)break;let d=c+30+e.readUInt16LE(c+26)+e.readUInt16LE(c+28);if(d+a>e.length)break;let h=e.subarray(d,d+a),P;try{P=i===0?Buffer.from(h):i===8?be(h):Buffer.alloc(0)}catch{break}if(i!==0&&i!==8||P.length!==l)break;return P}r+=46+o+e.readUInt16LE(r+30)+e.readUInt16LE(r+32)}throw new Ce(H)}function te(e,n,t){if(t!=="win32"||!w(n)){E(e,n);return}let r=R(n),s=(i)=>i.startsWith(`${Z(n)}.`)&&i.endsWith(".old");for(let i of ye(r).filter(s))try{k(u(r,i),{force:!0})}catch{}let o=`${n}.${process.pid}-${Date.now()}.old`;E(n,o);try{E(e,n)}catch(i){throw E(o,n),i}try{k(o,{force:!0})}catch{}}function Ae(e=process.env,n=m()){let t=e.REASON_NETWORK_HOME?.trim()||e.TINCAN_HOME?.trim();if(t)return t;let r=u(n,".reason","network"),s=u(n,".tincan");return!K(r)&&K(s)?s:r}var K=(e)=>w(u(e,"network.db"))||w(u(e,"tincan.db"));function Me(e,n=process.platform,t=Ne.native){let r=w(u(e,"network.db"))||!w(u(e,"tincan.db"));if(n==="win32"){let o=e;try{o=t(e),o=o.startsWith("\\\\?\\")?o.slice(4):o.startsWith("\\\\")?`UNC\\${o.slice(2)}`:o}catch{}return`\\\\.\\pipe\\${r?"reason-network":"tincan"}-${z(o)}`}let s=u(e,r?"network.sock":"tincan.sock");if(Buffer.byteLength(s)<100)return s;return u("/tmp",`${r?"reason-network":"tincan"}-${process.getuid?.()??0}`,`${z(s)}.sock`)}function z(e){let n=0xcbf29ce484222325n;for(let t of Buffer.from(e))n=BigInt.asUintN(64,(n^BigInt(t))*0x100000001b3n);return n.toString(16).padStart(16,"0")}class qr extends Error{code;constructor(e,n){super(e);this.code=n}}function Ji(e){return e instanceof qr&&/isn't registered/.test(e.message)}var re="not_in_team",se=15000,Le=new Set(["who","team","inbox","unread","held"]),Be=90000,De="Reason Network on this computer closed the connection";class x{socket;nextId=1;buffer="";pending=new Map;closed=null;hungUp=!1;constructor(e){this.socket=e;e.setEncoding("utf8"),e.on("data",(t)=>this.read(t));let n=(t)=>{this.closed=t;for(let r of this.pending.values())r.reject(t);this.pending.clear()};e.on("error",(t)=>n(t)),e.on("close",()=>n(Error(this.hungUp?"the connection to Reason Network on this computer was closed here":De)))}static open(e){return new Promise((n,t)=>{let r=Se(e);r.once("connect",()=>n(new x(r))),r.once("error",t)})}read(e){this.buffer+=e;let n=this.buffer.indexOf(`
|
|
6
|
+
`);while(n>=0){let t=this.buffer.slice(0,n);if(this.buffer=this.buffer.slice(n+1),n=this.buffer.indexOf(`
|
|
7
|
+
`),!t.trim())continue;let r;try{r=JSON.parse(t)}catch{continue}if(typeof r.id!=="number")continue;let s=this.pending.get(r.id);if(!s)continue;if(this.pending.delete(r.id),r.ok){s.resolve(r.result);continue}let o=r.error??"Reason Network on this computer refused the request",i=typeof r.code==="string"?r.code:/not (in|connected to) a team/i.test(o)?re:null;s.reject(new qr(b(o),i))}}call(e,n={},t=se){if(this.closed)return Promise.reject(this.closed);let r=this.nextId++;return this.socket.write(`${JSON.stringify({id:r,op:e,...n})}
|
|
8
|
+
`),new Promise((s,o)=>{let i=setTimeout(()=>{this.pending.delete(r),o(Error(`Reason Network on this computer didn't answer ${e} within ${Math.round(t/1000)}s`))},t);this.pending.set(r,{resolve:(a)=>{clearTimeout(i),s(a)},reject:(a)=>{clearTimeout(i),o(a)}})})}get isClosed(){return this.closed!==null}close(){this.hungUp=!0,this.socket.end()}}var O=/^(Claude Code|Grok|Codex) \u00B7 (.*)$/,Ge={"Claude Code":"claude-code",Grok:"grok",Codex:"codex"},Je=/^ask-[0-9a-f]{6}$/;function V(e){return{id:e.id,from:e.from,fromAgent:e.from_agent,to:e.to,replyTo:e.reply_to,body:e.body,sentAt:e.sent_at}}function q(e){return{person:e.person,machine:e.machine,isMe:e.is_me,online:e.online,link:e.link,rttMs:e.rtt_ms}}class Ot{engine;env;connection=null;waits=new Set;constructor(e,n){this.engine=e;this.env=n}static async open(e=process.env,n){return new Ot(await Te(e,n),e)}static openInstalled(e=process.env){if(e[N])return new Ot(e[N],e);let n=S(),t=T();return t?.path===n&&y(n)===t.fingerprint?new Ot(n,e):null}socketPath(){return Me(Ae(this.env))}async open(){try{return await x.open(this.socketPath())}catch{return p(this.engine,["who","--json"],{env:this.env,stdio:"ignore",timeout:15000}),await x.open(this.socketPath())}}async call(e,n={},t){if(!this.connection||this.connection.isClosed)this.connection=await this.open();try{return await this.connection.call(e,n,t)}catch(r){if(!/closed|ECONNRESET|EPIPE/.test(String(r)))throw r;if(this.connection=await this.open(),!Le.has(e))throw r;return await this.connection.call(e,n)}}async waitOn(e,n){let t=await this.open();this.waits.add(t);try{return await t.call(e,n,n.wait_secs*1000+se)}finally{this.waits.delete(t),t.close()}}close(){this.connection?.close(),this.connection=null;for(let e of this.waits)e.close();this.waits.clear()}async team(){try{let{team_id:e,messages:n,...t}=await this.call("team"),r=t.machines.find((o)=>o.is_me)?.endpoint,s=Array.isArray(n)?n.flatMap((o)=>{let i=to.safeParse(o);return i.success?[i.data]:[]}):null;return{...t,...typeof e==="string"&&e?{teamId:e}:{},machines:t.machines.map(q),...typeof r==="string"&&r?{endpoint:r}:{},...s?{messageCounts:s}:{}}}catch(e){if(e instanceof qr&&e.code===re)return null;throw e}}async snapshot(e={}){let n=await this.call("who",{all:Boolean(e.all),...e.filter?{filter:e.filter}:{}}),t=new Set(n.sessions.filter((s)=>O.test(s.doing??"")).map((s)=>`${s.person}/${s.machine}:${s.cwd}`)),r=n.sessions.filter((s)=>e.all||!Je.test(s.name)).filter((s)=>O.test(s.doing??"")||!t.has(`${s.person}/${s.machine}:${s.cwd}`)).map((s)=>{let o=O.exec(s.doing??"");return{address:s.address,name:s.name,person:s.person,machine:s.machine,agent:o?Ge[o[1]]:s.agent,cwd:s.cwd,repo:s.repo,branch:s.branch,status:o?o[2]==="ready for work"?"idle":o[2]==="stopped"?"offline":"busy":s.status,since:s.since,doing:o?o[2]:s.doing,isMe:s.is_me,worker:Boolean(o),tier:s.tier??null}});return{team:n.team,person:n.person,machine:n.machine,machines:n.machines.map(q),sessions:r}}async send(e,n,t={}){if(!t.from)await this.call("hook",{agent:"cli",event:"stop",session_id:"terminal",name:"terminal",cwd:process.cwd(),mail:!1});let r=await this.call("send",{from:t.from??"cli:terminal",to:e,body:n,...t.replyTo?{reply_to:t.replyTo}:{},wake:t.wake??!0,...t.notify?{notify:!0}:{}});return{ids:r.ids,recipients:r.recipients.map((s)=>s.address),deliveries:r.recipients.map((s)=>({address:s.address,state:s.state,note:s.note??""}))}}async session(e,n={}){let t=n.agent??"cli",r=(a,l={})=>this.call("hook",{agent:t,event:a,session_id:e,name:e,cwd:process.cwd(),mail:!1,...l}),s=await r("stop"),o=`${t}:${e}`,i=s.address??e;return{name:e,get address(){return i},next:async(a)=>(await this.waitOn("inbox",{key:o,wait_secs:a,peek:!0})).messages.map(V),ack:async(a)=>{if(a.length)await this.call("delivered",{key:o,ids:a})},busy:async(a)=>{if(await r("prompt"),a)await r("doing",{doing:a})},idle:async(a)=>{if(await r("stop"),a)await r("doing",{doing:a})},doing:async(a)=>{await r("doing",{doing:a})},end:async()=>{await r("end")},rename:async(a)=>{i=(await this.call("set_status",{key:o,name:a})).address},send:(a,l,c,d)=>this.send(a,l,{from:o,...c?{replyTo:c}:{},...d?.notify?{notify:!0}:{}})}}async inbox(e={}){let t=(await this.waitOn("inbox",{key:"cli:terminal",wait_secs:e.waitSeconds??0,peek:!0}).catch((r)=>{if(/isn't registered/.test(String(r)))return{messages:[]};throw r})).messages.map(V);if(t.length&&!e.peek)await this.call("delivered",{key:"cli:terminal",ids:t.map((r)=>r.id)});return t}async link(e={}){return await this.call("link",{new:Boolean(e.new)})}async changeTeam(e,n){try{return await this.call(e,n,Be)}finally{this.close()}}async changeOntoTeam(e,n){try{await this.changeTeam(e,n)}catch(t){if(!/closed|ECONNRESET|EPIPE/.test(String(t)))throw t;if(await this.team())return;await this.changeTeam(e,n)}}async createTeam(e,n){await this.changeOntoTeam("create_team",{name:e,person:n})}async join(e,n){await this.changeOntoTeam("join",{ticket:e,person:n})}async leave(){return await this.changeTeam("leave",{force:!0})}async remove(e){return await this.call("remove",{who:e})}endpoint(){let e=p(this.engine,["endpoint"],{encoding:"utf8",env:this.env,timeout:30000}),n=e.status===0?e.stdout.trim():"";if(!n)throw new Ce(`Reason Network on this computer couldn't say its endpoint${X(e)}.`);return n}async enterTeam(e,n,t){let r=t?{proof:t}:{},[s,o]="create"in e?["create_team",{name:e.create,person:n,...r}]:["join",{ticket:e.join,person:n,...r}],i=null;for(let a=0;a<2&&!i?.person;a+=1)try{i=await this.changeTeam(s,o)}catch(l){let c=String(l),d=l instanceof qr&&l.code?l.code:/\(same_account_needs_owner\)/.test(c)?"same_account_needs_owner":/already in this team/.test(c)?"name_taken":null;if(d==="same_account_needs_owner")return{state:"needs_owner"};if(d==="name_taken")return{state:"name_taken"};if(!/closed|ECONNRESET|EPIPE/.test(c))throw l;let h=await this.team();if(h)i={name:h.name,person:h.person,machine:h.machine}}if(!i?.person)throw new Ce("Reason Network on this computer didn't join the team. Run reason network again.");return{state:"entered",teamId:i.team_id??"",teamName:i.team_name||i.name||"",person:i.person??n,machine:i.machine??""}}async setupAgents(){this.close();let e=p(this.engine,["setup",...M(this.env)?["--no-service"]:[]],{encoding:"utf8",env:await C(this.env),timeout:60000});if(e.status!==0)throw new Ce(`Couldn't connect this computer's agents to the network${X(e)}.`);return[...e.stdout.matchAll(/^ {2}([^:\n]+): (?!skipped)/gm)].map((n)=>n[1]).filter((n)=>n!=="service")}async setup(e,n={}){return this.passthrough(["setup",...e],n,await C(this.env))}passthrough(e,n={},t=this.env){this.close();let r=p(this.engine,e,{stdio:["inherit","pipe",n.person?"inherit":"pipe"],encoding:"utf8",env:t});if(!n.quiet||r.status!==0)process.stdout.write(Fe(b(r.stdout??""))),process.stderr.write(Fe(b(r.stderr??"")));return r.status??1}}function X(e){let n=b(((e.stderr||e.stdout)??"").trim().split(`
|
|
9
|
+
`).pop()??"");return n?` (${n})`:""}function b(e){return e.replace(/not in a team yet:[^\n]*/g,"this computer isn't on a network yet: run `reason network`").replace(/`tincan (\w+)/g,"`reason network $1").replace(/\btincan (who|send|inbox|invite|join|team|link|setup|doctor|remove|leave|listen)\b/g,"reason network $1").replace(/(?<![\w./-])tincan(?![\w./-])/gi,"Reason Network")}
|
|
10
|
+
export{Fe,Ce,al,cl,qr,Ji,Ot};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{te}from"./vm-hands-entry-lite-9g52kxyj.js";var ic=32;var oc="__ARA_PI_TOOL_CONFINED_SCRIPT_5f0c9e2a__",sc=262144;var F=2,bi=33554432,vi=200000,Mo=4000000,_r=240000;var Bo=2000;var Si=16384,zt=32768,gt=128,Fo=64,qt=2097152,pn=1,He=16384,Wt=32768,jo=8388608,_t=1000,hn=2500,Ei=2000,fn=hn+Ei,R=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/,h=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,ki={text_only:4430,invalid_json:4431,invalid_cancel_request:4432,invalid_sdk_response:4433,claim_required:4434,invalid_claim:4435,executor_mismatch:4436,stale_generation:4437,fence_conflict:4438,frame_too_large:4439,result_too_large:4440,progress_too_large:4441,terminal_cleanup_started:4442,job_journal_unavailable:4443},V=new Map(Object.entries(ki).map(([t,n])=>[n,t]));var N=["cancelled","command_failed","duplicate_request_id","duplicate_result_evicted","invalid_repl_response","invalid_request","process_group_cleanup_unconfirmed","repl_failed","result_too_large","repl_response_too_large","repl_transport_failed","request_ledger_full","request_journal_unavailable","request_outcome_uncertain","maintenance_held","request_not_found","resume_digest_mismatch","spawn_failed","stale_generation","timeout"],I=new Set(N),Ho=16384,y=["maintenance_held","invalid_job_request","jobs_disabled","job_not_found","job_conflict","job_capacity","job_journal_unavailable","job_not_running","job_lease_expired","job_input_sequence","job_input_backpressure","stale_generation","pty_unsupported","job_mode_mismatch"];class r extends Error{code;constructor(t){super(t);this.name="HandsProtocolError",this.code=t}}function m(t){return new TextEncoder().encode(t).byteLength}function a(t){return typeof t==="object"&&t!==null&&!Array.isArray(t)}function i(t,n){let e=new Set(n);return Object.keys(t).every((s)=>e.has(s))}function rt(t){return typeof t==="string"&&R.test(t)}function Ee(t){return Number.isSafeInteger(t)&&Number(t)>=1}function ce(t){return typeof t==="string"&&h.test(t)}function nt(t){return typeof t==="string"&&t.startsWith("pty-")&&ce(t.slice(4))}function p(t){return[t.cols,t.rows].every((n)=>Number.isSafeInteger(n)&&Number(n)>=1&&Number(n)<=_t)}function _(t){if(typeof t!=="string"||t.length>Math.ceil(He/3)*4||t.length%4!==0||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return-1;let n=t.endsWith("==")?2:t.endsWith("=")?1:0;if(n&&"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(t[t.length-n-1])&(n===2?15:3))return-1;let s=t.length/4*3-n;return s<=He?s:-1}function l(t){if(m(t)>bi)throw new r("frame_too_large");try{return JSON.parse(t)}catch{throw new r("invalid_json")}}function xi(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","jobId","action","input"])||n.type!=="job"||n.version!==F||!Ee(n.generation)||!rt(n.id)||!rt(n.jobId)||!a(n.input))throw new r("invalid_job_request");let e=n.input,s=Number.isSafeInteger(e.leaseExpiresAtMs)&&Number(e.leaseExpiresAtMs)>0,d=Number.isSafeInteger(e.sequence)&&Number(e.sequence)>=1;if(!(n.action==="start"?e.mode==="pty"?i(e,["mode","cols","rows","leaseExpiresAtMs"])&&nt(n.jobId)&&p(e)&&s:i(e,["script","leaseExpiresAtMs"])&&typeof e.script==="string"&&e.script.length<=vi&&s:n.action==="inspect"?i(e,["after"])&&Number.isSafeInteger(e.after)&&Number(e.after)>=0:n.action==="input"?"dataBase64"in e?i(e,["sequence","dataBase64"])&&nt(n.jobId)&&d&&_(e.dataBase64)>0:i(e,["sequence","data","eof"])&&d&&typeof e.data==="string"&&e.data.length<=Si&&typeof e.eof==="boolean":n.action==="resize"?i(e,["sequence","cols","rows"])&&nt(n.jobId)&&d&&p(e):n.action==="renew"?i(e,["leaseExpiresAtMs"])&&s:n.action==="cancel"&&i(e,[])))throw new r("invalid_job_request");return n}function Ci(t){let n=l(t);if(!a(n)||!i(n,["type","version","generation","id","ok","job","error"])||n.type!=="job_result"||n.version!==F||!Ee(n.generation)||!rt(n.id))throw new r("invalid_job_result");if(n.ok===!1&&n.job===void 0&&typeof n.error==="string"&&y.some((o)=>o===n.error))return n;let e=n.job;if(n.ok!==!0||n.error!==void 0||!a(e)||!i(e,["jobId","state","startedAtMs","finishedAtMs","leaseExpiresAtMs","exitCode","inputSequence","output","firstCursor","nextCursor","truncated","process","environmentRevision","environmentSnapshotId","pty"])||!rt(e.jobId)||!["starting","running","exited","cancelled","expired","uncertain"].includes(String(e.state))||!Number.isSafeInteger(e.startedAtMs)||Number(e.startedAtMs)<1||!Number.isSafeInteger(e.leaseExpiresAtMs)||Number(e.leaseExpiresAtMs)<1||e.finishedAtMs!==null&&(!Number.isSafeInteger(e.finishedAtMs)||Number(e.finishedAtMs)<Number(e.startedAtMs))||e.exitCode!==null&&(!Number.isSafeInteger(e.exitCode)||Number(e.exitCode)<0||Number(e.exitCode)>255)||!Number.isSafeInteger(e.inputSequence)||Number(e.inputSequence)<0||!Number.isSafeInteger(e.firstCursor)||Number(e.firstCursor)<1||!Number.isSafeInteger(e.nextCursor)||Number(e.nextCursor)<Number(e.firstCursor)-1||typeof e.truncated!=="boolean"||!Array.isArray(e.output)||e.output.length>gt)throw new r("invalid_job_result");if(e.environmentRevision===void 0!==(e.environmentSnapshotId===void 0)||e.environmentRevision!==void 0&&(!Number.isSafeInteger(e.environmentRevision)||Number(e.environmentRevision)<1||!ce(e.environmentSnapshotId)))throw new r("invalid_job_result");let s=Number(e.firstCursor)-1,d=0;for(let o of e.output){if(!a(o)||!i(o,["cursor","stream","text"])||!Number.isSafeInteger(o.cursor)||Number(o.cursor)<=s||Number(o.cursor)>Number(e.nextCursor)||!["stdout","stderr"].includes(String(o.stream))||typeof o.text!=="string")throw new r("invalid_job_result");d+=o.text.length,s=Number(o.cursor)}if(d>zt)throw new r("invalid_job_result");let c=e.state==="starting"||e.state==="running";if(c&&(e.finishedAtMs!==null||e.exitCode!==null)||!c&&e.finishedAtMs===null||e.state==="uncertain"&&e.exitCode!==null||e.state==="exited"&&e.exitCode===null||e.state==="cancelled"&&e.exitCode!==130||e.state==="expired"&&e.exitCode!==124)throw new r("invalid_job_result");if(e.process!==void 0){let o=e.process;if(!a(o)||!i(o,["pid","processGroupId","executorLaunchId"])||!Number.isSafeInteger(o.pid)||Number(o.pid)<1||o.processGroupId!==o.pid||!ce(o.executorLaunchId)||!["starting","running"].includes(String(e.state)))throw new r("invalid_job_result")}if(e.pty!==void 0){let o=e.pty;if(!a(o)||!i(o,["version","cols","rows","output","cleanup"])||o.version!==pn||!nt(e.jobId)||!p(o)||e.output.length!==0||!Array.isArray(o.output)||o.output.length>gt||(c?o.cleanup!=="pending":e.state==="uncertain"?o.cleanup!=="unconfirmed":o.cleanup!=="confirmed")||e.state==="running"&&(e.process===void 0||e.environmentRevision===void 0))throw new r("invalid_job_result");let g=Number(e.firstCursor)-1,b=0;for(let u of o.output){if(!a(u)||!i(u,["cursor","dataBase64"])||!Number.isSafeInteger(u.cursor)||Number(u.cursor)<=g||Number(u.cursor)>Number(e.nextCursor))throw new r("invalid_job_result");let f=_(u.dataBase64);if(f<=0||(b+=f)>Wt)throw new r("invalid_job_result");g=Number(u.cursor)}}return n}function Uo(t){if(m(t)>qt)throw new r("frame_too_large");let n=l(t);if(!a(n)||!i(n,["version","sessionId","operationId","runId","deviceId","rootId","workspace","binding","targetRevision","rootGrantRevision","generation","fenceId","executorLaunchId","job"])||n.version!==pn||![n.sessionId,n.operationId,n.runId].every(rt)||![n.deviceId,n.rootId,n.fenceId,n.executorLaunchId].every(ce)||!Ee(n.generation)||!Number.isSafeInteger(n.rootGrantRevision)||Number(n.rootGrantRevision)<1||!["workspace_source","mcp_control"].includes(String(n.binding))||!Number.isSafeInteger(n.targetRevision)||Number(n.targetRevision)<0||n.binding==="workspace_source"&&n.targetRevision!==0||!a(n.workspace))throw new r("invalid_pty_receipt");if(!te(n.workspace))throw new r("invalid_pty_receipt");let e=Ci(JSON.stringify({type:"job_result",version:F,generation:n.generation,id:n.operationId,ok:!0,job:n.job}));if(!e.ok||!e.job.pty||e.job.pty.output.length!==0||e.job.process&&e.job.process.executorLaunchId!==n.executorLaunchId)throw new r("invalid_pty_receipt");return n}export{ic,oc,sc,F,bi,vi,Mo,_r,Bo,Si,zt,gt,Fo,qt,pn,He,Wt,jo,_t,hn,Ei,fn,ki,Ho,rt,Ee,ce,nt,xi,Ci,Uo};
|