@wocwang/cortico-world-singer-for-coopanion 0.1.21 → 0.1.24

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 CHANGED
@@ -1,5 +1,38 @@
1
1
  # 更新记录
2
2
 
3
+ ## 0.1.24(2026-11-16)移除误打入包的测试文件
4
+
5
+ - 0.1.23 的 npm 包里混入了一个 2 字节的 `src/write-test.txt`(本地权限测试残留),
6
+ 本版移除;功能与 0.1.23 相同。
7
+
8
+ ## 0.1.23(2026-11-16)桌宠调用会自己拉起唱歌引擎
9
+
10
+ **改动**
11
+
12
+ - `singer_sing` 在推理服务未启动时先拉起服务并等引擎就绪(最多 60 秒),再合成;覆盖「随
13
+ Coopanion 启动」关闭、闲置回收后退出、引擎意外停着三种情况。
14
+ - 启动超时或失败会把具体原因回给模型,不再只回「未启动,去点启动服务」。
15
+ - **手动点「停止服务」仍是硬开关**:桌宠 / 对话页调用不会覆盖,回执明确说明需要手动启动。
16
+ - `ensureReady` 从「只拉闲置停」扩展为「服务开着且引擎 stopped 都拉回」;启动失败(error)
17
+ 不反复重试。配置文案同步更新,环境提示词说明桌宠会先自动拉起。
18
+ - 验证:`tsc --noEmit`、89 个单测全绿;未改 9882 接口契约。
19
+
20
+ ## 0.1.22(2026-11-16)模型下载:慢源自动切换、认代理、调整镜像顺序
21
+
22
+ **改动**
23
+
24
+ - 来源速度过低会主动放弃:起步 10 秒后按 6 秒窗口采样,平均低于 100 KB/s 就换下一个来源,
25
+ 已下部分带 `Range` 续传;最后一个来源不按速度放弃(再慢也比装不上强)。此前只有 HTTP 错误、
26
+ 截断或校验失败才切换,卡在慢源上会一直等下去。
27
+ - 认系统代理:设了 `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY`(含小写)时官方源排最前,
28
+ 不再先冲镜像。Node 的 `fetch` 本身不走系统代理,需要以 `--use-env-proxy` 启动 Coopanion
29
+ 才能让请求真正过代理(README 已写明)。
30
+ - 镜像顺序:绮萱包(401 MB)对 ghfast 稳定返回 403,改为 gh-proxy → ghproxy.net → 官方 → ghfast;
31
+ 声码器不受影响,仍是 ghfast → gh-proxy → 官方。设了代理时两者都变成官方最前。
32
+ - 语料不变:旋律与节奏代码没有改动。
33
+
34
+ 新增用例「来源速度长期过低时主动换下一个,并带 Range 续传」,全套 88 个用例通过。
35
+
3
36
  ## 0.1.21(2026-11-16)原版断句 + 新旋律(混合节奏)
4
37
 
5
38
  **改了什么**
package/README.md CHANGED
@@ -47,6 +47,16 @@ Coopanion 的 `kind: world` 插件:**让大肥鱼临场发挥、随意唱歌**
47
47
 
48
48
  装依赖前会先停引擎——worker 在跑时 `pip` 覆盖不了 venv 里的 `.pyd/.dll`。
49
49
 
50
+ 下载来源默认「镜像优先、官方兜底」:绮萱包(401 MB)实测 ghfast 稳定返回 403,顺序是
51
+ gh-proxy → ghproxy.net → 官方 → ghfast;声码器仍是 ghfast → gh-proxy → 官方。
52
+ 设了 `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` 时官方一律排最前
53
+ (代理通常已经把 GitHub 打通,不必再多跳一次镜像)。来源在起步 10 秒后按 6 秒窗口采样、
54
+ 平均速度低于 100 KB/s 就会被放弃并换下一个,已下的部分带 `Range` 续传,不会卡在慢源上;
55
+ 最后一个来源不按速度放弃(再慢也比装不上强)。
56
+ 注意 Node 的 `fetch` 不会自动走系统代理:想让请求真正经过代理,需要用 `--use-env-proxy`
57
+ 启动 Coopanion(Node 24 的实验参数);插件本身只按环境变量调整来源顺序。
58
+ 手工下载也可以:按下方文件名与字节数放进数据目录,校验大小一致就当作已下载,跳过网络。
59
+
50
60
  数据目录(`<Coopanion 数据目录>/singer/`):
