@namzu/computer-use 3.1.0 → 4.0.1
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/CHANGELOG.md +64 -1
- package/README.md +3 -3
- package/dist/SubprocessComputerUseHost.d.ts +58 -10
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/SubprocessComputerUseHost.js +214 -47
- package/dist/SubprocessComputerUseHost.js.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts +171 -10
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.js +1479 -161
- package/dist/adapters/cua-driver/adapter.js.map +1 -1
- package/dist/adapters/cua-driver/client.d.ts +16 -0
- package/dist/adapters/cua-driver/client.d.ts.map +1 -1
- package/dist/adapters/cua-driver/client.js +54 -5
- package/dist/adapters/cua-driver/client.js.map +1 -1
- package/dist/adapters/cua-driver/escalation.d.ts +67 -0
- package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
- package/dist/adapters/cua-driver/escalation.js +82 -0
- package/dist/adapters/cua-driver/escalation.js.map +1 -0
- package/dist/adapters/cua-driver/keys.d.ts +5 -0
- package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
- package/dist/adapters/cua-driver/keys.js +23 -0
- package/dist/adapters/cua-driver/keys.js.map +1 -1
- package/dist/adapters/cua-driver/observe.d.ts +99 -0
- package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
- package/dist/adapters/cua-driver/observe.js +227 -0
- package/dist/adapters/cua-driver/observe.js.map +1 -0
- package/dist/adapters/cua-driver/provision.d.ts +13 -13
- package/dist/adapters/cua-driver/provision.js +13 -13
- package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
- package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
- package/dist/adapters/cua-driver/ui-tree.js +142 -14
- package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
- package/dist/adapters/types.d.ts +4 -4
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/adapters/win32.d.ts +10 -0
- package/dist/adapters/win32.d.ts.map +1 -1
- package/dist/adapters/win32.js +12 -2
- package/dist/adapters/win32.js.map +1 -1
- package/dist/errors.d.ts +19 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -1
- package/dist/foreground/guard.d.ts +31 -0
- package/dist/foreground/guard.d.ts.map +1 -0
- package/dist/foreground/guard.js +156 -0
- package/dist/foreground/guard.js.map +1 -0
- package/dist/foreground/index.d.ts +11 -0
- package/dist/foreground/index.d.ts.map +1 -0
- package/dist/foreground/index.js +7 -0
- package/dist/foreground/index.js.map +1 -0
- package/dist/foreground/ladder.d.ts +143 -0
- package/dist/foreground/ladder.d.ts.map +1 -0
- package/dist/foreground/ladder.js +505 -0
- package/dist/foreground/ladder.js.map +1 -0
- package/dist/foreground/lease.d.ts +69 -0
- package/dist/foreground/lease.d.ts.map +1 -0
- package/dist/foreground/lease.js +182 -0
- package/dist/foreground/lease.js.map +1 -0
- package/dist/foreground/types.d.ts +287 -0
- package/dist/foreground/types.d.ts.map +1 -0
- package/dist/foreground/types.js +32 -0
- package/dist/foreground/types.js.map +1 -0
- package/dist/foreground/windows-helper-script.d.ts +19 -0
- package/dist/foreground/windows-helper-script.d.ts.map +1 -0
- package/dist/foreground/windows-helper-script.js +472 -0
- package/dist/foreground/windows-helper-script.js.map +1 -0
- package/dist/foreground/windows-monitor.d.ts +75 -0
- package/dist/foreground/windows-monitor.d.ts.map +1 -0
- package/dist/foreground/windows-monitor.js +216 -0
- package/dist/foreground/windows-monitor.js.map +1 -0
- package/dist/foreground/windows.d.ts +21 -0
- package/dist/foreground/windows.d.ts.map +1 -0
- package/dist/foreground/windows.js +54 -0
- package/dist/foreground/windows.js.map +1 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/presence/helper-script.d.ts +39 -0
- package/dist/presence/helper-script.d.ts.map +1 -0
- package/dist/presence/helper-script.js +320 -0
- package/dist/presence/helper-script.js.map +1 -0
- package/dist/presence/index.d.ts +6 -0
- package/dist/presence/index.d.ts.map +1 -0
- package/dist/presence/index.js +4 -0
- package/dist/presence/index.js.map +1 -0
- package/dist/presence/presence.d.ts +70 -0
- package/dist/presence/presence.d.ts.map +1 -0
- package/dist/presence/presence.js +147 -0
- package/dist/presence/presence.js.map +1 -0
- package/dist/presence/windows.d.ts +19 -0
- package/dist/presence/windows.d.ts.map +1 -0
- package/dist/presence/windows.js +39 -0
- package/dist/presence/windows.js.map +1 -0
- package/dist/util/call-scope.d.ts +34 -0
- package/dist/util/call-scope.d.ts.map +1 -0
- package/dist/util/call-scope.js +58 -0
- package/dist/util/call-scope.js.map +1 -0
- package/package.json +2 -2
- package/src/SubprocessComputerUseHost.ts +288 -46
- package/src/adapters/cua-driver/adapter.ts +1754 -175
- package/src/adapters/cua-driver/client.ts +59 -2
- package/src/adapters/cua-driver/escalation.ts +137 -0
- package/src/adapters/cua-driver/keys.ts +20 -0
- package/src/adapters/cua-driver/observe.ts +310 -0
- package/src/adapters/cua-driver/provision.ts +13 -13
- package/src/adapters/cua-driver/ui-tree.ts +219 -15
- package/src/adapters/types.ts +8 -3
- package/src/adapters/win32.ts +26 -3
- package/src/errors.ts +32 -0
- package/src/foreground/guard.ts +182 -0
- package/src/foreground/index.ts +45 -0
- package/src/foreground/ladder.ts +616 -0
- package/src/foreground/lease.ts +232 -0
- package/src/foreground/types.ts +318 -0
- package/src/foreground/windows-helper-script.ts +471 -0
- package/src/foreground/windows-monitor.ts +288 -0
- package/src/foreground/windows.ts +73 -0
- package/src/index.ts +15 -1
- package/src/presence/helper-script.ts +323 -0
- package/src/presence/index.ts +17 -0
- package/src/presence/presence.ts +195 -0
- package/src/presence/windows.ts +54 -0
- package/src/util/call-scope.ts +73 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Windows side of the presence overlay: one long-lived PowerShell process
|
|
3
|
+
* that owns two small windows and draws them itself.
|
|
4
|
+
*
|
|
5
|
+
* - the agent cursor, a pixel-art arrow in the project's green with a dark
|
|
6
|
+
* outline, that glides to each action point in {@link GLIDE_MS} and pulses on
|
|
7
|
+
* a click or on typing;
|
|
8
|
+
* - the presence border, a frame inside the operated window made of an
|
|
9
|
+
* ordered (Bayer) dither that thins towards the middle, which follows the
|
|
10
|
+
* window and fades out a while after the last action.
|
|
11
|
+
*
|
|
12
|
+
* Both windows are layered, click-through (`WS_EX_TRANSPARENT`), never
|
|
13
|
+
* activated (`WS_EX_NOACTIVATE`), kept out of the taskbar and alt-tab
|
|
14
|
+
* (`WS_EX_TOOLWINDOW`) and excluded from every screen capture
|
|
15
|
+
* (`SetWindowDisplayAffinity` with `WDA_EXCLUDEFROMCAPTURE`). If the exclusion
|
|
16
|
+
* cannot be set the helper shows nothing: an overlay that could end up in the
|
|
17
|
+
* model's own screenshot is worse than none. They are placed directly above
|
|
18
|
+
* the operated window in the z-order, never raised above others, so a window
|
|
19
|
+
* behind other windows gets its cursor and border without coming forward.
|
|
20
|
+
*
|
|
21
|
+
* Like the foreground helper it is handed to PowerShell as an encoded command
|
|
22
|
+
* and speaks one JSON object per line in each direction; its input closing
|
|
23
|
+
* ends it, and its windows go with it.
|
|
24
|
+
*/
|
|
25
|
+
export const GLIDE_MS = 120
|
|
26
|
+
/** How long the border and cursor stay after the last action, then fade. */
|
|
27
|
+
export const HOLD_MS = 2_500
|
|
28
|
+
export const FADE_MS = 600
|
|
29
|
+
|
|
30
|
+
export const PRESENCE_HELPER_SCRIPT = String.raw`
|
|
31
|
+
$ErrorActionPreference = 'Stop'
|
|
32
|
+
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
33
|
+
[Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
|
|
34
|
+
Add-Type -TypeDefinition @"
|
|
35
|
+
using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading;
|
|
36
|
+
public static class NzP {
|
|
37
|
+
[StructLayout(LayoutKind.Sequential)] struct PT { public int x; public int y; }
|
|
38
|
+
[StructLayout(LayoutKind.Sequential)] struct SZ { public int cx; public int cy; }
|
|
39
|
+
[StructLayout(LayoutKind.Sequential)] struct RC { public int l; public int t; public int r; public int b; }
|
|
40
|
+
[StructLayout(LayoutKind.Sequential)] struct BF { public byte op; public byte fl; public byte a; public byte fmt; }
|
|
41
|
+
[StructLayout(LayoutKind.Sequential)] struct BMI { public int size; public int w; public int h; public short planes; public short bits; public int comp; public int img; public int xp; public int yp; public int used; public int imp; }
|
|
42
|
+
[StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr h; public uint m; public IntPtr w; public IntPtr l; public uint t; public PT p; }
|
|
43
|
+
[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] struct WC { public uint size; public uint style; public IntPtr proc; public int cb; public int wb; public IntPtr inst; public IntPtr icon; public IntPtr cur; public IntPtr bg; public string menu; public string cls; public IntPtr small; }
|
|
44
|
+
delegate IntPtr WP(IntPtr h, uint m, IntPtr w, IntPtr l);
|
|
45
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern ushort RegisterClassEx(ref WC c);
|
|
46
|
+
[DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr CreateWindowEx(uint ex, string cls, string name, uint st, int x, int y, int w, int h, IntPtr par, IntPtr menu, IntPtr inst, IntPtr p);
|
|
47
|
+
[DllImport("user32.dll")] static extern IntPtr DefWindowProc(IntPtr h, uint m, IntPtr w, IntPtr l);
|
|
48
|
+
[DllImport("user32.dll")] static extern bool UpdateLayeredWindow(IntPtr h, IntPtr dst, ref PT pd, ref SZ sz, IntPtr src, ref PT ps, uint key, ref BF bf, uint fl);
|
|
49
|
+
[DllImport("user32.dll", SetLastError=true)] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int cy, uint fl);
|
|
50
|
+
[DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint c);
|
|
51
|
+
[DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);
|
|
52
|
+
[DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);
|
|
53
|
+
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
|
|
54
|
+
[DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int c);
|
|
55
|
+
[DllImport("user32.dll", SetLastError=true)] static extern bool SetWindowDisplayAffinity(IntPtr h, uint a);
|
|
56
|
+
[DllImport("user32.dll")] static extern bool GetWindowDisplayAffinity(IntPtr h, out uint a);
|
|
57
|
+
[DllImport("user32.dll")] static extern UIntPtr SetTimer(IntPtr h, UIntPtr id, uint ms, IntPtr f);
|
|
58
|
+
[DllImport("user32.dll")] static extern bool KillTimer(IntPtr h, UIntPtr id);
|
|
59
|
+
[DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
|
|
60
|
+
[DllImport("user32.dll")] static extern int GetMessage(out MSG m, IntPtr h, uint a, uint b);
|
|
61
|
+
[DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m);
|
|
62
|
+
[DllImport("user32.dll")] static extern int SetWindowLong(IntPtr h, int i, int v);
|
|
63
|
+
[DllImport("user32.dll", EntryPoint="SetWindowLongPtrW", SetLastError=true)] static extern IntPtr SetWindowLongPtr64(IntPtr h, int i, IntPtr v);
|
|
64
|
+
[DllImport("user32.dll", EntryPoint="SetWindowLongW", SetLastError=true)] static extern int SetWindowLongPtr32(IntPtr h, int i, int v);
|
|
65
|
+
[DllImport("user32.dll")] static extern int GetWindowLong(IntPtr h, int i);
|
|
66
|
+
[DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr h);
|
|
67
|
+
[DllImport("user32.dll")] static extern int ReleaseDC(IntPtr h, IntPtr dc);
|
|
68
|
+
[DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
|
|
69
|
+
[DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr dc);
|
|
70
|
+
[DllImport("gdi32.dll")] static extern IntPtr CreateDIBSection(IntPtr dc, ref BMI bmi, uint u, out IntPtr bits, IntPtr sec, uint off);
|
|
71
|
+
[DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr dc, IntPtr o);
|
|
72
|
+
[DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr o);
|
|
73
|
+
[DllImport("gdi32.dll")] static extern bool DeleteDC(IntPtr dc);
|
|
74
|
+
[DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int a, out RC r, int n);
|
|
75
|
+
[DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr c);
|
|
76
|
+
[DllImport("kernel32.dll")] static extern void SetLastError(uint e);
|
|
77
|
+
[DllImport("kernel32.dll")] static extern IntPtr GetModuleHandle(string n);
|
|
78
|
+
|
|
79
|
+
const uint EX = 0x20 | 0x08000000 | 0x80;
|
|
80
|
+
static readonly string[] Sprite = {
|
|
81
|
+
"#...........","##..........","#g#.........","#gg#........","#ggg#.......","#gggg#......","#ggggg#.....","#gggggg#....","#ggggggg#...",
|
|
82
|
+
"#gggggggg#..","#ggggg#####.","#gg#gg#.....","#g#.#gg#....","##..#gg#....","#....#gg#...",".....#gg#...","......##...."
|
|
83
|
+
};
|
|
84
|
+
static readonly int[] Bayer = { 0,8,2,10, 12,4,14,6, 3,11,1,9, 15,7,13,5 };
|
|
85
|
+
const int S = 3, PAD = 36, CW = 100, CH = 110, T = 8, CELL = 2;
|
|
86
|
+
static readonly double[] Dens = { 1.0, 0.62, 0.38, 0.16 };
|
|
87
|
+
const int GREEN = 0x5fff5f, INK = 0x0b0f0c;
|
|
88
|
+
|
|
89
|
+
static IntPtr frm, cur, mem1, mem2, bmp1, bmp2, bits1, bits2; static WP proc;
|
|
90
|
+
static int fw, fh, lastX, lastY, lastW, lastH; static IntPtr lastPrev;
|
|
91
|
+
public static long Hwnd1, Hwnd2; public static bool Excluded, Ready; public static string Err = "";
|
|
92
|
+
static ManualResetEvent ready = new ManualResetEvent(false);
|
|
93
|
+
static object gate = new object();
|
|
94
|
+
// Command state (written by the reader thread, read by the UI thread).
|
|
95
|
+
static IntPtr target; static double ax, ay; static bool hasPoint; static int kind; static long actTick; static bool hidden = true;
|
|
96
|
+
// Animation state (UI thread only).
|
|
97
|
+
static double rx, ry, fx, fy, tx, ty; static long glideAt = -1000; static long pulseAt = -10000; static int pulseKind; static bool placed;
|
|
98
|
+
static int lastAlpha = -1; static bool borderDrawn; static IntPtr drawnFor;
|
|
99
|
+
public static long Ticks, TickUs, MaxTickUs; static Stopwatch sw = Stopwatch.StartNew();
|
|
100
|
+
static bool timerOn; static long refuseUntil; public static int Refused;
|
|
101
|
+
public static int GlideMs = ${GLIDE_MS}, HoldMs = ${HOLD_MS}, FadeMs = ${FADE_MS};
|
|
102
|
+
|
|
103
|
+
static long Now() { return sw.ElapsedMilliseconds; }
|
|
104
|
+
static IntPtr Wnd(IntPtr h, uint m, IntPtr w, IntPtr l) {
|
|
105
|
+
if (m == 0x113) { try { Tick(); } catch (Exception e) { Err = e.Message; } return IntPtr.Zero; }
|
|
106
|
+
if (m == 0x8000) { try { Tick(); } catch (Exception e) { Err = e.Message; } return IntPtr.Zero; }
|
|
107
|
+
return DefWindowProc(h, m, w, l);
|
|
108
|
+
}
|
|
109
|
+
static IntPtr Make(string cls, ref uint aff) {
|
|
110
|
+
IntPtr h = CreateWindowEx(EX, cls, "", 0x80000000, 0, 0, 1, 1, IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero);
|
|
111
|
+
if (h == IntPtr.Zero) throw new Exception("CreateWindowEx " + Marshal.GetLastWin32Error());
|
|
112
|
+
// Windows refuses the exclusion on a window that is already layered, so it is
|
|
113
|
+
// set first and the layered style added after; the setting survives.
|
|
114
|
+
bool set = SetWindowDisplayAffinity(h, 0x11); int le = Marshal.GetLastWin32Error();
|
|
115
|
+
SetWindowLong(h, -20, GetWindowLong(h, -20) | 0x80000);
|
|
116
|
+
if (!set) throw new Exception("capture exclusion unavailable " + le);
|
|
117
|
+
uint a; GetWindowDisplayAffinity(h, out a); aff = a;
|
|
118
|
+
return h;
|
|
119
|
+
}
|
|
120
|
+
static IntPtr Dib(int w, int h, out IntPtr mem, out IntPtr bits) {
|
|
121
|
+
IntPtr sd = GetDC(IntPtr.Zero); mem = CreateCompatibleDC(sd);
|
|
122
|
+
BMI b = new BMI(); b.size = 40; b.w = w; b.h = -h; b.planes = 1; b.bits = 32;
|
|
123
|
+
IntPtr bm = CreateDIBSection(sd, ref b, 0, out bits, IntPtr.Zero, 0); ReleaseDC(IntPtr.Zero, sd);
|
|
124
|
+
SelectObject(mem, bm); return bm;
|
|
125
|
+
}
|
|
126
|
+
public static bool Start() {
|
|
127
|
+
var t = new Thread(() => {
|
|
128
|
+
try {
|
|
129
|
+
// Physical pixels: the frame bounds come from the window manager in physical units, and a
|
|
130
|
+
// DPI-unaware thread would have them scaled again on a display set above 100%.
|
|
131
|
+
try { SetThreadDpiAwarenessContext((IntPtr)(-4)); } catch (Exception) { }
|
|
132
|
+
proc = Wnd; WC c = new WC(); c.size = (uint)Marshal.SizeOf(typeof(WC)); c.proc = Marshal.GetFunctionPointerForDelegate(proc); c.inst = GetModuleHandle(null); c.cls = "NzPresence";
|
|
133
|
+
RegisterClassEx(ref c);
|
|
134
|
+
uint a1 = 0, a2 = 0;
|
|
135
|
+
frm = Make("NzPresence", ref a1); cur = Make("NzPresence", ref a2);
|
|
136
|
+
Hwnd1 = (long)frm; Hwnd2 = (long)cur; Excluded = a1 == 0x11 && a2 == 0x11;
|
|
137
|
+
if (!Excluded) throw new Exception("capture exclusion not applied");
|
|
138
|
+
bmp2 = Dib(CW, CH, out mem2, out bits2);
|
|
139
|
+
Ready = true; ready.Set();
|
|
140
|
+
MSG m; while (GetMessage(out m, IntPtr.Zero, 0, 0) > 0) { DispatchMessage(ref m); }
|
|
141
|
+
} catch (Exception e) { Err = e.Message; ready.Set(); }
|
|
142
|
+
});
|
|
143
|
+
t.IsBackground = true; t.SetApartmentState(ApartmentState.STA); t.Start();
|
|
144
|
+
ready.WaitOne(10000); return Ready;
|
|
145
|
+
}
|
|
146
|
+
// Called from the reader thread.
|
|
147
|
+
public static void Act(long hwnd, double x, double y, bool point, int k) {
|
|
148
|
+
lock (gate) {
|
|
149
|
+
IntPtr h = (IntPtr)hwnd; if (h != target) { target = h; placed = false; borderDrawn = false; }
|
|
150
|
+
hasPoint = point; ax = x; ay = y; kind = k; actTick = Now(); hidden = false; pending = true;
|
|
151
|
+
}
|
|
152
|
+
PostMessage(frm, 0x8000, IntPtr.Zero, IntPtr.Zero);
|
|
153
|
+
}
|
|
154
|
+
static bool pending;
|
|
155
|
+
public static void Hide() { lock (gate) { hidden = true; pending = true; } PostMessage(frm, 0x8000, IntPtr.Zero, IntPtr.Zero); }
|
|
156
|
+
static void HideNow() {
|
|
157
|
+
ShowWindow(frm, 0); ShowWindow(cur, 0); lastW = 0; lastH = 0; lastPrev = IntPtr.Zero; lastAlpha = -1;
|
|
158
|
+
if (timerOn) { KillTimer(frm, (UIntPtr)1); timerOn = false; }
|
|
159
|
+
}
|
|
160
|
+
// An owned window stays directly above its owner in the z-order whatever else moves, in front of or behind other windows, without raising the owner.
|
|
161
|
+
static bool Own(IntPtr w, IntPtr owner) {
|
|
162
|
+
SetLastError(0);
|
|
163
|
+
long r = IntPtr.Size == 8 ? (long)SetWindowLongPtr64(w, -8, owner) : SetWindowLongPtr32(w, -8, (int)owner);
|
|
164
|
+
return r != 0 || Marshal.GetLastWin32Error() == 0;
|
|
165
|
+
}
|
|
166
|
+
static IntPtr ownedBy;
|
|
167
|
+
// A window without a frame rectangle (a hidden application window) covers nothing.
|
|
168
|
+
static bool Overlaps(IntPtr h, RC r) { RC o; if (!Rect(h, out o)) return false; return o.l < r.r && o.r > r.l && o.t < r.b && o.b > r.t; }
|
|
169
|
+
static bool Rect(IntPtr h, out RC r) { return DwmGetWindowAttribute(h, 9, out r, 16) == 0 && r.r > r.l && r.b > r.t; }
|
|
170
|
+
static void Tick() {
|
|
171
|
+
long t0 = sw.ElapsedTicks; IntPtr tg; bool hid, hp, ch; double px, py; int k; long at;
|
|
172
|
+
lock (gate) { tg = target; hid = hidden; hp = hasPoint; px = ax; py = ay; k = kind; at = actTick; ch = pending; pending = false; }
|
|
173
|
+
if (hid || tg == IntPtr.Zero || !IsWindow(tg) || IsIconic(tg) || !IsWindowVisible(tg)) { HideNow(); return; }
|
|
174
|
+
RC r; if (!Rect(tg, out r)) { HideNow(); return; }
|
|
175
|
+
long now = Now(); int w = r.r - r.l, h = r.b - r.t;
|
|
176
|
+
double age = now - at, alpha = 1.0;
|
|
177
|
+
if (age > HoldMs) alpha = 1.0 - (age - HoldMs) / FadeMs;
|
|
178
|
+
if (alpha <= 0) { lock (gate) { hidden = true; } HideNow(); return; }
|
|
179
|
+
if (now < refuseUntil) return;
|
|
180
|
+
if (!timerOn) { SetTimer(frm, (UIntPtr)1, 16, IntPtr.Zero); timerOn = true; }
|
|
181
|
+
if (ch && hp) {
|
|
182
|
+
// New action point in window coordinates: relative to the window's rectangle.
|
|
183
|
+
px -= r.l; py -= r.t; fx = placed ? rx : px; fy = placed ? ry : py; tx = px; ty = py; glideAt = now; placed = true; if (k != 0) { pulseAt = now; pulseKind = k; }
|
|
184
|
+
} else if (ch) {
|
|
185
|
+
if (k != 0) { pulseAt = now; pulseKind = k; }
|
|
186
|
+
if (!placed) { tx = w / 2.0; ty = h / 2.0; fx = tx; fy = ty; rx = tx; ry = ty; placed = true; glideAt = -1000; }
|
|
187
|
+
}
|
|
188
|
+
if (placed) {
|
|
189
|
+
double u = (now - glideAt) / (double)GlideMs; if (u > 1) u = 1; if (u < 0) u = 0;
|
|
190
|
+
double e = 1 - Math.Pow(1 - u, 3); rx = fx + (tx - fx) * e; ry = fy + (ty - fy) * e;
|
|
191
|
+
}
|
|
192
|
+
// z-order: directly above the operated window, never above others.
|
|
193
|
+
IntPtr prev = GetWindow(tg, 3);
|
|
194
|
+
// Windows that are not shown (input-method helpers and the like) sit in bands of their own: ordering against them has no effect.
|
|
195
|
+
// A window that does not overlap the operated one cannot hide it, so ordering against it is not needed.
|
|
196
|
+
// A window in the other (topmost or not) band is above or below it by band, and an overlay cannot be placed after it without changing band, which Windows refuses for a window owned by one in the other band.
|
|
197
|
+
while (prev != IntPtr.Zero && (prev == frm || prev == cur || !IsWindowVisible(prev) || !Overlaps(prev, r) || (GetWindowLong(prev, -20) & 8) != (GetWindowLong(tg, -20) & 8))) prev = GetWindow(prev, 3);
|
|
198
|
+
// The operated window can move up past the overlay (it is raised, or the window above it closes): the overlay must be right above it again.
|
|
199
|
+
bool moved = r.l != lastX || r.t != lastY || w != lastW || h != lastH || prev != lastPrev || Steps(frm, tg) < 0;
|
|
200
|
+
bool fresh = lastW == 0;
|
|
201
|
+
if (w != fw || h != fh || !borderDrawn || drawnFor != tg) DrawBorder(w, h, tg);
|
|
202
|
+
int a = (int)(alpha * 255);
|
|
203
|
+
if (moved || fresh || a != lastAlpha) {
|
|
204
|
+
PT pd = new PT(); pd.x = r.l; pd.y = r.t; SZ sz = new SZ(); sz.cx = w; sz.cy = h; PT ps = new PT();
|
|
205
|
+
BF bf = new BF(); bf.op = 0; bf.fl = 0; bf.a = (byte)a; bf.fmt = 1;
|
|
206
|
+
UpdateLayeredWindow(frm, IntPtr.Zero, ref pd, ref sz, mem1, ref ps, 0, ref bf, 2);
|
|
207
|
+
lastAlpha = a;
|
|
208
|
+
}
|
|
209
|
+
// The cursor window follows the glide; its sprite tip sits at the window's (PAD,PAD).
|
|
210
|
+
double sx = r.l + rx, sy = r.t + ry;
|
|
211
|
+
if (sx < r.l) sx = r.l; if (sy < r.t) sy = r.t; if (sx > r.r - 1) sx = r.r - 1; if (sy > r.b - 1) sy = r.b - 1;
|
|
212
|
+
DrawCursor(now, (int)Math.Round(sx) - PAD, (int)Math.Round(sy) - PAD, alpha);
|
|
213
|
+
uint fl = 0x10 | 0x40; // NOACTIVATE | SHOWWINDOW
|
|
214
|
+
if (ownedBy != tg) { ownedBy = Own(frm, tg) && Own(cur, tg) ? tg : IntPtr.Zero; moved = true; }
|
|
215
|
+
if (moved || fresh) {
|
|
216
|
+
int cx = (int)Math.Round(sx) - PAD, cy = (int)Math.Round(sy) - PAD;
|
|
217
|
+
// Ownership keeps an owned window above its owner only when it is raised; it does not reorder
|
|
218
|
+
// windows already stacked above the owner (a target created after the overlay), so the order is
|
|
219
|
+
// set explicitly: right above the operated window, never above others.
|
|
220
|
+
IntPtr ins = prev != IntPtr.Zero ? prev : ((GetWindowLong(tg, -20) & 8) != 0 ? (IntPtr)(-1) : IntPtr.Zero); // top of its band when it is in front
|
|
221
|
+
// Windows refuses to order after some windows (an access error); then the next one up is tried, ending at the top of the band.
|
|
222
|
+
SetLastError(0);
|
|
223
|
+
for (int up = 0; !SetWindowPos(frm, ins, r.l, r.t, 0, 0, fl | 0x1) && ins != IntPtr.Zero && ins != (IntPtr)(-1) && up < 40; up++) ins = GetWindow(ins, 3);
|
|
224
|
+
SetWindowPos(cur, frm, cx, cy, 0, 0, fl | 0x1);
|
|
225
|
+
// A layered window shown for the first time takes its picture again.
|
|
226
|
+
if (fresh) { PT p2 = new PT(); p2.x = r.l; p2.y = r.t; SZ s2 = new SZ(); s2.cx = w; s2.cy = h; PT q2 = new PT(); BF b2 = new BF(); b2.fmt = 1; b2.a = (byte)a; UpdateLayeredWindow(frm, IntPtr.Zero, ref p2, ref s2, mem1, ref q2, 0, ref b2, 2); }
|
|
227
|
+
lastX = r.l; lastY = r.t; lastW = w; lastH = h; lastPrev = prev;
|
|
228
|
+
// A window the overlay cannot be ordered against gets no overlay at all: a frame hidden
|
|
229
|
+
// behind its window is worse than none.
|
|
230
|
+
if (!IsWindowVisible(frm) || Steps(frm, tg) < 0) { ShowWindow(frm, 0); ShowWindow(cur, 0); lastW = 0; refuseUntil = now + 500; Refused++; }
|
|
231
|
+
}
|
|
232
|
+
long us = (sw.ElapsedTicks - t0) * 1000000 / Stopwatch.Frequency;
|
|
233
|
+
Ticks++; TickUs += us; if (us > MaxTickUs) MaxTickUs = us;
|
|
234
|
+
}
|
|
235
|
+
static void DrawBorder(int w, int h, IntPtr tg) {
|
|
236
|
+
if (bmp1 != IntPtr.Zero) { SelectObject(mem1, IntPtr.Zero); DeleteObject(bmp1); DeleteDC(mem1); }
|
|
237
|
+
bmp1 = Dib(w, h, out mem1, out bits1); fw = w; fh = h; drawnFor = tg; borderDrawn = true;
|
|
238
|
+
int[] px = new int[w * h]; int g = unchecked((int)(0xFF000000 | GREEN));
|
|
239
|
+
for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
|
|
240
|
+
int d = Math.Min(Math.Min(x, w - 1 - x), Math.Min(y, h - 1 - y)); if (d >= T) { if (y >= T && y < h - T) { x = w - T - 1; } continue; }
|
|
241
|
+
int c = d / CELL; int cx = x / CELL, cy = y / CELL;
|
|
242
|
+
if (Bayer[(cy & 3) * 4 + (cx & 3)] < Dens[c] * 16) px[y * w + x] = g;
|
|
243
|
+
}
|
|
244
|
+
Marshal.Copy(px, 0, bits1, w * h); lastAlpha = -1;
|
|
245
|
+
}
|
|
246
|
+
static void Put(int[] b, int x, int y, int argb) { if (x >= 0 && y >= 0 && x < CW && y < CH) b[y * CW + x] = argb; }
|
|
247
|
+
static int Pre(int rgb, int a) {
|
|
248
|
+
int r = ((rgb >> 16) & 255) * a / 255, g = ((rgb >> 8) & 255) * a / 255, b = (rgb & 255) * a / 255;
|
|
249
|
+
return (a << 24) | (r << 16) | (g << 8) | b;
|
|
250
|
+
}
|
|
251
|
+
static void DrawCursor(long now, int x, int y, double alpha) {
|
|
252
|
+
int[] b = new int[CW * CH];
|
|
253
|
+
// Pulse: a square pixel ring that grows and fades around the tip.
|
|
254
|
+
double pu = (now - pulseAt) / 360.0;
|
|
255
|
+
if (pu >= 0 && pu < 1) {
|
|
256
|
+
int rad = (pulseKind == 2 ? 6 : 8) + (int)(pu * (pulseKind == 2 ? 14 : 22)) / 2 * 2; int a = (int)((1 - pu) * 230);
|
|
257
|
+
for (int i = -rad; i <= rad; i += 2) {
|
|
258
|
+
foreach (int[] p in new int[][] { new int[]{i,-rad}, new int[]{i,rad}, new int[]{-rad,i}, new int[]{rad,i} }) {
|
|
259
|
+
int bx = PAD + p[0], by = PAD + p[1];
|
|
260
|
+
if (Bayer[(((by / 2) & 3) * 4) + ((bx / 2) & 3)] < 11) { for (int dy = 0; dy < 2; dy++) for (int dx = 0; dx < 2; dx++) Put(b, bx + dx, by + dy, Pre(GREEN, a)); }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
for (int sy = 0; sy < Sprite.Length; sy++) for (int sx = 0; sx < Sprite[sy].Length; sx++) {
|
|
265
|
+
char c = Sprite[sy][sx]; if (c == '.') continue;
|
|
266
|
+
int col = c == '#' ? INK : GREEN;
|
|
267
|
+
for (int dy = 0; dy < S; dy++) for (int dx = 0; dx < S; dx++) Put(b, PAD + sx * S + dx, PAD + sy * S + dy, Pre(col, 255));
|
|
268
|
+
}
|
|
269
|
+
Marshal.Copy(b, 0, bits2, CW * CH);
|
|
270
|
+
PT pd = new PT(); pd.x = x; pd.y = y; SZ sz = new SZ(); sz.cx = CW; sz.cy = CH; PT ps = new PT();
|
|
271
|
+
BF bf = new BF(); bf.op = 0; bf.fl = 0; bf.a = (byte)(alpha * 255); bf.fmt = 1;
|
|
272
|
+
UpdateLayeredWindow(cur, IntPtr.Zero, ref pd, ref sz, mem2, ref ps, 0, ref bf, 2);
|
|
273
|
+
}
|
|
274
|
+
static int Steps(IntPtr from, IntPtr to) { IntPtr w = from; for (int i = 0; i < 400 && w != IntPtr.Zero; i++) { if (w == to) return i; w = GetWindow(w, 2); } return -1; }
|
|
275
|
+
public static string Info() {
|
|
276
|
+
uint a1, a2; GetWindowDisplayAffinity(frm, out a1); GetWindowDisplayAffinity(cur, out a2);
|
|
277
|
+
return "{\"frame\":\"0x" + Hwnd1.ToString("X") + "\",\"cursor\":\"0x" + Hwnd2.ToString("X") + "\",\"affinity\":[" + a1 + "," + a2 + "],\"ex\":[" + (uint)GetWindowLong(frm, -20) + "," + (uint)GetWindowLong(cur, -20) + "],\"above\":" + (Steps(frm, target) >= 0 ? "true" : "false") + ",\"fvis\":" + (IsWindowVisible(frm) ? 1 : 0) + ",\"cvis\":" + (IsWindowVisible(cur) ? 1 : 0) + ",\"lastAlpha\":" + lastAlpha + ",\"fwh\":\"" + fw + "x" + fh + " last " + lastW + "x" + lastH + " at " + lastX + "," + lastY + "\",\"owned\":" + (ownedBy == target ? "true" : "false") + ",\"refused\":" + Refused + ",\"err\":\"" + Err.Replace("\"", "'") + "\",\"ticks\":" + Ticks + ",\"avgTickUs\":" + (Ticks == 0 ? 0 : TickUs / Ticks) + ",\"maxTickUs\":" + MaxTickUs + ",\"foreground\":\"0x" + ((long)GetForegroundWindow()).ToString("X") + "\"}";
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
"@
|
|
281
|
+
$ok = [NzP]::Start()
|
|
282
|
+
function Reply($o) { [Console]::Out.WriteLine((ConvertTo-Json -InputObject $o -Compress -Depth 6)) }
|
|
283
|
+
Reply @{ ok = $ok; excluded = [NzP]::Excluded; error = [NzP]::Err }
|
|
284
|
+
if (-not $ok) { exit 1 }
|
|
285
|
+
while (($line = [Console]::In.ReadLine()) -ne $null) {
|
|
286
|
+
$cid = $null
|
|
287
|
+
try {
|
|
288
|
+
$c = $line | ConvertFrom-Json
|
|
289
|
+
$cid = $c.id
|
|
290
|
+
switch ($c.cmd) {
|
|
291
|
+
'act' {
|
|
292
|
+
$h = [Convert]::ToInt64(([string]$c.hwnd).Substring(2), 16)
|
|
293
|
+
$has = ($null -ne $c.x -and $null -ne $c.y)
|
|
294
|
+
$k = if ($c.kind -eq 'type') { 2 } elseif ($c.kind -eq 'move') { 0 } else { 1 }
|
|
295
|
+
[NzP]::Act($h, [double]$(if ($has) { $c.x } else { 0 }), [double]$(if ($has) { $c.y } else { 0 }), $has, $k)
|
|
296
|
+
$r = @{ ok = $true }
|
|
297
|
+
}
|
|
298
|
+
'hide' { [NzP]::Hide(); $r = @{ ok = $true } }
|
|
299
|
+
'info' { $r = ([NzP]::Info() | ConvertFrom-Json) }
|
|
300
|
+
'quit' { break }
|
|
301
|
+
default { $r = @{ error = 'unknown command' } }
|
|
302
|
+
}
|
|
303
|
+
if ($c.cmd -eq 'quit') { break }
|
|
304
|
+
Reply @{ ok = $true; id = $cid; r = $r }
|
|
305
|
+
} catch {
|
|
306
|
+
Reply @{ ok = $false; id = $cid; error = "$_" }
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
`
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* The script is longer than a Windows command line allows once encoded, so
|
|
313
|
+
* PowerShell is started with this short bootstrap, which reads the script as
|
|
314
|
+
* its first line of input (UTF-8, base64) and runs it; the line protocol
|
|
315
|
+
* follows on the same stream.
|
|
316
|
+
*/
|
|
317
|
+
export const PRESENCE_BOOTSTRAP =
|
|
318
|
+
'$s=[Console]::In.ReadLine();Invoke-Expression ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)))'
|
|
319
|
+
|
|
320
|
+
/** The first line to write to a helper started with {@link PRESENCE_BOOTSTRAP}. */
|
|
321
|
+
export function presenceScriptLine(script: string = PRESENCE_HELPER_SCRIPT): string {
|
|
322
|
+
return Buffer.from(script, 'utf8').toString('base64')
|
|
323
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { WindowsPresence } from './presence.js'
|
|
2
|
+
export type {
|
|
3
|
+
Presence,
|
|
4
|
+
PresenceKind,
|
|
5
|
+
PresenceMark,
|
|
6
|
+
PresenceProcess,
|
|
7
|
+
WindowsPresenceOptions,
|
|
8
|
+
} from './presence.js'
|
|
9
|
+
export { PRESENCE_ENV, createWindowsPresence, presenceDisabledByEnv } from './windows.js'
|
|
10
|
+
export type { WindowsPresenceFactoryOptions } from './windows.js'
|
|
11
|
+
export {
|
|
12
|
+
FADE_MS,
|
|
13
|
+
GLIDE_MS,
|
|
14
|
+
HOLD_MS,
|
|
15
|
+
PRESENCE_BOOTSTRAP,
|
|
16
|
+
PRESENCE_HELPER_SCRIPT,
|
|
17
|
+
} from './helper-script.js'
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { createInterface } from 'node:readline'
|
|
3
|
+
import { PRESENCE_BOOTSTRAP, presenceScriptLine } from './helper-script.js'
|
|
4
|
+
|
|
5
|
+
/** What the operated window shows: that an agent is working in it. */
|
|
6
|
+
export type PresenceKind = 'click' | 'type' | 'move'
|
|
7
|
+
|
|
8
|
+
export interface PresenceMark {
|
|
9
|
+
/** The window being operated. */
|
|
10
|
+
readonly hwnd: number
|
|
11
|
+
/** Where the action lands, in virtual-desktop pixels; absent for typing, which stays where the cursor is. */
|
|
12
|
+
readonly at?: { readonly x: number; readonly y: number }
|
|
13
|
+
readonly kind: PresenceKind
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The visible sign that an agent is operating a window: its own cursor and a
|
|
18
|
+
* border around the window. It never takes input, never changes the
|
|
19
|
+
* foreground window and is not captured by screenshots; a failure to show it
|
|
20
|
+
* never fails an action.
|
|
21
|
+
*/
|
|
22
|
+
export interface Presence {
|
|
23
|
+
/** Shows (or refreshes) the cursor and border for one action. Does not wait. */
|
|
24
|
+
mark(mark: PresenceMark): void
|
|
25
|
+
/**
|
|
26
|
+
* Starts the helper ahead of the first action, so that action already shows
|
|
27
|
+
* the overlay. Does not wait; safe to call again.
|
|
28
|
+
*/
|
|
29
|
+
warm(): void
|
|
30
|
+
/** Removes both at once: the task ended or the session stopped. */
|
|
31
|
+
hide(): void
|
|
32
|
+
dispose(): Promise<void>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The ends of a started helper; the real one is a child process. */
|
|
36
|
+
export interface PresenceProcess {
|
|
37
|
+
write(line: string): void
|
|
38
|
+
onLine(handler: (line: string) => void): void
|
|
39
|
+
onExit(handler: () => void): void
|
|
40
|
+
kill(): void
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface WindowsPresenceOptions {
|
|
44
|
+
/** Windows PowerShell, as this process starts it. */
|
|
45
|
+
readonly powershell: string
|
|
46
|
+
readonly env?: NodeJS.ProcessEnv
|
|
47
|
+
/** For tests. */
|
|
48
|
+
readonly spawnHelper?: () => PresenceProcess
|
|
49
|
+
/** Waiting for the helper to start (it compiles a small library), ms. Default 30 000. */
|
|
50
|
+
readonly startTimeoutMs?: number
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function spawnPowerShell(options: WindowsPresenceOptions): PresenceProcess {
|
|
54
|
+
const child = spawn(
|
|
55
|
+
options.powershell,
|
|
56
|
+
[
|
|
57
|
+
'-NoProfile',
|
|
58
|
+
'-NonInteractive',
|
|
59
|
+
'-ExecutionPolicy',
|
|
60
|
+
'Bypass',
|
|
61
|
+
'-EncodedCommand',
|
|
62
|
+
Buffer.from(PRESENCE_BOOTSTRAP, 'utf16le').toString('base64'),
|
|
63
|
+
],
|
|
64
|
+
{ env: options.env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
|
|
65
|
+
)
|
|
66
|
+
child.stdin.on('error', () => undefined)
|
|
67
|
+
child.on('error', () => undefined)
|
|
68
|
+
return {
|
|
69
|
+
write: (line) => {
|
|
70
|
+
child.stdin.write(`${line}\n`)
|
|
71
|
+
},
|
|
72
|
+
onLine: (handler) => createInterface({ input: child.stdout }).on('line', handler),
|
|
73
|
+
onExit: (handler) => {
|
|
74
|
+
child.once('exit', handler)
|
|
75
|
+
child.once('error', handler)
|
|
76
|
+
},
|
|
77
|
+
kill: () => {
|
|
78
|
+
try {
|
|
79
|
+
// Closing the input lets the helper close its windows and end.
|
|
80
|
+
child.stdin.end()
|
|
81
|
+
} catch {
|
|
82
|
+
// Already closed.
|
|
83
|
+
}
|
|
84
|
+
setTimeout(() => child.kill(), 2_000).unref()
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** How many times a helper that ended mid-session is started again. */
|
|
90
|
+
const MAX_RESTARTS = 3
|
|
91
|
+
|
|
92
|
+
const hex = (hwnd: number): string => `0x${hwnd.toString(16).toUpperCase()}`
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* {@link Presence} on a Windows desktop (WSL included), drawn by one
|
|
96
|
+
* long-lived PowerShell helper that starts on first use and is reused: an
|
|
97
|
+
* update is one line written to it, not a process. If the helper cannot start,
|
|
98
|
+
* or cannot keep its windows out of screen captures, nothing is shown.
|
|
99
|
+
*/
|
|
100
|
+
export class WindowsPresence implements Presence {
|
|
101
|
+
private proc: PresenceProcess | undefined
|
|
102
|
+
private starting: Promise<boolean> | undefined
|
|
103
|
+
private dead = false
|
|
104
|
+
private restarts = 0
|
|
105
|
+
private disposed = false
|
|
106
|
+
|
|
107
|
+
constructor(private readonly options: WindowsPresenceOptions) {}
|
|
108
|
+
|
|
109
|
+
/** Whether the overlay is available; false once it failed to start or exited. */
|
|
110
|
+
get available(): boolean {
|
|
111
|
+
return !this.dead && !this.disposed
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
mark(mark: PresenceMark): void {
|
|
115
|
+
if (!this.available) return
|
|
116
|
+
const line = JSON.stringify({
|
|
117
|
+
cmd: 'act',
|
|
118
|
+
hwnd: hex(mark.hwnd),
|
|
119
|
+
kind: mark.kind,
|
|
120
|
+
...(mark.at ? { x: Math.round(mark.at.x), y: Math.round(mark.at.y) } : {}),
|
|
121
|
+
})
|
|
122
|
+
void this.send(line)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
warm(): void {
|
|
126
|
+
if (this.available) void this.start()
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
hide(): void {
|
|
130
|
+
// Only a started helper has anything to hide.
|
|
131
|
+
if (this.proc && this.available) this.proc.write(JSON.stringify({ cmd: 'hide' }))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async dispose(): Promise<void> {
|
|
135
|
+
this.disposed = true
|
|
136
|
+
const proc = this.proc
|
|
137
|
+
this.proc = undefined
|
|
138
|
+
proc?.kill()
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private async send(line: string): Promise<void> {
|
|
142
|
+
const ready = await this.start()
|
|
143
|
+
if (ready && this.proc && this.available) this.proc.write(line)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
private start(): Promise<boolean> {
|
|
147
|
+
this.starting ??= new Promise<boolean>((resolve) => {
|
|
148
|
+
let proc: PresenceProcess
|
|
149
|
+
try {
|
|
150
|
+
proc = (this.options.spawnHelper ?? (() => spawnPowerShell(this.options)))()
|
|
151
|
+
} catch {
|
|
152
|
+
this.dead = true
|
|
153
|
+
resolve(false)
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
this.proc = proc
|
|
157
|
+
let greeted = false
|
|
158
|
+
const fail = (): void => {
|
|
159
|
+
this.dead = true
|
|
160
|
+
resolve(false)
|
|
161
|
+
proc.kill()
|
|
162
|
+
}
|
|
163
|
+
const timer = setTimeout(fail, this.options.startTimeoutMs ?? 30_000)
|
|
164
|
+
timer.unref()
|
|
165
|
+
proc.onExit(() => {
|
|
166
|
+
clearTimeout(timer)
|
|
167
|
+
// A helper that was running and ended (it crashed, or its host closed it) is
|
|
168
|
+
// started again by the next action, a few times; one that never came up stays off.
|
|
169
|
+
if (greeted && this.proc === proc && !this.disposed && this.restarts < MAX_RESTARTS) {
|
|
170
|
+
this.restarts++
|
|
171
|
+
this.proc = undefined
|
|
172
|
+
this.starting = undefined
|
|
173
|
+
} else this.dead = true
|
|
174
|
+
resolve(false)
|
|
175
|
+
})
|
|
176
|
+
proc.onLine((line) => {
|
|
177
|
+
if (greeted) return
|
|
178
|
+
greeted = true
|
|
179
|
+
clearTimeout(timer)
|
|
180
|
+
let hello: { ok?: boolean; excluded?: boolean }
|
|
181
|
+
try {
|
|
182
|
+
hello = JSON.parse(line) as { ok?: boolean; excluded?: boolean }
|
|
183
|
+
} catch {
|
|
184
|
+
fail()
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
// Without capture exclusion the overlay could land in a screenshot: show nothing.
|
|
188
|
+
if (hello.ok !== true || hello.excluded !== true) fail()
|
|
189
|
+
else resolve(true)
|
|
190
|
+
})
|
|
191
|
+
proc.write(presenceScriptLine())
|
|
192
|
+
})
|
|
193
|
+
return this.starting
|
|
194
|
+
}
|
|
195
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type WslProbes,
|
|
3
|
+
isWsl,
|
|
4
|
+
realWslProbes,
|
|
5
|
+
wslChildEnv,
|
|
6
|
+
wslPowerShellPath,
|
|
7
|
+
} from '../adapters/wsl.js'
|
|
8
|
+
import { type Presence, WindowsPresence } from './presence.js'
|
|
9
|
+
|
|
10
|
+
/** Variable names never handed to a helper process. */
|
|
11
|
+
const SECRET_NAME = /(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i
|
|
12
|
+
|
|
13
|
+
/** The environment variable that turns the presence overlay off (`off`, `0`, `false`, `no`). */
|
|
14
|
+
export const PRESENCE_ENV = 'NAMZU_COMPUTER_USE_PRESENCE'
|
|
15
|
+
|
|
16
|
+
export interface WindowsPresenceFactoryOptions {
|
|
17
|
+
readonly env?: NodeJS.ProcessEnv
|
|
18
|
+
readonly platform?: NodeJS.Platform
|
|
19
|
+
readonly wslProbes?: WslProbes
|
|
20
|
+
/** Default true. `false` shows nothing, whatever the environment says. */
|
|
21
|
+
readonly enabled?: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Whether the environment asks for the overlay to be off. */
|
|
25
|
+
export function presenceDisabledByEnv(env: NodeJS.ProcessEnv): boolean {
|
|
26
|
+
const value = env[PRESENCE_ENV]
|
|
27
|
+
return value !== undefined && /^(off|0|false|no|none)$/i.test(value.trim())
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The presence overlay for this machine's Windows desktop (WSL included), or
|
|
32
|
+
* undefined when it is turned off or there is no Windows PowerShell to run it in.
|
|
33
|
+
*/
|
|
34
|
+
export function createWindowsPresence(
|
|
35
|
+
options: WindowsPresenceFactoryOptions = {},
|
|
36
|
+
): Presence | undefined {
|
|
37
|
+
const env = options.env ?? process.env
|
|
38
|
+
if (options.enabled === false || presenceDisabledByEnv(env)) return undefined
|
|
39
|
+
const platform = options.platform ?? process.platform
|
|
40
|
+
const probes = options.wslProbes ?? realWslProbes
|
|
41
|
+
const wsl = isWsl(env, platform, probes)
|
|
42
|
+
const powershell = wsl
|
|
43
|
+
? wslPowerShellPath(probes)
|
|
44
|
+
: platform === 'win32'
|
|
45
|
+
? 'powershell.exe'
|
|
46
|
+
: undefined
|
|
47
|
+
if (!powershell) return undefined
|
|
48
|
+
const clean: NodeJS.ProcessEnv = {}
|
|
49
|
+
for (const [name, value] of Object.entries(env)) if (!SECRET_NAME.test(name)) clean[name] = value
|
|
50
|
+
return new WindowsPresence({
|
|
51
|
+
powershell,
|
|
52
|
+
env: wsl ? wslChildEnv(clean, [], probes) : clean,
|
|
53
|
+
})
|
|
54
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* A request was cancelled by its caller. `sent` tells whether it had been
|
|
5
|
+
* written to the desktop driver: when it had, the driver may still act on it,
|
|
6
|
+
* and the caller must not assume it did not.
|
|
7
|
+
*/
|
|
8
|
+
export class CallAbortedError extends Error {
|
|
9
|
+
override readonly name = 'CallAbortedError'
|
|
10
|
+
|
|
11
|
+
constructor(
|
|
12
|
+
readonly method: string,
|
|
13
|
+
readonly sent: boolean,
|
|
14
|
+
) {
|
|
15
|
+
super(
|
|
16
|
+
sent
|
|
17
|
+
? `${method} was cancelled after it was sent; the driver may still have acted on it.`
|
|
18
|
+
: `${method} was cancelled before it was sent.`,
|
|
19
|
+
)
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** What the tool call being served shares with every driver call made for it. */
|
|
24
|
+
export interface CallScope {
|
|
25
|
+
readonly signal: AbortSignal | undefined
|
|
26
|
+
/** Something that changes the desktop was sent for this call (or may have been). */
|
|
27
|
+
sent: boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const scope = new AsyncLocalStorage<CallScope>()
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Runs `run` as one tool call. Its `signal` reaches every driver call and
|
|
34
|
+
* foreground burst made on its behalf without each internal helper taking a
|
|
35
|
+
* parameter, and the scope records whether anything was sent.
|
|
36
|
+
*/
|
|
37
|
+
export function inCallScope<T>(
|
|
38
|
+
signal: AbortSignal | undefined,
|
|
39
|
+
run: (scope: CallScope) => Promise<T>,
|
|
40
|
+
): Promise<T> {
|
|
41
|
+
const own: CallScope = { signal, sent: false }
|
|
42
|
+
return scope.run(own, () => run(own))
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The signal of the call being served, when it has one. */
|
|
46
|
+
export function currentCallSignal(): AbortSignal | undefined {
|
|
47
|
+
return scope.getStore()?.signal
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Records that the call being served sent (or may have sent) something that changes the desktop. */
|
|
51
|
+
export function markSent(): void {
|
|
52
|
+
const own = scope.getStore()
|
|
53
|
+
if (own) own.sent = true
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Waits for `work`, but no longer than the call being served lives: when its
|
|
58
|
+
* signal aborts first, rejects with `CallAbortedError` (nothing was sent). The
|
|
59
|
+
* work itself is left to finish on its own.
|
|
60
|
+
*/
|
|
61
|
+
export function abortable<T>(name: string, work: Promise<T>): Promise<T> {
|
|
62
|
+
const signal = currentCallSignal()
|
|
63
|
+
if (!signal) return work
|
|
64
|
+
if (signal.aborted) {
|
|
65
|
+
work.catch(() => undefined)
|
|
66
|
+
return Promise.reject(new CallAbortedError(name, false))
|
|
67
|
+
}
|
|
68
|
+
return new Promise<T>((resolve, reject) => {
|
|
69
|
+
const onAbort = (): void => reject(new CallAbortedError(name, false))
|
|
70
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
71
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener('abort', onAbort))
|
|
72
|
+
})
|
|
73
|
+
}
|