agent-loft 0.2.65 → 0.2.67

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.
@@ -5,7 +5,7 @@
5
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
  // ---------- 开会话时 ----------
@@ -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,7 @@ 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
54
  import { builtinAgentDefaults, builtinAgentEvents, builtinAgentSession } from "./builtin-agents.js";
55
55
  import { mcpEvents } from "./mcp.js";
56
56
  import { isMachineCommand, sessionSkills } from "./skill-runtime.js";
@@ -280,7 +280,26 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
280
280
  // 技能装了、改了、停用了、变量改了:受影响的人空闲的会话换上新的
281
281
  skillEvents.on("changed", (users) => this.personalChanged(new Set(users)));
282
282
  // 专家修改只影响自定义专家;MCP 和内置默认配置修改也更新该账号的内置会话。
283
- expertEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
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
+ });
284
303
  mcpEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
285
304
  builtinAgentEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
286
305
  // workspaceRoot 改了:store 会把没显式 /cd 过的会话目录重置,正在跑的旧目录会话要作废
@@ -402,7 +421,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
402
421
  expertBadge(conv: Pick<Conversation, "agent" | "expert" | "owner" | "channel">): ExpertBadge {
403
422
  if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true };
404
423
  const e = getExpert(conv.expert);
405
- 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 };
406
425
  return {
407
426
  id: e.id,
408
427
  name: e.name,
@@ -417,27 +436,29 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
417
436
 
418
437
  /**
419
438
  * 拉起会话时交给 driver 的专家。内置专家返回 undefined(agent 原装的样子)。
420
- * 专家被删了、不是对话主人的、引擎对不上:抛错 —— 不能悄悄换成别的专家接着聊。
439
+ * 专家被删了、未授权共享、引擎对不上:抛错 —— 不能悄悄换成别的专家接着聊。
421
440
  */
422
441
  private expertFor(conv: Conversation): ExpertRuntime | undefined {
423
442
  if (!conv.expert) return undefined;
424
443
  const e = getExpert(conv.expert);
425
- 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("这条对话用的专家已经删除或取消共享了。新开一个对话,换个专家吧。");
426
446
  if (e.engine !== conv.agent) throw new Error(`专家「${e.name}」的引擎和这条对话的对不上,新开一个对话吧。`);
427
447
  return expertRuntime(e, (sub, access) =>
428
448
  expertSystemPrompt({ name: sub.name, prompt: sub.prompt, access, webSearch: sub.webSearch, webFetch: sub.webFetch }, searchLabel("claude", sub), conv.cwd),
449
+ owner,
429
450
  );
430
451
  }
431
452
 
432
453
  /**
433
- * 这个人在某个渠道能选的专家:允许的内置专家(agent 启用着的),加上他自己的、引擎可用的专家。
454
+ * 这个人在某个渠道能选的专家:允许的内置专家(agent 启用着的),加上自己的及共享的、引擎可用的专家。
434
455
  * 没有主人的对话(飞书群聊等)只有内置专家。
435
456
  */
436
- 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 }[] {
437
458
  const usable = new Set(this.enabledAgents().map((d) => d.id).filter((a) => allowedAgents.includes(a)));
438
459
  const builtin = [...usable].map((a) => ({ id: a, label: this.label(a), engine: a }));
439
- const own = owner ? listExperts(owner).filter((e) => usable.has(e.engine)) : [];
440
- 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));
441
462
  }
442
463
 
443
464
  /** 已注册且在配置里启用的 agent */
@@ -611,12 +632,40 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
611
632
  .sort((a, b) => b.activeAt - a.activeAt);
612
633
  }
613
634
 
635
+ /** 旧版飞书会话没有自动命名;只为当前要显示的会话从已有记录补首条消息。 */
636
+ async backfillFeishuTitles(list: ConversationInfo[]): Promise<ConversationInfo[]> {
637
+ return Promise.all(list.map(async (info) => {
638
+ const conv = getConversation(info.key);
639
+ if (!conv || conv.channel !== "feishu" || conv.title || conv.titleAuto === false) return info;
640
+ const { agent, cwd } = conv;
641
+ const sessionId = agentBinding(conv).sessionId;
642
+ const driver = this.enabledAgents().find((d) => d.id === agent);
643
+ if (!sessionId || !driver) return info;
644
+ try {
645
+ const messages = await withTimeout(driver.readHistory(sessionId, cwd), "读取会话标题", 3000);
646
+ const first = messages.find((m) => m.role === "user" && m.text.trim());
647
+ const now = getConversation(info.key);
648
+ // 读记录期间用户可能改名、切专家或切目录,不能把旧标题写进新会话。
649
+ if (first && now && !now.title && now.titleAuto !== false && now.agent === agent && now.cwd === cwd && agentBinding(now).sessionId === sessionId) {
650
+ updateConversation(info.key, { title: first.text.trim().replace(/\s+/g, " ").slice(0, 40), titleAuto: true });
651
+ this.emitEvent(info.key, { type: "meta" });
652
+ this.syncTitle(info.key, agent);
653
+ }
654
+ } catch (err) {
655
+ console.warn(`[${agent}] 补齐飞书会话标题失败:`, err instanceof Error ? err.message : err);
656
+ }
657
+ return this.info(info.key) ?? info;
658
+ }));
659
+ }
660
+
614
661
  /** 取活着的 agent 会话,没有就按绑定拉起(默认续用上次的会话)。 */
