cortico-world-agent-speed 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (189) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/LICENSE +0 -14
  3. package/README.md +29 -11
  4. package/THIRD_PARTY_NOTICES.md +69 -0
  5. package/activity.d.ts +15 -0
  6. package/activity.js +88 -3
  7. package/describe.json +806 -0
  8. package/dist/webui.css +2 -0
  9. package/dist/webui.css.map +7 -0
  10. package/dist/webui.js +2 -0
  11. package/dist/webui.js.map +7 -0
  12. package/host/app-store.cjs +68 -0
  13. package/host/cursor.cjs +67 -0
  14. package/host/electron-main.cjs +666 -0
  15. package/host/input-shape.cjs +63 -0
  16. package/host/mouse-lease.cjs +77 -0
  17. package/host/overlay.cjs +139 -0
  18. package/host/portrait.cjs +52 -0
  19. package/host/preload.cjs +60 -14
  20. package/host/renderer-gone.cjs +24 -0
  21. package/host/windows.cjs +251 -0
  22. package/package.json +27 -7
  23. package/scripts/build-webui.mjs +40 -0
  24. package/scripts/speech-bank/build.py +166 -0
  25. package/scripts/speech-bank/dicts.py +76 -0
  26. package/src/ENV_PROMPT.en.md +51 -0
  27. package/src/ENV_PROMPT.md +51 -0
  28. package/src/asr/address.ts +25 -0
  29. package/src/asr/hotkey.ts +335 -0
  30. package/src/asr/result.ts +51 -0
  31. package/src/asr/segmenter.ts +269 -0
  32. package/src/asr/sherpa.ts +280 -0
  33. package/src/asr/simplify.ts +38 -0
  34. package/src/asr/system-recognizer.ts +292 -0
  35. package/src/asr/system-sapi.ps1 +173 -0
  36. package/src/asr/transcription-api.ts +176 -0
  37. package/src/chat.ts +212 -0
  38. package/src/config.ts +481 -0
  39. package/src/cua/ENV_PROMPT.en.md +29 -0
  40. package/src/cua/ENV_PROMPT.md +29 -0
  41. package/src/cua/config.ts +88 -0
  42. package/src/cua/cua.ts +712 -0
  43. package/src/cua/engine/darwin.ts +410 -0
  44. package/src/cua/engine/display.ts +55 -0
  45. package/src/cua/engine/fail.ts +15 -0
  46. package/src/cua/engine/foreground.ts +8 -0
  47. package/src/cua/engine/image.ts +57 -0
  48. package/src/cua/engine/keys.ts +70 -0
  49. package/src/cua/engine/linux-keys.ts +29 -0
  50. package/src/cua/engine/linux.ts +343 -0
  51. package/src/cua/engine/mac-keys.ts +57 -0
  52. package/src/cua/engine/user-activity.ts +54 -0
  53. package/src/cua/engine/wait-idle.ts +31 -0
  54. package/src/cua/engine/win32.ts +299 -0
  55. package/src/cua/engine-child.ts +274 -0
  56. package/src/cua/engine-ipc.ts +140 -0
  57. package/src/cua/i18n/de.ts +53 -0
  58. package/src/cua/i18n/en.ts +63 -0
  59. package/src/cua/i18n/es-419.ts +53 -0
  60. package/src/cua/i18n/fr.ts +53 -0
  61. package/src/cua/i18n/index.ts +26 -0
  62. package/src/cua/i18n/it.ts +53 -0
  63. package/src/cua/i18n/ja.ts +53 -0
  64. package/src/cua/i18n/ko.ts +53 -0
  65. package/src/cua/i18n/pt-BR.ts +53 -0
  66. package/src/cua/i18n/ru.ts +59 -0
  67. package/src/cua/i18n/zh-Hant.ts +53 -0
  68. package/src/cua/i18n/zh.ts +59 -0
  69. package/src/cua/model-text.ts +252 -0
  70. package/src/cua/terminal.ts +31 -0
  71. package/src/cua/tools.ts +153 -0
  72. package/src/definition.ts +146 -0
  73. package/src/host-reason.ts +32 -0
  74. package/src/i18n/de.ts +409 -0
  75. package/src/i18n/en.ts +443 -0
  76. package/src/i18n/es-419.ts +409 -0
  77. package/src/i18n/fr.ts +409 -0
  78. package/src/i18n/index.ts +56 -0
  79. package/src/i18n/it.ts +409 -0
  80. package/src/i18n/ja.ts +409 -0
  81. package/src/i18n/ko.ts +409 -0
  82. package/src/i18n/pt-BR.ts +409 -0
  83. package/src/i18n/ru.ts +415 -0
  84. package/src/i18n/zh-Hant.ts +409 -0
  85. package/src/i18n/zh.ts +440 -0
  86. package/src/index.ts +15 -0
  87. package/src/model-text.ts +344 -0
  88. package/src/moves.ts +101 -0
  89. package/src/pack-import.ts +361 -0
  90. package/src/packs.ts +449 -0
  91. package/src/runtime/download.ts +29 -0
  92. package/src/runtime/store.ts +293 -0
  93. package/src/script.ts +202 -0
  94. package/src/self.ts +247 -0
  95. package/src/server.ts +479 -0
  96. package/src/speech/data/CMUDICT-LICENSE +33 -0
  97. package/src/speech/data/IPADIC-COPYING +71 -0
  98. package/src/speech/data/UNICODE-LICENSE +39 -0
  99. package/src/speech/data/en.tsv.gz +0 -0
  100. package/src/speech/data/ja-ipadic.tsv.gz +0 -0
  101. package/src/speech/data/ja-unihan.tsv.gz +0 -0
  102. package/src/speech/data/zh.json +1 -0
  103. package/src/speech/index.ts +204 -0
  104. package/src/speech/ipa.ts +83 -0
  105. package/src/speech/japanese.ts +105 -0
  106. package/src/speech/jukujikun.ts +22 -0
  107. package/src/speech/korean.ts +35 -0
  108. package/src/speech/lang.ts +151 -0
  109. package/src/speech/rules.ts +72 -0
  110. package/src/speech/syllable.ts +76 -0
  111. package/src/status.ts +164 -0
  112. package/src/tools.ts +110 -0
  113. package/src/webui/api-rows.css +2 -0
  114. package/src/webui/api-rows.ts +44 -0
  115. package/src/webui/client.ts +451 -0
  116. package/src/webui/dress-dialog.css +14 -0
  117. package/src/webui/dress-dialog.ts +117 -0
  118. package/src/webui/dress-panel.ts +160 -0
  119. package/src/webui/key-capture.ts +60 -0
  120. package/src/webui/shared/modal.css +13 -0
  121. package/src/webui/shared/modal.ts +77 -0
  122. package/src/webui/shared/problem.css +15 -0
  123. package/src/webui/shared/problem.ts +217 -0
  124. package/src/webui/shared/strings.ts +5 -0
  125. package/src/webui/style.css +50 -0
  126. package/src/window-host.ts +116 -0
  127. package/src/world.ts +2926 -0
  128. package/web/activity-motion.js +117 -0
  129. package/web/appearance.js +60 -0
  130. package/web/body-host.js +257 -0
  131. package/web/coo/coo.js +384 -0
  132. package/web/coo/figure.js +15 -0
  133. package/web/coo/figure.json +1224 -0
  134. package/web/dist/dress-dialog.css +1 -0
  135. package/web/dist/dress-dialog.js +1 -0
  136. package/web/drag-row.js +49 -0
  137. package/web/drag.js +149 -0
  138. package/web/dress.css +170 -0
  139. package/web/dress.html +37 -0
  140. package/web/dress.js +786 -0
  141. package/web/figure-frame.html +16 -0
  142. package/web/figure-frame.js +128 -0
  143. package/web/frame-loop.js +55 -0
  144. package/web/hints.js +77 -0
  145. package/web/i18n/de.js +170 -0
  146. package/web/i18n/en.js +177 -0
  147. package/web/i18n/es-419.js +170 -0
  148. package/web/i18n/fr.js +170 -0
  149. package/web/i18n/it.js +170 -0
  150. package/web/i18n/ja.js +170 -0
  151. package/web/i18n/ko.js +170 -0
  152. package/web/i18n/pt-BR.js +170 -0
  153. package/web/i18n/ru.js +170 -0
  154. package/web/i18n/zh-Hant.js +170 -0
  155. package/web/i18n/zh.js +175 -0
  156. package/web/i18n.js +54 -0
  157. package/{renderer/vendor → web}/kit/body.js +31 -58
  158. package/web/looks.js +70 -0
  159. package/web/mic-worklet.js +36 -0
  160. package/web/mic.js +117 -0
  161. package/web/motion-frames.js +80 -0
  162. package/web/motion-level.js +40 -0
  163. package/web/new-year-2027.svg +238 -0
  164. package/web/overlay.html +16 -0
  165. package/web/overlay.js +100 -0
  166. package/web/pet-app.js +3000 -0
  167. package/web/pet.css +642 -0
  168. package/web/pet.html +21 -0
  169. package/web/scale-slider.js +259 -0
  170. package/web/show-hide.js +49 -0
  171. package/web/sound.js +245 -0
  172. package/web/speech/zh.json +1 -0
  173. package/web/speech/zh.ogg +0 -0
  174. package/web/speech.js +197 -0
  175. package/web/stage.js +160 -0
  176. package/web/swap-motion.js +119 -0
  177. package/web/ui.js +195 -0
  178. package/host/launch.js +0 -187
  179. package/host/library.cjs +0 -638
  180. package/host/main.cjs +0 -389
  181. package/index.js +0 -93
  182. package/renderer/index.html +0 -22
  183. package/renderer/pet-sandbox.html +0 -11
  184. package/renderer/pet.css +0 -38
  185. package/renderer/pet.js +0 -251
  186. package/renderer/vendor/activity-motion.js +0 -101
  187. package/renderer/vendor/figure-frame.js +0 -115
  188. package/renderer/vendor/pack.css +0 -2
  189. /package/{renderer/vendor → web}/kit/rig.js +0 -0
