@namzu/computer-use 3.1.0 → 4.0.0

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.
Files changed (121) hide show
  1. package/CHANGELOG.md +58 -1
  2. package/dist/SubprocessComputerUseHost.d.ts +57 -9
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +213 -46
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/adapters/cua-driver/adapter.d.ts +171 -10
  7. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  8. package/dist/adapters/cua-driver/adapter.js +1476 -161
  9. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  10. package/dist/adapters/cua-driver/client.d.ts +16 -0
  11. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  12. package/dist/adapters/cua-driver/client.js +54 -5
  13. package/dist/adapters/cua-driver/client.js.map +1 -1
  14. package/dist/adapters/cua-driver/escalation.d.ts +67 -0
  15. package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
  16. package/dist/adapters/cua-driver/escalation.js +82 -0
  17. package/dist/adapters/cua-driver/escalation.js.map +1 -0
  18. package/dist/adapters/cua-driver/keys.d.ts +5 -0
  19. package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
  20. package/dist/adapters/cua-driver/keys.js +23 -0
  21. package/dist/adapters/cua-driver/keys.js.map +1 -1
  22. package/dist/adapters/cua-driver/observe.d.ts +99 -0
  23. package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
  24. package/dist/adapters/cua-driver/observe.js +227 -0
  25. package/dist/adapters/cua-driver/observe.js.map +1 -0
  26. package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
  27. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  28. package/dist/adapters/cua-driver/ui-tree.js +142 -14
  29. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  30. package/dist/adapters/types.d.ts +3 -3
  31. package/dist/adapters/types.d.ts.map +1 -1
  32. package/dist/adapters/types.js.map +1 -1
  33. package/dist/adapters/win32.d.ts +10 -0
  34. package/dist/adapters/win32.d.ts.map +1 -1
  35. package/dist/adapters/win32.js +12 -2
  36. package/dist/adapters/win32.js.map +1 -1
  37. package/dist/errors.d.ts +19 -0
  38. package/dist/errors.d.ts.map +1 -1
  39. package/dist/errors.js +26 -0
  40. package/dist/errors.js.map +1 -1
  41. package/dist/foreground/guard.d.ts +31 -0
  42. package/dist/foreground/guard.d.ts.map +1 -0
  43. package/dist/foreground/guard.js +156 -0
  44. package/dist/foreground/guard.js.map +1 -0
  45. package/dist/foreground/index.d.ts +11 -0
  46. package/dist/foreground/index.d.ts.map +1 -0
  47. package/dist/foreground/index.js +7 -0
  48. package/dist/foreground/index.js.map +1 -0
  49. package/dist/foreground/ladder.d.ts +143 -0
  50. package/dist/foreground/ladder.d.ts.map +1 -0
  51. package/dist/foreground/ladder.js +505 -0
  52. package/dist/foreground/ladder.js.map +1 -0
  53. package/dist/foreground/lease.d.ts +69 -0
  54. package/dist/foreground/lease.d.ts.map +1 -0
  55. package/dist/foreground/lease.js +182 -0
  56. package/dist/foreground/lease.js.map +1 -0
  57. package/dist/foreground/types.d.ts +287 -0
  58. package/dist/foreground/types.d.ts.map +1 -0
  59. package/dist/foreground/types.js +32 -0
  60. package/dist/foreground/types.js.map +1 -0
  61. package/dist/foreground/windows-helper-script.d.ts +19 -0
  62. package/dist/foreground/windows-helper-script.d.ts.map +1 -0
  63. package/dist/foreground/windows-helper-script.js +472 -0
  64. package/dist/foreground/windows-helper-script.js.map +1 -0
  65. package/dist/foreground/windows-monitor.d.ts +75 -0
  66. package/dist/foreground/windows-monitor.d.ts.map +1 -0
  67. package/dist/foreground/windows-monitor.js +216 -0
  68. package/dist/foreground/windows-monitor.js.map +1 -0
  69. package/dist/foreground/windows.d.ts +21 -0
  70. package/dist/foreground/windows.d.ts.map +1 -0
  71. package/dist/foreground/windows.js +54 -0
  72. package/dist/foreground/windows.js.map +1 -0
  73. package/dist/index.d.ts +6 -1
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +3 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/presence/helper-script.d.ts +39 -0
  78. package/dist/presence/helper-script.d.ts.map +1 -0
  79. package/dist/presence/helper-script.js +320 -0
  80. package/dist/presence/helper-script.js.map +1 -0
  81. package/dist/presence/index.d.ts +6 -0
  82. package/dist/presence/index.d.ts.map +1 -0
  83. package/dist/presence/index.js +4 -0
  84. package/dist/presence/index.js.map +1 -0
  85. package/dist/presence/presence.d.ts +70 -0
  86. package/dist/presence/presence.d.ts.map +1 -0
  87. package/dist/presence/presence.js +147 -0
  88. package/dist/presence/presence.js.map +1 -0
  89. package/dist/presence/windows.d.ts +19 -0
  90. package/dist/presence/windows.d.ts.map +1 -0
  91. package/dist/presence/windows.js +39 -0
  92. package/dist/presence/windows.js.map +1 -0
  93. package/dist/util/call-scope.d.ts +34 -0
  94. package/dist/util/call-scope.d.ts.map +1 -0
  95. package/dist/util/call-scope.js +58 -0
  96. package/dist/util/call-scope.js.map +1 -0
  97. package/package.json +2 -2
  98. package/src/SubprocessComputerUseHost.ts +287 -45
  99. package/src/adapters/cua-driver/adapter.ts +1751 -175
  100. package/src/adapters/cua-driver/client.ts +59 -2
  101. package/src/adapters/cua-driver/escalation.ts +137 -0
  102. package/src/adapters/cua-driver/keys.ts +20 -0
  103. package/src/adapters/cua-driver/observe.ts +310 -0
  104. package/src/adapters/cua-driver/ui-tree.ts +219 -15
  105. package/src/adapters/types.ts +7 -2
  106. package/src/adapters/win32.ts +26 -3
  107. package/src/errors.ts +32 -0
  108. package/src/foreground/guard.ts +182 -0
  109. package/src/foreground/index.ts +45 -0
  110. package/src/foreground/ladder.ts +616 -0
  111. package/src/foreground/lease.ts +232 -0
  112. package/src/foreground/types.ts +318 -0
  113. package/src/foreground/windows-helper-script.ts +471 -0
  114. package/src/foreground/windows-monitor.ts +288 -0
  115. package/src/foreground/windows.ts +73 -0
  116. package/src/index.ts +15 -1
  117. package/src/presence/helper-script.ts +323 -0
  118. package/src/presence/index.ts +17 -0
  119. package/src/presence/presence.ts +195 -0
  120. package/src/presence/windows.ts +54 -0
  121. package/src/util/call-scope.ts +73 -0