615
662
  session(key: string, opts: { resumeId?: string; fork?: boolean } = {}): AgentSession {
616
663
  const conv = getConversation(key);
617
664
  if (!conv) throw new Error(`会话不存在:${key}`);
618
665
  // 先检查 agent 还启用着:设置里关掉了,已经打开的会话也不能再用
619
666
  const driver = this.requireDriver(conv.agent);
667
+ // 撤回共享后,即使上一轮还在运行,也不能把新输入交给缓存着的会话。
668
+ if (conv.expert && !canUseExpert(memoryOwnerOf(conv), conv.expert)) throw new Error("这条对话用的专家已经删除或取消共享了。新开一个对话,换个专家吧。");
620
669
  const existing = this.live.get(key);
621
670
  if (existing && existing.agent === conv.agent && existing.cwd === conv.cwd && !opts.resumeId) {
622
671
  return existing.session;
@@ -993,7 +1042,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
993
1042
  // 闲置过期要按这次说话之前的活跃时间判断,所以先记下、后 touch
994
1043
  const lastActive = conv.activeAt;
995
1044
  touchConversation(key);
996
- if (!conv.title && conv.channel === "web" && shown.text.trim()) {
1045
+ if (!conv.title && conv.titleAuto !== false && (conv.channel === "web" || conv.channel === "feishu") && shown.text.trim()) {
997
1046
  // 先用首条消息占位,第一轮结束后换成 agent 自己生成的短标题(syncTitle)
998
1047
  updateConversation(key, { title: shown.text.trim().replace(/\s+/g, " ").slice(0, 40), titleAuto: true });
999
1048
  this.emitEvent(key, { type: "meta" });
@@ -1352,11 +1401,11 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1352
1401
  * 换专家(飞书里的 /agent、/claude、/codex):对话中途不能换专家,所以换了就开新会话。
1353
1402
  * target 可以是专家 id,也可以是名字。allowed:这个渠道允许的内置 agent。
1354
1403
  */
1355
- private async setExpertNow(key: string, target: string, allowed: string[], op: SwitchOp): Promise<string> {
1404
+ private async setExpertNow(key: string, target: string, allowed: string[], op: SwitchOp, allowedExperts?: string[]): Promise<string> {
1356
1405
  const conv = getConversation(key)!;
1357
1406
  // 网页上的对话(包括飞书 /web 接上的)从头到尾一个专家:要换就新建对话
1358
1407
  if (conv.channel === "web") return "网页上的对话中途不能换专家。在网页上新建一个对话,选好专家再聊。";
1359
- const choices = this.expertChoices(memoryOwnerOf(conv), allowed);
1408
+ const choices = this.expertChoices(memoryOwnerOf(conv), allowed, allowedExperts);
1360
1409
  const want = target.trim().toLowerCase();
1361
1410
  const hit = choices.find((c) => c.id.toLowerCase() === want) ?? choices.find((c) => c.label.toLowerCase().includes(want));
1362
1411
  if (!hit) return `这里没有「${target}」这个专家。可选:${choices.map((c) => c.label).join("、")}`;
@@ -1639,8 +1688,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1639
1688
  return this.serial(key, () => this.setEffortNow(key, effort));
1640
1689
  }
1641
1690
 
1642
- setExpert(key: string, target: string, allowed: string[]): Promise<string> {
1643
- return this.switchOp(key, (op) => this.setExpertNow(key, target, allowed, op));
1691
+ setExpert(key: string, target: string, allowed: string[], allowedExperts?: string[]): Promise<string> {
1692
+ return this.switchOp(key, (op) => this.setExpertNow(key, target, allowed, op, allowedExperts));
1644
1693
  }
1645
1694
 
1646
1695
  cd(key: string, dir: string): Promise<string> {
@@ -1662,6 +1711,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1662
1711
  cmd: ParsedCommand,
1663
1712
  ctx: {
1664
1713
  allowedAgents: string[];
1714
+ allowedExperts?: string[];
1665
1715
  by: string;
1666
1716
  channel?: string;
1667
1717
  /** 多用户:发命令的人能看到哪些 agent 会话(/sessions 列哪些、/resume 能恢复哪些) */
@@ -1686,7 +1736,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1686
1736
  ...(channel ? { channel } : {}),
1687
1737
  ...(owner && getUser(owner)?.role !== "admin" ? { member: true } : {}),
1688
1738
  });
1689
- return { type: "commands", agent: conv.agent, commands: all.filter((c) => !c.hidden) };
1739
+ 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))) };
1690
1740
  }
1691
1741
  case "pwd":
1692
1742
  return text(getConversation(key)!.cwd);
@@ -1719,11 +1769,11 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
1719
1769
  const conv = getConversation(key)!;
1720
1770
  return {
1721
1771
  type: "agents",
1722
- agents: this.expertChoices(memoryOwnerOf(conv), ctx.allowedAgents).map(({ id, label }) => ({ id, label })),
1772
+ agents: this.expertChoices(memoryOwnerOf(conv), ctx.allowedAgents, ctx.allowedExperts).map(({ id, label }) => ({ id, label })),
1723
1773
  current: expertIdOf(conv),
1724
1774
  };
1725
1775
  }
