ai_co_discuss 0.5.21 → 0.5.23

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 (85) hide show
  1. package/.agents/skills/codiscuss-draft-cleanup/SKILL.md +16 -0
  2. package/.agents/skills/codiscuss-draft-cleanup/cleanup.py +70 -0
  3. package/.agents/skills/codiscuss-draft-cleanup/scan.py +70 -0
  4. package/.agents/skills/discuss-host/references/control.md +2 -2
  5. package/.agents/skills/discuss-host/references/workflow.md +4 -2
  6. package/.agents/skills/discuss-participant/SKILL.md +2 -0
  7. package/.agents/skills/local-stt-setup/SKILL.md +9 -8
  8. package/.agents/skills/local-tts-setup/SKILL.md +10 -9
  9. package/.agents/skills/share-card/SKILL.md +7 -6
  10. package/.agents/skills/share-card/references/share-card.md +34 -8
  11. package/.agents/skills/workflow-creator/SKILL.md +22 -14
  12. package/README.md +2 -0
  13. package/README.zh-CN.md +2 -0
  14. package/backend/free_room.py +64 -8
  15. package/backend/message_queue.py +9 -0
  16. package/backend/schema.sql +13 -1
  17. package/backend/server.py +289 -59
  18. package/docs/en/guide/admin.md +18 -0
  19. package/docs/en/guide/members.md +7 -1
  20. package/docs/en/guide/remote.md +1 -1
  21. package/docs/en/guide/rooms.md +14 -6
  22. package/docs/en/guide/voice.md +2 -0
  23. package/docs/en/guide/workflows.md +9 -5
  24. package/docs/en/guide/working.md +6 -4
  25. package/docs/guide/admin.md +18 -0
  26. package/docs/guide/members.md +7 -1
  27. package/docs/guide/remote.md +1 -1
  28. package/docs/guide/rooms.md +13 -6
  29. package/docs/guide/voice.md +2 -0
  30. package/docs/guide/workflows.md +9 -5
  31. package/docs/guide/working.md +6 -4
  32. package/frontend/locales/en/admin.json +58 -1
  33. package/frontend/locales/en/app.json +18 -1
  34. package/frontend/locales/en/backend.json +6 -0
  35. package/frontend/locales/en/core.json +4 -2
  36. package/frontend/locales/en/discussion.json +4 -1
  37. package/frontend/locales/en/room.json +85 -1
  38. package/gateway/gateway.mjs +49 -9
  39. package/package.json +3 -1
  40. package/runner/account_space.mjs +10 -0
  41. package/runner/adapters/antigravity_app.mjs +31 -4
  42. package/runner/adapters/antigravity_cli.mjs +9 -2
  43. package/runner/adapters/api.mjs +3 -2
  44. package/runner/adapters/api_pi.mjs +3 -2
  45. package/runner/adapters/api_pi_extension.mjs +5 -3
  46. package/runner/adapters/claude.mjs +32 -9
  47. package/runner/adapters/cli.mjs +2 -2
  48. package/runner/adapters/codex_app.mjs +192 -69
  49. package/runner/adapters/codex_cli.mjs +10 -5
  50. package/runner/adapters/common.mjs +414 -11
  51. package/runner/adapters/index.mjs +6 -0
  52. package/runner/admin_cli.mjs +22 -5
  53. package/runner/admin_panel.mjs +118 -5
  54. package/runner/admin_storage.mjs +105 -0
  55. package/runner/discussion_launch.mjs +328 -128
  56. package/runner/discussion_runner.mjs +12 -3
  57. package/runner/discussion_service.mjs +224 -37
  58. package/runner/discussion_skills.mjs +1 -1
  59. package/runner/expert_prompts.mjs +2 -2
  60. package/runner/experts.mjs +227 -0
  61. package/runner/file_diff.mjs +1 -1
  62. package/runner/free_runner.mjs +236 -51
  63. package/runner/i18n_en.mjs +39 -0
  64. package/runner/os_users.mjs +33 -1
  65. package/runner/project_files.mjs +7 -1
  66. package/runner/project_migration.mjs +245 -0
  67. package/runner/relay_channel.mjs +1 -1
  68. package/runner/remote_launch.mjs +4 -3
  69. package/runner/share_card.mjs +17 -1
  70. package/runner/share_shared.mjs +26 -9
  71. package/runner/site_deploy.mjs +2 -1
  72. package/runner/slash_names.mjs +12 -1
  73. package/runner/speech_directories.mjs +20 -0
  74. package/runner/storage_guard.mjs +383 -0
  75. package/runner/tts_providers.mjs +22 -21
  76. package/runner/workflows.mjs +211 -57
  77. package/web/admin.css +1 -1
  78. package/web/admin.js +8 -8
  79. package/web/app.js +589 -80
  80. package/web/i18n.js +4 -4
  81. package/web/markdown.css +1 -1
  82. package/web/modern.css +1 -1
  83. package/web/modern.js +68 -66
  84. package/workflows/decision-council/flow.json +216 -25
  85. package/workflows/trpg-classic/flow.json +151 -21
