ai_co_discuss 0.4.33 → 0.4.34

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/docs/runner.md CHANGED
@@ -27,7 +27,7 @@ codiscuss setup
27
27
 
28
28
  `setup` 检测本机 CLI,保存软件配置、安装讨论技能,然后启动本机网站(`http://127.0.0.1:8765`)并打开浏览器。非交互环境可用 `codiscuss setup --yes`,用 `--clients codex,claude` 指定软件。结果提示“待处理”时,按提示处理后重跑 `setup`。
29
29
 
30
- **升级**:先 `codiscuss local stop`,再运行 `npm install --global --prefer-online ai_co_discuss@latest` 和 `codiscuss setup`。
30
+ **升级**:在管理面板“概览”页点“更新”即可;手动升级时先运行 `codiscuss panel stop` 和 `codiscuss local stop`,再运行 `npm install --global --prefer-online ai_co_discuss@latest` 和 `codiscuss setup`。
31
31
 
32
32
  **卸载**:先 `codiscuss local stop`,再 `npm uninstall --global ai_co_discuss`。讨论数据保存在 `~/.codiscuss`,卸载不会删除。本机服务会自动清理已删除房间的本机文件,并控制日志大小;也可运行 `codiscuss service clean` 立即清理。
33
33
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.33",
3
+ "version": "0.4.34",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import { spawn, spawnSync } from 'node:child_process';
11
11
  import { randomBytes } from 'node:crypto';
12
- import { closeSync, existsSync, openSync, realpathSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
12
+ import { closeSync, copyFileSync, existsSync, mkdirSync, openSync, realpathSync, readdirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
13
13
  import http from 'node:http';
14
14
  import { tmpdir } from 'node:os';
15
15
  import { dirname, extname, join, resolve } from 'node:path';
@@ -41,6 +41,10 @@ const LATEST_URL = `https://registry.npmjs.org/${NPM_PACKAGE}/latest`;
41
41
  const LATEST_TTL_MS = 60 * 60 * 1000;
42
42
  const LATEST_TIMEOUT_MS = 8000;
43
43
  const STATE_FILE = 'admin-panel.json';
44
+ // An update's progress and report, kept in the service directory (panel_updater.mjs writes it too), and how long an
45
+ // unfinished one blocks another.
46
+ const UPDATE_JOB_FILE = 'panel-update.json';
47
+ const UPDATE_STALE_MS = 10 * 60 * 1000;
44
48
  // Hosted accounts' failures, relayed to the owner's Weixin: how often, how far each account's outbox was read, and limits
45
49
  // on what one notice carries (the outbox is in the account's own folder, so its text is the account's, not ours).
46
50
  const RELAY_MS = 30_000;
@@ -110,36 +114,75 @@ function run_command(command, args) {
110
114
  });
111
115
  }
112
116
 
