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/packs.ts ADDED
@@ -0,0 +1,449 @@
1
+ /**
2
+ * Figure packs: the pet's body, as a directory with a `figure.json` manifest. Coo is one, built in
3
+ * (`web/coo/`), and so is the whale maid (`web/whale/`).
4
+ *
5
+ * A pack's code runs only inside the sandboxed figure frame (`web/figure-frame.html`): an opaque
6
+ * origin that may fetch only its own pack's files (an installed pack's), talking to the pet page by `postMessage` alone. The body there is
7
+ * the pack's own (walking, falling, faces, drawing; most packs build it on the kit, `web/kit/body.js`).
8
+ * What the World and the pages need without running it is in the manifest: names, the dress-up axes
9
+ * and presets, what the bot is told the body looks like, the words it does (`vocab`, the whole of the
10
+ * bot's vocabulary while it is on), its own sound files and voice, whether it walks, the targets of its own
11
+ * `speed_pet_move_to` takes (`moves`), the data about the desktop it asks the window for (`needs`), how far its
12
+ * effects reach past its box (`effects`) and its bubbles' colours (`bubble`).
13
+ *
14
+ * The embedding app names directories whose subdirectories are more packs (`packRoots`). A built-in
15
+ * id wins over an installed pack with the same id, and `coo` is only ever the built-in one.
16
+ *
17
+ * `skin.figure` is the pack id, `skin.scheme` the picked option of each axis joined by `-` in the
18
+ * manifest's axis order (one axis: the option id), or a preset id. Coo keeps its picks in the skin's
19
+ * own fields, one per axis (`lookOf`, `lookPatch`).
20
+ */
21
+ import { existsSync, readdirSync } from 'node:fs';
22
+ import { extname, join, normalize, sep } from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+ import type { Language } from 'cortico/core/language.ts';
25
+ import { readTextFile } from 'cortico/core/util.ts';
26
+ import type { ModelLanguage } from './model-text.ts';
27
+ import { INLINE_TAG_MAX, type VocabWord } from './script.ts';
28
+ import { petText, type PetText } from './i18n/index.ts';
29
+
30
+ type PackText = PetText['packs'];
31
+
32
+ export const MANIFEST_FILE = 'figure.json';
33
+ /**
34
+ * The manifest version this World reads packs as, and the figure frame's contract (`web/figure-frame.js`).
35
+ * A pack made for an older version keeps loading (README, 形象包兼容承诺): the version that replaces one of
36
+ * these brings the older manifest up to it in `readManifest` and keeps running the older contract in the frame.
37
+ * The oldest ones are where that promise starts; they never go up.
38
+ */
39
+ export const MANIFEST_VERSION = 2;
40
+ export const FIGURE_API = 2;
41
+ export const MANIFEST_OLDEST = 2;
42
+ export const FIGURE_API_OLDEST = 2;
43
+ /** The built-in body, and the one shown when the skin names a pack that is not there. */
44
+ export const COO = 'coo';
45
+ /** Kinds a pack's own sounds are filed under, as web/sound.js mutes them (BODY_SOUND_KINDS). */
46
+ export const PACK_SOUND_KINDS = ['move', 'touch', 'face', 'snore', 'talk'] as const;
47
+ /** How a sound asked for while its last play has not ended plays (`repeat`, web/sound.js): over it, after fading it out, or not at all. */
48
+ export const SOUND_REPEATS = ['overlap', 'restart', 'finish'] as const;
49
+ /** Data about the desktop a pack may ask for: `windows`, the windows on the pet's display and their visible top edges. */
50
+ export const PACK_NEEDS = ['windows'] as const;
51
+ /** The range of `voice.pitch`, and of `effects.reach` in 256-unit squares. */
52
+ export const VOICE_PITCH = { min: .5, max: 2 } as const;
53
+ export const EFFECTS_REACH_MAX = 2;
54
+ /** Most targets a pack declares, and most numbers one of them takes. */
55
+ export const MOVES_MAX = 8;
56
+ export const MOVE_PARAMS_MAX = 2;
57
+ /** What `speed_pet_move_to` takes as a target of its own; a pack's target cannot be one of these or a number. */
58
+ export const DEFAULT_TARGETS = ['left', 'center', 'right', 'cursor'] as const;
59
+ /** Audio files every platform's Chromium decodes. */
60
+ const AUDIO = new Set(['.ogg', '.mp3', '.wav']);
61
+
62
+ const ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
63
+ /** Option ids are joined with `-` into `skin.scheme`, so they cannot hold one. */
64
+ const OPTION_ID = /^[a-z0-9]{1,24}$/;
65
+
66
+ export type Names = Record<string, string>;
67
+
68
+ export interface FigureAxis {
69
+ id: string;
70
+ name: Names;
71
+ options: Array<{ id: string; name: Names; thumb?: string; accent?: string }>;
72
+ }
73
+
74
+ /** The settings window's colours for a preset, see core/console-theme.ts in Coopanion. */
75
+ export interface ConsoleHues { a: string; a2: string; on: string; t: string; c3: string; c4: string }
76
+
77
+ export interface FigurePreset {
78
+ id: string;
79
+ /** The option of each axis. */
80
+ pick: Record<string, string>;
81
+ name?: Names;
82
+ /** Colours the sleep z's and the listening and thinking marks. */
83
+ accent?: string;
84
+ console?: { light: ConsoleHues; dark: ConsoleHues };
85
+ /** The bubbles' colours while this preset is on, over the pack's own. */
86
+ bubble?: BubbleTheme;
87
+ }
88
+
89
+ /** A bubble's colours (hex): its fill, its text, and its outline with the tail. */
90
+ export interface BubbleColors { fill: string; text: string; line: string }
91
+ /** The bot's bubbles in each of the pet's themes; the lines the person said keep the page's. */
92
+ export interface BubbleTheme { light: BubbleColors; dark: BubbleColors }
93
+
94
+ /** How the body talks: `pitch` scales the page's babble and the speed its own `talk` sounds play at. */
95
+ export interface PackVoice { pitch: number }
96
+
97
+ export interface PackSound {
98
+ /** Relative to the pack. */
99
+ file: string;
100
+ kind: typeof PACK_SOUND_KINDS[number];
101
+ /** 0–1, times the page's volume. */
102
+ volume: number;
103
+ /** Absent: `overlap`. Never on a `talk` sound, whose syllables always overlap. */
104
+ repeat?: Exclude<typeof SOUND_REPEATS[number], 'overlap'>;
105
+ }
106
+
107
+ /** A number a pack's target takes: `speed_pet_move_to` refuses one outside min–max. */
108
+ export interface MoveParam {
109
+ id: string;
110
+ /** What it sets, for the bot, by language. */
111
+ about: Names;
112
+ min: number;
113
+ max: number;
114
+ }
115
+
116
+ /** A target of the pack's own for `speed_pet_move_to`; the World checks the call against it and the body does the rest. */
117
+ export interface MoveTarget {
118
+ id: string;
119
+ name: Names;
120
+ /** Where it goes and how, for the bot, by language. */
121
+ about: Names;
122
+ params: MoveParam[];
123
+ }
124
+
125
+ export interface FigureManifest {
126
+ manifest: number;
127
+ api: number;
128
+ id: string;
129
+ version: string;
130
+ name: Names;
131
+ /** What the body looks like, for the bot's prompt, by language. */
132
+ about: Names;
133
+ author?: string;
134
+ license?: string;
135
+ credits?: Array<{ role: string; name: string; url?: string }>;
136
+ /** The module the frame imports, relative to the pack, and the factory it exports. */
137
+ entry: string;
138
+ export: string;
139
+ /** JSON handed to the factory as `opts.model`, relative to the pack. */
140
+ model?: string;
141
+ thumb?: string;
142
+ axes: FigureAxis[];
143
+ presets: FigurePreset[];
144
+ /** The words the bot may use while this body is on: every expression and motion it does. */
145
+ vocab: VocabWord[];
146
+ /** Its own sound files by name; the body asks for them, the page plays them. */
147
+ sounds: Record<string, PackSound>;
148
+ /** `walk`: whether it walks to the default targets of `speed_pet_move_to`. */
149
+ can: { walk: boolean };
150
+ moves: MoveTarget[];
151
+ /** What the page passes its body beyond the stage's size (`host.bounds()`); the window reads none of it for a pack that does not ask. */
152
+ needs: Array<typeof PACK_NEEDS[number]>;
153
+ voice: PackVoice;
154
+ /** `reach`: how far past the body's box its effects are drawn, in 256-unit squares at its scale, each side. */
155
+ effects: { reach: number };
156
+ bubble?: BubbleTheme;
157
+ }
158
+
159
+ export interface FigurePack {
160
+ id: string;
161
+ dir: string;
162
+ /** URL path the pages load the pack's files from, ending in `/`. */
163
+ base: string;
164
+ builtin: boolean;
165
+ manifest: FigureManifest;
166
+ }
167
+
168
+ const namesOf = (v: unknown): Names | null => {
169
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return null;
170
+ const out: Names = {};
171
+ for (const [k, s] of Object.entries(v)) if (typeof s === 'string' && s.trim()) out[k] = s.trim();
172
+ return Object.keys(out).length ? out : null;
173
+ };
174
+ /** A path inside the pack: relative, no `..`, none of `<>"` or a control character (no Windows file name holds them). */
175
+ const inside = (p: unknown): p is string => typeof p === 'string' && p !== '' && !p.startsWith('/') && !p.split(/[\\/]/).includes('..') && !/^[a-z]+:/i.test(p)
176
+ && !/[<>"\x00-\x1f]/.test(p);
177
+ /** Characters that end a word in a script's markers (script.ts): a name holding one could never be written. */
178
+ const NAME_BREAK = /[,,、\s【】<><>]/;
179
+ const WORD_KINDS = new Set(['expression', 'motion']);
180
+ const SOUND_NAME = /^[a-z][a-zA-Z0-9-]{0,31}$/;
181
+ const PARAM_ID = /^[a-z][a-zA-Z0-9]{0,23}$/;
182
+ const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
183
+
184
+ /** `raw` as bubble colours, or undefined when it is not one whole set of hex colours per theme (left out, as a bad accent is). */
185
+ function bubbleOf(raw: unknown): BubbleTheme | undefined {
186
+ const theme = (v: unknown): BubbleColors | null => {
187
+ const c = v as Record<string, unknown> | null;
188
+ return c && typeof c === 'object' && [c.fill, c.text, c.line].every((h) => typeof h === 'string' && HEX.test(h))
189
+ ? { fill: c.fill as string, text: c.text as string, line: c.line as string } : null;
190
+ };
191
+ const r = raw as Record<string, unknown> | null;
192
+ const light = theme(r?.light), dark = theme(r?.dark);
193
+ return light && dark ? { light, dark } : undefined;
194
+ }
195
+ /** A number in [min, max], else `fallback`. */
196
+ const within = (v: unknown, min: number, max: number, fallback: number) => (typeof v === 'number' && v >= min && v <= max ? v : fallback);
197
+
198
+ /** The vocabulary in `raw`, checked; a string says what is wrong with it. A word of a kind this version does not know is left out and named in `skipped`. */
199
+ function readVocab(raw: unknown, skipped: string[], t: PackText): VocabWord[] | string {
200
+ if (!Array.isArray(raw)) return t.vocabNotArray;
201
+ const out: VocabWord[] = [];
202
+ const taken = new Set<string>();
203
+ for (const w of raw as Array<Record<string, unknown>>) {
204
+ const id = w?.id;
205
+ if (typeof id !== 'string' || !ID.test(id)) return t.badWordId(JSON.stringify(id));
206
+ if (!WORD_KINDS.has(w.kind as string)) { skipped.push(t.unknownKind(id, JSON.stringify(w.kind))); continue; }
207
+ const names: Record<string, string[]> = {};
208
+ for (const [lang, list] of Object.entries((w.names ?? {}) as Record<string, unknown>)) {
209
+ if (!Array.isArray(list)) return t.namesNotArray(id, lang);
210
+ for (const n of list) {
211
+ // longer than an inline marker holds, a name would be read as text there
212
+ if (typeof n !== 'string' || !n.trim() || n.length > INLINE_TAG_MAX || NAME_BREAK.test(n)) return t.badWordName(id, JSON.stringify(n));
213
+ }
214
+ names[lang] = list as string[];
215
+ }
216
+ for (const n of [id, ...Object.values(names).flat()]) {
217
+ if (taken.has(n)) return t.nameTaken(n);
218
+ taken.add(n);
219
+ }
220
+ const about = namesOf(w.about);
221
+ if (!about) return t.noWordAbout(id);
222
+ if (typeof w.seconds !== 'number' || !(w.seconds > 0) || !Number.isFinite(w.seconds)) return t.badSeconds(id);
223
+ out.push({ id, kind: w.kind as VocabWord['kind'], names, about, seconds: w.seconds, ...(w.lasting === true ? { lasting: true } : {}) });
224
+ }
225
+ return out;
226
+ }
227
+
228
+ /**
229
+ * The sounds in `raw`, checked; a string says what is wrong with them. A sound whose file is not there, or
230
+ * whose file type or kind this version does not know, is left out and named in `skipped`; a `repeat` it does
231
+ * not know is named there and the sound plays as `overlap`.
232
+ */
233
+ function readSounds(raw: unknown, dir: string, skipped: string[], t: PackText): Record<string, PackSound> | string {
234
+ if (raw === undefined) return {};
235
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return t.soundsNotObject;
236
+ const out: Record<string, PackSound> = {};
237
+ for (const [name, d] of Object.entries(raw as Record<string, Record<string, unknown>>)) {
238
+ if (!SOUND_NAME.test(name)) return t.badSoundName(JSON.stringify(name));
239
+ if (!inside(d?.file)) return t.badSoundFile(name);
240
+ if (d.volume !== undefined && (typeof d.volume !== 'number' || !(d.volume >= 0 && d.volume <= 1))) return t.badVolume(name);
241
+ if (!AUDIO.has(extname(d.file).toLowerCase())) { skipped.push(t.soundType(name, d.file)); continue; }
242
+ if (!PACK_SOUND_KINDS.includes(d.kind as PackSound['kind'])) { skipped.push(t.soundKind(name, JSON.stringify(d.kind), PACK_SOUND_KINDS)); continue; }
243
+ if (!existsSync(join(dir, d.file))) { skipped.push(t.soundMissing(name, d.file)); continue; }
244
+ let repeat: PackSound['repeat'];
245
+ if (d.kind !== 'talk' && d.repeat !== undefined) {
246
+ if (!(SOUND_REPEATS as readonly unknown[]).includes(d.repeat)) skipped.push(t.soundRepeat(name, JSON.stringify(d.repeat), SOUND_REPEATS));
247
+ else if (d.repeat !== 'overlap') repeat = d.repeat as PackSound['repeat'];
248
+ }
249
+ out[name] = { file: d.file, kind: d.kind as PackSound['kind'], volume: (d.volume as number | undefined) ?? 1, ...(repeat ? { repeat } : {}) };
250
+ }
251
+ return out;
252
+ }
253
+
254
+ /** The targets in `raw`, checked; a string says what is wrong with them. */
255
+ function readMoves(raw: unknown, t: PackText): MoveTarget[] | string {
256
+ if (raw === undefined) return [];
257
+ if (!Array.isArray(raw)) return t.movesNotArray;
258
+ if (raw.length > MOVES_MAX) return t.tooManyMoves(MOVES_MAX);
259
+ const out: MoveTarget[] = [];
260
+ for (const m of raw as Array<Record<string, unknown>>) {
261
+ const id = m?.id;
262
+ if (typeof id !== 'string' || !ID.test(id) || (DEFAULT_TARGETS as readonly string[]).includes(id) || Number.isFinite(Number(id))) return t.badMoveId(JSON.stringify(id));
263
+ if (out.some((o) => o.id === id)) return t.moveTaken(id);
264
+ const name = namesOf(m.name), about = namesOf(m.about);
265
+ if (!name || !about) return t.noMoveText(id);
266
+ const params: MoveParam[] = [];
267
+ const list = m.params ?? [];
268
+ if (!Array.isArray(list) || list.length > MOVE_PARAMS_MAX) return t.badMoveParams(id, MOVE_PARAMS_MAX);
269
+ for (const p of list as Array<Record<string, unknown>>) {
270
+ const pa = namesOf(p?.about);
271
+ if (typeof p?.id !== 'string' || !PARAM_ID.test(p.id) || params.some((q) => q.id === p.id) || !pa
272
+ || typeof p.min !== 'number' || typeof p.max !== 'number' || !Number.isFinite(p.min) || !Number.isFinite(p.max) || !(p.min < p.max)) return t.badMoveParams(id, MOVE_PARAMS_MAX);
273
+ params.push({ id: p.id, about: pa, min: p.min, max: p.max });
274
+ }
275
+ out.push({ id, name, about, params });
276
+ }
277
+ return out;
278
+ }
279
+
280
+ /** The data asked for in `raw`, checked; what this version does not provide is left out and named in `skipped`. */
281
+ function readNeeds(raw: unknown, skipped: string[], t: PackText): FigureManifest['needs'] | string {
282
+ if (raw === undefined) return [];
283
+ if (!Array.isArray(raw)) return t.needsNotArray;
284
+ const out: FigureManifest['needs'] = [];
285
+ for (const n of raw) {
286
+ if ((PACK_NEEDS as readonly unknown[]).includes(n)) { if (!out.includes(n)) out.push(n); } else skipped.push(t.unknownNeed(JSON.stringify(n)));
287
+ }
288
+ return out;
289
+ }
290
+
291
+ /**
292
+ * The manifest at `dir`, checked; a string says what is wrong with it. `builtin`: one of the package's own
293
+ * (only those may be `coo`). What a newer version may add, and this one does not know (a word's kind, a sound's
294
+ * kind, repeat or file type, a value of `can` or `needs`), is left out and named in `skipped` with the sound files that are not
295
+ * there; the pack loads without it. Unknown fields are not read at all. What is wrong is said in the words of `t`.
296
+ */
297
+ export function readManifest(dir: string, builtin = false, skipped: string[] = [], t: PackText = petText().packs): FigureManifest | string {
298
+ const file = join(dir, MANIFEST_FILE);
299
+ if (!existsSync(file)) return t.noManifest(MANIFEST_FILE);
300
+ let raw: Record<string, unknown>;
301
+ try { raw = JSON.parse(readTextFile(file)) as Record<string, unknown>; } catch (err) { return t.badJson(MANIFEST_FILE, (err as Error).message); }
302
+ for (const [key, oldest, now] of [['manifest', MANIFEST_OLDEST, MANIFEST_VERSION], ['api', FIGURE_API_OLDEST, FIGURE_API]] as const) {
303
+ const v = raw[key];
304
+ if (typeof v !== 'number' || !Number.isInteger(v)) return t.notInteger(key, JSON.stringify(v));
305
+ if (v > now) return t.tooNew(key, v, now);
306
+ if (v < oldest) return t.tooOld(key, v, oldest);
307
+ }
308
+ if (typeof raw.id !== 'string' || !ID.test(raw.id) || (raw.id === COO && !builtin)) return t.badId(JSON.stringify(raw.id));
309
+ const name = namesOf(raw.name), about = namesOf(raw.about);
310
+ if (!name) return t.noName;
311
+ if (!about) return t.noAbout;
312
+ if (!inside(raw.entry) || typeof raw.export !== 'string' || !raw.export) return t.badEntry;
313
+ if (raw.model !== undefined && !inside(raw.model)) return t.badModel;
314
+ if (raw.thumb !== undefined && !inside(raw.thumb)) return t.badThumb;
315
+ const axes: FigureAxis[] = [];
316
+ for (const a of Array.isArray(raw.axes) ? raw.axes as Array<Record<string, unknown>> : []) {
317
+ const an = namesOf(a?.name);
318
+ if (typeof a?.id !== 'string' || !ID.test(a.id) || !an || !Array.isArray(a.options) || !a.options.length) return t.badAxis(JSON.stringify(a?.id));
319
+ const options: FigureAxis['options'] = [];
320
+ for (const o of a.options as Array<Record<string, unknown>>) {
321
+ const on = namesOf(o?.name);
322
+ if (typeof o?.id !== 'string' || !OPTION_ID.test(o.id) || !on || (o.thumb !== undefined && !inside(o.thumb))) return t.badOption(a.id, JSON.stringify(o?.id));
323
+ options.push({ id: o.id, name: on, ...(o.thumb ? { thumb: o.thumb as string } : {}), ...(typeof o.accent === 'string' ? { accent: o.accent } : {}) });
324
+ }
325
+ axes.push({ id: a.id, name: an, options });
326
+ }
327
+ const presets: FigurePreset[] = [];
328
+ for (const p of Array.isArray(raw.presets) ? raw.presets as Array<Record<string, unknown>> : []) {
329
+ const pick = p?.pick as Record<string, unknown> | undefined;
330
+ if (typeof p?.id !== 'string' || !ID.test(p.id) || !pick || typeof pick !== 'object') return t.badPreset(JSON.stringify(p?.id));
331
+ for (const a of axes) if (!a.options.some((o) => o.id === pick[a.id])) return t.presetMissing(p.id, a.id);
332
+ presets.push({
333
+ id: p.id, pick: Object.fromEntries(axes.map((a) => [a.id, pick[a.id] as string])),
334
+ ...(namesOf(p.name) ? { name: namesOf(p.name)! } : {}),
335
+ ...(typeof p.accent === 'string' ? { accent: p.accent } : {}),
336
+ ...(p.console && typeof p.console === 'object' ? { console: p.console as FigurePreset['console'] } : {}),
337
+ ...(bubbleOf(p.bubble) ? { bubble: bubbleOf(p.bubble)! } : {}),
338
+ });
339
+ }
340
+ const vocab = readVocab(raw.vocab, skipped, t);
341
+ if (typeof vocab === 'string') return vocab;
342
+ const sounds = readSounds(raw.sounds, dir, skipped, t);
343
+ if (typeof sounds === 'string') return sounds;
344
+ const can = (raw.can ?? {}) as Record<string, unknown>;
345
+ if (can.walk !== undefined && typeof can.walk !== 'boolean') skipped.push(t.badWalk(JSON.stringify(can.walk)));
346
+ const moves = readMoves(raw.moves, t);
347
+ if (typeof moves === 'string') return moves;
348
+ const needs = readNeeds(raw.needs, skipped, t);
349
+ if (typeof needs === 'string') return needs;
350
+ const voice = { pitch: within((raw.voice as Record<string, unknown> | undefined)?.pitch, VOICE_PITCH.min, VOICE_PITCH.max, 1) };
351
+ const effects = { reach: within((raw.effects as Record<string, unknown> | undefined)?.reach, 0, EFFECTS_REACH_MAX, 0) };
352
+ const bubble = bubbleOf(raw.bubble);
353
+ return {
354
+ manifest: MANIFEST_VERSION, api: raw.api as number, id: raw.id, version: typeof raw.version === 'string' ? raw.version : '0.0.0',
355
+ name, about, entry: raw.entry, export: raw.export, axes, presets, vocab, sounds, can: { walk: can.walk !== false }, moves, needs, voice, effects,
356
+ ...(bubble ? { bubble } : {}),
357
+ ...(typeof raw.author === 'string' ? { author: raw.author } : {}),
358
+ ...(typeof raw.license === 'string' ? { license: raw.license } : {}),
359
+ ...(Array.isArray(raw.credits) ? { credits: raw.credits as FigureManifest['credits'] } : {}),
360
+ ...(raw.model ? { model: raw.model as string } : {}),
361
+ ...(raw.thumb ? { thumb: raw.thumb as string } : {}),
362
+ };
363
+ }
364
+
365
+ /** What a scan found wrong in a pack directory: `loaded` false when the pack was left out, true for a part of it left out. */
366
+ export interface PackProblem { dir: string; reason: string; loaded: boolean }
367
+ export interface PackScan { packs: FigurePack[]; problems: PackProblem[] }
368
+
369
+ /** The packs that ship with the World: directory and the URL path the pages load it from. */
370
+ export const BUILTIN_PACKS: ReadonlyArray<{ dir: string; base: string }> = [
371
+ { dir: fileURLToPath(new URL('../web/coo/', import.meta.url)), base: '/web/coo/' },
372
+ { dir: fileURLToPath(new URL('../web/whale/', import.meta.url)), base: '/web/whale/' },
373
+ ];
374
+
375
+ /** The built-in packs and those installed under `roots` (each subdirectory one pack); problems are worded in `language`. */
376
+ export function figurePacks(roots: readonly string[], language: Language = 'zh'): PackScan {
377
+ return scanPacks(BUILTIN_PACKS, roots, petText(language).packs);
378
+ }
379
+
380
+ /**
381
+ * The built-in packs (`builtin`: directory → URL path), then each pack directory under `roots`. An app may
382
+ * ship the World without a built-in pack's directory (the whale's): that pack is not there, and one
383
+ * installed with its id loads in its place.
384
+ */
385
+ export function scanPacks(builtin: ReadonlyArray<{ dir: string; base: string }>, roots: readonly string[], t: PackText = petText().packs): PackScan {
386
+ const packs: FigurePack[] = [];
387
+ const problems: PackProblem[] = [];
388
+ const add = (dir: string, base: (id: string) => string, isBuiltin: boolean) => {
389
+ const skipped: string[] = [];
390
+ const m = readManifest(dir, isBuiltin, skipped, t);
391
+ if (typeof m === 'string') { problems.push({ dir, reason: m, loaded: false }); return; }
392
+ const taken = packs.find((p) => p.id === m.id);
393
+ if (taken) { problems.push({ dir, reason: t.idTaken(m.id, taken.builtin), loaded: false }); return; }
394
+ for (const reason of skipped) problems.push({ dir, reason, loaded: true });
395
+ packs.push({ id: m.id, dir, base: base(m.id), builtin: isBuiltin, manifest: m });
396
+ };
397
+ for (const b of builtin) if (existsSync(b.dir)) add(b.dir, () => b.base, true);
398
+ for (const root of roots) {
399
+ if (!existsSync(root)) continue;
400
+ for (const e of readdirSync(root, { withFileTypes: true })) {
401
+ if (e.isDirectory()) add(join(root, e.name), (id) => `/packs/${id}/`, false);
402
+ }
403
+ }
404
+ return { packs, problems };
405
+ }
406
+
407
+ /** A file of `pack` by its path inside it, or null when the path leaves the pack. */
408
+ export function packFile(pack: FigurePack, path: string): string | null {
409
+ const root = normalize(pack.dir).replace(/[\\/]+$/, '') + sep;
410
+ const full = normalize(join(root, path));
411
+ return full.startsWith(root) ? full : null;
412
+ }
413
+
414
+ /** The name in `language`, else Chinese, else the first one given. */
415
+ export function nameIn(n: Names, language = 'zh'): string {
416
+ return n[language] ?? n.zh ?? Object.values(n)[0] ?? '';
417
+ }
418
+
419
+ /**
420
+ * A name of a figure, axis, option or preset as the bot reads it: in Chinese as `nameIn` gives it,
421
+ * in English the English name, else `id` (what the tools take).
422
+ */
423
+ export function modelName(n: Names | undefined, id: string, language: ModelLanguage): string {
424
+ if (language === 'en') return n?.en ?? id;
425
+ return n ? nameIn(n) : id;
426
+ }
427
+
428
+ /** The pack the skin asks for: the one with `figure`'s id, else Coo (a pack that went away shows as Coo). */
429
+ export function packFor(packs: readonly FigurePack[], figure: string | undefined): FigurePack | null {
430
+ return packs.find((p) => p.id === (figure ?? COO)) ?? packs.find((p) => p.id === COO) ?? null;
431
+ }
432
+
433
+ /** Coo's picks are the skin's own fields named by its axes; another pack's are `skin.scheme`. */
434
+ type SkinLook = { scheme?: string } & object;
435
+
436
+ /** The scheme the skin picks for `pack` (see the top of this file). */
437
+ export function lookOf(pack: FigurePack, skin: SkinLook): string {
438
+ if (pack.id !== COO) return skin.scheme ?? '';
439
+ const fields = skin as Record<string, unknown>;
440
+ return pack.manifest.axes.map((a) => String(fields[a.id] ?? a.options[0]!.id)).join('-');
441
+ }
442
+
443
+ /** The skin fields that pick `scheme` for `pack` (a scheme `pickWords` accepted). */
444
+ export function lookPatch(pack: FigurePack, scheme: string): Record<string, string> {
445
+ if (pack.id !== COO) return { scheme };
446
+ const preset = pack.manifest.presets.find((p) => p.id === scheme);
447
+ const parts = scheme.split('-');
448
+ return Object.fromEntries(pack.manifest.axes.map((a, i) => [a.id, preset ? preset.pick[a.id]! : parts[i]!]));
449
+ }
@@ -0,0 +1,29 @@
1
+ /** Streams one URL to a file, reporting progress; the caller owns the partial-file protocol. */
2
+ import { createWriteStream, mkdirSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ import { Readable, Transform } from 'node:stream';
5
+ import { pipeline } from 'node:stream/promises';
6
+
7
+ export interface DownloadOptions {
8
+ fetchImpl?: typeof fetch;
9
+ onProgress?: (done: number, total: number | null) => void;
10
+ signal?: AbortSignal;
11
+ }
12
+
13
+ export async function downloadFile(url: string, dest: string, options: DownloadOptions = {}): Promise<void> {
14
+ const fetchImpl = options.fetchImpl ?? fetch;
15
+ const res = await fetchImpl(url, { signal: options.signal, redirect: 'follow' });
16
+ if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
17
+ const length = Number(res.headers.get('content-length'));
18
+ const total = Number.isFinite(length) && length > 0 ? length : null;
19
+ let done = 0;
20
+ const counter = new Transform({
21
+ transform(chunk: Buffer, _encoding, callback) {
22
+ done += chunk.length;
23
+ options.onProgress?.(done, total);
24
+ callback(null, chunk);
25
+ },
26
+ });
27
+ mkdirSync(dirname(dest), { recursive: true });
28
+ await pipeline(Readable.fromWeb(res.body as import('node:stream/web').ReadableStream), counter, createWriteStream(dest));
29
+ }