ai_co_discuss 0.4.40 → 0.4.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/runner/admin_panel.mjs +8 -3
- package/runner/cli_login.mjs +1 -1
- package/runner/discussion_setup.mjs +6 -3
- package/runner/discussion_tui.mjs +29 -14
- package/runner/hosting_setup.mjs +48 -3
- package/runner/hosting_tunnel.mjs +88 -11
- package/runner/os_users.mjs +39 -4
- package/web/admin.css +1 -1
- package/web/admin.js +2 -2
- package/web/modern.js +1 -1
package/package.json
CHANGED
package/runner/admin_panel.mjs
CHANGED
|
@@ -21,7 +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
|
+
import { ensure_tunnel, start_tunnel_setup, tunnel_setup_state, tunnel_status } from './hosting_tunnel.mjs';
|
|
25
25
|
import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
|
|
26
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,
|
|
27
27
|
start_instance_as_user } from './os_users.mjs';
|
|
@@ -563,7 +563,7 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
|
|
|
563
563
|
const op = { list_accounts, add_account, reset_password, set_account_disabled, remove_account, run_instance, create_os_user, remove_os_user,
|
|
564
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,
|
|
565
565
|
save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, begin_update,
|
|
566
|
-
autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, protect_account, start_verified, hand_over: () => {}, ...ops };
|
|
566
|
+
autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, keep_tunnel, start_tunnel_setup, protect_account, start_verified, hand_over: () => {}, ...ops };
|
|
567
567
|
const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
|
568
568
|
|
|
569
569
|
async function api(method, path, body) {
|
|
@@ -637,6 +637,11 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
|
|
|
637
637
|
await op.keep_tunnel(data);
|
|
638
638
|
return op.entry_overview(data);
|
|
639
639
|
}
|
|
640
|
+
// The outside address: a Cloudflare tunnel set up by a job of its own (it waits for the owner in the browser).
|
|
641
|
+
if (section === 'tunnel' && name === 'setup') {
|
|
642
|
+
if (method === 'GET') return tunnel_setup_state(data);
|
|
643
|
+
if (method === 'POST') return op.start_tunnel_setup(data, body.host, body.name);
|
|
644
|
+
}
|
|
640
645
|
if (method === 'POST' && section === 'entry' && name === 'settings') { save_entry_settings(data, { public_url: body.public_url }); return op.entry_overview(data); }
|
|
641
646
|
// The default system prompt of new hosted accounts.
|
|
642
647
|
if (section === 'hosted-prompt') {
|
|
@@ -725,7 +730,7 @@ function keep_tunnel(data) {
|
|
|
725
730
|
async function entry_overview(data) {
|
|
726
731
|
const { port, public_url, tunnel } = entry_settings(data), status = await entry_status(data);
|
|
727
732
|
return { running: status.running, port: status.running ? status.port : port, public_url,
|
|
728
|
-
tunnel: tunnel ? { host: tunnel.host, ...(await tunnel_status(data)) } : null };
|
|
733
|
+
tunnel: tunnel ? { host: tunnel.host, name: tunnel.name, ...(await tunnel_status(data)) } : null };
|
|
729
734
|
}
|
|
730
735
|
|
|
731
736
|
// ---- Hosted accounts' failures, to the owner's Weixin ----
|
package/runner/cli_login.mjs
CHANGED
|
@@ -54,7 +54,7 @@ export const LOGIN_METHODS = {
|
|
|
54
54
|
/** The programs a target runs: the owner's own copies, or the shared copies a hosted account's user runs. */
|
|
55
55
|
function executables(target) {
|
|
56
56
|
return Object.fromEntries(Object.entries(cli_sources()).map(([key, cli]) => [key, target ? cli.executable || cli.target
|
|
57
|
-
:
|
|
57
|
+
: cli.program || cli.source]));
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
function check_target(data, target) {
|
|
@@ -13,7 +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
|
+
import { ask_hosting, configure_hosting, finish_hosting, hosting_requested } from './hosting_setup.mjs';
|
|
17
17
|
export { checkbox_prompt } from './discussion_tui.mjs';
|
|
18
18
|
|
|
19
19
|
const ROOT = fileURLToPath(new URL('../', import.meta.url));
|
|
@@ -52,7 +52,7 @@ install 将当前 npm 包安装为持久命令,再运行 setup;setup 配置
|
|
|
52
52
|
--hosting / --no-hosting 在管理面板中显示 / 隐藏托管管理(用户、Windows 用户、命令行登录、API 密钥),选择会记住;
|
|
53
53
|
Windows 上加 --hosting 时还会设好登录入口(随管理面板启动)、开启登录自启,并检查入口能否打开
|
|
54
54
|
--entry-port PORT 登录入口端口,默认 8780
|
|
55
|
-
--public-host 域名 外网地址(可选),如
|
|
55
|
+
--public-host 域名 外网地址(可选),如 codiscuss.example.com;终端里运行 --hosting 而不给时会询问。域名须已托管在 Cloudflare;会安装 cloudflared、
|
|
56
56
|
在浏览器里授权 Cloudflare、建固定隧道并添加域名记录,隧道由管理面板运行
|
|
57
57
|
--tunnel-name NAME Cloudflare 隧道名,默认 codiscuss
|
|
58
58
|
--workflows 安装全部随包工作流,已有同名的覆盖为最新版(原来的先备份到服务目录 backups/);
|
|
@@ -453,8 +453,11 @@ async function setup(options) {
|
|
|
453
453
|
const hosting_setup = hosting_requested(options, choices.hosting);
|
|
454
454
|
let hosting = null;
|
|
455
455
|
if (hosting_setup) {
|
|
456
|
+
// The outside address is asked here when not given (a terminal run): the domain, the tunnel name, the Cloudflare checks.
|
|
457
|
+
const show = (title, lines) => styled ? step(title, lines, tone.yellow('▲')) : process.stderr.write(`${[title, ...lines].join('\n')}\n`);
|
|
458
|
+
await ask_hosting(home, options, { ask, show });
|
|
456
459
|
// 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`) });
|
|
460
|
+
hosting = await configure_hosting(home, options, { say: line => process.stderr.write(`${line}\n`) });
|
|
458
461
|
step(hosting.issues.length ? '登录入口已设置,有待处理项' : '登录入口已设置', [...hosting.lines, ...hosting.issues]);
|
|
459
462
|
}
|
|
460
463
|
const result = { home, python, clients: selected.map(item => item.name), ...configured, workflows, ...(choices.hosting ? { hosting: true } : {}),
|
|
@@ -14,6 +14,8 @@ const LOGO = [
|
|
|
14
14
|
];
|
|
15
15
|
const PREFIX_LETTERS = 2;
|
|
16
16
|
const GRADIENT = [[91, 140, 255], [167, 139, 250], [240, 171, 252]];
|
|
17
|
+
// An empty answer sooner than this after a question is a key left from before it, not the owner's answer.
|
|
18
|
+
const STALE_ANSWER_MS = 300;
|
|
17
19
|
|
|
18
20
|
export const styled = Boolean(process.stderr.isTTY) && !process.env.NO_COLOR;
|
|
19
21
|
const paint = (code, text) => (styled ? `\x1b[${code}m${text}\x1b[0m` : text);
|
|
@@ -78,6 +80,18 @@ export function step(title, lines = [], mark = tone.green('◇')) {
|
|
|
78
80
|
write(`${mark} ${title}\n${lines.map(line => `${bar()} ${line}\n`).join('')}${bar()}\n`);
|
|
79
81
|
}
|
|
80
82
|
|
|
83
|
+
/**
|
|
84
|
+
* Draw a prompt's lines over its previous drawing and return how many terminal rows it now takes. A line wider than the
|
|
85
|
+
* terminal wraps onto more rows, so rows are counted by display width: counting lines instead leaves the top of the old
|
|
86
|
+
* drawing on screen at every redraw in a narrow window.
|
|
87
|
+
*/
|
|
88
|
+
function redraw(output, lines, drawn) {
|
|
89
|
+
const columns = output.columns || 80;
|
|
90
|
+
if (drawn) output.write(`\x1b[${drawn}A\r`);
|
|
91
|
+
output.write(`\x1b[J${lines.join('\n')}\n`);
|
|
92
|
+
return lines.reduce((sum, line) => sum + Math.max(1, Math.ceil(text_width(line) / columns)), 0);
|
|
93
|
+
}
|
|
94
|
+
|
|
81
95
|
/** Animate a step while asynchronous work runs; synchronous work simply shows the first frame. */
|
|
82
96
|
export function spinner(title) {
|
|
83
97
|
if (!styled) return { done: () => {}, fail: () => {} };
|
|
@@ -94,11 +108,22 @@ export function spinner(title) {
|
|
|
94
108
|
|
|
95
109
|
/** Ask one free-text question inside the gutter, falling back to a plain prompt. */
|
|
96
110
|
export async function ask(question, hint = '') {
|
|
111
|
+
// Keys typed before the question are not its answer: an Enter left from the previous prompt, or keys pressed while setup
|
|
112
|
+
// worked, would otherwise answer at once (an empty answer, often the default) without the owner seeing the question.
|
|
113
|
+
// Only at a terminal: input piped in (a script, a test) is written ahead on purpose and is the answer.
|
|
114
|
+
const terminal = Boolean(process.stdin.isTTY) && typeof process.stdin.setRawMode === 'function';
|
|
115
|
+
if (terminal) while (process.stdin.read?.() != null) { /* dropped */ }
|
|
97
116
|
const prompt = createInterface({ input: process.stdin, output: process.stderr });
|
|
117
|
+
const line = async text => {
|
|
118
|
+
for (;;) {
|
|
119
|
+
const started = Date.now(), answer = await prompt.question(text);
|
|
120
|
+
if (answer || !terminal || Date.now() - started >= STALE_ANSWER_MS) return answer;
|
|
121
|
+
}
|
|
122
|
+
};
|
|
98
123
|
try {
|
|
99
|
-
if (!styled) return await
|
|
124
|
+
if (!styled) return await line(`${question}${hint}:`);
|
|
100
125
|
write(`${tone.cyan('◆')} ${question.split('\n').join(`\n${bar()} `)}\n`);
|
|
101
|
-
const answer = await
|
|
126
|
+
const answer = await line(`${bar()} ${tone.dim(hint)} ${tone.cyan('›')} `);
|
|
102
127
|
write(`${bar()}\n`);
|
|
103
128
|
return answer;
|
|
104
129
|
} finally { prompt.close(); }
|
|
@@ -127,12 +152,7 @@ export function checkbox_prompt(message, items, input = process.stdin, output =
|
|
|
127
152
|
if (!items[next].disabled) { cursor = next; return; }
|
|
128
153
|
}
|
|
129
154
|
};
|
|
130
|
-
const draw =
|
|
131
|
-
if (drawn) output.write(`\x1b[${drawn}A`);
|
|
132
|
-
output.write(`${lines.map(line => `\x1b[2K${line}`).join('\n')}\n`);
|
|
133
|
-
if (lines.length < drawn) output.write(`\x1b[J`);
|
|
134
|
-
drawn = lines.length;
|
|
135
|
-
};
|
|
155
|
+
const draw = lines => { drawn = redraw(output, lines, drawn); };
|
|
136
156
|
const active = () => [`${tone.cyan('◆')} ${message}`, ...rows.map((item, index) => checkbox_row(item, index === cursor, checked[index])),
|
|
137
157
|
`${tone.gray('└')} ${tone.dim('↑↓ 移动 · 空格 勾选 · 回车 确认')}`];
|
|
138
158
|
return new Promise((done, fail) => {
|
|
@@ -185,12 +205,7 @@ export function tree_prompt(message, groups, input = process.stdin, output = pro
|
|
|
185
205
|
const enabled = () => checked.flat().filter(Boolean).length;
|
|
186
206
|
const rows = () => groups.flatMap((group, index) => [{ group: index },
|
|
187
207
|
...(expanded.has(index) ? group.items.map((_, item) => ({ group: index, item })) : [])]);
|
|
188
|
-
const draw = lines => {
|
|
189
|
-
if (drawn) output.write(`\x1b[${drawn}A`);
|
|
190
|
-
output.write(`${lines.map(line => `\x1b[2K${line}`).join('\n')}\n`);
|
|
191
|
-
if (lines.length < drawn) output.write('\x1b[J');
|
|
192
|
-
drawn = lines.length;
|
|
193
|
-
};
|
|
208
|
+
const draw = lines => { drawn = redraw(output, lines, drawn); };
|
|
194
209
|
const row_text = ({ group, item }, focused) => {
|
|
195
210
|
const pointer = focused ? tone.cyan('›') : ' ';
|
|
196
211
|
if (item === undefined) {
|
package/runner/hosting_setup.mjs
CHANGED
|
@@ -6,14 +6,16 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { spawnSync } from 'node:child_process';
|
|
8
8
|
import { existsSync } from 'node:fs';
|
|
9
|
+
import { homedir } from 'node:os';
|
|
9
10
|
import { dirname, join } from 'node:path';
|
|
10
11
|
import { fileURLToPath } from 'node:url';
|
|
11
12
|
|
|
12
13
|
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 { prepare_tunnel, remove_legacy_tunnel_start, tunnel_host, tunnel_log_tail, tunnel_name } from './hosting_tunnel.mjs';
|
|
14
15
|
import { launcher_path, set_autostart } from './launcher.mjs';
|
|
15
16
|
|
|
16
17
|
const PANEL_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), 'admin_panel.mjs');
|
|
18
|
+
const CLOUDFLARE_CERT = join(homedir(), '.cloudflared', 'cert.pem');
|
|
17
19
|
const LOGIN_PATH = '/_entry/login';
|
|
18
20
|
const LOCAL_WAIT_MS = 60_000;
|
|
19
21
|
// A new tunnel's host name can take a minute or two to resolve.
|
|
@@ -26,21 +28,64 @@ export function hosting_requested(options, hosting_on) {
|
|
|
26
28
|
return process.platform === 'win32' && hosting_on && Boolean(options.hosting || options['public-host'] || options['entry-port']);
|
|
27
29
|
}
|
|
28
30
|
|
|
31
|
+
// What the owner checks on the Cloudflare site of the domain first: it may serve another website, and its rules apply to
|
|
32
|
+
// the entry's host name too.
|
|
33
|
+
const CLOUDFLARE_CHECKS = [
|
|
34
|
+
'缓存规则:不能有对所有主机或这个子域名生效的“缓存全部内容”(Cache Everything),否则一个账号的页面可能被缓存后给到另一个账号',
|
|
35
|
+
'安全:关闭 Bot Fight Mode,或为这个子域名加跳过规则,否则网页的接口请求会被拦',
|
|
36
|
+
'速度:关闭 Rocket Loader(会改写页面脚本)',
|
|
37
|
+
'DNS:这个子域名还没有记录(有的话先删掉)',
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Ask in the terminal for the outside address when it was not given: the domain (blank keeps the current one, or keeps
|
|
42
|
+
* the entry to this computer), the tunnel name, and a pause to check the Cloudflare site first. Sets
|
|
43
|
+
* options['public-host'] and options['tunnel-name']; a run without a terminal, with --yes or with --public-host is not
|
|
44
|
+
* asked anything.
|
|
45
|
+
*
|
|
46
|
+
* Args:
|
|
47
|
+
* ask: (question, hint) => Promise<string>, the setup's own prompt.
|
|
48
|
+
* show: (title, lines) => void, how setup shows a step.
|
|
49
|
+
*/
|
|
50
|
+
export async function ask_hosting(home, options, { ask, show, interactive = Boolean(process.stdin.isTTY) }) {
|
|
51
|
+
if (!interactive || options.yes || options['public-host']) return;
|
|
52
|
+
const current = entry_settings(home).tunnel;
|
|
53
|
+
for (;;) {
|
|
54
|
+
const answer = (await ask('外网域名:须已托管在 Cloudflare,如 codiscuss.example.com',
|
|
55
|
+
current ? `当前 ${current.host},直接回车保持` : '直接回车则只在本机用')).trim();
|
|
56
|
+
if (!answer) return;
|
|
57
|
+
try { options['public-host'] = tunnel_host(answer); break; }
|
|
58
|
+
catch (error) { show(error.message, []); }
|
|
59
|
+
}
|
|
60
|
+
if (current?.host === options['public-host'] && !options['tunnel-name']) options['tunnel-name'] = current.name;
|
|
61
|
+
if (!options['tunnel-name']) {
|
|
62
|
+
for (;;) {
|
|
63
|
+
const name = (await ask('Cloudflare 隧道名', '直接回车用 codiscuss')).trim();
|
|
64
|
+
try { options['tunnel-name'] = tunnel_name(name || undefined); break; }
|
|
65
|
+
catch (error) { show(error.message, []); }
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
show(`开始前在 Cloudflare 后台检查 ${options['public-host']} 所在站点`, CLOUDFLARE_CHECKS.map((line, index) => `${index + 1}. ${line}`));
|
|
69
|
+
await ask('检查完后继续:接下来会安装 cloudflared,并打开浏览器授权 Cloudflare', '回车继续,Ctrl+C 退出');
|
|
70
|
+
}
|
|
71
|
+
|
|
29
72
|
/**
|
|
30
73
|
* Save the entry's settings and prepare the outside address, before the service starts. Returns { lines, issues }:
|
|
31
74
|
* what was set, and what is left for the owner.
|
|
32
75
|
*/
|
|
33
|
-
export function configure_hosting(home, options, { interactive = Boolean(process.stdin.isTTY), say = () => {} } = {}) {
|
|
76
|
+
export async function configure_hosting(home, options, { interactive = Boolean(process.stdin.isTTY), say = () => {} } = {}) {
|
|
34
77
|
const lines = [], issues = [];
|
|
35
78
|
const changes = { running: true };
|
|
36
79
|
if (options['entry-port']) changes.port = Number(options['entry-port']);
|
|
37
80
|
if (options['public-host']) {
|
|
38
81
|
try {
|
|
39
82
|
const host = tunnel_host(options['public-host']);
|
|
40
|
-
const tunnel = prepare_tunnel({ host, name: options['tunnel-name'], interactive, say });
|
|
83
|
+
const tunnel = await prepare_tunnel({ host, name: options['tunnel-name'], interactive, say });
|
|
41
84
|
Object.assign(changes, { public_url: `https://${host}`, tunnel });
|
|
42
85
|
lines.push(`外网地址 https://${host},经 Cloudflare 隧道 ${tunnel.name} 转到登录入口;隧道独立运行,由管理面板按设置维持`);
|
|
43
86
|
if (remove_legacy_tunnel_start()) lines.push('已移除旧的“CoDiscuss Tunnel”开机任务,改由管理面板运行隧道');
|
|
87
|
+
// cert.pem manages the whole Cloudflare site, while the running tunnel needs only its own credentials.
|
|
88
|
+
if (existsSync(CLOUDFLARE_CERT)) lines.push(`Cloudflare 授权文件 ${CLOUDFLARE_CERT} 能在该站点下建隧道、改 DNS,隧道运行用不到它:建议移出这台电脑自己保管(重建隧道或换域名时再放回或重新授权);托管账号务必全部隔离`);
|
|
44
89
|
} catch (error) { issues.push(`外网地址没有设好:${error.message}`); }
|
|
45
90
|
}
|
|
46
91
|
const saved = save_entry_settings(home, changes);
|
|
@@ -14,7 +14,10 @@ import { spawn, spawnSync } from 'node:child_process';
|
|
|
14
14
|
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
15
15
|
import net from 'node:net';
|
|
16
16
|
import { homedir } from 'node:os';
|
|
17
|
-
import { join } from 'node:path';
|
|
17
|
+
import { join, resolve } from 'node:path';
|
|
18
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
19
|
+
|
|
20
|
+
import { save_entry_settings } from '../gateway/gateway.mjs';
|
|
18
21
|
|
|
19
22
|
const TUNNEL_HOME = join(homedir(), '.cloudflared');
|
|
20
23
|
// Where winget puts it; a process started before the install does not see the new PATH yet.
|
|
@@ -24,6 +27,8 @@ const HOST_PATTERN = /^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-
|
|
|
24
27
|
const NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
25
28
|
export const DEFAULT_TUNNEL_NAME = 'codiscuss';
|
|
26
29
|
const STATE_FILE = 'tunnel.json';
|
|
30
|
+
// The panel's setup job writes its progress here (start_tunnel_setup).
|
|
31
|
+
const SETUP_FILE = 'tunnel-setup.json';
|
|
27
32
|
const LOG_FILE = 'tunnel.log';
|
|
28
33
|
const READY_TIMEOUT_MS = 1500;
|
|
29
34
|
// The scheduled task and Run entry hosting-setup.ps1 used before the panel kept the tunnel.
|
|
@@ -52,18 +57,38 @@ export function cloudflared_path() {
|
|
|
52
57
|
return found?.trim() || INSTALLED_PATHS.find(path => existsSync(path)) || '';
|
|
53
58
|
}
|
|
54
59
|
|
|
55
|
-
/** Install cloudflared with winget when it is missing, and return its path. */
|
|
56
|
-
export function install_cloudflared() {
|
|
60
|
+
/** Install cloudflared with winget when it is missing, and return its path. `shown` prints winget's output (a terminal). */
|
|
61
|
+
export function install_cloudflared(shown = true) {
|
|
57
62
|
const present = cloudflared_path();
|
|
58
63
|
if (present) return present;
|
|
59
64
|
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
|
|
65
|
+
{ stdio: shown ? TO_STDERR : 'ignore', windowsHide: true });
|
|
66
|
+
if (winget.error) throw new Error('没有 winget:请先从 Microsoft Store 安装“应用安装程序”,或自行安装 cloudflared 后再试');
|
|
62
67
|
const path = cloudflared_path();
|
|
63
|
-
if (!path) throw new Error(
|
|
68
|
+
if (!path) throw new Error(`cloudflared 没有装上(winget 退出码 ${winget.status})`);
|
|
64
69
|
return path;
|
|
65
70
|
}
|
|
66
71
|
|
|
72
|
+
/**
|
|
73
|
+
* Sign in to Cloudflare: cloudflared opens the browser and waits until the owner authorizes. Its output is read as it
|
|
74
|
+
* comes, so the link reaches `on_url` (shown in the panel, for a browser that did not open) while it waits.
|
|
75
|
+
*/
|
|
76
|
+
function login_in_browser(cloudflared, { shown, on_url }) {
|
|
77
|
+
return new Promise((done, fail) => {
|
|
78
|
+
const child = spawn(cloudflared, ['tunnel', 'login'], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
79
|
+
const read = chunk => {
|
|
80
|
+
const text = String(chunk);
|
|
81
|
+
if (shown) process.stderr.write(text);
|
|
82
|
+
const url = text.match(/https:\/\/dash\.cloudflare\.com\/\S+/)?.[0];
|
|
83
|
+
if (url) on_url(url);
|
|
84
|
+
};
|
|
85
|
+
child.stdout.on('data', read);
|
|
86
|
+
child.stderr.on('data', read);
|
|
87
|
+
child.on('error', fail);
|
|
88
|
+
child.on('exit', code => (code === 0 ? done() : fail(new Error(`Cloudflare 授权没有完成(退出码 ${code}),重新开始即可再试`))));
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
67
92
|
function run(cloudflared, args, shown = false) {
|
|
68
93
|
const result = spawnSync(cloudflared, args, { encoding: 'utf8', windowsHide: !shown, stdio: shown ? TO_STDERR : 'pipe' });
|
|
69
94
|
if (result.status !== 0) throw new Error(`cloudflared ${args.join(' ')} 失败:${String(result.stderr || '').trim().split(/\r?\n/).pop() || `退出码 ${result.status}`}`);
|
|
@@ -79,21 +104,29 @@ function find_tunnel(cloudflared, name) {
|
|
|
79
104
|
* Prepare the tunnel for `host`, safe to repeat: sign in to Cloudflare in the browser the first time (`interactive`
|
|
80
105
|
* false refuses instead), create the tunnel unless it exists, point the host name at it. Returns the settings it runs
|
|
81
106
|
* with, kept in the entry's settings: { name, host, id, credentials }.
|
|
107
|
+
*
|
|
108
|
+
* Args:
|
|
109
|
+
* shown: print the programs' output (a terminal); the panel's job runs without one.
|
|
110
|
+
* progress: (step) => void, told each step as it starts; on_url: (url) => void, the Cloudflare sign-in link.
|
|
82
111
|
*/
|
|
83
|
-
export function prepare_tunnel({ host, name = DEFAULT_TUNNEL_NAME, interactive = true, say = () => {} }) {
|
|
112
|
+
export async function prepare_tunnel({ host, name = DEFAULT_TUNNEL_NAME, interactive = true, shown = true, say = () => {}, progress = () => {}, on_url = () => {} }) {
|
|
84
113
|
host = tunnel_host(host); name = tunnel_name(name);
|
|
85
|
-
|
|
114
|
+
progress('安装 cloudflared');
|
|
115
|
+
const cloudflared = install_cloudflared(shown);
|
|
86
116
|
if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) {
|
|
87
|
-
if (!interactive) throw new Error('还没有授权 Cloudflare
|
|
117
|
+
if (!interactive) throw new Error('还没有授权 Cloudflare:在管理面板“概览”页设置外网地址,或在终端运行 codiscuss setup --hosting,在浏览器里完成授权');
|
|
118
|
+
progress('等待 Cloudflare 授权');
|
|
88
119
|
say(`即将打开浏览器:登录 Cloudflare,选择 ${host.split('.').slice(-2).join('.')} 并点 Authorize,完成后回到这里`);
|
|
89
|
-
|
|
90
|
-
if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) throw new Error('Cloudflare
|
|
120
|
+
await login_in_browser(cloudflared, { shown, on_url });
|
|
121
|
+
if (!existsSync(join(TUNNEL_HOME, 'cert.pem'))) throw new Error('Cloudflare 授权没有完成,重新开始即可再试');
|
|
91
122
|
}
|
|
123
|
+
progress('建立隧道');
|
|
92
124
|
let tunnel = find_tunnel(cloudflared, name);
|
|
93
125
|
if (!tunnel) { run(cloudflared, ['tunnel', 'create', name]); tunnel = find_tunnel(cloudflared, name); }
|
|
94
126
|
if (!tunnel) throw new Error(`隧道 ${name} 建了却读不到,重新运行即可`);
|
|
95
127
|
const credentials = join(TUNNEL_HOME, `${tunnel.id}.json`);
|
|
96
128
|
if (!existsSync(credentials)) throw new Error(`找不到隧道凭据 ${credentials}:这条隧道可能建在别的电脑上,换一个 --tunnel-name 重新运行`);
|
|
129
|
+
progress('添加域名记录');
|
|
97
130
|
try { run(cloudflared, ['tunnel', 'route', 'dns', name, host]); }
|
|
98
131
|
catch (error) {
|
|
99
132
|
// An existing record that already points at this tunnel is fine; any other is reported by the final check.
|
|
@@ -196,3 +229,47 @@ export function remove_legacy_tunnel_start() {
|
|
|
196
229
|
export function tunnel_log_tail(data, lines = 3) {
|
|
197
230
|
try { return readFileSync(join(data, LOG_FILE), 'utf8').trim().split(/\r?\n/).slice(-lines).join(' '); } catch { return ''; }
|
|
198
231
|
}
|
|
232
|
+
|
|
233
|
+
// ---- Setting the outside address from the management panel ----
|
|
234
|
+
|
|
235
|
+
/** The panel's setup job, as it last wrote: { status: 'running'|'done'|'failed', step, url, note, error, host, pid, started_at }. */
|
|
236
|
+
export function tunnel_setup_state(data) {
|
|
237
|
+
try { return JSON.parse(readFileSync(join(data, SETUP_FILE), 'utf8')); } catch { return { status: 'none' }; }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Start setting the outside address from the panel: installing cloudflared and waiting for the owner to authorize in the
|
|
242
|
+
* browser can take minutes, so a job of its own does it (this file, run as `prepare`) and records each step for the page.
|
|
243
|
+
*/
|
|
244
|
+
export function start_tunnel_setup(data, host, name) {
|
|
245
|
+
host = tunnel_host(host); name = tunnel_name(name);
|
|
246
|
+
const current = tunnel_setup_state(data);
|
|
247
|
+
if (current.status === 'running' && current.pid && alive(current.pid)) throw new Error('外网地址正在设置中,请等它完成');
|
|
248
|
+
mkdirSync(data, { recursive: true });
|
|
249
|
+
const log = openSync(join(data, LOG_FILE), 'a');
|
|
250
|
+
const child = spawn(process.execPath, [fileURLToPath(import.meta.url), 'prepare', data, host, name], { cwd: data, stdio: ['ignore', log, log], windowsHide: true });
|
|
251
|
+
closeSync(log);
|
|
252
|
+
const state = { status: 'running', step: '准备', url: '', note: '', error: '', host, pid: child.pid, started_at: Date.now() };
|
|
253
|
+
writeFileSync(join(data, SETUP_FILE), JSON.stringify(state));
|
|
254
|
+
return state;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The job itself: prepare the tunnel, keep it in the entry's settings, take over from the old start, start it. */
|
|
258
|
+
async function prepare_job(data, host, name) {
|
|
259
|
+
const path = join(data, SETUP_FILE);
|
|
260
|
+
const state = { ...tunnel_setup_state(data), status: 'running', pid: process.pid };
|
|
261
|
+
const save = change => writeFileSync(path, JSON.stringify(Object.assign(state, change)));
|
|
262
|
+
try {
|
|
263
|
+
const tunnel = await prepare_tunnel({ host, name, shown: false, progress: step => save({ step }), on_url: url => save({ url }), say: note => save({ note }) });
|
|
264
|
+
save({ step: '启动隧道', url: '' });
|
|
265
|
+
const settings = save_entry_settings(data, { public_url: `https://${tunnel.host}`, tunnel });
|
|
266
|
+
remove_legacy_tunnel_start();
|
|
267
|
+
await ensure_tunnel(data, tunnel, settings.port, settings.running);
|
|
268
|
+
save({ status: 'done', step: '', host: tunnel.host });
|
|
269
|
+
} catch (error) { save({ status: 'failed', error: error.message }); }
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href && process.argv[2] === 'prepare') {
|
|
273
|
+
const [, , , data, host, name] = process.argv;
|
|
274
|
+
prepare_job(data, host, name);
|
|
275
|
+
}
|
package/runner/os_users.mjs
CHANGED
|
@@ -40,14 +40,49 @@ const ELEVATED_TIMEOUT_MS = 300_000;
|
|
|
40
40
|
export function cli_sources(home = homedir(), env = process.env) {
|
|
41
41
|
const app_data = env.APPDATA || join(home, 'AppData', 'Roaming');
|
|
42
42
|
const local = env.LOCALAPPDATA || join(home, 'AppData', 'Local');
|
|
43
|
+
const codex = codex_source(app_data, env);
|
|
43
44
|
return {
|
|
44
|
-
claude: { label: 'Claude Code', source: join(home, '.local', 'bin', 'claude.exe'), target: join(CLI_ROOT, 'claude.exe'), adapter: 'claude' },
|
|
45
|
-
codex:
|
|
46
|
-
|
|
47
|
-
|
|
45
|
+
claude: { label: 'Claude Code', source: installed_program(join(home, '.local', 'bin', 'claude.exe'), 'claude.exe', env), target: join(CLI_ROOT, 'claude.exe'), adapter: 'claude' },
|
|
46
|
+
codex: codex.single
|
|
47
|
+
? { label: 'Codex', source: codex.program, target: join(CLI_ROOT, 'codex', 'codex.exe'), adapter: 'codex_cli' }
|
|
48
|
+
: { label: 'Codex', source: codex.folder, program: codex.program, target: join(CLI_ROOT, 'codex'), executable: join(CLI_ROOT, 'codex', 'bin', 'codex.exe'),
|
|
49
|
+
adapter: 'codex_cli', folder: true },
|
|
50
|
+
agy: { label: 'Antigravity CLI', source: installed_program(join(local, 'agy', 'bin', 'agy.exe'), 'agy.exe', env), target: join(CLI_ROOT, 'agy.exe'), adapter: 'antigravity_cli' },
|
|
48
51
|
};
|
|
49
52
|
}
|
|
50
53
|
|
|
54
|
+
/** The first `name` on PATH, or ''. */
|
|
55
|
+
function on_path(name, env) {
|
|
56
|
+
const found = spawnSync('where.exe', [name], { encoding: 'utf8', windowsHide: true, env }).stdout?.split(/\r?\n/).find(Boolean);
|
|
57
|
+
return found?.trim() || '';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A program at its installer's usual place, else the one on PATH; the usual place when neither is there. */
|
|
61
|
+
function installed_program(usual, name, env) {
|
|
62
|
+
return existsSync(usual) ? usual : on_path(name, env) || usual;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const CODEX_PLATFORM = process.arch === 'arm64' ? ['codex-win32-arm64', 'aarch64-pc-windows-msvc'] : ['codex-win32-x64', 'x86_64-pc-windows-msvc'];
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Codex's native program as installed. npm puts it in a platform package with the tools it runs beside it (the whole
|
|
69
|
+
* folder is what the shared copy takes): nested under @openai/codex, or beside it with newer npm, in the npm folder the
|
|
70
|
+
* codex command is in (any prefix) or the default one. A standalone codex.exe on PATH is taken alone (`single`). Returns
|
|
71
|
+
* { folder, program, single }; when Codex is not installed, the default npm place, so a message names where it was looked for.
|
|
72
|
+
*/
|
|
73
|
+
function codex_source(app_data, env) {
|
|
74
|
+
const [platform, triple] = CODEX_PLATFORM;
|
|
75
|
+
const command = on_path('codex.cmd', env);
|
|
76
|
+
const npm_folders = [...new Set([command ? dirname(command) : '', join(app_data, 'npm')].filter(Boolean))];
|
|
77
|
+
const folders = npm_folders.flatMap(npm => [join(npm, 'node_modules', '@openai', 'codex', 'node_modules', '@openai', platform, 'vendor', triple),
|
|
78
|
+
join(npm, 'node_modules', '@openai', platform, 'vendor', triple)]);
|
|
79
|
+
const folder = folders.find(item => existsSync(join(item, 'bin', 'codex.exe')));
|
|
80
|
+
if (folder) return { folder, program: join(folder, 'bin', 'codex.exe'), single: false };
|
|
81
|
+
const standalone = on_path('codex.exe', env);
|
|
82
|
+
if (standalone) return { folder: dirname(standalone), program: standalone, single: true };
|
|
83
|
+
return { folder: folders.at(-2), program: join(folders.at(-2), 'bin', 'codex.exe'), single: false };
|
|
84
|
+
}
|
|
85
|
+
|
|
51
86
|
/** The shared program each adapter runs for accounts with their own Windows user. */
|
|
52
87
|
export function shared_executables() {
|
|
53
88
|
return Object.fromEntries(Object.values(cli_sources()).map(cli => [cli.adapter, cli.executable || cli.target]));
|