agent-loft 0.2.48 → 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 (52) hide show
  1. package/README.md +26 -12
  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 +24 -17
  10. package/src/channels/web/experts-api.ts +185 -0
  11. package/src/channels/web/skills-api.ts +1 -7
  12. package/src/channels/web/tasks-api.ts +9 -5
  13. package/src/core/command-catalog.ts +4 -6
  14. package/src/core/commands.ts +6 -11
  15. package/src/core/expert-prompt.ts +119 -0
  16. package/src/core/experts.ts +416 -0
  17. package/src/core/hub.ts +134 -102
  18. package/src/core/mcp.ts +253 -0
  19. package/src/core/memory-curator.ts +8 -9
  20. package/src/core/memory.ts +11 -4
  21. package/src/core/personal.ts +5 -1
  22. package/src/core/skill-runtime.ts +11 -114
  23. package/src/core/store.ts +30 -11
  24. package/src/core/task-prompt.ts +1 -1
  25. package/src/core/task-runner.ts +24 -11
  26. package/src/core/tasks-bridge.ts +7 -7
  27. package/src/core/tasks.ts +49 -14
  28. package/src/core/types.ts +4 -7
  29. package/src/core/uploads.ts +7 -7
  30. package/src/mcp/tasks-server.ts +1 -2
  31. package/web/css/experts.css +103 -0
  32. package/web/css/messages.css +43 -0
  33. package/web/css/overlay.css +12 -0
  34. package/web/css/sidebar.css +3 -2
  35. package/web/css/skills.css +0 -11
  36. package/web/css/topbar.css +2 -2
  37. package/web/index.html +1 -0
  38. package/web/settings/experts.js +444 -0
  39. package/web/settings/index.js +3 -0
  40. package/web/settings/memory.js +21 -5
  41. package/web/settings/skills.js +3 -3
  42. package/web/state.js +5 -2
  43. package/web/views/composer.js +4 -16
  44. package/web/views/conv-actions.js +7 -9
  45. package/web/views/experts.js +73 -0
  46. package/web/views/layout.js +4 -3
  47. package/web/views/messages.js +44 -11
  48. package/web/views/sidebar.js +2 -2
  49. package/web/views/tasks.js +21 -36
  50. package/web/views/topbar.js +43 -74
  51. package/src/core/chat-mode.ts +0 -62
  52. package/web/views/mention.js +0 -202
@@ -5,7 +5,8 @@
5
5
  import { appServer } from "./app-server.js";
6
6
  import { refusalFor, UnsupportedRequest } from "./refusals.js";
7
7
  import { config } from "../../core/config.js";
8
- import { contextBlock } from "../../core/chat-mode.js";
8
+ import { contextBlock } from "../../core/expert-prompt.js";
9
+ import { ACCESS_LEVELS, type ExpertAccess, type ExpertRuntime } from "../../core/experts.js";
9
10
  import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
10
11
  import { SKILLS_MCP_NAME, skillsMcpSpawn, TASK_TOOL_TIMEOUT_SEC, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
11
12
  import { codexSkillLines } from "../../core/skill-runtime.js";
@@ -85,13 +86,13 @@ function sandboxPolicyFor(mode: string, cwd: string): unknown {
85
86
  };
86
87
  }
87
88
 
88
- // ---------- 聊天模式 ----------
89
+ // ---------- 自定义专家 ----------
89
90
 
90
91
  /**
91
- * 聊天模式要关掉的东西(thread/start / resume 的 config 覆盖)。实测一句话的输入从约 2 万 token
92
- * 降到约 1.1 万,大头是技能清单(约 2.5 万字符)和权限说明(约 1.1 万字符)。剩下的是 Codex 自己的基础指令
93
- * (改不得,见 modeParams)和关不掉的工具定义。
94
- * 不认识的 feature 名 Codex 会忽略;万一哪天哪个键让 thread 起不来,openOnce 会退回不带这些覆盖再试一次。
92
+ * 只能联网的专家要关掉的东西(thread/start / resume 的 config 覆盖),也是别的权限的底子(expertConfig 再按权限打开)。
93
+ * 实测一句话的输入从约 2 万 token 降到约 1.1 万,大头是技能清单(约 2.5 万字符)和权限说明(约 1.1 万字符)。
94
+ * 剩下的是 Codex 自己的基础指令(改不得,见 modeParams)和关不掉的工具定义。
95
+ * 不认识的 feature 名 Codex 会忽略;配置被拒绝时直接报错,不能丢掉专家限制后重试。
95
96
  */
96
97
  export const CHAT_CONFIG: Record<string, unknown> = {
97
98
  web_search: "live",
@@ -126,6 +127,35 @@ export const CHAT_CONFIG: Record<string, unknown> = {
126
127
  ),
127
128
  };
128
129
 
