ai_co_discuss 0.4.29 → 0.4.31
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 +9 -1
- package/package.json +1 -1
- package/runner/account_env.mjs +155 -0
- package/runner/admin_panel.mjs +135 -25
- package/runner/os_users.mjs +55 -14
- package/runner/skill_library.mjs +118 -0
- package/web/admin.css +1 -1
- package/web/admin.js +13 -13
- package/web/modern.js +2 -2
package/docs/runner.md
CHANGED
|
@@ -41,7 +41,15 @@ codiscuss setup
|
|
|
41
41
|
|
|
42
42
|
不选项目目录时,房间使用**草稿空间**:程序在草稿空间里为这个房间单独建一个文件夹(房间名加短编号)并作为它的项目目录,成员生成的文件存在这里,“文件”页可以浏览,成员也可以设为可写。草稿空间默认在服务目录旁(`~/.codiscuss-workspace`)。房间画的图除了作为附件随消息发出,成员对项目目录可写时、或房间在草稿空间时,还会在该目录的 `images/` 下留一份。
|
|
43
43
|
|
|
44
|
-
Windows 上在终端运行 `codiscuss setup` 时,“安装配置”一步有“桌面快捷方式”:还没有时默认勾选“创建‘共议’快捷方式”,已有时显示为“重新生成”、默认不勾(非交互运行不创建);也可随时运行 `codiscuss launcher` 生成或重新生成。它会生成“共议”程序,桌面和开始菜单各有一个快捷方式,双击即可启动服务并打开网站。服务运行时任务栏右下角有共议图标:左键打开**管理面板**(也可运行 `codiscuss panel
|
|
44
|
+
Windows 上在终端运行 `codiscuss setup` 时,“安装配置”一步有“桌面快捷方式”:还没有时默认勾选“创建‘共议’快捷方式”,已有时显示为“重新生成”、默认不勾(非交互运行不创建);也可随时运行 `codiscuss launcher` 生成或重新生成。它会生成“共议”程序,桌面和开始菜单各有一个快捷方式,双击即可启动服务并打开网站。服务运行时任务栏右下角有共议图标:左键打开**管理面板**(也可运行 `codiscuss panel`),右键可打开共议、重启或关闭服务。管理面板的“概览”页显示本机服务状态(可启动、重启、停止)、你自己的 Claude Code / Codex / Antigravity 登录(可直接登录、切换方式、退出;Claude Code 推荐 Setup Token)、检查并安装新版本(同时更新你的房间技能)、开关“登录 Windows 时自动启动”;面板只能在这台电脑上打开。第一次需要在“设置 → 个性化 → 任务栏 → 其他系统托盘图标”里打开“共议”,图标才会常驻任务栏。
|
|
45
|
+
|
|
46
|
+
给别人开账号用这台电脑上的 AI 时,在 setup 的“安装配置”里勾选“托管管理”(或加 `--hosting`,`--no-hosting` 关闭;选择会记住),面板会多出“托管账号”页:
|
|
47
|
+
- 点“新建账号”,填账号名,默认“隔离”(给它一个独立的 Windows 用户,电脑会弹出一次管理员确认);向导会一次装好它要用的程序、房间技能、系统提示词和随包工作流,并启动它的网站,最后显示一次密码。
|
|
48
|
+
- 点某个账号进入它的页面:登录它的命令行、配置 API 密钥、从技能库勾选技能、修改它的系统提示词、启动或停止、重设密码。
|
|
49
|
+
- “技能库”里可以拖入技能文件夹或 .zip,再到账号页选择装给谁。
|
|
50
|
+
- 更新共议时,隔离账号的程序、技能会一起更新,运行中的网站会重启。
|
|
51
|
+
|
|
52
|
+
一般自用不需要打开托管管理。
|
|
45
53
|
|
|
46
54
|
### 浏览项目文件
|
|
47
55
|
|
package/package.json
CHANGED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* The AI environment of the Windows user this runs as: one skills folder and one system prompt shared by Claude Code,
|
|
4
|
+
* Codex and Antigravity, laid out the way the computer owner's own is.
|
|
5
|
+
*
|
|
6
|
+
* skills ~/.agents/skills (Codex reads it as is); ~/.claude/skills is a junction to it; Antigravity lists it in
|
|
7
|
+
* ~/.gemini/config/skills.json.
|
|
8
|
+
* prompt ~/.codex/AGENTS.md; ~/.claude/CLAUDE.md and ~/.gemini/config/AGENTS.md are hard links to the same file.
|
|
9
|
+
*
|
|
10
|
+
* The management panel runs this as a hosted account's own Windows user, from the shared copy of this program, because
|
|
11
|
+
* that user's files are its own and the owner cannot reach them. Usage: node account_env.mjs <action> <job folder>, the job
|
|
12
|
+
* folder holding request.json; prints one JSON line.
|
|
13
|
+
* init lay out the folders, write the prompt if there is none (request.prompt), install the discussion skills
|
|
14
|
+
* (an edited copy is kept) and the shipped workflows the instance lacks (request.home, its service home).
|
|
15
|
+
* status the skills installed, the prompt, and whether the layout is complete.
|
|
16
|
+
* skills install the skill folders in <job>/skills/ (replacing a copy of the same name) and remove request.remove.
|
|
17
|
+
* prompt write request.prompt as the system prompt of all three.
|
|
18
|
+
*/
|
|
19
|
+
import { cpSync, existsSync, linkSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
20
|
+
import { homedir } from 'node:os';
|
|
21
|
+
import { dirname, join, resolve } from 'node:path';
|
|
22
|
+
|
|
23
|
+
import { SKILLS, install_skills, install_workflows, remove_legacy_skills, shipped_workflows } from './discussion_skills.mjs';
|
|
24
|
+
import { workflow_directory } from './workflows.mjs';
|
|
25
|
+
|
|
26
|
+
const HOME = homedir();
|
|
27
|
+
const SKILLS_DIR = join(HOME, '.agents', 'skills');
|
|
28
|
+
const CLAUDE_SKILLS = join(HOME, '.claude', 'skills');
|
|
29
|
+
const AGY_SKILL_CONFIG = join(HOME, '.gemini', 'config', 'skills.json');
|
|
30
|
+
// A folder an earlier version of the panel filled with its own copies; they move into the shared folder.
|
|
31
|
+
const OLD_AGY_SKILLS = join(HOME, '.gemini', 'config', 'skills');
|
|
32
|
+
const PROMPT = join(HOME, '.codex', 'AGENTS.md');
|
|
33
|
+
const PROMPT_LINKS = [join(HOME, '.claude', 'CLAUDE.md'), join(HOME, '.gemini', 'config', 'AGENTS.md')];
|
|
34
|
+
const RECORD = 'skills-manifest.json';
|
|
35
|
+
const SKILL_NAME = /^[\w.-]{1,64}$/;
|
|
36
|
+
|
|
37
|
+
// ---- Layout ----
|
|
38
|
+
|
|
39
|
+
function is_link(path) {
|
|
40
|
+
try { return lstatSync(path).isSymbolicLink(); } catch { return false; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Make ~/.claude/skills a junction to the shared folder, first moving in anything a real folder there held. */
|
|
44
|
+
function link_claude_skills() {
|
|
45
|
+
if (is_link(CLAUDE_SKILLS) && resolve(readlinkSync(CLAUDE_SKILLS)).toLowerCase() === resolve(SKILLS_DIR).toLowerCase()) return;
|
|
46
|
+
if (existsSync(CLAUDE_SKILLS) && !is_link(CLAUDE_SKILLS)) {
|
|
47
|
+
for (const name of readdirSync(CLAUDE_SKILLS)) {
|
|
48
|
+
const target = join(SKILLS_DIR, name);
|
|
49
|
+
if (!existsSync(target)) renameSync(join(CLAUDE_SKILLS, name), target);
|
|
50
|
+
}
|
|
51
|
+
rmSync(CLAUDE_SKILLS, { recursive: true, force: true });
|
|
52
|
+
} else if (is_link(CLAUDE_SKILLS)) unlinkSync(CLAUDE_SKILLS);
|
|
53
|
+
mkdirSync(dirname(CLAUDE_SKILLS), { recursive: true });
|
|
54
|
+
// A junction needs no administrator rights, unlike a symbolic link.
|
|
55
|
+
symlinkSync(SKILLS_DIR, CLAUDE_SKILLS, 'junction');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** List the shared folder in Antigravity's skills.json, keeping any other entries. */
|
|
59
|
+
function list_for_agy() {
|
|
60
|
+
let config = {};
|
|
61
|
+
try { config = JSON.parse(readFileSync(AGY_SKILL_CONFIG, 'utf8')); } catch { config = {}; }
|
|
62
|
+
const entries = Array.isArray(config.entries) ? config.entries : [];
|
|
63
|
+
const path = SKILLS_DIR.replaceAll('\\', '/');
|
|
64
|
+
if (entries.some(entry => String(entry?.path || '').replaceAll('\\', '/').toLowerCase() === path.toLowerCase())) return;
|
|
65
|
+
mkdirSync(dirname(AGY_SKILL_CONFIG), { recursive: true });
|
|
66
|
+
writeFileSync(AGY_SKILL_CONFIG, `${JSON.stringify({ ...config, entries: [...entries, { path }] }, null, 2)}\n`);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Make the two other prompt files hard links to the one prompt, keeping the prompt's text. */
|
|
70
|
+
function link_prompts(fallback = '') {
|
|
71
|
+
mkdirSync(dirname(PROMPT), { recursive: true });
|
|
72
|
+
if (!existsSync(PROMPT)) writeFileSync(PROMPT, fallback);
|
|
73
|
+
for (const path of PROMPT_LINKS) {
|
|
74
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
75
|
+
if (existsSync(path)) {
|
|
76
|
+
if (lstatSync(path).ino === lstatSync(PROMPT).ino) continue;
|
|
77
|
+
unlinkSync(path);
|
|
78
|
+
}
|
|
79
|
+
linkSync(PROMPT, path);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function layout_status() {
|
|
84
|
+
const prompt_inode = existsSync(PROMPT) ? lstatSync(PROMPT).ino : -1;
|
|
85
|
+
let agy = false;
|
|
86
|
+
try { agy = JSON.parse(readFileSync(AGY_SKILL_CONFIG, 'utf8')).entries.some(entry => String(entry.path).replaceAll('\\', '/').toLowerCase() === SKILLS_DIR.replaceAll('\\', '/').toLowerCase()); } catch { agy = false; }
|
|
87
|
+
return { skills_folder: existsSync(SKILLS_DIR), claude_linked: is_link(CLAUDE_SKILLS), agy_listed: agy,
|
|
88
|
+
prompt_linked: prompt_inode !== -1 && PROMPT_LINKS.every(path => existsSync(path) && lstatSync(path).ino === prompt_inode) };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ---- Actions ----
|
|
92
|
+
|
|
93
|
+
function init(request) {
|
|
94
|
+
mkdirSync(SKILLS_DIR, { recursive: true });
|
|
95
|
+
const record = join(request.home, RECORD);
|
|
96
|
+
// Copies an earlier version put in Antigravity's own folder go, unless someone edited them; the shared folder has them.
|
|
97
|
+
remove_legacy_skills(OLD_AGY_SKILLS, record);
|
|
98
|
+
link_claude_skills();
|
|
99
|
+
list_for_agy();
|
|
100
|
+
link_prompts(String(request.prompt || ''));
|
|
101
|
+
const results = install_skills(SKILLS_DIR, record);
|
|
102
|
+
const missing = shipped_workflows().map(item => item.name).filter(name => !existsSync(workflow_directory(request.home, name)));
|
|
103
|
+
const workflows = (missing.length ? install_workflows(request.home, missing) : []).map(({ name, status }) => ({ name, status }));
|
|
104
|
+
return { skills: results.map(({ name, status }) => ({ name, status })), workflows, layout: layout_status() };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A skill's one-line description, from the front matter of its SKILL.md. */
|
|
108
|
+
function describe(folder) {
|
|
109
|
+
try {
|
|
110
|
+
const text = readFileSync(join(folder, 'SKILL.md'), 'utf8');
|
|
111
|
+
return text.match(/^description:\s*(.+)$/m)?.[1].replace(/^["']|["']$/g, '').trim().slice(0, 200) || '';
|
|
112
|
+
} catch { return ''; }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function status() {
|
|
116
|
+
const skills = existsSync(SKILLS_DIR) ? readdirSync(SKILLS_DIR, { withFileTypes: true }).filter(entry => entry.isDirectory() || entry.isSymbolicLink())
|
|
117
|
+
.map(entry => ({ name: entry.name, discussion: SKILLS.includes(entry.name), description: describe(join(SKILLS_DIR, entry.name)) })) : [];
|
|
118
|
+
return { skills, prompt: existsSync(PROMPT) ? readFileSync(PROMPT, 'utf8') : '', layout: layout_status() };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function skills(job, request) {
|
|
122
|
+
mkdirSync(SKILLS_DIR, { recursive: true });
|
|
123
|
+
const incoming = join(job, 'skills'), installed = [], removed = [];
|
|
124
|
+
for (const name of existsSync(incoming) ? readdirSync(incoming) : []) {
|
|
125
|
+
if (!SKILL_NAME.test(name)) continue;
|
|
126
|
+
rmSync(join(SKILLS_DIR, name), { recursive: true, force: true });
|
|
127
|
+
cpSync(join(incoming, name), join(SKILLS_DIR, name), { recursive: true });
|
|
128
|
+
installed.push(name);
|
|
129
|
+
}
|
|
130
|
+
for (const name of Array.isArray(request.remove) ? request.remove : []) {
|
|
131
|
+
if (!SKILL_NAME.test(name) || !existsSync(join(SKILLS_DIR, name))) continue;
|
|
132
|
+
rmSync(join(SKILLS_DIR, name), { recursive: true, force: true });
|
|
133
|
+
removed.push(name);
|
|
134
|
+
}
|
|
135
|
+
return { installed, removed };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function prompt(request) {
|
|
139
|
+
link_prompts();
|
|
140
|
+
// Writing in place keeps the hard links: all three names point at this one file.
|
|
141
|
+
writeFileSync(PROMPT, String(request.prompt || ''));
|
|
142
|
+
return { ok: true, layout: layout_status() };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function main() {
|
|
146
|
+
const [action, job] = process.argv.slice(2);
|
|
147
|
+
const path = join(job, 'request.json');
|
|
148
|
+
const request = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
|
|
149
|
+
rmSync(path, { force: true });
|
|
150
|
+
const run = { init, status, skills: () => skills(job, request), prompt }[action];
|
|
151
|
+
if (!run) throw new Error(`未知操作:${action}`);
|
|
152
|
+
process.stdout.write(`${JSON.stringify(run(request))}\n`);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
try { main(); } catch (error) { process.stdout.write(`${JSON.stringify({ error: error.message })}\n`); process.exitCode = 1; }
|
package/runner/admin_panel.mjs
CHANGED
|
@@ -19,7 +19,9 @@ import { parseArgs } from 'node:util';
|
|
|
19
19
|
import { account_home, add_account, data_home, instance_home, read_accounts, remove_account, reset_password } from '../gateway/gateway.mjs';
|
|
20
20
|
import { API_PROVIDERS, save_api_key } from './discussion_api.mjs';
|
|
21
21
|
import { apply_login, cancel_login, LOGIN_METHODS, login_progress, login_status, logout, start_login, submit_login } from './cli_login.mjs';
|
|
22
|
-
import { create_os_user,
|
|
22
|
+
import { create_os_user, install_shared_runtime, read_os_users, remove_os_user, run_as_user, shared_cli_state, shared_executables, shared_paths, start_instance_as_user } from './os_users.mjs';
|
|
23
|
+
import { install_workflows, shipped_workflows } from './discussion_skills.mjs';
|
|
24
|
+
import { hosted_prompt, import_skill, library_root, list_library, remove_library_skill, save_hosted_prompt } from './skill_library.mjs';
|
|
23
25
|
import { local_status } from './discussion_local.mjs';
|
|
24
26
|
import { autostart_enabled, launcher_path, set_autostart } from './launcher.mjs';
|
|
25
27
|
import { show_tray } from './tray.mjs';
|
|
@@ -34,8 +36,13 @@ const LATEST_URL = `https://registry.npmjs.org/${NPM_PACKAGE}/latest`;
|
|
|
34
36
|
const LATEST_TTL_MS = 60 * 60 * 1000;
|
|
35
37
|
const LATEST_TIMEOUT_MS = 8000;
|
|
36
38
|
const STATE_FILE = 'admin-panel.json';
|
|
39
|
+
// Where account_env.mjs (and setup) record the skills they installed, in the service home.
|
|
40
|
+
const SKILL_RECORD = 'skills-manifest.json';
|
|
41
|
+
// How a panel started by an update receives its predecessor's key and sessions (only that child process sees it).
|
|
42
|
+
const HANDOVER_VARIABLE = 'CODISCUSS_PANEL_HANDOVER';
|
|
37
43
|
const SESSION_COOKIE = 'codiscuss_panel';
|
|
38
44
|
const BODY_LIMIT = 64 * 1024;
|
|
45
|
+
const UPLOAD_LIMIT = 40 * 1024 * 1024;
|
|
39
46
|
const PROBE_TIMEOUT_MS = 1500;
|
|
40
47
|
const STATIC_FILES = { '/': 'admin.html', '/admin.html': 'admin.html', '/admin.js': 'admin.js', '/admin.css': 'admin.css', '/mark.svg': 'mark.svg' };
|
|
41
48
|
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
|
|
@@ -84,20 +91,35 @@ function run_command(command, args) {
|
|
|
84
91
|
child.stdout.on('data', chunk => { output = (output + chunk).slice(-4000); });
|
|
85
92
|
child.stderr.on('data', chunk => { output = (output + chunk).slice(-4000); });
|
|
86
93
|
child.on('error', fail);
|
|
87
|
-
child.on('exit', code => code === 0 ? done() : fail(new Error(`${command} ${args.join(' ')}
|
|
94
|
+
child.on('exit', code => code === 0 ? done() : fail(Object.assign(new Error(`${command} ${args.join(' ')} 失败(退出码 ${code}):${output.trim().split(/\r?\n/).slice(-3).join(' ')}`), { code })));
|
|
88
95
|
});
|
|
89
96
|
}
|
|
90
97
|
|
|
91
98
|
/**
|
|
92
|
-
* Install a published version
|
|
93
|
-
* the
|
|
99
|
+
* Install a published version and bring everything on this computer onto it, reporting each step: the owner's skills
|
|
100
|
+
* (setup without questions), the owner's service, and with hosting on, the shared copy and every account with its own
|
|
101
|
+
* Windows user (skills, missing workflows, a running instance restarted). A step that fails is reported and the rest go
|
|
102
|
+
* on. The panel itself still runs the old code afterwards; `on_updated` restarts it.
|
|
94
103
|
*/
|
|
95
104
|
async function update_package(data, version, on_updated) {
|
|
96
105
|
await run_command('npm', ['install', '--global', `${NPM_PACKAGE}@${version}`]);
|
|
97
|
-
|
|
98
|
-
|
|
106
|
+
const steps = [`已安装 v${version}`];
|
|
107
|
+
const step = async (done, work) => { try { await work(); steps.push(done); } catch (error) { steps.push(`${done.replace(/^已/, '')}失败:${error.message}`); } };
|
|
108
|
+
await step('已更新本机技能', () => run_command(process.execPath, [installed_script('codiscuss.mjs'), 'setup', '--yes', '--no-start', '--json']).catch(error => {
|
|
109
|
+
// Setup exits 2 when it finished with items to look at (an edited skill is kept, for one); that still counts.
|
|
110
|
+
if (error.code !== 2) throw error;
|
|
111
|
+
}));
|
|
112
|
+
await step('已重启本机服务', async () => { await run_owner_service(data, 'stop'); await run_owner_service(data, 'start'); });
|
|
113
|
+
if (hosting_enabled(data)) {
|
|
114
|
+
await step('已更新共享运行环境', () => { const result = install_runtime(data); if (result.warnings.length) throw new Error(result.warnings.join(';')); });
|
|
115
|
+
for (const account of await list_accounts(data)) {
|
|
116
|
+
if (!account.os_user) continue;
|
|
117
|
+
await step(`已更新 ${account.name} 的技能`, () => prepare_account(data, account.name));
|
|
118
|
+
if (account.running) await step(`已重启 ${account.name} 的实例`, async () => { await run_instance(data, account.name, 'stop'); await run_instance(data, account.name, 'start'); });
|
|
119
|
+
}
|
|
120
|
+
}
|
|
99
121
|
setTimeout(on_updated, 500);
|
|
100
|
-
return { version };
|
|
122
|
+
return { version, steps };
|
|
101
123
|
}
|
|
102
124
|
|
|
103
125
|
// ---- Accounts ----
|
|
@@ -114,25 +136,92 @@ function instance_running(port) {
|
|
|
114
136
|
async function list_accounts(data) {
|
|
115
137
|
const users = read_os_users(data);
|
|
116
138
|
return Promise.all(Object.entries(read_accounts(data)).map(async ([name, account]) => ({ name, port: account.port, home: account_home(data, name),
|
|
117
|
-
os_user: users[name]?.user || '', running: await instance_running(account.port), keys: list_keys(instance_home(data, name)).length
|
|
139
|
+
os_user: users[name]?.user || '', running: await instance_running(account.port), keys: list_keys(instance_home(data, name)).length,
|
|
140
|
+
// The AI environment is set up once account_env.mjs has run for its Windows user (it records skills in the service home).
|
|
141
|
+
skills: Boolean(users[name]) && existsSync(join(instance_home(data, name), SKILL_RECORD)) })));
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function write_settings(path, value) {
|
|
145
|
+
const draft = `${path}.${process.pid}.tmp`;
|
|
146
|
+
writeFileSync(draft, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
|
|
147
|
+
renameSync(draft, path);
|
|
118
148
|
}
|
|
119
149
|
|
|
120
|
-
/** Point the account's command-line members at the shared copies every Windows user can run. */
|
|
150
|
+
/** Point the account's command-line members and its website's Python at the shared copies every Windows user can run. */
|
|
121
151
|
function use_shared_programs(data, name) {
|
|
122
|
-
const
|
|
152
|
+
const service = instance_home(data, name), path = join(service, 'launch-settings.json');
|
|
123
153
|
const settings = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
|
|
124
154
|
const shared = shared_executables(), participants = { ...(settings.participants || {}) };
|
|
125
155
|
for (const [member, profile] of Object.entries(participants)) if (shared[profile?.adapter]) participants[member] = { ...profile, executable: shared[profile.adapter] };
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
156
|
+
write_settings(path, { ...settings, participants });
|
|
157
|
+
const local = join(service, 'local-settings.json'), python = shared_paths().python;
|
|
158
|
+
if (existsSync(local) && existsSync(python)) write_settings(local, { ...JSON.parse(readFileSync(local, 'utf8')), python });
|
|
129
159
|
}
|
|
130
160
|
|
|
131
|
-
/**
|
|
161
|
+
/** The Python the owner's own website runs, which the shared copy is made from. */
|
|
162
|
+
function owner_python(data) {
|
|
163
|
+
try { return JSON.parse(readFileSync(join(data, 'local-settings.json'), 'utf8')).python || ''; } catch { return ''; }
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Copy the shared programs, then point every account with its own Windows user at them. */
|
|
167
|
+
function install_runtime(data) {
|
|
168
|
+
const result = install_shared_runtime(owner_python(data));
|
|
169
|
+
for (const name of Object.keys(read_os_users(data))) if (read_accounts(data)[name]) use_shared_programs(data, name);
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Run account_env.mjs as the account's own Windows user, from the shared copy, and return its JSON answer.
|
|
175
|
+
* `folders` are folders of the owner's copied into the job folder for it (library skills).
|
|
176
|
+
*/
|
|
177
|
+
function account_env(data, name, action, request = {}, folders = {}) {
|
|
178
|
+
const { env_script } = shared_paths();
|
|
179
|
+
if (!existsSync(env_script)) throw new Error('还没有安装共享运行环境,请先在“托管账号”页安装');
|
|
180
|
+
const text = run_as_user(data, name, `& ${ps_quote(process.execPath)} ${ps_quote(env_script)} ${action} $Job`,
|
|
181
|
+
{ files: { 'request.json': JSON.stringify(request) }, folders, timeout: 120_000 });
|
|
182
|
+
const line = text.split(/\r?\n/).reverse().find(item => item.trim().startsWith('{'));
|
|
183
|
+
const result = line ? JSON.parse(line) : { error: text.trim().slice(0, 300) || '没有读到结果' };
|
|
184
|
+
if (result.error) throw new Error(result.error);
|
|
185
|
+
return result;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Set up an account's AI environment, safe to repeat: for an account with its own Windows user, the shared skills folder
|
|
190
|
+
* and system prompt laid out like the owner's, the discussion skills, and the shipped workflows its instance lacks (an
|
|
191
|
+
* existing prompt and workflows are kept). One without its own user uses the owner's, so only its workflows are filled in.
|
|
192
|
+
*/
|
|
193
|
+
function prepare_account(data, name) {
|
|
194
|
+
const service = instance_home(data, name);
|
|
195
|
+
if (!read_os_users(data)[name]) {
|
|
196
|
+
const missing = shipped_workflows().map(item => item.name).filter(item => !existsSync(join(service, 'workflows', item)));
|
|
197
|
+
return { skills: [], workflows: (missing.length ? install_workflows(service, missing) : []).map(({ name: item, status }) => ({ name: item, status })) };
|
|
198
|
+
}
|
|
199
|
+
return account_env(data, name, 'init', { home: service, prompt: hosted_prompt(data) });
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Install library skills for an account's own Windows user and remove others: { install: [name], remove: [name] }. */
|
|
203
|
+
function account_skills(data, name, { install = [], remove = [] } = {}) {
|
|
204
|
+
const library = library_root(data), folders = {};
|
|
205
|
+
for (const skill of install) {
|
|
206
|
+
if (!existsSync(join(library, String(skill), 'SKILL.md'))) throw new Error(`技能库里没有 ${skill}`);
|
|
207
|
+
folders[join('skills', String(skill))] = join(library, String(skill));
|
|
208
|
+
}
|
|
209
|
+
return account_env(data, name, 'skills', { remove }, folders);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const ps_quote = text => `'${String(text).replaceAll("'", "''")}'`;
|
|
213
|
+
|
|
214
|
+
/** Start or stop an account's instance: as its Windows user from the shared copy when it has one, otherwise as the owner. */
|
|
132
215
|
function run_instance(data, name, command) {
|
|
133
216
|
if (!read_accounts(data)[name]) throw new Error(`账号不存在:${name}`);
|
|
134
217
|
const service = instance_home(data, name);
|
|
135
|
-
if (command === 'start' && read_os_users(data)[name])
|
|
218
|
+
if (command === 'start' && read_os_users(data)[name]) {
|
|
219
|
+
const { local_script } = shared_paths();
|
|
220
|
+
if (!existsSync(local_script)) throw new Error('还没有安装共享运行环境,请先在“托管账号”页安装');
|
|
221
|
+
// Whatever was set up first, the instance starts on the shared copies its Windows user can run.
|
|
222
|
+
use_shared_programs(data, name);
|
|
223
|
+
return start_instance_as_user(data, name, service, local_script);
|
|
224
|
+
}
|
|
136
225
|
const child = spawn(process.execPath, [LOCAL_SCRIPT, command, '--json'], { stdio: 'ignore', windowsHide: true, env: { ...process.env, DISCUSS_SERVICE_HOME: service } });
|
|
137
226
|
return new Promise((done, fail) => {
|
|
138
227
|
child.on('error', fail);
|
|
@@ -169,10 +258,10 @@ function send_json(response, status, value) {
|
|
|
169
258
|
response.end(JSON.stringify(value));
|
|
170
259
|
}
|
|
171
260
|
|
|
172
|
-
function read_body(request) {
|
|
261
|
+
function read_body(request, limit = BODY_LIMIT) {
|
|
173
262
|
return new Promise((done, fail) => {
|
|
174
263
|
let size = 0; const chunks = [];
|
|
175
|
-
request.on('data', chunk => { size += chunk.length; if (size >
|
|
264
|
+
request.on('data', chunk => { size += chunk.length; if (size > limit) { fail(new Error(limit > BODY_LIMIT ? '技能太大(上限 40 MB)' : '请求过大')); request.destroy(); } else chunks.push(chunk); });
|
|
176
265
|
request.on('end', () => { try { done(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } catch { fail(new Error('请求不是 JSON')); } });
|
|
177
266
|
request.on('error', fail);
|
|
178
267
|
});
|
|
@@ -191,10 +280,9 @@ function cookie(request, name) {
|
|
|
191
280
|
* port: The port this server listens on, so only requests addressed to it as a local page are accepted.
|
|
192
281
|
* ops: Injected for tests; defaults to the real account and Windows operations.
|
|
193
282
|
*/
|
|
194
|
-
export function create_panel({ data, key, port, ops = {} }) {
|
|
195
|
-
const sessions = new Set();
|
|
283
|
+
export function create_panel({ data, key, port, ops = {}, sessions = new Set() }) {
|
|
196
284
|
const op = { list_accounts, add_account, reset_password, remove_account, run_instance, create_os_user, remove_os_user,
|
|
197
|
-
login_status, apply_login, logout, start_login, login_progress, submit_login, cancel_login,
|
|
285
|
+
login_status, apply_login, logout, start_login, login_progress, submit_login, cancel_login, install_runtime, prepare_account, account_env, account_skills, shared_cli_state,
|
|
198
286
|
save_api_key, list_keys, remove_key, use_shared_programs, service_overview, run_owner_service, latest_version, update_package,
|
|
199
287
|
autostart_enabled, set_autostart, on_updated: () => {}, ...ops };
|
|
200
288
|
const hosts = new Set([`127.0.0.1:${port}`, `localhost:${port}`]);
|
|
@@ -239,7 +327,17 @@ export function create_panel({ data, key, port, ops = {} }) {
|
|
|
239
327
|
}
|
|
240
328
|
// Hosting: only once the owner turned it on in setup.
|
|
241
329
|
if (!hosting) throw new Error('托管管理未打开:运行 codiscuss setup 勾选“托管管理(管理面板)”');
|
|
242
|
-
if (method === 'POST' && section === 'clis' && name === 'install') return op.
|
|
330
|
+
if (method === 'POST' && section === 'clis' && name === 'install') return op.install_runtime(data);
|
|
331
|
+
// The skill library and the default system prompt, both the owner's, for hosted accounts.
|
|
332
|
+
if (section === 'skill-library') {
|
|
333
|
+
if (method === 'GET') return list_library(data);
|
|
334
|
+
if (method === 'POST' && !name) return import_skill(data, body);
|
|
335
|
+
if (method === 'POST' && action === 'remove') { remove_library_skill(data, name); return { ok: true }; }
|
|
336
|
+
}
|
|
337
|
+
if (section === 'hosted-prompt') {
|
|
338
|
+
if (method === 'GET') return { text: hosted_prompt(data) };
|
|
339
|
+
if (method === 'POST') { save_hosted_prompt(data, body.text); return { ok: true }; }
|
|
340
|
+
}
|
|
243
341
|
if (section !== 'accounts') throw new Error('接口不存在');
|
|
244
342
|
if (method === 'POST' && !name) return op.add_account(data, String(body.name || '').trim());
|
|
245
343
|
account();
|
|
@@ -252,6 +350,11 @@ export function create_panel({ data, key, port, ops = {} }) {
|
|
|
252
350
|
op.use_shared_programs(data, name);
|
|
253
351
|
return result;
|
|
254
352
|
}
|
|
353
|
+
// Its AI environment: set up (safe to repeat), what is installed, chosen library skills, its system prompt.
|
|
354
|
+
if (method === 'POST' && action === 'env' && extra === 'init') return op.prepare_account(data, name);
|
|
355
|
+
if (method === 'GET' && action === 'env') return op.account_env(data, name, 'status');
|
|
356
|
+
if (method === 'POST' && action === 'env' && extra === 'skills') return op.account_skills(data, name, { install: body.install || [], remove: body.remove || [] });
|
|
357
|
+
if (method === 'POST' && action === 'env' && extra === 'prompt') return op.account_env(data, name, 'prompt', { prompt: String(body.text ?? '') });
|
|
255
358
|
const service = instance_home(data, name);
|
|
256
359
|
if (method === 'GET' && action === 'keys') return op.list_keys(service);
|
|
257
360
|
if (method === 'POST' && action === 'keys' && extra === 'remove') { op.remove_key(service, String(body.ref || '')); return { ok: true }; }
|
|
@@ -279,7 +382,8 @@ export function create_panel({ data, key, port, ops = {} }) {
|
|
|
279
382
|
if (request.method !== 'GET' && (!origin || !hosts.has(origin.replace(/^http:\/\//, '')) || request.headers['x-codiscuss-panel'] !== '1')) {
|
|
280
383
|
return send_json(response, 403, { error: '拒绝跨站请求' });
|
|
281
384
|
}
|
|
282
|
-
|
|
385
|
+
// A dropped skill arrives whole (its files in base64), so that one request may be large.
|
|
386
|
+
const body = request.method === 'POST' ? await read_body(request, url.pathname === '/api/skill-library' ? UPLOAD_LIMIT : BODY_LIMIT) : {};
|
|
283
387
|
return send_json(response, 200, await api(request.method, url.pathname, body));
|
|
284
388
|
}
|
|
285
389
|
const name = STATIC_FILES[url.pathname] || (url.pathname.startsWith('/icons/') && /^\/icons\/[\w.-]+$/.test(url.pathname) ? url.pathname.slice(1) : '');
|
|
@@ -389,14 +493,20 @@ export function hosting_enabled(data) {
|
|
|
389
493
|
function run_panel(data, port) {
|
|
390
494
|
const running = read_state(data);
|
|
391
495
|
if (running && running.pid !== process.pid && alive(running.pid)) throw new Error(`管理面板已在运行:http://127.0.0.1:${running.port}`);
|
|
392
|
-
|
|
496
|
+
// A panel started by an update takes over its predecessor's key and sessions, so the open window keeps working.
|
|
497
|
+
let handover = {};
|
|
498
|
+
try { handover = JSON.parse(process.env[HANDOVER_VARIABLE] || '{}'); } catch { handover = {}; }
|
|
499
|
+
delete process.env[HANDOVER_VARIABLE];
|
|
500
|
+
const state = { pid: process.pid, port, key: handover.key || randomBytes(24).toString('hex'), version: VERSION };
|
|
501
|
+
const sessions = new Set(Array.isArray(handover.sessions) ? handover.sessions : []);
|
|
393
502
|
// After an update this process still runs the old code: it steps aside and starts the newly installed panel.
|
|
394
503
|
const on_updated = () => {
|
|
395
504
|
shutdown(false);
|
|
396
|
-
spawn(process.execPath, [installed_script('admin_panel.mjs'), 'start', '--data', data, '--port', String(port)], { detached: true, stdio: 'ignore', windowsHide: true
|
|
505
|
+
spawn(process.execPath, [installed_script('admin_panel.mjs'), 'start', '--data', data, '--port', String(port)], { detached: true, stdio: 'ignore', windowsHide: true,
|
|
506
|
+
env: { ...process.env, [HANDOVER_VARIABLE]: JSON.stringify({ key: state.key, sessions: [...sessions] }) } }).unref();
|
|
397
507
|
setTimeout(() => process.exit(0), 300);
|
|
398
508
|
};
|
|
399
|
-
const server = create_panel({ data, key: state.key, port, ops: { on_updated } });
|
|
509
|
+
const server = create_panel({ data, key: state.key, port, ops: { on_updated }, sessions });
|
|
400
510
|
server.listen(port, '127.0.0.1', () => {
|
|
401
511
|
writeFileSync(state_path(data), JSON.stringify(state), { mode: 0o600 });
|
|
402
512
|
process.stdout.write(`管理面板已启动:http://127.0.0.1:${port}\n`);
|
package/runner/os_users.mjs
CHANGED
|
@@ -12,7 +12,8 @@ import { spawnSync } from 'node:child_process';
|
|
|
12
12
|
import { randomBytes } from 'node:crypto';
|
|
13
13
|
import { cpSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
14
14
|
import { homedir } from 'node:os';
|
|
15
|
-
import { dirname, join } from 'node:path';
|
|
15
|
+
import { basename, dirname, join } from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
16
17
|
|
|
17
18
|
const USERS_FILE = 'os-users.json';
|
|
18
19
|
const USER_PREFIX = 'cd-';
|
|
@@ -20,6 +21,13 @@ const USER_PREFIX = 'cd-';
|
|
|
20
21
|
const MAX_USER_NAME = 20;
|
|
21
22
|
const SHARED_ROOT = join(process.env.ProgramData || 'C:\\ProgramData', 'CoDiscuss');
|
|
22
23
|
const CLI_ROOT = join(SHARED_ROOT, 'cli');
|
|
24
|
+
const APP_ROOT = join(SHARED_ROOT, 'app');
|
|
25
|
+
const PYTHON_ROOT = join(SHARED_ROOT, 'python');
|
|
26
|
+
const PACKAGE_ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
|
27
|
+
// What an account's instance runs from the shared copy of this program.
|
|
28
|
+
const APP_PARTS = ['package.json', 'server.py', 'runner', 'gateway', 'backend', 'web', '.agents', 'workflows'];
|
|
29
|
+
// Parts of a Python installation the website does not need; site-packages is most of its size.
|
|
30
|
+
const PYTHON_SKIP = new Set(['site-packages', 'Doc', 'include', 'libs', 'tcl', 'share', 'Scripts', 'test', 'idlelib', 'tkinter', 'turtledemo', '__pycache__']);
|
|
23
31
|
const JOB_ROOT = join(SHARED_ROOT, 'jobs');
|
|
24
32
|
const POWERSHELL = 'powershell.exe';
|
|
25
33
|
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
@@ -150,15 +158,17 @@ function job_folder(user) {
|
|
|
150
158
|
* Start a PowerShell script as the account's user.
|
|
151
159
|
*
|
|
152
160
|
* Args:
|
|
153
|
-
* script: Runs with $Job set to its job folder; input files can be placed there first through `files
|
|
161
|
+
* script: Runs with $Job set to its job folder; input files can be placed there first through `files` (name → text)
|
|
162
|
+
* and `folders` (name → a folder of the owner's, copied in, as the account's user cannot read the owner's files).
|
|
154
163
|
* visible: Show its window on this desktop instead of running hidden (for programs that need a person to type).
|
|
155
164
|
* wait: Wait for it and return its output; otherwise return { folder } at once, and the caller reads output.txt later.
|
|
156
165
|
*/
|
|
157
|
-
export function run_as_user(data, account, script, { files = {}, visible = false, wait = true, timeout = DEFAULT_TIMEOUT_MS, run = run_powershell } = {}) {
|
|
166
|
+
export function run_as_user(data, account, script, { files = {}, folders = {}, visible = false, wait = true, timeout = DEFAULT_TIMEOUT_MS, run = run_powershell } = {}) {
|
|
158
167
|
const record = read_os_users(data)[account];
|
|
159
|
-
if (!record) throw new Error(`账号 ${account} 还没有 Windows
|
|
168
|
+
if (!record) throw new Error(`账号 ${account} 还没有 Windows 用户,请先隔离这个账号`);
|
|
160
169
|
const folder = job_folder(record.user);
|
|
161
170
|
for (const [name, text] of Object.entries(files)) writeFileSync(join(folder, name), text, 'utf8');
|
|
171
|
+
for (const [name, source] of Object.entries(folders)) cpSync(source, join(folder, name), { recursive: true });
|
|
162
172
|
const job = join(folder, 'job.ps1'), output = join(folder, 'output.txt');
|
|
163
173
|
writeFileSync(job, `\ufeff[Console]::OutputEncoding = [Text.Encoding]::UTF8\n$Job = ${quote(folder)}\n${script}\n`, 'utf8');
|
|
164
174
|
const command = visible ? `-NoProfile -ExecutionPolicy Bypass -NoExit -File ${quote(job)}`
|
|
@@ -171,7 +181,10 @@ $process.Id`;
|
|
|
171
181
|
run(start, { timeout: timeout + 10_000 });
|
|
172
182
|
if (!wait) return { folder, output };
|
|
173
183
|
return existsSync(output) ? read_output(output).trim() : '';
|
|
174
|
-
} finally {
|
|
184
|
+
} finally {
|
|
185
|
+
// A program the script started may still hold the folder; the job's result does not depend on removing it.
|
|
186
|
+
if (wait) try { rmSync(folder, { recursive: true, force: true }); } catch { /* left for the next cleanup */ }
|
|
187
|
+
}
|
|
175
188
|
}
|
|
176
189
|
|
|
177
190
|
/**
|
|
@@ -184,26 +197,52 @@ export function read_output(path) {
|
|
|
184
197
|
return bytes.toString('utf8').replace(/^/, '');
|
|
185
198
|
}
|
|
186
199
|
|
|
200
|
+
/** Where the shared copies of this program and of Python are, for accounts with their own Windows user. */
|
|
201
|
+
export function shared_paths() {
|
|
202
|
+
return { app: APP_ROOT, local_script: join(APP_ROOT, 'runner', 'discussion_local.mjs'), env_script: join(APP_ROOT, 'runner', 'account_env.mjs'),
|
|
203
|
+
python: join(PYTHON_ROOT, 'python.exe') };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Copy a folder over an older copy, reporting a file in use (a running instance holds Python) instead of failing. */
|
|
207
|
+
function copy_over(source, target, filter) {
|
|
208
|
+
try { cpSync(source, target, { recursive: true, force: true, filter }); return ''; }
|
|
209
|
+
catch (error) { return error.code === 'EBUSY' || error.code === 'EPERM' ? '部分文件正被运行中的实例使用,停止实例后再更新一次' : error.message; }
|
|
210
|
+
}
|
|
211
|
+
|
|
187
212
|
/**
|
|
188
|
-
* Copy
|
|
213
|
+
* Copy what an account's own Windows user needs to run to a folder every user can read: the owner's command-line
|
|
214
|
+
* programs, this program (the owner's npm folder is inside the owner's profile, which other users cannot open) and the
|
|
215
|
+
* Python the owner's instance uses, without its third-party packages, tests and documentation (the website needs only
|
|
216
|
+
* the standard library).
|
|
189
217
|
*
|
|
190
218
|
* Returns:
|
|
191
|
-
* { installed: [label], missing: [label] }.
|
|
219
|
+
* { installed: [label], missing: [label], warnings: [text] }.
|
|
192
220
|
*/
|
|
193
|
-
export function
|
|
194
|
-
const installed = [], missing = [];
|
|
221
|
+
export function install_shared_runtime(python_source = '') {
|
|
222
|
+
const installed = [], missing = [], warnings = [];
|
|
195
223
|
for (const cli of Object.values(cli_sources())) {
|
|
196
224
|
if (!existsSync(cli.source)) { missing.push(cli.label); continue; }
|
|
197
225
|
mkdirSync(dirname(cli.target), { recursive: true });
|
|
198
|
-
|
|
199
|
-
installed.push(cli.label);
|
|
226
|
+
const failed = cli.folder ? copy_over(cli.source, cli.target) : (() => { try { cpSync(cli.source, cli.target, { force: true }); return ''; } catch (error) { return error.message; } })();
|
|
227
|
+
if (failed) warnings.push(`${cli.label}:${failed}`); else installed.push(cli.label);
|
|
200
228
|
}
|
|
201
|
-
|
|
229
|
+
mkdirSync(APP_ROOT, { recursive: true });
|
|
230
|
+
const app_failed = APP_PARTS.filter(part => existsSync(join(PACKAGE_ROOT, part))).map(part => copy_over(join(PACKAGE_ROOT, part), join(APP_ROOT, part))).find(Boolean);
|
|
231
|
+
if (app_failed) warnings.push(`共议程序:${app_failed}`); else installed.push('共议程序');
|
|
232
|
+
if (python_source && existsSync(python_source)) {
|
|
233
|
+
const failed = copy_over(dirname(python_source), PYTHON_ROOT, source => !PYTHON_SKIP.has(basename(source)));
|
|
234
|
+
if (failed) warnings.push(`Python:${failed}`); else installed.push('Python');
|
|
235
|
+
} else missing.push('Python');
|
|
236
|
+
return { installed, missing, warnings };
|
|
202
237
|
}
|
|
203
238
|
|
|
204
|
-
/** Which shared programs are installed: { claude, codex, agy } booleans. */
|
|
239
|
+
/** Which shared programs are installed: { claude, codex, agy, app, python } booleans, and the shared program's version. */
|
|
205
240
|
export function shared_cli_state() {
|
|
206
|
-
|
|
241
|
+
const paths = shared_paths();
|
|
242
|
+
let app_version = '';
|
|
243
|
+
try { app_version = JSON.parse(readFileSync(join(APP_ROOT, 'package.json'), 'utf8')).version; } catch { /* not installed */ }
|
|
244
|
+
return { ...Object.fromEntries(Object.entries(cli_sources()).map(([key, cli]) => [key, existsSync(cli.executable || cli.target)])),
|
|
245
|
+
app: existsSync(paths.local_script), python: existsSync(paths.python), app_version };
|
|
207
246
|
}
|
|
208
247
|
|
|
209
248
|
/**
|
|
@@ -212,6 +251,8 @@ export function shared_cli_state() {
|
|
|
212
251
|
* The instance supervisor runs with the account's service directory; it keeps running after this returns.
|
|
213
252
|
*/
|
|
214
253
|
export function start_instance_as_user(data, account, service_home, local_script, node = process.execPath, options = {}) {
|
|
254
|
+
// The instance keeps running in its own folder rather than in the job folder, which is removed afterwards.
|
|
215
255
|
run_as_user(data, account, `$env:DISCUSS_SERVICE_HOME = ${quote(service_home)}
|
|
256
|
+
Set-Location ${quote(service_home)}
|
|
216
257
|
& ${quote(node)} ${quote(local_script)} start --json`, { ...options, timeout: 90_000 });
|
|
217
258
|
}
|