agent-loft 0.2.64 → 0.2.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -27,7 +27,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
27
27
  |---|---|---|
28
28
  | 🤖 | **同时管理多个 agent** | Claude Code(官方 Claude Agent SDK)和 Codex(官方 `codex app-server`)共用会话列表、工作目录和授权。新建对话时选专家:内置的 Claude Code / Codex,或者自己配的专家 |
29
29
  | 🧑‍🏫 | **专家** | 自己配专家:选引擎、写提示词,定它能做什么(只能联网 / 读文件 / 改文件 / 跑命令),挂哪些技能和 MCP,能把活派给哪些子智能体。新对话、定时任务都能选 |
30
- | 🔀 | **飞书机器人灵活绑定 agent** | 机器人数量不限,每个机器人可以只对应一个 agent,也可以对应多个(在会话里切换)。网页上扫码就能创建,改完立即生效;由服务端主动连向飞书,家里没有公网 IP 也能在外面用 |
30
+ | 🔀 | **飞书机器人灵活绑定 agent** | 机器人数量不限,每个机器人可以直接勾选内置或共享专家,并选择默认专家(可在会话里切换)。网页上扫码就能创建,改完立即生效;由服务端主动连向飞书,家里没有公网 IP 也能在外面用 |
31
31
  | 🔗 | **飞书续接 Web 任务** | 飞书里发 `/web` 接上一条 Web 会话,或者在网页侧栏右键会话选「在飞书继续…」。之后回复、授权、提问都发到飞书,发 `/detach` 回来 |
32
32
  | 🖥️ | **完整的 Web 工作台** | 流式回复、附件、语音输入、模型和思考程度切换、上下文占用、从任意回复分叉、按项目分组的侧栏、搜索会话、全部设置,电脑和手机(PWA)都能用 |
33
33
  | 🔔 | **飞书 + 苹果系统推送** | 除了飞书消息,Web 会话还能推送到 iPhone、iPad 锁屏和 Mac 通知中心(标准 Web Push,不需要开发者账号),图标上显示未读数 |
@@ -36,7 +36,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
36
36
  ## 能做什么
37
37
 
38
38
  - **多个 agent**:Claude Code、Codex。两个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
39
- - **多个飞书机器人**:一个机器人对应一个 agent,或者一个机器人能切换多个 agent,都在设置页里勾选。机器人能在 Web 上扫码创建(Lark 国际版用「手动添加」),改完配置立即生效,不用重启。
39
+ - **多个飞书机器人**:设置 → 飞书 →「可用专家」直接勾选内置或共享专家,并选择「默认专家」。只勾一个共享专家即可专用,不用再勾选底层 Agent;每个人绑定自己的账号后,直接私聊就是这个专家,使用各自的记忆和工具。机器人能在 Web 上扫码创建(Lark 国际版用「手动添加」),改完配置立即生效,不用重启。
40
40
  - 群聊里要 @ 机器人;不同话题是各自独立的会话;支持文字、富文本、图片、文件、语音和视频。
41
41
  - 思考和工具调用显示在实时刷新的过程卡片里,最终回复是普通消息。
42
42
  - 陌生人发消息会拿到配对码,在设置页批准后才能使用;每个机器人单独授权。
@@ -72,7 +72,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
72
72
  - **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
73
73
  - **设置都在网页上**,按用途分组:**我的**(账号和密码、飞书绑定、登录设备、通知、记忆、技能、用量,每个人都有);**Agent**(运行环境、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、额度查询;工作目录、会话闲置过期、授权卡超时和 Claude 的「总是允许」名单;「/」命令);**连接**(飞书机器人、配对批准、指令面板同步;远程控制;服务器);**管理**(用户、所有人的登录设备;服务端版本和升级、重启、局域网访问和端口)。改了没保存就切页或关掉设置会先提醒。