51
61
 
52
62
  ```
package/describe.json CHANGED
@@ -52,7 +52,7 @@
52
52
  "key": "worlds.singer.envPrompt",
53
53
  "title": "DiffSinger 唱歌 · 环境提示词",
54
54
  "role": "envPrompt",
55
- "content": "## 唱歌(DiffSinger · 绮萱(中))\n\n状态:{{singer.state}}\n\n- 桌宠或对话页里,用户让你唱、说「随便唱几句」「唱一个」「来一段」,或者气氛适合唱时,就真的唱:先调 `singer_sing`,`lyrics` 按刚才的聊天现写一句 8–16 字的中文歌词;**等它返回**,再用 `pet_say` 原样显示它返回的那句歌词(不加引号、不加解释)。返回失败时不要拿歌词做气泡,如实说这次没唱成。\n- 先唱后显示:`singer_sing` 要等这一句真正开始出声才返回,气泡才会跟声音一起出现。不要把 `singer_sing` 和 `pet_say` 放在同一批里一起发出去。\n- 用户说「唱慢一点 / 唱快一点 / 调高点 / 调低点 / 换小调」这类话时,不要让主人去设置页:下一次 `singer_sing` 直接带上 `bpm`(60–200,默认 96,慢一点≈66–80)、`keyShift`(半音,正数更高,高一点≈+2~+4)或 `scale`(major / minor)。这些值会沿用到再改一次为止。\n- QQ 里点歌仍走 `qq_send`:`voice` 设为 true,正文只写「【唱】」加一句中文歌词;那条消息里不要写别的话。QQ 里不要调 `singer_sing`(它只在本机外放)。\n- 想先说一句再说唱,桌宠 / 对话页就分两次回复:先 `pet_say` 说那句,下一轮再 `singer_sing` → 等返回 → `pet_say` 歌词。\n- 唱日语要写假名(汉字没有读音会被跳过),而且得先把唱歌插件的声库换成日语声库;没换之前日语歌词唱不出来,会退回念。\n- 唱英语按单词写(空格分词);用自带英语词典的声库(绮萱自带,不用换)。要唱中文就换回中文声库。\n- 状态是「未启动」时多半是面板里点过「停止服务」:让主人到「DiffSinger 唱歌」页点「启动服务」,别假装已经唱了;这时 `singer_sing` 会回没有声音。\n"
55
+ "content": "## 唱歌(DiffSinger · 绮萱(中))\n\n状态:{{singer.state}}\n\n- 桌宠或对话页里,用户让你唱、说「随便唱几句」「唱一个」「来一段」,或者气氛适合唱时,就真的唱:先调 `singer_sing`,`lyrics` 按刚才的聊天现写一句 8–16 字的中文歌词;**等它返回**,再用 `pet_say` 原样显示它返回的那句歌词(不加引号、不加解释)。返回失败时不要拿歌词做气泡,如实说这次没唱成。\n- 先唱后显示:`singer_sing` 要等这一句真正开始出声才返回,气泡才会跟声音一起出现。不要把 `singer_sing` 和 `pet_say` 放在同一批里一起发出去。\n- 用户说「唱慢一点 / 唱快一点 / 调高点 / 调低点 / 换小调」这类话时,不要让主人去设置页:下一次 `singer_sing` 直接带上 `bpm`(60–200,默认 96,慢一点≈66–80)、`keyShift`(半音,正数更高,高一点≈+2~+4)或 `scale`(major / minor)。这些值会沿用到再改一次为止。\n- QQ 里点歌仍走 `qq_send`:`voice` 设为 true,正文只写「【唱】」加一句中文歌词;那条消息里不要写别的话。QQ 里不要调 `singer_sing`(它只在本机外放)。\n- 想先说一句再说唱,桌宠 / 对话页就分两次回复:先 `pet_say` 说那句,下一轮再 `singer_sing` → 等返回 → `pet_say` 歌词。\n- 唱日语要写假名(汉字没有读音会被跳过),而且得先把唱歌插件的声库换成日语声库;没换之前日语歌词唱不出来,会退回念。\n- 唱英语按单词写(空格分词);用自带英语词典的声库(绮萱自带,不用换)。要唱中文就换回中文声库。\n- 状态是「未启动」时工具会先自动拉起引擎(随机启动关着、闲置回收后都算),不用让主人先去点启动;只有主人手动点过「停止服务」才会回没有声音,这时让他到「DiffSinger 唱歌」页点「启动服务」,别假装已经唱了。\n"
56
56
  }
57
57
  ]
58
58
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wocwang/cortico-world-singer-for-coopanion",
3
- "version": "0.1.21",
3
+ "version": "0.1.24",
4
4
  "type": "module",
5
5
  "description": "Cortico World for Coopanion: let the pet improvise a line and sing it on the spot with DiffSinger (Qixuan voicebank), optionally through RVC",
6
6
  "author": "wocwang",
package/prompts/env.md CHANGED
@@ -9,4 +9,4 @@
9
9
  - 想先说一句再说唱,桌宠 / 对话页就分两次回复:先 `pet_say` 说那句,下一轮再 `singer_sing` → 等返回 → `pet_say` 歌词。
10
10
  - 唱日语要写假名(汉字没有读音会被跳过),而且得先把唱歌插件的声库换成日语声库;没换之前日语歌词唱不出来,会退回念。
11
11
  - 唱英语按单词写(空格分词);用自带英语词典的声库(绮萱自带,不用换)。要唱中文就换回中文声库。
12
- - 状态是「未启动」时多半是面板里点过「停止服务」:让主人到「DiffSinger 唱歌」页点「启动服务」,别假装已经唱了;这时 `singer_sing` 会回没有声音。
12
+ - 状态是「未启动」时工具会先自动拉起引擎(随机启动关着、闲置回收后都算),不用让主人先去点启动;只有主人手动点过「停止服务」才会回没有声音,这时让他到「DiffSinger 唱歌」页点「启动服务」,别假装已经唱了。
package/src/catalog.ts CHANGED
@@ -5,7 +5,9 @@
5
5
  * 断点续传、校验通过才落位,然后就地解压(保留完整声库,含使用条款文件),
6
6
  * 解压完把 zip 删掉省下 451 MB。
7
7
  *
8
- * 来源顺序:第三方 GitHub 代理(国内直连 release 只有几十 KB/s)→ 官方 release。
8
+ * 来源顺序:默认镜像优先、官方兜底,个别对某资产不好使的镜像压到官方之后(绮萱包的 ghfast);
9
+ * 设了 HTTPS_PROXY / HTTP_PROXY / ALL_PROXY 时官方源一律排最前——代理通常已经把 GitHub 打通,
10
+ * 不必再多跳一次镜像。任一来源速度过低会被主动放弃并换下一个(见 install.ts)。
9
11
  */
10
12
 
11
13
  /** 绮萱声库(v2.7.0,OpenUTAU 版,ONNX)。 */
@@ -29,20 +31,35 @@ const QIXUAN_URL =
29
31
  const VOCODER_URL =
30
32
  'https://github.com/openvpi/vocoders/releases/download/pc-nsf-hifigan-44.1k-hop512-128bin-2025.02/pc_nsf_hifigan_44.1k_hop512_128bin_2025.02.oudep';
31
33
 
32
- /** GitHub 代理:按实测速度排序(ghfast 最快),最后回官方。 */
33
- const PROXIES: ReadonlyArray<(url: string) => string> = [
34
- (url) => `https://ghfast.top/${url}`,
35
- (url) => `https://gh-proxy.com/${url}`,
36
- (url) => url,
37
- ];
34
+ /** GitHub 代理;具体某个文件用哪几个、什么顺序,由 viaProxies 的调用方决定。 */
35
+ const ghfast = (url: string): string => `https://ghfast.top/${url}`;
36
+ const ghProxy = (url: string): string => `https://gh-proxy.com/${url}`;
37
+ const ghproxyNet = (url: string): string => `https://ghproxy.net/${url}`;
38
38
 
