ai_co_discuss 0.4.38 → 0.4.40

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.
@@ -506,16 +506,18 @@ function run_instance(data, name, command) {
506
506
  /** The entry's saved settings: the loopback port it listens on and the public address customers open. */
507
507
  export function entry_settings(data) {
508
508
  const saved = read_json(join(data, ENTRY_SETTINGS_FILE));
509
+ const tunnel = saved.tunnel && typeof saved.tunnel === 'object' && ['name', 'host', 'id', 'credentials'].every(key => saved.tunnel[key]) ? saved.tunnel : null;
509
510
  return { port: Number.isInteger(saved.port) ? saved.port : DEFAULT_ENTRY_PORT, public_url: typeof saved.public_url === 'string' ? saved.public_url : '',
510
- running: saved.running === true };
511
+ running: saved.running === true, tunnel };
511
512
  }
512
513
 
513
514
  /**
514
515
  * Save part of the entry's settings.
515
516
  *
516
517
  * Args:
517
- * changes: `port` (1–65535), `public_url` (an https address, kept as its origin; empty clears it) and `running`, the
518
- * state the panel restores when it starts again.
518
+ * changes: `port` (1–65535), `public_url` (an https address, kept as its origin; empty clears it), `running`, the
519
+ * state the panel restores when it starts again, and `tunnel`, the Cloudflare tunnel the panel runs for the outside
520
+ * address ({ name, host, id, credentials } from hosting_tunnel.mjs, or null for none).
519
521
  *
520
522
  * Returns:
521
523
  * The settings as saved.
@@ -529,6 +531,7 @@ export function save_entry_settings(data, changes) {
529
531
  }
530
532
  if (changes.public_url !== undefined) next.public_url = public_origin(changes.public_url);
531
533
  if (changes.running !== undefined) next.running = Boolean(changes.running);
534
+ if (changes.tunnel !== undefined) next.tunnel = changes.tunnel || null;
532
535
  write_json(join(data, ENTRY_SETTINGS_FILE), next);
533
536
  return next;
534
537
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.38",
3
+ "version": "0.4.40",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -21,6 +21,7 @@ import { account_home, add_account, data_home, entry_settings, entry_status, ins
21
21
  import { verified_connection } from './entry_client.mjs';
22
22
  import { API_PROVIDERS, save_api_key } from './discussion_api.mjs';
23
23
  import { STT_PROVIDERS, TTS_PROVIDERS } from './tts_providers.mjs';
24
+ import { ensure_tunnel, tunnel_status } from './hosting_tunnel.mjs';
24
25
  import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
25
26
  import { create_os_user, install_shared_runtime, instance_key_file, place_instance_key, read_os_users, remove_os_user, run_as_user, shared_cli_state, shared_executables, shared_paths,
26
27
  start_instance_as_user } from './os_users.mjs';
@@ -48,6 +49,9 @@ const STATE_FILE = 'admin-panel.json';
48
49
  const UPDATE_JOB_FILE = 'panel-update.json';
49
50
  const UPDATE_STALE_MS = 10 * 60 * 1000;
50
51
  const OWNER_ENV_TIMEOUT_MS = 120_000;
52
+ // How often the panel makes sure the entry's tunnel runs as set, and how long an update waits for the entry to be back.
53
+ const TUNNEL_CHECK_MS = 60_000;
54
+ const ENTRY_BACK_MS = 15_000;
51
55
  // Hosted accounts' failures, relayed to the owner's Weixin: how often, how far each account's outbox was read, and limits
52
56
  // on what one notice carries (the outbox is in the account's own folder, so its text is the account's, not ours).
53
57
  const RELAY_MS = 30_000;
@@ -144,6 +148,8 @@ async function begin_update(data, version, hand_over) {
144
148
  write_update_job(data, job);
145
149
  (async () => {
146
150
  await update_step(job.steps, '已停止本机服务', () => run_owner_service(data, 'stop'));
151
+ // The entry runs the package's code too: stopped here, the installed panel starts it again on the new version.
152
+ if (hosting_enabled(data) && (await entry_status(data)).running) await update_step(job.steps, '已停止登录入口', () => stop_entry(data));
147
153
  for (const account of running) if (!account.os_user) await update_step(job.steps, `已停止 ${account.name} 的实例`, () => run_instance(data, account.name, 'stop'));
148
154
  const updater = join(data, 'update', 'panel_updater.mjs');
149
155
  mkdirSync(dirname(updater), { recursive: true });
@@ -173,6 +179,11 @@ async function finish_update(data) {
173
179
  if (error.code !== 2) throw error;
174
180
  }));
175
181
  await update_step(steps, '已启动本机服务', () => run_owner_service(data, 'start'));
182
+ // The panel itself starts an entry left on (run_panel); the report says once it serves again.
183
+ if (hosting_enabled(data) && entry_settings(data).running) await update_step(steps, '已重新启动登录入口', async () => {
184
+ for (let waited = 0; waited < ENTRY_BACK_MS; waited += 500) { if ((await entry_status(data)).running) return; await new Promise(done => setTimeout(done, 500)); }
185
+ throw new Error('入口没有重新启动,在“概览”页“托管”下点“启动”看原因');
186
+ });
176
187
  if (hosting_enabled(data)) {
177
188
  if (installed) await update_step(steps, '已同步隔离账号的程序副本', () => { const result = install_runtime(data); if (result.warnings.length) throw new Error(result.warnings.join(';')); });
178
189
  for (const account of await list_accounts(data)) {
@@ -552,7 +563,7 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
552
563
  const op = { list_accounts, add_account, reset_password, set_account_disabled, remove_account, run_instance, create_os_user, remove_os_user,
553
564
  login_status, apply_login, logout, start_login, login_progress, submit_login, cancel_login, install_runtime, prepare_account, account_env, account_skills, account_workflows, owner_env, owner_skills, owner_prompts, save_owner_prompt, shared_cli_state,
554
565
  save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, begin_update,
555
- autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, protect_account, start_verified, hand_over: () => {}, ...ops };
566
+ autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, protect_account, start_verified, hand_over: () => {}, ...ops };
556
567
  const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
557
568
 
558
569
  async function api(method, path, body) {
@@ -622,6 +633,8 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
622
633
  if (method === 'POST' && section === 'entry' && (name === 'start' || name === 'stop')) {
623
634
  await (name === 'start' ? op.start_entry(data) : op.stop_entry(data));
624
635
  save_entry_settings(data, { running: name === 'start' });
636
+ // Its tunnel goes with it.
637
+ await op.keep_tunnel(data);
625
638
  return op.entry_overview(data);
626
639
  }
627
640
  if (method === 'POST' && section === 'entry' && name === 'settings') { save_entry_settings(data, { public_url: body.public_url }); return op.entry_overview(data); }
@@ -703,9 +716,16 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
703
716
  }
704
717
 
705
718
  /** The account entry as the hosting page shows it: whether it runs, its loopback port and the address customers open. */
