agent-loft 0.2.48 → 0.2.50

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 (57) hide show
  1. package/README.md +32 -15
  2. package/package.json +1 -1
  3. package/src/agents/claude/driver.ts +1 -1
  4. package/src/agents/claude/session.ts +140 -47
  5. package/src/agents/codex/driver.ts +1 -1
  6. package/src/agents/codex/session.ts +90 -58
  7. package/src/channels/feishu/bot.ts +1 -3
  8. package/src/channels/feishu/cards.ts +2 -2
  9. package/src/channels/web/api.ts +49 -19
  10. package/src/channels/web/conv-pages.ts +37 -0
  11. package/src/channels/web/experts-api.ts +203 -0
  12. package/src/channels/web/skills-api.ts +1 -7
  13. package/src/channels/web/tasks-api.ts +9 -5
  14. package/src/core/command-catalog.ts +4 -6
  15. package/src/core/commands.ts +6 -11
  16. package/src/core/expert-prompt.ts +119 -0
  17. package/src/core/experts.ts +438 -0
  18. package/src/core/hub.ts +137 -102
  19. package/src/core/mcp.ts +253 -0
  20. package/src/core/memory-curator.ts +14 -19
  21. package/src/core/memory.ts +11 -4
  22. package/src/core/personal.ts +5 -1
  23. package/src/core/skill-runtime.ts +11 -114
  24. package/src/core/store.ts +30 -11
  25. package/src/core/task-prompt.ts +1 -1
  26. package/src/core/task-runner.ts +24 -11
  27. package/src/core/tasks-bridge.ts +7 -7
  28. package/src/core/tasks.ts +49 -14
  29. package/src/core/types.ts +4 -7
  30. package/src/core/uploads.ts +7 -7
  31. package/src/mcp/tasks-server.ts +1 -2
  32. package/web/css/experts.css +225 -0
  33. package/web/css/messages.css +43 -0
  34. package/web/css/overlay.css +12 -0
  35. package/web/css/search.css +214 -0
  36. package/web/css/sidebar.css +79 -56
  37. package/web/css/skills.css +0 -11
  38. package/web/css/topbar.css +135 -5
  39. package/web/index.html +2 -0
  40. package/web/lib/dom.js +6 -14
  41. package/web/settings/experts.js +622 -0
  42. package/web/settings/index.js +3 -0
  43. package/web/settings/memory.js +23 -7
  44. package/web/settings/skills.js +3 -3
  45. package/web/state.js +7 -2
  46. package/web/views/composer.js +31 -29
  47. package/web/views/conv-actions.js +8 -9
  48. package/web/views/conv-search.js +206 -0
  49. package/web/views/experts.js +74 -0
  50. package/web/views/layout.js +9 -4
  51. package/web/views/messages.js +44 -11
  52. package/web/views/quota.js +13 -10
  53. package/web/views/sidebar.js +71 -19
  54. package/web/views/tasks.js +21 -36
  55. package/web/views/topbar.js +148 -74
  56. package/src/core/chat-mode.ts +0 -62
  57. package/web/views/mention.js +0 -202
