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,63 @@
1
+ /**
2
+ * The pet window's X input shape in a Wayland session.
3
+ *
4
+ * XWayland knows where the cursor is only while it is over an X11 window, so in a Wayland session
5
+ * the cursor reports (cursor.cjs) stop where the cursor left the last one, and a click-through
6
+ * window never learns that the cursor reached the pet. There the window's input shape is the parts
7
+ * of the page that take the mouse, as the page reports them, and the compositor gives the window
8
+ * the clicks on those parts and every other click to the window underneath.
9
+ *
10
+ * Null outside a Wayland session, or when libX11 or libXext does not load or the X server has no
11
+ * SHAPE extension.
12
+ */
13
+ const SHAPE_INPUT = 2, SHAPE_SET = 0, UNSORTED = 0;
14
+
15
+ function createInputShape({ screen, platform = process.platform, env = process.env, loadKoffi = () => require('koffi') }) {
16
+ if (platform !== 'linux' || !(env.XDG_SESSION_TYPE === 'wayland' || env.WAYLAND_DISPLAY)) return null;
17
+ let dpy = null, combine, flush, closeDisplay;
18
+ try {
19
+ const koffi = loadKoffi();
20
+ const x11 = koffi.load('libX11.so.6'), xext = koffi.load('libXext.so.6');
21
+ const openDisplay = x11.func('void *XOpenDisplay(const char *name)');
22
+ flush = x11.func('int XFlush(void *dpy)');
23
+ closeDisplay = x11.func('int XCloseDisplay(void *dpy)');
24
+ const queryShape = xext.func('int XShapeQueryExtension(void *dpy, _Out_ int *event_base, _Out_ int *error_base)');
25
+ combine = xext.func('void XShapeCombineRectangles(void *dpy, unsigned long win, int kind, int x, int y, void *rects, int n, int op, int ordering)');
26
+ dpy = openDisplay(null);
27
+ if (dpy && !queryShape(dpy, [0], [0])) close();
28
+ } catch {
29
+ close();
30
+ }
31
+ if (!dpy) return null;
32
+
33
+ function close() {
34
+ if (!dpy) return;
35
+ const connection = dpy;
36
+ dpy = null;
37
+ closeDisplay(connection);
38
+ }
39
+
40
+ return {
41
+ /** Sets `win`'s input shape to `rects` ({ x, y, width, height } in page pixels); an empty list passes every click through. */
42
+ set(win, rects) {
43
+ if (!dpy || win.isDestroyed()) return;
44
+ const s = screen.getDisplayMatching(win.getBounds()).scaleFactor;
45
+ // XRectangle: short x, y; unsigned short width, height
46
+ const buf = Buffer.alloc(8 * rects.length);
47
+ rects.forEach((r, i) => {
48
+ const x = Math.floor(r.x * s), y = Math.floor(r.y * s);
49
+ buf.writeInt16LE(Math.max(-32768, Math.min(32767, x)) || 0, 8 * i);
50
+ buf.writeInt16LE(Math.max(-32768, Math.min(32767, y)) || 0, 8 * i + 2);
51
+ buf.writeUInt16LE(Math.max(0, Math.min(65535, Math.ceil((r.x + r.width) * s) - x)) || 0, 8 * i + 4);
52
+ buf.writeUInt16LE(Math.max(0, Math.min(65535, Math.ceil((r.y + r.height) * s) - y)) || 0, 8 * i + 6);
53
+ });
54
+ const h = win.getNativeWindowHandle();
55
+ const xid = h.length >= 8 ? h.readBigUInt64LE(0) : h.readUInt32LE(0);
56
+ combine(dpy, xid, SHAPE_INPUT, 0, 0, buf, rects.length, SHAPE_SET, UNSORTED);
57
+ flush(dpy);
58
+ },
59
+ close,
60
+ };
61
+ }
62
+
63
+ module.exports = { createInputShape };
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Who holds the mouse, and when it is given back.
3
+ *
4
+ * The pet window covers a work area, so while it holds the mouse every click on that screen goes
5
+ * to it, and the page is the only side that can hand it back. The window process keeps the last
6
+ * word instead:
7
+ *
8
+ * - `ask(wish)` is the page's wish, a lease of `leaseMs` the page renews while it holds the mouse,
9
+ * so a page that stops reporting loses the mouse;
10
+ * - the mouse is held only while the window is visible, and never while it is locked (`lock(on)`,
11
+ * the tray's "click through"), whatever the page asks;
12
+ * - a verdict stands for `reassertMs` and is then applied again, because the X input shape does
13
+ * not survive the window being mapped and the shape set while the window is still off screen
14
+ * does not stick. `forget()` drops the memory of the last verdict, for a caller that knows the
15
+ * shape was reset.
16
+ *
17
+ * The wish is whether the whole window takes the mouse. With `shape` (input-shape.cjs, a Wayland
18
+ * session) it is the list of rects that take it, and the verdict sets the window's input shape to
19
+ * them, or to none.
20
+ *
21
+ * The window is read through `getWindow`, so the lease can be exercised without Electron.
22
+ */
23
+
24
+ /**
25
+ * Whether a click-through window still passes the mouse moves to the page. On Windows Electron
26
+ * forwards them through a low-level mouse hook that every mouse event on the system goes through,
27
+ * which stalls the window process under a high-rate mouse; there the page follows the cursor
28
+ * through the cursor reports alone.
29
+ */
30
+ const FORWARD_MOVES = process.platform !== 'win32';
31
+
32
+ function createMouseLease({ getWindow, shape = null, leaseMs = 1500, reassertMs = 2000, now = () => Date.now() }) {
33
+ const none = shape ? [] : false;
34
+ let wanted = none, askedAt = 0, locked = false;
35
+ /** The last verdict, or null while it is not known to be in force. */
36
+ let held = null, appliedAt = 0;
37
+
38
+ const apply = () => {
39
+ const win = getWindow();
40
+ if (!win) return;
41
+ const hold = !locked && now() - askedAt < leaseMs && win.isVisible() ? wanted : none;
42
+ const verdict = shape ? JSON.stringify(hold) : hold;
43
+ const stamp = now();
44
+ if (verdict === held && stamp - appliedAt < reassertMs) return;
45
+ held = verdict;
46
+ appliedAt = stamp;
47
+ if (shape) shape.set(win, hold);
48
+ else win.setIgnoreMouseEvents(!hold, { forward: FORWARD_MOVES });
49
+ };
50
+
51
+ return {
52
+ /** The page's wish; called where the page asks. */
53
+ ask(wish) {
54
+ wanted = shape ? wish : !!wish;
55
+ askedAt = now();
56
+ apply();
57
+ },
58
+ /** Locked, every click passes through until it is unlocked; the page's wishes are kept meanwhile. */
59
+ lock(on) {
60
+ locked = !!on;
61
+ apply();
62
+ },
63
+ /** A cursor report went out: the lease may have run out, or the verdict be due again. */
64
+ tick: apply,
65
+ /** The window is going away: the mouse is not held any more. */
66
+ release() {
67
+ wanted = none;
68
+ apply();
69
+ },
70
+ /** The next verdict is applied from scratch, whatever was told to the window before. */
71
+ forget() {
72
+ held = null;
73
+ },
74
+ };
75
+ }
76
+
77
+ module.exports = { createMouseLease, FORWARD_MOVES };
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The pet window as a streaming layer: while the World says someone watches its `/overlay` page
3
+ * (`worlds.desktop-pet.window.exportOverlay` is on), this sends the part of the window where the
4
+ * pet and its bubbles are to the World's `overlay-source` socket, one frame for each frame the page draws.
5
+ *
6
+ * While it is told the stream is on (`pet:overlay`), the page reports every frame it draws
7
+ * (`pet:overlayFrame`: the part in CSS pixels, and when the frame was drawn in milliseconds since the
8
+ * epoch). A frame sent is 6 little-endian uint32 (the width and height of the display the window is
9
+ * on, and the part's x, y, width and height on that display, all in device pixels), a little-endian
10
+ * float64 (when the page drew it), and the part's BGRA pixels, alpha premultiplied as Chromium paints
11
+ * them, deflated. The window covers the display's work area, so the part is placed by the window's
12
+ * offset in the display. A part of 0 × 0 clears the layer: the window is hidden or nothing is drawn.
13
+ */
14
+ const { deflate } = require('node:zlib');
15
+ const { screen } = require('electron');
16
+
17
+ /** A frame waits while more than this many bytes are still on their way to the World. */
18
+ const MAX_BUFFERED = 4 * 1024 * 1024;
19
+ /**
20
+ * Captures under way at once; a frame drawn while they are all under way is not sent. A capture
21
+ * resolves with a frame drawn after it was asked for: one at a time they came 48 ms apart on a
22
+ * 2560-pixel display at 150 % (21 a second), and three at once keep up with 60 frames a second.
23
+ */
24
+ const MAX_CAPTURES = 3;
25
+ /** A hidden window draws no frames: how often the layer is checked for one, to clear it. */
26
+ const HIDDEN_CHECK_MS = 500;
27
+ /** Milliseconds before the socket is tried again after it closed. */
28
+ const RECONNECT_MS = 2000;
29
+
30
+ /**
31
+ * Connects to `origin` (the World's page server) and streams while it asks. `getWindow` returns the
32
+ * pet window or null.
33
+ */
34
+ function createOverlaySource({ origin, key, getWindow }) {
35
+ // the global WebSocket came with Node 22 (Electron 35): an older Electron set by the app streams nothing
36
+ if (typeof WebSocket !== 'function') return { frame: () => {}, pageLoaded: () => {}, stop: () => {} };
37
+ let socket = null;
38
+ /** The last frame sent cleared the layer: a hidden window sends that once, not at every check. */
39
+ let cleared = false;
40
+ let on = false;
41
+ let capturing = 0;
42
+ let timer = null;
43
+ let stopped = false;
44
+
45
+ const tellPage = () => getWindow()?.webContents.send('pet:overlay', on);
46
+
47
+ const connect = () => {
48
+ if (stopped) return;
49
+ const params = new URLSearchParams({ role: 'overlay-source', key });
50
+ const ws = new WebSocket(`${origin.replace(/^http/, 'ws')}/socket?${params}`);
51
+ ws.binaryType = 'arraybuffer';
52
+ ws.addEventListener('message', (e) => {
53
+ if (typeof e.data !== 'string') return;
54
+ try {
55
+ const msg = JSON.parse(e.data);
56
+ if (msg.t === 'overlay') setOn(!!msg.on);
57
+ } catch { /* not ours */ }
58
+ });
59
+ ws.addEventListener('close', () => {
60
+ if (socket === ws) { socket = null; setOn(false); }
61
+ if (!stopped) setTimeout(connect, RECONNECT_MS);
62
+ });
63
+ ws.addEventListener('error', () => { /* close follows */ });
64
+ socket = ws;
65
+ };
66
+
67
+ const setOn = (value) => {
68
+ if (value === on) return;
69
+ on = value;
70
+ cleared = false;
71
+ tellPage();
72
+ if (on && !timer) timer = setInterval(() => { const win = getWindow(); if (win && !win.isVisible()) clear(win, Date.now()); }, HIDDEN_CHECK_MS);
73
+ if (!on && timer) { clearInterval(timer); timer = null; }
74
+ };
75
+
76
+ const open = () => socket && socket.readyState === WebSocket.OPEN && socket.bufferedAmount <= MAX_BUFFERED;
77
+
78
+ const send = (head, at, pixels) => {
79
+ if (!open()) return;
80
+ cleared = !head[4];
81
+ const stamp = Buffer.alloc(8);
82
+ stamp.writeDoubleLE(at);
83
+ socket.send(Buffer.concat([Buffer.from(new Uint32Array(head).buffer), stamp, pixels]));
84
+ };
85
+
86
+ /** The display the window is on, in device pixels, and the window's offset in it in DIPs. */
87
+ const placement = (win) => {
88
+ // the page's zoom stays at 1 (electron-main.cjs), so CSS pixels are DIPs
89
+ const display = screen.getDisplayMatching(win.getBounds());
90
+ const scale = display.scaleFactor;
91
+ const b = win.getContentBounds();
92
+ // Windows rounds each display's pixel size its own way; elsewhere DIPs times the scale are the pixels
93
+ const px = process.platform === 'win32' ? screen.dipToScreenRect(null, display.bounds) : null;
94
+ const size = px ? [px.width, px.height] : [Math.round(display.bounds.width * scale), Math.round(display.bounds.height * scale)];
95
+ return { scale, size, dx: b.x - display.bounds.x, dy: b.y - display.bounds.y };
96
+ };
97
+
98
+ const clear = (win, at) => {
99
+ if (!cleared && open()) send([...placement(win).size, 0, 0, 0, 0], at, Buffer.alloc(0));
100
+ };
101
+
102
+ /** One frame the page drew: `r` is the part in CSS pixels or null, `at` when it was drawn. */
103
+ const frame = async (r, at) => {
104
+ const win = getWindow();
105
+ if (!on || !win || !open() || !Number.isFinite(at)) return;
106
+ const rect = r && [r.x, r.y, r.width, r.height].every(Number.isFinite)
107
+ ? { x: Math.max(0, Math.floor(r.x)), y: Math.max(0, Math.floor(r.y)), width: Math.ceil(r.width), height: Math.ceil(r.height) }
108
+ : null;
109
+ if (!win.isVisible() || !rect || rect.width < 1 || rect.height < 1) { clear(win, at); return; }
110
+ if (capturing >= MAX_CAPTURES) return;
111
+ capturing++;
112
+ try {
113
+ const { scale, size, dx, dy } = placement(win);
114
+ // capturePage starts the image at x × scale rounded, as placed here
115
+ const image = await win.webContents.capturePage(rect);
116
+ const { width, height } = image.getSize();
117
+ if (!width || !height) return;
118
+ const pixels = await new Promise((done, fail) => deflate(image.toBitmap(), { level: 1 }, (err, out) => (err ? fail(err) : done(out))));
119
+ send([...size, Math.round((dx + rect.x) * scale), Math.round((dy + rect.y) * scale), width, height], at, pixels);
120
+ } catch { /* the window closed mid-capture */ } finally {
121
+ capturing--;
122
+ }
123
+ };
124
+
125
+ connect();
126
+ return {
127
+ frame: (r, at) => void frame(r, at),
128
+ /** The page loaded again: tell it whether to report. */
129
+ pageLoaded: tellPage,
130
+ stop: () => {
131
+ stopped = true;
132
+ if (timer) clearInterval(timer);
133
+ timer = null;
134
+ socket?.close();
135
+ },
136
+ };
137
+ }
138
+
139
+ module.exports = { createOverlaySource };
@@ -0,0 +1,52 @@
1
+ /**
2
+ * A picture of the body for the bot to look at (`pet_see_self`): the part of the pet window the page names, as
3
+ * the window draws it, laid over a plain backdrop in place of the desktop, as a PNG.
4
+ *
5
+ * Every figure runs in the page's sandboxed frame (web/body-host.js), whose pixels the page cannot read, so the
6
+ * picture is taken from the window's own drawing, the way the streaming layer's frames are (overlay.cjs).
7
+ */
8
+
9
+ /** The backdrop's grey, 0–255: a light body and a dark one both show against it. */
10
+ const BACKDROP = 128;
11
+ /**
12
+ * The longest side of the picture, in pixels; a larger capture is scaled down to it. The page's rect is about
13
+ * 1.8 × 2.4 body boxes, and a box about 108 CSS pixels at size 1: at 200 % display scaling that is 390 × 520 pixels,
14
+ * unscaled up to size 2. A figure enlarged further (the size goes to 10) still comes out at most a megapixel.
15
+ */
16
+ const MAX_SIDE = 1024;
17
+
18
+ /**
19
+ * Lays `pixels` (BGRA, alpha premultiplied, as Chromium paints a transparent window) over the backdrop, in place:
20
+ * every pixel comes out opaque.
21
+ */
22
+ function flatten(pixels) {
23
+ for (let i = 0; i < pixels.length; i += 4) {
24
+ const rest = BACKDROP * (255 - pixels[i + 3]) / 255;
25
+ pixels[i] = Math.min(255, Math.round(pixels[i] + rest));
26
+ pixels[i + 1] = Math.min(255, Math.round(pixels[i + 1] + rest));
27
+ pixels[i + 2] = Math.min(255, Math.round(pixels[i + 2] + rest));
28
+ pixels[i + 3] = 255;
29
+ }
30
+ return pixels;
31
+ }
32
+
33
+ /**
34
+ * The picture of `rect` (CSS pixels of the page) of window `win`: `{ png, width, height }`, the PNG in base64
35
+ * and its size in pixels, or null when the rect is empty or the window gave no pixels. `nativeImage` is Electron's.
36
+ */
37
+ async function capturePortrait(win, rect, nativeImage) {
38
+ const r = rect && [rect.x, rect.y, rect.width, rect.height].every(Number.isFinite)
39
+ ? { x: Math.max(0, Math.floor(rect.x)), y: Math.max(0, Math.floor(rect.y)), width: Math.ceil(rect.width), height: Math.ceil(rect.height) }
40
+ : null;
41
+ if (!r || r.width < 1 || r.height < 1) return null;
42
+ const shot = await win.webContents.capturePage(r);
43
+ const { width, height } = shot.getSize();
44
+ if (!width || !height) return null;
45
+ let image = nativeImage.createFromBitmap(flatten(shot.toBitmap()), { width, height });
46
+ const k = MAX_SIDE / Math.max(width, height);
47
+ if (k < 1) image = image.resize({ width: Math.max(1, Math.round(width * k)), height: Math.max(1, Math.round(height * k)), quality: 'best' });
48
+ const size = image.getSize();
49
+ return { png: image.toPNG().toString('base64'), width: size.width, height: size.height };
50
+ }
51
+
52
+ module.exports = { capturePortrait, flatten, BACKDROP, MAX_SIDE };
package/host/preload.cjs CHANGED
@@ -1,16 +1,62 @@
1
+ // The only surface the pet page gets from the window process.
1
2
  const { contextBridge, ipcRenderer } = require('electron');
2
3
 
3
- // A sandboxed preload is intended only for the window's main document. The
4
- // host separately checks the originating WebContents, frame and exact URL.
5
- if (process.isMainFrame && location.href === 'coopanion-ui://app/index.html') {
6
- contextBridge.exposeInMainWorld('agentSpeed', {
7
- getState: () => ipcRenderer.invoke('agent-speed-pet:get-state'),
8
- onState(callback) {
9
- if (typeof callback !== 'function') throw new TypeError('Expected a state listener.');
10
- const listen = (_event, value) => callback(value);
11
- ipcRenderer.on('agent-speed-pet:state', listen);
12
- return () => { ipcRenderer.removeListener('agent-speed-pet:state', listen); };
13
- },
14
- openMenu: () => { ipcRenderer.send('agent-speed-pet:open-menu'); },
15
- });
16
- }
4
+ contextBridge.exposeInMainWorld('petHost', {
5
+ /**
6
+ * true: the window takes the mouse; false: clicks pass through to what is underneath.
7
+ * The wish is a lease the window process keeps for itself (`host/mouse-lease.cjs`).
8
+ */
9
+ setInteractive: (on) => ipcRenderer.send('pet:interactive', !!on),
10
+ /** Whether the window takes the mouse only over the rects the page reports with `setInputRects` (a Wayland session); the window process ignores `setInteractive` then. */
11
+ onInputShape: (cb) => ipcRenderer.on('pet:inputShape', (_e, on) => cb(!!on)),
12
+ /** The parts of the page that take the mouse, `{ x, y, width, height }` in page pixels; a lease like `setInteractive`'s. */
13
+ setInputRects: (rects) => ipcRenderer.send('pet:inputRects', rects),
14
+ focus: () => ipcRenderer.send('pet:focus'),
15
+ /** Takes the keyboard from whatever window has it (a question's number keys), and gives it back. */
16
+ grabFocus: () => ipcRenderer.send('pet:grabFocus'),
17
+ releaseFocus: () => ipcRenderer.send('pet:releaseFocus'),
18
+ hide: () => ipcRenderer.send('pet:hide'),
19
+ /** Whether the window is shown, each time it is shown or hidden (by the menu, the tray or a fullscreen window). */
20
+ onShown: (cb) => ipcRenderer.on('pet:shown', (_e, shown) => cb(!!shown)),
21
+ /** Whether the window hides itself while a fullscreen window covers its display. */
22
+ hideWhenFullscreen: (on) => ipcRenderer.send('pet:hideWhenFullscreen', !!on),
23
+ /** Whether every click passes through the window while a fullscreen window covers its display. */
24
+ passWhenFullscreen: (on) => ipcRenderer.send('pet:passWhenFullscreen', !!on),
25
+ /** Whether the window reaches down over a taskbar at the bottom of its display. */
26
+ overTaskbar: (on) => ipcRenderer.send('pet:overTaskbar', !!on),
27
+ /** Whether the window is left out of screenshots and screen recordings. */
28
+ hideFromCapture: (on) => ipcRenderer.send('pet:hideFromCapture', !!on),
29
+ /** Whether clicks pass through right now because of that setting, each time it changes. */
30
+ onFullscreenThrough: (cb) => ipcRenderer.on('pet:fullscreenThrough', (_e, on) => cb(!!on)),
31
+ /** Whether the pet fades while a fullscreen window covers its display. */
32
+ fadeWhenFullscreen: (on) => ipcRenderer.send('pet:fadeWhenFullscreen', !!on),
33
+ /** Whether that setting is on and a fullscreen window covers the display right now, each time it changes. */
34
+ onFullscreenFade: (cb) => ipcRenderer.on('pet:fullscreenFade', (_e, on) => cb(!!on)),
35
+ /** Whether every click passes through the window (the tray's "click through"); the window process enforces it. */
36
+ clickThrough: (on) => ipcRenderer.send('pet:clickThrough', !!on),
37
+ /** Whether clicks reach the page despite click-through right now: the click-through pause key held, or the person dealing with the pet. */
38
+ lendClicks: (on) => ipcRenderer.send('pet:lendClicks', !!on),
39
+ openDress: () => ipcRenderer.send('pet:openDress'),
40
+ /** The app language the page shows, for the window process's own words (the tray menu). */
41
+ setLanguage: (code) => ipcRenderer.send('pet:language', String(code)),
42
+ /** How far the window reaches below the floor (over a taskbar), in page pixels, each time it is placed. */
43
+ onFloor: (cb) => ipcRenderer.on('pet:floor', (_e, below) => cb(Number(below) || 0)),
44
+ /** Whether the window reads the other windows on its display: on only while the body on screen's pack asks for them. */
45
+ watchWindows: (on) => ipcRenderer.send('pet:watchWindows', !!on),
46
+ /** Those windows while they are read, each time they change: `{ ledges, windows }` in page pixels as web/figure-frame.js describes them, or null when they cannot be read. */
47
+ onWindows: (cb) => ipcRenderer.on('pet:windows', (_e, desk) => cb(Array.isArray(desk?.ledges) && Array.isArray(desk?.windows) ? desk : null)),
48
+ /** Where the cursor is, in page pixels, or null off the window: called every 15 ms on Windows, 10 times a second elsewhere. */
49
+ onCursor: (cb) => ipcRenderer.on('pet:cursor', (_e, p) => cb(p)),
50
+ /** Screen pixels behind `rect`, minus `skip` rects (page coordinates), as a flat [r, g, b, …]; null where the screen cannot be read. */
51
+ sampleBackdrop: (rect, skip) => ipcRenderer.invoke('pet:sampleBackdrop', { rect, skip }),
52
+ /** Moves the window to the display under the cursor: { x, y } the cursor and { w, h } the new size in page pixels, or null when it stays. */
53
+ followCursor: () => ipcRenderer.invoke('pet:followCursor'),
54
+ /** Whether the cursor is over another display than the one the window covers, so `followCursor` would move it. */
55
+ cursorElsewhere: () => ipcRenderer.invoke('pet:cursorElsewhere'),
56
+ /** Whether the window streams to the World's OBS overlay; while it does, the page reports each frame with `overlayFrame`. */
57
+ onOverlay: (cb) => ipcRenderer.on('pet:overlay', (_e, on) => cb(!!on)),
58
+ /** A frame drawn: the part of the page the overlay shows (the pet and its bubbles) in page pixels or null, and when it was drawn (ms since the epoch). */
59
+ overlayFrame: (rect, at) => ipcRenderer.send('pet:overlayFrame', rect, at),
60
+ /** A picture of `rect` (page pixels) as the window draws it, over a plain backdrop: `{ png, width, height }` (base64, pixels), or null when none could be taken. */
61
+ portrait: (rect) => ipcRenderer.invoke('pet:portrait', rect),
62
+ });
@@ -0,0 +1,24 @@
1
+ /** Logs each end of a window's renderer with its reason and exit code. */
2
+
3
+ /** An exit code as Windows writes it (0x80000003), elsewhere the number. */
4
+ function exitCodeText(code) {
5
+ return process.platform === 'win32' ? `0x${(code >>> 0).toString(16).toUpperCase().padStart(8, '0')}` : String(code);
6
+ }
7
+
8
+ /**
9
+ * Gives `log` one line per end of a renderer of `contents`, saying when its page had not finished loading.
10
+ * Each new renderer counts as not loaded until its page finishes loading.
11
+ * @param {Pick<Electron.WebContents, 'on'>} contents
12
+ * @param {{ name: string, log: (line: string) => void }} opts
13
+ */
14
+ function watchRenderer(contents, { name, log }) {
15
+ let loaded = false;
16
+ contents.on('did-finish-load', () => { loaded = true; });
17
+ contents.on('render-process-gone', (_e, { reason, exitCode }) => {
18
+ const before = loaded ? '' : ',页面还没加载完';
19
+ log(`${name}的渲染进程退出:${reason}(退出码 ${exitCodeText(exitCode)})${before}`);
20
+ loaded = false;
21
+ });
22
+ }
23
+
24
+ module.exports = { watchRenderer };