agent-loft 0.2.47 → 0.2.49

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