719
+ /** Keep the entry's tunnel as the settings say: running while hosting is on and the entry is meant to run. */
720
+ function keep_tunnel(data) {
721
+ const { tunnel, port, running } = entry_settings(data);
722
+ return ensure_tunnel(data, hosting_enabled(data) ? tunnel : null, port, running);
723
+ }
724
+
706
725
  async function entry_overview(data) {
707
- const { port, public_url } = entry_settings(data), status = await entry_status(data);
708
- return { running: status.running, port: status.running ? status.port : port, public_url };
726
+ const { port, public_url, tunnel } = entry_settings(data), status = await entry_status(data);
727
+ return { running: status.running, port: status.running ? status.port : port, public_url,
728
+ tunnel: tunnel ? { host: tunnel.host, ...(await tunnel_status(data)) } : null };
709
729
  }
710
730
 
711
731
  // ---- Hosted accounts' failures, to the owner's Weixin ----
@@ -917,8 +937,13 @@ function run_panel(data, port) {
917
937
  setTimeout(() => process.exit(0), 300);
918
938
  };
919
939
  const server = create_panel({ data, key: state.key, port, ops: { hand_over }, sessions });
920
- // An entry left on starts again with the panel (only the entry: the accounts' instances and the HTTPS tunnel are separate).
940
+ // An entry left on starts again with the panel (only the entry: the accounts' instances are separate).
921
941
  if (hosting_enabled(data) && entry_settings(data).running) start_entry(data).catch(error => process.stderr.write(`入口没有启动:${error.message}\n`));
942
+ // The entry's outside address runs on its own; the panel keeps it as set now and every minute (restarted if it stopped
943
+ // or its settings changed, stopped when the entry is off).
944
+ const keep = () => keep_tunnel(data).catch(error => process.stderr.write(`隧道:${error.message}\n`));
945
+ keep();
946
+ const keeper = setInterval(keep, TUNNEL_CHECK_MS);
922
947
  // Hosted accounts' failures reach the owner's Weixin; one pass at a time.
923
948
  let relaying = false;
924
949
  const relay = setInterval(() => {
@@ -952,6 +977,8 @@ function run_panel(data, port) {
952
977
  } });