117
+ function update_job(data) {
118
+ try { return JSON.parse(readFileSync(join(data, UPDATE_JOB_FILE), 'utf8')); } catch { return null; }
119
+ }
120
+
121
+ function write_update_job(data, job) {
122
+ writeFileSync(join(data, UPDATE_JOB_FILE), JSON.stringify(job), { mode: 0o600 });
123
+ }
124
+
125
+ /** A step of an update, recorded as done or as failed with its reason; the steps after it still run. */
126
+ async function update_step(steps, done, work) {
127
+ try { await work(); steps.push(done); } catch (error) { steps.push(`${done.replace(/^已/, '')}失败:${error.message}`); }
128
+ }
129
+
130
+ /**
131
+ * Start installing a published version. npm cannot replace the package while anything runs from it (Windows refuses with
132
+ * EBUSY), so the owner's service and the running instances of accounts without their own Windows user (they run from the
133
+ * package) are stopped first; then this panel hands over to panel_updater.mjs, run from the service directory, which
134
+ * installs and starts the new panel (`finish_update`). The page follows along with GET update/progress.
135
+ */
136
+ async function begin_update(data, version, hand_over) {
137
+ const current = update_job(data);
138
+ if (current && current.status !== 'done' && Date.now() - current.started_at < UPDATE_STALE_MS) throw new Error('正在更新,请稍候');
139
+ const running = hosting_enabled(data) ? (await list_accounts(data)).filter(account => account.running) : [];
140
+ const job = { version, status: 'stopping', steps: [], restart: running.map(account => account.name), started_at: Date.now() };
141
+ write_update_job(data, job);
142
+ (async () => {
143
+ await update_step(job.steps, '已停止本机服务', () => run_owner_service(data, 'stop'));
144
+ for (const account of running) if (!account.os_user) await update_step(job.steps, `已停止 ${account.name} 的实例`, () => run_instance(data, account.name, 'stop'));
145
+ const updater = join(data, 'update', 'panel_updater.mjs');
146
+ mkdirSync(dirname(updater), { recursive: true });
147
+ copyFileSync(join(ROOT, 'runner', 'panel_updater.mjs'), updater);
148
+ write_update_job(data, { ...job, status: 'installing' });
149
+ hand_over(updater);
150
+ })().catch(error => {
151
+ // Nothing was installed: what was stopped starts again on finish_update's path.
152
+ write_update_job(data, { ...job, status: 'install_failed', steps: [...job.steps, `更新失败:${error.message}`] });
153
+ finish_update(data).catch(() => {});
154
+ });
155
+ return { version, status: 'stopping' };
156
+ }
157
+
113
158
  /**
114
- * Install a published version and bring everything on this computer onto it, reporting each step: the owner's skills
115
- * (setup without questions), the owner's service, and with hosting on, the shared copy and every account with its own
116
- * Windows user (skills, missing workflows, a running instance restarted). A step that fails is reported and the rest go
117
- * on. The panel itself still runs the old code afterwards; `on_updated` restarts it.
159
+ * Finish an update panel_updater.mjs installed (or failed to), from the panel it started, reporting each step: with the
160
+ * new version, the owner's skills (setup without questions), the shared copy and the skills of every account with its own
161
+ * Windows user; in any case the owner's service started again and the instances that ran before restarted.
118
162
  */
