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.
- package/CHANGELOG.md +64 -0
- package/LICENSE +0 -14
- package/README.md +29 -11
- package/THIRD_PARTY_NOTICES.md +69 -0
- package/activity.d.ts +15 -0
- package/activity.js +88 -3
- package/describe.json +806 -0
- package/dist/webui.css +2 -0
- package/dist/webui.css.map +7 -0
- package/dist/webui.js +2 -0
- package/dist/webui.js.map +7 -0
- package/host/app-store.cjs +68 -0
- package/host/cursor.cjs +67 -0
- package/host/electron-main.cjs +666 -0
- package/host/input-shape.cjs +63 -0
- package/host/mouse-lease.cjs +77 -0
- package/host/overlay.cjs +139 -0
- package/host/portrait.cjs +52 -0
- package/host/preload.cjs +60 -14
- package/host/renderer-gone.cjs +24 -0
- package/host/windows.cjs +251 -0
- package/package.json +27 -7
- package/scripts/build-webui.mjs +40 -0
- package/scripts/speech-bank/build.py +166 -0
- package/scripts/speech-bank/dicts.py +76 -0
- package/src/ENV_PROMPT.en.md +51 -0
- package/src/ENV_PROMPT.md +51 -0
- package/src/asr/address.ts +25 -0
- package/src/asr/hotkey.ts +335 -0
- package/src/asr/result.ts +51 -0
- package/src/asr/segmenter.ts +269 -0
- package/src/asr/sherpa.ts +280 -0
- package/src/asr/simplify.ts +38 -0
- package/src/asr/system-recognizer.ts +292 -0
- package/src/asr/system-sapi.ps1 +173 -0
- package/src/asr/transcription-api.ts +176 -0
- package/src/chat.ts +212 -0
- package/src/config.ts +481 -0
- package/src/cua/ENV_PROMPT.en.md +29 -0
- package/src/cua/ENV_PROMPT.md +29 -0
- package/src/cua/config.ts +88 -0
- package/src/cua/cua.ts +712 -0
- package/src/cua/engine/darwin.ts +410 -0
- package/src/cua/engine/display.ts +55 -0
- package/src/cua/engine/fail.ts +15 -0
- package/src/cua/engine/foreground.ts +8 -0
- package/src/cua/engine/image.ts +57 -0
- package/src/cua/engine/keys.ts +70 -0
- package/src/cua/engine/linux-keys.ts +29 -0
- package/src/cua/engine/linux.ts +343 -0
- package/src/cua/engine/mac-keys.ts +57 -0
- package/src/cua/engine/user-activity.ts +54 -0
- package/src/cua/engine/wait-idle.ts +31 -0
- package/src/cua/engine/win32.ts +299 -0
- package/src/cua/engine-child.ts +274 -0
- package/src/cua/engine-ipc.ts +140 -0
- package/src/cua/i18n/de.ts +53 -0
- package/src/cua/i18n/en.ts +63 -0
- package/src/cua/i18n/es-419.ts +53 -0
- package/src/cua/i18n/fr.ts +53 -0
- package/src/cua/i18n/index.ts +26 -0
- package/src/cua/i18n/it.ts +53 -0
- package/src/cua/i18n/ja.ts +53 -0
- package/src/cua/i18n/ko.ts +53 -0
- package/src/cua/i18n/pt-BR.ts +53 -0
- package/src/cua/i18n/ru.ts +59 -0
- package/src/cua/i18n/zh-Hant.ts +53 -0
- package/src/cua/i18n/zh.ts +59 -0
- package/src/cua/model-text.ts +252 -0
- package/src/cua/terminal.ts +31 -0
- package/src/cua/tools.ts +153 -0
- package/src/definition.ts +146 -0
- package/src/host-reason.ts +32 -0
- package/src/i18n/de.ts +409 -0
- package/src/i18n/en.ts +443 -0
- package/src/i18n/es-419.ts +409 -0
- package/src/i18n/fr.ts +409 -0
- package/src/i18n/index.ts +56 -0
- package/src/i18n/it.ts +409 -0
- package/src/i18n/ja.ts +409 -0
- package/src/i18n/ko.ts +409 -0
- package/src/i18n/pt-BR.ts +409 -0
- package/src/i18n/ru.ts +415 -0
- package/src/i18n/zh-Hant.ts +409 -0
- package/src/i18n/zh.ts +440 -0
- package/src/index.ts +15 -0
- package/src/model-text.ts +344 -0
- package/src/moves.ts +101 -0
- package/src/pack-import.ts +361 -0
- package/src/packs.ts +449 -0
- package/src/runtime/download.ts +29 -0
- package/src/runtime/store.ts +293 -0
- package/src/script.ts +202 -0
- package/src/self.ts +247 -0
- package/src/server.ts +479 -0
- package/src/speech/data/CMUDICT-LICENSE +33 -0
- package/src/speech/data/IPADIC-COPYING +71 -0
- package/src/speech/data/UNICODE-LICENSE +39 -0
- package/src/speech/data/en.tsv.gz +0 -0
- package/src/speech/data/ja-ipadic.tsv.gz +0 -0
- package/src/speech/data/ja-unihan.tsv.gz +0 -0
- package/src/speech/data/zh.json +1 -0
- package/src/speech/index.ts +204 -0
- package/src/speech/ipa.ts +83 -0
- package/src/speech/japanese.ts +105 -0
- package/src/speech/jukujikun.ts +22 -0
- package/src/speech/korean.ts +35 -0
- package/src/speech/lang.ts +151 -0
- package/src/speech/rules.ts +72 -0
- package/src/speech/syllable.ts +76 -0
- package/src/status.ts +164 -0
- package/src/tools.ts +110 -0
- package/src/webui/api-rows.css +2 -0
- package/src/webui/api-rows.ts +44 -0
- package/src/webui/client.ts +451 -0
- package/src/webui/dress-dialog.css +14 -0
- package/src/webui/dress-dialog.ts +117 -0
- package/src/webui/dress-panel.ts +160 -0
- package/src/webui/key-capture.ts +60 -0
- package/src/webui/shared/modal.css +13 -0
- package/src/webui/shared/modal.ts +77 -0
- package/src/webui/shared/problem.css +15 -0
- package/src/webui/shared/problem.ts +217 -0
- package/src/webui/shared/strings.ts +5 -0
- package/src/webui/style.css +50 -0
- package/src/window-host.ts +116 -0
- package/src/world.ts +2926 -0
- package/web/activity-motion.js +117 -0
- package/web/appearance.js +60 -0
- package/web/body-host.js +257 -0
- package/web/coo/coo.js +384 -0
- package/web/coo/figure.js +15 -0
- package/web/coo/figure.json +1224 -0
- package/web/dist/dress-dialog.css +1 -0
- package/web/dist/dress-dialog.js +1 -0
- package/web/drag-row.js +49 -0
- package/web/drag.js +149 -0
- package/web/dress.css +170 -0
- package/web/dress.html +37 -0
- package/web/dress.js +786 -0
- package/web/figure-frame.html +16 -0
- package/web/figure-frame.js +128 -0
- package/web/frame-loop.js +55 -0
- package/web/hints.js +77 -0
- package/web/i18n/de.js +170 -0
- package/web/i18n/en.js +177 -0
- package/web/i18n/es-419.js +170 -0
- package/web/i18n/fr.js +170 -0
- package/web/i18n/it.js +170 -0
- package/web/i18n/ja.js +170 -0
- package/web/i18n/ko.js +170 -0
- package/web/i18n/pt-BR.js +170 -0
- package/web/i18n/ru.js +170 -0
- package/web/i18n/zh-Hant.js +170 -0
- package/web/i18n/zh.js +175 -0
- package/web/i18n.js +54 -0
- package/{renderer/vendor → web}/kit/body.js +31 -58
- package/web/looks.js +70 -0
- package/web/mic-worklet.js +36 -0
- package/web/mic.js +117 -0
- package/web/motion-frames.js +80 -0
- package/web/motion-level.js +40 -0
- package/web/new-year-2027.svg +238 -0
- package/web/overlay.html +16 -0
- package/web/overlay.js +100 -0
- package/web/pet-app.js +3000 -0
- package/web/pet.css +642 -0
- package/web/pet.html +21 -0
- package/web/scale-slider.js +259 -0
- package/web/show-hide.js +49 -0
- package/web/sound.js +245 -0
- package/web/speech/zh.json +1 -0
- package/web/speech/zh.ogg +0 -0
- package/web/speech.js +197 -0
- package/web/stage.js +160 -0
- package/web/swap-motion.js +119 -0
- package/web/ui.js +195 -0
- package/host/launch.js +0 -187
- package/host/library.cjs +0 -638
- package/host/main.cjs +0 -389
- package/index.js +0 -93
- package/renderer/index.html +0 -22
- package/renderer/pet-sandbox.html +0 -11
- package/renderer/pet.css +0 -38
- package/renderer/pet.js +0 -251
- package/renderer/vendor/activity-motion.js +0 -101
- package/renderer/vendor/figure-frame.js +0 -115
- package/renderer/vendor/pack.css +0 -2
- /package/{renderer/vendor → web}/kit/rig.js +0 -0
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Managed downloads: the speech models (FunASR's SenseVoiceSmall and Whisper small, int8 in
|
|
3
|
+
* sherpa-onnx's format) and the Electron runtime that hosts the pet window when it runs outside an
|
|
4
|
+
* app. Every artifact is pinned. Files land at `<CORTICO_HOME>/runtimes/<id>/<version>/` and
|
|
5
|
+
* `<CORTICO_HOME>/models/desktop-pet/<model id>/`, are written to `.partial` first and renamed
|
|
6
|
+
* into place when complete; model files are checked against their published SHA-256.
|
|
7
|
+
*
|
|
8
|
+
* A model is fetched from ModelScope first, which answers from mainland China, and from Hugging
|
|
9
|
+
* Face when ModelScope does not; the files are the same (their SHA-256 match).
|
|
10
|
+
*
|
|
11
|
+
* Archives are unpacked with the system `tar` (bsdtar on Windows and macOS reads zip too);
|
|
12
|
+
* Linux zips go through `unzip`.
|
|
13
|
+
*/
|
|
14
|
+
import { spawn } from 'node:child_process';
|
|
15
|
+
import { createHash } from 'node:crypto';
|
|
16
|
+
import { createReadStream, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
|
17
|
+
import { join, resolve } from 'node:path';
|
|
18
|
+
import { downloadFile, type DownloadOptions } from './download.ts';
|
|
19
|
+
import { petText, type PetText } from '../i18n/index.ts';
|
|
20
|
+
|
|
21
|
+
/** The words of the download steps, in the language at the time of each step. */
|
|
22
|
+
type StoreText = () => PetText['store'];
|
|
23
|
+
|
|
24
|
+
export type Phase = 'absent' | 'working' | 'ready' | 'error';
|
|
25
|
+
|
|
26
|
+
export interface ArtifactState {
|
|
27
|
+
phase: Phase;
|
|
28
|
+
/** Where the artifact lives (a directory for runtimes, a file for models). */
|
|
29
|
+
path: string;
|
|
30
|
+
done: number;
|
|
31
|
+
total: number | null;
|
|
32
|
+
detail: string | null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const platformKey = (): string => `${process.platform}-${process.arch}`;
|
|
36
|
+
|
|
37
|
+
/** A model: its files with their sizes and SHA-256, and where to fetch them from, in order. */
|
|
38
|
+
export interface ModelSpec {
|
|
39
|
+
id: string;
|
|
40
|
+
/** `role` is what the recognizer loads the file as (`src/asr/sherpa.ts`). */
|
|
41
|
+
files: ReadonlyArray<{ role: string; name: string; bytes: number; sha256: string }>;
|
|
42
|
+
sources: ReadonlyArray<(file: string) => string>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** FunASR's SenseVoiceSmall, int8, as sherpa-onnx loads it (Apache-2.0 export by k2-fsa). */
|
|
46
|
+
export const FUNASR_MODEL: ModelSpec = {
|
|
47
|
+
id: 'sensevoice-small-int8-2024-07-17',
|
|
48
|
+
files: [
|
|
49
|
+
{ role: 'model', name: 'model.int8.onnx', bytes: 239_233_841, sha256: 'c71f0ce00bec95b07744e116345e33d8cbbe08cef896382cf907bf4b51a2cd51' },
|
|
50
|
+
{ role: 'tokens', name: 'tokens.txt', bytes: 315_894, sha256: 'f449eb28dc567533d7fa59be34e2abca8784f771850c78a47fb731a31429a1dc' },
|
|
51
|
+
],
|
|
52
|
+
/** Tried in order for each file. */
|
|
53
|
+
sources: [
|
|
54
|
+
(file: string) => `https://modelscope.cn/models/pengzhendong/sherpa-onnx-sense-voice-zh-en-ja-ko-yue/resolve/master/${file}`,
|
|
55
|
+
(file: string) => `https://huggingface.co/csukuangfj/sherpa-onnx-sense-voice-zh-en-ja-ko-yue-2024-07-17/resolve/main/${file}`,
|
|
56
|
+
],
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
/** OpenAI's Whisper small, int8, as sherpa-onnx loads it (MIT; export by k2-fsa, uploaded 2024-07-13). */
|
|
60
|
+
export const WHISPER_MODEL: ModelSpec = {
|
|
61
|
+
id: 'whisper-small-int8-2024-07-13',
|
|
62
|
+
files: [
|
|
63
|
+
{ role: 'encoder', name: 'small-encoder.int8.onnx', bytes: 112_442_483, sha256: '4cbe7b22fa9026b843b60a68640c747de05bafb1a11b57edc0e66c232d9f33a9' },
|
|
64
|
+
{ role: 'decoder', name: 'small-decoder.int8.onnx', bytes: 262_226_114, sha256: 'acad50b5c782696e91b55914cc5ab4f756f1532f76e22aa6fc615f39fb69a8ee' },
|
|
65
|
+
{ role: 'tokens', name: 'small-tokens.txt', bytes: 816_730, sha256: 'b34b360dbb493e781e479794586d661700670d65564001f23024971d1f2fa126' },
|
|
66
|
+
],
|
|
67
|
+
sources: [
|
|
68
|
+
(file: string) => `https://modelscope.cn/models/pengzhendong/sherpa-onnx-whisper-small/resolve/master/${file}`,
|
|
69
|
+
(file: string) => `https://huggingface.co/csukuangfj/sherpa-onnx-whisper-small/resolve/main/${file}`,
|
|
70
|
+
],
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export const ELECTRON_RUNTIME = {
|
|
74
|
+
id: 'electron',
|
|
75
|
+
version: '44.4.4',
|
|
76
|
+
assets: {
|
|
77
|
+
'win32-x64': { file: 'electron-v44.4.4-win32-x64.zip', bytes: 158_149_795 },
|
|
78
|
+
'win32-arm64': { file: 'electron-v44.4.4-win32-arm64.zip', bytes: 156_416_869 },
|
|
79
|
+
'darwin-arm64': { file: 'electron-v44.4.4-darwin-arm64.zip', bytes: 130_390_806 },
|
|
80
|
+
'darwin-x64': { file: 'electron-v44.4.4-darwin-x64.zip', bytes: 134_174_708 },
|
|
81
|
+
'linux-x64': { file: 'electron-v44.4.4-linux-x64.zip', bytes: 122_970_570 },
|
|
82
|
+
} as Record<string, { file: string; bytes: number }>,
|
|
83
|
+
url: (file: string) => `https://github.com/electron/electron/releases/download/v44.4.4/${file}`,
|
|
84
|
+
executable: process.platform === 'win32' ? 'electron.exe' : process.platform === 'darwin' ? 'Electron' : 'electron',
|
|
85
|
+
} as const;
|
|
86
|
+
|
|
87
|
+
/** Depth-first search for a file name under `dir`. */
|
|
88
|
+
function findFile(dir: string, name: string, depth = 5): string | null {
|
|
89
|
+
if (!existsSync(dir) || depth < 0) return null;
|
|
90
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
91
|
+
const full = join(dir, entry.name);
|
|
92
|
+
if (entry.isFile() && entry.name === name) return full;
|
|
93
|
+
}
|
|
94
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
95
|
+
if (!entry.isDirectory() || entry.name.endsWith('.partial')) continue;
|
|
96
|
+
const hit = findFile(join(dir, entry.name), name, depth - 1);
|
|
97
|
+
if (hit) return hit;
|
|
98
|
+
}
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function run(cmd: string, args: string[], cwd: string, t: PetText['store']): Promise<void> {
|
|
103
|
+
return new Promise((done, fail) => {
|
|
104
|
+
const child = spawn(cmd, args, { cwd, windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'] });
|
|
105
|
+
let err = '';
|
|
106
|
+
child.stderr.on('data', (d: Buffer) => { err += d.toString(); });
|
|
107
|
+
child.on('error', fail);
|
|
108
|
+
child.on('close', (code) => (code === 0 ? done() : fail(new Error(t.exitCode(cmd, code, err.trim().slice(0, 300))))));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function extract(archive: string, into: string, t: PetText['store'] = petText().store): Promise<void> {
|
|
113
|
+
mkdirSync(into, { recursive: true });
|
|
114
|
+
if (process.platform === 'win32') {
|
|
115
|
+
// bsdtar ships with Windows 10+; GNU tar earlier on PATH (Git's) cannot read zip
|
|
116
|
+
const tar = resolve(process.env.SystemRoot ?? 'C:\\Windows', 'System32', 'tar.exe');
|
|
117
|
+
await run(tar, ['-xf', archive, '-C', into], into, t);
|
|
118
|
+
} else if (archive.endsWith('.zip') && process.platform === 'linux') {
|
|
119
|
+
await run('unzip', ['-q', '-o', archive, '-d', into], into, t);
|
|
120
|
+
} else {
|
|
121
|
+
await run('tar', ['-xf', archive, '-C', into], into, t);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function sha256File(file: string): Promise<string> {
|
|
126
|
+
const hash = createHash('sha256');
|
|
127
|
+
for await (const chunk of createReadStream(file)) hash.update(chunk as Buffer);
|
|
128
|
+
return hash.digest('hex');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
interface Job { state: ArtifactState; promise: Promise<void> | null }
|
|
132
|
+
|
|
133
|
+
/** Tracks one runtime directory: present when its executable is found inside. */
|
|
134
|
+
class RuntimeSlot {
|
|
135
|
+
private job: Job;
|
|
136
|
+
constructor(
|
|
137
|
+
private readonly root: () => string,
|
|
138
|
+
private readonly spec: typeof ELECTRON_RUNTIME,
|
|
139
|
+
private readonly text: StoreText,
|
|
140
|
+
private readonly fetchImpl?: typeof fetch,
|
|
141
|
+
) {
|
|
142
|
+
this.job = { state: { phase: 'absent', path: '', done: 0, total: null, detail: null }, promise: null };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
get dir(): string {
|
|
146
|
+
return join(this.root(), this.spec.id, this.spec.version);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
get supported(): boolean {
|
|
150
|
+
return platformKey() in this.spec.assets;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The executable inside the installed runtime, or null. */
|
|
154
|
+
executable(): string | null {
|
|
155
|
+
if (process.platform === 'darwin' && this.spec.id === 'electron') {
|
|
156
|
+
const app = join(this.dir, 'Electron.app', 'Contents', 'MacOS', 'Electron');
|
|
157
|
+
return existsSync(app) ? app : null;
|
|
158
|
+
}
|
|
159
|
+
return findFile(this.dir, this.spec.executable);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
state(): ArtifactState {
|
|
163
|
+
if (this.job.promise) return { ...this.job.state };
|
|
164
|
+
const exe = this.executable();
|
|
165
|
+
if (exe) return { phase: 'ready', path: this.dir, done: 0, total: null, detail: null };
|
|
166
|
+
return { ...this.job.state, phase: this.job.state.phase === 'error' ? 'error' : 'absent', path: this.dir };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
install(): Promise<void> {
|
|
170
|
+
if (this.job.promise) return this.job.promise;
|
|
171
|
+
const asset = this.spec.assets[platformKey()];
|
|
172
|
+
if (!asset) {
|
|
173
|
+
this.job.state = { phase: 'error', path: this.dir, done: 0, total: null, detail: this.text().noBuild(platformKey()) };
|
|
174
|
+
return Promise.resolve();
|
|
175
|
+
}
|
|
176
|
+
this.job.state = { phase: 'working', path: this.dir, done: 0, total: asset.bytes, detail: this.text().downloading(asset.file) };
|
|
177
|
+
const partial = `${this.dir}.partial`;
|
|
178
|
+
const work = (async () => {
|
|
179
|
+
rmSync(partial, { recursive: true, force: true });
|
|
180
|
+
mkdirSync(partial, { recursive: true });
|
|
181
|
+
const archive = join(partial, asset.file);
|
|
182
|
+
const opts: DownloadOptions = { fetchImpl: this.fetchImpl, onProgress: (done, total) => { this.job.state.done = done; this.job.state.total = total ?? asset.bytes; } };
|
|
183
|
+
await downloadFile(this.spec.url(asset.file), archive, opts);
|
|
184
|
+
this.job.state.detail = this.text().unpacking;
|
|
185
|
+
await extract(archive, partial, this.text());
|
|
186
|
+
rmSync(archive, { force: true });
|
|
187
|
+
writeFileSync(join(partial, 'cortico-runtime.json'), JSON.stringify({ id: this.spec.id, version: this.spec.version, source: this.spec.url(asset.file) }, null, 2));
|
|
188
|
+
rmSync(this.dir, { recursive: true, force: true });
|
|
189
|
+
renameSync(partial, this.dir);
|
|
190
|
+
this.job.state = { phase: 'ready', path: this.dir, done: asset.bytes, total: asset.bytes, detail: null };
|
|
191
|
+
})().catch((err: Error) => {
|
|
192
|
+
rmSync(partial, { recursive: true, force: true });
|
|
193
|
+
this.job.state = { phase: 'error', path: this.dir, done: 0, total: null, detail: err.message };
|
|
194
|
+
}).finally(() => { this.job.promise = null; });
|
|
195
|
+
this.job.promise = work;
|
|
196
|
+
return work;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** A speech model: present when every file is there at its full size. */
|
|
201
|
+
class ModelSlot {
|
|
202
|
+
private job: Job;
|
|
203
|
+
readonly bytes: number;
|
|
204
|
+
constructor(private readonly root: () => string, private readonly spec: ModelSpec, private readonly text: StoreText, private readonly fetchImpl?: typeof fetch) {
|
|
205
|
+
this.bytes = spec.files.reduce((n, f) => n + f.bytes, 0);
|
|
206
|
+
this.job = { state: { phase: 'absent', path: '', done: 0, total: null, detail: null }, promise: null };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
get dir(): string {
|
|
210
|
+
return join(this.root(), this.spec.id);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
file(name: string): string {
|
|
214
|
+
return join(this.dir, name);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** Where each file lives, by role. */
|
|
218
|
+
paths(): Record<string, string> {
|
|
219
|
+
return Object.fromEntries(this.spec.files.map((f) => [f.role, this.file(f.name)]));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private has(f: { name: string; bytes: number }): boolean {
|
|
223
|
+
const path = this.file(f.name);
|
|
224
|
+
return existsSync(path) && statSync(path).size === f.bytes;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
state(): ArtifactState {
|
|
228
|
+
if (this.job.promise) return { ...this.job.state };
|
|
229
|
+
if (this.spec.files.every((f) => this.has(f))) return { phase: 'ready', path: this.dir, done: this.bytes, total: this.bytes, detail: null };
|
|
230
|
+
return { ...this.job.state, phase: this.job.state.phase === 'error' ? 'error' : 'absent', path: this.dir };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
install(): Promise<void> {
|
|
234
|
+
if (this.job.promise) return this.job.promise;
|
|
235
|
+
this.job.state = { phase: 'working', path: this.dir, done: 0, total: this.bytes, detail: this.text().downloadingModel };
|
|
236
|
+
const work = (async () => {
|
|
237
|
+
mkdirSync(this.dir, { recursive: true });
|
|
238
|
+
let before = 0;
|
|
239
|
+
for (const f of this.spec.files) {
|
|
240
|
+
if (this.has(f)) { before += f.bytes; this.job.state.done = before; continue; }
|
|
241
|
+
const partial = `${this.file(f.name)}.partial`;
|
|
242
|
+
const errors: string[] = [];
|
|
243
|
+
for (const source of this.spec.sources) {
|
|
244
|
+
const url = source(f.name);
|
|
245
|
+
try {
|
|
246
|
+
this.job.state.detail = this.text().downloadingFrom(f.name, new URL(url).host);
|
|
247
|
+
await downloadFile(url, partial, { fetchImpl: this.fetchImpl, onProgress: (done) => { this.job.state.done = before + done; } });
|
|
248
|
+
this.job.state.detail = this.text().verifying(f.name);
|
|
249
|
+
const sum = await sha256File(partial);
|
|
250
|
+
if (sum !== f.sha256) throw new Error(this.text().mismatch(sum.slice(0, 12)));
|
|
251
|
+
renameSync(partial, this.file(f.name));
|
|
252
|
+
break;
|
|
253
|
+
} catch (err) {
|
|
254
|
+
rmSync(partial, { force: true });
|
|
255
|
+
errors.push(`${new URL(url).host}: ${(err as Error).message}`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (!this.has(f)) throw new Error(this.text().failed(f.name, errors.join('; ')));
|
|
259
|
+
before += f.bytes;
|
|
260
|
+
this.job.state.done = before;
|
|
261
|
+
}
|
|
262
|
+
this.job.state = { phase: 'ready', path: this.dir, done: this.bytes, total: this.bytes, detail: null };
|
|
263
|
+
})().catch((err: Error) => {
|
|
264
|
+
this.job.state = { phase: 'error', path: this.dir, done: 0, total: null, detail: err.message };
|
|
265
|
+
}).finally(() => { this.job.promise = null; });
|
|
266
|
+
this.job.promise = work;
|
|
267
|
+
return work;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
export interface RuntimeStoreOptions {
|
|
272
|
+
runtimesRoot: () => string;
|
|
273
|
+
modelsDir: () => string;
|
|
274
|
+
fetchImpl?: typeof fetch;
|
|
275
|
+
/** The speech models; tests pass small ones. */
|
|
276
|
+
funasrModel?: ModelSpec;
|
|
277
|
+
whisperModel?: ModelSpec;
|
|
278
|
+
/** The text table of the app language, read at each step; Chinese when absent. */
|
|
279
|
+
text?: () => PetText;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
export class RuntimeStore {
|
|
283
|
+
readonly electron: RuntimeSlot;
|
|
284
|
+
readonly funasr: ModelSlot;
|
|
285
|
+
readonly whisper: ModelSlot;
|
|
286
|
+
|
|
287
|
+
constructor(opts: RuntimeStoreOptions) {
|
|
288
|
+
const text = () => (opts.text?.() ?? petText()).store;
|
|
289
|
+
this.electron = new RuntimeSlot(opts.runtimesRoot, ELECTRON_RUNTIME, text, opts.fetchImpl);
|
|
290
|
+
this.funasr = new ModelSlot(opts.modelsDir, opts.funasrModel ?? FUNASR_MODEL, text, opts.fetchImpl);
|
|
291
|
+
this.whisper = new ModelSlot(opts.modelsDir, opts.whisperModel ?? WHISPER_MODEL, text, opts.fetchImpl);
|
|
292
|
+
}
|
|
293
|
+
}
|
package/src/script.ts
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Speech scripts for the pet's bubble. Markers name expressions and motions:
|
|
3
|
+
*
|
|
4
|
+
* - `【a, b】` blocking: runs the words, then starts a new bubble with the text after it.
|
|
5
|
+
* - `<a, b>` inline: runs the words when typing reaches that point, without a new bubble.
|
|
6
|
+
*
|
|
7
|
+
* The words are the vocabulary of the body on screen (its pack's `vocab`, src/packs.ts), by id or
|
|
8
|
+
* by any of their names; unknown words are dropped and reported back. An inline marker longer than
|
|
9
|
+
* `INLINE_TAG_MAX` or spanning a line is text.
|
|
10
|
+
*/
|
|
11
|
+
import type { ModelLanguage } from './model-text.ts';
|
|
12
|
+
|
|
13
|
+
/** One word of a body's vocabulary. */
|
|
14
|
+
export interface VocabWord {
|
|
15
|
+
id: string;
|
|
16
|
+
kind: 'expression' | 'motion';
|
|
17
|
+
/** Names the bot may write it by, by language; the id always works. */
|
|
18
|
+
names: Record<string, string[]>;
|
|
19
|
+
/** What it looks like on this body, by language. */
|
|
20
|
+
about: Record<string, string>;
|
|
21
|
+
/** Seconds the page waits after it before the next word in a row. */
|
|
22
|
+
seconds: number;
|
|
23
|
+
/** Held until the next word (sitting, sleeping). */
|
|
24
|
+
lasting?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const lookups = new WeakMap<readonly VocabWord[], Map<string, VocabWord>>();
|
|
28
|
+
function lookup(vocab: readonly VocabWord[]): Map<string, VocabWord> {
|
|
29
|
+
let m = lookups.get(vocab);
|
|
30
|
+
if (!m) {
|
|
31
|
+
m = new Map();
|
|
32
|
+
for (const v of vocab) {
|
|
33
|
+
m.set(v.id, v);
|
|
34
|
+
for (const n of Object.values(v.names).flat()) m.set(n, v);
|
|
35
|
+
}
|
|
36
|
+
lookups.set(vocab, m);
|
|
37
|
+
}
|
|
38
|
+
return m;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The id of a word of `vocab` (its id or one of its names), or null. */
|
|
42
|
+
export function vocabId(word: string, vocab: readonly VocabWord[]): string | null {
|
|
43
|
+
const m = lookup(vocab);
|
|
44
|
+
return m.get(word.trim().toLowerCase())?.id ?? m.get(word.trim())?.id ?? null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface Anchor {
|
|
48
|
+
/** Character offset in the beat's text. */
|
|
49
|
+
at: number;
|
|
50
|
+
actions: string[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface Beat {
|
|
54
|
+
actions: string[];
|
|
55
|
+
text: string;
|
|
56
|
+
anchors: Anchor[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export interface ParsedScript {
|
|
60
|
+
beats: Beat[];
|
|
61
|
+
dropped: string[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const INLINE_TAG_MAX = 32;
|
|
65
|
+
|
|
66
|
+
function words(inner: string, dropped: string[], vocab: readonly VocabWord[]): string[] {
|
|
67
|
+
const out: string[] = [];
|
|
68
|
+
for (const w of inner.split(/[,,、\s]+/)) {
|
|
69
|
+
if (!w) continue;
|
|
70
|
+
const id = vocabId(w, vocab);
|
|
71
|
+
if (id) out.push(id);
|
|
72
|
+
else dropped.push(w);
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function parseScript(script: string, vocab: readonly VocabWord[]): ParsedScript {
|
|
78
|
+
const dropped: string[] = [];
|
|
79
|
+
const beats: Beat[] = [];
|
|
80
|
+
let cur: Beat = { actions: [], text: '', anchors: [] };
|
|
81
|
+
let i = 0;
|
|
82
|
+
while (i < script.length) {
|
|
83
|
+
const ch = script[i];
|
|
84
|
+
if (ch === '【') {
|
|
85
|
+
const end = script.indexOf('】', i + 1);
|
|
86
|
+
if (end < 0) { cur.text += script.slice(i); break; }
|
|
87
|
+
const acts = words(script.slice(i + 1, end), dropped, vocab);
|
|
88
|
+
if (cur.text.trim() || cur.actions.length || cur.anchors.length) beats.push(cur);
|
|
89
|
+
cur = { actions: acts, text: '', anchors: [] };
|
|
90
|
+
i = end + 1;
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (ch === '<' || ch === '<') {
|
|
94
|
+
const close = ch === '<' ? '>' : '>';
|
|
95
|
+
const end = script.indexOf(close, i + 1);
|
|
96
|
+
const inner = end < 0 ? '' : script.slice(i + 1, end);
|
|
97
|
+
if (end < 0 || inner.length > INLINE_TAG_MAX || /\n/.test(inner)) { cur.text += ch; i++; continue; }
|
|
98
|
+
const acts = words(inner, dropped, vocab);
|
|
99
|
+
if (acts.length) cur.anchors.push({ at: cur.text.length, actions: acts });
|
|
100
|
+
i = end + 1;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
cur.text += ch;
|
|
104
|
+
i++;
|
|
105
|
+
}
|
|
106
|
+
if (cur.text.trim() || cur.actions.length || cur.anchors.length) beats.push(cur);
|
|
107
|
+
for (const b of beats) {
|
|
108
|
+
const lead = b.text.length - b.text.trimStart().length;
|
|
109
|
+
b.text = b.text.trim();
|
|
110
|
+
for (const a of b.anchors) a.at = Math.max(0, Math.min(b.text.length, a.at - lead));
|
|
111
|
+
}
|
|
112
|
+
return { beats, dropped };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Seconds a script stays on screen: typing at ~20 × `speed` chars/s, plus reading time per bubble: `holdSec`
|
|
117
|
+
* (`window.sayBubbleHoldSec`), or while that is 0 one by its length divided by `speed` (`window.bubbleSpeed`). `steps`
|
|
118
|
+
* gives each character's typing steps (1/20 s) when they are not one each (the pet's speech, src/speech).
|
|
119
|
+
*/
|
|
120
|
+
export function estimateSeconds(beats: readonly Beat[], speed: number, steps?: (ch: string) => number, holdSec = 0): number {
|
|
121
|
+
let s = 0;
|
|
122
|
+
for (const b of beats) {
|
|
123
|
+
if (b.actions.length) s += .5;
|
|
124
|
+
const typed = steps ? [...b.text].reduce((n, ch) => n + steps(ch), 0) : b.text.length;
|
|
125
|
+
if (b.text) s += typed / 20 / speed + (holdSec || (1.6 + b.text.length * .07) / speed);
|
|
126
|
+
}
|
|
127
|
+
return Math.round(s * 10) / 10;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Validates an action list for `speed_pet_act`, splitting known ids from unknown words. */
|
|
131
|
+
export function parseActions(list: readonly unknown[], vocab: readonly VocabWord[]): { actions: string[]; dropped: string[] } {
|
|
132
|
+
const actions: string[] = [];
|
|
133
|
+
const dropped: string[] = [];
|
|
134
|
+
for (const raw of list) {
|
|
135
|
+
if (typeof raw !== 'string') { dropped.push(String(raw)); continue; }
|
|
136
|
+
const id = vocabId(raw, vocab);
|
|
137
|
+
if (id) actions.push(id);
|
|
138
|
+
else dropped.push(raw);
|
|
139
|
+
}
|
|
140
|
+
return { actions, dropped };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const pickIn = <T>(by: Record<string, T>, language: string): T | undefined => by[language] ?? by.zh ?? Object.values(by)[0];
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* The vocabulary as the bot reads it, by model-text language. A row gives what a word is called and
|
|
147
|
+
* what it looks like. The Chinese table lists every word's Chinese names; the English one only the
|
|
148
|
+
* English names a pack gives, so the bot writes ids or English words in English bubbles. A look
|
|
149
|
+
* without English text is given in the pack's own language.
|
|
150
|
+
*/
|
|
151
|
+
const VOCAB_TEXT = {
|
|
152
|
+
zh: {
|
|
153
|
+
row: (v: VocabWord) => `| ${v.id} | ${(pickIn(v.names, 'zh') ?? []).join(' / ')} | ${pickIn(v.about, 'zh') ?? ''}${v.lasting ? ',保持到下一个动作' : ''} |`,
|
|
154
|
+
head: '| 词 | 中文 | 样子 |\n|---|---|---|\n',
|
|
155
|
+
expressions: '表情(持续几秒后回到平常的脸):',
|
|
156
|
+
motions: '动作:',
|
|
157
|
+
changed: '词表变了。',
|
|
158
|
+
gone: (words: readonly VocabWord[]) => `这些词用不了了:${words.map((v) => `${v.id}(${pickIn(v.names, 'zh')?.[0] ?? v.id})`).join('、')}。`,
|
|
159
|
+
fresh: '新增或样子变了的:',
|
|
160
|
+
kinds: { expression: '表情', motion: '动作' } as Record<VocabWord['kind'], string>,
|
|
161
|
+
},
|
|
162
|
+
en: {
|
|
163
|
+
row: (v: VocabWord) => `| ${[v.id, ...v.names.en ?? []].join(' / ')} | ${pickIn(v.about, 'en') ?? ''}${v.lasting ? '; held until the next action' : ''} |`,
|
|
164
|
+
head: '| word | looks like |\n|---|---|\n',
|
|
165
|
+
expressions: 'Expressions (they last a few seconds, then the face goes back to normal):',
|
|
166
|
+
motions: 'Motions:',
|
|
167
|
+
changed: 'The vocabulary changed.',
|
|
168
|
+
gone: (words: readonly VocabWord[]) => ` These words no longer work: ${words.map((v) => v.id).join(', ')}.`,
|
|
169
|
+
fresh: ' New or changed:',
|
|
170
|
+
kinds: { expression: 'Expressions', motion: 'Motions' } as Record<VocabWord['kind'], string>,
|
|
171
|
+
},
|
|
172
|
+
} satisfies Record<ModelLanguage, unknown>;
|
|
173
|
+
|
|
174
|
+
/** The vocabulary as the bot's prompt shows it: expressions, then motions. */
|
|
175
|
+
export function vocabTable(vocab: readonly VocabWord[], language: ModelLanguage = 'zh'): string {
|
|
176
|
+
const t = VOCAB_TEXT[language];
|
|
177
|
+
const rows = (kind: VocabWord['kind']) => vocab.filter((v) => v.kind === kind).map(t.row).join('\n');
|
|
178
|
+
return `${t.expressions}\n\n${t.head}${rows('expression')}\n\n`
|
|
179
|
+
+ `${t.motions}\n\n${t.head}${rows('motion')}`;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* How the vocabulary went from `before` to `after`, for the bot: the words gone, then the rows of the words
|
|
184
|
+
* new or told differently (kind, names, look). Empty when the bot would see the same table.
|
|
185
|
+
*/
|
|
186
|
+
export function vocabChange(before: readonly VocabWord[], after: readonly VocabWord[], language: ModelLanguage = 'zh'): string {
|
|
187
|
+
const t = VOCAB_TEXT[language];
|
|
188
|
+
const told = new Map(before.map((v) => [v.id, `${v.kind}${t.row(v)}`]));
|
|
189
|
+
const gone = before.filter((v) => !after.some((w) => w.id === v.id));
|
|
190
|
+
const fresh = after.filter((v) => told.get(v.id) !== `${v.kind}${t.row(v)}`);
|
|
191
|
+
if (!gone.length && !fresh.length) return '';
|
|
192
|
+
const lines = [t.changed];
|
|
193
|
+
if (gone.length) lines[0] += t.gone(gone);
|
|
194
|
+
if (fresh.length) {
|
|
195
|
+
lines[0] += t.fresh;
|
|
196
|
+
for (const kind of ['expression', 'motion'] as const) {
|
|
197
|
+
const rows = fresh.filter((v) => v.kind === kind);
|
|
198
|
+
if (rows.length) lines.push(`${t.kinds[kind]}:\n\n${t.head}${rows.map(t.row).join('\n')}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return lines.join('\n\n');
|
|
202
|
+
}
|