ai_co_discuss 0.4.49 → 0.4.52

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.
@@ -12,6 +12,7 @@ import { randomBytes } from 'node:crypto';
12
12
  import { closeSync, copyFileSync, cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, realpathSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
13
13
  import http from 'node:http';
14
14
  import { homedir, tmpdir } from 'node:os';
15
+ import tls from 'node:tls';
15
16
  import { dirname, extname, join, resolve } from 'node:path';
16
17
  import { fileURLToPath, pathToFileURL } from 'node:url';
17
18
  import { parseArgs } from 'node:util';
@@ -43,7 +44,12 @@ const VERSION = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')).ver
43
44
  const NPM_PACKAGE = 'ai_co_discuss';
44
45
  const LATEST_URL = `https://registry.npmjs.org/${NPM_PACKAGE}/latest`;
45
46
  const LATEST_TTL_MS = 60 * 60 * 1000;
46
- const LATEST_TIMEOUT_MS = 8000;
47
+ const OUTSIDE_TIMEOUT_MS = 15_000, OUTSIDE_ATTEMPTS = 2;
48
+ // Node 24 (OpenSSL 3.5) offers a post-quantum key share first, which makes its TLS greeting span several packets; behind
49
+ // a Clash (Mihomo) TUN such connections were reset more than half the time, while curl and browsers got through (seen
50
+ // 2026-11-14). What the panel fetches outside is public (the latest version, a site's entry address, the relay's state),
51
+ // so it offers the classic key shares only.
52
+ tls.DEFAULT_ECDH_CURVE = 'X25519:prime256v1:secp384r1';
47
53
  const STATE_FILE = 'admin-panel.json';
48
54
  // An update's progress and report, kept in the service directory (panel_updater.mjs writes it too), and how long an
49
55
  // unfinished one blocks another.
@@ -95,10 +101,27 @@ function service_overview(data) {
95
101
 
96
102
  let latest = { at: 0, version: '' };
97
103
 
104
+ /**
105
+ * Fetch an outside address, trying once more when the connection is dropped; a request that stalls to its timeout is not
106
+ * tried again (that would keep the owner waiting). Failing is reported naming the host, not as a problem of the site.
107
+ */
108
+ async function fetch_outside(url, timeout_ms) {
109
+ for (let attempt = 1; ; attempt += 1) {
110
+ try {
111
+ return await fetch(url, { signal: AbortSignal.timeout(timeout_ms) });
112
+ } catch (error) {
113
+ const timed_out = error.name === 'TimeoutError';
114
+ if (!timed_out && attempt < OUTSIDE_ATTEMPTS) continue;
115
+ const why = timed_out ? `${timeout_ms / 1000} 秒内没有响应` : `连接被断开(${error.cause?.code || error.message})`;
116
+ throw new Error(`连不上 ${new URL(url).host}:${why},请检查这台电脑的网络或代理后重试`);
117
+ }
118
+ }
119
+ }
120
+
98
121
  /** The newest published version, asked of the npm registry at most once an hour (nothing about this computer is sent). */
99
122
  async function latest_version(force = false) {
100
123
  if (!force && latest.version && Date.now() - latest.at < LATEST_TTL_MS) return latest.version;
101
- const response = await fetch(LATEST_URL, { signal: AbortSignal.timeout(LATEST_TIMEOUT_MS) });
124
+ const response = await fetch_outside(LATEST_URL, OUTSIDE_TIMEOUT_MS);
102
125
  if (!response.ok) throw new Error(`查询新版本失败(HTTP ${response.status})`);
103
126
  latest = { at: Date.now(), version: String((await response.json()).version || '') };
104
127
  return latest.version;
@@ -503,7 +526,7 @@ function run_instance(data, name, command) {
503
526
  // An account without its own Windows user runs as the owner and could read everything the owner can; it is not let
504
527
  // run while people outside can reach the entry.
505
528
  if (command === 'start' && process.platform === 'win32' && !read_os_users(data)[name] && entry_settings(data).mode !== 'local') {
506
- throw new Error(`外网访问已开启,${name} 未隔离(以你的身份运行),不能启动:请先隔离该账号,或把外网访问改为“仅本机”`);
529
+ throw new Error(`外网访问已开启,${name} 未隔离(以你的身份运行),不能启动:请先隔离该账号,或把登录入口的访问方式改为“仅这台电脑”`);
507
530
  }
508
531
  if (command === 'start' && read_os_users(data)[name]) {
509
532
  const { local_script } = shared_paths();
@@ -775,7 +798,7 @@ function bound_site(data) {
775
798
  /** Ask the relay's entry Worker whether it is one and whether this computer is connected to it. */
776
799
  async function relay_status(relay_url, machine) {
777
800
  try {
778
- const answer = await fetch(`${relay_url}/_codiscuss/status?machine=${machine || '0'.repeat(32)}`, { signal: AbortSignal.timeout(RELAY_CHECK_MS) });
801
+ const answer = await fetch_outside(`${relay_url}/_codiscuss/status?machine=${machine || '0'.repeat(32)}`, RELAY_CHECK_MS);
779
802
  const result = await answer.json();
780
803
  return result.service === 'codiscuss-entry' ? { reachable: true, online: Boolean(result.online) } : { reachable: false, online: false };
781
804
  } catch { return { reachable: false, online: false }; }
@@ -820,7 +843,7 @@ async function set_entry_mode(data, mode) {
820
843
  const users = read_os_users(data), accounts = read_accounts(data);
821
844
  const exposed = [];
822
845
  for (const [name, account] of Object.entries(accounts)) if (!users[name] && await instance_running(account.port)) exposed.push(name);
823
- if (exposed.length) throw new Error(`未隔离的账号正在运行(${exposed.join('、')}),它们以你的身份运行,开启外网访问前请先停止或隔离`);
846
+ if (exposed.length) throw new Error(`未隔离的账号正在运行(${exposed.join('、')}),它们以你的身份运行,改用线上中转或自有域名前请先停止或隔离`);
824
847
  }
825
848
  save_entry_settings(data, { mode });
826
849
  if (mode !== 'local' && !(await entry_status(data)).running) { await start_entry(data); save_entry_settings(data, { running: true }); }
@@ -893,7 +916,8 @@ async function join_relay(data, text) {
893
916
 
894
917
  /** The entry Worker address an online site gives (`GET /api/entry`). */
895
918
  async function site_entry_url(site) {
896
- const given = await fetch(`${site}/api/entry`, { signal: AbortSignal.timeout(RELAY_CHECK_MS) }).then(answer => answer.json()).catch(() => ({}));
919
+ const answer = await fetch_outside(`${site}/api/entry`, OUTSIDE_TIMEOUT_MS);
920
+ const given = await answer.json().catch(() => ({}));
897
921
  if (!given.entry_url) throw new Error(`${site} 没有提供入口地址:请部署线上站点的人在部署配置里设置 ENTRY_URL 并重新发布`);
898
922
  return given.entry_url;
899
923
  }
@@ -1,133 +1,135 @@
1
- #!/usr/bin/env node
2
- /** Unified entrypoint for the local service and the discussion website client. */
3
- import { spawnSync } from 'node:child_process';
4
- import { fileURLToPath } from 'node:url';
5
- import { parseArgs } from 'node:util';
6
-
7
- import { admin_main } from './admin_account.mjs';
8
- import { main as service_main, read_registry, run_service, service_home, service_pid } from './discussion_service.mjs';
9
- import { launch_main } from './discussion_launch.mjs';
10
- import { local_settings, setup_main } from './discussion_setup.mjs';
11
- import { local_main } from './discussion_local.mjs';
12
-
13
- const HELP = `AI CoDiscuss CLI
14
-
15
- 用法:codiscuss [命令] [选项]
16
-
17
- (无命令) 在当前终端启动服务,Ctrl+C 停止
18
- install / setup 安装持久命令并配置 / 配置已有安装
19
- local COMMAND 管理本机网站,或 connect 连接线上站点
20
- token 生成线上网站的一次性管理员注册令牌
21
- panel [open|start|stop] 打开本机管理面板(托管用户、命令行登录、API 密钥)
22
- launcher 生成“共议.exe”与桌面、开始菜单快捷方式,双击即可启动(Windows)
23
- service COMMAND 启动、停止、查询服务,或登记房间
24
- launch COMMAND 保存启动配置,或从 AI 对话启动讨论
25
- room COMMAND 创建、读取或更新讨论房间
26
- message COMMAND 检索原文、提交观点
27
- attachment COMMAND 上传、查询与下载讨论附件
28
- turn COMMAND 安排发言、读取待办与回答
29
- state COMMAND 读取或保存共享状态
30
- run COMMAND 配置、启动或暂停网站上的讨论
31
- execution COMMAND 进入或查询一次 AI 执行
32
- health 检查网站健康状态
33
- schema [COMMAND] 离线查看命令与参数
34
- api PATH 访问尚未封装的网站接口
35
-
36
- codiscuss service --help
37
- codiscuss room --help
38
- codiscuss health --site http://127.0.0.1:8765
39
-
40
- 网站操作使用 --site、DISCUSS_URL 或 --access-file 中的站点,并需要 Python 3.10+。
41
- 原有 start、status、stop、add 等服务命令继续兼容。
42
- `;
43
- const SERVICE_HELP = `AI CoDiscuss 讨论服务
44
-
45
- 用法:codiscuss service [命令] [选项]
46
-
47
- (无命令) / run 在当前终端运行,Ctrl+C 停止
48
- start 在后台启动,已运行时复用
49
- status 查看服务与房间状态
50
- stop 暂停托管中的讨论并停止服务
51
- add --config FILE 登记房间的私有接入配置
52
- remove --config FILE 移除已登记配置
53
- list 列出已登记配置
54
- clean 立即清理无房间使用的启动目录、草稿与超长日志(服务每 6 小时自动清理一次)
55
- open 后台启动并打开讨论网站
56
- shortcut 创建 Windows 桌面快捷方式
57
- autostart on|off 开启或关闭 Windows 登录自启
58
-
59
- --json 以 JSON 输出命令结果(前台运行除外)
60
- -h, --help 显示帮助
61
-
62
- 登记或启动服务不会自动开始讨论,仍需在网页明确启动。
63
- `;
64
- const STATUS_LABELS = { running: '运行中', paused: '已暂停', idle: '等待启动', error: '异常' };
65
- const SERVICE_COMMANDS = new Set(['start', 'status', 'stop', 'add', 'remove', 'list', 'open', 'shortcut', 'autostart']);
66
- const WEBSITE_CLIENT = fileURLToPath(new URL('./discuss.py', import.meta.url));
67
-
68
- /** Forward untouched arguments, streams and exit codes to the existing Python client. */
69
- function website_cli(args) {
70
- const executable = local_settings().python || (process.platform === 'win32' ? 'python' : 'python3');
71
- const result = spawnSync(executable, ['-X', 'utf8', WEBSITE_CLIENT, ...args], {
72
- stdio: 'inherit', windowsHide: true, env: { ...process.env, DISCUSS_CLI_NAME: 'codiscuss' },
73
- });
74
- if (result.error) throw new Error(`网站操作需要 Python 3.10+,无法启动 ${executable}:${result.error.message}`);
75
- process.exitCode = result.status ?? (result.signal === 'SIGINT' ? 130 : 1);
76
- }
77
-
78
- /** Format service receipts without exposing room credentials. */
79
- function print_result(result) {
80
- const lines = [];
81
- if (typeof result.running === 'boolean') {
82
- lines.push(result.running ? `讨论服务${result.ready === false ? '尚未确认就绪' : '运行中'}(PID ${result.pid})` : '讨论服务未运行');
83
- }
84
- if (result.home) lines.push(`服务目录:${result.home}`);
85
- if (result.configs) lines.push(`已登记 ${result.configs.length} 个房间`, ...result.configs);
86
- for (const room of result.rooms || []) {
87
- lines.push(`${room.site || ''}/${room.room || room.config}:${STATUS_LABELS[room.status] || room.status}${room.error ? `;${room.error}` : ''}`);
88
- }
89
- if (result.added) lines.push(`已登记房间:${result.site}/${result.added}`);
90
- if (result.removed) lines.push(`已移除:${result.removed}`);
91
- if (result.shortcut) lines.push(`已创建快捷方式:${result.shortcut}`);
92
- if (result.autostart) lines.push(`已开启登录自启:${result.autostart}`);
93
- if (result.opened) lines.push(...result.opened.map(site => `已打开:${site}`));
94
- process.stdout.write(`${lines.join('\n')}\n`);
95
- }
96
-
97
- /** Run the resident service or one of its management commands. */
98
- async function service_cli(args) {
99
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
100
- config: { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
101
- } });
102
- if (values.help || positionals[0] === 'help') return process.stdout.write(SERVICE_HELP);
103
- const command = positionals[0] || 'run';
104
- if (command === 'run') {
105
- const home = service_home();
106
- if (service_pid(home)) return service_main(['status'], print_result);
107
- const count = read_registry(home).length;
108
- process.stdout.write(`AI CoDiscuss 讨论服务\n服务目录:${home}\n已登记 ${count} 个房间\nCtrl+C 停止服务\n`);
109
- if (!count) process.stdout.write('尚未登记房间;可在另一终端运行 codiscuss service add --config FILE。\n');
110
- return run_service(home, line => process.stdout.write(`${line}\n`));
111
- }
112
- const forwarded = [...positionals];
113
- if (values.config) forwarded.push('--config', values.config);
114
- return service_main(forwarded, values.json ? value => process.stdout.write(`${JSON.stringify(value)}\n`) : print_result);
115
- }
116
-
117
- /** Keep startup convenient while separating local service management from website operations. */
118
- async function main(args = process.argv.slice(2)) {
119
- const [command] = args;
120
- if (['--help', '-h', 'help'].includes(command)) return process.stdout.write(HELP);
121
- if (command === 'service') return service_cli(args.slice(1));
122
- if (command === 'launch') return launch_main(args.slice(1));
123
- if (['install', 'setup'].includes(command)) return setup_main(command, args.slice(1));
124
- if (command === 'local') return local_main(args.slice(1));
125
- if (command === 'token') return admin_main(args.slice(1));
126
- if (command === 'panel') return (await import('./admin_panel.mjs')).panel_main(args.slice(1));
127
- if (command === 'launcher') return (await import('./launcher.mjs')).launcher_main();
128
- if (!command || (command === 'run' && args.length === 1)) return service_cli([]);
129
- if (SERVICE_COMMANDS.has(command) || command === '--json') return service_cli(args);
130
- return website_cli(args);
131
- }
132
-
133
- main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; });
1
+ #!/usr/bin/env node
2
+ /** Unified entrypoint for the local service and the discussion website client. */
3
+ import { spawnSync } from 'node:child_process';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { parseArgs } from 'node:util';
6
+
7
+ import { admin_main } from './admin_account.mjs';
8
+ import { main as service_main, read_registry, run_service, service_home, service_pid } from './discussion_service.mjs';
9
+ import { launch_main } from './discussion_launch.mjs';
10
+ import { local_settings, setup_main } from './discussion_setup.mjs';
11
+ import { local_main } from './discussion_local.mjs';
12
+
13
+ const HELP = `AI CoDiscuss CLI
14
+
15
+ 用法:codiscuss [命令] [选项]
16
+
17
+ (无命令) 在当前终端启动服务,Ctrl+C 停止
18
+ install / setup 安装持久命令并配置 / 配置已有安装
19
+ local COMMAND 管理本机网站,或 connect 连接线上站点
20
+ token 生成线上网站的一次性管理员注册令牌
21
+ panel [open|start|stop] 打开本机管理面板(托管用户、命令行登录、API 密钥)
22
+ admin COMMAND 以命令行完成管理面板的全部操作(启动、退出、更新、托管账号等)
23
+ launcher 生成“共议.exe”与桌面、开始菜单快捷方式,双击即可启动(Windows)
24
+ service COMMAND 启动、停止、查询服务,或登记房间
25
+ launch COMMAND 保存启动配置,或从 AI 对话启动讨论
26
+ room COMMAND 创建、读取或更新讨论房间
27
+ message COMMAND 检索原文、提交观点
28
+ attachment COMMAND 上传、查询与下载讨论附件
29
+ turn COMMAND 安排发言、读取待办与回答
30
+ state COMMAND 读取或保存共享状态
31
+ run COMMAND 配置、启动或暂停网站上的讨论
32
+ execution COMMAND 进入或查询一次 AI 执行
33
+ health 检查网站健康状态
34
+ schema [COMMAND] 离线查看命令与参数
35
+ api PATH 访问尚未封装的网站接口
36
+
37
+ codiscuss service --help
38
+ codiscuss room --help
39
+ codiscuss health --site http://127.0.0.1:8765
40
+
41
+ 网站操作使用 --site、DISCUSS_URL 或 --access-file 中的站点,并需要 Python 3.10+。
42
+ 原有 start、status、stop、add 等服务命令继续兼容。
43
+ `;
44
+ const SERVICE_HELP = `AI CoDiscuss 讨论服务
45
+
46
+ 用法:codiscuss service [命令] [选项]
47
+
48
+ (无命令) / run 在当前终端运行,Ctrl+C 停止
49
+ start 在后台启动,已运行时复用
50
+ status 查看服务与房间状态
51
+ stop 暂停托管中的讨论并停止服务
52
+ add --config FILE 登记房间的私有接入配置
53
+ remove --config FILE 移除已登记配置
54
+ list 列出已登记配置
55
+ clean 立即清理无房间使用的启动目录、草稿与超长日志(服务每 6 小时自动清理一次)
56
+ open 后台启动并打开讨论网站
57
+ shortcut 创建 Windows 桌面快捷方式
58
+ autostart on|off 开启或关闭 Windows 登录自启
59
+
60
+ --json 以 JSON 输出命令结果(前台运行除外)
61
+ -h, --help 显示帮助
62
+
63
+ 登记或启动服务不会自动开始讨论,仍需在网页明确启动。
64
+ `;
65
+ const STATUS_LABELS = { running: '运行中', paused: '已暂停', idle: '等待启动', error: '异常' };
66
+ const SERVICE_COMMANDS = new Set(['start', 'status', 'stop', 'add', 'remove', 'list', 'open', 'shortcut', 'autostart']);
67
+ const WEBSITE_CLIENT = fileURLToPath(new URL('./discuss.py', import.meta.url));
68
+
69
+ /** Forward untouched arguments, streams and exit codes to the existing Python client. */
70
+ function website_cli(args) {
71
+ const executable = local_settings().python || (process.platform === 'win32' ? 'python' : 'python3');
72
+ const result = spawnSync(executable, ['-X', 'utf8', WEBSITE_CLIENT, ...args], {
73
+ stdio: 'inherit', windowsHide: true, env: { ...process.env, DISCUSS_CLI_NAME: 'codiscuss' },
74
+ });
75
+ if (result.error) throw new Error(`网站操作需要 Python 3.10+,无法启动 ${executable}:${result.error.message}`);
76
+ process.exitCode = result.status ?? (result.signal === 'SIGINT' ? 130 : 1);
77
+ }
78
+
79
+ /** Format service receipts without exposing room credentials. */
80
+ function print_result(result) {
81
+ const lines = [];
82
+ if (typeof result.running === 'boolean') {
83
+ lines.push(result.running ? `讨论服务${result.ready === false ? '尚未确认就绪' : '运行中'}(PID ${result.pid})` : '讨论服务未运行');
84
+ }
85
+ if (result.home) lines.push(`服务目录:${result.home}`);
86
+ if (result.configs) lines.push(`已登记 ${result.configs.length} 个房间`, ...result.configs);
87
+ for (const room of result.rooms || []) {
88
+ lines.push(`${room.site || ''}/${room.room || room.config}:${STATUS_LABELS[room.status] || room.status}${room.error ? `;${room.error}` : ''}`);
89
+ }
90
+ if (result.added) lines.push(`已登记房间:${result.site}/${result.added}`);
91
+ if (result.removed) lines.push(`已移除:${result.removed}`);
92
+ if (result.shortcut) lines.push(`已创建快捷方式:${result.shortcut}`);
93
+ if (result.autostart) lines.push(`已开启登录自启:${result.autostart}`);
94
+ if (result.opened) lines.push(...result.opened.map(site => `已打开:${site}`));
95
+ process.stdout.write(`${lines.join('\n')}\n`);
96
+ }
97
+
98
+ /** Run the resident service or one of its management commands. */
99
+ async function service_cli(args) {
100
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
101
+ config: { type: 'string' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
102
+ } });
103
+ if (values.help || positionals[0] === 'help') return process.stdout.write(SERVICE_HELP);
104
+ const command = positionals[0] || 'run';
105
+ if (command === 'run') {
106
+ const home = service_home();
107
+ if (service_pid(home)) return service_main(['status'], print_result);
108
+ const count = read_registry(home).length;
109
+ process.stdout.write(`AI CoDiscuss 讨论服务\n服务目录:${home}\n已登记 ${count} 个房间\nCtrl+C 停止服务\n`);
110
+ if (!count) process.stdout.write('尚未登记房间;可在另一终端运行 codiscuss service add --config FILE。\n');
111
+ return run_service(home, line => process.stdout.write(`${line}\n`));
112
+ }
113
+ const forwarded = [...positionals];
114
+ if (values.config) forwarded.push('--config', values.config);
115
+ return service_main(forwarded, values.json ? value => process.stdout.write(`${JSON.stringify(value)}\n`) : print_result);
116
+ }
117
+
118
+ /** Keep startup convenient while separating local service management from website operations. */
119
+ async function main(args = process.argv.slice(2)) {
120
+ const [command] = args;
121
+ if (['--help', '-h', 'help'].includes(command)) return process.stdout.write(HELP);
122
+ if (command === 'service') return service_cli(args.slice(1));
123
+ if (command === 'launch') return launch_main(args.slice(1));
124
+ if (['install', 'setup'].includes(command)) return setup_main(command, args.slice(1));
125
+ if (command === 'local') return local_main(args.slice(1));
126
+ if (command === 'token') return admin_main(args.slice(1));
127
+ if (command === 'panel') return (await import('./admin_panel.mjs')).panel_main(args.slice(1));
128
+ if (command === 'admin') return (await import('./admin_cli.mjs')).admin_cli(args.slice(1));
129
+ if (command === 'launcher') return (await import('./launcher.mjs')).launcher_main();
130
+ if (!command || (command === 'run' && args.length === 1)) return service_cli([]);
131
+ if (SERVICE_COMMANDS.has(command) || command === '--json') return service_cli(args);
132
+ return website_cli(args);
133
+ }
134
+
135
+ main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; });