130
+ /**
131
+ * 按权限在 CHAT_CONFIG 上打开的东西。能读文件就要 shell(Codex 读文件也是跑命令,沙箱只读管着它改不了);
132
+ * 能改文件再给 apply_patch。
133
+ */
134
+ export function expertConfig(e: ExpertRuntime): Record<string, unknown> {
135
+ const rank = ACCESS_LEVELS.indexOf(e.access);
136
+ return {
137
+ ...CHAT_CONFIG,
138
+ web_search: e.webSearch ? "live" : "disabled",
139
+ ...(rank >= 1
140
+ ? { include_permissions_instructions: true, "features.shell_tool": true, "features.unified_exec": true, "features.view_image": true }
141
+ : {}),
142
+ ...(rank >= 2 ? { include_apply_patch_tool: true } : {}),
143
+ };
144
+ }
145
+
146
+ /** 专家选的 MCP 写成 Codex 的 mcp_servers 配置 */
147
+ export function codexMcp(mcp: ExpertRuntime["mcp"], ask: readonly string[] = []): Record<string, unknown> {
148
+ const out: Record<string, unknown> = {};
149
+ for (const [name, spec] of Object.entries(mcp)) {
150
+ const policy = { enabled: true, default_tools_approval_mode: ask.includes(name) ? "prompt" : "approve" };
151
+ if (spec.type === "stdio") out[`mcp_servers.${name}`] = { command: spec.command, args: spec.args, env: spec.env, ...policy };
152
+ else if (spec.type === "http") out[`mcp_servers.${name}`] = { url: spec.url, ...(Object.keys(spec.headers).length ? { http_headers: spec.headers } : {}), ...policy };
153
+ }
154
+ return out;
155
+ }
156
+
157
+ const SANDBOX_RANK = ["read-only", "workspace-write", "danger-full-access"];
158
+
129
159
  /** 用户自己配的 MCP 服务(config.toml 里的 mcp_servers)。名字因人而异,只能读出来再逐个关 */
130
160
  let userMcpCache: { names: string[]; at: number } | null = null;
131
161
 
@@ -137,8 +167,7 @@ export async function userMcpServers(): Promise<string[]> {
137
167
  userMcpCache = { names, at: Date.now() };
138
168
  return names;
139
169
  } catch (err) {
140
- console.warn("[codex] 读取 MCP 配置失败,聊天模式下可能仍会加载用户的 MCP:", err instanceof Error ? err.message : err);
141
- return [];
170
+ throw new Error("读取 Codex MCP 配置失败,无法应用专家的 MCP 限制", { cause: err });
142
171
  }
143
172
  }
144
173
 
