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
@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
5
5
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
6
+ import { drafts_root } from './account_space.mjs';
6
7
  import { DatabaseSync } from 'node:sqlite';
7
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
8
9
  import { parseArgs } from 'node:util';
@@ -43,8 +44,12 @@ export function load_config(path) {
43
44
 
44
45
  /** Keep service-managed answers outside all room credentials, logs and databases. */
45
46
  export function service_drafts(home, directory) {
46
- const key = createHash('sha256').update(resolve(directory)).digest('hex');
47
- return join(home, 'drafts', key);
47
+ return join(drafts_root(home), room_draft_key(directory));
48
+ }
49
+
50
+ /** Stable room key across project data directory changes. */
51
+ export function room_draft_key(directory) {
52
+ return createHash('sha256').update(resolve(directory)).digest('hex');
48
53
  }
49
54
 
50
55
  /** Validate a launch draft with the same rules as a registered room configuration. */
@@ -70,6 +75,8 @@ export function validate_config(input, base_directory) {
70
75
  if (!adapter_profile(participant.adapter).efforts.includes(participant.effort)) delete participant.effort;
71
76
  }
72
77
  participant.cwd = participant.cwd ?? config.cwd;
78
+ if (participant.cwd && Array.isArray(config.extra_directories) && config.extra_directories.some(item =>
79
+ item?.access === 'read' && typeof item.path === 'string' && overlapping_directories(item.path, participant.cwd))) participant.project_access = 'read';
73
80
  participant.project_name = participant.project_name ?? config.discussion_project;
74
81
  participant.project_access = participant.project_access || config.project_access || 'read';
75
82
  // `own` is set only when the service takes over a manual member: it keeps its own session's permissions.
@@ -116,7 +123,9 @@ export function check_extra_directories(cwd, directories, { exists = true } = {}
116
123
  if (!Array.isArray(directories) || directories.length > MAX_EXTRA_DIRECTORIES) throw new Error(`extra_directories 须为最多 ${MAX_EXTRA_DIRECTORIES} 个目录的列表`);
117
124
  if (directories.length && !cwd) throw new Error('添加其他项目目录前须先指定房间的项目目录');
118
125
  const seen = cwd ? [cwd] : [];
119
- for (const directory of directories) {
126
+ for (const entry of directories) {
127
+ const directory = typeof entry === 'string' ? entry : entry?.path;
128
+ if (typeof entry !== 'string' && !['read', 'write'].includes(entry?.access)) throw new Error('项目目录权限须为 read 或 write');
120
129
  if (typeof directory !== 'string' || !isAbsolute(directory)) throw new Error('项目目录须为完整绝对路径');
121
130
  if (exists && (!existsSync(directory) || !statSync(directory).isDirectory())) throw new Error(`项目目录 ${directory} 在本机不存在或不是文件夹`);
122
131
  const overlap = seen.find(other => overlapping_directories(other, directory));
@@ -1,7 +1,7 @@
1
1
  /** Resident local service that dispatches registered rooms to software or configured API participants. */
2
2
  import { spawn, spawnSync } from 'node:child_process';
3
3
  import { createHash, randomUUID } from 'node:crypto';
4
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
4
+ import { appendFileSync, chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmdirSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
5
5
  import { homedir } from 'node:os';
6
6
  import { basename, dirname, join, resolve } from 'node:path';
7
7
  import { DatabaseSync } from 'node:sqlite';
@@ -10,14 +10,17 @@ import { parseArgs } from 'node:util';
10
10
  import { setTimeout as sleep } from 'node:timers/promises';
11
11
  import { cleanup_room, sweep_adapters } from './adapters/index.mjs';
12
12
  import { same_session_family } from './adapters/profiles.mjs';
13
+ import { room_directories } from './project_files.mjs';
14
+ import { ensure_global_experts_migrated } from './experts.mjs';
13
15
  import { atomic_json } from './files.mjs';
16
+ import * as storage_guard from './storage_guard.mjs';
14
17
  import { relay_health_writer } from './relay_health.mjs';
15
18
  import { t } from './i18n.mjs';
16
19
  import { DiscussionStore, acquire_lock, api, load_config, pause_if_running, service_drafts, validate_config } from './discussion_runner.mjs';
17
- import { FreeRoomRunner, write_proactive_access } from './free_runner.mjs';
20
+ import { FreeRoomRunner, member_drafts, write_proactive_access } from './free_runner.mjs';
18
21
  import { can_notify, notice_sent, receive_replies, send_notice } from './weixin.mjs';
19
22
  import { answer_by_weixin } from './question_weixin.mjs';
20
- import { OPERATOR_EVENTS_FILE, account_space } from './account_space.mjs';
23
+ import { OPERATOR_EVENTS_FILE, account_space, drafts_root } from './account_space.mjs';
21
24
  import { install_pi, pi_outdated } from './pi_runtime.mjs';
22
25
  import { site_fetch } from './entry_client.mjs';
23
26
  import { destroy_draft_space, destroy_room_sessions, room_bindings } from './room_destruction.mjs';
@@ -435,11 +438,37 @@ class RoomWorker {
435
438
 
436
439
  /** Keep workers aligned with the registry and tick each one per poll. */
437
440
  export class DiscussionService {
438
- constructor(home, create_runner = (config, store, log) => new FreeRoomRunner(config, store, undefined, log), log = () => {}) {
441
+ constructor(home, create_runner, log = () => {}, guard = storage_guard) {
439
442
  this.home = home;
440
- this.create_runner = create_runner;
443
+ this.guard = guard;
444
+ this.drafts_root = drafts_root(home);
445
+ this.create_runner = create_runner || ((config, store, write_log) => {
446
+ const runner = new FreeRoomRunner(config, store, undefined, write_log);
447
+ runner.on_drafts_finished = name => this.refresh_drafts(config, name);
448
+ runner.storage_reason = async stoppable => {
449
+ try {
450
+ const key = basename(config.draft_directory);
451
+ const disk = this.disk_space();
452
+ const low = this.guard.block_reason(null, key, disk);
453
+ if (low) return low;
454
+ let snapshot = await this.scan_storage(Boolean(this.guard.block_reason(this.storage, '', null)), disk);
455
+ if (!this.guard.block_reason(snapshot, '', null) && this.guard.block_reason(snapshot, key, null, { stoppable })) {
456
+ snapshot = await this.refresh_drafts(config);
457
+ }
458
+ return this.guard.block_reason(snapshot, key, this.disk_space(), { stoppable });
459
+ } catch (error) {
460
+ return this.guard.storage_error_reason ? this.guard.storage_error_reason(error) : storage_guard.storage_error_reason(error);
461
+ }
462
+ };
463
+ return runner;
464
+ });
441
465
  this.log = log;
442
466
  this.workers = new Map();
467
+ this.storage = null;
468
+ this.storage_scan = null;
469
+ this.storage_stops = new Map();
470
+ this.draft_scans = new Map();
471
+ this.disk_checked = -Infinity;
443
472
  // Rooms whose destruction this computer is still cleaning up; the loop leaves them to that one cleanup.
444
473
  this.cleaning = new Set();
445
474
  // How often each room is checked without a push: a local site costs nothing, a hosted one spends its database quota.
@@ -578,9 +607,107 @@ export class DiscussionService {
578
607
  })();
579
608
  this.streams.set(site, stream);
580
609
  }
581
- /** Publish every room's latest state for `codiscuss status` and the website's service check. */
610
+ /** Concurrent deliveries and maintenance share one scan for this service home. */
611
+ disk_space() { return storage_guard.storage_disk(this.home, this.drafts_root, this.guard.disk_free); }
612
+
613
+ scan_storage(force = false, disk = this.disk_space()) {
614
+ if (this.storage_scan) return this.storage_scan;
615
+ const volumes = disk.volumes || [disk.available_bytes];
616
+ const drop = volumes.reduce((sum, available, index) => sum + Math.max(0, (this.scan_available?.[index] ?? available) - available), 0);
617
+ const remaining = this.storage && storage_guard.HOME_LIMIT - this.storage.total_bytes;
618
+ const early = remaining > 0 && drop >= remaining;
619
+ if (!force && !early && this.storage) return this.storage;
620
+ this.scan_available = volumes;
621
+ this.storage_disk = disk;
622
+ this.storage_scan = this.guard.measure(this.home, { members: true, drafts_root: this.drafts_root }).catch(error => { this.storage = null; throw error; }).then(snapshot => {
623
+ if (early && snapshot.unreadable > (this.storage.unreadable ?? 0)) {
624
+ snapshot = { ...snapshot, uncertain_growth: true };
625
+ }
626
+ this.storage = snapshot;
627
+ for (const { runner, config } of this.workers.values()) {
628
+ if (!runner?.reclaim_failed_scratch || this.closed) continue;
629
+ const room_bytes = snapshot.rooms[basename(config.draft_directory)] || 0;
630
+ if (snapshot.draft_bytes >= storage_guard.DRAFT_LIMIT * storage_guard.SCRATCH_PRESSURE_RATIO ||
631
+ room_bytes >= storage_guard.ROOM_DRAFT_LIMIT * storage_guard.SCRATCH_PRESSURE_RATIO) {
632
+ try { runner.reclaim_failed_scratch(); } catch (error) { this.log(error.message); }
633
+ }
634
+ }
635
+ if (!this.closed) this.enforce_storage();
636
+ return snapshot;
637
+ }).finally(() => { this.storage_scan = null; });
638
+ return this.storage_scan;
639
+ }
640
+
641
+ /** Refresh a finished member or a blocked room, sharing simultaneous reads of the same subtree. */
642
+ async refresh_drafts(config, member) {
643
+ if (this.storage_scan) await this.storage_scan;
644
+ const base = this.storage;
645
+ if (!base || base.truncated) return this.scan_storage(true);
646
+ const path = member ? member_drafts(config, member) : config.draft_directory;
647
+ if (this.draft_scans.has(path)) return this.draft_scans.get(path);
648
+ for (const [other, pending] of this.draft_scans) {
649
+ if (dirname(other) === path || dirname(path) === other) {
650
+ await pending;
651
+ return this.refresh_drafts(config, member);
652
+ }
653
+ }
654
+ const room = basename(config.draft_directory);
655
+ const parents = [dirname(config.draft_directory), config.draft_directory, path];
656
+ if (parents.some(dir => lstatSync(dir, { throwIfNoEntry: false })?.isSymbolicLink())) return this.scan_storage(true);
657
+ const scan = this.guard.measure(path, { model_dirs: [], members: true, room_key: member ? '' : room }).then(async usage => {
658
+ if (this.storage_scan) return this.storage_scan;
659
+ if (this.storage !== base) return this.storage || this.scan_storage(true);
660
+ if (usage.shared_links || usage.truncated || usage.unreadable) return this.scan_storage(true);
661
+ const members = (base.members ||= {})[room] ||= {};
662
+ const delta = usage.total_bytes - ((member ? members[basename(path)] : base.rooms[room]) || 0);
663
+ if (delta && (member ? base.linked_members?.[room]?.[basename(path)] : base.shared_links)) return this.scan_storage(true);
664
+ if (member) members[basename(path)] = usage.total_bytes;
665
+ else base.members[room] = usage.members?.[room] || {};
666
+ base.rooms[room] = (base.rooms[room] || 0) + delta;
667
+ base.draft_bytes += delta;
668
+ base.total_bytes += delta;
669
+ if (!this.closed) this.enforce_storage();
670
+ return base;
671
+ }).finally(() => this.draft_scans.delete(path));
672
+ this.draft_scans.set(path, scan);
673
+ return scan;
674
+ }
675
+
676
+ /** Apply a sampled limit to busy rooms through their capability-aware stop operation. */
677
+ enforce_storage() {
678
+ for (const { runner, config } of this.workers.values()) {
679
+ if (!runner?.inbox?.executions?.length && !runner?.children?.size) continue;
680
+ const reason = this.guard.block_reason(this.storage, basename(config.draft_directory), this.storage_disk);
681
+ if (!reason || this.storage_stops.has(runner)) continue;
682
+ const stopping = Promise.resolve().then(() => runner.stop_for_storage(reason))
683
+ .catch(error => this.log(error.message)).finally(() => this.storage_stops.delete(runner));
684
+ this.storage_stops.set(runner, stopping);
685
+ }
686
+ }
687
+
688
+ /** Check disk space independently of any pending quota scan. */
689
+ monitor_storage(maintenance = false, now = Date.now()) {
690
+ const active = [...this.workers.values()].some(({ runner }) => runner?.inbox?.executions?.length || runner?.children?.size);
691
+ if (!active && !maintenance) return;
692
+ const disk_due = active && now - this.disk_checked >= storage_guard.DISK_CHECK_MS;
693
+ if (disk_due) {
694
+ this.disk_checked = now;
695
+ this.storage_disk = this.disk_space();
696
+ this.enforce_storage();
697
+ }
698
+ if (!this.storage_scan && (maintenance || disk_due)) {
699
+ const scan = this.scan_storage(maintenance, disk_due ? this.storage_disk : undefined);
700
+ if (!this.storage_scan) return;
701
+ scan.catch(error => this.log(error.message));
702
+ }
703
+ }
704
+
705
+ /** Publish every room's latest state for the status command and website. */
582
706
  write_status() {
707
+ const warning_reason = storage_guard.warn_reason(this.storage);
583
708
  atomic_json(join(this.home, 'status.json'), { pid: process.pid, updated_at: Math.floor(Date.now() / 1000),
709
+ storage: this.storage && { total_bytes: this.storage.total_bytes, local_bytes: this.storage.local_bytes || 0,
710
+ unreadable: this.storage.unreadable || 0, warning: Boolean(warning_reason), warning_reason },
584
711
  rooms: [...this.workers.values()].map(worker => worker.state) });
585
712
  }
586
713
  /** Tick one room; a room deleted on its website is unregistered here. */
@@ -616,7 +743,8 @@ export class DiscussionService {
616
743
  // Its runtime, task files and answer drafts serve no one now; a file still held is left to the periodic sweep.
617
744
  try { remove_room_files(this.home, path, directory); } catch (error) { this.log(`${worker.state.room || path}: 本机文件未能删除,稍后清理:${error.message}`); }
618
745
  const folder = dirname(resolve(path));
619
- const leftover = (dirname(folder) === resolve(this.home, 'launches') && existsSync(folder)) || (directory && existsSync(service_drafts(this.home, directory)));
746
+ const draft_dirs = [directory, folder, join(folder, 'runtime')].filter(Boolean).map(dir => service_drafts(this.home, dir));
747
+ const leftover = (dirname(folder) === resolve(this.home, 'launches') && existsSync(folder)) || draft_dirs.some(existsSync);
620
748
  items.push({ kind: 'runtime_files', state: leftover ? 'failed' : 'deleted' });
621
749
  this.log(`${worker.state.site || ''}/${worker.state.room || path}: 房间已在网站删除,已撤销登记并删除本机文件`);
622
750
  if (record?.sessions) this.report_destruction(config, items);
@@ -684,6 +812,8 @@ export class DiscussionService {
684
812
  }
685
813
  async close() {
686
814
  this.closed = true;
815
+ await this.storage_scan?.catch(error => this.log(error.message));
816
+ await Promise.all(this.storage_stops.values());
687
817
  for (const stream of this.streams.values()) stream.controller.abort();
688
818
  await Promise.all([...this.streams.values()].map(stream => stream.done));
689
819
  this.streams.clear();
@@ -707,7 +837,7 @@ export function folders_in_use(home, except) {
707
837
  if (resolve(path) === resolve(except)) continue;
708
838
  try {
709
839
  const config = JSON.parse(readFileSync(path, 'utf8'));
710
- for (const folder of [config.cwd, ...(config.extra_directories || [])]) if (typeof folder === 'string' && folder) used.add(resolve(folder));
840
+ for (const folder of room_directories(config)) if (typeof folder === 'string' && folder) used.add(resolve(folder));
711
841
  } catch { /* An unreadable room names no folder. */ }
712
842
  }
713
843
  return used;
@@ -753,24 +883,67 @@ export function sessions_in_use(home, except) {
753
883
  return used;
754
884
  }
755
885
 
886
+ /**
887
+ * Remove a file or directory tree, clearing read-only bits on failure and continuing past locked or
888
+ * permission-denied entries so sibling files and later cleanup targets are still removed.
889
+ */
890
+ function remove_tree(target) {
891
+ if (!target) return;
892
+ try { rmSync(target, { recursive: true, force: true }); return; }
893
+ catch (error) { if (error.code === 'ENOENT') return; }
894
+ let first_error = null;
895
+ const note = (error) => { if (!first_error && error.code !== 'ENOENT') first_error = error; };
896
+ const make_writable = (path, mode) => { try { chmodSync(path, mode); } catch { /* Best effort. */ } };
897
+ const walk = (path) => {
898
+ let entry;
899
+ try { entry = lstatSync(path); } catch (error) { note(error); return; }
900
+ if (entry.isSymbolicLink()) {
901
+ try { unlinkSync(path); }
902
+ catch (error) { try { rmdirSync(path); } catch { note(error); } }
903
+ return;
904
+ }
905
+ if (!entry.isDirectory()) {
906
+ try { unlinkSync(path); return; } catch (error) {
907
+ make_writable(path, 0o666);
908
+ try { unlinkSync(path); } catch { note(error); }
909
+ }
910
+ return;
911
+ }
912
+ make_writable(path, 0o777);
913
+ let children;
914
+ try { children = readdirSync(path); } catch (error) { note(error); return; }
915
+ for (const name of children) walk(join(path, name));
916
+ try { rmdirSync(path); } catch (error) {
917
+ make_writable(path, 0o777);
918
+ try { rmdirSync(path); } catch { note(error); }
919
+ }
920
+ };
921
+ walk(target);
922
+ if (first_error) throw first_error;
923
+ }
924
+
756
925
  /** Delete one room's local files: its adapter state, answer drafts, and its launch folder when created under launches/. */
757
926
  export function remove_room_files(home, config_path, data_directory) {
758
927
  const folder = dirname(resolve(config_path));
759
- for (const directory of [data_directory, folder, join(folder, 'runtime')].filter(Boolean)) {
760
- cleanup_room(directory);
761
- rmSync(service_drafts(home, directory), { recursive: true, force: true });
928
+ const directories = [...new Set([data_directory, folder, join(folder, 'runtime')].filter(Boolean).map(dir => resolve(dir)))];
929
+ let first_error = null;
930
+ const attempt = (fn) => { try { fn(); } catch (error) { if (!first_error) first_error = error; } };
931
+ for (const directory of directories) {
932
+ attempt(() => cleanup_room(directory));
933
+ attempt(() => remove_tree(service_drafts(home, directory)));
762
934
  }
763
- if (dirname(folder) === resolve(home, 'launches')) rmSync(folder, { recursive: true, force: true });
935
+ if (dirname(folder) === resolve(home, 'launches')) attempt(() => remove_tree(folder));
936
+ if (first_error) throw first_error;
764
937
  }
765
938
 
766
939
  /** Keep only the newest part of a log that grew past the limit; writers append, so they continue at its new end. */
767
- function trim_log(path) {
768
- if (!existsSync(path) || statSync(path).size <= LOG_LIMIT_BYTES) return false;
769
- const size = statSync(path).size, tail = Buffer.alloc(LOG_KEEP_BYTES);
940
+ function trim_log(path, limit = LOG_LIMIT_BYTES, keep = LOG_KEEP_BYTES) {
941
+ if (!existsSync(path) || statSync(path).size <= limit) return false;
942
+ const size = statSync(path).size, tail = Buffer.alloc(keep);
770
943
  const handle = openSync(path, 'r');
771
- try { readSync(handle, tail, 0, LOG_KEEP_BYTES, size - LOG_KEEP_BYTES); } finally { closeSync(handle); }
944
+ try { readSync(handle, tail, 0, keep, size - keep); } finally { closeSync(handle); }
772
945
  // Start at a whole line so the kept part does not open mid-entry.
773
- writeFileSync(path, tail.subarray(tail.indexOf(10) + 1));
946
+ writeFileSync(path, keep === storage_guard.LOG_TAIL ? tail : tail.subarray(tail.indexOf(10) + 1));
774
947
  return true;
775
948
  }
776
949
 
@@ -782,24 +955,32 @@ function current_executions(directory) {
782
955
  try {
783
956
  if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='free_deliveries'").get()) return new Set();
784
957
  return new Set(db.prepare('SELECT execution_id FROM free_deliveries').all().map(row => row.execution_id));
785
- } catch { return null; } finally { db.close(); }
958
+ } finally { db.close(); }
786
959
  }
787
960
 
788
961
  /** Remove a room's per-execution files once they are a week old and no member's delivery still names the execution. */
789
- function sweep_execution_files(directory, now) {
962
+ function sweep_execution_files(directory, now, removed_logs) {
790
963
  if (!existsSync(directory)) return 0;
791
964
  const current = current_executions(directory);
792
- // An unreadable delivery table gives no proof which executions ended, so nothing is removed.
793
- if (!current) return 0;
794
965
  let removed = 0;
795
966
  // Credential and task files sit in each member's runtime folder (`members/<key>`), logs in the runtime directory.
796
967
  const members = join(directory, 'members');
797
- const folders = [directory, ...(existsSync(members) ? readdirSync(members).map(name => join(members, name)) : [])];
798
- for (const [folder, name] of folders.flatMap(folder => { try { return readdirSync(folder).map(name => [folder, name]); } catch { return []; } })) {
968
+ const folders = [directory];
969
+ if (lstatSync(members, { throwIfNoEntry: false })?.isDirectory()) {
970
+ for (const entry of readdirSync(members, { withFileTypes: true })) {
971
+ if (entry.isDirectory()) folders.push(join(members, entry.name));
972
+ }
973
+ }
974
+ for (const folder of folders) for (const name of readdirSync(folder)) {
799
975
  const id = EXECUTION_FILE.exec(name)?.[1];
800
- if (!id || current.has(Number(id))) continue;
976
+ if (!id) continue;
801
977
  const path = join(folder, name);
802
- if (now - statSync(path).mtimeMs < STALE_LAUNCH_MS) continue;
978
+ const entry = lstatSync(path, { throwIfNoEntry: false });
979
+ if (!entry?.isFile() || entry.nlink > 1) continue;
980
+ if (current.has(Number(id)) || now - entry.mtimeMs < STALE_LAUNCH_MS) {
981
+ if (name.endsWith('.log') && trim_log(path, storage_guard.LOG_TAIL, storage_guard.LOG_TAIL)) removed_logs.push(path);
982
+ continue;
983
+ }
803
984
  rmSync(path, { force: true });
804
985
  removed += 1;
805
986
  }
@@ -816,17 +997,18 @@ function launch_touched(folder) {
816
997
  * never confirmed, once they are a week old and no process holds them; answer drafts whose folder is gone; registered
817
998
  * rooms' task, credential and log files of executions that ended a week ago; and the oversized part of the service's logs. Registered rooms, settings and the local website's database are never touched.
818
999
  */
819
- export function sweep_service_home(home, now = Date.now()) {
1000
+ export function sweep_service_home(home, now = Date.now(), log = () => {}) {
820
1001
  const registered = read_registry(home).map(path => dirname(resolve(path)));
821
- const launches = join(home, 'launches'), removed = { launches: [], drafts: [], logs: [], execution_files: 0, adapter_files: 0 };
1002
+ const launches = join(home, 'launches'), removed = { launches: [], drafts: [], logs: [], execution_files: 0, adapter_files: 0, failures: 0 };
1003
+ const failed = (path, error) => { removed.failures++; log(path + ": " + error.message); };
822
1004
  const resolved_home = resolve(home);
823
1005
  if (basename(resolved_home) === '.codiscuss') {
824
- try { removed.adapter_files = sweep_adapters(resolved_home, dirname(resolved_home)); } catch { /* Sandboxed or held; the next sweep retries. */ }
1006
+ try { removed.adapter_files = sweep_adapters(resolved_home, dirname(resolved_home)); } catch (error) { failed(resolved_home, error); }
825
1007
  }
826
1008
  for (const name of existsSync(launches) ? readdirSync(launches) : []) {
827
1009
  const folder = join(launches, name);
828
1010
  if (registered.includes(folder) || service_pid(folder) || service_pid(join(folder, 'runtime')) || now - launch_touched(folder) < STALE_LAUNCH_MS) continue;
829
- try { remove_room_files(home, join(folder, 'config.json')); removed.launches.push(name); } catch { /* Still held; the next sweep retries. */ }
1011
+ try { remove_room_files(home, join(folder, 'config.json')); removed.launches.push(name); } catch (error) { failed(folder, error); }
830
1012
  }
831
1013
  // A draft folder is keyed by its room's data directory; one matching no remaining folder or registered room is orphaned.
832
1014
  const live = new Set(), runtimes = new Set();
@@ -837,21 +1019,24 @@ export function sweep_service_home(home, now = Date.now()) {
837
1019
  const { directory } = validate_config(JSON.parse(readFileSync(path, 'utf8')), folder);
838
1020
  live.add(service_drafts(home, directory));
839
1021
  runtimes.add(resolve(directory));
840
- } catch { /* Covered by the folder keys; an unreadable configuration keeps its execution files. */ }
1022
+ } catch (error) { failed(path, error); }
841
1023
  }
842
1024
  for (const directory of runtimes) {
843
- try { removed.execution_files += sweep_execution_files(directory, now); } catch { /* Still held; the next sweep retries. */ }
1025
+ try { removed.execution_files += sweep_execution_files(directory, now, removed.logs); } catch (error) { failed(directory, error); }
844
1026
  }
845
1027
  for (const name of existsSync(launches) ? readdirSync(launches) : []) {
846
1028
  for (const directory of [join(launches, name), join(launches, name, 'runtime')]) live.add(service_drafts(home, directory));
847
1029
  }
848
- const drafts = join(home, 'drafts');
1030
+ const drafts = drafts_root(home);
849
1031
  for (const name of existsSync(drafts) ? readdirSync(drafts) : []) {
850
1032
  if (live.has(join(drafts, name))) continue;
851
- rmSync(join(drafts, name), { recursive: true, force: true });
852
- removed.drafts.push(name);
1033
+ try { remove_tree(join(drafts, name)); removed.drafts.push(name); }
1034
+ catch (error) { failed(join(drafts, name), error); }
1035
+ }
1036
+ for (const name of SERVICE_LOGS) {
1037
+ try { if (trim_log(join(home, name))) removed.logs.push(name); }
1038
+ catch (error) { failed(join(home, name), error); }
853
1039
  }
854
- for (const log of SERVICE_LOGS) if (trim_log(join(home, log))) removed.logs.push(log);
855
1040
  return removed;
856
1041
  }
857
1042
 
@@ -875,6 +1060,7 @@ export function service_ready(home, pid = service_pid(home)) {
875
1060
  /** Foreground service loop; `start` runs this detached in the background. */
876
1061
  export async function run_service(home, output = () => {}) {
877
1062
  assert_shared_home(home);
1063
+ ensure_global_experts_migrated(home);
878
1064
  const release = acquire_lock(home);
879
1065
  const log_line = message => {
880
1066
  const line = `${new Date().toISOString()} ${message}`;
@@ -927,10 +1113,11 @@ export async function run_service(home, output = () => {}) {
927
1113
  };
928
1114
  while (!stopped && !existsSync(stop_path)) {
929
1115
  try { await service.tick({ wait: false }); } catch (error) { log_line(`服务检查失败:${error.message}`); }
1116
+ try { service.monitor_storage(Date.now() - swept_at >= SWEEP_MS); } catch (error) { log_line(error.message); }
930
1117
  if (Date.now() - swept_at >= SWEEP_MS) {
931
1118
  swept_at = Date.now();
932
1119
  try {
933
- const removed = sweep_service_home(home);
1120
+ const removed = sweep_service_home(home, Date.now(), log_line);
934
1121
  if (removed.launches.length || removed.drafts.length || removed.logs.length || removed.execution_files || removed.adapter_files) {
935
1122
  log_line(`清理本机文件:启动目录 ${removed.launches.length} 个,草稿 ${removed.drafts.length} 个,执行文件 ${removed.execution_files} 个,软件遗留项 ${removed.adapter_files} 个,日志 ${removed.logs.join('、') || '无'}`);
936
1123
  }
@@ -1047,7 +1234,7 @@ function service_status(home) {
1047
1234
  const path = join(home, 'status.json');
1048
1235
  const saved = pid && existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
1049
1236
  const last = saved.pid === pid ? saved : {};
1050
- return { running: Boolean(pid), ready: service_ready(home, pid), pid, home, configs: read_registry(home), updated_at: last.updated_at || 0, rooms: last.rooms || [] };
1237
+ return { running: Boolean(pid), ready: service_ready(home, pid), pid, home, drafts_root: drafts_root(home), configs: read_registry(home), updated_at: last.updated_at || 0, storage: last.storage || null, rooms: last.rooms || [] };
1051
1238
  }
1052
1239
 
1053
1240
  /** Open each registered site once in the default browser. */
@@ -11,7 +11,7 @@ import { atomic_json } from './files.mjs';
11
11
  import { WORKFLOW_ID_PATTERN, install_workflow_folder, parse_markdown, workflow_directory } from './workflows.mjs';
12
12
 
13
13
  const SOURCE = fileURLToPath(new URL('../.agents/skills/', import.meta.url));
14
- export const SKILLS = ['discuss-host', 'discuss-participant', 'discuss-goal', 'discuss-session', 'discuss-report', 'share-card', 'workflow-creator', 'local-tts-setup', 'local-stt-setup'];
14
+ export const SKILLS = ['discuss-host', 'discuss-participant', 'discuss-goal', 'discuss-session', 'discuss-report', 'share-card', 'workflow-creator', 'local-tts-setup', 'local-stt-setup', 'codiscuss-draft-cleanup'];
15
15
  const LEGACY_MANIFEST = '.codiscuss-skills.json';
16
16
 
17
17
  /** Hash names and contents, rejecting links instead of following them outside a skill. */
@@ -79,7 +79,7 @@ export function access_label(level) { return level === 'own' ? '自行决定' :
79
79
  * Subcommands an automatic task may run; service, run, api, setup and the rest of launch stay unapproved.
80
80
  * `launch workflow-adopt`, `launch workflow-join`, `launch workflow-leave` and `launch host-control` check themselves that the caller is the room's host (adopt and host-control also need the owner's grant).
81
81
  */
82
- export const TASK_SUBCOMMANDS = ['room', 'message', 'turn', 'state', 'goal', 'mode', 'review', 'sequence', 'question', 'execution', 'health', 'schema', 'launch workflow-adopt', 'launch workflow-join', 'launch workflow-leave', 'launch host-control', 'attachment', 'launch image', 'repo', 'site', 'share-card'];
82
+ export const TASK_SUBCOMMANDS = ['room', 'message', 'turn', 'state', 'goal', 'mode', 'review', 'sequence', 'question', 'execution', 'health', 'schema', 'launch workflow-adopt', 'launch workflow-promote', 'launch workflow-join', 'launch workflow-leave', 'launch host-control', 'attachment', 'launch image', 'repo', 'site', 'share-card'];
83
83
 
84
84
  /**
85
85
  * The limit on a quick answer given inline with --body: a run allowed only codiscuss commands refuses a command line
@@ -189,7 +189,7 @@ export function free_task_text({ name, discussion, discussion_request, profile,
189
189
  const extras = extra_directories.length ? 'extra_directories 是本房间的其他项目目录,access 为 read 的只读、不修改。' : '';
190
190
  // The expert's own knowledge: read its index, write what it verified; it may write there whatever its project access.
191
191
  const knowing = knowledge ? 'knowledge_directory 里每个文件夹是一条你自己的技能:先读各条 SKILL.md 开头的描述,用到哪条再读哪条的 references;查证过的新知识写进对应技能的 references;可以新建一条技能,新建时写好 SKILL.md(头信息有 name、description);写之前先读当前内容(别的房间可能刚写过)。' : '';
192
- const instructions = `${software_rules(profile, cli, extra_directories)}${scope}${project_rule(profile, '按请求', extra_directories)}${extras}${commands}草稿写在 draft_directory。${knowing}`;
192
+ const instructions = `${software_rules(profile, cli, extra_directories)}${scope}${project_rule(profile, '按请求', extra_directories)}${extras}${commands}草稿写在 draft_directory。小型可重建临时文件放在 scratch_directory,执行成功后会清理。大型素材和仓库在项目目录中处理,即使项目只读也禁止复制到 draft_directory 或 scratch_directory。只读时直接读取原件,确需工作副本时请用户指定可写的项目目录。交付物和未提交修改保存在临时目录之外。${knowing}`;
193
193
  if (discussion_request) {
194
194
  const role = discussion_request.purpose === 'discuss_host' ? '主持任务' : '发言请求';
195
195
  const prompt = `你(${name})收到了讨论中的${role}。先读任务文件 ${task_path},按其中列出的技能处理本次请求并保存结果。${read_rule}${files}`;