39
- const viaProxies = (url: string): string[] => PROXIES.map((wrap) => wrap(url));
39
+ const hasProxyEnv = (): boolean =>
40
+ ['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy', 'ALL_PROXY', 'all_proxy']
41
+ .some((name) => Boolean(process.env[name]));
40
42
 
43
+ /**
44
+ * 拼一个文件的来源顺序:设了代理时官方最前(其余顺序不变),否则镜像在前、官方按 `afterOfficial`
45
+ * 决定插在哪。`afterOfficial` 用来把「已知对该资产不好使」的镜像压到官方之后,避免每次白跑一趟。
46
+ */
47
+ const viaProxies = (
48
+ url: string,
49
+ mirrors: ReadonlyArray<(url: string) => string>,
50
+ afterOfficial: ReadonlyArray<(url: string) => string> = [],
51
+ ): string[] => {
52
+ const head = mirrors.map((wrap) => wrap(url));
53
+ const tail = afterOfficial.map((wrap) => wrap(url));
54
+ return hasProxyEnv() ? [url, ...head, ...tail] : [...head, url, ...tail];
55
+ };
56
+
57
+ // 绮萱这个 401 MB 的包对 ghfast 稳定返回 403:官方排在它前面,ghfast 只作最后兜底。
41
58
  export const VOICEBANK_FILE: PinnedFile = {
42
59
  path: `${VOICEBANK_NAME}.zip`,
43
60
  bytes: 420_707_627,
44
61
  sha256: 'fe8ee7c95883d327a2b7facbbe832a7a53e1344918dc791ca83fc23b08034110',
45
- sources: viaProxies(QIXUAN_URL),
62
+ sources: viaProxies(QIXUAN_URL, [ghProxy, ghproxyNet], [ghfast]),
46
63
  };