@@ -0,0 +1,383 @@
1
+ /** Local storage and disk-reserve guard for the service home (`~/.codiscuss`). */
2
+ import { statfsSync, statSync } from 'node:fs';
3
+ import { lstat, readdir, realpath } from 'node:fs/promises';
4
+ import { basename, dirname, join, relative, resolve } from 'node:path';
5
+ import { t } from './i18n.mjs';
6
+ import { speech_model_directories } from './speech_directories.mjs';
7
+
8
+ export const KIB = 1024;
9
+ export const MIB = 1024 ** 2;
10
+ export const GIB = 1024 ** 3;
11
+
12
+ export const ROOM_DRAFT_LIMIT = 1 * GIB;
13
+ export const DRAFT_LIMIT = 3 * GIB;
14
+ export const HOME_WARN = 8 * GIB;
15
+ export const HOME_LIMIT = 10 * GIB;
16
+ export const LOG_TAIL = 16 * MIB;
17
+
18
+ export const DISK_RESERVE_MIN = 10 * GIB;
19
+ export const DISK_RESERVE_MAX = 30 * GIB;
20
+ export const DISK_RESERVE_RATIO = 0.05;
21
+ export const MAX_SCAN_FILES = 200_000;
22
+ export const SCRATCH_PRESSURE_RATIO = 0.8;
23
+ export const DISK_CHECK_MS = 2_000;
24
+
25
+ // Legacy local speech model directories inside `~/.codiscuss`; excluded from the 10 GiB data budget.
26
+ export const MODEL_DIRS = ['yovoice', 'crispasr'];
27
+
28
+ const DRAFTS_DIR = 'drafts';
29
+ const LOCAL_DIR = 'local';
30
+ const STAT_BATCH = 32;
31
+ const BYTE_UNITS = [[GIB, 'GiB'], [MIB, 'MiB'], [KIB, 'KiB']];
32
+
33
+ /** Normalize a directory name or path for case comparison on the current platform. */
34
+ function path_key(value) {
35
+ return process.platform === 'win32' ? String(value).toLowerCase() : String(value);
36
+ }
37
+
38
+ /** Rewrite a path under `logical_root` onto `real_root` when the service root itself is a link or junction. */
39
+ function remap_root(target, logical_root, real_root) {
40
+ const full = resolve(target);
41
+ if (path_key(logical_root) === path_key(real_root)) return full;
42
+ const rel = relative(logical_root, full);
43
+ if (rel === '') return real_root;
44
+ if (!rel.startsWith('..') && rel !== '..' && !/^([a-zA-Z]:|[\\/])/.test(rel)) return join(real_root, rel);
45
+ return full;
46
+ }
47
+
48
+ /**
49
+ * Format a byte count into a human-readable IEC unit string (e.g. `1.5 GiB`, `10 GiB`, `512 MiB`).
50
+ * @param {number} bytes Non-negative byte count.
51
+ * @returns {string} Formatted size string.
52
+ */
53
+ export function format_bytes(bytes) {
54
+ const safe = Math.max(0, Number(bytes) || 0);
55
+ for (const [unit, label] of BYTE_UNITS) {
56
+ if (safe >= unit) {
57
+ const value = safe / unit;
58
+ const text = Number.isInteger(value) ? String(value) : value.toFixed(2).replace(/\.?0+$/, '');
59
+ return `${text} ${label}`;
60
+ }
61
+ }
62
+ return `${Math.round(safe)} B`;
63
+ }
64
+
65
+ /** Safely lstat one path, skipping missing entries and counting unreadable ones. */
66
+ async function safe_lstat(path, state, lstat_fn) {
67
+ try {
68
+ return await lstat_fn(path, { bigint: true });
69
+ } catch (error) {
70
+ if (error?.code !== 'ENOENT') state.unreadable += 1;
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /** Resolve the service root itself through a symlink or Windows junction without following nested links later. */
76
+ async function resolve_root(path, state, realpath_fn) {
77
+ try {
78
+ return await realpath_fn(path);
79
+ } catch (error) {
80
+ if (error?.code !== 'ENOENT') state.unreadable += 1;
81
+ return '';
82
+ }
83
+ }
84
+
85
+ /** Build normalized excluded path keys, including active speech model paths configured via `*-root.txt`. */
86
+ async function build_excluded_paths(logical_root, real_root, options, state, realpath_fn) {
87
+ const raw = [...(options.exclude_paths || []).filter(Boolean)];
88
+ if (options.model_dirs === undefined) {
89
+ try {
90
+ for (const item of speech_model_directories(logical_root)) raw.push(item.path);
91
+ } catch { state.unreadable += 1; }
92
+ }
93
+ const excluded = new Set();
94
+ for (const item of raw) {
95
+ excluded.add(path_key(remap_root(item, logical_root, real_root)));
96
+ try { excluded.add(path_key(await realpath_fn(item))); } catch { /* Missing or unreadable optional model path. */ }
97
+ }
98
+ return excluded;
99
+ }
100
+
101
+ /** Build a case-normalized scratch lookup map that matches paths after resolving a junctioned service root. */
102
+ function build_scratch_lookup(scratch, logical_root, real_root) {
103
+ if (!scratch) return null;
104
+ const map = new Map();
105
+ for (const [key, value] of scratch.entries()) {
106
+ map.set(path_key(resolve(key)), value);
107
+ map.set(path_key(remap_root(key, logical_root, real_root)), value);
108
+ }
109
+ return map;
110
+ }
111
+
112
+ /** Record one regular file into total, local, draft and room byte totals without double-counting hard links. */
113
+ function record_file(stat, room_key, in_drafts, in_local, state) {
114
+ const size = Number(stat.size);
115
+ const linked = stat.nlink > 1n && stat.ino !== 0n;
116
+ const id = linked ? `${stat.dev}:${stat.ino}` : '';
117
+ if (!linked || !state.seen_total.has(id)) {
118
+ if (linked) state.seen_total.add(id);
119
+ state.total_bytes += size;
120
+ }
121
+ if (in_local && (!linked || !state.seen_local.has(id))) {
122
+ if (linked) state.seen_local.add(id);
123
+ state.local_bytes += size;
124
+ }
125
+ if (!in_drafts) return;
126
+ if (!linked || !state.seen_draft.has(id)) {
127
+ if (linked) state.seen_draft.add(id);
128
+ state.draft_bytes += size;
129
+ }
130
+ if (!room_key) return;
131
+ let seen = state.seen_rooms.get(room_key);
132
+ if (linked) {
133
+ if (!seen) { seen = new Set(); state.seen_rooms.set(room_key, seen); }
134
+ if (seen.has(id)) return;
135
+ seen.add(id);
136
+ }
137
+ state.rooms[room_key] = (state.rooms[room_key] || 0) + size;
138
+ }
139
+
140
+ /** Scan one directory frame into `state`, enqueueing subdirectories and stopping at `max_files`. */
141
+ async function scan_directory(frame, queue, state, config) {
142
+ let entries;
143
+ try {
144
+ entries = await config.readdir(frame.path, { withFileTypes: true });
145
+ } catch (error) {
146
+ if (error?.code !== 'ENOENT') state.unreadable += 1;
147
+ return;
148
+ }
149
+ // Scan `drafts/` first at the top level so room sizes are captured even if another folder later truncates.
150
+ if (frame.depth === 0) {
151
+ entries.sort((a, b) => Number(path_key(b.name) === DRAFTS_DIR) - Number(path_key(a.name) === DRAFTS_DIR));
152
+ }
153
+ for (let offset = 0; offset < entries.length && !state.truncated; offset += STAT_BATCH) {
154
+ const slice = entries.slice(offset, offset + STAT_BATCH);
155
+ const items = await Promise.all(slice.map(async entry => {
156
+ if (entry.isSymbolicLink()) return null;
157
+ const full_path = join(frame.path, entry.name);
158
+ if (frame.depth === 0 && config.excluded_names.has(path_key(entry.name))) return null;
159
+ if (config.excluded_paths.has(path_key(resolve(full_path)))) return null;
160
+ const stat = await safe_lstat(full_path, state, config.lstat);
161
+ return stat && !stat.isSymbolicLink() ? { entry, full_path, stat } : null;
162
+ }));
163
+ for (const item of items) {
164
+ if (!item) continue;
165
+ const { entry, full_path, stat } = item;
166
+ const top_key = frame.depth === 0 ? path_key(entry.name) : '';
167
+ const in_drafts = frame.in_drafts || top_key === DRAFTS_DIR;
168
+ const in_local = frame.in_local || top_key === LOCAL_DIR;
169
+ const room_key = frame.room_key || (frame.in_drafts && frame.depth === 1 && stat.isDirectory() ? entry.name : '');
170
+ const member = frame.member || (room_key && frame.depth === 2 && stat.isDirectory() ? entry.name : '');
171
+ if (stat.isDirectory()) {
172
+ if (room_key && !Object.hasOwn(state.rooms, room_key)) state.rooms[room_key] = 0;
173
+ const scratch = frame.scratch || config.scratch?.get(path_key(full_path));
174
+ queue.push({ path: full_path, depth: frame.depth + 1, in_drafts, in_local, room_key, member, scratch });
175
+ } else if (stat.isFile()) {
176
+ state.files += 1;
177
+ if (state.files > config.max_files) { state.truncated = true; return; }
178
+ record_file(stat, room_key, in_drafts, in_local, state);
179
+ if (frame.scratch && stat.nlink === 1n) frame.scratch.bytes += Number(stat.size);
180
+ if (member && state.members) {
181
+ const totals = state.members[room_key] ||= Object.create(null);
182
+ const key = stat.nlink > 1n && stat.ino !== 0n && JSON.stringify([room_key, member, String(stat.dev), String(stat.ino)]);
183
+ if (!key || !state.member_links.has(key)) totals[member] = (totals[member] || 0) + Number(stat.size);
184
+ if (key) {
185
+ state.member_links.add(key);
186
+ (state.linked_members[room_key] ||= Object.create(null))[member] = true;
187
+ }
188
+ }
189
+ }
190
+ }
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Asynchronously measure `.codiscuss` storage usage, excluding speech model directories and nested links/reparse points.
196
+ * Resolves the service root itself through a symlink or Windows junction so redirected roots still enforce quotas.
197
+ * @param {string} home Service home directory (e.g. `~/.codiscuss`).
198
+ * @param {object} [options] Optional overrides (`max_files`, `model_dirs`, `exclude_paths`, `readdir`, `lstat`, `realpath`).
199
+ * @returns {Promise<{total_bytes: number, draft_bytes: number, local_bytes: number, rooms: Record<string, number>, unreadable: number, truncated: boolean}>}
200
+ */
201
+ export async function measure(home, options = {}) {
202
+ const max_files = options.max_files ?? MAX_SCAN_FILES;
203
+ const model_dirs = options.model_dirs ?? MODEL_DIRS;
204
+ const realpath_fn = options.realpath || realpath;
205
+ const state = {
206
+ total_bytes: 0,
207
+ draft_bytes: 0,
208
+ local_bytes: 0,
209
+ rooms: Object.create(null),
210
+ members: options.members ? Object.create(null) : null,
211
+ member_links: new Set(),
212
+ linked_members: Object.create(null),
213
+ unreadable: 0,
214
+ truncated: false,
215
+ files: 0,
216
+ seen_total: new Set(),
217
+ seen_local: new Set(),
218
+ seen_draft: new Set(),
219
+ seen_rooms: new Map(),
220
+ };
221
+ if (!home) return { total_bytes: 0, draft_bytes: 0, local_bytes: 0, rooms: {}, unreadable: 0, truncated: false };
222
+ const logical_root = resolve(home);
223
+ const real_root = await resolve_root(logical_root, state, realpath_fn);
224
+ if (!real_root) return { total_bytes: 0, draft_bytes: 0, local_bytes: 0, rooms: {}, unreadable: state.unreadable, truncated: false };
225
+ const lstat_fn = options.lstat || lstat;
226
+ const root_stat = await safe_lstat(real_root, state, lstat_fn);
227
+ if (!root_stat || !root_stat.isDirectory()) {
228
+ return { total_bytes: 0, draft_bytes: 0, local_bytes: 0, rooms: {}, unreadable: state.unreadable, truncated: false };
229
+ }
230
+ const config = {
231
+ max_files,
232
+ scratch: build_scratch_lookup(options.scratch, logical_root, real_root),
233
+ readdir: options.readdir || readdir,
234
+ lstat: lstat_fn,
235
+ excluded_names: new Set(model_dirs.map(path_key)),
236
+ excluded_paths: await build_excluded_paths(logical_root, real_root, options, state, realpath_fn),
237
+ };
238
+ const queue = [{ path: real_root, depth: options.room_key ? 2 : 0, in_drafts: Boolean(options.room_key),
239
+ in_local: false, room_key: options.room_key || '' }];
240
+ if (options.drafts_root && relative(join(logical_root, DRAFTS_DIR), options.drafts_root)) {
241
+ const external = resolve(options.drafts_root);
242
+ if (relative(external, await realpath_fn(external))) throw new Error('Redirected project drafts directory');
243
+ queue.push({ path: external, depth: 1, in_drafts: true, in_local: false, room_key: '' });
244
+ }
245
+ while (queue.length && !state.truncated) {
246
+ await scan_directory(queue.shift(), queue, state, config);
247
+ }
248
+ return {
249
+ total_bytes: state.total_bytes,
250
+ draft_bytes: state.draft_bytes,
251
+ local_bytes: state.local_bytes,
252
+ rooms: { ...state.rooms },
253
+ ...(options.members ? { members: state.members, linked_members: state.linked_members, shared_links: state.seen_total.size > 0 } : {}),
254
+ unreadable: state.unreadable,
255
+ truncated: state.truncated,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Read available space and computed safety reserve `min(max(10 GiB, 5%), 30 GiB)` for the volume holding `target_path`.
261
+ * @param {string} target_path Directory or file path on the target volume.
262
+ * @param {object} [options] Optional overrides (`statfs`, `min_reserve`, `max_reserve`, `ratio`).
263
+ * @returns {{available_bytes: number, reserve_bytes: number}}
264
+ */
265
+ export function disk_free(target_path, options = {}) {
266
+ const statfs = options.statfs || statfsSync;
267
+ const min_reserve = options.min_reserve ?? DISK_RESERVE_MIN;
268
+ const max_reserve = options.max_reserve ?? DISK_RESERVE_MAX;
269
+ const ratio = options.ratio ?? DISK_RESERVE_RATIO;
270
+ let current = resolve(String(target_path || '.'));
271
+ let stats;
272
+ for (;;) {
273
+ try {
274
+ stats = statfs(current);
275
+ break;
276
+ } catch (error) {
277
+ const parent = dirname(current);
278
+ if (error?.code !== 'ENOENT' || parent === current) throw error;
279
+ current = parent;
280
+ }
281
+ }
282
+ const block_size = Number(stats.bsize || stats.frsize || 0);
283
+ const available_bytes = Math.max(0, block_size * Number(stats.bavail || 0));
284
+ const total_bytes = Math.max(0, block_size * Number(stats.blocks || 0));
285
+ const reserve_bytes = Math.min(Math.max(min_reserve, Math.floor(total_bytes * ratio)), max_reserve);
286
+ return { available_bytes, reserve_bytes };
287
+ }
288
+
289
+ /** Check both managed volumes. Return the tighter reserve and each distinct volume's free bytes. */
290
+ export function storage_disk(home, drafts, check = disk_free, device = path => statSync(path).dev) {
291
+ const service = check(home);
292
+ if (!relative(join(home, DRAFTS_DIR), drafts) || device(home) === device(drafts)) return service;
293
+ const project = check(drafts);
294
+ const tightest = project.available_bytes - project.reserve_bytes < service.available_bytes - service.reserve_bytes ? project : service;
295
+ return { ...tightest, volumes: [service.available_bytes, project.available_bytes], service, project };
296
+ }
297
+
298
+ /**
299
+ * Return an empty string when storage and disk free space are within limits, or a localized blocking reason containing
300
+ * measured usage, limit and out-of-room cleanup entry.
301
+ * @param {{total_bytes?: number, draft_bytes?: number, local_bytes?: number, rooms?: Record<string, number>, truncated?: boolean}|null} snapshot
302
+ * @param {string} [room_key] Room draft folder key under `drafts/`.
303
+ * @param {{available_bytes: number, reserve_bytes: number}|null} [disk] Result of `disk_free()`.
304
+ * @param {object} [options] Optional limit and locale overrides.
305
+ * @returns {string}
306
+ */
307
+ export function block_reason(snapshot, room_key = '', disk = null, options = {}) {
308
+ const locale = options.locale;
309
+ const room_limit = options.room_limit ?? ROOM_DRAFT_LIMIT;
310
+ const draft_limit = options.draft_limit ?? DRAFT_LIMIT;
311
+ const home_limit = options.home_limit ?? HOME_LIMIT;
312
+ const max_files = options.max_files ?? MAX_SCAN_FILES;
313
+
314
+ if (disk && Number.isFinite(disk.available_bytes) && Number.isFinite(disk.reserve_bytes) && disk.available_bytes < disk.reserve_bytes) {
315
+ return t('磁盘剩余空间仅 {available},低于安全线 {reserve},已停止派活。请先清理磁盘空间;清理旧草稿请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup,或在管理面板“存储”页清理临时文件。',
316
+ { available: format_bytes(disk.available_bytes), reserve: format_bytes(disk.reserve_bytes) }, locale);
317
+ }
318
+ if (!snapshot) return '';
319
+ if (snapshot.truncated) {
320
+ return t('本机数据目录文件数超过 {limit} 上限(已扫到 {total},草稿 {draft}),按超限停止派活。房间被拦截时请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup,或在管理面板“存储”页清理临时文件。',
321
+ { limit: max_files, total: format_bytes(snapshot.total_bytes), draft: format_bytes(snapshot.draft_bytes) }, locale);
322
+ }
323
+ const rooms = snapshot.rooms || {};
324
+ const normalized_room = room_key && Object.hasOwn(rooms, room_key) ? room_key : (room_key ? basename(room_key) : '');
325
+ const room_bytes = normalized_room ? Number(rooms[normalized_room] || 0) : 0;
326
+ if (normalized_room && room_bytes > room_limit) {
327
+ return t('本房间草稿占用 {used},超过 {limit} 上限(目录 drafts/{room}),已停止派活。房间被拦截时请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 清理可重建副本,或在管理面板“存储”页清理临时文件。',
328
+ { used: format_bytes(room_bytes), limit: format_bytes(room_limit), room: normalized_room }, locale);
329
+ }
330
+ if (Number(snapshot.draft_bytes || 0) > draft_limit) {
331
+ return t('全机草稿占用 {used},超过 {limit} 上限(目录 drafts/),已停止派活。请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 清理旧草稿,或在管理面板“存储”页清理临时文件。',
332
+ { used: format_bytes(snapshot.draft_bytes), limit: format_bytes(draft_limit) }, locale);
333
+ }
334
+ if (Number(snapshot.total_bytes || 0) > home_limit) {
335
+ const local_bytes = Number(snapshot.local_bytes || 0);
336
+ if (local_bytes > 0) {
337
+ return t('本机 .codiscuss 数据占用 {used}(不含语音模型;草稿 {draft},房间记录与附件 {local}),超过 {limit} 上限,已停止派活。房间记录与附件不会自动删除,请先销毁不需要的旧房间;清理旧草稿请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup。',
338
+ { used: format_bytes(snapshot.total_bytes), draft: format_bytes(snapshot.draft_bytes), local: format_bytes(local_bytes), limit: format_bytes(home_limit) }, locale);
339
+ }
340
+ return t('本机 .codiscuss 数据占用 {used}(不含语音模型;草稿 {draft}),超过 {limit} 上限,已停止派活。清理旧草稿请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup,或在管理面板“存储”页清理临时文件;若由房间记录与附件占满,请销毁旧房间。',
341
+ { used: format_bytes(snapshot.total_bytes), draft: format_bytes(snapshot.draft_bytes), limit: format_bytes(home_limit) }, locale);
342
+ }
343
+ if (snapshot.uncertain_growth) {
344
+ return t('磁盘余量下降后复扫发现不可读项增至 {count} 处,已暂停派活,下次扫描将重新判断。', { count: snapshot.unreadable }, locale);
345
+ }
346
+ if (options.stoppable === false && room_bytes >= room_limit * SCRATCH_PRESSURE_RATIO) {
347
+ return t('本房间草稿已用 {used}(上限 {limit}),达到 80%,已暂停向无法确认可停止的成员派活。请先清理本房间草稿。', { used: format_bytes(room_bytes), limit: format_bytes(room_limit) }, locale);
348
+ }
349
+ return '';
350
+ }
351
+
352
+ /**
353
+ * Return a localized warning when `.codiscuss` usage reaches the 8 GiB warning threshold, or an empty string.
354
+ * Includes the count of unreadable entries when any were skipped due to permissions.
355
+ * @param {{total_bytes?: number, unreadable?: number}|null} snapshot
356
+ * @param {object} [options] Optional threshold and locale overrides.
357
+ * @returns {string}
358
+ */
359
+ export function warn_reason(snapshot, options = {}) {
360
+ const locale = options.locale;
361
+ const home_warn = options.home_warn ?? HOME_WARN;
362
+ const home_limit = options.home_limit ?? HOME_LIMIT;
363
+ if (!snapshot || Number(snapshot.total_bytes || 0) < home_warn) return '';
364
+ const unreadable = Number(snapshot.unreadable || 0);
365
+ if (unreadable > 0) {
366
+ return t('本机 .codiscuss 数据已占 {used}(不含语音模型,另有 {unreadable} 处因权限无法读取未计入),接近 {limit} 上限(预警线 {warn})。请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 或在管理面板“存储”页清理临时文件。',
367
+ { used: format_bytes(snapshot.total_bytes), unreadable, limit: format_bytes(home_limit), warn: format_bytes(home_warn) }, locale);
368
+ }
369
+ return t('本机 .codiscuss 数据已占 {used}(不含语音模型),接近 {limit} 上限(预警线 {warn})。请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 或在管理面板“存储”页清理临时文件。',
370
+ { used: format_bytes(snapshot.total_bytes), limit: format_bytes(home_limit), warn: format_bytes(home_warn) }, locale);
371
+ }
372
+
373
+ /**
374
+ * Wrap an unexpected storage measurement or disk check error in a localized user-facing pause reason.
375
+ * @param {unknown} error Caught exception.
376
+ * @param {object} [options] Optional locale override.
377
+ * @returns {string}
378
+ */
379
+ export function storage_error_reason(error, options = {}) {
380
+ const locale = options.locale;
381
+ const detail = String(error?.message || error || '').trim() || t('未知错误', undefined, locale);
382
+ return t('无法检查本机存储与磁盘空间,已暂停派活({reason})。请检查 .codiscuss 目录权限或稍后重试。', { reason: detail }, locale);
383
+ }
@@ -13,6 +13,7 @@ import { tmpdir } from 'node:os';
13
13
  import { join } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { promisify } from 'node:util';
16
+ import { speech_directory } from './speech_directories.mjs';
16
17
 
17
18
  const TTS_TIMEOUT_MS = 45_000;
18
19
  const VOLC_ENDPOINT = 'https://openspeech.bytedance.com/api/v3/tts/unidirectional';
@@ -45,7 +46,7 @@ const OPENAI_FORMAT = 'aac';
45
46
  const SILENT_AAC_FRAME = Buffer.from([0xff, 0xf1, 0x58, 0x40, 0x01, 0x7f, 0xfc, 0x00, 0x00, 0x00, 0x07]);
46
47
  const SILENT_AAC_FRAME_MS = 1024 / 24;
47
48
  // Local speech: yovoice serving Qwen3-TTS CustomVoice on this computer, installed by the local-tts-setup skill into
48
- // `<service home>/yovoice` (CLI in `cli/`, engine and model in `data/`). Like voice input's local service, the runner
49
+ // its configured installation directory (CLI in `cli/`, engine and model in `data/`). Like voice input's local service, the runner
49
50
  // starts it through a supervisor (`local_speech_service.mjs`) and renews its lease on every request; five minutes without
50
51
  // one (or an explicit release) stops it, so the model does not hold graphics memory between uses, even when the
51
52
  // runner has crashed.
@@ -65,7 +66,7 @@ const LOCAL_DESIGNED_VOICES = {
65
66
  voxcpm2_elderly_male: '六十多岁的老年男性,嗓音低沉略带沙哑,说话很慢,像老人在家里平平淡淡地回忆往事,朴素自然,没有播音腔',
66
67
  voxcpm2_middle_aged_male: '五十岁左右的普通中年男性,声音低沉厚实,说话很慢,语气平淡朴实,像和熟人闲聊,没有播音腔,不像短视频解说',
67
68
  };
68
- const LOCAL_DIR = 'yovoice';
69
+
69
70
  const LOCAL_START_MS = 30_000;
70
71
  const LOCAL_POLL_MS = 500;
71
72
  const LOCAL_CONVERT_MS = 30_000;
@@ -75,11 +76,11 @@ const LOCAL_EXE = process.platform === 'win32' ? '.exe' : '';
75
76
  const run_file = promisify(execFile);
76
77
  const LOCAL_SUPERVISOR = fileURLToPath(new URL('./local_speech_service.mjs', import.meta.url));
77
78
  // Voice input on this computer: CrispASR serving Qwen3-ASR 0.6B, installed by the local-stt-setup skill into
78
- // `<service home>/crispasr` (program in `cli/`, model in `models/`), started, renewed and stopped like the read-aloud
79
+ // its configured installation directory (program in `cli/`, model in `models/`), started, renewed and stopped like the read-aloud
79
80
  // service. Measured 2026-11-10 (RTX 5060, cuda13): about 35× realtime once loaded, a 5-minute recording in 8.5 s.
80
81
  const LOCAL_STT_KEY_URL = 'http://127.0.0.1/crispasr';
81
82
  const LOCAL_STT_LEGACY_KEY_URL = 'http://127.0.0.1:18766';
82
- const LOCAL_STT_DIR = 'crispasr';
83
+
83
84
  const LOCAL_STT_MODEL = 'qwen3-asr-0.6b-q8_0.gguf';
84
85
  const LOCAL_STT_TIMEOUT_MS = 120_000;
85
86
  // The local services the settings page shows, by the program each runs; a stuck one (its supervisor killed) is found by
@@ -88,8 +89,8 @@ const LOCAL_STT_TIMEOUT_MS = 120_000;
88
89
  // does not take it; when the port is taken anyway, on a free one the system gives. The port of the running service is
89
90
  // recorded in `<service dir>/port`, which its supervisor removes when the service ends.
90
91
  const LOCAL_SERVICES = {
91
- tts: { directory: LOCAL_DIR, port: 37641, program: 'yovoice' },
92
- stt: { directory: LOCAL_STT_DIR, port: 37642, program: 'crispasr' },
92
+ tts: { port: 37641, program: 'yovoice' },
93
+ stt: { port: 37642, program: 'crispasr' },
93
94
  };
94
95
  const PORT_FILE = 'port';
95
96
  const LOCAL_PROBE_MS = 1000;
@@ -362,7 +363,7 @@ function local_release(directory) {
362
363
  * instead of reaching whatever else may listen on its preferred port (with the token).
363
364
  */
364
365
  function local_port(home, id) {
365
- try { return Number(readFileSync(join(home, LOCAL_SERVICES[id].directory, PORT_FILE), 'utf8')) || 0; } catch { return 0; }
366
+ try { return Number(readFileSync(join(speech_directory(home, id), PORT_FILE), 'utf8')) || 0; } catch { return 0; }
366
367
  }
367
368
 
368
369
  const local_url = (home, id) => `http://${LOCAL_HOST}:${local_port(home, id)}`;
@@ -378,10 +379,10 @@ function try_listen(port) {
378
379
 
379
380
  /** Pick the port a local service starts on, its preferred one when free, and record it for the requests that follow. */
380
381
  async function local_choose_port(home, id) {
381
- const { directory, port } = LOCAL_SERVICES[id];
382
+ const { port } = LOCAL_SERVICES[id];
382
383
  const chosen = await try_listen(port) || await try_listen(0);
383
384
  if (!chosen) throw new Error('找不到可用的本机端口');
384
- writeFileSync(join(home, directory, PORT_FILE), String(chosen));
385
+ writeFileSync(join(speech_directory(home, id), PORT_FILE), String(chosen));
385
386
  return chosen;
386
387
  }
387
388
 
@@ -391,7 +392,7 @@ async function local_choose_port(home, id) {
391
392
  * setup skill to point at when it is missing.
392
393
  */
393
394
  async function local_supervise(home, id, { executable, args, env, ready, key, skill, wait_ms = LOCAL_START_MS }, request) {
394
- const directory = join(home, LOCAL_SERVICES[id].directory);
395
+ const directory = speech_directory(home, id);
395
396
  if (!existsSync(executable)) throw new Error(`本机服务尚未安装:请让本机 AI 按 ${skill} 技能安装`);
396
397
  local_renew(directory);
397
398
  const port = await local_choose_port(home, id);
@@ -406,7 +407,7 @@ async function local_supervise(home, id, { executable, args, env, ready, key, sk
406
407
 
407
408
  /** Start the read-aloud service (yovoice). */
408
409
  function local_start(home, key, request) {
409
- const directory = join(home, LOCAL_DIR);
410
+ const directory = speech_directory(home, 'tts');
410
411
  return local_supervise(home, 'tts', { executable: join(directory, 'cli', `yovoice${LOCAL_EXE}`), key, skill: 'local-tts-setup',
411
412
  args: port => ['serve', '--listen', `${LOCAL_HOST}:${port}`, '--data-dir', join(directory, 'data')], env: { YOVOICE_API_TOKEN: key },
412
413
  ready: '/v1/status' }, request);
@@ -420,7 +421,7 @@ async function local_convert(home, wav) {
420
421
  const work = mkdtempSync(join(tmpdir(), 'codiscuss-tts-'));
421
422
  try {
422
423
  writeFileSync(join(work, 'in.wav'), wav);
423
- await run_file(join(home, LOCAL_DIR, 'cli', 'tools', `ffmpeg${LOCAL_EXE}`), ['-hide_banner', '-loglevel', 'error', '-i', join(work, 'in.wav'),
424
+ await run_file(join(speech_directory(home, 'tts'), 'cli', 'tools', `ffmpeg${LOCAL_EXE}`), ['-hide_banner', '-loglevel', 'error', '-i', join(work, 'in.wav'),
424
425
  '-c:a', 'aac', '-b:a', LOCAL_BIT_RATE, '-movflags', '+faststart', '-f', 'ipod', join(work, 'out.m4a')], { windowsHide: true, timeout: LOCAL_CONVERT_MS })
425
426
  .catch(() => { throw new Error('本机语音转码失败:请重新运行 local-tts-setup 技能修复安装'); });
426
427
  return readFileSync(join(work, 'out.m4a'));
@@ -439,7 +440,7 @@ async function local_once({ home, key, text, speaker, context, silence }, { requ
439
440
  try { response = await local_generate({ home, key, text, speaker, context }, request); }
440
441
  catch (error) {
441
442
  if (error.name === 'TimeoutError') throw new Error('本机语音合成超时,请稍后再试');
442
- if (started) throw new Error(`本机语音服务已启动但连接失败,请查看 ${join(home, LOCAL_DIR, 'serve.log')}`);
443
+ if (started) throw new Error(`本机语音服务已启动但连接失败,请查看 ${join(speech_directory(home, 'tts'), 'serve.log')}`);
443
444
  await start(home, key, request);
444
445
  started = true;
445
446
  continue;
@@ -452,7 +453,7 @@ async function local_once({ home, key, text, speaker, context, silence }, { requ
452
453
  if (!response.ok) {
453
454
  const code = (await response.json().catch(() => ({}))).error?.code;
454
455
  if (code === '@yovoice.error.modelRequired') throw new Error('这个音色的模型尚未安装:请让本机 AI 按 local-tts-setup 技能安装');
455
- throw new Error(`本机语音合成失败(HTTP ${response.status}${code ? ` ${code}` : ''}),请查看 ${join(home, LOCAL_DIR, 'data', 'logs')}`);
456
+ throw new Error(`本机语音合成失败(HTTP ${response.status}${code ? ` ${code}` : ''}),请查看 ${join(speech_directory(home, 'tts'), 'data', 'logs')}`);
456
457
  }
457
458
  const audio = await convert(home, wav_with_silence(Buffer.from(await response.arrayBuffer()), silence));
458
459
  return { audio: audio.toString('base64'), format: 'm4a', marks: [] };
@@ -460,7 +461,7 @@ async function local_once({ home, key, text, speaker, context, silence }, { requ
460
461
 
461
462
  /** Queue this process's local requests; each renews the lease when it arrives and, unless reading was stopped, when it ends. */
462
463
  function local_speak(input, transport) {
463
- const directory = join(input.home, LOCAL_DIR);
464
+ const directory = speech_directory(input.home, 'tts');
464
465
  local_renew(directory);
465
466
  const result = local_queue.then(() => local_once(input, transport));
466
467
  local_queue = result.catch(() => {}).then(() => local_renew(directory, { keep_release: true }));
@@ -479,7 +480,7 @@ export const STT_PROVIDERS = [
479
480
 
480
481
  /** Start the voice-input service (CrispASR); its token comes in the environment, never on the command line. */
481
482
  function local_stt_start(home, key, request) {
482
- const directory = join(home, LOCAL_STT_DIR);
483
+ const directory = speech_directory(home, 'stt');
483
484
  return local_supervise(home, 'stt', { executable: join(directory, 'cli', `crispasr${LOCAL_EXE}`), key, skill: 'local-stt-setup',
484
485
  args: port => ['--server', '--host', LOCAL_HOST, '--port', String(port), '--backend', 'qwen3', '-m', join(directory, 'models', LOCAL_STT_MODEL), '-l', 'zh'],
485
486
  env: { CRISPASR_API_KEYS: key }, ready: '/health' }, request);
@@ -501,7 +502,7 @@ function local_stt_send(home, key, wav, request) {
501
502
  * @returns {Promise<string>} The recognized text.
502
503
  */
503
504
  export async function local_transcribe({ home, key, wav }, { request = fetch, start = local_stt_start } = {}) {
504
- const directory = join(home, LOCAL_STT_DIR);
505
+ const directory = speech_directory(home, 'stt');
505
506
  local_renew(directory);
506
507
  try {
507
508
  let response, started = false;
@@ -544,7 +545,7 @@ export function provider_speak(provider, input, { request = fetch, open = (url,
544
545
  * @param {string} home The service home.
545
546
  */
546
547
  export function provider_release(provider, home) {
547
- if (provider === 'local') local_release(join(home, LOCAL_DIR));
548
+ if (provider === 'local') local_release(speech_directory(home, 'tts'));
548
549
  }
549
550
 
550
551
  /** The process listening on a local TCP port as `{ pid, name }`, or null when none or it cannot be looked up. */
@@ -586,8 +587,8 @@ async function kill_tree(pid) {
586
587
  * records one, so another program on its preferred port only makes the next start pick another port.
587
588
  */
588
589
  async function local_service_status(home, id, { find, probe }) {
589
- const { directory, program } = LOCAL_SERVICES[id];
590
- const installed = existsSync(join(home, directory, 'cli', `${program}${LOCAL_EXE}`));
590
+ const { program } = LOCAL_SERVICES[id];
591
+ const installed = existsSync(join(speech_directory(home, id), 'cli', `${program}${LOCAL_EXE}`));
591
592
  const port = local_port(home, id);
592
593
  if (!port) return { installed, port: LOCAL_SERVICES[id].port, pid: null, name: '', state: 'stopped' };
593
594
  const owner = await find(port);
@@ -622,7 +623,7 @@ export async function local_service_stop(home, id, { find = find_listener, probe
622
623
  if (status.state === 'other') throw new Error(`端口 ${status.port} 被其他程序(${status.name},PID ${status.pid})占用,未结束它`);
623
624
  if (status.state !== 'running') return local_services(home, { find, probe });
624
625
  if (!status.pid) {
625
- local_release(join(home, LOCAL_SERVICES[id].directory));
626
+ local_release(speech_directory(home, id));
626
627
  return local_services(home, { find, probe });
627
628
  }
628
629
  // It may have ended meanwhile (its lease ran out); whether it still runs afterwards is what counts.