@@ -0,0 +1,292 @@
1
+ /**
2
+ * Windows' own speech recognizer: SAPI dictation through System.Speech, in one long-lived
3
+ * PowerShell process (`system-sapi.ps1`). A sentence is streamed while it is spoken: its
4
+ * audio goes in frame by frame and the text heard so far comes back as it grows, so the pet
5
+ * shows what it hears before the sentence ends.
6
+ *
7
+ * Nothing to download: every Windows has System.Speech, and a Chinese Windows has the zh-CN
8
+ * recognizer. It is less accurate than SenseVoice and Whisper (src/asr/sherpa.ts), one of which is the default.
9
+ *
10
+ * The script goes in through `-EncodedCommand`, so neither the execution policy nor the
11
+ * console code page touches it; its output escapes everything outside ASCII for the same reason.
12
+ */
13
+ import { spawn, type ChildProcess } from 'node:child_process';
14
+ import { join } from 'node:path';
15
+ import { createInterface } from 'node:readline';
16
+ import { fileURLToPath } from 'node:url';
17
+ import type { Logger } from 'cortico/core/types.ts';
18
+ import { readTextFile } from 'cortico/core/util.ts';
19
+ import type { TranscribeResult } from './result.ts';
20
+ import { petText, type PetText } from '../i18n/index.ts';
21
+
22
+ export type SystemPhase = 'stopped' | 'starting' | 'running' | 'error';
23
+
24
+ export interface SystemRecognizerState {
25
+ phase: SystemPhase;
26
+ /** What the panel shows as the engine's address. */
27
+ url: string;
28
+ pid: number | null;
29
+ detail: string | null;
30
+ }
31
+
32
+ export interface SystemRecognizerOptions {
33
+ /** ISO 639-1 or 'auto'; a change restarts the process before the next sentence. */
34
+ language: () => string;
35
+ /**
36
+ * The recognizer preferred among those for the language, as a culture name (`zh-TW`, `es-MX`), when
37
+ * more than one is installed; else the one matching the Windows display language. A change restarts too.
38
+ */
39
+ culture?: () => string;
40
+ timeoutMs: () => number;
41
+ log: Logger;
42
+ /** Starts the helper; tests pass a fake. */
43
+ spawnImpl?: typeof spawn;
44
+ /** The text table of the app language, for the state and errors; Chinese when absent. */
45
+ text?: () => PetText;
46
+ }
47
+
48
+ /** One sentence being heard: frames go in while it is spoken, the text comes back after `end`. */
49
+ export interface SystemSentence {
50
+ write(frame: Int16Array): void;
51
+ end(): Promise<TranscribeResult>;
52
+ }
53
+
54
+ const SCRIPT_FILE = fileURLToPath(new URL('./system-sapi.ps1', import.meta.url));
55
+ /** How long PowerShell gets to compile the helper and open the recognizer. */
56
+ const READY_TIMEOUT_MS = 30_000;
57
+ /** Samples per `A` line when a finished sentence is streamed in at once. */
58
+ const CHUNK = 1600;
59
+
60
+ /** Available at all: Windows only. */
61
+ export const systemRecognizerSupported = (): boolean => process.platform === 'win32';
62
+
63
+ /** What the helper's `fatal` codes say. */
64
+ const FATAL: Record<string, (t: PetText['system'], lang: string) => string> = {
65
+ 'system-speech': (t) => t.noSpeech,
66
+ 'no-recognizer': (t, lang) => t.noRecognizer(lang),
67
+ };
68
+
69
+ function powershellExe(): string {
70
+ const root = process.env.SystemRoot || process.env.windir || 'C:\\Windows';
71
+ return join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
72
+ }
73
+
74
+ interface OpenSentence {
75
+ onPartial: (text: string) => void;
76
+ resolve: (r: TranscribeResult) => void;
77
+ /** When the sentence ended: the reported time is what recognition took after that. */
78
+ endedAt: number;
79
+ timer: NodeJS.Timeout | null;
80
+ }
81
+
82
+ export class SystemRecognizer {
83
+ private child: ChildProcess | null = null;
84
+ private phase: SystemPhase = 'stopped';
85
+ private detail: string | null = null;
86
+ private culture = '';
87
+ private language = '';
88
+ private starting: Promise<void> | null = null;
89
+ private generation = 0;
90
+ private cancelStart: (() => void) | null = null;
91
+ private readonly open = new Map<number, OpenSentence>();
92
+ private nextId = 1;
93
+
94
+ constructor(private readonly opts: SystemRecognizerOptions) {}
95
+
96
+ private get t(): PetText['system'] {
97
+ return (this.opts.text?.() ?? petText()).system;
98
+ }
99
+
100
+ /** The language and the preferred culture configured now, as the helper is started with them. */
101
+ private wanted(): string {
102
+ return `${this.opts.language() || 'auto'} ${this.opts.culture?.() ?? ''}`;
103
+ }
104
+
105
+ state(): SystemRecognizerState {
106
+ return { phase: this.phase, url: this.t.name(this.culture), pid: this.child?.pid ?? null, detail: this.detail };
107
+ }
108
+
109
+ /** Running, in the configured language, and able to take a sentence now. */
110
+ get ready(): boolean {
111
+ return this.phase === 'running' && this.language === this.wanted() && !!this.child?.stdin?.writable;
112
+ }
113
+
114
+ /** Started (or failed) for another language or culture than the configured one. */
115
+ get languageChanged(): boolean {
116
+ return this.language !== '' && this.phase !== 'starting' && this.language !== this.wanted();
117
+ }
118
+
119
+ /** Worth starting now: not ready, and not failed for the language still configured. */
120
+ private get restartable(): boolean {
121
+ return !this.ready && (this.phase !== 'error' || this.languageChanged);
122
+ }
123
+
124
+ start(): Promise<void> {
125
+ this.starting ??= this.doStart().finally(() => { this.starting = null; });
126
+ return this.starting;
127
+ }
128
+
129
+ private async doStart(): Promise<void> {
130
+ const generation = this.generation;
131
+ if (this.ready) return;
132
+ if (this.child) await this.stopChild();
133
+ if (generation !== this.generation) return;
134
+ if (!systemRecognizerSupported()) {
135
+ this.phase = 'error';
136
+ this.detail = this.t.windowsOnly;
137
+ return;
138
+ }
139
+ const language = this.opts.language() || 'auto';
140
+ this.language = this.wanted();
141
+ this.phase = 'starting';
142
+ this.detail = null;
143
+ const encoded = Buffer.from(readTextFile(SCRIPT_FILE), 'utf16le').toString('base64');
144
+ let child: ChildProcess;
145
+ try {
146
+ child = (this.opts.spawnImpl ?? spawn)(powershellExe(), ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', encoded], {
147
+ windowsHide: true,
148
+ stdio: ['pipe', 'pipe', 'pipe'],
149
+ env: { ...process.env, PET_ASR_LANGUAGE: language, PET_ASR_CULTURE: this.opts.culture?.() ?? '', PET_ASR_TIMEOUT_MS: String(this.opts.timeoutMs()) },
150
+ });
151
+ } catch (err) {
152
+ this.phase = 'error';
153
+ this.detail = this.t.startFailed((err as Error).message);
154
+ return;
155
+ }
156
+ this.child = child;
157
+ const log = this.opts.log.child('sapi');
158
+ child.stderr?.on('data', (d: Buffer) => { for (const line of d.toString().split(/\r?\n/)) if (line.trim()) log.debug(line); });
159
+ // a helper that died mid-write must not take the World down with an EPIPE
160
+ child.stdin?.on('error', (err) => log.debug(`stdin: ${err.message}`));
161
+ let ready: (ok: boolean) => void = () => {};
162
+ const readyP = new Promise<boolean>((r) => { ready = r; });
163
+ this.cancelStart = () => ready(false);
164
+ createInterface({ input: child.stdout! }).on('line', (line) => {
165
+ if (this.child !== child) return;
166
+ let msg: Record<string, unknown>;
167
+ try { msg = JSON.parse(line) as Record<string, unknown>; } catch { log.debug(line); return; }
168
+ if (msg.ready) {
169
+ this.culture = typeof msg.culture === 'string' ? msg.culture : '';
170
+ this.phase = 'running';
171
+ log.info(`系统语音识别已就绪:${this.culture} ${typeof msg.name === 'string' ? msg.name : ''}`);
172
+ ready(true);
173
+ } else if (typeof msg.fatal === 'string') {
174
+ this.phase = 'error';
175
+ this.detail = FATAL[msg.fatal]?.(this.t, language) ?? msg.fatal;
176
+ ready(false);
177
+ } else this.answer(msg);
178
+ });
179
+ child.on('error', (err) => {
180
+ ready(false);
181
+ if (this.child !== child) return;
182
+ this.phase = 'error'; this.detail = err.message;
183
+ });
184
+ child.on('exit', (code) => {
185
+ ready(false);
186
+ if (this.child !== child) return;
187
+ this.child = null;
188
+ this.failAll(this.t.exited);
189
+ if (this.phase !== 'stopped' && this.phase !== 'error') { this.phase = 'error'; this.detail = this.t.exitedCode(code); }
190
+ });
191
+ const timer = setTimeout(() => ready(false), READY_TIMEOUT_MS);
192
+ const ok = await readyP;
193
+ clearTimeout(timer);
194
+ if (this.child === child) this.cancelStart = null;
195
+ if (!ok && this.child === child) {
196
+ const detail = (this.phase as SystemPhase) === 'error' ? this.detail : this.t.notReady;
197
+ await this.stopChild();
198
+ if (generation !== this.generation) return;
199
+ this.phase = 'error';
200
+ this.detail = detail;
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Starts hearing a sentence of 16 kHz mono audio, or returns null when the recognizer is not
206
+ * ready. A stopped one, or one set to another language, is started then for later sentences;
207
+ * one that failed for this language waits to be started again, so a missing recognizer is not
208
+ * retried per sentence.
209
+ * `onPartial` gets the whole text so far.
210
+ */
211
+ sentence(onPartial: (text: string) => void = () => {}): SystemSentence | null {
212
+ if (!this.ready) { if (this.restartable) void this.start(); return null; }
213
+ const stdin = this.child!.stdin!;
214
+ const id = this.nextId++;
215
+ const done = new Promise<TranscribeResult>((resolve) => {
216
+ this.open.set(id, { onPartial, resolve, endedAt: 0, timer: null });
217
+ });
218
+ let ended = false;
219
+ stdin.write(`B ${id}\n`);
220
+ return {
221
+ write: (frame) => {
222
+ if (ended || !stdin.writable) return;
223
+ stdin.write(`A ${Buffer.from(frame.buffer, frame.byteOffset, frame.byteLength).toString('base64')}\n`);
224
+ },
225
+ end: () => {
226
+ if (ended) return done;
227
+ ended = true;
228
+ const o = this.open.get(id);
229
+ if (o) {
230
+ o.endedAt = Date.now();
231
+ // past its own timeout the helper is stuck; a new one starts for a later sentence
232
+ o.timer = setTimeout(() => { void this.stop(); }, this.opts.timeoutMs() + 5000);
233
+ if (stdin.writable) stdin.write('E\n');
234
+ }
235
+ return done;
236
+ },
237
+ };
238
+ }
239
+
240
+ /** One finished sentence, streamed in as fast as it goes. */
241
+ async transcribe(pcm: Int16Array): Promise<TranscribeResult> {
242
+ const started = Date.now();
243
+ if (this.restartable) await this.start();
244
+ const s = this.sentence();
245
+ if (!s) return { text: '', ms: Date.now() - started, error: this.detail ?? this.t.notRunning };
246
+ for (let at = 0; at < pcm.length; at += CHUNK) s.write(pcm.subarray(at, at + CHUNK));
247
+ return s.end();
248
+ }
249
+
250
+ private answer(msg: Record<string, unknown>): void {
251
+ const id = typeof msg.id === 'number' ? msg.id : -1;
252
+ const o = this.open.get(id);
253
+ if (!o) return;
254
+ if (typeof msg.partial === 'string') { o.onPartial(msg.partial.trim()); return; }
255
+ this.open.delete(id);
256
+ if (o.timer) clearTimeout(o.timer);
257
+ const ms = o.endedAt ? Date.now() - o.endedAt : 0;
258
+ if (typeof msg.error === 'string') o.resolve({ text: '', ms, error: msg.error === 'timeout' ? this.t.timeout(this.opts.timeoutMs()) : msg.error });
259
+ else o.resolve({ text: typeof msg.text === 'string' ? msg.text.trim() : '', ms, error: null });
260
+ }
261
+
262
+ private failAll(reason: string): void {
263
+ for (const o of this.open.values()) {
264
+ if (o.timer) clearTimeout(o.timer);
265
+ o.resolve({ text: '', ms: o.endedAt ? Date.now() - o.endedAt : 0, error: reason });
266
+ }
267
+ this.open.clear();
268
+ }
269
+
270
+ async stop(): Promise<void> {
271
+ this.generation++;
272
+ await this.stopChild();
273
+ await this.starting;
274
+ }
275
+
276
+ private async stopChild(): Promise<void> {
277
+ const child = this.child;
278
+ this.child = null;
279
+ this.cancelStart?.();
280
+ this.cancelStart = null;
281
+ if (this.phase !== 'error') this.phase = 'stopped';
282
+ this.failAll(this.t.stopped);
283
+ if (!child || child.exitCode !== null) return;
284
+ const exited = new Promise<void>((r) => child.once('exit', () => r()));
285
+ // closing stdin ends the helper's read loop; a stuck one is killed
286
+ child.stdin?.end();
287
+ let timer: NodeJS.Timeout | undefined;
288
+ const quit = await Promise.race([exited.then(() => true), new Promise<boolean>((r) => { timer = setTimeout(() => r(false), 1500); })]);
289
+ if (timer) clearTimeout(timer);
290
+ if (!quit) child.kill();
291
+ }
292
+ }
@@ -0,0 +1,173 @@
1
+ # Windows' own speech recognizer (SAPI dictation through System.Speech) as a line protocol,
2
+ # started by src/asr/system-recognizer.ts. Arguments come in environment variables:
3
+ # PET_ASR_LANGUAGE (ISO 639-1 or 'auto'), PET_ASR_CULTURE (the recognizer to prefer, such as zh-TW;
4
+ # empty prefers the Windows display language's) and PET_ASR_TIMEOUT_MS.
5
+ #
6
+ # Sentences are streamed: audio goes in while the person speaks and the text so far comes
7
+ # back as it grows, so the pet can show it before the sentence ends.
8
+ #
9
+ # stdin, one command per line; end of input ends the process:
10
+ # B <id> a sentence begins
11
+ # A <base64> 16 kHz mono PCM16 of the current sentence
12
+ # E the current sentence ends
13
+ # stdout, one JSON line each, non-ASCII escaped so the console code page cannot garble it:
14
+ # {"ready":true,"culture":"zh-CN","name":"..."} once, or {"fatal":"..."} and exit
15
+ # (`system-speech`: System.Speech would not load; `no-recognizer`: none for the language);
16
+ # {"id":1,"partial":"..."} while the sentence is heard, the whole text so far;
17
+ # {"id":1,"text":"..."} or {"id":1,"error":"..."} once it has ended.
18
+ $ErrorActionPreference = 'Stop'
19
+ # module loading would otherwise write progress records to stderr
20
+ $ProgressPreference = 'SilentlyContinue'
21
+ try {
22
+ Add-Type -AssemblyName System.Speech
23
+ Add-Type -ReferencedAssemblies System.Speech -TypeDefinition @'
24
+ using System;
25
+ using System.Collections.Generic;
26
+ using System.Globalization;
27
+ using System.IO;
28
+ using System.Text;
29
+ using System.Threading;
30
+ using System.Speech.AudioFormat;
31
+ using System.Speech.Recognition;
32
+
33
+ /**
34
+ * One sentence of audio as the recognizer reads it. SAPI takes a read that returns fewer bytes
35
+ * than asked for as the end of the stream, so a read waits until the whole request has
36
+ * arrived; only after `End` does it return what is left, then nothing.
37
+ */
38
+ public class PetFeed : Stream {
39
+ readonly Queue<byte[]> queue = new Queue<byte[]>();
40
+ byte[] cur; int at; int avail; bool ended;
41
+
42
+ public void Add(byte[] b) { lock (queue) { queue.Enqueue(b); avail += b.Length; Monitor.PulseAll(queue); } }
43
+ public void End() { lock (queue) { ended = true; Monitor.PulseAll(queue); } }
44
+
45
+ public override int Read(byte[] buf, int off, int n) {
46
+ if (n == 0) return 0;
47
+ lock (queue) {
48
+ while (!ended && avail < n) Monitor.Wait(queue);
49
+ int got = 0;
50
+ while (got < n) {
51
+ if (cur == null || at >= cur.Length) { if (queue.Count == 0) break; cur = queue.Dequeue(); at = 0; }
52
+ int k = Math.Min(n - got, cur.Length - at);
53
+ Array.Copy(cur, at, buf, off + got, k);
54
+ at += k; got += k; avail -= k;
55
+ }
56
+ return got;
57
+ }
58
+ }
59
+ public override bool CanRead { get { return true; } }
60
+ public override bool CanSeek { get { return false; } }
61
+ public override bool CanWrite { get { return false; } }
62
+ // SAPI reads nothing from a stream that says it is empty
63
+ public override long Length { get { return int.MaxValue; } }
64
+ public override long Position { get { return 0; } set { } }
65
+ public override void Flush() { }
66
+ public override long Seek(long o, SeekOrigin s) { return 0; }
67
+ public override void SetLength(long v) { }
68
+ public override void Write(byte[] b, int o, int c) { }
69
+ }
70
+
71
+ public static class PetSapi {
72
+ static SpeechRecognitionEngine engine;
73
+ static readonly object outLock = new object();
74
+ static readonly SpeechAudioFormatInfo format = new SpeechAudioFormatInfo(16000, AudioBitsPerSample.Sixteen, AudioChannel.Mono);
75
+ static PetFeed feed;
76
+ static string id = "";
77
+ /** Phrases the recognizer has settled on in the current sentence. */
78
+ static readonly StringBuilder settled = new StringBuilder();
79
+ static readonly ManualResetEvent idle = new ManualResetEvent(true);
80
+ static Timer overdue;
81
+ static bool timedOut;
82
+
83
+ public static string Json(string key, string value) {
84
+ var sb = new StringBuilder("\"" + key + "\":\"");
85
+ foreach (char c in value ?? "") {
86
+ if (c == '"' || c == '\\') sb.Append('\\').Append(c);
87
+ else if (c < 32 || c > 126) sb.AppendFormat("\\u{0:x4}", (int)c);
88
+ else sb.Append(c);
89
+ }
90
+ return sb.Append('"').ToString();
91
+ }
92
+
93
+ static void Emit(string line) { lock (outLock) { Console.Out.WriteLine(line); Console.Out.Flush(); } }
94
+
95
+ /** The installed recognizer for `language`, preferring the one of `culture`, else the one matching the Windows display language. */
96
+ public static string Open(string language, string culture) {
97
+ RecognizerInfo pick = null;
98
+ var prefer = string.IsNullOrEmpty(culture) ? CultureInfo.CurrentUICulture.Name : culture;
99
+ foreach (var r in SpeechRecognitionEngine.InstalledRecognizers()) {
100
+ bool fits = language == "auto" || string.Equals(r.Culture.TwoLetterISOLanguageName, language, StringComparison.OrdinalIgnoreCase);
101
+ if (!fits) continue;
102
+ if (pick == null || string.Equals(r.Culture.Name, prefer, StringComparison.OrdinalIgnoreCase)) pick = r;
103
+ }
104
+ if (pick == null) return null;
105
+ engine = new SpeechRecognitionEngine(pick);
106
+ engine.LoadGrammar(new DictationGrammar());
107
+ engine.SpeechHypothesized += (s, e) => {
108
+ lock (settled) Emit("{\"id\":" + id + "," + Json("partial", settled + e.Result.Text) + "}");
109
+ };
110
+ engine.SpeechRecognized += (s, e) => {
111
+ lock (settled) { settled.Append(e.Result.Text); Emit("{\"id\":" + id + "," + Json("partial", settled.ToString()) + "}"); }
112
+ };
113
+ engine.RecognizeCompleted += (s, e) => {
114
+ if (overdue != null) overdue.Dispose();
115
+ overdue = null;
116
+ lock (settled) {
117
+ if (timedOut) Emit("{\"id\":" + id + "," + Json("error", "timeout") + "}");
118
+ else if (e.Error != null) Emit("{\"id\":" + id + "," + Json("error", e.Error.Message) + "}");
119
+ else Emit("{\"id\":" + id + "," + Json("text", settled.ToString()) + "}");
120
+ }
121
+ idle.Set();
122
+ };
123
+ return "{\"ready\":true," + Json("culture", pick.Culture.Name) + "," + Json("name", pick.Description) + "}";
124
+ }
125
+
126
+ /** Reads commands until the input ends. */
127
+ public static void Serve(int timeoutMs) {
128
+ string line;
129
+ while ((line = Console.In.ReadLine()) != null) {
130
+ if (line.Length == 0) continue;
131
+ try {
132
+ if (line[0] == 'A' && feed != null) feed.Add(Convert.FromBase64String(line.Substring(2)));
133
+ else if (line[0] == 'B') Begin(line.Substring(2).Trim(), timeoutMs);
134
+ else if (line[0] == 'E' && feed != null) End(timeoutMs);
135
+ } catch (Exception err) {
136
+ Emit("{\"id\":" + (id == "" ? "0" : id) + "," + Json("error", err.Message) + "}");
137
+ }
138
+ }
139
+ }
140
+
141
+ static void Begin(string next, int timeoutMs) {
142
+ // the sentence before may still be finishing its last phrase
143
+ if (!idle.WaitOne(timeoutMs)) { engine.RecognizeAsyncCancel(); idle.WaitOne(2000); }
144
+ lock (settled) { settled.Clear(); id = next; timedOut = false; }
145
+ feed = new PetFeed();
146
+ engine.SetInputToAudioStream(feed, format);
147
+ idle.Reset();
148
+ engine.RecognizeAsync(RecognizeMode.Multiple);
149
+ }
150
+
151
+ static void End(int timeoutMs) {
152
+ feed.End();
153
+ feed = null;
154
+ overdue = new Timer((_) => { timedOut = true; engine.RecognizeAsyncCancel(); }, null, timeoutMs, Timeout.Infinite);
155
+ }
156
+ }
157
+ '@
158
+ } catch {
159
+ # PetSapi may not exist here, so the reason is only a code
160
+ [Console]::Out.WriteLine('{"fatal":"system-speech"}')
161
+ exit 1
162
+ }
163
+
164
+ $language = if ($env:PET_ASR_LANGUAGE) { $env:PET_ASR_LANGUAGE } else { 'auto' }
165
+ $culture = if ($env:PET_ASR_CULTURE) { $env:PET_ASR_CULTURE } else { '' }
166
+ $timeout = if ($env:PET_ASR_TIMEOUT_MS) { [int]$env:PET_ASR_TIMEOUT_MS } else { 20000 }
167
+ $ready = $null
168
+ try { $ready = [PetSapi]::Open($language, $culture) } catch { $ready = '{' + [PetSapi]::Json('fatal', $_.Exception.Message) + '}' }
169
+ if (-not $ready) { $ready = '{"fatal":"no-recognizer"}' }
170
+ [Console]::Out.WriteLine($ready)
171
+ [Console]::Out.Flush()
172
+ if ($ready -notlike '{"ready"*') { exit 1 }
173
+ [PetSapi]::Serve($timeout)
@@ -0,0 +1,176 @@
1
+ /**
2
+ * An OpenAI-compatible transcription service (engine `api`): each finished sentence goes out as a
3
+ * 16 kHz mono 16-bit WAV file in one `POST {baseUrl}/audio/transcriptions` (multipart: `file`,
4
+ * `model`, `language` when the recognition language is a two-letter code, `response_format=json`),
5
+ * and the reply's `text` is the result. Requests go through the global `fetch`, so the system proxy
6
+ * Core sets up applies.
7
+ *
8
+ * A remote address takes https only (`plainRemote`, the provider's rule). A failed request (an HTTP
9
+ * error, no answer within the timeout, no connection) puts the engine in `error` with the reason;
10
+ * nothing more is sent until it is started again, which a change of address or model, or an API Key
11
+ * saved from the voice panel, also does.
12
+ */
13
+ import type { Logger } from 'cortico/core/types.ts';
14
+ import { plainRemote } from './address.ts';
15
+ import type { TranscribeResult } from './result.ts';
16
+ import type { SystemSentence } from './system-recognizer.ts';
17
+ import { petText, type PetText } from '../i18n/index.ts';
18
+
19
+ export type TranscriptionPhase = 'stopped' | 'running' | 'error';
20
+
21
+ export interface TranscriptionState {
22
+ phase: TranscriptionPhase;
23
+ /** What the panel shows as the engine's address: the URL requests go to. */
24
+ url: string;
25
+ pid: null;
26
+ detail: string | null;
27
+ }
28
+
29
+ export interface TranscriptionApiOptions {
30
+ /** The address and model as configured now (`asr.api`). */
31
+ config: () => { baseUrl: string; model: string };
32
+ /** The API Key; empty sends no Authorization header. */
33
+ key: () => string;
34
+ /** ISO 639-1 or 'auto'. */
35
+ language: () => string;
36
+ timeoutMs: () => number;
37
+ log: Logger;
38
+ /** The text table of the app language; Chinese when absent. */
39
+ text?: () => PetText;
40
+ }
41
+
42
+ /** Samples a second of the PCM the pet page sends, and of the WAV made from it. */
43
+ export const SAMPLE_RATE = 16_000;
44
+ /** The longest part of an error body shown when it is not `{ error: { message } }`. */
45
+ const BODY_MAX = 300;
46
+
47
+ /** 16-bit mono PCM at 16 kHz as a WAV file. */
48
+ export function wavFile(pcm: Int16Array): Uint8Array<ArrayBuffer> {
49
+ const bytes = pcm.length * 2;
50
+ const v = new DataView(new ArrayBuffer(44 + bytes));
51
+ const ascii = (at: number, s: string) => { for (let i = 0; i < s.length; i++) v.setUint8(at + i, s.charCodeAt(i)); };
52
+ ascii(0, 'RIFF');
53
+ v.setUint32(4, 36 + bytes, true);
54
+ ascii(8, 'WAVEfmt ');
55
+ v.setUint32(16, 16, true);
56
+ v.setUint16(20, 1, true); // PCM
57
+ v.setUint16(22, 1, true); // channels
58
+ v.setUint32(24, SAMPLE_RATE, true);
59
+ v.setUint32(28, SAMPLE_RATE * 2, true); // bytes a second
60
+ v.setUint16(32, 2, true); // bytes a frame
61
+ v.setUint16(34, 16, true); // bits a sample
62
+ ascii(36, 'data');
63
+ v.setUint32(40, bytes, true);
64
+ for (let i = 0; i < pcm.length; i++) v.setInt16(44 + i * 2, pcm[i]!, true);
65
+ return new Uint8Array(v.buffer);
66
+ }
67
+
68
+ const endpointOf = (baseUrl: string) => `${baseUrl.trim().replace(/\/+$/, '')}/audio/transcriptions`;
69
+
70
+ export class TranscriptionApi {
71
+ private phase: TranscriptionPhase = 'stopped';
72
+ private detail: string | null = null;
73
+ /** Address and model the engine was last started with. */
74
+ private started = '';
75
+ /** Counts starts and stops; a request begun before one does not change the state when it lands. */
76
+ private generation = 0;
77
+
78
+ constructor(private readonly opts: TranscriptionApiOptions) {}
79
+
80
+ private get t(): PetText['transcription'] {
81
+ return (this.opts.text?.() ?? petText()).transcription;
82
+ }
83
+
84
+ state(): TranscriptionState {
85
+ const { baseUrl } = this.opts.config();
86
+ return { phase: this.phase, url: baseUrl.trim() ? endpointOf(baseUrl) : '', pid: null, detail: this.detail };
87
+ }
88
+
89
+ /** The address or model changed since the engine was started. Polled with the config, so the key, whose read can open `.env`, is not compared. */
90
+ get configChanged(): boolean {
91
+ return this.started !== this.signature();
92
+ }
93
+
94
+ private signature(): string {
95
+ const { baseUrl, model } = this.opts.config();
96
+ return JSON.stringify([baseUrl, model]);
97
+ }
98
+
99
+ /** Takes the configured address and model, or says why they cannot be used; nothing is sent. */
100
+ async start(): Promise<void> {
101
+ this.generation++;
102
+ this.started = this.signature();
103
+ const { baseUrl, model } = this.opts.config();
104
+ const why = this.problem(baseUrl.trim(), model.trim());
105
+ this.phase = why ? 'error' : 'running';
106
+ this.detail = why;
107
+ }
108
+
109
+ private problem(baseUrl: string, model: string): string | null {
110
+ if (!baseUrl) return this.t.noUrl;
111
+ let url: URL;
112
+ try { url = new URL(baseUrl); } catch { return this.t.badUrl(baseUrl); }
113
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return this.t.badUrl(baseUrl);
114
+ if (plainRemote(baseUrl)) return this.t.httpRemote;
115
+ return model ? null : this.t.noModel;
116
+ }
117
+
118
+ async stop(): Promise<void> {
119
+ this.generation++;
120
+ this.phase = 'stopped';
121
+ this.detail = null;
122
+ }
123
+
124
+ /** The service hears only finished sentences. */
125
+ sentence(): SystemSentence | null {
126
+ return null;
127
+ }
128
+
129
+ /** One finished sentence to text. */
130
+ async transcribe(pcm: Int16Array): Promise<TranscribeResult> {
131
+ const started = Date.now();
132
+ if (this.phase !== 'running') return { text: '', ms: 0, error: this.detail ?? this.t.notRunning };
133
+ const generation = this.generation;
134
+ const { baseUrl, model } = this.opts.config();
135
+ const language = this.opts.language();
136
+ const form = new FormData();
137
+ form.append('file', new Blob([wavFile(pcm)], { type: 'audio/wav' }), 'speech.wav');
138
+ form.append('model', model.trim());
139
+ if (/^[a-z]{2}$/.test(language)) form.append('language', language);
140
+ form.append('response_format', 'json');
141
+ const key = this.opts.key();
142
+ const timeoutMs = this.opts.timeoutMs();
143
+ let error: string;
144
+ try {
145
+ const res = await fetch(endpointOf(baseUrl), {
146
+ method: 'POST',
147
+ headers: key ? { Authorization: `Bearer ${key}` } : {},
148
+ body: form,
149
+ signal: AbortSignal.timeout(timeoutMs),
150
+ });
151
+ const body = await res.text();
152
+ const json = parseJson(body);
153
+ if (res.ok) {
154
+ const text = (json as { text?: unknown } | null)?.text;
155
+ if (typeof text === 'string') return { text: text.trim(), ms: Date.now() - started, error: null };
156
+ error = this.t.noText;
157
+ } else {
158
+ const message = (json as { error?: { message?: unknown } } | null)?.error?.message;
159
+ error = this.t.status(res.status, typeof message === 'string' ? message : body.trim().slice(0, BODY_MAX));
160
+ }
161
+ } catch (err) {
162
+ const e = err as Error & { cause?: { message?: string } };
163
+ error = e.name === 'TimeoutError' ? this.t.timeout(timeoutMs) : this.t.network(e.cause?.message ?? e.message);
164
+ }
165
+ this.opts.log.warn(`转写接口请求失败:${error}`);
166
+ if (generation === this.generation) {
167
+ this.phase = 'error';
168
+ this.detail = error;
169
+ }
170
+ return { text: '', ms: Date.now() - started, error };
171
+ }
172
+ }
173
+
174
+ function parseJson(body: string): unknown {
175
+ try { return JSON.parse(body); } catch { return null; }
176
+ }