package/src/core/hub.ts CHANGED
@@ -16,6 +16,7 @@ import { interactions, SETTLEMENT_LABEL } from "./interactions.js";
16
16
  import {
17
17
  agentBinding,
18
18
  ensureConversation,
19
+ expertIdOf,
19
20
  getConversation,
20
21
  isExpired,
21
22
  listConversations,
@@ -34,7 +35,6 @@ import type {
34
35
  AttachmentInfo,
35
36
  AgentSession,
36
37
  ContextUsage,
37
- ConversationMode,
38
38
  ApprovalDecision,
39
39
  HistoryMessage,
40
40
  InteractionSpec,
@@ -48,8 +48,10 @@ import type {
48
48
  import { buildCatalog, expandCustomCommand, type AgentCommand, type CommandEntry, type CommandPrefs } from "./command-catalog.js";
49
49
  import { helpText, type ParsedCommand } from "./commands.js";
50
50
  import { listScheduled } from "./scheduled.js";
51
- import { stripContext, wrapContext } from "./chat-mode.js";
52
- import { isMachineCommand, mentionContext, sessionSkills, skillsText } from "./skill-runtime.js";
51
+ import { expertSystemPrompt, searchLabel, stripContext } from "./expert-prompt.js";
52
+ import { avatarUrl, expertEvents, expertRuntime, getExpert, isBuiltin, listExperts, type ExpertRuntime } from "./experts.js";
53
+ import { mcpEvents } from "./mcp.js";
54
+ import { isMachineCommand, sessionSkills } from "./skill-runtime.js";
53
55
  import { skillEvents } from "./skills.js";
54
56
  import { isSilentReply } from "./task-prompt.js";
55
57
 
@@ -133,6 +135,7 @@ export type CommandReply =
133
135
  currentEffort?: string;
134
136
  effortSupported: boolean;
135
137
  }
138
+ /** 能换成哪些专家(飞书:换专家 = 开新会话) */
136
139
  | { type: "agents"; agents: { id: string; label: string }[]; current: string }
137
140
  /** 只发了「/」:可用命令(已按用户配置排序、去掉隐藏的) */
138
141
  | { type: "commands"; agent: string; commands: CommandEntry[] }
@@ -163,8 +166,8 @@ export type ConversationInfo = {
163
166
  forkOf?: string;
164
167
  /** 当前 agent 能不能从某条回复处分叉成新对话 */
165
168
  canFork?: boolean;
166
- /** 聊天模式还是工作模式 */
167
- mode: ConversationMode;
169
+ /** 这条对话的专家 */
170
+ expert: ExpertBadge;
168
171
  /** 这条对话有主人、会用上主人的记忆(主人自己关了记忆的话实际不会注入,见 personal.ts) */
169
172
  personal?: boolean;
170
173
  /** 排着的定时消息(见 core/scheduled.ts),按发送时间先后 */
@@ -173,6 +176,23 @@ export type ConversationInfo = {
173
176
  taskId?: string;
174
177
  };
175
178
 
179
+ /** 顶栏、列表里显示的专家 */
180
+ export type ExpertBadge = {
181
+ id: string;
182
+ name: string;
183
+ icon?: string;
184
+ /** 头像地址(/api/experts/<id>/avatar?v=...) */
185
+ avatar?: string;
186
+ color?: string;
187
+ builtin?: true;
188
+ /** 自定义专家的权限(只能联网的不显示工作目录) */
189
+ access?: string;
190
+ /** 专家被删了:对话还能看,不能再发消息 */
191
+ missing?: true;
192
+ welcome?: string;
193
+ quickPrompts?: { title: string; prompt: string }[];
194
+ };
195
+
176
196
  /** 普通成员点了会落盘的「总是允许」 */
177
197
  export const GLOBAL_ALWAYS_DENIED = "「总是允许」会对所有人的会话生效,只有管理员能点。可以用「允许一次」或「本会话全部允许」。";
178
198
 
@@ -254,6 +274,9 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
254
274
  interactions.on("created", (i) => this.emitEvent(i.convKey, { type: "ix", id: i.id }));
255
275
  // 技能装了、改了、停用了、变量改了:受影响的人空闲的会话换上新的
256
276
  skillEvents.on("changed", (users) => this.personalChanged(new Set(users)));
277
+ // 专家、MCP 改了:用着自定义专家的会话空闲下来换上新的(内置专家不受影响)
278
+ expertEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
279
+ mcpEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
257
280
  // workspaceRoot 改了:store 会把没显式 /cd 过的会话目录重置,正在跑的旧目录会话要作废
258
281
  onConfigChange((next, prev) => {
259
282
  // 默认模型可能改了,缓存作废,下次显示时重新读
@@ -346,7 +369,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
346
369
  const peek = live && live.agent === conv.agent ? (live.session.peekRuntime?.() ?? {}) : {};
347
370
  const last = this.lastRuntime.get(conv.key);
348
371
  const lastRt = last && last.agent === conv.agent ? last.runtime : {};
349
- const defaults = (config().agents as Record<string, { defaultModel?: string; defaultEffort?: string }>)[conv.agent];
372
+ const defaults = this.defaultsOf(conv);
350
373
  const fallback = this.defaultsCache.get(conv.agent);
351
374
  if (!fallback) this.loadDefaults(conv.agent);
352
375
  const model = peek.model ?? binding.model ?? lastRt.model ?? (defaults?.defaultModel || undefined) ?? fallback?.model;
@@ -354,10 +377,63 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
354
377
  return { ...(model ? { model } : {}), ...(effort ? { effort } : {}) };
355
378
  }
356
379
 
380
+ /** 设置里的默认模型 / 思考程度:自定义专家配了就用专家的,没配的项用 agent 的 */
381
+ private defaultsOf(conv: Pick<Conversation, "agent" | "expert">): { defaultModel?: string; defaultEffort?: string } {
382
+ const agent = (config().agents as Record<string, { defaultModel?: string; defaultEffort?: string }>)[conv.agent];
383
+ const expert = conv.expert ? getExpert(conv.expert) : undefined;
384
+ const model = expert?.model || agent?.defaultModel;
385
+ const effort = expert?.effort || agent?.defaultEffort;
386
+ return { ...(model ? { defaultModel: model } : {}), ...(effort ? { defaultEffort: effort } : {}) };
387
+ }
388
+
357
389
  driver(id: string): AgentDriver | undefined {
358
390
  return this.drivers.get(id);
359
391
  }
360
392
 
393
+ // ---------- 专家 ----------
394
+
395
+ /** 对话的专家,给顶栏和列表看 */
396
+ expertBadge(conv: Pick<Conversation, "agent" | "expert" | "owner" | "channel">): ExpertBadge {
397
+ if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true };
398
+ const e = getExpert(conv.expert);
399
+ if (!e || e.owner !== memoryOwnerOf(conv)) return { id: conv.expert, name: "(已删除的专家)", missing: true };
400
+ return {
401
+ id: e.id,
402
+ name: e.name,
403
+ access: e.access,
404
+ ...(e.icon ? { icon: e.icon } : {}),
405
+ ...(e.avatar ? { avatar: avatarUrl(e) } : {}),
406
+ ...(e.color ? { color: e.color } : {}),
407
+ ...(e.welcome ? { welcome: e.welcome } : {}),
408
+ ...(e.quickPrompts.length ? { quickPrompts: e.quickPrompts } : {}),
409
+ };
410
+ }
411
+
412
+ /**
413
+ * 拉起会话时交给 driver 的专家。内置专家返回 undefined(agent 原装的样子)。
414
+ * 专家被删了、不是对话主人的、引擎对不上:抛错 —— 不能悄悄换成别的专家接着聊。
415
+ */
416
+ private expertFor(conv: Conversation): ExpertRuntime | undefined {
417
+ if (!conv.expert) return undefined;
418
+ const e = getExpert(conv.expert);
419
+ if (!e || e.owner !== memoryOwnerOf(conv)) throw new Error("这条对话用的专家已经删除了。新开一个对话,换个专家吧。");
420
+ if (e.engine !== conv.agent) throw new Error(`专家「${e.name}」的引擎和这条对话的对不上,新开一个对话吧。`);
421
+ return expertRuntime(e, (sub, access) =>
422
+ expertSystemPrompt({ name: sub.name, prompt: sub.prompt, access, webSearch: sub.webSearch, webFetch: sub.webFetch }, searchLabel("claude", sub), conv.cwd),
423
+ );
424
+ }
425
+
426
+ /**
427
+ * 这个人在某个渠道能选的专家:允许的内置专家(agent 启用着的),加上他自己的、引擎可用的专家。
428
+ * 没有主人的对话(飞书群聊等)只有内置专家。
429
+ */
430
+ expertChoices(owner: string | undefined, allowedAgents: string[]): { id: string; label: string; engine: string }[] {
431
+ const usable = new Set(this.enabledAgents().map((d) => d.id).filter((a) => allowedAgents.includes(a)));
432
+ const builtin = [...usable].map((a) => ({ id: a, label: this.label(a), engine: a }));
433
+ const own = owner ? listExperts(owner).filter((e) => usable.has(e.engine)) : [];
434
+ return [...builtin, ...own.map((e) => ({ id: e.id, label: `${e.icon ? `${e.icon} ` : ""}${e.name}`, engine: e.engine }))];
435
+ }
436
+
361
437
  /** 已注册且在配置里启用的 agent */
362
438
  enabledAgents(): AgentDriver[] {
363
439
  const agents = config().agents as Record<string, { enabled: boolean }>;
@@ -458,6 +534,10 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
458
534
  channel: string;
459
535
  channelId: string;
460
536
  defaultAgent: string;
537
+ /** 自定义专家的 id(新建时才用)。不给就是内置专家 defaultAgent */
538
+ expert?: string;
539
+ /** 新建时的工作目录。不给就是工作区根目录 */
540
+ cwd?: string;
461
541
  title?: string;
462
542
  /** 谁的对话(用户 id)。只有 Web 上新建的有 */
463
543
  owner?: string;
@@ -467,6 +547,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
467
547
  channel: params.channel,
468
548
  channelId: params.channelId,
469
549
  agent: params.defaultAgent,
550
+ ...(params.expert && !isBuiltin(params.expert) ? { expert: params.expert } : {}),
551
+ ...(params.cwd ? { cwd: params.cwd } : {}),
470
552
  ...(params.title ? { title: params.title } : {}),
471
553
  ...(params.owner ? { owner: params.owner } : {}),
472
554
  });
@@ -508,7 +590,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
508
590
  ...(conv.hidden ? { hidden: true } : {}),
509
591
  ...(conv.forkOf ? { forkOf: conv.forkOf } : {}),
510
592
  ...(this.drivers.get(conv.agent)?.forkAt ? { canFork: true } : {}),
511
- mode: conv.mode ?? "work",
593
+ expert: this.expertBadge(conv),
512
594
  ...(memoryOwnerOf(conv) ? { personal: true } : {}),
513
595
  ...(conv.taskId ? { taskId: conv.taskId } : {}),
514
596
  ...(() => {
@@ -545,11 +627,9 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
545
627
 
546
628
  const binding = agentBinding(conv);
547
629
 
548
- const agentDefaults = (config().agents as Record<string, { defaultModel?: string; defaultEffort?: string }>)[
549
- conv.agent
550
- ];
551
- const model = binding.model || agentDefaults?.defaultModel || undefined;
552
- const effort = binding.effort || agentDefaults?.defaultEffort || undefined;
630
+ const defaults = this.defaultsOf(conv);
631
+ const model = binding.model || defaults.defaultModel || undefined;
632
+ const effort = binding.effort || defaults.defaultEffort || undefined;
553
633
  // 有待分叉的记录:从它分叉(见 AgentBinding.forkFrom)
554
634
  const pendingFork = !opts.resumeId && binding.forkFrom ? binding.forkFrom : undefined;
555
635
  const resumeId = opts.resumeId ?? pendingFork ?? (opts.fork ? undefined : binding.sessionId);
@@ -560,23 +640,16 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
560
640
  const holder: { session?: AgentSession } = {};
561
641
  const alive = () => this.live.get(key)?.session === holder.session;
562
642
 
643
+ // 专家:自定义的按它的配置来;被删了就在这里抛错,这条对话不能再用
644
+ const expert = this.expertFor(conv);
563
645
  // 记忆在拉起会话这一刻读一次:会话里 agent 自己记下的,上下文里本来就有;
564
- // 用户在设置里改了,memoryChanged() 会让空闲的会话下次说话时带着新的重新拉起
565
- const memory = sessionMemory(conv);
646
+ // 用户在设置里改了,memoryChanged() 会让空闲的会话下次说话时带着新的重新拉起。专家可以不带记忆
647
+ const memory = expert && !expert.memory ? undefined : sessionMemory(conv);
566
648
  // 定时任务工具:和记忆一样只给有主人的对话(飞书群聊里谁都能让机器人建任务,算不清是谁的)
567
649
  const taskOwner = memoryOwnerOf(conv);
568
- // 技能也跟着主人走:他启用的技能、填的变量;成员看不到机器上原有的技能(见 skill-runtime.ts)
569
- const skills = sessionSkills(taskOwner);
570
- const mode = conv.mode ?? "work";
571
- // 续着的会话上次被告知的模式和现在不一样(新会话没有历史,算原装的工作模式)
572
- const announceMode = (resumeId ? (binding.announcedMode ?? "work") : "work") !== mode;
573
- // 真开始一轮了才算告诉过它(/status 之类也会拉起会话,但什么都没发过去)
574
- let announced = false;
575
- const markAnnounced = () => {
576
- if (announced) return;
577
- announced = true;
578
- updateAgentBinding(key, agent, { announcedMode: mode === "work" ? undefined : mode });
579
- };
650
+ // 技能也跟着主人走:他启用的技能、填的变量;成员看不到机器上原有的技能(见 skill-runtime.ts)。
651
+ // 自定义专家只给它选中的
652
+ const skills = sessionSkills(taskOwner, expert?.skills);
580
653
  const session = driver.createSession(
581
654
  {
582
655
  cwd: conv.cwd,
@@ -586,16 +659,14 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
586
659
  ...(resumeId ? { resumeId } : {}),
587
660
  ...(fork ? { fork: true } : {}),
588
661
  ...(conv.autoEdit ? { autoEdit: true } : {}),
589
- ...(conv.mode === "chat" ? { mode: "chat" as const } : {}),
662
+ ...(expert ? { expert } : {}),
590
663
  ...(memory ? { memory } : {}),
591
- ...(announceMode ? { announceMode: true } : {}),
592
664
  ...(taskOwner ? { tasks: { userId: taskOwner, convKey: key } } : {}),
593
665
  ...(skills ? { skills } : {}),
594
666
  },
595
667
  {
596
668
  onTurnStart: () => {
597
669
  if (!alive()) return;
598
- markAnnounced();
599
670
  this.emitEvent(key, { type: "turn_start" });
600
671
  },
601
672
  onStep: (kind, text) => alive() && this.emitEvent(key, { type: "step", kind, text }),
@@ -956,30 +1027,20 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
956
1027
  this.emitEvent(key, { type: "notice", text: blocked });
957
1028
  return gone(blocked);
958
1029
  }
959
- this.sendNow(key, this.withMentions(key, input), task ?? null, { id: shown.id, queued: shown.queued });
1030
+ this.sendNow(key, input, task ?? null, { id: shown.id, queued: shown.queued });
960
1031
  } finally {
961
1032
  this.waitingSends.set(key, Math.max(0, (this.waitingSends.get(key) ?? 1) - 1));
962
1033
  }
963
1034
  });
964
1035
  }
965
1036
 
966
- /**
967
- * 消息里 @ 了技能:附一段背景告诉 agent 用哪个、怎么用(用户看不到,见 skill-runtime.ts 的 mentionContext)。
968
- * 按发出去这一刻对话的 agent 和模式拼:排队期间可能刚切过。
969
- */
970
- private withMentions(key: string, input: UserInput): UserInput {
971
- const conv = getConversation(key);
972
- if (!conv) return input;
973
- const lines = mentionContext(stripContext(input.text), { owner: memoryOwnerOf(conv), agent: conv.agent, mode: conv.mode ?? "work" });
974
- return lines ? { ...input, text: `${input.text}\n\n${wrapContext(lines)}` } : input;
975
- }
976
-
977
1037
  /** 成员直接发「/机器上的技能」:Claude 会绕过技能白名单把它展开,这里先拦下。返回拦下的原因 */
978
1038
  private async blockedSlash(key: string, text: string): Promise<string | null> {
979
1039
  const m = /^[//](\S+)/.exec(text.trim());
980
1040
  if (!m) return null;
981
1041
  const conv = getConversation(key);
982
- if (!conv || conv.agent !== "claude" || conv.mode === "chat") return null;
1042
+ // 只有内置的 Claude Code 专家读机器上的技能;自定义专家的技能白名单里只有它选的
1043
+ if (!conv || conv.agent !== "claude" || conv.expert) return null;
983
1044
  const owner = memoryOwnerOf(conv);
984
1045
  if (!owner || getUser(owner)?.role === "admin") return null;
985
1046
  const driver = this.enabledAgents().find((d) => d.id === conv.agent);
@@ -1071,9 +1132,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1071
1132
  } catch (err) {
1072
1133
  console.error("[会话] 读取模型信息失败:", err);
1073
1134
  }
1074
- const defaults = (config().agents as Record<string, { defaultModel?: string; defaultEffort?: string }>)[
1075
- conv.agent
1076
- ];
1135
+ const defaults = this.defaultsOf(conv);
1077
1136
  const fallback =
1078
1137
  runtime.model && runtime.effort
1079
1138
  ? {}
@@ -1214,35 +1273,6 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1214
1273
  return this.serial(key, () => this.setAutoEditNow(key, on));
1215
1274
  }
1216
1275
 
1217
- // ---------- 聊天 / 工作模式 ----------
1218
-
1219
- /**
1220
- * /chat、/work。同一条对话、同一个 agent 会话接着聊:丢掉活着的进程,下一条消息带着新模式的
1221
- * 系统提示和工具 resume 回来(Claude、Codex 都实测过能接上上下文)。正在回复时不切:
1222
- * 丢进程会把这一轮打断。
1223
- */
1224
- private async setModeNow(key: string, mode: ConversationMode): Promise<string> {
1225
- const conv = getConversation(key)!;
1226
- if ((conv.mode ?? "work") === mode) {
1227
- return mode === "chat" ? "已经是💬 聊天模式了。发 /work 切到工作模式。" : "已经是🛠 工作模式了。发 /chat 切到聊天模式。";
1228
- }
1229
- if (this.isBusy(key)) return "正在回复,等这一轮结束(或者先 /stop)再切换模式。";
1230
- // 聊过的聊天对话切到工作模式:之后再回聊天模式就省不了了(Web 上点按钮时会先问,命令直接切,提醒一句)
1231
- const hadChat = mode === "work" && !!agentBinding(conv).sessionId;
1232
- await this.drop(key, "已切换模式");
1233
- updateConversation(key, { mode: mode === "chat" ? "chat" : undefined });
1234
- this.emitEvent(key, { type: "meta" });
1235
- return mode === "chat"
1236
- ? "已切到💬 聊天模式:精简的系统提示,只能联网搜索,不执行命令、不读写文件,每轮的开销小很多。上下文接着之前的。要动手干活时发 /work。"
1237
- : `已切到🛠 工作模式:${this.label(conv.agent)} 原装的全部能力(执行命令、改文件、技能、MCP)。上下文接着之前的。发 /chat 切回聊天模式。${
1238
- hadChat ? "\n\n提示:工作模式会在这条会话里留下一大段背景,之后再切回聊天模式就省不了多少了。干完活想回到省 token 的聊天,发 /new 开个新会话再发 /chat。" : ""
1239
- }`;
1240
- }
1241
-
1242
- setMode(key: string, mode: ConversationMode): Promise<string> {
1243
- return this.serial(key, () => this.setModeNow(key, mode));
1244
- }
1245
-
1246
1276
  // ---------- 记忆变了 / 主人变了 ----------
1247
1277
 
1248
1278
  /** 记忆过期了的会话进程(Live.id):空闲下来就丢掉,下次说话带着新记忆重新拉起 */
@@ -1260,7 +1290,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1260
1290
  this.staleLive.add(live.id);
1261
1291
  return;
1262
1292
  }
