ai_co_discuss 0.4.56 → 0.4.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai_co_discuss",
3
- "version": "0.4.56",
3
+ "version": "0.4.58",
4
4
  "bin": {
5
5
  "codiscuss": "runner/codiscuss.mjs"
6
6
  },
@@ -414,7 +414,7 @@ async function confirm_restart(reason, options) {
414
414
 
415
415
  /** Configure Python, selected clients and skills, returning partial results on startup failure. */
416
416
  async function setup(options) {
417
- intro(t('配置 AI CoDiscuss'), PACKAGE.version, PACKAGE.description);
417
+ intro(t('配置 AI CoDiscuss'), PACKAGE.version, t('让不同 AI 在各自软件中协作的共享讨论空间'));
418
418
  const { home, previous, python, port } = setup_environment(options);
419
419
  if (styled && !process.env.CODISCUSS_TUI_NESTED) step(t('运行环境就绪'), [environment_line(python, port)]);
420
420
  const scan = spinner(t('检测已安装的 AI 软件'));
@@ -93,11 +93,25 @@ function redraw(output, lines, drawn) {
93
93
  return lines.reduce((sum, line) => sum + Math.max(1, Math.ceil(text_width(line) / columns)), 0);
94
94
  }
95
95
 
96
- /** Animate a step while asynchronous work runs; synchronous work simply shows the first frame. */
96
+ /** Cut text to a display width, ending in … when shortened. */
97
+ function fit(text, width) {
98
+ if (text_width(text) <= width) return text;
99
+ let kept = '';
100
+ for (const char of text) { if (text_width(`${kept}${char}`) > width - 1) break; kept += char; }
101
+ return `${kept}…`;
102
+ }
103
+
104
+ /** Items of a short list in the interface language (、 in Chinese, a comma in English). */
105
+ export const list_text = items => items.join(t('、'));
106
+
107
+ /**
108
+ * Animate a step while asynchronous work runs; synchronous work simply shows the first frame. The line is kept to one
109
+ * terminal row: `\r` returns only to the start of the last row, so a wrapped line would leave a copy at every frame.
110
+ */
97
111
  export function spinner(title) {
98
112
  if (!styled) return { done: () => {}, fail: () => {} };
99
113
  let frame = 0;
100
- const render = () => write(`\r\x1b[2K${tone.cyan(SPIN_FRAMES[frame++ % SPIN_FRAMES.length])} ${title}${tone.dim('…')}`);
114
+ const render = () => write(`\r\x1b[2K${tone.cyan(SPIN_FRAMES[frame++ % SPIN_FRAMES.length])} ${fit(title, (process.stderr.columns || 80) - 5)}${tone.dim('…')}`);
101
115
  render();
102
116
  const timer = setInterval(render, SPIN_MS);
103
117
  const clear = () => { clearInterval(timer); write('\r\x1b[2K'); };
@@ -161,7 +175,7 @@ export function checkbox_prompt(message, items, input = process.stdin, output =
161
175
  input.off('keypress', on_key);
162
176
  input.setRawMode(false);
163
177
  input.pause();
164
- const chosen = items.filter((_, index) => checked[index]).map(item => item.label).join('、') || t('不接入软件,只配置网站');
178
+ const chosen = list_text(items.filter((_, index) => checked[index]).map(item => item.label)) || t('不接入软件,只配置网站');
165
179
  draw(error ? [`${tone.red('■')} ${message}`, `${bar()} ${tone.dim(t('已取消'))}`] : [`${tone.green('◇')} ${message}`, `${bar()} ${tone.dim(chosen)}`, bar()]);
166
180
  output.write('\x1b[?25h');
167
181
  if (error) fail(error); else done(checked);
@@ -233,7 +247,7 @@ export function tree_prompt(message, groups, input = process.stdin, output = pro
233
247
  input.off('keypress', on_key);
234
248
  input.setRawMode(false);
235
249
  input.pause();
236
- const summary = groups.map((group, index) => `${group.label}:${group.items.filter((_, item) => checked[index][item]).map(item => item.label).join('、') || t('不安装')}`);
250
+ const summary = groups.map((group, index) => t('{value1}:{value2}', { value1: group.label, value2: list_text(group.items.filter((_, item) => checked[index][item]).map(item => item.label)) || t('不安装') }));
237
251
  draw(error ? [`${tone.red('■')} ${message}`, `${bar()} ${tone.dim(t('已取消'))}`]
238
252
  : [`${tone.green('◇')} ${message}`, ...summary.map(line => `${bar()} ${tone.dim(line)}`), bar()]);
239
253
  output.write('\x1b[?25h');
@@ -405,5 +405,8 @@ export default {
405
405
  "问题 #{id} 已交给主持人处理,这条回复没有作答;需要补充请在房间里说。": "Question #{id} is with the host; this reply answered nothing. To add something, say it in the room.",
406
406
  "问题 #{id} 已更新到第 {version} 版(例如主持人给了推荐),这条回复没有作答;新版本会另发通知。": "Question #{id} is now at version {version} (for example the host recommended an answer); this reply answered nothing. The new version will be sent to you.",
407
407
  "已按 {picked}回答问题 #{id}。": "Answered question #{id} with {picked}.",
408
- "已把你的回复交给主持人判断(问题 #{id}),它会代为选择或在房间里追问。": "Your reply went to the host (question #{id}); it will choose for you or ask in the room."
408
+ "已把你的回复交给主持人判断(问题 #{id}),它会代为选择或在房间里追问。": "Your reply went to the host (question #{id}); it will choose for you or ask in the room.",
409
+ "、": ", ",
410
+ "{value1}:{value2}": "{value1}: {value2}",
411
+ "让不同 AI 在各自软件中协作的共享讨论空间": "A shared discussion space where different AIs work together, each in its own app"
409
412
  };
@@ -8,7 +8,7 @@
8
8
  * after moving them.
9
9
  */
10
10
  import { spawnSync } from 'node:child_process';
11
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
11
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
12
12
  import { homedir, tmpdir } from 'node:os';
13
13
  import { dirname, join } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
@@ -277,11 +277,21 @@ static class TrayMenu {
277
277
  return strip;
278
278
  }
279
279
 
280
+ // An invisible window that never has a taskbar button. Making the menu itself the foreground window gave it one: an
281
+ // ownerless top-level window there gets a taskbar button (seen 2026-11-15 on both computers).
282
+ static Form anchor;
283
+
280
284
  public static void Show(ContextMenuStrip strip, Point at) {
285
+ if (anchor == null) {
286
+ anchor = new Form();
287
+ anchor.ShowInTaskbar = false; anchor.FormBorderStyle = FormBorderStyle.None; anchor.StartPosition = FormStartPosition.Manual;
288
+ anchor.Location = new Point(-32000, -32000); anchor.Size = new Size(1, 1); anchor.Opacity = 0;
289
+ anchor.Show();
290
+ }
291
+ // A menu closes on an outside click only when this program is in the foreground.
292
+ SetForegroundWindow(anchor.Handle);
281
293
  // Opened downward from one menu-height above the pointer, so it sits up and to the right of it.
282
294
  strip.Show(new Point(at.X, at.Y - strip.Height), ToolStripDropDownDirection.BelowRight);
283
- // A menu closes on an outside click only when this program is in the foreground.
284
- SetForegroundWindow(strip.Handle);
285
295
  }
286
296
  }
287
297
 
@@ -578,6 +588,20 @@ export function launcher_installed(home = join(homedir(), '.codiscuss')) {
578
588
  return Boolean(desktop) && existsSync(join(desktop, SHORTCUT_NAME));
579
589
  }
580
590
 
591
+ /**
592
+ * Put a new exe in place of one that may be running. Windows lets a running exe be renamed but not overwritten or
593
+ * deleted, so it is moved aside (its icon keeps working until it is restarted) and removed on a later run.
594
+ */
595
+ function replace_running(draft, exe) {
596
+ const folder = dirname(exe);
597
+ // An old one still running (its icon not restarted yet) stays until a later run.
598
+ for (const name of readdirSync(folder)) if (name.endsWith('.old')) try { rmSync(join(folder, name), { force: true }); } catch { /* still running */ }
599
+ if (existsSync(exe)) {
600
+ try { rmSync(exe); } catch { renameSync(exe, join(folder, `launcher-${Date.now()}.old`)); }
601
+ }
602
+ renameSync(draft, exe);
603
+ }
604
+
581
605
  /**
582
606
  * Build 共议.exe and its shortcuts.
583
607
  *
@@ -594,9 +618,12 @@ export function install_launcher(home = join(homedir(), '.codiscuss')) {
594
618
  const source = join(folder, 'launcher.cs'), exe = launcher_path(home);
595
619
  writeFileSync(source, `\ufeff${launcher_source({ node: process.execPath, local_script: installed_script('discussion_local.mjs'),
596
620
  panel_script: installed_script('admin_panel.mjs'), home })}`, 'utf8');
621
+ // Compiled beside it first: the running exe (it hosts the taskbar icon) cannot be overwritten (CS0016, seen 2026-11-15).
622
+ const draft = join(folder, 'launcher.new.exe');
597
623
  const result = spawnSync(CSC, ['/nologo', '/target:winexe', '/codepage:65001', '/optimize+', '/r:System.Windows.Forms.dll', '/r:System.Drawing.dll',
598
- `/out:${exe}`, ...(icon ? [`/win32icon:${icon}`] : []), source], { encoding: 'utf8', windowsHide: true });
624
+ `/out:${draft}`, ...(icon ? [`/win32icon:${icon}`] : []), source], { encoding: 'utf8', windowsHide: true });
599
625
  if (result.status !== 0) throw new Error(t('编译启动器失败:{value1}', { value1: (result.stdout || result.stderr).trim() }));
626
+ replace_running(draft, exe);
600
627
  const shortcuts = ['Desktop', 'Programs'].map(place => write_shortcut(place, exe, icon));
601
628
  return { exe, icon, shortcuts };
602
629
  }
@@ -5,8 +5,11 @@
5
5
  * owner's files. The owner's management panel creates the user (one elevation prompt), runs programs as it with the
6
6
  * stored password, installs the command-line programs where every user can run them, and signs them in.
7
7
  *
8
- * The password is kept in the owner's service directory, encrypted with Windows DPAPI for the owner's own user, so only
9
- * the owner can use it. Everything here is Windows only.
8
+ * The password is kept in the owner's service directory, which only the owner and administrators can read, encrypted with
9
+ * Windows DPAPI for this computer. The computer scope, not the owner's own, because an administrator signed in over SSH
10
+ * with a key has no user DPAPI key (Windows answers "Access is denied"; seen 2026-11-15 on the hosting test computer),
11
+ * and hosted computers are managed over SSH. Passwords saved earlier with the owner's scope still work where that scope
12
+ * does. Everything here is Windows only.
10
13
  */
11
14
  import { spawnSync } from 'node:child_process';
12
15
  import { randomBytes } from 'node:crypto';
@@ -33,6 +36,9 @@ const JOB_ROOT = join(SHARED_ROOT, 'jobs');
33
36
  // the shared folder, so they cannot depend on it already being secure.
34
37
  const OWNER_JOB_ROOT = join(tmpdir(), 'codiscuss-owner-jobs');
35
38
  const POWERSHELL = 'powershell.exe';
39
+ // Stored passwords encrypted for this computer start with this; older ones are the owner's DPAPI (ConvertFrom-SecureString).
40
+ const MACHINE_SECRET = 'machine:';
41
+ const SECRET_ENTROPY = 'AI CoDiscuss hosted account';
36
42
  const DEFAULT_TIMEOUT_MS = 120_000;
37
43
  const ELEVATED_TIMEOUT_MS = 300_000;
38
44
 
@@ -158,9 +164,16 @@ exit $process.ExitCode`;
158
164
  } finally { rmSync(job, { recursive: true, force: true }); }
159
165
  }
160
166
 
161
- /** The owner's DPAPI encryption of a password, usable only by the owner on this computer. */
167
+ /** A password encrypted with DPAPI for this computer; what keeps it private is the owner-only file it is stored in. */
162
168
  function protect(password) {
163
- return run_powershell(`ConvertTo-SecureString ${quote(password)} -AsPlainText -Force | ConvertFrom-SecureString`);
169
+ return MACHINE_SECRET + run_powershell(`Add-Type -AssemblyName System.Security
170
+ [Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect([Text.Encoding]::UTF8.GetBytes(${quote(password)}), [Text.Encoding]::UTF8.GetBytes(${quote(SECRET_ENTROPY)}), 'LocalMachine'))`);
171
+ }
172
+
173
+ /** A PowerShell expression giving the stored password back as a SecureString (either encryption). */
174
+ function secure_secret(secret) {
175
+ if (!secret.startsWith(MACHINE_SECRET)) return `(ConvertTo-SecureString ${quote(secret)})`;
176
+ return `(& { Add-Type -AssemblyName System.Security; ConvertTo-SecureString ([Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect([Convert]::FromBase64String(${quote(secret.slice(MACHINE_SECRET.length))}), [Text.Encoding]::UTF8.GetBytes(${quote(SECRET_ENTROPY)}), 'LocalMachine'))) -AsPlainText -Force })`;
164
177
  }
165
178
 
166
179
  /**
@@ -173,6 +186,8 @@ export function create_os_user(data, account, account_folder, { run = run_powers
173
186
  const user = os_user_name(account);
174
187
  if (read_os_users(data)[account]) throw new Error(`账号 ${account} 已有 Windows 用户 ${user}`);
175
188
  const password = `Cd!${randomBytes(18).toString('base64url')}`;
189
+ // Encrypted before anything changes, so a failure here leaves the computer as it was.
190
+ const secret = protect(password);
176
191
  run(`$secure = ConvertTo-SecureString ${quote(password)} -AsPlainText -Force
177
192
  if (Get-LocalUser -Name ${quote(user)} -ErrorAction SilentlyContinue) { Set-LocalUser -Name ${quote(user)} -Password $secure }
178
193
  else { New-LocalUser -Name ${quote(user)} -Password $secure -PasswordNeverExpires -UserMayNotChangePassword -Description 'AI CoDiscuss hosted account' | Out-Null }
@@ -180,7 +195,7 @@ if (-not (Get-LocalGroupMember -Group 'Users' -Member ${quote(user)} -ErrorActio
180
195
  icacls ${quote(account_folder)} /grant ${quote(`${user}:(OI)(CI)M`)} /T /C /Q | Out-Null
181
196
  ${register_task_script(account, user, '$secure', owner_sid({ run }))}
182
197
  'ok'`, { elevated: true });
183
- write_os_users(data, { ...read_os_users(data), [account]: { user, secret: protect(password) } });
198
+ write_os_users(data, { ...read_os_users(data), [account]: { user, secret } });
184
199
  return { user };
185
200
  }
186
201
 
@@ -249,8 +264,13 @@ export function run_as_user(data, account, script, { files = {}, folders = {}, v
249
264
  writeFileSync(job, `\ufeff[Console]::OutputEncoding = [Text.Encoding]::UTF8\n$Job = ${quote(folder)}\n$Out = ${quote(join(folder, 'out'))}\n${script}\n`, 'utf8');
250
265
  const command = visible ? `-NoProfile -ExecutionPolicy Bypass -NoExit -File ${quote(job)}`
251
266
  : `-NoProfile -ExecutionPolicy Bypass -Command & ${quote(job)} *> ${quote(output)}`;
252
- const start = `$credential = New-Object System.Management.Automation.PSCredential(${quote(record.user)}, (ConvertTo-SecureString ${quote(record.secret)}))
253
- $process = Start-Process ${POWERSHELL} -Credential $credential -LoadUserProfile -WorkingDirectory ${quote(folder)} -PassThru ${visible ? '' : '-WindowStyle Hidden'} -ArgumentList ${quote(command)}
267
+ // Start-Process -Credential hands the new process this PowerShell's standard output and error, which are the pipes the
268
+ // caller's spawnSync reads to their end: a process left running would hold this start (and the panel's whole event
269
+ // loop) until its timeout (seen 2026-11-15: a sign-in froze the panel and its taskbar icon for two minutes). Not waiting,
270
+ // they go to files in the job folder instead, which only the owner writes.
271
+ const detach = wait ? '' : `-RedirectStandardOutput ${quote(join(folder, 'start-out.txt'))} -RedirectStandardError ${quote(join(folder, 'start-error.txt'))}`;
272
+ const start = `$credential = New-Object System.Management.Automation.PSCredential(${quote(record.user)}, ${secure_secret(record.secret)})
273
+ $process = Start-Process ${POWERSHELL} -Credential $credential -LoadUserProfile -WorkingDirectory ${quote(folder)} -PassThru ${visible ? '' : '-WindowStyle Hidden'} ${detach} -ArgumentList ${quote(command)}
254
274
  ${wait ? `if (-not $process.WaitForExit(${timeout})) { $process.Kill(); throw '运行超时' }` : ''}
255
275
  $process.Id`;
256
276
  try {
@@ -520,7 +540,7 @@ $task.SetSecurityDescriptor($task.GetSecurityDescriptor(4) + '(A;;GRGX;;;${sid})
520
540
  /** Register the instance task of an account isolated before instances ran as tasks (one elevation prompt). */
521
541
  function register_instance_task(data, account, { run = run_powershell } = {}) {
522
542
  const record = read_os_users(data)[account];
523
- run(`$secure = ConvertTo-SecureString ${quote(record.secret)}
543
+ run(`$secure = ${secure_secret(record.secret)}
524
544
  ${register_task_script(account, record.user, '$secure', owner_sid({ run }))}
525
545
  'ok'`, { elevated: true });
526
546
  }