47
64
 
48
65
  /**
@@ -53,7 +70,7 @@ export const VOCODER_FILE: PinnedFile = {
53
70
  path: `${VOCODER_NAME}.oudep`,
54
71
  bytes: 52_760_610,
55
72
  sha256: 'ba7d43142d41f6900c8264b5662ca7125a50feb8760bb8b9615c61a8f5e6902e',
56
- sources: viaProxies(VOCODER_URL),
73
+ sources: viaProxies(VOCODER_URL, [ghfast, ghProxy]),
57
74
  };
58
75
 
59
76
  export const MODEL_FILES: readonly PinnedFile[] = [VOICEBANK_FILE, VOCODER_FILE];
package/src/config.ts CHANGED
@@ -132,8 +132,8 @@ const TEXT = {
132
132
  tierCuda: '显卡(NVIDIA)',
133
133
  tierCpu: 'CPU',
134
134
  device: { title: '推理设备', description: '自动:显卡档运行时、派生 venv 里的 onnxruntime-gpu 与 NVIDIA 显卡都齐了就用显卡,缺一样退回 CPU。显卡推理多占约 0.8 GB 显存,热跑快约 6 倍;首次载入会热身一句,之后每句都不等。切到显卡后第一次「重启引擎」会补装 onnxruntime-gpu(约 215 MB,走阿里云镜像)。' },
135
- autoStart: { title: '随 Coopanion 启动服务', description: '开着时插件随 Coopanion 一起拉起唱歌引擎与本机接口;关掉后即使插件已加载也先不启动,省内存,要用时在面板「服务」点「启动服务」。这项只在下次启动 Coopanion 时决定初始状态,当前这次随时可以用面板的启动 / 停止。' },
136
- idleMinutes: { title: '闲置回收(分钟)', description: '多久没有唱歌就停掉引擎子进程、释放内存;0 表示不回收(默认,保持旧行为)。只回收引擎,9882 接口照常监听,下一条请求会自动重新拉起。手动点「停止服务」后不会自动重启。' },
135
+ autoStart: { title: '随 Coopanion 启动服务', description: '开着时插件随 Coopanion 一起拉起唱歌引擎与本机接口;关掉后启动时不预热,省内存,但面板生成、桌宠唱歌和 9882 请求仍会按需拉起。手动点「停止服务」后不会被自动拉起。' },
136
+ idleMinutes: { title: '闲置回收(分钟)', description: '多久没有唱歌就停掉引擎子进程、释放内存;0 表示不回收(默认,保持旧行为)。只回收引擎,9882 接口照常监听,下一条请求会自动重新拉起。手动点「停止服务」后不会自动重启,也不会被桌宠拉起。' },
137
137
  deviceAuto: '自动',
138
138
  deviceCuda: '显卡(NVIDIA)',
139
139
  deviceCpu: 'CPU',
@@ -167,8 +167,8 @@ const TEXT = {
167
167
  tierCuda: 'GPU (NVIDIA)',
168
168
  tierCpu: 'CPU',
169
169
  device: { title: 'Inference device', description: 'Auto uses the GPU when the GPU runtime, onnxruntime-gpu in the derived venv and an NVIDIA GPU are all present; otherwise CPU. GPU inference takes about 0.8 GB of VRAM and is roughly 6x faster once warm; the engine sings a short warm-up line after loading, so the first real line never waits. Switching to GPU makes the next Restart engine install onnxruntime-gpu (~215 MB, Aliyun mirror first).' },
170
- autoStart: { title: 'Start the service with Coopanion', description: 'On means the plugin brings the singing engine and the loopback API up together with Coopanion. Off keeps the service stopped even though the plugin is loaded, saving memory; click Start service in the Service panel when you need it. This only decides the initial state on the next Coopanion launch; the Start / Stop buttons still work any time.' },
171
- idleMinutes: { title: 'Idle shutdown (minutes)', description: 'Stop the engine process and free memory after this many idle minutes; 0 keeps it running (default, same as before). Only the engine is recycled — the 9882 API keeps listening and the next request starts it again. A manual Stop service is never overridden.' },
170
+ autoStart: { title: 'Start the service with Coopanion', description: 'On brings the singing engine and the loopback API up with Coopanion. Off skips the warm-up to save memory, but panel generations, pet song requests and 9882 requests still start it on demand. A manual Stop service is never overridden.' },
171
+ idleMinutes: { title: 'Idle shutdown (minutes)', description: 'Stop the engine process and free memory after this many idle minutes; 0 keeps it running (default, same as before). Only the engine is recycled — the 9882 API keeps listening and the next request starts it again. A manual Stop service is never restarted, including by the pet.' },
172
172
  deviceAuto: 'Auto',
173
173
  deviceCuda: 'GPU (NVIDIA)',
174
174
  deviceCpu: 'CPU',
package/src/install.ts CHANGED
@@ -54,37 +54,78 @@ export function hasFile(dir: string, file: PinnedFile): boolean {
54
54
  /** 校验失败:数据本身不对,`.partial` 必须扔掉,换下一个来源重下。 */