@@ -0,0 +1,320 @@
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
+ export const PRESENCE_HELPER_SCRIPT = String.raw `
30
+ $ErrorActionPreference = 'Stop'
31
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
32
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
33
+ Add-Type -TypeDefinition @"
34
+ using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading;
35
+ public static class NzP {
36
+ [StructLayout(LayoutKind.Sequential)] struct PT { public int x; public int y; }
37
+ [StructLayout(LayoutKind.Sequential)] struct SZ { public int cx; public int cy; }
38
+ [StructLayout(LayoutKind.Sequential)] struct RC { public int l; public int t; public int r; public int b; }
39
+ [StructLayout(LayoutKind.Sequential)] struct BF { public byte op; public byte fl; public byte a; public byte fmt; }
40
+ [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; }
41
+ [StructLayout(LayoutKind.Sequential)] struct MSG { public IntPtr h; public uint m; public IntPtr w; public IntPtr l; public uint t; public PT p; }
42
+ [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; }
43
+ delegate IntPtr WP(IntPtr h, uint m, IntPtr w, IntPtr l);
44
+ [DllImport("user32.dll", CharSet=CharSet.Unicode)] static extern ushort RegisterClassEx(ref WC c);
45
+ [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);
46
+ [DllImport("user32.dll")] static extern IntPtr DefWindowProc(IntPtr h, uint m, IntPtr w, IntPtr l);
47
+ [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);
48
+ [DllImport("user32.dll", SetLastError=true)] static extern bool SetWindowPos(IntPtr h, IntPtr after, int x, int y, int w, int cy, uint fl);
49
+ [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr h, uint c);
50
+ [DllImport("user32.dll")] static extern bool IsWindow(IntPtr h);
51
+ [DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);
52
+ [DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
53
+ [DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int c);
54
+ [DllImport("user32.dll", SetLastError=true)] static extern bool SetWindowDisplayAffinity(IntPtr h, uint a);
55
+ [DllImport("user32.dll")] static extern bool GetWindowDisplayAffinity(IntPtr h, out uint a);
56
+ [DllImport("user32.dll")] static extern UIntPtr SetTimer(IntPtr h, UIntPtr id, uint ms, IntPtr f);
57
+ [DllImport("user32.dll")] static extern bool KillTimer(IntPtr h, UIntPtr id);
58
+ [DllImport("user32.dll")] static extern bool PostMessage(IntPtr h, uint m, IntPtr w, IntPtr l);
59
+ [DllImport("user32.dll")] static extern int GetMessage(out MSG m, IntPtr h, uint a, uint b);
60
+ [DllImport("user32.dll")] static extern IntPtr DispatchMessage(ref MSG m);
61
+ [DllImport("user32.dll")] static extern int SetWindowLong(IntPtr h, int i, int v);
62
+ [DllImport("user32.dll", EntryPoint="SetWindowLongPtrW", SetLastError=true)] static extern IntPtr SetWindowLongPtr64(IntPtr h, int i, IntPtr v);
63
+ [DllImport("user32.dll", EntryPoint="SetWindowLongW", SetLastError=true)] static extern int SetWindowLongPtr32(IntPtr h, int i, int v);
64
+ [DllImport("user32.dll")] static extern int GetWindowLong(IntPtr h, int i);
65
+ [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr h);
66
+ [DllImport("user32.dll")] static extern int ReleaseDC(IntPtr h, IntPtr dc);
67
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
68
+ [DllImport("gdi32.dll")] static extern IntPtr CreateCompatibleDC(IntPtr dc);
69
+ [DllImport("gdi32.dll")] static extern IntPtr CreateDIBSection(IntPtr dc, ref BMI bmi, uint u, out IntPtr bits, IntPtr sec, uint off);
70
+ [DllImport("gdi32.dll")] static extern IntPtr SelectObject(IntPtr dc, IntPtr o);
71
+ [DllImport("gdi32.dll")] static extern bool DeleteObject(IntPtr o);
72
+ [DllImport("gdi32.dll")] static extern bool DeleteDC(IntPtr dc);
73
+ [DllImport("dwmapi.dll")] static extern int DwmGetWindowAttribute(IntPtr h, int a, out RC r, int n);
74
+ [DllImport("user32.dll")] static extern IntPtr SetThreadDpiAwarenessContext(IntPtr c);
75
+ [DllImport("kernel32.dll")] static extern void SetLastError(uint e);
76
+ [DllImport("kernel32.dll")] static extern IntPtr GetModuleHandle(string n);
77
+
78
+ const uint EX = 0x20 | 0x08000000 | 0x80;
79
+ static readonly string[] Sprite = {
80
+ "#...........","##..........","#g#.........","#gg#........","#ggg#.......","#gggg#......","#ggggg#.....","#gggggg#....","#ggggggg#...",
81
+ "#gggggggg#..","#ggggg#####.","#gg#gg#.....","#g#.#gg#....","##..#gg#....","#....#gg#...",".....#gg#...","......##...."
82
+ };
83
+ static readonly int[] Bayer = { 0,8,2,10, 12,4,14,6, 3,11,1,9, 15,7,13,5 };
84
+ const int S = 3, PAD = 36, CW = 100, CH = 110, T = 8, CELL = 2;
85
+ static readonly double[] Dens = { 1.0, 0.62, 0.38, 0.16 };
86
+ const int GREEN = 0x5fff5f, INK = 0x0b0f0c;
87
+
88
+ static IntPtr frm, cur, mem1, mem2, bmp1, bmp2, bits1, bits2; static WP proc;
89
+ static int fw, fh, lastX, lastY, lastW, lastH; static IntPtr lastPrev;
90
+ public static long Hwnd1, Hwnd2; public static bool Excluded, Ready; public static string Err = "";
91
+ static ManualResetEvent ready = new ManualResetEvent(false);
92
+ static object gate = new object();
93
+ // Command state (written by the reader thread, read by the UI thread).
94
+ static IntPtr target; static double ax, ay; static bool hasPoint; static int kind; static long actTick; static bool hidden = true;
95
+ // Animation state (UI thread only).
96
+ static double rx, ry, fx, fy, tx, ty; static long glideAt = -1000; static long pulseAt = -10000; static int pulseKind; static bool placed;
97
+ static int lastAlpha = -1; static bool borderDrawn; static IntPtr drawnFor;
98
+ public static long Ticks, TickUs, MaxTickUs; static Stopwatch sw = Stopwatch.StartNew();
99
+ static bool timerOn; static long refuseUntil; public static int Refused;
100
+ public static int GlideMs = ${GLIDE_MS}, HoldMs = ${HOLD_MS}, FadeMs = ${FADE_MS};
101
+
102
+ static long Now() { return sw.ElapsedMilliseconds; }
103
+ static IntPtr Wnd(IntPtr h, uint m, IntPtr w, IntPtr l) {
104
+ if (m == 0x113) { try { Tick(); } catch (Exception e) { Err = e.Message; } return IntPtr.Zero; }
105
+ if (m == 0x8000) { try { Tick(); } catch (Exception e) { Err = e.Message; } return IntPtr.Zero; }
106
+ return DefWindowProc(h, m, w, l);
107
+ }
108
+ static IntPtr Make(string cls, ref uint aff) {
109
+ IntPtr h = CreateWindowEx(EX, cls, "", 0x80000000, 0, 0, 1, 1, IntPtr.Zero, IntPtr.Zero, GetModuleHandle(null), IntPtr.Zero);
110
+ if (h == IntPtr.Zero) throw new Exception("CreateWindowEx " + Marshal.GetLastWin32Error());
111
+ // Windows refuses the exclusion on a window that is already layered, so it is
112
+ // set first and the layered style added after; the setting survives.
113
+ bool set = SetWindowDisplayAffinity(h, 0x11); int le = Marshal.GetLastWin32Error();
114
+ SetWindowLong(h, -20, GetWindowLong(h, -20) | 0x80000);
115
+ if (!set) throw new Exception("capture exclusion unavailable " + le);
116
+ uint a; GetWindowDisplayAffinity(h, out a); aff = a;
117
+ return h;
118
+ }
119
+ static IntPtr Dib(int w, int h, out IntPtr mem, out IntPtr bits) {
120
+ IntPtr sd = GetDC(IntPtr.Zero); mem = CreateCompatibleDC(sd);
121
+ BMI b = new BMI(); b.size = 40; b.w = w; b.h = -h; b.planes = 1; b.bits = 32;
122
+ IntPtr bm = CreateDIBSection(sd, ref b, 0, out bits, IntPtr.Zero, 0); ReleaseDC(IntPtr.Zero, sd);
123
+ SelectObject(mem, bm); return bm;
124
+ }
125
+ public static bool Start() {
126
+ var t = new Thread(() => {
127
+ try {
128
+ // Physical pixels: the frame bounds come from the window manager in physical units, and a
129
+ // DPI-unaware thread would have them scaled again on a display set above 100%.
130
+ try { SetThreadDpiAwarenessContext((IntPtr)(-4)); } catch (Exception) { }
131
+ 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";
132
+ RegisterClassEx(ref c);
133
+ uint a1 = 0, a2 = 0;
134
+ frm = Make("NzPresence", ref a1); cur = Make("NzPresence", ref a2);
135
+ Hwnd1 = (long)frm; Hwnd2 = (long)cur; Excluded = a1 == 0x11 && a2 == 0x11;
136
+ if (!Excluded) throw new Exception("capture exclusion not applied");
137
+ bmp2 = Dib(CW, CH, out mem2, out bits2);
138
+ Ready = true; ready.Set();
139
+ MSG m; while (GetMessage(out m, IntPtr.Zero, 0, 0) > 0) { DispatchMessage(ref m); }
140
+ } catch (Exception e) { Err = e.Message; ready.Set(); }
141
+ });
142
+ t.IsBackground = true; t.SetApartmentState(ApartmentState.STA); t.Start();
143
+ ready.WaitOne(10000); return Ready;
144
+ }
145
+ // Called from the reader thread.
146
+ public static void Act(long hwnd, double x, double y, bool point, int k) {
147
+ lock (gate) {
148
+ IntPtr h = (IntPtr)hwnd; if (h != target) { target = h; placed = false; borderDrawn = false; }
149
+ hasPoint = point; ax = x; ay = y; kind = k; actTick = Now(); hidden = false; pending = true;
150
+ }
151
+ PostMessage(frm, 0x8000, IntPtr.Zero, IntPtr.Zero);
152
+ }
153
+ static bool pending;
154
+ public static void Hide() { lock (gate) { hidden = true; pending = true; } PostMessage(frm, 0x8000, IntPtr.Zero, IntPtr.Zero); }
155
+ static void HideNow() {
156
+ ShowWindow(frm, 0); ShowWindow(cur, 0); lastW = 0; lastH = 0; lastPrev = IntPtr.Zero; lastAlpha = -1;
157
+ if (timerOn) { KillTimer(frm, (UIntPtr)1); timerOn = false; }
158
+ }
159
+ // 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.
160
+ static bool Own(IntPtr w, IntPtr owner) {
161
+ SetLastError(0);
162
+ long r = IntPtr.Size == 8 ? (long)SetWindowLongPtr64(w, -8, owner) : SetWindowLongPtr32(w, -8, (int)owner);
163
+ return r != 0 || Marshal.GetLastWin32Error() == 0;
164
+ }
165
+ static IntPtr ownedBy;
166
+ // A window without a frame rectangle (a hidden application window) covers nothing.
167
+ 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; }
168
+ static bool Rect(IntPtr h, out RC r) { return DwmGetWindowAttribute(h, 9, out r, 16) == 0 && r.r > r.l && r.b > r.t; }
169
+ static void Tick() {
170
+ long t0 = sw.ElapsedTicks; IntPtr tg; bool hid, hp, ch; double px, py; int k; long at;
171
+ lock (gate) { tg = target; hid = hidden; hp = hasPoint; px = ax; py = ay; k = kind; at = actTick; ch = pending; pending = false; }
172
+ if (hid || tg == IntPtr.Zero || !IsWindow(tg) || IsIconic(tg) || !IsWindowVisible(tg)) { HideNow(); return; }
173
+ RC r; if (!Rect(tg, out r)) { HideNow(); return; }
174
+ long now = Now(); int w = r.r - r.l, h = r.b - r.t;
175
+ double age = now - at, alpha = 1.0;
176
+ if (age > HoldMs) alpha = 1.0 - (age - HoldMs) / FadeMs;
177
+ if (alpha <= 0) { lock (gate) { hidden = true; } HideNow(); return; }
178
+ if (now < refuseUntil) return;
179
+ if (!timerOn) { SetTimer(frm, (UIntPtr)1, 16, IntPtr.Zero); timerOn = true; }
180
+ if (ch && hp) {
181
+ // New action point in window coordinates: relative to the window's rectangle.
182
+ 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; }
183
+ } else if (ch) {
184
+ if (k != 0) { pulseAt = now; pulseKind = k; }
185
+ if (!placed) { tx = w / 2.0; ty = h / 2.0; fx = tx; fy = ty; rx = tx; ry = ty; placed = true; glideAt = -1000; }
186
+ }
187
+ if (placed) {
188
+ double u = (now - glideAt) / (double)GlideMs; if (u > 1) u = 1; if (u < 0) u = 0;
189
+ double e = 1 - Math.Pow(1 - u, 3); rx = fx + (tx - fx) * e; ry = fy + (ty - fy) * e;
190
+ }
191
+ // z-order: directly above the operated window, never above others.
192
+ IntPtr prev = GetWindow(tg, 3);
193
+ // Windows that are not shown (input-method helpers and the like) sit in bands of their own: ordering against them has no effect.
194
+ // A window that does not overlap the operated one cannot hide it, so ordering against it is not needed.
195
+ // 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.
196
+ 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);
197
+ // 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.
198
+ bool moved = r.l != lastX || r.t != lastY || w != lastW || h != lastH || prev != lastPrev || Steps(frm, tg) < 0;
199
+ bool fresh = lastW == 0;
200
+ if (w != fw || h != fh || !borderDrawn || drawnFor != tg) DrawBorder(w, h, tg);
201
+ int a = (int)(alpha * 255);
202
+ if (moved || fresh || a != lastAlpha) {
203
+ 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();
204
+ BF bf = new BF(); bf.op = 0; bf.fl = 0; bf.a = (byte)a; bf.fmt = 1;
205
+ UpdateLayeredWindow(frm, IntPtr.Zero, ref pd, ref sz, mem1, ref ps, 0, ref bf, 2);
206
+ lastAlpha = a;
207
+ }
208
+ // The cursor window follows the glide; its sprite tip sits at the window's (PAD,PAD).
209
+ double sx = r.l + rx, sy = r.t + ry;
210
+ 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;
211
+ DrawCursor(now, (int)Math.Round(sx) - PAD, (int)Math.Round(sy) - PAD, alpha);
212
+ uint fl = 0x10 | 0x40; // NOACTIVATE | SHOWWINDOW
213
+ if (ownedBy != tg) { ownedBy = Own(frm, tg) && Own(cur, tg) ? tg : IntPtr.Zero; moved = true; }
214
+ if (moved || fresh) {
215
+ int cx = (int)Math.Round(sx) - PAD, cy = (int)Math.Round(sy) - PAD;
216
+ // Ownership keeps an owned window above its owner only when it is raised; it does not reorder
217
+ // windows already stacked above the owner (a target created after the overlay), so the order is
218
+ // set explicitly: right above the operated window, never above others.
219
+ IntPtr ins = prev != IntPtr.Zero ? prev : ((GetWindowLong(tg, -20) & 8) != 0 ? (IntPtr)(-1) : IntPtr.Zero); // top of its band when it is in front
220
+ // Windows refuses to order after some windows (an access error); then the next one up is tried, ending at the top of the band.
221
+ SetLastError(0);
222
+ 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);
223
+ SetWindowPos(cur, frm, cx, cy, 0, 0, fl | 0x1);
224
+ // A layered window shown for the first time takes its picture again.
225
+ 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); }
226
+ lastX = r.l; lastY = r.t; lastW = w; lastH = h; lastPrev = prev;
227
+ // A window the overlay cannot be ordered against gets no overlay at all: a frame hidden
228
+ // behind its window is worse than none.
229
+ if (!IsWindowVisible(frm) || Steps(frm, tg) < 0) { ShowWindow(frm, 0); ShowWindow(cur, 0); lastW = 0; refuseUntil = now + 500; Refused++; }
230
+ }
231
+ long us = (sw.ElapsedTicks - t0) * 1000000 / Stopwatch.Frequency;
232
+ Ticks++; TickUs += us; if (us > MaxTickUs) MaxTickUs = us;
233
+ }
234
+ static void DrawBorder(int w, int h, IntPtr tg) {
235
+ if (bmp1 != IntPtr.Zero) { SelectObject(mem1, IntPtr.Zero); DeleteObject(bmp1); DeleteDC(mem1); }
236
+ bmp1 = Dib(w, h, out mem1, out bits1); fw = w; fh = h; drawnFor = tg; borderDrawn = true;
237
+ int[] px = new int[w * h]; int g = unchecked((int)(0xFF000000 | GREEN));
238
+ for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) {
239
+ 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; }
240
+ int c = d / CELL; int cx = x / CELL, cy = y / CELL;
241
+ if (Bayer[(cy & 3) * 4 + (cx & 3)] < Dens[c] * 16) px[y * w + x] = g;
242
+ }
243
+ Marshal.Copy(px, 0, bits1, w * h); lastAlpha = -1;
244
+ }
245
+ 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; }
246
+ static int Pre(int rgb, int a) {
247
+ int r = ((rgb >> 16) & 255) * a / 255, g = ((rgb >> 8) & 255) * a / 255, b = (rgb & 255) * a / 255;
248
+ return (a << 24) | (r << 16) | (g << 8) | b;
249
+ }
250
+ static void DrawCursor(long now, int x, int y, double alpha) {
251
+ int[] b = new int[CW * CH];
252
+ // Pulse: a square pixel ring that grows and fades around the tip.
253
+ double pu = (now - pulseAt) / 360.0;
254
+ if (pu >= 0 && pu < 1) {
255
+ int rad = (pulseKind == 2 ? 6 : 8) + (int)(pu * (pulseKind == 2 ? 14 : 22)) / 2 * 2; int a = (int)((1 - pu) * 230);
256
+ for (int i = -rad; i <= rad; i += 2) {
257
+ foreach (int[] p in new int[][] { new int[]{i,-rad}, new int[]{i,rad}, new int[]{-rad,i}, new int[]{rad,i} }) {
258
+ int bx = PAD + p[0], by = PAD + p[1];
259
+ 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)); }
260
+ }
261
+ }
262
+ }
263
+ for (int sy = 0; sy < Sprite.Length; sy++) for (int sx = 0; sx < Sprite[sy].Length; sx++) {
264
+ char c = Sprite[sy][sx]; if (c == '.') continue;
265
+ int col = c == '#' ? INK : GREEN;
266
+ 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));
267
+ }
268
+ Marshal.Copy(b, 0, bits2, CW * CH);
269
+ PT pd = new PT(); pd.x = x; pd.y = y; SZ sz = new SZ(); sz.cx = CW; sz.cy = CH; PT ps = new PT();
270
+ BF bf = new BF(); bf.op = 0; bf.fl = 0; bf.a = (byte)(alpha * 255); bf.fmt = 1;
271
+ UpdateLayeredWindow(cur, IntPtr.Zero, ref pd, ref sz, mem2, ref ps, 0, ref bf, 2);
272
+ }
273
+ 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; }
274
+ public static string Info() {
275
+ uint a1, a2; GetWindowDisplayAffinity(frm, out a1); GetWindowDisplayAffinity(cur, out a2);
276
+ 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") + "\"}";
277
+ }
278
+ }
279
+ "@
280
+ $ok = [NzP]::Start()
281
+ function Reply($o) { [Console]::Out.WriteLine((ConvertTo-Json -InputObject $o -Compress -Depth 6)) }
282
+ Reply @{ ok = $ok; excluded = [NzP]::Excluded; error = [NzP]::Err }
283
+ if (-not $ok) { exit 1 }
284
+ while (($line = [Console]::In.ReadLine()) -ne $null) {
285
+ $cid = $null
286
+ try {
287
+ $c = $line | ConvertFrom-Json
288
+ $cid = $c.id
289
+ switch ($c.cmd) {
290
+ 'act' {
291
+ $h = [Convert]::ToInt64(([string]$c.hwnd).Substring(2), 16)
292
+ $has = ($null -ne $c.x -and $null -ne $c.y)
293
+ $k = if ($c.kind -eq 'type') { 2 } elseif ($c.kind -eq 'move') { 0 } else { 1 }
294
+ [NzP]::Act($h, [double]$(if ($has) { $c.x } else { 0 }), [double]$(if ($has) { $c.y } else { 0 }), $has, $k)
295
+ $r = @{ ok = $true }
296
+ }
297
+ 'hide' { [NzP]::Hide(); $r = @{ ok = $true } }
298
+ 'info' { $r = ([NzP]::Info() | ConvertFrom-Json) }
299
+ 'quit' { break }
300
+ default { $r = @{ error = 'unknown command' } }
301
+ }
302
+ if ($c.cmd -eq 'quit') { break }
303
+ Reply @{ ok = $true; id = $cid; r = $r }
304
+ } catch {
305
+ Reply @{ ok = $false; id = $cid; error = "$_" }
306
+ }
307
+ }
308
+ `;
309
+ /**
310
+ * The script is longer than a Windows command line allows once encoded, so
311
+ * PowerShell is started with this short bootstrap, which reads the script as
312
+ * its first line of input (UTF-8, base64) and runs it; the line protocol
313
+ * follows on the same stream.
314
+ */
315
+ export const PRESENCE_BOOTSTRAP = '$s=[Console]::In.ReadLine();Invoke-Expression ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)))';
316
+ /** The first line to write to a helper started with {@link PRESENCE_BOOTSTRAP}. */
317
+ export function presenceScriptLine(script = PRESENCE_HELPER_SCRIPT) {
318
+ return Buffer.from(script, 'utf8').toString('base64');
319
+ }
320
+ //# sourceMappingURL=helper-script.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helper-script.js","sourceRoot":"","sources":["../../src/presence/helper-script.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,GAAG,CAAA;AAC3B,4EAA4E;AAC5E,MAAM,CAAC,MAAM,OAAO,GAAG,KAAK,CAAA;AAC5B,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,CAAA;AAE1B,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;+BAuEjB,QAAQ,cAAc,OAAO,cAAc,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgNhF,CAAA;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAC9B,kHAAkH,CAAA;AAEnH,mFAAmF;AACnF,MAAM,UAAU,kBAAkB,CAAC,SAAiB,sBAAsB;IACzE,OAAO,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;AACtD,CAAC"}
@@ -0,0 +1,6 @@
1
+ export { WindowsPresence } from './presence.js';
2
+ export type { Presence, PresenceKind, PresenceMark, PresenceProcess, WindowsPresenceOptions, } from './presence.js';
3
+ export { PRESENCE_ENV, createWindowsPresence, presenceDisabledByEnv } from './windows.js';
4
+ export type { WindowsPresenceFactoryOptions } from './windows.js';
5
+ export { FADE_MS, GLIDE_MS, HOLD_MS, PRESENCE_BOOTSTRAP, PRESENCE_HELPER_SCRIPT, } from './helper-script.js';
6
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/presence/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC/C,YAAY,EACX,QAAQ,EACR,YAAY,EACZ,YAAY,EACZ,eAAe,EACf,sBAAsB,GACtB,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AACzF,YAAY,EAAE,6BAA6B,EAAE,MAAM,cAAc,CAAA;AACjE,OAAO,EACN,OAAO,EACP,QAAQ,EACR,OAAO,EACP,kBAAkB,EAClB,sBAAsB,GACtB,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,4 @@
1
+ export { WindowsPresence } from './presence.js';
2
+ export { PRESENCE_ENV, createWindowsPresence, presenceDisabledByEnv } from './windows.js';
3
+ export { FADE_MS, GLIDE_MS, HOLD_MS, PRESENCE_BOOTSTRAP, PRESENCE_HELPER_SCRIPT, } from './helper-script.js';
4
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/presence/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAQ/C,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAA;AAEzF,OAAO,EACN,OAAO,EACP,QAAQ,EACR,OAAO,EACP,kBAAkB,EAClB,sBAAsB,GACtB,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1,70 @@
1
+ /** What the operated window shows: that an agent is working in it. */
2
+ export type PresenceKind = 'click' | 'type' | 'move';
3
+ export interface PresenceMark {
4
+ /** The window being operated. */
5
+ readonly hwnd: number;
6
+ /** Where the action lands, in virtual-desktop pixels; absent for typing, which stays where the cursor is. */
7
+ readonly at?: {
8
+ readonly x: number;
9
+ readonly y: number;
10
+ };
11
+ readonly kind: PresenceKind;
12
+ }
13
+ /**
14
+ * The visible sign that an agent is operating a window: its own cursor and a
15
+ * border around the window. It never takes input, never changes the
16
+ * foreground window and is not captured by screenshots; a failure to show it
17
+ * never fails an action.
18
+ */
19
+ export interface Presence {
20
+ /** Shows (or refreshes) the cursor and border for one action. Does not wait. */
21
+ mark(mark: PresenceMark): void;
22
+ /**
23
+ * Starts the helper ahead of the first action, so that action already shows
24
+ * the overlay. Does not wait; safe to call again.
25
+ */
26
+ warm(): void;
27
+ /** Removes both at once: the task ended or the session stopped. */
28
+ hide(): void;
29
+ dispose(): Promise<void>;
30
+ }
31
+ /** The ends of a started helper; the real one is a child process. */
32
+ export interface PresenceProcess {
33
+ write(line: string): void;
34
+ onLine(handler: (line: string) => void): void;
35
+ onExit(handler: () => void): void;
36
+ kill(): void;
37
+ }
38
+ export interface WindowsPresenceOptions {
39
+ /** Windows PowerShell, as this process starts it. */
40
+ readonly powershell: string;
41
+ readonly env?: NodeJS.ProcessEnv;
42
+ /** For tests. */
43
+ readonly spawnHelper?: () => PresenceProcess;
44
+ /** Waiting for the helper to start (it compiles a small library), ms. Default 30 000. */
45
+ readonly startTimeoutMs?: number;
46
+ }
47
+ /**
48
+ * {@link Presence} on a Windows desktop (WSL included), drawn by one
49
+ * long-lived PowerShell helper that starts on first use and is reused: an
50
+ * update is one line written to it, not a process. If the helper cannot start,
51
+ * or cannot keep its windows out of screen captures, nothing is shown.
52
+ */
53
+ export declare class WindowsPresence implements Presence {
54
+ private readonly options;
55
+ private proc;
56
+ private starting;
57
+ private dead;
58
+ private restarts;
59
+ private disposed;
60
+ constructor(options: WindowsPresenceOptions);
61
+ /** Whether the overlay is available; false once it failed to start or exited. */
62
+ get available(): boolean;
63
+ mark(mark: PresenceMark): void;
64
+ warm(): void;
65
+ hide(): void;
66
+ dispose(): Promise<void>;
67
+ private send;
68
+ private start;
69
+ }
70
+ //# sourceMappingURL=presence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.d.ts","sourceRoot":"","sources":["../../src/presence/presence.ts"],"names":[],"mappings":"AAIA,sEAAsE;AACtE,MAAM,MAAM,YAAY,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,CAAA;AAEpD,MAAM,WAAW,YAAY;IAC5B,iCAAiC;IACjC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,6GAA6G;IAC7G,QAAQ,CAAC,EAAE,CAAC,EAAE;QAAE,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IACxD,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAA;CAC3B;AAED;;;;;GAKG;AACH,MAAM,WAAW,QAAQ;IACxB,gFAAgF;IAChF,IAAI,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAAA;IAC9B;;;OAGG;IACH,IAAI,IAAI,IAAI,CAAA;IACZ,mEAAmE;IACnE,IAAI,IAAI,IAAI,CAAA;IACZ,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAA;CACxB;AAED,qEAAqE;AACrE,MAAM,WAAW,eAAe;IAC/B,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,MAAM,CAAC,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAAG,IAAI,CAAA;IAC7C,MAAM,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI,CAAA;IACjC,IAAI,IAAI,IAAI,CAAA;CACZ;AAED,MAAM,WAAW,sBAAsB;IACtC,qDAAqD;IACrD,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAA;IAChC,iBAAiB;IACjB,QAAQ,CAAC,WAAW,CAAC,EAAE,MAAM,eAAe,CAAA;IAC5C,yFAAyF;IACzF,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CAChC;AA2CD;;;;;GAKG;AACH,qBAAa,eAAgB,YAAW,QAAQ;IAOnC,OAAO,CAAC,QAAQ,CAAC,OAAO;IANpC,OAAO,CAAC,IAAI,CAA6B;IACzC,OAAO,CAAC,QAAQ,CAA8B;IAC9C,OAAO,CAAC,IAAI,CAAQ;IACpB,OAAO,CAAC,QAAQ,CAAI;IACpB,OAAO,CAAC,QAAQ,CAAQ;gBAEK,OAAO,EAAE,sBAAsB;IAE5D,iFAAiF;IACjF,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI;IAW9B,IAAI,IAAI,IAAI;IAIZ,IAAI,IAAI,IAAI;IAKN,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;YAOhB,IAAI;IAKlB,OAAO,CAAC,KAAK;CAiDb"}
@@ -0,0 +1,147 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createInterface } from 'node:readline';
3
+ import { PRESENCE_BOOTSTRAP, presenceScriptLine } from './helper-script.js';
4
+ function spawnPowerShell(options) {
5
+ const child = spawn(options.powershell, [
6
+ '-NoProfile',
7
+ '-NonInteractive',
8
+ '-ExecutionPolicy',
9
+ 'Bypass',
10
+ '-EncodedCommand',
11
+ Buffer.from(PRESENCE_BOOTSTRAP, 'utf16le').toString('base64'),
12
+ ], { env: options.env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
13
+ child.stdin.on('error', () => undefined);
14
+ child.on('error', () => undefined);
15
+ return {
16
+ write: (line) => {
17
+ child.stdin.write(`${line}\n`);
18
+ },
19
+ onLine: (handler) => createInterface({ input: child.stdout }).on('line', handler),
20
+ onExit: (handler) => {
21
+ child.once('exit', handler);
22
+ child.once('error', handler);
23
+ },
24
+ kill: () => {
25
+ try {
26
+ // Closing the input lets the helper close its windows and end.
27
+ child.stdin.end();
28
+ }
29
+ catch {
30
+ // Already closed.
31
+ }
32
+ setTimeout(() => child.kill(), 2_000).unref();
33
+ },
34
+ };
35
+ }
36
+ /** How many times a helper that ended mid-session is started again. */
37
+ const MAX_RESTARTS = 3;
38
+ const hex = (hwnd) => `0x${hwnd.toString(16).toUpperCase()}`;
39
+ /**
40
+ * {@link Presence} on a Windows desktop (WSL included), drawn by one
41
+ * long-lived PowerShell helper that starts on first use and is reused: an
42
+ * update is one line written to it, not a process. If the helper cannot start,
43
+ * or cannot keep its windows out of screen captures, nothing is shown.
44
+ */
45
+ export class WindowsPresence {
46
+ options;
47
+ proc;
48
+ starting;
49
+ dead = false;
50
+ restarts = 0;
51
+ disposed = false;
52
+ constructor(options) {
53
+ this.options = options;
54
+ }
55
+ /** Whether the overlay is available; false once it failed to start or exited. */
56
+ get available() {
57
+ return !this.dead && !this.disposed;
58
+ }
59
+ mark(mark) {
60
+ if (!this.available)
61
+ return;
62
+ const line = JSON.stringify({
63
+ cmd: 'act',
64
+ hwnd: hex(mark.hwnd),
65
+ kind: mark.kind,
66
+ ...(mark.at ? { x: Math.round(mark.at.x), y: Math.round(mark.at.y) } : {}),
67
+ });
68
+ void this.send(line);
69
+ }
70
+ warm() {
71
+ if (this.available)
72
+ void this.start();
73
+ }
74
+ hide() {
75
+ // Only a started helper has anything to hide.
76
+ if (this.proc && this.available)
77
+ this.proc.write(JSON.stringify({ cmd: 'hide' }));
78
+ }
79
+ async dispose() {
80
+ this.disposed = true;
81
+ const proc = this.proc;
82
+ this.proc = undefined;
83
+ proc?.kill();
84
+ }
85
+ async send(line) {
86
+ const ready = await this.start();
87
+ if (ready && this.proc && this.available)
88
+ this.proc.write(line);
89
+ }
90
+ start() {
91
+ this.starting ??= new Promise((resolve) => {
92
+ let proc;
93
+ try {
94
+ proc = (this.options.spawnHelper ?? (() => spawnPowerShell(this.options)))();
95
+ }
96
+ catch {
97
+ this.dead = true;
98
+ resolve(false);
99
+ return;
100
+ }
101
+ this.proc = proc;
102
+ let greeted = false;
103
+ const fail = () => {
104
+ this.dead = true;
105
+ resolve(false);
106
+ proc.kill();
107
+ };
108
+ const timer = setTimeout(fail, this.options.startTimeoutMs ?? 30_000);
109
+ timer.unref();
110
+ proc.onExit(() => {
111
+ clearTimeout(timer);
112
+ // A helper that was running and ended (it crashed, or its host closed it) is
113
+ // started again by the next action, a few times; one that never came up stays off.
114
+ if (greeted && this.proc === proc && !this.disposed && this.restarts < MAX_RESTARTS) {
115
+ this.restarts++;
116
+ this.proc = undefined;
117
+ this.starting = undefined;
118
+ }
119
+ else
120
+ this.dead = true;
121
+ resolve(false);
122
+ });
123
+ proc.onLine((line) => {
124
+ if (greeted)
125
+ return;
126
+ greeted = true;
127
+ clearTimeout(timer);
128
+ let hello;
129
+ try {
130
+ hello = JSON.parse(line);
131
+ }
132
+ catch {
133
+ fail();
134
+ return;
135
+ }
136
+ // Without capture exclusion the overlay could land in a screenshot: show nothing.
137
+ if (hello.ok !== true || hello.excluded !== true)
138
+ fail();
139
+ else
140
+ resolve(true);
141
+ });
142
+ proc.write(presenceScriptLine());
143
+ });
144
+ return this.starting;
145
+ }
146
+ }
147
+ //# sourceMappingURL=presence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"presence.js","sourceRoot":"","sources":["../../src/presence/presence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC/C,OAAO,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAA;AAkD3E,SAAS,eAAe,CAAC,OAA+B;IACvD,MAAM,KAAK,GAAG,KAAK,CAClB,OAAO,CAAC,UAAU,EAClB;QACC,YAAY;QACZ,iBAAiB;QACjB,kBAAkB;QAClB,QAAQ;QACR,iBAAiB;QACjB,MAAM,CAAC,IAAI,CAAC,kBAAkB,EAAE,SAAS,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,19 @@
1
+ import { type WslProbes } from '../adapters/wsl.js';
2
+ import { type Presence } from './presence.js';
3
+ /** The environment variable that turns the presence overlay off (`off`, `0`, `false`, `no`). */
4
+ export declare const PRESENCE_ENV = "NAMZU_COMPUTER_USE_PRESENCE";
5
+ export interface WindowsPresenceFactoryOptions {
6
+ readonly env?: NodeJS.ProcessEnv;
7
+ readonly platform?: NodeJS.Platform;
8
+ readonly wslProbes?: WslProbes;
9
+ /** Default true. `false` shows nothing, whatever the environment says. */
10
+ readonly enabled?: boolean;
11
+ }
12
+ /** Whether the environment asks for the overlay to be off. */
13
+ export declare function presenceDisabledByEnv(env: NodeJS.ProcessEnv): boolean;
14
+ /**
15
+ * The presence overlay for this machine's Windows desktop (WSL included), or
16
+ * undefined when it is turned off or there is no Windows PowerShell to run it in.
17
+ */
18
+ export declare function createWindowsPresence(options?: WindowsPresenceFactoryOptions): Presence | undefined;
19
+ //# sourceMappingURL=windows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"windows.d.ts","sourceRoot":"","sources":["../../src/presence/windows.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,SAAS,EAKd,MAAM,oBAAoB,CAAA;AAC3B,OAAO,EAAE,KAAK,QAAQ,EAAmB,MAAM,eAAe,CAAA;AAK9D,gGAAgG;AAChG,eAAO,MAAM,YAAY,gCAAgC,CAAA;AAEzD,MAAM,WAAW,6BAA6B;IAC7C,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAA;IAChC,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC,QAAQ,CAAA;IACnC,QAAQ,CAAC,SAAS,CAAC,EAAE,SAAS,CAAA;IAC9B,0EAA0E;IAC1E,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,8DAA8D;AAC9D,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,OAAO,CAGrE;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACpC,OAAO,GAAE,6BAAkC,GACzC,QAAQ,GAAG,SAAS,CAkBtB"}
@@ -0,0 +1,39 @@
1
+ import { isWsl, realWslProbes, wslChildEnv, wslPowerShellPath, } from '../adapters/wsl.js';
2
+ import { WindowsPresence } from './presence.js';
3
+ /** Variable names never handed to a helper process. */
4
+ const SECRET_NAME = /(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i;
5
+ /** The environment variable that turns the presence overlay off (`off`, `0`, `false`, `no`). */
6
+ export const PRESENCE_ENV = 'NAMZU_COMPUTER_USE_PRESENCE';
7
+ /** Whether the environment asks for the overlay to be off. */
8
+ export function presenceDisabledByEnv(env) {
9
+ const value = env[PRESENCE_ENV];
10
+ return value !== undefined && /^(off|0|false|no|none)$/i.test(value.trim());
11
+ }
12
+ /**
13
+ * The presence overlay for this machine's Windows desktop (WSL included), or
14
+ * undefined when it is turned off or there is no Windows PowerShell to run it in.
15
+ */
16
+ export function createWindowsPresence(options = {}) {
17
+ const env = options.env ?? process.env;
18
+ if (options.enabled === false || presenceDisabledByEnv(env))
19
+ return undefined;
20
+ const platform = options.platform ?? process.platform;
21
+ const probes = options.wslProbes ?? realWslProbes;
22
+ const wsl = isWsl(env, platform, probes);
23
+ const powershell = wsl
24
+ ? wslPowerShellPath(probes)
25
+ : platform === 'win32'
26
+ ? 'powershell.exe'
27
+ : undefined;
28
+ if (!powershell)
29
+ return undefined;
30
+ const clean = {};
31
+ for (const [name, value] of Object.entries(env))
32
+ if (!SECRET_NAME.test(name))
33
+ clean[name] = value;
34
+ return new WindowsPresence({
35
+ powershell,
36
+ env: wsl ? wslChildEnv(clean, [], probes) : clean,
37
+ });
38
+ }
39
+ //# sourceMappingURL=windows.js.map