119
- async function update_package(data, version, on_updated) {
120
- await run_command('npm', ['install', '--global', `${NPM_PACKAGE}@${version}`]);
121
- const steps = [`已安装 v${version}`];
122
- // The restarted service starts the new version's panel, which replaces a panel of another version; marked as updating,
123
- // this one is left to finish its report and hand over itself (`on_updated`).
124
- const panel = read_state(data);
125
- if (panel?.pid === process.pid) writeFileSync(state_path(data), JSON.stringify({ ...panel, updating: true }), { mode: 0o600 });
126
- const step = async (done, work) => { try { await work(); steps.push(done); } catch (error) { steps.push(`${done.replace(/^已/, '')}失败:${error.message}`); } };
127
- await step('已更新本机技能', () => run_command(process.execPath, [installed_script('codiscuss.mjs'), 'setup', '--yes', '--no-start', '--json']).catch(error => {
163
+ async function finish_update(data) {
164
+ const job = update_job(data);
165
+ if (!['installed', 'install_failed'].includes(job?.status)) return;
166
+ const installed = job.status === 'installed', steps = [...job.steps];
167
+ write_update_job(data, { ...job, status: 'finishing' });
168
+ if (installed) await update_step(steps, '已更新本机技能', () => run_command(process.execPath, [installed_script('codiscuss.mjs'), 'setup', '--yes', '--no-start', '--json']).catch(error => {
128
169
  // Setup exits 2 when it finished with items to look at (an edited skill is kept, for one); that still counts.
129
170
  if (error.code !== 2) throw error;
130
171
  }));
131
- await step('已重启本机服务', async () => { await run_owner_service(data, 'stop'); await run_owner_service(data, 'start'); });
172
+ await update_step(steps, '已启动本机服务', () => run_owner_service(data, 'start'));
132
173
  if (hosting_enabled(data)) {
133
- await step('已更新共享运行环境', () => { const result = install_runtime(data); if (result.warnings.length) throw new Error(result.warnings.join(';')); });
174
+ if (installed) await update_step(steps, '已更新共享运行环境', () => { const result = install_runtime(data); if (result.warnings.length) throw new Error(result.warnings.join(';')); });
134
175
  for (const account of await list_accounts(data)) {
135
- if (!account.os_user) continue;
136
- await step(`已更新 ${account.name} 的技能`, () => prepare_account(data, account.name));
137
- // Reported restarted only once it serves again as the account is set (start_verified).
138
- if (account.running) await step(`已重启 ${account.name} 的实例`, async () => { await run_instance(data, account.name, 'stop'); await start_verified(data, account.name); });
176
+ if (installed && account.os_user) await update_step(steps, `已更新 ${account.name} 的技能`, () => prepare_account(data, account.name));
177
+ // Reported restarted only once it serves again as the account is set (start_verified). Instances run from the
178
+ // package were stopped before the install; those running from the shared copy are stopped here.
179
+ if ((job.restart || []).includes(account.name)) await update_step(steps, `已重启 ${account.name} 的实例`, async () => {
180
+ if (account.os_user) await run_instance(data, account.name, 'stop');
181
+ await start_verified(data, account.name);
182
+ });
139
183
  }
140
184
  }
141
- setTimeout(on_updated, 500);
142
- return { version, steps };
185
+ write_update_job(data, { ...job, status: 'done', ok: installed, steps });
143
186
  }
144
187
 
145
188
  // ---- Accounts ----
@@ -414,8 +457,8 @@ function cookie(request, name) {
414
457
  export function create_panel({ data, key, port, ops = {}, sessions = new Set() }) {
415
458
  const op = { list_accounts, add_account, reset_password, set_account_disabled, remove_account, run_instance, create_os_user, remove_os_user,
416
459
  login_status, apply_login, logout, start_login, login_progress, submit_login, cancel_login, install_runtime, prepare_account, account_env, account_skills, shared_cli_state,
417
- save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, update_package,
418
- autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, protect_account, start_verified, on_updated: () => {}, ...ops };
460
+ save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, begin_update,
461
+ autostart_enabled, set_autostart, entry_overview, start_entry, stop_entry, protect_account, start_verified, hand_over: () => {}, ...ops };
419
462
  const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
420
463
 
421
464
  async function api(method, path, body) {
@@ -436,11 +479,12 @@ export function create_panel({ data, key, port, ops = {}, sessions = new Set() }
436
479
  if (name !== 'stop') await op.run_owner_service(data, 'start');
437
480
  return op.service_overview(data);
438
481
  }
482
+ if (method === 'GET' && section === 'update' && name === 'progress') return update_job(data) || { status: 'none' };
439
483
  if (method === 'GET' && section === 'update') {
440
484
  const current = op.service_overview(data).version || VERSION, version = await op.latest_version(name === 'check');
441
485
  return { current, latest: version, available: newer_version(version, current) };
442
486
  }
443
- if (method === 'POST' && section === 'update') return op.update_package(data, await op.latest_version(true), op.on_updated);
487
+ if (method === 'POST' && section === 'update') return op.begin_update(data, await op.latest_version(true), op.hand_over);
444
488
  if (method === 'POST' && section === 'autostart') return { autostart: op.set_autostart(Boolean(body.on), data) };
445
489
  // Command-line sign-in: '_' is the owner; an account name is a hosted account with its own Windows user.
446
490
  if (section === 'login-jobs') {
@@ -737,20 +781,25 @@ export function hosting_enabled(data) {
737
781
  function run_panel(data, port) {
738
782
  const running = read_state(data);
739
783
  if (running && running.pid !== process.pid && alive(running.pid)) throw new Error(`管理面板已在运行:http://127.0.0.1:${running.port}`);
784
+ // Out of the package folder (the 共议 launcher starts here from it), with everything this starts, the panel window
785
+ // included: Windows will not let npm replace a folder that is any process's working directory.
786
+ process.chdir(data);
740
787
  // A panel started by an update takes over its predecessor's key and sessions, so the open window keeps working.
741
788
  let handover = {};
742
789
  try { handover = JSON.parse(process.env[HANDOVER_VARIABLE] || '{}'); } catch { handover = {}; }
743
790
  delete process.env[HANDOVER_VARIABLE];
744
791
  const state = { pid: process.pid, port, key: handover.key || randomBytes(24).toString('hex'), version: VERSION };
745
792
  const sessions = new Set(Array.isArray(handover.sessions) ? handover.sessions : []);
746
- // After an update this process still runs the old code: it steps aside and starts the newly installed panel.
747
- const on_updated = () => {
793
+ // For an update this process steps aside: the updater, run from outside the package, installs once it has exited and
794
+ // starts the installed panel, which takes over the key and sessions.
795
+ const hand_over = updater => {
748
796
  shutdown(false);
749
- spawn(process.execPath, [installed_script('admin_panel.mjs'), 'start', '--data', data, '--port', String(port)], { detached: true, stdio: 'ignore', windowsHide: true,
750
- env: { ...process.env, [HANDOVER_VARIABLE]: JSON.stringify({ key: state.key, sessions: [...sessions] }) } }).unref();
797
+ spawn(process.execPath, [updater, '--data', data, '--pid', String(process.pid), '--panel', installed_script('admin_panel.mjs'), '--port', String(port)],
798
+ { cwd: dirname(updater), detached: true, stdio: 'ignore', windowsHide: true,
799
+ env: { ...process.env, [HANDOVER_VARIABLE]: JSON.stringify({ key: state.key, sessions: [...sessions] }) } }).unref();
751
800
  setTimeout(() => process.exit(0), 300);
752
801
  };
753
- const server = create_panel({ data, key: state.key, port, ops: { on_updated }, sessions });
802
+ const server = create_panel({ data, key: state.key, port, ops: { hand_over }, sessions });
754
803
  // An entry left on starts again with the panel (only the entry: the accounts' instances and the HTTPS tunnel are separate).
755
804
  if (hosting_enabled(data) && entry_settings(data).running) start_entry(data).catch(error => process.stderr.write(`入口没有启动:${error.message}\n`));
756
805
  // Hosted accounts' failures reach the owner's Weixin; one pass at a time.
@@ -763,6 +812,7 @@ function run_panel(data, port) {
763
812
  server.listen(port, '127.0.0.1', () => {
764
813
  writeFileSync(state_path(data), JSON.stringify(state), { mode: 0o600 });
765
814
  process.stdout.write(`管理面板已启动:http://127.0.0.1:${port}\n`);
815
+ finish_update(data).catch(error => process.stderr.write(`更新收尾失败:${error.message}\n`));
766
816
  });
767
817
  const rendered = join(data, 'launcher', 'codiscuss.ico');
768
818
  const tray = show_tray({ title: '共议', icon_path: existsSync(rendered) ? rendered : '', window_title: WINDOW_TITLE,
@@ -798,7 +848,7 @@ function run_panel(data, port) {
798
848
  /** Start the panel in the background unless it already runs; returns its state. */
799
849
  async function start_panel(data, port) {
800
850
  const running = read_state(data);
801
- if (running && alive(running.pid) && (running.version === VERSION || running.updating)) return running;
851
+ if (running && alive(running.pid) && running.version === VERSION) return running;
802
852
  // A panel of another version (left running across an update) is replaced, so the icon and panel match what is installed.
803
853
  if (running && alive(running.pid)) {
804
854
  process.kill(running.pid);
@@ -199,6 +199,9 @@ function start_panel_icon(home, settings) {
199
199
  /** Run one supervisor, recording readiness and handling an explicit local stop request. */
200
200
  async function supervise(home) {
201
201
  assert_shared_home(home);
202
+ // Out of the package folder, with the website and service this starts: Windows will not let npm replace a folder that
203
+ // is any process's working directory (the 共议 launcher starts here from the package).
204
+ process.chdir(resolve(home));
202
205
  const directory = join(home, 'local');
203
206
  const release = acquire_lock(directory);
204
207
  const status_path = join(directory, 'status.json');
@@ -67,7 +67,8 @@ static class Launcher {
67
67
  ProcessStartInfo info = new ProcessStartInfo(Node, "\\"" + script + "\\" " + command);
68
68
  info.UseShellExecute = false;
69
69
  info.CreateNoWindow = true;
70
- info.WorkingDirectory = Path.GetDirectoryName(script);
70
+ // Not the package folder: npm cannot replace a folder that is a running process's working directory.
71
+ info.WorkingDirectory = Directory.Exists(Home) ? Home : Path.GetTempPath();
71
72
  info.EnvironmentVariables["DISCUSS_SERVICE_HOME"] = Home;
72
73
  Process.Start(info);
73
74
  }
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Install a new codiscuss version for the management panel's update button, from outside the package folder.
4
+ *
5
+ * npm replaces a global package by renaming its folder, which Windows refuses (EBUSY) while any process runs from it,
6
+ * the panel included. So the panel stops what runs from the package, copies this file into the service directory, starts
7
+ * it from there and exits. This waits for the panel to exit, installs, records the result in the update record and starts
8
+ * the installed panel, which finishes the remaining steps. Only Node built-ins and no imports of the package: the package
9
+ * folder is replaced while this runs.
10
+ *
11
+ * Usage: node panel_updater.mjs --data DIR --pid PANEL_PID --panel ADMIN_PANEL_SCRIPT --port PORT
12
+ */
13
+ import { spawn } from 'node:child_process';
14
+ import { readFileSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { parseArgs } from 'node:util';
17
+
18
+ // Shared with admin_panel.mjs (this file cannot import it).
19
+ const JOB_FILE = 'panel-update.json';
20
+ const NPM_PACKAGE = 'ai_co_discuss';
21
+ const EXIT_WAIT_MS = 30_000;
22
+ const POLL_MS = 300;
23
+ // Windows may keep a folder busy a moment after its last process exits (an antivirus scan, for one).
24
+ const INSTALL_ATTEMPTS = 3;
25
+ const RETRY_MS = 3000;
26
+ const OUTPUT_LIMIT = 4000;
27
+
28
+ const sleep = ms => new Promise(done => setTimeout(done, ms));
29
+
30
+ function alive(pid) {
31
+ try { process.kill(pid, 0); return true; } catch { return false; }
32
+ }
33
+
34
+ /** Run npm to its end; fails with the last lines of its output. */
35
+ function npm(args, cwd) {
36
+ return new Promise((done, fail) => {
37
+ // npm is a .cmd on Windows, which only a shell runs.
38
+ const child = spawn('npm', args, { cwd, shell: process.platform === 'win32', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
39
+ let output = '';
40
+ child.stdout.on('data', chunk => { output = (output + chunk).slice(-OUTPUT_LIMIT); });
41
+ child.stderr.on('data', chunk => { output = (output + chunk).slice(-OUTPUT_LIMIT); });
42
+ child.on('error', fail);
43
+ child.on('exit', code => code === 0 ? done() : fail(new Error(`npm ${args.join(' ')} 失败(退出码 ${code}):${output.trim().split(/\r?\n/).slice(-3).join(' ')}`)));
44
+ });
45
+ }
46
+
47
+ async function main() {
48
+ const { values } = parseArgs({ options: { data: { type: 'string' }, pid: { type: 'string' }, panel: { type: 'string' }, port: { type: 'string' } } });
49
+ const job_path = join(values.data, JOB_FILE);
50
+ const job = JSON.parse(readFileSync(job_path, 'utf8'));
51
+ const save = change => writeFileSync(job_path, JSON.stringify(Object.assign(job, change)), { mode: 0o600 });
52
+ for (let waited = 0; waited < EXIT_WAIT_MS && alive(Number(values.pid)); waited += POLL_MS) await sleep(POLL_MS);
53
+ let failure = null;
54
+ for (let attempt = 1; attempt <= INSTALL_ATTEMPTS; attempt += 1) {
55
+ try { await npm(['install', '--global', `${NPM_PACKAGE}@${job.version}`], values.data); failure = null; break; }
56
+ catch (error) { failure = error; if (attempt < INSTALL_ATTEMPTS) await sleep(RETRY_MS); }
57
+ }
58
+ save(failure ? { status: 'install_failed', steps: [...job.steps, `安装失败:${failure.message}`] }
59
+ : { status: 'installed', steps: [...job.steps, `已安装 v${job.version}`] });
60
+ // The installed panel (the old one when npm failed) takes over the open window's key and sessions from the environment.
61
+ spawn(process.execPath, [values.panel, 'start', '--data', values.data, '--port', values.port],
62
+ { cwd: values.data, detached: true, stdio: 'ignore', windowsHide: true }).unref();
63
+ }
64
+
65
+ main().catch(error => { process.stderr.write(`${error.message}\n`); process.exitCode = 1; });