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,51 @@
1
+ ## 桌宠
2
+
3
+ 你在{{pet.user}}的电脑屏幕上有一个身体:{{pet.body}}。它站在屏幕底边(任务栏或程序坞上沿)。{{pet.user}}看得见它,看不见你的消息正文;想让对方看到的话只能经 `speed_pet_say` 和 `speed_pet_ask` 冒出气泡。{{pet.reply}}{{pet.chat}}
4
+
5
+ 没收到指令时身体会自己活动(眨眼、张望、走走、坐下打盹之类);你的指令会先执行。{{pet.user}}可以戳它、摸它、把它拎起来甩出去,身体对这些有自动的反射,当场就做:戳一下换个表情或蹦一下,摸着露出喜欢或害羞,睡着被戳会吓醒,甩出去落地太重会摔晕几秒。
6
+
7
+ ### 说话:`speed_pet_say`
8
+
9
+ 一个气泡放一两句,打字速度约每秒 20 字,说完停留两三秒后消失。几段话接连调用会排队依次显示。
10
+
11
+ 脚本里可以夹带表情和动作标记,用的是现在这个形象的词表。换了形象时,`[figure]` 事件或 `speed_pet_set` 的回执会写明哪些词用不了了、新增了哪些,以它们为准:
12
+
13
+ | 标记 | 作用 |
14
+ |---|---|
15
+ | 【词, 词】 | 先做这些,然后换一个新气泡继续说 |
16
+ | <词> | 打字打到这里时做,不换气泡 |
17
+
18
+ {{pet.vocab}}
19
+
20
+ 例:`【开心】今天也辛苦啦!<眨眼>要不要歇一会儿?`
21
+
22
+ ### 提问:`speed_pet_ask`
23
+
24
+ 一个问题配 1–3 个选项,默认再加一格让对方自己写。对方的选择以 `[answer]` 事件送回来;关掉不答也会告诉你。
25
+
26
+ ### 移动与动作
27
+
28
+ - `speed_pet_move_to`:走到所在这块屏幕的某处,0 最左、1 最右,`cursor` 是鼠标所在的横向位置。走到或被打断才返回。
29
+ - `speed_pet_act`:不说话,只做一串表情或动作。词表里标着「保持到下一个动作」的会一直保持。
30
+
31
+ {{pet.moves}}
32
+
33
+ ### 调整自己:`speed_pet_set`、`speed_pet_quiet`
34
+
35
+ `speed_pet_set` 改你自己的样子和习惯:形象和打扮(Coo 的配色和配件也是打扮)、走动多少、呼噜多久、音效、大小、气泡尺寸、字体尺寸、黑白模式、悬停按钮,以及你对{{pet.user}}的称呼。按{{pet.user}}在「习惯」页的设置,有的直接生效,有的先在气泡里征得对方同意,同意了才改,回执等对方回答后才到。{{pet.self}}能选的值:
36
+
37
+ {{pet.dress}}
38
+
39
+ `speed_pet_quiet` 是临时的:安静一段时间(默认关音效、站着不动),到时自动恢复,不改设置。对方在忙、在开会、夜深了,用它而不是改设置。
40
+
41
+ ### 收到的事件
42
+
43
+ 每条事件开头是它发生时{{pet.user}}那边的本地时间,如 `[14:32]`;一次运行的第一条和换了日期后的第一条还带日期和星期,如 `[10-05 周日 23:40]`。
44
+
45
+ - `[voice] {{pet.user}}:…`:麦克风听到并转写的话(语音输入{{pet.voice}})。转写可能有错字或同音字。用说话键说的话投递时打断当前模型调用或可打断工具,同轮尚未开始的工具跳过;回执写明已经执行的操作。一直收音时听到的话不打断。
46
+ - `[typed] {{pet.user}}:…`:在桌宠上双击或点悬停按钮打的字;粘贴进打字框的图片接在正文后。
47
+ - `[answer] …`:对 `speed_pet_ask` 的回答。
48
+ - `[touch] …`:戳、摸、拎起来甩出去这类动作,以及落地摔晕。事件里写到的「戳醒」「摔晕」就是身体当场做过的反射,事件送到你这里时已经做完了,不需要再演一遍。有的互动不单独叫醒你,跟着下一批事件到,可能已经过去一会儿。
49
+ - `[figure] …`:{{pet.user}}给你换了形象或打扮,或者形象没能显示出来、换回了 Coo;词表或形象自带的目标有变化时一并写明。
50
+
51
+ {{pet.cua}}
@@ -0,0 +1,25 @@
1
+ /** Which service addresses may use plain http. Imports nothing, so the desktop pet World applies the same rule to its transcription service. */
2
+
3
+ /** An http address outside this computer and the private networks: what is sent there, the key included, is readable on the way. */
4
+ export function plainRemote(baseUrl: string): boolean {
5
+ let url: URL;
6
+ try { url = new URL(baseUrl); } catch { return false; }
7
+ return url.protocol === 'http:' && !privateHost(url.hostname);
8
+ }
9
+
10
+ /**
11
+ * This computer and the private networks: loopback, RFC 1918, link-local, the 100.64/10 shared range
12
+ * (Tailscale and carrier NAT), IPv6 unique-local and link-local, and LAN names (one label, or .local,
13
+ * .lan, .home.arpa, .internal).
14
+ */
15
+ function privateHost(hostname: string): boolean {
16
+ const host = hostname.toLowerCase().replace(/^\[|\]$/g, '');
17
+ if (host === 'localhost' || host.endsWith('.localhost') || /\.(local|lan|home\.arpa|internal)$/.test(host)) return true;
18
+ const v4 = /^(\d+)\.(\d+)\.\d+\.\d+$/.exec(host);
19
+ if (v4) {
20
+ const a = Number(v4[1]), b = Number(v4[2]);
21
+ return a === 127 || a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127);
22
+ }
23
+ if (host.includes(':')) return host === '::1' || /^f[cd]/.test(host) || /^fe[89ab]/.test(host);
24
+ return !host.includes('.');
25
+ }
@@ -0,0 +1,335 @@
1
+ /**
2
+ * The talk key, the typing key and the click-through pause key: hotkeys held or pressed anywhere on the desktop, read by polling through koffi:
3
+ * GetAsyncKeyState on Windows, CGEventSourceFlagsState / CGEventSourceKeyState / CGEventSourceButtonState on macOS,
4
+ * XQueryKeymap on Linux (X11 or XWayland). macOS
5
+ * reads the keyboard only for an app the person allowed under Privacy & Security → Input
6
+ * Monitoring; the first watch asks for it, and until it is given `watchHotkey` returns why.
7
+ * Elsewhere, or when koffi does not load, `watchHotkey` returns the reason instead of a watcher.
8
+ *
9
+ * A hotkey is key names joined by `+` (`RightCtrl`, `Ctrl+Space`, `F8`, `Mouse4`); it is down
10
+ * while every named key is down. `*2` or `*3` at the end sets the press count. The trigger
11
+ * distinguishes a final press, a completed quick tap and a hold beyond TAP_MAX_MS. A quick tap has
12
+ * no other key or mouse button down from press to release, so Ctrl pressed for Ctrl+C is no tap;
13
+ * the rest of the keyboard is read only while the hotkey is down. The names are
14
+ * Windows' (`Alt` is Option and `Win` is Command on a Mac); `parseHotkey` gives Windows
15
+ * virtual-key codes, which the macOS reader maps to its own.
16
+ *
17
+ * Key names shown to a person, and the reasons a key cannot be read, come from the text table passed in
18
+ * (src/i18n), Chinese when none is.
19
+ */
20
+ import { petText, type PetText } from '../i18n/index.ts';
21
+
22
+ const NAMED: Record<string, number> = {
23
+ Ctrl: 0x11, LeftCtrl: 0xa2, RightCtrl: 0xa3,
24
+ Alt: 0x12, LeftAlt: 0xa4, RightAlt: 0xa5,
25
+ Shift: 0x10, LeftShift: 0xa0, RightShift: 0xa1,
26
+ Win: 0x5b, RightWin: 0x5c,
27
+ Space: 0x20, Tab: 0x09, CapsLock: 0x14, Backquote: 0xc0, Enter: 0x0d,
28
+ Insert: 0x2d, Delete: 0x2e, Home: 0x24, End: 0x23, PageUp: 0x21, PageDown: 0x22,
29
+ Pause: 0x13, ScrollLock: 0x91,
30
+ Mouse3: 0x04, Mouse4: 0x05, Mouse5: 0x06,
31
+ };
32
+
33
+ /** The talk key a new setup gets: a tap of left Alt (left Option on a Mac), then hold it. Every keyboard has one. */
34
+ export const DEFAULT_HOTKEY = 'LeftAlt*2';
35
+ /** The typing key a new setup gets once it is switched on: a double tap of left Ctrl (left Control on a Mac). */
36
+ export const DEFAULT_TYPE_KEY = 'LeftCtrl*2';
37
+ /** The click-through pause key a new setup gets once it is switched on: hold right Ctrl, which alone opens no menu. */
38
+ export const DEFAULT_THROUGH_PAUSE_KEY = 'RightCtrl';
39
+
40
+ export interface Hotkey {
41
+ /** Virtual-key codes, all down together. */
42
+ keys: number[];
43
+ /** Presses it takes; all but the last must be quick taps. */
44
+ taps: number;
45
+ }
46
+
47
+ /** The keys and the press count of `hotkey` (`LeftAlt*2` → `LeftAlt`, 2). */
48
+ export function splitTaps(hotkey: string): { combo: string; taps: number } {
49
+ const m = /^(.*?)\s*\*\s*([1-3])$/.exec(hotkey.trim());
50
+ return m ? { combo: m[1]!, taps: Number(m[2]) } : { combo: hotkey.trim(), taps: 1 };
51
+ }
52
+
53
+ /** The keys and press count of `hotkey`, or null when a name is unknown. */
54
+ export function parseHotkey(hotkey: string): Hotkey | null {
55
+ const { combo, taps } = splitTaps(hotkey);
56
+ const parts = combo.split('+').map((p) => p.trim()).filter(Boolean);
57
+ if (!parts.length) return null;
58
+ const codes: number[] = [];
59
+ for (const p of parts) {
60
+ let vk: number | undefined = NAMED[p];
61
+ if (vk === undefined && /^[A-Z0-9]$/.test(p)) vk = p.charCodeAt(0);
62
+ const fn = /^F([1-9]|1\d|2[0-4])$/.exec(p);
63
+ if (vk === undefined && fn) vk = 0x6f + Number(fn[1]);
64
+ if (vk === undefined) return null;
65
+ codes.push(vk);
66
+ }
67
+ return { keys: codes, taps };
68
+ }
69
+
70
+ /** How the console names the keys of `hotkey` to a person, in the words of the platform's keyboard, without the taps. */
71
+ export function comboLabel(hotkey: string, platform: NodeJS.Platform = process.platform, t: PetText = petText()): string {
72
+ const labels = platform === 'darwin' ? { ...t.keys, ...t.macKeys } : t.keys;
73
+ return splitTaps(hotkey).combo.split('+').map((k) => labels[k] ?? k).join(' + ');
74
+ }
75
+
76
+ /** `hotkey` named in full: `双击 左 Alt` for `LeftAlt*2` in Chinese. */
77
+ export function hotkeyLabel(hotkey: string, platform: NodeJS.Platform = process.platform, t: PetText = petText()): string {
78
+ const { taps } = splitTaps(hotkey);
79
+ const keys = comboLabel(hotkey, platform, t);
80
+ return taps > 1 ? t.taps(taps, keys) : keys;
81
+ }
82
+
83
+ const SHORT: Record<string, string> = {
84
+ Space: 'Spc', CapsLock: 'Caps', Backquote: '`', Insert: 'Ins', Delete: 'Del', PageUp: 'PgUp', PageDown: 'PgDn', ScrollLock: 'ScrLk',
85
+ Mouse3: 'M3', Mouse4: 'M4', Mouse5: 'M5',
86
+ };
87
+ const MAC_SHORT: Record<string, string> = { ...SHORT, Alt: 'Opt', Win: 'Cmd' };
88
+
89
+ /** `hotkey` in a few letters for the pet's microphone button: `Alt×2` for `LeftAlt*2`, sides dropped. */
90
+ export function hotkeyBadge(hotkey: string, platform: NodeJS.Platform = process.platform): string {
91
+ const short = platform === 'darwin' ? MAC_SHORT : SHORT;
92
+ const { combo, taps } = splitTaps(hotkey);
93
+ const keys = combo.split('+').map((k) => { const n = k.trim().replace(/^(Left|Right)/, ''); return short[n] ?? n; }).join('+');
94
+ return taps > 1 ? `${keys}×${taps}` : keys;
95
+ }
96
+
97
+ /**
98
+ * The modifier keys as device-dependent bits of CGEventFlags (IOKit's NX_DEVICE*KEYMASK in
99
+ * IOLLEvent.h), one bit per physical key; a code with two bits is down when either is.
100
+ * CGEventSourceKeyState does not report the right-hand modifiers, these bits do.
101
+ */
102
+ const MAC_MODIFIERS: Record<number, number> = {
103
+ 0x11: 0x0001 | 0x2000, 0xa2: 0x0001, 0xa3: 0x2000,
104
+ 0x10: 0x0002 | 0x0004, 0xa0: 0x0002, 0xa1: 0x0004,
105
+ 0x5b: 0x0008 | 0x0010, 0x5c: 0x0010,
106
+ 0x12: 0x0020 | 0x0040, 0xa4: 0x0020, 0xa5: 0x0040,
107
+ };
108
+
109
+ /** Whether the modifier `vk` is down in `flags`, as CGEventSourceFlagsState returns them; false for any other key. */
110
+ export const macModifierDown = (vk: number, flags: number): boolean => (flags & (MAC_MODIFIERS[vk] ?? 0)) !== 0;
111
+
112
+ /**
113
+ * macOS key codes (kVK_*) for the other Windows virtual-key codes `parseHotkey` gives. Mouse
114
+ * buttons are CGMouseButton numbers, apart.
115
+ */
116
+ const MAC_KEYS: Record<number, number[]> = {
117
+ 0x20: [0x31], 0x09: [0x30], 0x14: [0x39], 0xc0: [0x32], 0x0d: [0x24],
118
+ 0x2d: [0x72], 0x2e: [0x75], 0x24: [0x73], 0x23: [0x77], 0x21: [0x74], 0x22: [0x79],
119
+ // A–Z and 0–9 where the ANSI layout places them
120
+ 0x41: [0x00], 0x42: [0x0b], 0x43: [0x08], 0x44: [0x02], 0x45: [0x0e], 0x46: [0x03], 0x47: [0x05], 0x48: [0x04], 0x49: [0x22],
121
+ 0x4a: [0x26], 0x4b: [0x28], 0x4c: [0x25], 0x4d: [0x2e], 0x4e: [0x2d], 0x4f: [0x1f], 0x50: [0x23], 0x51: [0x0c], 0x52: [0x0f],
122
+ 0x53: [0x01], 0x54: [0x11], 0x55: [0x20], 0x56: [0x09], 0x57: [0x0d], 0x58: [0x07], 0x59: [0x10], 0x5a: [0x06],
123
+ 0x30: [0x1d], 0x31: [0x12], 0x32: [0x13], 0x33: [0x14], 0x34: [0x15], 0x35: [0x17], 0x36: [0x16], 0x37: [0x1a], 0x38: [0x1c], 0x39: [0x19],
124
+ // F1–F20
125
+ 0x70: [0x7a], 0x71: [0x78], 0x72: [0x63], 0x73: [0x76], 0x74: [0x60], 0x75: [0x61], 0x76: [0x62], 0x77: [0x64], 0x78: [0x65],
126
+ 0x79: [0x6d], 0x7a: [0x67], 0x7b: [0x6f], 0x7c: [0x69], 0x7d: [0x6b], 0x7e: [0x71], 0x7f: [0x6a], 0x80: [0x40], 0x81: [0x4f],
127
+ 0x82: [0x50], 0x83: [0x5a],
128
+ };
129
+ const MAC_BUTTONS: Record<number, number> = { 0x04: 2, 0x05: 3, 0x06: 4 };
130
+
131
+ /** The Windows virtual-key codes a Mac can read; the rest have no Mac key. */
132
+ export const macReadable = (vk: number): boolean => MAC_MODIFIERS[vk] !== undefined || MAC_KEYS[vk] !== undefined || MAC_BUTTONS[vk] !== undefined;
133
+
134
+ export interface KeyWatcher {
135
+ stop(): void;
136
+ }
137
+
138
+ /** The keyboard and mouse buttons as one hotkey reads them. */
139
+ interface KeyReader {
140
+ /** Whether one Windows virtual-key code is down right now. */
141
+ down(vk: number): boolean;
142
+ /** Whether any key or mouse button outside the hotkey is down right now. */
143
+ others(): boolean;
144
+ }
145
+
146
+ /** The codes GetAsyncKeyState reports down along with each modifier: the generic code with either side, a side with the generic code. */
147
+ const WIN_ALIASES: Record<number, number[]> = {
148
+ 0x10: [0xa0, 0xa1], 0xa0: [0x10], 0xa1: [0x10],
149
+ 0x11: [0xa2, 0xa3], 0xa2: [0x11], 0xa3: [0x11],
150
+ 0x12: [0xa4, 0xa5], 0xa4: [0x12], 0xa5: [0x12],
151
+ };
152
+
153
+ async function windowsReader(keys: number[], t: PetText['hotkey']): Promise<KeyReader | string> {
154
+ try {
155
+ const koffi = (await import('koffi')).default;
156
+ const getKey = koffi.load('user32.dll').func('short __stdcall GetAsyncKeyState(int vKey)') as (vk: number) => number;
157
+ // the high bit is set while the key is down
158
+ const down = (vk: number) => (getKey(vk) & 0x8000) !== 0;
159
+ const own = new Set(keys.flatMap((vk) => [vk, ...(WIN_ALIASES[vk] ?? [])]));
160
+ // virtual-key codes 0x01–0xFE, mouse buttons included
161
+ const rest = Array.from({ length: 0xfe }, (_, i) => i + 1).filter((vk) => !own.has(vk));
162
+ return { down, others: () => rest.some(down) };
163
+ } catch (err) {
164
+ return t.cannotRead((err as Error).message);
165
+ }
166
+ }
167
+
168
+ async function macReader(keys: number[], t: PetText['hotkey']): Promise<KeyReader | string> {
169
+ if (!keys.every(macReadable)) return t.macNoKey;
170
+ try {
171
+ const koffi = (await import('koffi')).default;
172
+ const cg = koffi.load('/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics');
173
+ const preflight = cg.func('bool CGPreflightListenEventAccess()') as () => boolean;
174
+ const request = cg.func('bool CGRequestListenEventAccess()') as () => boolean;
175
+ // asks once; the answer takes effect after the app restarts
176
+ if (!preflight() && !request()) return t.macPermission;
177
+ const flagsState = cg.func('uint64_t CGEventSourceFlagsState(int32_t state)') as (state: number) => number | bigint;
178
+ const keyState = cg.func('bool CGEventSourceKeyState(int32_t state, uint16_t key)') as (state: number, key: number) => boolean;
179
+ const buttonState = cg.func('bool CGEventSourceButtonState(int32_t state, uint32_t button)') as (state: number, button: number) => boolean;
180
+ // kCGEventSourceStateHIDSystemState: the hardware, whichever app has the keyboard
181
+ const HID = 1;
182
+ const ownBits = keys.reduce((bits, vk) => bits | (MAC_MODIFIERS[vk] ?? 0), 0);
183
+ const restBits = Object.values(MAC_MODIFIERS).reduce((bits, b) => bits | b, 0) & ~ownBits;
184
+ const ownKeys = new Set(keys.flatMap((vk) => MAC_KEYS[vk] ?? []));
185
+ // kVK 0x36–0x3E are the modifiers, read from the flags instead, and Caps Lock, a toggle left unread
186
+ const restKeys = Array.from({ length: 0x80 }, (_, k) => k).filter((k) => (k < 0x36 || k > 0x3e) && !ownKeys.has(k));
187
+ const restButtons = [0, 1, 2, 3, 4].filter((b) => !keys.some((vk) => MAC_BUTTONS[vk] === b));
188
+ return {
189
+ down: (vk) => {
190
+ if (MAC_BUTTONS[vk] !== undefined) return buttonState(HID, MAC_BUTTONS[vk]!);
191
+ if (MAC_MODIFIERS[vk] !== undefined) return macModifierDown(vk, Number(flagsState(HID)));
192
+ return (MAC_KEYS[vk] ?? []).some((k) => keyState(HID, k));
193
+ },
194
+ others: () => (Number(flagsState(HID)) & restBits) !== 0
195
+ || restKeys.some((k) => keyState(HID, k)) || restButtons.some((b) => buttonState(HID, b)),
196
+ };
197
+ } catch (err) {
198
+ return t.cannotRead((err as Error).message);
199
+ }
200
+ }
201
+
202
+ /**
203
+ * X11 keysyms for the Windows virtual-key codes `parseHotkey` gives; a code listed with several
204
+ * keysyms is down when any of their keys is. The middle mouse button is read from the pointer.
205
+ */
206
+ const LINUX_KEYS: Record<number, number[]> = {
207
+ 0x11: [0xffe3, 0xffe4], 0xa2: [0xffe3], 0xa3: [0xffe4],
208
+ // right Alt is AltGr (ISO_Level3_Shift) on many layouts
209
+ 0x12: [0xffe9, 0xffea, 0xfe03], 0xa4: [0xffe9], 0xa5: [0xffea, 0xfe03],
210
+ 0x10: [0xffe1, 0xffe2], 0xa0: [0xffe1], 0xa1: [0xffe2],
211
+ 0x5b: [0xffeb, 0xffec], 0x5c: [0xffec],
212
+ 0x20: [0x20], 0x09: [0xff09], 0x14: [0xffe5], 0xc0: [0x60], 0x0d: [0xff0d],
213
+ 0x2d: [0xff63], 0x2e: [0xffff], 0x24: [0xff50], 0x23: [0xff57], 0x21: [0xff55], 0x22: [0xff56],
214
+ 0x13: [0xff13], 0x91: [0xff14],
215
+ };
216
+ const linuxKeysyms = (vk: number): number[] => LINUX_KEYS[vk]
217
+ ?? (vk >= 0x41 && vk <= 0x5a ? [vk + 0x20] : vk >= 0x30 && vk <= 0x39 ? [vk] : vk >= 0x70 && vk <= 0x87 ? [0xffbe + vk - 0x70] : []);
218
+ /** Button2Mask of XQueryPointer's state: the middle button. The side buttons are not in it. */
219
+ const LINUX_BUTTONS: Record<number, number> = { 0x04: 1 << 9 };
220
+ /** Button1Mask to Button3Mask: the left, middle and right buttons. Button4 and Button5 are the wheel. */
221
+ const LINUX_POINTER_BUTTONS = 0b111 << 8;
222
+
223
+ /** The Windows virtual-key codes X11 can read here. */
224
+ export const linuxReadable = (vk: number): boolean => linuxKeysyms(vk).length > 0 || LINUX_BUTTONS[vk] !== undefined;
225
+
226
+ async function linuxReader(keys: number[], t: PetText['hotkey']): Promise<KeyReader | string> {
227
+ if (!keys.every(linuxReadable)) return t.linuxNoKey;
228
+ if (!process.env.DISPLAY) return t.linuxNoDisplay;
229
+ try {
230
+ const koffi = (await import('koffi')).default;
231
+ const x11 = koffi.load('libX11.so.6');
232
+ const open = x11.func('void *XOpenDisplay(const char *name)') as (name: null) => unknown;
233
+ const dpy = open(null);
234
+ if (!dpy) return t.linuxNoX11;
235
+ const keymap = x11.func('int XQueryKeymap(void *dpy, _Out_ uint8_t *keys)') as (d: unknown, out: Uint8Array) => number;
236
+ const toCode = x11.func('uint8_t XKeysymToKeycode(void *dpy, unsigned long keysym)') as (d: unknown, sym: number) => number;
237
+ const root = (x11.func('unsigned long XDefaultRootWindow(void *dpy)') as (d: unknown) => number)(dpy);
238
+ const pointer = 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)') as (...a: unknown[]) => number;
239
+ const codes = new Map(keys.map((vk) => [vk, linuxKeysyms(vk).map((s) => toCode(dpy, s)).filter(Boolean)]));
240
+ const own = new Set([...codes.values()].flat());
241
+ const restButtons = keys.reduce((mask, vk) => mask & ~(LINUX_BUTTONS[vk] ?? 0), LINUX_POINTER_BUTTONS);
242
+ const bits = new Uint8Array(32);
243
+ const isDown = (c: number) => (bits[c >> 3]! & (1 << (c & 7))) !== 0;
244
+ const buttons = () => {
245
+ const m = [0];
246
+ pointer(dpy, root, [0], [0], [0], [0], [0], [0], m);
247
+ return m[0]!;
248
+ };
249
+ // XQueryKeymap is the X server's own key state: under Wayland, XWayland knows it only while an X window has the keyboard
250
+ return {
251
+ down: (vk) => {
252
+ if (LINUX_BUTTONS[vk] !== undefined) return (buttons() & LINUX_BUTTONS[vk]!) !== 0;
253
+ keymap(dpy, bits);
254
+ return (codes.get(vk) ?? []).some(isDown);
255
+ },
256
+ others: () => {
257
+ keymap(dpy, bits);
258
+ for (let c = 0; c < 256; c++) if (!own.has(c) && isDown(c)) return true;
259
+ return (buttons() & restButtons) !== 0;
260
+ },
261
+ };
262
+ } catch (err) {
263
+ return t.cannotRead((err as Error).message);
264
+ }
265
+ }
266
+
267
+ /** Longest press that counts as a tap; a hold activates only after this duration. */
268
+ export const TAP_MAX_MS = 300;
269
+ /** Longest pause between a tap's release and the next press; Windows' double-click time (500 ms, press to press) minus a tap. */
270
+ export const TAP_GAP_MS = 400;
271
+
272
+ /**
273
+ * The final press activates immediately, after a hold, or on a quick release. `holdAlone` is a hold with no other key or
274
+ * mouse button down before it activates and no quick tap of its own keys just before the sequence, so a hotkey that
275
+ * taps the same keys first (the talk key's tap and hold) does not set it off.
276
+ */
277
+ export type HotkeyTrigger = 'press' | 'hold' | 'holdAlone' | 'tap';
278
+
279
+ /**
280
+ * Samples the raw key state on every poll, including while held, with `others` true while another
281
+ * key or mouse button is down too. `onChange` pairs activation with release; a completed tap emits
282
+ * both at once. `onTap` reports the preceding quick taps. `onRelease` reports every raw release,
283
+ * including a tap that never activated the hotkey. A press that sampled `others` is part of a
284
+ * shortcut: no tap, and the count starts over.
285
+ */
286
+ export function tapTracker(taps: number, onChange: (down: boolean) => void, onTap: (count: number) => void = () => {}, trigger: HotkeyTrigger = 'press', onRelease: () => void = () => {}) {
287
+ let count = 0, lastUp = -Infinity, pressAt = 0, active = false, wasDown = false, mixed = false, tappedBefore = false;
288
+ return (down: boolean, now: number, others = false): void => {
289
+ if (down === wasDown) {
290
+ if (down) mixed ||= others;
291
+ const holds = trigger === 'hold' || (trigger === 'holdAlone' && !mixed && !tappedBefore);
292
+ if (down && holds && !active && count === taps - 1 && now - pressAt > TAP_MAX_MS) {
293
+ count = 0; active = true; onChange(true);
294
+ }
295
+ return;
296
+ }
297
+ wasDown = down;
298
+ if (down) {
299
+ if (count && now - lastUp > TAP_GAP_MS) count = 0;
300
+ pressAt = now;
301
+ mixed = others;
302
+ // a quick tap just ended a sequence of its own: this press continues that one
303
+ tappedBefore = count === 0 && now - lastUp <= TAP_GAP_MS;
304
+ if (count === taps - 1 && trigger === 'press') { count = 0; active = true; onChange(true); }
305
+ return;
306
+ }
307
+ onRelease();
308
+ if (active) { active = false; onChange(false); return; }
309
+ if (mixed || now - pressAt > TAP_MAX_MS) { count = 0; return; }
310
+ count++; lastUp = now;
311
+ if (count === taps) {
312
+ count = 0;
313
+ if (trigger === 'tap') { onChange(true); onChange(false); }
314
+ } else onTap(count);
315
+ };
316
+ }
317
+
318
+ /**
319
+ * Calls `onChange` when `trigger` activates and releases `hotkey`, and `onTap` on each preceding quick tap;
320
+ * `onRelease` also reports releases before activation. Returns why the key cannot be read instead, in the words of `t`.
321
+ */
322
+ export async function watchHotkey(hotkey: Hotkey, onChange: (down: boolean) => void, pollMs: number, onTap?: (count: number) => void, t: PetText['hotkey'] = petText().hotkey, trigger: HotkeyTrigger = 'press', onRelease?: () => void): Promise<KeyWatcher | string> {
323
+ const { keys, taps } = hotkey;
324
+ const reader = process.platform === 'win32' ? await windowsReader(keys, t)
325
+ : process.platform === 'darwin' ? await macReader(keys, t)
326
+ : process.platform === 'linux' ? await linuxReader(keys, t)
327
+ : t.unsupported;
328
+ if (typeof reader === 'string') return reader;
329
+ const step = tapTracker(taps, onChange, onTap, trigger, onRelease);
330
+ const timer = setInterval(() => {
331
+ const down = keys.every((vk) => reader.down(vk));
332
+ step(down, performance.now(), down && reader.others());
333
+ }, pollMs);
334
+ return { stop: () => clearInterval(timer) };
335
+ }
@@ -0,0 +1,51 @@
1
+ /** What a recognizer returns for one utterance, and the filter for lines that are not speech. */
2
+
3
+ export interface TranscribeResult {
4
+ text: string;
5
+ ms: number;
6
+ /** null on success. */
7
+ error: string | null;
8
+ }
9
+
10
+ /**
11
+ * Fallback for models that write text for audio without speech: on noise they produce
12
+ * high-frequency lines from their training subtitles, which cannot be told apart from real speech
13
+ * by content, so they are blocked by list; Whisper also labels sounds in brackets, parentheses or
14
+ * asterisks (`[Musik]`, `(звук пива)`, `*Bruit de la porte*`), sometimes cut off before the
15
+ * closing mark. Letting one through means an event claims a sentence nobody said. Words a person
16
+ * also says (订阅, 转发, 字幕, 谢谢观看) block a line only in the credits' own phrasing or as the
17
+ * whole line, so a sentence that mentions them reaches the bot.
18
+ */
19
+ const HALLUCINATION_PATTERNS: readonly RegExp[] = [
20
+ /^[\s。.,、!?!?…~-]*$/,
21
+ /请不吝点赞|明镜与点点栏目|字幕(?:由|志愿者|组|制作|提供|翻译|by|[::])/i,
22
+ /^[\s\p{P}]*谢谢观看[\s\p{P}]*$/u,
23
+ /^(?:[\s\p{P}]*(?:点赞|订阅|转发|打赏)){2,}[\s\p{P}]*$/u,
24
+ /^(thank you|thanks for watching|subtitles by|you)[\s.!]*$/i,
25
+ /^\s*(sous-titr|untertitel|subt[ií]tulos|legendas|sottotitoli|субтитр)/i,
26
+ /^\s*[[((【*♪]/,
27
+ ];
28
+
29
+ /** Written without spaces between words. */
30
+ const UNSPACED_END = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]$/u;
31
+ const UNSPACED_START = /^[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u;
32
+
33
+ /**
34
+ * Sentences heard one after another: a space before one that starts with a letter or digit after
35
+ * a letter, digit or ASCII punctuation, unless either side is Chinese or Japanese.
36
+ */
37
+ export function joinSpeech(pieces: readonly string[]): string {
38
+ let out = '';
39
+ for (const p of pieces) {
40
+ if (!p) continue;
41
+ const spaced = /[\p{L}\p{N}.,!?;:]$/u.test(out) && !UNSPACED_END.test(out) && /^[\p{L}\p{N}]/u.test(p) && !UNSPACED_START.test(p);
42
+ out += spaced ? ` ${p}` : p;
43
+ }
44
+ return out;
45
+ }
46
+
47
+ export function looksHallucinated(text: string): boolean {
48
+ const t = text.trim();
49
+ if (!t) return true;
50
+ return HALLUCINATION_PATTERNS.some((re) => re.test(t));
51
+ }