74
74
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
75
- - **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex` 换专家会开新会话)。**内置专家**:Claude Code、Codex,就是 agent 原装的样子(原装提示词、机器上的技能和 MCP、所有工具)。**自定义专家**每人管自己的,可以配:
75
+ - **专家**:设置 → 专家。专家是一份配置,新建对话、定时任务时选一个,对话从头到尾都是它(中途不能换;飞书里 `/expert 名字`、`/claude`、`/codex` 换专家会开新会话)。**内置专家**:Claude Code、Codex,保留原装提示词和所有工具,默认技能与 MCP 在「设置 → Agent」中按账号、按引擎分别选择。**自定义专家**由创建者管理,可以勾选「共享给所有账号」。共享后,其他人能在网页、绑定账号后的飞书私聊和定时任务中选择它;只有创建者能修改设定。每个人在该专家的「我的工具」里选择自己的技能和 MCP,使用各自的变量、凭据、记忆和聊天记录;创建者沿用原有工具选择,其他人未配置时不加载技能或 MCP。取消共享后,其他人的历史对话保留,后续消息不能继续调用该专家,相关定时任务在下次运行时暂停。可以配:
76
76
  - 头像(点头像区域的加号上传;未上传时,会话中用引擎的图标)、引擎(Claude / Codex,建好后不能换)、默认模型和思考程度(从模型列表里选);
77
77
  - 提示词:人设、规则、输出格式。agent-loft 在后面自动补上这个专家能做什么、今天的日期、记忆。Claude 专家默认只用这段提示词(一句话约 2 千 token),也可以选「追加在 Claude Code 原装提示词后面」(干活更稳,每轮多约 1.6 万);Codex 的基础指令改不了,专家的提示词附在第一条消息后面,约束力弱一些;
78
78
  - 权限,勾选:联网搜索、读网页,以及文件权限(一级包含一级):都不勾就是**只能联网**(不碰本机文件、不弹授权,文本附件内容直接放进消息)/**能读文件**/**能改文件**/**能跑命令**(跑命令就等于能改任何文件,需要授权时弹卡)。Claude 按权限给工具;Codex 按权限开 shell、apply_patch,沙箱只读或 workspace-write;
@@ -82,10 +82,10 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
82
82
  - 子智能体(只有 Claude):别的 Claude 专家,主专家用 Agent 工具把子任务派给它。子智能体的权限不能超过主专家(运行时也封顶在主专家的权限)。
83
83
 
84
84
  只勾联网搜索、读网页的 Claude 专家就是以前聊天模式的效果。专家改了,用它的对话下一条消息起生效;专家删了,用它的对话还能看、不能再发消息,用它的定时任务暂停。以前的聊天模式取消了:升级后聊天模式的旧对话不再保留,聊天模式的定时任务暂停,选个专家再启用。
85
- - **MCP**:设置 → MCP,每人管自己的:本机进程(命令 + 参数 + 环境变量)或 HTTP 地址(+ 请求头),值可以标成密钥(网页上不回显,只交给 MCP 进程或请求头,不进提示词)。可以设「调用前询问」,不设就直接用。只给自定义专家用,内置专家照旧用机器上配的。
85
+ - **MCP**:设置 → MCP,每人管自己的:本机进程(命令 + 参数 + 环境变量)或 HTTP 地址(+ 请求头),值可以标成密钥(网页上不回显,只交给 MCP 进程或请求头,不进提示词)。可以设「调用前询问」,不设就直接用。自定义专家加载各自勾选的服务;内置专家在「设置 → Agent → 内置 Agent 默认加载」里选择,支持个人 MCP、管理员可选的机器 MCP,也可全部取消;不指定时管理员沿用机器配置。
86
86
  - **记忆**:像 ChatGPT 的记忆,设置 → 记忆(默认关)。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 2 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理选中专家的对话;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话)。聊天记录索引不开记忆也会记(侧栏的「搜索」也用它),升级后会把已有对话收录进来一次;没开记忆时记进来的不拿去整理。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
87
87
  - **定时任务**:像 ChatGPT 的 Tasks,侧栏的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选专家和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
88
- - **技能(skills)**:设置 → 技能。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。每人管自己的,不做分享和技能广场(以前从别人那装过的照常能用,可以卸载)。**使用**:内置专家能用你启用的全部技能,自定义专家只用它选中的;agent 遇到对得上的事自己用。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
88
+ - **技能(skills)**:设置 → 技能。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。每人管自己的,不做分享和技能广场(以前从别人那装过的照常能用,可以卸载)。**使用**:内置专家默认使用你启用的全部技能,也可以在「设置 → Agent」中分别指定 Claude Code / Codex 加载哪些技能;自定义专家只用它选中的;agent 遇到对得上的事自己用。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
89
89
  - **资料库**:像 ChatGPT 的资料库,侧栏的「资料库」。对话里发过的附件、agent 回复里给出的、这一轮新写出来的图片 / 文档 / 音视频(复制一份收进来,之后原文件改了删了不影响)都汇总在这里:按图片 / 文档 / 音视频筛、按文件名搜,点开看大图或下载,「在新对话里用」,单个或批量删除(文件从磁盘上删掉)。输入框的「+」也能「从资料库选」。从资料库拿到对话里的文件硬链接进那条对话的上传目录,不占双份空间,agent 照常能读。按人隔离,规则同对话:自己的;没主人的对话(飞书群聊等)的归管理员。上传了一直没发出去的一天后清掉,对话被删的连同文件一起删。
90
90
  - **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
91
91
  - 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,工具栏上选画质:流畅 / 标准(默认)/ 高清由服务端把画面缩小到长边 1280 / 1920 / 2560、只把变了的地方压成 JPEG 发过来(macOS 屏幕共享只给无损的 ZRLE,5K 屏一整屏 30MB,原样转发隔着公网几秒一帧),原画是原样转发、只适合局域网;远程那边接了几块屏时可以只看其中一块(按系统里的显示器名称选,服务端只截那块再缩,比几块屏拼在一起缩小清楚得多;macOS 的各块屏位置要从屏幕共享发来的画面里学,第一次连上要几秒,原画下不能选);可以缩放到窗口或按原始大小看、全屏(手机上也能,iPhone 上是铺满页面)、「只看不控制」、发送 Ctrl+Alt+Del 之类的组合键。手机上有两种手势(右上角切换,「?」看说明):**触控板模式**(默认)屏幕上有个指针,单指滑动移动、轻点单击、双指轻点右键、长按后拖动是按住左键拖、双指滑动滚动;**触摸模式**点哪就点哪。两种模式都能双指捏合在本地放大画面(放大后小按钮也点得准,右下角「还原」),画面下面一排 Esc / Tab / Ctrl / Alt / Win / 方向键,Ctrl、Alt、Win 点一下会粘住,带给下一个按键或点击;键盘按钮弹出软键盘打字,中文输入法也能用。Linux 上 agent-loft 在有人连时用 x11vnc 共享当前的桌面(Xorg 会话;只听 127.0.0.1、随机端口、每次随机密码,需要 `sudo apt install x11vnc`),没人连着 30 分钟后停掉;macOS 上在 设置 → 远程控制 里改用「已有的 VNC 服务」,接系统自带的屏幕共享:填 VNC 密码,或者屏幕共享没开 VNC 密码时填 Mac 的用户名和登录密码(苹果认证,由服务端登录)。
@@ -181,7 +181,7 @@ agent-loft service install
181
181
  - agent 子进程拿不到本服务自己的凭据(`FEISHU_*`、`AGENT_LOFT_*` 等环境变量会被剔除)。
182
182
  - 技能存在 `data/skills/`:技能本体在 `files/<技能 id>/`,每个人装了哪些、变量的值在 `users/<用户 id>.json`(0600)。普通变量注入到会话环境里,agent 能读到;受保护的密钥 agent 看不到值,但和多用户一样不是安全边界——能读文件的专家(包括内置的 Claude Code / Codex)能直接读这些文件。别人分享的技能会在你的会话里照着执行,装之前在技能页点开看一眼它要做什么、要哪些变量。
183
183
  - 记忆和聊天记录索引都存在 `data/agent-loft.db`(SQLite,会话、脚注、用量也在里面)。记给谁由 agent-loft 在拉起记忆工具时定死(工具参数里没有用户),模型想写别人的记忆也写不了;但和多用户一样不是安全边界:能读文件的专家能读到这个数据库文件。只能联网的专家没有读写本机文件的工具,网页里的提示注入也骗不走本机文件。
184
- - 专家存在 `data/experts.json`,MCP 存在 `data/mcp.json`(0600,含 MCP 的密钥值)。和技能一样不是安全边界:能读文件的专家读得到。
184
+ - 专家存在 `data/experts.json`,MCP 存在 `data/mcp.json`(0600,含 MCP 的密钥值),内置 Agent 的个人默认选择存在 `data/builtin-agents.json`。和技能一样不是安全边界:能读文件的专家读得到。
185
185
 
186
186
  ## 结构
187
187
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.64",
3
+ "version": "0.2.66",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -219,13 +219,13 @@ export function expertOptions(opts: SessionOptions): Partial<Options> {
219
219
  const skills = opts.skills;
220
220
  const expert = opts.expert;
221
221
  if (!expert) {
222
- const mcpServers = loftMcp(opts);
222
+ const mcpServers = { ...opts.builtinMcp?.mcp, ...loftMcp(opts) };
223
223
  const append = [RICH_REPLY_LINES.join("\n"), memory?.prompt, skills?.prompt].filter(Boolean).join("\n\n");
224
224
  return {
225
225
  systemPrompt: { type: "preset", preset: "claude_code", append, snapshot: false },
226
- ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
226
+ ...(opts.builtinMcp && !opts.builtinMcp.inheritMachine ? { strictMcpConfig: true, mcpServers } : Object.keys(mcpServers).length ? { mcpServers } : {}),
227
227
  ...(skills?.pluginDir ? { plugins: [{ type: "local" as const, path: skills.pluginDir, skipMcpDiscovery: true }] } : {}),
228
- ...(skills && !skills.admin ? { skills: memberSkillAllowlist(skills, opts.cwd) } : {}),
228
+ ...(skills && (!skills.admin || skills.machineSkills === false) ? { skills: memberSkillAllowlist(skills, opts.cwd) } : {}),
229
229
  };
230
230
  }
231
231
 
@@ -579,10 +579,10 @@ export class ClaudeSession implements AgentSession {
579
579
  /** 自定义专家:它配了的联网工具、MCP 工具(没标「调用前询问」的)是用户自己给的,不再逐次问 */
580
580
  private expertPreApproved(toolName: string): boolean {
581
581
  const e = this.opts.expert;
582
- if (!e) return false;
583
- if ((toolName === "WebSearch" && e.webSearch) || (toolName === "WebFetch" && e.webFetch)) return true;
582
+ if (e && ((toolName === "WebSearch" && e.webSearch) || (toolName === "WebFetch" && e.webFetch))) return true;
583
+ const config = e ?? this.opts.builtinMcp;
584
584
  const m = /^mcp__(.+?)__/.exec(toolName);
585
- return !!m && m[1]! in e.mcp && !e.askMcp.includes(m[1]!);
585
+ return !!config && !!m && m[1]! in config.mcp && !config.askMcp.includes(m[1]!);
586
586
  }
587
587
 
588
588
  /** 内置专家算能跑命令 */
@@ -428,7 +428,13 @@ export class CodexSession implements AgentSession {
428
428
  const off = Object.fromEntries((await userMcpServers()).filter((n) => !keep.has(n)).map((n) => [`mcp_servers.${n}.enabled`, false]));
429
429
  return { config: { ...expertConfig(expert), ...off, ...codexMcp(expert.mcp, expert.askMcp), ...mcp, ...this.skillConfig() } };
430
430
  }
431
- const work = { ...mcp, ...this.skillConfig() };
431
+ const builtin = this.opts.builtinMcp;
432
+ const keep = new Set([...(builtin?.machineMcp ?? []), ...Object.keys(builtin?.mcp ?? {})]);
433
+ const off = builtin && !builtin.inheritMachine
434
+ ? Object.fromEntries((await userMcpServers()).filter((n) => !keep.has(n)).map((n) => [`mcp_servers.${n}.enabled`, false]))
435
+ : {};
436
+ const selected = Object.fromEntries((builtin?.machineMcp ?? []).map((n) => [`mcp_servers.${n}.enabled`, true]));
437
+ const work = { ...off, ...selected, ...codexMcp(builtin?.mcp ?? {}, builtin?.askMcp), ...mcp, ...this.skillConfig() };
432
438
  return Object.keys(work).length ? { config: work } : {};
433
439
  }
434
440
 
@@ -442,7 +448,7 @@ export class CodexSession implements AgentSession {
442
448
  if (!skills) return {};
443
449
  return {
444
450
  ...(this.access === "exec" ? Object.fromEntries(Object.entries(skills.env).map(([k, v]) => [`shell_environment_policy.set.${k}`, v])) : {}),
445
- ...(skills.admin && !this.opts.expert ? {} : { "skills.include_instructions": false, "features.skill_search": false }),
451
+ ...(skills.admin && skills.machineSkills !== false && !this.opts.expert ? {} : { "skills.include_instructions": false, "features.skill_search": false }),
446
452
  };
447
453
  }
448
454
 
@@ -710,7 +716,7 @@ export class CodexSession implements AgentSession {
710
716
  case "mcpServer/elicitation/request": {
711
717
  const req = params as { serverName: string; mode?: string; message?: string; _meta?: Record<string, unknown> };
712
718
  // Codex 用 elicitation 传工具审批;普通 MCP 表单仍按未支持处理,不能把表单当授权。
713
- if (req.mode !== "form" || req._meta?.codex_approval_kind !== "mcp_tool_call" || !this.opts.expert?.mcp[req.serverName]) {
719
+ if (req.mode !== "form" || req._meta?.codex_approval_kind !== "mcp_tool_call" || !(this.opts.expert ?? this.opts.builtinMcp)?.mcp[req.serverName]) {
714
720
  return refusalFor(method);
715
721
  }
716
722
  const detail = [req.message, req._meta.tool_params === undefined ? "" : `\`\`\`json\n${JSON.stringify(req._meta.tool_params, null, 2)}\n\`\`\``].filter(Boolean).join("\n\n");
