ai_co_discuss 0.5.21 → 0.5.23

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.
Files changed (85) hide show
  1. package/.agents/skills/codiscuss-draft-cleanup/SKILL.md +16 -0
  2. package/.agents/skills/codiscuss-draft-cleanup/cleanup.py +70 -0
  3. package/.agents/skills/codiscuss-draft-cleanup/scan.py +70 -0
  4. package/.agents/skills/discuss-host/references/control.md +2 -2
  5. package/.agents/skills/discuss-host/references/workflow.md +4 -2
  6. package/.agents/skills/discuss-participant/SKILL.md +2 -0
  7. package/.agents/skills/local-stt-setup/SKILL.md +9 -8
  8. package/.agents/skills/local-tts-setup/SKILL.md +10 -9
  9. package/.agents/skills/share-card/SKILL.md +7 -6
  10. package/.agents/skills/share-card/references/share-card.md +34 -8
  11. package/.agents/skills/workflow-creator/SKILL.md +22 -14
  12. package/README.md +2 -0
  13. package/README.zh-CN.md +2 -0
  14. package/backend/free_room.py +64 -8
  15. package/backend/message_queue.py +9 -0
  16. package/backend/schema.sql +13 -1
  17. package/backend/server.py +289 -59
  18. package/docs/en/guide/admin.md +18 -0
  19. package/docs/en/guide/members.md +7 -1
  20. package/docs/en/guide/remote.md +1 -1
  21. package/docs/en/guide/rooms.md +14 -6
  22. package/docs/en/guide/voice.md +2 -0
  23. package/docs/en/guide/workflows.md +9 -5
  24. package/docs/en/guide/working.md +6 -4
  25. package/docs/guide/admin.md +18 -0
  26. package/docs/guide/members.md +7 -1
  27. package/docs/guide/remote.md +1 -1
  28. package/docs/guide/rooms.md +13 -6
  29. package/docs/guide/voice.md +2 -0
  30. package/docs/guide/workflows.md +9 -5
  31. package/docs/guide/working.md +6 -4
  32. package/frontend/locales/en/admin.json +58 -1
  33. package/frontend/locales/en/app.json +18 -1
  34. package/frontend/locales/en/backend.json +6 -0
  35. package/frontend/locales/en/core.json +4 -2
  36. package/frontend/locales/en/discussion.json +4 -1
  37. package/frontend/locales/en/room.json +85 -1
  38. package/gateway/gateway.mjs +49 -9
  39. package/package.json +3 -1
  40. package/runner/account_space.mjs +10 -0
  41. package/runner/adapters/antigravity_app.mjs +31 -4
  42. package/runner/adapters/antigravity_cli.mjs +9 -2
  43. package/runner/adapters/api.mjs +3 -2
  44. package/runner/adapters/api_pi.mjs +3 -2
  45. package/runner/adapters/api_pi_extension.mjs +5 -3
  46. package/runner/adapters/claude.mjs +32 -9
  47. package/runner/adapters/cli.mjs +2 -2
  48. package/runner/adapters/codex_app.mjs +192 -69
  49. package/runner/adapters/codex_cli.mjs +10 -5
  50. package/runner/adapters/common.mjs +414 -11
  51. package/runner/adapters/index.mjs +6 -0
  52. package/runner/admin_cli.mjs +22 -5
  53. package/runner/admin_panel.mjs +118 -5
  54. package/runner/admin_storage.mjs +105 -0
  55. package/runner/discussion_launch.mjs +328 -128
  56. package/runner/discussion_runner.mjs +12 -3
  57. package/runner/discussion_service.mjs +224 -37
  58. package/runner/discussion_skills.mjs +1 -1
  59. package/runner/expert_prompts.mjs +2 -2
  60. package/runner/experts.mjs +227 -0
  61. package/runner/file_diff.mjs +1 -1
  62. package/runner/free_runner.mjs +236 -51
  63. package/runner/i18n_en.mjs +39 -0
  64. package/runner/os_users.mjs +33 -1
  65. package/runner/project_files.mjs +7 -1
  66. package/runner/project_migration.mjs +245 -0
  67. package/runner/relay_channel.mjs +1 -1
  68. package/runner/remote_launch.mjs +4 -3
  69. package/runner/share_card.mjs +17 -1
  70. package/runner/share_shared.mjs +26 -9
  71. package/runner/site_deploy.mjs +2 -1
  72. package/runner/slash_names.mjs +12 -1
  73. package/runner/speech_directories.mjs +20 -0
  74. package/runner/storage_guard.mjs +383 -0
  75. package/runner/tts_providers.mjs +22 -21
  76. package/runner/workflows.mjs +211 -57
  77. package/web/admin.css +1 -1
  78. package/web/admin.js +8 -8
  79. package/web/app.js +589 -80
  80. package/web/i18n.js +4 -4
  81. package/web/markdown.css +1 -1
  82. package/web/modern.css +1 -1
  83. package/web/modern.js +68 -66
  84. package/workflows/decision-council/flow.json +216 -25
  85. package/workflows/trpg-classic/flow.json +151 -21
@@ -1,5 +1,18 @@
1
1
  /** English CLI strings. */
