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.
@@ -15,6 +15,7 @@ import { interactions, type Interaction } from "../../core/interactions.js";
15
15
  import { getConversation } from "../../core/store.js";
16
16
  import { taskEvents } from "../../core/tasks.js";
17
17
  import { skillEvents } from "../../core/skills.js";
18
+ import { expertEvents } from "../../core/experts.js";
18
19
  import { enforceTerminalAccess, killAllTerminals, terminalEvents, watchTerminalAccess } from "../../core/terminals.js";
19
20
  import { RUNNING_VERSION } from "../../core/upgrade.js";
20
21
  import type { Settlement } from "../../core/types.js";
@@ -239,6 +240,11 @@ function broadcastTerminals(owner: string): void {
239
240
  /** 用户改了(比如远程控制权限被开通 / 收回)、远程控制的设置改了:页面重新问一下能用什么 */
240
241
  function broadcastUsersChanged(): void {
241
242
  for (const client of clients) send(client, { t: "remote" });
243
+ broadcastExperts();
244
+ }
245
+
246
+ function broadcastExperts(): void {
247
+ for (const client of clients) send(client, { t: "experts" });
242
248
  }
243
249
 
244
250
  /** 技能变了:以前装过别人技能的人也受影响,通知所有人重新拉(列表很小) */
@@ -571,6 +577,7 @@ export async function startWeb(): Promise<void> {
571
577
  interactions.on("settled", broadcastInteraction);
572
578
  taskEvents.on("changed", broadcastTasks);
573
579
  skillEvents.on("changed", broadcastSkills);
580
+ expertEvents.on("changed", broadcastExperts);
574
581
  terminalEvents.on("changed", broadcastTerminals);
575
582
  userEvents.on("changed", broadcastUsersChanged);
576
583
  watchTerminalAccess();
@@ -619,6 +626,7 @@ export async function stopWeb(): Promise<void> {
619
626
  interactions.off("settled", broadcastInteraction);
620
627
  taskEvents.off("changed", broadcastTasks);
621
628
  skillEvents.off("changed", broadcastSkills);
629
+ expertEvents.off("changed", broadcastExperts);
622
630
  terminalEvents.off("changed", broadcastTerminals);
623
631
  userEvents.off("changed", broadcastUsersChanged);
624
632
  stopWatchingRemote?.();
@@ -0,0 +1,96 @@
1
+ // 内置 Agent 的个人默认配置;与管理员管理的运行环境分开,按账号、引擎保存。
2
+ import path from "node:path";
3
+ import { EventEmitter } from "node:events";
4
+ import { dataDir, readJson, writeJsonAtomic } from "../home.js";
5
+ import { ENGINES, resolveMcp, type Engine } from "./experts.js";
6
+ import { getMcp, isMachineId, machineName } from "./mcp.js";
7
+ import { activeSkills } from "./skills.js";
8
+ import { sessionSkills } from "./skill-runtime.js";
9
+ import { getUser } from "./users.js";
10
+ import type { SessionOptions } from "./types.js";
11
+
12
+ export type BuiltinAgentDefaults = {
13
+ /** null = 全部已启用的个人技能;[] = 不加载个人技能 */
14
+ skills: string[] | null;
15
+ machineSkills: boolean;
16
+ /** null = 沿用机器配置;[] = 不加载 MCP(系统工具除外) */
17
+ mcp: string[] | null;
18
+ };
19
+ type Defaults = Record<Engine, BuiltinAgentDefaults>;
20
+ const file = path.join(dataDir, "builtin-agents.json");
21
+ export const builtinAgentEvents = new EventEmitter<{ changed: [owner: string] }>();
22
+
23
+ export function builtinAgentDefaults(owner: string): Defaults {
24
+ const admin = getUser(owner)?.role === "admin";
25
+ const stored = readJson<Record<string, Partial<Defaults>>>(file, {})[owner];
26
+ const defaults = (engine: Engine): BuiltinAgentDefaults => ({
27
+ skills: stored?.[engine]?.skills ?? null,
28
+ machineSkills: admin && stored?.[engine]?.machineSkills !== false,
29
+ mcp: stored?.[engine]?.mcp ?? (admin ? null : []),
30
+ });
31
+ return { claude: defaults("claude"), codex: defaults("codex") };
32
+ }
33
+
34
+ function selection(value: unknown, what: string): string[] | null {
35
+ if (value === null) return null;
36
+ if (!Array.isArray(value) || value.length > 200 || value.some((v) => typeof v !== "string" || v.length > 100)) throw new Error(`${what}必须是列表或 null`);
37
+ return [...new Set(value as string[])];
38
+ }
39
+
40
+ export function setBuiltinAgentDefaults(owner: string, patch: unknown): Defaults {
41
+ if (!patch || typeof patch !== "object" || Array.isArray(patch)) throw new Error("Agent 配置格式不对");
42
+ const user = getUser(owner);
43
+ if (!user) throw new Error("用户不存在");
44
+ const next = builtinAgentDefaults(owner);
45
+ const available = new Set(activeSkills(owner).map((s) => s.id));
46
+ for (const [engine, raw] of Object.entries(patch)) {
47
+ if (!ENGINES.includes(engine as Engine) || !raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("Agent 配置格式不对");
48
+ const p = raw as Record<string, unknown>;
49
+ const current = next[engine as Engine];
50
+ if (p.skills !== undefined) {
51
+ const ids = selection(p.skills, "技能");
52
+ if (ids?.some((id) => !available.has(id))) throw new Error("只能选择自己已启用的技能");
53
+ current.skills = ids;
54
+ }
55
+ if (p.machineSkills !== undefined) {
56
+ if (typeof p.machineSkills !== "boolean") throw new Error("机器技能开关必须是布尔值");
57
+ if (p.machineSkills && user.role !== "admin") throw new Error("只有管理员能加载机器上的技能");
58
+ current.machineSkills = p.machineSkills;
59
+ }
60
+ if (p.mcp !== undefined) {
61
+ const ids = selection(p.mcp, "MCP");
62
+ if (ids === null && user.role !== "admin") throw new Error("只有管理员能沿用机器 MCP 配置");
63
+ const names = new Set<string>();
64
+ for (const id of ids ?? []) {
65
+ const server = getMcp(id);
66
+ const name = isMachineId(id) ? machineName(id) : server?.name;
67
+ if (isMachineId(id) ? user.role !== "admin" || !name || !/^[A-Za-z0-9_-]{1,100}$/.test(name) : !server || server.owner !== owner) throw new Error("只能选择自己的 MCP(机器 MCP 仅管理员可选)");
68
+ if (names.has(name!)) throw new Error(`MCP 服务名重复:${name}`);
69
+ names.add(name!);
70
+ }
71
+ current.mcp = ids;
72
+ }
73
+ }
74
+ const all = readJson<Record<string, Defaults>>(file, {});
75
+ all[owner] = next;
76
+ writeJsonAtomic(file, all);
77
+ builtinAgentEvents.emit("changed", owner);
78
+ return next;
79
+ }
80
+
81
+ export function builtinAgentSession(owner: string | undefined, engine: Engine): Pick<SessionOptions, "skills" | "builtinMcp"> {
82
+ if (!owner || !getUser(owner)) return {};
83
+ const prefs = builtinAgentDefaults(owner)[engine];
84
+ const resolved = resolveMcp({ owner, engine, mcp: prefs.mcp ?? [] }, getUser(owner)?.role === "admin");
85
+ return {
86
+ skills: sessionSkills(owner, prefs.skills ?? undefined, prefs.machineSkills, `builtin-${engine}`),
87
+ builtinMcp: { mcp: resolved.mcp, askMcp: resolved.ask, machineMcp: resolved.machine, inheritMachine: prefs.mcp === null },
88
+ };
89
+ }
90
+
91
+ export function deleteBuiltinAgentDefaults(owner: string): void {
92
+ const all = readJson<Record<string, Defaults>>(file, {});
93
+ if (!(owner in all)) return;
94
+ delete all[owner];
95
+ writeJsonAtomic(file, all);
96
+ }
@@ -26,6 +26,10 @@ export type FeishuBotConfig = {
26
26
  agents: string[];
27
27
  /** 新会话默认用哪个 agent,必须在 agents 里 */
28
28
  defaultAgent: string;
29
+ /** 明确选择可用专家(内置 id 或共享专家 id);未设置时兼容旧的按引擎配置 */
30
+ experts?: string[];
31
+ /** 新聊天默认使用的专家,必须在 experts 中 */
32
+ defaultExpert?: string;
29
33
  };
30
34
 
31
35
  export type AppConfig = {
@@ -167,6 +171,7 @@ function mergeDefaults<T>(base: T, value: unknown): T {
167
171
  function normalizeBot(raw: Partial<FeishuBotConfig>): FeishuBotConfig {
168
172
  const agents = (raw.agents ?? []).filter((a) => (AGENT_IDS as readonly string[]).includes(a));
169
173
  const list = agents.length > 0 ? agents : ["claude"];
174
+ const experts = Array.isArray(raw.experts) ? [...new Set(raw.experts.filter((id) => typeof id === "string" && (AGENT_IDS.includes(id as typeof AGENT_IDS[number]) || /^e_[a-f0-9]+$/.test(id))))] : undefined;
170
175
  return {
171
176
  id: raw.id?.trim() || `bot_${crypto.randomBytes(3).toString("hex")}`,
172
177
  name: raw.name?.trim() || "飞书机器人",
@@ -179,6 +184,7 @@ function normalizeBot(raw: Partial<FeishuBotConfig>): FeishuBotConfig {
179
184
  .filter((s) => s.startsWith("ou_")),
180
185
  agents: list,
181
186
  defaultAgent: raw.defaultAgent && list.includes(raw.defaultAgent) ? raw.defaultAgent : list[0]!,
187
+ ...(experts ? { experts, defaultExpert: raw.defaultExpert && experts.includes(raw.defaultExpert) ? raw.defaultExpert : experts[0] ?? "" } : {}),
182
188
  };
183
189
  }
184
190
 
@@ -2,10 +2,10 @@
2
2
  // 挂哪些技能和 MCP、能把活派给哪些子智能体。新建对话、定时任务时选一个专家,对话从头到尾都是它,
3
3
  // 中途不能换(飞书里换专家等于开新会话)。
4
4
  //
5
- // 两个内置专家 claude、codex 不存盘:就是 agent 原装的样子(原装提示词、机器上的技能和 MCP、所有工具)。
5
+ // 两个内置专家 claude、codex 不存成自定义专家:保留原装提示词和工具,技能 / MCP 默认项由 builtin-agents.ts 按人保存。
6
6
  // 对话和任务里没写 expert 的,专家就是它的 agent —— 升级前的数据不用迁移。
7
7
  //
8
- // 自定义专家每人管自己的,不分享。存储:data/experts.json,只有主进程读写。
8
+ // 自定义专家由创建者维护;共享后其他账号可以使用,技能、MCP 和记忆仍按使用者分别加载。
9
9
  import crypto from "node:crypto";
10
10
  import { EventEmitter } from "node:events";
11
11
  import fs from "node:fs";
@@ -34,6 +34,8 @@ export type QuickPrompt = { title: string; prompt: string };
34
34
  export type Expert = {
35
35
  id: string;
36
36
  owner: string;
37
+ /** 共享给所有已登录、已绑定的账号;只有创建者能修改设定 */
38
+ shared?: boolean;
37
39
  name: string;
38
40
  description: string;
39
41
  /** emoji(以前的图标;有头像时用头像) */
@@ -107,6 +109,10 @@ type StoredExpert = Omit<Expert, "avatar"> & { avatar?: string; avatarFile?: str
107
109
 
108
110
  /** 专家改了 / 删了。owner:谁的。用着它的会话空闲下来要换上新的 */
109
111
  export const expertEvents = new EventEmitter<{ changed: [owner: string, id: string] }>();
112
+ export const expertToolEvents = new EventEmitter<{ changed: [owner: string, id: string] }>();
113
+ export type ExpertTools = { skills: string[]; mcp: string[] };
114
+ const toolsPath = path.join(dataDir, "expert-tools.json");
115
+ type PersonalTools = Record<string, Record<string, ExpertTools>>;
110
116
 
111
117
  let cache: Expert[] | null = null;
112
118
 
@@ -179,15 +185,70 @@ export function listExperts(owner: string): Expert[] {
179
185
  .sort((a, b) => a.createdAt - b.createdAt);
180
186
  }
181
187
 
188
+ /** 选择器展示自己的专家和其他人共享的专家;不改变 listExperts 的所有权语义。 */
189
+ export function availableExperts(owner: string): Expert[] {
190
+ return load().filter((e) => canUseExpert(owner, e.id)).sort((a, b) => a.createdAt - b.createdAt);
191
+ }
192
+
182
193
  export function getExpert(id: string): Expert | undefined {
183
194
  return load().find((e) => e.id === id);
184
195
  }
185
196
 
186
- /** 谁都能用的(内置)或者是他自己的 */
197
+ /** 共享只开放使用权,不转移专家、工具或会话的所有权。无身份的飞书聊天不能用。 */
187
198
  export function canUseExpert(owner: string | undefined, id: string): boolean {
188
199
  if (isBuiltin(id)) return true;
189
200
  const e = getExpert(id);
190
- return !!e && !!owner && e.owner === owner;
201
+ if (!e || !owner) return false;
202
+ if (e.owner === owner) return true;
203
+ const creator = getUser(e.owner);
204
+ const user = getUser(owner);
205
+ return e.shared === true && !!creator && !creator.disabled && !!user && !user.disabled;
206
+ }
207
+
208
+ /** 发布者沿用专家原有的工具选择;其他人未配置时不加载技能和 MCP。 */
209
+ export function expertTools(owner: string, expert: Expert): ExpertTools {
210
+ if (!canUseExpert(owner, expert.id)) throw new Error("这个专家不存在或已取消共享");
211
+ if (expert.owner === owner) return { skills: expert.skills, mcp: expert.mcp };
212
+ return readJson<PersonalTools>(toolsPath, {})[owner]?.[expert.id] ?? { skills: [], mcp: [] };
213
+ }
214
+
215
+ export function setExpertTools(owner: string, id: string, input: unknown): ExpertTools {
216
+ const expert = getExpert(id);
217
+ if (!expert || !canUseExpert(owner, id)) throw new Error("这个专家不存在或已取消共享");
218
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("工具配置格式不对");
219
+ const raw = input as Record<string, unknown>;
220
+ const selection = (value: unknown): string[] => {
221
+ if (!Array.isArray(value) || value.length > 200 || value.some((v) => typeof v !== "string" || v.length > 100)) throw new Error("技能和 MCP 必须是列表");
222
+ return [...new Set(value as string[])];
223
+ };
224
+ const next = { skills: selection(raw.skills), mcp: selection(raw.mcp) };
225
+ const available = new Set(activeSkills(owner).map((s) => s.id));
226
+ if (next.skills.some((id) => !available.has(id))) throw new Error("只能选择自己已启用的技能");
227
+ const admin = getUser(owner)?.role === "admin";
228
+ const names = new Set<string>();
229
+ for (const id of next.mcp) {
230
+ const server = getMcp(id);
231
+ const name = isMachineId(id) ? machineName(id) : server?.name;
232
+ if (isMachineId(id) ? !admin || !name || !/^[A-Za-z0-9_-]{1,100}$/.test(name) : !server || server.owner !== owner) throw new Error("只能选择自己的 MCP(机器 MCP 仅管理员可选)");
233
+ if (names.has(name!)) throw new Error(`MCP 服务名重复:${name}`);
234
+ names.add(name!);
235
+ }
236
+ if (expert.owner === owner) {
237
+ updateExpert(owner, id, next);
238
+ } else {
239
+ const all = readJson<PersonalTools>(toolsPath, {});
240
+ (all[owner] ??= {})[id] = next;
241
+ writeJsonAtomic(toolsPath, all);
242
+ expertToolEvents.emit("changed", owner, id);
243
+ }
244
+ return next;
245
+ }
246
+
247
+ function purgeExpertTools(owner?: string, expertId?: string): void {
248
+ const all = readJson<PersonalTools>(toolsPath, {});
249
+ if (owner) delete all[owner];
250
+ if (expertId) for (const tools of Object.values(all)) delete tools[expertId];
251
+ writeJsonAtomic(toolsPath, all);
191
252
  }
192
253
 
193
254
  export const accessRank = (a: ExpertAccess) => ACCESS_LEVELS.indexOf(a);
@@ -208,6 +269,9 @@ function validate(owner: string, input: ExpertInput, prev?: Expert, selfId?: str
208
269
  const user = getUser(owner);
209
270
  if (!user) throw new Error("用户不存在");
210
271
  const admin = user.role === "admin";
272
+ const sharedRaw = pick("shared");
273
+ if (sharedRaw !== undefined && typeof sharedRaw !== "boolean") throw new Error("共享开关必须是布尔值");
274
+ const shared = sharedRaw === true;
211
275
 
212
276
  const name = text(pick("name"), EXPERT_LIMITS.name, "名字");
213
277
  if (!name) throw new Error("给专家起个名字");
@@ -255,6 +319,7 @@ function validate(owner: string, input: ExpertInput, prev?: Expert, selfId?: str
255
319
  if (id === selfId) throw new Error("子智能体不能是它自己");
256
320
  const sub = getExpert(id);
257
321
  if (!sub || sub.owner !== owner) continue;
322
+ if (shared && !sub.shared) throw new Error(`共享专家的子智能体「${sub.name}」也需要先共享`);
258
323
  if (sub.engine !== "claude") throw new Error(`「${sub.name}」是 Codex 专家,子智能体只能用 Claude 专家`);
259
324
  if (accessRank(sub.access) > accessRank(access as ExpertAccess)) {
260
325
  throw new Error(`「${sub.name}」的权限(${ACCESS_LABEL[sub.access]})比这个专家高,子智能体的权限不能超过主专家`);
@@ -273,6 +338,7 @@ function validate(owner: string, input: ExpertInput, prev?: Expert, selfId?: str
273
338
  const model = text(pick("model"), 100, "模型");
274
339
  const effort = text(pick("effort"), 20, "思考程度");
275
340
  return {
341
+ shared,
276
342
  name,
277
343
  description: text(pick("description"), EXPERT_LIMITS.description, "说明"),
278
344
  icon: text(pick("icon"), 16, "图标"),
@@ -316,7 +382,13 @@ export function updateExpert(owner: string, id: string, input: ExpertInput): Exp
316
382
  const next: Expert = { id, owner, ...validate(owner, input, prev, id), rev: prev.rev + 1, createdAt: prev.createdAt, updatedAt: Date.now() };
317
383
  list[idx] = next;
318
384
  save();
319
- expertEvents.emit("changed", owner, id);
385
+ // 工具是发布者本人的选择,不需要让其他使用者重载共享设定。
386
+ const definitionChanged = [...new Set([...Object.keys(prev), ...Object.keys(next)])].some((key) =>
387
+ !["skills", "mcp", "rev", "updatedAt"].includes(key) &&
388
+ JSON.stringify(prev[key as keyof Expert]) !== JSON.stringify(next[key as keyof Expert]),
389
+ );
390
+ if (definitionChanged) expertEvents.emit("changed", owner, id);
391
+ else expertToolEvents.emit("changed", owner, id);
320
392
  return next;
321
393
  }
322
394
 
@@ -325,6 +397,7 @@ export function deleteExpert(owner: string, id: string): void {
325
397
  const idx = list.findIndex((e) => e.id === id && e.owner === owner);
326
398
  if (idx < 0) throw new Error("这个专家不存在");
327
399
  list.splice(idx, 1);
400
+ purgeExpertTools(undefined, id);
328
401
  // 别的专家把它当子智能体的,一并去掉
329
402
  for (const e of list) {
330
403
  if (e.subagents.includes(id)) {
@@ -338,11 +411,9 @@ export function deleteExpert(owner: string, id: string): void {
338
411
  }
339
412
 
340
413
  export function purgeUserExperts(owner: string): void {
414
+ purgeExpertTools(owner);
341
415
  const list = load();
342
- const kept = list.filter((e) => e.owner !== owner);
343
- if (kept.length === list.length) return;
344
- cache = kept;
345
- save();
416
+ for (const e of [...list]) if (e.owner === owner) deleteExpert(owner, e.id);
346
417
  }
347
418
 
348
419
  // ---------- 开会话时 ----------
@@ -389,7 +460,7 @@ export type ExpertRuntime = {
389
460
  };
390
461
 
391
462
  /** 专家选中的 MCP 解析成启动参数。机器上的:Claude 读 ~/.claude.json,Codex 只要名字(由它自己按 config.toml 起) */
392
- function resolveMcp(expert: Expert, admin: boolean): { mcp: Record<string, ResolvedMcp>; ask: string[]; machine: string[] } {
463
+ export function resolveMcp(expert: Pick<Expert, "owner" | "engine" | "mcp">, admin: boolean): { mcp: Record<string, ResolvedMcp>; ask: string[]; machine: string[] } {
393
464
  const mcp: Record<string, ResolvedMcp> = {};
394
465
  const ask: string[] = [];
395
466
  const machine: string[] = [];
@@ -428,18 +499,23 @@ function subagentKey(name: string, taken: Set<string>): string {
428
499
  * 按专家配置拼出交给 driver 的样子。prompt:子智能体的完整提示词怎么拼(core/expert-prompt.ts 给)。
429
500
  * 子智能体的权限封顶在主专家的权限:主专家后来降了权限也不会被子智能体绕过去。
430
501
  */
431
- export function expertRuntime(expert: Expert, subPrompt: (sub: Expert, access: ExpertAccess) => string): ExpertRuntime {
432
- const admin = getUser(expert.owner)?.role === "admin";
433
- const active = new Map(activeSkills(expert.owner).map((s) => [s.id, s]));
434
- const { mcp, ask, machine } = resolveMcp(expert, admin);
502
+ export function expertRuntime(expert: Expert, subPrompt: (sub: Expert, access: ExpertAccess) => string, owner = expert.owner): ExpertRuntime {
503
+ if (!canUseExpert(owner, expert.id)) throw new Error("这个专家不存在或已取消共享");
504
+ const tools = expertTools(owner, expert);
505
+ const admin = getUser(owner)?.role === "admin";
506
+ const active = new Map(activeSkills(owner).map((s) => [s.id, s]));
507
+ const { mcp, ask, machine } = resolveMcp({ owner, engine: expert.engine, mcp: tools.mcp }, admin);
435
508
  const taken = new Set<string>();
436
509
  const subagents: SubagentRuntime[] = [];
437
510
  if (expert.engine === "claude") {
438
511
  for (const id of expert.subagents) {
439
512
  const sub = getExpert(id);
440
513
  if (!sub || sub.owner !== expert.owner || sub.engine !== "claude" || sub.id === expert.id) continue;
514
+ // 共享主专家不能把未共享的私人子专家带给其他使用者。
515
+ if ((expert.shared && !sub.shared) || !canUseExpert(owner, sub.id)) continue;
516
+ const subTools = expertTools(owner, sub);
441
517
  const access = accessRank(sub.access) > accessRank(expert.access) ? expert.access : sub.access;
442
- const subMcp = resolveMcp(sub, admin).mcp;
518
+ const subMcp = resolveMcp({ owner, engine: sub.engine, mcp: subTools.mcp }, admin).mcp;
443
519
  subagents.push({
444
520
  key: subagentKey(sub.name, taken),
445
521
  name: sub.name,
@@ -449,7 +525,7 @@ export function expertRuntime(expert: Expert, subPrompt: (sub: Expert, access: E
449
525
  webSearch: sub.webSearch,
450
526
  webFetch: sub.webFetch,
451
527
  ...(sub.model ? { model: sub.model } : {}),
452
- skills: sub.skills.map((s) => active.get(s)?.name).filter((n): n is string => !!n),
528
+ skills: subTools.skills.map((s) => active.get(s)?.name).filter((n): n is string => !!n),
453
529
  mcp: subMcp,
454
530
  });
455
531
  }
@@ -463,7 +539,7 @@ export function expertRuntime(expert: Expert, subPrompt: (sub: Expert, access: E
463
539
  access: expert.access,
464
540
  webSearch: expert.webSearch,
465
541
  webFetch: expert.webFetch,
466
- skills: expert.skills.filter((id) => active.has(id)),
542
+ skills: tools.skills.filter((id) => active.has(id)),
467
543
  mcp,
468
544
  askMcp: ask,
469
545
  machineMcp: machine,
@@ -0,0 +1,28 @@
1
+ // 飞书机器人的专家选择与兼容旧的按引擎配置。无效、删除或撤回共享的专家不能退回内置 Agent。
2
+ import type { FeishuBotConfig } from "./config.js";
3
+ import { getExpert, isBuiltin } from "./experts.js";
4
+ import { getUser } from "./users.js";
5
+
6
+ export function botExpertEngine(id: string): string | undefined {
7
+ if (isBuiltin(id)) return id;
8
+ const expert = getExpert(id);
9
+ const creator = expert && getUser(expert.owner);
10
+ return expert?.shared && creator && !creator.disabled ? expert.engine : undefined;
11
+ }
12
+
13
+ export function botExpertIds(cfg: FeishuBotConfig): string[] | undefined {
14
+ return cfg.experts?.filter((id) => !!botExpertEngine(id));
15
+ }
16
+
17
+ export function botAgentIds(cfg: FeishuBotConfig): string[] {
18
+ return cfg.experts === undefined ? cfg.agents : [...new Set(cfg.experts.map(botExpertEngine).filter((id): id is string => !!id))];
19
+ }
20
+
21
+ /** 配置接口严格校验;引擎随专家推导,前端不需要再额外勾底层 Agent。 */
22
+ export function botExpertSelection(experts: unknown, defaultExpert: unknown): Pick<FeishuBotConfig, "experts" | "defaultExpert" | "agents" | "defaultAgent"> {
23
+ if (!Array.isArray(experts) || !experts.length || experts.length > 200 || experts.some((id) => typeof id !== "string" || !botExpertEngine(id))) throw new Error("至少选择一个内置专家或仍在共享的专家");
24
+ const selected = [...new Set(experts as string[])];
25
+ const first = typeof defaultExpert === "string" && selected.includes(defaultExpert) ? defaultExpert : selected[0]!;
26
+ const agents = [...new Set(selected.map((id) => botExpertEngine(id)!))];
27
+ return { experts: selected, defaultExpert: first, agents, defaultAgent: botExpertEngine(first)! };
28
+ }
package/src/core/hub.ts CHANGED
@@ -30,7 +30,7 @@ import {
30
30
  import { attachmentInfo, ensureUploadsDir, KIND_LABEL } from "./uploads.js";
31
31
  import { memoryOwnerOf, sessionMemory } from "./personal.js";
32
32
  import { readMemory } from "./memory.js";
33
- import { getUser } from "./users.js";
33
+ import { getUser, userEvents } from "./users.js";
34
34
  import type {
35
35
  AgentDriver,
36
36
  AttachmentInfo,
@@ -50,7 +50,8 @@ import { buildCatalog, expandCustomCommand, type AgentCommand, type CommandEntry
50
50
  import { helpText, type ParsedCommand } from "./commands.js";
51
51
  import { listScheduled } from "./scheduled.js";
52
52
  import { expertSystemPrompt, searchLabel, stripContext } from "./expert-prompt.js";
53
- import { avatarUrl, expertEvents, expertRuntime, getExpert, isBuiltin, listExperts, type ExpertRuntime } from "./experts.js";
53
+ import { availableExperts, avatarUrl, canUseExpert, expertEvents, expertToolEvents, expertRuntime, getExpert, isBuiltin, type ExpertRuntime } from "./experts.js";
54
+ import { builtinAgentDefaults, builtinAgentEvents, builtinAgentSession } from "./builtin-agents.js";
54
55
  import { mcpEvents } from "./mcp.js";
55
56
  import { isMachineCommand, sessionSkills } from "./skill-runtime.js";
56
57
  import { skillEvents } from "./skills.js";
@@ -278,9 +279,29 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
278
279
  interactions.on("created", (i) => this.emitEvent(i.convKey, { type: "ix", id: i.id }));
279
280
  // 技能装了、改了、停用了、变量改了:受影响的人空闲的会话换上新的
280
281
  skillEvents.on("changed", (users) => this.personalChanged(new Set(users)));
281
- // 专家、MCP 改了:用着自定义专家的会话空闲下来换上新的(内置专家不受影响)
282
- expertEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
283
- mcpEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
282
+ // 专家修改只影响自定义专家;MCP 和内置默认配置修改也更新该账号的内置会话。
283
+ expertEvents.on("changed", (_owner, id) => {
284
+ for (const conv of listConversations()) {
285
+ if (conv.expert !== id && !(conv.expert && getExpert(conv.expert)?.subagents.includes(id))) continue;
286
+ const live = this.live.get(conv.key);
287
+ if (live) {
288
+ this.staleLive.add(live.id);
289
+ this.dropIfStale(conv.key);
290
+ }
291
+ this.emitEvent(conv.key, { type: "meta" });
292
+ }
293
+ });
294
+ expertToolEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
295
+ userEvents.on("changed", () => {
296
+ for (const [key, live] of this.live) {
297
+ const conv = getConversation(key);
298
+ if (!conv?.expert || canUseExpert(memoryOwnerOf(conv), conv.expert)) continue;
299
+ this.staleLive.add(live.id);
300
+ this.dropIfStale(key);
301
+ }
302
+ });
303
+ mcpEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
304
+ builtinAgentEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
284
305
  // workspaceRoot 改了:store 会把没显式 /cd 过的会话目录重置,正在跑的旧目录会话要作废
285
306
  onConfigChange((next, prev) => {
286
307
  // 默认模型可能改了,缓存作废,下次显示时重新读
@@ -400,7 +421,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
400
421
  expertBadge(conv: Pick<Conversation, "agent" | "expert" | "owner" | "channel">): ExpertBadge {
401
422
  if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true };
402
423
  const e = getExpert(conv.expert);
403
- if (!e || e.owner !== memoryOwnerOf(conv)) return { id: conv.expert, name: "(已删除的专家)", missing: true };
424
+ if (!e || !canUseExpert(memoryOwnerOf(conv), e.id)) return { id: conv.expert, name: "(专家已删除或未共享)", missing: true };
404
425
  return {
405
426
  id: e.id,
406
427
  name: e.name,
@@ -415,27 +436,29 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
415
436
 
416
437
  /**
417
438
  * 拉起会话时交给 driver 的专家。内置专家返回 undefined(agent 原装的样子)。
418
- * 专家被删了、不是对话主人的、引擎对不上:抛错 —— 不能悄悄换成别的专家接着聊。
439
+ * 专家被删了、未授权共享、引擎对不上:抛错 —— 不能悄悄换成别的专家接着聊。
419
440
  */
420
441
  private expertFor(conv: Conversation): ExpertRuntime | undefined {
421
442
  if (!conv.expert) return undefined;
422
443
  const e = getExpert(conv.expert);
423
- if (!e || e.owner !== memoryOwnerOf(conv)) throw new Error("这条对话用的专家已经删除了。新开一个对话,换个专家吧。");
444
+ const owner = memoryOwnerOf(conv);
445
+ if (!e || !owner || !canUseExpert(owner, e.id)) throw new Error("这条对话用的专家已经删除或取消共享了。新开一个对话,换个专家吧。");
424
446
  if (e.engine !== conv.agent) throw new Error(`专家「${e.name}」的引擎和这条对话的对不上,新开一个对话吧。`);
425
447
  return expertRuntime(e, (sub, access) =>
426
448
  expertSystemPrompt({ name: sub.name, prompt: sub.prompt, access, webSearch: sub.webSearch, webFetch: sub.webFetch }, searchLabel("claude", sub), conv.cwd),
449
+ owner,
427
450
  );
428
451
  }
429
452
 
430
453
  /**
431
- * 这个人在某个渠道能选的专家:允许的内置专家(agent 启用着的),加上他自己的、引擎可用的专家。
454
+ * 这个人在某个渠道能选的专家:允许的内置专家(agent 启用着的),加上自己的及共享的、引擎可用的专家。
432
455
  * 没有主人的对话(飞书群聊等)只有内置专家。
433
456
  */
434
- expertChoices(owner: string | undefined, allowedAgents: string[]): { id: string; label: string; engine: string }[] {
457
+ expertChoices(owner: string | undefined, allowedAgents: string[], allowedExperts?: string[]): { id: string; label: string; engine: string }[] {
435
458
  const usable = new Set(this.enabledAgents().map((d) => d.id).filter((a) => allowedAgents.includes(a)));
436
459
  const builtin = [...usable].map((a) => ({ id: a, label: this.label(a), engine: a }));
437
- const own = owner ? listExperts(owner).filter((e) => usable.has(e.engine)) : [];
438
- return [...builtin, ...own.map((e) => ({ id: e.id, label: `${e.icon ? `${e.icon} ` : ""}${e.name}`, engine: e.engine }))];
460
+ const own = owner ? availableExperts(owner).filter((e) => usable.has(e.engine)) : [];
461
+ return [...builtin, ...own.map((e) => ({ id: e.id, label: `${e.icon ? `${e.icon} ` : ""}${e.name}`, engine: e.engine }))].filter((e) => allowedExperts === undefined || allowedExperts.includes(e.id));
439
462
  }
440
463
 
441
464
  /** 已注册且在配置里启用的 agent */
@@ -615,6 +638,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
615
638
  if (!conv) throw new Error(`会话不存在:${key}`);
616
639
  // 先检查 agent 还启用着:设置里关掉了,已经打开的会话也不能再用
617
640
  const driver = this.requireDriver(conv.agent);
641
+ // 撤回共享后,即使上一轮还在运行,也不能把新输入交给缓存着的会话。
642
+ if (conv.expert && !canUseExpert(memoryOwnerOf(conv), conv.expert)) throw new Error("这条对话用的专家已经删除或取消共享了。新开一个对话,换个专家吧。");
618
643
  const existing = this.live.get(key);
619
644
  if (existing && existing.agent === conv.agent && existing.cwd === conv.cwd && !opts.resumeId) {
620
645
  return existing.session;
@@ -650,7 +675,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
650
675
  const taskOwner = memoryOwnerOf(conv);
651
676
  // 技能也跟着主人走:他启用的技能、填的变量;成员看不到机器上原有的技能(见 skill-runtime.ts)。
652
677
  // 自定义专家只给它选中的
653
- const skills = sessionSkills(taskOwner, expert?.skills);
678
+ const builtin = !expert && isBuiltin(agent) ? builtinAgentSession(taskOwner, agent) : {};
679
+ const skills = expert ? sessionSkills(taskOwner, expert.skills) : builtin.skills;
654
680
  const session = driver.createSession(
655
681
  {
656
682
  cwd: conv.cwd,
@@ -664,6 +690,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
664
690
  ...(memory ? { memory } : {}),
665
691
  ...(taskOwner ? { tasks: { userId: taskOwner, convKey: key } } : {}),
666
692
  ...(skills ? { skills } : {}),
693
+ ...(builtin.builtinMcp ? { builtinMcp: builtin.builtinMcp } : {}),
667
694
  },
668
695
  {
669
696
  onUserAnchor: (input, anchor) => {
@@ -1050,11 +1077,11 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1050
1077
  // 只有内置的 Claude Code 专家读机器上的技能;自定义专家的技能白名单里只有它选的
1051
1078
  if (!conv || conv.agent !== "claude" || conv.expert) return null;
1052
1079
  const owner = memoryOwnerOf(conv);
1053
- if (!owner || getUser(owner)?.role === "admin") return null;
1080
+ if (!owner || (getUser(owner)?.role === "admin" && builtinAgentDefaults(owner).claude.machineSkills)) return null;
1054
1081
  const driver = this.enabledAgents().find((d) => d.id === conv.agent);
1055
1082
  if (!driver?.commands) return null;
1056
1083
  const native = await withTimeout(driver.commands(conv.cwd), "读取命令列表").catch(() => [] as AgentCommand[]);
1057
- return isMachineCommand(m[1]!, native, conv.cwd) ? `/${m[1]} 是这台机器上装的技能,只有管理员能用。` : null;
1084
+ return isMachineCommand(m[1]!, native, conv.cwd) ? `/${m[1]} 是机器上的技能,当前账号的 Agent 设置未允许加载。` : null;
1058
1085
  }
1059
1086
 
1060
1087
  /** 刚点过停止(被打断的那一轮还可能晚到一个出错,见 onError 里的 stopped) */
@@ -1310,7 +1337,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1310
1337
 
1311
1338
  /**
1312
1339
  * 这些人的记忆、技能、专家或 MCP 变了:他们名下活着的会话空闲下来就重新拉起。
1313
- * onlyExperts:只管用自定义专家的会话(专家、MCP 变了不影响内置专家)
1340
+ * onlyExperts:只管用自定义专家的会话(修改自定义专家配置时使用)
1314
1341
  */
1315
1342
  private personalChanged(users: Set<string>, onlyExperts = false): void {
1316
1343
  for (const [key, live] of this.live) {
@@ -1348,11 +1375,11 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1348
1375
  * 换专家(飞书里的 /agent、/claude、/codex):对话中途不能换专家,所以换了就开新会话。
1349
1376
  * target 可以是专家 id,也可以是名字。allowed:这个渠道允许的内置 agent。
1350
1377
  */
1351
- private async setExpertNow(key: string, target: string, allowed: string[], op: SwitchOp): Promise<string> {
1378
+ private async setExpertNow(key: string, target: string, allowed: string[], op: SwitchOp, allowedExperts?: string[]): Promise<string> {
1352
1379
  const conv = getConversation(key)!;
1353
1380
  // 网页上的对话(包括飞书 /web 接上的)从头到尾一个专家:要换就新建对话
1354
1381
  if (conv.channel === "web") return "网页上的对话中途不能换专家。在网页上新建一个对话,选好专家再聊。";
1355
- const choices = this.expertChoices(memoryOwnerOf(conv), allowed);
1382
+ const choices = this.expertChoices(memoryOwnerOf(conv), allowed, allowedExperts);
1356
1383
  const want = target.trim().toLowerCase();
1357
1384
  const hit = choices.find((c) => c.id.toLowerCase() === want) ?? choices.find((c) => c.label.toLowerCase().includes(want));
1358
1385
  if (!hit) return `这里没有「${target}」这个专家。可选:${choices.map((c) => c.label).join("、")}`;
@@ -1635,8 +1662,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1635
1662
  return this.serial(key, () => this.setEffortNow(key, effort));
1636
1663
  }
1637
1664
 
1638
- setExpert(key: string, target: string, allowed: string[]): Promise<string> {
1639
- return this.switchOp(key, (op) => this.setExpertNow(key, target, allowed, op));
1665
+ setExpert(key: string, target: string, allowed: string[], allowedExperts?: string[]): Promise<string> {
1666
+ return this.switchOp(key, (op) => this.setExpertNow(key, target, allowed, op, allowedExperts));
1640
1667
  }
1641
1668
 
1642
1669
  cd(key: string, dir: string): Promise<string> {
@@ -1658,6 +1685,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1658
1685
  cmd: ParsedCommand,
1659
1686
  ctx: {
1660
1687
  allowedAgents: string[];
1688
+ allowedExperts?: string[];
1661
1689
  by: string;
1662
1690
  channel?: string;
1663
1691
  /** 多用户:发命令的人能看到哪些 agent 会话(/sessions 列哪些、/resume 能恢复哪些) */
@@ -1682,7 +1710,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1682
1710
  ...(channel ? { channel } : {}),
1683
1711
  ...(owner && getUser(owner)?.role !== "admin" ? { member: true } : {}),
1684
1712
  });
1685
- return { type: "commands", agent: conv.agent, commands: all.filter((c) => !c.hidden) };
1713
+ return { type: "commands", agent: conv.agent, commands: all.filter((c) => !c.hidden && (!["claude", "codex"].includes(c.name) || ctx.allowedExperts === undefined || ctx.allowedExperts.includes(c.name))) };
1686
1714
  }
1687
1715
  case "pwd":
1688
1716
  return text(getConversation(key)!.cwd);
@@ -1715,11 +1743,11 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1715
1743
  const conv = getConversation(key)!;
1716
1744
  return {
1717
1745
  type: "agents",
1718
- agents: this.expertChoices(memoryOwnerOf(conv), ctx.allowedAgents).map(({ id, label }) => ({ id, label })),
1746
+ agents: this.expertChoices(memoryOwnerOf(conv), ctx.allowedAgents, ctx.allowedExperts).map(({ id, label }) => ({ id, label })),
1719
1747
  current: expertIdOf(conv),
1720
1748
  };
1721
1749
  }
1722
- return text(await this.setExpert(key, cmd.agent, ctx.allowedAgents));
1750
+ return text(await this.setExpert(key, cmd.agent, ctx.allowedAgents, ctx.allowedExperts));
1723
1751
  }
1724
1752
  case "stop":
1725
1753
  return text(await this.stop(key));
package/src/core/mcp.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  // 和技能一样是「信任型」的:能执行命令的专家读得到 data/ 下的文件,包括这里的值。
8
8
  //
9
9
  // 机器上原有的 MCP(Claude 的 ~/.claude.json、Codex 的 config.toml)只给管理员选,id 写成 machine:<名字>。
10
- // 内置的 Claude Code / Codex 专家不经过这里:它们照旧加载机器上的配置。
10
+ // 内置的 Claude Code / Codex 专家按 builtin-agents.ts 的个人默认选择加载;管理员默认沿用机器配置。
11
11
  //
12
12
  // 存储:data/mcp.json,所有人的放在一起,只有主进程读写。
13
13
  import crypto from "node:crypto";
@@ -8,6 +8,7 @@ import { purgeUserExperts } from "./experts.js";
8
8
  import { purgeUserMcp } from "./mcp.js";
9
9
  import type { Conversation } from "./store.js";
10
10
  import { getUser, legacyOwnerId } from "./users.js";
11
+ import { deleteBuiltinAgentDefaults } from "./builtin-agents.js";
11
12
  import { deleteUiPrefs } from "./ui-prefs.js";
12
13
 
13
14
  /**
@@ -51,4 +52,5 @@ export function purgeUserData(userId: string): void {
51
52
  purgeUserExperts(userId);
52
53
  purgeUserMcp(userId);
53
54
  deleteUiPrefs(userId);
55
+ deleteBuiltinAgentDefaults(userId);
54
56
  }