@reason-machines/cli-linux-x64 0.2.561 → 0.2.565
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 +2 -2
- package/bin/vm-hands/agent-network-mnv1fm1c.js +2 -0
- package/bin/vm-hands/api-credentials-082cnpn9.js +2 -0
- package/bin/vm-hands/api-sq672f51.js +2 -0
- package/bin/vm-hands/{ask-relay-xx0rzpch.js → ask-relay-v5btnjvb.js} +2 -2
- package/bin/vm-hands/connect-cli-rxb3qtra.js +2 -0
- package/bin/vm-hands/credentials-sk4sag42.js +2 -0
- package/bin/vm-hands/custom-endpoint-device-3jscber1.js +2 -0
- package/bin/vm-hands/desktop-account-xma0330a.js +2 -0
- package/bin/vm-hands/desktop-components-099xyxmz.js +2 -0
- package/bin/vm-hands/desktop-delegate-tch2qzx0.js +2 -0
- package/bin/vm-hands/device-workspace-4bj43nxq.js +2 -0
- package/bin/vm-hands/{fsevents-vxv56sp5.js → fsevents-ezcg3e40.js} +1 -1
- package/bin/vm-hands/hands-worker-source-8pe7yv0m.js +2 -0
- package/bin/vm-hands/{index-03p9c17x.js → index-w92ys6ra.js} +16 -16
- package/bin/vm-hands/install-receipt-68xxg7hn.js +2 -0
- package/bin/vm-hands/local-automation-7pjd5nc1.js +2 -0
- package/bin/vm-hands/local-capabilities-ha0ey4zh.js +2 -0
- package/bin/vm-hands/local-desktop-users-jpf0resr.js +2 -0
- package/bin/vm-hands/local-display-mac-h5yz0ydd.js +2 -0
- package/bin/vm-hands/local-display-session-0mkswxgk.js +2 -0
- package/bin/vm-hands/local-display-video-c3fk87c5.js +2 -0
- package/bin/vm-hands/local-managed-process-ahr2jync.js +2 -0
- package/bin/vm-hands/local-pty-session-tqn2xmph.js +2 -0
- package/bin/vm-hands/managed-runtime-shzb3tr3.js +2 -0
- package/bin/vm-hands/network-auto-update-3m94436w.js +3 -0
- package/bin/vm-hands/network-contract-nkwcf4r9.js +2 -0
- package/bin/vm-hands/{network-sign-in-61gmpmaa.js → network-sign-in-xm79s170.js} +2 -2
- package/bin/vm-hands/package-9w0mmxb5.js +2 -0
- package/bin/vm-hands/permissions-scffy1px.js +2 -0
- package/bin/vm-hands/reason-hands-protocol-pck5har9.js +2 -0
- package/bin/vm-hands/serve-service-grp91ybk.js +2 -0
- package/bin/vm-hands/{status-khqk4cjw.js → status-89999mdn.js} +7 -7
- package/bin/vm-hands/version-wyshazh7.js +2 -0
- package/bin/vm-hands/{vm-hands-entry-lite-zawytz09.js → vm-hands-entry-lite-12ck5swp.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-j10cw3d9.js → vm-hands-entry-lite-13nx02p7.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-vdv4nm5f.js → vm-hands-entry-lite-1b21avcs.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-1eyg750p.js +48 -0
- package/bin/vm-hands/{vm-hands-entry-lite-2dak7e1h.js → vm-hands-entry-lite-1xhpn3hw.js} +3 -5
- package/bin/vm-hands/{vm-hands-entry-lite-ms99mzp0.js → vm-hands-entry-lite-284z7ct8.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-a7bf7xr7.js → vm-hands-entry-lite-2qfmabqn.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-q9s1e2y1.js → vm-hands-entry-lite-33at6g06.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-jgk5z8zc.js → vm-hands-entry-lite-34b4tws6.js} +6 -6
- package/bin/vm-hands/{vm-hands-entry-lite-e3fn8ys2.js → vm-hands-entry-lite-3gc2bn5a.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hxfxs7r9.js → vm-hands-entry-lite-3q2ng4e9.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-432khjd5.js +150 -0
- package/bin/vm-hands/vm-hands-entry-lite-6vnjgy77.js +81 -0
- package/bin/vm-hands/{vm-hands-entry-lite-ht6hzkgj.js → vm-hands-entry-lite-7r27208j.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-hs6sdn60.js → vm-hands-entry-lite-88dxn9b5.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-997y1m1r.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-zh6ncdjn.js → vm-hands-entry-lite-a3gq377t.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-m1we91g4.js → vm-hands-entry-lite-af45ma9p.js} +10 -10
- package/bin/vm-hands/{vm-hands-entry-lite-0wb1n769.js → vm-hands-entry-lite-b1vanmtv.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-5y4phfv1.js → vm-hands-entry-lite-bsk184m7.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-q9djb28r.js → vm-hands-entry-lite-cc8hwgxc.js} +3 -3
- package/bin/vm-hands/vm-hands-entry-lite-chq0qx9f.js +12 -0
- package/bin/vm-hands/{vm-hands-entry-lite-84mc1f7h.js → vm-hands-entry-lite-cmmb9k3g.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-gxpw14jv.js → vm-hands-entry-lite-dy204qh4.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-ptycjmkc.js → vm-hands-entry-lite-fccn6s4j.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-qf990rxw.js → vm-hands-entry-lite-fn2805g8.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-71ebge0c.js → vm-hands-entry-lite-fxptf351.js} +5 -5
- package/bin/vm-hands/{vm-hands-entry-lite-vkhacd00.js → vm-hands-entry-lite-gcqqnnze.js} +19 -19
- package/bin/vm-hands/{vm-hands-entry-lite-57ajjwmh.js → vm-hands-entry-lite-gxf2r5en.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-hjjbjpd7.js → vm-hands-entry-lite-jj7873n8.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-9g52kxyj.js → vm-hands-entry-lite-kbnxk71q.js} +2 -2
- package/bin/vm-hands/vm-hands-entry-lite-ncyrz48z.js +4 -0
- package/bin/vm-hands/{vm-hands-entry-lite-y3nz20wb.js → vm-hands-entry-lite-ngn4tafr.js} +105 -105
- package/bin/vm-hands/{vm-hands-entry-lite-52qz0n30.js → vm-hands-entry-lite-ngry8nkq.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-8xv6c0rm.js → vm-hands-entry-lite-pg7nnyc6.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-h7nk2848.js → vm-hands-entry-lite-pt19vacn.js} +42 -42
- package/bin/vm-hands/{vm-hands-entry-lite-tcmye5ny.js → vm-hands-entry-lite-q62g6sx0.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-v4hr9x9h.js → vm-hands-entry-lite-qjrgvdbj.js} +34 -34
- package/bin/vm-hands/{vm-hands-entry-lite-bj3w2ven.js → vm-hands-entry-lite-rqfhfp09.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-krpqqx12.js → vm-hands-entry-lite-rxydyqke.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-weqam12f.js → vm-hands-entry-lite-s93f3pbv.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-z0ht62s4.js → vm-hands-entry-lite-sh4mqy93.js} +3 -3
- package/bin/vm-hands/{vm-hands-entry-lite-xvccy3z4.js → vm-hands-entry-lite-sz7z1qby.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-wcgm41jq.js → vm-hands-entry-lite-t43bz0ey.js} +7 -7
- package/bin/vm-hands/{vm-hands-entry-lite-6jxshhps.js → vm-hands-entry-lite-t86kt9jz.js} +6 -6
- package/bin/vm-hands/{vm-hands-entry-lite-7pfhwxn5.js → vm-hands-entry-lite-tnj3483k.js} +1 -1
- package/bin/vm-hands/vm-hands-entry-lite-wnqqjsew.js +3 -0
- package/bin/vm-hands/{vm-hands-entry-lite-pxtycfdv.js → vm-hands-entry-lite-xfak34av.js} +4 -4
- package/bin/vm-hands/{vm-hands-entry-lite-sy7dcccg.js → vm-hands-entry-lite-y0jtj8zz.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-yvws5zpx.js → vm-hands-entry-lite-yg4dk99m.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-2rgf8866.js → vm-hands-entry-lite-z65xva21.js} +2 -2
- package/bin/vm-hands/{vm-hands-entry-lite-jpvmkce5.js → vm-hands-entry-lite-zp7chzcc.js} +1 -1
- package/bin/vm-hands/{vm-hands-entry-lite-k5ytpgzz.js → vm-hands-entry-lite-zpvr7wc6.js} +19 -19
- package/bin/vm-hands/vm-hands-entry-lite.js +2 -2
- package/bin/vm-hands/vm-hands-executor-kyb5t371.js +12 -0
- package/bin/vm-hands/vm-hands-op-runner-gkt79hcp.js +2 -0
- package/bin/vm-hands/{vm-hands-runtime-1qxf96z7.js → vm-hands-runtime-tdr6j55n.js} +3 -3
- package/bin/vm-hands/worker-preview-readiness-h96yr4wf.js +2 -0
- package/bin/vm-hands/worker-sandbox-6kkhvryn.js +2 -0
- package/package.json +1 -1
- package/bin/vm-hands/agent-network-kk36zca7.js +0 -2
- package/bin/vm-hands/api-credentials-mtfdk175.js +0 -2
- package/bin/vm-hands/api-w6w7vfp3.js +0 -2
- package/bin/vm-hands/connect-cli-dmwph620.js +0 -2
- package/bin/vm-hands/credentials-s7ps7y6s.js +0 -2
- package/bin/vm-hands/custom-endpoint-device-3xnrp33e.js +0 -2
- package/bin/vm-hands/desktop-account-eg8thn79.js +0 -2
- package/bin/vm-hands/device-workspace-h5rsecq8.js +0 -2
- package/bin/vm-hands/hands-worker-source-vk664w8p.js +0 -2
- package/bin/vm-hands/install-receipt-j04hdw1k.js +0 -2
- package/bin/vm-hands/local-automation-vvt9d9xb.js +0 -2
- package/bin/vm-hands/local-capabilities-pwv76ns5.js +0 -2
- package/bin/vm-hands/local-desktop-users-sq4trh07.js +0 -2
- package/bin/vm-hands/local-display-mac-yxcxvg2z.js +0 -2
- package/bin/vm-hands/local-display-session-axh9mfdk.js +0 -2
- package/bin/vm-hands/local-display-video-pxhztqk7.js +0 -2
- package/bin/vm-hands/local-managed-process-4mgqn7tg.js +0 -2
- package/bin/vm-hands/local-pty-session-edd8ttf9.js +0 -2
- package/bin/vm-hands/managed-runtime-pcagtyfz.js +0 -2
- package/bin/vm-hands/network-auto-update-wkzb91qz.js +0 -3
- package/bin/vm-hands/network-contract-8mxtma3w.js +0 -2
- package/bin/vm-hands/package-vwvzjtn0.js +0 -2
- package/bin/vm-hands/permissions-348prrcx.js +0 -2
- package/bin/vm-hands/reason-hands-protocol-1nkpw1v3.js +0 -2
- package/bin/vm-hands/serve-service-3dkyznay.js +0 -2
- package/bin/vm-hands/version-c1hen0wn.js +0 -2
- package/bin/vm-hands/vm-hands-entry-lite-9yfmkd1f.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-ab1pq3xg.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-hn9pq7zj.js +0 -127
- package/bin/vm-hands/vm-hands-entry-lite-nn6zcvmp.js +0 -3
- package/bin/vm-hands/vm-hands-entry-lite-z213y4pj.js +0 -150
- package/bin/vm-hands/vm-hands-executor-csdtg7kj.js +0 -12
- package/bin/vm-hands/vm-hands-op-runner-z7tsd84c.js +0 -2
- package/bin/vm-hands/worker-preview-readiness-06tygyjs.js +0 -2
- package/bin/vm-hands/worker-sandbox-e1cpkzfz.js +0 -2
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{D}from"./vm-hands-entry-lite-13nx02p7.js";import{_s}from"./vm-hands-entry-lite-t86kt9jz.js";import{rs}from"./vm-hands-entry-lite-cc8hwgxc.js";import{s}from"./vm-hands-entry-lite-12ck5swp.js";import{r}from"./vm-hands-entry-lite-qy9xg6em.js";import{createHash as pe}from"crypto";import{once as Te}from"events";import{createWriteStream as Ne,existsSync as Ae,mkdirSync as Me,mkdtempSync as Pt,readFileSync as L,readdirSync as Dt,renameSync as Ue,realpathSync as He,rmSync as Le,statSync as z,writeFileSync as je}from"fs";import{delimiter as Nt,dirname as J,join as a}from"path";import{finished as Fe}from"stream/promises";var Xt="omljlfpmafedpplnpkkahegadhkimdje",yc="https://chromewebstore.google.com/detail/reason/omljlfpmafedpplnpkkahegadhkimdje";var x={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"}},S={version:"155.0.8059.84",macArm64Sha256:"13b9e98ce56f5ce18e100a009f455c9285f399e7c9dc8a76fdf2f3a9755bb5f2",linux64Sha256:"cf0f049892dea22e6a6db26d47ed0d7776b7158edcbec4634086633df8bafcbc",win64Sha256:"507f2a031441d10c62b5e3d4e863f09ac1198a571c1419976cbd8387f639afde"};var R={ocu:{url:`https://registry.npmjs.org/open-computer-use/-/open-computer-use-${x.ocu.version}.tgz`,sha256:"7c16a87c8cd357787b02c0ebd040dd5f93880c1fb51c1901caa2e0c05d063130",size_bytes:5844280},obu:{url:`https://registry.npmjs.org/open-browser-use/-/open-browser-use-${x.obu.version}.tgz`,sha256:"9386d8ce0a147b3f55e1807b68edf736836378807541c457c9b5f6ca2cabaa4e",size_bytes:21372018},extension:{url:`https://github.com/iFurySt/open-browser-use/releases/download/v${x.obu.version}/open-browser-use-chrome-extension-${x.obu.version}.zip`,sha256:"c9c07bec1175e12ea6985b0e7784a5ef01fd03f014b958224a1e17dcd838a241",size_bytes:31070}},le="pnbmoicbkopffjjgfgfglopechaiemkp";import{spawn as B}from"child_process";import{createRequire as Se}from"module";import{join as ke}from"path";var Ee=30000,Ce=1048576;function G(){return process.env.SystemRoot??"C:\\Windows"}function Ie(){return ke(G(),"System32","WindowsPowerShell","v1.0","powershell.exe")}var Oe=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 W(e){let t=Oe.replace("__MODE__",e).replace("__PARENT__",String(process.pid)).replace("__MAX_TEXT_BYTES__",String(D));return[Ie(),["-NoLogo","-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(t,"utf16le").toString("base64")]]}var Re=["USERPROFILE","LOCALAPPDATA","APPDATA","TEMP","TMP","PSModuleAnalysisCachePath"];function K(){let e=Re.flatMap((t)=>process.env[t]?[[t,process.env[t]]]:[]);return{...Object.fromEntries(e),SystemRoot:G(),windir:G()}}function ie(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!=="object")return null;let n=t,o=(i,l)=>typeof i==="number"&&Number.isSafeInteger(i)&&i>=l;return o(n.session,0)&&o(n.width,1)&&o(n.height,1)?{session:n.session,width:n.width,height:n.height}:null}function wc(){return new Promise((e)=>{let t=B(...W("probe"),{env:K(),stdio:["ignore","pipe","ignore"],windowsHide:!0}),n="",o=setTimeout(()=>{t.kill("SIGKILL"),e(null)},Ee);t.stdout.setEncoding("utf8").on("data",(i)=>{n+=i}),t.once("error",()=>{clearTimeout(o),e(null)}),t.once("close",()=>{clearTimeout(o),e(ie(n.split(/\r?\n/)[0]??""))})})}var P;function ae(){if(P!==void 0)return P;if(process.platform!=="win32")return P=!1;try{let e=Se(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 P=t.ProcessIdToSessionId(t.GetCurrentProcessId(),n)!==0&&n[0]>0}catch{return P=!1}}var ee=[{bit:1,down:2,up:4},{bit:2,down:32,up:64},{bit:4,down:8,up:16}],te=2048,ne=4096,$e=[[8,te,120],[16,te,-120],[32,ne,-120],[64,ne,120]],oe=1,F=2,Pe=4,De=new Set([65505,65506]),se=new Set([65507,65508,65511,65512,65513,65514,65027,65515,65516]),re=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 ce{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 ee){let l=(this.mask&i.bit)!==0,c=(n&i.bit)!==0;if(l!==c)o.push(`b ${c?i.down:i.up} 0`)}for(let[i,l,c]of $e)if(!(this.mask&i)&&n&i)o.push(`b ${l} ${c}`);return this.mask=n,o}key(e,t){let n=e?0:F;if(De.has(t)||se.has(t))if(e)this.held.add(t);else this.held.delete(t);let o=re.get(t);if(o)return[`k ${o[0]} 0 ${n|(o[1]?oe:0)}`];let i=t<256?t:(t&4278190080)===16777216?t&16777215:0,l=String.fromCharCode(i),c=[...this.held].some((f)=>se.has(f)),d=/^[A-Za-z0-9]$/.test(l)?l.toUpperCase().charCodeAt(0):0;if(d&&(e?c:this.pressed.has(d))){if(e)this.pressed.add(d);else this.pressed.delete(d);return[`k ${d} 0 ${n}`]}if(i<33||i>=127&&i<160||i>65535||i>=55296&&i<57344)return[];return[`k 0 ${i} ${n|Pe}`]}release(){let e=ee.filter((t)=>this.mask&t.bit).map((t)=>`b ${t.up} 0`);for(let t of this.pressed)e.push(`k ${t} 0 ${F}`);for(let t of this.held){let[n,o]=re.get(t);e.push(`k ${n} 0 ${F|(o?oe:0)}`)}return this.mask=0,this.pressed.clear(),this.held.clear(),e}}function bc(e){let t=B(...W("input"),{env:K(),stdio:["pipe","pipe","ignore"],windowsHide:!0}),n=new ce,o="",i=!1,l=null,c=()=>{if(l?.kill("SIGKILL"),t.exitCode!==null||t.signalCode!==null)return;t.stdin.end(n.release().map((u)=>`${u}
|
|
68
|
+
`).join("")),setTimeout(()=>t.kill("SIGKILL"),2000).unref()},d=(u)=>{if(i)return;i=!0,c(),e.end(u)},f=(u)=>d({error:new r("display_unavailable",u)}),h=(u)=>{if(i||u.length===0)return;if(t.stdin.write(u.map((m)=>`${m}
|
|
69
|
+
`).join("")),t.stdin.writableLength>Ce)d({reason:"input_backpressure"})},y=()=>{l=B(...W("clipboard"),{env:K(),stdio:["ignore","pipe","ignore"],windowsHide:!0});let u="";l.stdout?.on("data",(m)=>{if(i)return;u+=m.toString("ascii");for(let g=u.indexOf(`
|
|
70
|
+
`);g>=0;g=u.indexOf(`
|
|
71
|
+
`)){let T=u.slice(0,g).replace(/\r$/,"");if(u=u.slice(g+1),!T.startsWith("c "))continue;let v=T.slice(2);if(v.length>Math.ceil(D/3)*4||!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(v)){d({reason:"display_protocol"});return}let p=Buffer.from(v,"base64");if(p.byteLength<=D)e.clipboard(p.toString("utf8"));if(i)return}if(u.length>Math.ceil(D/3)*4+4)d({reason:"display_protocol"})}),l.once("error",()=>f("Reason could not watch this computer's desktop clipboard.")),l.once("exit",()=>{if(!i)f("Reason could not watch this computer's desktop clipboard.")})};return t.stdout.on("data",(u)=>{if(i||o===null)return;o+=u.toString("utf8");let m=o.indexOf(`
|
|
72
|
+
`);if(m<0){if(o.length>4096)d({reason:"display_protocol"});return}let g=ie(o.slice(0,m).trim());if(o=null,!g)d({reason:"display_protocol"});else if(g.session===0)f("This Windows worker runs as a service, which has no desktop: run it in the signed-in desktop session.");else y(),e.ready({width:g.width,height:g.height})}),t.stdin.on("error",()=>{return}),t.once("error",()=>f("Reason could not start this computer's desktop input.")),t.once("exit",()=>{if(o!==null)f("Reason could not start this computer's desktop input.");else d({reason:"display_closed"})}),{pointer:(u,m,g)=>h(n.pointer(u,m,g)),key:(u,m)=>h(n.key(u,m)),clipboard:(u)=>h([`c ${Buffer.from(u,"utf8").toString("base64")}`]),close(){i=!0,c()}}}var Be=["none","standard","all"],H="22.23.4",Ge={"linux-x64":"b8492284c76a54baf58d61668dd0e41ee0fc98adabf9503d30f05d08f55b4406","linux-arm64":"f7a1e486dbc8b286847815b477d4fb5e9fb963ed4489c3e1588853d685f589f9","darwin-arm64":"c9e1dbc748b33ed2d14f42445191ecaf14c56259c7a9a26d0042c49ec2b66428","win32-x64":"cbc74b5e0982c9dbb41525fd8fb5dcd32fbee237863f7829072f4639a1ce5f20","win32-arm64":"a8b8cd79cbbb3062435f449591d98dd63730bbbf30ce2d7cc3a6376c236cb111"},X={"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"}},fe="chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",me="chrome-win64/chrome.exe",E={version:"9.0.2",url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffmpeg.zip",sha256:"c8ed4c4e6978a03c485edbfe4e0a5dc2380f8a30bba5150531b31b094492d924"},We={version:E.version,url:"https://ffmpeg.martin-riedl.de/download/macos/arm64/1789931890_9.0.2/ffprobe.zip",sha256:"fcbe839537485eaee7a7a8bc5cbc0f90d53617e80943e8a5b2e31cb851197ea6"},V={version:E.version,url:`https://github.com/GyanD/codexffmpeg/releases/download/${E.version}/ffmpeg-${E.version}-essentials_build.zip`,sha256:"60f467265b1e312373dbcd92200c2618a74850f98d3d078e94296bb3fa2047ba"},ue=`ffmpeg-${V.version}-essentials_build/bin`,k="com.ifuryst.open_browser_use.extension",ge="com.reasonmachines.browser_use.extension",Sr="/tmp/reason-browser-use",q=["tint2","picom","xterm","pcmanfm"],he=["fonts-droid-fallback"],be=["pulseaudio"],xe=["tigervnc-standalone-server"],Ke=["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",...he,"galculator","chromium","ffmpeg","tmux",...be,...xe,...q],Xe=new Set([...q,...he,...be,...xe]),de=Ke.filter((e)=>e!=="chromium"&&!Xe.has(e)),Ve=["Xvfb","openbox","x11vnc","xdotool","dbus-launch","python3","ffmpeg","tmux"],U="/usr/bin/chromium",ze=["/usr/local/bin","/usr/bin","/bin","/opt/homebrew/bin"];function we(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 C(e){return e==="win32-x64"||e==="win32-arm64"}function Y(e){return C(e)?`node-v${H}-${e.replace("win32","win")}`:`node-v${H}-${e}`}function j(e){return{node:{version:H,url:`https://nodejs.org/dist/v${H}/${Y(e)}${C(e)?".zip":".tar.gz"}`,sha256:Ge[e]},open_computer_use:{version:x.ocu.version,url:R.ocu.url,sha256:R.ocu.sha256},open_browser_use:{version:x.obu.version,url:R.obu.url,sha256:R.obu.sha256},...e==="darwin-arm64"?{chrome_for_testing:{version:S.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${S.version}/mac-arm64/chrome-mac-arm64.zip`,sha256:S.macArm64Sha256}}:C(e)?{chrome_for_testing:{version:S.version,url:`https://storage.googleapis.com/chrome-for-testing-public/${S.version}/win64/chrome-win64.zip`,sha256:S.win64Sha256}}:{}}}function Je(e){let t={extension:le};for(let[n,o]of Object.entries(j(e)))t[n]=`${o.version}@${o.sha256}`;return t}function ye(e){return a(e,".local","share","reason","desktop")}function Er(e,t=rs()){let n=ye(t),o=(u)=>a(n,u,j(e)[u]?.version??""),i=o("open_computer_use"),l=o("open_browser_use"),c=e==="darwin-arm64",d=C(e),f=a(t,"Library","Application Support"),h=a(process.platform==="win32"&&process.env.LOCALAPPDATA?process.env.LOCALAPPDATA:a(t,"AppData","Local"),"OpenBrowserUse"),y=c?a(f,"Google","Chrome","NativeMessagingHosts",`${k}.json`):d?a(h,"NativeMessagingHosts",`${k}.json`):a(t,".config","google-chrome","NativeMessagingHosts",`${k}.json`);return{root:n,automation:a(J(n),"automation"),receipt:a(n,"receipt.json"),minimal:Q(t),node:d?a(o("node"),Y(e),"node.exe"):a(o("node"),"bin","node"),ocuDir:i,ocu:a(i,X[e].ocu),ocuApp:c?a(i,"dist","Open Computer Use.app"):null,obuDir:l,obu:a(l,"cli","open-browser-use.js"),nativeHost:a(l,X[e].obu),extensionDir:c?a(f,"OpenBrowserUse","chrome-extension","release"):d?a(h,"chrome-extension","release"):a(t,".local","share","open-browser-use","chrome-extension","release"),setupNativeHostManifest:y,nativeHostManifests:c?[y,a(f,"Google","ChromeForTesting","NativeMessagingHosts",`${k}.json`)]:d?[y]:[a(t,".config","chromium","NativeMessagingHosts",`${k}.json`),a(t,".config","google-chrome-for-testing","NativeMessagingHosts",`${k}.json`)],browser:c?a(o("chrome_for_testing"),fe):d?a(o("chrome_for_testing"),me):U,userChromeHost:c?a(n,"user-chrome","reason-browser-use"):null,userChromeRegistration:c?a(f,"Google","Chrome","NativeMessagingHosts",`${ge}.json`):null,ffmpegDir:a(n,"ffmpeg"),ffmpeg:c?a(n,"ffmpeg",E.version,"ffmpeg"):d?a(n,"ffmpeg",V.version,ue,"ffmpeg.exe"):null,ffprobe:c?a(n,"ffprobe",We.version,"ffprobe"):d?a(n,"ffmpeg",V.version,ue,"ffprobe.exe"):null}}function _e(e){try{let t=JSON.parse(L(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")||!Be.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 qe(e,t,n=384){Me(J(e),{recursive:!0,mode:448});let o=`${e}.pending.${process.pid}`;je(o,t,{mode:n}),Ue(o,e)}function w(e){try{return z(e).isFile()}catch{return!1}}function ve(e){try{let t=z(e);return t.isFile()&&(t.mode&73)!==0}catch{return!1}}function Ye(e){try{return L(e,"utf8")}catch{return null}}function _(e){for(let t of ze){let n=a(t,e);try{let o=z(n);if(o.isFile()&&(o.mode&73)!==0)return n}catch{}}return null}function Ze(e){try{let t=JSON.parse(L(a(e,"package.json"),"utf8"));return typeof t==="object"&&t!==null&&typeof t.version==="string"?t.version:null}catch{return null}}function Qe(e,t,n){let o=j(n)[e];if(!o)return!1;let i=C(n);if(e==="node")return w(i?a(t,Y(n),"node.exe"):a(t,"bin","node"));if(e==="chrome_for_testing")return w(a(t,i?me:fe));let l=X[n][e==="open_computer_use"?"ocu":"obu"];return Ze(t)===o.version&&w(a(t,l))&&(e==="open_computer_use"||w(a(t,"cli","open-browser-use.js")))}function et(e){return pe("sha256").update(Buffer.from(e,"base64")).digest("hex").slice(0,32).replace(/./g,(t)=>String.fromCharCode(97+Number.parseInt(t,16)))}function Z(e){try{let t=JSON.parse(L(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function tt(e){let t=Z(a(e.extensionDir,"manifest.json"));return t!==null&&t.version===x.obu.version&&typeof t.key==="string"&&et(t.key)===le}function nt(e,t){let n=e?.allowed_origins;return e!==null&&e.name===k&&Array.isArray(n)&&n.length===1&&n[0]===`chrome-extension://${le}/`&&(t===void 0||e.path===t)}function ot(e){return tt(e)&&w(e.nativeHost)&&e.nativeHostManifests.every((t)=>nt(Z(t),e.nativeHost))}function st(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 ${Sr} ;;
|
|
77
|
+
mcp) shift; exec "$obu" mcp --socket-dir ${Sr} "$@" ;;
|
|
78
|
+
esac
|
|
79
|
+
exec "$obu" "$@"
|
|
80
|
+
`}function rt(e){let t=Z(e),n=t?.allowed_origins;return t!==null&&t.name===ge&&t.type==="stdio"&&Array.isArray(n)&&n.includes(`chrome-extension://${Xt}/`)&&typeof t.path==="string"&&ve(t.path)}function it(e,t){if(!e.userChromeHost||!e.userChromeRegistration)return null;if(!t||Ye(e.userChromeHost)!==st(e.nativeHost)||!ve(e.userChromeHost))return{code:"user_chrome_browser_use_missing"};return rt(e.userChromeRegistration)?{host:e.userChromeHost}:{code:"user_chrome_native_host_unregistered"}}var at={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 A(e={}){let t=e.platform===void 0?we():e.platform;if(!t)return null;let n=Er(t,e.home),o=_e(n.receipt),i=Je(t),l=o!==null&&o.platform===t&&JSON.stringify(Object.entries(o.pins).sort())===JSON.stringify(Object.entries(i).sort()),c=[],d=j(t);for(let p of["node","open_computer_use","open_browser_use","chrome_for_testing"]){let b=d[p];if(!b)continue;let N=Qe(p,a(n.root,p,b.version),t),I=o?.pins[p],M=N&&I===i[p]?"ready":I!==void 0&&I!==i[p]?"outdated":"missing";c.push({name:p,state:M,detail:b.version})}let f=o?.pins.extension===le&&ot(n);c.push({name:"browser_extension",state:f?"ready":"missing",detail:le});let h=_("Xvfb"),y=_("x11vnc"),u=_("openbox");if(C(t))c.push(ae()?{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&&w(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(w(U)?{name:"browser",state:"ready",detail:U}:{name:"browser",state:"missing",detail:`non-snap Chromium at ${U}`});let p=h!==null&&y!==null&&u!==null;c.push({name:"display",state:p?"ready":"missing",detail:"Xvfb + openbox + x11vnc"});let b=Ve.filter((O)=>_(O)===null),N=(o?.missing_system_packages??de).filter((O)=>de.includes(O)),I=b.length===0&&N.length===0;c.push(I?{name:"system_packages",state:"ready"}:{name:"system_packages",state:"missing",detail:[...new Set([...N,...b])].join(" ")});let M=q.filter((O)=>_(O)===null);c.push(M.length===0?{name:"desktop_look",state:"ready"}:{name:"desktop_look",state:"missing",detail:M.join(" ")})}let m=n.ffmpeg&&w(n.ffmpeg)?n.ffmpeg:_("ffmpeg"),g=!m?null:m===n.ffmpeg?n.ffprobe:a(J(He(m)),"ffprobe"),T=l&&c.every((p)=>p.state==="ready"),v=(p)=>l&&c.every((b)=>!at[p].includes(b.name)||b.state==="ready");return{platform:t,root:n.root,automation:n.automation,ready:T,features:{display:v("display"),computer:v("computer"),browser:v("browser")},node:n.node,ocu:n.ocu,obu:n.obu,nativeHost:n.nativeHost,extensionDir:n.extensionDir,browser:n.browser,ffmpeg:m,ffprobe:g&&w(g)?g:null,userChrome:it(n,l&&["node","open_browser_use"].every((p)=>c.find((b)=>b.name===p)?.state==="ready")),pulseaudio:_("pulseaudio"),xvnc:_("Xvnc"),xvfb:h,x11vnc:y,openbox:u,components:c}}function Zo(e){return ct(e)?_s():[]}function ct(e){return e?.platform==="darwin-arm64"&&e.ffmpeg===a(e.root,"ffmpeg",E.version,"ffmpeg")}async function Qo(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 l=pe("sha256"),c=Ne(n,{mode:384});try{let f=i.body.getReader();for(let h=await f.read();!h.done;h=await f.read())if(l.update(h.value),!c.write(h.value))await Te(c,"drain")}finally{c.end(),await Fe(c)}let d=l.digest("hex");if(d!==t)throw Error(`digest mismatch for ${e}: expected ${t}, got ${d}`)}catch(i){throw Le(n,{force:!0}),i}}function Q(e){return a(ye(e),"minimal.json")}function ut(e=s()){return Ae(Q(e))}function es(e={}){qe(Q(e.home??s()),`${JSON.stringify({version:1,minimal_at:(e.now?.()??new Date).toISOString()})}
|
|
81
|
+
`)}function ts(e={}){let t=e.platform===void 0?we():e.platform;if(t===null)return null;let n=e.home??s();if(_e(Er(t,n).receipt)!==null)return"refresh";return ut(n)?null:"install"}export{Xt,yc,le,wc,bc,Sr,Er,A,Zo,Qo,es,ts};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
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{
|
|
2
|
+
import{Pa}from"./vm-hands-entry-lite-cmmb9k3g.js";import{R}from"./vm-hands-entry-lite-z65xva21.js";import{W}from"./vm-hands-entry-lite-33at6g06.js";import{Q,oo,ve,so}from"./vm-hands-entry-lite-2qfmabqn.js";import{Ir}from"./vm-hands-entry-lite-rqfhfp09.js";import{t,o,_,d,n,ll,we,c,i}from"./vm-hands-entry-lite-zpvr7wc6.js";var E=/^(0|[1-9][0-9]{0,5})\.(0|[1-9][0-9]{0,5})$/;function k(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 P}from"crypto";import{createInterface as M}from"readline";var v=["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=v.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 Ca(){let e=P(48).toString("base64url"),s=q("sha256").update(e).digest("base64url");return{verifier:e,challenge:s,state:P(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 oo(l,s.path??Q()),l}var w=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??R(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=w.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 S=(f)=>f!==null&&(p.oauthCode==="invalid_client"?f.clientId!==r.clientId:f.refreshToken!==r.refreshToken),O=Date.now()+N;while(!S(ve(s))&&Date.now()<O)await new Promise((f)=>setTimeout(f,H));if(S(ve(s)))return be({fetchImpl:e.fetchImpl,path:s});return so(s),null}).finally(()=>{if(w.get(u)===h)w.delete(u)}),w.set(u,h),I(h,e.signal)}function Aa(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=ll({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 b(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 no(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 b(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 b(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":Ir,"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(Pa,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 k(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 b(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{Ca,be,Aa,C,no,me};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
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(!
|
|
3
|
-
export{
|
|
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(!Mi(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 Mi(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(!Mi(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?bt:()=>r},e!==void 0)}function wt(n,...r){return De(n),K(n,...r)}function cs(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:bt});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 Sc(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 Ec(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 bt(){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{Mi,De,wt,cs,Sc,Ec,bt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var gn=String.raw`(function(loadFfi, existsSync) {
|
|
3
3
|
const STARTF_USESTDHANDLES = 0x100;
|
|
4
4
|
const CREATE_SUSPENDED = 0x4;
|
|
5
5
|
const CREATE_UNICODE_ENVIRONMENT = 0x400;
|
|
@@ -242,4 +242,4 @@ var dn=String.raw`(function(loadFfi, existsSync) {
|
|
|
242
242
|
}
|
|
243
243
|
return { available, unavailableReason, defaultShell, shellArgs, quoteArg, environmentBlock, spawn };
|
|
244
244
|
})`;
|
|
245
|
-
export{
|
|
245
|
+
export{gn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{R}from"./vm-hands-entry-lite-z65xva21.js";import{w}from"./vm-hands-entry-lite-33at6g06.js";import{ot,as,$i,We}from"./vm-hands-entry-lite-y0jtj8zz.js";import{fs,Ln,jc}from"./vm-hands-entry-lite-t86kt9jz.js";import{B}from"./vm-hands-entry-lite-pg7nnyc6.js";import{spawnSync as v}from"child_process";import{createHash as Se,randomUUID as we}from"crypto";import{chmodSync as $e,existsSync as T,mkdirSync as ye,readdirSync as Fe,readFileSync as p,renameSync as ve,rmSync as u,statSync as be,writeFileSync as Ae}from"fs";import{dirname as xe,isAbsolute as q,join as g}from"path";import{spawnSync as ue}from"child_process";import{readFileSync as me}from"fs";import{userInfo as O}from"os";import{join as fe}from"path";var ge="REASON_SCHEDULED_TASK";function Oi(r){return fe(r,"AppData","Local","Reason","Tasks")}function S(r){if(/[\0-\x1f\x7f"%]/.test(r))throw Error(`A background task cannot use a value with a double quote, percent sign or control character: ${r}`);return`'${r.replace(/['\u2018\u2019\u201a\u201b]/g,"$&$&")}'`}function D(r){if(!/^[A-Za-z0-9._-]+$/.test(r))throw Error(`Invalid Windows Scheduled Task name: ${r}`);return`$env:${ge}=${S(r)};`}function H(r){let e=Object.entries(r.environment).map(([t,i])=>{if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))throw Error(`Invalid Windows Scheduled Task environment name: ${t}`);return`$env:${t}=${S(i)};`}),n=`$global:LASTEXITCODE=1; & ${[r.program,...r.args].map(S).join(" ")} 2>&1 | ForEach-Object { Add-Content -LiteralPath ${S(r.log)} -Value $_.ToString() -Encoding UTF8 }; $c=$LASTEXITCODE;`;return[D(r.name),...e,"$ErrorActionPreference='Continue';",r.keepAlive?`do { ${n} if ($c) { Start-Sleep -Seconds 10 } } while ($c)`:`${n} exit $c`].join(" ")}function I(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function pe(){let r=process.env.USERDOMAIN?.trim();return r?`${r}\\${O().username}`:O().username}function M(r){let e=I(r.user??pe()),n=r.schedule==="logon",t=r.schedule==="logon"?`<LogonTrigger><Enabled>true</Enabled><UserId>${e}</UserId></LogonTrigger>`:`<TimeTrigger><Repetition><Interval>PT${r.schedule.everyMinutes}M</Interval><StopAtDurationEnd>false</StopAtDurationEnd></Repetition><StartBoundary>2026-01-01T00:00:00</StartBoundary><Enabled>true</Enabled></TimeTrigger>`,i=`-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -Command "${r.script}"`;return`<?xml version="1.0" encoding="UTF-16"?>
|
|
3
3
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
4
4
|
<RegistrationInfo>
|
|
5
5
|
<Description>${I(r.description)}</Description>
|
|
@@ -42,12 +42,12 @@ import{P}from"./vm-hands-entry-lite-2rgf8866.js";import{w}from"./vm-hands-entry-
|
|
|
42
42
|
`)}function V(r,e){return["/Create","/TN",r,"/XML",e,"/F"]}function x(r){return["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand",Buffer.from(r,"utf16le").toString("base64")]}function E(r){return`'*${D(r).replaceAll("'","''")}*'`}function _(r,e){return x(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${E(r)} })`,...e.keepWrapper?[]:["foreach ($w in $wrappers) { Stop-Process -Id $w.ProcessId -Force -ErrorAction SilentlyContinue }"],`foreach ($w in $wrappers) { $all | ? { $_.ParentProcessId -eq $w.ProcessId } | % { taskkill.exe /F ${e.tree?"/T ":""}/PID $_.ProcessId | Out-Null } }`].join(`
|
|
43
43
|
`))}function F(r){return x(["$all = @(Get-CimInstance Win32_Process)",`$wrappers = @($all | ? { $_.ProcessId -ne $PID -and $_.CommandLine -like ${E(r)} })`,"foreach ($w in $wrappers) { if ($all | ? { $_.ParentProcessId -eq $w.ProcessId -and $_.Name -ne 'conhost.exe' }) { 'running'; exit 0 } }","exit 1"].join(`
|
|
44
44
|
`))}function X(r,e=process.pid){let n=ue(B("powershell.exe"),x(["$all = @{}; Get-CimInstance Win32_Process | % { $all[[int]$_.ProcessId] = $_ }",`$p = $all[${Math.trunc(e)}]`,"for ($i = 0; $p -and $i -lt 64; $i++) {",` if ($p.CommandLine -like ${E(r)}) { exit 10 }`," $n = $all[[int]$p.ParentProcessId]"," if (-not $n -or $n.ProcessId -eq $p.ProcessId -or $n.CreationDate -gt $p.CreationDate) { exit 11 }"," $p = $n","}","exit 11"].join(`
|
|
45
|
-
`)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var ke="REASON_WORKER_SERVICE",
|
|
46
|
-
`)}function z(r,e){let n;try{n=p(r,"utf8")}catch{return null}let t=Y(n);if(!t)return null;let i=q(t.launcher)
|
|
47
|
-
${L}`);if(!a)o=o.replace(y,"");else if(y.test(o))o=o.replace(y,(l,c,m)=>`${c}${d(a.app)}${m}`);else o=o.replace(
|
|
48
|
-
<key>${
|
|
49
|
-
<string>${d(a.app)}</string>${m}`);return o===n?null:o}function
|
|
50
|
-
`:""}${ce}`)===te(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function N(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function G(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new j("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function te(r,e,n,t,i,s){let a=N(r,e),o=J(t,a.args,i),l={HOME:i.home,PATH:s,[ke]:n.label,...a.environment,...o.identity?{[
|
|
45
|
+
`)),{stdio:"ignore",timeout:15000,windowsHide:!0});return n.status===10?!0:n.status===11?!1:null}var ke="REASON_WORKER_SERVICE",Ee="worker_identity_unavailable";function de(r){return{platform:process.platform,home:r,uid:process.getuid?.(),command:(e,n)=>v(B(e),[...n],{stdio:"ignore"}).status??1,read:(e,n)=>{let t=v(B(e),[...n],{stdio:["ignore","pipe","ignore"],encoding:"utf8",timeout:1e4});return t.status===0?t.stdout:null},sleep:(e)=>Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e),workerIdentity:(e)=>jc(r,e),insideService:(e,n)=>_e(e,process.platform,process.getuid?.(),n)}}function _e(r,e,n,t=!0){if(process.env[ke]===r||process.env.XPC_SERVICE_NAME===r)return!0;if(e==="linux")try{return p("/proc/self/cgroup","utf8").includes(`/${r}.service`)}catch{return!0}if(e==="win32")return X(r)??t;if(e!=="darwin")return!1;if(typeof n!=="number")return!0;let i=v("/bin/launchctl",["print",`gui/${n}/${r}`],{encoding:"utf8",timeout:5000});if(i.status===Te)return!1;if(i.error||i.status!==0)return!0;let s=Number(/^\s*pid = (\d+)$/m.exec(i.stdout??"")?.[1]??0);if(!s)return!1;let a=process.pid;for(let o=0;o<64&&a>1;o+=1){if(a===s)return!0;let l=v("/bin/ps",["-o","ppid=","-p",String(a)],{encoding:"utf8",timeout:5000}),c=Number(l.stdout?.trim());if(l.error||l.status!==0||!Number.isSafeInteger(c)||c<=0)return!0;if(c===a)return!1;a=c}return a>1}var Te=113;class j extends Error{code;constructor(r,e){super(r);this.code=e}}function ze(r,e){if(!ee(r.home,r.platform))throw new j(Q);if(r.platform==="darwin")k(r);let n=We(ot(e,r.home)),t=w({env:e})==="staging",i=t?"ara-staging":"ara",s=[n?as(n):null,R(e,"REASON_CLI_LAUNCHER_PATH")?.trim(),r.platform==="win32"?g(r.home,"AppData","Local","Reason",...t?["staging"]:[],"bin",t?"reason-staging.exe":"reason.exe"):g(r.home,".local","bin",i)];for(let a of s)try{if(a&&q(a)&&be(a).isFile())return $i(a)}catch{}throw new j(`A background service runs the installed Reason launcher, which was not found. Install Reason with: ${r.platform==="win32"?"irm https://reasonmachines.com/install.ps1 | iex":"curl -fsSL https://reasonmachines.com/install | sh"}`,"worker_launcher_missing")}var P=/(<key>ProgramArguments<\/key>\s*<array>\n)((?:\s*<string>[^<]*<\/string>\n)*)(\s*<\/array>)/,y=new RegExp(`(\\n\\s*<key>${Ln}</key>\\s*<string>)[^<]*(</string>)`),Pe=/(<key>EnvironmentVariables<\/key>\s*<dict>[\s\S]*?)(\n\s*<\/dict>)/;function Re(r){return r.replaceAll("<","<").replaceAll(">",">").replaceAll(""",'"').replaceAll("'","'").replaceAll("&","&")}function Y(r){let e=[...(P.exec(r)?.[2]??"").matchAll(/<string>([^<]*)<\/string>/g)].map((t)=>Re(t[1])),n=e[1]==="--run-worker"?e.slice(2):e;return n[0]?{launcher:n[0],args:n.slice(1)}:null}function J(r,e,n){let t=n.workerIdentity?.(r)??null;return{program:t?[t.executable,"--run-worker",r,...e]:[r,...e],identity:t}}function C(r){return r.map((e)=>` <string>${d(e)}</string>`).join(`
|
|
46
|
+
`)}function z(r,e){let n;try{n=p(r,"utf8")}catch{return null}let t=Y(n);if(!t)return null;let i=q(t.launcher)?$i(t.launcher):t.launcher,{program:s,identity:a}=J(i,t.args,e),o=n.replace(P,(l,c,m,L)=>`${c}${C(s)}
|
|
47
|
+
${L}`);if(!a)o=o.replace(y,"");else if(y.test(o))o=o.replace(y,(l,c,m)=>`${c}${d(a.app)}${m}`);else o=o.replace(Pe,(l,c,m)=>`${c}
|
|
48
|
+
<key>${Ln}</key>
|
|
49
|
+
<string>${d(a.app)}</string>${m}`);return o===n?null:o}function Ce(r,e){let n=z(r,e);if(n!==null)A(r,n)}function ns(r,e,n){if(e.platform!=="darwin")return!1;let t=qe(r,e,n);return t!==null&&z(t.definition,e)!==null}var W="com.reasonmachines.worker.",h="so.reason.worker.",Z=[W,h];function En(r,e=W){return`${e}connect${r==="production"?"":`.${r}`}`}function is(r,e){return Z.some((n)=>r===En(e,n))}function he(r,e,n){if(e==="connect")return En(r.channel,n);let t=Se("sha256").update(r.workspaceRoot).digest("hex").slice(0,8);return`${n}${r.name.toLowerCase()}.${t}`}var Q="A background service needs macOS (launchd), Linux (systemd --user) or Windows (Task Scheduler).";function ee(r,e){if(e==="darwin")return{directory:g(r,"Library","LaunchAgents"),suffix:".plist"};if(e==="linux")return{directory:g(r,".config","systemd","user"),suffix:".service"};if(e==="win32")return{directory:Oi(r),suffix:".xml"};return null}function f(r,e,n,t=W){let i=he(r,n,t),s=ee(e.home,e.platform);if(!s)return null;return{label:i,definition:g(s.directory,`${i}${s.suffix}`),logs:e.platform==="linux"?`journalctl --user -u ${i}.service`:g(r.stateDirectory,"service.log")}}function qe(r,e,n="serve"){return re(r,e,n)[0]??null}function re(r,e,n){return Z.map((t)=>f(r,e,n,t)).filter((t)=>t!==null&&T(t.definition))}function ne(r,e,n){let t=f(r,e,n,h);return t&&T(t.definition)?t:null}function Ni(r,e,n){let t=f(r,e,n),i=ne(r,e,n);if(!t||!i||!T(t.definition)||e.insideService?.(i.label))return null;if(!Ne(t,e))return"current_not_running";if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);return u(i.definition,{force:!0}),"retired"}if(e.platform==="win32")return b(i,e,!0),"retired";return e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),"retired"}function Ne(r,e){if(e.platform==="darwin")return typeof e.uid==="number"&&e.uid>0&&e.command("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`])===0;if(e.platform==="win32")return e.command("schtasks",["/Query","/TN",r.label])===0;let n=`${r.label}.service`;return e.command("systemctl",["--user","is-enabled","--quiet",n])===0&&Le.has(e.read("systemctl",["--user","show","--property=ActiveState","--value",n])?.trim()??"")}var Le=new Set(["active","activating","reloading"]);function Li(r,e){if(e.platform==="darwin"){if(typeof e.uid!=="number"||e.uid<=0)return!1;let n=e.read("/bin/launchctl",["print",`gui/${e.uid}/${r.label}`]);return Number(/^\s*pid = (\d+)$/m.exec(n??"")?.[1]??0)>0}if(e.platform==="win32")return e.read("powershell.exe",F(r.label))?.trim()==="running";return Number(e.read("systemctl",["--user","show","--property=MainPID","--value",`${r.label}.service`])?.trim()??0)>0}function os(r){let{config:e,launcher:n,host:t,kind:i}=r,s=f(e,t,i);if(!s)return!1;let a;try{a=t.platform==="win32"?U(s.definition):p(s.definition,"utf8")}catch{return!1}if(t.platform==="win32")return a===oe(e,i,s,n);if(t.platform!=="darwin")return a===ie(e,i,s,n,t.home,r.path);let o=Y(a);return a.replace(y,"").replace(P,(c,m,L,ce)=>`${m}${o?`${C([o.launcher,...o.args])}
|
|
50
|
+
`:""}${ce}`)===te(e,i,s,n,{...t,workerIdentity:()=>null},r.path).plist}function N(r,e){if(e==="connect")return{args:["connect"],environment:{REASON_CLI_CHANNEL:r.channel},description:"Reason connection of this computer"};return{args:["serve",r.name,"--dir",r.workspaceRoot,...r.executionMode==="confined"?["--sandbox"]:[]],environment:{},description:`Reason machine ${r.name} worker`}}function d(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function G(r,e=!1){if(/[\0-\x1f\x7f]/.test(r))throw new j("A background service cannot use a path with control characters.");let n=r.replaceAll("\\","\\\\").replaceAll('"',"\\\"").replaceAll("%","%%");return`"${e?n.replaceAll("$","$$$$"):n}"`}function te(r,e,n,t,i,s){let a=N(r,e),o=J(t,a.args,i),l={HOME:i.home,PATH:s,[ke]:n.label,...a.environment,...o.identity?{[Ln]:o.identity.app}:{}};return{identity:o.identity,plist:`<?xml version="1.0" encoding="UTF-8"?>
|
|
51
51
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
52
52
|
<plist version="1.0">
|
|
53
53
|
<dict>
|
|
@@ -55,7 +55,7 @@ ${L}`);if(!a)o=o.replace(y,"");else if(y.test(o))o=o.replace(y,(l,c,m)=>`${c}${d
|
|
|
55
55
|
<string>${d(n.label)}</string>
|
|
56
56
|
<key>AssociatedBundleIdentifiers</key>
|
|
57
57
|
<array>
|
|
58
|
-
<string>${
|
|
58
|
+
<string>${fs}</string>
|
|
59
59
|
</array>
|
|
60
60
|
<key>ProgramArguments</key>
|
|
61
61
|
<array>
|
|
@@ -101,5 +101,5 @@ UMask=0077
|
|
|
101
101
|
|
|
102
102
|
[Install]
|
|
103
103
|
WantedBy=default.target
|
|
104
|
-
`}function oe(r,e,n,t){let i=N(r,e);return M({description:i.description,schedule:"logon",script:H({name:n.label,program:t,args:i.args,environment:{[ke]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function se(r,e,n){e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!n}))}function b(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function A(r,e){ye(
|
|
105
|
-
export{
|
|
104
|
+
`}function oe(r,e,n,t){let i=N(r,e);return M({description:i.description,schedule:"logon",script:H({name:n.label,program:t,args:i.args,environment:{[ke]:n.label,...i.environment},log:n.logs,keepAlive:!0})})}function se(r,e,n){e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!n}))}function b(r,e,n){e.command("schtasks",["/Delete","/F","/TN",r.label]),e.command("powershell.exe",_(r.label,{tree:n,keepWrapper:!1})),u(r.definition,{force:!0})}function A(r,e){ye(xe(r),{recursive:!0,mode:448});let n=`${r}.${we()}.tmp`;try{Ae(n,e,{mode:384,flag:"wx"}),$e(n,384),ve(n,r)}finally{u(n,{force:!0})}}function k(r){if(typeof r.uid!=="number"||!Number.isSafeInteger(r.uid)||r.uid<=0)throw new j("Set up a background service as your own user, not with sudo.","worker_service_root_user");return`gui/${r.uid}`}function kn(r){let{config:e,launcher:n,host:t}=r,i=r.kind??"serve",s=ne(e,t,i),a=s!==null&&t.insideService?.(s.label)===!0,o=f(e,t,i,a?h:W);if(!o)throw new j(Q);if(t.platform==="darwin")k(t);if(t.platform==="linux"&&t.command("systemctl",["--user","show-environment"])!==0)throw new j("No background service here: this computer has no systemd user session.","worker_service_manager_missing");let l=t.platform==="darwin"?te(e,i,o,n,t,r.path):null;if(A(o.definition,l?l.plist:t.platform==="win32"?K(oe(e,i,o,n)):ie(e,i,o,n,t.home,r.path)),ae(e,t,o,a?null:s),l)return l.identity?o:{...o,identityProblem:Ee};if(t.platform==="win32")return o;return{...o,lingering:t.command("loginctl",["enable-linger"])===0}}function ae(r,e,n,t){if(e.platform==="darwin"){let a=k(e);if(t)e.command("/bin/launchctl",["bootout",`${a}/${t.label}`]);if(le(r,n,e)){if(t)u(t.definition,{force:!0});return}if(u(n.definition,{force:!0}),t)e.command("/bin/launchctl",["bootstrap",a,t.definition]);throw new j("Could not start the background service (launchctl bootstrap failed).","worker_service_start_failed")}if(e.platform==="win32"){if(t)b(t,e,!0);if(e.command("schtasks",V(n.label,n.definition))===0){if(se(n,e,e.insideService?.(n.label)!==!0),e.command("schtasks",["/Run","/TN",n.label])===0)return}throw b(n,e,!0),new j("Could not start the background service (schtasks failed).")}let i=`${n.label}.service`,s=t?`${t.label}.service`:null;if(e.command("systemctl",["--user","daemon-reload"])!==0||s!==null&&e.command("systemctl",["--user","disable","--now",s])!==0||e.command("systemctl",["--user","enable",i])!==0||e.command("systemctl",["--user","restart",i])!==0){if(e.command("systemctl",["--user","disable",i]),u(n.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"]),s)e.command("systemctl",["--user","enable","--now",s]);throw new j("Could not start the background service (systemctl --user failed).","worker_service_start_failed")}if(t)u(t.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}function le(r,e,n){let t=k(n);n.command("/bin/launchctl",["bootout",`${t}/${e.label}`]);let i=(Math.ceil(r.shutdownGraceMs/1000)+10)*1000;for(let s=0,a=100;;a=Math.min(a*2,2000)){if(n.command("/bin/launchctl",["bootstrap",t,e.definition])===0)return!0;if(s>=i)return!1;n.sleep(a),s+=a}}function Ie(r,e,n){let t=qe(r,e,n);if(!t)return null;let i=e.insideService?.(t.label)===!0;if(e.platform==="darwin"&&!i)Ce(t.definition,e);let s=f(r,e,n);if(s&&t.label!==s.label&&!i)return A(s.definition,p(t.definition,"utf8").replaceAll(t.label,s.label)),ae(r,e,s,t),s;let a=e.platform==="darwin"&&i,o;if(e.platform==="win32")se(t,e,!i),o=e.command("schtasks",["/Run","/TN",t.label])===0;else if(a)o=e.command("/bin/launchctl",["kickstart","-k",`${k(e)}/${t.label}`])===0;else if(e.platform==="darwin")o=le(r,t,e);else e.command("systemctl",["--user","enable",`${t.label}.service`]),o=e.command("systemctl",["--user","restart",`${t.label}.service`])===0;if(!o)throw new j(`Could not restart the background service ${t.label}.`,"worker_service_restart_failed");if(s&&t.label===s.label)Ni(r,e,n);return t}function ss(r,e,n,t){let i=qe(r,n,t),s=f(e,n,t);if(n.platform!=="darwin"||!i||!s)return;let a=`<string>${d(i.logs)}</string>`,o=p(i.definition,"utf8");if(o.includes(a))A(i.definition,o.replaceAll(a,`<string>${d(s.logs)}</string>`))}function xn(r,e,n="serve"){let t=re(r,e,n);for(let i of t){if(e.platform==="win32"){b(i,e,e.insideService?.(i.label,!1)!==!0);continue}if(e.platform==="darwin"){if(typeof e.uid==="number"&&e.uid>0)e.command("/bin/launchctl",["bootout",`gui/${e.uid}/${i.label}`]);u(i.definition,{force:!0});continue}e.command("systemctl",["--user","disable","--now",`${i.label}.service`]),u(i.definition,{force:!0}),e.command("systemctl",["--user","daemon-reload"])}return t[0]??null}
|
|
105
|
+
export{Oi,ke,de,j,ze,ns,En,is,qe,Ni,Li,os,kn,Ie,ss,xn};
|