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/server.ts ADDED
@@ -0,0 +1,479 @@
1
+ /**
2
+ * Local HTTP + WebSocket server for the pet's pages. Binds 127.0.0.1 only and answers only
3
+ * requests whose Host is a loopback name, so a web page cannot reach it through DNS rebinding.
4
+ *
5
+ * - `/pet`: the pet itself. In the pet window it is transparent and click-through outside
6
+ * the figure; in a browser tab it draws a floor.
7
+ * - `/dress`: the dressing page; changes go through `POST /api/skin` and `POST /api/prefs`, and the saved
8
+ * looks are read at `GET /api/looks` and written whole through `POST /api/looks`.
9
+ * - `POST /api/speech` (`{ text }`): the syllables the pet page's speech plays for a bubble's text (src/speech).
10
+ * - `/api/figures`: the figure packs (src/packs.ts) the pages may load, Coo's first, each with whether it
11
+ * can be uninstalled (`removable`); `/packs/<id>/…`: an installed pack's files (a built-in one is under
12
+ * `/web/`). `/api/figures/status`: the installed packs that did not load and why, and whether packs can be
13
+ * imported here; `POST /api/figures/import` (a zip, or the page's framing of folders), `…/import/install`
14
+ * and `…/import/cancel` import them, `POST /api/figures/remove` (`{ id }`) uninstalls one (src/pack-import.ts).
15
+ * - `/figure-frame?pack=<id>`: the sandbox a pack's code runs in. Its own CSP sandboxes it (an opaque
16
+ * origin) and lets it connect only to `/packs/<id>/` of an installed pack, nowhere for any other id;
17
+ * scripts and images come from this server only. Files
18
+ * under `/web/` and `/packs/` answer that opaque origin's CORS requests; nothing else does,
19
+ * and a write (`POST`, the socket) from it is refused.
20
+ * - `/socket?role=pet|dress&host=window|tab`: one live pet connection plus any number of
21
+ * pages that only receive skin and preference updates. The window and overlay source authenticate
22
+ * with the key carried by `windowUrl`. A newer pet connection replaces the live one, except
23
+ * that a browser tab only watches while the pet window is connected. A
24
+ * watching tab still sends typed text, preference changes and run-control clicks.
25
+ * Binary frames from the pet connection are 16 kHz mono PCM16 microphone audio.
26
+ * - `/overlay` and `/socket?role=overlay`: the OBS overlay page and its feed, while `overlay()` is on
27
+ * (404 and a closed socket otherwise). `/socket?role=overlay-source` is the pet window process: it is told
28
+ * `{ t: 'overlay', on }` (on while the overlay is on and a page watches) and its binary frames
29
+ * (host/overlay.cjs) go to every overlay page as they are; when it goes, the pages are sent a frame that clears them.
30
+ */
31
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
32
+ import { randomUUID } from 'node:crypto';
33
+ import { readFile } from 'node:fs/promises';
34
+ import { basename, extname, join, normalize, sep } from 'node:path';
35
+ import { WebSocketServer, type WebSocket } from 'ws';
36
+ import { languageTag, type Language } from 'cortico/core/language.ts';
37
+ import { readTextFile } from 'cortico/core/util.ts';
38
+ import { packFile, type FigurePack, type PackProblem } from './packs.ts';
39
+ import { BUNDLE_TYPE, IMPORT_LARGE, PACK_DEPTH, filesFromBundle, filesFromZip, type PackImporter } from './pack-import.ts';
40
+ import { petText, type PetText } from './i18n/index.ts';
41
+ import type { SpeechUnit } from './speech/index.ts';
42
+
43
+ const MIME: Record<string, string> = {
44
+ '.html': 'text/html; charset=utf-8',
45
+ '.js': 'text/javascript; charset=utf-8',
46
+ '.css': 'text/css; charset=utf-8',
47
+ '.svg': 'image/svg+xml',
48
+ '.png': 'image/png',
49
+ '.json': 'application/json; charset=utf-8',
50
+ '.ogg': 'audio/ogg',
51
+ '.mp3': 'audio/mpeg',
52
+ '.wav': 'audio/wav',
53
+ };
54
+ const PAGES: Record<string, string> = { '/pet': 'pet.html', '/dress': 'dress.html' };
55
+ const LOOPBACK = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
56
+ const PORT_ATTEMPTS = 10;
57
+ /**
58
+ * A pack's files: the figure frame imports its scripts and loads its images, which this does not
59
+ * restrict; a pack's HTML or SVG opened as a page runs in an opaque origin with no network.
60
+ */
61
+ const PACK_CSP = "sandbox allow-scripts; default-src 'none'";
62
+ /** The pages' own CSP. */
63
+ const PAGE_CSP = "default-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws://127.0.0.1:* ws://localhost:*; img-src 'self' data:; media-src 'self' blob:; worker-src 'self' blob:; frame-ancestors 'self' http://127.0.0.1:* http://localhost:*";
64
+ /** What a watching pet page may still send: input that is the person's whichever page it came from. */
65
+ const WATCHER_MESSAGES = new Set(['text', 'prefs', 'control']);
66
+
67
+ export type PageMessage = Record<string, unknown> & { t: string };
68
+
69
+ export interface PetServerOptions {
70
+ port: () => number;
71
+ webDir: string;
72
+ /** Snapshot sent to every new connection and served at `/api/state`. */
73
+ snapshot(): Record<string, unknown>;
74
+ onPetMessage(msg: PageMessage): void;
75
+ onAudio(frame: Int16Array): void;
76
+ onPetConnect(): void;
77
+ onPetDisconnect(): void;
78
+ /** A dressing page saved a skin. */
79
+ /** `scale`: the size to put the look on at, when it is a saved look's. */
80
+ onSkin(skin: unknown, scale?: unknown): void;
81
+ onPrefs(prefs: Record<string, unknown>): void;
82
+ /** The saved looks, and the list a dressing page writes back whole. */
83
+ looks(): unknown[];
84
+ onLooks(looks: unknown): void;
85
+ /** The figure packs, looked up again for each request. */
86
+ packs?(): FigurePack[];
87
+ /** What was wrong in the pack directories, looked up again for each request. */
88
+ packProblems?(): PackProblem[];
89
+ /** Installs packs the dressing page sends; without it the page offers no import. */
90
+ importer?: PackImporter;
91
+ /** The app language, stamped on each page's `<html lang>` as it is served; the page loads its text in it. `zh` when absent. */
92
+ language?(): Language;
93
+ /** The text table of the app language, for errors; Chinese when absent. */
94
+ text?(): PetText;
95
+ /** Whether the OBS overlay is served; off when absent. */
96
+ overlay?(): boolean;
97
+ /** The syllables `text` is spoken as; `POST /api/speech` answers 404 without it. */
98
+ speech?(text: string): SpeechUnit[];
99
+ }
100
+
101
+ export class PetServer {
102
+ private http: Server | null = null;
103
+ private wss: WebSocketServer | null = null;
104
+ private pet: WebSocket | null = null;
105
+ private petIsWindow = false;
106
+ /** Dressing pages and pet pages that only watch. */
107
+ private readonly dressers = new Set<WebSocket>();
108
+ /** The pet window process sending the overlay's frames, and the overlay pages watching. */
109
+ private overlaySource: WebSocket | null = null;
110
+ private readonly overlayViewers = new Set<WebSocket>();
111
+ /** What the source was last told. */
112
+ private overlayTold: boolean | null = null;
113
+ private boundPort = 0;
114
+ private readonly windowKey = randomUUID();
115
+
116
+ constructor(private readonly opts: PetServerOptions) {}
117
+
118
+ get port(): number {
119
+ return this.boundPort;
120
+ }
121
+
122
+ private get t(): PetText {
123
+ return this.opts.text?.() ?? petText();
124
+ }
125
+
126
+ get origin(): string {
127
+ return this.boundPort ? `http://127.0.0.1:${this.boundPort}` : '';
128
+ }
129
+
130
+ /** Only the window host receives this URL; its fragment stays out of HTTP requests and referrers. */
131
+ get windowUrl(): string {
132
+ return `${this.origin}/pet#key=${this.windowKey}`;
133
+ }
134
+
135
+ get petConnected(): boolean {
136
+ return this.pet !== null && this.pet.readyState === this.pet.OPEN;
137
+ }
138
+
139
+ /** The connected pet page is the pet window, not a browser tab. */
140
+ get petInWindow(): boolean {
141
+ return this.petConnected && this.petIsWindow;
142
+ }
143
+
144
+ async start(): Promise<number> {
145
+ const base = this.opts.port();
146
+ let lastErr: Error | null = null;
147
+ for (let i = 0; i < PORT_ATTEMPTS; i++) {
148
+ const server = createServer((req, res) => { void this.handle(req, res); });
149
+ try {
150
+ await new Promise<void>((done, fail) => {
151
+ server.once('error', fail);
152
+ server.listen(base === 0 ? 0 : base + i, '127.0.0.1', () => { server.off('error', fail); done(); });
153
+ });
154
+ } catch (err) {
155
+ lastErr = err as Error;
156
+ const code = (err as NodeJS.ErrnoException).code;
157
+ if (code === 'EADDRINUSE' || code === 'EACCES') continue;
158
+ throw err;
159
+ }
160
+ this.http = server;
161
+ const addr = server.address();
162
+ this.boundPort = typeof addr === 'object' && addr ? addr.port : 0;
163
+ this.wss = new WebSocketServer({ noServer: true });
164
+ server.on('upgrade', (req, socket, head) => {
165
+ if (!this.allowed(req, true)) { socket.end('HTTP/1.1 421 Misdirected Request\r\nConnection: close\r\n\r\n'); return; }
166
+ const url = new URL(req.url ?? '/', this.origin);
167
+ if (url.pathname !== '/socket') { socket.destroy(); return; }
168
+ const params = url.searchParams;
169
+ if ((params.get('host') === 'window' || params.get('role') === 'overlay-source') && params.get('key') !== this.windowKey) {
170
+ socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return;
171
+ }
172
+ this.wss!.handleUpgrade(req, socket, head, (ws) => this.accept(ws, req));
173
+ });
174
+ return this.boundPort;
175
+ }
176
+ throw new Error(this.t.portsTaken(base, base + PORT_ATTEMPTS - 1, lastErr?.message ?? ''));
177
+ }
178
+
179
+ async stop(): Promise<void> {
180
+ for (const ws of [this.pet, ...this.dressers, this.overlaySource, ...this.overlayViewers]) ws?.close();
181
+ this.pet = null;
182
+ this.dressers.clear();
183
+ this.overlaySource = null;
184
+ this.overlayViewers.clear();
185
+ this.wss?.close();
186
+ this.wss = null;
187
+ const http = this.http;
188
+ this.http = null;
189
+ this.boundPort = 0;
190
+ if (http) {
191
+ http.closeAllConnections();
192
+ await new Promise<void>((r) => http.close(() => r()));
193
+ }
194
+ }
195
+
196
+ /** Sends to the pet page; false when no page is connected. */
197
+ sendPet(msg: PageMessage): boolean {
198
+ if (!this.petConnected) return false;
199
+ this.pet!.send(JSON.stringify(msg));
200
+ return true;
201
+ }
202
+
203
+ /** Sends to the pet page and every dressing page. */
204
+ broadcast(msg: PageMessage): void {
205
+ const text = JSON.stringify(msg);
206
+ for (const ws of [this.pet, ...this.dressers]) if (ws && ws.readyState === ws.OPEN) ws.send(text);
207
+ }
208
+
209
+ /** Follows `overlay()`: off closes the overlay pages; the source streams while it is on and a page watches. */
210
+ syncOverlay(): void {
211
+ if (!this.overlayEnabled) for (const ws of this.overlayViewers) ws.close(4003, 'overlay off');
212
+ const source = this.overlaySource;
213
+ if (!source || source.readyState !== source.OPEN) return;
214
+ const on = this.overlayEnabled && this.overlayViewers.size > 0;
215
+ if (on === this.overlayTold) return;
216
+ this.overlayTold = on;
217
+ source.send(JSON.stringify({ t: 'overlay', on }));
218
+ }
219
+
220
+ private get overlayEnabled(): boolean {
221
+ return this.opts.overlay?.() ?? false;
222
+ }
223
+
224
+ /** Browser writes require this service's HTTP origin; local clients may omit Origin. Reads also allow loopback and opaque origins. */
225
+ private allowed(req: IncomingMessage, write: boolean): boolean {
226
+ if (!LOOPBACK.test(req.headers.host ?? '')) return false;
227
+ const origin = req.headers.origin;
228
+ if (origin === 'null') return !write;
229
+ if (!origin) return true;
230
+ if (write) return origin === this.origin || origin === `http://localhost:${this.boundPort}`;
231
+ try {
232
+ return LOOPBACK.test(new URL(origin).host);
233
+ } catch {
234
+ return false;
235
+ }
236
+ }
237
+
238
+ private accept(ws: WebSocket, req: IncomingMessage): void {
239
+ const params = new URL(req.url ?? '/', 'http://x').searchParams;
240
+ const fromWindow = params.get('host') === 'window';
241
+ if (params.get('role') === 'overlay-source') return this.acceptOverlaySource(ws);
242
+ if (params.get('role') === 'overlay') return this.acceptOverlayViewer(ws);
243
+ ws.send(JSON.stringify({ t: 'init', ...this.opts.snapshot() }));
244
+ // the pet window outranks a browser tab: a tab opened while the window is connected only watches
245
+ const watcher = params.get('role') !== 'pet' || (!fromWindow && this.petConnected && this.petIsWindow);
246
+ if (!watcher) {
247
+ const old = this.pet;
248
+ this.pet = ws;
249
+ this.petIsWindow = fromWindow;
250
+ if (old) old.close(4000, 'replaced');
251
+ this.opts.onPetConnect();
252
+ ws.on('message', (data, isBinary) => {
253
+ if (this.pet !== ws) return;
254
+ if (isBinary) {
255
+ const buf = data as Buffer;
256
+ if (buf.length % 2 === 0) this.opts.onAudio(new Int16Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length)));
257
+ return;
258
+ }
259
+ const msg = parse(data.toString());
260
+ if (msg) this.opts.onPetMessage(msg);
261
+ });
262
+ ws.on('close', () => {
263
+ if (this.pet !== ws) return;
264
+ this.pet = null;
265
+ this.opts.onPetDisconnect();
266
+ });
267
+ return;
268
+ }
269
+ if (params.get('role') === 'pet') {
270
+ ws.send(JSON.stringify({ t: 'watching' }));
271
+ ws.on('message', (data, isBinary) => {
272
+ const msg = isBinary ? null : parse(data.toString());
273
+ if (msg && WATCHER_MESSAGES.has(msg.t)) this.opts.onPetMessage(msg);
274
+ });
275
+ }
276
+ this.dressers.add(ws);
277
+ ws.on('close', () => this.dressers.delete(ws));
278
+ }
279
+
280
+ private acceptOverlaySource(ws: WebSocket): void {
281
+ this.overlaySource?.close(4000, 'replaced');
282
+ this.overlaySource = ws;
283
+ this.overlayTold = null;
284
+ ws.on('message', (data, isBinary) => {
285
+ if (this.overlaySource !== ws || !isBinary || !this.overlayEnabled) return;
286
+ for (const viewer of this.overlayViewers) if (viewer.readyState === viewer.OPEN) viewer.send(data, { binary: true });
287
+ });
288
+ ws.on('close', () => {
289
+ if (this.overlaySource !== ws) return;
290
+ this.overlaySource = null;
291
+ // the window process is gone: the pages must not keep its last picture
292
+ const clear = Buffer.alloc(24);
293
+ for (const viewer of this.overlayViewers) if (viewer.readyState === viewer.OPEN) viewer.send(clear, { binary: true });
294
+ });
295
+ this.syncOverlay();
296
+ }
297
+
298
+ private acceptOverlayViewer(ws: WebSocket): void {
299
+ if (!this.overlayEnabled) { ws.close(4003, 'overlay off'); return; }
300
+ this.overlayViewers.add(ws);
301
+ ws.on('close', () => { this.overlayViewers.delete(ws); this.syncOverlay(); });
302
+ this.syncOverlay();
303
+ }
304
+
305
+ private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
306
+ if (!this.allowed(req, req.method !== 'GET' && req.method !== 'HEAD')) { res.writeHead(421).end(); return; }
307
+ const url = new URL(req.url ?? '/', 'http://x');
308
+ const path = url.pathname;
309
+ if (req.method === 'GET' && path === '/api/figures') {
310
+ const importer = this.opts.importer;
311
+ return json(res, 200, (this.opts.packs?.() ?? []).map((pack) => {
312
+ const { id, base, manifest: m } = pack;
313
+ return {
314
+ id, base, name: m.name, thumb: m.thumb ?? null, entry: m.entry, export: m.export, model: m.model ?? null, axes: m.axes, presets: m.presets,
315
+ vocab: m.vocab.map(({ id: w, kind, seconds, lasting }) => ({ id: w, kind, seconds, ...(lasting ? { lasting } : {}) })), sounds: m.sounds, can: m.can, needs: m.needs,
316
+ voice: m.voice, effects: m.effects, bubble: m.bubble ?? null,
317
+ removable: importer?.removable(pack) ?? false,
318
+ };
319
+ }));
320
+ }
321
+ if (req.method === 'GET' && path === '/api/figures/status') {
322
+ return json(res, 200, {
323
+ importable: !!this.opts.importer, large: IMPORT_LARGE, depth: PACK_DEPTH,
324
+ problems: (this.opts.packProblems?.() ?? []).filter((p) => !p.loaded).map((p) => ({ dir: basename(p.dir), reason: p.reason })),
325
+ });
326
+ }
327
+ if (req.method === 'POST' && path.startsWith('/api/figures/import') && this.opts.importer) return this.importRequest(req, res, path, this.opts.importer);
328
+ if (req.method === 'POST' && path === '/api/figures/remove' && this.opts.importer) {
329
+ const msg = parse(await readBody(req) ?? '');
330
+ if (typeof msg?.id !== 'string') return json(res, 400, { error: 'bad json' });
331
+ const out = await this.opts.importer.remove(msg.id);
332
+ return json(res, 'error' in out ? 400 : 200, out);
333
+ }
334
+ if (req.method === 'GET' && path === '/figure-frame') {
335
+ const self = `http://${req.headers.host}`;
336
+ // an installed pack (`?pack=<id>`) may fetch its own folder, which never redirects (a CSP path stops holding after
337
+ // a redirect); a built-in pack, an unknown id or none connects nowhere
338
+ const id = url.searchParams.get('pack');
339
+ const own = id && (this.opts.packs?.() ?? []).some((p) => p.id === id && !p.builtin) ? `${self}/packs/${id}/` : "'none'";
340
+ return this.sendFile(res, join(this.opts.webDir, 'figure-frame.html'), [
341
+ 'sandbox allow-scripts', "default-src 'none'", `script-src ${self}`, `img-src ${self} data: blob:`, "style-src 'unsafe-inline'", `connect-src ${own}`,
342
+ // the pet page holds it, and the console that shows the pet page in its own frames (another local port) is an ancestor too
343
+ `frame-ancestors ${self} http://127.0.0.1:* http://localhost:*`,
344
+ ].join('; '));
345
+ }
346
+ if (req.method === 'GET' && path.startsWith('/packs/')) {
347
+ const [, , id, ...rest] = path.split('/');
348
+ const pack = (this.opts.packs?.() ?? []).find((p) => p.id === id && !p.builtin);
349
+ const full = pack ? packFile(pack, decodeURIComponent(rest.join('/'))) : null;
350
+ if (!full) { res.writeHead(404).end(); return; }
351
+ return this.sendFile(res, full, PACK_CSP, req.headers.origin === 'null');
352
+ }
353
+ if (req.method === 'GET' && path === '/api/state') return json(res, 200, this.opts.snapshot());
354
+ if (req.method === 'POST' && path === '/api/speech') {
355
+ const msg = parse(await readBody(req) ?? '');
356
+ if (!this.opts.speech) { res.writeHead(404).end(); return; }
357
+ if (typeof msg?.text !== 'string') return json(res, 400, { error: 'bad json' });
358
+ return json(res, 200, { units: this.opts.speech(msg.text) });
359
+ }
360
+ if (req.method === 'GET' && path === '/api/looks') return json(res, 200, this.opts.looks());
361
+ if (req.method === 'POST' && path === '/api/looks') {
362
+ const msg = parse(await readBody(req) ?? '');
363
+ if (!Array.isArray(msg?.looks)) return json(res, 400, { error: 'bad json' });
364
+ this.opts.onLooks(msg.looks);
365
+ return json(res, 200, this.opts.looks());
366
+ }
367
+ if (req.method === 'POST' && (path === '/api/skin' || path === '/api/prefs')) {
368
+ const body = await readBody(req);
369
+ const msg = body ? parse(body) : null;
370
+ if (!msg) return json(res, 400, { error: 'bad json' });
371
+ if (path === '/api/skin') this.opts.onSkin(msg.skin, msg.scale);
372
+ else this.opts.onPrefs(msg);
373
+ return json(res, 200, { ok: true });
374
+ }
375
+ if (req.method !== 'GET') { res.writeHead(405).end(); return; }
376
+ if (path === '/') { res.writeHead(302, { location: '/pet' }).end(); return; }
377
+ if (path === '/overlay') {
378
+ if (!this.overlayEnabled) { res.writeHead(404).end(); return; }
379
+ return this.sendPage(res, join(this.opts.webDir, 'overlay.html'));
380
+ }
381
+ const file = PAGES[path] ?? (path.startsWith('/web/') ? path.slice(5) : null);
382
+ if (!file) { res.writeHead(404).end(); return; }
383
+ const root = normalize(this.opts.webDir).replace(/[\\/]+$/, '') + sep;
384
+ const full = normalize(join(root, file));
385
+ if (!full.startsWith(root)) { res.writeHead(403).end(); return; }
386
+ if (PAGES[path]) return this.sendPage(res, full);
387
+ return this.sendFile(res, full, null, path.startsWith('/web/') && req.headers.origin === 'null');
388
+ }
389
+
390
+ /** A page, its `<html lang>` set to the app language (`zh` as `zh-CN`). */
391
+ private async sendPage(res: ServerResponse, full: string): Promise<void> {
392
+ const lang = languageTag(this.opts.language?.() ?? 'zh');
393
+ try {
394
+ const html = readTextFile(full).replace(/<html lang="[^"]*"/, `<html lang="${lang}"`);
395
+ res.writeHead(200, { 'content-type': MIME['.html'], 'cache-control': 'no-cache', 'content-security-policy': PAGE_CSP });
396
+ res.end(html);
397
+ } catch {
398
+ res.writeHead(404).end();
399
+ }
400
+ }
401
+
402
+ private async importRequest(req: IncomingMessage, res: ServerResponse, path: string, importer: PackImporter): Promise<void> {
403
+ if (path === '/api/figures/import') {
404
+ const type = (req.headers['content-type'] ?? '').split(';')[0]!.trim();
405
+ if (type !== 'application/zip' && type !== BUNDLE_TYPE) return json(res, 415, { error: this.t.importing.zipOrFolder });
406
+ const bytes = await readBytes(req);
407
+ if (!bytes) return json(res, 400, { error: this.t.importing.truncated });
408
+ const files = type === BUNDLE_TYPE ? filesFromBundle(bytes, this.t.importing) : filesFromZip(bytes, this.t.importing);
409
+ if (typeof files === 'string') return json(res, 400, { error: files });
410
+ const out = await importer.stage(files, type === BUNDLE_TYPE);
411
+ return json(res, 'error' in out ? 400 : 200, out);
412
+ }
413
+ const body = await readBody(req);
414
+ const msg = body ? parse(body) : null;
415
+ if (path === '/api/figures/import/install' && msg && typeof msg.token === 'string' && Array.isArray(msg.dirs)) {
416
+ const replace = Array.isArray(msg.replace) ? msg.replace.filter((id): id is string => typeof id === 'string') : [];
417
+ const out = await importer.install(msg.token, msg.dirs.filter((d): d is string => typeof d === 'string'), replace);
418
+ return json(res, 'error' in out ? 400 : 'conflicts' in out ? 409 : 200, out);
419
+ }
420
+ if (path === '/api/figures/import/cancel') { await importer.cancel(); return json(res, 200, { ok: true }); }
421
+ return json(res, 400, { error: 'bad request' });
422
+ }
423
+
424
+ /** A file with the pages' CSP (or `csp`); `frame` answers the figure frame's CORS request. */
425
+ private async sendFile(res: ServerResponse, full: string, csp: string | null, frame = false): Promise<void> {
426
+ try {
427
+ const bytes = await readFile(full);
428
+ res.writeHead(200, {
429
+ 'content-type': MIME[extname(full)] ?? 'application/octet-stream',
430
+ 'cache-control': 'no-cache',
431
+ 'content-security-policy': csp ?? PAGE_CSP,
432
+ 'x-content-type-options': 'nosniff',
433
+ ...(frame ? { 'access-control-allow-origin': 'null' } : {}),
434
+ });
435
+ res.end(bytes);
436
+ } catch {
437
+ res.writeHead(404).end();
438
+ }
439
+ }
440
+ }
441
+
442
+ function parse(text: string): PageMessage | null {
443
+ try {
444
+ const v = JSON.parse(text) as unknown;
445
+ return v && typeof v === 'object' && !Array.isArray(v) ? (v as PageMessage) : null;
446
+ } catch {
447
+ return null;
448
+ }
449
+ }
450
+
451
+ function json(res: ServerResponse, status: number, body: unknown): void {
452
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
453
+ res.end(JSON.stringify(body));
454
+ }
455
+
456
+ /** The body of `req`, or null when it is longer than `max` bytes or breaks off. */
457
+ function readBytes(req: IncomingMessage): Promise<Uint8Array | null> {
458
+ return new Promise((done) => {
459
+ const chunks: Buffer[] = [];
460
+ req.on('data', (c: Buffer) => chunks.push(c));
461
+ req.on('end', () => done(Buffer.concat(chunks)));
462
+ req.on('error', () => done(null));
463
+ });
464
+ }
465
+
466
+ const MAX_BODY = 64 * 1024;
467
+ function readBody(req: IncomingMessage): Promise<string | null> {
468
+ return new Promise((done) => {
469
+ let size = 0;
470
+ const chunks: Buffer[] = [];
471
+ req.on('data', (c: Buffer) => {
472
+ size += c.length;
473
+ if (size > MAX_BODY) { req.destroy(); done(null); return; }
474
+ chunks.push(c);
475
+ });
476
+ req.on('end', () => done(Buffer.concat(chunks).toString('utf8')));
477
+ req.on('error', () => done(null));
478
+ });
479
+ }
@@ -0,0 +1,33 @@
1
+ Copyright (C) 1993-2015 Carnegie Mellon University. All rights reserved.
2
+
3
+ Redistribution and use in source and binary forms, with or without
4
+ modification, are permitted provided that the following conditions
5
+ are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright
8
+ notice, this list of conditions and the following disclaimer.
9
+ The contents of this file are deemed to be source code.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright
12
+ notice, this list of conditions and the following disclaimer in
13
+ the documentation and/or other materials provided with the
14
+ distribution.
15
+
16
+ This work was supported in part by funding from the Defense Advanced
17
+ Research Projects Agency, the Office of Naval Research and the National
18
+ Science Foundation of the United States of America, and by member
19
+ companies of the Carnegie Mellon Sphinx Speech Consortium. We acknowledge
20
+ the contributions of many volunteers to the expansion and improvement of
21
+ this dictionary.
22
+
23
+ THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
24
+ ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
25
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
27
+ NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,71 @@
1
+ Copyright 2000, 2001, 2002, 2003 Nara Institute of Science
2
+ and Technology. All Rights Reserved.
3
+
4
+ Use, reproduction, and distribution of this software is permitted.
5
+ Any copy of this software, whether in its original form or modified,
6
+ must include both the above copyright notice and the following
7
+ paragraphs.
8
+
9
+ Nara Institute of Science and Technology (NAIST),
10
+ the copyright holders, disclaims all warranties with regard to this
11
+ software, including all implied warranties of merchantability and
12
+ fitness, in no event shall NAIST be liable for
13
+ any special, indirect or consequential damages or any damages
14
+ whatsoever resulting from loss of use, data or profits, whether in an
15
+ action of contract, negligence or other tortuous action, arising out
16
+ of or in connection with the use or performance of this software.
17
+
18
+ A large portion of the dictionary entries
19
+ originate from ICOT Free Software. The following conditions for ICOT
20
+ Free Software applies to the current dictionary as well.
21
+
22
+ Each User may also freely distribute the Program, whether in its
23
+ original form or modified, to any third party or parties, PROVIDED
24
+ that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear
25
+ on, or be attached to, the Program, which is distributed substantially
26
+ in the same form as set out herein and that such intended
27
+ distribution, if actually made, will neither violate or otherwise
28
+ contravene any of the laws and regulations of the countries having
29
+ jurisdiction over the User or the intended distribution itself.
30
+
31
+ NO WARRANTY
32
+
33
+ The program was produced on an experimental basis in the course of the
34
+ research and development conducted during the project and is provided
35
+ to users as so produced on an experimental basis. Accordingly, the
36
+ program is provided without any warranty whatsoever, whether express,
37
+ implied, statutory or otherwise. The term "warranty" used herein
38
+ includes, but is not limited to, any warranty of the quality,
39
+ performance, merchantability and fitness for a particular purpose of
40
+ the program and the nonexistence of any infringement or violation of
41
+ any right of any third party.
42
+
43
+ Each user of the program will agree and understand, and be deemed to
44
+ have agreed and understood, that there is no warranty whatsoever for
45
+ the program and, accordingly, the entire risk arising from or
46
+ otherwise connected with the program is assumed by the user.
47
+
48
+ Therefore, neither ICOT, the copyright holder, or any other
49
+ organization that participated in or was otherwise related to the
50
+ development of the program and their respective officials, directors,
51
+ officers and other employees shall be held liable for any and all
52
+ damages, including, without limitation, general, special, incidental
53
+ and consequential damages, arising out of or otherwise in connection
54
+ with the use or inability to use the program or any product, material
55
+ or result produced or otherwise obtained by using the program,
56
+ regardless of whether they have been advised of, or otherwise had
57
+ knowledge of, the possibility of such damages at any time during the
58
+ project or thereafter. Each user will be deemed to have agreed to the
59
+ foregoing by his or her commencement of use of the program. The term
60
+ "use" as used herein includes, but is not limited to, the use,
61
+ modification, copying and distribution of the program and the
62
+ production of secondary products from the program.
63
+
64
+ In the case where the program, whether in its original form or
65
+ modified, was distributed or delivered to or received by a user from
66
+ any person, organization or entity other than ICOT, unless it makes or
67
+ grants independently of ICOT any specific warranty to the user in
68
+ writing, such person, organization or entity, will also be exempted
69
+ from and not be held liable to the user for any such damages as noted
70
+ above as far as the program is concerned.
71
+ ��
@@ -0,0 +1,39 @@
1
+ UNICODE LICENSE V3
2
+
3
+ COPYRIGHT AND PERMISSION NOTICE
4
+
5
+ Copyright © 1991-2026 Unicode, Inc.
6
+
7
+ NOTICE TO USER: Carefully read the following legal agreement. BY
8
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of data files and any associated documentation (the "Data Files") or
15
+ software and any associated documentation (the "Software") to deal in the
16
+ Data Files or Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
18
+ copies of the Data Files or Software, and to permit persons to whom the
19
+ Data Files or Software are furnished to do so, provided that either (a)
20
+ this copyright and permission notice appear with all copies of the Data
21
+ Files or Software, or (b) this copyright and permission notice appear in
22
+ associated Documentation.
23
+
24
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27
+ THIRD PARTY RIGHTS.
28
+
29
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34
+ FILES OR SOFTWARE.
35
+
36
+ Except as contained in this notice, the name of a copyright holder shall
37
+ not be used in advertising or otherwise to promote the sale, use or other
38
+ dealings in these Data Files or Software without prior written
39
+ authorization of the copyright holder.
Binary file
Binary file
Binary file