@@ -8,6 +8,7 @@ import os from "node:os";
8
8
  import path from "node:path";
9
9
  import * as Lark from "@larksuiteoapi/node-sdk";
10
10
  import { config, type FeishuBotConfig } from "../../core/config.js";
11
+ import { botAgentIds, botExpertIds } from "../../core/feishu-experts.js";
11
12
  import { hub, type CommandReply, type EventEnvelope } from "../../core/hub.js";
12
13
  import { interactions, type Interaction } from "../../core/interactions.js";
13
14
  import { parseCommand } from "../../core/commands.js";
@@ -96,11 +97,12 @@ export class FeishuBot {
96
97
  * 飞书的指令面板是整个应用一份,不分会话,没法跟着每个会话当前的 agent 变。
97
98
  */
98
99
  private async slashCommands(): Promise<CommandEntry[]> {
99
- const agents = [this.cfg.defaultAgent, ...this.cfg.agents.filter((a) => a !== this.cfg.defaultAgent)];
100
+ const allowed = this.allowedAgents();
101
+ const agents = [this.cfg.defaultAgent, ...allowed.filter((a) => a !== this.cfg.defaultAgent)].filter((a) => allowed.includes(a));
100
102
  const out: CommandEntry[] = [];
101
103
  for (const agent of agents) {
102
104
  if (!hub.driver(agent)) continue;
103
- out.push(...(await hub.commandCatalog(agent, { allowedAgents: this.cfg.agents, channel: "feishu" })));
105
+ out.push(...(await hub.commandCatalog(agent, { allowedAgents: allowed, channel: "feishu" })).filter((c) => !["claude", "codex"].includes(c.name) || this.cfg.experts === undefined || this.cfg.experts.includes(c.name)));
104
106
  }
105
107
  return out;
106
108
  }
@@ -132,7 +134,7 @@ export class FeishuBot {
132
134
  /** 这个机器人能用的 agent:配置里勾选的 ∩ 已启用的 */
133
135
  allowedAgents(): string[] {
134
136
  const enabled = new Set(hub.enabledAgents().map((d) => d.id));
135
- return this.cfg.agents.filter((a) => enabled.has(a));
137
+ return botAgentIds(this.cfg).filter((a) => enabled.has(a));
136
138
  }
137
139
 
138
140
  /** 某条会话能切到哪些 agent:自己的会话按机器人的勾选;接着的 Web 会话和 Web 上一样,启用的都行 */
@@ -140,6 +142,22 @@ export class FeishuBot {
140
142
  return this.mine(key) ? this.allowedAgents() : hub.enabledAgents().map((d) => d.id);
141
143
  }
142
144
 
145
+ private expertsFor(key: string): string[] | undefined {
146
+ return this.mine(key) ? botExpertIds(this.cfg) : undefined;
147
+ }
148
+
149
+ /** 下载附件、旧卡片点击期间配置可能变化,真正发送前再核对一次。 */
150
+ private send(...args: Parameters<typeof hub.send>): void {
151
+ const [key] = args;
152
+ const selected = this.expertsFor(key);
153
+ const conv = getConversation(key);
154
+ if (selected !== undefined && (!conv || !selected.includes(conv.expert ?? conv.agent))) {
155
+ hub.notice(key, "这个聊天的专家已不在机器人的可用列表中,请重新发消息以选择默认专家。");
156
+ return;
157
+ }
158
+ hub.send(...args);
159
+ }
160
+
143
161
  // ---------- 这个聊天能碰哪些东西 ----------
144
162
  //
145
163
  // 飞书聊天自己的会话有主人(绑定了账号的私聊,见 core/feishu-links.ts):按主人算,和他在 Web 上一样;
@@ -629,20 +647,21 @@ export class FeishuBot {
629
647
  if (!text && attachments.length === 0) return;
630
648
 
631
649
  const allowed = this.allowedAgents();
632
- if (allowed.length === 0) {
633
- await this.client.sendText(chatId, "这个机器人没有可用的 agent,请到 agent-loft 设置里给它勾选至少一个。");
650
+ if (allowed.length === 0 && feishuCommandOf(text)?.kind !== "bind") {
651
+ await this.client.sendText(chatId, "这个机器人没有可用的专家。所选专家可能已取消共享、删除,或引擎已停用;请在设置 → 飞书中重新选择。");
634
652
  return;
635
653
  }
636
654
 
637
655
  const ownKey = this.keyOf(chatId, message.thread_id);
656
+ const fresh = !getConversation(ownKey);
638
657
  const conv = hub.ensure({
639
658
  key: ownKey,
640
659
  channel: "feishu",
641
660
  channelId: this.cfg.id,
642
- defaultAgent: allowed.includes(this.cfg.defaultAgent) ? this.cfg.defaultAgent : allowed[0]!,
661
+ defaultAgent: allowed.includes(this.cfg.defaultAgent) ? this.cfg.defaultAgent : allowed[0] ?? this.cfg.defaultAgent,
643
662
  });
644
- // 配置改过(这个机器人不再能用当前 agent):退回默认
645
- if (!allowed.includes(conv.agent)) {
663
+ // 旧配置按引擎选择;明确选择专家的新配置在下面通过 setExpert 切换,清掉旧上下文。
664
+ if (this.cfg.experts === undefined && !allowed.includes(conv.agent)) {
646
665
  updateConversation(ownKey, { agent: allowed.includes(this.cfg.defaultAgent) ? this.cfg.defaultAgent : allowed[0]! });
647
666
  }
648
667
  const operator = openId!.trim().toLowerCase();
@@ -651,7 +670,8 @@ export class FeishuBot {
651
670
  // 私聊的主人跟着发消息的人的绑定走:绑定了就是他的个人会话(用他的记忆),解绑了就回到管理员的地盘。
652
671
  // 群聊不动:群里不止一个人
653
672
  const p2p = message.chat_type === "p2p";
654
- if (p2p && hub.reassignOwner(ownKey, linkedUser(this.cfg.id, operator)?.id)) {
673
+ const ownerChanged = p2p && hub.reassignOwner(ownKey, linkedUser(this.cfg.id, operator)?.id);
674
+ if (ownerChanged) {
655
675
  const owner = this.viewerOf(ownKey);
656
676
  console.log(`${this.tag} 私聊 ${ownKey} 的主人变为 ${owner?.name ?? "(无,归管理员)"}`);
657
677
  }
@@ -667,11 +687,23 @@ export class FeishuBot {
667
687
  const key = this.attachedWeb(ownKey) ?? ownKey;
668
688
  this.operators.set(pairKey(key, chatId), operator);
669
689
 
690
+ const selected = this.expertsFor(key);
691
+ let noExpert = false;
692
+ if (selected !== undefined) {
693
+ const choices = hub.expertChoices(this.viewerOf(ownKey)?.id, allowed, selected);
694
+ noExpert = choices.length === 0;
695
+ if (!noExpert && (fresh || ownerChanged || !choices.some((e) => e.id === (conv.expert ?? conv.agent)))) {
696
+ const preferred = choices.find((e) => e.id === this.cfg.defaultExpert) ?? choices[0]!;
697
+ await hub.setExpert(ownKey, preferred.id, allowed, selected);
698
+ }
699
+ }
700
+
670
701
  const command = attachments.length > 0 ? ({ kind: "chat", text } as const) : parseCommand(text);
671
702
  if (command.kind !== "chat") {
672
703
  try {
673
704
  const reply = await hub.command(key, command, {
674
705
  allowedAgents: this.allowedFor(key),
706
+ allowedExperts: this.expertsFor(key),
675
707
  by: "飞书命令",
676
708
  channel: "feishu",
677
709
  // 别人的 agent 会话、挂着的请求,这个聊天里都碰不到
@@ -684,13 +716,18 @@ export class FeishuBot {
684
716
  return;
685
717
  }
686
718
 
719
+ if (noExpert) {
720
+ await this.client.sendText(chatId, p2p ? "这个机器人使用共享专家。请先在网页「设置 → 账号 → 飞书账号」生成绑定码,再私聊发送 /bind 绑定码,即可使用你自己的记忆和工具。" : "这个机器人只选择了共享专家,请在私聊中绑定你自己的账号后使用。");
721
+ return;
722
+ }
723
+
687
724
  void this.markTyping(key, message.message_id);
688
725
  const origin = { channel: "feishu", channelId: this.cfg.id, name: "飞书", chatId };
689
726
  // 收到消息这一刻的代次:下载附件期间点了 /stop、或者 /cd /new 换了会话,这条就作废
690
727
  const gen = hub.generation(key);
691
728
  this.enqueue(key, async () => {
692
729
  if (attachments.length === 0) {
693
- hub.send(key, { text: command.text, attachments: [] }, origin, gen);
730
+ this.send(key, { text: command.text, attachments: [] }, origin, gen);
694
731
  return;
695
732
  }
696
733
  const { saved, failed } = await this.download(key, message.message_id, attachments);
@@ -704,7 +741,7 @@ export class FeishuBot {
704
741
  this.clearTyping(key);
705
742
  return;
706
743
  }
707
- hub.send(key, { text: command.text, attachments: saved }, origin, gen);
744
+ this.send(key, { text: command.text, attachments: saved }, origin, gen);
708
745
  });
709
746
  }
710
747
 
@@ -746,19 +783,25 @@ export class FeishuBot {
746
783
  try {
747
784
  if (cmd.kind === "web") await this.sendWebList(ownKey, chatId);
748
785
  else if (cmd.kind === "detach") await this.client.sendCard(chatId, replyCard(this.detachFrom(ownKey)));
749
- else await this.client.sendCard(chatId, replyCard(this.bind(cmd.code, ownKey, sender)));
786
+ else await this.client.sendCard(chatId, replyCard(await this.bind(cmd.code, ownKey, sender)));
750
787
  } catch (err) {
751
788
  await this.client.sendText(chatId, `出错了:${err instanceof Error ? err.message : String(err)}`);
752
789
  }
753
790
  }
754
791
 
755
792
  /** /bind 绑定码:把发消息的人的飞书账号绑到生成这个码的 agent-loft 用户上 */
756
- private bind(code: string, ownKey: string, sender: { openId: string; p2p: boolean } | undefined): string {
793
+ private async bind(code: string, ownKey: string, sender: { openId: string; p2p: boolean } | undefined): Promise<string> {
757
794
  if (!sender) return "请直接在聊天里发 `/bind 绑定码`。";
758
795
  // 群里发的码别人也看得见,而且群聊本来就不归个人:只在私聊里绑
759
796
  if (!sender.p2p) return "请在和我的私聊里发 `/bind 绑定码`(群里别人也看得到绑定码)。绑定码已经露出来了的话,到 Web 上重新生成一个。";
760
797
  const user = redeemLinkCode(code, this.cfg.id, sender.openId);
761
798
  hub.reassignOwner(ownKey, user.id);
799
+ const selected = this.expertsFor(ownKey);
800
+ if (selected !== undefined) {
801
+ const choices = hub.expertChoices(user.id, this.allowedAgents(), selected);
802
+ const preferred = choices.find((e) => e.id === this.cfg.defaultExpert) ?? choices[0];
803
+ if (preferred) await hub.setExpert(ownKey, preferred.id, this.allowedAgents(), selected);
804
+ }
762
805
  console.log(`${this.tag} ${sender.openId} 绑定到用户 ${user.name}`);
763
806
  return [
764
807
  `已绑定到 agent-loft 用户 **${user.name}**。`,
@@ -917,7 +960,7 @@ export class FeishuBot {
917
960
  case "effort":
918
961
  return this.background(envelope.k, chatId, `思考程度设为 ${envelope.f}`, () => hub.setEffort(envelope.k, envelope.f));
919
962
  case "agent":
920
- return this.background(envelope.k, chatId, "正在换专家…", () => hub.setExpert(envelope.k, envelope.g, this.allowedFor(envelope.k)));
963
+ return this.background(envelope.k, chatId, "正在换专家…", () => hub.setExpert(envelope.k, envelope.g, this.allowedFor(envelope.k), this.expertsFor(envelope.k)));
921
964
  case "cmd":
922
965
  return this.runCardCommand(envelope.k, chatId, operatorOpenId, `/${envelope.c}`);
923
966
  case "attach": {
@@ -966,11 +1009,11 @@ export class FeishuBot {
966
1009
  if (command.kind === "chat") {
967
1010
  const origin = { channel: "feishu", channelId: this.cfg.id, name: "飞书", chatId: chat };
968
1011
  const gen = hub.generation(key);
969
- this.enqueue(key, async () => hub.send(key, { text, attachments: [] }, origin, gen));
1012
+ this.enqueue(key, async () => this.send(key, { text, attachments: [] }, origin, gen));
970
1013
  return { toast: { type: "success", content: `已发送 ${text}` } };
971
1014
  }
972
1015
  void hub
973
- .command(key, command, { allowedAgents: this.allowedFor(key), by: "飞书命令", channel: "feishu", ...this.commandScope(ownKey) })
1016
+ .command(key, command, { allowedAgents: this.allowedFor(key), allowedExperts: this.expertsFor(key), by: "飞书命令", channel: "feishu", ...this.commandScope(ownKey) })
974
1017
  .then((reply) => this.renderReply(key, chat, reply))
975
1018
  .catch((err) => this.client.sendText(chat, `出错了:${err instanceof Error ? err.message : String(err)}`));
976
1019
  return { toast: { type: "info", content: `正在执行 ${text}` } };
@@ -23,6 +23,8 @@ function reconcile(list: FeishuBotConfig[]): void {
23
23
  for (const [id, cfg] of wanted) {
24
24
  const existing = bots.get(id);
25
25
  if (existing) {
26
+ delete existing.cfg.experts;
27
+ delete existing.cfg.defaultExpert;
26
28
  Object.assign(existing.cfg, cfg);
27
29
  continue;
28
30
  }
@@ -42,7 +44,7 @@ export function startFeishu(): void {
42
44
  for (const bot of bots.values()) {
43
45
  const before = prev.feishu.bots.find((b) => b.id === bot.id);
44
46
  const agentsChanged =
45
- !before || JSON.stringify([before.agents, before.defaultAgent]) !== JSON.stringify([bot.cfg.agents, bot.cfg.defaultAgent]);
47
+ !before || JSON.stringify([before.agents, before.defaultAgent, before.experts, before.defaultExpert]) !== JSON.stringify([bot.cfg.agents, bot.cfg.defaultAgent, bot.cfg.experts, bot.cfg.defaultExpert]);
46
48
  if (commandsChanged || agentsChanged) bot.slash.request();
47
49
  }
48
50
  });
@@ -75,7 +75,8 @@ import { handleLibraryApi } from "./library-api.js";
75
75
  import { attachToConversation, canSeeFile, getLibraryFile } from "../../core/library.js";
76
76
  import { handleSkillsApi } from "./skills-api.js";
77
77
  import { handleExpertsApi } from "./experts-api.js";
78
- import { canUseExpert, getExpert, isBuiltin, listExperts } from "../../core/experts.js";
78
+ import { availableExperts, canUseExpert, getExpert, isBuiltin } from "../../core/experts.js";
79
+ import { botExpertSelection } from "../../core/feishu-experts.js";
79
80
  import { expertBrief } from "./experts-api.js";
80
81
  import { handleTerminalApi } from "./terminal.js";
81
82
  import { handleDesktopApi, remoteStatus } from "./desktop.js";
@@ -265,7 +266,7 @@ type Registration = {
265
266
  };
266
267
  const registrations = new Map<string, Registration>();
267
268
 
268
- async function startRegistration(name: string, agents: string[]): Promise<{ id: string } & Registration> {
269
+ async function startRegistration(name: string, agents: string[], selection?: ReturnType<typeof botExpertSelection>): Promise<{ id: string } & Registration> {
269
270
  await initRegistration("feishu");
270
271
  const begin = await beginRegistration("feishu");
271
272
  const id = crypto.randomBytes(8).toString("hex");
@@ -291,6 +292,7 @@ async function startRegistration(name: string, agents: string[]): Promise<{ id:
291
292
  allowFrom: outcome.result.openId ? [outcome.result.openId.toLowerCase()] : [],
292
293
  agents: list.length ? list : ["claude"],
293
294
  defaultAgent: list[0] ?? "claude",
295
+ ...selection,
294
296
  });
295
297
  saveConfig(cfg);
296
298
  reg.status = "success";
@@ -407,7 +409,14 @@ function applyConfig(input: Partial<AppConfig>, selfOrigin?: string): void {
407
409
  const old = current.feishu.bots.find((o) => o.id === b.id);
408
410
  // 前端拿到的是打码后的密钥,原样传回来表示「没改」
409
411
  const secret = !b.appSecret || b.appSecret.startsWith(MASK) ? (old?.appSecret ?? "") : b.appSecret;
410
- return { ...b, appSecret: secret };
412
+ try {
413
+ if (old?.experts && JSON.stringify([b.experts, b.defaultExpert]) === JSON.stringify([old.experts, old.defaultExpert])) {
414
+ return { ...b, appSecret: secret, agents: old.agents, defaultAgent: old.defaultAgent };
415
+ }
416
+ return { ...b, appSecret: secret, ...(b.experts === undefined ? {} : botExpertSelection(b.experts, b.defaultExpert)) };
417
+ } catch (err) {
418
+ throw new HttpError(400, err instanceof Error ? err.message : String(err));
419
+ }
411
420
  });
412
421
  }
413
422
  }
@@ -680,8 +689,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
680
689
  }),
681
690
  // 飞书机器人是管理员配的,飞书会话也只给管理员看
682
691
  bots: admin ? config().feishu.bots.map((b) => ({ id: b.id, name: b.name, agents: b.agents, enabled: b.enabled })) : [],
683
- // 自己的专家(新对话、定时任务里选)。内置的 Claude Code / Codex 就是上面的 agents
684
- experts: listExperts(user.id).map(expertBrief),
692
+ // 自己的和共享的专家(新对话、定时任务里选)。内置的 Claude Code / Codex 就是上面的 agents
693
+ experts: availableExperts(user.id).map(expertBrief),
685
694
  workspaceRoot: config().workspaceRoot,
686
695
  quotaRefreshMin: config().web.quotaRefreshMin,
687
696
  quotaEnabled: config().web.quotaEnabled,
@@ -770,7 +779,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
770
779
  if (p.startsWith("/api/tasks") && (await handleTasksApi(req, res, p, user))) return;
771
780
  if (p.startsWith("/api/library") && (await handleLibraryApi(req, res, p, user))) return;
772
781
  if (p.startsWith("/api/skills") && (await handleSkillsApi(req, res, url, user))) return;
773
- if ((p.startsWith("/api/experts") || p.startsWith("/api/mcp")) && (await handleExpertsApi(req, res, p, user))) return;
782
+ if ((p === "/api/agents/defaults" || p.startsWith("/api/experts") || p.startsWith("/api/mcp")) && (await handleExpertsApi(req, res, p, user))) return;
774
783
  if (p.startsWith("/api/terminals") && (await handleTerminalApi(req, res, p, user))) return;
775
784
  if ((p === "/api/remote" || p.startsWith("/api/desktop/")) && (await handleDesktopApi(req, res, p, user))) return;
776
785
 
@@ -847,11 +856,12 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
847
856
  return;
848
857
  }
849
858
  if (p === "/api/conversations" && method === "POST") {
850
- // expert:新对话页上选的专家(内置的 claude / codex,或者自己的专家 id)。agent 是以前的叫法
859
+ // expert:新对话页上选的专家(内置的 claude / codex,或者自己的、共享的专家 id)。agent 是以前的叫法
851
860
  const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
852
861
  const enabled = hub.enabledAgents().map((d) => d.id);
853
862
  const wanted = body.expert ?? body.agent;
854
- let expertId = wanted && canUseExpert(user.id, wanted) ? wanted : enabled[0];
863
+ if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家不存在或已取消共享");
864
+ const expertId = wanted || enabled[0];
855
865
  if (!expertId) throw new HttpError(400, "没有可用的 agent");
856
866
  const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
857
867
  const agent = custom ? custom.engine : expertId;
@@ -1500,8 +1510,14 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1500
1510
  return;
1501
1511
  }
1502
1512
  if (p === "/api/feishu/register" && method === "POST") {
1503
- const body = await readJsonBody<{ name?: string; agents?: string[] }>(req);
1504
- sendJson(res, 200, await startRegistration(String(body.name ?? ""), Array.isArray(body.agents) ? body.agents : []));
1513
+ const body = await readJsonBody<{ name?: string; agents?: string[]; experts?: unknown; defaultExpert?: unknown }>(req);
1514
+ let selection: ReturnType<typeof botExpertSelection> | undefined;
1515
+ try {
1516
+ if (body.experts !== undefined) selection = botExpertSelection(body.experts, body.defaultExpert);
1517
+ } catch (err) {
1518
+ throw new HttpError(400, err instanceof Error ? err.message : String(err));
1519
+ }
1520
+ sendJson(res, 200, await startRegistration(String(body.name ?? ""), Array.isArray(body.agents) ? body.agents : [], selection));
1505
1521
  return;
1506
1522
  }
1507
1523
  const regMatch = /^\/api\/feishu\/register\/([a-f0-9]+)$/.exec(p);
@@ -1,21 +1,25 @@
1
- // 专家和 MCP 的接口:/api/experts、/api/mcp。每人管自己的,看不到别人的(管理员也一样)。
1
+ // 专家由创建者管理,可共享使用;工具选择和 MCP 配置按登录账号隔离。
2
2
  import type { IncomingMessage, ServerResponse } from "node:http";
3
3
  import { userMcpServers } from "../../agents/codex/session.js";
4
4
  import {
5
5
  ACCESS_LABEL,
6
6
  ACCESS_LEVELS,
7
+ availableExperts,
7
8
  avatarImage,
8
9
  avatarUrl,
9
10
  createExpert,
11
+ canUseExpert,
10
12
  deleteExpert,
11
13
  EXPERT_LIMITS,
12
14
  EXPERT_TEMPLATES,
13
15
  getExpert,
14
- listExperts,
16
+ expertTools,
15
17
  updateExpert,
18
+ setExpertTools,
16
19
  type Expert,
17
20
  type ExpertInput,
18
21
  } from "../../core/experts.js";
22
+ import { builtinAgentDefaults, setBuiltinAgentDefaults } from "../../core/builtin-agents.js";
19
23
  import { hub } from "../../core/hub.js";
20
24
  import { claudeMachineMcp, createMcp, deleteMcp, getMcp, listMcp, MACHINE_PREFIX, MCP_LIMITS, mcpView, updateMcp, type McpInput } from "../../core/mcp.js";
21
25
  import { activeSkills } from "../../core/skills.js";
@@ -24,7 +28,8 @@ import { HttpError, readJsonBody, sendJson } from "./http.js";
24
28
 
25
29
  const bad = (err: unknown) => (err instanceof HttpError ? err : new HttpError(400, err instanceof Error ? err.message : String(err)));
26
30
 
27
- function expertView(e: Expert) {
31
+ function expertView(e: Expert, viewer: string) {
32
+ const tools = expertTools(viewer, e);
28
33
  return {
29
34
  id: e.id,
30
35
  name: e.name,
@@ -43,9 +48,11 @@ function expertView(e: Expert) {
43
48
  cwd: e.cwd ?? "",
44
49
  webSearch: e.webSearch,
45
50
  webFetch: e.webFetch,
46
- skills: e.skills,
47
- mcp: e.mcp,
48
- subagents: e.subagents,
51
+ shared: e.shared === true,
52
+ editable: e.owner === viewer,
53
+ skills: tools.skills,
54
+ mcp: tools.mcp,
55
+ subagents: e.subagents.filter((id) => canUseExpert(viewer, id)),
49
56
  memory: e.memory,
50
57
  updatedAt: e.updatedAt,
51
58
  };
@@ -54,6 +61,7 @@ function expertView(e: Expert) {
54
61
  /** 选专家时要的那点信息(bootstrap 里给,/api/experts/brief 刷新) */
55
62
  export function expertBrief(e: Expert) {
56
63
  return {
64
+ shared: e.shared === true,
57
65
  id: e.id,
58
66
  name: e.name,
59
67
  description: e.description,
@@ -85,10 +93,29 @@ async function machineMcp(user: User): Promise<{ claude: string[]; codex: string
85
93
  export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse, p: string, user: User): Promise<boolean> {
86
94
  const method = req.method ?? "GET";
87
95
 
96
+ if (p === "/api/agents/defaults" && method === "GET") {
97
+ sendJson(res, 200, {
98
+ agents: builtinAgentDefaults(user.id),
99
+ skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
100
+ mcp: listMcp(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
101
+ ...(await machineMcp(user).then((m) => m ? { machineMcp: m, machinePrefix: MACHINE_PREFIX } : {})),
102
+ });
103
+ return true;
104
+ }
105
+ if (p === "/api/agents/defaults" && method === "PUT") {
106
+ const body = await readJsonBody<{ agents?: unknown }>(req);
107
+ try {
108
+ sendJson(res, 200, { agents: setBuiltinAgentDefaults(user.id, body.agents) });
109
+ } catch (err) {
110
+ throw bad(err);
111
+ }
112
+ return true;
113
+ }
114
+
88
115
  if (p === "/api/experts" && method === "GET") {
89
116
  const enabled = hub.enabledAgents().map((d) => d.id);
90
117
  sendJson(res, 200, {
91
- experts: listExperts(user.id).map(expertView),
118
+ experts: availableExperts(user.id).map((e) => expertView(e, user.id)),
92
119
  builtin: enabled.map((id) => ({ id, name: hub.label(id), engine: id })),
93
120
  engines: enabled,
94
121
  templates: EXPERT_TEMPLATES.map((t) => ({ id: t.id, label: t.label, expert: t.expert })),
@@ -102,14 +129,14 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
102
129
  }
103
130
 
104
131
  if (p === "/api/experts/brief" && method === "GET") {
105
- sendJson(res, 200, { experts: listExperts(user.id).map(expertBrief) });
132
+ sendJson(res, 200, { experts: availableExperts(user.id).map(expertBrief) });
106
133
  return true;
107
134
  }
108
135
 
109
136
  if (p === "/api/experts" && method === "POST") {
110
137
  const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
111
138
  try {
112
- sendJson(res, 200, expertView(createExpert(user.id, body)));
139
+ sendJson(res, 200, expertView(createExpert(user.id, body), user.id));
113
140
  } catch (err) {
114
141
  throw bad(err);
115
142
  }
@@ -127,18 +154,31 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
127
154
  return true;
128
155
  }
129
156
 
157
+ const tm = /^\/api\/experts\/(e_[a-f0-9]+)\/tools$/.exec(p);
158
+ if (tm && method === "PUT") {
159
+ if (!canUseExpert(user.id, tm[1]!)) throw new HttpError(404, "这个专家不存在");
160
+ const body = await readJsonBody<unknown>(req);
161
+ try {
162
+ sendJson(res, 200, setExpertTools(user.id, tm[1]!, body));
163
+ } catch (err) {
164
+ throw bad(err);
165
+ }
166
+ return true;
167
+ }
168
+
130
169
  const em = /^\/api\/experts\/(e_[a-f0-9]+)$/.exec(p);
131
170
  if (em) {
132
171
  const expert = getExpert(em[1]!);
133
- if (!expert || expert.owner !== user.id) throw new HttpError(404, "这个专家不存在");
172
+ if (!expert || !canUseExpert(user.id, expert.id)) throw new HttpError(404, "这个专家不存在");
134
173
  if (method === "GET") {
135
- sendJson(res, 200, expertView(expert));
174
+ sendJson(res, 200, expertView(expert, user.id));
136
175
  return true;
137
176
  }
177
+ if (expert.owner !== user.id) throw new HttpError(403, "只有创建者能修改或删除共享专家;你的工具可单独配置");
138
178
  if (method === "PATCH") {
139
179
  const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
140
180
  try {
141
- sendJson(res, 200, expertView(updateExpert(user.id, expert.id, body)));
181
+ sendJson(res, 200, expertView(updateExpert(user.id, expert.id, body), user.id));
142
182
  } catch (err) {
143
183
  throw bad(err);
144
184
  }
@@ -157,9 +197,9 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
157
197
  }
158
198
 
159
199
  if (p === "/api/mcp" && method === "GET") {
160
- const experts = listExperts(user.id);
200
+ const experts = availableExperts(user.id);
161
201
  sendJson(res, 200, {
162
- servers: listMcp(user.id).map((s) => ({ ...mcpView(s), usedBy: experts.filter((e) => e.mcp.includes(s.id)).map((e) => e.name) })),
202
+ servers: listMcp(user.id).map((s) => ({ ...mcpView(s), usedBy: experts.filter((e) => expertTools(user.id, e).mcp.includes(s.id)).map((e) => e.name) })),
163
203
  limits: MCP_LIMITS,
164
204
  });
165
205
  return true;