55
55
  class VerifyError extends Error {}
56
56
 
57
+ /** 来源太慢:保留 `.partial`,换下一个来源续传(慢不是错,但不能一直等)。 */
58
+ class SlowSourceError extends Error {}
59
+
60
+ /** 低速判定:先给一段起步时间,之后按窗口平均速度采样,低于阈值就切源。 */
61
+ const envNumber = (name: string, fallback: number): number => {
62
+ const value = Number(process.env[name]);
63
+ return Number.isFinite(value) && value > 0 ? value : fallback;
64
+ };
65
+ const MIN_BPS = (): number => envNumber('SINGER_MIN_BPS', 100 * 1024);
66
+ const GRACE_MS = (): number => envNumber('SINGER_LOW_SPEED_GRACE_MS', 10_000);
67
+ const WINDOW_MS = (): number => envNumber('SINGER_LOW_SPEED_WINDOW_MS', 6_000);
68
+
57
69
  /**
58
70
  * 把一个地址下到 `dest`;`offset > 0` 时带 `Range` 续传。
59
71
  * 服务器忽略 Range(回 200)就截断重下,保证不会把两段数据拼在一起。
72
+ * 起步后按窗口统计速度,低于阈值主动中断并抛 `SlowSourceError`,由调用方换下一个来源续传
73
+ * (最后一个来源传 `enforceSpeed = false`,不因慢而放弃)。
60
74
  */
