ai_co_discuss 0.4.25 → 0.4.26

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,2310 +1,2320 @@
1
- /** Shared launch configuration for an existing AI conversation and the local website. */
2
- import { spawn } from 'node:child_process';
3
- import { createHash, randomUUID } from 'node:crypto';
4
- import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from 'node:fs';
5
- import { homedir } from 'node:os';
6
- import { dirname, isAbsolute, join, posix, resolve, win32 } from 'node:path';
7
- import { DatabaseSync } from 'node:sqlite';
8
- import { setTimeout as sleep } from 'node:timers/promises';
9
- import { pathToFileURL } from 'node:url';
10
- import { parseArgs } from 'node:util';
11
-
12
- import { account_projects, account_space, create_account_project, draft_folder } from './account_space.mjs';
13
- import { atomic_json } from './files.mjs';
14
- import { bundle_project_markdown, bundle_project_page, outside_directory, project_media, read_only_enforced, read_project_files, room_directories, search_project_roots } from './project_files.mjs';
15
- import { guard_remote_request, list_remote_directories } from './remote_policy.mjs';
16
- import { list_devices, machine_fingerprint, revoke_device, start_pairing } from './device_auth.mjs';
17
- import { setup_sidecar } from './adapters/antigravity_app.mjs';
18
- import { adapter_of, adoption_adapter, BRANCHABLE_ADAPTERS, branch_session, execution_details, session_settings, software_defaults, software_defaults_stamp, software_effort, software_models, software_skills } from './adapters/index.mjs';
19
- import { ADAPTER_IDS, ADAPTER_PROFILES, adapter_profile, DEFAULT_API_MAX_REQUESTS, MAX_API_MAX_REQUESTS, platform_adapters, same_session_family } from './adapters/profiles.mjs';
20
- import { API_PROVIDERS, api_check, api_models, managed_api_keys, save_api_key, saved_api_keys, validate_api_profile } from './discussion_api.mjs';
21
- import { DEFAULT_SCHEDULER_MODE, SCHEDULER_MODES, SCHEDULER_PROVIDERS, scheduler_check } from './scheduler.mjs';
22
- import { save_tts_settings, tts_release, tts_settings, tts_speak } from './tts.mjs';
23
- import { local_service_stop, local_services } from './tts_providers.mjs';
24
- import { weixin_command } from './weixin.mjs';
25
- import { stt_part } from './stt.mjs';
26
- import { image_settings, room_image, save_image_settings } from './image_service.mjs';
27
- import { open_project } from './adapters/api_files.mjs';
28
- import { run_image_tool } from './adapters/api_images.mjs';
29
- import { access_levels, BUILTIN_EXPERT_PRESETS, MAX_EXPERT_PROMPT, PROJECT_ACCESS } from './expert_prompts.mjs';
30
- import { acquire_lock, api, check_extra_directories, DiscussionStore, service_drafts, validate_config } from './discussion_runner.mjs';
31
- import { FreeRoomRunner, free_task_files } from './free_runner.mjs';
32
- import { assert_workflow_enabled, bind_room_workflow, delete_workflow, get_workflow, list_workflows, load_room_workflow, parse_workflow_draft, preview_workflow, rename_workflow, save_workflow, set_workflow_disabled, workflow_cards, workflow_directory, WORKFLOW_ID_PATTERN } from './workflows.mjs';
33
- import { assert_shared_home, CONNECTION_FIELDS, configuration_snapshot, read_registry, registered_identity, register_room, service_home, service_pid, start_service } from './discussion_service.mjs';
34
-
35
- // A platform is a type; `Claude-review` is another Claude instance with its own session, model and effort. An ID is
36
- // English letters, digits and underscores only; a Chinese name is a display label.
37
- const INSTANCE_PATTERN = /^(Codex|Claude|Antigravity|DeepSeek|Qwen|Grok|OpenAI|Custom)(?:-[0-9A-Za-z_]{1,16})?$/;
38
-
39
- /** The platform of an AI instance name, or null. */
40
- export function platform_of(name) { return typeof name === 'string' ? INSTANCE_PATTERN.exec(name)?.[1] ?? null : null; }
41
-
42
- /** The first unused instance name of a platform: the platform itself, then platform-2, platform-3, …. */
43
- export function next_instance(platform, taken) {
44
- if (!taken.has(platform)) return platform;
45
- for (let number = 2; ; number++) if (!taken.has(`${platform}-${number}`)) return `${platform}-${number}`;
46
- }
47
-
48
- /** A free name from a used one, as the website numbers copies: Codex → Codex-2, Codex-review → Codex-review2. */
49
- function free_instance(name, taken) {
50
- if (!name.includes('-')) return next_instance(name, taken);
51
- for (let number = 2; ; number++) if (!taken.has(`${name}${number}`)) return `${name}${number}`;
52
- }
53
-
54
- /** Supported local clients of an instance's platform. */
55
- function clients_of(name) { return platform_adapters(platform_of(name)); }
56
- const PROFILE_FIELDS = ['adapter', 'executable', 'model', 'effort', 'source_thread_id', 'ipc_directory', 'allowed_tools', 'cwd', 'project_name', 'project_id', 'base_url', 'api_protocol', 'api_key_ref', 'system_prompt'];
57
- // Saved before drawing became the room's switch; read as absent.
58
- const LEGACY_PROFILE_FIELDS = ['image_model'];
59
- const MAX_MINUTES = 1440;
60
- const SESSION_ID_PATTERN = /^[0-9A-Za-z_-]{8,128}$/;
61
- const LOCAL_MEMBERS_FORMAT = 'ai-codiscuss-local-members';
62
- // Reading the inbox proves the owner credential without transferring any messages.
63
- const CONFIG_APPLY_TIMEOUT_MS = 6000;
64
- const CONFIG_APPLY_POLL_MS = 100;
65
- const HELP = `用法:codiscuss launch settings [--file FILE]
66
- codiscuss launch start --file FILE [--dry-run]
67
- codiscuss launch room-config --file FILE
68
- codiscuss launch room-models --file FILE
69
- codiscuss launch room-skills --file FILE
70
- codiscuss launch room-files --file FILE
71
- codiscuss launch room-page --file FILE
72
- codiscuss launch room-media --file FILE
73
- codiscuss launch execution-details --file FILE
74
- codiscuss launch models --file FILE
75
- codiscuss launch api-key --file FILE
76
- codiscuss launch api-check --file FILE
77
- codiscuss launch scheduler-check --file FILE
78
- codiscuss launch image-settings [--file FILE]
79
- codiscuss launch image --file REQUEST [--access-file FILE]
80
- codiscuss launch tts-settings [--file FILE]
81
- codiscuss launch tts --file FILE
82
- codiscuss launch tts-release
83
- codiscuss launch local-speech [--file FILE]
84
- codiscuss launch weixin [--file FILE]
85
- codiscuss launch stt --file FILE
86
- codiscuss launch room-member --file FILE
87
- codiscuss launch room-member-access --file FILE
88
- codiscuss launch room-member-allow --file FILE
89
- codiscuss launch room-member-model --file FILE
90
- codiscuss launch room-member-adapter --file FILE
91
- codiscuss launch room-profiles --file FILE
92
- codiscuss launch room-restore --file FILE
93
- codiscuss launch room-fork --file FILE
94
- codiscuss launch pick-directory
95
- codiscuss launch browse-directory [--file FILE]
96
- codiscuss launch device-pairing [--file FILE]
97
- codiscuss launch devices [--file FILE]
98
- codiscuss launch projects [--file FILE]
99
- codiscuss launch presets [--file FILE]
100
- codiscuss launch machine-link --file FILE
101
- codiscuss launch workflow-adopt (--draft FILE | --id WORKFLOW) [--access-file FILE]
102
- codiscuss launch workflow-join [--card ID[,ID] | --sub SUB] [--access-file FILE]
103
- codiscuss launch workflow-leave --sub SUB [--access-file FILE]
104
- codiscuss launch host-control ACTION [选项] [--access-file FILE]
105
- codiscuss launch workflow-check (--dir DIR | --draft FILE)
106
- codiscuss launch workflow-save (--dir DIR | --draft FILE)
107
-
108
- settings 读取本机软件默认配置;指定文件时保存,不启动 AI。
109
- start 使用启动 JSON 创建或接入房间并启动;--dry-run 只校验和预览。
110
- room-config 修正已暂停房间的软件路径或切换 Codex App / CLI,不启动讨论;须提供 site、room_id、token。
111
- room-models 只读指定 site、room_id 的本机登记模型与思考强度,不启动讨论;quick 为 true 时不查询 agy 的默认模型(较慢),该成员标 defaults_pending。
112
- room-skills 只读指定成员本机安装的技能,须提供 site、room_id、token、name;软件与项目目录只取本机已保存配置,不启动 AI。
113
- room-files 只读房间已保存的项目目录,须提供 site、room_id、token,可选相对 path 和目录分页 offset;文件返回最多前 128 KiB 文本;给 query 时改为按名称搜索整个项目(含 / 时按路径),最多返回 50 项。
114
- room-page 只读项目目录里的一个 HTML 文件(path,可选 root),把它按相对路径引用的样式、脚本、图片、字体与音视频内联为 data URL,以 base64 的 data 返回(最多 8 MiB);Markdown 文件则返回它按相对路径引用的项目图片 {项目路径: data URL} 的 JSON;其他设备经中转时分段返回,按 offset 续读并核对 version;未能载入的引用列在 missing(不存在或在项目目录外)与 skipped(超出大小)。
115
- room-media 核对项目目录里的一个图片、视频或音频文件(path,可选 root)可读:本机网站凭它登记一个 10 分钟有效的播放地址,按 Range 直接读盘,网页拿不到文件路径;其他设备经中转时分段返回 base64 的 data(按 offset 续读并核对 version),最多 64 MB。
116
- execution-details 只读房间某次执行的过程细节(中间说明、命令与输出、搜索、改动、工具调用),由本机日志还原,须提供 site、room_id、token、execution_id;细节只留在本机,不写入网站。
117
- models 按 adapter、executable 或 API profile 读取模型目录,不启动讨论或生成回答。
118
- api-key 将 base_url、api_key 保存于本机私有目录,只返回 api_key_ref。
119
- api-check 用 API profile 向模型发送一次极短请求,核对地址、密钥、协议与模型是否可用。
120
- scheduler-check 用智能调度配置(provider、model、api_key_ref)向决策模型发送一道是非题,核对供应商、模型与密钥是否可用。
121
- image-settings 读取这台电脑的生图服务(base_url、图片模型 model、api_key_ref,configured 表示已配置 Key);内容非空时保存。
122
- image 成员按任务凭据生图(房间须添加了生图卡片):REQUEST 为 JSON,必填 action(generate 生成 / edit 改图)与 prompt;可选 size(auto、1024x1024、1536x1024、1024x1536 或 16 倍数的 宽x高)、quality(auto/low/medium/high,2.5、2.6 系列另有 xhigh/max)、n(1–10 张)、output_format(png/jpeg/webp/gif,生成另可 svg)、background(auto/opaque/transparent)、file_name(附件名)、save_path(另存进可写项目);edit 另需 images(1–16 个 {attachment_id} 或 {file_path},第一张为主图),可加 mask 或 markup(同样格式,二选一)。图片存为成员的附件,返回附件 ID,再用 message post --attachment 附上。
123
- tts-settings 读取朗读设置;内容非空时保存(语音服务 provider:local(本机,由 local-tts-setup 技能安装)/ volcengine / aliyun / azure / openai,语速 speech_rate,以及 providers.<服务> 的 api_key_ref、speaker、member_voices、file_voice,本机、火山引擎与 OpenAI 另有语气提示 context(各自默认不同),Azure 另有 region;语音输入服务 stt_provider:local / volcengine / openai)。
124
- tts 用朗读设置把 text(不超过 300 字)合成为音频(本机服务为 m4a,其余为 MP3),返回 base64。
125
- weixin 微信通知:action 为 status(默认,读取绑定状态)、login(生成扫码内容)、complete(等待扫码确认,约 20 秒)、test(发一条测试通知)或 unbind(解除本机绑定)。Goal 待确认 5 分钟仍未回复时通知房主,房主在微信回复即作为房主发言发回该房间;只用本机服务目录保存凭据。
126
- tts-release 用户停止朗读:所选服务释放在这台电脑上占用的资源(本机语音在 5 秒内结束、释放显存),云端服务无操作。
127
- local-speech 读取本机朗读(tts,yovoice)与语音识别(stt,crispasr)服务的运行状态(state:running / stopped / other(端口被其他程序占用),及 pid、进程名);内容为 {"stop": "tts" | "stt"} 时强行结束该服务(连同子进程),只结束端口上属于该服务程序的进程。
128
- stt 按序接收录音片段(upload_id、index、base64 PCM 16 kHz 单声道、final);最后一段时识别整段录音并返回 text。
129
- pick-directory 在本机弹出系统目录选择窗口,返回所选路径;取消时不返回路径。
130
- browse-directory 列出常用项目及其中的子文件夹(只含文件夹名,分页),供其他设备选择目录;path 为空时列出常用项目。
131
- device-pairing 在本机生成 12 位设备配对码(2 分钟有效,可选 temporary 临时设备、without_passkey 允许这次配对不用通行密钥、site 指定已绑定的网站),扫码链接带本机密钥指纹;只能在这台电脑上执行,新设备只能在电脑前添加。
132
- devices 列出已配对设备;提供 revoke(设备 id)撤销设备。
133
- projects 读取本机已配置的项目(名称与绝对路径);提供 JSON(projects 列表)时整体替换保存。
134
- presets 读取本机的专家预设(含未删除的内置预设)与各平台默认描述;提供 JSON(presets 列表、description_templates 和/或 hidden_builtins 已删除的内置预设名)时替换对应部分。
135
- machine-link 返回本机连接指定 site 的电脑编号、名称与凭据,供已登录管理员的网页完成配对;不存在时创建。
136
- room-member 为房间邀请、请回一位成员;须提供 site、room_id、token、action(add/rejoin)、name。
137
- room-member-access 修改一位本机唤醒成员的项目权限(project_access 为 read/write/auto/full),下次投递起生效、保留原会话;须提供 site、room_id、token、name、project_access。
138
- room-member-allow 把被拒绝的操作加入一位本机唤醒的 Claude Code 或 agy 成员的 allowed_tools,下次投递起生效;须提供 site、room_id、token、name、rules。
139
- room-member-model 修改一位本机唤醒 CLI 或 API 成员的模型与思考强度(空值恢复软件默认;API 成员空模型保留原模型),下次投递起生效、保留原会话;须提供 site、room_id、token、name、model、effort。
140
- room-member-adapter 把自由房间里空闲的 Codex 成员在 App(codex)与 CLI(codex_cli)间切换,保留原会话;须提供 site、room_id、token、name、adapter。
141
- room-profiles 导出房间的本机成员软件配置与实际会话 ID(不含凭据),供备份附带;须提供 site、room_id、token。
142
- room-restore 把导入房间的本机成员配置登记到本机并核对原会话存在,Claude Code 成员保持手动;须提供 site、room_id、token、local_members。
143
- room-fork 把从原房间分支出的新房间登记到本机,各本机成员从原会话分叉、不含分支点之后的执行,原会话不变;须提供 site、room_id、token、source_room_id、source_token、executions({成员名: [排除的执行编号]})。
144
- workflow-adopt 主持人在本房间启用工作流:--draft 把自己的草稿(一段,分段头 1/1)保存进工作流库后启用,--id 启用工作流库里已有的工作流(不改动它);缺的卡片成员由本机服务邀请,项目权限最高可写;须房主已为本房间打开“主持人完整权限”。凭据为本次任务的 access_file(或 DISCUSS_ACCESS_FILE)。
145
- workflow-join 主持人为本房间在用工作流里还没有成员的卡片(启用后才新增的)邀请成员,不填 --card 即全部主线卡片;无需额外授权,离开或移除的成员由用户请回。--sub 改为请进该子工作流的卡片成员(离开的请回原会话)。凭据同上。
146
- workflow-leave 主持人用完子工作流后,把 --sub 子工作流卡片的成员设为离开(会话保留,下次 workflow-join --sub 请回);主线成员不能这样请离。凭据同上。
147
- host-control 主持人代房主控制房间,须房主已为本房间打开“主持人完整权限”,凭据同上;成员用 --member(成员 ID 或显示名),除 retry、model、label 外不能是主持人自己:
148
- 诊断:details --execution N 读取该执行的本机过程日志(服务端详情与事件记录用 execution / room events 读取);
149
- 恢复:stop --member 打断;stop-all 停止全部执行、请求与接力;steer --member --text 话 [--submission-id ID] 向它进行中的执行插话;
150
- retry --execution N 重试失败的执行(含你自己的);model --member [--model M] [--effort E] 改 CLI 或 API 成员的模型与强度(空值恢复默认;API 成员不填模型则保留原模型);
151
- adapter --member --adapter ID 在同一软件的 App 与 CLI 间切换;access --member --access read|write 调整项目权限;
152
- 成员:invite --name 平台 [--access read|write] [--model M] [--effort E] 用本机已配置的软件邀请,项目权限最高可写;
153
- away / remove / back --member 暂离、移除、请回;label --member [--label 显示名] [--description 描述];
154
- 撤回:withdraw --message N 撤回自己的一次派活:接力或循环停下,未开始的请求取消,进行中的停止,不再交回;
155
- 兜底:checkin --minutes N 房间有进行中的工作时每 N 分钟(5–120)给你发一次定时检查,房间空闲、停止全部或换主持人后自动结束;checkin --off 关闭;
156
- 推进:order 读取发言顺序,order --order 甲,乙 --revision REV 调整尚未发言的部分;
157
- discussion 读取讨论,discussion --do start --goal 目标 --revision REV 开启(上限用房间默认值),--do pause|resume|end --revision REV;
158
- goal 读取 Goal,goal --do start --goal 目标 --revision REV 开启(预算用房主默认值,默认不限时为 8 次续跑、90 分钟),--do pause|resume|end --revision REV。
159
- 不开放:批准超出上限的轮数、项目权限高于可写或放行工具、改项目目录、撤回回退用户消息、私聊、对主持人自己的其他操作。
160
- workflow-check 按导入规则校验工作流文件夹或单段草稿,返回预览,不保存;workflow-save 校验后保存进工作流库(同 ID 覆盖),卡片按声明的项目权限保存。写法见 workflow-creator 技能。
161
- JSON 指定 site、entry(conversation/web)、room(建房内容,含 submission_id)
162
- 或 room_id(已有房间)、participants(本次软件覆盖配置)。
163
- conversation 还须 current_session_id,当前会话接手首个主持任务。
164
- 已有受保护房间使用 access_file。路径、凭据只保存在本机。
165
- 详见 docs/runner.md 的“两种讨论入口与启动配置”。
166
- `;
167
-
168
- // Windows PowerShell 5.1 ships WinForms. A background process cannot take the foreground, so the owner must be
169
- // shown (transparent) as a topmost window; the dialog it owns then stays above the browser that asked for it.
170
- // Keep the owner on-screen because the Common Item Dialog positions itself relative to its owner.
171
- // windowsHide turns the process's first Show into a hide, so the owner is shown a second time to really appear.
172
- // Under the local service the whole process chain has no console and no foreground rights: Windows then silently ignores
173
- // SetWindowPos(HWND_TOPMOST) on the dialog (it returns success). So once the dialog exists, a timer in its message loop
174
- // briefly attaches to the foreground window's input thread (the browser that asked) to borrow its right to raise the dialog.
175
- // The C# source must not contain single quotes: it is embedded in a single-quoted PowerShell string.
176
- const PICKER_RAISE_SOURCE = [
177
- 'using System; using System.Runtime.InteropServices;',
178
- 'public static class PickerRaise {',
179
- ' delegate bool EnumProc(IntPtr handle, IntPtr arg);',
180
- ' [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc proc, IntPtr arg);',
181
- ' [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr handle, uint command);',
182
- ' [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr handle, IntPtr after, int x, int y, int width, int height, uint flags);',
183
- ' [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();',
184
- ' [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr handle, IntPtr process);',
185
- ' [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();',
186
- ' [DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool on);',
187
- ' [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr handle);',
188
- ' [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr handle);',
189
- ' public static bool OwnedBy(IntPtr owner) {',
190
- ' IntPtr dialog = IntPtr.Zero;',
191
- ' EnumWindows((handle, arg) => { if (GetWindow(handle, 4) == owner) dialog = handle; return dialog == IntPtr.Zero; }, IntPtr.Zero);',
192
- ' if (dialog == IntPtr.Zero) return false;',
193
- ' uint current = GetCurrentThreadId(), foreground = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);',
194
- ' bool attached = foreground != 0 && foreground != current && AttachThreadInput(current, foreground, true);',
195
- ' SetWindowPos(dialog, (IntPtr)(-1), 0, 0, 0, 0, 0x13); BringWindowToTop(dialog); SetForegroundWindow(dialog);',
196
- ' if (attached) AttachThreadInput(current, foreground, false);',
197
- ' return true;',
198
- ' }',
199
- '}',
200
- ].join(' ');
201
- // Use the Common Item Dialog: unlike Framework WinForms, it has an editable address bar.
202
- // COM declarations retain the native vtable order through the last method used.
203
- const FOLDER_PICKER_SOURCE = `
204
- public static class FolderPicker {
205
- const uint FOS_PICKFOLDERS = 0x20, FOS_FORCEFILESYSTEM = 0x40, FOS_PATHMUSTEXIST = 0x800;
206
- const uint SIGDN_FILESYSPATH = 0x80058000;
207
- const int CANCELLED = unchecked((int)0x800704C7);
208
- [ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
209
- interface IFileDialog {
210
- [PreserveSig] int Show(IntPtr owner);
211
- void SetFileTypes(uint count, IntPtr filters);
212
- void SetFileTypeIndex(uint index);
213
- void GetFileTypeIndex(out uint index);
214
- void Advise(IntPtr events, out uint cookie);
215
- void Unadvise(uint cookie);
216
- void SetOptions(uint options);
217
- void GetOptions(out uint options);
218
- void SetDefaultFolder(IShellItem folder);
219
- void SetFolder(IShellItem folder);
220
- void GetFolder(out IShellItem folder);
221
- void GetCurrentSelection(out IShellItem item);
222
- void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
223
- void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
224
- void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
225
- void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
226
- void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
227
- void GetResult(out IShellItem item);
228
- }
229
- [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
230
- interface IShellItem {
231
- void BindToHandler(IntPtr context, ref Guid handler, ref Guid iid, out IntPtr result);
232
- void GetParent(out IShellItem parent);
233
- void GetDisplayName(uint format, [MarshalAs(UnmanagedType.LPWStr)] out string name);
234
- }
235
- /// <summary>Choose an existing filesystem folder, or return null when cancelled.</summary>
236
- public static string Show(IntPtr owner) {
237
- var dialog = (IFileDialog)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")));
238
- IShellItem item = null;
239
- try {
240
- uint options;
241
- dialog.GetOptions(out options);
242
- dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
243
- dialog.SetTitle("选择项目目录");
244
- int result = dialog.Show(owner);
245
- if (result == CANCELLED) return null;
246
- Marshal.ThrowExceptionForHR(result);
247
- dialog.GetResult(out item);
248
- string path;
249
- item.GetDisplayName(SIGDN_FILESYSPATH, out path);
250
- return path;
251
- } finally {
252
- if (item != null) Marshal.ReleaseComObject(item);
253
- Marshal.ReleaseComObject(dialog);
254
- }
255
- }
256
- }
257
- `;
258
- const WINDOWS_PICKER = [
259
- '$ErrorActionPreference = "Stop"',
260
- 'Add-Type -AssemblyName System.Windows.Forms',
261
- '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
262
- '$owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; Opacity = 0; ShowInTaskbar = $false; FormBorderStyle = "None"; StartPosition = "CenterScreen"; Size = New-Object System.Drawing.Size(1, 1) }',
263
- `Add-Type -TypeDefinition '${PICKER_RAISE_SOURCE} ${FOLDER_PICKER_SOURCE}'`,
264
- '$owner.Show(); $owner.Hide(); $owner.Show(); $owner.Activate()',
265
- '$timer = New-Object System.Windows.Forms.Timer -Property @{ Interval = 150 }; $timer.Add_Tick({ if ([PickerRaise]::OwnedBy($owner.Handle)) { $timer.Stop() } }); $timer.Start()',
266
- 'try { [FolderPicker]::Show($owner.Handle) } finally { $timer.Stop(); $timer.Dispose(); $owner.Close(); $owner.Dispose() }',
267
- ].join('; ');
268
- const PICKERS = {
269
- win32: ['powershell.exe', ['-NoProfile', '-STA', '-Command', WINDOWS_PICKER]],
270
- darwin: ['osascript', ['-e', 'POSIX path of (choose folder with prompt "选择项目目录")']],
271
- linux: ['zenity', ['--file-selection', '--directory', '--title=选择项目目录']],
272
- };
273
-
274
- /** Show the platform's own folder dialog on this computer; cancelling resolves without a path. */
275
- export function pick_directory({ platform = process.platform, spawn_process = spawn } = {}) {
276
- const picker = PICKERS[platform];
277
- if (!picker) return Promise.reject(new Error('此系统不支持目录选择窗口,请直接输入完整路径'));
278
- return new Promise((resolve_result, reject) => {
279
- const child = spawn_process(picker[0], picker[1], { shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
280
- let output = '';
281
- child.stdout.setEncoding('utf8');
282
- child.stdout.on('data', chunk => { output += chunk; });
283
- child.once('error', () => reject(new Error('无法打开目录选择窗口,请直接输入完整路径')));
284
- child.once('close', code => {
285
- const path = output.trim();
286
- // Judge the path by the picker's platform, not the host's: a Windows path is not absolute on POSIX.
287
- const absolute = platform === 'win32' ? win32.isAbsolute(path) : posix.isAbsolute(path);
288
- resolve_result(code === 0 && absolute ? { path } : { cancelled: true });
289
- });
290
- });
291
- }
292
-
293
- /** Some CLIs take seconds to list models; reuse a good list for a day unless the executable changes or the user retries. */
294
- const MODEL_CACHE_MS = 24 * 60 * 60 * 1000;
295
-
296
- /** The executable's size and modification time, so a reinstalled or updated CLI is read again. */
297
- function executable_stamp(profile) {
298
- try { const file = statSync(profile.executable); return `${file.size}:${file.mtimeMs}`; } catch { return ''; }
299
- }
300
-
301
- /**
302
- * The model and effort a software runs with when the card leaves them empty. One read from its own settings is
303
- * cheap and always fresh; one that must run the CLI (agy) is kept for a day, because each run may refresh the
304
- * software's login and, when that refresh fails, it opens a browser sign-in. `refresh` reads it again.
305
- * agy updates itself often, so the key leaves out the executable stamp; a failed run is recorded too and keeps the
306
- * last good answer, so a run that cannot sign in is not repeated on every room read. Changing the default model in the
307
- * software's own settings (`stamp`) reads it again at once.
308
- */
309
- export async function cached_software_defaults(home, profile, { refresh = false, query = software_defaults, stamp = software_defaults_stamp } = {}) {
310
- if (!adapter_profile(profile.adapter)?.defaults_by_query) return query(profile);
311
- const path = join(home, 'model-catalogs.json');
312
- const key = JSON.stringify(['defaults', profile.adapter, profile.executable || '']);
313
- let cache = {};
314
- try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
315
- const entry = cache[key];
316
- const setting = stamp(profile);
317
- if (!refresh && entry && Date.now() - entry.at < MODEL_CACHE_MS && (entry.setting ?? '') === setting) return entry.result;
318
- const answer = await query(profile);
319
- const result = answer?.model ? answer : entry?.result || answer;
320
- try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
321
- atomic_json(path, { ...cache, [key]: { at: Date.now(), setting, result } });
322
- return result;
323
- }
324
-
325
- /** Return the software catalog, served from the private service home when still valid. */
326
- export async function cached_software_models(home, profile, { refresh = false, query = software_models, query_effort = software_effort, query_defaults = software_defaults } = {}) {
327
- const path = join(home, 'model-catalogs.json');
328
- const stamp = executable_stamp(profile);
329
- const key = JSON.stringify([profile.adapter, profile.executable || '', stamp]);
330
- const effort_key = JSON.stringify([profile.adapter, profile.executable || '', stamp, 'effort', profile.model || '']);
331
- let cache = {};
332
- try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
333
- const cached = entry => !refresh && entry && Date.now() - entry.at < MODEL_CACHE_MS ? entry.result : null;
334
- const [result, effort, defaults] = await Promise.all([cached(cache[key]) || query(profile),
335
- adapter_profile(profile.adapter)?.efforts_per_model ? cached(cache[effort_key]) || query_effort(profile) : null,
336
- cached_software_defaults(home, profile, { refresh, query: query_defaults })]);
337
- const updates = {};
338
- if (!cached(cache[key]) && !result.error && result.models.length) {
339
- updates[key] = { at: Date.now(), result };
340
- }
341
- if (effort && !effort.error && !cached(cache[effort_key])) {
342
- updates[effort_key] = { at: Date.now(), result: effort };
343
- }
344
- if (Object.keys(updates).length) {
345
- try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
346
- const prefix = JSON.stringify([profile.adapter, profile.executable || '']).slice(0, -1);
347
- for (const old of Object.keys(cache)) if (old.startsWith(prefix) && !old.startsWith(key.slice(0, -1))) delete cache[old];
348
- atomic_json(path, { ...cache, ...updates });
349
- }
350
- return { ...result, defaults, ...(effort ? { efforts: effort.levels, ...(effort.error ? { effort_error: effort.error } : {}) } : {}) };
351
- }
352
-
353
- /** Read private defaults without selecting a global room or identity. */
354
- export function launch_settings(home) {
355
- const path = join(home, 'launch-settings.json');
356
- const settings = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { participants: {} };
357
- for (const profile of Object.values(settings.participants || {})) for (const field of LEGACY_PROFILE_FIELDS) delete profile?.[field];
358
- return settings;
359
- }
360
-
361
- /**
362
- * Read the registered room's model choices, what each software selects for empty ones, and its smart scheduler, never connection secrets.
363
- * `actual_model` / `actual_effort` (present only when known) are what each member's session last ran with, read from the software's own session log.
364
- * With `quick`, agy's default model is not queried and its entry is marked `defaults_pending`.
365
- */
366
- export async function room_models(home, raw, { read_defaults = profile => cached_software_defaults(home, profile), read_session = session_settings } = {}) {
367
- const input = launch_input({ ...raw, entry: 'web' });
368
- if (!input.room_id) throw new Error('读取本场模型须提供 room_id');
369
- const paths = read_registry(home).filter(path => {
370
- const identity = registered_identity(path);
371
- return identity?.site === input.site && identity.room === input.room_id;
372
- });
373
- if (paths.length > 1) throw new Error('本场存在多份登记配置,无法确定模型设置');
374
- const config = paths.length ? configuration_snapshot(paths[0]).config : {};
375
- const profiles = config.participants || {};
376
- let sessions = {};
377
- try { if (paths.length) sessions = bound_sessions(config, paths[0]); } catch { /* No readable runtime yet: fall back to borrowed sessions. */ }
378
- const participants = Object.fromEntries(await Promise.all(Object.entries(profiles).map(async ([name, profile]) => {
379
- const facts = adapter_profile(profile.adapter);
380
- // An App chooses its model itself; a CLI or API member's card sets it.
381
- const card_model = facts?.kind !== 'app';
382
- // A software read by running it to name its default model takes seconds; a quick read leaves that to a later full read.
383
- const pending = input.quick === true && Boolean(facts?.defaults_by_query);
384
- const defaults = pending ? { model: '', effort: '' } : await read_defaults(profile);
385
- const actual = read_session(profile.adapter, sessions[name] || profile.session_id);
386
- return [name, { ...(pending ? { defaults_pending: true } : {}), adapter: profile.adapter, model: card_model ? profile.model || '' : '',
387
- effort: facts?.efforts ? profile.effort || '' : '', default_model: defaults.model, default_effort: defaults.effort,
388
- ...(actual.model ? { actual_model: actual.model } : {}), ...(actual.effort ? { actual_effort: actual.effort } : {}),
389
- project_access: !facts?.capabilities.project ? 'read' : profile.project_access || config.project_access || 'read',
390
- // A member bound to its own conversation may keep that conversation's project, so this tool cannot set its access.
391
- own_project: Boolean(facts?.own_project_when_bound && profile.session_id),
392
- // A member working outside every project directory of the room only reads them; the page warns and names its directory.
393
- ...(facts?.capabilities.project && outside_directory(config, profile) ? { outside_directory: outside_directory(config, profile),
394
- outside_enforced: read_only_enforced({ ...profile, project_access: profile.project_access || config.project_access || 'read' }) } : {}) }];
395
- })));
396
- // Smart scheduling is a local choice; only which model decides is shown, never its key.
397
- const scheduler = config.scheduler ? { provider: config.scheduler.provider, model: config.scheduler.model, mode: config.scheduler.mode || DEFAULT_SCHEDULER_MODE } : null;
398
- return { room_id: input.room_id, registered: paths.length > 0, participants, scheduler, project_directory: config.cwd || '',
399
- extra_directories: config.extra_directories || [],
400
- workflow: room_workflow_status(config, home), host_workflows: Boolean(config.host_workflows),
401
- api_max_requests: config.api_max_requests ?? DEFAULT_API_MAX_REQUESTS,
402
- // Whether members may draw here, and whether this computer has an image service to draw with.
403
- image_generation: Boolean(config.image_generation), image_configured: image_settings(home).configured };
404
- }
405
-
406
- /** Read one member's installed skills for the room owner, using only this computer's saved software and directory. */
407
- export async function room_skills(home, raw, { read_skills = software_skills } = {}) {
408
- const { input, config } = await member_room_context(home, raw);
409
- const profile = config.participants?.[input.name];
410
- if (!profile) return { room_id: input.room_id, member: input.name, available: false, skills: [], reason: '本机没有此成员的软件配置,无法读取技能' };
411
- const result = await read_skills({ ...profile, cwd: profile.cwd || config.cwd || '' });
412
- return { room_id: input.room_id, member: input.name, ...result };
413
- }
414
-
415
- /**
416
- * The room's workflow as the right column shows it; `available` is false when its folder is gone or broken, and
417
- * `cards` lists the card IDs the library has now, so the page offers a refresh only when the room differs from it.
418
- */
419
- function room_workflow_status(config, home) {
420
- if (!config.workflow?.id) return null;
421
- const loaded = load_room_workflow({ ...config, api_home: config.api_home || home, workflow: { ...config.workflow, enabled: true } });
422
- // `cards` are the main flow's, which a refresh fills; a sub-workflow's cards join only when it is used.
423
- const cards = Object.values(loaded.cards || {});
424
- return { id: config.workflow.id, label: loaded.label || config.workflow.id, enabled: Boolean(config.workflow.enabled),
425
- available: !loaded.error, members: config.workflow.members || {}, cards: cards.filter(card => !card.sub_workflow).map(card => card.card),
426
- sub_workflows: (loaded.sub_workflows || []).map(sub => ({ id: sub.id, label: sub.label || sub.id, description: sub.description, cards: sub.cards })) };
427
- }
428
-
429
- /**
430
- * Read the owner's saved room projects, never a directory supplied by the request: `root` picks one of the room's
431
- * directories by index (0, the main one, by default), and a search covers all of them.
432
- */
433
- export async function room_files(home, raw, { trust = false } = {}) {
434
- const { input, config } = await member_room_context(home, raw, { trust });
435
- const directories = room_directories(config);
436
- if (input.query) return { room_id: input.room_id, ...search_project_roots(directories, input.query) };
437
- const root = input.root ?? 0;
438
- if (!Number.isSafeInteger(root) || root < 0 || (directories.length && root >= directories.length)) throw new Error('项目目录编号无效,请刷新后重试');
439
- return { room_id: input.room_id, root, ...read_project_files(directories[root], input.path, input.offset) };
440
- }
441
-
442
- /**
443
- * `room-files` asked for by another device, answered inside the relay's own process: the same checks as the local
444
- * entrypoint with `--remote`, without starting Node for every folder opened.
445
- */
446
- export async function remote_room_files(home, input) {
447
- assert_shared_home(home);
448
- guard_remote_request('room-files', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
449
- return room_files(home, input, { trust: true });
450
- }
451
-
452
- // A relayed answer carries this much of a page at a time, within the relay's encrypted envelope after base64.
453
- const PAGE_PART_BYTES = 192 * 1024;
454
-
455
- /**
456
- * One HTML file of the room's project with the files it refers to inlined (see `bundle_project_page`), or the images a
457
- * Markdown file shows (`bundle_project_markdown`), as base64
458
- * `data` from `offset`. With `parts` (another device, through the relay) at most `PAGE_PART_BYTES` at a time; the
459
- * caller asks again from where a part ended and checks `version` stays the same.
460
- */
461
- export async function room_page(home, raw, { trust = false, parts = false } = {}) {
462
- const { input, config } = await member_room_context(home, raw, { trust });
463
- const directories = room_directories(config);
464
- const root = input.root ?? 0;
465
- const offset = input.offset ?? 0;
466
- if (!Number.isSafeInteger(root) || root < 0 || root >= Math.max(1, directories.length)) throw new Error('项目目录编号无效,请刷新后重试');
467
- if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('页面读取位置无效');
468
- const bundle = /\.(md|markdown)$/i.test(String(input.path || '')) ? bundle_project_markdown : bundle_project_page;
469
- const { bytes, ...page } = bundle(directories[root], input.path);
470
- const part = bytes.subarray(offset, parts ? offset + PAGE_PART_BYTES : bytes.length);
471
- return { room_id: input.room_id, root, ...page, total: bytes.length, offset, data: part.toString('base64') };
472
- }
473
-
474
- // Through the relay a media file comes whole, in parts, so another device plays at most this much.
475
- export const REMOTE_MEDIA_MAX_BYTES = 64 * 1024 * 1024;
476
-
477
- /**
478
- * One image, video or audio file of the room's project (see `project_media`). For the computer's own page it names
479
- * the real file, which the local site streams by a ticket and never shows the page; with `parts` (another device,
480
- * through the relay) it returns base64 `data` from `offset`, at most `PAGE_PART_BYTES` at a time, for files up to
481
- * `REMOTE_MEDIA_MAX_BYTES`, and the caller checks `version` stays the same.
482
- */
483
- export async function room_media(home, raw, { trust = false, parts = false } = {}) {
484
- const { input, config } = await member_room_context(home, raw, { trust });
485
- const directories = room_directories(config);
486
- const root = input.root ?? 0;
487
- const offset = input.offset ?? 0;
488
- if (!Number.isSafeInteger(root) || root < 0 || root >= Math.max(1, directories.length)) throw new Error('项目目录编号无效,请刷新后重试');
489
- if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('文件读取位置无效');
490
- const { file, ...media } = project_media(directories[root], input.path);
491
- if (!parts) return { room_id: input.room_id, root, ...media, file };
492
- if (media.size > REMOTE_MEDIA_MAX_BYTES) throw new Error(`文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可播放的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上打开`);
493
- const part = Buffer.alloc(Math.max(0, Math.min(PAGE_PART_BYTES, media.size - offset)));
494
- const handle = openSync(file, 'r');
495
- try { readSync(handle, part, 0, part.length, offset); } finally { closeSync(handle); }
496
- return { room_id: input.room_id, root, ...media, total: media.size, offset, data: part.toString('base64') };
497
- }
498
-
499
- /** `room-media` asked for by another device, answered inside the relay's own process in parts. */
500
- export async function remote_room_media(home, input) {
501
- assert_shared_home(home);
502
- guard_remote_request('room-media', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
503
- return room_media(home, input, { trust: true, parts: true });
504
- }
505
-
506
- /** `room-page` asked for by another device, answered inside the relay's own process in parts, like `remote_room_files`. */
507
- export async function remote_room_page(home, input) {
508
- assert_shared_home(home);
509
- guard_remote_request('room-page', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
510
- return room_page(home, input, { trust: true, parts: true });
511
- }
512
-
513
- // The newest part of a long-running execution's log is what its detail view needs; older lines are dropped.
514
- const DETAIL_LOG_TAIL_BYTES = 4 * 1024 * 1024;
515
-
516
- /**
517
- * What a member did in one execution, rebuilt from the raw event log its process wrote in the room's runtime directory
518
- * (`<adapter>-free-<execution>.log`). The log stays on this computer: the page reads it here or through the relay.
519
- * `available: false` when the execution kept no such log (an App or manual member, or an API member).
520
- */
521
- export async function execution_details_command(home, raw, { trust = false } = {}) {
522
- const { input, config } = await member_room_context(home, raw, { trust });
523
- // A private chat turn (`chat_id`) keeps its log the same way as an execution.
524
- const chat = input.chat_id !== undefined;
525
- const execution_id = Number(chat ? input.chat_id : input.execution_id);
526
- if (!Number.isSafeInteger(execution_id) || execution_id <= 0) throw new Error(chat ? '私聊编号无效' : '执行编号无效');
527
- const suffix = `-${chat ? 'chat' : 'free'}-${execution_id}.log`;
528
- const name = existsSync(config.directory) ? readdirSync(config.directory).find(file => file.endsWith(suffix)) : undefined;
529
- const parsed = name ? execution_details(name.slice(0, -suffix.length), read_log_tail(join(config.directory, name))) : null;
530
- return { room_id: input.room_id, [chat ? 'chat_id' : 'execution_id']: execution_id, available: Boolean(parsed), ...parsed };
531
- }
532
-
533
- /**
534
- * `execution-details` asked for by another device, answered inside the relay's own process like `remote_room_files`:
535
- * the private-chat page reads it for every turn and again every poll for a running one, so starting Node and asking
536
- * the site to check the credential each time made the page wait seconds for what is already on this computer.
537
- */
538
- export async function remote_execution_details(home, input) {
539
- assert_shared_home(home);
540
- guard_remote_request('execution-details', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
541
- return execution_details_command(home, input, { trust: true });
542
- }
543
-
544
- /** The last bytes of a log as text, starting at a whole line. */
545
- function read_log_tail(path) {
546
- const size = statSync(path).size, length = Math.min(size, DETAIL_LOG_TAIL_BYTES);
547
- const buffer = Buffer.alloc(length), descriptor = openSync(path, 'r');
548
- try { readSync(descriptor, buffer, 0, length, size - length); } finally { closeSync(descriptor); }
549
- const text = buffer.toString('utf8');
550
- return length < size ? text.slice(text.indexOf('\n') + 1) : text;
551
- }
552
-
553
- const CREATE_PREFERENCE_RANGES = { max_rounds: [0, 100], max_minutes: [0, 1440], goal_max_continues: [0, 100], goal_max_minutes: [0, 1440], chain_rounds: [0, 100],
554
- api_max_requests: [0, MAX_API_MAX_REQUESTS] };
555
- const CREATE_PREFERENCE_FLAGS = ['named_followup', 'host_workflows', 'advanced_open'];
556
- const MAX_PREFERENCE_MODEL_LENGTH = 200;
557
- const SETTINGS_LOCK_WAIT_MS = 5000;
558
-
559
- /** Validate only reusable form choices; room text, members, paths and credentials are never preferences. */
560
- function validate_create_preferences(input) {
561
- if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('建房偏好须为对象');
562
- for (const [field, value] of Object.entries(input)) {
563
- let valid = false;
564
- if (CREATE_PREFERENCE_FLAGS.includes(field)) valid = typeof value === 'boolean';
565
- else if (Object.hasOwn(CREATE_PREFERENCE_RANGES, field)) {
566
- const [minimum, maximum] = CREATE_PREFERENCE_RANGES[field];
567
- valid = Number.isInteger(value) && value >= minimum && value <= maximum;
568
- } else if (field === 'drive') valid = ['free', 'discussion', 'goal'].includes(value);
569
- else if (field === 'workflow_id') valid = typeof value === 'string' && (!value || WORKFLOW_ID_PATTERN.test(value));
570
- else if (field === 'scheduler') valid = valid_scheduler_preference(value);
571
- if (!valid) throw new Error(`建房偏好字段无效:${field}`);
572
- }
573
- }
574
-
575
- /** A scheduler preference carries selections, never a key or even a key reference. */
576
- function valid_scheduler_preference(value) {
577
- if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
578
- const fields = {
579
- enabled: item => typeof item === 'boolean',
580
- provider: item => typeof item === 'string' && (!item || Object.hasOwn(SCHEDULER_PROVIDERS, item)),
581
- model: item => typeof item === 'string' && item.length <= MAX_PREFERENCE_MODEL_LENGTH,
582
- mode: item => typeof item === 'string' && (!item || Object.hasOwn(SCHEDULER_MODES, item)),
583
- };
584
- return Object.entries(value).every(([field, item]) => Object.hasOwn(fields, field) && fields[field](item));
585
- }
586
-
587
- /** Update software defaults or form preferences independently, preserving the other section. */
588
- export function save_launch_settings(home, input) {
589
- const patch = {};
590
- if (Object.hasOwn(input, 'participants')) {
591
- const participants = {};
592
- for (const [name, profile] of Object.entries(input.participants || {})) {
593
- if (platform_of(name) !== name) throw new Error(`本机默认配置按平台保存;${name} 的模型与强度只用于本场讨论`);
594
- validate_profile(name, profile);
595
- participants[name] = profile;
596
- }
597
- patch.participants = participants;
598
- }
599
- if (Object.hasOwn(input, 'create_preferences')) {
600
- validate_create_preferences(input.create_preferences);
601
- patch.create_preferences = input.create_preferences;
602
- }
603
- mkdirSync(home, { recursive: true, mode: 0o700 });
604
- const lock = new DatabaseSync(join(home, 'launch-settings-lock.sqlite3'));
605
- try {
606
- lock.exec(`PRAGMA busy_timeout=${SETTINGS_LOCK_WAIT_MS}; BEGIN IMMEDIATE`);
607
- const previous = launch_settings(home);
608
- const settings = { ...previous, ...patch };
609
- if (patch.create_preferences) settings.create_preferences = { ...previous.create_preferences, ...patch.create_preferences };
610
- atomic_json(join(home, 'launch-settings.json'), settings);
611
- lock.exec('COMMIT');
612
- return settings;
613
- } finally { lock.close(); }
614
- }
615
-
616
- const PROJECT_NAME_LIMIT = 80;
617
- const PROJECT_ID_PATTERN = /^[0-9a-f]{8,32}$/;
618
-
619
- /** Read the named project directories saved on this computer, offered as launch cwd choices. */
620
- export function launch_projects(home) {
621
- // An ordinary account's projects are the folders under its projects root; it keeps no list of its own.
622
- const { projects_root } = account_space(home);
623
- if (projects_root) return { projects: account_projects(projects_root), restricted: true };
624
- const path = join(home, 'launch-projects.json');
625
- return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { projects: [] };
626
- }
627
-
628
- /** Replace the project list; every path must be an existing folder on this computer. */
629
- // The id outlives renames and moves: other devices choose a project by id and never see its path.
630
- export function save_launch_projects(home, input) {
631
- const { projects_root } = account_space(home);
632
- if (projects_root) {
633
- if (typeof input.create !== 'string') throw new Error('此账号的项目只能在自己的项目文件夹内新建:请提供 create(项目名称)');
634
- const created = create_account_project(projects_root, input.create);
635
- return { ...launch_projects(home), created };
636
- }
637
- if (!Array.isArray(input.projects)) throw new Error('projects 必须为列表');
638
- const projects = input.projects.map(item => ({ id: PROJECT_ID_PATTERN.test(item?.id) ? item.id : randomUUID().replaceAll('-', '').slice(0, 16),
639
- name: String(item?.name || '').trim(), path: String(item?.path || '').trim() }));
640
- const names = new Set();
641
- for (const { name, path } of projects) {
642
- if (!name || name.length > PROJECT_NAME_LIMIT) throw new Error(`项目名称不能为空,且不超过 ${PROJECT_NAME_LIMIT} 字`);
643
- if (names.has(name)) throw new Error(`项目名称重复:${name}`);
644
- names.add(name);
645
- if (!isAbsolute(path)) throw new Error(`${name}:路径必须为完整绝对路径`);
646
- if (!existsSync(path) || !statSync(path).isDirectory()) throw new Error(`${name}:这台电脑上不存在此文件夹:${path}`);
647
- }
648
- mkdirSync(home, { recursive: true, mode: 0o700 });
649
- atomic_json(join(home, 'launch-projects.json'), { projects });
650
- return { projects };
651
- }
652
-
653
- const MAX_EXPERT_PRESETS = 30;
654
- const MAX_PRESET_DESCRIPTION = 500;
655
- const MAX_PRESET_FIELD = 200;
656
- // name is the instance a preset adds (platform-suffix); label is the free name shown for it, on the add row and in the room.
657
- const PRESET_FIELDS = ['name', 'label', 'description', 'system_prompt', 'project_access', 'model', 'effort'];
658
- const MAX_PRESET_LABEL = 32;
659
-
660
- /**
661
- * Presets saved while IDs could hold Chinese: such an ID becomes `platform-presetN` and its old name the label, so the
662
- * add row still shows it. The next save keeps the new form.
663
- */
664
- function english_preset_ids(presets) {
665
- const taken = new Set(presets.map(preset => preset.name));
666
- return presets.map(preset => {
667
- const platform = /^(Codex|Claude|Antigravity|DeepSeek|Qwen|Grok|OpenAI|Custom)(?:-|$)/.exec(preset.name || '')?.[1];
668
- if (!platform || platform_of(preset.name)) return preset;
669
- let number = 1;
670
- while (taken.has(`${platform}-preset${number}`)) number++;
671
- const name = `${platform}-preset${number}`;
672
- taken.add(name);
673
- return { ...preset, name, label: preset.label || preset.name };
674
- });
675
- }
676
-
677
- /** The user's expert presets and per-platform default descriptions saved on this computer, plus the built-in presets the user has not deleted. */
678
- export function expert_presets(home) {
679
- const path = join(home, 'expert-presets.json');
680
- const saved = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
681
- const hidden_builtins = saved.hidden_builtins || [];
682
- // A preset saved while members drew with their own image model keeps the rest; drawing is the room's switch now.
683
- const presets = (saved.presets || []).map(({ image_model, ...preset }) => preset);
684
- return { presets: english_preset_ids(presets), description_templates: saved.description_templates || {}, hidden_builtins,
685
- builtin_presets: BUILTIN_EXPERT_PRESETS.filter(preset => !hidden_builtins.includes(preset.name)) };
686
- }
687
-
688
- /** Check one expert preset; a workflow's agent card is a preset and obeys the same rule. */
689
- export function validate_preset(preset) {
690
- if (!preset || typeof preset !== 'object' || Object.keys(preset).some(key => !PRESET_FIELDS.includes(key))) throw new Error('预设只能包含名称、显示名、描述、提示词、项目权限、模型与强度');
691
- if (!platform_of(preset.name) || !clients_of(preset.name)) throw new Error(`预设 ID 须为“平台名”或“平台名-后缀”,后缀只用英文、数字和下划线:${preset.name}`);
692
- if (Object.values(preset).some(value => typeof value !== 'string')) throw new Error(`${preset.name} 的字段必须为文本`);
693
- if ((preset.label || '').trim().length > MAX_PRESET_LABEL) throw new Error(`${preset.name} 的显示名最多 ${MAX_PRESET_LABEL} 字`);
694
- if ((preset.description || '').length > MAX_PRESET_DESCRIPTION) throw new Error(`${preset.name} 的描述最多 ${MAX_PRESET_DESCRIPTION} 字`);
695
- if ((preset.system_prompt || '').length > MAX_EXPERT_PROMPT) throw new Error(`${preset.name} 的提示词最多 ${MAX_EXPERT_PROMPT} 字`);
696
- if (preset.project_access && !PROJECT_ACCESS.includes(preset.project_access)) throw new Error(`${preset.name} 的项目权限须为 read、write、auto 或 full`);
697
- if ([preset.model, preset.effort].some(value => (value || '').length > MAX_PRESET_FIELD)) throw new Error(`${preset.name} 的模型或强度过长`);
698
- }
699
-
700
- /** Replace the user's presets, default descriptions or deleted built-ins (whichever the input carries); every field is checked first. */
701
- export function save_expert_presets(home, input) {
702
- const current = expert_presets(home);
703
- const presets = input.presets === undefined ? current.presets : input.presets;
704
- const templates = input.description_templates === undefined ? current.description_templates : input.description_templates;
705
- const hidden_builtins = input.hidden_builtins === undefined ? current.hidden_builtins : input.hidden_builtins;
706
- const builtin_names = BUILTIN_EXPERT_PRESETS.map(preset => preset.name);
707
- if (!Array.isArray(hidden_builtins) || hidden_builtins.some(name => !builtin_names.includes(name))) throw new Error(`hidden_builtins 只能列出内置预设:${builtin_names.join('、')}`);
708
- if (!Array.isArray(presets) || presets.length > MAX_EXPERT_PRESETS) throw new Error(`presets 必须为列表,最多 ${MAX_EXPERT_PRESETS} 个`);
709
- const names = new Set();
710
- for (const preset of presets) {
711
- validate_preset(preset);
712
- if (names.has(preset.name)) throw new Error(`预设名称重复:${preset.name}`);
713
- names.add(preset.name);
714
- }
715
- if (!templates || typeof templates !== 'object' || Array.isArray(templates) || Object.entries(templates).some(([platform, text]) =>
716
- platform_of(platform) !== platform || typeof text !== 'string' || !text.trim() || text.length > MAX_PRESET_DESCRIPTION)) {
717
- throw new Error(`description_templates 须为 {平台名: 描述},每段 1–${MAX_PRESET_DESCRIPTION} 字`);
718
- }
719
- mkdirSync(home, { recursive: true, mode: 0o700 });
720
- atomic_json(join(home, 'expert-presets.json'), { presets, description_templates: templates, hidden_builtins });
721
- return expert_presets(home);
722
- }
723
-
724
- /** Reject malformed client fields before saving defaults or creating any discussion. */
725
- function validate_profile(name, profile, binding = false) {
726
- if (!clients_of(name) || !profile || typeof profile !== 'object' || Array.isArray(profile)) throw new Error(`不支持的软件配置:${name}`);
727
- if (profile.adapter && !clients_of(name).includes(profile.adapter)) throw new Error(`${name} 的客户端不匹配`);
728
- // Session bindings and project write access apply to one launch only, never to machine defaults.
729
- const fields = binding ? [...PROFILE_FIELDS, 'session_id', 'project_access'] : PROFILE_FIELDS;
730
- if (Object.keys(profile).some(key => !fields.includes(key))) throw new Error('软件配置包含不支持的字段;默认配置不能保存房间或会话绑定');
731
- for (const [key, value] of Object.entries(profile)) {
732
- if (key === 'allowed_tools') {
733
- if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) throw new Error(`${name}.allowed_tools 必须为工具名称数组`);
734
- } else if (typeof value !== 'string') throw new Error(`${name}.${key} 必须为文本`);
735
- if (['executable', 'cwd', 'ipc_directory'].includes(key) && value && !isAbsolute(value)) throw new Error(`${name}.${key} 必须为完整绝对路径`);
736
- // The model is passed as one CLI argument, so it must not look like a flag or contain spaces.
737
- if (key === 'model' && value && !/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]*$/.test(value)) throw new Error(`${name}.${key} 只能是模型名称,例如 gpt-6-astra、opus 或 gemini-4-argon-high`);
738
- if (key === 'system_prompt' && value.length > MAX_EXPERT_PROMPT) throw new Error(`${name} 的专属提示词最多 ${MAX_EXPERT_PROMPT} 字`);
739
- }
740
- const facts = adapter_profile(profile.adapter);
741
- if (facts?.kind === 'api') validate_api_profile(profile);
742
- // The UI discovers each model's supported subset; omitted values keep the CLI's own default.
743
- if (profile.effort && facts?.kind !== 'api' && !facts?.efforts?.includes(profile.effort)) {
744
- throw new Error(facts?.efforts ? `${name}.effort 只能是 ${facts.efforts.join(' / ')}` : `${name} 的思考档位在原软件中选择`);
745
- }
746
- }
747
-
748
- /** Send one request without following redirects that could disclose the room credential. */
749
- async function site_request(site, path, token, body, headers = {}) {
750
- const response = await fetch(`${site}${path}`, { method: body === undefined ? 'GET' : 'POST',
751
- headers: { 'Content-Type': 'application/json', 'X-Discussion-Token': token, ...headers },
752
- body: body === undefined ? undefined : JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(10000) });
753
- const result = await response.json();
754
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${result.error || '请求失败'}`);
755
- return result;
756
- }
757
-
758
- /** Require an explicit website, launch entry and stable creation identity. */
759
- function launch_input(input) {
760
- const value = structuredClone(input);
761
- const url = new URL(value.site);
762
- if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('site 必须为 HTTP(S) 根地址');
763
- value.site = url.origin;
764
- if (!['conversation', 'web'].includes(value.entry)) throw new Error('entry 必须为 conversation 或 web');
765
- if (value.entry === 'conversation' && (typeof value.current_session_id !== 'string' || !value.current_session_id.trim())) throw new Error('对话入口须提供当前实际会话的 current_session_id');
766
- if (value.cwd && (typeof value.cwd !== 'string' || !isAbsolute(value.cwd))) throw new Error('cwd 必须为完整绝对路径');
767
- // A new room's extra project directories; an existing room changes them through room-settings.
768
- if (!value.room_id && value.extra_directories?.length) check_extra_directories(value.cwd, value.extra_directories);
769
- else if (!value.room_id) delete value.extra_directories;
770
- if (value.project_access && !PROJECT_ACCESS.includes(value.project_access)) throw new Error('project_access 只能为 read、write、auto 或 full');
771
- if (value.room_id && !/^[A-Za-z0-9_-]+$/.test(value.room_id)) throw new Error('房间编号无效');
772
- if (!value.room_id && !value.room?.submission_id) throw new Error('新房间须提供 room.submission_id;重试沿用原编号');
773
- if (value.room?.mode === 'free') {
774
- // P1: a free room is launched once, at creation, from the web page.
775
- if (value.entry !== 'web' || value.room_id) throw new Error('房间目前只能在网页创建时启动');
776
- const members = value.room.members;
777
- const names = members?.map(member => typeof member === 'string' ? member : member.name);
778
- const woken = Array.isArray(members) ? members.filter(woken_member).map(member => typeof member === 'string' ? member : member.name) : [];
779
- if ((!woken.length && !value.scheduler && !value.cwd) || !names?.length || new Set(names).size !== names.length || woken.some(name => !clients_of(name))) {
780
- throw new Error('房间须选择至少 1 位支持自动接入的 AI 成员(或开启智能调度、指定项目目录),且不能重复');
781
- }
782
- }
783
- if (value.access_file) {
784
- const access = JSON.parse(readFileSync(resolve(value.access_file), 'utf8'));
785
- if (access.site?.replace(/\/$/, '') !== value.site || access.room !== value.room_id) throw new Error('access_file 与本次站点或房间不符');
786
- value.token = access.token;
787
- }
788
- return value;
789
- }
790
-
791
- /** Discussion experts the member list marks as manual: they answer with their own credential and need no local software. */
792
- function manual_experts(room) {
793
- return new Set((room.members || []).filter(member => member && typeof member === 'object' && member.access === 'manual').map(member => member.name));
794
- }
795
-
796
- /** Merge machine defaults and explicit room overrides, preserving the selected participants. */
797
- function launch_config(home, input, room, directory, options) {
798
- // In a creation input, mode='free' means no immediate discussion; omitted mode still requests a hosted discussion.
799
- if (room.mode === 'free') return free_launch_config(home, input, room, directory, options);
800
- if (!clients_of(room.host)) throw new Error('请选择支持全自动讨论的 AI 主持人');
801
- if (!room.experts || room.experts[room.host] !== 'cli') throw new Error('请将 AI 主持人的参与方式设为本地读写');
802
- const other = Object.entries(room.experts).filter(([, mode]) => mode !== 'cli').map(([name]) => name);
803
- if (other.length) throw new Error(`全自动讨论的参与方式须为本地读写:${other.join('、')}`);
804
- const defaults = options.defaults || launch_settings(home).participants;
805
- const manual = manual_experts(room);
806
- if (manual.has(room.host)) throw new Error('AI 主持人由本机服务续接,不能选择手动接入');
807
- const participants = {};
808
- for (const name of new Set([room.host, ...Object.keys(room.experts)])) {
809
- if (!manual.has(name)) participants[name] = participant_profile(name, defaults, input, name === room.host);
810
- }
811
- const members = launch_members(input, Object.keys(participants), options);
812
- return validate_config({ site: input.site, room: room.id || 'preview', token: options.token, mode: 'free', participants, members, api_home: home,
813
- scheduler: input.scheduler || undefined,
814
- cwd: input.cwd, extra_directories: input.extra_directories, discussion_project: input.discussion_project, project_access: input.project_access || undefined,
815
- data_directory: join(directory, 'runtime'), draft_directory: service_drafts(home, join(directory, 'runtime')) }, directory);
816
- }
817
-
818
- /** A free-room member the local service wakes; manual members join without local configuration. */
819
- function woken_member(member) { return typeof member === 'string' || !member.access || member.access === 'runner'; }
820
-
821
- /** Free rooms add one private credential per woken member, kept with the room configuration for retries. */
822
- function free_launch_config(home, input, room, directory, options) {
823
- const defaults = options.defaults || launch_settings(home).participants;
824
- const names = room.members.filter(woken_member).map(member => typeof member === 'string' ? member : member.name);
825
- const participants = Object.fromEntries(names.map(name => [name, participant_profile(name, defaults, input, false)]));
826
- const members = launch_members(input, names, options);
827
- // A workflow chosen at creation is written with the members, so the first wake already carries it.
828
- const workflow = input.workflow ? bind_room_workflow({}, { ...input.workflow, enabled: true }).workflow : undefined;
829
- if (workflow) { get_workflow(home, workflow.id); assert_workflow_enabled(home, workflow.id); }
830
- if (workflow && Object.values(workflow.members).some(name => !names.includes(name))) throw new Error('工作流成员须在本次邀请的成员中');
831
- return validate_config({ site: input.site, room: room.id || 'preview', token: options.token, mode: 'free', participants, members, api_home: home,
832
- scheduler: input.scheduler || undefined, cwd: input.cwd, extra_directories: input.extra_directories, project_access: input.project_access || undefined, workflow,
833
- host_workflows: input.host_workflows === true || undefined, api_max_requests: input.api_max_requests,
834
- image_generation: input.image_generation === true || undefined,
835
- data_directory: join(directory, 'runtime'), draft_directory: service_drafts(home, join(directory, 'runtime')) }, directory);
836
- }
837
-
838
- /** Members in the order of the creation form's cards, so the room's joining order (and default speaking order) follows it. */
839
- function card_order(cards, members) {
840
- const names = (cards || []).map(member => typeof member === 'string' ? member : member?.name);
841
- const place = (name) => names.includes(name) ? names.indexOf(name) : names.length;
842
- return [...members].sort((left, right) => place(left.name) - place(right.name));
843
- }
844
-
845
- /** Preserve caller-generated member credentials; journal newly generated ones before creation. */
846
- function launch_members(input, names, options) {
847
- return Object.fromEntries(names.map(name => {
848
- const supplied = input.room?.members?.find(member => member?.name === name);
849
- return [name, { token: supplied?.token || options.members?.[name]?.token || `${randomUUID()}${randomUUID()}` }];
850
- }));
851
- }
852
-
853
- /**
854
- * Merge one participant's machine defaults with this launch's overrides and check its software. A launch from another
855
- * device (`input.without_saved_tools`) takes no tool approvals saved here, whichever way its members are named.
856
- */
857
- export function participant_profile(name, defaults, input, current_host) {
858
- const platform = platform_of(name);
859
- // An extra instance starts from its platform's settings but never from another instance's bound session.
860
- const { session_id: ignored_session, ...inherited } = name === platform ? {} : input.participants?.[platform] || {};
861
- const saved = { ...defaults[platform], ...(name === platform ? {} : defaults[name]) };
862
- if (input.without_saved_tools) delete saved.allowed_tools;
863
- const profile = { ...saved, ...inherited, ...input.participants?.[name] };
864
- for (const field of ['cwd', 'model', 'effort', 'project_name', 'project_id', 'project_access']) if (profile[field] === '') delete profile[field];
865
- validate_profile(name, profile, true);
866
- if (!clients_of(name)?.includes(profile.adapter)) throw new Error(`请配置 ${name} 的 CLI / App 客户端`);
867
- const facts = adapter_profile(profile.adapter);
868
- if (facts?.kind === 'api') {
869
- if (input.entry === 'conversation' && current_host) throw new Error('API 主持人请从网页启动;当前软件会话主持须选择对应 CLI / App');
870
- return profile;
871
- }
872
- if (facts?.location === 'executable' && (!existsSync(profile.executable || '') || !statSync(profile.executable).isFile()
873
- || (process.platform === 'win32' && !/\.exe$/i.test(profile.executable)))) throw new Error(`${name}:请指定实际原生可执行文件,Windows 使用 .exe`);
874
- const cwd = profile.cwd || input.cwd;
875
- if (cwd && (!existsSync(cwd) || !statSync(cwd).isDirectory())) throw new Error(`${name}:工作目录不存在或不是文件夹,请核对本次目录配置`);
876
- if (input.entry === 'conversation' && current_host) profile.session_id = input.current_session_id;
877
- // A new agy conversation always gets this tool's discussion project; only a manual agy expert the owner chose to host (input.adopt) keeps its own.
878
- if (!facts?.host_existing && profile.session_id && !input.adopt) throw new Error(`${name}:${facts?.label || profile.adapter} 不能绑定已有会话或从当前对话主持全自动讨论;请从网页或其他软件发起,它会由讨论服务新建会话`);
879
- return profile;
880
- }
881
-
882
- /** List every file below a directory, or nothing when the software has never stored a session there. */
883
- function session_files(directory) {
884
- return existsSync(directory) ? readdirSync(directory, { recursive: true }).map(path => join(directory, String(path))) : [];
885
- }
886
-
887
- /** Compare directories as the operating system resolves them (Windows short names and case). */
888
- function same_directory(left, right) {
889
- const real = path => { try { return realpathSync.native(path); } catch { return resolve(path); } };
890
- const [a, b] = [real(left), real(right)];
891
- return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
892
- }
893
-
894
- /**
895
- * Prove an invited existing conversation is on this machine before it can hold a turn, so a mistyped ID
896
- * fails here instead of pausing the discussion later. Claude stores sessions per directory and resumes only
897
- * from the original one, so its cwd follows the session: a session kept elsewhere than the room's project joins as a
898
- * member working in its own directory (it only reads the room's directories); only a directory the member's own
899
- * settings name explicitly must match.
900
- */
901
- export function borrowed_session(name, profile, room_cwd, env = process.env) {
902
- const id = profile.session_id;
903
- if (!SESSION_ID_PATTERN.test(id)) throw new Error(`${name}:会话 ID 格式不正确`);
904
- const adapter = adapter_of(profile.adapter);
905
- if (!adapter?.adopt || !adapter.session) {
906
- const adoptable = ADAPTER_IDS.filter(item => ADAPTER_PROFILES[item].adopt).map(item => ADAPTER_PROFILES[item].label);
907
- throw new Error(`${name}:只有 ${adoptable.join('、')} 可以接入已有会话`);
908
- }
909
- if (!adapter.session.exists(id, { env })) throw new Error(`${name}:本机找不到 ${adapter.label} 会话 ${id},请核对会话 ID`);
910
- if (adapter.adopt !== 'own_cwd') return profile;
911
- const cwd = adapter.session.cwd(id, { env });
912
- if (!cwd) throw new Error(`${name}:${adapter.label} 会话 ${id} 没有记录原工作目录,无法续接`);
913
- if (profile.cwd && !same_directory(profile.cwd, cwd)) throw new Error(`${name}:这个 ${adapter.label} 会话属于 ${cwd},只能在原目录续接;请让此 AI 的工作目录与它一致,或留空会话 ID 新建会话`);
914
- return { ...profile, cwd: profile.cwd || (room_cwd && same_directory(room_cwd, cwd) ? room_cwd : cwd) };
915
- }
916
-
917
- // An owner credential the website accepted is trusted this long for read-only file browsing in a long-running process
918
- // (the relay), so each folder opened from another device does not ask the website again.
919
- const ROOM_FILES_TRUST_MS = 60000;
920
- const trusted_room_tokens = new Map();
921
-
922
- /** Find the one registered configuration of a room after proving the owner's credential; `trust` reuses a recent proof. */
923
- async function member_room_context(home, raw, { trust = false } = {}) {
924
- const input = launch_input({ ...raw, entry: 'web' });
925
- if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('管理成员须提供房间编号和房间控制凭据');
926
- const paths = read_registry(home).filter(path => {
927
- const identity = registered_identity(path);
928
- return identity?.site === input.site && identity.room === input.room_id;
929
- });
930
- if (paths.length !== 1) throw new Error('未找到本房间唯一的已登记配置,请核对本机接入服务');
931
- const config = configuration_snapshot(paths[0]).config;
932
- const proof = `${input.site}
933
- ${input.room_id}
934
- ${createHash('sha256').update(input.token).digest('hex')}`;
935
- if (!trust || !(Date.now() - (trusted_room_tokens.get(proof) ?? -Infinity) < ROOM_FILES_TRUST_MS)) {
936
- // Both reads need the owner credential; the inbox transfers no messages.
937
- await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
938
- trusted_room_tokens.set(proof, Date.now());
939
- }
940
- return { input, path: paths[0], config };
941
- }
942
-
943
- /** Write a manual member's private credential next to the room configuration, never into a receipt. */
944
- function manual_access(path, input, name, token) {
945
- const access_path = join(dirname(path), `manual-${name}.access.json`);
946
- atomic_json(access_path, { site: input.site, room: input.room_id, member: name, token });
947
- return access_path;
948
- }
949
-
950
- /**
951
- * Invite (add) or bring back (rejoin) one member of a room.
952
- * The local configuration is written before the website call, so a retry reuses the same credential.
953
- * A manual member answers with its own credential and is never woken.
954
- */
955
- export async function room_member(home, raw, locked = false, headers = {}) {
956
- const { input, path } = await member_room_context(home, raw);
957
- const { action, name } = input;
958
- const access = input.access || 'runner';
959
- const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
960
- if (!['add', 'rejoin'].includes(action) || !platform_of(name) || (access !== 'manual' && !clients_of(name)) || !['runner', 'manual'].includes(access)) {
961
- throw new Error('action 须为 add/rejoin,成员须为支持的 AI,接入方式须为 runner/manual');
962
- }
963
- const release = locked ? () => {} : acquire_lock(join(dirname(path), 'configuration-edit'));
964
- try {
965
- const config = configuration_snapshot(path).config;
966
- config.api_home = home;
967
- const roster = room.free.members;
968
- if (action === 'add' && input.new_instance) {
969
- // A name once bound keeps its session locally, so a new instance never reuses a removed member's name.
970
- const taken = new Set([...roster.map(member => member.name), ...Object.keys(config.participants), ...Object.keys(config.members || {})]);
971
- return room_member(home, { ...raw, name: next_instance(platform_of(name), taken), new_instance: false }, true, headers);
972
- }
973
- const current = roster.find(member => member.name === name);
974
- if (input.member_token !== undefined && (typeof input.member_token !== 'string' || input.member_token.length < 32 || input.member_token.length > 256)) throw new Error('member_token 须为 32–256 字符');
975
- if (current?.status === 'active' && input.member_token && config.members?.[name]?.token === input.member_token) {
976
- const view = await site_request(input.site, `/api/rooms/${input.room_id}/members/${current.id}`, input.token, { action: 'active', token: input.member_token }, headers);
977
- return { room_id: input.room_id, member: name, access: current.access, free: view, access_file: null };
978
- }
979
- if (action === 'add' && !current && config.participants[name] && !locked) {
980
- // A removed member's name keeps its bound session locally, so the new one joins under the next free name; a retry
981
- // finds the name its own credential was saved under.
982
- const taken = new Set([...roster.map(member => member.name), ...Object.keys(config.participants), ...Object.keys(config.members || {})]);
983
- const retried = Object.keys(config.members || {}).find(key => key !== name && input.member_token && config.members[key].token === input.member_token
984
- && !roster.some(member => member.name === key));
985
- const renamed = retried || free_instance(name, taken);
986
- const participants = raw.participants?.[name] ? { participants: { ...raw.participants, [renamed]: raw.participants[name] } } : {};
987
- return room_member(home, { ...raw, name: renamed, ...participants }, true, headers);
988
- }
989
- if (action === 'rejoin' && current?.status !== 'away') throw new Error(`${name} 不是离开状态,无需请回`);
990
- if (action === 'add' && current) throw new Error(`${name} 已是本房间成员;离开的成员请用请回`);
991
- const manual = action === 'rejoin' ? current.access === 'manual' : access === 'manual';
992
- const pending = input.retry_token && config.members?.[name]?.pending === input.retry_token;
993
- const token = input.member_token || (pending ? config.members[name].token : `${randomUUID()}${randomUUID()}`);
994
- let profile = config.participants[name];
995
- if (!manual) {
996
- if (action === 'add') {
997
- profile = participant_profile(name, launch_settings(home).participants, { ...input, cwd: input.cwd || config.cwd }, false);
998
- if (profile.session_id) profile = borrowed_session(name, profile, input.cwd || config.cwd);
999
- }
1000
- if (!profile) throw new Error(`${name} 没有本机接入配置;请移除后重新邀请`);
1001
- const next = { ...config, participants: { ...config.participants, [name]: profile },
1002
- members: { ...config.members, [name]: { token, pending: input.retry_token || '' } } };
1003
- validate_config(next, dirname(path));
1004
- atomic_json(path, next);
1005
- }
1006
- const access_file = manual ? manual_access(path, input, name, token) : null;
1007
- const body = action === 'add'
1008
- ? { name, adapter: manual ? '' : profile.adapter, token, access, session_mode: profile?.session_id ? 'borrowed' : 'new' }
1009
- : { action: 'active', token };
1010
- const view = await site_request(input.site, action === 'add' ? `/api/rooms/${input.room_id}/members` : `/api/rooms/${input.room_id}/members/${current.id}`,
1011
- input.token, body, headers);
1012
- return { room_id: input.room_id, member: name, access: manual ? 'manual' : 'runner', free: view, access_file };
1013
- } finally { release(); }
1014
- }
1015
-
1016
-
1017
- /**
1018
- * Change this room's runner settings, any of: `api_max_requests`, how many model requests one execution of an API member
1019
- * may make (0 = no limit); `cwd`, the main project directory, accepted only while the room has none (once set it never
1020
- * changes: sessions and file-change tracking are bound to it); `extra_directories`, the project directories shared
1021
- * besides the main one, replaced as a whole. Members already in a room that gets its main directory keep working where
1022
- * their sessions are (their `cwd` is pinned to '') and reach the room's directories as extra ones; members invited later
1023
- * work in it; `image_generation`, whether members may draw with this computer's image service; `scheduler`, the room's
1024
- * smart scheduling ({provider, model, api_key_ref, mode}, or null to turn it off), picked up by the running service at
1025
- * its next tick. Everything is read at each delivery, so it applies from the next execution and keeps every session.
1026
- */
1027
- export async function room_settings(home, raw) {
1028
- const { input, path } = await member_room_context(home, raw);
1029
- const { api_max_requests: requests, extra_directories: directories, cwd, image_generation: images, scheduler } = input;
1030
- if (requests === undefined && directories === undefined && cwd === undefined && images === undefined && scheduler === undefined) throw new Error('须提供 api_max_requests、image_generation、scheduler、cwd 或 extra_directories');
1031
- if (scheduler !== undefined && scheduler !== null && (typeof scheduler !== 'object' || Array.isArray(scheduler))) throw new Error('scheduler 须为智能调度配置或 null');
1032
- if (requests !== undefined && !Number.isInteger(requests)) throw new Error('api_max_requests 须为整数');
1033
- if (images !== undefined && typeof images !== 'boolean') throw new Error('image_generation 须为 true 或 false');
1034
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1035
- try {
1036
- const config = configuration_snapshot(path).config;
1037
- const next = { ...config, ...(requests !== undefined ? { api_max_requests: requests } : {}), ...(images !== undefined ? { image_generation: images } : {}) };
1038
- // Off is written as null, not dropped, so the running service's merge of the new configuration turns it off too.
1039
- if (scheduler !== undefined) next.scheduler = scheduler && { provider: scheduler.provider, model: scheduler.model, api_key_ref: scheduler.api_key_ref, ...(scheduler.mode ? { mode: scheduler.mode } : {}) };
1040
- if (cwd !== undefined) {
1041
- if (config.cwd) throw new Error('本房间已有项目目录,建房后不能更改;可添加其他项目目录');
1042
- if (typeof cwd !== 'string' || !isAbsolute(cwd) || !existsSync(cwd) || !statSync(cwd).isDirectory()) throw new Error('项目目录须为本机已有文件夹的完整路径');
1043
- next.cwd = cwd;
1044
- next.participants = Object.fromEntries(Object.entries(config.participants || {}).map(([name, profile]) => [name, { ...profile, cwd: profile.cwd ?? '' }]));
1045
- }
1046
- if (directories !== undefined) {
1047
- check_extra_directories(next.cwd, directories);
1048
- next.extra_directories = directories.length ? directories : undefined;
1049
- }
1050
- validate_config(next, dirname(path));
1051
- atomic_json(path, next);
1052
- return { room_id: input.room_id, ...(requests !== undefined ? { api_max_requests: requests } : {}), ...(images !== undefined ? { image_generation: images } : {}),
1053
- ...(scheduler !== undefined ? { scheduler: next.scheduler ? { provider: next.scheduler.provider, model: next.scheduler.model, mode: next.scheduler.mode || DEFAULT_SCHEDULER_MODE } : null } : {}),
1054
- ...(cwd !== undefined ? { project_directory: cwd } : {}), ...(directories !== undefined ? { extra_directories: directories } : {}) };
1055
- } finally { release(); }
1056
- }
1057
-
1058
- /**
1059
- * Switch one woken member's project files between read-only and writable after the room is created. Every run builds its
1060
- * permissions from the configuration, so the change applies from the member's next delivery and keeps its session.
1061
- */
1062
- export async function room_member_access(home, raw) {
1063
- const { input, path } = await member_room_context(home, raw);
1064
- const { name, project_access } = input;
1065
- if (!PROJECT_ACCESS.includes(project_access)) throw new Error('project_access 只能为 read、write、auto 或 full');
1066
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1067
- try {
1068
- const config = configuration_snapshot(path).config;
1069
- const profile = config.participants?.[name];
1070
- if (!profile) throw new Error(`${name} 不由本机唤醒,项目权限由它自己的会话决定`);
1071
- if (profile.project_access === 'own') throw new Error(`${name} 是手动接入的成员,权限沿用它自己会话的软件设置`);
1072
- const facts = adapter_profile(profile.adapter);
1073
- // A CLI's project access is set per run; an App follows its own settings and an API member only reads.
1074
- if (!facts?.access_levels) throw new Error(!facts?.capabilities.project ? `${name} 没有本机文件工具,项目固定只读` : `${name} 的项目权限在 App 内设置`);
1075
- if (!facts.access_levels.includes(project_access)) throw new Error(facts.unsupported_hints?.[project_access] || `${facts.label} 不支持此档位`);
1076
- if (facts.own_project_when_bound && profile.session_id) throw new Error(`${name} 续接的是它自己的 ${facts.label} 对话,项目权限沿用该对话所在项目,请在原软件中设置`);
1077
- if (project_access === 'write' && !(profile.cwd || config.cwd)) throw new Error('本房间没有指定项目目录,可写没有作用;请在新建房间时选择项目目录');
1078
- const next = { ...config, participants: { ...config.participants, [name]: { ...profile, project_access } } };
1079
- validate_config(next, dirname(path));
1080
- atomic_json(path, next);
1081
- return { room_id: input.room_id, member: name, project_access };
1082
- } finally { release(); }
1083
- }
1084
-
1085
- /**
1086
- * Change a woken CLI or API member's model and thinking effort after the room is created. Each run passes them to the
1087
- * software, and neither is part of the member's session context, so the change applies from its next delivery and keeps
1088
- * its session. An empty value goes back to the software's default; an API member has no default model, so an empty
1089
- * model keeps its current one.
1090
- */
1091
- export async function room_member_model(home, raw) {
1092
- const { input, path } = await member_room_context(home, raw);
1093
- const { name } = input;
1094
- const model = typeof input.model === 'string' ? input.model.trim() : '';
1095
- const effort = typeof input.effort === 'string' ? input.effort.trim() : '';
1096
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1097
- try {
1098
- const config = configuration_snapshot(path).config;
1099
- const profile = config.participants?.[name];
1100
- if (!profile) throw new Error(`${name} 不由本机唤醒,模型由它自己的会话决定`);
1101
- if (profile.project_access === 'own') throw new Error(`${name} 是手动接入的成员,模型与强度沿用它自己会话的设置`);
1102
- const facts = adapter_profile(profile.adapter);
1103
- // An App chooses its model and effort in its own window; a CLI or API member's run is started with them.
1104
- if (!facts || facts.kind === 'app') throw new Error(`${name} 的模型在 ${facts?.label || '它的软件'} 内设置`);
1105
- if (effort && !facts.efforts?.includes(effort)) {
1106
- throw new Error(`${facts.label} 不支持思考强度 ${effort}${facts.efforts ? `,可选 ${facts.efforts.join(' / ')}` : ''}`);
1107
- }
1108
- const next = { ...profile, model: model || (facts.kind === 'api' ? profile.model : ''), effort };
1109
- if (!next.model) delete next.model;
1110
- if (!effort) delete next.effort;
1111
- const updated = { ...config, participants: { ...config.participants, [name]: next } };
1112
- validate_config(updated, dirname(path));
1113
- atomic_json(path, updated);
1114
- return { room_id: input.room_id, member: name, model: next.model || '', effort };
1115
- } finally { release(); }
1116
- }
1117
-
1118
- const MAX_ALLOWED_TOOLS = 50;
1119
-
1120
- /**
1121
- * Allow operations a woken member's software refused, by adding the rules the runner reported with them to its
1122
- * `allowed_tools`: Claude passes them to `--allowedTools`, agy adds them to its discussion project's grants. Like the
1123
- * project access, they apply from the member's next delivery and keep its session.
1124
- */
1125
- export async function room_member_allow(home, raw) {
1126
- const { input, path } = await member_room_context(home, raw);
1127
- const { name, rules } = input;
1128
- if (!Array.isArray(rules) || !rules.length || rules.some(rule => typeof rule !== 'string' || !rule.trim() || rule.length > 300)) {
1129
- throw new Error('rules 须为要放行的规则列表');
1130
- }
1131
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1132
- try {
1133
- const config = configuration_snapshot(path).config;
1134
- const profile = config.participants?.[name];
1135
- if (!profile) throw new Error(`${name} 不由本机唤醒,权限由它自己的会话决定`);
1136
- const facts = adapter_profile(profile.adapter);
1137
- if (!facts?.per_tool_allow) throw new Error(`${name} 的软件不支持逐条放行,请改用更高的权限档位`);
1138
- if (facts.own_project_when_bound && profile.session_id) throw new Error(`${name} 续接的是它自己的 ${facts.label} 对话,权限沿用该对话所在项目,请在原软件中设置`);
1139
- const allowed_tools = [...new Set([...(profile.allowed_tools || []), ...rules.map(rule => rule.trim())])];
1140
- if (allowed_tools.length > MAX_ALLOWED_TOOLS) throw new Error(`每位成员最多放行 ${MAX_ALLOWED_TOOLS} 条规则`);
1141
- const next = { ...config, participants: { ...config.participants, [name]: { ...profile, allowed_tools } } };
1142
- validate_config(next, dirname(path));
1143
- atomic_json(path, next);
1144
- return { room_id: input.room_id, member: name, allowed_tools };
1145
- } finally { release(); }
1146
- }
1147
-
1148
- /**
1149
- * Switch an idle free-room Codex member between the App and the CLI, keeping its conversation: the App resumes the
1150
- * bound chat by its session, and the CLI resumes it only after the App has released it. Model and effort are chosen
1151
- * in the App, so switching to it drops them.
1152
- */
1153
- export async function room_member_adapter(home, raw) {
1154
- const { input, path } = await member_room_context(home, raw);
1155
- const { name, adapter } = input;
1156
- if (!ADAPTER_IDS.some(other => same_session_family(other, adapter))) throw new Error('只能在共用会话的 App 与 CLI 接入之间切换');
1157
- const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1158
- const member = room.free.members.find(item => item.name === name);
1159
- if (member?.pending > 0 || ['dispatched', 'started'].includes(member?.execution?.status)) throw new Error(`${name} 正在处理请求,请等它完成或先停止`);
1160
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1161
- try {
1162
- const config = configuration_snapshot(path).config;
1163
- const profile = config.participants?.[name];
1164
- if (profile?.adapter !== adapter && !same_session_family(profile?.adapter, adapter)) throw new Error(`${name} 不是本机唤醒、能切换到该接入方式的成员`);
1165
- if (profile.adapter === adapter) return { room_id: input.room_id, member: name, adapter };
1166
- const context = { config, path };
1167
- const next = { ...profile };
1168
- switch_codex_adapter(context, name, next, adapter);
1169
- // An App chooses its own model and effort.
1170
- if (!adapter_profile(adapter).models) delete next.model;
1171
- if (!adapter_profile(adapter).efforts) delete next.effort;
1172
- const updated = { ...config, participants: { ...config.participants, [name]: next } };
1173
- validate_config(updated, dirname(path));
1174
- atomic_json(path, updated);
1175
- return { room_id: input.room_id, member: name, adapter };
1176
- } finally { release(); }
1177
- }
1178
-
1179
- /**
1180
- * Register a manual Claude, Codex or agy expert's own session as a hosted participant, so the service resumes it for later turns.
1181
- * Returns the adapter used. Throws when the local software is not configured or the session is not found on this machine; the member then stays manual.
1182
- */
1183
- export function adopt_member_profile(home, path, name, session_id, client, member_token) {
1184
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1185
- try {
1186
- const config = configuration_snapshot(path).config;
1187
- // The adapter whose store holds the session: a desktop chat is resumed through its App, others through the CLI.
1188
- const adapter = adoption_adapter(client, session_id);
1189
- if (!adapter) throw new Error(`${name}:本机不能接管 ${client} 的会话`);
1190
- // An App conversation is reached through this room's own Sidecar, which the App starts as soon as it is configured.
1191
- const sidecar = adapter_profile(adapter).location === 'ipc_directory' ? { ipc_directory: join(dirname(path), 'agy-app-sidecar') } : {};
1192
- // A manually started member keeps its own session's permissions; the room's 只读 / 可写 does not apply to it.
1193
- const input = { cwd: config.cwd, adopt: true, participants: { [name]: { adapter, session_id, project_access: 'own', ...sidecar } } };
1194
- // Its model, effort, prompt and tools stay as the user set them in that session; machine defaults never override them.
1195
- const { model, effort, allowed_tools, system_prompt, ...own } = participant_profile(name, launch_settings(home).participants, input, false);
1196
- const profile = borrowed_session(name, own, config.cwd);
1197
- if (sidecar.ipc_directory) setup_sidecar(sidecar);
1198
- // A room delivers with each member's own credential; the browser-made one is not kept locally, so the owner issues a new one.
1199
- const next = { ...config, participants: { ...config.participants, [name]: profile },
1200
- members: { ...config.members, [name]: { token: member_token, pending: '' } } };
1201
- validate_config(next, dirname(path));
1202
- atomic_json(path, next);
1203
- return adapter;
1204
- } finally { release(); }
1205
- }
1206
-
1207
- /** The one registered configuration of a room on this machine, or null when it was never registered here. */
1208
- function registered_room_path(home, site, room_id) {
1209
- const paths = read_registry(home).filter(path => {
1210
- const identity = registered_identity(path);
1211
- return identity?.site === site && identity.room === room_id;
1212
- });
1213
- if (paths.length > 1) throw new Error('本房间存在多份登记配置,无法确定成员会话');
1214
- return paths[0] || null;
1215
- }
1216
-
1217
- /** The session each participant actually resumes, read without writing to a runtime the service may be using. */
1218
- function bound_sessions(config, path) {
1219
- const file = join(resolve(config.data_directory || join(dirname(path), `discussion-${config.room}`)), 'runtime.sqlite3');
1220
- if (!existsSync(file)) return {};
1221
- const db = new DatabaseSync(file, { readOnly: true });
1222
- try { return Object.fromEntries(db.prepare('SELECT participant,session_id FROM bindings').all().map(row => [row.participant, row.session_id])); }
1223
- finally { db.close(); }
1224
- }
1225
-
1226
- /**
1227
- * Export a room's local member software and the sessions they hold, so a backup imported on this machine resumes them.
1228
- * Requires the owner's credential; member credentials and API keys are never included (only the key reference).
1229
- * Returns `local_members: null` when the room is not registered here.
1230
- */
1231
- export async function room_profiles(home, raw) {
1232
- const input = launch_input({ ...raw, entry: 'web' });
1233
- if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('导出本机成员配置须提供房间编号和房间控制凭据');
1234
- const path = registered_room_path(home, input.site, input.room_id);
1235
- if (!path) return { room_id: input.room_id, local_members: null };
1236
- const config = configuration_snapshot(path).config;
1237
- await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
1238
- const sessions = bound_sessions(config, path);
1239
- const participants = Object.fromEntries(Object.entries(config.participants).map(([name, profile]) => {
1240
- const kept = Object.fromEntries(Object.entries(profile).filter(([key]) => [...PROFILE_FIELDS, 'project_access'].includes(key)));
1241
- const session_id = sessions[name] || profile.session_id;
1242
- return [name, session_id ? { ...kept, session_id } : kept];
1243
- }));
1244
- return { room_id: input.room_id, local_members: { format: LOCAL_MEMBERS_FORMAT, version: 1, mode: 'free',
1245
- cwd: config.cwd, discussion_project: config.discussion_project, project_access: config.project_access, scheduler: config.scheduler,
1246
- workflow: config.workflow, participants } };
1247
- }
1248
-
1249
- /**
1250
- * Register an imported free room on this machine with its exported member software, each member resuming its original session.
1251
- * A session or software missing here fails that member instead of starting a new conversation. Claude Code members stay manual,
1252
- * and are never taken over, because a background resume forks the session away from its original window.
1253
- * Returns `{room_id, registered, members: [{name, status: resumed|manual|failed, session_id?, cwd?, error?}]}`.
1254
- */
1255
- export async function restore_room(home, raw) {
1256
- const input = launch_input({ ...raw, entry: 'web' });
1257
- const local = input.local_members;
1258
- if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('恢复本机成员须提供房间编号和房间控制凭据');
1259
- if (local?.format !== LOCAL_MEMBERS_FORMAT || local.version !== 1 || !local.participants || typeof local.participants !== 'object') throw new Error('本机成员配置格式无效');
1260
- await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
1261
- const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1262
- if (registered_room_path(home, input.site, input.room_id)) throw new Error('本房间已在本机登记,不重复恢复');
1263
- if (local.cwd && (!isAbsolute(local.cwd) || !existsSync(local.cwd) || !statSync(local.cwd).isDirectory())) throw new Error(`房间项目目录 ${local.cwd} 在本机不存在`);
1264
- const keep_manual = room.free.members.filter(member => member.access === 'manual' && member.status !== 'removed'
1265
- && platform_adapters(platform_of(member.name)).some(id => ADAPTER_PROFILES[id].restore_manual)).map(member => member.name);
1266
- const participants = {}, members = [];
1267
- for (const [name, exported] of Object.entries(local.participants)) {
1268
- try {
1269
- const profile = participant_profile(name, {}, { cwd: local.cwd, adopt: true, participants: { [name]: exported } }, false);
1270
- // A member whose software cannot take over other conversations (an API member) resumes only its own session, and
1271
- // only while this machine still has it; otherwise, like one without a session store, it starts fresh.
1272
- const software = adapter_of(profile.adapter);
1273
- if (!software?.session || (!software.adopt && !software.session.exists(profile.session_id))) delete profile.session_id;
1274
- const resumed = profile.session_id && software.adopt ? borrowed_session(name, profile, local.cwd) : profile;
1275
- if (adapter_profile(profile.adapter)?.restore_manual) {
1276
- keep_manual.push(name);
1277
- const cwd = resumed.cwd || local.cwd || '';
1278
- const command = resumed.session_id && adapter_profile(profile.adapter).resume_command?.(resumed.session_id);
1279
- members.push({ name, status: 'manual', session_id: resumed.session_id || '', cwd,
1280
- resume: command ? { command, cwd } : null });
1281
- } else {
1282
- participants[name] = resumed;
1283
- members.push({ name, status: 'resumed', session_id: resumed.session_id || '' });
1284
- }
1285
- } catch (error) { members.push({ name, status: 'failed', error: error.message }); }
1286
- }
1287
- if (!Object.keys(participants).length && !local.cwd && !local.scheduler) return { room_id: input.room_id, registered: false, members };
1288
- register_copied_room(home, input, local, participants, keep_manual);
1289
- return { room_id: input.room_id, registered: true, members };
1290
- }
1291
-
1292
- /**
1293
- * Register an imported or forked free room's local members under a fresh launch directory; `seed` writes the new
1294
- * runtime's bindings before the service can see the room. Returns the runtime directory.
1295
- */
1296
- function register_copied_room(home, input, local, participants, keep_manual, seed = () => {}) {
1297
- const key = createHash('sha256').update(`${input.site}/${input.room_id}`).digest('hex');
1298
- // A leftover directory of a deleted room with the same ID would carry its old bindings, so a restore never reuses one.
1299
- const base = join(home, 'launches', key), directory = existsSync(base) ? `${base}-${Date.now()}` : base;
1300
- // Members arrive away; these placeholders are replaced by the credential issued when the owner brings each one back.
1301
- const config = { site: input.site, room: input.room_id, token: input.token, mode: 'free', participants, keep_manual, api_home: home,
1302
- members: Object.fromEntries(Object.keys(participants).map(name => [name, { token: `${randomUUID()}${randomUUID()}`, pending: '' }])),
1303
- scheduler: local.scheduler || undefined, cwd: local.cwd || undefined, discussion_project: local.discussion_project || undefined,
1304
- project_access: local.project_access || undefined, workflow: local.workflow || undefined, data_directory: join(directory, 'runtime'), draft_directory: service_drafts(home, join(directory, 'runtime')) };
1305
- validate_config(config, directory);
1306
- mkdirSync(directory, { recursive: true });
1307
- atomic_json(join(directory, 'config.json'), config);
1308
- seed(config.data_directory);
1309
- register_room(home, join(directory, 'config.json'));
1310
- return config.data_directory;
1311
- }
1312
-
1313
- // Software whose session a fork branches; other local members start a new conversation in the forked room.
1314
-
1315
- /**
1316
- * Register a room forked from another on this machine: each local member continues from its own session as it stood
1317
- * at the fork point, without the executions the fork leaves out. The source room's sessions are never changed.
1318
- * Requires both rooms' owner credentials; members the new room keeps manual are not registered here.
1319
- * Returns `{room_id, registered, members: [{name, status: forked|fresh|failed, error?}]}`.
1320
- */
1321
- export async function fork_room(home, raw) {
1322
- const input = launch_input({ ...raw, entry: 'web' });
1323
- if (!input.room_id || typeof input.token !== 'string' || !input.token.trim() || typeof raw.source_room_id !== 'string' || typeof raw.source_token !== 'string') {
1324
- throw new Error('分支须提供新房间与原房间的编号和控制凭据');
1325
- }
1326
- const local = (await room_profiles(home, { site: input.site, room_id: raw.source_room_id, token: raw.source_token })).local_members;
1327
- if (!local) return { room_id: input.room_id, registered: false, members: [] };
1328
- await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
1329
- const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1330
- if (registered_room_path(home, input.site, input.room_id)) throw new Error('分支房间已在本机登记');
1331
- const runners = new Set(room.free.members.filter(member => member.access === 'runner' && member.status !== 'removed').map(member => member.name));
1332
- const left_out = raw.executions && typeof raw.executions === 'object' ? raw.executions : {};
1333
- const participants = {}, members = [], bindings = {}, forks = {};
1334
- for (const [name, exported] of Object.entries(local.participants)) {
1335
- if (!runners.has(name)) continue;
1336
- try {
1337
- const profile = participant_profile(name, {}, { cwd: local.cwd, adopt: true, participants: { [name]: exported } }, false);
1338
- if (!profile.session_id || !BRANCHABLE_ADAPTERS.includes(profile.adapter)) {
1339
- delete profile.session_id;
1340
- participants[name] = profile;
1341
- members.push({ name, status: 'fresh' });
1342
- continue;
1343
- }
1344
- // Claude resumes a session only in its original directory, so the forked member works there too.
1345
- const located = adapter_profile(profile.adapter)?.adopt === 'own_cwd' ? borrowed_session(name, profile, local.cwd) : profile;
1346
- const branch = await branch_session(located, profile.session_id, (left_out[name] || []).filter(Number.isInteger), { always: true });
1347
- const { session_id, ...forked } = located;
1348
- participants[name] = forked;
1349
- bindings[name] = branch.session_id;
1350
- if (branch.fork) forks[name] = branch.fork;
1351
- members.push({ name, status: branch.session_id ? 'forked' : 'fresh' });
1352
- } catch (error) { members.push({ name, status: 'failed', error: error.message }); }
1353
- }
1354
- if (!Object.keys(participants).length && !local.cwd && !local.scheduler) return { room_id: input.room_id, registered: false, members };
1355
- register_copied_room(home, input, local, participants, [], data_directory => {
1356
- const store = new DiscussionStore(data_directory);
1357
- try {
1358
- for (const [name, session_id] of Object.entries(bindings)) store.bind(name, session_id);
1359
- // A Claude fork happens on the member's next turn; the runner keeps it pending until that session exists.
1360
- for (const [name, fork] of Object.entries(forks)) store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value')
1361
- .run(`session-fork:${name}`, JSON.stringify(fork));
1362
- } finally { store.close(); }
1363
- });
1364
- return { room_id: input.room_id, registered: true, members };
1365
- }
1366
-
1367
- /** Stable signatures make changed retry requests explicit without putting credentials in receipts. */
1368
- function signature(value) {
1369
- if (Array.isArray(value)) return `[${value.map(signature).join(',')}]`;
1370
- if (value && typeof value === 'object') return `{${Object.keys(value).sort().filter(key => value[key] !== undefined).map(key => `${JSON.stringify(key)}:${signature(value[key])}`).join(',')}}`;
1371
- return JSON.stringify(value);
1372
- }
1373
-
1374
- /** Inherit the topic duration unless overridden; zero leaves the run without a time limit. */
1375
- function launch_minutes(input, room) {
1376
- const minutes = Number(input.minutes ?? room.limits?.max_minutes ?? 0);
1377
- if (!Number.isFinite(minutes) || minutes < 0 || minutes > MAX_MINUTES) throw new Error('讨论总时长或 minutes 须在 [0,1440],0 表示不限时长');
1378
- return minutes;
1379
- }
1380
-
1381
- /** Refuse a second registry owner before changing the website runtime. */
1382
- function check_registration(home, config, path) {
1383
- for (const registered of read_registry(home)) {
1384
- if (resolve(registered) === path || !existsSync(registered)) continue;
1385
- const other = registered_identity(registered);
1386
- if (other?.site === config.site && other.room === config.room) throw new Error('房间已使用另一份接入配置登记;请沿用原配置,不重复接入');
1387
- }
1388
- }
1389
-
1390
- /** Start a session once, reconciling a lost response from the durable start intent. */
1391
- async function start_session(config, record, persist, room, minutes) {
1392
- const state = await api(config, '/discussion');
1393
- if (record.session_id && state.session?.id === record.session_id && !record.start_pending) {
1394
- if (record.start_submission_id && state.session.start_submission_id !== record.start_submission_id) {
1395
- throw new Error('房间当前讨论的启动编号与本次记录不同');
1396
- }
1397
- if (state.session.status !== 'active') throw new Error('讨论已暂停或结束;请在房间核对状态后再操作');
1398
- return state.session;
1399
- }
1400
- if (record.session_id && state.session?.id !== record.session_id) throw new Error('房间当前讨论与本次启动记录不同');
1401
- if (state.session && !record.start_pending) {
1402
- if (state.session.status !== 'active') throw new Error('讨论已暂停或结束;请在房间核对状态后再操作');
1403
- throw new Error('房间已有进行中的讨论;请沿用原启动记录');
1404
- }
1405
- if (room.session?.status === 'concluded' && !record.start_pending) throw new Error('房间中的讨论已结束;请从房间明确开启新讨论');
1406
- if (!record.start_submission_id) record.start_submission_id = randomUUID();
1407
- if (!record.start_request) {
1408
- if (record.start_revision && record.start_revision !== state.revision) throw new Error('开启期间讨论状态已变化,请重新读取房间状态');
1409
- const topic_minutes = Number(room.limits?.max_minutes || 0);
1410
- const session_minutes = topic_minutes > 0 ? (minutes > 0 ? Math.min(topic_minutes, minutes) : topic_minutes) : minutes;
1411
- record.start_revision = state.revision;
1412
- record.start_request = { action: 'start', revision: state.revision, submission_id: record.start_submission_id,
1413
- goal: room.goal || room.title, named_followup: Boolean(room.named_followup),
1414
- limits: { max_rounds: room.limits?.max_rounds ?? 0, max_minutes: session_minutes,
1415
- execution_minutes: room.limits?.execution_minutes ?? 0 } };
1416
- record.start_pending = true;
1417
- persist();
1418
- }
1419
- const result = await api(config, '/discussion', record.start_request);
1420
- if (!result.session || result.session.start_submission_id !== record.start_submission_id) throw new Error('网站返回的讨论会话与本次启动编号不符');
1421
- record.session_id = result.session.id;
1422
- record.start_pending = false;
1423
- persist();
1424
- if (result.session.status !== 'active') throw new Error('本次讨论已暂停或结束;请在房间核对状态后再操作');
1425
- return result.session;
1426
- }
1427
-
1428
- /** Reserve the first host task for the calling conversation without sending it a duplicate prompt. */
1429
- async function current_host_task(config, record, persist, room) {
1430
- if (record.current_task) return record.current_task;
1431
- const discussion = await api(config, '/discussion');
1432
- if (discussion.session?.status !== 'active' || discussion.session.id !== record.session_id) throw new Error('本次讨论会话已暂停、结束或变化;请核对原房间');
1433
- const page = await api(config, '/inbox');
1434
- const member = page.members.find(item => item.name === room.host && item.role === 'host');
1435
- const request = member?.pending.find(item => item.purpose === 'discuss_host' && item.session_id === record.session_id);
1436
- if (!member || (!request && !record.execution_client_id && !record.execution_id)) throw new Error('没有可由当前会话接手的主持请求;请核对原房间');
1437
- record.execution_client_id ||= randomUUID();
1438
- persist();
1439
- const execution = record.execution_id ? await api(config, `/executions/${record.execution_id}`)
1440
- : await api(config, '/executions', { member_id: member.id, client_id: record.execution_client_id, cwd: '' });
1441
- if (!['dispatched', 'started'].includes(execution.status)) throw new Error('主持请求已不再等待执行;请核对原房间');
1442
- if (!execution.requests?.some(item => item.purpose === 'discuss_host' && item.session_id === record.session_id)) {
1443
- throw new Error('预约到的执行不属于本次讨论主持请求');
1444
- }
1445
- record.execution_id = execution.id;
1446
- persist();
1447
- const store = new DiscussionStore(config.directory);
1448
- try {
1449
- store.context(config);
1450
- store.scope(config);
1451
- const session_id = config.participants[room.host].session_id;
1452
- store.bind(room.host, session_id);
1453
- const task = free_task_files(config, member, execution, { session_id }, { session: discussion.session, process_access: false });
1454
- new FreeRoomRunner(config, store).save(room.host, { client_id: record.execution_client_id, execution_id: execution.id,
1455
- status: 'running', attempts: 0, started: Date.now(), last_renew: Date.now() });
1456
- record.current_task = { execution_id: execution.id, access_file: task.access_path, task_file: join(config.directory, `${task.id}.task.json`) };
1457
- persist();
1458
- return record.current_task;
1459
- } finally { store.close(); }
1460
- }
1461
-
1462
- /** Return launch evidence and paths, never raw control or execution tokens. */
1463
- async function launch_receipt(config, record, config_path) {
1464
- const room = await api(config, '');
1465
- const discussion = record.session_id ? await api(config, '/discussion') : null;
1466
- return { entry: record.entry, room, url: `${config.site}/?room=${config.room}`, config_path,
1467
- status: discussion?.session?.status || (record.session_id ? 'concluded' : 'free'), current_task: record.current_task || null };
1468
- }
1469
-
1470
- /** Read a saved launch without creating state during validation or preview. */
1471
- function read_launch(directory) {
1472
- const path = join(directory, 'launch.json');
1473
- return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null;
1474
- }
1475
-
1476
- /** Find the registered room only after proving the caller's original control credential. */
1477
- async function room_config_context(home, raw, options = {}) {
1478
- const input = launch_input({ ...raw, entry: 'web' });
1479
- if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('读取本场配置须提供房间编号和原控制凭据');
1480
- const room = options.local_guard ? { id: input.room_id, archived: false }
1481
- : await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1482
- const config = { site: input.site, room: input.room_id, token: input.token };
1483
- if (!options.local_guard) await verify_control(config, room);
1484
- const discussion = options.local_guard
1485
- ? { session: { status: 'paused' }, revision: raw.session_revision ?? raw.runtime_revision }
1486
- : await api(config, '/discussion');
1487
- if (room.archived || discussion.session?.status !== 'paused') throw new Error('请先暂停本场讨论,再修正软件路径');
1488
- const paths = read_registry(home).filter(path => {
1489
- const identity = registered_identity(path);
1490
- return identity?.site === input.site && identity.room === input.room_id;
1491
- });
1492
- if (paths.length !== 1) throw new Error('未找到本场唯一的已登记配置,请核对原接入服务');
1493
- const path = paths[0];
1494
- const journal = read_launch(dirname(path));
1495
- if (journal && !journal.finished) throw new Error('本次启动尚未完成,请先核对原启动待办');
1496
- return { input, room, discussion, path, ...configuration_snapshot(path) };
1497
- }
1498
-
1499
- /** Expose only editable connection paths, never credentials or unrelated room settings. */
1500
- function connection_view(context) {
1501
- return { room_id: context.room.id, session_revision: context.discussion.revision, runtime_revision: context.discussion.revision, version: context.version,
1502
- participants: Object.fromEntries(Object.entries(context.config.participants).map(([name, profile]) =>
1503
- [name, Object.fromEntries(['adapter', ...CONNECTION_FIELDS].filter(field => profile[field] !== undefined).map(field => [field, profile[field]]))])) };
1504
- }
1505
-
1506
- /** Switch only Codex's execution entrypoint, keeping its actual original conversation. */
1507
- function switch_codex_adapter(context, name, profile, adapter) {
1508
- if (!same_session_family(profile.adapter, adapter)) throw new Error('本场仅支持共用会话的 App / CLI 接入之间切换');
1509
- const current = validate_config(context.config, dirname(context.path));
1510
- let session = profile.session_id;
1511
- if (existsSync(join(current.directory, 'runtime.sqlite3'))) {
1512
- const store = new DiscussionStore(current.directory);
1513
- try {
1514
- const binding = store.binding(name).session_id;
1515
- if (session && binding && session !== binding) throw new Error('原会话绑定不一致,请先核对原会话');
1516
- session = binding || session;
1517
- } finally { store.close(); }
1518
- }
1519
- if (!session) throw new Error('尚无实际 Codex 会话,不能切换;请先完成首次接入');
1520
- profile.adapter = adapter;
1521
- profile.session_id = session;
1522
- }
1523
-
1524
- /** Validate paused-room paths and Codex entrypoints without replacing the discussion or session. */
1525
- function corrected_configuration(context) {
1526
- const config = structuredClone(context.config);
1527
- for (const [name, patch] of Object.entries(context.input.participants)) {
1528
- const profile = config.participants[name];
1529
- const field = adapter_profile(profile?.adapter)?.location || 'executable';
1530
- const fields = ADAPTER_IDS.some(other => same_session_family(other, profile?.adapter)) ? [field, 'adapter'] : [field];
1531
- if (!profile || !patch || typeof patch !== 'object' || Array.isArray(patch) || Object.keys(patch).some(key => !fields.includes(key))) throw new Error('本场修正仅支持软件路径、Sidecar 目录及 Codex App / CLI;参与者、项目及会话保持不变');
1532
- validate_profile(name, patch);
1533
- if (patch.adapter && patch.adapter !== profile.adapter) switch_codex_adapter(context, name, profile, patch.adapter);
1534
- const path = patch[field] ?? profile[field];
1535
- if (typeof path !== 'string' || !path || !existsSync(path)
1536
- || (field === 'executable' ? !statSync(path).isFile() || (process.platform === 'win32' && !/\.exe$/i.test(path)) : !statSync(path).isDirectory())) throw new Error(`${name}:请提供有效的软件文件或连接目录`);
1537
- profile[field] = path;
1538
- }
1539
- validate_config(config, dirname(context.path));
1540
- return config;
1541
- }
1542
-
1543
- /** Wait for the resident worker to read this version before suggesting a manual restart. */
1544
- async function configuration_applied(home, path, version) {
1545
- for (let waited = 0; waited < CONFIG_APPLY_TIMEOUT_MS; waited += CONFIG_APPLY_POLL_MS) {
1546
- const pid = service_pid(home);
1547
- if (!pid) return false;
1548
- const status_path = join(home, 'status.json');
1549
- const status = existsSync(status_path) ? JSON.parse(readFileSync(status_path, 'utf8')) : {};
1550
- const worker = status.rooms?.find(item => resolve(item.config) === resolve(path));
1551
- if (status.pid === pid && worker?.config_version === version && worker.status !== 'error') return true;
1552
- await sleep(CONFIG_APPLY_POLL_MS);
1553
- }
1554
- return false;
1555
- }
1556
-
1557
- /** Read or save a paused room's connection paths without changing its runtime or global defaults. */
1558
- export async function room_configuration(home, raw, options = {}) {
1559
- let context = await room_config_context(home, raw, options);
1560
- if (raw.participants !== undefined && !options.local_guard) {
1561
- const saved = await save_room_connection(raw);
1562
- return { ...saved, applied: await configuration_applied(home, context.path, saved.version) };
1563
- }
1564
- if (raw.participants === undefined) return connection_view(context);
1565
- if (!raw.participants || typeof raw.participants !== 'object' || Array.isArray(raw.participants)) throw new Error('participants 须为本场软件路径对象');
1566
- const release = acquire_lock(join(dirname(context.path), 'configuration-edit'));
1567
- try {
1568
- context = await room_config_context(home, raw, options);
1569
- const config = corrected_configuration(context);
1570
- if (raw.version !== context.version || (raw.session_revision ?? raw.runtime_revision) !== context.discussion.revision) throw new Error('房间状态或配置已变化,请重新读取本场配置后核对');
1571
- atomic_json(context.path, config);
1572
- const saved = { ...context, ...configuration_snapshot(context.path) };
1573
- // The local website holds its database write lock here; the worker can acknowledge only after that lock is released.
1574
- return { ...connection_view(saved), applied: false };
1575
- } finally { release(); }
1576
- }
1577
-
1578
- /** Serialize file replacement with runtime changes through the local website's database guard. */
1579
- async function save_room_connection(raw) {
1580
- const input = launch_input({ ...raw, entry: 'web' });
1581
- const url = new URL(input.site);
1582
- if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(url.hostname)) throw new Error('本场路径修正须通过已启用本机启动的回环网站');
1583
- const response = await fetch(`${input.site}/api/local/room-config`, { method: 'POST',
1584
- headers: { 'Content-Type': 'application/json', 'X-CoDiscuss-Local': '1' },
1585
- body: JSON.stringify(input), redirect: 'error', signal: AbortSignal.timeout(15000) });
1586
- const result = await response.json();
1587
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${result.error || '本场配置保存失败'}`);
1588
- return result;
1589
- }
1590
-
1591
- /** Prove dispatcher access before a protected room is started or a corrected credential is saved. */
1592
- async function verify_control(config, room) {
1593
- await api({ ...config, room: room.id }, '/inbox');
1594
- }
1595
-
1596
- /** Pin resolved defaults, while comparing retries against only the caller's explicit request. */
1597
- async function prepare_launch(home, input, directory, options = {}) {
1598
- const previous = read_launch(directory);
1599
- if (options.browser_request && (typeof input.token !== 'string' || !input.token.trim())) throw new Error('网页启动须携带本次原始控制凭据,不能认领其他启动记录');
1600
- const { token: ignored_token, access_file: ignored_access, ...request } = input;
1601
- const request_signature = signature(request);
1602
- if (previous?.request_signature && previous.request_signature !== request_signature) throw new Error('启动配置与原请求不同;同一次重试须沿用原配置,新讨论请使用新提交编号');
1603
- const config_path = join(directory, 'config.json');
1604
- const saved = previous?.config || (previous && existsSync(config_path) ? JSON.parse(readFileSync(config_path, 'utf8')) : null);
1605
- const token = input.token || previous?.token || randomUUID();
1606
- const room_id = input.room_id || previous?.room_id || (saved?.room !== 'preview' ? saved?.room : null);
1607
- if (options.browser_request && previous && token !== previous.token && !room_id) throw new Error('尚未确认原房间,不能替换本次控制凭据');
1608
- const room = room_id ? await site_request(input.site, `/api/rooms/${room_id}`, token) : input.room;
1609
- const config = previous?.request_signature ? { ...structuredClone(saved), token }
1610
- : launch_config(home, input, room, directory, { token, defaults: saved?.participants, members: saved?.members });
1611
- config.draft_directory = service_drafts(home, config.directory);
1612
- if (previous?.request_signature && !previous.finished) validate_config(config, directory);
1613
- const minutes = previous?.minutes ?? launch_minutes(input, room);
1614
- const draft = signature({ entry: input.entry, room_id: input.room_id, room: input.room, participants: config.participants, cwd: input.cwd, discussion_project: input.discussion_project, minutes });
1615
- if (room.id) await verify_control(config, room);
1616
- return { input, config, room, minutes, draft, request_signature, directory, previous };
1617
- }
1618
-
1619
- /** Launch a room through either entry, using a durable journal for safe retries. */
1620
- export async function launch_discussion(home, raw, options = {}) {
1621
- assert_shared_home(home);
1622
- const input = launch_input(raw);
1623
- // A room created from the page without a project works in its own folder of the draft space, which is then its project.
1624
- if (!input.room_id && !input.cwd && input.entry === 'web' && !options.dry_run) input.cwd = draft_folder(home, input.room.title, input.room.submission_id);
1625
- const key = createHash('sha256').update(`${input.site}/${input.room_id || input.room.submission_id}`).digest('hex');
1626
- const directory = join(home, 'launches', key);
1627
- let release;
1628
- try {
1629
- const preview = await prepare_launch(home, input, directory, options);
1630
- if (options.dry_run) return { dry_run: true, entry: input.entry, site: input.site, room_id: input.room_id || null,
1631
- host: preview.room.host, participants: preview.config.participants, cwd: preview.config.cwd || null,
1632
- discussion_project: preview.config.discussion_project || null, minutes: preview.minutes };
1633
- release = acquire_lock(directory);
1634
- return await perform_launch(home, await prepare_launch(home, input, directory, options), options);
1635
- } catch (error) {
1636
- error.launch ||= { stage: existsSync(join(directory, 'launch.json')) ? 'unconfirmed' : 'not_started' };
1637
- throw error;
1638
- } finally { release?.(); }
1639
- }
1640
-
1641
- /** Persist preparation before writes, hand off the current host when needed, then register once. */
1642
- async function perform_launch(home, context, options) {
1643
- const { input, config, minutes, draft, request_signature, directory, previous } = context;
1644
- // This is the creation input's start-discussion choice, not the persisted room model (always free).
1645
- const discussion = previous?.discussion ?? (input.room ? input.room.mode !== 'free' : Boolean(context.room.session && context.room.session.status !== 'concluded'));
1646
- const record = previous || { token: config.token, signature: draft, request_signature, config, minutes, entry: input.entry, discussion };
1647
- record.discussion = discussion;
1648
- const persist = () => atomic_json(join(directory, 'launch.json'), record);
1649
- if (!previous) persist();
1650
- const progress = { stage: 'unconfirmed' };
1651
- try {
1652
- let room = context.room;
1653
- if (!input.room_id) room = await site_request(input.site, '/api/rooms', config.token, {
1654
- ...input.room,
1655
- members: card_order(input.room.members, [...Object.keys(config.participants).map(name => ({ name, adapter: config.participants[name].adapter,
1656
- token: config.members[name].token, access: 'runner', session_mode: config.participants[name].session_id ? 'borrowed' : 'new' })),
1657
- // Manual members keep the credentials the browser generated; nothing local is configured for them.
1658
- ...(input.room.members || []).filter(member => record.discussion ? member?.access === 'manual' : !woken_member(member))
1659
- .map(({ name, token, access }) => ({ name, token, access, adapter: '', session_mode: 'new' }))]),
1660
- });
1661
- config.room = room.id;
1662
- await verify_control(config, room);
1663
- Object.assign(progress, { stage: 'created', room_id: room.id });
1664
- Object.assign(record, { token: config.token, request_signature, config, minutes, room_id: room.id });
1665
- persist();
1666
- const config_path = join(directory, 'config.json');
1667
- check_registration(home, config, config_path);
1668
- if (record.finished) {
1669
- const saved = existsSync(config_path) ? JSON.parse(readFileSync(config_path, 'utf8')) : config;
1670
- if (saved.token !== config.token || !existsSync(config_path)) atomic_json(config_path, { ...saved, token: config.token });
1671
- return launch_receipt(config, record, config_path);
1672
- }
1673
- atomic_json(config_path, config);
1674
- const service = await (options.start_service || start_service)(home);
1675
- if (!service?.running) throw new Error('讨论服务未就绪,未开始本次讨论');
1676
- if (record.discussion) await start_session(config, record, persist, room, minutes);
1677
- progress.stage = 'started';
1678
- if (record.discussion && input.entry === 'conversation') record.current_task = await current_host_task(config, record, persist, room);
1679
- register_room(home, config_path);
1680
- record.finished = true;
1681
- persist();
1682
- return launch_receipt(config, record, config_path);
1683
- } catch (error) { error.launch = progress; throw error; }
1684
- }
1685
-
1686
- /** The workflow library: list, read, save, rename, disable or enable, delete, preview an import, or read a room's member cards. */
1687
- export function workflows_command(home, input = {}) {
1688
- const action = input.action || 'list';
1689
- if (action === 'list') return { workflows: list_workflows(home) };
1690
- if (action === 'get') return get_workflow(home, input.id);
1691
- if (action === 'save') return save_workflow(home, input.workflow, validate_preset);
1692
- if (action === 'delete') return delete_workflow(home, input.id);
1693
- if (action === 'rename') return rename_workflow(home, input.id, input.label);
1694
- if (action === 'disable' || action === 'enable') return set_workflow_disabled(home, input.id, action === 'disable');
1695
- if (action === 'preview') {
1696
- return preview_workflow(input, validate_preset, name => card_platform_ready(home, name));
1697
- }
1698
- if (action === 'room-cards') return room_cards(home, input);
1699
- throw new Error('action 须为 list、get、save、rename、disable、enable、delete、preview 或 room-cards');
1700
- }
1701
-
1702
- /** Cards made from a registered room's members as configured here, prompts verbatim; no credential or path is returned. */
1703
- async function room_cards(home, raw) {
1704
- const input = launch_input({ ...raw, entry: 'web' });
1705
- if (!input.room_id) throw new Error('读取成员卡片须提供 room_id');
1706
- const path = registered_room_path(home, input.site, input.room_id);
1707
- if (!path) throw new Error('本机没有登记这个房间');
1708
- const config = configuration_snapshot(path).config;
1709
- const room = await api(config, ''), taken = new Set();
1710
- const members = new Set((room.free?.members || []).filter(member => member.status !== 'removed').map(member => member.name));
1711
- return { cards: Object.entries(config.participants || {}).filter(([name]) => members.has(name)).map(([name, profile]) => {
1712
- const suffix = (name.split('-')[1] || platform_of(name)).toLowerCase();
1713
- let card = suffix.slice(0, 16);
1714
- for (let number = 2; taken.has(card.toLowerCase()); number++) card = `${suffix.slice(0, 16 - String(number).length)}${number}`;
1715
- taken.add(card.toLowerCase());
1716
- // A card names its member platform-card; the room member it came from may have another suffix.
1717
- return { card, name: `${platform_of(name)}-${card}`, label: room.labels?.[name] || '', description: room.descriptions?.[name] || '',
1718
- ...Object.fromEntries(['system_prompt', 'project_access', 'model', 'effort']
1719
- .filter(field => profile[field] && profile[field] !== 'own').map(field => [field, profile[field]])) };
1720
- }) };
1721
- }
1722
-
1723
- /**
1724
- * Bind a room's workflow, or end and resume it with the members it brought. Members are invited or brought back by the
1725
- * usual member commands first; enabling only records which card each member plays, and a different workflow replaces
1726
- * the binding (its members stay as ordinary members). `away` (and the older `disable`) sends its members away and ends
1727
- * it, keeping who played which card; `back` brings them back to their sessions and resumes it. `sync` refreshes it
1728
- * after a library edit (see refresh_room_workflow).
1729
- */
1730
- export async function room_workflow(home, raw) {
1731
- if (raw?.action === 'sync') return refresh_room_workflow(home, raw);
1732
- const { input, path } = await member_room_context(home, raw);
1733
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1734
- try {
1735
- const config = configuration_snapshot(path).config;
1736
- if (input.action === 'host') {
1737
- // The owner's per-room grant that lets the host save and enable workflows by itself (workflow-adopt).
1738
- const next = { ...config, host_workflows: input.allowed === true || undefined };
1739
- atomic_json(path, next);
1740
- return { room_id: input.room_id, host_workflows: Boolean(next.host_workflows) };
1741
- }
1742
- if (input.action === 'enable') {
1743
- get_workflow(home, input.workflow?.id);
1744
- assert_workflow_enabled(home, input.workflow.id);
1745
- const next = bind_room_workflow(config, { ...input.workflow, enabled: true });
1746
- validate_config({ ...next, api_home: home }, dirname(path));
1747
- atomic_json(path, next);
1748
- return { room_id: input.room_id, workflow: room_workflow_status(next, home) };
1749
- }
1750
- if (!['away', 'back', 'disable'].includes(input.action)) throw new Error('action 须为 enable、sync、away、back、disable 或 host');
1751
- if (!config.workflow?.id) throw new Error('本房间没有工作流');
1752
- const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1753
- const names = new Set(Object.values(config.workflow.members || {}));
1754
- const members = room.free.members.filter(item => names.has(item.name) && item.role !== 'host');
1755
- if (input.action === 'back') {
1756
- // Each comes back to its own session; a removed member stays removed.
1757
- for (const member of members.filter(item => item.status === 'away')) await room_member(home, { ...raw, action: 'rejoin', name: member.name }, true);
1758
- } else {
1759
- for (const member of members.filter(item => item.status === 'active')) {
1760
- await site_request(input.site, `/api/rooms/${input.room_id}/members/${member.id}`, input.token, { action: 'away' });
1761
- }
1762
- }
1763
- // Sending its members away ends the workflow; bringing them back resumes it.
1764
- const next = { ...config, workflow: { ...config.workflow, enabled: input.action === 'back' } };
1765
- atomic_json(path, next);
1766
- return { room_id: input.room_id, workflow: room_workflow_status(next, home) };
1767
- } finally { release(); }
1768
- }
1769
-
1770
- // The most a host-made card may ask for; anything above writing is lowered to it.
1771
- const HOST_CARD_ACCESS = ['read', 'write'];
1772
-
1773
- /**
1774
- * The registered room whose present host holds this task's access file.
1775
- * Returns its configuration path, configuration and the site's member list; throws for anyone else.
1776
- */
1777
- async function host_room(home, access_file) {
1778
- if (!access_file) throw new Error('凭据用 --access-file 或 DISCUSS_ACCESS_FILE');
1779
- const access = JSON.parse(readFileSync(resolve(access_file), 'utf8').replace(/^/, ''));
1780
- const path = registered_room_path(home, String(access.site || '').replace(/\/$/, ''), access.room);
1781
- if (!path) throw new Error('本机没有登记这个房间');
1782
- const config = configuration_snapshot(path).config;
1783
- const host = Object.keys(config.members || {}).find(name => config.members[name].token === access.token);
1784
- const room = await api(config, '');
1785
- const roster = room.free?.members || [];
1786
- if (!host || !roster.some(member => member.name === host && member.role === 'host' && member.status === 'active')) throw new Error('只有本房间的主持人能运行此命令');
1787
- return { path, config, roster, labels: room.labels || {}, host };
1788
- }
1789
-
1790
- const IMAGE_ACTIONS = { generate: 'generate_image', edit: 'edit_image' };
1791
-
1792
- /**
1793
- * One drawing by a member, with its task credential: `{action: generate|edit, ...the image tool's arguments}` (the same
1794
- * arguments an API member's generate_image / edit_image take). Allowed only while the room's owner has drawing on and
1795
- * this computer has an image service. The images become the member's attachments, which it posts with
1796
- * `message post --attachment ID`; project files are read and written under the member's own project access.
1797
- */
1798
- export async function draw_image(home, { access_file, request }) {
1799
- if (!access_file) throw new Error('凭据用 --access-file 或 DISCUSS_ACCESS_FILE');
1800
- const access = JSON.parse(readFileSync(resolve(access_file), 'utf8').replace(/^/, ''));
1801
- const path = registered_room_path(home, String(access.site || '').replace(/\/$/, ''), access.room);
1802
- if (!path) throw new Error('本机没有登记这个房间');
1803
- const config = configuration_snapshot(path).config;
1804
- const member = Object.keys(config.members || {}).find(name => config.members[name].token === access.token);
1805
- if (!member) throw new Error('凭据不属于本房间的成员');
1806
- if (!config.image_generation) throw new Error('本房间没有添加生图服务,请房主在“成员与设置 → 协作设置”的“生图”中添加');
1807
- const image = room_image(home, config);
1808
- if (!image) throw new Error('这台电脑的生图服务还没有填写密钥(房间“生图”卡片的设置)');
1809
- const { action, ...args } = request || {};
1810
- if (!IMAGE_ACTIONS[action]) throw new Error('action 须为 generate 或 edit');
1811
- const profile = config.participants?.[member] || {};
1812
- const project = open_project({ cwd: profile.cwd ?? config.cwd, project_access: profile.project_access === 'read' ? 'read' : 'write',
1813
- extra_directories: config.extra_directories || [] }, [home, dirname(path)]);
1814
- const context = { home, image, site: config.site, room: config.room, token: access.token, participant: member, directory: dirname(path),
1815
- project, signal: new AbortController().signal, generated_attachments: [] };
1816
- const result = await run_image_tool(context, IMAGE_ACTIONS[action], args);
1817
- if (result.error) throw new Error(result.error);
1818
- return { ...result, note: '图片已存为你的附件;回答时用 message post --attachment 附件ID 附上(可重复,最多 10 个)' };
1819
- }
1820
-
1821
- /**
1822
- * The API settings a program-started card on a platform without local software starts from, as the invite form fills
1823
- * them: the platform's official API with the key last saved here for that root. Null when the platform has saved
1824
- * software settings or local software, or no key is saved.
1825
- */
1826
- function card_api_profile(home, platform) {
1827
- if (launch_settings(home).participants[platform] || platform_adapters(platform).some(id => adapter_profile(id).kind !== 'api')) return null;
1828
- const provider = API_PROVIDERS[platform];
1829
- const api_key_ref = provider && saved_api_keys(home)[provider.base_url];
1830
- return api_key_ref ? { adapter: 'api', base_url: provider.base_url, api_protocol: provider.api_protocol, model: provider.models[0], api_key_ref } : null;
1831
- }
1832
-
1833
- /** Whether a card's platform can start here: saved software settings, or an API with a saved key. */
1834
- function card_platform_ready(home, name) {
1835
- const platform = platform_of(name || '');
1836
- return Boolean(platform && (launch_settings(home).participants[platform] || card_api_profile(home, platform)));
1837
- }
1838
-
1839
- /**
1840
- * Give cards of the room's workflow a member: a present one stays, one that left is brought back, and a card with
1841
- * none (or whose member was removed) is invited as a program-started member with the card's settings, label and
1842
- * description. `cards` limits it to those card IDs. Returns the updated {card ID: member name} map.
1843
- */
1844
- async function join_workflow_cards(home, config, roster, workflow, members, cards) {
1845
- const owner = { site: config.site, room_id: config.room, token: config.token };
1846
- const next = { ...members }, labels = {}, descriptions = {};
1847
- // Without a list, the main flow's cards; a sub-workflow's cards are named when it is used.
1848
- for (const agent of cards ? workflow_cards(workflow).filter(item => cards.includes(item.card)) : workflow.agents) {
1849
- const current = roster.find(member => member.name === next[agent.card] && member.status !== 'removed');
1850
- if (current?.status === 'active') continue;
1851
- if (current?.status === 'away') { await room_member(home, { ...owner, action: 'rejoin', name: current.name }); continue; }
1852
- const taken = new Set([...roster.map(member => member.name), ...Object.values(next)]);
1853
- const name = taken.has(agent.name) ? free_instance(agent.name, taken) : agent.name;
1854
- const api = card_api_profile(home, platform_of(agent.name));
1855
- const card = Object.fromEntries(['project_access', 'model', 'effort'].filter(field => agent[field]).map(field => [field, agent[field]]));
1856
- // An API member has no command line, so a card asking for more than writing gets the most it allows.
1857
- if (api && card.project_access && !access_levels('api').includes(card.project_access)) card.project_access = 'write';
1858
- const profile = { ...api, ...card };
1859
- const joined = await room_member(home, { ...owner, action: 'add', name, participants: { [name]: profile } });
1860
- next[agent.card] = joined.member;
1861
- if (agent.label) labels[joined.member] = agent.label;
1862
- if (agent.description) descriptions[joined.member] = agent.description;
1863
- }
1864
- if (Object.keys(labels).length) await site_request(config.site, `/api/rooms/${config.room}/labels`, config.token, { labels });
1865
- if (Object.keys(descriptions).length) await site_request(config.site, `/api/rooms/${config.room}/descriptions`, config.token, { descriptions });
1866
- return next;
1867
- }
1868
-
1869
- /**
1870
- * Bring the room's binding in line with its workflow as saved now, after the workflow was edited while in use: the
1871
- * given cards (all when omitted) join as in join_workflow_cards, and cards the workflow no longer has leave the
1872
- * binding, their members staying as ordinary members. Returns the room's workflow status and the card map.
1873
- */
1874
- async function sync_workflow_cards(home, path, config, roster, cards) {
1875
- if (!config.workflow?.id || !config.workflow.enabled) throw new Error('本房间没有在用的工作流');
1876
- const workflow = get_workflow(home, config.workflow.id);
1877
- const known = workflow_cards(workflow).map(agent => agent.card);
1878
- const unknown = (cards || []).filter(card => !known.includes(card));
1879
- if (unknown.length) throw new Error(`工作流 ${workflow.id} 没有这些卡片:${unknown.join('、')};现有卡片:${known.join('、') || '无'}`);
1880
- const kept = Object.fromEntries(Object.entries(config.workflow.members || {}).filter(([card]) => known.includes(card)));
1881
- const members = await join_workflow_cards(home, config, roster, workflow, kept, cards);
1882
- const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1883
- try {
1884
- const current = configuration_snapshot(path).config;
1885
- if (current.workflow?.id !== workflow.id) throw new Error('本房间的工作流已更换,请重新读取后再试');
1886
- // The map is replaced, not merged, so dropped cards leave it.
1887
- const next = { ...current, workflow: { ...current.workflow, members } };
1888
- atomic_json(path, next);
1889
- return { room_id: config.room, workflow: room_workflow_status(next, home), members };
1890
- } finally { release(); }
1891
- }
1892
-
1893
- /**
1894
- * The owner refreshes the room's workflow after editing it in the library (`room-workflow` `sync`): every card gets
1895
- * a member and dropped cards leave the binding. Returns the room's workflow status and the card map.
1896
- */
1897
- async function refresh_room_workflow(home, raw) {
1898
- const { path } = await member_room_context(home, raw);
1899
- const config = configuration_snapshot(path).config;
1900
- const roster = (await api(config, '')).free?.members || [];
1901
- return sync_workflow_cards(home, path, config, roster);
1902
- }
1903
-
1904
- /**
1905
- * The host brings in members for cards added to the room's workflow after it was enabled; the owner's enabling
1906
- * authorized the workflow's cards, so this needs no further grant. Only cards with no member yet may be named, so a
1907
- * member the user sent away or removed stays so. Returns the room's workflow status and the card map.
1908
- */
1909
- export async function join_workflow(home, { access_file, cards, sub }) {
1910
- const { path, config, roster } = await host_room(home, access_file);
1911
- if (sub) return sync_workflow_cards(home, path, config, roster, sub_workflow_cards(home, config, sub));
1912
- const mapped = Object.keys(config.workflow?.members || {});
1913
- const taken = (cards || []).filter(card => mapped.includes(card));
1914
- if (taken.length) throw new Error(`这些卡片已有成员:${taken.join('、')};离开或移除的成员由用户请回`);
1915
- const known = config.workflow?.id && config.workflow.enabled ? get_workflow(home, config.workflow.id).agents.map(agent => agent.card) : [];
1916
- return sync_workflow_cards(home, path, config, roster, cards?.length ? cards : known.filter(card => !mapped.includes(card)));
1917
- }
1918
-
1919
- /** The cards a sub-workflow of the room's workflow in use brings; refuses one it lacks or one with no cards. */
1920
- function sub_workflow_cards(home, config, sub) {
1921
- if (!config.workflow?.id || !config.workflow.enabled) throw new Error('本房间没有在用的工作流');
1922
- const list = get_workflow(home, config.workflow.id).sub_workflows;
1923
- const found = list.find(item => item.id === sub);
1924
- if (!found) throw new Error(`工作流 ${config.workflow.id} 没有子工作流 ${sub};现有子工作流:${list.map(item => item.id).join('、') || '无'}`);
1925
- if (!found.agents.length) throw new Error(`子工作流 ${sub} 没有卡片,不需要请成员加入`);
1926
- return found.agents.map(agent => agent.card);
1927
- }
1928
-
1929
- /**
1930
- * The host ends a sub-workflow's use: the members its cards brought are set away (pending requests cancelled, running work
1931
- * stopped, sessions kept), so `workflow-join --sub` brings them back to their own sessions. Only a sub-workflow's cards
1932
- * may be sent away this way; the main flow's members stay for the user to manage.
1933
- */
1934
- export async function leave_sub_workflow(home, { access_file, sub }) {
1935
- if (!sub) throw new Error('须用 --sub 指定子工作流');
1936
- const { config, roster } = await host_room(home, access_file);
1937
- const cards = sub_workflow_cards(home, config, sub);
1938
- const names = cards.map(card => config.workflow.members?.[card]).filter(Boolean);
1939
- const away = roster.filter(member => names.includes(member.name) && member.status === 'active' && member.role !== 'host');
1940
- for (const member of away) await site_request(config.site, `/api/rooms/${config.room}/members/${member.id}`, config.token, { action: 'away' });
1941
- return { room_id: config.room, sub, away: away.map(member => member.name) };
1942
- }
1943
-
1944
- // When the owner left the room's goal budget at no limit, a goal the host opens itself still stops by these.
1945
- const HOST_GOAL_BUDGET = { max_continues: 8, max_minutes: 90 };
1946
- const LIVE_EXECUTION = ['dispatched', 'started'];
1947
-
1948
- /**
1949
- * The active-or-away member a host names by member ID or display name. The host itself only with `self`: changes that
1950
- * apply from its next delivery (model, label) let it recover, e.g. from one model's quota; stopping, access and
1951
- * presence stay with the owner.
1952
- */
1953
- function host_target({ roster, labels, host }, wanted, { self = false } = {}) {
1954
- if (!wanted) throw new Error('须用 --member 指定成员(成员 ID 或显示名)');
1955
- const member = roster.find(item => item.status !== 'removed' && (item.name === wanted || labels[item.name] === wanted));
1956
- if (!member) throw new Error(`本房间没有成员 ${wanted}`);
1957
- if (member.name === host && !self) throw new Error('主持人不能对自己执行此操作(自己只能改模型与强度、显示名);更换或移除主持人由用户决定');
1958
- return member;
1959
- }
1960
-
1961
- /** The profile a host-invited member starts from: this computer's saved settings, project access at most write. */
1962
- function host_invite_profile(home, name, { access, model, effort }) {
1963
- if (access && !HOST_CARD_ACCESS.includes(access)) throw new Error('主持人邀请的成员项目权限只能是 read 或 write');
1964
- if (!card_platform_ready(home, name)) {
1965
- const ready = [...new Set([...Object.keys(launch_settings(home).participants), ...Object.keys(API_PROVIDERS).filter(platform => card_api_profile(home, platform))])];
1966
- throw new Error(`本机没有配置 ${name} 的软件或 API Key;只能邀请本机已配置的平台:${ready.join('、')}`);
1967
- }
1968
- const api = card_api_profile(home, platform_of(name));
1969
- const saved = launch_settings(home).participants[platform_of(name)]?.project_access;
1970
- const project_access = access || (HOST_CARD_ACCESS.includes(saved) ? saved : 'write');
1971
- return { ...api, project_access, ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
1972
- }
1973
-
1974
- /** The positive execution number a host passes with --execution. */
1975
- function execution_number(value) {
1976
- const id = Number(value);
1977
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('须用 --execution 指定执行编号');
1978
- return id;
1979
- }
1980
-
1981
- /** Read the discussion, or start (room default limits), pause, resume or end it with the revision just read. */
1982
- function host_discussion(ctx, { do: step, goal, revision, submission_id }) {
1983
- if (!step) return ctx.call('/discussion');
1984
- if (step === 'start') {
1985
- if (!goal) throw new Error('开启讨论须用 --goal 写明讨论目标');
1986
- return ctx.call('/discussion', { action: 'start', goal, revision, submission_id: submission_id || randomUUID() });
1987
- }
1988
- if (!['pause', 'resume', 'end'].includes(step)) throw new Error('--do 须为 start、pause、resume 或 end');
1989
- return ctx.call('/discussion', { action: step, revision });
1990
- }
1991
-
1992
- /** Read the goal, or open it under the owner's default budget (a bounded one when that is unlimited), pause, resume or end it. */
1993
- function host_goal(ctx, { do: step, goal, revision }) {
1994
- if (!step) return ctx.call('/goal');
1995
- if (step === 'start') {
1996
- if (!goal) throw new Error('开启 Goal 须用 --goal 写明目标');
1997
- const preferences = launch_settings(ctx.home).create_preferences || {};
1998
- const budget = {
1999
- max_continues: preferences.goal_max_continues || HOST_GOAL_BUDGET.max_continues,
2000
- max_minutes: preferences.goal_max_minutes || HOST_GOAL_BUDGET.max_minutes,
2001
- };
2002
- return ctx.call('/goal', { action: 'start', objective: goal, revision, ...budget });
2003
- }
2004
- if (!['pause', 'resume', 'end'].includes(step)) throw new Error('--do 须为 start、pause、resume 或 end');
2005
- return ctx.call('/goal', { action: step === 'end' ? 'clear' : step, revision });
2006
- }
2007
-
2008
- /** Steer a member's running execution with an interjection; a retry passes the same --submission-id. */
2009
- function host_steer(ctx, { member: wanted, text, submission_id }) {
2010
- const member = host_target(ctx, wanted);
2011
- if (!text) throw new Error('须用 --text 写明要对它说的话');
2012
- if (!LIVE_EXECUTION.includes(member.execution?.status)) throw new Error(`${wanted} 当前没有进行中的执行;要它发言请在回答里用 --to 点名`);
2013
- return ctx.call(`/executions/${member.execution.id}`, { action: 'interject', text, submission_id: submission_id || randomUUID() });
2014
- }
2015
-
2016
- /** Set a member's display name and, optionally, its description. */
2017
- async function host_label(ctx, { member: wanted, label, description }) {
2018
- const member = host_target(ctx, wanted, { self: true });
2019
- if (!label && !description) throw new Error('须用 --label 或 --description 指定显示名或描述');
2020
- if (label) await ctx.call('/labels', { labels: { [member.name]: label } });
2021
- if (description) await ctx.call('/descriptions', { descriptions: { [member.name]: description } });
2022
- return { member: member.name, label: label || null, description: description || null };
2023
- }
2024
-
2025
- /** Invite a member from this computer's configured software, project access at most write. */
2026
- async function host_invite(ctx, options) {
2027
- if (!options.name) throw new Error('须用 --name 指定要邀请的平台(如 Claude、Codex)');
2028
- const taken = new Set(ctx.roster.map(member => member.name));
2029
- const name = taken.has(options.name) ? free_instance(options.name, taken) : options.name;
2030
- const profile = host_invite_profile(ctx.home, name, options);
2031
- const joined = await room_member(ctx.home, { ...ctx.owner, action: 'add', name, participants: { [name]: profile } }, false, ctx.headers);
2032
- return { member: joined.member, project_access: profile.project_access };
2033
- }
2034
-
2035
- /** Read the speaking order, or change its not-yet-spoken part with the revision just read; display names are accepted. */
2036
- function host_order(ctx, { order, revision }) {
2037
- if (!order) return ctx.call('/speaking-order');
2038
- if (!revision) throw new Error('调整发言顺序前先不带 --order 读取当前顺序,再用 --revision 带上其 revision');
2039
- const names = order.split(',').map(name => name.trim()).filter(Boolean)
2040
- .map(name => ctx.roster.find(member => member.status === 'active' && ctx.labels[member.name] === name && member.name !== name)?.name || name);
2041
- return ctx.call('/speaking-order', { revision, order: names });
2042
- }
2043
-
2044
- const HOST_CONTROLS = {
2045
- stop: (ctx, o) => ctx.call(`/members/${host_target(ctx, o.member).id}/interrupt`, {}),
2046
- 'stop-all': ctx => ctx.call('/stop', {}),
2047
- steer: host_steer,
2048
- retry: (ctx, o) => ctx.call(`/executions/${execution_number(o.execution)}`, { action: 'retry' }),
2049
- details: (ctx, o) => execution_details_command(ctx.home, { ...ctx.owner, execution_id: execution_number(o.execution) }),
2050
- order: host_order,
2051
- invite: host_invite,
2052
- away: (ctx, o) => ctx.call(`/members/${host_target(ctx, o.member).id}`, { action: 'away' }),
2053
- remove: (ctx, o) => ctx.call(`/members/${host_target(ctx, o.member).id}`, { action: 'remove' }),
2054
- back: (ctx, o) => room_member(ctx.home, { ...ctx.owner, action: 'rejoin', name: host_target(ctx, o.member).name }, false, ctx.headers),
2055
- model: (ctx, o) => room_member_model(ctx.home, { ...ctx.owner, name: host_target(ctx, o.member, { self: true }).name, model: o.model || '', effort: o.effort || '' }),
2056
- access: (ctx, o) => {
2057
- if (!HOST_CARD_ACCESS.includes(o.access)) throw new Error('主持人只能把成员的项目权限设为 read 或 write');
2058
- return room_member_access(ctx.home, { ...ctx.owner, name: host_target(ctx, o.member).name, project_access: o.access });
2059
- },
2060
- adapter: (ctx, o) => room_member_adapter(ctx.home, { ...ctx.owner, name: host_target(ctx, o.member).name, adapter: o.adapter }),
2061
- label: host_label,
2062
- discussion: host_discussion,
2063
- goal: host_goal,
2064
- withdraw: (ctx, o) => {
2065
- const id = Number(o.message);
2066
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('须用 --message 指定要撤回的派活消息编号');
2067
- return ctx.call(`/dispatches/${id}/withdraw`, {});
2068
- },
2069
- checkin: (ctx, o) => {
2070
- if (o.off) return ctx.call('/host-checkin', { off: true });
2071
- const minutes = Number(o.minutes);
2072
- if (!Number.isSafeInteger(minutes)) throw new Error('须用 --minutes 指定间隔分钟数(5–120),或 --off 关闭');
2073
- return ctx.call('/host-checkin', { minutes });
2074
- },
2075
- };
2076
-
2077
- /**
2078
- * The host runs a room control the owner otherwise does in the web page, when the owner granted this room full host
2079
- * control (`host_workflows`), so it can keep work moving and handle what goes wrong by itself: stop, steer or retry a
2080
- * member, read an execution's local log, change the speaking order, invite (configured software, at most write), send
2081
- * away, remove or bring back members, change a member's model, effort, client or access (read/write only), label it,
2082
- * and read, start, pause, resume or end the discussion or goal. The site checks every write as for the owner (revisions
2083
- * included). What stays the owner's: acting on the host itself, approving rounds beyond the limit, access above write
2084
- * or tool approvals, project directories, the owner's messages and private chats.
2085
- */
2086
- export async function host_control(home, action, options) {
2087
- if (!Object.hasOwn(HOST_CONTROLS, action || '')) throw new Error(`操作须为 ${Object.keys(HOST_CONTROLS).join('、')} 之一`);
2088
- const { config, roster, labels, host } = await host_room(home, options.access_file);
2089
- if (!config.host_workflows) throw new Error('房主没有为本房间打开“主持人完整权限”;请让用户在电脑上“成员与设置 → 协作设置”打开后再试');
2090
- const headers = { 'User-Agent': `AI-CoDiscuss-host:${host}` };
2091
- const owner = { site: config.site, room_id: config.room, token: config.token };
2092
- const call = (path, body) => site_request(config.site, `/api/rooms/${config.room}${path}`, config.token, body, headers);
2093
- return HOST_CONTROLS[action]({ home, config, roster, labels, host, headers, owner, call }, options);
2094
- }
2095
-
2096
- /** Cards as the host may bring them: any access above writing is lowered to it. */
2097
- const host_cards = agents => agents.map(agent => agent.project_access && !HOST_CARD_ACCESS.includes(agent.project_access)
2098
- ? { ...agent, project_access: 'write' } : agent);
2099
-
2100
- /**
2101
- * The host enables a workflow in its own room, when the owner allowed that for this room (`host_workflows`): either
2102
- * its own draft, saved into the library first (the same ID again updates it), or one already in the library, named by
2103
- * `workflow_id` and left unchanged there. Each card the room lacks is invited as a program-started member with at most
2104
- * write access, one that left is brought back. Returns which member plays which card and where its SKILL.md is, so the
2105
- * host can follow it and name them in the same execution.
2106
- */
2107
- export async function adopt_workflow(home, { access_file, draft_file, workflow_id }) {
2108
- if (!draft_file === !workflow_id) throw new Error('须提供 --draft 草稿文件或 --id 工作流库中的工作流 ID 之一;凭据用 --access-file 或 DISCUSS_ACCESS_FILE');
2109
- const { config, roster } = await host_room(home, access_file);
2110
- if (!config.host_workflows) throw new Error('房主没有为本房间打开“主持人完整权限”;请让用户在电脑上“成员与设置 → 协作设置”打开后再试');
2111
- const bound = config.workflow?.id;
2112
- let workflow;
2113
- if (workflow_id) workflow = get_workflow(home, workflow_id);
2114
- else {
2115
- const draft = parse_workflow_draft([readFileSync(resolve(draft_file), 'utf8')]);
2116
- if (bound !== draft.id && list_workflows(home).some(item => item.id === draft.id)) throw new Error(`工作流库已有 ${draft.id},主持人不能覆盖其他工作流;要启用它请用 --id ${draft.id},新建请换一个 ID`);
2117
- workflow = draft;
2118
- }
2119
- assert_workflow_enabled(home, workflow.id);
2120
- const missing = workflow.agents.filter(agent => !card_platform_ready(home, agent.name)).map(agent => agent.name || agent.card);
2121
- if (missing.length) {
2122
- const ready = [...new Set([...Object.keys(launch_settings(home).participants), ...Object.keys(API_PROVIDERS).filter(platform => card_api_profile(home, platform))])];
2123
- throw new Error(`本机没有配置这些卡片的软件或 API Key:${missing.join('、')};卡片的 platform 只能用本机已配置的平台 ID:${ready.join('、')}`);
2124
- }
2125
- workflow = workflow_id ? { ...workflow, agents: host_cards(workflow.agents) }
2126
- : save_workflow(home, { ...workflow, agents: host_cards(workflow.agents) }, validate_preset);
2127
- const owner = { site: config.site, room_id: config.room, token: config.token };
2128
- const members = await join_workflow_cards(home, config, roster, workflow, bound === workflow.id ? config.workflow.members || {} : {});
2129
- const enabled = await room_workflow(home, { ...owner, action: 'enable', workflow: { id: workflow.id, members } });
2130
- return { ...enabled, members, skill_path: join(workflow_directory(home, workflow.id), 'SKILL.md') };
2131
- }
2132
-
2133
- /**
2134
- * Check a workflow folder or one-part draft as an import would, and optionally save it. A local AI uses this outside
2135
- * rooms with its user present, so the cards keep the project access they declare.
2136
- */
2137
- export function check_or_save_workflow(home, { dir, draft }, save = false) {
2138
- if (!dir === !draft) throw new Error('须提供 --dir 工作流文件夹或 --draft 草稿文件之一');
2139
- const source = dir ? { folder: dir } : { parts: [readFileSync(resolve(draft), 'utf8')] };
2140
- const preview = workflows_command(home, { action: 'preview', ...source });
2141
- if (!save) return preview;
2142
- const declared = list => list.map(({ requested_access, ...agent }) => requested_access ? { ...agent, project_access: requested_access } : agent);
2143
- const sub_workflows = preview.sub_workflows?.map(sub => ({ ...sub, agents: declared(sub.agents) }));
2144
- return save_workflow(home, { ...preview, agents: declared(preview.agents), ...(sub_workflows ? { sub_workflows } : {}) }, validate_preset);
2145
- }
2146
-
2147
- const WRITING_ACCESS = new Set(['write', 'auto', 'full', 'own']);
2148
-
2149
- /** The configuration this computer keeps for a room, found by its id; null when it runs no such room. */
2150
- function room_config_by_id(home, room_id) {
2151
- if (typeof room_id !== 'string' || !room_id) return null;
2152
- const paths = read_registry(home).filter(path => registered_identity(path)?.room === room_id);
2153
- return paths.length === 1 ? configuration_snapshot(paths[0]).config : null;
2154
- }
2155
-
2156
- /**
2157
- * The folders a request without this computer owner's standing may use: for an ordinary account, its own projects and
2158
- * draft space; for another device of the owner, the saved projects.
2159
- */
2160
- function granted_projects(home) {
2161
- const { projects_root, workspace } = account_space(home);
2162
- if (!projects_root) return launch_projects(home).projects;
2163
- mkdirSync(workspace, { recursive: true });
2164
- return [...account_projects(projects_root), { name: '草稿空间', path: workspace }];
2165
- }
2166
-
2167
- /** Fill program locations another device left out with the ones saved here, so saving defaults cannot drop them. */
2168
- function keep_saved_locations(home, participants) {
2169
- const saved = launch_settings(home).participants;
2170
- return Object.fromEntries(Object.entries(participants).map(([name, profile]) => {
2171
- const kept = Object.fromEntries(['executable', 'ipc_directory'].filter(field => !profile?.[field] && saved[name]?.[field]).map(field => [field, saved[name][field]]));
2172
- return [name, { ...profile, ...kept }];
2173
- }));
2174
- }
2175
-
2176
- /** CLI and local HTTP bridge use the same commands and configuration validation. */
2177
- export async function launch_main(args = process.argv.slice(2), input_text) {
2178
- const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
2179
- file: { type: 'string' }, 'dry-run': { type: 'boolean' }, browser: { type: 'boolean' }, remote: { type: 'boolean' }, device: { type: 'string' },
2180
- 'configuration-locked': { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
2181
- draft: { type: 'string' }, 'access-file': { type: 'string' }, dir: { type: 'string' }, card: { type: 'string' }, sub: { type: 'string' }, id: { type: 'string' },
2182
- member: { type: 'string' }, order: { type: 'string' }, revision: { type: 'string' }, name: { type: 'string' }, access: { type: 'string' },
2183
- model: { type: 'string' }, effort: { type: 'string' }, do: { type: 'string' }, execution: { type: 'string' }, text: { type: 'string' },
2184
- goal: { type: 'string' }, label: { type: 'string' }, description: { type: 'string' }, adapter: { type: 'string' }, 'submission-id': { type: 'string' },
2185
- message: { type: 'string' }, minutes: { type: 'string' }, off: { type: 'boolean' },
2186
- } });
2187
- if (values.help || !positionals.length) return process.stdout.write(HELP);
2188
- if (positionals[0] === 'workflow-adopt') {
2189
- const home = service_home();
2190
- const result = await adopt_workflow(home, { draft_file: values.draft, workflow_id: values.id, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2191
- return process.stdout.write(`${JSON.stringify(result)}\n`);
2192
- }
2193
- if (positionals[0] === 'host-control') {
2194
- const { member, order, revision, name, access, model, effort, execution, text, goal, label, description, adapter } = values;
2195
- const result = await host_control(service_home(), positionals[1], { member, order, revision, name, access, model, effort, execution, text, goal,
2196
- label, description, adapter, message: values.message, minutes: values.minutes, off: values.off, do: values.do, submission_id: values['submission-id'], access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2197
- return process.stdout.write(`${JSON.stringify(result)}
2198
- `);
2199
- }
2200
- if (positionals[0] === 'workflow-join') {
2201
- const cards = (values.card || '').split(',').map(card => card.trim()).filter(Boolean);
2202
- const result = await join_workflow(service_home(), { cards, sub: values.sub, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2203
- return process.stdout.write(`${JSON.stringify(result)}
2204
- `);
2205
- }
2206
- if (positionals[0] === 'workflow-leave') {
2207
- const result = await leave_sub_workflow(service_home(), { sub: values.sub, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2208
- return process.stdout.write(`${JSON.stringify(result)}
2209
- `);
2210
- }
2211
- if (positionals[0] === 'image') {
2212
- if (!values.file) throw new Error('用 --file 指定请求 JSON:{"action":"generate"|"edit","prompt":"…",…}');
2213
- const request = JSON.parse(readFileSync(values.file, 'utf8').replace(/^/, ''));
2214
- const result = await draw_image(service_home(), { request, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2215
- return process.stdout.write(`${JSON.stringify(result)}\n`);
2216
- }
2217
- if (['workflow-check', 'workflow-save'].includes(positionals[0])) {
2218
- const result = check_or_save_workflow(service_home(), { dir: values.dir, draft: values.draft }, positionals[0] === 'workflow-save');
2219
- return process.stdout.write(`${JSON.stringify(result)}\n`);
2220
- }
2221
- const input = input_text === undefined ? (values.file ? JSON.parse(readFileSync(values.file, 'utf8').replace(/^\uFEFF/, '')) : null) : JSON.parse(input_text);
2222
- const home = service_home();
2223
- assert_shared_home(home);
2224
- // Another device's request may only use what this computer granted; the flag is set by the relay, never by the request.
2225
- // An ordinary account's instance holds every request, from any page, to that account's own folders.
2226
- const space = account_space(home), restricted = Boolean(space.projects_root);
2227
- if (values.remote || restricted) {
2228
- guard_remote_request(positionals[0], input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
2229
- if (values.remote && positionals[0] === 'room-workflow' && input?.action === 'host') throw new Error('“主持人完整权限”只能在电脑上开启');
2230
- if (restricted && positionals[0] === 'pick-directory') throw new Error('此账号只能使用自己的项目文件夹');
2231
- // Another device repeats the saved program locations it cannot see; keep them rather than dropping them.
2232
- if (positionals[0] === 'settings' && input?.participants) input.participants = keep_saved_locations(home, input.participants);
2233
- }
2234
- if (values.remote) {
2235
- // Tool approvals saved here stay this computer's decision; a room created from another device does not take them.
2236
- if (positionals[0] === 'start' && input) input.without_saved_tools = true;
2237
- }
2238
- let result;
2239
- if (positionals[0] === 'settings') result = { ...(input ? save_launch_settings(home, input) : launch_settings(home)), api_providers: API_PROVIDERS,
2240
- scheduler_providers: SCHEDULER_PROVIDERS, scheduler_modes: SCHEDULER_MODES, scheduler_default_mode: DEFAULT_SCHEDULER_MODE, api_keys: saved_api_keys(home), managed_api_keys: restricted ? managed_api_keys(home) : [], projects: launch_projects(home).projects, projects_restricted: restricted, workspace: space.workspace, user_home: restricted ? homedir() : '', ...expert_presets(home), workflows: list_workflows(home) };
2241
- else if (positionals[0] === 'projects') result = input ? save_launch_projects(home, input) : launch_projects(home);
2242
- else if (positionals[0] === 'presets') result = input ? save_expert_presets(home, input) : expert_presets(home);
2243
- else if (positionals[0] === 'workflows') result = await workflows_command(home, input || {});
2244
- else if (positionals[0] === 'room-workflow' && input) result = await room_workflow(home, input);
2245
- else if (positionals[0] === 'room-settings' && input) result = await room_settings(home, input);
2246
- else if (positionals[0] === 'api-key' && input) result = save_api_key(home, { base_url: input.base_url, api_key: input.api_key });
2247
- else if (positionals[0] === 'api-check' && input) result = await api_check(home, input);
2248
- else if (positionals[0] === 'scheduler-check' && input) result = await scheduler_check(home, input);
2249
- else if (positionals[0] === 'image-settings') result = input && Object.keys(input).length ? save_image_settings(home, input) : image_settings(home);
2250
- else if (positionals[0] === 'tts-settings') result = input && Object.keys(input).length ? save_tts_settings(home, input) : tts_settings(home);
2251
- else if (positionals[0] === 'tts' && input) result = await tts_speak(home, input);
2252
- else if (positionals[0] === 'tts-release') result = tts_release(home);
2253
- else if (positionals[0] === 'local-speech') result = input?.stop ? await local_service_stop(home, input.stop) : await local_services(home);
2254
- else if (positionals[0] === 'weixin') result = await weixin_command(home, input || {});
2255
- else if (positionals[0] === 'stt' && input) result = await stt_part(home, input);
2256
- else if (positionals[0] === 'room-models' && input) result = await room_models(home, input);
2257
- else if (positionals[0] === 'room-skills' && input) result = await room_skills(home, input);
2258
- else if (positionals[0] === 'room-files' && input) result = await room_files(home, input);
2259
- else if (positionals[0] === 'room-page' && input) result = await room_page(home, input, { parts: Boolean(values.remote) });
2260
- else if (positionals[0] === 'room-media' && input) result = await room_media(home, input, { parts: Boolean(values.remote) });
2261
- else if (positionals[0] === 'execution-details' && input) result = await execution_details_command(home, input);
2262
- else if (positionals[0] === 'models' && adapter_profile(input?.adapter)?.kind === 'api') result = await api_models(home, input);
2263
- else if (positionals[0] === 'models' && input) {
2264
- const saved = Object.values(launch_settings(home).participants).find(profile => profile.adapter === input.adapter);
2265
- result = await cached_software_models(home, { adapter: input.adapter, executable: input.executable || saved?.executable,
2266
- ...(input.model ? { model: input.model } : {}) }, { refresh: input.refresh === true });
2267
- }
2268
- else if (positionals[0] === 'room-member' && input) result = await room_member(home, input);
2269
- else if (positionals[0] === 'room-member-access' && input) result = await room_member_access(home, input);
2270
- else if (positionals[0] === 'room-member-allow' && input) result = await room_member_allow(home, input);
2271
- else if (positionals[0] === 'room-member-adapter' && input) result = await room_member_adapter(home, input);
2272
- else if (positionals[0] === 'room-member-model' && input) result = await room_member_model(home, input);
2273
- else if (positionals[0] === 'room-profiles' && input) result = await room_profiles(home, input);
2274
- else if (positionals[0] === 'room-restore' && input) result = await restore_room(home, input);
2275
- else if (positionals[0] === 'room-fork' && input) result = await fork_room(home, input);
2276
- else if (positionals[0] === 'pick-directory') result = await pick_directory();
2277
- else if (positionals[0] === 'browse-directory') result = list_remote_directories(input || {}, { projects: granted_projects(home), home });
2278
- // Device trust from this computer's own screen; other devices reach the same actions through the relay instead.
2279
- else if (positionals[0] === 'device-pairing' && !values.remote) {
2280
- // The QR code opens the paired website and carries this computer's key fingerprint for the new device to check.
2281
- const { keyed_links } = await import('./remote_launch.mjs');
2282
- const [site, link] = Object.entries(keyed_links(home).sites).find(([origin]) => !input?.site || origin === input.site) || [];
2283
- if (!link) throw new Error('这台电脑还没有绑定线上网站,请先运行 codiscuss local connect 网站地址');
2284
- result = start_pairing(home, { site, fingerprint: machine_fingerprint(link), temporary: input?.temporary === true, without_passkey: input?.without_passkey === true });
2285
- }
2286
- else if (positionals[0] === 'devices' && !values.remote) {
2287
- result = input?.revoke ? revoke_device(home, String(input.revoke)) : list_devices(home);
2288
- // The website takes devices only from the list this computer signs, so a revocation is sent at once.
2289
- if (input?.revoke) await (await import('./remote_launch.mjs')).sync_remote_launches(home).catch(() => {});
2290
- }
2291
- else if (positionals[0] === 'machine-link' && input) result = (await import('./remote_launch.mjs')).machine_link(home, input.site);
2292
- else if (positionals[0] === 'start' && input) {
2293
- result = await launch_discussion(home, input, { dry_run: values['dry-run'], browser_request: values.browser });
2294
- }
2295
- else if (positionals[0] === 'room-config' && input) result = await room_configuration(home, input, { local_guard: values['configuration-locked'] });
2296
- else throw new Error(HELP);
2297
- process.stdout.write(`${JSON.stringify(result)}\n`);
2298
- }
2299
-
2300
- if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
2301
- const args = process.argv.slice(2);
2302
- const stdin = args.includes('--stdin') ? readFileSync(0, 'utf8') : undefined;
2303
- launch_main(args.filter(arg => arg !== '--stdin'), stdin).catch(error => {
2304
- // A request that needs the page to do something first (pair, renew, confirm writing) says so in a field it can read.
2305
- const need = error.need ? { need: error.need, ...(error.room_id ? { room_id: error.room_id } : {}) } : {};
2306
- const failure = args.includes('--browser') ? JSON.stringify({ error: error.message, ...need, launch: error.launch || { stage: 'not_started' } })
2307
- : error.need ? JSON.stringify({ error: error.message, ...need }) : error.message;
2308
- process.stderr.write(`${failure}\n`); process.exitCode = 1;
2309
- });
2310
- }
1
+ /** Shared launch configuration for an existing AI conversation and the local website. */
2
+ import { spawn } from 'node:child_process';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join, posix, resolve, win32 } from 'node:path';
7
+ import { DatabaseSync } from 'node:sqlite';
8
+ import { setTimeout as sleep } from 'node:timers/promises';
9
+ import { pathToFileURL } from 'node:url';
10
+ import { parseArgs } from 'node:util';
11
+
12
+ import { account_projects, account_space, create_account_project, draft_folder } from './account_space.mjs';
13
+ import { atomic_json } from './files.mjs';
14
+ import { bundle_project_markdown, bundle_project_page, outside_directory, project_media, read_only_enforced, read_project_files, room_directories, search_project_roots } from './project_files.mjs';
15
+ import { guard_remote_request, list_remote_directories } from './remote_policy.mjs';
16
+ import { list_devices, machine_fingerprint, revoke_device, start_pairing } from './device_auth.mjs';
17
+ import { setup_sidecar } from './adapters/antigravity_app.mjs';
18
+ import { adapter_of, adoption_adapter, BRANCHABLE_ADAPTERS, branch_session, execution_details, session_settings, software_defaults, software_defaults_stamp, software_effort, software_models, software_skills } from './adapters/index.mjs';
19
+ import { ADAPTER_IDS, ADAPTER_PROFILES, adapter_profile, DEFAULT_API_MAX_REQUESTS, MAX_API_MAX_REQUESTS, platform_adapters, same_session_family } from './adapters/profiles.mjs';
20
+ import { API_PROVIDERS, api_check, api_models, managed_api_keys, save_api_key, saved_api_keys, validate_api_profile } from './discussion_api.mjs';
21
+ import { DEFAULT_SCHEDULER_MODE, SCHEDULER_MODES, SCHEDULER_PROVIDERS, scheduler_check } from './scheduler.mjs';
22
+ import { save_tts_settings, tts_release, tts_settings, tts_speak } from './tts.mjs';
23
+ import { local_service_stop, local_services } from './tts_providers.mjs';
24
+ import { weixin_command } from './weixin.mjs';
25
+ import { stt_part } from './stt.mjs';
26
+ import { image_settings, room_image, save_image_settings } from './image_service.mjs';
27
+ import { open_project } from './adapters/api_files.mjs';
28
+ import { run_image_tool } from './adapters/api_images.mjs';
29
+ import { access_levels, BUILTIN_EXPERT_PRESETS, MAX_EXPERT_PROMPT, PROJECT_ACCESS } from './expert_prompts.mjs';
30
+ import { acquire_lock, api, check_extra_directories, DiscussionStore, service_drafts, validate_config } from './discussion_runner.mjs';
31
+ import { FreeRoomRunner, free_task_files } from './free_runner.mjs';
32
+ import { assert_workflow_enabled, bind_room_workflow, delete_workflow, get_workflow, list_workflows, load_room_workflow, parse_workflow_draft, preview_workflow, rename_workflow, save_workflow, set_workflow_disabled, workflow_cards, workflow_directory, WORKFLOW_ID_PATTERN } from './workflows.mjs';
33
+ import { assert_shared_home, CONNECTION_FIELDS, configuration_snapshot, read_registry, registered_identity, register_room, service_home, service_pid, start_service } from './discussion_service.mjs';
34
+
35
+ // A platform is a type; `Claude-review` is another Claude instance with its own session, model and effort. An ID is
36
+ // English letters, digits and underscores only; a Chinese name is a display label.
37
+ const INSTANCE_PATTERN = /^(Codex|Claude|Antigravity|DeepSeek|Qwen|Grok|OpenAI|Custom)(?:-[0-9A-Za-z_]{1,16})?$/;
38
+
39
+ /** The platform of an AI instance name, or null. */
40
+ export function platform_of(name) { return typeof name === 'string' ? INSTANCE_PATTERN.exec(name)?.[1] ?? null : null; }
41
+
42
+ /** The first unused instance name of a platform: the platform itself, then platform-2, platform-3, …. */
43
+ export function next_instance(platform, taken) {
44
+ if (!taken.has(platform)) return platform;
45
+ for (let number = 2; ; number++) if (!taken.has(`${platform}-${number}`)) return `${platform}-${number}`;
46
+ }
47
+
48
+ /** A free name from a used one, as the website numbers copies: Codex → Codex-2, Codex-review → Codex-review2. */
49
+ function free_instance(name, taken) {
50
+ if (!name.includes('-')) return next_instance(name, taken);
51
+ for (let number = 2; ; number++) if (!taken.has(`${name}${number}`)) return `${name}${number}`;
52
+ }
53
+
54
+ /** Supported local clients of an instance's platform. */
55
+ function clients_of(name) { return platform_adapters(platform_of(name)); }
56
+ const PROFILE_FIELDS = ['adapter', 'executable', 'model', 'effort', 'source_thread_id', 'ipc_directory', 'allowed_tools', 'cwd', 'project_name', 'project_id', 'base_url', 'api_protocol', 'api_key_ref', 'system_prompt'];
57
+ // Saved before drawing became the room's switch; read as absent.
58
+ const LEGACY_PROFILE_FIELDS = ['image_model'];
59
+ const MAX_MINUTES = 1440;
60
+ const SESSION_ID_PATTERN = /^[0-9A-Za-z_-]{8,128}$/;
61
+ const LOCAL_MEMBERS_FORMAT = 'ai-codiscuss-local-members';
62
+ // Reading the inbox proves the owner credential without transferring any messages.
63
+ const CONFIG_APPLY_TIMEOUT_MS = 6000;
64
+ const CONFIG_APPLY_POLL_MS = 100;
65
+ const HELP = `用法:codiscuss launch settings [--file FILE]
66
+ codiscuss launch start --file FILE [--dry-run]
67
+ codiscuss launch room-config --file FILE
68
+ codiscuss launch room-models --file FILE
69
+ codiscuss launch room-skills --file FILE
70
+ codiscuss launch room-files --file FILE
71
+ codiscuss launch room-page --file FILE
72
+ codiscuss launch room-media --file FILE
73
+ codiscuss launch execution-details --file FILE
74
+ codiscuss launch models --file FILE
75
+ codiscuss launch api-key --file FILE
76
+ codiscuss launch api-check --file FILE
77
+ codiscuss launch scheduler-check --file FILE
78
+ codiscuss launch image-settings [--file FILE]
79
+ codiscuss launch image --file REQUEST [--access-file FILE]
80
+ codiscuss launch tts-settings [--file FILE]
81
+ codiscuss launch tts --file FILE
82
+ codiscuss launch tts-release
83
+ codiscuss launch local-speech [--file FILE]
84
+ codiscuss launch weixin [--file FILE]
85
+ codiscuss launch stt --file FILE
86
+ codiscuss launch room-member --file FILE
87
+ codiscuss launch room-member-access --file FILE
88
+ codiscuss launch room-member-allow --file FILE
89
+ codiscuss launch room-member-model --file FILE
90
+ codiscuss launch room-member-adapter --file FILE
91
+ codiscuss launch room-profiles --file FILE
92
+ codiscuss launch room-restore --file FILE
93
+ codiscuss launch room-fork --file FILE
94
+ codiscuss launch pick-directory
95
+ codiscuss launch browse-directory [--file FILE]
96
+ codiscuss launch device-pairing [--file FILE]
97
+ codiscuss launch devices [--file FILE]
98
+ codiscuss launch projects [--file FILE]
99
+ codiscuss launch presets [--file FILE]
100
+ codiscuss launch machine-link --file FILE
101
+ codiscuss launch workflow-adopt (--draft FILE | --id WORKFLOW) [--access-file FILE]
102
+ codiscuss launch workflow-join [--card ID[,ID] | --sub SUB] [--access-file FILE]
103
+ codiscuss launch workflow-leave --sub SUB [--access-file FILE]
104
+ codiscuss launch host-control ACTION [选项] [--access-file FILE]
105
+ codiscuss launch workflow-check (--dir DIR | --draft FILE)
106
+ codiscuss launch workflow-save (--dir DIR | --draft FILE)
107
+
108
+ settings 读取本机软件默认配置;指定文件时保存,不启动 AI。
109
+ start 使用启动 JSON 创建或接入房间并启动;--dry-run 只校验和预览。
110
+ room-config 修正已暂停房间的软件路径或切换 Codex App / CLI,不启动讨论;须提供 site、room_id、token。
111
+ room-models 只读指定 site、room_id 的本机登记模型与思考强度,不启动讨论;quick 为 true 时不查询 agy 的默认模型(较慢),该成员标 defaults_pending。
112
+ room-skills 只读指定成员本机安装的技能,须提供 site、room_id、token、name;软件与项目目录只取本机已保存配置,不启动 AI。
113
+ room-files 只读房间已保存的项目目录,须提供 site、room_id、token,可选相对 path 和目录分页 offset;文件返回最多前 128 KiB 文本;给 query 时改为按名称搜索整个项目(含 / 时按路径),最多返回 50 项。
114
+ room-page 只读项目目录里的一个 HTML 文件(path,可选 root),把它按相对路径引用的样式、脚本、图片、字体与音视频内联为 data URL,以 base64 的 data 返回(最多 8 MiB);Markdown 文件则返回它按相对路径引用的项目图片 {项目路径: data URL} 的 JSON;其他设备经中转时分段返回,按 offset 续读并核对 version;未能载入的引用列在 missing(不存在或在项目目录外)与 skipped(超出大小)。
115
+ room-media 核对项目目录里的一个图片、视频或音频文件(path,可选 root)可读:本机网站凭它登记一个 10 分钟有效的播放地址,按 Range 直接读盘,网页拿不到文件路径;其他设备经中转时分段返回 base64 的 data(按 offset 续读并核对 version),最多 64 MB。
116
+ execution-details 只读房间某次执行的过程细节(中间说明、命令与输出、搜索、改动、工具调用),由本机日志还原,须提供 site、room_id、token、execution_id;细节只留在本机,不写入网站。
117
+ models 按 adapter、executable 或 API profile 读取模型目录,不启动讨论或生成回答。
118
+ api-key 将 base_url、api_key 保存于本机私有目录,只返回 api_key_ref。
119
+ api-check 用 API profile 向模型发送一次极短请求,核对地址、密钥、协议与模型是否可用。
120
+ scheduler-check 用智能调度配置(provider、model、api_key_ref)向决策模型发送一道是非题,核对供应商、模型与密钥是否可用。
121
+ image-settings 读取这台电脑的生图服务(base_url、图片模型 model、api_key_ref,configured 表示已配置 Key);内容非空时保存。
122
+ image 成员按任务凭据生图(房间须添加了生图卡片):REQUEST 为 JSON,必填 action(generate 生成 / edit 改图)与 prompt;可选 size(auto、1024x1024、1536x1024、1024x1536 或 16 倍数的 宽x高)、quality(auto/low/medium/high,2.5、2.6 系列另有 xhigh/max)、n(1–10 张)、output_format(png/jpeg/webp/gif,生成另可 svg)、background(auto/opaque/transparent)、file_name(附件名)、save_path(另存进可写项目);edit 另需 images(1–16 个 {attachment_id} 或 {file_path},第一张为主图),可加 mask 或 markup(同样格式,二选一)。图片存为成员的附件,返回附件 ID,再用 message post --attachment 附上。
123
+ tts-settings 读取朗读设置;内容非空时保存(语音服务 provider:local(本机,由 local-tts-setup 技能安装)/ volcengine / aliyun / azure / openai,语速 speech_rate,以及 providers.<服务> 的 api_key_ref、speaker、member_voices、file_voice,本机、火山引擎与 OpenAI 另有语气提示 context(各自默认不同),Azure 另有 region;语音输入服务 stt_provider:local / volcengine / openai)。
124
+ tts 用朗读设置把 text(不超过 300 字)合成为音频(本机服务为 m4a,其余为 MP3),返回 base64。
125
+ weixin 微信通知:action 为 status(默认,读取绑定状态)、login(生成扫码内容)、complete(等待扫码确认,约 20 秒)、test(发一条测试通知)或 unbind(解除本机绑定)。Goal 待确认 5 分钟仍未回复时通知房主,房主在微信回复即作为房主发言发回该房间;只用本机服务目录保存凭据。
126
+ tts-release 用户停止朗读:所选服务释放在这台电脑上占用的资源(本机语音在 5 秒内结束、释放显存),云端服务无操作。
127
+ local-speech 读取本机朗读(tts,yovoice)与语音识别(stt,crispasr)服务的运行状态(state:running / stopped / other(端口被其他程序占用),及 pid、进程名);内容为 {"stop": "tts" | "stt"} 时强行结束该服务(连同子进程),只结束端口上属于该服务程序的进程。
128
+ stt 按序接收录音片段(upload_id、index、base64 PCM 16 kHz 单声道、final);最后一段时识别整段录音并返回 text。
129
+ pick-directory 在本机弹出系统目录选择窗口,返回所选路径;取消时不返回路径。
130
+ browse-directory 列出常用项目及其中的子文件夹(只含文件夹名,分页),供其他设备选择目录;path 为空时列出常用项目。
131
+ device-pairing 在本机生成 12 位设备配对码(2 分钟有效,可选 temporary 临时设备、without_passkey 允许这次配对不用通行密钥、site 指定已绑定的网站),扫码链接带本机密钥指纹;只能在这台电脑上执行,新设备只能在电脑前添加。
132
+ devices 列出已配对设备;提供 revoke(设备 id)撤销设备。
133
+ projects 读取本机已配置的项目(名称与绝对路径);提供 JSON(projects 列表)时整体替换保存。
134
+ presets 读取本机的专家预设(含未删除的内置预设)与各平台默认描述;提供 JSON(presets 列表、description_templates 和/或 hidden_builtins 已删除的内置预设名)时替换对应部分。
135
+ machine-link 返回本机连接指定 site 的电脑编号、名称与凭据,供已登录管理员的网页完成配对;不存在时创建。
136
+ room-member 为房间邀请、请回一位成员;须提供 site、room_id、token、action(add/rejoin)、name。
137
+ room-member-access 修改一位本机唤醒成员的项目权限(project_access 为 read/write/auto/full),下次投递起生效、保留原会话;须提供 site、room_id、token、name、project_access。
138
+ room-member-allow 把被拒绝的操作加入一位本机唤醒的 Claude Code 或 agy 成员的 allowed_tools,下次投递起生效;须提供 site、room_id、token、name、rules。
139
+ room-member-model 修改一位本机唤醒 CLI 或 API 成员的模型与思考强度(空值恢复软件默认;API 成员空模型保留原模型),下次投递起生效、保留原会话;须提供 site、room_id、token、name、model、effort。
140
+ room-member-adapter 把自由房间里空闲的 Codex 成员在 App(codex)与 CLI(codex_cli)间切换,保留原会话;须提供 site、room_id、token、name、adapter。
141
+ room-profiles 导出房间的本机成员软件配置与实际会话 ID(不含凭据),供备份附带;须提供 site、room_id、token。
142
+ room-restore 把导入房间的本机成员配置登记到本机并核对原会话存在,Claude Code 成员保持手动;须提供 site、room_id、token、local_members。
143
+ room-fork 把从原房间分支出的新房间登记到本机,各本机成员从原会话分叉、不含分支点之后的执行,原会话不变;须提供 site、room_id、token、source_room_id、source_token、executions({成员名: [排除的执行编号]})。
144
+ workflow-adopt 主持人在本房间启用工作流:--draft 把自己的草稿(一段,分段头 1/1)保存进工作流库后启用,--id 启用工作流库里已有的工作流(不改动它);缺的卡片成员由本机服务邀请,项目权限最高可写;须房主已为本房间打开“主持人完整权限”。凭据为本次任务的 access_file(或 DISCUSS_ACCESS_FILE)。
145
+ workflow-join 主持人为本房间在用工作流里还没有成员的卡片(启用后才新增的)邀请成员,不填 --card 即全部主线卡片;无需额外授权,离开或移除的成员由用户请回。--sub 改为请进该子工作流的卡片成员(离开的请回原会话)。凭据同上。
146
+ workflow-leave 主持人用完子工作流后,把 --sub 子工作流卡片的成员设为离开(会话保留,下次 workflow-join --sub 请回);主线成员不能这样请离。凭据同上。
147
+ host-control 主持人代房主控制房间,须房主已为本房间打开“主持人完整权限”,凭据同上;成员用 --member(成员 ID 或显示名),除 retry、model、label 外不能是主持人自己:
148
+ 诊断:details --execution N 读取该执行的本机过程日志(服务端详情与事件记录用 execution / room events 读取);
149
+ 恢复:stop --member 打断;stop-all 停止全部执行、请求与接力;steer --member --text 话 [--submission-id ID] 向它进行中的执行插话;
150
+ retry --execution N 重试失败的执行(含你自己的);model --member [--model M] [--effort E] 改 CLI 或 API 成员的模型与强度(空值恢复默认;API 成员不填模型则保留原模型);
151
+ adapter --member --adapter ID 在同一软件的 App 与 CLI 间切换;access --member --access read|write 调整项目权限;
152
+ 成员:invite --name 平台 [--access read|write] [--model M] [--effort E] 用本机已配置的软件邀请,项目权限最高可写;
153
+ away / remove / back --member 暂离、移除、请回;label --member [--label 显示名] [--description 描述];
154
+ 撤回:withdraw --message N 撤回自己的一次派活:接力或循环停下,未开始的请求取消,进行中的停止,不再交回;
155
+ 兜底:checkin --minutes N 房间有进行中的工作时每 N 分钟(5–120)给你发一次定时检查,房间空闲、停止全部或换主持人后自动结束;checkin --off 关闭;
156
+ 推进:order 读取发言顺序,order --order 甲,乙 --revision REV 调整尚未发言的部分;
157
+ discussion 读取讨论,discussion --do start --goal 目标 --revision REV 开启(上限用房间默认值),--do pause|resume|end --revision REV;
158
+ goal 读取 Goal,goal --do start --goal 目标 --revision REV 开启(预算用房主默认值,默认不限时为 8 次续跑、90 分钟),--do pause|resume|end --revision REV。
159
+ 不开放:批准超出上限的轮数、项目权限高于可写或放行工具、改项目目录、撤回回退用户消息、私聊、对主持人自己的其他操作。
160
+ workflow-check 按导入规则校验工作流文件夹或单段草稿,返回预览,不保存;workflow-save 校验后保存进工作流库(同 ID 覆盖),卡片按声明的项目权限保存。写法见 workflow-creator 技能。
161
+ JSON 指定 site、entry(conversation/web)、room(建房内容,含 submission_id)
162
+ 或 room_id(已有房间)、participants(本次软件覆盖配置)。
163
+ conversation 还须 current_session_id,当前会话接手首个主持任务。
164
+ 已有受保护房间使用 access_file。路径、凭据只保存在本机。
165
+ 详见 docs/runner.md 的“两种讨论入口与启动配置”。
166
+ `;
167
+
168
+ // Windows PowerShell 5.1 ships WinForms. A background process cannot take the foreground, so the owner must be
169
+ // shown (transparent) as a topmost window; the dialog it owns then stays above the browser that asked for it.
170
+ // Keep the owner on-screen because the Common Item Dialog positions itself relative to its owner.
171
+ // windowsHide turns the process's first Show into a hide, so the owner is shown a second time to really appear.
172
+ // Under the local service the whole process chain has no console and no foreground rights: Windows then silently ignores
173
+ // SetWindowPos(HWND_TOPMOST) on the dialog (it returns success). So once the dialog exists, a timer in its message loop
174
+ // briefly attaches to the foreground window's input thread (the browser that asked) to borrow its right to raise the dialog.
175
+ // The C# source must not contain single quotes: it is embedded in a single-quoted PowerShell string.
176
+ const PICKER_RAISE_SOURCE = [
177
+ 'using System; using System.Runtime.InteropServices;',
178
+ 'public static class PickerRaise {',
179
+ ' delegate bool EnumProc(IntPtr handle, IntPtr arg);',
180
+ ' [DllImport("user32.dll")] static extern bool EnumWindows(EnumProc proc, IntPtr arg);',
181
+ ' [DllImport("user32.dll")] static extern IntPtr GetWindow(IntPtr handle, uint command);',
182
+ ' [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr handle, IntPtr after, int x, int y, int width, int height, uint flags);',
183
+ ' [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();',
184
+ ' [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr handle, IntPtr process);',
185
+ ' [DllImport("kernel32.dll")] static extern uint GetCurrentThreadId();',
186
+ ' [DllImport("user32.dll")] static extern bool AttachThreadInput(uint attach, uint to, bool on);',
187
+ ' [DllImport("user32.dll")] static extern bool BringWindowToTop(IntPtr handle);',
188
+ ' [DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr handle);',
189
+ ' public static bool OwnedBy(IntPtr owner) {',
190
+ ' IntPtr dialog = IntPtr.Zero;',
191
+ ' EnumWindows((handle, arg) => { if (GetWindow(handle, 4) == owner) dialog = handle; return dialog == IntPtr.Zero; }, IntPtr.Zero);',
192
+ ' if (dialog == IntPtr.Zero) return false;',
193
+ ' uint current = GetCurrentThreadId(), foreground = GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero);',
194
+ ' bool attached = foreground != 0 && foreground != current && AttachThreadInput(current, foreground, true);',
195
+ ' SetWindowPos(dialog, (IntPtr)(-1), 0, 0, 0, 0, 0x13); BringWindowToTop(dialog); SetForegroundWindow(dialog);',
196
+ ' if (attached) AttachThreadInput(current, foreground, false);',
197
+ ' return true;',
198
+ ' }',
199
+ '}',
200
+ ].join(' ');
201
+ // Use the Common Item Dialog: unlike Framework WinForms, it has an editable address bar.
202
+ // COM declarations retain the native vtable order through the last method used.
203
+ const FOLDER_PICKER_SOURCE = `
204
+ public static class FolderPicker {
205
+ const uint FOS_PICKFOLDERS = 0x20, FOS_FORCEFILESYSTEM = 0x40, FOS_PATHMUSTEXIST = 0x800;
206
+ const uint SIGDN_FILESYSPATH = 0x80058000;
207
+ const int CANCELLED = unchecked((int)0x800704C7);
208
+ [ComImport, Guid("42F85136-DB7E-439C-85F1-E4075D135FC8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
209
+ interface IFileDialog {
210
+ [PreserveSig] int Show(IntPtr owner);
211
+ void SetFileTypes(uint count, IntPtr filters);
212
+ void SetFileTypeIndex(uint index);
213
+ void GetFileTypeIndex(out uint index);
214
+ void Advise(IntPtr events, out uint cookie);
215
+ void Unadvise(uint cookie);
216
+ void SetOptions(uint options);
217
+ void GetOptions(out uint options);
218
+ void SetDefaultFolder(IShellItem folder);
219
+ void SetFolder(IShellItem folder);
220
+ void GetFolder(out IShellItem folder);
221
+ void GetCurrentSelection(out IShellItem item);
222
+ void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name);
223
+ void GetFileName([MarshalAs(UnmanagedType.LPWStr)] out string name);
224
+ void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
225
+ void SetOkButtonLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
226
+ void SetFileNameLabel([MarshalAs(UnmanagedType.LPWStr)] string label);
227
+ void GetResult(out IShellItem item);
228
+ }
229
+ [ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
230
+ interface IShellItem {
231
+ void BindToHandler(IntPtr context, ref Guid handler, ref Guid iid, out IntPtr result);
232
+ void GetParent(out IShellItem parent);
233
+ void GetDisplayName(uint format, [MarshalAs(UnmanagedType.LPWStr)] out string name);
234
+ }
235
+ /// <summary>Choose an existing filesystem folder, or return null when cancelled.</summary>
236
+ public static string Show(IntPtr owner) {
237
+ var dialog = (IFileDialog)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")));
238
+ IShellItem item = null;
239
+ try {
240
+ uint options;
241
+ dialog.GetOptions(out options);
242
+ dialog.SetOptions(options | FOS_PICKFOLDERS | FOS_FORCEFILESYSTEM | FOS_PATHMUSTEXIST);
243
+ dialog.SetTitle("选择项目目录");
244
+ int result = dialog.Show(owner);
245
+ if (result == CANCELLED) return null;
246
+ Marshal.ThrowExceptionForHR(result);
247
+ dialog.GetResult(out item);
248
+ string path;
249
+ item.GetDisplayName(SIGDN_FILESYSPATH, out path);
250
+ return path;
251
+ } finally {
252
+ if (item != null) Marshal.ReleaseComObject(item);
253
+ Marshal.ReleaseComObject(dialog);
254
+ }
255
+ }
256
+ }
257
+ `;
258
+ const WINDOWS_PICKER = [
259
+ '$ErrorActionPreference = "Stop"',
260
+ 'Add-Type -AssemblyName System.Windows.Forms',
261
+ '[Console]::OutputEncoding = [Text.Encoding]::UTF8',
262
+ '$owner = New-Object System.Windows.Forms.Form -Property @{ TopMost = $true; Opacity = 0; ShowInTaskbar = $false; FormBorderStyle = "None"; StartPosition = "CenterScreen"; Size = New-Object System.Drawing.Size(1, 1) }',
263
+ `Add-Type -TypeDefinition '${PICKER_RAISE_SOURCE} ${FOLDER_PICKER_SOURCE}'`,
264
+ '$owner.Show(); $owner.Hide(); $owner.Show(); $owner.Activate()',
265
+ '$timer = New-Object System.Windows.Forms.Timer -Property @{ Interval = 150 }; $timer.Add_Tick({ if ([PickerRaise]::OwnedBy($owner.Handle)) { $timer.Stop() } }); $timer.Start()',
266
+ 'try { [FolderPicker]::Show($owner.Handle) } finally { $timer.Stop(); $timer.Dispose(); $owner.Close(); $owner.Dispose() }',
267
+ ].join('; ');
268
+ const PICKERS = {
269
+ win32: ['powershell.exe', ['-NoProfile', '-STA', '-Command', WINDOWS_PICKER]],
270
+ darwin: ['osascript', ['-e', 'POSIX path of (choose folder with prompt "选择项目目录")']],
271
+ linux: ['zenity', ['--file-selection', '--directory', '--title=选择项目目录']],
272
+ };
273
+
274
+ /** Show the platform's own folder dialog on this computer; cancelling resolves without a path. */
275
+ export function pick_directory({ platform = process.platform, spawn_process = spawn } = {}) {
276
+ const picker = PICKERS[platform];
277
+ if (!picker) return Promise.reject(new Error('此系统不支持目录选择窗口,请直接输入完整路径'));
278
+ return new Promise((resolve_result, reject) => {
279
+ const child = spawn_process(picker[0], picker[1], { shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'] });
280
+ let output = '';
281
+ child.stdout.setEncoding('utf8');
282
+ child.stdout.on('data', chunk => { output += chunk; });
283
+ child.once('error', () => reject(new Error('无法打开目录选择窗口,请直接输入完整路径')));
284
+ child.once('close', code => {
285
+ const path = output.trim();
286
+ // Judge the path by the picker's platform, not the host's: a Windows path is not absolute on POSIX.
287
+ const absolute = platform === 'win32' ? win32.isAbsolute(path) : posix.isAbsolute(path);
288
+ resolve_result(code === 0 && absolute ? { path } : { cancelled: true });
289
+ });
290
+ });
291
+ }
292
+
293
+ /** Some CLIs take seconds to list models; reuse a good list for a day unless the executable changes or the user retries. */
294
+ const MODEL_CACHE_MS = 24 * 60 * 60 * 1000;
295
+
296
+ /** The executable's size and modification time, so a reinstalled or updated CLI is read again. */
297
+ function executable_stamp(profile) {
298
+ try { const file = statSync(profile.executable); return `${file.size}:${file.mtimeMs}`; } catch { return ''; }
299
+ }
300
+
301
+ /**
302
+ * The model and effort a software runs with when the card leaves them empty. One read from its own settings is
303
+ * cheap and always fresh; one that must run the CLI (agy) is kept for a day, because each run may refresh the
304
+ * software's login and, when that refresh fails, it opens a browser sign-in. `refresh` reads it again.
305
+ * agy updates itself often, so the key leaves out the executable stamp; a failed run is recorded too and keeps the
306
+ * last good answer, so a run that cannot sign in is not repeated on every room read. Changing the default model in the
307
+ * software's own settings (`stamp`) reads it again at once.
308
+ */
309
+ export async function cached_software_defaults(home, profile, { refresh = false, query = software_defaults, stamp = software_defaults_stamp } = {}) {
310
+ if (!adapter_profile(profile.adapter)?.defaults_by_query) return query(profile);
311
+ const path = join(home, 'model-catalogs.json');
312
+ const key = JSON.stringify(['defaults', profile.adapter, profile.executable || '']);
313
+ let cache = {};
314
+ try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
315
+ const entry = cache[key];
316
+ const setting = stamp(profile);
317
+ if (!refresh && entry && Date.now() - entry.at < MODEL_CACHE_MS && (entry.setting ?? '') === setting) return entry.result;
318
+ const answer = await query(profile);
319
+ const result = answer?.model ? answer : entry?.result || answer;
320
+ try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
321
+ atomic_json(path, { ...cache, [key]: { at: Date.now(), setting, result } });
322
+ return result;
323
+ }
324
+
325
+ /** Return the software catalog, served from the private service home when still valid. */
326
+ export async function cached_software_models(home, profile, { refresh = false, query = software_models, query_effort = software_effort, query_defaults = software_defaults } = {}) {
327
+ const path = join(home, 'model-catalogs.json');
328
+ const stamp = executable_stamp(profile);
329
+ const key = JSON.stringify([profile.adapter, profile.executable || '', stamp]);
330
+ const effort_key = JSON.stringify([profile.adapter, profile.executable || '', stamp, 'effort', profile.model || '']);
331
+ let cache = {};
332
+ try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
333
+ const cached = entry => !refresh && entry && Date.now() - entry.at < MODEL_CACHE_MS ? entry.result : null;
334
+ const [result, effort, defaults] = await Promise.all([cached(cache[key]) || query(profile),
335
+ adapter_profile(profile.adapter)?.efforts_per_model ? cached(cache[effort_key]) || query_effort(profile) : null,
336
+ cached_software_defaults(home, profile, { refresh, query: query_defaults })]);
337
+ const updates = {};
338
+ if (!cached(cache[key]) && !result.error && result.models.length) {
339
+ updates[key] = { at: Date.now(), result };
340
+ }
341
+ if (effort && !effort.error && !cached(cache[effort_key])) {
342
+ updates[effort_key] = { at: Date.now(), result: effort };
343
+ }
344
+ if (Object.keys(updates).length) {
345
+ try { cache = JSON.parse(readFileSync(path, 'utf8')); } catch {}
346
+ const prefix = JSON.stringify([profile.adapter, profile.executable || '']).slice(0, -1);
347
+ for (const old of Object.keys(cache)) if (old.startsWith(prefix) && !old.startsWith(key.slice(0, -1))) delete cache[old];
348
+ atomic_json(path, { ...cache, ...updates });
349
+ }
350
+ return { ...result, defaults, ...(effort ? { efforts: effort.levels, ...(effort.error ? { effort_error: effort.error } : {}) } : {}) };
351
+ }
352
+
353
+ /** Read private defaults without selecting a global room or identity. */
354
+ export function launch_settings(home) {
355
+ const path = join(home, 'launch-settings.json');
356
+ const settings = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { participants: {} };
357
+ for (const profile of Object.values(settings.participants || {})) for (const field of LEGACY_PROFILE_FIELDS) delete profile?.[field];
358
+ return settings;
359
+ }
360
+
361
+ /**
362
+ * Read the registered room's model choices, what each software selects for empty ones, and its smart scheduler, never connection secrets.
363
+ * `actual_model` / `actual_effort` (present only when known) are what each member's session last ran with, read from the software's own session log.
364
+ * With `quick`, agy's default model is not queried and its entry is marked `defaults_pending`.
365
+ */
366
+ export async function room_models(home, raw, { read_defaults = profile => cached_software_defaults(home, profile), read_session = session_settings } = {}) {
367
+ const input = launch_input({ ...raw, entry: 'web' });
368
+ if (!input.room_id) throw new Error('读取本场模型须提供 room_id');
369
+ const paths = read_registry(home).filter(path => {
370
+ const identity = registered_identity(path);
371
+ return identity?.site === input.site && identity.room === input.room_id;
372
+ });
373
+ if (paths.length > 1) throw new Error('本场存在多份登记配置,无法确定模型设置');
374
+ const config = paths.length ? configuration_snapshot(paths[0]).config : {};
375
+ const profiles = config.participants || {};
376
+ let sessions = {};
377
+ try { if (paths.length) sessions = bound_sessions(config, paths[0]); } catch { /* No readable runtime yet: fall back to borrowed sessions. */ }
378
+ const participants = Object.fromEntries(await Promise.all(Object.entries(profiles).map(async ([name, profile]) => {
379
+ const facts = adapter_profile(profile.adapter);
380
+ // An App chooses its model itself; a CLI or API member's card sets it.
381
+ const card_model = facts?.kind !== 'app';
382
+ // A software read by running it to name its default model takes seconds; a quick read leaves that to a later full read.
383
+ const pending = input.quick === true && Boolean(facts?.defaults_by_query);
384
+ const defaults = pending ? { model: '', effort: '' } : await read_defaults(profile);
385
+ const actual = read_session(profile.adapter, sessions[name] || profile.session_id);
386
+ return [name, { ...(pending ? { defaults_pending: true } : {}), adapter: profile.adapter, model: card_model ? profile.model || '' : '',
387
+ effort: facts?.efforts ? profile.effort || '' : '', default_model: defaults.model, default_effort: defaults.effort,
388
+ ...(actual.model ? { actual_model: actual.model } : {}), ...(actual.effort ? { actual_effort: actual.effort } : {}),
389
+ project_access: !facts?.capabilities.project ? 'read' : profile.project_access || config.project_access || 'read',
390
+ // A member bound to its own conversation may keep that conversation's project, so this tool cannot set its access.
391
+ own_project: Boolean(facts?.own_project_when_bound && profile.session_id),
392
+ // A member working outside every project directory of the room only reads them; the page warns and names its directory.
393
+ ...(facts?.capabilities.project && outside_directory(config, profile) ? { outside_directory: outside_directory(config, profile),
394
+ outside_enforced: read_only_enforced({ ...profile, project_access: profile.project_access || config.project_access || 'read' }) } : {}) }];
395
+ })));
396
+ // Smart scheduling is a local choice; only which model decides is shown, never its key.
397
+ const scheduler = config.scheduler ? { provider: config.scheduler.provider, model: config.scheduler.model, mode: config.scheduler.mode || DEFAULT_SCHEDULER_MODE } : null;
398
+ return { room_id: input.room_id, registered: paths.length > 0, participants, scheduler, project_directory: config.cwd || '',
399
+ extra_directories: config.extra_directories || [],
400
+ workflow: room_workflow_status(config, home), host_workflows: Boolean(config.host_workflows),
401
+ api_max_requests: config.api_max_requests ?? DEFAULT_API_MAX_REQUESTS,
402
+ // Whether members may draw here, and whether this computer has an image service to draw with.
403
+ image_generation: Boolean(config.image_generation), image_configured: image_settings(home).configured };
404
+ }
405
+
406
+ /** Read one member's installed skills for the room owner, using only this computer's saved software and directory. */
407
+ export async function room_skills(home, raw, { read_skills = software_skills } = {}) {
408
+ const { input, config } = await member_room_context(home, raw);
409
+ const profile = config.participants?.[input.name];
410
+ if (!profile) return { room_id: input.room_id, member: input.name, available: false, skills: [], reason: '本机没有此成员的软件配置,无法读取技能' };
411
+ const result = await read_skills({ ...profile, cwd: profile.cwd || config.cwd || '' });
412
+ return { room_id: input.room_id, member: input.name, ...result };
413
+ }
414
+
415
+ /**
416
+ * The room's workflow as the right column shows it; `available` is false when its folder is gone or broken, and
417
+ * `cards` lists the card IDs the library has now, so the page offers a refresh only when the room differs from it.
418
+ */
419
+ function room_workflow_status(config, home) {
420
+ if (!config.workflow?.id) return null;
421
+ const loaded = load_room_workflow({ ...config, api_home: config.api_home || home, workflow: { ...config.workflow, enabled: true } });
422
+ // `cards` are the main flow's, which a refresh fills; a sub-workflow's cards join only when it is used.
423
+ const cards = Object.values(loaded.cards || {});
424
+ return { id: config.workflow.id, label: loaded.label || config.workflow.id, enabled: Boolean(config.workflow.enabled),
425
+ available: !loaded.error, members: config.workflow.members || {}, cards: cards.filter(card => !card.sub_workflow).map(card => card.card),
426
+ sub_workflows: (loaded.sub_workflows || []).map(sub => ({ id: sub.id, label: sub.label || sub.id, description: sub.description, cards: sub.cards })) };
427
+ }
428
+
429
+ /**
430
+ * Read the owner's saved room projects, never a directory supplied by the request: `root` picks one of the room's
431
+ * directories by index (0, the main one, by default), and a search covers all of them.
432
+ */
433
+ export async function room_files(home, raw, { trust = false } = {}) {
434
+ const { input, config } = await member_room_context(home, raw, { trust });
435
+ const directories = room_directories(config);
436
+ if (input.query) return { room_id: input.room_id, ...search_project_roots(directories, input.query) };
437
+ const root = input.root ?? 0;
438
+ if (!Number.isSafeInteger(root) || root < 0 || (directories.length && root >= directories.length)) throw new Error('项目目录编号无效,请刷新后重试');
439
+ return { room_id: input.room_id, root, ...read_project_files(directories[root], input.path, input.offset) };
440
+ }
441
+
442
+ /**
443
+ * `room-files` asked for by another device, answered inside the relay's own process: the same checks as the local
444
+ * entrypoint with `--remote`, without starting Node for every folder opened.
445
+ */
446
+ export async function remote_room_files(home, input) {
447
+ assert_shared_home(home);
448
+ guard_remote_request('room-files', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
449
+ return room_files(home, input, { trust: true });
450
+ }
451
+
452
+ // A relayed answer carries this much of a page at a time, within the relay's encrypted envelope after base64.
453
+ const PAGE_PART_BYTES = 192 * 1024;
454
+
455
+ /**
456
+ * One HTML file of the room's project with the files it refers to inlined (see `bundle_project_page`), or the images a
457
+ * Markdown file shows (`bundle_project_markdown`), as base64
458
+ * `data` from `offset`. With `parts` (another device, through the relay) at most `PAGE_PART_BYTES` at a time; the
459
+ * caller asks again from where a part ended and checks `version` stays the same.
460
+ */
461
+ export async function room_page(home, raw, { trust = false, parts = false } = {}) {
462
+ const { input, config } = await member_room_context(home, raw, { trust });
463
+ const directories = room_directories(config);
464
+ const root = input.root ?? 0;
465
+ const offset = input.offset ?? 0;
466
+ if (!Number.isSafeInteger(root) || root < 0 || root >= Math.max(1, directories.length)) throw new Error('项目目录编号无效,请刷新后重试');
467
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('页面读取位置无效');
468
+ const bundle = /\.(md|markdown)$/i.test(String(input.path || '')) ? bundle_project_markdown : bundle_project_page;
469
+ const { bytes, ...page } = bundle(directories[root], input.path);
470
+ const part = bytes.subarray(offset, parts ? offset + PAGE_PART_BYTES : bytes.length);
471
+ return { room_id: input.room_id, root, ...page, total: bytes.length, offset, data: part.toString('base64') };
472
+ }
473
+
474
+ // Through the relay a media file comes whole, in parts, so another device plays at most this much.
475
+ export const REMOTE_MEDIA_MAX_BYTES = 64 * 1024 * 1024;
476
+
477
+ /**
478
+ * One image, video or audio file of the room's project (see `project_media`). For the computer's own page it names
479
+ * the real file, which the local site streams by a ticket and never shows the page; with `parts` (another device,
480
+ * through the relay) it returns base64 `data` from `offset`, at most `PAGE_PART_BYTES` at a time, for files up to
481
+ * `REMOTE_MEDIA_MAX_BYTES`, and the caller checks `version` stays the same.
482
+ */
483
+ export async function room_media(home, raw, { trust = false, parts = false } = {}) {
484
+ const { input, config } = await member_room_context(home, raw, { trust });
485
+ const directories = room_directories(config);
486
+ const root = input.root ?? 0;
487
+ const offset = input.offset ?? 0;
488
+ if (!Number.isSafeInteger(root) || root < 0 || root >= Math.max(1, directories.length)) throw new Error('项目目录编号无效,请刷新后重试');
489
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error('文件读取位置无效');
490
+ const { file, ...media } = project_media(directories[root], input.path);
491
+ if (!parts) return { room_id: input.room_id, root, ...media, file };
492
+ if (media.size > REMOTE_MEDIA_MAX_BYTES) throw new Error(`文件 ${Math.ceil(media.size / 1024 / 1024)} MB,超过其他设备可播放的 ${REMOTE_MEDIA_MAX_BYTES / 1024 / 1024} MB 上限;请在这台电脑上打开`);
493
+ const part = Buffer.alloc(Math.max(0, Math.min(PAGE_PART_BYTES, media.size - offset)));
494
+ const handle = openSync(file, 'r');
495
+ try { readSync(handle, part, 0, part.length, offset); } finally { closeSync(handle); }
496
+ return { room_id: input.room_id, root, ...media, total: media.size, offset, data: part.toString('base64') };
497
+ }
498
+
499
+ /** `room-media` asked for by another device, answered inside the relay's own process in parts. */
500
+ export async function remote_room_media(home, input) {
501
+ assert_shared_home(home);
502
+ guard_remote_request('room-media', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
503
+ return room_media(home, input, { trust: true, parts: true });
504
+ }
505
+
506
+ /** `room-page` asked for by another device, answered inside the relay's own process in parts, like `remote_room_files`. */
507
+ export async function remote_room_page(home, input) {
508
+ assert_shared_home(home);
509
+ guard_remote_request('room-page', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
510
+ return room_page(home, input, { trust: true, parts: true });
511
+ }
512
+
513
+ // The newest part of a long-running execution's log is what its detail view needs; older lines are dropped.
514
+ const DETAIL_LOG_TAIL_BYTES = 4 * 1024 * 1024;
515
+
516
+ /**
517
+ * What a member did in one execution, rebuilt from the raw event log its process wrote in the room's runtime directory
518
+ * (`<adapter>-free-<execution>.log`). The log stays on this computer: the page reads it here or through the relay.
519
+ * `available: false` when the execution kept no such log (an App or manual member, or an API member).
520
+ */
521
+ export async function execution_details_command(home, raw, { trust = false } = {}) {
522
+ const { input, config } = await member_room_context(home, raw, { trust });
523
+ // A private chat turn (`chat_id`) keeps its log the same way as an execution.
524
+ const chat = input.chat_id !== undefined;
525
+ const execution_id = Number(chat ? input.chat_id : input.execution_id);
526
+ if (!Number.isSafeInteger(execution_id) || execution_id <= 0) throw new Error(chat ? '私聊编号无效' : '执行编号无效');
527
+ const suffix = `-${chat ? 'chat' : 'free'}-${execution_id}.log`;
528
+ const name = existsSync(config.directory) ? readdirSync(config.directory).find(file => file.endsWith(suffix)) : undefined;
529
+ const parsed = name ? execution_details(name.slice(0, -suffix.length), read_log_tail(join(config.directory, name))) : null;
530
+ return { room_id: input.room_id, [chat ? 'chat_id' : 'execution_id']: execution_id, available: Boolean(parsed), ...parsed };
531
+ }
532
+
533
+ /**
534
+ * `execution-details` asked for by another device, answered inside the relay's own process like `remote_room_files`:
535
+ * the private-chat page reads it for every turn and again every poll for a running one, so starting Node and asking
536
+ * the site to check the credential each time made the page wait seconds for what is already on this computer.
537
+ */
538
+ export async function remote_execution_details(home, input) {
539
+ assert_shared_home(home);
540
+ guard_remote_request('execution-details', input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
541
+ return execution_details_command(home, input, { trust: true });
542
+ }
543
+
544
+ /** The last bytes of a log as text, starting at a whole line. */
545
+ function read_log_tail(path) {
546
+ const size = statSync(path).size, length = Math.min(size, DETAIL_LOG_TAIL_BYTES);
547
+ const buffer = Buffer.alloc(length), descriptor = openSync(path, 'r');
548
+ try { readSync(descriptor, buffer, 0, length, size - length); } finally { closeSync(descriptor); }
549
+ const text = buffer.toString('utf8');
550
+ return length < size ? text.slice(text.indexOf('\n') + 1) : text;
551
+ }
552
+
553
+ const CREATE_PREFERENCE_RANGES = { max_rounds: [0, 100], max_minutes: [0, 1440], goal_max_continues: [0, 100], goal_max_minutes: [0, 1440], chain_rounds: [0, 100],
554
+ api_max_requests: [0, MAX_API_MAX_REQUESTS] };
555
+ const CREATE_PREFERENCE_FLAGS = ['named_followup', 'host_workflows', 'advanced_open'];
556
+ const MAX_PREFERENCE_MODEL_LENGTH = 200;
557
+ const SETTINGS_LOCK_WAIT_MS = 5000;
558
+
559
+ /** Validate only reusable form choices; room text, members, paths and credentials are never preferences. */
560
+ function validate_create_preferences(input) {
561
+ if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('建房偏好须为对象');
562
+ for (const [field, value] of Object.entries(input)) {
563
+ let valid = false;
564
+ if (CREATE_PREFERENCE_FLAGS.includes(field)) valid = typeof value === 'boolean';
565
+ else if (Object.hasOwn(CREATE_PREFERENCE_RANGES, field)) {
566
+ const [minimum, maximum] = CREATE_PREFERENCE_RANGES[field];
567
+ valid = Number.isInteger(value) && value >= minimum && value <= maximum;
568
+ } else if (field === 'drive') valid = ['free', 'discussion', 'goal'].includes(value);
569
+ else if (field === 'workflow_id') valid = typeof value === 'string' && (!value || WORKFLOW_ID_PATTERN.test(value));
570
+ else if (field === 'scheduler') valid = valid_scheduler_preference(value);
571
+ if (!valid) throw new Error(`建房偏好字段无效:${field}`);
572
+ }
573
+ }
574
+
575
+ /** A scheduler preference carries selections, never a key or even a key reference. */
576
+ function valid_scheduler_preference(value) {
577
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
578
+ const fields = {
579
+ enabled: item => typeof item === 'boolean',
580
+ provider: item => typeof item === 'string' && (!item || Object.hasOwn(SCHEDULER_PROVIDERS, item)),
581
+ model: item => typeof item === 'string' && item.length <= MAX_PREFERENCE_MODEL_LENGTH,
582
+ mode: item => typeof item === 'string' && (!item || Object.hasOwn(SCHEDULER_MODES, item)),
583
+ };
584
+ return Object.entries(value).every(([field, item]) => Object.hasOwn(fields, field) && fields[field](item));
585
+ }
586
+
587
+ /** Update software defaults or form preferences independently, preserving the other section. */
588
+ export function save_launch_settings(home, input) {
589
+ const patch = {};
590
+ if (Object.hasOwn(input, 'participants')) {
591
+ const participants = {};
592
+ for (const [name, profile] of Object.entries(input.participants || {})) {
593
+ if (platform_of(name) !== name) throw new Error(`本机默认配置按平台保存;${name} 的模型与强度只用于本场讨论`);
594
+ validate_profile(name, profile);
595
+ participants[name] = profile;
596
+ }
597
+ patch.participants = participants;
598
+ }
599
+ if (Object.hasOwn(input, 'create_preferences')) {
600
+ validate_create_preferences(input.create_preferences);
601
+ patch.create_preferences = input.create_preferences;
602
+ }
603
+ mkdirSync(home, { recursive: true, mode: 0o700 });
604
+ const lock = new DatabaseSync(join(home, 'launch-settings-lock.sqlite3'));
605
+ try {
606
+ lock.exec(`PRAGMA busy_timeout=${SETTINGS_LOCK_WAIT_MS}; BEGIN IMMEDIATE`);
607
+ const previous = launch_settings(home);
608
+ const settings = { ...previous, ...patch };
609
+ if (patch.create_preferences) settings.create_preferences = { ...previous.create_preferences, ...patch.create_preferences };
610
+ atomic_json(join(home, 'launch-settings.json'), settings);
611
+ lock.exec('COMMIT');
612
+ return settings;
613
+ } finally { lock.close(); }
614
+ }
615
+
616
+ const PROJECT_NAME_LIMIT = 80;
617
+ const PROJECT_ID_PATTERN = /^[0-9a-f]{8,32}$/;
618
+
619
+ /** Read the named project directories saved on this computer, offered as launch cwd choices. */
620
+ export function launch_projects(home) {
621
+ // An ordinary account's projects are the folders under its projects root; it keeps no list of its own.
622
+ const { projects_root } = account_space(home);
623
+ if (projects_root) return { projects: account_projects(projects_root), restricted: true };
624
+ const path = join(home, 'launch-projects.json');
625
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : { projects: [] };
626
+ }
627
+
628
+ /** Replace the project list; every path must be an existing folder on this computer. */
629
+ // The id outlives renames and moves: other devices choose a project by id and never see its path.
630
+ export function save_launch_projects(home, input) {
631
+ const { projects_root } = account_space(home);
632
+ if (projects_root) {
633
+ if (typeof input.create !== 'string') throw new Error('此账号的项目只能在自己的项目文件夹内新建:请提供 create(项目名称)');
634
+ const created = create_account_project(projects_root, input.create);
635
+ return { ...launch_projects(home), created };
636
+ }
637
+ if (!Array.isArray(input.projects)) throw new Error('projects 必须为列表');
638
+ const projects = input.projects.map(item => ({ id: PROJECT_ID_PATTERN.test(item?.id) ? item.id : randomUUID().replaceAll('-', '').slice(0, 16),
639
+ name: String(item?.name || '').trim(), path: String(item?.path || '').trim() }));
640
+ const names = new Set();
641
+ for (const { name, path } of projects) {
642
+ if (!name || name.length > PROJECT_NAME_LIMIT) throw new Error(`项目名称不能为空,且不超过 ${PROJECT_NAME_LIMIT} 字`);
643
+ if (names.has(name)) throw new Error(`项目名称重复:${name}`);
644
+ names.add(name);
645
+ if (!isAbsolute(path)) throw new Error(`${name}:路径必须为完整绝对路径`);
646
+ if (!existsSync(path) || !statSync(path).isDirectory()) throw new Error(`${name}:这台电脑上不存在此文件夹:${path}`);
647
+ }
648
+ mkdirSync(home, { recursive: true, mode: 0o700 });
649
+ atomic_json(join(home, 'launch-projects.json'), { projects });
650
+ return { projects };
651
+ }
652
+
653
+ const MAX_EXPERT_PRESETS = 30;
654
+ const MAX_PRESET_DESCRIPTION = 500;
655
+ const MAX_PRESET_FIELD = 200;
656
+ // name is the instance a preset adds (platform-suffix); label is the free name shown for it, on the add row and in the room.
657
+ const PRESET_FIELDS = ['name', 'label', 'description', 'system_prompt', 'project_access', 'model', 'effort'];
658
+ const MAX_PRESET_LABEL = 32;
659
+
660
+ /**
661
+ * Presets saved while IDs could hold Chinese: such an ID becomes `platform-presetN` and its old name the label, so the
662
+ * add row still shows it. The next save keeps the new form.
663
+ */
664
+ function english_preset_ids(presets) {
665
+ const taken = new Set(presets.map(preset => preset.name));
666
+ return presets.map(preset => {
667
+ const platform = /^(Codex|Claude|Antigravity|DeepSeek|Qwen|Grok|OpenAI|Custom)(?:-|$)/.exec(preset.name || '')?.[1];
668
+ if (!platform || platform_of(preset.name)) return preset;
669
+ let number = 1;
670
+ while (taken.has(`${platform}-preset${number}`)) number++;
671
+ const name = `${platform}-preset${number}`;
672
+ taken.add(name);
673
+ return { ...preset, name, label: preset.label || preset.name };
674
+ });
675
+ }
676
+
677
+ /** The user's expert presets and per-platform default descriptions saved on this computer, plus the built-in presets the user has not deleted. */
678
+ export function expert_presets(home) {
679
+ const path = join(home, 'expert-presets.json');
680
+ const saved = existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : {};
681
+ const hidden_builtins = saved.hidden_builtins || [];
682
+ // A preset saved while members drew with their own image model keeps the rest; drawing is the room's switch now.
683
+ const presets = (saved.presets || []).map(({ image_model, ...preset }) => preset);
684
+ return { presets: english_preset_ids(presets), description_templates: saved.description_templates || {}, hidden_builtins,
685
+ builtin_presets: BUILTIN_EXPERT_PRESETS.filter(preset => !hidden_builtins.includes(preset.name)) };
686
+ }
687
+
688
+ /** Check one expert preset; a workflow's agent card is a preset and obeys the same rule. */
689
+ export function validate_preset(preset) {
690
+ if (!preset || typeof preset !== 'object' || Object.keys(preset).some(key => !PRESET_FIELDS.includes(key))) throw new Error('预设只能包含名称、显示名、描述、提示词、项目权限、模型与强度');
691
+ if (!platform_of(preset.name) || !clients_of(preset.name)) throw new Error(`预设 ID 须为“平台名”或“平台名-后缀”,后缀只用英文、数字和下划线:${preset.name}`);
692
+ if (Object.values(preset).some(value => typeof value !== 'string')) throw new Error(`${preset.name} 的字段必须为文本`);
693
+ if ((preset.label || '').trim().length > MAX_PRESET_LABEL) throw new Error(`${preset.name} 的显示名最多 ${MAX_PRESET_LABEL} 字`);
694
+ if ((preset.description || '').length > MAX_PRESET_DESCRIPTION) throw new Error(`${preset.name} 的描述最多 ${MAX_PRESET_DESCRIPTION} 字`);
695
+ if ((preset.system_prompt || '').length > MAX_EXPERT_PROMPT) throw new Error(`${preset.name} 的提示词最多 ${MAX_EXPERT_PROMPT} 字`);
696
+ if (preset.project_access && !PROJECT_ACCESS.includes(preset.project_access)) throw new Error(`${preset.name} 的项目权限须为 read、write、auto 或 full`);
697
+ if ([preset.model, preset.effort].some(value => (value || '').length > MAX_PRESET_FIELD)) throw new Error(`${preset.name} 的模型或强度过长`);
698
+ }
699
+
700
+ /** Replace the user's presets, default descriptions or deleted built-ins (whichever the input carries); every field is checked first. */
701
+ export function save_expert_presets(home, input) {
702
+ const current = expert_presets(home);
703
+ const presets = input.presets === undefined ? current.presets : input.presets;
704
+ const templates = input.description_templates === undefined ? current.description_templates : input.description_templates;
705
+ const hidden_builtins = input.hidden_builtins === undefined ? current.hidden_builtins : input.hidden_builtins;
706
+ const builtin_names = BUILTIN_EXPERT_PRESETS.map(preset => preset.name);
707
+ if (!Array.isArray(hidden_builtins) || hidden_builtins.some(name => !builtin_names.includes(name))) throw new Error(`hidden_builtins 只能列出内置预设:${builtin_names.join('、')}`);
708
+ if (!Array.isArray(presets) || presets.length > MAX_EXPERT_PRESETS) throw new Error(`presets 必须为列表,最多 ${MAX_EXPERT_PRESETS} 个`);
709
+ const names = new Set();
710
+ for (const preset of presets) {
711
+ validate_preset(preset);
712
+ if (names.has(preset.name)) throw new Error(`预设名称重复:${preset.name}`);
713
+ names.add(preset.name);
714
+ }
715
+ if (!templates || typeof templates !== 'object' || Array.isArray(templates) || Object.entries(templates).some(([platform, text]) =>
716
+ platform_of(platform) !== platform || typeof text !== 'string' || !text.trim() || text.length > MAX_PRESET_DESCRIPTION)) {
717
+ throw new Error(`description_templates 须为 {平台名: 描述},每段 1–${MAX_PRESET_DESCRIPTION} 字`);
718
+ }
719
+ mkdirSync(home, { recursive: true, mode: 0o700 });
720
+ atomic_json(join(home, 'expert-presets.json'), { presets, description_templates: templates, hidden_builtins });
721
+ return expert_presets(home);
722
+ }
723
+
724
+ /** Reject malformed client fields before saving defaults or creating any discussion. */
725
+ function validate_profile(name, profile, binding = false) {
726
+ if (!clients_of(name) || !profile || typeof profile !== 'object' || Array.isArray(profile)) throw new Error(`不支持的软件配置:${name}`);
727
+ if (profile.adapter && !clients_of(name).includes(profile.adapter)) throw new Error(`${name} 的客户端不匹配`);
728
+ // Session bindings and project write access apply to one launch only, never to machine defaults.
729
+ const fields = binding ? [...PROFILE_FIELDS, 'session_id', 'project_access'] : PROFILE_FIELDS;
730
+ if (Object.keys(profile).some(key => !fields.includes(key))) throw new Error('软件配置包含不支持的字段;默认配置不能保存房间或会话绑定');
731
+ for (const [key, value] of Object.entries(profile)) {
732
+ if (key === 'allowed_tools') {
733
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) throw new Error(`${name}.allowed_tools 必须为工具名称数组`);
734
+ } else if (typeof value !== 'string') throw new Error(`${name}.${key} 必须为文本`);
735
+ if (['executable', 'cwd', 'ipc_directory'].includes(key) && value && !isAbsolute(value)) throw new Error(`${name}.${key} 必须为完整绝对路径`);
736
+ // The model is passed as one CLI argument, so it must not look like a flag or contain spaces.
737
+ if (key === 'model' && value && !/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]*$/.test(value)) throw new Error(`${name}.${key} 只能是模型名称,例如 gpt-6-astra、opus 或 gemini-4-argon-high`);
738
+ if (key === 'system_prompt' && value.length > MAX_EXPERT_PROMPT) throw new Error(`${name} 的专属提示词最多 ${MAX_EXPERT_PROMPT} 字`);
739
+ }
740
+ const facts = adapter_profile(profile.adapter);
741
+ if (facts?.kind === 'api') validate_api_profile(profile);
742
+ // The UI discovers each model's supported subset; omitted values keep the CLI's own default.
743
+ if (profile.effort && facts?.kind !== 'api' && !facts?.efforts?.includes(profile.effort)) {
744
+ throw new Error(facts?.efforts ? `${name}.effort 只能是 ${facts.efforts.join(' / ')}` : `${name} 的思考档位在原软件中选择`);
745
+ }
746
+ }
747
+
748
+ /** Send one request without following redirects that could disclose the room credential. */
749
+ async function site_request(site, path, token, body, headers = {}) {
750
+ const response = await fetch(`${site}${path}`, { method: body === undefined ? 'GET' : 'POST',
751
+ headers: { 'Content-Type': 'application/json', 'X-Discussion-Token': token, ...headers },
752
+ body: body === undefined ? undefined : JSON.stringify(body), redirect: 'error', signal: AbortSignal.timeout(10000) });
753
+ const result = await response.json();
754
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${result.error || '请求失败'}`);
755
+ return result;
756
+ }
757
+
758
+ /** Require an explicit website, launch entry and stable creation identity. */
759
+ function launch_input(input) {
760
+ const value = structuredClone(input);
761
+ const url = new URL(value.site);
762
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.pathname !== '/' || url.search || url.hash) throw new Error('site 必须为 HTTP(S) 根地址');
763
+ value.site = url.origin;
764
+ if (!['conversation', 'web'].includes(value.entry)) throw new Error('entry 必须为 conversation 或 web');
765
+ if (value.entry === 'conversation' && (typeof value.current_session_id !== 'string' || !value.current_session_id.trim())) throw new Error('对话入口须提供当前实际会话的 current_session_id');
766
+ if (value.cwd && (typeof value.cwd !== 'string' || !isAbsolute(value.cwd))) throw new Error('cwd 必须为完整绝对路径');
767
+ // A new room's extra project directories; an existing room changes them through room-settings.
768
+ if (!value.room_id && value.extra_directories?.length) check_extra_directories(value.cwd, value.extra_directories);
769
+ else if (!value.room_id) delete value.extra_directories;
770
+ if (value.project_access && !PROJECT_ACCESS.includes(value.project_access)) throw new Error('project_access 只能为 read、write、auto 或 full');
771
+ if (value.room_id && !/^[A-Za-z0-9_-]+$/.test(value.room_id)) throw new Error('房间编号无效');
772
+ if (!value.room_id && !value.room?.submission_id) throw new Error('新房间须提供 room.submission_id;重试沿用原编号');
773
+ if (value.room?.mode === 'free') {
774
+ // P1: a free room is launched once, at creation, from the web page.
775
+ if (value.entry !== 'web' || value.room_id) throw new Error('房间目前只能在网页创建时启动');
776
+ const members = value.room.members;
777
+ const names = members?.map(member => typeof member === 'string' ? member : member.name);
778
+ const woken = Array.isArray(members) ? members.filter(woken_member).map(member => typeof member === 'string' ? member : member.name) : [];
779
+ if ((!woken.length && !value.scheduler && !value.cwd) || !names?.length || new Set(names).size !== names.length || woken.some(name => !clients_of(name))) {
780
+ throw new Error('房间须选择至少 1 位支持自动接入的 AI 成员(或开启智能调度、指定项目目录),且不能重复');
781
+ }
782
+ }
783
+ if (value.access_file) {
784
+ const access = JSON.parse(readFileSync(resolve(value.access_file), 'utf8'));
785
+ if (access.site?.replace(/\/$/, '') !== value.site || access.room !== value.room_id) throw new Error('access_file 与本次站点或房间不符');
786
+ value.token = access.token;
787
+ }
788
+ return value;
789
+ }
790
+
791
+ /** Discussion experts the member list marks as manual: they answer with their own credential and need no local software. */
792
+ function manual_experts(room) {
793
+ return new Set((room.members || []).filter(member => member && typeof member === 'object' && member.access === 'manual').map(member => member.name));
794
+ }
795
+
796
+ /** Merge machine defaults and explicit room overrides, preserving the selected participants. */
797
+ function launch_config(home, input, room, directory, options) {
798
+ // In a creation input, mode='free' means no immediate discussion; omitted mode still requests a hosted discussion.
799
+ if (room.mode === 'free') return free_launch_config(home, input, room, directory, options);
800
+ if (!clients_of(room.host)) throw new Error('请选择支持全自动讨论的 AI 主持人');
801
+ if (!room.experts || room.experts[room.host] !== 'cli') throw new Error('请将 AI 主持人的参与方式设为本地读写');
802
+ const other = Object.entries(room.experts).filter(([, mode]) => mode !== 'cli').map(([name]) => name);
803
+ if (other.length) throw new Error(`全自动讨论的参与方式须为本地读写:${other.join('、')}`);
804
+ const defaults = options.defaults || launch_settings(home).participants;
805
+ const manual = manual_experts(room);
806
+ if (manual.has(room.host)) throw new Error('AI 主持人由本机服务续接,不能选择手动接入');
807
+ const participants = {};
808
+ for (const name of new Set([room.host, ...Object.keys(room.experts)])) {
809
+ if (!manual.has(name)) participants[name] = participant_profile(name, defaults, input, name === room.host);
810
+ }
811
+ const members = launch_members(input, Object.keys(participants), options);
812
+ return validate_config({ site: input.site, room: room.id || 'preview', token: options.token, mode: 'free', participants, members, api_home: home,
813
+ scheduler: input.scheduler || undefined,
814
+ cwd: input.cwd, extra_directories: input.extra_directories, discussion_project: input.discussion_project, project_access: input.project_access || undefined,
815
+ data_directory: join(directory, 'runtime'), draft_directory: service_drafts(home, join(directory, 'runtime')) }, directory);
816
+ }
817
+
818
+ /** A free-room member the local service wakes; manual members join without local configuration. */
819
+ function woken_member(member) { return typeof member === 'string' || !member.access || member.access === 'runner'; }
820
+
821
+ /** Free rooms add one private credential per woken member, kept with the room configuration for retries. */
822
+ function free_launch_config(home, input, room, directory, options) {
823
+ const defaults = options.defaults || launch_settings(home).participants;
824
+ const names = room.members.filter(woken_member).map(member => typeof member === 'string' ? member : member.name);
825
+ const participants = Object.fromEntries(names.map(name => [name, participant_profile(name, defaults, input, false)]));
826
+ const members = launch_members(input, names, options);
827
+ // A workflow chosen at creation is written with the members, so the first wake already carries it.
828
+ const workflow = input.workflow ? bind_room_workflow({}, { ...input.workflow, enabled: true }).workflow : undefined;
829
+ if (workflow) { get_workflow(home, workflow.id); assert_workflow_enabled(home, workflow.id); }
830
+ if (workflow && Object.values(workflow.members).some(name => !names.includes(name))) throw new Error('工作流成员须在本次邀请的成员中');
831
+ return validate_config({ site: input.site, room: room.id || 'preview', token: options.token, mode: 'free', participants, members, api_home: home,
832
+ scheduler: input.scheduler || undefined, cwd: input.cwd, extra_directories: input.extra_directories, project_access: input.project_access || undefined, workflow,
833
+ host_workflows: input.host_workflows === true || undefined, api_max_requests: input.api_max_requests,
834
+ image_generation: input.image_generation === true || undefined,
835
+ data_directory: join(directory, 'runtime'), draft_directory: service_drafts(home, join(directory, 'runtime')) }, directory);
836
+ }
837
+
838
+ /** Members in the order of the creation form's cards, so the room's joining order (and default speaking order) follows it. */
839
+ function card_order(cards, members) {
840
+ const names = (cards || []).map(member => typeof member === 'string' ? member : member?.name);
841
+ const place = (name) => names.includes(name) ? names.indexOf(name) : names.length;
842
+ return [...members].sort((left, right) => place(left.name) - place(right.name));
843
+ }
844
+
845
+ /** Preserve caller-generated member credentials; journal newly generated ones before creation. */
846
+ function launch_members(input, names, options) {
847
+ return Object.fromEntries(names.map(name => {
848
+ const supplied = input.room?.members?.find(member => member?.name === name);
849
+ return [name, { token: supplied?.token || options.members?.[name]?.token || `${randomUUID()}${randomUUID()}` }];
850
+ }));
851
+ }
852
+
853
+ /**
854
+ * Merge one participant's machine defaults with this launch's overrides and check its software. A launch from another
855
+ * device (`input.without_saved_tools`) takes no tool approvals saved here, whichever way its members are named.
856
+ */
857
+ export function participant_profile(name, defaults, input, current_host) {
858
+ const platform = platform_of(name);
859
+ // An extra instance starts from its platform's settings but never from another instance's bound session.
860
+ const { session_id: ignored_session, ...inherited } = name === platform ? {} : input.participants?.[platform] || {};
861
+ const saved = { ...defaults[platform], ...(name === platform ? {} : defaults[name]) };
862
+ if (input.without_saved_tools) delete saved.allowed_tools;
863
+ const profile = { ...saved, ...inherited, ...input.participants?.[name] };
864
+ for (const field of ['cwd', 'model', 'effort', 'project_name', 'project_id', 'project_access']) if (profile[field] === '') delete profile[field];
865
+ validate_profile(name, profile, true);
866
+ if (!clients_of(name)?.includes(profile.adapter)) throw new Error(`请配置 ${name} 的 CLI / App 客户端`);
867
+ const facts = adapter_profile(profile.adapter);
868
+ if (facts?.kind === 'api') {
869
+ if (input.entry === 'conversation' && current_host) throw new Error('API 主持人请从网页启动;当前软件会话主持须选择对应 CLI / App');
870
+ return profile;
871
+ }
872
+ if (facts?.location === 'executable' && (!existsSync(profile.executable || '') || !statSync(profile.executable).isFile()
873
+ || (process.platform === 'win32' && !/\.exe$/i.test(profile.executable)))) throw new Error(`${name}:请指定实际原生可执行文件,Windows 使用 .exe`);
874
+ const cwd = profile.cwd || input.cwd;
875
+ if (cwd && (!existsSync(cwd) || !statSync(cwd).isDirectory())) throw new Error(`${name}:工作目录不存在或不是文件夹,请核对本次目录配置`);
876
+ if (input.entry === 'conversation' && current_host) profile.session_id = input.current_session_id;
877
+ // A new agy conversation always gets this tool's discussion project; only a manual agy expert the owner chose to host (input.adopt) keeps its own.
878
+ if (!facts?.host_existing && profile.session_id && !input.adopt) throw new Error(`${name}:${facts?.label || profile.adapter} 不能绑定已有会话或从当前对话主持全自动讨论;请从网页或其他软件发起,它会由讨论服务新建会话`);
879
+ return profile;
880
+ }
881
+
882
+ /** List every file below a directory, or nothing when the software has never stored a session there. */
883
+ function session_files(directory) {
884
+ return existsSync(directory) ? readdirSync(directory, { recursive: true }).map(path => join(directory, String(path))) : [];
885
+ }
886
+
887
+ /** Compare directories as the operating system resolves them (Windows short names and case). */
888
+ function same_directory(left, right) {
889
+ const real = path => { try { return realpathSync.native(path); } catch { return resolve(path); } };
890
+ const [a, b] = [real(left), real(right)];
891
+ return process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
892
+ }
893
+
894
+ /**
895
+ * Prove an invited existing conversation is on this machine before it can hold a turn, so a mistyped ID
896
+ * fails here instead of pausing the discussion later. Claude stores sessions per directory and resumes only
897
+ * from the original one, so its cwd follows the session: a session kept elsewhere than the room's project joins as a
898
+ * member working in its own directory (it only reads the room's directories); only a directory the member's own
899
+ * settings name explicitly must match.
900
+ */
901
+ export function borrowed_session(name, profile, room_cwd, env = process.env) {
902
+ const id = profile.session_id;
903
+ if (!SESSION_ID_PATTERN.test(id)) throw new Error(`${name}:会话 ID 格式不正确`);
904
+ const adapter = adapter_of(profile.adapter);
905
+ if (!adapter?.adopt || !adapter.session) {
906
+ const adoptable = ADAPTER_IDS.filter(item => ADAPTER_PROFILES[item].adopt).map(item => ADAPTER_PROFILES[item].label);
907
+ throw new Error(`${name}:只有 ${adoptable.join('、')} 可以接入已有会话`);
908
+ }
909
+ if (!adapter.session.exists(id, { env })) throw new Error(`${name}:本机找不到 ${adapter.label} 会话 ${id},请核对会话 ID`);
910
+ if (adapter.adopt !== 'own_cwd') return profile;
911
+ const cwd = adapter.session.cwd(id, { env });
912
+ if (!cwd) throw new Error(`${name}:${adapter.label} 会话 ${id} 没有记录原工作目录,无法续接`);
913
+ if (profile.cwd && !same_directory(profile.cwd, cwd)) throw new Error(`${name}:这个 ${adapter.label} 会话属于 ${cwd},只能在原目录续接;请让此 AI 的工作目录与它一致,或留空会话 ID 新建会话`);
914
+ return { ...profile, cwd: profile.cwd || (room_cwd && same_directory(room_cwd, cwd) ? room_cwd : cwd) };
915
+ }
916
+
917
+ // An owner credential the website accepted is trusted this long for read-only file browsing in a long-running process
918
+ // (the relay), so each folder opened from another device does not ask the website again.
919
+ const ROOM_FILES_TRUST_MS = 60000;
920
+ const trusted_room_tokens = new Map();
921
+
922
+ /** Find the one registered configuration of a room after proving the owner's credential; `trust` reuses a recent proof. */
923
+ async function member_room_context(home, raw, { trust = false } = {}) {
924
+ const input = launch_input({ ...raw, entry: 'web' });
925
+ if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('管理成员须提供房间编号和房间控制凭据');
926
+ const paths = read_registry(home).filter(path => {
927
+ const identity = registered_identity(path);
928
+ return identity?.site === input.site && identity.room === input.room_id;
929
+ });
930
+ if (paths.length !== 1) throw new Error('未找到本房间唯一的已登记配置,请核对本机接入服务');
931
+ const config = configuration_snapshot(paths[0]).config;
932
+ const proof = `${input.site}
933
+ ${input.room_id}
934
+ ${createHash('sha256').update(input.token).digest('hex')}`;
935
+ if (!trust || !(Date.now() - (trusted_room_tokens.get(proof) ?? -Infinity) < ROOM_FILES_TRUST_MS)) {
936
+ // Both reads need the owner credential; the inbox transfers no messages.
937
+ await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
938
+ trusted_room_tokens.set(proof, Date.now());
939
+ }
940
+ return { input, path: paths[0], config };
941
+ }
942
+
943
+ /** Write a manual member's private credential next to the room configuration, never into a receipt. */
944
+ function manual_access(path, input, name, token) {
945
+ const access_path = join(dirname(path), `manual-${name}.access.json`);
946
+ atomic_json(access_path, { site: input.site, room: input.room_id, member: name, token });
947
+ return access_path;
948
+ }
949
+
950
+ /**
951
+ * Invite (add) or bring back (rejoin) one member of a room.
952
+ * The local configuration is written before the website call, so a retry reuses the same credential.
953
+ * A manual member answers with its own credential and is never woken.
954
+ */
955
+ export async function room_member(home, raw, locked = false, headers = {}) {
956
+ const { input, path } = await member_room_context(home, raw);
957
+ const { action, name } = input;
958
+ const access = input.access || 'runner';
959
+ const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
960
+ if (!['add', 'rejoin'].includes(action) || !platform_of(name) || (access !== 'manual' && !clients_of(name)) || !['runner', 'manual'].includes(access)) {
961
+ throw new Error('action 须为 add/rejoin,成员须为支持的 AI,接入方式须为 runner/manual');
962
+ }
963
+ const release = locked ? () => {} : acquire_lock(join(dirname(path), 'configuration-edit'));
964
+ try {
965
+ const config = configuration_snapshot(path).config;
966
+ config.api_home = home;
967
+ const roster = room.free.members;
968
+ if (action === 'add' && input.new_instance) {
969
+ // A name once bound keeps its session locally, so a new instance never reuses a removed member's name.
970
+ const taken = new Set([...roster.map(member => member.name), ...Object.keys(config.participants), ...Object.keys(config.members || {})]);
971
+ return room_member(home, { ...raw, name: next_instance(platform_of(name), taken), new_instance: false }, true, headers);
972
+ }
973
+ const current = roster.find(member => member.name === name);
974
+ if (input.member_token !== undefined && (typeof input.member_token !== 'string' || input.member_token.length < 32 || input.member_token.length > 256)) throw new Error('member_token 须为 32–256 字符');
975
+ if (current?.status === 'active' && input.member_token && config.members?.[name]?.token === input.member_token) {
976
+ const view = await site_request(input.site, `/api/rooms/${input.room_id}/members/${current.id}`, input.token, { action: 'active', token: input.member_token }, headers);
977
+ return { room_id: input.room_id, member: name, access: current.access, free: view, access_file: null };
978
+ }
979
+ if (action === 'add' && !current && config.participants[name] && !locked) {
980
+ // A removed member's name keeps its bound session locally, so the new one joins under the next free name; a retry
981
+ // finds the name its own credential was saved under.
982
+ const taken = new Set([...roster.map(member => member.name), ...Object.keys(config.participants), ...Object.keys(config.members || {})]);
983
+ const retried = Object.keys(config.members || {}).find(key => key !== name && input.member_token && config.members[key].token === input.member_token
984
+ && !roster.some(member => member.name === key));
985
+ const renamed = retried || free_instance(name, taken);
986
+ const participants = raw.participants?.[name] ? { participants: { ...raw.participants, [renamed]: raw.participants[name] } } : {};
987
+ return room_member(home, { ...raw, name: renamed, ...participants }, true, headers);
988
+ }
989
+ if (action === 'rejoin' && current?.status !== 'away') throw new Error(`${name} 不是离开状态,无需请回`);
990
+ if (action === 'add' && current) throw new Error(`${name} 已是本房间成员;离开的成员请用请回`);
991
+ const manual = action === 'rejoin' ? current.access === 'manual' : access === 'manual';
992
+ const pending = input.retry_token && config.members?.[name]?.pending === input.retry_token;
993
+ const token = input.member_token || (pending ? config.members[name].token : `${randomUUID()}${randomUUID()}`);
994
+ let profile = config.participants[name];
995
+ if (!manual) {
996
+ if (action === 'add') {
997
+ profile = participant_profile(name, launch_settings(home).participants, { ...input, cwd: input.cwd || config.cwd }, false);
998
+ if (profile.session_id) profile = borrowed_session(name, profile, input.cwd || config.cwd);
999
+ }
1000
+ if (!profile) throw new Error(`${name} 没有本机接入配置;请移除后重新邀请`);
1001
+ const next = { ...config, participants: { ...config.participants, [name]: profile },
1002
+ members: { ...config.members, [name]: { token, pending: input.retry_token || '' } } };
1003
+ validate_config(next, dirname(path));
1004
+ atomic_json(path, next);
1005
+ }
1006
+ const access_file = manual ? manual_access(path, input, name, token) : null;
1007
+ const body = action === 'add'
1008
+ ? { name, adapter: manual ? '' : profile.adapter, token, access, session_mode: profile?.session_id ? 'borrowed' : 'new' }
1009
+ : { action: 'active', token };
1010
+ const view = await site_request(input.site, action === 'add' ? `/api/rooms/${input.room_id}/members` : `/api/rooms/${input.room_id}/members/${current.id}`,
1011
+ input.token, body, headers);
1012
+ return { room_id: input.room_id, member: name, access: manual ? 'manual' : 'runner', free: view, access_file };
1013
+ } finally { release(); }
1014
+ }
1015
+
1016
+
1017
+ /**
1018
+ * Change this room's runner settings, any of: `api_max_requests`, how many model requests one execution of an API member
1019
+ * may make (0 = no limit); `cwd`, the main project directory, accepted only while the room has none (once set it never
1020
+ * changes: sessions and file-change tracking are bound to it); `extra_directories`, the project directories shared
1021
+ * besides the main one, replaced as a whole. Members already in a room that gets its main directory keep working where
1022
+ * their sessions are (their `cwd` is pinned to '') and reach the room's directories as extra ones; members invited later
1023
+ * work in it; `image_generation`, whether members may draw with this computer's image service; `scheduler`, the room's
1024
+ * smart scheduling ({provider, model, api_key_ref, mode}, or null to turn it off), picked up by the running service at
1025
+ * its next tick. Everything is read at each delivery, so it applies from the next execution and keeps every session.
1026
+ */
1027
+ export async function room_settings(home, raw) {
1028
+ const { input, path } = await member_room_context(home, raw);
1029
+ const { api_max_requests: requests, extra_directories: directories, cwd, image_generation: images, scheduler } = input;
1030
+ if (requests === undefined && directories === undefined && cwd === undefined && images === undefined && scheduler === undefined) throw new Error('须提供 api_max_requests、image_generation、scheduler、cwd 或 extra_directories');
1031
+ if (scheduler !== undefined && scheduler !== null && (typeof scheduler !== 'object' || Array.isArray(scheduler))) throw new Error('scheduler 须为智能调度配置或 null');
1032
+ if (requests !== undefined && !Number.isInteger(requests)) throw new Error('api_max_requests 须为整数');
1033
+ if (images !== undefined && typeof images !== 'boolean') throw new Error('image_generation 须为 true 或 false');
1034
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1035
+ try {
1036
+ const config = configuration_snapshot(path).config;
1037
+ const next = { ...config, ...(requests !== undefined ? { api_max_requests: requests } : {}), ...(images !== undefined ? { image_generation: images } : {}) };
1038
+ // Off is written as null, not dropped, so the running service's merge of the new configuration turns it off too.
1039
+ if (scheduler !== undefined) next.scheduler = scheduler && { provider: scheduler.provider, model: scheduler.model, api_key_ref: scheduler.api_key_ref, ...(scheduler.mode ? { mode: scheduler.mode } : {}) };
1040
+ if (cwd !== undefined) {
1041
+ if (config.cwd) throw new Error('本房间已有项目目录,建房后不能更改;可添加其他项目目录');
1042
+ if (typeof cwd !== 'string' || !isAbsolute(cwd) || !existsSync(cwd) || !statSync(cwd).isDirectory()) throw new Error('项目目录须为本机已有文件夹的完整路径');
1043
+ next.cwd = cwd;
1044
+ next.participants = Object.fromEntries(Object.entries(config.participants || {}).map(([name, profile]) => [name, { ...profile, cwd: profile.cwd ?? '' }]));
1045
+ }
1046
+ if (directories !== undefined) {
1047
+ check_extra_directories(next.cwd, directories);
1048
+ next.extra_directories = directories.length ? directories : undefined;
1049
+ }
1050
+ validate_config(next, dirname(path));
1051
+ atomic_json(path, next);
1052
+ return { room_id: input.room_id, ...(requests !== undefined ? { api_max_requests: requests } : {}), ...(images !== undefined ? { image_generation: images } : {}),
1053
+ ...(scheduler !== undefined ? { scheduler: next.scheduler ? { provider: next.scheduler.provider, model: next.scheduler.model, mode: next.scheduler.mode || DEFAULT_SCHEDULER_MODE } : null } : {}),
1054
+ ...(cwd !== undefined ? { project_directory: cwd } : {}), ...(directories !== undefined ? { extra_directories: directories } : {}) };
1055
+ } finally { release(); }
1056
+ }
1057
+
1058
+ /**
1059
+ * Switch one woken member's project files between read-only and writable after the room is created. Every run builds its
1060
+ * permissions from the configuration, so the change applies from the member's next delivery and keeps its session.
1061
+ */
1062
+ export async function room_member_access(home, raw) {
1063
+ const { input, path } = await member_room_context(home, raw);
1064
+ const { name, project_access } = input;
1065
+ if (!PROJECT_ACCESS.includes(project_access)) throw new Error('project_access 只能为 read、write、auto 或 full');
1066
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1067
+ try {
1068
+ const config = configuration_snapshot(path).config;
1069
+ const profile = config.participants?.[name];
1070
+ if (!profile) throw new Error(`${name} 不由本机唤醒,项目权限由它自己的会话决定`);
1071
+ if (profile.project_access === 'own') throw new Error(`${name} 是手动接入的成员,权限沿用它自己会话的软件设置`);
1072
+ const facts = adapter_profile(profile.adapter);
1073
+ // A CLI's project access is set per run; an App follows its own settings and an API member only reads.
1074
+ if (!facts?.access_levels) throw new Error(!facts?.capabilities.project ? `${name} 没有本机文件工具,项目固定只读` : `${name} 的项目权限在 App 内设置`);
1075
+ if (!facts.access_levels.includes(project_access)) throw new Error(facts.unsupported_hints?.[project_access] || `${facts.label} 不支持此档位`);
1076
+ if (facts.own_project_when_bound && profile.session_id) throw new Error(`${name} 续接的是它自己的 ${facts.label} 对话,项目权限沿用该对话所在项目,请在原软件中设置`);
1077
+ if (project_access === 'write' && !(profile.cwd || config.cwd)) throw new Error('本房间没有指定项目目录,可写没有作用;请在新建房间时选择项目目录');
1078
+ const next = { ...config, participants: { ...config.participants, [name]: { ...profile, project_access } } };
1079
+ validate_config(next, dirname(path));
1080
+ atomic_json(path, next);
1081
+ return { room_id: input.room_id, member: name, project_access };
1082
+ } finally { release(); }
1083
+ }
1084
+
1085
+ /**
1086
+ * Change a woken CLI or API member's model and thinking effort after the room is created. Each run passes them to the
1087
+ * software, and neither is part of the member's session context, so the change applies from its next delivery and keeps
1088
+ * its session. An empty value goes back to the software's default; an API member has no default model, so an empty
1089
+ * model keeps its current one.
1090
+ */
1091
+ export async function room_member_model(home, raw) {
1092
+ const { input, path } = await member_room_context(home, raw);
1093
+ const { name } = input;
1094
+ const model = typeof input.model === 'string' ? input.model.trim() : '';
1095
+ const effort = typeof input.effort === 'string' ? input.effort.trim() : '';
1096
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1097
+ try {
1098
+ const config = configuration_snapshot(path).config;
1099
+ const profile = config.participants?.[name];
1100
+ if (!profile) throw new Error(`${name} 不由本机唤醒,模型由它自己的会话决定`);
1101
+ if (profile.project_access === 'own') throw new Error(`${name} 是手动接入的成员,模型与强度沿用它自己会话的设置`);
1102
+ const facts = adapter_profile(profile.adapter);
1103
+ // An App chooses its model and effort in its own window; a CLI or API member's run is started with them.
1104
+ if (!facts || facts.kind === 'app') throw new Error(`${name} 的模型在 ${facts?.label || '它的软件'} 内设置`);
1105
+ if (effort && !facts.efforts?.includes(effort)) {
1106
+ throw new Error(`${facts.label} 不支持思考强度 ${effort}${facts.efforts ? `,可选 ${facts.efforts.join(' / ')}` : ''}`);
1107
+ }
1108
+ const next = { ...profile, model: model || (facts.kind === 'api' ? profile.model : ''), effort };
1109
+ if (!next.model) delete next.model;
1110
+ if (!effort) delete next.effort;
1111
+ const updated = { ...config, participants: { ...config.participants, [name]: next } };
1112
+ validate_config(updated, dirname(path));
1113
+ atomic_json(path, updated);
1114
+ return { room_id: input.room_id, member: name, model: next.model || '', effort };
1115
+ } finally { release(); }
1116
+ }
1117
+
1118
+ const MAX_ALLOWED_TOOLS = 50;
1119
+
1120
+ /**
1121
+ * Allow operations a woken member's software refused, by adding the rules the runner reported with them to its
1122
+ * `allowed_tools`: Claude passes them to `--allowedTools`, agy adds them to its discussion project's grants. Like the
1123
+ * project access, they apply from the member's next delivery and keep its session.
1124
+ */
1125
+ export async function room_member_allow(home, raw) {
1126
+ const { input, path } = await member_room_context(home, raw);
1127
+ const { name, rules } = input;
1128
+ if (!Array.isArray(rules) || !rules.length || rules.some(rule => typeof rule !== 'string' || !rule.trim() || rule.length > 300)) {
1129
+ throw new Error('rules 须为要放行的规则列表');
1130
+ }
1131
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1132
+ try {
1133
+ const config = configuration_snapshot(path).config;
1134
+ const profile = config.participants?.[name];
1135
+ if (!profile) throw new Error(`${name} 不由本机唤醒,权限由它自己的会话决定`);
1136
+ const facts = adapter_profile(profile.adapter);
1137
+ if (!facts?.per_tool_allow) throw new Error(`${name} 的软件不支持逐条放行,请改用更高的权限档位`);
1138
+ if (facts.own_project_when_bound && profile.session_id) throw new Error(`${name} 续接的是它自己的 ${facts.label} 对话,权限沿用该对话所在项目,请在原软件中设置`);
1139
+ const allowed_tools = [...new Set([...(profile.allowed_tools || []), ...rules.map(rule => rule.trim())])];
1140
+ if (allowed_tools.length > MAX_ALLOWED_TOOLS) throw new Error(`每位成员最多放行 ${MAX_ALLOWED_TOOLS} 条规则`);
1141
+ const next = { ...config, participants: { ...config.participants, [name]: { ...profile, allowed_tools } } };
1142
+ validate_config(next, dirname(path));
1143
+ atomic_json(path, next);
1144
+ return { room_id: input.room_id, member: name, allowed_tools };
1145
+ } finally { release(); }
1146
+ }
1147
+
1148
+ /**
1149
+ * Switch an idle free-room Codex member between the App and the CLI, keeping its conversation: the App resumes the
1150
+ * bound chat by its session, and the CLI resumes it only after the App has released it. Model and effort are chosen
1151
+ * in the App, so switching to it drops them.
1152
+ */
1153
+ export async function room_member_adapter(home, raw) {
1154
+ const { input, path } = await member_room_context(home, raw);
1155
+ const { name, adapter } = input;
1156
+ if (!ADAPTER_IDS.some(other => same_session_family(other, adapter))) throw new Error('只能在共用会话的 App 与 CLI 接入之间切换');
1157
+ const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1158
+ const member = room.free.members.find(item => item.name === name);
1159
+ if (member?.pending > 0 || ['dispatched', 'started'].includes(member?.execution?.status)) throw new Error(`${name} 正在处理请求,请等它完成或先停止`);
1160
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1161
+ try {
1162
+ const config = configuration_snapshot(path).config;
1163
+ const profile = config.participants?.[name];
1164
+ if (profile?.adapter !== adapter && !same_session_family(profile?.adapter, adapter)) throw new Error(`${name} 不是本机唤醒、能切换到该接入方式的成员`);
1165
+ if (profile.adapter === adapter) return { room_id: input.room_id, member: name, adapter };
1166
+ const context = { config, path };
1167
+ const next = { ...profile };
1168
+ switch_codex_adapter(context, name, next, adapter);
1169
+ // An App chooses its own model and effort.
1170
+ if (!adapter_profile(adapter).models) delete next.model;
1171
+ if (!adapter_profile(adapter).efforts) delete next.effort;
1172
+ const updated = { ...config, participants: { ...config.participants, [name]: next } };
1173
+ validate_config(updated, dirname(path));
1174
+ atomic_json(path, updated);
1175
+ return { room_id: input.room_id, member: name, adapter };
1176
+ } finally { release(); }
1177
+ }
1178
+
1179
+ /**
1180
+ * Register a manual Claude, Codex or agy expert's own session as a hosted participant, so the service resumes it for later turns.
1181
+ * Returns the adapter used. Throws when the local software is not configured or the session is not found on this machine; the member then stays manual.
1182
+ */
1183
+ export function adopt_member_profile(home, path, name, session_id, client, member_token) {
1184
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1185
+ try {
1186
+ const config = configuration_snapshot(path).config;
1187
+ // The adapter whose store holds the session: a desktop chat is resumed through its App, others through the CLI.
1188
+ const adapter = adoption_adapter(client, session_id);
1189
+ if (!adapter) throw new Error(`${name}:本机不能接管 ${client} 的会话`);
1190
+ // An App conversation is reached through this room's own Sidecar, which the App starts as soon as it is configured.
1191
+ const sidecar = adapter_profile(adapter).location === 'ipc_directory' ? { ipc_directory: join(dirname(path), 'agy-app-sidecar') } : {};
1192
+ // A manually started member keeps its own session's permissions; the room's 只读 / 可写 does not apply to it.
1193
+ const input = { cwd: config.cwd, adopt: true, participants: { [name]: { adapter, session_id, project_access: 'own', ...sidecar } } };
1194
+ // Its model, effort, prompt and tools stay as the user set them in that session; machine defaults never override them.
1195
+ const { model, effort, allowed_tools, system_prompt, ...own } = participant_profile(name, launch_settings(home).participants, input, false);
1196
+ const profile = borrowed_session(name, own, config.cwd);
1197
+ if (sidecar.ipc_directory) setup_sidecar(sidecar);
1198
+ // A room delivers with each member's own credential; the browser-made one is not kept locally, so the owner issues a new one.
1199
+ const next = { ...config, participants: { ...config.participants, [name]: profile },
1200
+ members: { ...config.members, [name]: { token: member_token, pending: '' } } };
1201
+ validate_config(next, dirname(path));
1202
+ atomic_json(path, next);
1203
+ return adapter;
1204
+ } finally { release(); }
1205
+ }
1206
+
1207
+ /** The one registered configuration of a room on this machine, or null when it was never registered here. */
1208
+ function registered_room_path(home, site, room_id) {
1209
+ const paths = read_registry(home).filter(path => {
1210
+ const identity = registered_identity(path);
1211
+ return identity?.site === site && identity.room === room_id;
1212
+ });
1213
+ if (paths.length > 1) throw new Error('本房间存在多份登记配置,无法确定成员会话');
1214
+ return paths[0] || null;
1215
+ }
1216
+
1217
+ /** The session each participant actually resumes, read without writing to a runtime the service may be using. */
1218
+ function bound_sessions(config, path) {
1219
+ const file = join(resolve(config.data_directory || join(dirname(path), `discussion-${config.room}`)), 'runtime.sqlite3');
1220
+ if (!existsSync(file)) return {};
1221
+ const db = new DatabaseSync(file, { readOnly: true });
1222
+ try { return Object.fromEntries(db.prepare('SELECT participant,session_id FROM bindings').all().map(row => [row.participant, row.session_id])); }
1223
+ finally { db.close(); }
1224
+ }
1225
+
1226
+ /**
1227
+ * Export a room's local member software and the sessions they hold, so a backup imported on this machine resumes them.
1228
+ * Requires the owner's credential; member credentials and API keys are never included (only the key reference).
1229
+ * Returns `local_members: null` when the room is not registered here.
1230
+ */
1231
+ export async function room_profiles(home, raw) {
1232
+ const input = launch_input({ ...raw, entry: 'web' });
1233
+ if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('导出本机成员配置须提供房间编号和房间控制凭据');
1234
+ const path = registered_room_path(home, input.site, input.room_id);
1235
+ if (!path) return { room_id: input.room_id, local_members: null };
1236
+ const config = configuration_snapshot(path).config;
1237
+ await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
1238
+ const sessions = bound_sessions(config, path);
1239
+ const participants = Object.fromEntries(Object.entries(config.participants).map(([name, profile]) => {
1240
+ const kept = Object.fromEntries(Object.entries(profile).filter(([key]) => [...PROFILE_FIELDS, 'project_access'].includes(key)));
1241
+ const session_id = sessions[name] || profile.session_id;
1242
+ return [name, session_id ? { ...kept, session_id } : kept];
1243
+ }));
1244
+ return { room_id: input.room_id, local_members: { format: LOCAL_MEMBERS_FORMAT, version: 1, mode: 'free',
1245
+ cwd: config.cwd, discussion_project: config.discussion_project, project_access: config.project_access, scheduler: config.scheduler,
1246
+ workflow: config.workflow, participants } };
1247
+ }
1248
+
1249
+ /**
1250
+ * Register an imported free room on this machine with its exported member software, each member resuming its original session.
1251
+ * A session or software missing here fails that member instead of starting a new conversation. Claude Code members stay manual,
1252
+ * and are never taken over, because a background resume forks the session away from its original window.
1253
+ * Returns `{room_id, registered, members: [{name, status: resumed|manual|failed, session_id?, cwd?, error?}]}`.
1254
+ */
1255
+ export async function restore_room(home, raw) {
1256
+ const input = launch_input({ ...raw, entry: 'web' });
1257
+ const local = input.local_members;
1258
+ if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('恢复本机成员须提供房间编号和房间控制凭据');
1259
+ if (local?.format !== LOCAL_MEMBERS_FORMAT || local.version !== 1 || !local.participants || typeof local.participants !== 'object') throw new Error('本机成员配置格式无效');
1260
+ await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
1261
+ const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1262
+ if (registered_room_path(home, input.site, input.room_id)) throw new Error('本房间已在本机登记,不重复恢复');
1263
+ if (local.cwd && (!isAbsolute(local.cwd) || !existsSync(local.cwd) || !statSync(local.cwd).isDirectory())) throw new Error(`房间项目目录 ${local.cwd} 在本机不存在`);
1264
+ const keep_manual = room.free.members.filter(member => member.access === 'manual' && member.status !== 'removed'
1265
+ && platform_adapters(platform_of(member.name)).some(id => ADAPTER_PROFILES[id].restore_manual)).map(member => member.name);
1266
+ const participants = {}, members = [];
1267
+ for (const [name, exported] of Object.entries(local.participants)) {
1268
+ try {
1269
+ const profile = participant_profile(name, {}, { cwd: local.cwd, adopt: true, participants: { [name]: exported } }, false);
1270
+ // A member whose software cannot take over other conversations (an API member) resumes only its own session, and
1271
+ // only while this machine still has it; otherwise, like one without a session store, it starts fresh.
1272
+ const software = adapter_of(profile.adapter);
1273
+ if (!software?.session || (!software.adopt && !software.session.exists(profile.session_id))) delete profile.session_id;
1274
+ const resumed = profile.session_id && software.adopt ? borrowed_session(name, profile, local.cwd) : profile;
1275
+ if (adapter_profile(profile.adapter)?.restore_manual) {
1276
+ keep_manual.push(name);
1277
+ const cwd = resumed.cwd || local.cwd || '';
1278
+ const command = resumed.session_id && adapter_profile(profile.adapter).resume_command?.(resumed.session_id);
1279
+ members.push({ name, status: 'manual', session_id: resumed.session_id || '', cwd,
1280
+ resume: command ? { command, cwd } : null });
1281
+ } else {
1282
+ participants[name] = resumed;
1283
+ members.push({ name, status: 'resumed', session_id: resumed.session_id || '' });
1284
+ }
1285
+ } catch (error) { members.push({ name, status: 'failed', error: error.message }); }
1286
+ }
1287
+ if (!Object.keys(participants).length && !local.cwd && !local.scheduler) return { room_id: input.room_id, registered: false, members };
1288
+ register_copied_room(home, input, local, participants, keep_manual);
1289
+ return { room_id: input.room_id, registered: true, members };
1290
+ }
1291
+
1292
+ /**
1293
+ * Register an imported or forked free room's local members under a fresh launch directory; `seed` writes the new
1294
+ * runtime's bindings before the service can see the room. Returns the runtime directory.
1295
+ */
1296
+ function register_copied_room(home, input, local, participants, keep_manual, seed = () => {}) {
1297
+ const key = createHash('sha256').update(`${input.site}/${input.room_id}`).digest('hex');
1298
+ // A leftover directory of a deleted room with the same ID would carry its old bindings, so a restore never reuses one.
1299
+ const base = join(home, 'launches', key), directory = existsSync(base) ? `${base}-${Date.now()}` : base;
1300
+ // Members arrive away; these placeholders are replaced by the credential issued when the owner brings each one back.
1301
+ const config = { site: input.site, room: input.room_id, token: input.token, mode: 'free', participants, keep_manual, api_home: home,
1302
+ members: Object.fromEntries(Object.keys(participants).map(name => [name, { token: `${randomUUID()}${randomUUID()}`, pending: '' }])),
1303
+ scheduler: local.scheduler || undefined, cwd: local.cwd || undefined, discussion_project: local.discussion_project || undefined,
1304
+ project_access: local.project_access || undefined, workflow: local.workflow || undefined, data_directory: join(directory, 'runtime'), draft_directory: service_drafts(home, join(directory, 'runtime')) };
1305
+ validate_config(config, directory);
1306
+ mkdirSync(directory, { recursive: true });
1307
+ atomic_json(join(directory, 'config.json'), config);
1308
+ seed(config.data_directory);
1309
+ register_room(home, join(directory, 'config.json'));
1310
+ return config.data_directory;
1311
+ }
1312
+
1313
+ // Software whose session a fork branches; other local members start a new conversation in the forked room.
1314
+
1315
+ /**
1316
+ * Register a room forked from another on this machine: each local member continues from its own session as it stood
1317
+ * at the fork point, without the executions the fork leaves out. The source room's sessions are never changed.
1318
+ * Requires both rooms' owner credentials; members the new room keeps manual are not registered here.
1319
+ * Returns `{room_id, registered, members: [{name, status: forked|fresh|failed, error?}]}`.
1320
+ */
1321
+ export async function fork_room(home, raw) {
1322
+ const input = launch_input({ ...raw, entry: 'web' });
1323
+ if (!input.room_id || typeof input.token !== 'string' || !input.token.trim() || typeof raw.source_room_id !== 'string' || typeof raw.source_token !== 'string') {
1324
+ throw new Error('分支须提供新房间与原房间的编号和控制凭据');
1325
+ }
1326
+ const local = (await room_profiles(home, { site: input.site, room_id: raw.source_room_id, token: raw.source_token })).local_members;
1327
+ if (!local) return { room_id: input.room_id, registered: false, members: [] };
1328
+ await site_request(input.site, `/api/rooms/${input.room_id}/inbox`, input.token);
1329
+ const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1330
+ if (registered_room_path(home, input.site, input.room_id)) throw new Error('分支房间已在本机登记');
1331
+ const runners = new Set(room.free.members.filter(member => member.access === 'runner' && member.status !== 'removed').map(member => member.name));
1332
+ const left_out = raw.executions && typeof raw.executions === 'object' ? raw.executions : {};
1333
+ const participants = {}, members = [], bindings = {}, forks = {};
1334
+ for (const [name, exported] of Object.entries(local.participants)) {
1335
+ if (!runners.has(name)) continue;
1336
+ try {
1337
+ const profile = participant_profile(name, {}, { cwd: local.cwd, adopt: true, participants: { [name]: exported } }, false);
1338
+ if (!profile.session_id || !BRANCHABLE_ADAPTERS.includes(profile.adapter)) {
1339
+ delete profile.session_id;
1340
+ participants[name] = profile;
1341
+ members.push({ name, status: 'fresh' });
1342
+ continue;
1343
+ }
1344
+ // Claude resumes a session only in its original directory, so the forked member works there too.
1345
+ const located = adapter_profile(profile.adapter)?.adopt === 'own_cwd' ? borrowed_session(name, profile, local.cwd) : profile;
1346
+ const branch = await branch_session(located, profile.session_id, (left_out[name] || []).filter(Number.isInteger), { always: true });
1347
+ const { session_id, ...forked } = located;
1348
+ participants[name] = forked;
1349
+ bindings[name] = branch.session_id;
1350
+ if (branch.fork) forks[name] = branch.fork;
1351
+ members.push({ name, status: branch.session_id ? 'forked' : 'fresh' });
1352
+ } catch (error) { members.push({ name, status: 'failed', error: error.message }); }
1353
+ }
1354
+ if (!Object.keys(participants).length && !local.cwd && !local.scheduler) return { room_id: input.room_id, registered: false, members };
1355
+ register_copied_room(home, input, local, participants, [], data_directory => {
1356
+ const store = new DiscussionStore(data_directory);
1357
+ try {
1358
+ for (const [name, session_id] of Object.entries(bindings)) store.bind(name, session_id);
1359
+ // A Claude fork happens on the member's next turn; the runner keeps it pending until that session exists.
1360
+ for (const [name, fork] of Object.entries(forks)) store.db.prepare('INSERT INTO metadata VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value')
1361
+ .run(`session-fork:${name}`, JSON.stringify(fork));
1362
+ } finally { store.close(); }
1363
+ });
1364
+ return { room_id: input.room_id, registered: true, members };
1365
+ }
1366
+
1367
+ /** Stable signatures make changed retry requests explicit without putting credentials in receipts. */
1368
+ function signature(value) {
1369
+ if (Array.isArray(value)) return `[${value.map(signature).join(',')}]`;
1370
+ if (value && typeof value === 'object') return `{${Object.keys(value).sort().filter(key => value[key] !== undefined).map(key => `${JSON.stringify(key)}:${signature(value[key])}`).join(',')}}`;
1371
+ return JSON.stringify(value);
1372
+ }
1373
+
1374
+ /** Inherit the topic duration unless overridden; zero leaves the run without a time limit. */
1375
+ function launch_minutes(input, room) {
1376
+ const minutes = Number(input.minutes ?? room.limits?.max_minutes ?? 0);
1377
+ if (!Number.isFinite(minutes) || minutes < 0 || minutes > MAX_MINUTES) throw new Error('讨论总时长或 minutes 须在 [0,1440],0 表示不限时长');
1378
+ return minutes;
1379
+ }
1380
+
1381
+ /** Refuse a second registry owner before changing the website runtime. */
1382
+ function check_registration(home, config, path) {
1383
+ for (const registered of read_registry(home)) {
1384
+ if (resolve(registered) === path || !existsSync(registered)) continue;
1385
+ const other = registered_identity(registered);
1386
+ if (other?.site === config.site && other.room === config.room) throw new Error('房间已使用另一份接入配置登记;请沿用原配置,不重复接入');
1387
+ }
1388
+ }
1389
+
1390
+ /** Start a session once, reconciling a lost response from the durable start intent. */
1391
+ async function start_session(config, record, persist, room, minutes) {
1392
+ const state = await api(config, '/discussion');
1393
+ if (record.session_id && state.session?.id === record.session_id && !record.start_pending) {
1394
+ if (record.start_submission_id && state.session.start_submission_id !== record.start_submission_id) {
1395
+ throw new Error('房间当前讨论的启动编号与本次记录不同');
1396
+ }
1397
+ if (state.session.status !== 'active') throw new Error('讨论已暂停或结束;请在房间核对状态后再操作');
1398
+ return state.session;
1399
+ }
1400
+ if (record.session_id && state.session?.id !== record.session_id) throw new Error('房间当前讨论与本次启动记录不同');
1401
+ if (state.session && !record.start_pending) {
1402
+ if (state.session.status !== 'active') throw new Error('讨论已暂停或结束;请在房间核对状态后再操作');
1403
+ throw new Error('房间已有进行中的讨论;请沿用原启动记录');
1404
+ }
1405
+ if (room.session?.status === 'concluded' && !record.start_pending) throw new Error('房间中的讨论已结束;请从房间明确开启新讨论');
1406
+ if (!record.start_submission_id) record.start_submission_id = randomUUID();
1407
+ if (!record.start_request) {
1408
+ if (record.start_revision && record.start_revision !== state.revision) throw new Error('开启期间讨论状态已变化,请重新读取房间状态');
1409
+ const topic_minutes = Number(room.limits?.max_minutes || 0);
1410
+ const session_minutes = topic_minutes > 0 ? (minutes > 0 ? Math.min(topic_minutes, minutes) : topic_minutes) : minutes;
1411
+ record.start_revision = state.revision;
1412
+ record.start_request = { action: 'start', revision: state.revision, submission_id: record.start_submission_id,
1413
+ goal: room.goal || room.title, named_followup: Boolean(room.named_followup),
1414
+ limits: { max_rounds: room.limits?.max_rounds ?? 0, max_minutes: session_minutes,
1415
+ execution_minutes: room.limits?.execution_minutes ?? 0 } };
1416
+ record.start_pending = true;
1417
+ persist();
1418
+ }
1419
+ const result = await api(config, '/discussion', record.start_request);
1420
+ if (!result.session || result.session.start_submission_id !== record.start_submission_id) throw new Error('网站返回的讨论会话与本次启动编号不符');
1421
+ record.session_id = result.session.id;
1422
+ record.start_pending = false;
1423
+ persist();
1424
+ if (result.session.status !== 'active') throw new Error('本次讨论已暂停或结束;请在房间核对状态后再操作');
1425
+ return result.session;
1426
+ }
1427
+
1428
+ /** Reserve the first host task for the calling conversation without sending it a duplicate prompt. */
1429
+ async function current_host_task(config, record, persist, room) {
1430
+ if (record.current_task) return record.current_task;
1431
+ const discussion = await api(config, '/discussion');
1432
+ if (discussion.session?.status !== 'active' || discussion.session.id !== record.session_id) throw new Error('本次讨论会话已暂停、结束或变化;请核对原房间');
1433
+ const page = await api(config, '/inbox');
1434
+ const member = page.members.find(item => item.name === room.host && item.role === 'host');
1435
+ const request = member?.pending.find(item => item.purpose === 'discuss_host' && item.session_id === record.session_id);
1436
+ if (!member || (!request && !record.execution_client_id && !record.execution_id)) throw new Error('没有可由当前会话接手的主持请求;请核对原房间');
1437
+ record.execution_client_id ||= randomUUID();
1438
+ persist();
1439
+ const execution = record.execution_id ? await api(config, `/executions/${record.execution_id}`)
1440
+ : await api(config, '/executions', { member_id: member.id, client_id: record.execution_client_id, cwd: '' });
1441
+ if (!['dispatched', 'started'].includes(execution.status)) throw new Error('主持请求已不再等待执行;请核对原房间');
1442
+ if (!execution.requests?.some(item => item.purpose === 'discuss_host' && item.session_id === record.session_id)) {
1443
+ throw new Error('预约到的执行不属于本次讨论主持请求');
1444
+ }
1445
+ record.execution_id = execution.id;
1446
+ persist();
1447
+ const store = new DiscussionStore(config.directory);
1448
+ try {
1449
+ store.context(config);
1450
+ store.scope(config);
1451
+ const session_id = config.participants[room.host].session_id;
1452
+ store.bind(room.host, session_id);
1453
+ const task = free_task_files(config, member, execution, { session_id }, { session: discussion.session, process_access: false });
1454
+ new FreeRoomRunner(config, store).save(room.host, { client_id: record.execution_client_id, execution_id: execution.id,
1455
+ status: 'running', attempts: 0, started: Date.now(), last_renew: Date.now() });
1456
+ record.current_task = { execution_id: execution.id, access_file: task.access_path, task_file: join(config.directory, `${task.id}.task.json`) };
1457
+ persist();
1458
+ return record.current_task;
1459
+ } finally { store.close(); }
1460
+ }
1461
+
1462
+ /** Return launch evidence and paths, never raw control or execution tokens. */
1463
+ async function launch_receipt(config, record, config_path) {
1464
+ const room = await api(config, '');
1465
+ const discussion = record.session_id ? await api(config, '/discussion') : null;
1466
+ return { entry: record.entry, room, url: `${config.site}/?room=${config.room}`, config_path,
1467
+ status: discussion?.session?.status || (record.session_id ? 'concluded' : 'free'), current_task: record.current_task || null };
1468
+ }
1469
+
1470
+ /** Read a saved launch without creating state during validation or preview. */
1471
+ function read_launch(directory) {
1472
+ const path = join(directory, 'launch.json');
1473
+ return existsSync(path) ? JSON.parse(readFileSync(path, 'utf8')) : null;
1474
+ }
1475
+
1476
+ /** Find the registered room only after proving the caller's original control credential. */
1477
+ async function room_config_context(home, raw, options = {}) {
1478
+ const input = launch_input({ ...raw, entry: 'web' });
1479
+ if (!input.room_id || typeof input.token !== 'string' || !input.token.trim()) throw new Error('读取本场配置须提供房间编号和原控制凭据');
1480
+ const room = options.local_guard ? { id: input.room_id, archived: false }
1481
+ : await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1482
+ const config = { site: input.site, room: input.room_id, token: input.token };
1483
+ if (!options.local_guard) await verify_control(config, room);
1484
+ const discussion = options.local_guard
1485
+ ? { session: { status: 'paused' }, revision: raw.session_revision ?? raw.runtime_revision }
1486
+ : await api(config, '/discussion');
1487
+ if (room.archived || discussion.session?.status !== 'paused') throw new Error('请先暂停本场讨论,再修正软件路径');
1488
+ const paths = read_registry(home).filter(path => {
1489
+ const identity = registered_identity(path);
1490
+ return identity?.site === input.site && identity.room === input.room_id;
1491
+ });
1492
+ if (paths.length !== 1) throw new Error('未找到本场唯一的已登记配置,请核对原接入服务');
1493
+ const path = paths[0];
1494
+ const journal = read_launch(dirname(path));
1495
+ if (journal && !journal.finished) throw new Error('本次启动尚未完成,请先核对原启动待办');
1496
+ return { input, room, discussion, path, ...configuration_snapshot(path) };
1497
+ }
1498
+
1499
+ /** Expose only editable connection paths, never credentials or unrelated room settings. */
1500
+ function connection_view(context) {
1501
+ return { room_id: context.room.id, session_revision: context.discussion.revision, runtime_revision: context.discussion.revision, version: context.version,
1502
+ participants: Object.fromEntries(Object.entries(context.config.participants).map(([name, profile]) =>
1503
+ [name, Object.fromEntries(['adapter', ...CONNECTION_FIELDS].filter(field => profile[field] !== undefined).map(field => [field, profile[field]]))])) };
1504
+ }
1505
+
1506
+ /** Switch only Codex's execution entrypoint, keeping its actual original conversation. */
1507
+ function switch_codex_adapter(context, name, profile, adapter) {
1508
+ if (!same_session_family(profile.adapter, adapter)) throw new Error('本场仅支持共用会话的 App / CLI 接入之间切换');
1509
+ const current = validate_config(context.config, dirname(context.path));
1510
+ let session = profile.session_id;
1511
+ if (existsSync(join(current.directory, 'runtime.sqlite3'))) {
1512
+ const store = new DiscussionStore(current.directory);
1513
+ try {
1514
+ const binding = store.binding(name).session_id;
1515
+ if (session && binding && session !== binding) throw new Error('原会话绑定不一致,请先核对原会话');
1516
+ session = binding || session;
1517
+ } finally { store.close(); }
1518
+ }
1519
+ if (!session) throw new Error('尚无实际 Codex 会话,不能切换;请先完成首次接入');
1520
+ profile.adapter = adapter;
1521
+ profile.session_id = session;
1522
+ }
1523
+
1524
+ /** Validate paused-room paths and Codex entrypoints without replacing the discussion or session. */
1525
+ function corrected_configuration(context) {
1526
+ const config = structuredClone(context.config);
1527
+ for (const [name, patch] of Object.entries(context.input.participants)) {
1528
+ const profile = config.participants[name];
1529
+ const field = adapter_profile(profile?.adapter)?.location || 'executable';
1530
+ const fields = ADAPTER_IDS.some(other => same_session_family(other, profile?.adapter)) ? [field, 'adapter'] : [field];
1531
+ if (!profile || !patch || typeof patch !== 'object' || Array.isArray(patch) || Object.keys(patch).some(key => !fields.includes(key))) throw new Error('本场修正仅支持软件路径、Sidecar 目录及 Codex App / CLI;参与者、项目及会话保持不变');
1532
+ validate_profile(name, patch);
1533
+ if (patch.adapter && patch.adapter !== profile.adapter) switch_codex_adapter(context, name, profile, patch.adapter);
1534
+ const path = patch[field] ?? profile[field];
1535
+ if (typeof path !== 'string' || !path || !existsSync(path)
1536
+ || (field === 'executable' ? !statSync(path).isFile() || (process.platform === 'win32' && !/\.exe$/i.test(path)) : !statSync(path).isDirectory())) throw new Error(`${name}:请提供有效的软件文件或连接目录`);
1537
+ profile[field] = path;
1538
+ }
1539
+ validate_config(config, dirname(context.path));
1540
+ return config;
1541
+ }
1542
+
1543
+ /** Wait for the resident worker to read this version before suggesting a manual restart. */
1544
+ async function configuration_applied(home, path, version) {
1545
+ for (let waited = 0; waited < CONFIG_APPLY_TIMEOUT_MS; waited += CONFIG_APPLY_POLL_MS) {
1546
+ const pid = service_pid(home);
1547
+ if (!pid) return false;
1548
+ const status_path = join(home, 'status.json');
1549
+ const status = existsSync(status_path) ? JSON.parse(readFileSync(status_path, 'utf8')) : {};
1550
+ const worker = status.rooms?.find(item => resolve(item.config) === resolve(path));
1551
+ if (status.pid === pid && worker?.config_version === version && worker.status !== 'error') return true;
1552
+ await sleep(CONFIG_APPLY_POLL_MS);
1553
+ }
1554
+ return false;
1555
+ }
1556
+
1557
+ /** Read or save a paused room's connection paths without changing its runtime or global defaults. */
1558
+ export async function room_configuration(home, raw, options = {}) {
1559
+ let context = await room_config_context(home, raw, options);
1560
+ if (raw.participants !== undefined && !options.local_guard) {
1561
+ const saved = await save_room_connection(raw);
1562
+ return { ...saved, applied: await configuration_applied(home, context.path, saved.version) };
1563
+ }
1564
+ if (raw.participants === undefined) return connection_view(context);
1565
+ if (!raw.participants || typeof raw.participants !== 'object' || Array.isArray(raw.participants)) throw new Error('participants 须为本场软件路径对象');
1566
+ const release = acquire_lock(join(dirname(context.path), 'configuration-edit'));
1567
+ try {
1568
+ context = await room_config_context(home, raw, options);
1569
+ const config = corrected_configuration(context);
1570
+ if (raw.version !== context.version || (raw.session_revision ?? raw.runtime_revision) !== context.discussion.revision) throw new Error('房间状态或配置已变化,请重新读取本场配置后核对');
1571
+ atomic_json(context.path, config);
1572
+ const saved = { ...context, ...configuration_snapshot(context.path) };
1573
+ // The local website holds its database write lock here; the worker can acknowledge only after that lock is released.
1574
+ return { ...connection_view(saved), applied: false };
1575
+ } finally { release(); }
1576
+ }
1577
+
1578
+ /** Serialize file replacement with runtime changes through the local website's database guard. */
1579
+ async function save_room_connection(raw) {
1580
+ const input = launch_input({ ...raw, entry: 'web' });
1581
+ const url = new URL(input.site);
1582
+ if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(url.hostname)) throw new Error('本场路径修正须通过已启用本机启动的回环网站');
1583
+ const response = await fetch(`${input.site}/api/local/room-config`, { method: 'POST',
1584
+ headers: { 'Content-Type': 'application/json', 'X-CoDiscuss-Local': '1' },
1585
+ body: JSON.stringify(input), redirect: 'error', signal: AbortSignal.timeout(15000) });
1586
+ const result = await response.json();
1587
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${result.error || '本场配置保存失败'}`);
1588
+ return result;
1589
+ }
1590
+
1591
+ /** Prove dispatcher access before a protected room is started or a corrected credential is saved. */
1592
+ async function verify_control(config, room) {
1593
+ await api({ ...config, room: room.id }, '/inbox');
1594
+ }
1595
+
1596
+ /** Pin resolved defaults, while comparing retries against only the caller's explicit request. */
1597
+ async function prepare_launch(home, input, directory, options = {}) {
1598
+ const previous = read_launch(directory);
1599
+ if (options.browser_request && (typeof input.token !== 'string' || !input.token.trim())) throw new Error('网页启动须携带本次原始控制凭据,不能认领其他启动记录');
1600
+ const { token: ignored_token, access_file: ignored_access, ...request } = input;
1601
+ const request_signature = signature(request);
1602
+ if (previous?.request_signature && previous.request_signature !== request_signature) throw new Error('启动配置与原请求不同;同一次重试须沿用原配置,新讨论请使用新提交编号');
1603
+ const config_path = join(directory, 'config.json');
1604
+ const saved = previous?.config || (previous && existsSync(config_path) ? JSON.parse(readFileSync(config_path, 'utf8')) : null);
1605
+ const token = input.token || previous?.token || randomUUID();
1606
+ const room_id = input.room_id || previous?.room_id || (saved?.room !== 'preview' ? saved?.room : null);
1607
+ if (options.browser_request && previous && token !== previous.token && !room_id) throw new Error('尚未确认原房间,不能替换本次控制凭据');
1608
+ const room = room_id ? await site_request(input.site, `/api/rooms/${room_id}`, token) : input.room;
1609
+ const config = previous?.request_signature ? { ...structuredClone(saved), token }
1610
+ : launch_config(home, input, room, directory, { token, defaults: saved?.participants, members: saved?.members });
1611
+ config.draft_directory = service_drafts(home, config.directory);
1612
+ if (previous?.request_signature && !previous.finished) validate_config(config, directory);
1613
+ const minutes = previous?.minutes ?? launch_minutes(input, room);
1614
+ const draft = signature({ entry: input.entry, room_id: input.room_id, room: input.room, participants: config.participants, cwd: input.cwd, discussion_project: input.discussion_project, minutes });
1615
+ if (room.id) await verify_control(config, room);
1616
+ return { input, config, room, minutes, draft, request_signature, directory, previous };
1617
+ }
1618
+
1619
+ /** Launch a room through either entry, using a durable journal for safe retries. */
1620
+ export async function launch_discussion(home, raw, options = {}) {
1621
+ assert_shared_home(home);
1622
+ const input = launch_input(raw);
1623
+ // A room created from the page without a project works in its own folder of the draft space, which is then its project.
1624
+ if (!input.room_id && !input.cwd && input.entry === 'web' && !options.dry_run) input.cwd = draft_folder(home, input.room.title, input.room.submission_id);
1625
+ const key = createHash('sha256').update(`${input.site}/${input.room_id || input.room.submission_id}`).digest('hex');
1626
+ const directory = join(home, 'launches', key);
1627
+ let release;
1628
+ try {
1629
+ const preview = await prepare_launch(home, input, directory, options);
1630
+ if (options.dry_run) return { dry_run: true, entry: input.entry, site: input.site, room_id: input.room_id || null,
1631
+ host: preview.room.host, participants: preview.config.participants, cwd: preview.config.cwd || null,
1632
+ discussion_project: preview.config.discussion_project || null, minutes: preview.minutes };
1633
+ release = acquire_lock(directory);
1634
+ return await perform_launch(home, await prepare_launch(home, input, directory, options), options);
1635
+ } catch (error) {
1636
+ error.launch ||= { stage: existsSync(join(directory, 'launch.json')) ? 'unconfirmed' : 'not_started' };
1637
+ throw error;
1638
+ } finally { release?.(); }
1639
+ }
1640
+
1641
+ /** Persist preparation before writes, hand off the current host when needed, then register once. */
1642
+ async function perform_launch(home, context, options) {
1643
+ const { input, config, minutes, draft, request_signature, directory, previous } = context;
1644
+ // This is the creation input's start-discussion choice, not the persisted room model (always free).
1645
+ const discussion = previous?.discussion ?? (input.room ? input.room.mode !== 'free' : Boolean(context.room.session && context.room.session.status !== 'concluded'));
1646
+ const record = previous || { token: config.token, signature: draft, request_signature, config, minutes, entry: input.entry, discussion };
1647
+ record.discussion = discussion;
1648
+ const persist = () => atomic_json(join(directory, 'launch.json'), record);
1649
+ if (!previous) persist();
1650
+ const progress = { stage: 'unconfirmed' };
1651
+ try {
1652
+ let room = context.room;
1653
+ if (!input.room_id) room = await site_request(input.site, '/api/rooms', config.token, {
1654
+ ...input.room,
1655
+ members: card_order(input.room.members, [...Object.keys(config.participants).map(name => ({ name, adapter: config.participants[name].adapter,
1656
+ token: config.members[name].token, access: 'runner', session_mode: config.participants[name].session_id ? 'borrowed' : 'new' })),
1657
+ // Manual members keep the credentials the browser generated; nothing local is configured for them.
1658
+ ...(input.room.members || []).filter(member => record.discussion ? member?.access === 'manual' : !woken_member(member))
1659
+ .map(({ name, token, access }) => ({ name, token, access, adapter: '', session_mode: 'new' }))]),
1660
+ });
1661
+ config.room = room.id;
1662
+ await verify_control(config, room);
1663
+ Object.assign(progress, { stage: 'created', room_id: room.id });
1664
+ Object.assign(record, { token: config.token, request_signature, config, minutes, room_id: room.id });
1665
+ persist();
1666
+ const config_path = join(directory, 'config.json');
1667
+ check_registration(home, config, config_path);
1668
+ if (record.finished) {
1669
+ const saved = existsSync(config_path) ? JSON.parse(readFileSync(config_path, 'utf8')) : config;
1670
+ if (saved.token !== config.token || !existsSync(config_path)) atomic_json(config_path, { ...saved, token: config.token });
1671
+ return launch_receipt(config, record, config_path);
1672
+ }
1673
+ atomic_json(config_path, config);
1674
+ const service = await (options.start_service || start_service)(home);
1675
+ if (!service?.running) throw new Error('讨论服务未就绪,未开始本次讨论');
1676
+ if (record.discussion) await start_session(config, record, persist, room, minutes);
1677
+ progress.stage = 'started';
1678
+ if (record.discussion && input.entry === 'conversation') record.current_task = await current_host_task(config, record, persist, room);
1679
+ register_room(home, config_path);
1680
+ record.finished = true;
1681
+ persist();
1682
+ return launch_receipt(config, record, config_path);
1683
+ } catch (error) { error.launch = progress; throw error; }
1684
+ }
1685
+
1686
+ /** The workflow library: list, read, save, rename, disable or enable, delete, preview an import, or read a room's member cards. */
1687
+ export function workflows_command(home, input = {}) {
1688
+ const action = input.action || 'list';
1689
+ if (action === 'list') return workflow_library(home);
1690
+ if (action === 'get') return get_workflow(home, input.id);
1691
+ if (action === 'save') return save_workflow(home, input.workflow, validate_preset);
1692
+ if (action === 'delete') return delete_workflow(home, input.id);
1693
+ if (action === 'rename') return rename_workflow(home, input.id, input.label);
1694
+ if (action === 'disable' || action === 'enable') return set_workflow_disabled(home, input.id, action === 'disable');
1695
+ if (action === 'preview') {
1696
+ return preview_workflow(input, validate_preset, name => card_platform_ready(home, name));
1697
+ }
1698
+ if (action === 'room-cards') return room_cards(home, input);
1699
+ throw new Error('action 须为 list、get、save、rename、disable、enable、delete、preview 或 room-cards');
1700
+ }
1701
+
1702
+ /** Cards made from a registered room's members as configured here, prompts verbatim; no credential or path is returned. */
1703
+ async function room_cards(home, raw) {
1704
+ const input = launch_input({ ...raw, entry: 'web' });
1705
+ if (!input.room_id) throw new Error('读取成员卡片须提供 room_id');
1706
+ const path = registered_room_path(home, input.site, input.room_id);
1707
+ if (!path) throw new Error('本机没有登记这个房间');
1708
+ const config = configuration_snapshot(path).config;
1709
+ const room = await api(config, ''), taken = new Set();
1710
+ const members = new Set((room.free?.members || []).filter(member => member.status !== 'removed').map(member => member.name));
1711
+ return { cards: Object.entries(config.participants || {}).filter(([name]) => members.has(name)).map(([name, profile]) => {
1712
+ const suffix = (name.split('-')[1] || platform_of(name)).toLowerCase();
1713
+ let card = suffix.slice(0, 16);
1714
+ for (let number = 2; taken.has(card.toLowerCase()); number++) card = `${suffix.slice(0, 16 - String(number).length)}${number}`;
1715
+ taken.add(card.toLowerCase());
1716
+ // A card names its member platform-card; the room member it came from may have another suffix.
1717
+ return { card, name: `${platform_of(name)}-${card}`, label: room.labels?.[name] || '', description: room.descriptions?.[name] || '',
1718
+ ...Object.fromEntries(['system_prompt', 'project_access', 'model', 'effort']
1719
+ .filter(field => profile[field] && profile[field] !== 'own').map(field => [field, profile[field]])) };
1720
+ }) };
1721
+ }
1722
+
1723
+ /**
1724
+ * Bind a room's workflow, or end and resume it with the members it brought. Members are invited or brought back by the
1725
+ * usual member commands first; enabling only records which card each member plays, and a different workflow replaces
1726
+ * the binding (its members stay as ordinary members). `away` (and the older `disable`) sends its members away and ends
1727
+ * it, keeping who played which card; `back` brings them back to their sessions and resumes it. `sync` refreshes it
1728
+ * after a library edit (see refresh_room_workflow).
1729
+ */
1730
+ export async function room_workflow(home, raw) {
1731
+ if (raw?.action === 'sync') return refresh_room_workflow(home, raw);
1732
+ const { input, path } = await member_room_context(home, raw);
1733
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1734
+ try {
1735
+ const config = configuration_snapshot(path).config;
1736
+ if (input.action === 'host') {
1737
+ // The owner's per-room grant that lets the host save and enable workflows by itself (workflow-adopt).
1738
+ const next = { ...config, host_workflows: input.allowed === true || undefined };
1739
+ atomic_json(path, next);
1740
+ return { room_id: input.room_id, host_workflows: Boolean(next.host_workflows) };
1741
+ }
1742
+ if (input.action === 'enable') {
1743
+ get_workflow(home, input.workflow?.id);
1744
+ assert_workflow_enabled(home, input.workflow.id);
1745
+ const next = bind_room_workflow(config, { ...input.workflow, enabled: true });
1746
+ validate_config({ ...next, api_home: home }, dirname(path));
1747
+ atomic_json(path, next);
1748
+ return { room_id: input.room_id, workflow: room_workflow_status(next, home) };
1749
+ }
1750
+ if (!['away', 'back', 'disable'].includes(input.action)) throw new Error('action 须为 enable、sync、away、back、disable 或 host');
1751
+ if (!config.workflow?.id) throw new Error('本房间没有工作流');
1752
+ const room = await site_request(input.site, `/api/rooms/${input.room_id}`, input.token);
1753
+ const names = new Set(Object.values(config.workflow.members || {}));
1754
+ const members = room.free.members.filter(item => names.has(item.name) && item.role !== 'host');
1755
+ if (input.action === 'back') {
1756
+ // Each comes back to its own session; a removed member stays removed.
1757
+ for (const member of members.filter(item => item.status === 'away')) await room_member(home, { ...raw, action: 'rejoin', name: member.name }, true);
1758
+ } else {
1759
+ for (const member of members.filter(item => item.status === 'active')) {
1760
+ await site_request(input.site, `/api/rooms/${input.room_id}/members/${member.id}`, input.token, { action: 'away' });
1761
+ }
1762
+ }
1763
+ // Sending its members away ends the workflow; bringing them back resumes it.
1764
+ const next = { ...config, workflow: { ...config.workflow, enabled: input.action === 'back' } };
1765
+ atomic_json(path, next);
1766
+ return { room_id: input.room_id, workflow: room_workflow_status(next, home) };
1767
+ } finally { release(); }
1768
+ }
1769
+
1770
+ // The most a host-made card may ask for; anything above writing is lowered to it.
1771
+ const HOST_CARD_ACCESS = ['read', 'write'];
1772
+
1773
+ /**
1774
+ * The registered room whose present host holds this task's access file.
1775
+ * Returns its configuration path, configuration and the site's member list; throws for anyone else.
1776
+ */
1777
+ async function host_room(home, access_file) {
1778
+ if (!access_file) throw new Error('凭据用 --access-file 或 DISCUSS_ACCESS_FILE');
1779
+ const access = JSON.parse(readFileSync(resolve(access_file), 'utf8').replace(/^/, ''));
1780
+ const path = registered_room_path(home, String(access.site || '').replace(/\/$/, ''), access.room);
1781
+ if (!path) throw new Error('本机没有登记这个房间');
1782
+ const config = configuration_snapshot(path).config;
1783
+ const host = Object.keys(config.members || {}).find(name => config.members[name].token === access.token);
1784
+ const room = await api(config, '');
1785
+ const roster = room.free?.members || [];
1786
+ if (!host || !roster.some(member => member.name === host && member.role === 'host' && member.status === 'active')) throw new Error('只有本房间的主持人能运行此命令');
1787
+ return { path, config, roster, labels: room.labels || {}, host };
1788
+ }
1789
+
1790
+ const IMAGE_ACTIONS = { generate: 'generate_image', edit: 'edit_image' };
1791
+
1792
+ /**
1793
+ * One drawing by a member, with its task credential: `{action: generate|edit, ...the image tool's arguments}` (the same
1794
+ * arguments an API member's generate_image / edit_image take). Allowed only while the room's owner has drawing on and
1795
+ * this computer has an image service. The images become the member's attachments, which it posts with
1796
+ * `message post --attachment ID`; project files are read and written under the member's own project access.
1797
+ */
1798
+ export async function draw_image(home, { access_file, request }) {
1799
+ if (!access_file) throw new Error('凭据用 --access-file 或 DISCUSS_ACCESS_FILE');
1800
+ const access = JSON.parse(readFileSync(resolve(access_file), 'utf8').replace(/^/, ''));
1801
+ const path = registered_room_path(home, String(access.site || '').replace(/\/$/, ''), access.room);
1802
+ if (!path) throw new Error('本机没有登记这个房间');
1803
+ const config = configuration_snapshot(path).config;
1804
+ const member = Object.keys(config.members || {}).find(name => config.members[name].token === access.token);
1805
+ if (!member) throw new Error('凭据不属于本房间的成员');
1806
+ if (!config.image_generation) throw new Error('本房间没有添加生图服务,请房主在“成员与设置 → 协作设置”的“生图”中添加');
1807
+ const image = room_image(home, config);
1808
+ if (!image) throw new Error('这台电脑的生图服务还没有填写密钥(房间“生图”卡片的设置)');
1809
+ const { action, ...args } = request || {};
1810
+ if (!IMAGE_ACTIONS[action]) throw new Error('action 须为 generate 或 edit');
1811
+ const profile = config.participants?.[member] || {};
1812
+ const project = open_project({ cwd: profile.cwd ?? config.cwd, project_access: profile.project_access === 'read' ? 'read' : 'write',
1813
+ extra_directories: config.extra_directories || [] }, [home, dirname(path)]);
1814
+ const context = { home, image, site: config.site, room: config.room, token: access.token, participant: member, directory: dirname(path),
1815
+ project, signal: new AbortController().signal, generated_attachments: [] };
1816
+ const result = await run_image_tool(context, IMAGE_ACTIONS[action], args);
1817
+ if (result.error) throw new Error(result.error);
1818
+ return { ...result, note: '图片已存为你的附件;回答时用 message post --attachment 附件ID 附上(可重复,最多 10 个)' };
1819
+ }
1820
+
1821
+ /**
1822
+ * The API settings a program-started card on a platform without local software starts from, as the invite form fills
1823
+ * them: the platform's official API with the key last saved here for that root. Null when the platform has saved
1824
+ * software settings or local software, or no key is saved.
1825
+ */
1826
+ function card_api_profile(home, platform) {
1827
+ if (launch_settings(home).participants[platform] || platform_adapters(platform).some(id => adapter_profile(id).kind !== 'api')) return null;
1828
+ const provider = API_PROVIDERS[platform];
1829
+ const api_key_ref = provider && saved_api_keys(home)[provider.base_url];
1830
+ return api_key_ref ? { adapter: 'api', base_url: provider.base_url, api_protocol: provider.api_protocol, model: provider.models[0], api_key_ref } : null;
1831
+ }
1832
+
1833
+ /** The platforms a card may name on this computer: saved software settings, or an API with a saved key. */
1834
+ function configured_platforms(home) {
1835
+ return [...new Set([...Object.keys(launch_settings(home).participants), ...Object.keys(API_PROVIDERS).filter(platform => card_api_profile(home, platform))])];
1836
+ }
1837
+
1838
+ /** The library as listed: each workflow with the cards this computer cannot start, and the platforms cards may name here. */
1839
+ function workflow_library(home) {
1840
+ return { workflows: list_workflows(home, name => card_platform_ready(home, name)), platforms: configured_platforms(home) };
1841
+ }
1842
+
1843
+ /** Whether a card's platform can start here: saved software settings, or an API with a saved key. */
1844
+ function card_platform_ready(home, name) {
1845
+ const platform = platform_of(name || '');
1846
+ return Boolean(platform && (launch_settings(home).participants[platform] || card_api_profile(home, platform)));
1847
+ }
1848
+
1849
+ /**
1850
+ * Give cards of the room's workflow a member: a present one stays, one that left is brought back, and a card with
1851
+ * none (or whose member was removed) is invited as a program-started member with the card's settings, label and
1852
+ * description. `cards` limits it to those card IDs. Returns the updated {card ID: member name} map.
1853
+ */
1854
+ async function join_workflow_cards(home, config, roster, workflow, members, cards) {
1855
+ const owner = { site: config.site, room_id: config.room, token: config.token };
1856
+ const next = { ...members }, labels = {}, descriptions = {};
1857
+ // Without a list, the main flow's cards; a sub-workflow's cards are named when it is used.
1858
+ for (const agent of cards ? workflow_cards(workflow).filter(item => cards.includes(item.card)) : workflow.agents) {
1859
+ const current = roster.find(member => member.name === next[agent.card] && member.status !== 'removed');
1860
+ if (current?.status === 'active') continue;
1861
+ if (current?.status === 'away') { await room_member(home, { ...owner, action: 'rejoin', name: current.name }); continue; }
1862
+ const taken = new Set([...roster.map(member => member.name), ...Object.values(next)]);
1863
+ const name = taken.has(agent.name) ? free_instance(agent.name, taken) : agent.name;
1864
+ const api = card_api_profile(home, platform_of(agent.name));
1865
+ const card = Object.fromEntries(['project_access', 'model', 'effort'].filter(field => agent[field]).map(field => [field, agent[field]]));
1866
+ // An API member has no command line, so a card asking for more than writing gets the most it allows.
1867
+ if (api && card.project_access && !access_levels('api').includes(card.project_access)) card.project_access = 'write';
1868
+ const profile = { ...api, ...card };
1869
+ const joined = await room_member(home, { ...owner, action: 'add', name, participants: { [name]: profile } });
1870
+ next[agent.card] = joined.member;
1871
+ if (agent.label) labels[joined.member] = agent.label;
1872
+ if (agent.description) descriptions[joined.member] = agent.description;
1873
+ }
1874
+ if (Object.keys(labels).length) await site_request(config.site, `/api/rooms/${config.room}/labels`, config.token, { labels });
1875
+ if (Object.keys(descriptions).length) await site_request(config.site, `/api/rooms/${config.room}/descriptions`, config.token, { descriptions });
1876
+ return next;
1877
+ }
1878
+
1879
+ /**
1880
+ * Bring the room's binding in line with its workflow as saved now, after the workflow was edited while in use: the
1881
+ * given cards (all when omitted) join as in join_workflow_cards, and cards the workflow no longer has leave the
1882
+ * binding, their members staying as ordinary members. Returns the room's workflow status and the card map.
1883
+ */
1884
+ async function sync_workflow_cards(home, path, config, roster, cards) {
1885
+ if (!config.workflow?.id || !config.workflow.enabled) throw new Error('本房间没有在用的工作流');
1886
+ const workflow = get_workflow(home, config.workflow.id);
1887
+ const known = workflow_cards(workflow).map(agent => agent.card);
1888
+ const unknown = (cards || []).filter(card => !known.includes(card));
1889
+ if (unknown.length) throw new Error(`工作流 ${workflow.id} 没有这些卡片:${unknown.join('、')};现有卡片:${known.join('、') || '无'}`);
1890
+ const kept = Object.fromEntries(Object.entries(config.workflow.members || {}).filter(([card]) => known.includes(card)));
1891
+ const members = await join_workflow_cards(home, config, roster, workflow, kept, cards);
1892
+ const release = acquire_lock(join(dirname(path), 'configuration-edit'));
1893
+ try {
1894
+ const current = configuration_snapshot(path).config;
1895
+ if (current.workflow?.id !== workflow.id) throw new Error('本房间的工作流已更换,请重新读取后再试');
1896
+ // The map is replaced, not merged, so dropped cards leave it.
1897
+ const next = { ...current, workflow: { ...current.workflow, members } };
1898
+ atomic_json(path, next);
1899
+ return { room_id: config.room, workflow: room_workflow_status(next, home), members };
1900
+ } finally { release(); }
1901
+ }
1902
+
1903
+ /**
1904
+ * The owner refreshes the room's workflow after editing it in the library (`room-workflow` `sync`): every card gets
1905
+ * a member and dropped cards leave the binding. Returns the room's workflow status and the card map.
1906
+ */
1907
+ async function refresh_room_workflow(home, raw) {
1908
+ const { path } = await member_room_context(home, raw);
1909
+ const config = configuration_snapshot(path).config;
1910
+ const roster = (await api(config, '')).free?.members || [];
1911
+ return sync_workflow_cards(home, path, config, roster);
1912
+ }
1913
+
1914
+ /**
1915
+ * The host brings in members for cards added to the room's workflow after it was enabled; the owner's enabling
1916
+ * authorized the workflow's cards, so this needs no further grant. Only cards with no member yet may be named, so a
1917
+ * member the user sent away or removed stays so. Returns the room's workflow status and the card map.
1918
+ */
1919
+ export async function join_workflow(home, { access_file, cards, sub }) {
1920
+ const { path, config, roster } = await host_room(home, access_file);
1921
+ if (sub) return sync_workflow_cards(home, path, config, roster, sub_workflow_cards(home, config, sub));
1922
+ const mapped = Object.keys(config.workflow?.members || {});
1923
+ const taken = (cards || []).filter(card => mapped.includes(card));
1924
+ if (taken.length) throw new Error(`这些卡片已有成员:${taken.join('、')};离开或移除的成员由用户请回`);
1925
+ const known = config.workflow?.id && config.workflow.enabled ? get_workflow(home, config.workflow.id).agents.map(agent => agent.card) : [];
1926
+ return sync_workflow_cards(home, path, config, roster, cards?.length ? cards : known.filter(card => !mapped.includes(card)));
1927
+ }
1928
+
1929
+ /** The cards a sub-workflow of the room's workflow in use brings; refuses one it lacks or one with no cards. */
1930
+ function sub_workflow_cards(home, config, sub) {
1931
+ if (!config.workflow?.id || !config.workflow.enabled) throw new Error('本房间没有在用的工作流');
1932
+ const list = get_workflow(home, config.workflow.id).sub_workflows;
1933
+ const found = list.find(item => item.id === sub);
1934
+ if (!found) throw new Error(`工作流 ${config.workflow.id} 没有子工作流 ${sub};现有子工作流:${list.map(item => item.id).join('、') || '无'}`);
1935
+ if (!found.agents.length) throw new Error(`子工作流 ${sub} 没有卡片,不需要请成员加入`);
1936
+ return found.agents.map(agent => agent.card);
1937
+ }
1938
+
1939
+ /**
1940
+ * The host ends a sub-workflow's use: the members its cards brought are set away (pending requests cancelled, running work
1941
+ * stopped, sessions kept), so `workflow-join --sub` brings them back to their own sessions. Only a sub-workflow's cards
1942
+ * may be sent away this way; the main flow's members stay for the user to manage.
1943
+ */
1944
+ export async function leave_sub_workflow(home, { access_file, sub }) {
1945
+ if (!sub) throw new Error('须用 --sub 指定子工作流');
1946
+ const { config, roster } = await host_room(home, access_file);
1947
+ const cards = sub_workflow_cards(home, config, sub);
1948
+ const names = cards.map(card => config.workflow.members?.[card]).filter(Boolean);
1949
+ const away = roster.filter(member => names.includes(member.name) && member.status === 'active' && member.role !== 'host');
1950
+ for (const member of away) await site_request(config.site, `/api/rooms/${config.room}/members/${member.id}`, config.token, { action: 'away' });
1951
+ return { room_id: config.room, sub, away: away.map(member => member.name) };
1952
+ }
1953
+
1954
+ // When the owner left the room's goal budget at no limit, a goal the host opens itself still stops by these.
1955
+ const HOST_GOAL_BUDGET = { max_continues: 8, max_minutes: 90 };
1956
+ const LIVE_EXECUTION = ['dispatched', 'started'];
1957
+
1958
+ /**
1959
+ * The active-or-away member a host names by member ID or display name. The host itself only with `self`: changes that
1960
+ * apply from its next delivery (model, label) let it recover, e.g. from one model's quota; stopping, access and
1961
+ * presence stay with the owner.
1962
+ */
1963
+ function host_target({ roster, labels, host }, wanted, { self = false } = {}) {
1964
+ if (!wanted) throw new Error('须用 --member 指定成员(成员 ID 或显示名)');
1965
+ const member = roster.find(item => item.status !== 'removed' && (item.name === wanted || labels[item.name] === wanted));
1966
+ if (!member) throw new Error(`本房间没有成员 ${wanted}`);
1967
+ if (member.name === host && !self) throw new Error('主持人不能对自己执行此操作(自己只能改模型与强度、显示名);更换或移除主持人由用户决定');
1968
+ return member;
1969
+ }
1970
+
1971
+ /** The profile a host-invited member starts from: this computer's saved settings, project access at most write. */
1972
+ function host_invite_profile(home, name, { access, model, effort }) {
1973
+ if (access && !HOST_CARD_ACCESS.includes(access)) throw new Error('主持人邀请的成员项目权限只能是 read 或 write');
1974
+ if (!card_platform_ready(home, name)) {
1975
+ const ready = configured_platforms(home);
1976
+ throw new Error(`本机没有配置 ${name} 的软件或 API Key;只能邀请本机已配置的平台:${ready.join('、')}`);
1977
+ }
1978
+ const api = card_api_profile(home, platform_of(name));
1979
+ const saved = launch_settings(home).participants[platform_of(name)]?.project_access;
1980
+ const project_access = access || (HOST_CARD_ACCESS.includes(saved) ? saved : 'write');
1981
+ return { ...api, project_access, ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
1982
+ }
1983
+
1984
+ /** The positive execution number a host passes with --execution. */
1985
+ function execution_number(value) {
1986
+ const id = Number(value);
1987
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('须用 --execution 指定执行编号');
1988
+ return id;
1989
+ }
1990
+
1991
+ /** Read the discussion, or start (room default limits), pause, resume or end it with the revision just read. */
1992
+ function host_discussion(ctx, { do: step, goal, revision, submission_id }) {
1993
+ if (!step) return ctx.call('/discussion');
1994
+ if (step === 'start') {
1995
+ if (!goal) throw new Error('开启讨论须用 --goal 写明讨论目标');
1996
+ return ctx.call('/discussion', { action: 'start', goal, revision, submission_id: submission_id || randomUUID() });
1997
+ }
1998
+ if (!['pause', 'resume', 'end'].includes(step)) throw new Error('--do 须为 start、pause、resume 或 end');
1999
+ return ctx.call('/discussion', { action: step, revision });
2000
+ }
2001
+
2002
+ /** Read the goal, or open it under the owner's default budget (a bounded one when that is unlimited), pause, resume or end it. */
2003
+ function host_goal(ctx, { do: step, goal, revision }) {
2004
+ if (!step) return ctx.call('/goal');
2005
+ if (step === 'start') {
2006
+ if (!goal) throw new Error('开启 Goal 须用 --goal 写明目标');
2007
+ const preferences = launch_settings(ctx.home).create_preferences || {};
2008
+ const budget = {
2009
+ max_continues: preferences.goal_max_continues || HOST_GOAL_BUDGET.max_continues,
2010
+ max_minutes: preferences.goal_max_minutes || HOST_GOAL_BUDGET.max_minutes,
2011
+ };
2012
+ return ctx.call('/goal', { action: 'start', objective: goal, revision, ...budget });
2013
+ }
2014
+ if (!['pause', 'resume', 'end'].includes(step)) throw new Error('--do 须为 start、pause、resume 或 end');
2015
+ return ctx.call('/goal', { action: step === 'end' ? 'clear' : step, revision });
2016
+ }
2017
+
2018
+ /** Steer a member's running execution with an interjection; a retry passes the same --submission-id. */
2019
+ function host_steer(ctx, { member: wanted, text, submission_id }) {
2020
+ const member = host_target(ctx, wanted);
2021
+ if (!text) throw new Error('须用 --text 写明要对它说的话');
2022
+ if (!LIVE_EXECUTION.includes(member.execution?.status)) throw new Error(`${wanted} 当前没有进行中的执行;要它发言请在回答里用 --to 点名`);
2023
+ return ctx.call(`/executions/${member.execution.id}`, { action: 'interject', text, submission_id: submission_id || randomUUID() });
2024
+ }
2025
+
2026
+ /** Set a member's display name and, optionally, its description. */
2027
+ async function host_label(ctx, { member: wanted, label, description }) {
2028
+ const member = host_target(ctx, wanted, { self: true });
2029
+ if (!label && !description) throw new Error('须用 --label 或 --description 指定显示名或描述');
2030
+ if (label) await ctx.call('/labels', { labels: { [member.name]: label } });
2031
+ if (description) await ctx.call('/descriptions', { descriptions: { [member.name]: description } });
2032
+ return { member: member.name, label: label || null, description: description || null };
2033
+ }
2034
+
2035
+ /** Invite a member from this computer's configured software, project access at most write. */
2036
+ async function host_invite(ctx, options) {
2037
+ if (!options.name) throw new Error('须用 --name 指定要邀请的平台(如 Claude、Codex)');
2038
+ const taken = new Set(ctx.roster.map(member => member.name));
2039
+ const name = taken.has(options.name) ? free_instance(options.name, taken) : options.name;
2040
+ const profile = host_invite_profile(ctx.home, name, options);
2041
+ const joined = await room_member(ctx.home, { ...ctx.owner, action: 'add', name, participants: { [name]: profile } }, false, ctx.headers);
2042
+ return { member: joined.member, project_access: profile.project_access };
2043
+ }
2044
+
2045
+ /** Read the speaking order, or change its not-yet-spoken part with the revision just read; display names are accepted. */
2046
+ function host_order(ctx, { order, revision }) {
2047
+ if (!order) return ctx.call('/speaking-order');
2048
+ if (!revision) throw new Error('调整发言顺序前先不带 --order 读取当前顺序,再用 --revision 带上其 revision');
2049
+ const names = order.split(',').map(name => name.trim()).filter(Boolean)
2050
+ .map(name => ctx.roster.find(member => member.status === 'active' && ctx.labels[member.name] === name && member.name !== name)?.name || name);
2051
+ return ctx.call('/speaking-order', { revision, order: names });
2052
+ }
2053
+
2054
+ const HOST_CONTROLS = {
2055
+ stop: (ctx, o) => ctx.call(`/members/${host_target(ctx, o.member).id}/interrupt`, {}),
2056
+ 'stop-all': ctx => ctx.call('/stop', {}),
2057
+ steer: host_steer,
2058
+ retry: (ctx, o) => ctx.call(`/executions/${execution_number(o.execution)}`, { action: 'retry' }),
2059
+ details: (ctx, o) => execution_details_command(ctx.home, { ...ctx.owner, execution_id: execution_number(o.execution) }),
2060
+ order: host_order,
2061
+ invite: host_invite,
2062
+ away: (ctx, o) => ctx.call(`/members/${host_target(ctx, o.member).id}`, { action: 'away' }),
2063
+ remove: (ctx, o) => ctx.call(`/members/${host_target(ctx, o.member).id}`, { action: 'remove' }),
2064
+ back: (ctx, o) => room_member(ctx.home, { ...ctx.owner, action: 'rejoin', name: host_target(ctx, o.member).name }, false, ctx.headers),
2065
+ model: (ctx, o) => room_member_model(ctx.home, { ...ctx.owner, name: host_target(ctx, o.member, { self: true }).name, model: o.model || '', effort: o.effort || '' }),
2066
+ access: (ctx, o) => {
2067
+ if (!HOST_CARD_ACCESS.includes(o.access)) throw new Error('主持人只能把成员的项目权限设为 read 或 write');
2068
+ return room_member_access(ctx.home, { ...ctx.owner, name: host_target(ctx, o.member).name, project_access: o.access });
2069
+ },
2070
+ adapter: (ctx, o) => room_member_adapter(ctx.home, { ...ctx.owner, name: host_target(ctx, o.member).name, adapter: o.adapter }),
2071
+ label: host_label,
2072
+ discussion: host_discussion,
2073
+ goal: host_goal,
2074
+ withdraw: (ctx, o) => {
2075
+ const id = Number(o.message);
2076
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('须用 --message 指定要撤回的派活消息编号');
2077
+ return ctx.call(`/dispatches/${id}/withdraw`, {});
2078
+ },
2079
+ checkin: (ctx, o) => {
2080
+ if (o.off) return ctx.call('/host-checkin', { off: true });
2081
+ const minutes = Number(o.minutes);
2082
+ if (!Number.isSafeInteger(minutes)) throw new Error('须用 --minutes 指定间隔分钟数(5–120),或 --off 关闭');
2083
+ return ctx.call('/host-checkin', { minutes });
2084
+ },
2085
+ };
2086
+
2087
+ /**
2088
+ * The host runs a room control the owner otherwise does in the web page, when the owner granted this room full host
2089
+ * control (`host_workflows`), so it can keep work moving and handle what goes wrong by itself: stop, steer or retry a
2090
+ * member, read an execution's local log, change the speaking order, invite (configured software, at most write), send
2091
+ * away, remove or bring back members, change a member's model, effort, client or access (read/write only), label it,
2092
+ * and read, start, pause, resume or end the discussion or goal. The site checks every write as for the owner (revisions
2093
+ * included). What stays the owner's: acting on the host itself, approving rounds beyond the limit, access above write
2094
+ * or tool approvals, project directories, the owner's messages and private chats.
2095
+ */
2096
+ export async function host_control(home, action, options) {
2097
+ if (!Object.hasOwn(HOST_CONTROLS, action || '')) throw new Error(`操作须为 ${Object.keys(HOST_CONTROLS).join('、')} 之一`);
2098
+ const { config, roster, labels, host } = await host_room(home, options.access_file);
2099
+ if (!config.host_workflows) throw new Error('房主没有为本房间打开“主持人完整权限”;请让用户在电脑上“成员与设置 → 协作设置”打开后再试');
2100
+ const headers = { 'User-Agent': `AI-CoDiscuss-host:${host}` };
2101
+ const owner = { site: config.site, room_id: config.room, token: config.token };
2102
+ const call = (path, body) => site_request(config.site, `/api/rooms/${config.room}${path}`, config.token, body, headers);
2103
+ return HOST_CONTROLS[action]({ home, config, roster, labels, host, headers, owner, call }, options);
2104
+ }
2105
+
2106
+ /** Cards as the host may bring them: any access above writing is lowered to it. */
2107
+ const host_cards = agents => agents.map(agent => agent.project_access && !HOST_CARD_ACCESS.includes(agent.project_access)
2108
+ ? { ...agent, project_access: 'write' } : agent);
2109
+
2110
+ /**
2111
+ * The host enables a workflow in its own room, when the owner allowed that for this room (`host_workflows`): either
2112
+ * its own draft, saved into the library first (the same ID again updates it), or one already in the library, named by
2113
+ * `workflow_id` and left unchanged there. Each card the room lacks is invited as a program-started member with at most
2114
+ * write access, one that left is brought back. Returns which member plays which card and where its SKILL.md is, so the
2115
+ * host can follow it and name them in the same execution.
2116
+ */
2117
+ export async function adopt_workflow(home, { access_file, draft_file, workflow_id }) {
2118
+ if (!draft_file === !workflow_id) throw new Error('须提供 --draft 草稿文件或 --id 工作流库中的工作流 ID 之一;凭据用 --access-file 或 DISCUSS_ACCESS_FILE');
2119
+ const { config, roster } = await host_room(home, access_file);
2120
+ if (!config.host_workflows) throw new Error('房主没有为本房间打开“主持人完整权限”;请让用户在电脑上“成员与设置 → 协作设置”打开后再试');
2121
+ const bound = config.workflow?.id;
2122
+ let workflow;
2123
+ if (workflow_id) workflow = get_workflow(home, workflow_id);
2124
+ else {
2125
+ const draft = parse_workflow_draft([readFileSync(resolve(draft_file), 'utf8')]);
2126
+ if (bound !== draft.id && list_workflows(home).some(item => item.id === draft.id)) throw new Error(`工作流库已有 ${draft.id},主持人不能覆盖其他工作流;要启用它请用 --id ${draft.id},新建请换一个 ID`);
2127
+ workflow = draft;
2128
+ }
2129
+ assert_workflow_enabled(home, workflow.id);
2130
+ const missing = workflow.agents.filter(agent => !card_platform_ready(home, agent.name)).map(agent => agent.name || agent.card);
2131
+ if (missing.length) {
2132
+ const ready = configured_platforms(home);
2133
+ throw new Error(`本机没有配置这些卡片的软件或 API Key:${missing.join('、')};卡片的 platform 只能用本机已配置的平台 ID:${ready.join('、')}`);
2134
+ }
2135
+ workflow = workflow_id ? { ...workflow, agents: host_cards(workflow.agents) }
2136
+ : save_workflow(home, { ...workflow, agents: host_cards(workflow.agents) }, validate_preset);
2137
+ const owner = { site: config.site, room_id: config.room, token: config.token };
2138
+ const members = await join_workflow_cards(home, config, roster, workflow, bound === workflow.id ? config.workflow.members || {} : {});
2139
+ const enabled = await room_workflow(home, { ...owner, action: 'enable', workflow: { id: workflow.id, members } });
2140
+ return { ...enabled, members, skill_path: join(workflow_directory(home, workflow.id), 'SKILL.md') };
2141
+ }
2142
+
2143
+ /**
2144
+ * Check a workflow folder or one-part draft as an import would, and optionally save it. A local AI uses this outside
2145
+ * rooms with its user present, so the cards keep the project access they declare.
2146
+ */
2147
+ export function check_or_save_workflow(home, { dir, draft }, save = false) {
2148
+ if (!dir === !draft) throw new Error('须提供 --dir 工作流文件夹或 --draft 草稿文件之一');
2149
+ const source = dir ? { folder: dir } : { parts: [readFileSync(resolve(draft), 'utf8')] };
2150
+ const preview = workflows_command(home, { action: 'preview', ...source });
2151
+ if (!save) return preview;
2152
+ const declared = list => list.map(({ requested_access, ...agent }) => requested_access ? { ...agent, project_access: requested_access } : agent);
2153
+ const sub_workflows = preview.sub_workflows?.map(sub => ({ ...sub, agents: declared(sub.agents) }));
2154
+ return save_workflow(home, { ...preview, agents: declared(preview.agents), ...(sub_workflows ? { sub_workflows } : {}) }, validate_preset);
2155
+ }
2156
+
2157
+ const WRITING_ACCESS = new Set(['write', 'auto', 'full', 'own']);
2158
+
2159
+ /** The configuration this computer keeps for a room, found by its id; null when it runs no such room. */
2160
+ function room_config_by_id(home, room_id) {
2161
+ if (typeof room_id !== 'string' || !room_id) return null;
2162
+ const paths = read_registry(home).filter(path => registered_identity(path)?.room === room_id);
2163
+ return paths.length === 1 ? configuration_snapshot(paths[0]).config : null;
2164
+ }
2165
+
2166
+ /**
2167
+ * The folders a request without this computer owner's standing may use: for an ordinary account, its own projects and
2168
+ * draft space; for another device of the owner, the saved projects.
2169
+ */
2170
+ function granted_projects(home) {
2171
+ const { projects_root, workspace } = account_space(home);
2172
+ if (!projects_root) return launch_projects(home).projects;
2173
+ mkdirSync(workspace, { recursive: true });
2174
+ return [...account_projects(projects_root), { name: '草稿空间', path: workspace }];
2175
+ }
2176
+
2177
+ /** Fill program locations another device left out with the ones saved here, so saving defaults cannot drop them. */
2178
+ function keep_saved_locations(home, participants) {
2179
+ const saved = launch_settings(home).participants;
2180
+ return Object.fromEntries(Object.entries(participants).map(([name, profile]) => {
2181
+ const kept = Object.fromEntries(['executable', 'ipc_directory'].filter(field => !profile?.[field] && saved[name]?.[field]).map(field => [field, saved[name][field]]));
2182
+ return [name, { ...profile, ...kept }];
2183
+ }));
2184
+ }
2185
+
2186
+ /** CLI and local HTTP bridge use the same commands and configuration validation. */
2187
+ export async function launch_main(args = process.argv.slice(2), input_text) {
2188
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
2189
+ file: { type: 'string' }, 'dry-run': { type: 'boolean' }, browser: { type: 'boolean' }, remote: { type: 'boolean' }, device: { type: 'string' },
2190
+ 'configuration-locked': { type: 'boolean' }, help: { type: 'boolean', short: 'h' },
2191
+ draft: { type: 'string' }, 'access-file': { type: 'string' }, dir: { type: 'string' }, card: { type: 'string' }, sub: { type: 'string' }, id: { type: 'string' },
2192
+ member: { type: 'string' }, order: { type: 'string' }, revision: { type: 'string' }, name: { type: 'string' }, access: { type: 'string' },
2193
+ model: { type: 'string' }, effort: { type: 'string' }, do: { type: 'string' }, execution: { type: 'string' }, text: { type: 'string' },
2194
+ goal: { type: 'string' }, label: { type: 'string' }, description: { type: 'string' }, adapter: { type: 'string' }, 'submission-id': { type: 'string' },
2195
+ message: { type: 'string' }, minutes: { type: 'string' }, off: { type: 'boolean' },
2196
+ } });
2197
+ if (values.help || !positionals.length) return process.stdout.write(HELP);
2198
+ if (positionals[0] === 'workflow-adopt') {
2199
+ const home = service_home();
2200
+ const result = await adopt_workflow(home, { draft_file: values.draft, workflow_id: values.id, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2201
+ return process.stdout.write(`${JSON.stringify(result)}\n`);
2202
+ }
2203
+ if (positionals[0] === 'host-control') {
2204
+ const { member, order, revision, name, access, model, effort, execution, text, goal, label, description, adapter } = values;
2205
+ const result = await host_control(service_home(), positionals[1], { member, order, revision, name, access, model, effort, execution, text, goal,
2206
+ label, description, adapter, message: values.message, minutes: values.minutes, off: values.off, do: values.do, submission_id: values['submission-id'], access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2207
+ return process.stdout.write(`${JSON.stringify(result)}
2208
+ `);
2209
+ }
2210
+ if (positionals[0] === 'workflow-join') {
2211
+ const cards = (values.card || '').split(',').map(card => card.trim()).filter(Boolean);
2212
+ const result = await join_workflow(service_home(), { cards, sub: values.sub, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2213
+ return process.stdout.write(`${JSON.stringify(result)}
2214
+ `);
2215
+ }
2216
+ if (positionals[0] === 'workflow-leave') {
2217
+ const result = await leave_sub_workflow(service_home(), { sub: values.sub, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2218
+ return process.stdout.write(`${JSON.stringify(result)}
2219
+ `);
2220
+ }
2221
+ if (positionals[0] === 'image') {
2222
+ if (!values.file) throw new Error('用 --file 指定请求 JSON:{"action":"generate"|"edit","prompt":"…",…}');
2223
+ const request = JSON.parse(readFileSync(values.file, 'utf8').replace(/^/, ''));
2224
+ const result = await draw_image(service_home(), { request, access_file: values['access-file'] || process.env.DISCUSS_ACCESS_FILE });
2225
+ return process.stdout.write(`${JSON.stringify(result)}\n`);
2226
+ }
2227
+ if (['workflow-check', 'workflow-save'].includes(positionals[0])) {
2228
+ const result = check_or_save_workflow(service_home(), { dir: values.dir, draft: values.draft }, positionals[0] === 'workflow-save');
2229
+ return process.stdout.write(`${JSON.stringify(result)}\n`);
2230
+ }
2231
+ const input = input_text === undefined ? (values.file ? JSON.parse(readFileSync(values.file, 'utf8').replace(/^\uFEFF/, '')) : null) : JSON.parse(input_text);
2232
+ const home = service_home();
2233
+ assert_shared_home(home);
2234
+ // Another device's request may only use what this computer granted; the flag is set by the relay, never by the request.
2235
+ // An ordinary account's instance holds every request, from any page, to that account's own folders.
2236
+ const space = account_space(home), restricted = Boolean(space.projects_root);
2237
+ if (values.remote || restricted) {
2238
+ guard_remote_request(positionals[0], input, { projects: granted_projects(home), participants: launch_settings(home).participants, home });
2239
+ if (values.remote && positionals[0] === 'room-workflow' && input?.action === 'host') throw new Error('“主持人完整权限”只能在电脑上开启');
2240
+ if (restricted && positionals[0] === 'pick-directory') throw new Error('此账号只能使用自己的项目文件夹');
2241
+ // Another device repeats the saved program locations it cannot see; keep them rather than dropping them.
2242
+ if (positionals[0] === 'settings' && input?.participants) input.participants = keep_saved_locations(home, input.participants);
2243
+ }
2244
+ if (values.remote) {
2245
+ // Tool approvals saved here stay this computer's decision; a room created from another device does not take them.
2246
+ if (positionals[0] === 'start' && input) input.without_saved_tools = true;
2247
+ }
2248
+ let result;
2249
+ if (positionals[0] === 'settings') result = { ...(input ? save_launch_settings(home, input) : launch_settings(home)), api_providers: API_PROVIDERS,
2250
+ scheduler_providers: SCHEDULER_PROVIDERS, scheduler_modes: SCHEDULER_MODES, scheduler_default_mode: DEFAULT_SCHEDULER_MODE, api_keys: saved_api_keys(home), managed_api_keys: restricted ? managed_api_keys(home) : [], projects: launch_projects(home).projects, projects_restricted: restricted, workspace: space.workspace, user_home: restricted ? homedir() : '', ...expert_presets(home), ...workflow_library(home) };
2251
+ else if (positionals[0] === 'projects') result = input ? save_launch_projects(home, input) : launch_projects(home);
2252
+ else if (positionals[0] === 'presets') result = input ? save_expert_presets(home, input) : expert_presets(home);
2253
+ else if (positionals[0] === 'workflows') result = await workflows_command(home, input || {});
2254
+ else if (positionals[0] === 'room-workflow' && input) result = await room_workflow(home, input);
2255
+ else if (positionals[0] === 'room-settings' && input) result = await room_settings(home, input);
2256
+ else if (positionals[0] === 'api-key' && input) result = save_api_key(home, { base_url: input.base_url, api_key: input.api_key });
2257
+ else if (positionals[0] === 'api-check' && input) result = await api_check(home, input);
2258
+ else if (positionals[0] === 'scheduler-check' && input) result = await scheduler_check(home, input);
2259
+ else if (positionals[0] === 'image-settings') result = input && Object.keys(input).length ? save_image_settings(home, input) : image_settings(home);
2260
+ else if (positionals[0] === 'tts-settings') result = input && Object.keys(input).length ? save_tts_settings(home, input) : tts_settings(home);
2261
+ else if (positionals[0] === 'tts' && input) result = await tts_speak(home, input);
2262
+ else if (positionals[0] === 'tts-release') result = tts_release(home);
2263
+ else if (positionals[0] === 'local-speech') result = input?.stop ? await local_service_stop(home, input.stop) : await local_services(home);
2264
+ else if (positionals[0] === 'weixin') result = await weixin_command(home, input || {});
2265
+ else if (positionals[0] === 'stt' && input) result = await stt_part(home, input);
2266
+ else if (positionals[0] === 'room-models' && input) result = await room_models(home, input);
2267
+ else if (positionals[0] === 'room-skills' && input) result = await room_skills(home, input);
2268
+ else if (positionals[0] === 'room-files' && input) result = await room_files(home, input);
2269
+ else if (positionals[0] === 'room-page' && input) result = await room_page(home, input, { parts: Boolean(values.remote) });
2270
+ else if (positionals[0] === 'room-media' && input) result = await room_media(home, input, { parts: Boolean(values.remote) });
2271
+ else if (positionals[0] === 'execution-details' && input) result = await execution_details_command(home, input);
2272
+ else if (positionals[0] === 'models' && adapter_profile(input?.adapter)?.kind === 'api') result = await api_models(home, input);
2273
+ else if (positionals[0] === 'models' && input) {
2274
+ const saved = Object.values(launch_settings(home).participants).find(profile => profile.adapter === input.adapter);
2275
+ result = await cached_software_models(home, { adapter: input.adapter, executable: input.executable || saved?.executable,
2276
+ ...(input.model ? { model: input.model } : {}) }, { refresh: input.refresh === true });
2277
+ }
2278
+ else if (positionals[0] === 'room-member' && input) result = await room_member(home, input);
2279
+ else if (positionals[0] === 'room-member-access' && input) result = await room_member_access(home, input);
2280
+ else if (positionals[0] === 'room-member-allow' && input) result = await room_member_allow(home, input);
2281
+ else if (positionals[0] === 'room-member-adapter' && input) result = await room_member_adapter(home, input);
2282
+ else if (positionals[0] === 'room-member-model' && input) result = await room_member_model(home, input);
2283
+ else if (positionals[0] === 'room-profiles' && input) result = await room_profiles(home, input);
2284
+ else if (positionals[0] === 'room-restore' && input) result = await restore_room(home, input);
2285
+ else if (positionals[0] === 'room-fork' && input) result = await fork_room(home, input);
2286
+ else if (positionals[0] === 'pick-directory') result = await pick_directory();
2287
+ else if (positionals[0] === 'browse-directory') result = list_remote_directories(input || {}, { projects: granted_projects(home), home });
2288
+ // Device trust from this computer's own screen; other devices reach the same actions through the relay instead.
2289
+ else if (positionals[0] === 'device-pairing' && !values.remote) {
2290
+ // The QR code opens the paired website and carries this computer's key fingerprint for the new device to check.
2291
+ const { keyed_links } = await import('./remote_launch.mjs');
2292
+ const [site, link] = Object.entries(keyed_links(home).sites).find(([origin]) => !input?.site || origin === input.site) || [];
2293
+ if (!link) throw new Error('这台电脑还没有绑定线上网站,请先运行 codiscuss local connect 网站地址');
2294
+ result = start_pairing(home, { site, fingerprint: machine_fingerprint(link), temporary: input?.temporary === true, without_passkey: input?.without_passkey === true });
2295
+ }
2296
+ else if (positionals[0] === 'devices' && !values.remote) {
2297
+ result = input?.revoke ? revoke_device(home, String(input.revoke)) : list_devices(home);
2298
+ // The website takes devices only from the list this computer signs, so a revocation is sent at once.
2299
+ if (input?.revoke) await (await import('./remote_launch.mjs')).sync_remote_launches(home).catch(() => {});
2300
+ }
2301
+ else if (positionals[0] === 'machine-link' && input) result = (await import('./remote_launch.mjs')).machine_link(home, input.site);
2302
+ else if (positionals[0] === 'start' && input) {
2303
+ result = await launch_discussion(home, input, { dry_run: values['dry-run'], browser_request: values.browser });
2304
+ }
2305
+ else if (positionals[0] === 'room-config' && input) result = await room_configuration(home, input, { local_guard: values['configuration-locked'] });
2306
+ else throw new Error(HELP);
2307
+ process.stdout.write(`${JSON.stringify(result)}\n`);
2308
+ }
2309
+
2310
+ if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
2311
+ const args = process.argv.slice(2);
2312
+ const stdin = args.includes('--stdin') ? readFileSync(0, 'utf8') : undefined;
2313
+ launch_main(args.filter(arg => arg !== '--stdin'), stdin).catch(error => {
2314
+ // A request that needs the page to do something first (pair, renew, confirm writing) says so in a field it can read.
2315
+ const need = error.need ? { need: error.need, ...(error.room_id ? { room_id: error.room_id } : {}) } : {};
2316
+ const failure = args.includes('--browser') ? JSON.stringify({ error: error.message, ...need, launch: error.launch || { stage: 'not_started' } })
2317
+ : error.need ? JSON.stringify({ error: error.message, ...need }) : error.message;
2318
+ process.stderr.write(`${failure}\n`); process.exitCode = 1;
2319
+ });
2320
+ }