ai_co_discuss 0.4.26 → 0.4.28

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.
@@ -1,559 +1,589 @@
1
- /** npm bootstrap and per-user setup; never logs in or starts an AI conversation. */
2
- import { spawn, spawnSync } from 'node:child_process';
3
- import { accessSync, constants, copyFileSync, existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync } from 'node:fs';
4
- import { homedir, tmpdir } from 'node:os';
5
- import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
6
- import { fileURLToPath } from 'node:url';
7
- import { parseArgs } from 'node:util';
8
-
9
- import { atomic_json } from './files.mjs';
10
- import { launch_settings, save_launch_settings } from './discussion_launch.mjs';
11
- import { assert_shared_home, service_home } from './discussion_service.mjs';
12
- import { SKILLS, install_skills, install_workflows, remove_legacy_skills, shipped_workflows } from './discussion_skills.mjs';
13
- import { ask, checkbox_prompt, intro, outro, pad, short_path, spinner, step, styled, text_width, tone, tree_prompt } from './discussion_tui.mjs';
14
- import { install_launcher, launcher_path } from './launcher.mjs';
15
- export { checkbox_prompt } from './discussion_tui.mjs';
16
-
17
- const ROOT = fileURLToPath(new URL('../', import.meta.url));
18
- const PACKAGE = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
19
- const PROBE_TIMEOUT = 10000;
20
- const MIN_NODE_MAJOR = 24;
21
- const DEFAULT_PORT = 8765;
22
- const ATTENTION_EXIT_CODE = 2;
23
- const AGY_SETTINGS = ['.gemini', 'antigravity-cli', 'settings.json'];
24
- const AGY_RULE_RECORD = 'agy-permission.json';
25
- const AGY_SETTINGS_BACKUP = 'agy-settings.backup.json';
26
- const SKILL_RECORD = 'skills-manifest.json';
27
- const AGY_SKILL_CONFIG = ['.gemini', 'config', 'skills.json'];
28
- const CLIENTS = {
29
- codex: { name: 'Codex', commands: ['codex'], adapter: 'codex_cli', skills: ['.agents', 'skills'] },
30
- claude: { name: 'Claude', commands: ['claude'], adapter: 'claude', skills: ['.claude', 'skills'] },
31
- antigravity: { name: 'Antigravity', commands: ['agy'], adapter: 'antigravity_cli', skills: ['.gemini', 'config', 'skills'],
32
- legacy_skills: ['.gemini', 'antigravity-cli', 'skills'] },
33
- cursor: { name: 'Grok(Cursor CLI)', commands: ['agent', 'cursor-agent'], skills: ['.cursor', 'skills'] },
34
- };
35
- const OPTIONS = { yes: { type: 'boolean' }, clients: { type: 'string' }, python: { type: 'string' },
36
- codex: { type: 'string' }, claude: { type: 'string' }, antigravity: { type: 'string' }, cursor: { type: 'string' },
37
- port: { type: 'string' }, prefix: { type: 'string' }, 'skills-home': { type: 'string' },
38
- 'no-start': { type: 'boolean' }, 'no-open': { type: 'boolean' }, workflows: { type: 'boolean' }, json: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } };
39
- const HELP = `用法:codiscuss install [选项] / codiscuss setup [选项]
40
- install 将当前 npm 包安装为持久命令,再运行 setup;setup 配置已有安装。
41
- --yes 使用已检测且支持自动接入的软件,冲突保留并报告
42
- --clients codex,claude,antigravity,cursor 选择 CLI;none 只配置网站
43
- --python PATH 指定 Python 3.10+ 原生可执行文件
44
- --codex/--claude/--antigravity/--cursor PATH 指定 CLI(Windows 为 .exe,Cursor 也支持 .cmd)
45
- --port PORT 本机网站端口,默认 8765
46
- --no-start / --no-open 只配置 / 启动但不打开浏览器
47
- --prefix DIR npm 安装前缀(install)
48
- --skills-home DIR 技能用户根目录(默认当前用户目录)
49
- --workflows 安装全部随包工作流,已有同名的覆盖为最新版(原来的先备份到服务目录 backups/);
50
- 交互运行时也可在“安装配置”里逐个勾选;不选则不安装,选择不会记住
51
- Antigravity(显示名 Gemini)使用 agy;Grok 使用 Cursor CLI(agent / cursor-agent)。仅检测 CLI。
52
- Cursor 当前只安装技能,可手动参与;全自动接入尚未提供。已有软件设置保留。
53
- 显式软件路径可更新已支持的 CLI 配置。安装不会开始讨论。
54
- 中文摘要写入 stderr;输出被重定向或加 --json 时结果 JSON 写入 stdout;退出码 0=完成,2=配置待处理,1=失败。
55
- `;
56
-
57
- /** Read local settings stored outside the npm installation. */
58
- export function local_settings(home = service_home()) {
59
- const path = join(home, 'local-settings.json');
60
- return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
61
- }
62
-
63
- /** Validate prerequisites before installing a package or changing configuration. */
64
- function setup_environment(options) {
65
- if (Number(process.versions.node.split('.')[0]) < MIN_NODE_MAJOR) throw new Error('需要 Node.js 24+,请升级后重试。');
66
- const home = service_home();
67
- assert_shared_home(home);
68
- const previous = local_settings(home);
69
- const python = detect_python(options.python || previous.python);
70
- const port = Number(options.port || previous.port || DEFAULT_PORT);
71
- if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('端口必须为 1–65535 的整数');
72
- return { home, previous, python, port };
73
- }
74
-
75
- /** Summarise the checked runtime in one short line for the styled installer. */
76
- function environment_line(python, port) {
77
- const probe = spawnSync(python, ['-c', 'import sys; print(".".join(map(str, sys.version_info[:3])))'],
78
- { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT });
79
- return `Node ${process.version.slice(1)} · Python ${probe.stdout?.trim() || short_path(python)} · 端口 ${port}`;
80
- }
81
-
82
- /** Find executable PATH entries, explicitly allowing Cursor's Windows .cmd launcher. */
83
- function path_program(name, search_path = process.env.PATH || '', allow_cmd = false) {
84
- const suffixes = process.platform === 'win32' ? (allow_cmd ? ['.exe', '.cmd'] : ['.exe']) : [''];
85
- for (const directory of search_path.split(delimiter).filter(Boolean)) {
86
- for (const suffix of suffixes) {
87
- const path = join(directory.replace(/^"|"$/g, ''), `${name}${suffix}`);
88
- try {
89
- if (!statSync(path).isFile()) continue;
90
- accessSync(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
91
- return path;
92
- } catch { /* Continue through PATH when an entry is absent or not executable. */ }
93
- }
94
- }
95
- return '';
96
- }
97
-
98
- /** Locate npm Codex's native binary inside its package when only its shim is on PATH; dot directories are npm upgrade leftovers. */
99
- function codex_binary(search_path) {
100
- const roots = search_path.split(delimiter).filter(Boolean)
101
- .map(directory => join(directory, 'node_modules', '@openai'));
102
- const queue = roots.filter(existsSync).map(path => [path, 0]);
103
- for (let index = 0; index < queue.length; index++) {
104
- const [directory, depth] = queue[index];
105
- for (const entry of readdirSync(directory, { withFileTypes: true })) {
106
- const path = join(directory, entry.name);
107
- if (entry.isFile() && entry.name === 'codex.exe') return path;
108
- if (entry.isDirectory() && !entry.name.startsWith('.') && depth < 7) queue.push([path, depth + 1]);
109
- }
110
- }
111
- return '';
112
- }
113
-
114
- /** Probe Python, recording sys.executable so aliases and py launcher arguments are unnecessary later. */
115
- export function detect_python(explicit = '') {
116
- const candidates = explicit ? [[explicit]] : [['python3'], ['python'], ['py', '-3']];
117
- for (const [command, ...args] of candidates) {
118
- const result = spawnSync(command, [...args, '-c',
119
- 'import json,sys; print(json.dumps({"path":sys.executable,"version":list(sys.version_info[:3])}))'],
120
- { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT });
121
- if (result.status !== 0) continue;
122
- try {
123
- const found = JSON.parse(result.stdout);
124
- if (found.version[0] === 3 && found.version[1] >= 10 && isAbsolute(found.path)) return found.path;
125
- } catch { /* Try the next installed Python. */ }
126
- }
127
- throw new Error('未找到 Python 3.10+;安装后重试,或用 --python 指定可执行文件。');
128
- }
129
-
130
- /** Probe the fixed --version argument; Cursor's Windows launcher runs through a fixed PowerShell command. */
131
- function probe_cli(executable, allow_cmd) {
132
- const options = { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT };
133
- if (process.platform === 'win32' && /\.cmd$/i.test(executable) && allow_cmd) {
134
- return spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
135
- '& $env:DISCUSS_PROBE_PATH --version; exit $LASTEXITCODE'],
136
- { ...options, env: { ...process.env, DISCUSS_PROBE_PATH: executable } });
137
- }
138
- if (process.platform === 'win32' && !/\.exe$/i.test(executable)) return null;
139
- return spawnSync(executable, ['--version'], options);
140
- }
141
-
142
- /** Detect only the four supported CLI families; no App, login or model invocation checks. */
143
- export function detect_clients(options = {}, search_path = process.env.PATH || '') {
144
- return Object.entries(CLIENTS).map(([key, client]) => {
145
- const allow_cmd = key === 'cursor';
146
- const executable = options[key] ? resolve(options[key])
147
- : client.commands.map(command => path_program(command, search_path, allow_cmd)).find(Boolean)
148
- || (key === 'codex' && process.platform === 'win32' ? codex_binary(search_path) : '');
149
- const probe = executable ? probe_cli(executable, allow_cmd) : null;
150
- if (options[key] && probe?.status !== 0) throw new Error(`${client.name} 路径无法运行:${executable}`);
151
- return { key, ...client, executable: probe?.status === 0 ? executable : '' };
152
- });
153
- }
154
-
155
- /** Select detected clients interactively or through explicit noninteractive options. */
156
- async function selected_clients(options, detected) {
157
- let choice = options.clients;
158
- if (choice === undefined && !options.yes) {
159
- if (!process.stdin.isTTY) throw new Error('非交互终端请使用 --yes 或 --clients;只配置网站可用 --clients none。');
160
- const items = detected.map(item => ({ label: item.name, hint: item.executable ? short_path(item.executable) : '未检测到 CLI',
161
- checked: Boolean(item.executable && item.adapter), disabled: !item.executable }));
162
- const checked = await checkbox_prompt('选择要接入的软件', items);
163
- choice = detected.filter((_, index) => checked[index]).map(item => item.key).join(',') || 'none';
164
- } else if (!styled) for (const item of detected) process.stderr.write(`${item.name}:${item.executable || '未检测到 CLI'}\n`);
165
- return requested_clients(choice, detected);
166
- }
167
-
168
- /**
169
- * The install settings of this run: which shipped workflows to install, and whether to build the 共议 launcher.
170
- * Workflows: nothing by default; an interactive run offers them unchecked, a non-interactive one installs them only with
171
- * --workflows. Launcher: offered checked to an interactive run on Windows until it exists, so only the first setup asks;
172
- * a non-interactive run never builds it (`codiscuss launcher` does). Never remembered between runs.
173
- */
174
- async function install_choices(options, home) {
175
- const shipped = shipped_workflows();
176
- const offer_workflows = options.workflows === undefined && shipped.length;
177
- const offer_launcher = process.platform === 'win32' && !existsSync(launcher_path(home));
178
- const defaults = { workflows: options.workflows ? shipped.map(item => item.name) : [], launcher: false };
179
- // The tree needs key-by-key input; a terminal that cannot give it keeps the default.
180
- if (options.yes || !process.stdin.isTTY || typeof process.stdin.setRawMode !== 'function' || (!offer_workflows && !offer_launcher)) return defaults;
181
- const groups = [];
182
- if (offer_workflows) groups.push({ label: '随包工作流',
183
- description: '把安装包自带的工作流装进本机工作流库;已有同名的覆盖为最新版,原来那份先备份到服务目录 backups/workflows/',
184
- items: shipped.map(item => ({ label: item.label, hint: item.name, description: item.description, checked: false })) });
185
- if (offer_launcher) groups.push({ label: '桌面快捷方式',
186
- description: '在桌面与开始菜单放一个“共议”,双击启动网站与讨论服务;以后也可运行 codiscuss launcher 生成',
187
- items: [{ label: '创建“共议”快捷方式', hint: 'launcher', description: '用本机自带的 C# 编译器生成 共议.exe,不下载任何东西', checked: true }] });
188
- const picked = await tree_prompt('安装配置', groups);
189
- return {
190
- workflows: offer_workflows ? shipped.filter((_, index) => picked[0][index]).map(item => item.name) : defaults.workflows,
191
- launcher: offer_launcher && picked[groups.length - 1][0],
192
- };
193
- }
194
-
195
- /** Validate an explicit selection without prompting or changing files. */
196
- function requested_clients(choice, detected) {
197
- const available = detected.filter(item => item.executable);
198
- const keys = !choice ? available.filter(item => item.adapter).map(item => item.key)
199
- : choice === 'none' ? [] : choice.split(',').map(item => item.trim());
200
- for (const key of keys) {
201
- if (!CLIENTS[key]) throw new Error(`不支持的软件:${key}`);
202
- if (!available.some(item => item.key === key)) throw new Error(`${key} 未检测到,请安装其 CLI 或提供路径。`);
203
- }
204
- return detected.filter(item => keys.includes(item.key));
205
- }
206
-
207
- /** Compare executable destinations, including symlinks and Windows path casing. */
208
- function same_executable(left, right) {
209
- const canonical = path => {
210
- if (!path) return '';
211
- const value = existsSync(path) ? realpathSync(path) : resolve(path);
212
- return process.platform === 'win32' ? value.toLowerCase() : value;
213
- };
214
- return canonical(left) === canonical(right);
215
- }
216
-
217
- /** Resolve an existing profile mismatch without silently switching the user's client. */
218
- async function choose_profile(client, current, options) {
219
- const detected = { adapter: client.adapter, executable: client.executable };
220
- if (!client.adapter) return { client: client.name, status: 'manual' };
221
- const differs = current && (current.adapter !== client.adapter || !same_executable(current.executable, client.executable));
222
- let update = Boolean(options[client.key]), acknowledged = false;
223
- if (differs && !update && !options.yes && process.stdin.isTTY) {
224
- const choice = await ask(`${client.name} 已有配置:${current.adapter || '未设置类型'} / ${current.executable || '未设置路径'}\n检测到 CLI:${client.executable}\n保留已有配置或更新为此 CLI?`, '[保留/更新,默认保留]');
225
- update = ['更新', 'update', 'u'].includes(choice.trim().toLowerCase());
226
- acknowledged = !choice.trim() || ['保留', 'keep', 'k'].includes(choice.trim().toLowerCase());
227
- }
228
- if (differs && !update) return { client: client.name, status: acknowledged ? 'retained' : 'pending',
229
- effective: { adapter: current.adapter, executable: current.executable }, detected,
230
- action: `如需更新,运行 codiscuss setup --clients ${client.key} --${client.key} "${client.executable}";交互 setup 也可确认保留。` };
231
- return { client: client.name, status: 'configured', effective: detected };
232
- }
233
-
234
- /**
235
- * Remove global agy rules that earlier versions added; agy permissions now live only in each discussion project.
236
- * Only rules recorded by the installer are removed, after a backup; other settings and user rules stay untouched.
237
- */
238
- export function remove_legacy_agy_rules(home, user_home) {
239
- const record = join(home, AGY_RULE_RECORD);
240
- if (!existsSync(record)) return null;
241
- const path = join(user_home, ...AGY_SETTINGS);
242
- const saved = JSON.parse(readFileSync(record, 'utf8'));
243
- const legacy = saved.rules || (saved.rule ? [saved.rule] : []);
244
- let settings = {};
245
- try { if (existsSync(path)) settings = JSON.parse(readFileSync(path, 'utf8')); }
246
- catch { return { client: 'Antigravity', status: 'invalid', path }; }
247
- const allow = settings.permissions?.allow ?? [];
248
- if (!Array.isArray(allow)) return { client: 'Antigravity', status: 'invalid', path };
249
- const next = allow.filter(rule => !legacy.includes(rule));
250
- if (next.length !== allow.length) {
251
- copyFileSync(path, join(home, AGY_SETTINGS_BACKUP));
252
- atomic_json(path, { ...settings, permissions: { ...settings.permissions, allow: next } });
253
- }
254
- rmSync(record);
255
- return { client: 'Antigravity', status: next.length !== allow.length ? 'removed' : 'unchanged', path };
256
- }
257
-
258
- /** Follow a linked skill directory so clients sharing one folder install a single copy. */
259
- function real_directory(path) {
260
- try { return realpathSync.native(path); } catch { return resolve(path); }
261
- }
262
-
263
- /** True when an entry's include_only/exclude patterns let agy load every discussion skill; invalid patterns count as filtering. */
264
- function entry_loads_skills(entry) {
265
- const matches = (patterns, name) => patterns.some(pattern => {
266
- try { return new RegExp(`^(?:${pattern})$`).test(name); } catch { return true; }
267
- });
268
- const include = Array.isArray(entry.include_only) ? entry.include_only : null;
269
- const exclude = Array.isArray(entry.exclude) ? entry.exclude : [];
270
- return SKILLS.every(name => (!include || matches(include, name)) && !matches(exclude, name));
271
- }
272
-
273
- /** Absolute directories agy loads the discussion skills from through its global skills.json; agy leaves ~/ unexpanded on Windows. */
274
- function agy_skill_entries(user_home) {
275
- const path = join(user_home, ...AGY_SKILL_CONFIG);
276
- let config;
277
- try { config = JSON.parse(readFileSync(path, 'utf8')); } catch { return []; }
278
- return (Array.isArray(config?.entries) ? config.entries : [])
279
- .filter(entry => typeof entry?.path === 'string' && entry_loads_skills(entry)).map(entry => entry.path)
280
- .map(value => process.platform !== 'win32' && value.startsWith('~/') ? join(user_home, value.slice(2)) : value)
281
- .filter(value => isAbsolute(value)).map(real_directory);
282
- }
283
-
284
- /** Pick the directory each client really reads; agy reuses a skills.json entry instead of its own folder. */
285
- function skill_targets(selected, user_home) {
286
- const own = new Map(selected.map(client => [client.key, real_directory(join(user_home, ...client.skills))]));
287
- const entries = agy_skill_entries(user_home);
288
- return selected.map(client => {
289
- const directory = own.get(client.key);
290
- if (client.key !== 'antigravity' || !entries.length) return { client, directory, own: directory };
291
- const others = selected.filter(item => item.key !== client.key).map(item => own.get(item.key));
292
- return { client, directory: entries.find(entry => others.includes(entry)) || entries[0], own: directory };
293
- });
294
- }
295
-
296
- /** Save the selected effective profiles and copy complete skills without overwriting edits. */
297
- async function configure_clients(home, selected, options, existing) {
298
- const participants = { ...existing };
299
- const skills = [], profiles = [];
300
- const user_home = resolve(options['skills-home'] || homedir());
301
- const record = join(home, SKILL_RECORD), installed = new Map();
302
- for (const { client, directory, own } of skill_targets(selected, user_home)) {
303
- const profile = await choose_profile(client, participants[client.name], options);
304
- profiles.push(profile);
305
- if (profile.status === 'configured') participants[client.name] = { ...participants[client.name], ...profile.effective };
306
- if (!installed.has(directory)) installed.set(directory, install_skills(directory, record));
307
- const retired = [client.legacy_skills && real_directory(join(user_home, ...client.legacy_skills)), own]
308
- .filter(path => path && path !== directory);
309
- skills.push({ client: client.name, results: installed.get(directory), legacy: retired.flatMap(path => remove_legacy_skills(path, record)) });
310
- }
311
- save_launch_settings(home, { participants });
312
- const legacy = remove_legacy_agy_rules(home, user_home);
313
- return { skills, profiles, permissions: legacy ? [legacy] : [] };
314
- }
315
-
316
- /** Exclude npm exec's temporary command wrappers when checking persistent availability. */
317
- function persistent_search_path() {
318
- return (process.env.PATH || '').split(delimiter).filter(path => !path.split(/[\\/]/).includes('_npx')).join(delimiter);
319
- }
320
-
321
- /** Verify the resolved persistent npm command belongs to this installation and can run. */
322
- export function check_command(search_path = persistent_search_path()) {
323
- const executable = path_program('codiscuss', search_path, true);
324
- const cli = join(ROOT, 'runner', 'codiscuss.mjs');
325
- const package_root = resolve(ROOT);
326
- const prefix = basename(dirname(package_root)) === 'node_modules' ? dirname(dirname(package_root)) : '';
327
- const directory = prefix ? (process.platform === 'win32' ? prefix : join(dirname(prefix), 'bin')) : '';
328
- if (!executable) return { status: 'missing', directory,
329
- action: directory ? `将 ${directory} 加入 PATH,重新打开终端后运行 codiscuss setup。`
330
- : '尚未找到持久命令,请先运行 install,再重新打开终端运行 codiscuss setup。' };
331
- const target = process.platform === 'win32' ? join(dirname(executable), 'node_modules', 'ai_co_discuss', 'runner', 'codiscuss.mjs') : executable;
332
- const shim_matches = process.platform !== 'win32' || (/\.cmd$/i.test(executable)
333
- && readFileSync(executable, 'utf8').replaceAll('\\', '/').includes('node_modules/ai_co_discuss/runner/codiscuss.mjs'));
334
- if (!shim_matches || !same_executable(target, cli)) return { status: 'shadowed', path: executable, directory,
335
- action: `PATH 中的 ${executable} 未指向本次安装;${directory ? `将 ${directory} 放在旧入口之前` : '先运行 install 安装本版本'},再运行 setup。` };
336
- const probe = process.platform === 'win32'
337
- ? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '& $env:DISCUSS_COMMAND_PATH --help; exit $LASTEXITCODE'],
338
- { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT, env: { ...process.env, PATH: search_path, DISCUSS_COMMAND_PATH: executable } })
339
- : spawnSync(executable, ['--help'], { encoding: 'utf8', timeout: PROBE_TIMEOUT, env: { ...process.env, PATH: search_path } });
340
- return probe.status === 0 ? { status: 'ready', path: executable }
341
- : { status: 'failed', path: executable, action: `命令无法运行:${executable};请在终端运行此入口的 --help 检查 Node 和执行权限,再运行 setup。` };
342
- }
343
-
344
- /** Collect only unresolved setup work, keeping actual AI execution a separate validation. */
345
- function setup_issues(result) {
346
- const issues = result.profiles.filter(profile => profile.status === 'pending')
347
- .map(profile => `${profile.client} 保留了与检测结果不同的配置。${profile.action}`);
348
- for (const group of result.skills) for (const skill of group.results) {
349
- if (skill.status === 'conflict') issues.push(`${group.client} 技能冲突,已保留 ${skill.path};请核对并移走需替换的旧副本,再运行 setup。`);
350
- }
351
- for (const group of result.skills) for (const skill of group.legacy) {
352
- if (skill.status === 'kept') issues.push(`${group.client} 旧技能目录中的副本有改动,已保留 ${skill.path};软件会同时加载新旧两份,请核对后删除。`);
353
- }
354
- for (const permission of result.permissions) {
355
- if (permission.status === 'invalid') issues.push(`${permission.client} 设置文件无法解析,未能移除旧版全局放行规则:${permission.path};修复后重新运行 setup,否则全自动讨论会拒绝交付给 agy。`);
356
- }
357
- if (result.command.status !== 'ready') issues.push(result.command.action);
358
- return issues;
359
- }
360
-
361
- /** Ask before restarting a running website; non-interactive runs never stop it and report the pending restart instead. */
362
- async function confirm_restart(reason, options) {
363
- if (options.yes || !process.stdin.isTTY) return false;
364
- const choice = await ask(`${reason}\n重启后生效。重启会暂停进行中的讨论;进行中的执行会中断,随后在原会话里自动续跑。现在重启?`, '[Y/N,默认 Y]');
365
- return !choice.trim() || ['重启', 'restart', 'r', 'y', 'yes'].includes(choice.trim().toLowerCase());
366
- }
367
-
368
- /** Configure Python, selected clients and skills, returning partial results on startup failure. */
369
- async function setup(options) {
370
- intro('配置 AI CoDiscuss', PACKAGE.version, PACKAGE.description);
371
- const { home, previous, python, port } = setup_environment(options);
372
- if (styled && !process.env.CODISCUSS_TUI_NESTED) step('运行环境就绪', [environment_line(python, port)]);
373
- const scan = spinner('检测已安装的 AI 软件');
374
- const detected = detect_clients(options);
375
- const width = Math.max(...detected.map(item => text_width(item.name)));
376
- const listed = options.clients !== undefined || options.yes
377
- ? detected.map(item => `${pad(item.name, width)} ${tone.dim(item.executable ? short_path(item.executable) : '未检测到 CLI')}`) : [];
378
- scan.done(`检测到 ${detected.filter(item => item.executable).length} 个可接入的 CLI`, listed);
379
- const selected = await selected_clients(options, detected);
380
- const choices = await install_choices(options, home);
381
- const workflow_names = choices.workflows;
382
- const configured = await configure_clients(home, selected, options, launch_settings(home).participants);
383
- // The remote entry is retired: a saved remote_port from an older version is dropped here.
384
- const { remote_port: retired, ...kept } = previous;
385
- atomic_json(join(home, 'local-settings.json'), { ...kept, python, port });
386
- step('已写入软件配置与技能', configured.skills.map(group => `${pad(group.client, width)} ${tone.dim(short_path(dirname(group.results[0].path)))}`));
387
- // Shipped workflows are installed only when asked for each time, so a copy the user or a host edited is never replaced unasked.
388
- const workflows = workflow_names.length ? install_workflows(home, workflow_names) : [];
389
- // Model API members run in Pi, which codiscuss installs itself, at the release this version pins.
390
- let pi = null, pi_error = '';
391
- // A given Pi (CODISCUSS_PI_CLI, as in tests) is used as it is.
392
- if (!process.env.CODISCUSS_PI_CLI) {
393
- const pi_step = spinner('安装 Pi(模型 API 成员的运行框架)');
394
- try {
395
- pi = await (await import('./pi_runtime.mjs')).install_pi(home);
396
- pi_step.done(`Pi ${pi.version}${pi.updated ? ' 已安装' : ' 已就绪'}`);
397
- } catch (error) { pi_error = error.message; pi_step.fail(`Pi 安装失败:${error.message}`); }
398
- }
399
- let launcher = null, launcher_error = '';
400
- if (choices.launcher) {
401
- try { launcher = install_launcher(home); } catch (error) { launcher_error = error.message; }
402
- }
403
- const result = { home, python, clients: selected.map(item => item.name), ...configured, workflows,
404
- command: check_command(), ai_verified: false, ...(pi ? { pi: pi.version } : {}), ...(launcher ? { launcher: launcher.shortcuts[0] } : {}) };
405
- result.issues = setup_issues(result);
406
- if (pi_error) result.issues.push(`Pi 安装失败(${pi_error});模型 API 成员首次执行时会再试,或检查网络与 npm 后重新运行 setup。`);
407
- if (launcher_error) result.issues.push(`未能创建“共议”快捷方式(${launcher_error});可稍后运行 codiscuss launcher 重试。`);
408
- result.configured = result.issues.length === 0;
409
- result.status = result.configured ? 'configured' : 'needs_attention';
410
- if (!options['no-start']) {
411
- const { local_main, restart_reason } = await import('./discussion_local.mjs');
412
- const reason = restart_reason(home);
413
- if (reason && !await confirm_restart(reason, options)) {
414
- result.issues.push(`${reason};重启后才生效。重启会暂停进行中的讨论,进行中的执行会中断并在原会话里自动续跑。确认后运行 codiscuss local stop,再运行 codiscuss local open。`);
415
- result.configured = false;
416
- result.status = 'needs_attention';
417
- return result;
418
- }
419
- const launch = spinner(reason ? '重启本机网站与讨论服务' : '启动本机网站与讨论服务');
420
- try {
421
- if (reason) await local_main(['stop'], () => {});
422
- result.local = await local_main([options['no-open'] ? 'start' : 'open'], () => {});
423
- launch.done('网站与讨论服务已在后台运行', [`${tone.cyan(result.local.url)}${options['no-open'] ? tone.dim(' 未打开浏览器,可直接访问此地址') : tone.dim(' 已在浏览器打开')}`]);
424
- if (result.configured) result.status = 'ready';
425
- } catch (error) {
426
- launch.fail(error.message);
427
- result.status = 'start_failed';
428
- result.issues.push(`本机启动失败:${error.message};配置已保存,修复后重新运行 setup。`);
429
- }
430
- }
431
- return result;
432
- }
433
-
434
- const WORKFLOW_STATUS = { installed: '已安装', updated: '已覆盖为最新版,原来的备份在', unchanged: '已是最新' };
435
-
436
- /** One line naming each shipped workflow and what setup did with it. */
437
- function workflow_summary(workflows) {
438
- return workflows.map(item => `${item.name} ${WORKFLOW_STATUS[item.status]}${item.backup ? `:${item.backup}` : ''}`).join(' · ');
439
- }
440
-
441
- /** Print a concise human receipt while keeping stdout machine-readable. */
442
- function report_setup(result, options = {}) {
443
- if (styled) return report_styled(result, options);
444
- const labels = { ready: '安装配置完成,网站与讨论服务已就绪', configured: '配置完成,本次未启动网站',
445
- needs_attention: '配置待处理', start_failed: '本机启动失败' };
446
- const lines = [labels[result.status]];
447
- for (const profile of result.profiles) lines.push(profile.status === 'manual'
448
- ? `${profile.client}:仅安装技能,可手动参与,尚不支持全自动接入。`
449
- : `${profile.client}:${profile.status === 'configured' ? 'CLI 已配置' : '沿用已有配置'}(${profile.effective.adapter} / ${profile.effective.executable || '未设置路径'})`);
450
- for (const permission of result.permissions) {
451
- if (permission.status === 'removed') lines.push(`${permission.client}:已移除旧版全局放行规则(${permission.path})`);
452
- }
453
- for (const group of result.skills) lines.push(`${group.client} Skill:${group.results.filter(skill => skill.status !== 'conflict').length}/${group.results.length} 份文件就绪,目录 ${dirname(group.results[0].path)}`);
454
- if (result.workflows.length) lines.push(`内置工作流:${workflow_summary(result.workflows)}`);
455
- if (result.launcher) lines.push(`快捷方式:${result.launcher}(双击启动共议)`);
456
- if (result.command.path) lines.push(`持久命令:${result.command.path}(${result.command.status})`);
457
- if (result.local?.running) {
458
- lines.push(`本机网站:${result.local.url}${options['no-open'] ? '' : '(已在浏览器打开)'}`,
459
- '网站与讨论服务在后台运行,关闭此终端不影响;查看状态 codiscuss local status,停止 codiscuss local stop;电脑重启后运行 codiscuss local open 重新启动并打开浏览器(codiscuss local start 不打开浏览器);codiscuss service restart 重启讨论服务(使新环境变量生效)'
460
- + (process.platform === 'win32' ? ';codiscuss service autostart on 登录时自动启动。' : '。'));
461
- }
462
- lines.push(...result.issues, '真实 AI 执行尚未验证;可从网页创建讨论,或在新会话调用 Skill。');
463
- if (result.skills.length) lines.push('若新会话未发现技能,请让 AI 读取上述目录内的 discuss-host/SKILL.md 和 discuss-participant/SKILL.md。');
464
- process.stderr.write(`${lines.join('\n')}\n`);
465
- }
466
-
467
- /** Close the styled installer with aligned results, open issues and the commands to manage the site. */
468
- function report_styled(result, options) {
469
- const titles = { ready: ['安装完成', tone.green('◆')], configured: ['配置完成,本次未启动网站', tone.green('◆')],
470
- needs_attention: ['配置完成,仍有待处理项', tone.yellow('▲')], start_failed: ['本机启动失败', tone.red('■')] };
471
- const [title, mark] = titles[result.status];
472
- const rows = [];
473
- if (result.local?.running) rows.push(['网站', tone.cyan(result.local.url), options['no-open'] ? '' : '已在浏览器打开']);
474
- for (const profile of result.profiles) rows.push(profile.status === 'manual' ? [profile.client, '仅安装技能,可手动参与', '尚不支持全自动接入']
475
- : [profile.client, `${profile.status === 'configured' ? 'CLI 已配置' : '沿用已有配置'} · ${profile.effective.adapter}`, short_path(profile.effective.executable) || '未设置路径']);
476
- for (const permission of result.permissions) {
477
- if (permission.status === 'removed') rows.push([permission.client, '已移除旧版全局放行规则', short_path(permission.path)]);
478
- }
479
- if (result.skills.length) rows.push(['技能', result.skills.map(group => `${group.client} ${group.results.filter(skill => skill.status !== 'conflict').length}/${group.results.length}`).join(' · '), 'discuss-host · discuss-participant · discuss-goal · discuss-session · discuss-report · workflow-creator · local-tts-setup · local-stt-setup']);
480
- if (result.workflows.length) rows.push(['工作流', workflow_summary(result.workflows), '']);
481
- if (result.launcher) rows.push(['快捷方式', '双击“共议”启动', short_path(result.launcher)]);
482
- if (result.command.path) rows.push(['命令', `codiscuss ${tone.dim(`(${result.command.status})`)}`, short_path(result.command.path)]);
483
- const notes = result.issues.map(issue => tone.yellow(`▲ ${issue}`));
484
- if (result.local?.running) {
485
- const commands = [['codiscuss local status', '查看状态'], ['codiscuss local stop', '停止'], ['codiscuss local open', '启动并打开浏览器(重启电脑后用)'],
486
- ['codiscuss local start', '启动但不打开浏览器'],
487
- ['codiscuss service restart', '重启讨论服务(使新环境变量生效)']];
488
- if (process.platform === 'win32') commands.push(['codiscuss service autostart on', '登录时自动启动']);
489
- const width = Math.max(...commands.map(([command]) => command.length)) + 2;
490
- notes.push(tone.dim('网站与讨论服务在后台运行,关闭此终端不影响'),
491
- ...commands.map(([command, label]) => `${tone.cyan(command.padEnd(width))}${tone.dim(label)}`));
492
- }
493
- const closing = result.local?.running ? `在网页新建讨论,或在 AI 会话里调用 ${tone.cyan('discuss-host')} ${tone.dim('· 真实 AI 执行尚未验证')}`
494
- : `运行 ${tone.cyan('codiscuss local open')} 启动网站`;
495
- outro(title, rows, notes, closing, mark);
496
- }
497
-
498
- /** Locate npm's JavaScript entrypoint so paths with spaces never need shell quoting. */
499
- function npm_entry() {
500
- const candidates = [process.env.npm_execpath, join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
501
- join(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js')];
502
- const executable = path_program('npm');
503
- if (executable) candidates.push(realpathSync(executable));
504
- const entry = candidates.find(path => path && /\.(?:c?js|mjs)$/.test(path) && existsSync(path));
505
- if (!entry) throw new Error('未找到 npm;请安装带 npm 的 Node.js 24+ 后重试。');
506
- return entry;
507
- }
508
-
509
- /** Execute npm without lifecycle scripts asynchronously, so a progress spinner can animate. */
510
- function npm_run(entry, args) {
511
- return new Promise((done, fail) => {
512
- const child = spawn(process.execPath, [entry, ...args], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
513
- let stdout = '', stderr = '';
514
- child.stdout.on('data', data => { stdout += data; });
515
- child.stderr.on('data', data => { stderr += data; });
516
- child.on('error', fail);
517
- child.on('close', code => (code === 0 ? done(stdout.trim()) : fail(new Error(stderr || 'npm 执行失败'))));
518
- });
519
- }
520
-
521
- /** Install a real package copy, never a symlink into a disposable npx cache. */
522
- async function install(args, options) {
523
- intro('安装 AI CoDiscuss', PACKAGE.version, PACKAGE.description);
524
- const { python, port } = setup_environment(options);
525
- requested_clients(options.clients, detect_clients(options));
526
- if (styled) step('运行环境就绪', [environment_line(python, port)]);
527
- const entry = npm_entry();
528
- const temporary = mkdtempSync(join(tmpdir(), 'codiscuss-install-'));
529
- const prefix = options.prefix ? ['--prefix', resolve(options.prefix)] : [];
530
- const progress = spinner('安装 codiscuss 命令');
531
- try {
532
- const packed = JSON.parse(await npm_run(entry, ['pack', ROOT, '--ignore-scripts', '--json', '--pack-destination', temporary]));
533
- await npm_run(entry, ['install', '--global', ...prefix, '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund', join(temporary, packed[0].filename)]);
534
- // npm masks UUID-like path segments as *** in its output, so an explicit prefix is resolved locally.
535
- const install_prefix = options.prefix ? resolve(options.prefix) : await npm_run(entry, ['prefix', '--global']);
536
- const global_root = process.platform === 'win32' ? join(install_prefix, 'node_modules') : join(install_prefix, 'lib', 'node_modules');
537
- const installed = join(global_root, 'ai_co_discuss', 'runner', 'codiscuss.mjs');
538
- const directory = process.platform === 'win32' ? install_prefix : join(install_prefix, 'bin');
539
- progress.done('已安装 codiscuss 命令', [tone.dim(short_path(directory))]);
540
- if (!styled) process.stderr.write(`命令目录:${directory}\n`);
541
- const result = spawnSync(process.execPath, [installed, 'setup', ...args], { stdio: 'inherit', windowsHide: true,
542
- env: { ...process.env, PATH: persistent_search_path(), CODISCUSS_TUI_NESTED: '1' } });
543
- process.exitCode = result.status ?? 1;
544
- if (result.error) throw result.error;
545
- } catch (error) { progress.fail(error.message); throw error; }
546
- finally { rmSync(temporary, { recursive: true, force: true }); }
547
- }
548
-
549
- /** Dispatch bootstrap or setup, leaving website and launch commands untouched. */
550
- export async function setup_main(command, args) {
551
- const { values } = parseArgs({ args, options: OPTIONS });
552
- if (values.help) return process.stdout.write(HELP);
553
- if (command === 'install') return install(args, values);
554
- const result = await setup(values);
555
- report_setup(result, values);
556
- if (values.json || !process.stdout.isTTY) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
557
- process.exitCode = result.status === 'start_failed' ? 1 : result.status === 'needs_attention' ? ATTENTION_EXIT_CODE : 0;
558
- return result;
559
- }
1
+ /** npm bootstrap and per-user setup; never logs in or starts an AI conversation. */
2
+ import { spawn, spawnSync } from 'node:child_process';
3
+ import { accessSync, constants, copyFileSync, existsSync, mkdtempSync, readFileSync, readdirSync, realpathSync, rmSync, statSync } from 'node:fs';
4
+ import { homedir, tmpdir } from 'node:os';
5
+ import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { parseArgs } from 'node:util';
8
+
9
+ import { atomic_json } from './files.mjs';
10
+ import { launch_settings, save_launch_settings } from './discussion_launch.mjs';
11
+ import { assert_shared_home, service_home } from './discussion_service.mjs';
12
+ import { SKILLS, install_skills, install_workflows, remove_legacy_skills, shipped_workflows } from './discussion_skills.mjs';
13
+ import { ask, checkbox_prompt, intro, outro, pad, short_path, spinner, step, styled, text_width, tone, tree_prompt } from './discussion_tui.mjs';
14
+ import { install_launcher, launcher_installed } from './launcher.mjs';
15
+ export { checkbox_prompt } from './discussion_tui.mjs';
16
+
17
+ const ROOT = fileURLToPath(new URL('../', import.meta.url));
18
+ const PACKAGE = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
19
+ const PROBE_TIMEOUT = 10000;
20
+ const MIN_NODE_MAJOR = 24;
21
+ const DEFAULT_PORT = 8765;
22
+ const ATTENTION_EXIT_CODE = 2;
23
+ const AGY_SETTINGS = ['.gemini', 'antigravity-cli', 'settings.json'];
24
+ const AGY_RULE_RECORD = 'agy-permission.json';
25
+ const AGY_SETTINGS_BACKUP = 'agy-settings.backup.json';
26
+ const SKILL_RECORD = 'skills-manifest.json';
27
+ const AGY_SKILL_CONFIG = ['.gemini', 'config', 'skills.json'];
28
+ const CLIENTS = {
29
+ codex: { name: 'Codex', commands: ['codex'], adapter: 'codex_cli', skills: ['.agents', 'skills'] },
30
+ claude: { name: 'Claude', commands: ['claude'], adapter: 'claude', skills: ['.claude', 'skills'] },
31
+ antigravity: { name: 'Antigravity', commands: ['agy'], adapter: 'antigravity_cli', skills: ['.gemini', 'config', 'skills'],
32
+ legacy_skills: ['.gemini', 'antigravity-cli', 'skills'] },
33
+ cursor: { name: 'Grok(Cursor CLI)', commands: ['agent', 'cursor-agent'], skills: ['.cursor', 'skills'] },
34
+ };
35
+ const OPTIONS = { yes: { type: 'boolean' }, clients: { type: 'string' }, python: { type: 'string' },
36
+ codex: { type: 'string' }, claude: { type: 'string' }, antigravity: { type: 'string' }, cursor: { type: 'string' },
37
+ port: { type: 'string' }, prefix: { type: 'string' }, 'skills-home': { type: 'string' },
38
+ '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' } };
39
+ const HELP = `用法:codiscuss install [选项] / codiscuss setup [选项]
40
+ install 将当前 npm 包安装为持久命令,再运行 setup;setup 配置已有安装。
41
+ --yes 使用已检测且支持自动接入的软件,冲突保留并报告
42
+ --clients codex,claude,antigravity,cursor 选择 CLI;none 只配置网站
43
+ --python PATH 指定 Python 3.10+ 原生可执行文件
44
+ --codex/--claude/--antigravity/--cursor PATH 指定 CLI(Windows 为 .exe,Cursor 也支持 .cmd)
45
+ --port PORT 本机网站端口,默认 8765
46
+ --no-start / --no-open 只配置 / 启动但不打开浏览器
47
+ --prefix DIR npm 安装前缀(install)
48
+ --skills-home DIR 技能用户根目录(默认当前用户目录)
49
+ --hosting / --no-hosting 打开 / 关闭托管管理(Windows 任务栏图标里的管理面板),选择会记住
50
+ --workflows 安装全部随包工作流,已有同名的覆盖为最新版(原来的先备份到服务目录 backups/);
51
+ 交互运行时也可在“安装配置”里逐个勾选;不选则不安装,选择不会记住
52
+ Antigravity(显示名 Gemini)使用 agy;Grok 使用 Cursor CLI(agent / cursor-agent)。仅检测 CLI。
53
+ Cursor 当前只安装技能,可手动参与;全自动接入尚未提供。已有软件设置保留。
54
+ 显式软件路径可更新已支持的 CLI 配置。安装不会开始讨论。
55
+ 中文摘要写入 stderr;输出被重定向或加 --json 时结果 JSON 写入 stdout;退出码 0=完成,2=配置待处理,1=失败。
56
+ `;
57
+
58
+ /** Read local settings stored outside the npm installation. */
59
+ export function local_settings(home = service_home()) {
60
+ const path = join(home, 'local-settings.json');
61
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
62
+ }
63
+
64
+ /** Validate prerequisites before installing a package or changing configuration. */
65
+ function setup_environment(options) {
66
+ if (Number(process.versions.node.split('.')[0]) < MIN_NODE_MAJOR) throw new Error('需要 Node.js 24+,请升级后重试。');
67
+ const home = service_home();
68
+ assert_shared_home(home);
69
+ const previous = local_settings(home);
70
+ const python = detect_python(options.python || previous.python);
71
+ const port = Number(options.port || previous.port || DEFAULT_PORT);
72
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('端口必须为 1–65535 的整数');
73
+ return { home, previous, python, port };
74
+ }
75
+
76
+ /** Summarise the checked runtime in one short line for the styled installer. */
77
+ function environment_line(python, port) {
78
+ const probe = spawnSync(python, ['-c', 'import sys; print(".".join(map(str, sys.version_info[:3])))'],
79
+ { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT });
80
+ return `Node ${process.version.slice(1)} · Python ${probe.stdout?.trim() || short_path(python)} · 端口 ${port}`;
81
+ }
82
+
83
+ /** Find executable PATH entries, explicitly allowing Cursor's Windows .cmd launcher. */
84
+ function path_program(name, search_path = process.env.PATH || '', allow_cmd = false) {
85
+ const suffixes = process.platform === 'win32' ? (allow_cmd ? ['.exe', '.cmd'] : ['.exe']) : [''];
86
+ for (const directory of search_path.split(delimiter).filter(Boolean)) {
87
+ for (const suffix of suffixes) {
88
+ const path = join(directory.replace(/^"|"$/g, ''), `${name}${suffix}`);
89
+ try {
90
+ if (!statSync(path).isFile()) continue;
91
+ accessSync(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK);
92
+ return path;
93
+ } catch { /* Continue through PATH when an entry is absent or not executable. */ }
94
+ }
95
+ }
96
+ return '';
97
+ }
98
+
99
+ /** Locate npm Codex's native binary inside its package when only its shim is on PATH; dot directories are npm upgrade leftovers. */
100
+ function codex_binary(search_path) {
101
+ const roots = search_path.split(delimiter).filter(Boolean)
102
+ .map(directory => join(directory, 'node_modules', '@openai'));
103
+ const queue = roots.filter(existsSync).map(path => [path, 0]);
104
+ for (let index = 0; index < queue.length; index++) {
105
+ const [directory, depth] = queue[index];
106
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
107
+ const path = join(directory, entry.name);
108
+ if (entry.isFile() && entry.name === 'codex.exe') return path;
109
+ if (entry.isDirectory() && !entry.name.startsWith('.') && depth < 7) queue.push([path, depth + 1]);
110
+ }
111
+ }
112
+ return '';
113
+ }
114
+
115
+ /** Probe Python, recording sys.executable so aliases and py launcher arguments are unnecessary later. */
116
+ export function detect_python(explicit = '') {
117
+ const candidates = explicit ? [[explicit]] : [['python3'], ['python'], ['py', '-3']];
118
+ for (const [command, ...args] of candidates) {
119
+ const result = spawnSync(command, [...args, '-c',
120
+ 'import json,sys; print(json.dumps({"path":sys.executable,"version":list(sys.version_info[:3])}))'],
121
+ { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT });
122
+ if (result.status !== 0) continue;
123
+ try {
124
+ const found = JSON.parse(result.stdout);
125
+ if (found.version[0] === 3 && found.version[1] >= 10 && isAbsolute(found.path)) return found.path;
126
+ } catch { /* Try the next installed Python. */ }
127
+ }
128
+ throw new Error('未找到 Python 3.10+;安装后重试,或用 --python 指定可执行文件。');
129
+ }
130
+
131
+ /** Probe the fixed --version argument; Cursor's Windows launcher runs through a fixed PowerShell command. */
132
+ function probe_cli(executable, allow_cmd) {
133
+ const options = { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT };
134
+ if (process.platform === 'win32' && /\.cmd$/i.test(executable) && allow_cmd) {
135
+ return spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
136
+ '& $env:DISCUSS_PROBE_PATH --version; exit $LASTEXITCODE'],
137
+ { ...options, env: { ...process.env, DISCUSS_PROBE_PATH: executable } });
138
+ }
139
+ if (process.platform === 'win32' && !/\.exe$/i.test(executable)) return null;
140
+ return spawnSync(executable, ['--version'], options);
141
+ }
142
+
143
+ /** Detect only the four supported CLI families; no App, login or model invocation checks. */
144
+ export function detect_clients(options = {}, search_path = process.env.PATH || '') {
145
+ return Object.entries(CLIENTS).map(([key, client]) => {
146
+ const allow_cmd = key === 'cursor';
147
+ const executable = options[key] ? resolve(options[key])
148
+ : client.commands.map(command => path_program(command, search_path, allow_cmd)).find(Boolean)
149
+ || (key === 'codex' && process.platform === 'win32' ? codex_binary(search_path) : '');
150
+ const probe = executable ? probe_cli(executable, allow_cmd) : null;
151
+ if (options[key] && probe?.status !== 0) throw new Error(`${client.name} 路径无法运行:${executable}`);
152
+ return { key, ...client, executable: probe?.status === 0 ? executable : '' };
153
+ });
154
+ }
155
+
156
+ /** Select detected clients interactively or through explicit noninteractive options. */
157
+ async function selected_clients(options, detected) {
158
+ let choice = options.clients;
159
+ if (choice === undefined && !options.yes) {
160
+ if (!process.stdin.isTTY) throw new Error('非交互终端请使用 --yes 或 --clients;只配置网站可用 --clients none。');
161
+ const items = detected.map(item => ({ label: item.name, hint: item.executable ? short_path(item.executable) : '未检测到 CLI',
162
+ checked: Boolean(item.executable && item.adapter), disabled: !item.executable }));
163
+ const checked = await checkbox_prompt('选择要接入的软件', items);
164
+ choice = detected.filter((_, index) => checked[index]).map(item => item.key).join(',') || 'none';
165
+ } else if (!styled) for (const item of detected) process.stderr.write(`${item.name}:${item.executable || '未检测到 CLI'}\n`);
166
+ return requested_clients(choice, detected);
167
+ }
168
+
169
+ /**
170
+ * The install settings of this run: which shipped workflows to install, whether to build the 共议 launcher, and whether
171
+ * hosting (the management panel) is on.
172
+ * Workflows: nothing by default; an interactive run offers them unchecked, a non-interactive one installs them only with
173
+ * --workflows. Never remembered.
174
+ * Launcher: always offered to an interactive run on Windows, checked while the exe or its desktop shortcut is missing and
175
+ * unchecked (to rebuild) once both exist; a non-interactive run never builds it (`codiscuss launcher` does).
176
+ * Hosting: offered on Windows, checked as last saved (off at first); --hosting / --no-hosting set it without asking.
177
+ * Remembered in local-settings.json, as it stays on rather than being a one-off action.
178
+ */
179
+ async function install_choices(options, home, previous) {
180
+ const shipped = shipped_workflows();
181
+ const windows = process.platform === 'win32';
182
+ const hosting_flag = options.hosting ? true : options['no-hosting'] ? false : undefined;
183
+ const offer_workflows = options.workflows === undefined && shipped.length;
184
+ const offer_hosting = windows && hosting_flag === undefined;
185
+ const defaults = { workflows: options.workflows ? shipped.map(item => item.name) : [], launcher: false,
186
+ hosting: windows && (hosting_flag ?? previous.hosting === true) };
187
+ // The tree needs key-by-key input; a terminal that cannot give it keeps the default.
188
+ if (options.yes || !process.stdin.isTTY || typeof process.stdin.setRawMode !== 'function' || (!offer_workflows && !windows)) return defaults;
189
+ const installed = windows && launcher_installed(home);
190
+ const groups = [];
191
+ if (offer_workflows) groups.push({ key: 'workflows', label: '随包工作流',
192
+ description: '把安装包自带的工作流装进本机工作流库;已有同名的覆盖为最新版,原来那份先备份到服务目录 backups/workflows/',
193
+ items: shipped.map(item => ({ label: item.label, hint: item.name, description: item.description, checked: false })) });
194
+ if (windows) groups.push({ key: 'launcher', label: '桌面快捷方式',
195
+ description: '在桌面与开始菜单放一个“共议”,双击启动网站与讨论服务;以后也可运行 codiscuss launcher 生成',
196
+ items: [installed
197
+ ? { label: '重新生成“共议”快捷方式', hint: 'launcher', description: '已经有了;Node 或共议的安装位置变了、双击打不开时再勾选', checked: false }
198
+ : { label: '创建“共议”快捷方式', hint: 'launcher', description: '用本机自带的 C# 编译器生成 共议.exe,不下载任何东西', checked: true }] });
199
+ if (offer_hosting) groups.push({ key: 'hosting', label: '托管管理',
200
+ description: '给别人开账号用这台电脑上的 AI 时才需要;一般自用不用勾。勾选会记住,下次 setup 可取消',
201
+ items: [{ label: '托管管理(管理面板)', hint: 'hosting', description: '任务栏图标多出“打开管理面板”,左键打开面板:管理托管账号、Windows 用户、命令行登录与 API 密钥',
202
+ checked: defaults.hosting }] });
203
+ const picked = await tree_prompt('安装配置', groups);
204
+ const chosen = key => picked[groups.findIndex(group => group.key === key)];
205
+ return {
206
+ workflows: offer_workflows ? shipped.filter((_, index) => chosen('workflows')[index]).map(item => item.name) : defaults.workflows,
207
+ launcher: windows && chosen('launcher')[0],
208
+ hosting: offer_hosting ? chosen('hosting')[0] : defaults.hosting,
209
+ };
210
+ }
211
+
212
+ /** Restart the owner's taskbar icon if it is running (`panel stop` then `panel start`). */
213
+ function restart_panel_icon(home) {
214
+ const state = join(home, 'admin-panel.json');
215
+ if (process.platform !== 'win32' || !existsSync(state)) return;
216
+ const script = join(dirname(fileURLToPath(import.meta.url)), 'admin_panel.mjs');
217
+ for (const command of ['stop', 'start']) spawnSync(process.execPath, [script, command, '--data', home], { stdio: 'ignore', windowsHide: true, timeout: 20_000 });
218
+ }
219
+
220
+ /** Validate an explicit selection without prompting or changing files. */
221
+ function requested_clients(choice, detected) {
222
+ const available = detected.filter(item => item.executable);
223
+ const keys = !choice ? available.filter(item => item.adapter).map(item => item.key)
224
+ : choice === 'none' ? [] : choice.split(',').map(item => item.trim());
225
+ for (const key of keys) {
226
+ if (!CLIENTS[key]) throw new Error(`不支持的软件:${key}`);
227
+ if (!available.some(item => item.key === key)) throw new Error(`${key} 未检测到,请安装其 CLI 或提供路径。`);
228
+ }
229
+ return detected.filter(item => keys.includes(item.key));
230
+ }
231
+
232
+ /** Compare executable destinations, including symlinks and Windows path casing. */
233
+ function same_executable(left, right) {
234
+ const canonical = path => {
235
+ if (!path) return '';
236
+ const value = existsSync(path) ? realpathSync(path) : resolve(path);
237
+ return process.platform === 'win32' ? value.toLowerCase() : value;
238
+ };
239
+ return canonical(left) === canonical(right);
240
+ }
241
+
242
+ /** Resolve an existing profile mismatch without silently switching the user's client. */
243
+ async function choose_profile(client, current, options) {
244
+ const detected = { adapter: client.adapter, executable: client.executable };
245
+ if (!client.adapter) return { client: client.name, status: 'manual' };
246
+ const differs = current && (current.adapter !== client.adapter || !same_executable(current.executable, client.executable));
247
+ let update = Boolean(options[client.key]), acknowledged = false;
248
+ if (differs && !update && !options.yes && process.stdin.isTTY) {
249
+ const choice = await ask(`${client.name} 已有配置:${current.adapter || '未设置类型'} / ${current.executable || '未设置路径'}\n检测到 CLI:${client.executable}\n保留已有配置或更新为此 CLI?`, '[保留/更新,默认保留]');
250
+ update = ['更新', 'update', 'u'].includes(choice.trim().toLowerCase());
251
+ acknowledged = !choice.trim() || ['保留', 'keep', 'k'].includes(choice.trim().toLowerCase());
252
+ }
253
+ if (differs && !update) return { client: client.name, status: acknowledged ? 'retained' : 'pending',
254
+ effective: { adapter: current.adapter, executable: current.executable }, detected,
255
+ action: `如需更新,运行 codiscuss setup --clients ${client.key} --${client.key} "${client.executable}";交互 setup 也可确认保留。` };
256
+ return { client: client.name, status: 'configured', effective: detected };
257
+ }
258
+
259
+ /**
260
+ * Remove global agy rules that earlier versions added; agy permissions now live only in each discussion project.
261
+ * Only rules recorded by the installer are removed, after a backup; other settings and user rules stay untouched.
262
+ */
263
+ export function remove_legacy_agy_rules(home, user_home) {
264
+ const record = join(home, AGY_RULE_RECORD);
265
+ if (!existsSync(record)) return null;
266
+ const path = join(user_home, ...AGY_SETTINGS);
267
+ const saved = JSON.parse(readFileSync(record, 'utf8'));
268
+ const legacy = saved.rules || (saved.rule ? [saved.rule] : []);
269
+ let settings = {};
270
+ try { if (existsSync(path)) settings = JSON.parse(readFileSync(path, 'utf8')); }
271
+ catch { return { client: 'Antigravity', status: 'invalid', path }; }
272
+ const allow = settings.permissions?.allow ?? [];
273
+ if (!Array.isArray(allow)) return { client: 'Antigravity', status: 'invalid', path };
274
+ const next = allow.filter(rule => !legacy.includes(rule));
275
+ if (next.length !== allow.length) {
276
+ copyFileSync(path, join(home, AGY_SETTINGS_BACKUP));
277
+ atomic_json(path, { ...settings, permissions: { ...settings.permissions, allow: next } });
278
+ }
279
+ rmSync(record);
280
+ return { client: 'Antigravity', status: next.length !== allow.length ? 'removed' : 'unchanged', path };
281
+ }
282
+
283
+ /** Follow a linked skill directory so clients sharing one folder install a single copy. */
284
+ function real_directory(path) {
285
+ try { return realpathSync.native(path); } catch { return resolve(path); }
286
+ }
287
+
288
+ /** True when an entry's include_only/exclude patterns let agy load every discussion skill; invalid patterns count as filtering. */
289
+ function entry_loads_skills(entry) {
290
+ const matches = (patterns, name) => patterns.some(pattern => {
291
+ try { return new RegExp(`^(?:${pattern})$`).test(name); } catch { return true; }
292
+ });
293
+ const include = Array.isArray(entry.include_only) ? entry.include_only : null;
294
+ const exclude = Array.isArray(entry.exclude) ? entry.exclude : [];
295
+ return SKILLS.every(name => (!include || matches(include, name)) && !matches(exclude, name));
296
+ }
297
+
298
+ /** Absolute directories agy loads the discussion skills from through its global skills.json; agy leaves ~/ unexpanded on Windows. */
299
+ function agy_skill_entries(user_home) {
300
+ const path = join(user_home, ...AGY_SKILL_CONFIG);
301
+ let config;
302
+ try { config = JSON.parse(readFileSync(path, 'utf8')); } catch { return []; }
303
+ return (Array.isArray(config?.entries) ? config.entries : [])
304
+ .filter(entry => typeof entry?.path === 'string' && entry_loads_skills(entry)).map(entry => entry.path)
305
+ .map(value => process.platform !== 'win32' && value.startsWith('~/') ? join(user_home, value.slice(2)) : value)
306
+ .filter(value => isAbsolute(value)).map(real_directory);
307
+ }
308
+
309
+ /** Pick the directory each client really reads; agy reuses a skills.json entry instead of its own folder. */
310
+ function skill_targets(selected, user_home) {
311
+ const own = new Map(selected.map(client => [client.key, real_directory(join(user_home, ...client.skills))]));
312
+ const entries = agy_skill_entries(user_home);
313
+ return selected.map(client => {
314
+ const directory = own.get(client.key);
315
+ if (client.key !== 'antigravity' || !entries.length) return { client, directory, own: directory };
316
+ const others = selected.filter(item => item.key !== client.key).map(item => own.get(item.key));
317
+ return { client, directory: entries.find(entry => others.includes(entry)) || entries[0], own: directory };
318
+ });
319
+ }
320
+
321
+ /** Save the selected effective profiles and copy complete skills without overwriting edits. */
322
+ async function configure_clients(home, selected, options, existing) {
323
+ const participants = { ...existing };
324
+ const skills = [], profiles = [];
325
+ const user_home = resolve(options['skills-home'] || homedir());
326
+ const record = join(home, SKILL_RECORD), installed = new Map();
327
+ for (const { client, directory, own } of skill_targets(selected, user_home)) {
328
+ const profile = await choose_profile(client, participants[client.name], options);
329
+ profiles.push(profile);
330
+ if (profile.status === 'configured') participants[client.name] = { ...participants[client.name], ...profile.effective };
331
+ if (!installed.has(directory)) installed.set(directory, install_skills(directory, record));
332
+ const retired = [client.legacy_skills && real_directory(join(user_home, ...client.legacy_skills)), own]
333
+ .filter(path => path && path !== directory);
334
+ skills.push({ client: client.name, results: installed.get(directory), legacy: retired.flatMap(path => remove_legacy_skills(path, record)) });
335
+ }
336
+ save_launch_settings(home, { participants });
337
+ const legacy = remove_legacy_agy_rules(home, user_home);
338
+ return { skills, profiles, permissions: legacy ? [legacy] : [] };
339
+ }
340
+
341
+ /** Exclude npm exec's temporary command wrappers when checking persistent availability. */
342
+ function persistent_search_path() {
343
+ return (process.env.PATH || '').split(delimiter).filter(path => !path.split(/[\\/]/).includes('_npx')).join(delimiter);
344
+ }
345
+
346
+ /** Verify the resolved persistent npm command belongs to this installation and can run. */
347
+ export function check_command(search_path = persistent_search_path()) {
348
+ const executable = path_program('codiscuss', search_path, true);
349
+ const cli = join(ROOT, 'runner', 'codiscuss.mjs');
350
+ const package_root = resolve(ROOT);
351
+ const prefix = basename(dirname(package_root)) === 'node_modules' ? dirname(dirname(package_root)) : '';
352
+ const directory = prefix ? (process.platform === 'win32' ? prefix : join(dirname(prefix), 'bin')) : '';
353
+ if (!executable) return { status: 'missing', directory,
354
+ action: directory ? `将 ${directory} 加入 PATH,重新打开终端后运行 codiscuss setup。`
355
+ : '尚未找到持久命令,请先运行 install,再重新打开终端运行 codiscuss setup。' };
356
+ const target = process.platform === 'win32' ? join(dirname(executable), 'node_modules', 'ai_co_discuss', 'runner', 'codiscuss.mjs') : executable;
357
+ const shim_matches = process.platform !== 'win32' || (/\.cmd$/i.test(executable)
358
+ && readFileSync(executable, 'utf8').replaceAll('\\', '/').includes('node_modules/ai_co_discuss/runner/codiscuss.mjs'));
359
+ if (!shim_matches || !same_executable(target, cli)) return { status: 'shadowed', path: executable, directory,
360
+ action: `PATH 中的 ${executable} 未指向本次安装;${directory ? `将 ${directory} 放在旧入口之前` : '先运行 install 安装本版本'},再运行 setup。` };
361
+ const probe = process.platform === 'win32'
362
+ ? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '& $env:DISCUSS_COMMAND_PATH --help; exit $LASTEXITCODE'],
363
+ { encoding: 'utf8', windowsHide: true, timeout: PROBE_TIMEOUT, env: { ...process.env, PATH: search_path, DISCUSS_COMMAND_PATH: executable } })
364
+ : spawnSync(executable, ['--help'], { encoding: 'utf8', timeout: PROBE_TIMEOUT, env: { ...process.env, PATH: search_path } });
365
+ return probe.status === 0 ? { status: 'ready', path: executable }
366
+ : { status: 'failed', path: executable, action: `命令无法运行:${executable};请在终端运行此入口的 --help 检查 Node 和执行权限,再运行 setup。` };
367
+ }
368
+
369
+ /** Collect only unresolved setup work, keeping actual AI execution a separate validation. */
370
+ function setup_issues(result) {
371
+ const issues = result.profiles.filter(profile => profile.status === 'pending')
372
+ .map(profile => `${profile.client} 保留了与检测结果不同的配置。${profile.action}`);
373
+ for (const group of result.skills) for (const skill of group.results) {
374
+ if (skill.status === 'conflict') issues.push(`${group.client} 技能冲突,已保留 ${skill.path};请核对并移走需替换的旧副本,再运行 setup。`);
375
+ }
376
+ for (const group of result.skills) for (const skill of group.legacy) {
377
+ if (skill.status === 'kept') issues.push(`${group.client} 旧技能目录中的副本有改动,已保留 ${skill.path};软件会同时加载新旧两份,请核对后删除。`);
378
+ }
379
+ for (const permission of result.permissions) {
380
+ if (permission.status === 'invalid') issues.push(`${permission.client} 设置文件无法解析,未能移除旧版全局放行规则:${permission.path};修复后重新运行 setup,否则全自动讨论会拒绝交付给 agy。`);
381
+ }
382
+ if (result.command.status !== 'ready') issues.push(result.command.action);
383
+ return issues;
384
+ }
385
+
386
+ /** Ask before restarting a running website; non-interactive runs never stop it and report the pending restart instead. */
387
+ async function confirm_restart(reason, options) {
388
+ if (options.yes || !process.stdin.isTTY) return false;
389
+ const choice = await ask(`${reason}\n重启后生效。重启会暂停进行中的讨论;进行中的执行会中断,随后在原会话里自动续跑。现在重启?`, '[Y/N,默认 Y]');
390
+ return !choice.trim() || ['重启', 'restart', 'r', 'y', 'yes'].includes(choice.trim().toLowerCase());
391
+ }
392
+
393
+ /** Configure Python, selected clients and skills, returning partial results on startup failure. */
394
+ async function setup(options) {
395
+ intro('配置 AI CoDiscuss', PACKAGE.version, PACKAGE.description);
396
+ const { home, previous, python, port } = setup_environment(options);
397
+ if (styled && !process.env.CODISCUSS_TUI_NESTED) step('运行环境就绪', [environment_line(python, port)]);
398
+ const scan = spinner('检测已安装的 AI 软件');
399
+ const detected = detect_clients(options);
400
+ const width = Math.max(...detected.map(item => text_width(item.name)));
401
+ const listed = options.clients !== undefined || options.yes
402
+ ? detected.map(item => `${pad(item.name, width)} ${tone.dim(item.executable ? short_path(item.executable) : '未检测到 CLI')}`) : [];
403
+ scan.done(`检测到 ${detected.filter(item => item.executable).length} 个可接入的 CLI`, listed);
404
+ const selected = await selected_clients(options, detected);
405
+ const choices = await install_choices(options, home, previous);
406
+ const workflow_names = choices.workflows;
407
+ const configured = await configure_clients(home, selected, options, launch_settings(home).participants);
408
+ // The remote entry is retired: a saved remote_port from an older version is dropped here.
409
+ const { remote_port: retired, ...kept } = previous;
410
+ const { hosting: was_hosting, ...rest } = kept;
411
+ atomic_json(join(home, 'local-settings.json'), { ...rest, python, port, ...(choices.hosting ? { hosting: true } : {}) });
412
+ // A running taskbar icon read the setting when it started; restart it so the panel comes or goes now.
413
+ if (Boolean(was_hosting) !== choices.hosting) restart_panel_icon(home);
414
+ step('已写入软件配置与技能', configured.skills.map(group => `${pad(group.client, width)} ${tone.dim(short_path(dirname(group.results[0].path)))}`));
415
+ // Shipped workflows are installed only when asked for each time, so a copy the user or a host edited is never replaced unasked.
416
+ const workflows = workflow_names.length ? install_workflows(home, workflow_names) : [];
417
+ // Model API members run in Pi, which codiscuss installs itself, at the release this version pins.
418
+ let pi = null, pi_error = '';
419
+ // A given Pi (CODISCUSS_PI_CLI, as in tests) is used as it is.
420
+ if (!process.env.CODISCUSS_PI_CLI) {
421
+ const pi_step = spinner('安装 Pi(模型 API 成员的运行框架)');
422
+ try {
423
+ pi = await (await import('./pi_runtime.mjs')).install_pi(home);
424
+ pi_step.done(`Pi ${pi.version}${pi.updated ? ' 已安装' : ' 已就绪'}`);
425
+ } catch (error) { pi_error = error.message; pi_step.fail(`Pi 安装失败:${error.message}`); }
426
+ }
427
+ let launcher = null, launcher_error = '';
428
+ if (choices.launcher) {
429
+ try { launcher = install_launcher(home); } catch (error) { launcher_error = error.message; }
430
+ }
431
+ const result = { home, python, clients: selected.map(item => item.name), ...configured, workflows, ...(choices.hosting ? { hosting: true } : {}),
432
+ command: check_command(), ai_verified: false, ...(pi ? { pi: pi.version } : {}), ...(launcher ? { launcher: launcher.shortcuts[0] } : {}) };
433
+ result.issues = setup_issues(result);
434
+ if (pi_error) result.issues.push(`Pi 安装失败(${pi_error});模型 API 成员首次执行时会再试,或检查网络与 npm 后重新运行 setup。`);
435
+ if (launcher_error) result.issues.push(`未能创建“共议”快捷方式(${launcher_error});可稍后运行 codiscuss launcher 重试。`);
436
+ result.configured = result.issues.length === 0;
437
+ result.status = result.configured ? 'configured' : 'needs_attention';
438
+ if (!options['no-start']) {
439
+ const { local_main, restart_reason } = await import('./discussion_local.mjs');
440
+ const reason = restart_reason(home);
441
+ if (reason && !await confirm_restart(reason, options)) {
442
+ result.issues.push(`${reason};重启后才生效。重启会暂停进行中的讨论,进行中的执行会中断并在原会话里自动续跑。确认后运行 codiscuss local stop,再运行 codiscuss local open。`);
443
+ result.configured = false;
444
+ result.status = 'needs_attention';
445
+ return result;
446
+ }
447
+ const launch = spinner(reason ? '重启本机网站与讨论服务' : '启动本机网站与讨论服务');
448
+ try {
449
+ if (reason) await local_main(['stop'], () => {});
450
+ result.local = await local_main([options['no-open'] ? 'start' : 'open'], () => {});
451
+ launch.done('网站与讨论服务已在后台运行', [`${tone.cyan(result.local.url)}${options['no-open'] ? tone.dim(' 未打开浏览器,可直接访问此地址') : tone.dim(' 已在浏览器打开')}`]);
452
+ if (result.configured) result.status = 'ready';
453
+ } catch (error) {
454
+ launch.fail(error.message);
455
+ result.status = 'start_failed';
456
+ result.issues.push(`本机启动失败:${error.message};配置已保存,修复后重新运行 setup。`);
457
+ }
458
+ }
459
+ return result;
460
+ }
461
+
462
+ const WORKFLOW_STATUS = { installed: '已安装', updated: '已覆盖为最新版,原来的备份在', unchanged: '已是最新' };
463
+
464
+ /** One line naming each shipped workflow and what setup did with it. */
465
+ function workflow_summary(workflows) {
466
+ return workflows.map(item => `${item.name} ${WORKFLOW_STATUS[item.status]}${item.backup ? `:${item.backup}` : ''}`).join(' · ');
467
+ }
468
+
469
+ /** Print a concise human receipt while keeping stdout machine-readable. */
470
+ function report_setup(result, options = {}) {
471
+ if (styled) return report_styled(result, options);
472
+ const labels = { ready: '安装配置完成,网站与讨论服务已就绪', configured: '配置完成,本次未启动网站',
473
+ needs_attention: '配置待处理', start_failed: '本机启动失败' };
474
+ const lines = [labels[result.status]];
475
+ for (const profile of result.profiles) lines.push(profile.status === 'manual'
476
+ ? `${profile.client}:仅安装技能,可手动参与,尚不支持全自动接入。`
477
+ : `${profile.client}:${profile.status === 'configured' ? 'CLI 已配置' : '沿用已有配置'}(${profile.effective.adapter} / ${profile.effective.executable || '未设置路径'})`);
478
+ for (const permission of result.permissions) {
479
+ if (permission.status === 'removed') lines.push(`${permission.client}:已移除旧版全局放行规则(${permission.path})`);
480
+ }
481
+ for (const group of result.skills) lines.push(`${group.client} Skill:${group.results.filter(skill => skill.status !== 'conflict').length}/${group.results.length} 份文件就绪,目录 ${dirname(group.results[0].path)}`);
482
+ if (result.workflows.length) lines.push(`内置工作流:${workflow_summary(result.workflows)}`);
483
+ if (result.launcher) lines.push(`快捷方式:${result.launcher}(双击启动共议)`);
484
+ if (result.hosting) lines.push('托管管理:已打开,任务栏图标可打开管理面板');
485
+ if (result.command.path) lines.push(`持久命令:${result.command.path}(${result.command.status})`);
486
+ if (result.local?.running) {
487
+ lines.push(`本机网站:${result.local.url}${options['no-open'] ? '' : '(已在浏览器打开)'}`,
488
+ '网站与讨论服务在后台运行,关闭此终端不影响;查看状态 codiscuss local status,停止 codiscuss local stop;电脑重启后运行 codiscuss local open 重新启动并打开浏览器(codiscuss local start 不打开浏览器);codiscuss service restart 重启讨论服务(使新环境变量生效)'
489
+ + (process.platform === 'win32' ? ';codiscuss service autostart on 登录时自动启动。' : '。'));
490
+ }
491
+ lines.push(...result.issues, '真实 AI 执行尚未验证;可从网页创建讨论,或在新会话调用 Skill。');
492
+ if (result.skills.length) lines.push('若新会话未发现技能,请让 AI 读取上述目录内的 discuss-host/SKILL.md 和 discuss-participant/SKILL.md。');
493
+ process.stderr.write(`${lines.join('\n')}\n`);
494
+ }
495
+
496
+ /** Close the styled installer with aligned results, open issues and the commands to manage the site. */
497
+ function report_styled(result, options) {
498
+ const titles = { ready: ['安装完成', tone.green('◆')], configured: ['配置完成,本次未启动网站', tone.green('◆')],
499
+ needs_attention: ['配置完成,仍有待处理项', tone.yellow('▲')], start_failed: ['本机启动失败', tone.red('■')] };
500
+ const [title, mark] = titles[result.status];
501
+ const rows = [];
502
+ if (result.local?.running) rows.push(['网站', tone.cyan(result.local.url), options['no-open'] ? '' : '已在浏览器打开']);
503
+ for (const profile of result.profiles) rows.push(profile.status === 'manual' ? [profile.client, '仅安装技能,可手动参与', '尚不支持全自动接入']
504
+ : [profile.client, `${profile.status === 'configured' ? 'CLI 已配置' : '沿用已有配置'} · ${profile.effective.adapter}`, short_path(profile.effective.executable) || '未设置路径']);
505
+ for (const permission of result.permissions) {
506
+ if (permission.status === 'removed') rows.push([permission.client, '已移除旧版全局放行规则', short_path(permission.path)]);
507
+ }
508
+ if (result.skills.length) rows.push(['技能', result.skills.map(group => `${group.client} ${group.results.filter(skill => skill.status !== 'conflict').length}/${group.results.length}`).join(' · '), 'discuss-host · discuss-participant · discuss-goal · discuss-session · discuss-report · workflow-creator · local-tts-setup · local-stt-setup']);
509
+ if (result.workflows.length) rows.push(['工作流', workflow_summary(result.workflows), '']);
510
+ if (result.launcher) rows.push(['快捷方式', '双击“共议”启动', short_path(result.launcher)]);
511
+ if (result.hosting) rows.push(['托管管理', '已打开', '任务栏图标可打开管理面板']);
512
+ if (result.command.path) rows.push(['命令', `codiscuss ${tone.dim(`(${result.command.status})`)}`, short_path(result.command.path)]);
513
+ const notes = result.issues.map(issue => tone.yellow(`▲ ${issue}`));
514
+ if (result.local?.running) {
515
+ const commands = [['codiscuss local status', '查看状态'], ['codiscuss local stop', '停止'], ['codiscuss local open', '启动并打开浏览器(重启电脑后用)'],
516
+ ['codiscuss local start', '启动但不打开浏览器'],
517
+ ['codiscuss service restart', '重启讨论服务(使新环境变量生效)']];
518
+ if (process.platform === 'win32') commands.push(['codiscuss service autostart on', '登录时自动启动']);
519
+ const width = Math.max(...commands.map(([command]) => command.length)) + 2;
520
+ notes.push(tone.dim('网站与讨论服务在后台运行,关闭此终端不影响'),
521
+ ...commands.map(([command, label]) => `${tone.cyan(command.padEnd(width))}${tone.dim(label)}`));
522
+ }
523
+ const closing = result.local?.running ? `在网页新建讨论,或在 AI 会话里调用 ${tone.cyan('discuss-host')} ${tone.dim('· 真实 AI 执行尚未验证')}`
524
+ : `运行 ${tone.cyan('codiscuss local open')} 启动网站`;
525
+ outro(title, rows, notes, closing, mark);
526
+ }
527
+
528
+ /** Locate npm's JavaScript entrypoint so paths with spaces never need shell quoting. */
529
+ function npm_entry() {
530
+ const candidates = [process.env.npm_execpath, join(dirname(process.execPath), 'node_modules/npm/bin/npm-cli.js'),
531
+ join(dirname(process.execPath), '../lib/node_modules/npm/bin/npm-cli.js')];
532
+ const executable = path_program('npm');
533
+ if (executable) candidates.push(realpathSync(executable));
534
+ const entry = candidates.find(path => path && /\.(?:c?js|mjs)$/.test(path) && existsSync(path));
535
+ if (!entry) throw new Error('未找到 npm;请安装带 npm 的 Node.js 24+ 后重试。');
536
+ return entry;
537
+ }
538
+
539
+ /** Execute npm without lifecycle scripts asynchronously, so a progress spinner can animate. */
540
+ function npm_run(entry, args) {
541
+ return new Promise((done, fail) => {
542
+ const child = spawn(process.execPath, [entry, ...args], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
543
+ let stdout = '', stderr = '';
544
+ child.stdout.on('data', data => { stdout += data; });
545
+ child.stderr.on('data', data => { stderr += data; });
546
+ child.on('error', fail);
547
+ child.on('close', code => (code === 0 ? done(stdout.trim()) : fail(new Error(stderr || 'npm 执行失败'))));
548
+ });
549
+ }
550
+
551
+ /** Install a real package copy, never a symlink into a disposable npx cache. */
552
+ async function install(args, options) {
553
+ intro('安装 AI CoDiscuss', PACKAGE.version, PACKAGE.description);
554
+ const { python, port } = setup_environment(options);
555
+ requested_clients(options.clients, detect_clients(options));
556
+ if (styled) step('运行环境就绪', [environment_line(python, port)]);
557
+ const entry = npm_entry();
558
+ const temporary = mkdtempSync(join(tmpdir(), 'codiscuss-install-'));
559
+ const prefix = options.prefix ? ['--prefix', resolve(options.prefix)] : [];
560
+ const progress = spinner('安装 codiscuss 命令');
561
+ try {
562
+ const packed = JSON.parse(await npm_run(entry, ['pack', ROOT, '--ignore-scripts', '--json', '--pack-destination', temporary]));
563
+ await npm_run(entry, ['install', '--global', ...prefix, '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund', join(temporary, packed[0].filename)]);
564
+ // npm masks UUID-like path segments as *** in its output, so an explicit prefix is resolved locally.
565
+ const install_prefix = options.prefix ? resolve(options.prefix) : await npm_run(entry, ['prefix', '--global']);
566
+ const global_root = process.platform === 'win32' ? join(install_prefix, 'node_modules') : join(install_prefix, 'lib', 'node_modules');
567
+ const installed = join(global_root, 'ai_co_discuss', 'runner', 'codiscuss.mjs');
568
+ const directory = process.platform === 'win32' ? install_prefix : join(install_prefix, 'bin');
569
+ progress.done('已安装 codiscuss 命令', [tone.dim(short_path(directory))]);
570
+ if (!styled) process.stderr.write(`命令目录:${directory}\n`);
571
+ const result = spawnSync(process.execPath, [installed, 'setup', ...args], { stdio: 'inherit', windowsHide: true,
572
+ env: { ...process.env, PATH: persistent_search_path(), CODISCUSS_TUI_NESTED: '1' } });
573
+ process.exitCode = result.status ?? 1;
574
+ if (result.error) throw result.error;
575
+ } catch (error) { progress.fail(error.message); throw error; }
576
+ finally { rmSync(temporary, { recursive: true, force: true }); }
577
+ }
578
+
579
+ /** Dispatch bootstrap or setup, leaving website and launch commands untouched. */
580
+ export async function setup_main(command, args) {
581
+ const { values } = parseArgs({ args, options: OPTIONS });
582
+ if (values.help) return process.stdout.write(HELP);
583
+ if (command === 'install') return install(args, values);
584
+ const result = await setup(values);
585
+ report_setup(result, values);
586
+ if (values.json || !process.stdout.isTTY) process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
587
+ process.exitCode = result.status === 'start_failed' ? 1 : result.status === 'needs_attention' ? ATTENTION_EXIT_CODE : 0;
588
+ return result;
589
+ }