cortico-world-agent-speed 0.2.0 → 0.2.2

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 (189) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +0 -14
  3. package/README.md +29 -11
  4. package/THIRD_PARTY_NOTICES.md +69 -0
  5. package/activity.d.ts +15 -0
  6. package/activity.js +88 -3
  7. package/describe.json +806 -0
  8. package/dist/webui.css +2 -0
  9. package/dist/webui.css.map +7 -0
  10. package/dist/webui.js +2 -0
  11. package/dist/webui.js.map +7 -0
  12. package/host/app-store.cjs +68 -0
  13. package/host/cursor.cjs +67 -0
  14. package/host/electron-main.cjs +666 -0
  15. package/host/input-shape.cjs +63 -0
  16. package/host/mouse-lease.cjs +77 -0
  17. package/host/overlay.cjs +139 -0
  18. package/host/portrait.cjs +52 -0
  19. package/host/preload.cjs +60 -14
  20. package/host/renderer-gone.cjs +24 -0
  21. package/host/windows.cjs +251 -0
  22. package/package.json +27 -7
  23. package/scripts/build-webui.mjs +40 -0
  24. package/scripts/speech-bank/build.py +166 -0
  25. package/scripts/speech-bank/dicts.py +76 -0
  26. package/src/ENV_PROMPT.en.md +51 -0
  27. package/src/ENV_PROMPT.md +51 -0
  28. package/src/asr/address.ts +25 -0
  29. package/src/asr/hotkey.ts +335 -0
  30. package/src/asr/result.ts +51 -0
  31. package/src/asr/segmenter.ts +269 -0
  32. package/src/asr/sherpa.ts +280 -0
  33. package/src/asr/simplify.ts +38 -0
  34. package/src/asr/system-recognizer.ts +292 -0
  35. package/src/asr/system-sapi.ps1 +173 -0
  36. package/src/asr/transcription-api.ts +176 -0
  37. package/src/chat.ts +212 -0
  38. package/src/config.ts +481 -0
  39. package/src/cua/ENV_PROMPT.en.md +29 -0
  40. package/src/cua/ENV_PROMPT.md +29 -0
  41. package/src/cua/config.ts +88 -0
  42. package/src/cua/cua.ts +712 -0
  43. package/src/cua/engine/darwin.ts +410 -0
  44. package/src/cua/engine/display.ts +55 -0
  45. package/src/cua/engine/fail.ts +15 -0
  46. package/src/cua/engine/foreground.ts +8 -0
  47. package/src/cua/engine/image.ts +57 -0
  48. package/src/cua/engine/keys.ts +70 -0
  49. package/src/cua/engine/linux-keys.ts +29 -0
  50. package/src/cua/engine/linux.ts +343 -0
  51. package/src/cua/engine/mac-keys.ts +57 -0
  52. package/src/cua/engine/user-activity.ts +54 -0
  53. package/src/cua/engine/wait-idle.ts +31 -0
  54. package/src/cua/engine/win32.ts +299 -0
  55. package/src/cua/engine-child.ts +274 -0
  56. package/src/cua/engine-ipc.ts +140 -0
  57. package/src/cua/i18n/de.ts +53 -0
  58. package/src/cua/i18n/en.ts +63 -0
  59. package/src/cua/i18n/es-419.ts +53 -0
  60. package/src/cua/i18n/fr.ts +53 -0
  61. package/src/cua/i18n/index.ts +26 -0
  62. package/src/cua/i18n/it.ts +53 -0
  63. package/src/cua/i18n/ja.ts +53 -0
  64. package/src/cua/i18n/ko.ts +53 -0
  65. package/src/cua/i18n/pt-BR.ts +53 -0
  66. package/src/cua/i18n/ru.ts +59 -0
  67. package/src/cua/i18n/zh-Hant.ts +53 -0
  68. package/src/cua/i18n/zh.ts +59 -0
  69. package/src/cua/model-text.ts +252 -0
  70. package/src/cua/terminal.ts +31 -0
  71. package/src/cua/tools.ts +153 -0
  72. package/src/definition.ts +146 -0
  73. package/src/host-reason.ts +32 -0
  74. package/src/i18n/de.ts +409 -0
  75. package/src/i18n/en.ts +443 -0
  76. package/src/i18n/es-419.ts +409 -0
  77. package/src/i18n/fr.ts +409 -0
  78. package/src/i18n/index.ts +56 -0
  79. package/src/i18n/it.ts +409 -0
  80. package/src/i18n/ja.ts +409 -0
  81. package/src/i18n/ko.ts +409 -0
  82. package/src/i18n/pt-BR.ts +409 -0
  83. package/src/i18n/ru.ts +415 -0
  84. package/src/i18n/zh-Hant.ts +409 -0
  85. package/src/i18n/zh.ts +440 -0
  86. package/src/index.ts +15 -0
  87. package/src/model-text.ts +344 -0
  88. package/src/moves.ts +101 -0
  89. package/src/pack-import.ts +361 -0
  90. package/src/packs.ts +449 -0
  91. package/src/runtime/download.ts +29 -0
  92. package/src/runtime/store.ts +293 -0
  93. package/src/script.ts +202 -0
  94. package/src/self.ts +247 -0
  95. package/src/server.ts +479 -0
  96. package/src/speech/data/CMUDICT-LICENSE +33 -0
  97. package/src/speech/data/IPADIC-COPYING +71 -0
  98. package/src/speech/data/UNICODE-LICENSE +39 -0
  99. package/src/speech/data/en.tsv.gz +0 -0
  100. package/src/speech/data/ja-ipadic.tsv.gz +0 -0
  101. package/src/speech/data/ja-unihan.tsv.gz +0 -0
  102. package/src/speech/data/zh.json +1 -0
  103. package/src/speech/index.ts +204 -0
  104. package/src/speech/ipa.ts +83 -0
  105. package/src/speech/japanese.ts +105 -0
  106. package/src/speech/jukujikun.ts +22 -0
  107. package/src/speech/korean.ts +35 -0
  108. package/src/speech/lang.ts +151 -0
  109. package/src/speech/rules.ts +72 -0
  110. package/src/speech/syllable.ts +76 -0
  111. package/src/status.ts +164 -0
  112. package/src/tools.ts +110 -0
  113. package/src/webui/api-rows.css +2 -0
  114. package/src/webui/api-rows.ts +44 -0
  115. package/src/webui/client.ts +451 -0
  116. package/src/webui/dress-dialog.css +14 -0
  117. package/src/webui/dress-dialog.ts +117 -0
  118. package/src/webui/dress-panel.ts +160 -0
  119. package/src/webui/key-capture.ts +60 -0
  120. package/src/webui/shared/modal.css +13 -0
  121. package/src/webui/shared/modal.ts +77 -0
  122. package/src/webui/shared/problem.css +15 -0
  123. package/src/webui/shared/problem.ts +217 -0
  124. package/src/webui/shared/strings.ts +5 -0
  125. package/src/webui/style.css +50 -0
  126. package/src/window-host.ts +116 -0
  127. package/src/world.ts +2926 -0
  128. package/web/activity-motion.js +117 -0
  129. package/web/appearance.js +60 -0
  130. package/web/body-host.js +257 -0
  131. package/web/coo/coo.js +384 -0
  132. package/web/coo/figure.js +15 -0
  133. package/web/coo/figure.json +1224 -0
  134. package/web/dist/dress-dialog.css +1 -0
  135. package/web/dist/dress-dialog.js +1 -0
  136. package/web/drag-row.js +49 -0
  137. package/web/drag.js +149 -0
  138. package/web/dress.css +170 -0
  139. package/web/dress.html +37 -0
  140. package/web/dress.js +786 -0
  141. package/web/figure-frame.html +16 -0
  142. package/web/figure-frame.js +128 -0
  143. package/web/frame-loop.js +55 -0
  144. package/web/hints.js +77 -0
  145. package/web/i18n/de.js +170 -0
  146. package/web/i18n/en.js +177 -0
  147. package/web/i18n/es-419.js +170 -0
  148. package/web/i18n/fr.js +170 -0
  149. package/web/i18n/it.js +170 -0
  150. package/web/i18n/ja.js +170 -0
  151. package/web/i18n/ko.js +170 -0
  152. package/web/i18n/pt-BR.js +170 -0
  153. package/web/i18n/ru.js +170 -0
  154. package/web/i18n/zh-Hant.js +170 -0
  155. package/web/i18n/zh.js +175 -0
  156. package/web/i18n.js +54 -0
  157. package/{renderer/vendor → web}/kit/body.js +31 -58
  158. package/web/looks.js +70 -0
  159. package/web/mic-worklet.js +36 -0
  160. package/web/mic.js +117 -0
  161. package/web/motion-frames.js +80 -0
  162. package/web/motion-level.js +40 -0
  163. package/web/new-year-2027.svg +238 -0
  164. package/web/overlay.html +16 -0
  165. package/web/overlay.js +100 -0
  166. package/web/pet-app.js +3000 -0
  167. package/web/pet.css +642 -0
  168. package/web/pet.html +21 -0
  169. package/web/scale-slider.js +259 -0
  170. package/web/show-hide.js +49 -0
  171. package/web/sound.js +245 -0
  172. package/web/speech/zh.json +1 -0
  173. package/web/speech/zh.ogg +0 -0
  174. package/web/speech.js +197 -0
  175. package/web/stage.js +160 -0
  176. package/web/swap-motion.js +119 -0
  177. package/web/ui.js +195 -0
  178. package/host/launch.js +0 -187
  179. package/host/library.cjs +0 -638
  180. package/host/main.cjs +0 -389
  181. package/index.js +0 -93
  182. package/renderer/index.html +0 -22
  183. package/renderer/pet-sandbox.html +0 -11
  184. package/renderer/pet.css +0 -38
  185. package/renderer/pet.js +0 -251
  186. package/renderer/vendor/activity-motion.js +0 -101
  187. package/renderer/vendor/figure-frame.js +0 -115
  188. package/renderer/vendor/pack.css +0 -2
  189. /package/{renderer/vendor → web}/kit/rig.js +0 -0
