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
package/src/world.ts ADDED
@@ -0,0 +1,2926 @@
1
+ /**
2
+ * DesktopPetWorld: the pet on the desktop as a World.
3
+ *
4
+ * Output goes through four tools that drive the pet page (bubble, options, going somewhere,
5
+ * expressions and motions). Input arrives as events: speech heard through the pet window's
6
+ * microphone (transcribed in this process by FunASR's SenseVoice or by Whisper, by Windows' own recognizer, or by an
7
+ * OpenAI-compatible transcription service; the recording goes along when the endpoint takes audio), typed text, answers to `speed_pet_ask`, and touches
8
+ * (poke, petting, being thrown). The page reports what actually happened; receipts and
9
+ * events state only that.
10
+ *
11
+ * Processes owned here: the page server (always, while mounted), the pet window (when
12
+ * `window.enabled`) and the system recognizer's helper (voice input on, engine `system`). FunASR and
13
+ * Whisper run in this process once their model is downloaded.
14
+ *
15
+ * Two languages are read at each use: the model-text language for what the bot reads, and the app
16
+ * language (`DesktopPetWorldOptions.language`) for what the person reads: the pages' text (the
17
+ * snapshot carries it, so the pages follow a change within PREFS_SYNC_MS), status lines, voice
18
+ * hints, the default name for the person, and which recognizer and recognition language voice
19
+ * input uses by default. The console's text follows the console request's language.
20
+ */
21
+ import type { spawn } from 'node:child_process';
22
+ import { randomUUID } from 'node:crypto';
23
+ import { existsSync } from 'node:fs';
24
+ import { fileURLToPath } from 'node:url';
25
+ import { join } from 'node:path';
26
+ import type {
27
+ BlobInput, EventEnvelope, Logger, OutputTap, RunPhase, ToolCallContext, ToolDef, ToolOutcome, TriggerMode, World, WorldWebUiDecl,
28
+ WorldHost, WorldLamp, WorldPanelDecl, WorldStreamSocket,
29
+ } from 'cortico/core/types.ts';
30
+ import { nowIso, shortTime } from 'cortico/core/util.ts';
31
+ import type { Language } from 'cortico/core/language.ts';
32
+ import type { DeepPartial } from 'cortico/world.ts';
33
+ import {
34
+ DESKTOP_PET_ID, MAX_HOVER_BUTTONS, MAX_LOOK_NAME, MAX_SAVED_LOOKS, PET_ACTIONS, RECORDING_MINUTES_MAX, RECORDING_MINUTES_MIN, SELF_KEYS, THRESHOLD_DB_MAX,
35
+ THRESHOLD_DB_MIN, TOUCH_KINDS, USER_MAX, asrEngineFor,
36
+ desktopPetConfigGroups, directSettings, fadeOf, hoverButtonList, scaleOf, selfAdjustMode, speechFor, touchWakes,
37
+ type AsrEngine, type DesktopPetConfigSection, type MicMode, type PetSkin, type PetTheme, type SavedLook, type RoamMode, type SelfKey,
38
+ } from './config.ts';
39
+ import { capFor, cutChars, petText, type PetText } from './i18n/index.ts';
40
+ import { SpeechText, speechTextSteps } from './speech/index.ts';
41
+ import { PetServer, type PageMessage } from './server.ts';
42
+ import { connectActivity, type ActivitySnapshot } from '../activity.js';
43
+ import { StatusTracker, type DescribeTool } from './status.ts';
44
+ import { WindowHost, resolveHostCommand } from './window-host.ts';
45
+ import { describeHostReason } from './host-reason.ts';
46
+ import { RuntimeStore, type ModelSpec } from './runtime/store.ts';
47
+ import { SENSEVOICE, SherpaAsr, WHISPER, type SherpaModelKind, type SherpaModule, type SherpaState } from './asr/sherpa.ts';
48
+ import { SystemRecognizer, systemRecognizerSupported, type SystemRecognizerState, type SystemSentence } from './asr/system-recognizer.ts';
49
+ import { SAMPLE_RATE, TranscriptionApi, wavFile, type TranscriptionState } from './asr/transcription-api.ts';
50
+ import { Packer, SILENT_BELOW_DB, Segmenter, peakDb, rmsDb, type SegmentConfig, type SegmentSink, type Utterance } from './asr/segmenter.ts';
51
+ import { comboLabel, hotkeyBadge, hotkeyLabel, parseHotkey, splitTaps, TAP_MAX_MS, watchHotkey, type HotkeyTrigger, type KeyWatcher } from './asr/hotkey.ts';
52
+ import { joinSpeech, looksHallucinated } from './asr/result.ts';
53
+ import { toSimplified } from './asr/simplify.ts';
54
+ import { estimateSeconds, parseActions, parseScript, vocabChange, vocabTable, type VocabWord } from './script.ts';
55
+ import { ActivityGroup, ChatSockets, SELF_TYPE, chatHistory, chatItem, chatRefs, type ChatFigure } from './chat.ts';
56
+ import { ASK_OPTION_MAX, petToolDecls } from './tools.ts';
57
+ import { COO, figurePacks, lookOf, lookPatch, modelName, nameIn, packFor, type FigurePack, type MoveTarget, type PackProblem, type PackScan } from './packs.ts';
58
+ import { moveChange, moveTable, readMove } from './moves.ts';
59
+ import { Cua } from './cua/cua.ts';
60
+ import { CUA_OFF_TOOL_DECLS } from './cua/tools.ts';
61
+ import type { Answer } from './cua/engine-ipc.ts';
62
+ import { DressZipImport, PackImporter } from './pack-import.ts';
63
+ import { dressTable, planSettings, sayScale, type SettingChange } from './self.ts';
64
+ import { FIREWORKS_WORD, MODEL_TEXT, type ModelLanguage, type ModelText, type NoPortrait } from './model-text.ts';
65
+
66
+ /** The console panels, titled in `language`. */
67
+ function desktopPetPanelDecls(language: Language = 'zh'): WorldPanelDecl[] {
68
+ const p = petText(language).console.panels;
69
+ return [
70
+ { id: 'pet', ...p.pet, getMethods: ['state'] },
71
+ { id: 'voice', ...p.voice, getMethods: ['state'] },
72
+ ];
73
+ }
74
+
75
+ /** The culture of Windows' speech recognizer preferred for each app language, where its language has more than one. */
76
+ const SYSTEM_CULTURES: Readonly<Record<string, string>> = {
77
+ zh: 'zh-CN', 'zh-Hant': 'zh-TW', en: 'en-US', fr: 'fr-FR', de: 'de-DE', 'es-419': 'es-MX', 'pt-BR': 'pt-BR', it: 'it-IT', ru: 'ru-RU', ja: 'ja-JP', ko: 'ko-KR',
78
+ };
79
+
80
+ const WEB_DIR = fileURLToPath(new URL('../web/', import.meta.url));
81
+ const SPEECH_DATA = fileURLToPath(new URL('./speech/data/', import.meta.url));
82
+ /** The environment prompt template of each model-text language; English falls back to Chinese while its file is missing. */
83
+ const ENV_PROMPT_FILES: Record<ModelLanguage, string> = {
84
+ zh: fileURLToPath(new URL('./ENV_PROMPT.md', import.meta.url)),
85
+ en: fileURLToPath(new URL('./ENV_PROMPT.en.md', import.meta.url)),
86
+ };
87
+
88
+ /** Longest `speed_pet_quiet`: a quiet that outlasts a day is a setting, which `speed_pet_set` changes. */
89
+ const QUIET_MAX_MIN = 24 * 60;
90
+ const FRAME_MS = 20;
91
+ const WALK_TIMEOUT_MS = 30_000;
92
+ /**
93
+ * How long `speed_pet_see_self` waits for the pet page's picture. The page waits up to 400 ms for its frame and the
94
+ * display's (web/pet-app.js), the window takes about 50 ms to copy a frame (host/overlay.cjs) and less than that
95
+ * to encode a picture of at most a megapixel: ten times the sum.
96
+ */
97
+ const PORTRAIT_TIMEOUT_MS = 5000;
98
+ /** Touches of one kind closer than this are reported as one event with a count. */
99
+ const TOUCH_MERGE_MS = 2500;
100
+ /** How long a confirmation bubble waits for an answer, counted from when the page shows it. */
101
+ const CONFIRM_TIMEOUT_MS = 60_000;
102
+ /** How long a confirmation waits in all, while the page has not shown it (lines ahead of it in the queue). */
103
+ const CONFIRM_UNSHOWN_MS = 180_000;
104
+ /** History events read per chat page load; the page asks for the ones before by cursor. */
105
+ const CHAT_PAGE_EVENTS = 300;
106
+ /** A message from the chat page: text cut to this, up to IMAGES_MAX images of at most IMAGE_MAX_BYTES each, as the console World takes them. */
107
+ const CHAT_TEXT_MAX = 4000;
108
+ /** Text cut to these: the pet's typing box, and a written answer to `speed_pet_ask` from either page. The pages are told each cap and hold back longer text. */
109
+ const BOX_TEXT_MAX = 500;
110
+ const ANSWER_TEXT_MAX = 500;
111
+ const IMAGES_MAX = 8;
112
+ const IMAGE_MAX_BYTES = 8 * 1024 * 1024;
113
+ const IMAGE_MIMES = new Set(['image/jpeg', 'image/png', 'image/webp', 'image/gif']);
114
+ /** How often config edits from the console reach the pages: short enough that the size slider moves the pet with it. */
115
+ const PREFS_SYNC_MS = 150;
116
+ /** Talk-key polling interval: well under the shortest key tap. */
117
+ const HOTKEY_POLL_MS = 30;
118
+ /**
119
+ * Longest time from the physical press to hold activation, rounded up to whole audio frames: the
120
+ * press is seen up to one poll late, and TAP_MAX_MS being exceeded up to one more poll late.
121
+ */
122
+ const HOLD_PRE_ROLL_FRAMES = Math.ceil((TAP_MAX_MS + 2 * HOTKEY_POLL_MS) / FRAME_MS);
123
+ /**
124
+ * A microphone the talk key opened (`asr.mic.openOnPress`) closes this long after the key goes up,
125
+ * so a press right after a release finds it open. The end of speech does not wait on it: the
126
+ * segmenter is flushed when the key goes up, and frames that arrive later are not used.
127
+ */
128
+ const MIC_RELEASE_MS = 500;
129
+ /** Holidays the bot is told of, by the person's local date: `MM-DD` every year, `YYYY-MM-DD` once. */
130
+ const HOLIDAYS: Record<keyof ModelText['holiday'], string> = { christmas: '12-25', newYear2027: '2027-01-01' };
131
+ const HOLIDAY_TYPE = 'agent-speed.holiday';
132
+ /** How often the World looks for a holiday that began while the pet is on the desktop. */
133
+ const HOLIDAY_CHECK_MS = 60_000;
134
+ /** The New Year fireworks as `speed_pet_act` takes them while they are offered; the pet page draws them. */
135
+ const FIREWORKS: VocabWord = { id: FIREWORKS_WORD, kind: 'motion', names: {}, about: {}, seconds: 0 };
136
+
137
+ /**
138
+ * Run controls an embedding app lends the pet's menu. Each button shows only when its control is
139
+ * lent: pause/resume needs `isPaused` and `setPaused`, settings `openSettings`, the power button
140
+ * `quit`. Without any the menu shows the actions alone.
141
+ */
142
+ export interface PetBotControls {
143
+ isPaused?(): boolean;
144
+ setPaused?(paused: boolean): void;
145
+ openSettings?(): void;
146
+ /** Shows the app's computer-use switch together with what turning it on risks; while computer use is off, `speed_pet_cua_open_settings` calls it. */
147
+ openCuaSettings?(): void;
148
+ /** Shows the chat page; the bubble's expand button carries its draft there. */
149
+ openChat?(): void;
150
+ /** Shows the embedding app's own dress page; the menu's 「装扮」 then opens it instead of the pet's dress window. */
151
+ openDress?(): void;
152
+ /** Shows the embedding app's list of its Worlds; the hover button 「我的 World」 shows only when this is lent. */
153
+ openWorlds?(): void;
154
+ quit?(): void;
155
+ /** The power button's label, e.g. "Quit Coopanion", read when the menu opens. */
156
+ quitLabel?: string | (() => string);
157
+ /** Runs the embedding app's introduction again (the console's `pet.guide` panel method). */
158
+ guide?(): void;
159
+ }
160
+
161
+ /**
162
+ * One step of a conversation an embedding app holds through the pet's bubble (`dialog`): Coo says
163
+ * `text`, then shows `input`, if any, in the same bubble. `step` draws progress dots, `closable`
164
+ * a close button, `back` a button with that label before the dots.
165
+ */
166
+ export interface PetDialog {
167
+ text: string;
168
+ /** Words in `text` drawn in the theme color, such as a name said for the first time. */
169
+ marks?: string[];
170
+ /** Expressions and motions (vocabulary words) played as the line starts. */
171
+ actions?: string[];
172
+ step?: [number, number];
173
+ closable?: boolean;
174
+ back?: string;
175
+ input?: PetDialogInput;
176
+ }
177
+
178
+ /**
179
+ * - `buttons`: a row of buttons, answered with the index; a button's `hover` is the label it shows while pointed at or
180
+ * focused. `keys` shows a key cap above them, pressed `taps` times over and over, the last press held (a talk key
181
+ * tapped, then held).
182
+ * - `choices`: cards to try out before `confirm`, each with an optional level tag, a small `note` under its label, and icon (a web/ui.js
183
+ * `ICONS` name, or `image`, a `data:image/…` URL such as a service's logo); a card's `line` is typed when it is picked and
184
+ * its `motion` played (standing still, strolling, running about) until another is picked, and its `actions` (vocabulary
185
+ * words) once. A card's `skin` dresses the body in it while the card is picked, and stays on when it is the answer;
186
+ * closing the step puts the body back as the config has it. A card's `tint` (light and dark theme), or else the eye colour of
187
+ * its skin's Coo palette, colours its icon.
188
+ * `list` lays the cards out one per row; `hint` is a line beside the confirm button with `mark`, a word in it, drawn
189
+ * after the `icon` of that name. `more` is a last card that,
190
+ * clicked, unfolds its `options` after the others in place; the answer's index counts on through them, and a `value`
191
+ * among them shows them from the start.
192
+ * - `pick`: cards like `choices`, any number of them picked, from `min` (1 when absent) to `max`, answered with
193
+ * the indices picked (`picked`), in the cards' order; `value` are the ones picked from the start. How many are picked
194
+ * shows beside the confirm button, which waits for `min`.
195
+ * - `text`: a text box answered with the text; `secret` hides what is typed, `suggestions` are offered
196
+ * as the person types, `link` opens a page in the browser, `alt` is a second way out, answered as `{ alt: true }`.
197
+ * - `progress`: a bar the app moves with `update({ progress })`; it ends when the app closes it.
198
+ */
199
+ export type PetDialogInput =
200
+ | { kind: 'buttons'; options: Array<{ label: string; primary?: boolean; hover?: string }>; keys?: string; taps?: number }
201
+ | { kind: 'choices'; options: PetDialogChoice[]; more?: { label: string; icon?: string; image?: string; options: PetDialogChoice[] }; value?: number; confirm: string; list?: boolean; hint?: { text: string; mark: string; icon: string } }
202
+ | { kind: 'pick'; options: PetDialogChoice[]; value?: number[]; min?: number; max: number; confirm: string }
203
+ | { kind: 'text'; submit: string; placeholder?: string; value?: string; secret?: boolean; maxLength?: number; suggestions?: string[]; link?: { label: string; url: string }; alt?: string }
204
+ | { kind: 'progress'; label?: string };
205
+ export type PetDialogChoice = {
206
+ label: string; level?: string; note?: string; icon?: string; image?: string; line?: string; motion?: 'still' | 'walk' | 'run';
207
+ actions?: string[]; skin?: Partial<PetSkin>; tint?: { light: string; dark: string };
208
+ };
209
+
210
+ /**
211
+ * How a step ended: a button or card (`index`), the cards of a `pick` (`picked`), typed text, the text box's `alt`, the close
212
+ * button, the back button, the line read to the end with nothing to answer (`done`, also a progress step the app
213
+ * closed), or no pet page to show it on.
214
+ */
215
+ export type PetDialogAnswer =
216
+ | { index: number } | { picked: number[] } | { text: string } | { alt: true } | { closed: true } | { back: true } | { done: true } | { unavailable: true };
217
+
218
+ /** What the app changes on a step while it is up: the line, and a progress step's bar (0–1, or null while there is no telling). */
219
+ export interface PetDialogUpdate {
220
+ text?: string;
221
+ progress?: number | null;
222
+ }
223
+
224
+ export interface PetDialogHandle {
225
+ readonly answer: Promise<PetDialogAnswer>;
226
+ update(patch: PetDialogUpdate): void;
227
+ /** Takes the step off the bubble; an unanswered one resolves `done`. */
228
+ close(): void;
229
+ }
230
+
231
+ /**
232
+ * How a confirmation ended: one of the choices (`always` only when three were offered), closed, no answer in time,
233
+ * or no pet page to ask on.
234
+ */
235
+ export type ConfirmResult = 'yes' | 'always' | 'no' | 'dismissed' | 'timeout' | 'unavailable';
236
+
237
+ export interface DesktopPetWorldOptions {
238
+ cfg: DesktopPetConfigSection;
239
+ timezone: string;
240
+ persist: (patch: DeepPartial<DesktopPetConfigSection>) => void;
241
+ runtimesRoot: () => string;
242
+ modelsDir: () => string;
243
+ /** Downloads; tests pass a local stand-in. */
244
+ fetchImpl?: typeof fetch;
245
+ /** Loads sherpa-onnx; tests pass a fake recognizer. */
246
+ loadSherpa?: () => SherpaModule;
247
+ /** The speech models to download; tests pass small ones. */
248
+ funasrModel?: ModelSpec;
249
+ whisperModel?: ModelSpec;
250
+ /** The transcription service's API Key, read at each request, and where the voice panel saves a new one; absent, there is none. */
251
+ asrApiKey?: () => string;
252
+ storeAsrApiKey?: (key: string) => void;
253
+ /** The bot's name for the menu header, the chat page and computer use's question; read at each use. */
254
+ botName?: () => string;
255
+ controls?: PetBotControls;
256
+ /** Reads the talk key; tests pass a scripted one. */
257
+ watchHotkey?: typeof watchHotkey;
258
+ /** Starts the system recognizer's helper; tests pass a fake. */
259
+ spawnSystemRecognizer?: typeof spawn;
260
+ /** Directories whose subdirectories are installed figure packs (src/packs.ts). */
261
+ packRoots?: () => string[];
262
+ /** The one of them the dressing page installs packs into (src/pack-import.ts); without it the page offers no import. */
263
+ packDir?: () => string;
264
+ /** Called after the bot changed settings itself (`speed_pet_set`), so an app watching the config knows it was not the person. */
265
+ onBotChange?: () => void;
266
+ /** Called when the pet window comes onto the desktop or leaves it: shown or hidden, opened or closed. */
267
+ onDesktopChange?: (onDesktop: boolean) => void;
268
+ /** Called when click-through is turned on or off, by the pet panel's `setClickThrough` or the pet's own button. */
269
+ onClickThroughChange?: (on: boolean) => void;
270
+ /** What the status bubble shows for a tool call. */
271
+ describeTool?: DescribeTool;
272
+ /** The language of what the bot reads from this World (`model-text.ts`), read at each use; Chinese when absent. */
273
+ modelLanguage?: () => ModelLanguage;
274
+ /** The app language: what the person reads (see the module header). Read at each use; `zh` when absent. */
275
+ language?: () => Language;
276
+ /**
277
+ * The language the bot is to talk to the person in, named in the model-text language, when it is
278
+ * not that language itself; it becomes one line of the environment prompt (`{{pet.reply}}`). Null
279
+ * or absent: no such line.
280
+ */
281
+ replyLanguage?: () => string | null;
282
+ /** Called with each answer to computer use's question, asked in the pet's bubble. */
283
+ onCuaAnswer?: (answer: Answer) => void;
284
+ }
285
+
286
+ type SherpaEngine = Exclude<AsrEngine, 'system' | 'api'>;
287
+ type BackendState = SherpaState | SystemRecognizerState | TranscriptionState;
288
+
289
+ interface PendingWalk {
290
+ resolve: (text: string) => void;
291
+ timer: NodeJS.Timeout;
292
+ /** The figure's target it goes to, as the bot reads its name; absent for a default target. */
293
+ target?: string;
294
+ /** The call's interrupt asked the page to stop the walk. */
295
+ stopping?: boolean;
296
+ }
297
+
298
+ /** What the pet page answered a `portrait` order with: the PNG and its size in pixels, or why there is none. */
299
+ type Portrait = { png: Buffer; width: number; height: number } | NoPortrait;
300
+ /** The reasons the page itself gives. */
301
+ const PAGE_NO_PORTRAIT: readonly string[] = ['tab', 'hidden', 'no-body', 'capture'] satisfies NoPortrait[];
302
+
303
+ interface PendingAsk {
304
+ id: string;
305
+ question: string;
306
+ options: string[];
307
+ }
308
+
309
+ interface TouchBatch {
310
+ kind: string;
311
+ count: number;
312
+ woke: boolean;
313
+ asleep: boolean;
314
+ x: number | null;
315
+ crashed: boolean;
316
+ timer: NodeJS.Timeout;
317
+ }
318
+
319
+ interface HeardLine { text: string; at: number; ms: number; dropped?: boolean }
320
+
321
+ interface PendingConfirm {
322
+ resolve: (result: ConfirmResult) => void;
323
+ /** How many choices the bubble shows: the last one is no. */
324
+ choices: number;
325
+ /** Ends the wait with 'timeout': CONFIRM_UNSHOWN_MS from the ask, then CONFIRM_TIMEOUT_MS from when it was shown. */
326
+ timer: NodeJS.Timeout;
327
+ shown: boolean;
328
+ }
329
+
330
+ /** Characters a step's line is shown for per second (typing, then reading), for its time limit. */
331
+ const DIALOG_CPS = 4;
332
+
333
+ let seq = 0;
334
+ const nextId = (p: string) => `${p}${Date.now().toString(36)}${(seq++).toString(36)}`;
335
+ const samplesIn = (parts: readonly Int16Array[]) => parts.reduce((n, p) => n + p.length, 0);
336
+ const pct = (fraction: number) => `${Math.round(fraction * 100)}%`;
337
+
338
+ /** The first expression among a beat's words for the chat page's tag: its id, and its first name in each language of the body's vocabulary. */
339
+ function moodOf(actions: readonly string[], vocab: readonly VocabWord[]): { mood?: Record<string, string> } {
340
+ const v = actions.map((a) => vocab.find((e) => e.id === a)).find((e) => e?.kind === 'expression' && e.id !== 'neutral');
341
+ if (!v) return {};
342
+ return { mood: { id: v.id, ...Object.fromEntries(Object.entries(v.names).flatMap(([lang, names]) => (names[0] ? [[lang, names[0]]] : []))) } };
343
+ }
344
+
345
+ /** Images of a chat page message: the whole batch is taken, or the reason it is not. */
346
+ function parseChatImages(raw: unknown, user: string, s: PetText['chat'], m: ModelText): { ok: true; blobs: BlobInput[] } | { ok: false; reason: string } {
347
+ if (raw === undefined) return { ok: true, blobs: [] };
348
+ if (!Array.isArray(raw)) return { ok: false, reason: s.badImages };
349
+ if (raw.length > IMAGES_MAX) return { ok: false, reason: s.tooManyImages(IMAGES_MAX) };
350
+ const blobs: BlobInput[] = [];
351
+ for (const [i, item] of raw.entries()) {
352
+ const img = (item ?? {}) as { mime?: unknown; base64?: unknown; name?: unknown };
353
+ if (typeof img.mime !== 'string' || !IMAGE_MIMES.has(img.mime)) return { ok: false, reason: s.badMime(String(img.mime)) };
354
+ const bytes = typeof img.base64 === 'string' ? Buffer.from(img.base64, 'base64') : Buffer.alloc(0);
355
+ if (bytes.length === 0) return { ok: false, reason: s.emptyImage };
356
+ if (bytes.length > IMAGE_MAX_BYTES) return { ok: false, reason: s.bigImage(IMAGE_MAX_BYTES / 1048576) };
357
+ const name = typeof img.name === 'string' && img.name.trim() ? img.name.trim().slice(0, 120) : undefined;
358
+ blobs.push({ bytes, mime: img.mime, ...(name ? { name } : {}), fallbackText: m.image(user, i + 1, raw.length) });
359
+ }
360
+ return { ok: true, blobs };
361
+ }
362
+
363
+ /** A picture the typing box carries to the chat page with its draft, as the page's composer holds it; the page checks it again on send. */
364
+ interface DraftImage { name: string; mime: string; base64: string; bytes: number; width: number; height: number }
365
+
366
+ function draftImages(raw: unknown): DraftImage[] {
367
+ if (!Array.isArray(raw)) return [];
368
+ return raw.slice(0, IMAGES_MAX).flatMap((item) => {
369
+ const i = (item ?? {}) as Partial<Record<keyof DraftImage, unknown>>;
370
+ if (typeof i.mime !== 'string' || !IMAGE_MIMES.has(i.mime) || typeof i.base64 !== 'string' || !i.base64) return [];
371
+ if (i.base64.length > Math.ceil(IMAGE_MAX_BYTES / 3) * 4 || typeof i.width !== 'number' || typeof i.height !== 'number') return [];
372
+ const name = typeof i.name === 'string' && i.name ? i.name.slice(0, 120) : 'image';
373
+ const bytes = typeof i.bytes === 'number' ? i.bytes : Math.floor(i.base64.length * 3 / 4);
374
+ return [{ name, mime: i.mime, base64: i.base64, bytes, width: i.width, height: i.height }];
375
+ });
376
+ }
377
+
378
+ interface AudioSpeechBatch {
379
+ id: string;
380
+ parts: Int16Array[] | null;
381
+ text: string[];
382
+ reports: { text: string; ms: number; error?: string; dropped?: boolean }[];
383
+ pending: number;
384
+ closed: boolean;
385
+ sent: boolean;
386
+ cancels: number;
387
+ trigger: TriggerMode;
388
+ /** Encoded at the capture boundary; earlier text fallbacks may briefly hold delivery. */
389
+ blobs: BlobInput[];
390
+ reported: boolean;
391
+ transcriptShown: boolean;
392
+ /** The delivered recording's event, which the chat page shows the transcript on once it arrives. */
393
+ event: Promise<EventEnvelope | null> | null;
394
+ }
395
+
396
+ interface SpeechJob {
397
+ utterance: Utterance;
398
+ audio?: AudioSpeechBatch;
399
+ generation: number;
400
+ cancels: number;
401
+ }
402
+
403
+ export class DesktopPetWorld implements World {
404
+ readonly id = DESKTOP_PET_ID;
405
+ private host: WorldHost | null = null;
406
+ private log: Logger | null = null;
407
+ private readonly cfg: DesktopPetConfigSection;
408
+ private readonly server: PetServer;
409
+ /** The syllables of the pet page's speech; its dictionaries load the first time a text needs them. */
410
+ private readonly speechText = new SpeechText(SPEECH_DATA, join(WEB_DIR, 'speech', 'zh.json'));
411
+ private windowHost: WindowHost | null = null;
412
+ /** The tray's "click through": every click passes through the pet window. Not saved: it lasts until the Core stops. */
413
+ private clickThrough = false;
414
+ private readonly store: RuntimeStore;
415
+ private funasr: SherpaAsr | null = null;
416
+ private whisper: SherpaAsr | null = null;
417
+ private system: SystemRecognizer | null = null;
418
+ private api: TranscriptionApi | null = null;
419
+ /** The engine the running backend belongs to; a config change starts the other one. */
420
+ private runningEngine: AsrEngine | null = null;
421
+ private voiceGeneration = 0;
422
+ private voiceStopping: Promise<void> | null = null;
423
+ private voiceEnabled = false;
424
+ /** `cua.enabled` as syncPrefs last saw it: switching it off ends the engine process. */
425
+ private cuaSeen = false;
426
+ /** The person asked to send what was heard now, without waiting for the pause that ends a sentence. */
427
+ private committing = false;
428
+ private readonly segmenter: Segmenter;
429
+ private readonly packer = new Packer({ minChars: 1 });
430
+ /**
431
+ * PCM for the pending batch. Null keeps the batch text-only: a sentence was transcribed while its recording could
432
+ * not go along (`recordingGoes`), or the batch's recording ran past `asr.recording.maxMinutes`.
433
+ */
434
+ private heardPcm: Int16Array[] | null = [];
435
+ private readonly queue: SpeechJob[] = [];
436
+ private transcribing = false;
437
+ private activeSpeechJob: SpeechJob | null = null;
438
+ private audioBatch: AudioSpeechBatch | null = null;
439
+ private audioDisplay: AudioSpeechBatch | null = null;
440
+ /** Closed recordings in capture order. Only an earlier text fallback can hold a later WAV. */
441
+ private readonly audioDeliveries: AudioSpeechBatch[] = [];
442
+ private captureEnabled = false;
443
+ private packTimer: NodeJS.Timeout | null = null;
444
+ private audioSettleTimer: NodeJS.Timeout | null = null;
445
+ private wasSpeaking = false;
446
+ private screen: { w: number; h: number } | null = null;
447
+ /** The pet window said it is hidden (its menu's or the tray's 「隐藏」); reset when a page connects. */
448
+ private petHidden = false;
449
+ /** `onDesktop` as last told to `onDesktopChange`, null before the first time. */
450
+ private desktopTold: boolean | null = null;
451
+ /** When each line sent by `speed_pet_say` is estimated to be over, in sending order; the last one is when the bubble is free. */
452
+ private sayEnds: Array<{ id: string; at: number }> = [];
453
+ private readonly walks = new Map<string, PendingWalk>();
454
+ /** The `portrait` orders the page has not answered, by id. */
455
+ private readonly portraits = new Map<string, (portrait: Portrait) => void>();
456
+ private ask: PendingAsk | null = null;
457
+ private touch: TouchBatch | null = null;
458
+ /** A touch has woken the bot and no turn has ended since; touches until then wait for the next wake. */
459
+ private touchWoke = false;
460
+ /** The New Year event reached the bot in this turn and the fireworks are not lit yet. */
461
+ private fireworksOffered = false;
462
+ private holidayTimer: NodeJS.Timeout | null = null;
463
+ /** The local date of the last event's time stamp; the next event on another date names its date again. */
464
+ private stampDay = '';
465
+ private prefsKey = '';
466
+ private prefsTimer: NodeJS.Timeout | null = null;
467
+ /** Where the pet window last said the pet stands, measured as `petX` is; written by `savePosition` on stop. */
468
+ private standX: number | null = null;
469
+ /** How far down it stands, as `petY` is measured, when the body reported one with that position. */
470
+ private standY: number | null = null;
471
+ private readonly voiceSockets = new Set<WorldStreamSocket>();
472
+ private lastLevelAt = 0;
473
+ private readonly heard: HeardLine[] = [];
474
+ private readonly counts = { utterances: 0, delivered: 0, dropped: 0 };
475
+ private micState: { state: string; detail: string | null } = { state: 'off', detail: null };
476
+ private devices: Array<{ id: string; label: string }> = [];
477
+ private readonly confirms = new Map<string, PendingConfirm>();
478
+ private readonly dialogs = new Map<string, (a: PetDialogAnswer) => void>();
479
+ /** The talk key is down (hold) or was switched on (toggle). */
480
+ private talking = false;
481
+ /** Recent microphone frames retained until a shared talk key is confirmed as held. */
482
+ private readonly holdPreRoll: Array<{ frame: Int16Array; atMs: number }> = [];
483
+ /** With `micOnPress`: the microphone stays open from talk-key activation until MIC_RELEASE_MS after release. */
484
+ private micHeld = false;
485
+ private micReleaseTimer: NodeJS.Timeout | null = null;
486
+ /** Counts cancelled captures; a transcription begun before a cancel is dropped when it lands. */
487
+ private cancels = 0;
488
+ private keyWatcher: KeyWatcher | null = null;
489
+ /** Why the talk key cannot be read; the gate then stays closed. */
490
+ private hotkeyProblem: string | null = null;
491
+ /** The talk-key problem last delivered to the bot. */
492
+ private hotkeyProblemTold: string | null = null;
493
+ private hotkeyKey = '';
494
+ /** The typing key's watcher while `typeKey.enabled`, and why it cannot be read. */
495
+ private typeWatcher: KeyWatcher | null = null;
496
+ private typeKeyProblem: string | null = null;
497
+ private typeKeyKey = '';
498
+ /** The click-through pause key's watcher while `throughPauseKey.enabled`, why it cannot be read, and whether it is held now. */
499
+ private throughPauseWatcher: KeyWatcher | null = null;
500
+ private throughPauseKeyProblem: string | null = null;
501
+ private throughPauseKeyKey = '';
502
+ private throughPaused = false;
503
+ private level = -100;
504
+ private readonly chat = new ChatSockets();
505
+ private readonly activity = new ActivityGroup();
506
+ private stopAgentSpeedActivity: (() => void) | null = null;
507
+ private agentSpeedSnapshot: ActivitySnapshot | null = null;
508
+ /** What the status bubble shows. */
509
+ private readonly status: StatusTracker;
510
+ /** Computer use; its tools and its part of the environment prompt are there while `cua.enabled` is on. */
511
+ private readonly cua: Cua;
512
+ private phase: RunPhase | null = null;
513
+ /** The person's messages (typed, spoken) not yet delivered to the bot, by cursor. */
514
+ private readonly pendingChat = new Set<number>();
515
+ /** The first cursor of this run: Core queues this World's undelivered events from before it again at start. */
516
+ private startCursor = 0;
517
+ /** Text the bubble's expand button carried, until a chat page takes it. */
518
+ private draft: { text: string; images: DraftImage[] } | null = null;
519
+ private pausedShown: boolean | null = null;
520
+ private botShown: string | null = null;
521
+
522
+ /** Installs packs the dressing page sends, when the app named a directory for them. */
523
+ private readonly importer: PackImporter | null;
524
+ private readonly dressImport: DressZipImport | null;
525
+
526
+ constructor(private readonly opts: DesktopPetWorldOptions) {
527
+ this.cfg = opts.cfg;
528
+ this.sized = { figure: this.cfg.skin.figure ?? COO, scale: this.cfg.window.scale };
529
+ this.cua = new Cua({
530
+ cfg: () => this.cfg.cua,
531
+ botName: opts.botName,
532
+ modelLanguage: () => this.language,
533
+ language: () => this.appLanguage,
534
+ askPermission: async (question, choices) => {
535
+ const answer = await this.confirm(question, choices);
536
+ if (answer === 'unavailable') return null;
537
+ const said: Answer = answer === 'yes' || answer === 'timeout' ? answer : 'no';
538
+ opts.onCuaAnswer?.(said);
539
+ return said;
540
+ },
541
+ });
542
+ this.importer = opts.packDir ? new PackImporter({ packDir: opts.packDir, packs: () => this.packs(), text: () => this.ui }) : null;
543
+ const packDir = opts.packDir;
544
+ this.dressImport = packDir ? new DressZipImport((text) => new PackImporter({ packDir, packs: () => this.packs(), text: () => text })) : null;
545
+ this.status = new StatusTracker((status) => this.server.sendPet({ t: 'status', status }), opts.describeTool, () => this.ui.busy);
546
+ this.segmenter = new Segmenter(this.segmentConfig(), FRAME_MS);
547
+ this.segmenter.setSink(this.sink);
548
+ this.store = new RuntimeStore({ runtimesRoot: opts.runtimesRoot, modelsDir: opts.modelsDir, fetchImpl: opts.fetchImpl, funasrModel: opts.funasrModel, whisperModel: opts.whisperModel, text: () => this.ui });
549
+ this.server = new PetServer({
550
+ port: () => this.cfg.port,
551
+ webDir: WEB_DIR,
552
+ snapshot: () => this.snapshot(),
553
+ onPetMessage: (msg) => this.onPage(msg),
554
+ onAudio: (frame) => this.onAudio(frame),
555
+ onPetConnect: () => {
556
+ this.petHidden = false;
557
+ this.bodyMissing = null;
558
+ this.log?.info('桌宠页面已连接');
559
+ this.tellDesktop();
560
+ this.sendAgentSpeedActivity();
561
+ },
562
+ onPetDisconnect: () => this.onPageGone(),
563
+ onSkin: (skin, scale) => this.saveSkin(skin, scale),
564
+ onPrefs: (prefs) => this.savePrefs(prefs),
565
+ looks: () => this.cfg.looks,
566
+ onLooks: (looks) => this.saveLooks(looks),
567
+ packs: () => this.packs(),
568
+ packProblems: () => this.packProblemsNow(),
569
+ importer: this.importer ?? undefined,
570
+ language: () => this.appLanguage,
571
+ text: () => this.ui,
572
+ overlay: () => this.cfg.window.exportOverlay,
573
+ speech: (text) => this.speechText.units(text, this.appLanguage),
574
+ });
575
+ }
576
+
577
+ /* ---------- figures ---------- */
578
+
579
+ /** Pack problems already logged, so a broken pack is reported once, not on every scan. */
580
+ private readonly packProblems = new Set<string>();
581
+ /** The figure (and a pack's pick, `id:scheme`) the pet page last said it shows, null before it said. */
582
+ private figureShown: string | null = null;
583
+ /** The figure the page said would not run, while the skin still names it: the page shows Coo meanwhile. */
584
+ private figureFailed: string | null = null;
585
+ /** Why each pack would not run when the pet page last loaded it, by pack id; a pack leaves when the page shows it. */
586
+ private readonly runFailures = new Map<string, string>();
587
+ /** Why Coo, the last stand-in, would not run on the connected page, which then shows no figure at all. */
588
+ private bodyMissing: string | null = null;
589
+ /** The words each pack's body said it knows when the page last loaded it; a body that did not say is taken at its manifest's word. */
590
+ private readonly bodyWords = new Map<string, ReadonlySet<string>>();
591
+ /** The words the bot was last told it may use: its prompt's at start, then a `[figure]` event's or a `speed_pet_set` receipt's. */
592
+ private toldVocab: readonly VocabWord[] = [];
593
+ /** The figure's own `speed_pet_move_to` targets the bot was last told of, as `toldVocab` the words. */
594
+ private toldMoves: readonly MoveTarget[] = [];
595
+ /** A look the bot put on itself: the pet page's report of it is not told back (the receipt said it). */
596
+ private botLook: string | null = null;
597
+ /** The figure on screen and its size as `followFigure` last saw them. */
598
+ private sized: { figure: string; scale: number };
599
+ /** `speed_pet_quiet` in force: what it overrides, until when, and the settings it found (a change to them ends it). */
600
+ private quiet: { sound: boolean; roam: RoamMode; until: number; base: { sound: boolean; roam: RoamMode }; timer: NodeJS.Timeout } | null = null;
601
+
602
+ /** The built-in packs, then the installed ones; scanned on each call (a few small files). */
603
+ packs(): FigurePack[] {
604
+ return this.packScan().packs;
605
+ }
606
+
607
+ /** `packs()` with what was wrong in the pack directories, each problem logged once. */
608
+ private packScan(): PackScan {
609
+ const scan = figurePacks(this.opts.packRoots?.() ?? [], this.appLanguage);
610
+ for (const { dir, reason, loaded } of scan.problems) {
611
+ const line = `${loaded ? '形象包有一部分没用上' : '形象包没加载'}:${dir}:${reason}`;
612
+ if (!this.packProblems.has(line)) { this.packProblems.add(line); this.log?.warn(line); }
613
+ }
614
+ return scan;
615
+ }
616
+
617
+ /** What the scan found wrong, then the packs that scanned well and would not run on the pet page. */
618
+ private packProblemsNow(): PackProblem[] {
619
+ const { packs, problems } = this.packScan();
620
+ return [...problems, ...packs.flatMap((p) => { const reason = this.runFailures.get(p.id); return reason === undefined ? [] : [{ dir: p.dir, reason, loaded: false }]; })];
621
+ }
622
+
623
+ /** The pack of the figure the skin asks for (Coo for one that is not installed); null only when even Coo's would not load. */
624
+ private currentPack(): FigurePack | null {
625
+ const figure = this.cfg.skin.figure ?? COO;
626
+ return packFor(this.packs(), figure === this.figureFailed ? COO : figure);
627
+ }
628
+ /** The words the body on screen does: its pack's vocabulary, less the words its body said it does not know. */
629
+ private vocab(): VocabWord[] {
630
+ const pack = this.currentPack();
631
+ if (!pack) return [];
632
+ const known = this.bodyWords.get(pack.id);
633
+ return known ? pack.manifest.vocab.filter((w) => known.has(w.id)) : pack.manifest.vocab;
634
+ }
635
+ /** The `speed_pet_move_to` targets of the body on screen's pack, beyond the default ones. */
636
+ private moves(): MoveTarget[] {
637
+ return this.currentPack()?.manifest.moves ?? [];
638
+ }
639
+
640
+ /** The language of what the bot reads from this World. */
641
+ private get language(): ModelLanguage {
642
+ return this.opts.modelLanguage?.() ?? 'zh';
643
+ }
644
+
645
+ /** The text table of that language. */
646
+ private get t(): ModelText {
647
+ return MODEL_TEXT[this.language];
648
+ }
649
+
650
+ /** The app language: what the person reads. */
651
+ private get appLanguage(): Language {
652
+ return this.opts.language?.() ?? 'zh';
653
+ }
654
+
655
+ /** The text table of the app language. */
656
+ private get ui(): PetText {
657
+ return petText(this.appLanguage);
658
+ }
659
+
660
+ /** What events and bubbles call the person: the set name, else the app language's default. */
661
+ get userName(): string {
662
+ return this.cfg.user || this.ui.defaultUser;
663
+ }
664
+
665
+ /** Traditional characters heard become Simplified: the setting is on and the app language is Simplified Chinese. */
666
+ private get simplifies(): boolean {
667
+ return this.cfg.asr.simplified && this.appLanguage === 'zh';
668
+ }
669
+
670
+ /** Sends the pages what changed in the config now, without waiting for the next look; an app calls it after it changes the app language. */
671
+ refresh(): void {
672
+ this.syncPrefs();
673
+ }
674
+
675
+ /**
676
+ * How the words the bot may use and the places it may go changed since it was last told, or ''. From here the
677
+ * bot counts as told those of now.
678
+ */
679
+ private vocabNote(): string {
680
+ const now = this.vocab(), moves = this.moves();
681
+ const notes = [vocabChange(this.toldVocab, now, this.language), moveChange(this.toldMoves, moves, this.language)];
682
+ this.toldVocab = now;
683
+ this.toldMoves = moves;
684
+ return notes.filter(Boolean).join('\n\n');
685
+ }
686
+
687
+ /** What the body looks like now, with its picked options. */
688
+ private bodyText(pack: FigurePack | null): string {
689
+ if (!pack) return '';
690
+ const { language, t } = this;
691
+ const m = pack.manifest;
692
+ const scheme = lookOf(pack, this.cfg.skin);
693
+ const picks = scheme.split('-');
694
+ const preset = m.presets.find((p) => p.id === scheme);
695
+ const chosen = m.axes.map((a, i) => {
696
+ const o = a.options.find((x) => x.id === (preset?.pick[a.id] ?? picks[i])) ?? a.options[0]!;
697
+ return t.pick(modelName(a.name, a.id, language), modelName(o.name, o.id, language));
698
+ });
699
+ return t.body(modelName(m.name, pack.id, language), nameIn(m.about, language), chosen);
700
+ }
701
+
702
+ /**
703
+ * The pet page's report of the figure it shows: a switch the bot did not see in its prompt is told
704
+ * after the debounce (changes in a row come as one batch); a pack that would not load (the page then
705
+ * shows Coo) is told at once. Either way the bot hears how the words it may use changed, the words
706
+ * a newly loaded body says it does not know among them (`words`, the kit's bodies send it).
707
+ */
708
+ private onFigure(msg: PageMessage): void {
709
+ const id = typeof msg.id === 'string' ? msg.id : COO;
710
+ const before = this.figureShown;
711
+ const packs = this.packs();
712
+ const pack = packs.find((p) => p.id === id) ?? null;
713
+ if (msg.ok !== true) {
714
+ this.figureShown = COO;
715
+ this.figureFailed = id;
716
+ const reason = typeof msg.reason === 'string' ? msg.reason.slice(0, 200) : this.t.reasonUnknown;
717
+ this.runFailures.set(id, reason);
718
+ this.log?.warn(`形象包 ${id} 没能显示:${reason}`);
719
+ if (id === COO) this.bodyMissing = reason;
720
+ // the page shows Coo instead, whose words then hold too
721
+ const coo = packs.find((p) => p.id === COO) ?? null;
722
+ const note = this.vocabNote();
723
+ const name = modelName(pack?.manifest.name, id, this.language);
724
+ void this.push('agent-speed.figure', 'agent-speed.figure', this.t.figureFailed(name, reason, this.bodyText(coo), note), 'flush',
725
+ { meta: { figure: { kind: 'failed', name: { ...pack?.manifest.name, id }, reason } } });
726
+ return;
727
+ }
728
+ if ('words' in msg) {
729
+ if (Array.isArray(msg.words)) this.bodyWords.set(id, new Set(msg.words.filter((w): w is string => typeof w === 'string')));
730
+ else this.bodyWords.delete(id);
731
+ }
732
+ const known = this.bodyWords.get(id);
733
+ const unknown = pack && known ? pack.manifest.vocab.filter((w) => !known.has(w.id)).map((w) => w.id) : [];
734
+ const problem = `形象包 ${id} 的词表里有身体不认得的词,没给 bot 用:${unknown.join('、')}`;
735
+ if (unknown.length && !this.packProblems.has(problem)) { this.packProblems.add(problem); this.log?.warn(problem); }
736
+ this.runFailures.delete(id);
737
+ if (id === this.cfg.skin.figure) this.figureFailed = null;
738
+ this.bodyMissing = null;
739
+ const shown = id === COO ? COO : `${id}:${typeof msg.scheme === 'string' ? msg.scheme : ''}`;
740
+ this.figureShown = shown;
741
+ let look: string | null = null;
742
+ // what the chat page says of a switch the person made: another figure, or another dress of the same one
743
+ let change: ChatFigure | null = null;
744
+ if (before !== null && before !== shown) {
745
+ if (shown === this.botLook) this.botLook = null;
746
+ else {
747
+ look = this.t.figureNow(this.bodyText(pack));
748
+ change = { kind: before.split(':')[0] === id ? 'dress' : 'figure', name: { ...pack?.manifest.name, id } };
749
+ }
750
+ }
751
+ const note = this.vocabNote();
752
+ const text = look && note ? `${look}\n${note}` : look ?? (note ? this.t.figureNote(note) : null);
753
+ if (text) void this.push('agent-speed.figure', 'agent-speed.figure', text, 'debounce', change ? { meta: { figure: change } } : {});
754
+ }
755
+
756
+ /* ---------- lifecycle ---------- */
757
+
758
+ async start(host: WorldHost): Promise<void> {
759
+ this.host = host;
760
+ this.startCursor = host.store.latestCursor() + 1;
761
+ this.log = host.log;
762
+ this.cua.start(host);
763
+ // the words and targets the prompt is rendered with, until the bot is told otherwise
764
+ this.toldVocab = this.vocab();
765
+ this.toldMoves = this.moves();
766
+ await this.server.start();
767
+ this.stopAgentSpeedActivity = connectActivity({
768
+ onSnapshot: (snapshot) => {
769
+ this.agentSpeedSnapshot = snapshot;
770
+ this.sendAgentSpeedActivity();
771
+ },
772
+ });
773
+ this.windowHost = new WindowHost(host.log);
774
+ if (this.cfg.window.enabled) this.openWindow();
775
+ const sherpa = (engine: SherpaEngine, kind: SherpaModelKind) => new SherpaAsr({
776
+ kind,
777
+ model: () => this.sherpaModel(engine),
778
+ language: () => this.asrLanguage(),
779
+ text: () => this.ui,
780
+ threads: () => this.cfg.asr.threads,
781
+ log: host.log,
782
+ load: this.opts.loadSherpa,
783
+ });
784
+ this.funasr = sherpa('funasr', SENSEVOICE);
785
+ this.whisper = sherpa('whisper', WHISPER);
786
+ this.system = new SystemRecognizer({
787
+ language: () => this.asrLanguage(),
788
+ culture: () => SYSTEM_CULTURES[this.appLanguage] ?? '',
789
+ text: () => this.ui,
790
+ timeoutMs: () => this.cfg.asr.timeoutMs,
791
+ log: host.log,
792
+ spawnImpl: this.opts.spawnSystemRecognizer,
793
+ });
794
+ this.api = new TranscriptionApi({
795
+ config: () => this.cfg.asr.api,
796
+ key: () => this.opts.asrApiKey?.() ?? '',
797
+ language: () => this.asrLanguage(),
798
+ timeoutMs: () => this.cfg.asr.timeoutMs,
799
+ text: () => this.ui,
800
+ log: host.log,
801
+ });
802
+ this.cuaSeen = this.cfg.cua.enabled;
803
+ this.captureEnabled = this.cfg.asr.enabled;
804
+ if (this.recognitionWanted()) void this.startVoiceBackend();
805
+ await this.syncHotkey();
806
+ await this.syncTypeKey();
807
+ await this.syncThroughPauseKey();
808
+ this.prefsKey = this.prefsSignature();
809
+ this.prefsTimer = setInterval(() => this.syncPrefs(), PREFS_SYNC_MS);
810
+ this.holidayTimer = setInterval(() => { if (this.desktopTold) this.tellHoliday(); }, HOLIDAY_CHECK_MS);
811
+ }
812
+
813
+ async stop(): Promise<void> {
814
+ this.stopAgentSpeedActivity?.();
815
+ this.stopAgentSpeedActivity = null;
816
+ this.agentSpeedSnapshot = null;
817
+ this.discardSpeech();
818
+ this.voiceGeneration++;
819
+ this.runningEngine = null;
820
+ this.status.clear();
821
+ if (this.quiet) clearTimeout(this.quiet.timer);
822
+ this.quiet = null;
823
+ if (this.prefsTimer) clearInterval(this.prefsTimer);
824
+ this.prefsTimer = null;
825
+ if (this.holidayTimer) clearInterval(this.holidayTimer);
826
+ this.holidayTimer = null;
827
+ this.savePosition();
828
+ await this.dressImport?.cancel();
829
+ await this.importer?.cancel();
830
+ if (this.packTimer) clearTimeout(this.packTimer);
831
+ this.packTimer = null;
832
+ if (this.touch) clearTimeout(this.touch.timer);
833
+ this.touch = null;
834
+ this.touchWoke = false;
835
+ this.keyWatcher?.stop();
836
+ this.keyWatcher = null;
837
+ this.holdPreRoll.length = 0;
838
+ this.typeWatcher?.stop();
839
+ this.typeWatcher = null;
840
+ this.typeKeyKey = '';
841
+ this.throughPauseWatcher?.stop();
842
+ this.throughPauseWatcher = null;
843
+ this.throughPauseKeyKey = '';
844
+ this.throughPaused = false;
845
+ if (this.micReleaseTimer) clearTimeout(this.micReleaseTimer);
846
+ this.micReleaseTimer = null;
847
+ for (const c of this.confirms.values()) { clearTimeout(c.timer); c.resolve('unavailable'); }
848
+ this.confirms.clear();
849
+ for (const d of this.dialogs.values()) d({ unavailable: true });
850
+ this.dialogs.clear();
851
+ for (const w of this.walks.values()) { clearTimeout(w.timer); w.resolve(this.t.walkWorldStopped); }
852
+ this.walks.clear();
853
+ for (const done of [...this.portraits.values()]) done('gone');
854
+ for (const s of this.voiceSockets) s.close('stopped');
855
+ this.voiceSockets.clear();
856
+ this.chat.closeAll('stopped');
857
+ await this.windowHost?.stop();
858
+ await this.funasr?.stop();
859
+ await this.whisper?.stop();
860
+ await this.system?.stop();
861
+ await this.api?.stop();
862
+ await this.server.stop();
863
+ await this.cua.stop();
864
+ this.host = null;
865
+ }
866
+
867
+ onTurnEnded(): void {
868
+ this.touchWoke = false;
869
+ this.fireworksOffered = false;
870
+ this.cua.onTurnEnded();
871
+ }
872
+
873
+ /** Computer use is on and this system runs it. */
874
+ private get cuaOn(): boolean {
875
+ return this.cfg.cua.enabled && this.cua.unsupported() === null;
876
+ }
877
+
878
+ /** Computer use is off on a system that runs it, and the app can show its switch. */
879
+ private get cuaCanOpen(): boolean {
880
+ return !this.cfg.cua.enabled && this.cua.unsupported() === null && !!this.opts.controls?.openCuaSettings;
881
+ }
882
+
883
+ private openCuaSettings(): ToolOutcome {
884
+ this.opts.controls?.openCuaSettings?.();
885
+ return { text: this.t.cuaSettingsOpened(this.userName) };
886
+ }
887
+
888
+ outputTap(): OutputTap | undefined {
889
+ if (!this.server.petConnected) return undefined;
890
+ return {
891
+ // the pet shows nothing of the stream itself; its tools act when they run
892
+ externalizes: () => false,
893
+ onEvent: (event) => this.status.onEvent(event),
894
+ };
895
+ }
896
+
897
+ onRunPhase(phase: RunPhase): void {
898
+ this.phase = phase;
899
+ this.status.onPhase(phase);
900
+ if (this.activity.observe(phase, Date.now())) this.chat.broadcast({ t: 'activity', steps: this.activity.steps, startedAt: this.activity.startedAt });
901
+ if (phase.state === 'idle') void this.closeActivity();
902
+ this.chat.broadcast({ t: 'phase', phase });
903
+ }
904
+
905
+ /**
906
+ * A message that waited shows where the bot took it in: the steps done before that are recorded
907
+ * first, then a `delivered` record the history places the message at.
908
+ */
909
+ onEventsSettled(events: readonly EventEnvelope[], outcome: 'delivered' | 'discarded'): void {
910
+ if (outcome === 'delivered' && events.some((e) => e.senderKey === `${HOLIDAY_TYPE}.newYear2027`)) this.fireworksOffered = true;
911
+ const cursors = events
912
+ .filter((e) => this.pendingChat.delete(e.cursor) || (e.cursor < this.startCursor && chatItem(e)?.kind === 'user'))
913
+ .map((e) => e.cursor);
914
+ if (!cursors.length) return;
915
+ void (async () => {
916
+ await this.closeActivity();
917
+ const later = (this.host?.store.latestCursor() ?? 0) > Math.max(...cursors);
918
+ const at = outcome === 'delivered' && later
919
+ ? await this.record({ kind: 'delivered', cursors }, `送达了 ${cursors.map((c) => `#${c}`).join('、')}`)
920
+ : null;
921
+ this.chat.broadcast({ t: 'settled', cursors, outcome, ...(at !== null ? { at } : {}) });
922
+ })();
923
+ }
924
+
925
+ /** The steps since the pet's last line become one record: before each line, when the loop goes idle, before a waiting message is placed. */
926
+ private async closeActivity(): Promise<void> {
927
+ const group = this.activity.take(Date.now());
928
+ if (!group) return;
929
+ this.chat.broadcast({ t: 'activity', steps: null });
930
+ await this.record({ kind: 'activity', ...group }, `做了:${group.steps.join('、')}`);
931
+ }
932
+
933
+ /**
934
+ * One frame from a chat page:
935
+ * - `hello`: the history, the messages still pending, the loop's phase and the pause, and a draft the bubble carried
936
+ * - `more { before }`: the history before that cursor
937
+ * - `send { id, text, images }`: a message typed on the page, delivered with `preempt`; answered with `sent { id, cursor }` or `rejected { id, reason }`
938
+ * - `now { cursor }`: a pending message delivered at once, stopping what the bot is doing (`interrupt`)
939
+ * - `withdraw { cursor }`: a pending message taken back; answered with `withdrawn { cursor }` to every page, or `notice` when it was already delivered
940
+ * - `answer { askId, index | text }`: the open `speed_pet_ask` answered on the page
941
+ *
942
+ * `init` and `ask` frames carry the id of the question that can still be answered (`askId`, null
943
+ * when none). `init` and `older` carry `refs`: the `withdrawn`, `delivered` and `transcript` records in that
944
+ * stretch of history about messages before it, which the page applies to the pages it loads later.
945
+ * A recording's transcript recognized after its delivery goes to every page as `transcript { cursor, text }`.
946
+ */
947
+ private async onChat(msg: Record<string, unknown>, socket: WorldStreamSocket, language: Language): Promise<void> {
948
+ const host = this.host;
949
+ const s = petText(language).chat;
950
+ switch (msg.t) {
951
+ case 'hello': {
952
+ const page = host ? this.chatPage() : { items: [], more: false };
953
+ this.chat.send(socket, {
954
+ t: 'init', ...page, pending: [...this.pendingChat], askId: this.ask?.id ?? null, phase: this.phase,
955
+ activity: this.activity.steps.length ? { steps: this.activity.steps, startedAt: this.activity.startedAt } : null,
956
+ paused: this.opts.controls?.isPaused?.() ?? false, user: this.userName, bot: this.botName(),
957
+ imagesSeen: host?.modelFacts.accepts('image/jpeg') ?? false,
958
+ textMax: CHAT_TEXT_MAX, answerMax: ANSWER_TEXT_MAX,
959
+ });
960
+ if (this.draft !== null) { this.chat.send(socket, { t: 'draft', ...this.draft }); this.draft = null; }
961
+ return;
962
+ }
963
+ case 'more': {
964
+ if (!host || typeof msg.before !== 'number') return;
965
+ this.chat.send(socket, { t: 'older', ...this.chatPage(msg.before) });
966
+ return;
967
+ }
968
+ case 'send': {
969
+ const id = msg.id;
970
+ const text = typeof msg.text === 'string' ? msg.text.trim().slice(0, CHAT_TEXT_MAX) : '';
971
+ const images = parseChatImages(msg.images, this.userName, s, this.t);
972
+ if (!images.ok) { this.chat.send(socket, { t: 'rejected', id, reason: images.reason }); return; }
973
+ if (!text && images.blobs.length === 0) return;
974
+ if (!host) { this.chat.send(socket, { t: 'rejected', id, reason: s.offline }); return; }
975
+ const e = await this.push('agent-speed.message', 'agent-speed.chat', this.t.typed(this.userName, text), 'preempt',
976
+ { meta: { via: 'chat', text }, ...(images.blobs.length ? { blobs: images.blobs } : {}) });
977
+ this.chat.send(socket, e ? { t: 'sent', id, cursor: e.cursor } : { t: 'rejected', id, reason: s.notSent });
978
+ // the pet shows it beside Coo, as it shows what is typed or said there
979
+ if (e) this.server.sendPet({ t: 'said', via: 'chat', text, images: images.blobs.length, cursor: e.cursor });
980
+ return;
981
+ }
982
+ case 'now': {
983
+ if (!host?.promotePending || typeof msg.cursor !== 'number') return;
984
+ await host.promotePending(msg.cursor, 'interrupt');
985
+ return;
986
+ }
987
+ case 'withdraw': {
988
+ const cursor = msg.cursor;
989
+ if (!host?.withdrawPending || typeof cursor !== 'number') return;
990
+ if (!await host.withdrawPending(cursor)) {
991
+ this.chat.send(socket, { t: 'notice', cursor, text: s.tooLate });
992
+ return;
993
+ }
994
+ this.pendingChat.delete(cursor);
995
+ void this.record({ kind: 'withdrawn', cursor }, `撤回了 #${cursor}`);
996
+ this.chat.broadcast({ t: 'withdrawn', cursor });
997
+ this.server.sendPet({ t: 'said-withdrawn', cursor });
998
+ return;
999
+ }
1000
+ case 'answer': return this.onAnswer(msg, 'chat');
1001
+ }
1002
+ }
1003
+
1004
+ /**
1005
+ * The chat items of the last CHAT_PAGE_EVENTS events of this World, or of those before `before`,
1006
+ * and the records among them about messages further back.
1007
+ */
1008
+ private chatPage(before?: number): { items: ReturnType<typeof chatHistory>; refs: ReturnType<typeof chatRefs>; more: boolean; before: number | null } {
1009
+ const events = this.host!.store.range({ source: this.id, limit: CHAT_PAGE_EVENTS, ...(before !== undefined ? { toCursor: before - 1 } : {}) });
1010
+ const more = events.length === CHAT_PAGE_EVENTS;
1011
+ const first = events[0]?.cursor ?? 0;
1012
+ const refs = chatRefs(events);
1013
+ return {
1014
+ items: chatHistory(events),
1015
+ refs: { withdrawn: refs.withdrawn.filter((c) => c < first), delivered: refs.delivered.filter(([c]) => c < first), transcripts: refs.transcripts.filter(([c]) => c < first) },
1016
+ more, before: more ? first : null,
1017
+ };
1018
+ }
1019
+
1020
+ /** The open question changed: pages let only the one still open be answered. */
1021
+ private setAsk(ask: PendingAsk | null): void {
1022
+ this.ask = ask;
1023
+ this.chat.broadcast({ t: 'ask', askId: ask?.id ?? null });
1024
+ }
1025
+
1026
+ /* ---------- window ---------- */
1027
+
1028
+ get petUrl(): string {
1029
+ return `${this.server.origin}/pet`;
1030
+ }
1031
+
1032
+ openWindow(): void {
1033
+ if (!this.windowHost || !this.server.port) return;
1034
+ const managed = this.store.electron.executable();
1035
+ this.windowHost.start(resolveHostCommand(this.server.windowUrl, this.cfg.window.electronFile, managed));
1036
+ }
1037
+
1038
+ private sendAgentSpeedActivity(): void {
1039
+ if (this.server.petInWindow) {
1040
+ this.server.sendPet({ t: 'agent-speed-activity', snapshot: this.agentSpeedSnapshot });
1041
+ }
1042
+ }
1043
+
1044
+ /* ---------- page protocol ---------- */
1045
+
1046
+ private snapshot(): Record<string, unknown> {
1047
+ return {
1048
+ skin: this.cfg.skin,
1049
+ roam: this.quiet?.roam ?? this.cfg.roam,
1050
+ sound: this.quiet?.sound ?? this.cfg.sound,
1051
+ sounds: this.cfg.sounds,
1052
+ speech: speechFor(this.cfg.speech),
1053
+ theme: this.cfg.theme,
1054
+ rememberPosition: this.cfg.rememberPosition,
1055
+ // read by the page from `init` only
1056
+ startX: this.cfg.rememberPosition ? this.cfg.petX : null,
1057
+ startY: this.cfg.rememberPosition ? this.cfg.petY : null,
1058
+ hoverButtons: hoverButtonList(this.cfg.hoverButtons),
1059
+ cua: this.cuaButton(),
1060
+ doubleClickChat: this.cfg.doubleClickChat,
1061
+ scale: this.cfg.window.scale,
1062
+ bubbleSize: this.cfg.window.bubbleSize,
1063
+ fontSize: this.cfg.window.fontSize,
1064
+ bubbleSpeed: this.cfg.window.bubbleSpeed,
1065
+ sayBubbleHoldSec: this.cfg.window.sayBubbleHoldSec,
1066
+ glow: this.cfg.window.glow,
1067
+ frameRate: this.cfg.window.frameRate,
1068
+ lockFrameRate: this.cfg.window.lockFrameRate,
1069
+ motion: this.cfg.window.motion,
1070
+ fade: this.cfg.window.fade,
1071
+ fadeWhenFullscreen: this.cfg.window.fadeWhenFullscreen,
1072
+ fullscreenFade: this.cfg.window.fullscreenFade,
1073
+ hideWhenFullscreen: this.cfg.window.hideWhenFullscreen,
1074
+ passWhenFullscreen: this.cfg.window.passWhenFullscreen,
1075
+ overTaskbar: this.cfg.window.overTaskbar,
1076
+ hideFromCapture: this.cfg.window.hideFromCapture,
1077
+ clickThrough: this.clickThrough,
1078
+ language: this.appLanguage,
1079
+ user: this.userName,
1080
+ mic: this.micOpen(),
1081
+ voice: this.voiceBrief(),
1082
+ micDevice: this.cfg.asr.mic.deviceId,
1083
+ status: this.status.status,
1084
+ statusBubble: this.cfg.statusBubble,
1085
+ saidBubbles: this.cfg.saidBubbles,
1086
+ saidBubbleHoldSec: this.cfg.saidBubbleHoldSec,
1087
+ bot: this.botInfo(),
1088
+ };
1089
+ }
1090
+
1091
+ /** The computer use button: it switches computer use off, and on once the risks were confirmed, else through the settings window's switch. */
1092
+ private cuaButton(): { on: boolean; confirmed: boolean; canOpen: boolean } {
1093
+ const runs = this.cua.unsupported() === null;
1094
+ return { on: this.cuaOn, confirmed: runs && this.cfg.cua.risksConfirmed === true, canOpen: runs && !!this.opts.controls?.openCuaSettings };
1095
+ }
1096
+
1097
+ private botName(): string {
1098
+ return this.opts.botName?.() ?? '';
1099
+ }
1100
+
1101
+ private botInfo(): Record<string, unknown> {
1102
+ const c = this.opts.controls;
1103
+ const pause = !!(c?.isPaused && c.setPaused);
1104
+ const label = typeof c?.quitLabel === 'function' ? c.quitLabel() : c?.quitLabel;
1105
+ const quitLabel = c?.quit ? label || this.ui.menu.quit : '';
1106
+ return {
1107
+ name: this.botName(),
1108
+ controls: !!c,
1109
+ buttons: { pause, settings: !!c?.openSettings, dress: !!c?.openDress, worlds: !!c?.openWorlds, quit: !!c?.quit, chat: !!c?.openChat },
1110
+ // the typing box warns, as the chat page does, that the model gets only the count of pasted images
1111
+ imagesSeen: this.host?.modelFacts.accepts('image/jpeg') ?? false,
1112
+ textMax: { box: BOX_TEXT_MAX, chat: CHAT_TEXT_MAX },
1113
+ paused: pause && c?.isPaused ? c.isPaused() : null,
1114
+ quitLabel,
1115
+ quitPrompt: quitLabel ? this.ui.menu.quitPrompt(quitLabel) : '',
1116
+ };
1117
+ }
1118
+
1119
+ private prefsSignature(): string {
1120
+ const s = this.snapshot();
1121
+ delete s.status;
1122
+ // a talk key that opens the microphone sends each change by itself (setMicHeld): the signature keeps only that it does
1123
+ if (this.micOnPress()) s.mic = 'press';
1124
+ return JSON.stringify(s);
1125
+ }
1126
+
1127
+ /** Config is a live object edited by the console; changes reach the pages within PREFS_SYNC_MS. */
1128
+ private syncPrefs(): void {
1129
+ this.followFigure();
1130
+ this.segmenter.configure(this.segmentConfig());
1131
+ if (!this.holdPreRollEnabled()) this.holdPreRoll.length = 0;
1132
+ if (this.captureEnabled && !this.cfg.asr.enabled) this.discardSpeech();
1133
+ this.captureEnabled = this.cfg.asr.enabled;
1134
+ if (this.cfg.asr.enabled && this.audioBatch && !this.micWanted()) {
1135
+ const tail = this.segmenter.flush();
1136
+ if (tail) this.enqueue(tail);
1137
+ this.committing = true;
1138
+ this.schedulePack();
1139
+ }
1140
+ const wanted = this.recognitionWanted();
1141
+ const turnedOn = wanted && !this.voiceEnabled;
1142
+ this.voiceEnabled = wanted;
1143
+ if (!wanted && this.runningEngine) void this.stopVoiceBackend();
1144
+ else if (turnedOn || (wanted && this.runningEngine && this.runningEngine !== this.engine())) void this.startVoiceBackend();
1145
+ // the system recognizer serves one language; a new one needs a new helper
1146
+ else if (wanted && this.runningEngine === 'system' && this.system?.languageChanged) void this.startVoiceBackend();
1147
+ // the transcription service starts again for a new address or model, a failed one included; `setApi` starts it for a new API Key
1148
+ else if (wanted && this.runningEngine === 'api' && this.api?.configChanged) void this.startVoiceBackend();
1149
+ // FunASR and Whisper load the model for one language and thread count
1150
+ else if (wanted && this.runningEngine && this.runningEngine !== 'system' && this.runningEngine !== 'api' && this.sherpa(this.runningEngine)?.configChanged) void this.startVoiceBackend();
1151
+ // computer use switched off ends the engine process; the next call after it is switched on starts another
1152
+ if (this.cuaSeen && !this.cfg.cua.enabled) void this.cua.switchedOff();
1153
+ this.cuaSeen = this.cfg.cua.enabled;
1154
+ void this.syncHotkey();
1155
+ void this.syncTypeKey();
1156
+ void this.syncThroughPauseKey();
1157
+ // the person changed what a quiet holds back: theirs wins
1158
+ if (this.quiet && (this.cfg.sound !== this.quiet.base.sound || this.cfg.roam !== this.quiet.base.roam)) this.endQuiet();
1159
+ this.server.syncOverlay();
1160
+ const paused = this.opts.controls?.isPaused?.() ?? false;
1161
+ if (paused !== this.pausedShown) { this.pausedShown = paused; this.chat.broadcast({ t: 'paused', paused }); }
1162
+ const bot = this.botName();
1163
+ if (bot !== this.botShown) { this.botShown = bot; this.chat.broadcast({ t: 'bot', bot }); }
1164
+ const key = this.prefsSignature();
1165
+ if (key === this.prefsKey) return;
1166
+ this.prefsKey = key;
1167
+ this.server.broadcast({ t: 'prefs', ...this.snapshot() });
1168
+ }
1169
+
1170
+ private recognitionWanted(): boolean {
1171
+ return this.cfg.asr.enabled && this.cfg.asr.serviceEnabled !== false;
1172
+ }
1173
+
1174
+ private audioOnly(): boolean {
1175
+ return this.recordingGoes() && !this.cfg.asr.recording.transcript;
1176
+ }
1177
+
1178
+ private micWanted(): boolean {
1179
+ return this.cfg.asr.enabled && (this.audioOnly() || (this.recognitionWanted() && this.backendState()?.phase === 'running'));
1180
+ }
1181
+
1182
+ /** Hold mode with `asr.mic.openOnPress`: the microphone is open only around a held talk key. */
1183
+ private micOnPress(): boolean {
1184
+ return this.cfg.asr.mic.mode === 'hold' && this.cfg.asr.mic.openOnPress;
1185
+ }
1186
+
1187
+ /** The pet page keeps the microphone open: whenever voice input can hear, or only around a held talk key (`micOnPress`). */
1188
+ private micOpen(): boolean {
1189
+ return this.micWanted() && (!this.micOnPress() || this.micHeld);
1190
+ }
1191
+
1192
+ private setMicHeld(on: boolean): void {
1193
+ if (this.micReleaseTimer) clearTimeout(this.micReleaseTimer);
1194
+ this.micReleaseTimer = null;
1195
+ if (this.micHeld === on) return;
1196
+ this.micHeld = on;
1197
+ this.server.sendPet({ t: 'prefs', mic: this.micOpen() });
1198
+ }
1199
+
1200
+ private releaseMicSoon(): void {
1201
+ if (!this.micHeld || this.micReleaseTimer) return;
1202
+ this.micReleaseTimer = setTimeout(() => this.setMicHeld(false), MIC_RELEASE_MS);
1203
+ }
1204
+
1205
+ /** What the pet's microphone button shows: switched on, able to hear, and why not. */
1206
+ private voiceBrief(): Record<string, unknown> {
1207
+ const b = this.backendState();
1208
+ const ready = this.micWanted();
1209
+ return {
1210
+ enabled: this.cfg.asr.enabled,
1211
+ ready,
1212
+ detail: ready ? null : this.cfg.asr.serviceEnabled === false ? this.ui.voice.serviceStopped : b?.phase === 'starting' ? this.ui.voice.starting : b?.detail ?? this.ui.voice.notRunning,
1213
+ hint: this.talkHint(),
1214
+ mode: this.cfg.asr.mic.mode,
1215
+ key: hotkeyBadge(this.cfg.asr.mic.hotkey),
1216
+ };
1217
+ }
1218
+
1219
+ /** Puts on `raw`; with `scale` (a saved look's) at that size, else at the size the figure last had (`followFigure`). */
1220
+ private saveSkin(raw: unknown, scale?: unknown): void {
1221
+ if (!raw || typeof raw !== 'object') return;
1222
+ // a size set elsewhere since the last sync (the settings window) belongs to the figure on screen, not to this one
1223
+ this.followFigure();
1224
+ const skin = raw as PetSkin;
1225
+ const size = scaleOf(scale);
1226
+ this.opts.persist(size === null ? { skin } : { skin, window: { scale: size } });
1227
+ this.followFigure(size !== null);
1228
+ this.syncPrefs();
1229
+ }
1230
+
1231
+ /**
1232
+ * Each figure keeps its own size: when the figure on screen changes, the one replaced keeps the size it had in
1233
+ * `figureScales`, and the new one takes its own back from there, unless the size changed along with it or was
1234
+ * `given` with it (a saved look's, or `speed_pet_set`'s, the size on screen included).
1235
+ */
1236
+ private followFigure(given = false): void {
1237
+ const figure = this.cfg.skin.figure ?? COO, scale = this.cfg.window.scale;
1238
+ const was = this.sized;
1239
+ if (figure === was.figure) { was.scale = scale; return; }
1240
+ const own = !given && scale === was.scale ? scaleOf(this.cfg.figureScales[figure]) : null;
1241
+ this.opts.persist({ figureScales: { [was.figure]: was.scale }, ...(own !== null && own !== scale ? { window: { scale: own } } : {}) });
1242
+ this.sized = { figure, scale: own ?? scale };
1243
+ }
1244
+
1245
+ /** Keeps the entries that have an id, a name and a skin; names are trimmed to MAX_LOOK_NAME (an empty one becomes the id), the list to MAX_SAVED_LOOKS. */
1246
+ private saveLooks(raw: unknown): void {
1247
+ if (!Array.isArray(raw)) return;
1248
+ const seen = new Set<string>();
1249
+ const looks: SavedLook[] = [];
1250
+ for (const l of raw) {
1251
+ if (!l || typeof l !== 'object') continue;
1252
+ const { id, name, skin, scale } = l as Record<string, unknown>;
1253
+ if (typeof id !== 'string' || !id || seen.has(id) || typeof name !== 'string' || !skin || typeof skin !== 'object') continue;
1254
+ seen.add(id);
1255
+ const size = scaleOf(scale);
1256
+ looks.push({ id, name: name.trim().slice(0, MAX_LOOK_NAME) || id, skin: skin as PetSkin, ...(size === null ? {} : { scale: size }) });
1257
+ if (looks.length === MAX_SAVED_LOOKS) break;
1258
+ }
1259
+ this.opts.persist({ looks });
1260
+ }
1261
+
1262
+ /** Click-through lasts for the run and is not saved; the page enforces it and `onClickThroughChange` hears each change. */
1263
+ private setClickThrough(on: boolean): void {
1264
+ const changed = on !== this.clickThrough;
1265
+ this.clickThrough = on;
1266
+ this.server.sendPet({ t: 'prefs', clickThrough: on });
1267
+ if (changed) this.opts.onClickThroughChange?.(on);
1268
+ }
1269
+
1270
+ private savePrefs(prefs: Record<string, unknown>): void {
1271
+ const patch: DeepPartial<DesktopPetConfigSection> = {};
1272
+ if (prefs.roam === 'free' || prefs.roam === 'calm' || prefs.roam === 'off') patch.roam = prefs.roam as RoamMode;
1273
+ if (typeof prefs.sound === 'boolean') patch.sound = prefs.sound;
1274
+ // the menu's sound or roam button during a quiet: the person's choice, kept, and the quiet is over
1275
+ if (this.quiet && (patch.roam !== undefined || patch.sound !== undefined)) this.endQuiet();
1276
+ if (prefs.theme === 'dark' || prefs.theme === 'light') patch.theme = prefs.theme as PetTheme;
1277
+ const scale = scaleOf(prefs.scale), fade = fadeOf(prefs.fade), fullscreenFade = fadeOf(prefs.fullscreenFade);
1278
+ if (scale !== null || fade !== null || fullscreenFade !== null) {
1279
+ patch.window = { ...(scale !== null ? { scale } : {}), ...(fade !== null ? { fade } : {}), ...(fullscreenFade !== null ? { fullscreenFade } : {}) };
1280
+ }
1281
+ if (prefs.cua === false) patch.cua = { enabled: false };
1282
+ // a page turns it on only after the person confirmed the risks in the settings window
1283
+ else if (prefs.cua === true && this.cfg.cua.risksConfirmed && this.cua.unsupported() === null) patch.cua = { enabled: true };
1284
+ if (typeof prefs.mic === 'boolean') patch.asr = { enabled: prefs.mic };
1285
+ if (Array.isArray(prefs.hoverButtons)) {
1286
+ const ids = prefs.hoverButtons.filter((id): id is string => typeof id === 'string' && (PET_ACTIONS as readonly string[]).includes(id));
1287
+ patch.hoverButtons = hoverButtonList(ids.slice(0, MAX_HOVER_BUTTONS).join(',')).join(',');
1288
+ }
1289
+ const mic = prefs.micSettings as Record<string, unknown> | undefined;
1290
+ if (mic && typeof mic === 'object') {
1291
+ const m: { mode?: MicMode; hotkey?: string; deviceId?: string; openOnPress?: boolean } = {};
1292
+ if (mic.mode === 'hold' || mic.mode === 'toggle' || mic.mode === 'always') m.mode = mic.mode;
1293
+ if (typeof mic.hotkey === 'string' && parseHotkey(mic.hotkey)) m.hotkey = mic.hotkey;
1294
+ if (typeof mic.deviceId === 'string') m.deviceId = mic.deviceId;
1295
+ if (typeof mic.openOnPress === 'boolean') m.openOnPress = mic.openOnPress;
1296
+ patch.asr = { ...patch.asr, mic: m };
1297
+ }
1298
+ if (Object.keys(patch).length) this.opts.persist(patch);
1299
+ if (typeof prefs.clickThrough === 'boolean') this.setClickThrough(prefs.clickThrough);
1300
+ if (typeof prefs.mic === 'boolean' && prefs.mic && this.recognitionWanted()) void this.startVoiceBackend();
1301
+ this.syncPrefs();
1302
+ }
1303
+
1304
+ /**
1305
+ * Called only from `stop`, so config.json changes at most once a run: with `rememberPosition` on it
1306
+ * stores the last reported position, with it off it clears a stored one. A failed write leaves
1307
+ * the stored position as it was.
1308
+ */
1309
+ private savePosition(): void {
1310
+ const x = this.cfg.rememberPosition ? this.standX ?? this.cfg.petX : null;
1311
+ // a report without y comes from a body on the floor, which clears a saved height
1312
+ const y = !this.cfg.rememberPosition ? null : this.standX === null ? this.cfg.petY : this.standY;
1313
+ if (x === this.cfg.petX && y === this.cfg.petY) return;
1314
+ try {
1315
+ this.opts.persist({ petX: x, ...(y !== this.cfg.petY ? { petY: y } : {}) });
1316
+ } catch (err) {
1317
+ this.log?.warn(`桌宠位置没有保存:${(err as Error).message}`);
1318
+ }
1319
+ }
1320
+
1321
+ private onPage(msg: PageMessage): void {
1322
+ switch (msg.t) {
1323
+ case 'figure': return this.onFigure(msg);
1324
+ case 'hello': {
1325
+ const s = msg.screen as { w?: unknown; h?: unknown } | undefined;
1326
+ if (s && typeof s.w === 'number' && typeof s.h === 'number') this.screen = { w: s.w, h: s.h };
1327
+ return;
1328
+ }
1329
+ case 'arrived':
1330
+ case 'interrupted': {
1331
+ const w = this.walks.get(String(msg.walkId));
1332
+ if (!w) return;
1333
+ this.walks.delete(String(msg.walkId));
1334
+ clearTimeout(w.timer);
1335
+ const t = this.t;
1336
+ const at = (typeof msg.x === 'number' ? pct(msg.x) : '?') + (typeof msg.y === 'number' ? t.downAt(pct(msg.y)) : '');
1337
+ // what stopped a figure's own move is its body's word, kept short
1338
+ const by = String(msg.by).slice(0, 40);
1339
+ const name = w.target;
1340
+ w.resolve(msg.t === 'arrived' ? (name === undefined ? t.walkArrived(at) : t.moveArrived(name, at))
1341
+ : w.stopping ? (name === undefined ? t.walkStopped(at) : t.moveStopped(name, at))
1342
+ : msg.by === 'drag' ? (name === undefined ? t.walkGrabbed(at, this.userName) : t.moveGrabbed(name, at, this.userName))
1343
+ : name === undefined ? t.walkReplaced(at, by) : t.moveFailed(name, at, by));
1344
+ return;
1345
+ }
1346
+ case 'answer': return this.onAnswer(msg, 'pet');
1347
+ case 'portrait': {
1348
+ const png = typeof msg.png === 'string' ? Buffer.from(msg.png, 'base64') : null;
1349
+ const sized = [msg.width, msg.height].every((n) => typeof n === 'number' && n > 0);
1350
+ this.portraits.get(String(msg.id))?.(png?.length && sized ? { png, width: msg.width as number, height: msg.height as number }
1351
+ : PAGE_NO_PORTRAIT.includes(String(msg.failed)) ? msg.failed as NoPortrait : 'capture');
1352
+ return;
1353
+ }
1354
+ case 'visibility': this.petHidden = msg.hidden === true; this.tellDesktop(); return;
1355
+ case 'text': {
1356
+ const text = typeof msg.text === 'string' ? msg.text.trim().slice(0, BOX_TEXT_MAX) : '';
1357
+ const images = parseChatImages(msg.images, this.userName, petText(this.appLanguage).chat, this.t);
1358
+ if (!images.ok) { this.log?.warn(`打字框发来的图片没有收下:${images.reason}`); return; }
1359
+ if (!text && images.blobs.length === 0) return;
1360
+ void this.push('agent-speed.message', 'agent-speed.text', this.t.typed(this.userName, text), 'preempt',
1361
+ { meta: { via: 'bubble', text }, ...(images.blobs.length ? { blobs: images.blobs } : {}) });
1362
+ return;
1363
+ }
1364
+ case 'expand': {
1365
+ const text = typeof msg.text === 'string' ? msg.text.slice(0, CHAT_TEXT_MAX) : '';
1366
+ const images = draftImages(msg.images);
1367
+ this.draft = { text, images };
1368
+ if (this.chat.size) { this.chat.broadcast({ t: 'draft', text, images }); this.draft = null; }
1369
+ this.opts.controls?.openChat?.();
1370
+ return;
1371
+ }
1372
+ case 'touch': return this.onTouch(msg);
1373
+ case 'mic': {
1374
+ this.micState = { state: String(msg.state), detail: typeof msg.detail === 'string' ? msg.detail : null };
1375
+ // a closed microphone sends no more frames: the meter drops to silence
1376
+ if (this.micState.state !== 'on') {
1377
+ this.holdPreRoll.length = 0;
1378
+ this.level = -100;
1379
+ this.voiceFrame({ type: 'level', level: this.level, speaking: false, open: this.gateOpen() });
1380
+ }
1381
+ return;
1382
+ }
1383
+ case 'prefs': return this.savePrefs(msg);
1384
+ case 'position': {
1385
+ if (typeof msg.x !== 'number' || !Number.isFinite(msg.x)) return;
1386
+ this.standX = Math.min(1, Math.max(0, msg.x));
1387
+ this.standY = typeof msg.y === 'number' && Number.isFinite(msg.y) ? Math.min(1, Math.max(0, msg.y)) : null;
1388
+ return;
1389
+ }
1390
+ case 'devices': {
1391
+ const list = Array.isArray(msg.list) ? msg.list : [];
1392
+ this.devices = list
1393
+ .filter((d): d is { id: string; label: string } => !!d && typeof (d as { id?: unknown }).id === 'string')
1394
+ .map((d) => ({ id: d.id, label: typeof d.label === 'string' ? d.label : '' }));
1395
+ return;
1396
+ }
1397
+ case 'confirm-shown': {
1398
+ const id = String(msg.id), c = this.confirms.get(id);
1399
+ if (!c || c.shown) return;
1400
+ c.shown = true;
1401
+ clearTimeout(c.timer);
1402
+ c.timer = this.confirmTimer(id, CONFIRM_TIMEOUT_MS);
1403
+ return;
1404
+ }
1405
+ case 'confirmed': {
1406
+ const c = this.confirms.get(String(msg.id));
1407
+ if (!c) return;
1408
+ this.confirms.delete(String(msg.id));
1409
+ clearTimeout(c.timer);
1410
+ c.resolve(msg.index === 0 ? 'yes' : msg.index === c.choices - 1 ? 'no' : msg.index === 1 ? 'always' : 'dismissed');
1411
+ return;
1412
+ }
1413
+ case 'control': return this.onControl(String(msg.action));
1414
+ case 'dialog': {
1415
+ const settle = this.dialogs.get(String(msg.id));
1416
+ if (!settle) return;
1417
+ this.dialogs.delete(String(msg.id));
1418
+ settle(typeof msg.index === 'number' ? { index: msg.index }
1419
+ : Array.isArray(msg.picked) ? { picked: [...new Set(msg.picked.filter((i): i is number => Number.isInteger(i) && i >= 0))].sort((a, b) => a - b) }
1420
+ : typeof msg.text === 'string' ? { text: msg.text.slice(0, 2000) }
1421
+ : msg.alt ? { alt: true } : msg.closed ? { closed: true } : msg.back ? { back: true } : { done: true });
1422
+ return;
1423
+ }
1424
+ case 'commit': return this.commitSpeech();
1425
+ case 'cancel': return this.cancelSpeech();
1426
+ case 'skipped': {
1427
+ // the person ended a line early: the lines after it start now rather than when it was estimated to end
1428
+ const i = this.sayEnds.findIndex((l) => l.id === String(msg.id));
1429
+ if (i < 0) return;
1430
+ const shift = Date.now() - this.sayEnds[i]!.at;
1431
+ this.sayEnds = this.sayEnds.slice(i + 1).map((l) => ({ ...l, at: l.at + shift }));
1432
+ return;
1433
+ }
1434
+ }
1435
+ }
1436
+
1437
+ private onControl(action: string): void {
1438
+ const c = this.opts.controls;
1439
+ if (!c) return;
1440
+ if (action === 'pause' || action === 'resume') c.setPaused?.(action === 'pause');
1441
+ else if (action === 'settings') c.openSettings?.();
1442
+ else if (action === 'dress') c.openDress?.();
1443
+ else if (action === 'worlds') c.openWorlds?.();
1444
+ else if (action === 'cua' && this.cuaCanOpen) c.openCuaSettings?.();
1445
+ else if (action === 'quit') c.quit?.();
1446
+ this.syncPrefs();
1447
+ }
1448
+
1449
+ /** Ends the wait with 'timeout' after `ms`, and takes the confirmation off the page, queued or shown. */
1450
+ private confirmTimer(id: string, ms: number): NodeJS.Timeout {
1451
+ return setTimeout(() => {
1452
+ const c = this.confirms.get(id);
1453
+ this.confirms.delete(id);
1454
+ this.server.sendPet({ t: 'ask-close', id });
1455
+ c?.resolve('timeout');
1456
+ }, ms);
1457
+ }
1458
+
1459
+ /**
1460
+ * Asks the person in a bubble with two choices, the first one meaning yes, or three, the middle one
1461
+ * meaning yes and from now on. Answers never reach the bot as events; the caller gets them. A hidden
1462
+ * pet's bubble cannot be seen, so the caller gets 'unavailable' at once, as with no pet page. The answer
1463
+ * is awaited CONFIRM_TIMEOUT_MS from when the page shows the bubble, which may queue it behind lines.
1464
+ */
1465
+ confirm(question: string, choices: [yes: string, no: string] | [yes: string, always: string, no: string]): Promise<ConfirmResult> {
1466
+ const id = nextId('k');
1467
+ if (this.petHidden || !this.server.sendPet({ t: 'confirm', id, question, options: choices })) return Promise.resolve('unavailable');
1468
+ return new Promise((resolve) => {
1469
+ this.confirms.set(id, { resolve, timer: this.confirmTimer(id, CONFIRM_UNSHOWN_MS), choices: choices.length, shown: false });
1470
+ });
1471
+ }
1472
+
1473
+ /**
1474
+ * Shows one step of a conversation in the bubble; see `PetDialog`. Nothing reaches the bot: the
1475
+ * caller gets the answer. Steps wait for as long as the person takes; a step with nothing to
1476
+ * answer ends once its line has been read.
1477
+ */
1478
+ dialog(d: PetDialog): PetDialogHandle {
1479
+ const id = nextId('d');
1480
+ const vocab = this.vocab();
1481
+ const { actions } = parseActions(d.actions ?? [], vocab);
1482
+ // a card's words go through the same vocabulary as the line's
1483
+ const input = d.input?.kind === 'choices'
1484
+ ? { ...d.input, options: d.input.options.map((o) => (o.actions ? { ...o, actions: parseActions(o.actions, vocab).actions } : o)) }
1485
+ : d.input;
1486
+ let settle: (a: PetDialogAnswer) => void = () => {};
1487
+ const answer = new Promise<PetDialogAnswer>((resolve) => { settle = resolve; });
1488
+ if (!this.server.sendPet({ t: 'dialog', id, ...d, input, actions })) settle({ unavailable: true });
1489
+ // a pick is answered with indices of its own cards
1490
+ else this.dialogs.set(id, input?.kind === 'pick' ? (a) => settle('picked' in a ? { picked: a.picked.filter((i) => i < input.options.length) } : a) : settle);
1491
+ // a page that never reports back (a tab put to sleep) does not hold a line with nothing to answer forever
1492
+ if (!d.input && this.dialogs.has(id)) {
1493
+ const timer = setTimeout(() => this.dialogs.get(id)?.({ done: true }), 5000 + d.text.length / DIALOG_CPS * 1000);
1494
+ void answer.finally(() => { clearTimeout(timer); this.dialogs.delete(id); });
1495
+ }
1496
+ return {
1497
+ answer,
1498
+ update: (patch) => { if (this.dialogs.has(id)) this.server.sendPet({ t: 'dialog-update', id, ...patch }); },
1499
+ close: () => {
1500
+ const s = this.dialogs.get(id);
1501
+ this.dialogs.delete(id);
1502
+ this.server.sendPet({ t: 'dialog-close', id });
1503
+ s?.({ done: true });
1504
+ },
1505
+ };
1506
+ }
1507
+
1508
+ /** Dresses the body in `patch` over the skin as it is, and saves it, as a pick on the dressing page does. */
1509
+ dress(patch: Partial<PetSkin>): void {
1510
+ this.saveSkin({ ...this.cfg.skin, ...patch });
1511
+ }
1512
+
1513
+ /** Tells `onDesktopChange` when the pet window's place on the desktop changed since it was last told. */
1514
+ private tellDesktop(): void {
1515
+ const on = this.server.petInWindow && !this.petHidden;
1516
+ if (on === this.desktopTold) return;
1517
+ this.desktopTold = on;
1518
+ this.opts.onDesktopChange?.(on);
1519
+ if (on) this.tellHoliday();
1520
+ }
1521
+
1522
+ /** Tells the bot of today's holiday once that day; a reconnect or a restart finds the event already stored. */
1523
+ private tellHoliday(): void {
1524
+ const host = this.host;
1525
+ if (!host) return;
1526
+ const today = new Intl.DateTimeFormat('en-CA', { timeZone: this.opts.timezone }).format(new Date());
1527
+ const id = (Object.keys(HOLIDAYS) as Array<keyof typeof HOLIDAYS>).find((h) => today.endsWith(HOLIDAYS[h]));
1528
+ if (!id) return;
1529
+ const senderKey = `${HOLIDAY_TYPE}.${id}`;
1530
+ // today's event is less than a day old: the bound keeps the lookup off the older history
1531
+ const since = new Date(Date.now() - 86_400_000).toISOString();
1532
+ if (host.store.range({ source: this.id, senderKey, fromTs: since, limit: 1 }).length) return;
1533
+ void this.push(HOLIDAY_TYPE, senderKey, this.t.holiday[id], 'debounce');
1534
+ }
1535
+
1536
+ private onPageGone(): void {
1537
+ this.log?.info('桌宠页面断开');
1538
+ this.holdPreRoll.length = 0;
1539
+ this.tellDesktop();
1540
+ for (const [id, d] of this.dialogs) { d({ unavailable: true }); this.dialogs.delete(id); }
1541
+ for (const [id, w] of this.walks) { clearTimeout(w.timer); w.resolve(this.t.walkWindowGone); this.walks.delete(id); }
1542
+ for (const done of [...this.portraits.values()]) done('gone');
1543
+ for (const [id, c] of this.confirms) { clearTimeout(c.timer); c.resolve('unavailable'); this.confirms.delete(id); }
1544
+ this.segmenter.flush();
1545
+ if (this.wasSpeaking) this.wasSpeaking = false;
1546
+ }
1547
+
1548
+ /** An answer from the pet's bubble or the chat page; an answer from the page closes the bubble. */
1549
+ private onAnswer(msg: Record<string, unknown>, from: 'pet' | 'chat'): void {
1550
+ const ask = this.ask;
1551
+ if (!ask || ask.id !== msg.askId) return;
1552
+ const t = this.t;
1553
+ if (msg.dismissed) {
1554
+ this.setAsk(null);
1555
+ void this.push('agent-speed.answer', 'agent-speed.answer', t.answerClosed(this.userName, ask.question), 'debounce', { meta: { askId: ask.id, dismissed: true } });
1556
+ return;
1557
+ }
1558
+ const index = typeof msg.index === 'number' && ask.options[msg.index] !== undefined ? msg.index : null;
1559
+ const text = typeof msg.text === 'string' ? msg.text.trim().slice(0, ANSWER_TEXT_MAX) : '';
1560
+ if (index === null && !text) return;
1561
+ this.setAsk(null);
1562
+ if (from === 'chat') this.server.sendPet({ t: 'ask-close', id: ask.id });
1563
+ const line = index !== null
1564
+ ? t.answerPicked(this.userName, ask.question, index + 1, ask.options[index]!)
1565
+ : t.answerWrote(this.userName, ask.question, text);
1566
+ void this.push('agent-speed.answer', 'agent-speed.answer', line, 'flush',
1567
+ { meta: { askId: ask.id, ...(index !== null ? { index } : { text }) } });
1568
+ }
1569
+
1570
+ private onTouch(msg: PageMessage): void {
1571
+ if (!this.cfg.touch.enabled) return;
1572
+ const kind = String(msg.kind);
1573
+ if (kind === 'grab') return;
1574
+ if (kind === 'crash' && this.touch && (this.touch.kind === 'throw' || this.touch.kind === 'drop')) {
1575
+ this.touch.crashed = true;
1576
+ return;
1577
+ }
1578
+ if (this.touch && this.touch.kind === kind && kind !== 'throw' && kind !== 'drop') {
1579
+ this.touch.count++;
1580
+ this.touch.woke ||= msg.woke === true;
1581
+ clearTimeout(this.touch.timer);
1582
+ this.touch.timer = setTimeout(() => this.flushTouch(), TOUCH_MERGE_MS);
1583
+ return;
1584
+ }
1585
+ if (this.touch) this.flushTouch();
1586
+ this.touch = {
1587
+ kind, count: 1, woke: msg.woke === true, asleep: msg.asleep === true, crashed: false,
1588
+ x: typeof msg.x === 'number' ? msg.x : null,
1589
+ timer: setTimeout(() => this.flushTouch(), TOUCH_MERGE_MS),
1590
+ };
1591
+ }
1592
+
1593
+ private flushTouch(): void {
1594
+ const t = this.touch;
1595
+ this.touch = null;
1596
+ if (!t) return;
1597
+ clearTimeout(t.timer);
1598
+ const u = this.userName;
1599
+ const m = this.t;
1600
+ let text: string;
1601
+ switch (t.kind) {
1602
+ case 'poke': text = t.woke ? m.pokedAwake(u) : m.poked(u, t.count); break;
1603
+ case 'pet': text = t.asleep ? m.pettedAsleep(u) : m.petted(u, t.count); break;
1604
+ case 'throw': text = m.thrown(u, t.crashed); break;
1605
+ case 'drop': text = m.dropped(u, t.x !== null && this.screen ? pct(t.x / this.screen.w) : null, t.crashed); break;
1606
+ case 'crash': text = m.crashed; break;
1607
+ default: return;
1608
+ }
1609
+ const wakes = !this.touchWoke && touchWakes(this.cfg.touch, t.kind);
1610
+ if (wakes) this.touchWoke = true;
1611
+ void this.push('agent-speed.touch', 'agent-speed.touch', m.touch(text), wakes ? 'debounce' : 'piggyback',
1612
+ { meta: { touch: { kind: t.kind, count: t.count, woke: t.woke, crashed: t.crashed } } });
1613
+ }
1614
+
1615
+ /**
1616
+ * The person's local time an event happened, before its text: `[HH:MM] `, and `[MM-DD <weekday> HH:MM] ` for the
1617
+ * first event of a run and the first on a new date, so the bot knows the date without a clock in its prefix.
1618
+ * The weekday is short, in the model-text language (周日, Sun).
1619
+ */
1620
+ private stamp(now = new Date()): string {
1621
+ const parts = Object.fromEntries(new Intl.DateTimeFormat(this.t.dateLocale, { timeZone: this.opts.timezone, year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' })
1622
+ .formatToParts(now).map((p) => [p.type, p.value]));
1623
+ const day = `${parts.year}-${parts.month}-${parts.day}`;
1624
+ const time = shortTime(this.opts.timezone, now);
1625
+ if (day === this.stampDay) return `[${time}] `;
1626
+ this.stampDay = day;
1627
+ return `[${parts.month}-${parts.day} ${parts.weekday} ${time}] `;
1628
+ }
1629
+
1630
+ /**
1631
+ * Delivers an event to the bot. `meta` carries what the chat page shows of it; the person's
1632
+ * messages stay pending on the page until Core reports them delivered.
1633
+ */
1634
+ private async push(
1635
+ type: string, senderKey: string, text: string, trigger: TriggerMode,
1636
+ extra: { meta?: Record<string, unknown>; blobs?: BlobInput[] } = {},
1637
+ ): Promise<EventEnvelope | null> {
1638
+ const host = this.host;
1639
+ if (!host) return null;
1640
+ try {
1641
+ const e = await host.pushEvent({ type, source: this.id, senderKey, ts: nowIso(this.opts.timezone), text: this.stamp() + text, ...extra }, { trigger });
1642
+ const item = chatItem(e);
1643
+ if (!item) return e;
1644
+ const pending = item.kind === 'user' && e.contextDelivery === 'deliver';
1645
+ if (pending) this.pendingChat.add(e.cursor);
1646
+ this.chat.broadcast({ t: 'item', item, ...(pending ? { pending: true } : {}) });
1647
+ return e;
1648
+ } catch (err) {
1649
+ this.log?.warn(`事件没能送出:${(err as Error).message}`);
1650
+ return null;
1651
+ }
1652
+ }
1653
+
1654
+ /** Stores what the pet said or did for the chat page; never delivered to the bot. Resolves to its cursor. */
1655
+ private async record(meta: Record<string, unknown>, text: string, blobs: BlobInput[] = []): Promise<number | null> {
1656
+ const host = this.host;
1657
+ if (!host) return null;
1658
+ try {
1659
+ const e = await host.pushEvent({ type: SELF_TYPE, source: this.id, senderKey: SELF_TYPE, ts: nowIso(this.opts.timezone), text, meta, ...(blobs.length ? { blobs } : {}) }, { deliver: false });
1660
+ const item = chatItem(e);
1661
+ if (item) this.chat.broadcast({ t: 'item', item });
1662
+ return e.cursor;
1663
+ } catch (err) {
1664
+ this.log?.warn(`对话记录没能保存:${(err as Error).message}`);
1665
+ return null;
1666
+ }
1667
+ }
1668
+
1669
+ /* ---------- voice ---------- */
1670
+
1671
+ /** The model files of a sherpa-onnx engine, or why they are not there. */
1672
+ private sherpaModel(engine: SherpaEngine): { paths: Record<string, string> } | { missing: string } {
1673
+ const slot = this.store[engine];
1674
+ if (slot.state().phase !== 'ready') return { missing: this.ui.voice.modelMissing(Math.round(slot.bytes / 1048576)) };
1675
+ return { paths: slot.paths() };
1676
+ }
1677
+
1678
+ /** The engine in force (`asrEngineFor`). */
1679
+ engine(): AsrEngine {
1680
+ return asrEngineFor(this.cfg.asr.engine, this.appLanguage, systemRecognizerSupported());
1681
+ }
1682
+
1683
+ /** The sherpa-onnx engine whose model voice input downloads: the one in force, else the app language's. */
1684
+ private modelEngine(): SherpaEngine {
1685
+ const engine = this.engine();
1686
+ return engine === 'system' || engine === 'api' ? asrEngineFor('', this.appLanguage, false) as SherpaEngine : engine;
1687
+ }
1688
+
1689
+ private sherpa(engine: SherpaEngine): SherpaAsr | null {
1690
+ return engine === 'whisper' ? this.whisper : this.funasr;
1691
+ }
1692
+
1693
+ private recognizer(engine = this.engine()): SherpaAsr | SystemRecognizer | TranscriptionApi | null {
1694
+ return engine === 'system' ? this.system : engine === 'api' ? this.api : this.sherpa(engine);
1695
+ }
1696
+
1697
+ /** The recognition language: the set one, else the app language's ISO 639-1 code; FunASR and Whisper read a code they do not take as `auto`. */
1698
+ private asrLanguage(): string {
1699
+ return this.cfg.asr.language || this.appLanguage.split('-')[0]!;
1700
+ }
1701
+
1702
+ private backendState(): BackendState | null {
1703
+ return this.recognizer()?.state() ?? null;
1704
+ }
1705
+
1706
+ /** Starts the engine in force and stops the one that ran before. Each recognizer shares one start between concurrent calls. */
1707
+ async startVoiceBackend(): Promise<BackendState | null> {
1708
+ const generation = this.voiceGeneration;
1709
+ await this.voiceStopping;
1710
+ if (generation !== this.voiceGeneration || !this.recognitionWanted()) return this.backendState();
1711
+ const engine = this.engine();
1712
+ const recognizer = this.recognizer(engine);
1713
+ if (!recognizer) return null;
1714
+ if (this.runningEngine !== engine) {
1715
+ if (this.runningEngine) await this.recognizer(this.runningEngine)?.stop();
1716
+ if (generation !== this.voiceGeneration || !this.recognitionWanted() || engine !== this.engine()) return this.backendState();
1717
+ this.runningEngine = engine;
1718
+ }
1719
+ await recognizer.start();
1720
+ if (generation === this.voiceGeneration) this.syncPrefs();
1721
+ return this.backendState();
1722
+ }
1723
+
1724
+ private stopVoiceBackend(): Promise<void> {
1725
+ this.voiceGeneration++;
1726
+ this.holdPreRoll.length = 0;
1727
+ if (this.voiceStopping) return this.voiceStopping;
1728
+ const engine = this.runningEngine;
1729
+ this.runningEngine = null;
1730
+ const stopped = ((engine ? this.recognizer(engine)?.stop() : undefined) ?? Promise.resolve()).finally(() => {
1731
+ this.voiceStopping = null;
1732
+ this.syncPrefs();
1733
+ });
1734
+ this.voiceStopping = stopped;
1735
+ return stopped;
1736
+ }
1737
+
1738
+ /* ---------- talk key ---------- */
1739
+
1740
+ /** Audio reaches the segmenter only while this is true. */
1741
+ private gateOpen(): boolean {
1742
+ return this.cfg.asr.mic.mode === 'always' || this.talking;
1743
+ }
1744
+
1745
+ private holdPreRollEnabled(): boolean {
1746
+ const { mode, hotkey, openOnPress } = this.cfg.asr.mic;
1747
+ return this.micWanted() && mode === 'hold' && !openOnPress && this.typeKeyShares(hotkey);
1748
+ }
1749
+
1750
+ /**
1751
+ * While the talk key is held everything counts as speech: the segmenter never waits for a
1752
+ * loud onset or cuts at a pause, and releasing the key ends the utterance.
1753
+ */
1754
+ private segmentConfig(): SegmentConfig {
1755
+ const seg = this.cfg.asr.segment;
1756
+ return this.cfg.asr.mic.mode === 'hold' ? { ...seg, thresholdDb: -Infinity, minSpeechMs: 0 } : seg;
1757
+ }
1758
+
1759
+ /**
1760
+ * Starts, restarts or stops the key watcher to match the configured mode and key. Hold to talk
1761
+ * waits out a tap only while the typing key is the same key, so that key's double tap only types.
1762
+ */
1763
+ private async syncHotkey(): Promise<void> {
1764
+ const { mode, hotkey } = this.cfg.asr.mic;
1765
+ const trigger: HotkeyTrigger = mode === 'hold' && this.typeKeyShares(hotkey) ? 'hold' : 'press';
1766
+ const key = mode === 'always' || !this.host ? '' : `${mode}:${hotkey}:${trigger}`;
1767
+ if (key === this.hotkeyKey) { this.tellHotkeyProblem(); return; }
1768
+ this.hotkeyKey = key;
1769
+ this.keyWatcher?.stop();
1770
+ this.keyWatcher = null;
1771
+ this.hotkeyProblem = null;
1772
+ this.setTalking(false);
1773
+ if (!key) return;
1774
+ const parsed = parseHotkey(hotkey);
1775
+ const watch = this.opts.watchHotkey ?? watchHotkey;
1776
+ const watcher = parsed ? await watch(parsed, (down) => this.onTalkKey(down), HOTKEY_POLL_MS, () => this.onTalkTap(), this.ui.hotkey, trigger,
1777
+ () => { this.holdPreRoll.length = 0; }) : this.ui.voice.badKey(hotkey);
1778
+ if (key !== this.hotkeyKey) { if (typeof watcher !== 'string') watcher.stop(); return; }
1779
+ if (typeof watcher === 'string') {
1780
+ this.hotkeyProblem = watcher;
1781
+ this.log?.warn(`说话键不可用,暂不识别说话:${watcher}`);
1782
+ this.tellHotkeyProblem();
1783
+ } else this.keyWatcher = watcher;
1784
+ }
1785
+
1786
+ /** A key that cannot be read shows nothing when pressed, so the bot is told why: each problem once a run, while voice input is on. */
1787
+ private tellHotkeyProblem(): void {
1788
+ const problem = this.hotkeyProblem;
1789
+ if (!problem || problem === this.hotkeyProblemTold || !this.cfg.asr.enabled) return;
1790
+ this.hotkeyProblemTold = problem;
1791
+ void this.push('agent-speed.talk-key', 'agent-speed.talk-key', this.t.talkKeyUnreadable(this.userName, problem), 'flush').then((e) => {
1792
+ if (!e) this.hotkeyProblemTold = null;
1793
+ });
1794
+ }
1795
+
1796
+ /** The typing key is on and made of the same keys as `talk`, press counts aside. */
1797
+ private typeKeyShares(talk: string): boolean {
1798
+ const { enabled, hotkey } = this.cfg.typeKey;
1799
+ const a = parseHotkey(talk), b = parseHotkey(hotkey);
1800
+ if (!enabled || !a || !b) return false;
1801
+ const keys = new Set(b.keys);
1802
+ return new Set(a.keys).size === keys.size && a.keys.every((vk) => keys.has(vk));
1803
+ }
1804
+
1805
+ /** Starts, restarts or stops the typing key's watcher; multi-press shortcuts require completed quick taps. */
1806
+ private async syncTypeKey(): Promise<void> {
1807
+ const { enabled, hotkey } = this.cfg.typeKey;
1808
+ const key = enabled && this.host ? hotkey : '';
1809
+ if (key === this.typeKeyKey) return;
1810
+ this.typeKeyKey = key;
1811
+ this.typeWatcher?.stop();
1812
+ this.typeWatcher = null;
1813
+ this.typeKeyProblem = null;
1814
+ if (!key) return;
1815
+ const parsed = parseHotkey(hotkey);
1816
+ const watch = this.opts.watchHotkey ?? watchHotkey;
1817
+ const text = { ...this.ui.hotkey, ...this.ui.typeKey };
1818
+ // a hidden pet stays hidden: its typing box would open out of sight
1819
+ const onPress = (down: boolean) => { if (down && !this.petHidden) this.server.sendPet({ t: 'type' }); };
1820
+ const watcher = parsed ? await watch(parsed, onPress, HOTKEY_POLL_MS, undefined, text, parsed.taps > 1 ? 'tap' : 'press') : this.ui.voice.badKey(hotkey);
1821
+ if (key !== this.typeKeyKey) { if (typeof watcher !== 'string') watcher.stop(); return; }
1822
+ if (typeof watcher === 'string') {
1823
+ this.typeKeyProblem = watcher;
1824
+ this.log?.warn(`打字键不可用:${watcher}`);
1825
+ } else this.typeWatcher = watcher;
1826
+ }
1827
+
1828
+ /**
1829
+ * Starts, restarts or stops the click-through pause key's watcher. It activates on a hold during which no other key or mouse
1830
+ * button went down, so a modifier held for a shortcut does not count; the page then lets clicks reach the pet until release.
1831
+ */
1832
+ private async syncThroughPauseKey(): Promise<void> {
1833
+ const { enabled, hotkey } = this.cfg.throughPauseKey;
1834
+ const key = enabled && this.host ? hotkey : '';
1835
+ if (key === this.throughPauseKeyKey) return;
1836
+ this.throughPauseKeyKey = key;
1837
+ this.throughPauseWatcher?.stop();
1838
+ this.throughPauseWatcher = null;
1839
+ this.throughPauseKeyProblem = null;
1840
+ this.setThroughPaused(false);
1841
+ if (!key) return;
1842
+ const parsed = parseHotkey(hotkey);
1843
+ const watch = this.opts.watchHotkey ?? watchHotkey;
1844
+ const text = { ...this.ui.hotkey, ...this.ui.throughPauseKey };
1845
+ const watcher = parsed ? await watch(parsed, (down) => this.setThroughPaused(down), HOTKEY_POLL_MS, undefined, text, 'holdAlone') : this.ui.voice.badKey(hotkey);
1846
+ if (key !== this.throughPauseKeyKey) { if (typeof watcher !== 'string') watcher.stop(); return; }
1847
+ if (typeof watcher === 'string') {
1848
+ this.throughPauseKeyProblem = watcher;
1849
+ this.log?.warn(`暂停穿透键不可用:${watcher}`);
1850
+ } else this.throughPauseWatcher = watcher;
1851
+ }
1852
+
1853
+ /** The talk key is in use and pressed exactly as the click-through pause key: one hold sets off both. */
1854
+ private throughPauseSharesTalk(): boolean {
1855
+ const { mode, hotkey } = this.cfg.asr.mic;
1856
+ const a = parseHotkey(hotkey), b = parseHotkey(this.cfg.throughPauseKey.hotkey);
1857
+ if (!this.cfg.asr.enabled || mode === 'always' || !a || !b || a.taps !== b.taps) return false;
1858
+ const keys = new Set(b.keys);
1859
+ return new Set(a.keys).size === keys.size && a.keys.every((vk) => keys.has(vk));
1860
+ }
1861
+
1862
+ private setThroughPaused(on: boolean): void {
1863
+ if (on === this.throughPaused) return;
1864
+ this.throughPaused = on;
1865
+ this.server.sendPet({ t: 'throughPause', on });
1866
+ }
1867
+
1868
+ /** One line telling the person how to be heard. */
1869
+ private talkHint(): string {
1870
+ const { hotkey } = this.cfg.asr.mic;
1871
+ const ui = this.ui, v = ui.voice;
1872
+ const key = comboLabel(hotkey, process.platform, ui), { taps } = splitTaps(hotkey);
1873
+ const mode = this.cfg.asr.mic.mode;
1874
+ if (mode === 'always') return v.always;
1875
+ if (this.hotkeyProblem) return v.keyProblem(this.hotkeyProblem);
1876
+ if (mode === 'toggle') return taps > 1 ? v.toggleTaps(hotkeyLabel(hotkey, process.platform, ui), taps) : v.toggle(key);
1877
+ return taps > 1 ? v.holdTaps(key, taps) : v.hold(key);
1878
+ }
1879
+
1880
+ /** A quick tap before the held press: the pet perks up, so the hold that follows feels answered at once. */
1881
+ private onTalkTap(): void {
1882
+ if (this.talking || !this.cfg.asr.enabled || !this.micWanted()) return;
1883
+ this.server.sendPet({ t: 'listen', phase: 'ready' });
1884
+ }
1885
+
1886
+ private onTalkKey(down: boolean): void {
1887
+ if (this.cfg.asr.mic.mode === 'hold') this.setTalking(down);
1888
+ else if (down) this.setTalking(!this.talking);
1889
+ }
1890
+
1891
+ private setTalking(on: boolean): void {
1892
+ if (!on || !this.holdPreRollEnabled()) this.holdPreRoll.length = 0;
1893
+ if (this.talking === on) return;
1894
+ this.talking = on;
1895
+ this.voiceFrame({ type: 'gate', open: on });
1896
+ if (!on) this.releaseMicSoon();
1897
+ this.server.sendPet({ t: 'talk-key', down: on && this.cfg.asr.enabled && this.micWanted() });
1898
+ if (!this.cfg.asr.enabled || !this.micWanted()) return;
1899
+ if (on) {
1900
+ this.audioDisplay = null;
1901
+ this.listenOpen = true;
1902
+ // With openOnPress, the first microphone frame starts the listening bubble.
1903
+ if (this.micOnPress()) this.setMicHeld(true);
1904
+ else this.server.sendPet({ t: 'listen', phase: 'start' });
1905
+ const since = performance.now() - HOLD_PRE_ROLL_FRAMES * FRAME_MS;
1906
+ for (const { frame, atMs } of this.holdPreRoll.splice(0)) {
1907
+ if (atMs >= since) this.onAudio(frame);
1908
+ }
1909
+ return;
1910
+ }
1911
+ const tail = this.segmenter.flush();
1912
+ if (tail) this.enqueue(tail);
1913
+ this.wasSpeaking = false;
1914
+ this.schedulePack();
1915
+ }
1916
+
1917
+ /**
1918
+ * The listening bubble's cancel button (hold and toggle): what the bubble shows is dropped,
1919
+ * nothing goes to the bot, and the bubble closes. A held talk key's release that follows finds
1920
+ * nothing to send; a switched-on one is switched off.
1921
+ */
1922
+ private cancelSpeech(): void {
1923
+ this.holdPreRoll.length = 0;
1924
+ if (this.cfg.asr.mic.mode === 'always' || (!this.talking && !this.listenOpen)) return;
1925
+ if (this.talking) {
1926
+ this.talking = false;
1927
+ this.voiceFrame({ type: 'gate', open: false });
1928
+ this.releaseMicSoon();
1929
+ this.server.sendPet({ t: 'talk-key', down: false });
1930
+ }
1931
+ this.discardSpeech();
1932
+ this.log?.info('倾听气泡里点了取消,这次收音已丢弃');
1933
+ }
1934
+
1935
+ private discardSpeech(): void {
1936
+ this.clearAudioSettleTimer();
1937
+ this.segmenter.flush();
1938
+ if (this.packTimer) clearTimeout(this.packTimer);
1939
+ this.packTimer = null;
1940
+ this.interim = '';
1941
+ this.audioBatch = null;
1942
+ this.audioDisplay = null;
1943
+ this.audioDeliveries.length = 0;
1944
+ this.queue.length = 0;
1945
+ this.cancels++;
1946
+ this.packer.take();
1947
+ this.heardPcm = [];
1948
+ this.committing = false;
1949
+ this.partial = '';
1950
+ this.wasSpeaking = false;
1951
+ if (this.listenOpen) {
1952
+ this.listenOpen = false;
1953
+ this.server.sendPet({ t: 'listen', phase: 'none' });
1954
+ }
1955
+ }
1956
+
1957
+ /**
1958
+ * The pet's microphone button, held down: what was heard so far goes out now. The sentence
1959
+ * in progress is cut, and delivery waits only for transcription, not for the closing pause.
1960
+ * A switched-on talk key (toggle) is switched off: that sentence is finished.
1961
+ */
1962
+ private commitSpeech(): void {
1963
+ if (!this.cfg.asr.enabled || !this.micWanted()) return;
1964
+ this.committing = true;
1965
+ if (this.cfg.asr.mic.mode === 'toggle' && this.talking) this.setTalking(false);
1966
+ else {
1967
+ const tail = this.segmenter.flush();
1968
+ if (tail) this.enqueue(tail);
1969
+ this.wasSpeaking = false;
1970
+ }
1971
+ this.schedulePack();
1972
+ }
1973
+
1974
+ private validSpeechJob(job: SpeechJob): boolean {
1975
+ return job.cancels === this.cancels && job.generation === this.voiceGeneration && this.recognitionWanted();
1976
+ }
1977
+
1978
+ private textWork(): boolean {
1979
+ const current = this.activeSpeechJob;
1980
+ return (!!current && !current.audio && this.validSpeechJob(current))
1981
+ || this.queue.some((job) => !job.audio && this.validSpeechJob(job));
1982
+ }
1983
+
1984
+ /** Finish already recognized legacy text before a new recording-only batch starts. */
1985
+ private settleTextForAudio(): void {
1986
+ if (!this.audioOnly() || this.textWork() || !this.packer.pending) return;
1987
+ this.committing = true;
1988
+ this.schedulePack();
1989
+ }
1990
+
1991
+ private enqueue(u: Utterance): void {
1992
+ this.counts.utterances++;
1993
+ this.settleTextForAudio();
1994
+ if (this.audioBatch || (this.audioOnly() && !this.textWork() && !this.packer.pending)) {
1995
+ // hold mode keeps every held stretch (`segmentConfig`), a silent one included; that one is not sent as a recording
1996
+ if (this.cfg.asr.mic.mode === 'hold' && peakDb(u.pcm) < SILENT_BELOW_DB) return;
1997
+ const batch: AudioSpeechBatch = this.audioBatch ??= {
1998
+ id: randomUUID(), parts: [], text: [], reports: [], pending: 0, closed: false, sent: false, cancels: this.cancels,
1999
+ trigger: this.cfg.asr.mic.mode === 'always' ? 'flush' : 'interrupt',
2000
+ blobs: [], reported: false, transcriptShown: false, event: null,
2001
+ };
2002
+ if (batch.parts) {
2003
+ const parts = [...batch.parts, u.pcm];
2004
+ batch.parts = samplesIn(parts) <= this.cfg.asr.recording.maxMinutes * 60 * SAMPLE_RATE ? parts : null;
2005
+ }
2006
+ if (this.recognitionWanted() && this.backendState()?.phase === 'running') {
2007
+ batch.pending++;
2008
+ this.queue.push({ utterance: u, audio: batch, generation: this.voiceGeneration, cancels: this.cancels });
2009
+ void this.drain();
2010
+ }
2011
+ return;
2012
+ }
2013
+ if (!this.recognitionWanted()) return;
2014
+ this.queue.push({ utterance: u, generation: this.voiceGeneration, cancels: this.cancels });
2015
+ this.server.sendPet({ t: 'listen', phase: 'transcribing' });
2016
+ void this.drain();
2017
+ }
2018
+
2019
+ private onAudio(frame: Int16Array): void {
2020
+ if (!this.cfg.asr.enabled || !this.micWanted()) { this.holdPreRoll.length = 0; return; }
2021
+ const open = this.gateOpen();
2022
+ if (open) this.clearAudioSettleTimer();
2023
+ if (open) for (const u of this.segmenter.push(frame)) this.enqueue(u);
2024
+ else if (this.holdPreRollEnabled()) {
2025
+ this.holdPreRoll.push({ frame, atMs: performance.now() });
2026
+ while (this.holdPreRoll.length > HOLD_PRE_ROLL_FRAMES) this.holdPreRoll.shift();
2027
+ } else this.holdPreRoll.length = 0;
2028
+ this.level = open ? this.segmenter.level : rmsDb(frame);
2029
+ const speaking = open && this.segmenter.active;
2030
+ if (speaking && !this.wasSpeaking) {
2031
+ this.audioDisplay = null;
2032
+ this.server.sendPet({ t: 'listen', phase: 'start' });
2033
+ }
2034
+ this.wasSpeaking = speaking;
2035
+ const now = Date.now();
2036
+ if (now - this.lastLevelAt >= 100) {
2037
+ this.lastLevelAt = now;
2038
+ this.voiceFrame({ type: 'level', level: this.level, speaking, open });
2039
+ }
2040
+ if (open) this.schedulePack();
2041
+ }
2042
+
2043
+ private async drain(): Promise<void> {
2044
+ if (this.transcribing) return;
2045
+ this.transcribing = true;
2046
+ try {
2047
+ while (this.queue.length) {
2048
+ const job = this.queue.shift()!;
2049
+ const { utterance: u, audio } = job;
2050
+ this.activeSpeechJob = job;
2051
+ const valid = () => this.validSpeechJob(job);
2052
+ try {
2053
+ if (!valid()) continue;
2054
+ const recognizer = this.recognizer();
2055
+ const res = u.result
2056
+ ? await u.result
2057
+ : recognizer
2058
+ ? await recognizer.transcribe(u.pcm)
2059
+ : { text: '', ms: 0, error: this.ui.voice.notRunning };
2060
+ if (!valid()) continue;
2061
+ let text = res.text;
2062
+ if (this.simplifies) text = toSimplified(text);
2063
+ const dropped = !!res.error || looksHallucinated(text);
2064
+ if (audio) {
2065
+ audio.reports.push({ text, ms: res.ms, ...(res.error ? { error: res.error } : {}), dropped });
2066
+ if (!dropped) audio.text.push(text);
2067
+ continue;
2068
+ }
2069
+ if (dropped) {
2070
+ this.counts.dropped++;
2071
+ this.remember({ text: res.error ? this.ui.voice.failedLine(res.error) : text, at: Date.now(), ms: res.ms, dropped: true });
2072
+ this.voiceFrame({ type: 'dropped', text: res.error ?? text, ms: res.ms });
2073
+ if (u.result) this.showHeard();
2074
+ continue;
2075
+ }
2076
+ this.remember({ text, at: Date.now(), ms: res.ms });
2077
+ this.voiceFrame({ type: 'text', text, ms: res.ms });
2078
+ if (this.packer.add(text) && this.heardPcm !== null) {
2079
+ const parts = this.recordingGoes() ? [...this.heardPcm, u.pcm] : null;
2080
+ this.heardPcm = parts && samplesIn(parts) <= this.cfg.asr.recording.maxMinutes * 60 * SAMPLE_RATE ? parts : null;
2081
+ }
2082
+ this.pendingText(text);
2083
+ this.showHeard();
2084
+ } finally {
2085
+ this.activeSpeechJob = null;
2086
+ if (audio) {
2087
+ audio.pending--;
2088
+ this.finishAudioTranscript(audio);
2089
+ }
2090
+ this.schedulePack();
2091
+ }
2092
+ }
2093
+ } finally {
2094
+ this.transcribing = false;
2095
+ }
2096
+ this.schedulePack();
2097
+ }
2098
+
2099
+ private partial = '';
2100
+ private pendingText(add: string): string {
2101
+ this.partial = joinSpeech([this.partial, add]);
2102
+ return this.partial;
2103
+ }
2104
+
2105
+ /* ---------- hearing as it is spoken ---------- */
2106
+
2107
+ /** The sentence the recognizer is hearing now, and what it has made of it so far. */
2108
+ private sentence: SystemSentence | null = null;
2109
+ private interim = '';
2110
+
2111
+ /** The segmenter hands each sentence's audio over as it arrives when the engine can take it. */
2112
+ private readonly sink: SegmentSink = {
2113
+ begin: (frames) => {
2114
+ this.sentence = null;
2115
+ this.interim = '';
2116
+ // The independent audio path recognizes finished segments without streaming into the input bubble.
2117
+ this.settleTextForAudio();
2118
+ if (!this.recognitionWanted() || this.audioBatch || (this.audioOnly() && !this.textWork() && !this.packer.pending)) return;
2119
+ const recognizer = this.recognizer();
2120
+ if (!recognizer) return;
2121
+ const s: SystemSentence | null = recognizer.sentence((text) => {
2122
+ if (this.sentence !== s) return;
2123
+ this.interim = this.simplifies ? toSimplified(text) : text;
2124
+ this.showHeard();
2125
+ });
2126
+ this.sentence = s;
2127
+ if (s) for (const f of frames) s.write(f);
2128
+ },
2129
+ frame: (f) => { if (this.recognitionWanted()) this.sentence?.write(f); },
2130
+ end: (kept) => {
2131
+ const s = this.sentence;
2132
+ this.sentence = null;
2133
+ if (!s) return undefined;
2134
+ const result = s.end();
2135
+ if (!kept && this.interim) { this.interim = ''; this.showHeard(); }
2136
+ else this.interim = '';
2137
+ return kept ? result : undefined;
2138
+ },
2139
+ };
2140
+
2141
+ /** The listening bubble: sentences already transcribed, then the one being heard, greyed. */
2142
+ private showHeard(): void {
2143
+ this.server.sendPet({ t: 'listen', phase: 'partial', text: this.partial, interim: this.interim });
2144
+ }
2145
+
2146
+ /** `asr.recording.enabled` is on and the current endpoint takes `audio/wav`. */
2147
+ private recordingGoes(): boolean {
2148
+ return this.cfg.asr.recording.enabled && this.host?.modelFacts.accepts('audio/wav') === true;
2149
+ }
2150
+
2151
+ /** Takes the recording of the delivered sentences: one WAV while `recordingGoes`, else nothing. */
2152
+ private recording(transcript: boolean): BlobInput[] {
2153
+ const parts = this.heardPcm;
2154
+ this.heardPcm = [];
2155
+ return this.recordingBlobs(parts, transcript);
2156
+ }
2157
+
2158
+ private recordingBlobs(parts: Int16Array[] | null, transcript: boolean): BlobInput[] {
2159
+ if (!parts?.length || !this.recordingGoes()) return [];
2160
+ const pcm = new Int16Array(samplesIn(parts));
2161
+ let at = 0;
2162
+ for (const p of parts) { pcm.set(p, at); at += p.length; }
2163
+ const seconds = Math.round(pcm.length / SAMPLE_RATE * 10) / 10;
2164
+ const fallbackText = transcript ? this.t.recording(this.userName, seconds) : this.t.recordingAlone(this.userName, seconds);
2165
+ return [{ bytes: wavFile(pcm), mime: 'audio/wav', name: 'speech.wav', fallbackText }];
2166
+ }
2167
+
2168
+ /** Close at the capture boundary. Only an earlier unresolved text fallback delays sending a WAV. */
2169
+ private closeAudioBatch(batch: AudioSpeechBatch): void {
2170
+ this.clearAudioSettleTimer();
2171
+ batch.closed = true;
2172
+ this.audioDisplay = batch;
2173
+ batch.blobs = this.recordingBlobs(batch.parts, false);
2174
+ batch.parts = null;
2175
+ this.audioDeliveries.push(batch);
2176
+ this.finishAudioTranscript(batch);
2177
+ this.deliverAudioBatches();
2178
+ if (!batch.sent && this.audioDisplay === batch) {
2179
+ this.listenOpen = true;
2180
+ this.server.sendPet({ t: 'listen', phase: 'transcribing' });
2181
+ }
2182
+ }
2183
+
2184
+ /** Deliver recording-only batches in capture order, including any text fallback on overflow. */
2185
+ private deliverAudioBatches(): void {
2186
+ while (this.audioDeliveries.length) {
2187
+ const batch = this.audioDeliveries[0]!;
2188
+ // WAV is ready immediately; a missing/over-limit WAV must first await ASR text.
2189
+ if (!batch.blobs.length && batch.pending > 0 && this.recognitionWanted()) break;
2190
+ this.audioDeliveries.shift();
2191
+ batch.sent = true;
2192
+ if (batch.blobs.length) {
2193
+ this.counts.delivered++;
2194
+ const label = this.ui.voice.recorded;
2195
+ if (this.audioDisplay === batch) {
2196
+ this.listenOpen = false;
2197
+ this.server.sendPet({ t: 'listen', phase: 'heard', text: label, recordingId: batch.id });
2198
+ }
2199
+ batch.event = this.push('agent-speed.speech', 'agent-speed.voice', this.t.heardRecorded(this.userName), batch.trigger, { meta: { text: label }, blobs: batch.blobs });
2200
+ this.showAudioTranscript(batch);
2201
+ continue;
2202
+ }
2203
+ const text = joinSpeech(batch.text);
2204
+ if (this.audioDisplay === batch) this.listenOpen = false;
2205
+ if (text) {
2206
+ this.counts.delivered++;
2207
+ if (this.audioDisplay === batch) this.server.sendPet({ t: 'listen', phase: 'heard', text });
2208
+ void this.push('agent-speed.speech', 'agent-speed.voice', this.t.heard(this.userName, text), batch.trigger, { meta: { text } });
2209
+ } else {
2210
+ const error = this.ui.voice.recordingUnavailable;
2211
+ this.remember({ text: this.ui.voice.failedLine(error), at: Date.now(), ms: 0, dropped: true });
2212
+ this.voiceFrame({ type: 'dropped', text: error, ms: 0 });
2213
+ if (this.audioDisplay === batch) this.server.sendPet({ t: 'listen', phase: 'heard', text: error });
2214
+ }
2215
+ }
2216
+ }
2217
+
2218
+ /** A transcript that arrives after its recording was delivered replaces the recording's line in the bubble and on the chat page; it is never delivered. */
2219
+ private showAudioTranscript(batch: AudioSpeechBatch): void {
2220
+ if (!batch.reported || !batch.sent || !batch.blobs.length || batch.transcriptShown) return;
2221
+ batch.transcriptShown = true;
2222
+ const text = joinSpeech(batch.text);
2223
+ if (!text) return;
2224
+ this.server.sendPet({ t: 'listen', phase: 'recording-text', recordingId: batch.id, text });
2225
+ void batch.event?.then(async (e) => {
2226
+ if (!e) return;
2227
+ await this.record({ kind: 'transcript', cursor: e.cursor, text }, `转写了 #${e.cursor}:${text}`);
2228
+ this.chat.broadcast({ t: 'transcript', cursor: e.cursor, text });
2229
+ });
2230
+ }
2231
+
2232
+ private finishAudioTranscript(batch: AudioSpeechBatch): void {
2233
+ if (!batch.closed || batch.pending || batch.cancels !== this.cancels || !this.cfg.asr.enabled || batch.reported) return;
2234
+ batch.reported = true;
2235
+ for (const result of batch.reports.splice(0)) {
2236
+ if (result.dropped) this.counts.dropped++;
2237
+ const text = result.error ? this.ui.voice.failedLine(result.error) : result.text;
2238
+ this.remember({ text, at: Date.now(), ms: result.ms, ...(result.dropped ? { dropped: true } : {}) });
2239
+ this.voiceFrame({ type: result.dropped ? 'dropped' : 'text', text: result.error ?? result.text, ms: result.ms });
2240
+ }
2241
+ this.deliverAudioBatches();
2242
+ this.showAudioTranscript(batch);
2243
+ }
2244
+
2245
+ private clearAudioSettleTimer(): void {
2246
+ if (this.audioSettleTimer) clearTimeout(this.audioSettleTimer);
2247
+ this.audioSettleTimer = null;
2248
+ }
2249
+
2250
+ /** Delivers at the capture boundary, waiting for ASR only for a text batch. */
2251
+ private schedulePack(): void {
2252
+ if (this.audioBatch) {
2253
+ const remaining = this.segmenter.settleRemainingMs;
2254
+ const hold = !this.committing && (this.segmenter.active || remaining > 0);
2255
+ // The segmenter's silence clock advances only with frames. Each new frame resets this
2256
+ // deadline; if frames stop during the closing pause, finish the inactive segment once.
2257
+ if (hold && !this.segmenter.active && remaining > 0 && !this.audioSettleTimer) {
2258
+ const batch = this.audioBatch;
2259
+ this.audioSettleTimer = setTimeout(() => {
2260
+ this.audioSettleTimer = null;
2261
+ if (this.audioBatch !== batch || this.segmenter.active) return;
2262
+ this.segmenter.flush();
2263
+ this.schedulePack();
2264
+ }, remaining);
2265
+ }
2266
+ if (!hold) {
2267
+ const batch = this.audioBatch;
2268
+ this.audioBatch = null;
2269
+ this.committing = false;
2270
+ this.listenOpen = false;
2271
+ this.partial = '';
2272
+ this.closeAudioBatch(batch);
2273
+ }
2274
+ return;
2275
+ }
2276
+ const upstream = this.textWork();
2277
+ // A closed recording may be queued behind an older text fallback, even if its own ASR has finished.
2278
+ // Keep the pending bubble open until that recording really has been delivered.
2279
+ if (!upstream && !this.packer.pending && !this.segmenter.active && this.audioDisplay?.closed && !this.audioDisplay.sent) return;
2280
+ // a commit does not wait for the closing pause, nor for speech begun after it
2281
+ const hold = upstream || (!this.committing && (this.segmenter.active || this.segmenter.settleRemainingMs > 0));
2282
+ const text = this.committing && !upstream ? this.packer.take() : this.packer.due(hold);
2283
+ if (this.committing && !upstream && !text) {
2284
+ // nothing was heard: the committed episode closes empty, unless the talk key still holds it open
2285
+ this.committing = false;
2286
+ if (this.listenOpen && !this.talking && !this.segmenter.active) {
2287
+ this.listenOpen = false;
2288
+ this.partial = '';
2289
+ this.server.sendPet({ t: 'listen', phase: 'none' });
2290
+ }
2291
+ }
2292
+ if (text) {
2293
+ this.committing = false;
2294
+ this.partial = '';
2295
+ this.listenOpen = false;
2296
+ this.counts.delivered++;
2297
+ this.server.sendPet({ t: 'listen', phase: 'heard', text });
2298
+ // speech through the talk key stops the round; always listening also hears a TV or other people, so it only wakes
2299
+ const trigger = this.cfg.asr.mic.mode === 'always' ? 'flush' : 'interrupt';
2300
+ const transcript = this.cfg.asr.recording.transcript;
2301
+ const blobs = this.recording(transcript);
2302
+ // the recognized text is left out only while the recording goes in its place
2303
+ const heard = blobs.length && !transcript ? this.t.heardRecorded(this.userName) : this.t.heard(this.userName, text);
2304
+ void this.push('agent-speed.speech', 'agent-speed.voice', heard, trigger, { meta: { text }, ...(blobs.length ? { blobs } : {}) });
2305
+ return;
2306
+ }
2307
+ if (this.segmenter.active || upstream) this.listenOpen = true;
2308
+ else if (!hold && !this.packer.pending && this.listenOpen && !this.talking) {
2309
+ // the episode ended with nothing worth delivering; an open talk key keeps it going
2310
+ this.listenOpen = false;
2311
+ this.partial = '';
2312
+ this.server.sendPet({ t: 'listen', phase: 'none' });
2313
+ }
2314
+ if (this.packer.pending && !this.packTimer) {
2315
+ this.packTimer = setTimeout(() => { this.packTimer = null; this.schedulePack(); }, Math.max(50, this.segmenter.settleRemainingMs || 100));
2316
+ }
2317
+ }
2318
+
2319
+ /** A listening episode is open on the page (bubble shown) and has not been closed yet. */
2320
+ private listenOpen = false;
2321
+
2322
+ private remember(line: HeardLine): void {
2323
+ this.heard.push(line);
2324
+ if (this.heard.length > 50) this.heard.shift();
2325
+ }
2326
+
2327
+ private voiceFrame(frame: Record<string, unknown>): void {
2328
+ const text = JSON.stringify(frame);
2329
+ for (const s of this.voiceSockets) if (s.open) s.send(text);
2330
+ }
2331
+
2332
+ /* ---------- tools ---------- */
2333
+
2334
+ tools(): ToolDef[] {
2335
+ const handlers: Record<string, ToolDef['handler']> = {
2336
+ speed_pet_say: (args) => this.say(args),
2337
+ speed_pet_ask: (args) => this.askUser(args),
2338
+ speed_pet_move_to: (args, ctx) => this.moveTo(args, ctx),
2339
+ speed_pet_act: (args) => this.act(args),
2340
+ speed_pet_see_self: () => this.seeSelf(),
2341
+ speed_pet_set: (args) => this.setSettings(args),
2342
+ speed_pet_quiet: (args) => this.setQuiet(args),
2343
+ speed_pet_cua_open_settings: async () => this.openCuaSettings(),
2344
+ };
2345
+ const own = petToolDecls(this.appLanguage).map((decl) => ({ ...decl, handler: handlers[decl.name], ...(decl.name === 'speed_pet_move_to' ? { interruptible: true } : {}) }));
2346
+ if (this.cuaOn) return [...own, ...this.cua.tools()];
2347
+ return this.cuaCanOpen ? [...own, ...CUA_OFF_TOOL_DECLS.map((decl) => ({ ...decl, handler: handlers[decl.name] }))] : own;
2348
+ }
2349
+
2350
+ private notConnected(tool: string): ToolOutcome {
2351
+ const w = this.windowHost?.state();
2352
+ const detail = w && w.phase !== 'running' && w.reason ? describeHostReason(this.t.window, w.reason) : null;
2353
+ return { text: this.t.notConnected(tool, detail, this.userName), failed: true };
2354
+ }
2355
+
2356
+ private async say(args: Record<string, unknown>): Promise<ToolOutcome> {
2357
+ const script = typeof args.script === 'string' ? args.script : '';
2358
+ const shown = this.shownImages(args.images);
2359
+ if (!shown.ok) return { text: shown.reason, failed: true };
2360
+ const { beats, dropped } = parseScript(script, this.vocab());
2361
+ const spoken = beats.some((b) => b.text || b.actions.length || b.anchors.length);
2362
+ if (!spoken && shown.blobs.length === 0) return { text: this.t.sayEmpty, failed: true };
2363
+ const id = nextId('s');
2364
+ if (spoken && !this.server.sendPet({ t: 'say', id, beats })) return this.notConnected('speed_pet_say');
2365
+ void this.closeActivity();
2366
+ void this.record({ kind: 'say', beats: beats.map((b) => ({ text: b.text, ...moodOf(b.actions, this.vocab()) })) }, beats.map((b) => b.text).join(''), shown.blobs);
2367
+ if (!spoken) return { text: this.t.imagesShown(shown.blobs.length, this.chat.size > 0) };
2368
+ const now = Date.now();
2369
+ const selfSec = estimateSeconds(beats, this.cfg.window.bubbleSpeed, this.cfg.speech.enabled ? speechTextSteps : undefined, this.cfg.window.sayBubbleHoldSec);
2370
+ this.sayEnds = this.sayEnds.filter((l) => l.at > now);
2371
+ const free = this.sayEnds.at(-1)?.at ?? now;
2372
+ const waitSec = (free - now) / 1000;
2373
+ this.sayEnds.push({ id, at: free + selfSec * 1000 });
2374
+ const replaced = this.ask?.question ?? null;
2375
+ if (this.ask) this.setAsk(null);
2376
+ return { text: this.t.sayReceipt({ waitSec, selfSec, chatOpen: this.chat.size > 0, replaced, dropped, images: shown.blobs.length }) };
2377
+ }
2378
+
2379
+ /**
2380
+ * The images of a `speed_pet_say`: each handle is read through the host and attached again as bytes,
2381
+ * so the stored line keeps the picture it showed after a Memory file changes.
2382
+ */
2383
+ private shownImages(raw: unknown): { ok: true; blobs: BlobInput[] } | { ok: false; reason: string } {
2384
+ if (raw === undefined) return { ok: true, blobs: [] };
2385
+ if (!Array.isArray(raw) || raw.some((h) => typeof h !== 'string')) return { ok: false, reason: this.t.imagesNotHandles };
2386
+ if (raw.length > IMAGES_MAX) return { ok: false, reason: this.t.tooManyImages(IMAGES_MAX) };
2387
+ const blobs: BlobInput[] = [];
2388
+ for (const [i, handle] of (raw as string[]).entries()) {
2389
+ const got = this.host?.blob(handle);
2390
+ if (!got) return { ok: false, reason: this.t.imageMissing(handle) };
2391
+ if (!got.mime.startsWith('image/')) return { ok: false, reason: this.t.imageNotImage(handle, got.mime) };
2392
+ blobs.push({ bytes: got.bytes, mime: got.mime, fallbackText: this.t.shownImage(i + 1, raw.length) });
2393
+ }
2394
+ return { ok: true, blobs };
2395
+ }
2396
+
2397
+ private async askUser(args: Record<string, unknown>): Promise<ToolOutcome> {
2398
+ const question = typeof args.question === 'string' ? args.question.trim() : '';
2399
+ const raw = Array.isArray(args.options) ? args.options : [];
2400
+ const optionMax = capFor(ASK_OPTION_MAX, this.appLanguage);
2401
+ const options = raw.filter((o): o is string => typeof o === 'string' && o.trim() !== '').map((o) => cutChars(o.trim(), optionMax)).slice(0, 3);
2402
+ const allowOwn = args.allowOwnAnswer !== false;
2403
+ if (!question) return { text: this.t.askEmpty, failed: true };
2404
+ if (options.length === 0 && !allowOwn) return { text: this.t.askNoWay, failed: true };
2405
+ const id = nextId('a');
2406
+ if (!this.server.sendPet({ t: 'ask', id, question, options, own: allowOwn })) return this.notConnected('speed_pet_ask');
2407
+ const replaced = this.ask?.question ?? null;
2408
+ this.setAsk({ id, question, options });
2409
+ void this.closeActivity();
2410
+ void this.record({ kind: 'ask', askId: id, question, options, own: allowOwn }, question);
2411
+ return { text: this.t.askReceipt({ replaced, cut: raw.length > 3, chatOpen: this.chat.size > 0 }) };
2412
+ }
2413
+
2414
+ /**
2415
+ * Interruptible: an interrupt stops the walk or the move where the pet stands, and the receipt says where.
2416
+ * A default target is walked to by the page; a target of the figure's own goes to its body as the call gave it
2417
+ * once its params check out against the pack's declaration (moves.ts). The body reports either way.
2418
+ */
2419
+ private async moveTo(args: Record<string, unknown>, ctx?: ToolCallContext): Promise<ToolOutcome> {
2420
+ const { language, t } = this;
2421
+ const pack = this.currentPack();
2422
+ const order = readMove(args, this.moves());
2423
+ if (order.kind === 'noTarget') return { text: t.moveNoTarget, failed: true };
2424
+ if (order.kind === 'badTarget') return { text: t.moveBadTarget(order.got, this.moves().map((m) => m.id)), failed: true };
2425
+ if (order.kind === 'badParams') return { text: t.moveBadParams(order.target?.id ?? null, order.target?.params.map((p) => `${p.id} ${p.min}–${p.max}`) ?? [], order.got), failed: true };
2426
+ if (order.kind === 'walk' && pack?.manifest.can.walk === false) return { text: t.walkCannot(modelName(pack.manifest.name, pack.id, language)), failed: true };
2427
+ const walkId = nextId('w');
2428
+ const sent = order.kind === 'walk' ? this.server.sendPet({ t: 'walk', id: walkId, to: order.to, run: order.run })
2429
+ : this.server.sendPet({ t: 'move', id: walkId, move: { to: order.to, run: order.run, params: order.params } });
2430
+ if (!sent) return this.notConnected('speed_pet_move_to');
2431
+ const target = order.kind === 'move' ? modelName(order.target.name, order.target.id, language) : undefined;
2432
+ const text = await new Promise<string>((resolve) => {
2433
+ const onAbort = (): void => {
2434
+ if (!this.walks.has(walkId)) return;
2435
+ walk.stopping = true;
2436
+ this.server.sendPet({ t: 'walk-stop', id: walkId });
2437
+ };
2438
+ const done = (s: string): void => {
2439
+ ctx?.signal?.removeEventListener('abort', onAbort);
2440
+ resolve(s);
2441
+ };
2442
+ const timer = setTimeout(() => {
2443
+ this.walks.delete(walkId);
2444
+ done(target === undefined ? t.walkTimeout(WALK_TIMEOUT_MS / 1000) : t.moveTimeout(target, WALK_TIMEOUT_MS / 1000));
2445
+ }, WALK_TIMEOUT_MS);
2446
+ const walk: PendingWalk = { resolve: done, timer, ...(target === undefined ? {} : { target }) };
2447
+ this.walks.set(walkId, walk);
2448
+ ctx?.signal?.addEventListener('abort', onAbort, { once: true });
2449
+ });
2450
+ return { text };
2451
+ }
2452
+
2453
+ private async setSettings(args: Record<string, unknown>): Promise<ToolOutcome> {
2454
+ const t = this.t;
2455
+ if (selfAdjustMode(this.cfg.selfAdjust) === 'off') return { text: t.selfAdjustOff('speed_pet_set', this.userName), failed: true };
2456
+ const packs = this.packs();
2457
+ const plan = (a: Record<string, unknown>) => planSettings(a, { ...this.cfg, user: this.userName }, packs, this.language, capFor(USER_MAX, this.appLanguage), this.appLanguage);
2458
+ const { changes, errors } = plan(args);
2459
+ if (errors.length) return { text: t.setErrors(errors), failed: true };
2460
+ if (!changes.length) return { text: t.setNothing };
2461
+ const lines: string[] = [];
2462
+ /** Applies `list`; when a figure put on takes back the size it last had, that change is said too. */
2463
+ const apply = (list: SettingChange[]): string[] => {
2464
+ this.followFigure();
2465
+ const before = this.cfg.window.scale;
2466
+ const given = list.some((c) => c.key === 'scale') || scaleOf(args.scale) === before;
2467
+ for (const c of list) this.opts.persist(c.patch);
2468
+ this.followFigure(given);
2469
+ const skin = this.cfg.skin;
2470
+ if (list.some((c) => c.key === 'figure' || c.key === 'scheme')) this.botLook = (skin.figure ?? COO) === COO ? COO : `${skin.figure}:${skin.scheme ?? ''}`;
2471
+ this.syncPrefs();
2472
+ this.opts.onBotChange?.();
2473
+ const after = this.cfg.window.scale;
2474
+ return !given && after !== before ? [sayScale(before, after, this.language)] : [];
2475
+ };
2476
+ const says = (list: SettingChange[]) => list.map((c) => c.say);
2477
+ const mine = changes.filter((c) => c.tier === 'self');
2478
+ if (mine.length) { const also = apply(mine); lines.push(t.setDone([...says(mine), ...also])); }
2479
+ // a figure put on above may have taken back its own size: a size still to be asked for is measured from the one on screen now
2480
+ const asked = changes.filter((c) => c.tier === 'ask').flatMap((c) => (c.key === 'scale' && mine.length ? plan({ scale: args.scale }).changes : [c]));
2481
+ if (asked.length) {
2482
+ const c = this.ui.consent;
2483
+ const answer = await this.confirm(c.question(asked.map((x) => x.show)), c.choices);
2484
+ if (answer === 'always') {
2485
+ // these items stop being asked: the rest stay as they were, under `custom`; told to the app with the changes as the bot's own
2486
+ const keys = [...new Set(asked.map((x) => x.key))];
2487
+ this.opts.persist({ selfAdjust: 'custom', selfAdjustCustom: { ...directSettings(this.cfg), ...Object.fromEntries(keys.map((k) => [k, true])) } });
2488
+ const also = apply(asked);
2489
+ lines.push(t.setAlways(this.userName, [...says(asked), ...also], keys.map((k) => t.settingNames[k])));
2490
+ } else if (answer === 'yes') { const also = apply(asked); lines.push(t.setAgreed(this.userName, [...says(asked), ...also])); }
2491
+ else lines.push(t.setNotChanged(answer === 'unavailable' || answer === 'timeout' ? answer : 'no', this.userName, says(asked)));
2492
+ }
2493
+ if (mine.some((c) => c.key === 'figure' || c.key === 'scheme')) {
2494
+ lines.push(t.lookNow(this.bodyText(this.currentPack())));
2495
+ const note = this.vocabNote();
2496
+ if (note) lines.push(note);
2497
+ }
2498
+ return { text: lines.join('\n') };
2499
+ }
2500
+
2501
+ private async setQuiet(args: Record<string, unknown>): Promise<ToolOutcome> {
2502
+ const t = this.t;
2503
+ const minutes = args.minutes;
2504
+ if (typeof minutes !== 'number' || !(minutes >= 0) || minutes > QUIET_MAX_MIN) return { text: t.quietBad(QUIET_MAX_MIN), failed: true };
2505
+ if (minutes === 0) {
2506
+ if (!this.quiet) return { text: t.quietNone };
2507
+ this.endQuiet();
2508
+ return { text: t.quietEnded };
2509
+ }
2510
+ if (selfAdjustMode(this.cfg.selfAdjust) === 'off') return { text: t.selfAdjustOff('speed_pet_quiet', this.userName), failed: true };
2511
+ const sound = args.sound === true;
2512
+ const roam = args.roam === 'calm' ? 'calm' : 'off';
2513
+ const base = this.quiet?.base ?? { sound: this.cfg.sound, roam: this.cfg.roam };
2514
+ if (this.quiet) clearTimeout(this.quiet.timer);
2515
+ const until = Date.now() + minutes * 60_000;
2516
+ this.quiet = { sound, roam, until, base, timer: setTimeout(() => this.endQuiet(), minutes * 60_000) };
2517
+ this.syncPrefs();
2518
+ return { text: t.quietUntil(shortTime(this.opts.timezone, new Date(until)), sound, roam) };
2519
+ }
2520
+
2521
+ private endQuiet(): void {
2522
+ if (!this.quiet) return;
2523
+ clearTimeout(this.quiet.timer);
2524
+ this.quiet = null;
2525
+ this.syncPrefs();
2526
+ }
2527
+
2528
+ private async act(args: Record<string, unknown>): Promise<ToolOutcome> {
2529
+ const list = Array.isArray(args.actions) ? args.actions : typeof args.actions === 'string' ? [args.actions] : [];
2530
+ const vocab = this.fireworksOffered ? [...this.vocab(), FIREWORKS] : this.vocab();
2531
+ const { actions, dropped } = parseActions(list, vocab);
2532
+ if (!actions.length) return { text: this.t.actNone(dropped), failed: true };
2533
+ if (!this.server.sendPet({ t: 'act', id: nextId('c'), actions })) return this.notConnected('speed_pet_act');
2534
+ if (actions.includes(FIREWORKS.id)) this.fireworksOffered = false;
2535
+ const lasting = actions.filter((a) => vocab.find((v) => v.id === a)?.lasting);
2536
+ return { text: this.t.actReceipt(actions, lasting, dropped) };
2537
+ }
2538
+
2539
+ /**
2540
+ * The picture is the pet window's: the page names the body's room and the window process copies it from what it
2541
+ * draws (host/portrait.cjs). A browser tab has no such window and is not asked.
2542
+ */
2543
+ private async seeSelf(): Promise<ToolOutcome> {
2544
+ const t = this.t;
2545
+ if (!this.server.petConnected) return this.notConnected('speed_pet_see_self');
2546
+ const id = nextId('p');
2547
+ const portrait = !this.server.petInWindow ? 'tab' : await new Promise<Portrait>((resolve) => {
2548
+ const done = (p: Portrait): void => {
2549
+ clearTimeout(timer);
2550
+ this.portraits.delete(id);
2551
+ resolve(p);
2552
+ };
2553
+ const timer = setTimeout(() => done('timeout'), PORTRAIT_TIMEOUT_MS);
2554
+ this.portraits.set(id, done);
2555
+ this.server.sendPet({ t: 'portrait', id });
2556
+ });
2557
+ if (typeof portrait === 'string') return { text: t.selfNot(portrait, PORTRAIT_TIMEOUT_MS / 1000), failed: true };
2558
+ const { png, width, height } = portrait;
2559
+ return {
2560
+ text: t.selfSeen(width, height, this.bodyText(this.currentPack())),
2561
+ blobs: [{ bytes: png, mime: 'image/png', name: 'self.png', fallbackText: t.selfFallback(width, height) }],
2562
+ };
2563
+ }
2564
+
2565
+ /* ---------- prompt ---------- */
2566
+
2567
+ async envPromptVars(): Promise<Record<string, string>> {
2568
+ const { language, t } = this;
2569
+ const user = this.userName;
2570
+ const reply = this.opts.replyLanguage?.() ?? null;
2571
+ return {
2572
+ 'pet.cua': this.cuaOn ? await this.cua.envPrompt() : this.cua.unsupported() === null ? t.cuaOff(user, this.cuaCanOpen) : '',
2573
+ 'pet.user': user,
2574
+ 'pet.vocab': vocabTable(this.vocab(), language),
2575
+ 'pet.moves': moveTable(this.moves(), language),
2576
+ 'pet.voice': this.cfg.asr.enabled ? t.on : t.off,
2577
+ 'pet.body': this.bodyText(this.currentPack()),
2578
+ 'pet.dress': dressTable(this.packs(), language),
2579
+ 'pet.self': this.selfText(),
2580
+ 'pet.chat': this.opts.controls?.openChat ? t.chatPage(user) : '',
2581
+ 'pet.reply': reply ? t.reply(user, reply) : '',
2582
+ };
2583
+ }
2584
+
2585
+ /** `{{pet.self}}`: which `speed_pet_set` items change at once and which are asked first, or that none can change. */
2586
+ private selfText(): string {
2587
+ const t = this.t;
2588
+ if (selfAdjustMode(this.cfg.selfAdjust) === 'off') return t.selfNone(this.userName);
2589
+ const direct = directSettings(this.cfg);
2590
+ return t.selfTiers(this.userName, SELF_KEYS.filter((k) => direct[k]).map((k) => t.settingNames[k]), SELF_KEYS.filter((k) => !direct[k]).map((k) => t.settingNames[k]));
2591
+ }
2592
+
2593
+ /** The environment prompt template of the model-text language. */
2594
+ private envPromptFile(): string {
2595
+ const file = ENV_PROMPT_FILES[this.language];
2596
+ return existsSync(file) ? file : ENV_PROMPT_FILES.zh;
2597
+ }
2598
+
2599
+ /* ---------- WebUI ---------- */
2600
+
2601
+ webUi(language: Language = 'zh'): WorldWebUiDecl {
2602
+ const w = this.windowHost?.state();
2603
+ const v = this.backendState();
2604
+ const c = petText(language).console;
2605
+ // the lamp is the window's: a browser page standing in for it is only mentioned
2606
+ const inWindow = this.server.petInWindow;
2607
+ const hint = w?.reason ? describeHostReason(petText(language).windowReason, w.reason) : c.notOpen;
2608
+ const lamps: WorldLamp[] = [
2609
+ { label: 'Agent Speed', state: this.agentSpeedSnapshot === null ? 'offline' : 'online' },
2610
+ {
2611
+ label: c.window,
2612
+ state: inWindow ? (this.bodyMissing === null ? 'online' : 'error') : w?.phase === 'running' ? 'loading' : w?.phase === 'missing' || w?.phase === 'error' ? 'error' : 'offline',
2613
+ hint: inWindow ? (this.bodyMissing === null ? c.connected : c.noBody(this.bodyMissing)) : this.server.petConnected ? c.alsoBrowser(hint) : hint,
2614
+ },
2615
+ {
2616
+ label: c.voice,
2617
+ state: !this.cfg.asr.enabled ? 'offline' : this.micWanted() ? 'online' : v?.phase === 'starting' ? 'loading' : v?.phase === 'error' ? 'error' : 'offline',
2618
+ hint: v?.detail ?? v?.phase ?? c.notStarted,
2619
+ },
2620
+ ...(this.cfg.cua.enabled ? [this.cua.lamp(language)] : []),
2621
+ ];
2622
+ return {
2623
+ label: 'Agent Speed',
2624
+ lamps,
2625
+ panels: desktopPetPanelDecls(language),
2626
+ invoke: (panel, method, args) => this.invoke(panel, method, args, language),
2627
+ stream: (panel, socket) => {
2628
+ // `chat` has no panel: the embedding app draws its chat page from this stream
2629
+ if (panel === 'chat') { this.chat.add(socket, (msg, s) => void this.onChat(msg, s, language)); return; }
2630
+ if (panel !== 'voice') { socket.close('no stream'); return; }
2631
+ this.voiceSockets.add(socket);
2632
+ socket.onClose(() => this.voiceSockets.delete(socket));
2633
+ },
2634
+ links: this.server.port ? [{ label: c.viewInBrowser, href: this.petUrl }, { label: c.dress, href: `${this.server.origin}/dress` }] : [],
2635
+ config: desktopPetConfigGroups(language),
2636
+ promptDocs: [{
2637
+ key: `worlds.${DESKTOP_PET_ID}.envPrompt`,
2638
+ ...c.envPrompt,
2639
+ path: this.envPromptFile(),
2640
+ role: 'envPrompt',
2641
+ vars: ['pet.user', 'pet.vocab', 'pet.moves', 'pet.voice', 'pet.body', 'pet.dress', 'pet.self', 'pet.chat', 'pet.reply', 'pet.cua']
2642
+ .map((name) => ({ name, description: c.vars[name] ?? name, ...(name === 'pet.vocab' || name === 'pet.moves' || name === 'pet.dress' || name === 'pet.cua' ? { multiline: true } : {}) })),
2643
+ }],
2644
+ };
2645
+ }
2646
+
2647
+ /** A settings client needs option ids, even when the stored scheme names a preset. */
2648
+ private dressState(language: Language, packs = this.packs()) {
2649
+ const skin = this.cfg.skin;
2650
+ const pack = packFor(packs, skin.figure);
2651
+ const scheme = pack ? lookOf(pack, skin) : '';
2652
+ const parts = scheme.split('-');
2653
+ const preset = pack?.id === COO ? undefined : pack?.manifest.presets.find((p) => p.id === scheme);
2654
+ return {
2655
+ skin: pack ? {
2656
+ figure: pack.id,
2657
+ scheme: pack.manifest.axes.map((a, i) => {
2658
+ const pick = preset ? preset.pick[a.id] : parts[i];
2659
+ return a.options.find((o) => o.id === pick)?.id ?? a.options[0]!.id;
2660
+ }).join('-'),
2661
+ } : {},
2662
+ scale: this.cfg.window.scale,
2663
+ packs: packs.map(({ id, manifest }) => ({
2664
+ id, name: nameIn(manifest.name, language),
2665
+ axes: manifest.axes.map((a) => ({
2666
+ id: a.id, label: nameIn(a.name, language),
2667
+ options: a.options.map((o) => ({ id: o.id, label: nameIn(o.name, language) })),
2668
+ })),
2669
+ })),
2670
+ importable: !!this.dressImport,
2671
+ };
2672
+ }
2673
+
2674
+ private saveDress(raw: unknown, language: Language) {
2675
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)
2676
+ || Object.keys(raw).some((key) => key !== 'figure' && key !== 'scheme' && key !== 'scale')) {
2677
+ throw new Error('Invalid dress settings');
2678
+ }
2679
+ const patch = raw as Record<string, unknown>;
2680
+ const t = petText(language);
2681
+ const scale = scaleOf(patch.scale);
2682
+ if (Object.hasOwn(patch, 'scale') && scale === null) throw new Error('Invalid dress scale');
2683
+ const packs = this.packs();
2684
+ const hasFigure = Object.hasOwn(patch, 'figure'), hasScheme = Object.hasOwn(patch, 'scheme');
2685
+ if (hasFigure || hasScheme) {
2686
+ const current = this.cfg.skin.figure ?? COO;
2687
+ const figure = hasFigure ? patch.figure : current;
2688
+ const pack = packs.find((p) => p.id === figure);
2689
+ if (!pack) throw new Error(t.packs.badId(JSON.stringify(figure) ?? ''));
2690
+ const { axes, presets } = pack.manifest;
2691
+ let scheme: string | undefined;
2692
+ if (hasScheme) {
2693
+ const want = patch.scheme;
2694
+ if (typeof want !== 'string') throw new Error(t.packs.badPreset(JSON.stringify(want) ?? ''));
2695
+ const parts = want === '' ? [] : want.split('-');
2696
+ const picksAxes = axes.length === parts.length && axes.every((a, i) => a.options.some((o) => o.id === parts[i]));
2697
+ if (!picksAxes && !presets.some((p) => p.id === want)) throw new Error(t.packs.badPreset(JSON.stringify(want)));
2698
+ // Preserve a matching preset's styling, rather than saving only its equivalent axis combination.
2699
+ if (picksAxes && pack.id !== COO) {
2700
+ for (const p of presets) {
2701
+ if (!axes.every((a, i) => p.pick[a.id] === parts[i])) continue;
2702
+ scheme ??= p.id;
2703
+ if (figure === current && p.id === this.cfg.skin.scheme) { scheme = p.id; break; }
2704
+ }
2705
+ }
2706
+ scheme ??= want;
2707
+ } else if (pack.id !== current && pack.id !== COO) {
2708
+ scheme = presets[0]?.id ?? axes.map((a) => a.options[0]!.id).join('-');
2709
+ }
2710
+ this.saveSkin({ ...this.cfg.skin, figure: pack.id, ...(scheme === undefined ? {} : lookPatch(pack, scheme)) }, scale);
2711
+ } else if (scale !== null) {
2712
+ this.savePrefs({ scale });
2713
+ }
2714
+ return this.dressState(language, packs);
2715
+ }
2716
+
2717
+ private requireDressImport(language: Language): DressZipImport {
2718
+ if (!this.dressImport) throw new Error(petText(language).importing.expired);
2719
+ return this.dressImport;
2720
+ }
2721
+
2722
+ private async invoke(panel: string, method: string, args: unknown[], language: Language = this.appLanguage): Promise<unknown> {
2723
+ if (panel === 'pet') {
2724
+ switch (method) {
2725
+ case 'state': return this.petState();
2726
+ case 'dressState': return this.dressState(language);
2727
+ case 'dressSave': return this.saveDress(args[0], language);
2728
+ case 'dressImportStart': return this.requireDressImport(language).start(args[0], petText(language));
2729
+ case 'dressImportChunk': this.requireDressImport(language).chunk(args[0], args[1], petText(language)); return { ok: true };
2730
+ case 'dressImportFinish': return this.requireDressImport(language).finish(args[0], petText(language));
2731
+ case 'dressImportInstall': return this.requireDressImport(language).install(args[0], args[1], args[2], petText(language));
2732
+ case 'dressImportCancel':
2733
+ if (typeof args[0] === 'string') await this.dressImport?.cancel(args[0]);
2734
+ return { ok: true };
2735
+ case 'openWindow': this.openWindow(); return this.petState();
2736
+ case 'closeWindow': await this.windowHost?.stop(); return this.petState();
2737
+ // hides the window as the pet's menu does; it stays connected and comes back with openWindow
2738
+ case 'hideWindow': this.server.sendPet({ t: 'hide' }); return this.petState();
2739
+ // the tray's "click through": kept for this run only, and sent again to a window that reconnects
2740
+ case 'setClickThrough': this.setClickThrough(args[0] === true); return this.petState();
2741
+ case 'installElectron': void this.store.electron.install(); return this.petState();
2742
+ // the Habits page's custom picks (/api/config writes no list or map): `custom` and its picks in one write, as the person's change
2743
+ case 'setWakeKinds': {
2744
+ const picked = Array.isArray(args[0]) ? args[0] as unknown[] : [];
2745
+ this.opts.persist({ touch: { wakeOn: 'custom', wakeKinds: TOUCH_KINDS.filter((k) => picked.includes(k)) } });
2746
+ return this.petState();
2747
+ }
2748
+ case 'setSelfAdjustCustom': {
2749
+ const raw = args[0] && typeof args[0] === 'object' ? args[0] as Record<string, unknown> : {};
2750
+ const custom = this.selfCustom();
2751
+ for (const k of SELF_KEYS) if (typeof raw[k] === 'boolean') custom[k] = raw[k] as boolean;
2752
+ this.opts.persist({ selfAdjust: 'custom', selfAdjustCustom: custom });
2753
+ return this.petState();
2754
+ }
2755
+ // the typing key, as the talk key is set through setMic: on or off, and a key `parseHotkey` reads
2756
+ case 'setTypeKey': {
2757
+ const raw = args[0] && typeof args[0] === 'object' ? args[0] as Record<string, unknown> : {};
2758
+ const typeKey: { enabled?: boolean; hotkey?: string } = {};
2759
+ if (typeof raw.enabled === 'boolean') typeKey.enabled = raw.enabled;
2760
+ if (typeof raw.hotkey === 'string' && parseHotkey(raw.hotkey)) typeKey.hotkey = raw.hotkey;
2761
+ this.opts.persist({ typeKey });
2762
+ await this.syncTypeKey();
2763
+ // the talk key's trigger depends on the typing key
2764
+ await this.syncHotkey();
2765
+ return this.petState();
2766
+ }
2767
+ // the click-through pause key, set as the typing key is
2768
+ case 'setThroughPauseKey': {
2769
+ const raw = args[0] && typeof args[0] === 'object' ? args[0] as Record<string, unknown> : {};
2770
+ const throughPauseKey: { enabled?: boolean; hotkey?: string } = {};
2771
+ if (typeof raw.enabled === 'boolean') throughPauseKey.enabled = raw.enabled;
2772
+ if (typeof raw.hotkey === 'string' && parseHotkey(raw.hotkey)) throughPauseKey.hotkey = raw.hotkey;
2773
+ this.opts.persist({ throughPauseKey });
2774
+ await this.syncThroughPauseKey();
2775
+ return this.petState();
2776
+ }
2777
+ case 'guide': {
2778
+ if (!this.opts.controls?.guide) throw new Error(this.ui.console.noGuide);
2779
+ this.opts.controls.guide();
2780
+ return this.petState();
2781
+ }
2782
+ }
2783
+ }
2784
+ if (panel === 'voice') {
2785
+ switch (method) {
2786
+ case 'state': return this.voiceState();
2787
+ case 'install': void this.installVoice(); return this.voiceState();
2788
+ case 'start':
2789
+ this.opts.persist({ asr: { serviceEnabled: true } });
2790
+ await this.startVoiceBackend();
2791
+ return this.voiceState();
2792
+ case 'stop':
2793
+ this.opts.persist({ asr: { serviceEnabled: false } });
2794
+ await this.stopVoiceBackend();
2795
+ return this.voiceState();
2796
+ case 'setEngine': {
2797
+ const engine = args[0];
2798
+ if (engine === 'funasr' || engine === 'whisper' || engine === 'system' || engine === 'api') this.opts.persist({ asr: { engine } });
2799
+ if (this.recognitionWanted()) await this.startVoiceBackend();
2800
+ return this.voiceState();
2801
+ }
2802
+ // the transcription service: address and model go to the config, the API Key to the deployment's secrets
2803
+ case 'setApi': {
2804
+ const raw = args[0] && typeof args[0] === 'object' ? args[0] as Record<string, unknown> : {};
2805
+ const api: { baseUrl?: string; model?: string } = {};
2806
+ if (typeof raw.baseUrl === 'string') api.baseUrl = raw.baseUrl.trim();
2807
+ if (typeof raw.model === 'string') api.model = raw.model.trim();
2808
+ if (Object.keys(api).length) this.opts.persist({ asr: { api } });
2809
+ if (typeof raw.key === 'string' && raw.key.trim()) this.opts.storeAsrApiKey?.(raw.key.trim());
2810
+ if (this.recognitionWanted() && this.engine() === 'api') await this.startVoiceBackend();
2811
+ return this.voiceState();
2812
+ }
2813
+ case 'setEnabled': this.savePrefs({ mic: args[0] === true }); return this.voiceState();
2814
+ case 'setMic': {
2815
+ this.savePrefs({ micSettings: args[0] });
2816
+ await this.syncHotkey();
2817
+ return this.voiceState();
2818
+ }
2819
+ case 'setRecording': {
2820
+ const raw = args[0] && typeof args[0] === 'object' ? args[0] as Record<string, unknown> : {};
2821
+ const recording: Partial<DesktopPetConfigSection['asr']['recording']> = {};
2822
+ if (typeof raw.enabled === 'boolean') recording.enabled = raw.enabled;
2823
+ if (typeof raw.transcript === 'boolean') recording.transcript = raw.transcript;
2824
+ if (Number.isInteger(raw.maxMinutes)) recording.maxMinutes = Math.max(RECORDING_MINUTES_MIN, Math.min(RECORDING_MINUTES_MAX, raw.maxMinutes as number));
2825
+ if (Object.keys(recording).length) this.opts.persist({ asr: { recording } });
2826
+ return this.voiceState();
2827
+ }
2828
+ // the meter's mark; the segmenter reads the live section, so the next frame is measured against it
2829
+ case 'setThreshold': {
2830
+ const db = args[0];
2831
+ if (typeof db === 'number' && Number.isFinite(db)) this.opts.persist({ asr: { segment: { thresholdDb: Math.max(THRESHOLD_DB_MIN, Math.min(THRESHOLD_DB_MAX, db)) } } });
2832
+ return this.voiceState();
2833
+ }
2834
+ }
2835
+ }
2836
+ throw new Error(this.ui.console.unknownMethod(`${panel}.${method}`));
2837
+ }
2838
+
2839
+ /** Downloads the model of `modelEngine()`, chooses that engine, and starts it when voice input is on. */
2840
+ async installVoice(): Promise<void> {
2841
+ const engine = this.modelEngine();
2842
+ const slot = this.store[engine];
2843
+ if (slot.state().phase !== 'ready') await slot.install();
2844
+ if (slot.state().phase !== 'ready') { this.syncPrefs(); return; }
2845
+ // downloading the model is choosing it
2846
+ if (this.engine() !== engine) this.opts.persist({ asr: { engine } });
2847
+ if (this.recognitionWanted()) await this.startVoiceBackend();
2848
+ else this.syncPrefs();
2849
+ }
2850
+
2851
+ petState(): Record<string, unknown> {
2852
+ return {
2853
+ connected: this.server.petConnected,
2854
+ clickThrough: this.clickThrough,
2855
+ /** The connected pet page is the window's, not a browser page standing in for it. */
2856
+ inWindow: this.server.petInWindow,
2857
+ /** The pet window is connected and shown (hidden from its menu or the tray, it stays connected). */
2858
+ onDesktop: this.server.petInWindow && !this.petHidden,
2859
+ url: this.server.port ? this.petUrl : null,
2860
+ dressUrl: this.server.port ? `${this.server.origin}/dress` : null,
2861
+ /** The OBS overlay page while `window.exportOverlay` is on. */
2862
+ overlayUrl: this.server.port && this.cfg.window.exportOverlay ? `${this.server.origin}/overlay` : null,
2863
+ skin: this.cfg.skin,
2864
+ /** What the person is called while `user` is empty, in the app language. */
2865
+ defaultUser: this.ui.defaultUser,
2866
+ window: this.windowHost?.state() ?? null,
2867
+ electron: { ...this.store.electron.state(), supported: this.store.electron.supported },
2868
+ screen: this.screen,
2869
+ /** The Habits page's two rows, legacy values read as they now mean. */
2870
+ wake: { wakeOn: this.cfg.touch.wakeOn, wakeKinds: this.cfg.touch.wakeKinds },
2871
+ selfAdjust: { mode: selfAdjustMode(this.cfg.selfAdjust), custom: this.selfCustom() },
2872
+ /** The Habits page's typing key: the setting, the keys named in the app language, and why it cannot be read. */
2873
+ typeKey: { ...this.cfg.typeKey, keyLabel: comboLabel(this.cfg.typeKey.hotkey, process.platform, this.ui), problem: this.typeKeyProblem },
2874
+ /** The Habits page's click-through pause key, as `typeKey`. */
2875
+ throughPauseKey: {
2876
+ ...this.cfg.throughPauseKey, keyLabel: comboLabel(this.cfg.throughPauseKey.hotkey, process.platform, this.ui),
2877
+ problem: this.throughPauseKeyProblem ?? (this.throughPauseSharesTalk() ? this.ui.throughPauseKey.sharesTalk : null),
2878
+ },
2879
+ };
2880
+ }
2881
+
2882
+ /** `selfAdjustCustom` with every item, the default's for one missing. */
2883
+ private selfCustom(): Record<SelfKey, boolean> {
2884
+ return directSettings({ selfAdjust: 'custom', selfAdjustCustom: this.cfg.selfAdjustCustom });
2885
+ }
2886
+
2887
+ voiceState(): Record<string, unknown> {
2888
+ const modelEngine = this.modelEngine();
2889
+ const model = this.store[modelEngine];
2890
+ return {
2891
+ enabled: this.cfg.asr.enabled,
2892
+ serviceEnabled: this.cfg.asr.serviceEnabled !== false,
2893
+ engine: this.engine(),
2894
+ engineSetting: this.cfg.asr.engine,
2895
+ systemSupported: systemRecognizerSupported(),
2896
+ server: this.backendState(),
2897
+ model: { ...model.state(), bytes: model.bytes, engine: modelEngine },
2898
+ /** The transcription service's settings; of the API Key only whether one is saved. */
2899
+ api: { ...this.cfg.asr.api, keySaved: (this.opts.asrApiKey?.() ?? '') !== '' },
2900
+ mic: this.micState,
2901
+ input: {
2902
+ ...this.cfg.asr.mic,
2903
+ hotkeyLabel: hotkeyLabel(this.cfg.asr.mic.hotkey, process.platform, this.ui),
2904
+ /** The keys alone, and how many presses (the last one held): for a key cap that shows the taps. */
2905
+ keyLabel: comboLabel(this.cfg.asr.mic.hotkey, process.platform, this.ui),
2906
+ taps: splitTaps(this.cfg.asr.mic.hotkey).taps,
2907
+ hint: this.talkHint(),
2908
+ hotkeyProblem: this.hotkeyProblem,
2909
+ open: this.gateOpen(),
2910
+ devices: this.devices,
2911
+ },
2912
+ /** `asr.recording`, the range of its `maxMinutes`, and whether the current endpoint takes the recording. */
2913
+ recording: {
2914
+ ...this.cfg.asr.recording,
2915
+ range: [RECORDING_MINUTES_MIN, RECORDING_MINUTES_MAX],
2916
+ endpointTakesAudio: this.host?.modelFacts.accepts('audio/wav') === true,
2917
+ },
2918
+ level: this.level,
2919
+ thresholdDb: this.cfg.asr.segment.thresholdDb,
2920
+ recent: this.heard.slice(-20),
2921
+ counts: { ...this.counts },
2922
+ };
2923
+ }
2924
+ }
2925
+
2926
+ export const modelsDirFor = (root: string) => join(root, DESKTOP_PET_ID);