@@ -232,13 +261,6 @@ function parseQuestions(raw: unknown): ParsedQuestion[] | null {
232
261
  /** 会话已被丢弃,迟到的异步结果直接作废 */
233
262
  class DisposedError extends Error {}
234
263
 
235
- /** 聊天模式带着全套配置覆盖开 thread 失败了(见 openOnce 的退路) */
236
- class ChatConfigRejected extends Error {
237
- constructor(readonly cause: unknown) {
238
- super("聊天模式的配置覆盖被拒绝");
239
- }
240
- }
241
-
242
264
  export class CodexSession implements AgentSession {
243
265
  private threadId: string | undefined;
244
266
  private turnId: string | undefined;
@@ -361,24 +383,30 @@ export class CodexSession implements AgentSession {
361
383
  return this.opening;
362
384
  }
363
385
 
364
- private get chat(): boolean {
365
- return this.opts.mode === "chat";
386
+ /** 内置专家算能跑命令 */
387
+ private get access(): ExpertAccess {
388
+ return this.opts.expert?.access ?? "exec";
366
389
  }
367
390
 
368
- /** 沙箱:聊天模式一律只读(它本来就没有执行命令的工具,这是第二道保险) */
391
+ /**
392
+ * 沙箱:只能联网、能读文件的专家一律只读(只能联网的本来就没有执行命令的工具,这是第二道保险);
393
+ * 能改文件的最多到 workspace-write;能跑命令的和内置专家一样按设置里的。设置里本来更严就按设置的
394
+ */
369
395
  private get sandboxMode(): string {
370
- return this.chat ? "read-only" : config().agents.codex.sandbox;
396
+ const configured = config().agents.codex.sandbox;
397
+ const cap = this.access === "exec" ? configured : this.access === "edit" ? "workspace-write" : "read-only";
398
+ return SANDBOX_RANK.indexOf(cap) < SANDBOX_RANK.indexOf(configured) ? cap : configured;
371
399
  }
372
400
 
373
401
  /**
374
- * 按模式给 thread 的配置覆盖。thread/start、resume、fork 三条路都带上:配置是每次 resume 现给的,
375
- * 换模式时旧会话先退订(dispose),再 resume 回来就换上了(实测)。
402
+ * 按专家给 thread 的配置覆盖。thread/start、resume、fork 三条路都带上:配置是每次 resume 现给的,
403
+ * 专家改了以后旧会话先退订(dispose),再 resume 回来就换上了(实测)。
376
404
  *
377
- * 不动 baseInstructions / developerInstructions:Codex 把它们钉在 thread 上,切回工作模式时还原不了
378
- * (见 core/chat-mode.ts)。模式和记忆走 contextBlock,附在第一条消息后面。
379
- * minimal:上一次带全套覆盖没能起来,退回只挂记忆工具。
405
+ * 不动 baseInstructions / developerInstructions:Codex 把它们钉在 thread 上,改了专家也还原不了
406
+ * (见 core/expert-prompt.ts)。专家和记忆走 contextBlock,附在第一条消息后面。
407
+ * 自定义专家:机器上的 MCP 除了它选的都关掉,再挂上它选的 agent-loft 管的 MCP。
380
408
  */
381
- private async modeParams(minimal = false): Promise<Record<string, unknown>> {
409
+ private async modeParams(): Promise<Record<string, unknown>> {
382
410
  const memory = this.opts.memory;
383
411
  const tasks = this.opts.tasks;
384
412
  const mcp = {
@@ -391,57 +419,48 @@ export class CodexSession implements AgentSession {
391
419
  }
392
420
  : {}),
393
421
  };
394
- if (this.chat && !minimal) {
395
- const off = Object.fromEntries((await userMcpServers()).map((n) => [`mcp_servers.${n}.enabled`, false]));
396
- return { config: { ...CHAT_CONFIG, ...off, ...mcp } };
422
+ const expert = this.opts.expert;
423
+ if (expert) {
424
+ const keep = new Set([...expert.machineMcp, ...Object.keys(expert.mcp)]);
425
+ const off = Object.fromEntries((await userMcpServers()).filter((n) => !keep.has(n)).map((n) => [`mcp_servers.${n}.enabled`, false]));
426
+ return { config: { ...expertConfig(expert), ...off, ...codexMcp(expert.mcp, expert.askMcp), ...mcp, ...this.skillConfig() } };
397
427
  }
398
- const work = { ...mcp, ...(minimal ? {} : this.skillConfig()) };
428
+ const work = { ...mcp, ...this.skillConfig() };
399
429
  return Object.keys(work).length ? { config: work } : {};
400
430
  }
401
431
 
402
432
  /**
403
- * 工作模式的技能设置:变量逐个写进 shell_environment_policy.set(只作用于这个 thread 里跑的命令,
404
- * 一个个键写不会冲掉用户 config.toml 里本来设的);成员关掉 Codex 自己的技能清单 ——
405
- * 那里面是机器上装的技能,只给管理员。成员的技能走 contextBlock 里的清单。
433
+ * 技能设置:变量逐个写进 shell_environment_policy.set(只作用于这个 thread 里跑的命令,
434
+ * 一个个键写不会冲掉用户 config.toml 里本来设的),只给能跑命令的专家;成员和自定义专家关掉 Codex 自己的
435
+ * 技能清单 —— 那里面是机器上装的技能,只给管理员。agent-loft 的技能走 contextBlock 里的清单。
406
436
  */
407
437
  private skillConfig(): Record<string, unknown> {
408
438
  const skills = this.opts.skills;
409
439
  if (!skills) return {};
410
440
  return {
411
- ...Object.fromEntries(Object.entries(skills.env).map(([k, v]) => [`shell_environment_policy.set.${k}`, v])),
412
- ...(skills.admin ? {} : { "skills.include_instructions": false, "features.skill_search": false }),
441
+ ...(this.access === "exec" ? Object.fromEntries(Object.entries(skills.env).map(([k, v]) => [`shell_environment_policy.set.${k}`, v])) : {}),
442
+ ...(skills.admin && !this.opts.expert ? {} : { "skills.include_instructions": false, "features.skill_search": false }),
413
443
  };
414
444
  }
415
445
 
416
446
  /**
417
- * 这个会话进程还没告诉过 Codex 当前的模式和记忆:第一条消息后面附上 contextBlock。
418
- * 进程一换(切模式、记忆改了、服务重启)就是新的 CodexSession,会再附一次最新的。
419
- * 工作模式、没有记忆、模式也没换过:什么都不附,和原来一模一样。
447
+ * 这个会话进程还没告诉过 Codex 专家和记忆:第一条消息后面附上 contextBlock。
448
+ * 进程一换(专家改了、记忆改了、服务重启)就是新的 CodexSession,会再附一次最新的。
449
+ * 内置专家、没有记忆和技能:什么都不附,和原装的一模一样。
420
450
  */
421
451
  private contextSent = false;
422
452
 
423
453
  private get contextPending(): boolean {
424
- return !this.contextSent && (this.chat || !!this.opts.memory || !!this.opts.announceMode || codexSkillLines(this.opts.skills).length > 0);
454
+ return !this.contextSent && (!!this.opts.expert || !!this.opts.memory || codexSkillLines(this.opts.skills).length > 0);
425
455
  }
426
456
 
427
457
  private async openOnce(): Promise<string> {
428
- try {
429
- return await this.openWith(false);
430
- } catch (err) {
431
- // 聊天模式的那串配置覆盖是按当前版本的 Codex 测出来的:万一哪个键不认导致起不来,退回最小覆盖
432
- if (!(err instanceof ChatConfigRejected) || this.disposed) throw err;
433
- console.warn("[codex] 聊天模式的配置覆盖没能生效,退回只换系统提示:", err.cause instanceof Error ? err.cause.message : err.cause);
434
- return this.openWith(true);
435
- }
436
- }
437
-
438
- private async openWith(minimal: boolean): Promise<string> {
439
458
  const shared = {
440
459
  cwd: this.opts.cwd,
441
460
  approvalPolicy: "on-request",
442
461
  sandbox: this.sandboxMode,
443
462
  ...(this.opts.model ? { model: this.opts.model } : {}),
444
- ...(await this.modeParams(minimal)),
463
+ ...(await this.modeParams()),
445
464
  };
446
465
  if (this.disposed) throw new DisposedError();
447
466
  const resumeId = this.threadId ?? this.opts.resumeId;
@@ -463,8 +482,6 @@ export class CodexSession implements AgentSession {
463
482
  } else {
464
483
  res = await appServer.call<ThreadResponse>("thread/start", shared);
465
484
  }
466
- } catch (err) {
467
- throw this.chat && !minimal ? new ChatConfigRejected(err) : err;
468
485
  } finally {
469
486
  opening.delete(this);
470
487
  }
@@ -532,14 +549,17 @@ export class CodexSession implements AgentSession {
532
549
  this.turnId = undefined;
533
550
  this.stopRequested = false;
534
551
  const token = ++this.turnSeq;
535
- // 聊天模式没有执行命令的工具,读不了文件:文本附件的内容直接放进消息
536
- const chat = this.chat;
537
- const textMap = chat ? readTextAttachments(input.attachments) : new Map<string, string>();
552
+ // 只能联网的专家没有执行命令的工具,读不了文件:文本附件的内容直接放进消息
553
+ const noRead = this.access === "web";
554
+ const textMap = noRead ? readTextAttachments(input.attachments) : new Map<string, string>();
538
555
  const inlined = (a: SavedAttachment) => a.kind === "image" || textMap.has(a.path);
539
- const note = input.attachments.length ? describeAttachments(input.attachments, inlined, chat) : "";
540
- const texts = chat ? inlineTextBlocks(input.attachments, textMap) : "";
556
+ const note = input.attachments.length ? describeAttachments(input.attachments, inlined, noRead) : "";
557
+ const texts = noRead ? inlineTextBlocks(input.attachments, textMap) : "";
541
558
  // 放在最后:Codex 拿第一条消息的开头当会话预览,不能被这段背景占掉
542
- const context = this.contextPending ? contextBlock(chat ? "chat" : "work", this.opts.memory?.prompt, "联网搜索", codexSkillLines(this.opts.skills)) : "";
559
+ const expert = this.opts.expert;
560
+ const context = this.contextPending
561
+ ? contextBlock(expert ? { prompt: expert, cwd: this.opts.cwd } : undefined, this.opts.memory?.prompt, codexSkillLines(this.opts.skills))
562
+ : "";
543
563
  const text = [input.text, note, texts, context].filter(Boolean).join("\n\n");
544
564
  const images = input.attachments.filter((a) => a.kind === "image").map((a) => a.path);
545
565
  let startedOn: string | undefined;
@@ -673,6 +693,18 @@ export class CodexSession implements AgentSession {
673
693
  */
674
694
  async handleServerRequest(method: string, params: unknown): Promise<unknown> {
675
695
  switch (method) {
696
+ case "mcpServer/elicitation/request": {
697
+ const req = params as { serverName: string; mode?: string; message?: string; _meta?: Record<string, unknown> };
698
+ // Codex 用 elicitation 传工具审批;普通 MCP 表单仍按未支持处理,不能把表单当授权。
699
+ if (req.mode !== "form" || req._meta?.codex_approval_kind !== "mcp_tool_call" || !this.opts.expert?.mcp[req.serverName]) {
700
+ return refusalFor(method);
701
+ }
702
+ const detail = [req.message, req._meta.tool_params === undefined ? "" : `\`\`\`json\n${JSON.stringify(req._meta.tool_params, null, 2)}\n\`\`\``].filter(Boolean).join("\n\n");
703
+ // 每次都问,不沿用命令的「本会话全部允许」,也不把授权写回机器配置。
704
+ const outcome = await this.host({ kind: "approval", title: `需要授权:调用 MCP「${req.serverName}」`, detail: detail || "Codex 想调用这个 MCP 的工具。" });
705
+ return { action: allowed(outcome.settlement) ? "accept" : outcome.settlement === "cancelled" ? "cancel" : "decline", content: null, _meta: null };
706
+ }
707
+
676
708
  case "item/commandExecution/requestApproval": {
677
709
  const req = params as CommandExecutionApprovalParams;
678
710
  if (this.allowAll) return { decision: "acceptForSession" };
@@ -917,9 +917,7 @@ export class FeishuBot {
917
917
  case "effort":
918
918
  return this.background(envelope.k, chatId, `思考程度设为 ${envelope.f}`, () => hub.setEffort(envelope.k, envelope.f));
919
919
  case "agent":
920
- return this.background(envelope.k, chatId, `正在切换到 ${hub.label(envelope.g)}`, () =>
921
- hub.setAgent(envelope.k, envelope.g, this.allowedFor(envelope.k)),
922
- );
920
+ return this.background(envelope.k, chatId, "正在换专家…", () => hub.setExpert(envelope.k, envelope.g, this.allowedFor(envelope.k)));
923
921
  case "cmd":
924
922
  return this.runCardCommand(envelope.k, chatId, operatorOpenId, `/${envelope.c}`);
925
923
  case "attach": {
@@ -290,7 +290,7 @@ export function agentPickerCard(params: {
290
290
  }) {
291
291
  return card(
292
292
  [
293
- { tag: "markdown", content: "每个 agent 的会话各自保留,切回来能接着聊。" },
293
+ { tag: "markdown", content: "换专家会开一条新会话,之前的对话不接着聊。自己的专家在网页「设置 → 专家」里建。" },
294
294
  buttonRow(
295
295
  params.agents.map((a) =>
296
296
  button(
@@ -302,7 +302,7 @@ export function agentPickerCard(params: {
302
302
  ),
303
303
  ),
304
304
  ],
305
- { title: "切换 Agent", template: "blue" },
305
+ { title: "换专家", template: "blue" },
306
306
  );
307
307
  }
308
308
 
@@ -71,6 +71,9 @@ import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor } from "./conv
71
71
  import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
72
72
  import { handleTasksApi } from "./tasks-api.js";
73
73
  import { handleSkillsApi } from "./skills-api.js";
74
+ import { handleExpertsApi } from "./experts-api.js";
75
+ import { canUseExpert, getExpert, isBuiltin, listExperts } from "../../core/experts.js";
76
+ import { expertBrief } from "./experts-api.js";
74
77
  import { handleTerminalApi } from "./terminal.js";
75
78
  import { handleDesktopApi, remoteStatus } from "./desktop.js";
76
79
  import {
@@ -647,6 +650,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
647
650
  }),
648
651
  // 飞书机器人是管理员配的,飞书会话也只给管理员看
649
652
  bots: admin ? config().feishu.bots.map((b) => ({ id: b.id, name: b.name, agents: b.agents, enabled: b.enabled })) : [],
653
+ // 自己的专家(新对话、定时任务里选)。内置的 Claude Code / Codex 就是上面的 agents
654
+ experts: listExperts(user.id).map(expertBrief),
650
655
  workspaceRoot: config().workspaceRoot,
651
656
  quotaRefreshMin: config().web.quotaRefreshMin,
652
657
  quotaEnabled: config().web.quotaEnabled,
@@ -726,6 +731,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
726
731
  // ----- 定时任务 -----
727
732
  if (p.startsWith("/api/tasks") && (await handleTasksApi(req, res, p, user))) return;
728
733
  if (p.startsWith("/api/skills") && (await handleSkillsApi(req, res, url, user))) return;
734
+ if ((p.startsWith("/api/experts") || p.startsWith("/api/mcp")) && (await handleExpertsApi(req, res, p, user))) return;
729
735
  if (p.startsWith("/api/terminals") && (await handleTerminalApi(req, res, p, user))) return;
730
736
  if ((p === "/api/remote" || p.startsWith("/api/desktop/")) && (await handleDesktopApi(req, res, p, user))) return;
731
737
 
@@ -758,21 +764,25 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
758
764
  return;
759
765
  }
760
766
  if (p === "/api/conversations" && method === "POST") {
761
- const body = await readJsonBody<{ agent?: string; cwd?: string; mode?: string }>(req);
767
+ // expert:新对话页上选的专家(内置的 claude / codex,或者自己的专家 id)。agent 是以前的叫法
768
+ const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
762
769
  const enabled = hub.enabledAgents().map((d) => d.id);
763
- const agent = body.agent && enabled.includes(body.agent) ? body.agent : enabled[0];
764
- if (!agent) throw new HttpError(400, "没有可用的 agent");
765
- // 新对话发第一条消息前在页面上选的工作目录;和 /cd 一样只能在工作区之内
766
- let cwd: string | null = null;
767
- if (typeof body.cwd === "string" && body.cwd.trim()) {
768
- cwd = resolveWorkspacePath(body.cwd.trim());
769
- if (!cwd) throw new HttpError(400, `目录必须存在,且在 ${config().workspaceRoot} 之内`);
770
+ const wanted = body.expert ?? body.agent;
771
+ let expertId = wanted && canUseExpert(user.id, wanted) ? wanted : enabled[0];
772
+ if (!expertId) throw new HttpError(400, "没有可用的 agent");
773
+ const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
774
+ const agent = custom ? custom.engine : expertId;
775
+ if (!enabled.includes(agent)) throw new HttpError(400, `${hub.label(agent)} 没有启用,用不了这个专家`);
776
+ // 新对话发第一条消息前在页面上选的工作目录;和 /cd 一样只能在工作区之内。没选就用专家默认的
777
+ let cwd: string | undefined;
778
+ const rawCwd = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : custom?.cwd;
779
+ if (rawCwd) {
780
+ const resolved = resolveWorkspacePath(rawCwd);
781
+ if (!resolved) throw new HttpError(400, `目录必须存在,且在 ${config().workspaceRoot} 之内`);
782
+ cwd = resolved;
770
783
  }
771
784
  const key = `web:${crypto.randomBytes(6).toString("hex")}`;
772
- hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, owner: user.id });
773
- if (cwd && cwd !== config().workspaceRoot) updateConversation(key, { cwd, cwdExplicit: true });
774
- // 新对话页上选的模式
775
- if (body.mode === "chat") updateConversation(key, { mode: "chat" });
785
+ hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, ...(custom ? { expert: custom.id } : {}), ...(cwd ? { cwd } : {}), owner: user.id });
776
786
  sendJson(res, 200, hub.info(key));
777
787
  return;
778
788
  }
@@ -976,8 +986,9 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
976
986
  case "effort":
977
987
  text = await hub.setEffort(key, value);
978
988
  break;
989
+ // 换专家(开新会话):只有飞书的对话能换,网页上的 hub 会拒绝
979
990
  case "agent":
980
- text = await hub.setAgent(key, value, allowedAgentsFor(key));
991
+ text = await hub.setExpert(key, value, allowedAgentsFor(key));
981
992
  break;
982
993
  case "stop":
983
994
  text = await hub.stop(key);
@@ -989,10 +1000,6 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
989
1000
  case "cd":
990
1001
  text = await hub.cd(key, value);
991
1002
  break;
992
- case "mode":
993
- if (value !== "chat" && value !== "work") throw new HttpError(400, "模式只能是 chat 或 work");
994
- text = await hub.setMode(key, value);
995
- break;
996
1003
  default:
997
1004
  throw new HttpError(400, "未知操作");
998
1005
  }
@@ -0,0 +1,185 @@
1
+ // 专家和 MCP 的接口:/api/experts、/api/mcp。每人管自己的,看不到别人的(管理员也一样)。
2
+ import type { IncomingMessage, ServerResponse } from "node:http";
3
+ import { userMcpServers } from "../../agents/codex/session.js";
4
+ import {
5
+ ACCESS_LABEL,
6
+ ACCESS_LEVELS,
7
+ createExpert,
8
+ deleteExpert,
9
+ EXPERT_LIMITS,
10
+ EXPERT_TEMPLATES,
11
+ getExpert,
12
+ listExperts,
13
+ updateExpert,
14
+ type Expert,
15
+ type ExpertInput,
16
+ } from "../../core/experts.js";
17
+ import { hub } from "../../core/hub.js";
18
+ import { claudeMachineMcp, createMcp, deleteMcp, getMcp, listMcp, MACHINE_PREFIX, MCP_LIMITS, mcpView, updateMcp, type McpInput } from "../../core/mcp.js";
19
+ import { activeSkills } from "../../core/skills.js";
20
+ import { isAdmin, type User } from "../../core/users.js";
21
+ import { HttpError, readJsonBody, sendJson } from "./http.js";
22
+
23
+ const bad = (err: unknown) => (err instanceof HttpError ? err : new HttpError(400, err instanceof Error ? err.message : String(err)));
24
+
25
+ function expertView(e: Expert) {
26
+ return {
27
+ id: e.id,
28
+ name: e.name,
29
+ description: e.description,
30
+ icon: e.icon,
31
+ color: e.color,
32
+ welcome: e.welcome,
33
+ quickPrompts: e.quickPrompts,
34
+ engine: e.engine,
35
+ model: e.model ?? "",
36
+ effort: e.effort ?? "",
37
+ prompt: e.prompt,
38
+ basePrompt: e.basePrompt,
39
+ access: e.access,
40
+ cwd: e.cwd ?? "",
41
+ webSearch: e.webSearch,
42
+ webFetch: e.webFetch,
43
+ skills: e.skills,
44
+ mcp: e.mcp,
45
+ subagents: e.subagents,
46
+ memory: e.memory,
47
+ updatedAt: e.updatedAt,
48
+ };
49
+ }
50
+
51
+ /** 选专家时要的那点信息(bootstrap 里给,/api/experts/brief 刷新) */
52
+ export function expertBrief(e: Expert) {
53
+ return {
54
+ id: e.id,
55
+ name: e.name,
56
+ description: e.description,
57
+ icon: e.icon,
58
+ color: e.color,
59
+ engine: e.engine,
60
+ access: e.access,
61
+ cwd: e.cwd ?? "",
62
+ model: e.model ?? "",
63
+ effort: e.effort ?? "",
64
+ welcome: e.welcome,
65
+ quickPrompts: e.quickPrompts,
66
+ };
67
+ }
68
+
69
+ /** 机器上原有的 MCP,只给管理员。Codex 的要问 app-server,没启用就不问(问一次就会拉起它) */
70
+ async function machineMcp(user: User): Promise<{ claude: string[]; codex: string[] } | undefined> {
71
+ if (!isAdmin(user)) return undefined;
72
+ const enabled = new Set(hub.enabledAgents().map((d) => d.id));
73
+ const codex = enabled.has("codex") ? await userMcpServers().catch(() => [] as string[]) : [];
74
+ return { claude: enabled.has("claude") ? Object.keys(claudeMachineMcp()) : [], codex };
75
+ }
76
+
77
+ /** 处理了就返回 true */
78
+ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse, p: string, user: User): Promise<boolean> {
79
+ const method = req.method ?? "GET";
80
+
81
+ if (p === "/api/experts" && method === "GET") {
82
+ const enabled = hub.enabledAgents().map((d) => d.id);
83
+ sendJson(res, 200, {
84
+ experts: listExperts(user.id).map(expertView),
85
+ builtin: enabled.map((id) => ({ id, name: hub.label(id), engine: id })),
86
+ engines: enabled,
87
+ templates: EXPERT_TEMPLATES.map((t) => ({ id: t.id, label: t.label, expert: t.expert })),
88
+ access: ACCESS_LEVELS.map((id) => ({ id, label: ACCESS_LABEL[id] })),
89
+ skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
90
+ mcp: listMcp(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description, type: s.type })),
91
+ ...(await machineMcp(user).then((m) => (m ? { machineMcp: m, machinePrefix: MACHINE_PREFIX } : {}))),
92
+ limits: EXPERT_LIMITS,
93
+ });
94
+ return true;
95
+ }
96
+
97
+ if (p === "/api/experts/brief" && method === "GET") {
98
+ sendJson(res, 200, { experts: listExperts(user.id).map(expertBrief) });
99
+ return true;
100
+ }
101
+
102
+ if (p === "/api/experts" && method === "POST") {
103
+ const body = await readJsonBody<ExpertInput>(req, 256 * 1024);
104
+ try {
105
+ sendJson(res, 200, expertView(createExpert(user.id, body)));
106
+ } catch (err) {
107
+ throw bad(err);
108
+ }
109
+ return true;
110
+ }
111
+
112
+ const em = /^\/api\/experts\/(e_[a-f0-9]+)$/.exec(p);
113
+ if (em) {
114
+ const expert = getExpert(em[1]!);
115
+ if (!expert || expert.owner !== user.id) throw new HttpError(404, "这个专家不存在");
116
+ if (method === "GET") {
117
+ sendJson(res, 200, expertView(expert));
118
+ return true;
119
+ }
120
+ if (method === "PATCH") {
121
+ const body = await readJsonBody<ExpertInput>(req, 256 * 1024);
122
+ try {
123
+ sendJson(res, 200, expertView(updateExpert(user.id, expert.id, body)));
124
+ } catch (err) {
125
+ throw bad(err);
126
+ }
127
+ return true;
128
+ }
129
+ if (method === "DELETE") {
130
+ try {
131
+ deleteExpert(user.id, expert.id);
132
+ } catch (err) {
133
+ throw bad(err);
134
+ }
135
+ sendJson(res, 200, { ok: true });
136
+ return true;
137
+ }
138
+ return false;
139
+ }
140
+
141
+ if (p === "/api/mcp" && method === "GET") {
142
+ const experts = listExperts(user.id);
143
+ sendJson(res, 200, {
144
+ servers: listMcp(user.id).map((s) => ({ ...mcpView(s), usedBy: experts.filter((e) => e.mcp.includes(s.id)).map((e) => e.name) })),
145
+ limits: MCP_LIMITS,
146
+ });
147
+ return true;
148
+ }
149
+
150
+ if (p === "/api/mcp" && method === "POST") {
151
+ const body = await readJsonBody<McpInput>(req, 256 * 1024);
152
+ try {
153
+ sendJson(res, 200, mcpView(createMcp(user.id, body)));
154
+ } catch (err) {
155
+ throw bad(err);
156
+ }
157
+ return true;
158
+ }
159
+
160
+ const mm = /^\/api\/mcp\/(m_[a-f0-9]+)$/.exec(p);
161
+ if (mm) {
162
+ const server = getMcp(mm[1]!);
163
+ if (!server || server.owner !== user.id) throw new HttpError(404, "这个 MCP 不存在");
164
+ if (method === "PATCH") {
165
+ const body = await readJsonBody<McpInput>(req, 256 * 1024);
166
+ try {
167
+ sendJson(res, 200, mcpView(updateMcp(user.id, server.id, body)));
168
+ } catch (err) {
169
+ throw bad(err);
170
+ }
171
+ return true;
172
+ }
173
+ if (method === "DELETE") {
174
+ try {
175
+ deleteMcp(user.id, server.id);
176
+ } catch (err) {
177
+ throw bad(err);
178
+ }
179
+ sendJson(res, 200, { ok: true });
180
+ return true;
181
+ }
182
+ return false;
183
+ }
184
+ return false;
185
+ }
@@ -3,7 +3,7 @@
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import type { IncomingMessage, ServerResponse } from "node:http";
6
- import { machineSkills, mentionTargets } from "../../core/skill-runtime.js";
6
+ import { machineSkills } from "../../core/skill-runtime.js";
7
7
  import {
8
8
  canDelete,
9
9
  canSee,
@@ -119,12 +119,6 @@ export async function handleSkillsApi(req: IncomingMessage, res: ServerResponse,
119
119
  return true;
120
120
  }
121
121
 
122
- // 输入框 @ 的补全:自己能用的(管理员加上机器上原有的)
123
- if (p === "/api/skills/mention" && method === "GET") {
124
- sendJson(res, 200, { skills: mentionTargets(user.id).map((t) => ({ name: t.name, description: t.description, kind: t.kind })) });
125
- return true;
126
- }
127
-
128
122
  // 管理员看机器上原有技能的 SKILL.md
129
123
  if (p === "/api/skills/machine" && method === "GET") {
130
124
  if (!isAdmin(user)) throw new HttpError(403, "只有管理员能看机器上的技能");
@@ -1,6 +1,7 @@
1
1
  // 定时任务页面的接口:/api/tasks。每个人只看得到、改得了自己的任务(别人的一律当不存在)。
2
2
  import type { IncomingMessage, ServerResponse } from "node:http";
3
3
  import { config, resolveWorkspacePath } from "../../core/config.js";
4
+ import { canUseExpert, getExpert, isBuiltin } from "../../core/experts.js";
4
5
  import { hub } from "../../core/hub.js";
5
6
  import { memoryOwnerOf } from "../../core/personal.js";
6
7
  import { getConversation } from "../../core/store.js";
@@ -21,11 +22,14 @@ function view(task: Task) {
21
22
  };
22
23
  }
23
24
 
24
- /** 表单 / 请求里的字段先在这里核一遍:agent 要启用着、目录要在工作区里、对话要是自己的 */
25
+ /** 表单 / 请求里的字段先在这里核一遍:专家要是自己能用的、引擎要启用着,目录要在工作区里,对话要是自己的 */
25
26
  function checkInput(user: User, body: TaskInput): TaskInput {
26
27
  const out: TaskInput = { ...body };
27
- if (body.agent !== undefined) {
28
- const agent = String(body.agent);
28
+ const pick = body.expert ?? body.agent;
29
+ if (pick !== undefined) {
30
+ const id = String(pick);
31
+ if (!canUseExpert(user.id, id)) throw new HttpError(400, "这个专家不存在");
32
+ const agent = isBuiltin(id) ? id : getExpert(id)!.engine;
29
33
  if (!hub.enabledAgents().some((d) => d.id === agent)) throw new HttpError(400, `${hub.label(agent)} 没有启用`);
30
34
  }
31
35
  if (typeof body.cwd === "string" && body.cwd.trim()) {
@@ -52,8 +56,8 @@ export async function handleTasksApi(req: IncomingMessage, res: ServerResponse,
52
56
  }
53
57
  if (p === "/api/tasks" && method === "POST") {
54
58
  const body = await readJsonBody<TaskInput>(req);
55
- // 没选 agent(只启用了一个时表单里不显示):用第一个启用着的,不能默认成一个可能没启用的
56
- if (body.agent === undefined || body.agent === "") body.agent = hub.enabledAgents()[0]?.id;
59
+ // 没选专家:用第一个启用着的内置专家,不能默认成一个可能没启用的
60
+ if (!body.expert && !body.agent) body.expert = hub.enabledAgents()[0]?.id;
57
61
  let task: Task;
58
62
  try {
59
63
  task = createTask(user.id, checkInput(user, body), "user");
@@ -22,9 +22,6 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
22
22
  { name: "stop", description: "中断当前执行" },
23
23
  { name: "model", args: "[名称]", description: "切换模型(不带参数弹选择)" },
24
24
  { name: "effort", args: "[程度]", description: "切换思考程度" },
25
- { name: "chat", description: "切到聊天模式:精简、只能联网搜索,每轮开销小很多" },
26
- { name: "work", description: "切到工作模式:agent 原装的全部能力" },
27
- { name: "skills", description: "列出能用的技能(消息里写 @名字 点名使用)" },
28
25
  { name: "status", description: "查看当前会话、模型、目录、剩余额度" },
29
26
  { name: "sessions", args: "[all]", description: "列出历史会话,点按钮恢复;加 all 列所有目录" },
30
27
  { name: "resume", args: "<会话ID>", description: "恢复指定会话" },
@@ -32,9 +29,10 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
32
29
  { name: "pwd", description: "显示当前工作目录" },
33
30
  { name: "fork", description: "从当前会话分叉,原会话保留" },
34
31
  { name: "autoedit", args: "[on|off]", description: "本对话自动允许改工作目录内的文件(Bash 仍询问)" },
35
- { name: "agent", args: "[名称]", description: "查看 / 切换 agent", multiAgentOnly: true },
36
- { name: "claude", description: "切换到 Claude Code", multiAgentOnly: true },
37
- { name: "codex", description: "切换到 Codex", multiAgentOnly: true },
32
+ // 网页上的对话中途不能换专家(新建对话时选),这几个只在飞书里有
33
+ { name: "expert", args: "[名称]", description: "查看 / 换专家(换了会开新会话)", feishuOnly: true },
34
+ { name: "claude", description: "换成 Claude Code 专家(开新会话)", multiAgentOnly: true, feishuOnly: true },
35
+ { name: "codex", description: "换成 Codex 专家(开新会话)", multiAgentOnly: true, feishuOnly: true },
38
36
  { name: "web", description: "接上一条 Web 会话,在飞书里查看和回复", feishuOnly: true },
39
37
  { name: "detach", description: "不再接着 Web 会话,回到这个聊天自己的会话", feishuOnly: true },
40
38
  { name: "bind", args: "<绑定码>", description: "把这个飞书账号绑定到你的 agent-loft 用户(绑定码在 Web 的「设置 → 账号」里生成)", feishuOnly: true },