@@ -0,0 +1,343 @@
1
+ /**
2
+ * Linux (X11) access, the same surface as `win32.ts`: screen capture with XGetImage on the root
3
+ * window (where the X server has no picture of the screen, as a rootless XWayland under GNOME or
4
+ * WSLg, a screenshot tool: grim, spectacle, scrot or ImageMagick's import), mouse and keyboard through the XTest extension, the window list and the active window
5
+ * from the window manager's EWMH properties, the idle time from the MIT-SCREEN-SAVER extension,
6
+ * `xdotool` for typing text and raising a window, and `zenity` for the yes/no dialog.
7
+ *
8
+ * X11 coordinates are physical pixels of the whole screen; XRandR names the displays in it (without
9
+ * libXrandr the whole screen is one display). Under a Wayland session this runs
10
+ * through XWayland and sees only X11 clients; a session without an X server (no DISPLAY) is not
11
+ * supported. This module runs only inside the engine child.
12
+ */
13
+ import koffi from 'koffi';
14
+ import jpeg from 'jpeg-js';
15
+ import { execFile, execFileSync } from 'node:child_process';
16
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
17
+ import { tmpdir } from 'node:os';
18
+ import { join } from 'node:path';
19
+ import { linuxKeysym, zenityAnswer } from './linux-keys.ts';
20
+ import { EngineFailure } from './fail.ts';
21
+ import { crop, type NativeDisplay } from './display.ts';
22
+ import type { ForegroundWindow } from './foreground.ts';
23
+
24
+ const x11 = koffi.load('libX11.so.6');
25
+ const xtst = koffi.load('libXtst.so.6');
26
+ const xrandr = (() => { try { return koffi.load('libXrandr.so.2'); } catch { return null; } })();
27
+ const xss = (() => { try { return koffi.load('libXss.so.1'); } catch { return null; } })();
28
+
29
+ const XImage = koffi.struct('XImage', {
30
+ width: 'int', height: 'int', xoffset: 'int', format: 'int', data: 'void *',
31
+ byte_order: 'int', bitmap_unit: 'int', bitmap_bit_order: 'int', bitmap_pad: 'int', depth: 'int',
32
+ bytes_per_line: 'int', bits_per_pixel: 'int', red_mask: 'unsigned long', green_mask: 'unsigned long', blue_mask: 'unsigned long',
33
+ obdata: 'void *', f: koffi.array('void *', 6),
34
+ });
35
+ const XRRMonitorInfo = koffi.struct('XRRMonitorInfo', {
36
+ name: 'unsigned long', primary: 'int', automatic: 'int', noutput: 'int',
37
+ x: 'int', y: 'int', width: 'int', height: 'int', mwidth: 'int', mheight: 'int', outputs: 'void *',
38
+ });
39
+ const XScreenSaverInfo = koffi.struct('XScreenSaverInfo', {
40
+ window: 'unsigned long', state: 'int', kind: 'int', til_or_since: 'unsigned long', idle: 'unsigned long', eventMask: 'unsigned long',
41
+ });
42
+
43
+ const XOpenDisplay = x11.func('void *XOpenDisplay(const char *name)');
44
+ const XDefaultRootWindow = x11.func('unsigned long XDefaultRootWindow(void *dpy)');
45
+ const XDefaultScreen = x11.func('int XDefaultScreen(void *dpy)');
46
+ const XDisplayWidth = x11.func('int XDisplayWidth(void *dpy, int screen)');
47
+ const XDisplayHeight = x11.func('int XDisplayHeight(void *dpy, int screen)');
48
+ const XGetImage = x11.func('XImage *XGetImage(void *dpy, unsigned long d, int x, int y, unsigned int w, unsigned int h, unsigned long planes, int format)');
49
+ const XDestroyImage = x11.func('int XDestroyImage(XImage *img)');
50
+ const XQueryPointer = x11.func('int XQueryPointer(void *dpy, unsigned long w, _Out_ unsigned long *root, _Out_ unsigned long *child, _Out_ int *rx, _Out_ int *ry, _Out_ int *wx, _Out_ int *wy, _Out_ unsigned int *mask)');
51
+ const XFlush = x11.func('int XFlush(void *dpy)');
52
+ const XSync = x11.func('int XSync(void *dpy, int discard)');
53
+ const XKeysymToKeycode = x11.func('uint8_t XKeysymToKeycode(void *dpy, unsigned long keysym)');
54
+ const XInternAtom = x11.func('unsigned long XInternAtom(void *dpy, const char *name, int onlyIfExists)');
55
+ const XGetWindowProperty = x11.func('int XGetWindowProperty(void *dpy, unsigned long w, unsigned long prop, long offset, long length, int del, unsigned long type, _Out_ unsigned long *actualType, _Out_ int *actualFormat, _Out_ unsigned long *nitems, _Out_ unsigned long *after, _Out_ void **data)');
56
+ const XFree = x11.func('int XFree(void *data)');
57
+ const XGetGeometry = x11.func('int XGetGeometry(void *dpy, unsigned long d, _Out_ unsigned long *root, _Out_ int *x, _Out_ int *y, _Out_ unsigned int *w, _Out_ unsigned int *h, _Out_ unsigned int *border, _Out_ unsigned int *depth)');
58
+ const XTranslateCoordinates = x11.func('int XTranslateCoordinates(void *dpy, unsigned long src, unsigned long dst, int x, int y, _Out_ int *dx, _Out_ int *dy, _Out_ unsigned long *child)');
59
+ const XErrorHandler = koffi.proto('int XErrorHandler(void *dpy, void *event)');
60
+ const XSetErrorHandler = x11.func('void *XSetErrorHandler(XErrorHandler *handler)');
61
+ const XTestFakeMotionEvent = xtst.func('int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay)');
62
+ const XTestFakeButtonEvent = xtst.func('int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay)');
63
+ const XTestFakeKeyEvent = xtst.func('int XTestFakeKeyEvent(void *dpy, unsigned int keycode, int press, unsigned long delay)');
64
+ const XRRGetMonitors = xrandr?.func('void *XRRGetMonitors(void *dpy, unsigned long window, int getActive, _Out_ int *count)') ?? null;
65
+ const XRRFreeMonitors = xrandr?.func('void XRRFreeMonitors(void *monitors)') ?? null;
66
+ const XScreenSaverQueryExtension = xss?.func('int XScreenSaverQueryExtension(void *dpy, _Out_ int *event, _Out_ int *error)') ?? null;
67
+ const XScreenSaverQueryInfo = xss?.func('int XScreenSaverQueryInfo(void *dpy, unsigned long d, _Out_ XScreenSaverInfo *info)') ?? null;
68
+
69
+ const ZPIXMAP = 2, ALL_PLANES = 0xffffffff;
70
+ const BUTTON: Record<Button, number> = { left: 1, middle: 2, right: 3 };
71
+
72
+ const dpy = XOpenDisplay(null);
73
+ if (!dpy) throw new EngineFailure('x11Display');
74
+ // a window closing between listing it and reading it raises BadWindow; Xlib's default handler would exit the process
75
+ XSetErrorHandler(koffi.register(() => 0, koffi.pointer(XErrorHandler)));
76
+ const root = XDefaultRootWindow(dpy);
77
+ const screen = XDefaultScreen(dpy);
78
+ const hasIdle = !!XScreenSaverQueryExtension && !!XScreenSaverQueryExtension(dpy, [0], [0]);
79
+ const t0 = Date.now();
80
+
81
+ export interface Rect { x: number; y: number; width: number; height: number }
82
+
83
+ function screenSize(): { width: number; height: number } {
84
+ return { width: XDisplayWidth(dpy, screen), height: XDisplayHeight(dpy, screen) };
85
+ }
86
+
87
+ /** The monitors XRandR reports, named by their position; the whole screen when it reports none. */
88
+ export function displays(): NativeDisplay[] {
89
+ const count = [0];
90
+ const ptr = XRRGetMonitors?.(dpy, root, 1, count) ?? null;
91
+ if (ptr && count[0] > 0) {
92
+ try {
93
+ const list = koffi.decode(ptr, koffi.array(XRRMonitorInfo, count[0])) as Array<{ primary: number; x: number; y: number; width: number; height: number }>;
94
+ return list.map((m) => ({ id: `${m.x},${m.y}`, primary: m.primary !== 0, x: m.x, y: m.y, width: m.width, height: m.height, scale: 1 }));
95
+ } finally {
96
+ XRRFreeMonitors?.(ptr);
97
+ }
98
+ }
99
+ const { width, height } = screenSize();
100
+ return [{ id: 'screen', primary: true, x: 0, y: 0, width, height, scale: 1 }];
101
+ }
102
+
103
+ /** Screenshot tools that write a JPEG, tried in order when the X server cannot give the picture. */
104
+ const TOOLS: Array<[string, (file: string) => string[]]> = [
105
+ ['grim', (f) => ['-t', 'jpeg', f]],
106
+ ['spectacle', (f) => ['-b', '-n', '-f', '-o', f]],
107
+ ['scrot', (f) => ['-o', f]],
108
+ ['import', (f) => ['-window', 'root', f]],
109
+ ];
110
+
111
+ /** The whole screen from a screenshot tool. */
112
+ function captureWithTool(): { width: number; height: number; bgra: Uint8Array } {
113
+ const dir = mkdtempSync(join(tmpdir(), 'cua-shot-'));
114
+ const file = join(dir, 'screen.jpg');
115
+ try {
116
+ for (const [cmd, args] of TOOLS) {
117
+ try { execFileSync(cmd, args(file), { stdio: 'ignore', timeout: 15_000 }); } catch { continue; }
118
+ const img = jpeg.decode(readFileSync(file), { useTArray: true, formatAsRGBA: true, maxMemoryUsageInMB: 1024 });
119
+ const bgra = Buffer.from(img.data.buffer, img.data.byteOffset, img.data.byteLength);
120
+ for (let i = 0; i < bgra.length; i += 4) { const r = bgra[i]!; bgra[i] = bgra[i + 2]!; bgra[i + 2] = r; }
121
+ return { width: img.width, height: img.height, bgra };
122
+ }
123
+ } finally {
124
+ rmSync(dir, { recursive: true, force: true });
125
+ }
126
+ throw new EngineFailure('linuxNoScreenshot');
127
+ }
128
+
129
+ /** Display `d` as top-down BGRA. */
130
+ export function capture(d: NativeDisplay): { width: number; height: number; bgra: Uint8Array } {
131
+ const { width, height } = d;
132
+ const ptr = XGetImage(dpy, root, d.x, d.y, width, height, ALL_PLANES, ZPIXMAP);
133
+ if (!ptr) {
134
+ const whole = captureWithTool();
135
+ const full = screenSize();
136
+ // a tool that captured at another size (a scaled Wayland output) is returned whole
137
+ if (whole.width !== full.width || whole.height !== full.height) return whole;
138
+ return { width, height, bgra: crop(whole.bgra, whole.width, d.x, d.y, width, height) };
139
+ }
140
+ try {
141
+ const img = koffi.decode(ptr, XImage) as { data: unknown; bytes_per_line: number; bits_per_pixel: number; byte_order: number };
142
+ if (img.bits_per_pixel !== 32 || img.byte_order !== 0) throw new EngineFailure('linuxPixelFormat', [img.bits_per_pixel]);
143
+ // a copy: Electron's V8 sandbox does not allow an ArrayBuffer over outside memory (koffi.view)
144
+ const src = koffi.decode(img.data, koffi.array('uint8_t', img.bytes_per_line * height, 'Typed')) as Uint8Array;
145
+ const bgra = Buffer.alloc(width * height * 4);
146
+ // 32-bit ZPixmap on a little-endian TrueColor visual is B, G, R, unused
147
+ for (let y = 0; y < height; y++) {
148
+ bgra.set(src.subarray(y * img.bytes_per_line, y * img.bytes_per_line + width * 4), y * width * 4);
149
+ }
150
+ for (let i = 3; i < bgra.length; i += 4) bgra[i] = 255;
151
+ return { width, height, bgra };
152
+ } finally {
153
+ XDestroyImage(ptr);
154
+ }
155
+ }
156
+
157
+ export function cursor(): { x: number; y: number } {
158
+ const r = [0], c = [0], rx = [0], ry = [0], wx = [0], wy = [0], m = [0];
159
+ XQueryPointer(dpy, root, r, c, rx, ry, wx, wy, m);
160
+ return { x: rx[0]!, y: ry[0]! };
161
+ }
162
+
163
+ /** Milliseconds since the engine started, wrapping at 2^32 as Windows' tick does. */
164
+ export function tick(): number {
165
+ return (Date.now() - t0) >>> 0;
166
+ }
167
+
168
+ /** Tick of the last input the X server saw; null without a working screen-saver extension. */
169
+ export function lastInputTick(): number | null {
170
+ const info = { window: 0, state: 0, kind: 0, til_or_since: 0, idle: 0, eventMask: 0 };
171
+ if (!hasIdle || !XScreenSaverQueryInfo!(dpy, root, info)) return null;
172
+ return (tick() - Number(info.idle)) >>> 0;
173
+ }
174
+
175
+ export type Button = 'left' | 'right' | 'middle';
176
+
177
+ /** Absolute move in pixels of the screen. */
178
+ export function moveTo(x: number, y: number): void {
179
+ XTestFakeMotionEvent(dpy, -1, Math.round(x), Math.round(y), 0);
180
+ XFlush(dpy);
181
+ }
182
+
183
+ export function buttonDown(b: Button): void { XTestFakeButtonEvent(dpy, BUTTON[b], 1, 0); XFlush(dpy); }
184
+ export function buttonUp(b: Button): void { XTestFakeButtonEvent(dpy, BUTTON[b], 0, 0); XFlush(dpy); }
185
+
186
+ /** One notch per unit; positive `down` scrolls toward the end of a document. X11 wheels are buttons 4–7. */
187
+ export function wheel(down: number, right: number): void {
188
+ const notch = (button: number, n: number) => {
189
+ for (let i = 0; i < n; i++) { XTestFakeButtonEvent(dpy, button, 1, 0); XTestFakeButtonEvent(dpy, button, 0, 0); }
190
+ };
191
+ notch(down > 0 ? 5 : 4, Math.abs(down));
192
+ notch(right > 0 ? 7 : 6, Math.abs(right));
193
+ XFlush(dpy);
194
+ }
195
+
196
+ /** The keycodes of `vks` (Windows virtual-key codes); throws before anything is sent when one is missing. */
197
+ function keycodes(vks: Array<{ vk: number; extended: boolean }>): number[] {
198
+ return vks.map((k) => {
199
+ const sym = linuxKeysym(k.vk);
200
+ const code = sym === null ? 0 : XKeysymToKeycode(dpy, sym);
201
+ if (!code) throw new EngineFailure('linuxNoKey', [`0x${k.vk.toString(16)}`]);
202
+ return code;
203
+ });
204
+ }
205
+
206
+ /** Presses `vks` in order and leaves them down. The X server repeats a held key as a hardware key would. */
207
+ export function keysDown(vks: Array<{ vk: number; extended: boolean }>): void {
208
+ for (const c of keycodes(vks)) XTestFakeKeyEvent(dpy, c, 1, 0);
209
+ XSync(dpy, 0);
210
+ }
211
+
212
+ /** Releases `vks` in reverse order. */
213
+ export function keysUp(vks: Array<{ vk: number; extended: boolean }>): void {
214
+ for (const c of keycodes(vks).reverse()) XTestFakeKeyEvent(dpy, c, 0, 0);
215
+ XSync(dpy, 0);
216
+ }
217
+
218
+ /** Presses `vks` in order with their modifiers held, then releases them in reverse. */
219
+ export function chord(vks: Array<{ vk: number; extended: boolean }>): void {
220
+ keysDown(vks);
221
+ keysUp(vks);
222
+ }
223
+
224
+ /** Types text independent of the keyboard layout: xdotool maps each character to a spare keycode. */
225
+ export function typeUnicode(text: string): void {
226
+ const clean = text.replace(/\r/g, '');
227
+ if (!clean) return;
228
+ try {
229
+ execFileSync('xdotool', ['type', '--clearmodifiers', '--delay', '8', '--', clean], { stdio: 'ignore', timeout: 60_000 });
230
+ } catch (e) {
231
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') throw new EngineFailure('linuxNoXdotool');
232
+ throw e;
233
+ }
234
+ }
235
+
236
+ export interface WindowInfo {
237
+ handle: string;
238
+ title: string;
239
+ pid: number;
240
+ rect: Rect;
241
+ minimized: boolean;
242
+ foreground: boolean;
243
+ }
244
+
245
+ const atoms = new Map<string, number>();
246
+ const atom = (name: string): number => {
247
+ let a = atoms.get(name);
248
+ if (a === undefined) { a = Number(XInternAtom(dpy, name, 0)); atoms.set(name, a); }
249
+ return a;
250
+ };
251
+
252
+ /** A window property: numbers (32-bit format, as C longs) or bytes (8-bit format); null when absent. */
253
+ function prop(w: number, name: string): number[] | Buffer | null {
254
+ const type = [0], format = [0], n = [0], after = [0], data = [null];
255
+ if (XGetWindowProperty(dpy, w, atom(name), 0, 1 << 16, 0, 0, type, format, n, after, data) !== 0 || !data[0]) return null;
256
+ try {
257
+ const count = Number(n[0]);
258
+ if (!count) return null;
259
+ // decoded as a BigUint64Array: Array.from, since mapping a typed array writes back into it
260
+ if (format[0] === 32) return Array.from(koffi.decode(data[0], koffi.array('unsigned long', count)) as ArrayLike<number | bigint>, Number);
261
+ if (format[0] === 8) return Buffer.from(koffi.decode(data[0], koffi.array('uint8_t', count)) as number[]);
262
+ return null;
263
+ } finally {
264
+ XFree(data[0]);
265
+ }
266
+ }
267
+ const numbers = (v: number[] | Buffer | null): number[] => (Array.isArray(v) ? v : []);
268
+ const text = (v: number[] | Buffer | null): string => (Buffer.isBuffer(v) ? v.toString('utf8') : '');
269
+
270
+ function frame(w: number): Rect {
271
+ const r = [0], x = [0], y = [0], wd = [0], ht = [0], b = [0], d = [0];
272
+ if (!XGetGeometry(dpy, w, r, x, y, wd, ht, b, d)) return { x: 0, y: 0, width: 0, height: 0 };
273
+ const ax = [0], ay = [0], child = [0];
274
+ XTranslateCoordinates(dpy, w, root, 0, 0, ax, ay, child);
275
+ return { x: ax[0]!, y: ay[0]!, width: wd[0]!, height: ht[0]! };
276
+ }
277
+
278
+ /** The executable's name of process `pid` as the kernel keeps it (at most 15 characters), null when unknown. */
279
+ export function processName(pid: number): string | null {
280
+ if (!pid) return null;
281
+ try {
282
+ return readFileSync(`/proc/${pid}/comm`, 'utf8').trim() || null;
283
+ } catch {
284
+ return null;
285
+ }
286
+ }
287
+
288
+ export function foregroundWindow(): ForegroundWindow | null {
289
+ const active = numbers(prop(root, '_NET_ACTIVE_WINDOW'))[0];
290
+ if (!active) return null;
291
+ return {
292
+ title: text(prop(active, '_NET_WM_NAME')) || text(prop(active, 'WM_NAME')),
293
+ app: processName(numbers(prop(active, '_NET_WM_PID'))[0] ?? 0),
294
+ rect: frame(active),
295
+ };
296
+ }
297
+
298
+ /** Managed top-level windows with a title, front to back, from the window manager's stacking list. */
299
+ export function windows(): WindowInfo[] {
300
+ const active = numbers(prop(root, '_NET_ACTIVE_WINDOW'))[0] ?? 0;
301
+ const stack = numbers(prop(root, '_NET_CLIENT_LIST_STACKING'));
302
+ const list = stack.length ? stack : numbers(prop(root, '_NET_CLIENT_LIST'));
303
+ const hidden = atom('_NET_WM_STATE_HIDDEN');
304
+ const out: WindowInfo[] = [];
305
+ for (const w of [...list].reverse()) {
306
+ const title = text(prop(w, '_NET_WM_NAME')) || text(prop(w, 'WM_NAME'));
307
+ if (!title) continue;
308
+ const rect = frame(w);
309
+ if (rect.width < 2 || rect.height < 2) continue;
310
+ out.push({
311
+ handle: w.toString(16),
312
+ title,
313
+ pid: numbers(prop(w, '_NET_WM_PID'))[0] ?? 0,
314
+ rect,
315
+ minimized: numbers(prop(w, '_NET_WM_STATE')).includes(hidden),
316
+ foreground: w === active,
317
+ });
318
+ }
319
+ return out;
320
+ }
321
+
322
+ /** Restores and raises a window through the window manager (xdotool sends _NET_ACTIVE_WINDOW). */
323
+ export function focus(handle: string): boolean {
324
+ const id = Number.parseInt(handle, 16);
325
+ if (!Number.isInteger(id) || id <= 0) return false;
326
+ try {
327
+ execFileSync('xdotool', ['windowactivate', '--sync', String(id)], { stdio: 'ignore', timeout: 5000 });
328
+ return true;
329
+ } catch {
330
+ return false;
331
+ }
332
+ }
333
+
334
+ /** A yes/no dialog answered or given up after `timeoutMs`; without zenity the answer is no. */
335
+ export function askYesNo(text: string, caption: string, { yes, no }: { yes: string; no: string }, timeoutMs: number): Promise<'yes' | 'no' | 'timeout'> {
336
+ const secs = String(Math.max(1, Math.round(timeoutMs / 1000)));
337
+ return new Promise((resolve) => {
338
+ const p = execFile('zenity', ['--question', `--title=${caption}`, `--text=${text}`, `--ok-label=${yes}`, `--cancel-label=${no}`, `--timeout=${secs}`, '--no-markup'],
339
+ { timeout: timeoutMs + 5000 }, () => { /* the exit code is read below */ });
340
+ p.on('error', () => resolve('no'));
341
+ p.on('exit', (code) => resolve(zenityAnswer(code)));
342
+ });
343
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Windows virtual-key codes (what `keys.ts` parses) to macOS key codes (kVK_*) and modifier flags,
3
+ * and the reply of an AppleScript `display dialog`. Pure, so it is tested on every platform.
4
+ */
5
+
6
+ /** Modifier flags of CGEventFlags, by the Windows virtual-key code of the modifier. */
7
+ const MAC_MODIFIERS: Record<number, { key: number; flag: number }> = {
8
+ 0x10: { key: 0x38, flag: 0x20000 }, // shift
9
+ 0x11: { key: 0x3b, flag: 0x40000 }, // control
10
+ 0x12: { key: 0x3a, flag: 0x80000 }, // option
11
+ 0x5b: { key: 0x37, flag: 0x100000 }, // command ("win", "cmd", "meta" in speed_pet_cua_key)
12
+ };
13
+
14
+ const KEYS: Record<number, number> = {
15
+ 0x0d: 0x24, 0x1b: 0x35, 0x09: 0x30, 0x20: 0x31, 0x08: 0x33, 0x2e: 0x75, 0x2d: 0x72,
16
+ 0x24: 0x73, 0x23: 0x77, 0x21: 0x74, 0x22: 0x79, 0x25: 0x7b, 0x26: 0x7e, 0x27: 0x7c, 0x28: 0x7d,
17
+ 0x14: 0x39, 0xaf: 0x48, 0xae: 0x49, 0xad: 0x4a,
18
+ // A–Z and 0–9 where the ANSI layout places them
19
+ 0x41: 0x00, 0x42: 0x0b, 0x43: 0x08, 0x44: 0x02, 0x45: 0x0e, 0x46: 0x03, 0x47: 0x05, 0x48: 0x04, 0x49: 0x22,
20
+ 0x4a: 0x26, 0x4b: 0x28, 0x4c: 0x25, 0x4d: 0x2e, 0x4e: 0x2d, 0x4f: 0x1f, 0x50: 0x23, 0x51: 0x0c, 0x52: 0x0f,
21
+ 0x53: 0x01, 0x54: 0x11, 0x55: 0x20, 0x56: 0x09, 0x57: 0x0d, 0x58: 0x07, 0x59: 0x10, 0x5a: 0x06,
22
+ 0x30: 0x1d, 0x31: 0x12, 0x32: 0x13, 0x33: 0x14, 0x34: 0x15, 0x35: 0x17, 0x36: 0x16, 0x37: 0x1a, 0x38: 0x1c, 0x39: 0x19,
23
+ // F1–F20
24
+ 0x70: 0x7a, 0x71: 0x78, 0x72: 0x63, 0x73: 0x76, 0x74: 0x60, 0x75: 0x61, 0x76: 0x62, 0x77: 0x64, 0x78: 0x65,
25
+ 0x79: 0x6d, 0x7a: 0x67, 0x7b: 0x6f, 0x7c: 0x69, 0x7d: 0x6b, 0x7e: 0x71, 0x7f: 0x6a, 0x80: 0x40, 0x81: 0x4f, 0x82: 0x50, 0x83: 0x5a,
26
+ // US-layout punctuation: ; = , - . / ` [ \ ] '
27
+ 0xba: 0x29, 0xbb: 0x18, 0xbc: 0x2b, 0xbd: 0x1b, 0xbe: 0x2f, 0xbf: 0x2c, 0xc0: 0x32, 0xdb: 0x21, 0xdc: 0x2a, 0xdd: 0x1e, 0xde: 0x27,
28
+ };
29
+
30
+ /** The Mac key for a Windows virtual-key code, or null for keys a Mac keyboard lacks (Print Screen, the menu key, F21–F24). */
31
+ export function macKey(vk: number): { key: number; flag: number } | null {
32
+ if (MAC_MODIFIERS[vk]) return MAC_MODIFIERS[vk]!;
33
+ const key = KEYS[vk];
34
+ return key === undefined ? null : { key, flag: 0 };
35
+ }
36
+
37
+ /** Quotes a string for AppleScript. */
38
+ export const appleString = (s: string): string => `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
39
+
40
+ /** What `display dialog … giving up after` printed: which button, or that time ran out. */
41
+ export function dialogAnswer(stdout: string, yes: string): 'yes' | 'no' | 'timeout' {
42
+ if (/gave up:true/.test(stdout)) return 'timeout';
43
+ return new RegExp(`button returned:${yes.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(,|$)`).test(stdout.trim()) ? 'yes' : 'no';
44
+ }
45
+
46
+ /** UTF-16 units of `text` in pieces of at most `size`, never splitting a surrogate pair. */
47
+ export function unicodeChunks(text: string, size: number): Uint16Array[] {
48
+ const out: Uint16Array[] = [];
49
+ let cur: number[] = [];
50
+ for (const ch of text) {
51
+ const units = [...Array(ch.length)].map((_, i) => ch.charCodeAt(i));
52
+ if (cur.length + units.length > size) { out.push(Uint16Array.from(cur)); cur = []; }
53
+ cur.push(...units);
54
+ }
55
+ if (cur.length) out.push(Uint16Array.from(cur));
56
+ return out;
57
+ }
@@ -0,0 +1,54 @@
1
+ /** Input activity from unsigned 32-bit millisecond ticks and sampled native cursor positions. */
2
+ interface Point { x: number; y: number }
3
+
4
+ export interface InputSample {
5
+ now: number;
6
+ /** null when the system cannot report the last input. */
7
+ lastInputTick: number | null;
8
+ cursor: Point;
9
+ }
10
+
11
+ export interface InputActivity extends InputSample {
12
+ ownInputTick: number | null;
13
+ systemInputTick: number | null;
14
+ pointerTick: number | null;
15
+ pointerMoved: boolean;
16
+ idleMs: number;
17
+ }
18
+
19
+ const since = (now: number, then: number) => (now - then) >>> 0;
20
+
21
+ export class UserActivity {
22
+ private ownTick: number | null = null;
23
+ private cursor: Point | null = null;
24
+ private sampledTick: number | null = null;
25
+ private movedTick: number | null = null;
26
+
27
+ markOwn(now: number, cursor: Point): void {
28
+ this.ownTick = now;
29
+ this.cursor = cursor;
30
+ this.sampledTick = now;
31
+ this.movedTick = null;
32
+ }
33
+
34
+ /** Each signal's tick and their combined idle time; Infinity when neither records input. */
35
+ sample({ now, lastInputTick: last, cursor }: InputSample): InputActivity {
36
+ // Compare ages within the current tick cycle; pairwise ordering is ambiguous after half a cycle.
37
+ const inputAge = last === null ? Infinity : since(now, last);
38
+ const afterOwn = last !== null && (this.ownTick === null || since(now, this.ownTick) > inputAge + 40);
39
+ const pointerMoved = this.cursor !== null && (Math.abs(cursor.x - this.cursor.x) > 2 || Math.abs(cursor.y - this.cursor.y) > 2);
40
+ if (pointerMoved) {
41
+ // Movement observed between samples needs an input record at least as recent as the earlier sample.
42
+ const recorded = afterOwn && (this.sampledTick === null || inputAge <= since(now, this.sampledTick));
43
+ this.movedTick = recorded ? last : now;
44
+ this.cursor = cursor;
45
+ }
46
+ this.cursor ??= cursor;
47
+ this.sampledTick = now;
48
+ return {
49
+ now, lastInputTick: last, cursor, ownInputTick: this.ownTick,
50
+ systemInputTick: afterOwn ? last : null, pointerTick: this.movedTick, pointerMoved,
51
+ idleMs: Math.min(afterOwn ? inputAge : Infinity, this.movedTick === null ? Infinity : since(now, this.movedTick)),
52
+ };
53
+ }
54
+ }
@@ -0,0 +1,31 @@
1
+ import type { InputResult, Yield, YieldDiagnostics } from '../engine-ipc.ts';
2
+ import type { InputActivity } from './user-activity.ts';
3
+
4
+ export const INPUT_POLL_MS = 100;
5
+
6
+ export function recordActivity(diagnostics: YieldDiagnostics, sample: InputActivity, idleMs: number): void {
7
+ diagnostics.blockedBy = [];
8
+ diagnostics.lastSample = { now: sample.now, lastInputTick: sample.lastInputTick, ownInputTick: sample.ownInputTick, pointerMoved: sample.pointerMoved };
9
+ for (const [signal, tick] of [['systemInput', sample.systemInputTick], ['pointerMovement', sample.pointerTick]] as const) {
10
+ if (tick !== null && ((sample.now - tick) >>> 0) < idleMs) {
11
+ diagnostics.blockedBy.push(signal);
12
+ diagnostics[signal].count++;
13
+ diagnostics[signal].lastTick = tick;
14
+ }
15
+ }
16
+ }
17
+
18
+ export async function waitIdle(y: Yield, cancelled: () => boolean, sample: () => InputActivity): Promise<Pick<InputResult, 'yielded' | 'cancelled' | 'waitedMs' | 'activity'>> {
19
+ const start = Date.now();
20
+ const activity: YieldDiagnostics = {
21
+ blockedBy: [], systemInput: { count: 0, lastTick: null }, pointerMovement: { count: 0, lastTick: null }, lastSample: null,
22
+ };
23
+ for (;;) {
24
+ if (cancelled()) return { yielded: false, cancelled: true, waitedMs: Date.now() - start, activity };
25
+ const current = sample();
26
+ recordActivity(activity, current, y.idleMs);
27
+ if (current.idleMs >= y.idleMs) return { yielded: false, cancelled: false, waitedMs: Date.now() - start, activity };
28
+ if (Date.now() - start >= y.maxWaitMs) return { yielded: true, cancelled: false, waitedMs: Date.now() - start, activity };
29
+ await new Promise((resolve) => setTimeout(resolve, INPUT_POLL_MS));
30
+ }
31
+ }