953
978
  function shutdown(exit = true) {
954
979
  clearInterval(relay);
980
+ // The tunnel runs on without the panel, like the entry.
981
+ clearInterval(keeper);
955
982
  tray?.close();
956
983
  server.close();
957
984
  if (read_state(data)?.pid === process.pid) rmSync(state_path(data), { force: true });
@@ -13,6 +13,7 @@ import { assert_shared_home, service_home } from './discussion_service.mjs';
13
13
  import { SKILLS, install_skills, install_workflows, remove_legacy_skills, shipped_workflows } from './discussion_skills.mjs';
14
14
  import { ask, checkbox_prompt, intro, outro, pad, short_path, spinner, step, styled, text_width, tone, tree_prompt } from './discussion_tui.mjs';
15
15
  import { launcher_installed } from './launcher.mjs';
16
+ import { configure_hosting, finish_hosting, hosting_requested } from './hosting_setup.mjs';
16
17
  export { checkbox_prompt } from './discussion_tui.mjs';
17
18
 
18
19
  const ROOT = fileURLToPath(new URL('../', import.meta.url));
@@ -36,7 +37,8 @@ const CLIENTS = {
36
37
  const OPTIONS = { yes: { type: 'boolean' }, clients: { type: 'string' }, python: { type: 'string' },
37
38
  codex: { type: 'string' }, claude: { type: 'string' }, antigravity: { type: 'string' }, cursor: { type: 'string' },
38
39
  port: { type: 'string' }, prefix: { type: 'string' }, 'skills-home': { type: 'string' },
39
- 'no-start': { type: 'boolean' }, hosting: { type: 'boolean' }, 'no-hosting': { type: 'boolean' }, 'no-open': { type: 'boolean' }, workflows: { type: 'boolean' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } };
40
+ 'no-start': { type: 'boolean' }, hosting: { type: 'boolean' }, 'no-hosting': { type: 'boolean' }, 'no-open': { type: 'boolean' }, workflows: { type: 'boolean' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
41
+ 'public-host': { type: 'string' }, 'tunnel-name': { type: 'string' }, 'entry-port': { type: 'string' } };
40
42
  const HELP = `用法:codiscuss install [选项] / codiscuss setup [选项]
41
43
  install 将当前 npm 包安装为持久命令,再运行 setup;setup 配置已有安装。
42
44
  --yes 使用已检测且支持自动接入的软件,冲突保留并报告
@@ -47,7 +49,12 @@ install 将当前 npm 包安装为持久命令,再运行 setup;setup 配置
47
49
  --no-start / --no-open 只配置 / 启动但不打开浏览器
48
50
  --prefix DIR npm 安装前缀(install)
49
51
  --skills-home DIR 技能用户根目录(默认当前用户目录)
50
- --hosting / --no-hosting 在管理面板中显示 / 隐藏托管管理(用户、Windows 用户、命令行登录、API 密钥),选择会记住
52
+ --hosting / --no-hosting 在管理面板中显示 / 隐藏托管管理(用户、Windows 用户、命令行登录、API 密钥),选择会记住;
53
+ Windows 上加 --hosting 时还会设好登录入口(随管理面板启动)、开启登录自启,并检查入口能否打开
54
+ --entry-port PORT 登录入口端口,默认 8780
55
+ --public-host 域名 外网地址(可选),如 ai.example.com:域名须已托管在 Cloudflare;会安装 cloudflared、
56
+ 在浏览器里授权 Cloudflare、建固定隧道并添加域名记录,隧道由管理面板运行
57
+ --tunnel-name NAME Cloudflare 隧道名,默认 codiscuss
51
58
  --workflows 安装全部随包工作流,已有同名的覆盖为最新版(原来的先备份到服务目录 backups/);
52
59
  交互运行时也可在“安装配置”里逐个勾选;不选则不安装,选择不会记住
53
60
  Antigravity(显示名 Gemini)使用 agy;Grok 使用 Cursor CLI(agent / cursor-agent)。仅检测 CLI。
@@ -442,9 +449,18 @@ async function setup(options) {
442
449
  work.done('“共议”快捷方式已就绪', [tone.dim(short_path(launcher.shortcuts[0]))]);
443
450
  } catch (error) { launcher_error = error.message; work.fail(error.message); }
444
451
  }
452
+ // Hosting asked for: the entry, its optional outside address and starting with Windows, before the service starts.
453
+ const hosting_setup = hosting_requested(options, choices.hosting);
454
+ let hosting = null;
455
+ if (hosting_setup) {
456
+ // No spinner: installing cloudflared and signing in to Cloudflare print and wait for the owner.
457
+ hosting = configure_hosting(home, options, { say: line => process.stderr.write(`${line}\n`) });
458
+ step(hosting.issues.length ? '登录入口已设置,有待处理项' : '登录入口已设置', [...hosting.lines, ...hosting.issues]);
459
+ }
445
460
  const result = { home, python, clients: selected.map(item => item.name), ...configured, workflows, ...(choices.hosting ? { hosting: true } : {}),
446
- command: check_command(), ai_verified: false, ...(pi ? { pi: pi.version } : {}), ...(launcher ? { launcher: launcher.shortcuts[0] } : {}) };
447
- result.issues = setup_issues(result);
461
+ command: check_command(), ai_verified: false, ...(pi ? { pi: pi.version } : {}), ...(launcher ? { launcher: launcher.shortcuts[0] } : {}),
462
+ ...(hosting ? { hosting_setup: hosting.lines } : {}) };
463
+ result.issues = [...setup_issues(result), ...(hosting?.issues || [])];
448
464
  if (pi_error) result.issues.push(`Pi 安装失败(${pi_error});模型 API 成员首次执行时会再试,或检查网络与 npm 后重新运行 setup。`);
449
465
  if (launcher_error) result.issues.push(`未能创建“共议”快捷方式(${launcher_error});可稍后运行 codiscuss launcher 重试。`);
450
466
  result.configured = result.issues.length === 0;
@@ -464,6 +480,13 @@ async function setup(options) {
464
480
  result.local = await local_main([options['no-open'] ? 'start' : 'open'], () => {});
465
481
  launch.done('网站与讨论服务已在后台运行', [`${tone.cyan(result.local.url)}${options['no-open'] ? tone.dim(' 未打开浏览器,可直接访问此地址') : tone.dim(' 已在浏览器打开')}`]);
466
482
  if (result.configured) result.status = 'ready';
483
+ if (hosting_setup) {
484
+ const check = spinner('重启管理面板并检查登录入口(外网检查最多 2 分钟)');
485
+ const checked = await finish_hosting(home);
486
+ check.done(checked.issues.length ? '登录入口检查未全部通过' : '登录入口检查通过', [...checked.lines, ...checked.issues]);
487
+ result.hosting_setup.push(...checked.lines);
488
+ if (checked.issues.length) { result.issues.push(...checked.issues); result.configured = false; result.status = 'needs_attention'; }
489
+ }
467
490
  } catch (error) {
468
491
  launch.fail(error.message);
469
492
  result.status = 'start_failed';
@@ -496,6 +519,7 @@ function report_setup(result, options = {}) {
496
519
  if (result.workflows.length) lines.push(`内置工作流:${workflow_summary(result.workflows)}`);
497
520
  if (result.launcher) lines.push(`快捷方式:${result.launcher}(双击启动共议)`);
498
521
  if (result.hosting) lines.push('托管管理:已打开,在管理面板中可用');
522
+ for (const line of result.hosting_setup || []) lines.push(`托管:${line}`);
499
523
  if (result.command.path) lines.push(`持久命令:${result.command.path}(${result.command.status})`);
500
524
  if (result.local?.running) {
501
525
  lines.push(`本机网站:${result.local.url}${options['no-open'] ? '' : '(已在浏览器打开)'}`,
@@ -523,6 +547,7 @@ function report_styled(result, options) {
523
547
  if (result.workflows.length) rows.push(['工作流', workflow_summary(result.workflows), '']);
524
548
  if (result.launcher) rows.push(['快捷方式', '双击“共议”启动', short_path(result.launcher)]);
525
549
  if (result.hosting) rows.push(['托管管理', '已打开', '在管理面板中可用']);
550
+ for (const line of result.hosting_setup || []) rows.push(['托管', line, '']);
526
551
  if (result.command.path) rows.push(['命令', `codiscuss ${tone.dim(`(${result.command.status})`)}`, short_path(result.command.path)]);
527
552
  const notes = result.issues.map(issue => tone.yellow(`▲ ${issue}`));
528
553
  if (result.local?.running) {
@@ -0,0 +1,88 @@
1
+ /**
2
+ * What `codiscuss setup --hosting` does beyond turning hosting on, so a computer is ready to host accounts: the entry's
3
+ * port and start with the panel, the optional outside address (a Cloudflare tunnel from the owner's own domain, see
4
+ * hosting_tunnel.mjs), starting with Windows, then a restart of the panel so it runs the entry and tunnel as set, and a
5
+ * check that the entry answers here and outside. Safe to run again: what is already done is kept.
6
+ */
7
+ import { spawnSync } from 'node:child_process';
8
+ import { existsSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+
12
+ import { entry_settings, save_entry_settings } from '../gateway/gateway.mjs';
13
+ import { prepare_tunnel, remove_legacy_tunnel_start, tunnel_host, tunnel_log_tail } from './hosting_tunnel.mjs';
14
+ import { launcher_path, set_autostart } from './launcher.mjs';
15
+
16
+ const PANEL_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), 'admin_panel.mjs');
17
+ const LOGIN_PATH = '/_entry/login';
18
+ const LOCAL_WAIT_MS = 60_000;
19
+ // A new tunnel's host name can take a minute or two to resolve.
20
+ const PUBLIC_WAIT_MS = 120_000;
21
+ const PROBE_MS = 3000;
22
+ const PROBE_TIMEOUT_MS = 10_000;
23
+
24
+ /** Whether this run should set hosting up: asked for with --hosting or one of the entry's options, on Windows. */
25
+ export function hosting_requested(options, hosting_on) {
26
+ return process.platform === 'win32' && hosting_on && Boolean(options.hosting || options['public-host'] || options['entry-port']);
27
+ }
28
+
29
+ /**
30
+ * Save the entry's settings and prepare the outside address, before the service starts. Returns { lines, issues }:
31
+ * what was set, and what is left for the owner.
32
+ */
33
+ export function configure_hosting(home, options, { interactive = Boolean(process.stdin.isTTY), say = () => {} } = {}) {
34
+ const lines = [], issues = [];
35
+ const changes = { running: true };
36
+ if (options['entry-port']) changes.port = Number(options['entry-port']);
37
+ if (options['public-host']) {
38
+ try {
39
+ const host = tunnel_host(options['public-host']);
40
+ const tunnel = prepare_tunnel({ host, name: options['tunnel-name'], interactive, say });
41
+ Object.assign(changes, { public_url: `https://${host}`, tunnel });
42
+ lines.push(`外网地址 https://${host},经 Cloudflare 隧道 ${tunnel.name} 转到登录入口;隧道独立运行,由管理面板按设置维持`);
43
+ if (remove_legacy_tunnel_start()) lines.push('已移除旧的“CoDiscuss Tunnel”开机任务,改由管理面板运行隧道');
44
+ } catch (error) { issues.push(`外网地址没有设好:${error.message}`); }
45
+ }
46
+ const saved = save_entry_settings(home, changes);
47
+ lines.unshift(`登录入口:本机 ${saved.port} 端口,随管理面板启动`);
48
+ if (!saved.tunnel && !options['public-host']) lines.push('未设外网地址,仅本机可访问;有托管在 Cloudflare 的域名时,加 --public-host 域名 重新运行');
49
+ if (existsSync(launcher_path(home))) { set_autostart(true, home); lines.push('已开启登录 Windows 时自动启动'); }
50
+ else issues.push('还没有“共议”程序,没有开启登录自启:重新运行 setup 并勾选创建桌面快捷方式');
51
+ return { lines, issues };
52
+ }
53
+
54
+ async function answers(url, wait_ms) {
55
+ for (let waited = 0; waited < wait_ms; waited += PROBE_MS) {
56
+ try { if ((await fetch(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) })).ok) return true; } catch { /* not yet */ }
57
+ await new Promise(done => setTimeout(done, PROBE_MS));
58
+ }
59
+ return false;
60
+ }
61
+
62
+ /**
63
+ * After the service started: restart the panel, which starts the entry and brings the tunnel in line with the settings
64
+ * (its config follows the entry port) when it starts, then check the entry here and, with an outside address, from
65
+ * outside. Returns { lines, issues }.
66
+ */
67
+ export async function finish_hosting(home) {
68
+ const lines = [], issues = [];
69
+ spawnSync(process.execPath, [PANEL_SCRIPT, 'stop', '--data', home], { stdio: 'ignore', windowsHide: true });
70
+ const started = spawnSync(process.execPath, [PANEL_SCRIPT, 'start', '--data', home], { encoding: 'utf8', windowsHide: true });
71
+ if (started.status !== 0) {
72
+ issues.push(`管理面板没有启动:${String(started.stderr || '').trim() || `退出码 ${started.status}`}`);
73
+ return { lines, issues };
74
+ }
75
+ const { port, public_url, tunnel } = entry_settings(home);
76
+ if (await answers(`http://127.0.0.1:${port}${LOGIN_PATH}`, LOCAL_WAIT_MS)) lines.push(`本机入口 http://127.0.0.1:${port} 正常`);
77
+ else {
78
+ issues.push(`本机入口 ${LOCAL_WAIT_MS / 1000} 秒内没有打开:在管理面板“概览”页“托管”下的“登录入口”点“启动”,看提示的原因`);
79
+ return { lines, issues };
80
+ }
81
+ if (!tunnel || !public_url) return { lines, issues };
82
+ if (await answers(`${public_url}${LOGIN_PATH}`, PUBLIC_WAIT_MS)) lines.push(`外网入口 ${public_url} 正常`);
83
+ else {
84
+ const tail = tunnel_log_tail(home);
85
+ issues.push(`外网地址 ${PUBLIC_WAIT_MS / 1000} 秒内没有打开。依次检查:Cloudflare DNS 里 ${tunnel.host} 是否是指向隧道的 CNAME(被别的记录占用要先删掉);代理软件是否放行了 *.cloudflare.com、*.argotunnel.com(Clash 需开 TUN);管理面板“概览”页“登录入口”一行的隧道状态${tail ? `。隧道日志:${tail}` : ''}`);
86
+ }
87
+ return { lines, issues };
88
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The outside address of the hosted accounts' entry: a Cloudflare named tunnel from a host name on the owner's own
3
+ * Cloudflare domain to the entry port on this computer.
4
+ *
5
+ * `codiscuss setup --hosting --public-host NAME` prepares it once (installs cloudflared, signs in to Cloudflare in the
6
+ * browser, creates the tunnel, points the host name at it). From then on cloudflared runs as a background process of its
7
+ * own, like the entry: it outlives the panel (an update, a forced stop), and the panel only keeps it as set
8
+ * (`ensure_tunnel`, at start and every minute): running while the entry is meant to run, its config rewritten from the
9
+ * current settings and the process restarted when they changed. Whether it is connected is read from cloudflared's own
10
+ * readiness endpoint. A tunnel needs a domain on Cloudflare, so it is optional: without one the entry serves this
11
+ * computer only.
12
+ */
13
+ import { spawn, spawnSync } from 'node:child_process';
14
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
15
+ import net from 'node:net';
16
+ import { homedir } from 'node:os';
17
+ import { join } from 'node:path';
18
+
19
+ const TUNNEL_HOME = join(homedir(), '.cloudflared');
20
+ // Where winget puts it; a process started before the install does not see the new PATH yet.
21
+ const INSTALLED_PATHS = [join(process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)', 'cloudflared', 'cloudflared.exe'),
22
+ join(process.env.ProgramFiles || 'C:\\Program Files', 'cloudflared', 'cloudflared.exe')];
23
+ const HOST_PATTERN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/;
24
+ const NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/;
25
+ export const DEFAULT_TUNNEL_NAME = 'codiscuss';
26
+ const STATE_FILE = 'tunnel.json';
27
+ const LOG_FILE = 'tunnel.log';
28
+ const READY_TIMEOUT_MS = 1500;
29
+ // The scheduled task and Run entry hosting-setup.ps1 used before the panel kept the tunnel.
30
+ const LEGACY_TASK = 'CoDiscuss Tunnel';
31
+ const LEGACY_RUN = 'CoDiscussTunnel';
32
+ // Command output goes to stderr, so `setup --json` keeps stdout for its result.
33
+ const TO_STDERR = ['inherit', 2, 2];
34
+
35
+ /** The host name as typed, checked: a plain name such as ai.example.com (no scheme or path). */
36
+ export function tunnel_host(text) {
37
+ const host = String(text || '').trim().toLowerCase().replace(/^https?:\/\//, '').replace(/\/+$/, '');
38
+ if (!HOST_PATTERN.test(host)) throw new Error(`外网域名无效:${text}(应为 ai.example.com 这样的域名,且已托管在 Cloudflare)`);
39
+ return host;
40
+ }
41
+
42
+ export function tunnel_name(text = DEFAULT_TUNNEL_NAME) {
43
+ const name = String(text || DEFAULT_TUNNEL_NAME).trim();
44
+ if (!NAME_PATTERN.test(name)) throw new Error(`隧道名无效:${text}(小写字母、数字、下划线或短横线)`);
45
+ return name;
46
+ }
47
+
48
+ /** cloudflared's path, or '' when it is not installed. CODISCUSS_CLOUDFLARED names another program (tests). */
49
+ export function cloudflared_path() {
50
+ if (process.env.CODISCUSS_CLOUDFLARED) return process.env.CODISCUSS_CLOUDFLARED;
51
+ const found = spawnSync('where.exe', ['cloudflared'], { encoding: 'utf8', windowsHide: true }).stdout?.split(/\r?\n/).find(Boolean);
52
+ return found?.trim() || INSTALLED_PATHS.find(path => existsSync(path)) || '';
53
+ }
54
+
55
+ /** Install cloudflared with winget when it is missing, and return its path. */
56
+ export function install_cloudflared() {
57
+ const present = cloudflared_path();
58
+ if (present) return present;
59
+ const winget = spawnSync('winget', ['install', '--id', 'Cloudflare.cloudflared', '-e', '--accept-source-agreements', '--accept-package-agreements'],
60
+ { stdio: TO_STDERR, windowsHide: true });
61
+ if (winget.error) throw new Error('没有 winget:请先从 Microsoft Store 安装“应用安装程序”,或自行安装 cloudflared 后重新运行');
62
+ const path = cloudflared_path();
63
+ if (!path) throw new Error('cloudflared 没有装上,看上面 winget 的输出');
64
+ return path;
65
+ }
66
+
67
+ function run(cloudflared, args, shown = false) {
68
+ const result = spawnSync(cloudflared, args, { encoding: 'utf8', windowsHide: !shown, stdio: shown ? TO_STDERR : 'pipe' });
69
+ if (result.status !== 0) throw new Error(`cloudflared ${args.join(' ')} 失败:${String(result.stderr || '').trim().split(/\r?\n/).pop() || `退出码 ${result.status}`}`);
70
+ return String(result.stdout || '');
71
+ }
72
+
73
+ function find_tunnel(cloudflared, name) {
74
+ const text = run(cloudflared, ['tunnel', 'list', '--output', 'json']).trim();
75
+ return text ? JSON.parse(text).find(item => item.name === name) || null : null;
76
+ }
77
+
78
+ /**
79
+ * Prepare the tunnel for `host`, safe to repeat: sign in to Cloudflare in the browser the first time (`interactive`
80
+ * false refuses instead), create the tunnel unless it exists, point the host name at it. Returns the settings it runs
81
+ * with, kept in the entry's settings: { name, host, id, credentials }.
82
+ */
83
+ export function prepare_tunnel({ host, name = DEFAULT_TUNNEL_NAME, interactive = true, say = () => {} }) {
84
+ host = tunnel_host(host); name = tunnel_name(name);
85
+ const cloudflared = install_cloudflared();
86
+ if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) {
87
+ if (!interactive) throw new Error('还没有授权 Cloudflare:在终端里运行一次 codiscuss setup --hosting --public-host 域名,在浏览器里完成授权');
88
+ say(`即将打开浏览器:登录 Cloudflare,选择 ${host.split('.').slice(-2).join('.')} 并点 Authorize,完成后回到这里`);
89
+ run(cloudflared, ['tunnel', 'login'], true);
90
+ if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) throw new Error('Cloudflare 授权没有完成,重新运行即可再试');
91
+ }
92
+ let tunnel = find_tunnel(cloudflared, name);
93
+ if (!tunnel) { run(cloudflared, ['tunnel', 'create', name]); tunnel = find_tunnel(cloudflared, name); }
94
+ if (!tunnel) throw new Error(`隧道 ${name} 建了却读不到,重新运行即可`);
95
+ const credentials = join(TUNNEL_HOME, `${tunnel.id}.json`);
96
+ if (!existsSync(credentials)) throw new Error(`找不到隧道凭据 ${credentials}:这条隧道可能建在别的电脑上,换一个 --tunnel-name 重新运行`);
97
+ try { run(cloudflared, ['tunnel', 'route', 'dns', name, host]); }
98
+ catch (error) {
99
+ // An existing record that already points at this tunnel is fine; any other is reported by the final check.
100
+ say(`没有新建 ${host} 的域名记录(${error.message});若它已指向这条隧道可忽略`);
101
+ }
102
+ return { name, host, id: tunnel.id, credentials };
103
+ }
104
+
105
+ /** The config file of a tunnel as the settings say it now; http2 runs over TCP 443, which proxies block less than QUIC. */
106
+ function tunnel_config(tunnel, port) {
107
+ return [`tunnel: ${tunnel.id}`, `credentials-file: ${tunnel.credentials}`, 'protocol: http2', 'ingress:',
108
+ ` - hostname: ${tunnel.host}`, ` service: http://127.0.0.1:${port}`, ' - service: http_status:404', ''].join('\n');
109
+ }
110
+
111
+ function config_path(data) { return join(data, 'tunnel.yml'); }
112
+
113
+ function read_state(data) {
114
+ try { return JSON.parse(readFileSync(join(data, STATE_FILE), 'utf8')); } catch { return null; }
115
+ }
116
+
117
+ function alive(pid) {
118
+ try { process.kill(pid, 0); return true; } catch { return false; }
119
+ }
120
+
121
+ /** A free loopback port for cloudflared's readiness endpoint. */
122
+ function free_port() {
123
+ return new Promise((done, fail) => {
124
+ const server = net.createServer().once('error', fail);
125
+ server.listen(0, '127.0.0.1', () => { const { port } = server.address(); server.close(() => done(port)); });
126
+ });
127
+ }
128
+
129
+ /** End the tunnel process this directory runs, if any. */
130
+ export function stop_tunnel(data) {
131
+ const state = read_state(data);
132
+ if (state?.pid && alive(state.pid)) { try { process.kill(state.pid); } catch { /* already gone */ } }
133
+ rmSync(join(data, STATE_FILE), { force: true });
134
+ }
135
+
136
+ /**
137
+ * Keep the tunnel as set: with `tunnel` settings and `want` (the entry is meant to run), cloudflared runs on a config
138
+ * written from them for the entry `port`, started (again) when it is not running or its config changed; otherwise it is
139
+ * stopped. Returns what was done: 'started', 'restarted', 'running', 'stopped' or 'none'.
140
+ */
141
+ export async function ensure_tunnel(data, tunnel, port, want = true) {
142
+ if (!tunnel || !want) { const had = read_state(data); stop_tunnel(data); return had ? 'stopped' : 'none'; }
143
+ const cloudflared = cloudflared_path();
144
+ if (!cloudflared) throw new Error('没有找到 cloudflared,重新运行 codiscuss setup --hosting --public-host 域名');
145
+ const config = tunnel_config(tunnel, port), path = config_path(data);
146
+ const changed = !existsSync(path) || readFileSync(path, 'utf8') !== config;
147
+ const state = read_state(data), running = Boolean(state?.pid && alive(state.pid));
148
+ if (running && !changed) return 'running';
149
+ if (running) stop_tunnel(data);
150
+ mkdirSync(data, { recursive: true });
151
+ writeFileSync(path, config);
152
+ const metrics = await free_port();
153
+ const log = openSync(join(data, LOG_FILE), 'a');
154
+ // Detached and outside the package folder: it runs on after the panel, and never holds a folder npm replaces.
155
+ const child = spawn(cloudflared, ['tunnel', '--config', path, '--metrics', `127.0.0.1:${metrics}`, 'run', tunnel.name],
156
+ { cwd: data, detached: true, stdio: ['ignore', log, log], windowsHide: true });
157
+ closeSync(log);
158
+ child.unref();
159
+ writeFileSync(join(data, STATE_FILE), JSON.stringify({ pid: child.pid, metrics, started_at: Date.now() }));
160
+ return running ? 'restarted' : 'started';
161
+ }
162
+
163
+ /**
164
+ * The tunnel as it is: { running, connected, since } — running is the process, connected is cloudflared's own answer
165
+ * that it holds a connection to Cloudflare (its /ready endpoint).
166
+ */
167
+ export async function tunnel_status(data) {
168
+ const state = read_state(data);
169
+ if (!state?.pid || !alive(state.pid)) return { running: false, connected: false, since: 0 };
170
+ let connected = false;
171
+ try { connected = (await fetch(`http://127.0.0.1:${state.metrics}/ready`, { signal: AbortSignal.timeout(READY_TIMEOUT_MS) })).ok; } catch { connected = false; }
172
+ return { running: true, connected, since: state.started_at || 0 };
173
+ }
174
+
175
+ /**
176
+ * Remove the sign-in start hosting-setup.ps1 used to register for the tunnel, and end the cloudflared it started, so
177
+ * the panel's is the only one. Returns whether anything was removed.
178
+ */
179
+ export function remove_legacy_tunnel_start() {
180
+ if (process.platform !== 'win32') return false;
181
+ const task = spawnSync('schtasks', ['/Query', '/TN', LEGACY_TASK], { windowsHide: true }).status === 0;
182
+ if (task) {
183
+ spawnSync('schtasks', ['/End', '/TN', LEGACY_TASK], { windowsHide: true });
184
+ spawnSync('schtasks', ['/Delete', '/TN', LEGACY_TASK, '/F'], { windowsHide: true });
185
+ }
186
+ const run_key = spawnSync('reg', ['delete', 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run', '/v', LEGACY_RUN, '/f'], { windowsHide: true }).status === 0;
187
+ if (task || run_key) {
188
+ spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
189
+ "Get-CimInstance Win32_Process -Filter \"Name='cloudflared.exe'\" | Where-Object { $_.CommandLine -like '*\\.cloudflared\\config.yml*' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"],
190
+ { windowsHide: true });
191
+ }
192
+ return task || run_key;
193
+ }
194
+
195
+ /** The last lines of the tunnel's log, for a failed check. */
196
+ export function tunnel_log_tail(data, lines = 3) {
197
+ try { return readFileSync(join(data, LOG_FILE), 'utf8').trim().split(/\r?\n/).slice(-lines).join(' '); } catch { return ''; }
198
+ }
@@ -52,7 +52,9 @@ async function main() {
52
52
  for (let waited = 0; waited < EXIT_WAIT_MS && alive(Number(values.pid)); waited += POLL_MS) await sleep(POLL_MS);
53
53
  let failure = null;
54
54
  for (let attempt = 1; attempt <= INSTALL_ATTEMPTS; attempt += 1) {
55
- try { await npm(['install', '--global', `${NPM_PACKAGE}@${job.version}`], values.data); failure = null; break; }
55
+ // --prefer-online: the version was just read from the registry, while npm's cached package list may predate it
56
+ // (a fresh release fails with "notarget" until the cache expires).
57
+ try { await npm(['install', '--global', '--prefer-online', `${NPM_PACKAGE}@${job.version}`], values.data); failure = null; break; }
56
58
  catch (error) { failure = error; if (attempt < INSTALL_ATTEMPTS) await sleep(RETRY_MS); }
57
59
  }
58
60
  save(failure ? { status: 'install_failed', steps: [...job.steps, `安装失败:${failure.message}`] }