61
- async function fetchTo(url: string, dest: string, offset: number, signal: AbortSignal): Promise<void> {
75
+ async function fetchTo(url: string, dest: string, offset: number, signal: AbortSignal, enforceSpeed: boolean): Promise<void> {
62
76
  const headers = offset > 0 ? { Range: `bytes=${offset}-` } : undefined;
63
- const res = await fetch(url, { signal, redirect: 'follow', headers });
77
+ const local = new AbortController();
78
+ const combined = AbortSignal.any([signal, local.signal]);
79
+ const res = await fetch(url, { signal: combined, redirect: 'follow', headers });
64
80
  if (res.status === 416 && offset > 0) return; // 已经下到头,交给调用方校验
65
81
  if (!res.ok || !res.body) throw new Error(`HTTP ${res.status}`);
66
82
  const append = offset > 0 && res.status === 206;
67
83
  if (!append && offset > 0) rmSync(dest, { force: true });
84
+ let received = offset;
68
85
  const counter = new Transform({
69
- transform(chunk: Buffer, _enc, done) { done(null, chunk); },
86
+ transform(chunk: Buffer, _enc, done) { received += chunk.length; done(null, chunk); },
70
87
  });
88
+ const startedAt = Date.now();
89
+ let lastAt = startedAt;
90
+ let lastBytes = received;
91
+ const monitor = setInterval(() => {
92
+ const now = Date.now();
93
+ const elapsed = (now - lastAt) / 1000;
94
+ if (enforceSpeed && now - startedAt >= GRACE_MS()) {
95
+ const bps = (received - lastBytes) / Math.max(elapsed, 0.001);
96
+ if (bps < MIN_BPS()) {
97
+ local.abort(new SlowSourceError(`速度 ${(bps / 1024).toFixed(0)} KB/s,低于 ${(MIN_BPS() / 1024).toFixed(0)} KB/s`));
98
+ return;
99
+ }
100
+ }
101
+ lastAt = now;
102
+ lastBytes = received;
103
+ }, WINDOW_MS());
71
104
  mkdirSync(dirname(dest), { recursive: true });
72
- await pipeline(Readable.fromWeb(res.body as import('node:stream/web').ReadableStream), counter, createWriteStream(dest, { flags: append ? 'a' : 'w' }), { signal });
105
+ try {
106
+ await pipeline(Readable.fromWeb(res.body as import('node:stream/web').ReadableStream), counter, createWriteStream(dest, { flags: append ? 'a' : 'w' }), { signal: combined });
107
+ } catch (err) {
108
+ if (local.signal.aborted) throw local.signal.reason ?? err;
109
+ throw err;
110
+ } finally {
111
+ clearInterval(monitor);
112
+ }
73
113
  }
74
114
 
75
- /** 按来源顺序下完一个文件;网络中断保留 `.partial` 供下次续传,校验失败则丢弃重来。 */
115
+ /** 按来源顺序下完一个文件;网络中断/速度过慢保留 `.partial` 供下一个来源续传,校验失败则丢弃重来。 */
76
116
  async function downloadFile(dir: string, file: PinnedFile, signal: AbortSignal): Promise<void> {
77
117
  const dest = join(dir, file.path);
78
118
  const partial = `${dest}.partial`;
79
119
  if (hasFile(dir, file)) return;
80
120
  mkdirSync(dirname(dest), { recursive: true });
81
121
  const errors: string[] = [];
82
- for (const url of file.sources) {
122
+ for (const [index, url] of file.sources.entries()) {
83
123
  if (signal.aborted) throw new Error('已取消');
84
124
  let offset = sizeOf(partial);
85
125
  if (offset > file.bytes) { rmSync(partial, { force: true }); offset = 0; }
86
126
  try {
87
- await fetchTo(url, partial, offset, signal);
127
+ // 最后一个来源不按速度放弃:再慢也比彻底装不上强。
128
+ await fetchTo(url, partial, offset, signal, index < file.sources.length - 1);
88
129
  const size = sizeOf(partial);
89
130
  if (size !== file.bytes) throw new VerifyError(`大小 ${size},应为 ${file.bytes}`);
90
131
  if (await sha256File(partial) !== file.sha256) throw new VerifyError('SHA-256 不符');
package/src/world.ts CHANGED
@@ -157,6 +157,8 @@ export class SingerWorld implements World {
157
157
  private launchDetail = '';
158
158
  /** 引擎是「闲置回收」停的(不是用户手动停服务):下一条请求要能自动拉回来。 */
159
159
  private idleStopped = false;
160
+ /** 用户在面板手动点了「停止服务」:桌宠 / 对话页的调用默认不覆盖这个意图。 */
161
+ private serviceHeld = false;
160
162
  private idleTimer: NodeJS.Timeout | undefined;
161
163
  /** 正在执行 stop() 的那一小段:请求要等它结束再决定是否拉回。 */
162
164
  private idleSleep: Promise<void> | undefined;
@@ -248,6 +250,7 @@ export class SingerWorld implements World {
248
250
  this.log = host.log;
249
251
  this.player = this.opts.createPlayer ? this.opts.createPlayer(host.log) : new Player(host.log);
250
252
  this.stopped = false;
253
+ this.serviceHeld = false;
251
254
  this.launchDetail = '';
252
255
  this.setup();
253
256
  // 随 Coopanion 启动就看配置;关掉时插件仍加载,但引擎与接口先不启动,面板随时可以手动开。
@@ -332,6 +335,7 @@ export class SingerWorld implements World {
332
335
  private startService(): void {
333
336
  if (this.stopped) return;
334
337
  this.serviceOn = true;
338
+ this.serviceHeld = false;
335
339
  this.idleStopped = false;
336
340
  this.launchDetail = '';
337
341
  // 手动启停等同一次重试:上次换声库失败的目录可以再试一次。
@@ -343,6 +347,7 @@ export class SingerWorld implements World {
343
347
  /** 面板「停止服务」:停引擎、关接口;World 仍挂着,下次点「启动服务」再回来。 */
344
348
  private async stopService(): Promise<void> {
345
349
  this.serviceOn = false;
350
+ this.serviceHeld = true;
346
351
  this.idleStopped = false;
347
352
  this.cancelIdle();
348
353
  const server = this.server;
@@ -433,22 +438,66 @@ export class SingerWorld implements World {
433
438
  }
434
439
 
435
440
  /**
436
- * 回收后自动拉回:只处理「闲置停」这一种停止。
437
- * 手动停服务、未装声库、启动失败都保持原来的 409/未就绪语义,不在这里偷偷重试。
441
+ * 按需拉回:闲置回收、服务开着但引擎停着(含启动时没预热)都能拉起。
442
+ * 手动停服务(serviceOn=false)、未装声库、启动失败保持原有语义,不在这里偷偷重试。
438
443
  */
439
- async ensureReady(): Promise<void> {
444
+ async ensureReady(timeoutMs = 0): Promise<void> {
440
445
  if (this.stopped || !this.serviceOn) return;
441
446
  const engine = this.engine;
442
447
  if (!engine || engine.ready()) return;
443
448
  // 正在执行闲置回收:等 stop() 结束(期间请求排队,不吃 409)。
444
449
  if (this.idleSleep) await this.idleSleep.catch(() => undefined);
445
450
  // 已经在启动中(自动启动或别的请求触发):一起等,避免并发请求被 409 打回。
446
- if (this.starting) await this.starting.catch(() => undefined);
451
+ if (this.starting) await this.waitStarting(timeoutMs);
447
452
  if (engine.ready()) return;
448
- if (!this.idleStopped || engine.state().phase !== 'stopped') return;
453
+ if (engine.state().phase !== 'stopped') return;
449
454
  this.idleStopped = false;
450
455
  this.bootEngine();
451
- await this.starting?.catch(() => undefined);
456
+ await this.waitStarting(timeoutMs);
457
+ }
458
+
459
+ /** 等引擎启动完成;`timeoutMs>0` 时超时返回错误,后台启动本身继续。 */
460
+ private async waitStarting(timeoutMs: number): Promise<void> {
461
+ const starting = this.starting;
462
+ if (!starting) return;
463
+ if (timeoutMs <= 0) {
464
+ await starting.catch(() => undefined);
465
+ return;
466
+ }
467
+ let timer: NodeJS.Timeout | undefined;
468
+ try {
469
+ await Promise.race([
470
+ starting.catch(() => undefined),
471
+ new Promise<void>((_resolve, reject) => {
472
+ timer = setTimeout(() => reject(new Error(`engine start took longer than ${Math.round(timeoutMs / 1000)} s`)), timeoutMs);
473
+ timer.unref?.();
474
+ }),
475
+ ]);
476
+ } finally {
477
+ if (timer) clearTimeout(timer);
478
+ }
479
+ }
480
+
481
+ /**
482
+ * 桌宠 / 对话页调用前的「先拉起再执行」。
483
+ * 服务是手动停的就不覆盖;随机启动关着、闲置回收、引擎意外停着都会拉起并等就绪。
484
+ */
485
+ async ensureServiceForTool(timeoutMs = 60_000): Promise<{ ok: boolean; reason?: string }> {
486
+ if (this.stopped) return { ok: false, reason: 'the singer world is stopped' };
487
+ if (!this.serviceOn) {
488
+ if (this.serviceHeld) return { ok: false, reason: 'the singing service was stopped manually; start it on the Service page first' };
489
+ this.startService();
490
+ }
491
+ if (this.engine?.ready()) return { ok: true };
492
+ let timeout = '';
493
+ try {
494
+ await this.ensureReady(timeoutMs);
495
+ } catch (err) {
496
+ timeout = err instanceof Error ? err.message : String(err);
497
+ }
498
+ if (this.engine?.ready()) return { ok: true };
499
+ const detail = this.engine?.state().detail || this.launchDetail || timeout;
500
+ return { ok: false, reason: detail || 'the singing engine did not become ready' };
452
501
  }
453
502
 
454
503
  /** 面板/接口共用:此刻引擎状态。 */
@@ -581,11 +630,10 @@ export class SingerWorld implements World {
581
630
  }
582
631
 
583
632
  private async singAloudOnce(args: Record<string, unknown>): Promise<ToolOutcome> {
584
- if (!this.serviceOn) {
585
- return {
586
- text: 'No sound: the singing service is stopped. Ask the owner to press "启动服务" on the DiffSinger page.',
587
- failed: true,
588
- };
633
+ // 引擎没起(随机启动关着 / 闲置回收 / 意外停着)就先拉起再唱;手动停服务不覆盖。
634
+ const ready = await this.ensureServiceForTool();
635
+ if (!ready.ok) {
636
+ return { text: `No sound: ${ready.reason}.`, failed: true };
589
637
  }
590
638
  let job: SingJob;
591
639
  try {
@@ -976,6 +1024,7 @@ export class SingerWorld implements World {
976
1024
  if (this.stopped) return;
977
1025
  // 点「重启引擎」就等于要把服务开着:停了也能从这里启回来。
978
1026
  this.serviceOn = true;
1027
+ this.serviceHeld = false;
979
1028
  this.idleStopped = false;
980
1029
  this.cancelIdle();
981
1030
  await this.engine?.stop();