1263
- await this.drop(key, "记忆或技能已更新");
1293
+ await this.drop(key, "记忆、技能或专家已更新");
1264
1294
  });
1265
1295
  }
1266
1296
 
@@ -1272,12 +1302,15 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1272
1302
  this.personalChanged(new Set([userId]));
1273
1303
  }
1274
1304
 
1275
- /** 这些人的记忆或技能变了:他们名下活着的会话空闲下来就重新拉起 */
1276
- private personalChanged(users: Set<string>): void {
1305
+ /**
1306
+ * 这些人的记忆、技能、专家或 MCP 变了:他们名下活着的会话空闲下来就重新拉起。
1307
+ * onlyExperts:只管用自定义专家的会话(专家、MCP 变了不影响内置专家)
1308
+ */
1309
+ private personalChanged(users: Set<string>, onlyExperts = false): void {
1277
1310
  for (const [key, live] of this.live) {
1278
1311
  const conv = getConversation(key);
1279
1312
  const owner = conv ? memoryOwnerOf(conv) : undefined;
1280
- if (!owner || !users.has(owner)) continue;
1313
+ if (!owner || !users.has(owner) || (onlyExperts && !conv?.expert)) continue;
1281
1314
  this.staleLive.add(live.id);
1282
1315
  this.dropIfStale(key);
1283
1316
  }
@@ -1305,20 +1338,27 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1305
1338
  return true;
1306
1339
  }
1307
1340
 
1308
- /** 切 agent:各 agent 的会话各自保留,切回来接着聊。 */
1309
- private async setAgentNow(key: string, agent: string, allowed: string[], op: SwitchOp): Promise<string> {
1341
+ /**
1342
+ * 换专家(飞书里的 /agent、/claude、/codex):对话中途不能换专家,所以换了就开新会话。
1343
+ * target 可以是专家 id,也可以是名字。allowed:这个渠道允许的内置 agent。
1344
+ */
1345
+ private async setExpertNow(key: string, target: string, allowed: string[], op: SwitchOp): Promise<string> {
1310
1346
  const conv = getConversation(key)!;
1311
- if (!allowed.includes(agent)) {
1312
- return `这里不能用「${agent}」。可选:${allowed.join("、")}`;
1313
- }
1314
- this.requireDriver(agent);
1315
- if (conv.agent === agent) return `当前已经是 ${this.label(agent)}。`;
1316
- await this.drop(key, `已切换到 ${this.label(agent)}`);
1347
+ // 网页上的对话(包括飞书 /web 接上的)从头到尾一个专家:要换就新建对话
1348
+ if (conv.channel === "web") return "网页上的对话中途不能换专家。在网页上新建一个对话,选好专家再聊。";
1349
+ const choices = this.expertChoices(memoryOwnerOf(conv), allowed);
1350
+ const want = target.trim().toLowerCase();
1351
+ const hit = choices.find((c) => c.id.toLowerCase() === want) ?? choices.find((c) => c.label.toLowerCase().includes(want));
1352
+ if (!hit) return `这里没有「${target}」这个专家。可选:${choices.map((c) => c.label).join("、")}`;
1353
+ this.requireDriver(hit.engine);
1354
+ if (expertIdOf(conv) === hit.id) return `当前已经是 ${hit.label}。`;
1355
+ await this.drop(key, `已换成 ${hit.label}`);
1317
1356
  this.markSwitched(key, op.seq);
1318
- updateConversation(key, { agent });
1357
+ // 新会话:所有 agent 的旧会话都不接着用(专家换了,上下文里的人设、权限都不对了)
1358
+ updateConversation(key, { agent: hit.engine, expert: isBuiltin(hit.id) ? undefined : hit.id, perAgent: {} });
1359
+ this.clearOldUploads(key, op.at);
1319
1360
  this.emitEvent(key, { type: "meta" });
1320
- const resumed = agentBinding(getConversation(key)!, agent).sessionId;
1321
- return `已切换到 ${this.label(agent)}${resumed ? ",接着它上次的会话" : ""}。`;
1361
+ return `已换成专家「${hit.label}」,开了新会话。`;
1322
1362
  }
1323
1363
 
1324
1364
  async stop(key: string): Promise<string> {
@@ -1405,7 +1445,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1405
1445
  ? `记忆:开(${getUser(memoryOwner)?.name ?? memoryOwner} 的)`
1406
1446
  : "记忆:主人关掉了";
1407
1447
  return [
1408
- `模式:${conv.mode === "chat" ? "💬 聊天(/work 切到工作模式)" : "🛠 工作(/chat 切到聊天模式)"}`,
1448
+ `专家:${this.expertBadge(conv).name}`,
1409
1449
  memoryLine,
1410
1450
  `Agent:${driver.label}`,
1411
1451
  `会话:${agentBinding(conv).sessionId ?? "(尚未建立)"}`,
@@ -1470,7 +1510,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1470
1510
  cwd: conv.cwd,
1471
1511
  ...(conv.cwdExplicit ? { cwdExplicit: true } : {}),
1472
1512
  ...(conv.autoEdit ? { autoEdit: true } : {}),
1473
- ...(conv.mode ? { mode: conv.mode } : {}),
1513
+ ...(conv.expert ? { expert: conv.expert } : {}),
1474
1514
  forkOf: key,
1475
1515
  perAgent: {
1476
1516
  [conv.agent]: {
@@ -1500,8 +1540,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1500
1540
  return this.serial(key, () => this.setEffortNow(key, effort));
1501
1541
  }
1502
1542
 
1503
- setAgent(key: string, agent: string, allowed: string[]): Promise<string> {
1504
- return this.switchOp(key, (op) => this.setAgentNow(key, agent, allowed, op));
1543
+ setExpert(key: string, target: string, allowed: string[]): Promise<string> {
1544
+ return this.switchOp(key, (op) => this.setExpertNow(key, target, allowed, op));
1505
1545
  }
1506
1546
 
1507
1547
  cd(key: string, dir: string): Promise<string> {
@@ -1538,8 +1578,6 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1538
1578
  switch (cmd.kind) {
1539
1579
  case "help":
1540
1580
  return text(helpText(ctx.allowedAgents, channel));
1541
- case "skills":
1542
- return text(skillsText(memoryOwnerOf(getConversation(key)!)));
1543
1581
  case "commands": {
1544
1582
  const conv = getConversation(key)!;
1545
1583
  const owner = memoryOwnerOf(conv);
@@ -1555,8 +1593,6 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1555
1593
  return text(getConversation(key)!.cwd);
1556
1594
  case "autoedit":
1557
1595
  return text(await this.setAutoEdit(key, cmd.on));
1558
- case "mode":
1559
- return text(await this.setMode(key, cmd.mode));
1560
1596
  case "status":
1561
1597
  return text(await this.status(key));
1562
1598
  case "cd":
@@ -1581,15 +1617,14 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1581
1617
  return text(await this.setEffort(key, cmd.effort));
1582
1618
  case "agent": {
1583
1619
  if (!cmd.agent) {
1620
+ const conv = getConversation(key)!;
1584
1621
  return {
1585
1622
  type: "agents",
1586
- agents: ctx.allowedAgents
1587
- .filter((a) => this.drivers.has(a))
1588
- .map((id) => ({ id, label: this.label(id) })),
1589
- current: getConversation(key)!.agent,
1623
+ agents: this.expertChoices(memoryOwnerOf(conv), ctx.allowedAgents).map(({ id, label }) => ({ id, label })),
1624
+ current: expertIdOf(conv),
1590
1625
  };
1591
1626
  }
1592
- return text(await this.setAgent(key, cmd.agent, ctx.allowedAgents));
1627
+ return text(await this.setExpert(key, cmd.agent, ctx.allowedAgents));
1593
1628
  }
1594
1629
  case "stop":
1595
1630
  return text(await this.stop(key));