2
2
  export default {
3
+ " account migration-backups <名> 查看各迁移备份的位置与字节数": " account migration-backups <name> Show the path and byte count of each migration backup",
4
+ " account release-backup <名> <迁移编号> <目录类别> --confirm 停止实例并释放指定备份": " account release-backup <name> <migration-id> <kind> --confirm Stop the instance and release the selected backup",
5
+ "已有账号使用不同的数据目录,请用 account migrate-data 显式迁移。": "The existing account uses a different data directory. Use account migrate-data to move it explicitly.",
6
+ " account migrate-data <名> --project-data-root <目录> 停止实例并迁移项目数据": " account migrate-data <name> --project-data-root <path> Stop the instance and move project data",
7
+ " account add <名> --project-data-root <目录> 将新账号的项目、工作区和成员草稿放在指定目录": " account add <name> --project-data-root <path> Store a new account's projects, workspace and member drafts in this directory",
8
+ "存储清理范围无效": "Invalid storage cleanup scope",
9
+ " storage [clean] 查看存储用量,或清理已确认结束的执行临时目录": " storage [clean] Show storage usage or clean temporary directories of confirmed finished runs",
10
+ "房间:create-room --title 标题 [--goal 目标] [--members 甲,乙] [--host 平台] [--host-model 模型] [--host-effort 档位] [--cwd 子目录] [--access read|write] [--text 首条消息 | --body-file FILE] [--submission-id ID]": "Rooms: create-room --title TITLE [--goal GOAL] [--members A,B] [--host PLATFORM] [--host-model MODEL] [--host-effort LEVEL] [--cwd SUBDIRECTORY] [--access read|write] [--text MESSAGE | --body-file FILE] [--submission-id ID]",
11
+ "room-post --room 房间编号 (--text 话 | --body-file FILE) [--interrupt] [--submission-id ID] 在关联房间(你新建的,或新建本房间的)发言,空闲时直达主持人,忙时排队;仅父房间可用 --interrupt 打断子房间;自用户上次发言起两边互传的条数受本机“关联房间互传上限”限制(默认不限);读它用平常的读取命令、房间编号写新房间的(跨房间只能读)。": "room-post --room ROOM (--text MESSAGE | --body-file FILE) [--interrupt] [--submission-id ID] sends to the linked host, queuing when busy. Only a parent may interrupt its child. The linked-room message limit counts both directions since the last owner message and defaults to unlimited. Use regular read commands with the linked room ID to follow progress.",
12
+ "正文文件须位于主持人的项目或草稿目录": "The message file must be in the host’s project or drafts directory.",
13
+ "--body-file 与 --text 只能选一项": "Choose either --body-file or --text.",
14
+ "仅父房间主持人可以打断子房间": "Only the parent room’s host can interrupt a child room.",
15
+ "须用 --text 或 --body-file 写明要发的消息": "Provide the message with --text or --body-file.",
3
16
  "这个房间已有分享正在发布": "A share is already being published for this room.",
4
17
  "本机没有登记这个房间": "This room is not registered on this computer.",
5
18
  "分享请求失败(HTTP {status})": "Share request failed (HTTP {status}).",
@@ -376,6 +389,13 @@ export default {
376
389
  "已移除旧版全局放行规则": "Legacy global allow rules removed",
377
390
  "技能": "Skills",
378
391
  "工作流": "Workflows",
392
+ "工作流库里已有「{id}」;要整份覆盖它,请明确选择覆盖": "The workflow library already contains “{id}”. Explicitly choose overwrite to replace it.",
393
+ "全局工作流库里已有「{id}」,无法移至全局。": "The global workflow library already contains “{id}”, so this workflow cannot be moved there.",
394
+ "项目目录为只读,无法保存工作流。": "The project folder is read-only, so the workflow cannot be saved.",
395
+ "项目工作流「{id}」需要房主确认信任后才能启用。": "The room owner must confirm trust before enabling the project workflow “{id}”.",
396
+ "workflow-promote 将项目工作流移至全局并更新当前房间的绑定;全局已有同 ID 时拒绝。": "workflow-promote moves a project workflow to the global library and updates the current room’s binding. It refuses to replace a global workflow with the same ID.",
397
+ "workflow-adopt 保存草稿时默认使用主项目;没有主项目时默认全局。按 ID 启用时先查房间项目,再查全局。": "workflow-adopt saves drafts to the main project by default, or to the global library if there is no main project. When enabling by ID, it searches room projects before the global library.",
398
+ "使用 --scope project --project DIR 选择项目作用域,或使用 --scope global 选择全局作用域。": "Use --scope project --project DIR to select a project, or --scope global to select the global scope.",
379
399
  "快捷方式": "Shortcut",
380
400
  "双击“共议”启动": "Double-click CoDiscuss to start",
381
401
  "已打开": "Enabled",
@@ -685,6 +705,25 @@ export default {
685
705
  "未在系统可信安装位置找到可用的本地浏览器(Edge / Chrome / Chromium),无法将 HTML 导出为 PNG。请安装 Edge、Chrome 或 Chromium;也可以直接提供 PNG/JPG/WebP 图片。": "No local browser (Edge / Chrome / Chromium) was found in trusted system install locations to export HTML to PNG. Install Edge, Chrome, or Chromium, or provide a PNG/JPG/WebP image directly.",
686
706
  "AI CoDiscuss 分享卡封面工具\n\n用法:\n codiscuss share-card materials [房间ID] [--site URL] [--access-file FILE] [--max-highlights N] [--max-steps N]\n codiscuss share-card render <HTML文件> --out <PNG文件> [--width 750] [--height N] [--max-height 1500] [--scale 2] [--background #12141c]\n\n子命令:\n materials 按可分享范围读取房间的协作指标、并发曲线与必要素材索引(排除已撤回消息、私聊与敏感片段,输出截断标记)\n render 使用系统可信安装位置的隔离沙箱浏览器(进程私有控制通道、无 TCP 调试端口)将本地静态 HTML 导出为高清 PNG 封面图\n\n选项:\n --room ROOM 目标房间编号(省略时取凭据绑定的房间;传其他房间编号可跨房间只读取材)\n --site, --url SITE 站点地址(带任务凭据时须与凭据绑定站点一致)\n --access-file FILE 任务凭据文件(默认读取 DISCUSS_ACCESS_FILE)\n --max-highlights N 返回的代表发言索引上限(默认 12)\n --max-steps N 并发曲线最大时间步数(默认 240,超出时按峰值采样)\n --out, -o FILE render 输出的 PNG 路径(持任务凭据时须在允许写入的目录或自己的草稿目录内;本机房主手动运行时沿用当前账号文件权限)\n --width N render CSS 宽度(像素,默认 750,范围 320–1500)\n --height N render 固定 CSS 高度(省略时按内容自适应)\n --max-height N render 最大 CSS 高度(默认 1500,范围 200–2400)\n --scale N render 像素倍率(默认 2,750×2 = 1500px 宽)\n --background HEX render 默认底色(默认 #12141c)\n --json 以 JSON 输出(默认)\n -h, --help 显示帮助\n": "AI CoDiscuss Share-Card Cover Tool\n\nUsage:\n codiscuss share-card materials [ROOM_ID] [--site URL] [--access-file FILE] [--max-highlights N] [--max-steps N]\n codiscuss share-card render <HTML_FILE> --out <PNG_FILE> [--width 750] [--height N] [--max-height 1500] [--scale 2] [--background #12141c]\n\nSubcommands:\n materials Read shareable collaboration metrics, concurrency curve and material index (excludes withdrawn messages, private chats and flagged sensitive snippets, with truncation flags)\n render Export a local static HTML cover to a high-DPI PNG via an isolated, sandboxed browser from trusted system locations (private process pipe, no TCP debug port)\n\nOptions:\n --room ROOM Target room ID (defaults to the credential's room; pass another room ID to read cross-room)\n --site, --url SITE Site URL (must match the bound site when a task credential is present)\n --access-file FILE Task credential file (defaults to DISCUSS_ACCESS_FILE)\n --max-highlights N Max representative messages returned (default 12)\n --max-steps N Max concurrency-curve time buckets (default 240; peak-sampled above limit)\n --out, -o FILE Output PNG path for render (members with task credentials must write inside permitted directories or their own draft folder; manual terminal runs use the local user's OS permissions)\n --width N Render CSS width in px (default 750, range 320–1500)\n --height N Fixed render CSS height in px (auto-fits content when omitted)\n --max-height N Max render CSS height in px (default 1500, range 200–2400)\n --scale N Render pixel scale factor (default 2; 750×2 = 1500px wide)\n --background HEX Default render background color (default #12141c)\n --json Output JSON (default)\n -h, --help Show help\n",
687
707
  "未知子命令:{sub};运行 codiscuss share-card --help 查看用法": "Unknown subcommand: {sub}; run `codiscuss share-card --help` for usage",
708
+ "在提交封面 PNG 的同一条消息里,用 ```share-copy 代码块附上配套社交平台分享文案(标题、正文亮点、已上线产品链接、完整协作记录链接和标签)。若 share_link 为空,用 {{share_url}} 占位,分享面板选中该封面时会自动填入真实分享链接。": "In the same message as the cover PNG, include a ```share-copy code block with companion social-post copy (title, key highlights, deployed product links, full session share link and hashtags). When share_link is null, use {{share_url}} as a placeholder so the share dialog fills the live link when this cover is chosen.",
688
709
  "出于安全考虑,手机、平板等其他设备只能使用这台电脑“常用项目”里的目录,「{path}」不在其中,所以没有执行。请回到这台电脑上打开共议网页:在“新建房间”的项目目录里填入这个路径,点路径右侧的“加入常用项目”,之后其他设备就能直接选它;也可以加入它的上级目录。": "For security, phones, tablets and other devices can only use folders in this computer's “Saved projects”, and “{path}” is not one of them, so nothing was done. On this computer, open CoDiscuss, enter this path as the project folder under “New room”, then click “Add to saved projects” next to it; other devices can then pick it. You can also add a parent folder.",
689
710
  "出于安全考虑,其他设备只能查看这台电脑“常用项目”目录里的会话,「{path}」不在其中。请回到这台电脑上打开共议网页,在“新建房间”的项目目录里填入这个路径并点“加入常用项目”,之后再试。": "For security, other devices can only view sessions in this computer's “Saved projects” folders, and “{path}” is not one of them. On this computer, open CoDiscuss, enter this path as the project folder under “New room”, click “Add to saved projects”, then try again.",
711
+ "磁盘剩余空间仅 {available},低于安全线 {reserve},已停止派活。请先清理磁盘空间或运行 $codiscuss-draft-cleanup 清理旧草稿。": "Only {available} of disk space remains, below the {reserve} safety reserve. Dispatching has stopped. Free up disk space or run $codiscuss-draft-cleanup to clean old drafts.",
712
+ "磁盘剩余空间仅 {available},低于安全线 {reserve},已停止派活。请先清理磁盘空间;清理旧草稿请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup,或在管理面板“存储”页清理临时文件。": "Only {available} of disk space remains, below the {reserve} safety reserve. Dispatching has stopped. Free up disk space; to clean old drafts, run $codiscuss-draft-cleanup in an AI chat outside the room, or clear temporary files in the management panel Storage tab.",
713
+ "本机数据目录文件数超过 {limit} 上限(已扫到 {total},草稿 {draft}),按超限停止派活。请运行 $codiscuss-draft-cleanup 或 codiscuss service clean 清理后再继续。": "The local data folder exceeded the {limit}-file scan limit (scanned {total}, drafts {draft}). Dispatching has stopped. Run $codiscuss-draft-cleanup or codiscuss service clean to clean up before continuing.",
714
+ "本机数据目录文件数超过 {limit} 上限(已扫到 {total},草稿 {draft}),按超限停止派活。房间被拦截时请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup,或在管理面板“存储”页清理临时文件。": "The local data folder exceeded the {limit}-file scan limit (scanned {total}, drafts {draft}). Dispatching has stopped. While the room is blocked, run $codiscuss-draft-cleanup in an AI chat outside the room, or clear temporary files in the management panel Storage tab.",
715
+ "本房间草稿占用 {used},超过 {limit} 上限(目录 drafts/{room}),已停止派活。请运行 $codiscuss-draft-cleanup 清理可重建副本后再继续。": "This room's drafts use {used}, exceeding the {limit} limit (folder drafts/{room}). Dispatching has stopped. Run $codiscuss-draft-cleanup to remove rebuildable copies before continuing.",
716
+ "本房间草稿占用 {used},超过 {limit} 上限(目录 drafts/{room}),已停止派活。房间被拦截时请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 清理可重建副本,或在管理面板“存储”页清理临时文件。": "This room's drafts use {used}, exceeding the {limit} limit (folder drafts/{room}). Dispatching has stopped. While the room is blocked, run $codiscuss-draft-cleanup in an AI chat outside the room to remove rebuildable copies, or clear temporary files in the management panel Storage tab.",
717
+ "全机草稿占用 {used},超过 {limit} 上限(目录 drafts/),已停止派活。请运行 $codiscuss-draft-cleanup 清理旧草稿后再继续。": "Total drafts use {used}, exceeding the {limit} limit (folder drafts/). Dispatching has stopped. Run $codiscuss-draft-cleanup to clean old drafts before continuing.",
718
+ "全机草稿占用 {used},超过 {limit} 上限(目录 drafts/),已停止派活。请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 清理旧草稿,或在管理面板“存储”页清理临时文件。": "Total drafts use {used}, exceeding the {limit} limit (folder drafts/). Dispatching has stopped. Run $codiscuss-draft-cleanup in an AI chat outside the room to clean old drafts, or clear temporary files in the management panel Storage tab.",
719
+ "本机 .codiscuss 数据占用 {used}(不含语音模型),超过 {limit} 上限,已停止派活。请运行 $codiscuss-draft-cleanup 或 codiscuss service clean 清理旧草稿与旧房间后再继续。": "Local .codiscuss data uses {used} (excluding speech models), exceeding the {limit} limit. Dispatching has stopped. Run $codiscuss-draft-cleanup or codiscuss service clean to remove old drafts and rooms before continuing.",
720
+ "本机 .codiscuss 数据占用 {used}(不含语音模型;草稿 {draft},房间记录与附件 {local}),超过 {limit} 上限,已停止派活。房间记录与附件不会自动删除,请先销毁不需要的旧房间;清理旧草稿请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup。": "Local .codiscuss data uses {used} (excluding speech models; drafts {draft}, room records and attachments {local}), exceeding the {limit} limit. Dispatching has stopped. Room records and attachments are never deleted automatically—destroy old rooms you no longer need; to clean old drafts, run $codiscuss-draft-cleanup in an AI chat outside the room.",
721
+ "本机 .codiscuss 数据占用 {used}(不含语音模型;草稿 {draft}),超过 {limit} 上限,已停止派活。清理旧草稿请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup,或在管理面板“存储”页清理临时文件;若由房间记录与附件占满,请销毁旧房间。": "Local .codiscuss data uses {used} (excluding speech models; drafts {draft}), exceeding the {limit} limit. Dispatching has stopped. To clean old drafts, run $codiscuss-draft-cleanup in an AI chat outside the room or clear temporary files in the management panel Storage tab; if room records and attachments fill the limit, destroy old rooms.",
722
+ "本机 .codiscuss 数据已占 {used}(不含语音模型),接近 {limit} 上限(预警线 {warn})。建议运行 $codiscuss-draft-cleanup 或 codiscuss service clean 及时清理。": "Local .codiscuss data uses {used} (excluding speech models), approaching the {limit} limit (warning at {warn}). Run $codiscuss-draft-cleanup or codiscuss service clean to free space.",
723
+ "本机 .codiscuss 数据已占 {used}(不含语音模型,另有 {unreadable} 处因权限无法读取未计入),接近 {limit} 上限(预警线 {warn})。请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 或在管理面板“存储”页清理临时文件。": "Local .codiscuss data uses {used} (excluding speech models; {unreadable} unreadable entries excluded), approaching the {limit} limit (warning at {warn}). Run $codiscuss-draft-cleanup in an AI chat outside the room or clear temporary files in the management panel Storage tab.",
724
+ "本机 .codiscuss 数据已占 {used}(不含语音模型),接近 {limit} 上限(预警线 {warn})。请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 或在管理面板“存储”页清理临时文件。": "Local .codiscuss data uses {used} (excluding speech models), approaching the {limit} limit (warning at {warn}). Run $codiscuss-draft-cleanup in an AI chat outside the room or clear temporary files in the management panel Storage tab.",
725
+ "磁盘余量下降后复扫发现不可读项增至 {count} 处,已暂停派活,下次扫描将重新判断。": "After free disk space dropped, the number of unreadable entries rose to {count}. Dispatch is paused until the next scan reassesses usage.",
726
+ "本房间草稿已用 {used}(上限 {limit}),达到 80%,已暂停向无法确认可停止的成员派活。请先清理本房间草稿。": "Room drafts use {used} of {limit}, reaching the 80% threshold. New runs without confirmed stop support are paused. Clear room drafts first.",
727
+ "无法检查本机存储与磁盘空间,已暂停派活({reason})。请检查 .codiscuss 目录权限或稍后重试。": "Could not check local storage or disk space; dispatching is paused ({reason}). Check permissions on .codiscuss or retry shortly.",
728
+ "未知错误": "Unknown error",
690
729
  };
@@ -195,7 +195,7 @@ function secure_secret(secret) {
195
195
  * The user is an ordinary member of Users. It gets modify rights on the account's folder only; the owner's own profile
196
196
  * stays closed to it, and Windows lets it reach its folder inside that profile without listing anything on the way.
197
197
  */
198
- export function create_os_user(data, account, account_folder, { run = run_powershell } = {}) {
198
+ export function create_os_user(data, account, account_folder, { run = run_powershell, project_data_root = '' } = {}) {
199
199
  const user = os_user_name(account);
200
200
  if (read_os_users(data)[account]) throw new Error(`账号 ${account} 已有 Windows 用户 ${user}`);
201
201
  const password = `Cd!${randomBytes(18).toString('base64url')}`;
@@ -208,6 +208,9 @@ if (-not (Get-LocalGroupMember -Group 'Users' -Member ${quote(user)} -ErrorActio
208
208
  # Once the other drives are closed to hosted accounts (restrict_other_drives), a new account is closed out too.
209
209
  if ((Get-LocalGroup -Name ${quote(HOSTED_GROUP)} -ErrorAction SilentlyContinue) -and -not (Get-LocalGroupMember -Group ${quote(HOSTED_GROUP)} -Member ${quote(user)} -ErrorAction SilentlyContinue)) { Add-LocalGroupMember -Group ${quote(HOSTED_GROUP)} -Member ${quote(user)} }
210
210
  icacls ${quote(account_folder)} /grant ${quote(`${user}:(OI)(CI)M`)} /T /C /Q | Out-Null
211
+ ${project_data_root ? `if ((Get-Item -LiteralPath ${quote(project_data_root)} -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid project root' }
212
+ icacls ${quote(project_data_root)} /grant:r ${quote(`${user}:(OI)(CI)M`)} /Q | Out-Null
213
+ if ($LASTEXITCODE -ne 0) { throw '无法设置项目目录权限 / Failed to grant project access' }` : ''}
211
214
  ${register_task_script(account, user, '$secure', owner_sid({ run }))}
212
215
  'ok'`, { elevated: true });
213
216
  write_os_users(data, { ...read_os_users(data), [account]: { user, secret } });
@@ -386,6 +389,7 @@ while ($parent) {
386
389
  if (-not $next -or $next -eq $parent) { break }
387
390
  $parent = $next
388
391
  }
392
+
389
393
  if (Test-Path -LiteralPath $path) {
390
394
  if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "受保护目录 $path 是一个链接,已停止" }
391
395
  } else { New-Item -ItemType Directory -Path $path | Out-Null }
@@ -419,6 +423,34 @@ foreach ($rule in $read.Access) {
419
423
  'ok'`);
420
424
  }
421
425
 
426
+ function project_acl(script) {
427
+ const encoded = Buffer.from(`[Console]::OutputEncoding = [Text.Encoding]::UTF8
428
+ $ErrorActionPreference = 'Stop'
429
+ try { ${script} } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }`, 'utf16le').toString('base64');
430
+ const result = spawnSync(POWERSHELL, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, encoding: 'utf8' });
431
+ if (result.status !== 0) throw new Error(result.error?.message || result.stderr || 'Project ACL failed');
432
+ }
433
+
434
+ /** Refuse to copy while a detached editor, AI CLI or any other process still runs as the tenant. */
435
+ export function require_idle_os_user(user, { run = run_powershell } = {}) {
436
+ run(`$account = "$env:COMPUTERNAME\\" + ${quote(user)}
437
+ $active = @(Get-Process -IncludeUserName -ErrorAction Stop | Where-Object UserName -eq $account)
438
+ if ($active.Count) { throw ("请先结束账号进程 / Close tenant processes: " + ($active.ProcessName -join ', ')) }`, { elevated: true });
439
+ }
440
+
441
+ /** Seal a newly allocated project directory before creating any account files in it. */
442
+ export function secure_project_root(path, user = '', { run = project_acl } = {}) {
443
+ if (process.platform !== 'win32') return;
444
+ run(`$drive = [IO.Path]::GetPathRoot(${quote(path)})
445
+ $denied = (Get-Acl -LiteralPath $drive).Access | Where-Object {
446
+ $_.AccessControlType -eq 'Deny' -and ($_.IdentityReference.Value -split '\\\\')[-1] -eq ${quote(HOSTED_GROUP)}
447
+ }
448
+ if ($denied) { throw '托管账号已被禁止访问该卷 / Hosted accounts are blocked on this volume' }`);
449
+ secure_folder(path, [], { run });
450
+ if (user) run(`icacls ${quote(path)} /grant:r ${quote(`${user}:(OI)(CI)M`)} /Q | Out-Null
451
+ if ($LASTEXITCODE -ne 0) { throw '无法设置项目目录权限 / Failed to grant project access' }`);
452
+ }
453
+
422
454
  /** The shared folder, made one that only the owner can change: every account may read and run what is in it. */
423
455
  export function secure_shared_root({ root = SHARED_ROOT, run = run_powershell } = {}) {
424
456
  return secure_folder(root, [`(New-Object Security.Principal.SecurityIdentifier('${USERS_SID}'))`], { run });
@@ -160,8 +160,14 @@ function search_result(query, searches) {
160
160
  }
161
161
 
162
162
  /** The room's project directories: the main one (`cwd`) first, then the extra ones in the order they were added. */
163
+ export function room_directory_entries(config) {
164
+ return [config.cwd, ...(config.extra_directories || [])].filter(Boolean)
165
+ .map(item => typeof item === 'string' ? { path: item, access: 'write' } : item);
166
+ }
167
+
168
+ /** Project paths in room order, including legacy string-only entries. */
163
169
  export function room_directories(config) {
164
- return [config.cwd, ...(config.extra_directories || [])].filter(Boolean);
170
+ return room_directory_entries(config).map(item => item.path);
165
171
  }
166
172
 
167
173
  /** Whether `directory` is one of the room's project directories or lies inside one; Windows paths compare without case. */
@@ -0,0 +1,245 @@
1
+ /** Filesystem phase of a hosted project move. Isolated accounts run this file as their own OS user. */
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { spawnSync } from 'node:child_process';
4
+ import { lstat, mkdir, readdir, realpath, rename, rmdir, symlink, unlink, utimes, writeFile } from 'node:fs/promises';
5
+ import { createReadStream, createWriteStream, readFileSync } from 'node:fs';
6
+ import { dirname, join, relative, resolve } from 'node:path';
7
+ import { pipeline } from 'node:stream/promises';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ async function info(path) {
11
+ try { return await lstat(path); } catch (error) { if (error.code !== 'ENOENT') throw error; }
12
+ }
13
+
14
+ async function digest(path) {
15
+ const hash = createHash('sha256');
16
+ for await (const block of createReadStream(path)) hash.update(block);
17
+ return hash.digest('hex');
18
+ }
19
+
20
+ async function copy_verified(source, target) {
21
+ const from = await info(source), to = await info(target);
22
+ if (from?.isDirectory() && (!to || to.isDirectory())) {
23
+ if (!to) await mkdir(target);
24
+ const names = (await readdir(source)).sort();
25
+ for (const name of names) await copy_verified(join(source, name), join(target, name));
26
+ for (const folder of [source, target]) {
27
+ if (JSON.stringify(names) !== JSON.stringify((await readdir(folder)).sort())) throw new Error('目录内容已变化 / Directory contents changed: ' + folder);
28
+ }
29
+ return;
30
+ }
31
+ if (!from?.isFile() || (to && (!to.isFile() || to.nlink !== 1))) throw new Error('无法迁移链接或特殊文件 / Unsupported link or special file: ' + source);
32
+ // Create the file under the destination ACL. Files from the old volume may have explicit grants.
33
+ await pipeline(createReadStream(source), createWriteStream(target, { flags: to ? 'w' : 'wx', mode: from.mode & 0o700 }));
34
+ if (await digest(source) !== await digest(target)) throw new Error('文件校验失败 / File verification failed: ' + source);
35
+ await utimes(target, from.atime, from.mtime);
36
+ }
37
+
38
+ /** Resume from deterministic backups after interruption. Prior absolute room paths resolve through directory junctions. */
39
+ export function migration_folders({ service, previous, target, id }) {
40
+ return ['projects', 'workspace', 'drafts'].map(name => {
41
+ const source = join(previous || (name === 'drafts' ? service : dirname(service)), name);
42
+ // Keep all backups beside the running service, including legacy member drafts.
43
+ const backup = join(previous || dirname(service), name + '.before-' + id);
44
+ return { name, source, backup, destination: join(target, name) };
45
+ });
46
+ }
47
+
48
+ export async function move_project_files(job) {
49
+ const { service, target } = job;
50
+ const settings_file = join(service, 'local-settings.json');
51
+ const settings = JSON.parse(readFileSync(settings_file, 'utf8'));
52
+ const folders = migration_folders(job);
53
+ const old_drafts_backup = folders[2].source + '.before-' + job.id;
54
+ if (relative(old_drafts_backup, folders[2].backup) && await info(old_drafts_backup)) {
55
+ throw new Error('发现未登记的旧备份,请人工核对 / Older backup requires manual review: ' + old_drafts_backup);
56
+ }
57
+ if (relative(settings.projects_root, folders[0].source) || relative(settings.workspace, folders[1].source)) {
58
+ if (settings.project_data_root && !relative(settings.project_data_root, target)) return migration_receipts(folders);
59
+ throw Object.assign(new Error('账号配置与迁移记录不符 / Unexpected account paths'), { rolled_back: true });
60
+ }
61
+ try {
62
+ await switch_folders(folders);
63
+ const receipts = await migration_receipts(folders);
64
+ const temp = join(service, 'local-settings.' + randomUUID() + '.tmp');
65
+ await writeFile(temp, JSON.stringify({ ...settings, project_data_root: target, workspace: join(target, 'workspace'), projects_root: join(target, 'projects') }, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
66
+ await rename(temp, settings_file);
67
+ return receipts;
68
+ } catch (error) {
69
+ for (const { source, backup, destination } of folders.reverse()) {
70
+ const old = await info(source);
71
+ if (old?.isSymbolicLink() && !relative(await realpath(source), destination)) await unlink(source);
72
+ if (!(await info(source)) && await info(backup)) await rename(backup, source);
73
+ }
74
+ error.rolled_back = true;
75
+ throw error;
76
+ }
77
+ }
78
+
79
+ async function switch_folders(folders) {
80
+ for (const { source, backup, destination } of folders) {
81
+ const old = await info(source), saved = await info(backup);
82
+ if (old?.isSymbolicLink() && !relative(await realpath(source), destination)) continue;
83
+ if (old && (!old.isDirectory() || saved)) throw new Error('源目录冲突 / Source folder conflict: ' + source);
84
+ if (old) await rename(source, backup);
85
+ if (old || saved) await copy_verified(backup, destination);
86
+ else if (!(await info(destination))) await mkdir(destination);
87
+ await symlink(destination, source, 'junction');
88
+ }
89
+ }
90
+
91
+ async function checked_root(path) {
92
+ if (relative(await realpath(path), resolve(path))) throw new Error('目录路径已重定向 / Directory redirected: ' + path);
93
+ }
94
+
95
+ async function inventory(root, hash_files) {
96
+ await checked_root(root);
97
+ const entries = [];
98
+ async function visit(key) {
99
+ const path = join(root, key), stat = await lstat(path, { bigint: true });
100
+ if (!stat.isDirectory() && (!stat.isFile() || stat.nlink !== 1n)) throw new Error('备份含链接或特殊文件 / Link or special file: ' + path);
101
+ const folder = stat.isDirectory();
102
+ entries.push({ key, identity: stat.dev + '/' + stat.ino, folder, bytes: folder ? 0 : Number(stat.size),
103
+ ...(!hash_files && !folder && stat.blocks !== undefined ? { allocated: Number(stat.blocks) * 512 } : {}),
104
+ ...(hash_files && !folder ? { hash: await digest(path) } : {}) });
105
+ if (folder) for (const child of (await readdir(path)).sort()) await visit(join(key, child));
106
+ }
107
+ await visit('');
108
+ return entries;
109
+ }
110
+
111
+ function require_match(actual, expected, subset = false) {
112
+ const by_key = new Map(expected.map(entry => [entry.key, entry]));
113
+ if ((!subset && actual.length !== expected.length) || actual.some(entry => JSON.stringify(entry) !== JSON.stringify(by_key.get(entry.key)))) {
114
+ throw new Error('目录与迁移校验记录不一致,已保留 / Directory differs from the migration record');
115
+ }
116
+ }
117
+
118
+ async function check_link({ source, destination }) {
119
+ if (!(await info(source))?.isSymbolicLink() || relative(await realpath(source), destination)) {
120
+ throw new Error('旧房间联接已变化 / Room directory junction changed: ' + source);
121
+ }
122
+ }
123
+
124
+ /** Node hashes the default data stream. Keep Windows originals containing any additional streams. */
125
+ function windows_stream_bytes(root, entries, inspecting = false) {
126
+ if (process.platform !== 'win32') return;
127
+ const script = `$ErrorActionPreference = 'Stop'
128
+ [Console]::InputEncoding = [Text.Encoding]::UTF8
129
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
130
+ Add-Type -TypeDefinition @'
131
+ using System;
132
+ using System.ComponentModel;
133
+ using System.Runtime.InteropServices;
134
+ using Microsoft.Win32.SafeHandles;
135
+ public static class BackupStreams {
136
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
137
+ struct StreamInfo { public long size; [MarshalAs(UnmanagedType.ByValTStr, SizeConst=296)] public string name; }
138
+ [DllImport("kernel32", CharSet=CharSet.Unicode, SetLastError=true)] static extern IntPtr FindFirstStreamW(string path, int level, out StreamInfo item, int flags);
139
+ [DllImport("kernel32", CharSet=CharSet.Unicode, SetLastError=true)] static extern bool FindNextStreamW(IntPtr handle, out StreamInfo item);
140
+ [DllImport("kernel32")] static extern bool FindClose(IntPtr handle);
141
+ [DllImport("kernel32", CharSet=CharSet.Unicode, SetLastError=true)] static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
142
+ [DllImport("kernel32", SetLastError=true)] static extern bool GetFileInformationByHandleEx(SafeFileHandle file, int kind, IntPtr buffer, uint size);
143
+ static long Allocation(string path) {
144
+ using (var file = CreateFileW(path, 128, 7, IntPtr.Zero, 3, 0x02000000, IntPtr.Zero)) {
145
+ if (file.IsInvalid) throw new Win32Exception(Marshal.GetLastWin32Error());
146
+ var buffer = Marshal.AllocHGlobal(24);
147
+ try {
148
+ if (!GetFileInformationByHandleEx(file, 1, buffer, 24)) throw new Win32Exception(Marshal.GetLastWin32Error());
149
+ return Marshal.ReadInt64(buffer);
150
+ } finally { Marshal.FreeHGlobal(buffer); }
151
+ }
152
+ }
153
+ public static long Check(string path, bool inspecting) {
154
+ long bytes = 0;
155
+ StreamInfo item;
156
+ IntPtr handle = FindFirstStreamW(path, 0, out item, 0);
157
+ if (handle != new IntPtr(-1)) {
158
+ try {
159
+ do {
160
+ if (item.name != "::$DATA" && !inspecting) throw new Exception("Named data stream: " + path);
161
+ if (inspecting) bytes += Allocation(item.name == "::$DATA" ? path : path + item.name);
162
+ } while (FindNextStreamW(handle, out item));
163
+ int end = Marshal.GetLastWin32Error();
164
+ if (end != 38) throw new Win32Exception(end);
165
+ } finally { FindClose(handle); }
166
+ } else {
167
+ int error = Marshal.GetLastWin32Error();
168
+ if (error != 38) throw new Win32Exception(error);
169
+ }
170
+ return bytes;
171
+ }
172
+ }
173
+ '@
174
+ try {
175
+ [long]$bytes = 0
176
+ foreach ($path in (ConvertFrom-Json ([Console]::In.ReadToEnd()))) { $bytes += [BackupStreams]::Check($path, ${inspecting ? '$true' : '$false'}) }
177
+ [Console]::WriteLine($bytes)
178
+ } catch { [Console]::Error.WriteLine($_.Exception.Message); exit 1 }`;
179
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')],
180
+ { windowsHide: true, input: JSON.stringify(entries.map(entry => join(root, entry.key))), encoding: 'utf8' });
181
+ if (result.status !== 0) throw new Error('无法验证 Windows 数据流,备份已保留 / Cannot certify Windows streams: ' + (result.error?.message || result.stderr));
182
+ return Number(result.stdout.trim());
183
+ }
184
+
185
+ async function migration_receipts(folders) {
186
+ const receipts = {};
187
+ for (const folder of folders) {
188
+ if (!await info(folder.backup)) continue;
189
+ await check_link(folder);
190
+ const backup = await inventory(folder.backup, true), target = await inventory(folder.destination, true);
191
+ const content = rows => rows.map(({ identity, ...rest }) => rest);
192
+ require_match(content(backup), content(target));
193
+ receipts[folder.name] = { backup, target };
194
+ }
195
+ return receipts;
196
+ }
197
+
198
+ /** Operate on one owner-recorded backup. A partially released tree may only contain original verified entries. */
199
+ export async function backup_operation(request) {
200
+ const { record, kind, action, releasing } = request;
201
+ const folder = migration_folders(request).find(item => item.name === kind);
202
+ if (!folder || !record?.backup?.length) throw new Error('缺少迁移记录 / Missing migration record');
203
+ const { backup, destination } = folder;
204
+ if (action !== 'list') {
205
+ await check_link(folder);
206
+ await checked_root(destination);
207
+ const root = await lstat(destination, { bigint: true }), receipt = record.target?.[0];
208
+ if (receipt?.key !== '' || receipt.folder !== true || !root.isDirectory() || receipt.identity !== root.dev + '/' + root.ino) {
209
+ throw new Error('目标目录身份已变化 / Destination directory identity changed');
210
+ }
211
+ }
212
+ await checked_root(dirname(backup));
213
+ const present = await info(backup);
214
+ if (!present && releasing) return { bytes: 0, allocated_bytes: 0, path: backup };
215
+ if (!present) throw new Error('找不到已登记的备份 / Recorded backup missing: ' + backup);
216
+ const entries = await inventory(backup, action !== 'list');
217
+ if (entries[0].identity !== record.backup[0].identity) throw new Error('备份目录身份已变化 / Backup directory identity changed');
218
+ if (action === 'list') return { path: backup, bytes: entries.reduce((sum, entry) => sum + entry.bytes, 0),
219
+ allocated_bytes: windows_stream_bytes(backup, entries, true) ?? entries.reduce((sum, entry) => sum + (entry.allocated || 0), 0) };
220
+ require_match(entries, record.backup, releasing);
221
+ windows_stream_bytes(backup, entries);
222
+ if (action === 'release' && releasing) {
223
+ for (const entry of entries.reverse()) {
224
+ const path = join(backup, entry.key);
225
+ await checked_root(path);
226
+ const current = await lstat(path, { bigint: true });
227
+ if (entry.identity !== current.dev + '/' + current.ino || (!entry.folder && entry.hash !== await digest(path))) {
228
+ throw new Error('备份已变化 / Backup changed: ' + path);
229
+ }
230
+ if (entry.folder) await rmdir(path);
231
+ else await unlink(path);
232
+ }
233
+ }
234
+ return { path: backup };
235
+ }
236
+
237
+ if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
238
+ try {
239
+ const request = JSON.parse(readFileSync(process.argv[2], 'utf8'));
240
+ console.log(JSON.stringify({ result: request.action ? await backup_operation(request) : await move_project_files(request) }));
241
+ } catch (error) {
242
+ console.log(JSON.stringify({ error: error.message, rolled_back: error.rolled_back === true }));
243
+ process.exitCode = 1;
244
+ }
245
+ }
@@ -47,7 +47,7 @@ const FRAME_MAX_BYTES = 1024 * 1024 - 1024;
47
47
  // filled with large answers (images) holds back every other answer and the heartbeat behind them.
48
48
  const BACKLOG_LOG_BYTES = 4 * 1024 * 1024;
49
49
  const BACKLOG_LOG_MS = 60000;
50
- const ROOM_API_PATH = /^\/api\/(rooms|folders|revisions)(\/[A-Za-z0-9_.~-]+)*(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
50
+ const ROOM_API_PATH = /^\/api\/(rooms|folders|revisions|sites)(\/[A-Za-z0-9_.~-]+)*(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
51
51
  const RELAY_READ_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
52
52
  // Attachment uploads arrive in parts and are sent to the local website whole, as one browser upload would be.
53
53
  const UPLOAD_PATH = /^\/api\/rooms\/[A-Za-z0-9_-]+\/attachments(\/[A-Za-z0-9_-]+\/import)?(\?[A-Za-z0-9_.~%=&,:+-]*)?$/;
@@ -31,7 +31,7 @@ const LAUNCH_SCRIPT = fileURLToPath(new URL('./discussion_launch.mjs', import.me
31
31
  // What a connected browser may ask the local bridge for, minus the folder dialog nobody would see and pairing itself.
32
32
  export const RELAYED_ACTIONS = new Set(['settings', 'launch', 'wipe-histories', 'room-models', 'room-member', 'room-member-access', 'room-member-allow', 'room-member-adapter',
33
33
  'room-member-model', 'room-profiles', 'room-skills', 'room-files', 'share-job', 'room-page', 'room-media', 'execution-details', 'room-restore', 'room-fork', 'models', 'sessions', 'api-key', 'api-check', 'scheduler-check', 'image-check', 'image-settings', 'tts-settings', 'tts', 'tts-release', 'local-speech', 'stt', 'weixin', 'projects', 'presets', 'workflows', 'room-workflow', 'room-settings', 'browse-directory', 'room-invite', 'room-invites', 'room-invite-revoke',
34
- 'site-stage', 'site-publish', 'site-list', 'site-diagnose', 'site-renew', 'site-rollback', 'site-revoke',
34
+ 'storage', 'storage-clean', 'site-stage', 'site-publish', 'site-list', 'site-diagnose', 'site-renew', 'site-rollback', 'site-revoke',
35
35
  // Rooms on other computers this one was invited to (runner/external_client.mjs): its paired devices manage them as here.
36
36
  'invited-list', 'invited-join', 'invited-trust', 'invited-ai', 'invited-pause', 'invited-approve', 'invited-refuse', 'invited-lend', 'invited-leave', 'invited-remove', 'invited-room']);
37
37
  export const ROOM_ACTIONS = new Set(['launch', 'room-models', 'room-member', 'room-member-access', 'room-member-allow', 'room-member-adapter',
@@ -250,9 +250,10 @@ export async function unseal(key, envelope, label) {
250
250
  /** Turn a relayed action into the local entrypoint call the local website makes, pinned to the relaying site. */
251
251
  export function relayed_command(site, action, payload) {
252
252
  if (!RELAYED_ACTIONS.has(action)) throw new Error('该操作不能经其他设备执行');
253
- if (payload === undefined ? action !== 'settings' : !payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('命令内容无效');
253
+ if (payload === undefined ? !['settings', 'storage'].includes(action) : !payload || typeof payload !== 'object' || Array.isArray(payload)) throw new Error('命令内容无效');
254
254
  let input = payload;
255
- if (ROOM_ACTIONS.has(action)) {
255
+ if (['presets', 'workflows'].includes(action) && (payload?.cwd || payload?.extra_directories?.length)) throw new Error('其他设备须使用项目编号或房间编号');
256
+ if (ROOM_ACTIONS.has(action) || (action === 'presets' && payload.room_id)) {
256
257
  const { access_file, ...rest } = payload;
257
258
  input = { ...rest, site, entry: 'web' };
258
259
  }
@@ -9,6 +9,7 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync,
9
9
  import { createServer } from 'node:http';
10
10
  import { tmpdir } from 'node:os';
11
11
  import { basename, dirname, extname, isAbsolute, join, relative, resolve } from 'node:path';
12
+ import { drafts_root } from './account_space.mjs';
12
13
  import { setTimeout as delay } from 'node:timers/promises';
13
14
  import { parseArgs } from 'node:util';
14
15
 
@@ -397,6 +398,15 @@ export async function share_card_materials({
397
398
  .map((item) => ({ site_id: item.site_id, title: item.title || '', url: item.url, status: item.status, expires_at: item.expires_at || '' }));
398
399
  } catch { /* Sites endpoint is optional on older or minimal servers. */ }
399
400
 
401
+ let share_link = null;
402
+ try {
403
+ const directory = await room_json(resolved_site, '/api/rooms', request_headers, fetcher);
404
+ const listed = (directory.rooms || []).find((item) => item.id === target_room);
405
+ if (listed?.share_link?.url) {
406
+ share_link = { url: listed.share_link.url, expires_at: listed.share_link.expires_at || '' };
407
+ }
408
+ } catch { /* Directory lookup is optional when reading minimal endpoints. */ }
409
+
400
410
  const room_entry = find_room_config(home, target_room, resolved_site);
401
411
  const project_patterns = compile_project_patterns(collect_known_folders(room_entry, [room, [...by_exec_key.values()]], folders));
402
412
 
@@ -562,11 +572,17 @@ export async function share_card_materials({
562
572
  attachments_by_kind: [...kind_counts.values()],
563
573
  attachments,
564
574
  sites,
575
+ share_link,
565
576
  },
566
577
  cover_spec: {
567
578
  ...SHARE_CARD_COVER_SPEC,
568
579
  note: t('分享面板会自动在封面下方拼接统一的扫码底栏(二维码、域名和最新有效期),并可吸取封面底边颜色;封面 HTML 中请勿绘制二维码、分享链接或有效期。'),
569
580
  },
581
+ copy_spec: {
582
+ fence: 'share-copy',
583
+ share_url_placeholder: '{{share_url}}',
584
+ note: t('在提交封面 PNG 的同一条消息里,用 ```share-copy 代码块附上配套社交平台分享文案(标题、正文亮点、已上线产品链接、完整协作记录链接和标签)。若 share_link 为空,用 {{share_url}} 占位,分享面板选中该封面时会自动填入真实分享链接。'),
585
+ },
570
586
  };
571
587
  }
572
588
 
@@ -624,7 +640,7 @@ function member_hash_dir(name) {
624
640
 
625
641
  function service_drafts_dir(home, runtime_dir) {
626
642
  const key = createHash('sha256').update(resolve(runtime_dir)).digest('hex');
627
- return join(home, 'drafts', key);
643
+ return join(drafts_root(home), key);
628
644
  }
629
645
 
630
646
  function push_real_dir(list, dir) {
@@ -357,6 +357,22 @@ export function create_share_core({ t, display_name, collapse_visual_fences, is_
357
357
  return String(text || "").replace(/```[\s\S]*?```/g, " ").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[`*_>#|~-]+/g, " ").replace(/\s+/g, " ").trim();
358
358
  }
359
359
 
360
+ /** One concise lead sentence (or two short ones) from the opening paragraph, leaving bullet checklists and prompt tails off the card. */
361
+ function share_card_lead(text, max_chars = 160) {
362
+ const first_para = String(text || "").replace(/\r\n/g, "\n").trim()
363
+ .split(/\n\s*\n|\n\s*(?:[-*•]|\d+[.)、])\s+/)[0];
364
+ const clean = share_plain(first_para).replace(/^(?:@\S+\s+)+/, "").trim();
365
+ if (!clean) return "";
366
+ const sentences = clean.match(/[^。!?.!?]+(?:[。!?]|[.!?](?=\s|$)|$)/gu) || [];
367
+ const first = sentences[0]?.trim() || "";
368
+ if (!first) return clean.slice(0, max_chars);
369
+ if (first.length < 10 && sentences[1]) {
370
+ const two = `${first}${/[a-zA-Z0-9.!?]$/.test(first) ? " " : ""}${sentences[1].trim()}`;
371
+ if (two.length <= max_chars) return two;
372
+ }
373
+ return first.slice(0, max_chars);
374
+ }
375
+
360
376
  function share_card_messages(responses) {
361
377
  return Object.entries(responses).filter(([path]) => /\/messages\?/.test(path)).flatMap(([, body]) => body.messages || [])
362
378
  .filter(message => message.kind !== "system" && message.text).sort((a, b) => a.id - b.id);
@@ -372,19 +388,20 @@ export function create_share_core({ t, display_name, collapse_visual_fences, is_
372
388
  const room = draft.responses[`/api/rooms/${draft.room_id}`] || {};
373
389
  const members = (room.members || []).filter(member => member.status !== "removed").map(member => member.label || display_name(member.name));
374
390
  const messages = share_card_messages(draft.responses);
375
- const question = messages.find(message => message.author === "用户" && !is_share_question_receipt(message.text)
376
- && !/^\/?(?:继续|好的?|同意|continue|ok)[。.!!\s]*$/iu.test(message.text.trim()));
391
+ const question = messages.find(message => {
392
+ if (message.author !== "用户") return false;
393
+ const body = String(message.text || "").trim();
394
+ if (!body || is_share_question_receipt(body) || /^\/(?:goal|discuss)\b/i.test(body)) return false;
395
+ return !/^\/?(?:继续|好的?|行|ok|yes|收到|同意|开始|可以|确认|嗯|明白|go|continue)[。.!!,,\s]*$/iu.test(body);
396
+ });
377
397
  const answers = messages.filter(message => message.author !== "用户" && message.author !== "系统" && message.id > (question?.id ?? 0));
378
398
  const outcome = answers.findLast(message => message.summary) || answers.at(-1);
379
399
  // Text the owner was asked to check stays off the card, which cannot be taken back once posted; it can be typed in.
380
400
  const flagged = new Set((draft.spots || []).map(spot => spot.where));
381
- const text = (message, value) => message && !flagged.has(`#${message.id}`) ? share_plain(value) : "";
382
- const result = text(outcome, outcome?.summary || outcome?.text);
383
- const sentences = result.match(/[^。!?.!?]+(?:[。!?]|[.!?](?=\s|$)|$)/gu) || [];
384
- const complete = sentences[0]?.trim();
385
- return { title: draft.title, members, materials: { through: messages.at(-1)?.id ?? null, count: messages.length },
386
- question: text(question, question?.text).slice(0, 600),
387
- outcome: (complete && result.startsWith(complete) ? complete : result).slice(0, 600),
401
+ const lead = (message, value, limit) => message && !flagged.has(`#${message.id}`) ? share_card_lead(value, limit) : "";
402
+ return { title: draft.title, members, card_version: 2, materials: { through: messages.at(-1)?.id ?? null, count: messages.length },
403
+ question: lead(question, question?.text, 160),
404
+ outcome: lead(outcome, outcome?.summary || outcome?.text, 200),
388
405
  stats: t('{members} 位 AI · {messages} 条消息 · {runs} 次执行', { members: members.length, messages: room.message_count ?? messages.length, runs: draft.runs ?? 0 }),
389
406
  url: link.url, expires: t('{time} 前有效', { time: new Date(link.expires_at).toLocaleString(undefined, { hour12: false }) }) };
390
407
  }
@@ -5,6 +5,7 @@
5
5
  import { createHash, randomBytes } from 'node:crypto';
6
6
  import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
7
7
  import { basename, extname, isAbsolute, join, relative, resolve } from 'node:path';
8
+ import { drafts_root } from './account_space.mjs';
8
9
  import { parseArgs } from 'node:util';
9
10
 
10
11
  import { configuration_snapshot, read_registry, service_home } from './discussion_service.mjs';
@@ -219,7 +220,7 @@ function room_allowed_roots(config, home) {
219
220
  // Not `config.directory`: that is the launch's runtime folder, holding task files and member credentials.
220
221
  }
221
222
  // Draft directory for member-generated HTML files
222
- add(join(home, 'drafts'));
223
+ add(drafts_root(home));
223
224
  return roots;
224
225
  }
225
226
 
@@ -8,10 +8,21 @@
8
8
  const SLASH_NAME = /(?:^|[\s((,,。;;::])\/([A-Za-z0-9][\w:.-]*)(?![\w:/-])/gu;
9
9
 
10
10
  /** What the "/" menu inserts for a workflow or sub-workflow ID, with a space for the text that follows. */
11
- export function slash_insertion(id) {
11
+ export function slash_insertion(id, target) {
12
+ if (target?.scope === 'global') return `/global:${id} `;
13
+ if (target?.scope === 'project' && target.project_id) return `/project:${target.project_id}:${id} `;
12
14
  return `/${id} `;
13
15
  }
14
16
 
17
+ /** Decode a scoped menu choice or a bare workflow name. */
18
+ export function parse_slash_workflow(token) {
19
+ const name = String(token).trim().replace(/^\//, '');
20
+ const parts = name.split(':');
21
+ if (parts.length === 2 && parts[0] === 'global' && parts[1]) return { id: parts[1], scope: 'global', project_id: '' };
22
+ if (parts.length === 3 && parts[0] === 'project' && parts[1] && parts[2]) return { id: parts[2], scope: 'project', project_id: parts[1] };
23
+ return { id: name, scope: '', project_id: '' };
24
+ }
25
+
15
26
  /** The names a message gives with "/", outside code and quotes, each once in order of appearance. */
16
27
  export function slash_names(text) {
17
28
  const prose = String(text || '').replace(/```[\s\S]*?```/g, '').replace(/`[^`\n]*`/g, '').replace(/^>.*$/gm, '');
@@ -0,0 +1,20 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+
4
+ const programs = { tts: 'yovoice', stt: 'crispasr' };
5
+
6
+ /** Resolve the installation used by this computer. Installers record each chosen parent independently. */
7
+ export function speech_directory(home, id) {
8
+ const program = programs[id];
9
+ let parent;
10
+ try { parent = readFileSync(join(home, program + '-root.txt'), 'utf8').trim(); }
11
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
12
+ if (parent && !isAbsolute(parent)) throw new Error('Invalid absolute path in ' + program + '-root.txt');
13
+ return resolve(parent || home, program);
14
+ }
15
+
16
+ /** Return unique active and legacy installation paths for on-disk usage accounting. */
17
+ export function speech_model_directories(home) {
18
+ return Object.entries(programs).flatMap(([id, program]) =>
19
+ [...new Set([speech_directory(home, id), resolve(home, program)])].map(path => ({ id, program, path })));
20
+ }