1726
- return text(await this.setExpert(key, cmd.agent, ctx.allowedAgents));
1776
+ return text(await this.setExpert(key, cmd.agent, ctx.allowedAgents, ctx.allowedExperts));
1727
1777
  }
1728
1778
  case "stop":
1729
1779
  return text(await this.stop(key));
@@ -7,7 +7,7 @@
7
7
  // 更不能被当成对挂着的提问的回答。
8
8
  import crypto from "node:crypto";
9
9
  import { resolveWorkspacePath } from "./config.js";
10
- import { getExpert } from "./experts.js";
10
+ import { canUseExpert, getExpert } from "./experts.js";
11
11
  import { hub, type TaskTurnEnd } from "./hub.js";
12
12
  import { interactions } from "./interactions.js";
13
13
  import { memoryOwnerOf } from "./personal.js";
@@ -50,8 +50,8 @@ type Resolved = { key: string } | { pause: string } | { error: string };
50
50
 
51
51
  /** 这次该发到哪条对话;专用对话还没有(或者被删了)就新建一条 */
52
52
  function resolveConv(task: Task): Resolved {
53
- const missingExpert = (id: string | undefined) => !!id && getExpert(id)?.owner !== task.owner;
54
- const deletedExpert = { pause: "任务用的专家已经删除了,任务已暂停。编辑任务换一个专家再启用。" };
53
+ const missingExpert = (id: string | undefined) => !!id && !canUseExpert(task.owner, id);
54
+ const deletedExpert = { pause: "任务用的专家已经删除或取消共享了,任务已暂停。编辑任务换一个专家再启用。" };
55
55
  if (task.target.kind === "conv") {
56
56
  const conv = getConversation(task.target.key);
57
57
  if (!conv || conv.hidden) return { pause: "回复的那条对话已经被删除,任务已暂停。可以改成「专用对话」后再启用。" };
package/src/core/tasks.ts CHANGED
@@ -157,7 +157,7 @@ function cleanPrompt(v: unknown): string {
157
157
  return p;
158
158
  }
159
159
 
160
- /** 选的专家 → 引擎 + 自定义专家 id。只能选内置的或自己的 */
160
+ /** 选的专家 → 引擎 + 自定义专家 id。可选内置、自己的或共享的专家 */
161
161
  function cleanExpert(owner: string, v: unknown): { agent: string; expert?: string } {
162
162
  const id = str(v) || "claude";
163
163
  if (!canUseExpert(owner, id)) throw new Error("这个专家不存在");
@@ -255,6 +255,40 @@ button.conv-group:hover {
255
255
  display: grid;
256
256
  }
257
257
 
258
+ /* 飞书分组的同一位置:平时显示飞书,悬停或键盘聚焦时显示新建加号。 */
259
+ .bot-row .conv-item.proj {
260
+ padding-right: 36px;
261
+ }
262
+
263
+ .bot-new {
264
+ display: grid;
265
+ }
266
+
267
+ .bot-new .feishu-mark,
268
+ .bot-new .bot-plus {
269
+ grid-area: 1 / 1;
270
+ }
271
+
272
+ .bot-new .feishu-mark,
273
+ .bot-new .feishu-mark svg {
274
+ width: 14px;
275
+ height: 14px;
276
+ }
277
+
278
+ .bot-new .bot-plus {
279
+ visibility: hidden;
280
+ }
281
+
282
+ .bot-row:hover .bot-new .feishu-mark,
283
+ .bot-row:focus-within .bot-new .feishu-mark {
284
+ visibility: hidden;
285
+ }
286
+
287
+ .bot-row:hover .bot-new .bot-plus,
288
+ .bot-row:focus-within .bot-new .bot-plus {
289
+ visibility: visible;
290
+ }
291
+
258
292
  /* 鼠标挪到右边的加号上时,整行的 hover 底色还留着 */
259
293
  .proj-row:hover .conv-item.proj {
260
294
  padding-right: 36px;
@@ -266,6 +300,14 @@ button.conv-group:hover {
266
300
  .proj-new {
267
301
  display: grid;
268
302
  }
303
+
304
+ .bot-new .bot-plus {
305
+ visibility: visible;
306
+ }
307
+
308
+ .bot-new .feishu-mark {
309
+ visibility: hidden;
310
+ }
269
311
  }
270
312
 
271
313
  .conv-item {
@@ -54,7 +54,7 @@ export function closeMenu() {
54
54
  removeEventListener("blur", closeMenu);
55
55
  }
56
56
 
57
- /** beforeClose:点 × 或点外面关闭前先问它,返回(或 resolve 成)false 就不关。返回的 close 不问,直接关 */
57
+ /** 弹窗只通过按钮关闭,点击遮罩不关闭。beforeClose:点 × 前先问它,false 就不关。返回的 close 直接关 */
58
58
  export function modal({ title, body, foot, wide, tall, className = "", beforeClose }) {
59
59
  const close = () => overlay.remove();
60
60
  const tryClose = async () => {
@@ -62,11 +62,11 @@ export function modal({ title, body, foot, wide, tall, className = "", beforeClo
62
62
  };
63
63
  const overlay = h(
64
64
  "div",
65
- { class: "overlay", onclick: (e) => e.target === overlay && void tryClose() },
65
+ { class: "overlay" },
66
66
  h(
67
67
  "div",
68
68
  { class: `modal${wide ? " wide" : ""}${tall ? " tall" : ""}${className ? ` ${className}` : ""}` },
69
- h("div", { class: "modal-head" }, h("h3", {}, title), h("button", { class: "icon-btn", onclick: () => void tryClose() }, icon("x"))),
69
+ h("div", { class: "modal-head" }, h("h3", {}, title), h("button", { class: "icon-btn", "aria-label": "关闭", onclick: () => void tryClose() }, icon("x"))),
70
70
  body,
71
71
  foot ?? null,
72
72
  ),
@@ -110,7 +110,7 @@ export function placePopover(pop, anchor) {
110
110
 
111
111
  /**
112
112
  * 确认弹窗(替代浏览器自带的 confirm),样式和重命名弹窗一致。
113
- * 回车确认、Esc / 点外面取消;resolve 成 true / false
113
+ * 回车确认,点击取消按钮取消;resolve 成 true / false
114
114
  */
115
115
  /** altText:给了就多一个按钮,点它返回 "alt"(确定返回 true,取消返回 false) */
116
116
  export function confirmDialog({ title, message, sub, confirmText = "确定", danger = false, altText }) {
@@ -125,10 +125,7 @@ export function confirmDialog({ title, message, sub, confirmText = "确定", dan
125
125
  resolve(v);
126
126
  };
127
127
  const onKey = (e) => {
128
- if (e.key === "Escape") {
129
- e.preventDefault();
130
- done(false);
131
- } else if (e.key === "Enter" && !e.isComposing) {
128
+ if (e.key === "Enter" && !e.isComposing) {
132
129
  e.preventDefault();
133
130
  done(true);
134
131
  }
@@ -137,7 +134,7 @@ export function confirmDialog({ title, message, sub, confirmText = "确定", dan
137
134
  cancel.onclick = () => done(false);
138
135
  const overlay = h(
139
136
  "div",
140
- { class: "overlay dialog-overlay", onclick: (e) => e.target === overlay && done(false) },
137
+ { class: "overlay dialog-overlay" },
141
138
  h(
142
139
  "div",
143
140
  { class: "dialog confirm-dialog" },
package/web/lib/ws.js CHANGED
@@ -11,6 +11,7 @@ import { setBusy } from "../views/composer.js";
11
11
  import { SH, shownHere } from "./shell.js";
12
12
  import { currentPushSub } from "./push.js";
13
13
  import { renderScheduled } from "../views/schedule.js";
14
+ import { reloadExperts } from "../views/experts.js";
14
15
 
15
16
  // ---------- WebSocket ----------
16
17
 
@@ -281,6 +282,9 @@ function onWsMessage(msg) {
281
282
  // 自己的终端开了 / 关了,或者远程控制的权限、设置变了:重新问一下(views/layout.js)
282
283
  document.dispatchEvent(new Event("aim:remote"));
283
284
  return;
285
+ case "experts":
286
+ void reloadExperts();
287
+ return;
284
288
  case "skills":
285
289
  // 技能变了:设置里的技能页开着就重新拉,@ 补全的缓存作废
286
290
  document.dispatchEvent(new Event("aim:skills"));