agent-loft 0.2.97 → 0.2.99

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 (39) hide show
  1. package/README.md +6 -6
  2. package/package.json +1 -1
  3. package/src/agents/claude/session.ts +57 -5
  4. package/src/agents/codex/app-server.ts +2 -1
  5. package/src/agents/codex/protocol.ts +2 -1
  6. package/src/agents/codex/session.ts +65 -1
  7. package/src/channels/feishu/cards.ts +9 -4
  8. package/src/channels/web/api.ts +8 -0
  9. package/src/channels/web/experts-api.ts +32 -5
  10. package/src/channels/web/skills-api.ts +42 -27
  11. package/src/channels/weixin/bot.ts +2 -1
  12. package/src/channels/weixin/format.ts +5 -5
  13. package/src/core/builtin-agents.ts +49 -8
  14. package/src/core/command-catalog.ts +2 -1
  15. package/src/core/commands.ts +11 -0
  16. package/src/core/experts.ts +18 -9
  17. package/src/core/hub.ts +62 -12
  18. package/src/core/interactions.ts +1 -1
  19. package/src/core/mcp.ts +121 -18
  20. package/src/core/permission.ts +20 -2
  21. package/src/core/skill-runtime.ts +5 -4
  22. package/src/core/skills-bridge.ts +95 -24
  23. package/src/core/skills.ts +184 -37
  24. package/src/core/store.ts +5 -0
  25. package/src/core/types.ts +14 -0
  26. package/src/mcp/tasks-server.ts +1 -1
  27. package/web/css/composer.css +15 -0
  28. package/web/lib/permission.js +23 -4
  29. package/web/settings/agents.js +15 -5
  30. package/web/settings/commands.js +1 -1
  31. package/web/settings/experts.js +63 -10
  32. package/web/settings/skills.js +38 -13
  33. package/web/state.js +4 -0
  34. package/web/views/composer.js +4 -3
  35. package/web/views/conv-actions.js +24 -4
  36. package/web/views/interaction.js +9 -5
  37. package/web/views/sidebar.js +1 -0
  38. package/web/views/tasks.js +2 -2
  39. package/web/views/topbar.js +15 -10
@@ -1,27 +1,32 @@
1
1
  // 技能页面的接口:/api/skills。看得到的技能(自己的、公开的、指名给自己的)、安装 / 停用、变量、上传。
2
- // 只有作者能改;管理员能删别人公开或分享出来的(下架),但看不到、删不了别人私有的。
2
+ // 只有作者能改;管理员能查看、下架别人公开或分享出来的(包括没指名给他的),但看不到、删不了别人私有的。
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import type { IncomingMessage, ServerResponse } from "node:http";
6
6
  import { machineSkills } from "../../core/skill-runtime.js";
7
7
  import {
8
+ acceptSkillUpdate,
9
+ allowedHosts,
8
10
  canDelete,
9
11
  canSee,
12
+ canView,
10
13
  createSkill,
11
- declaredHosts,
12
14
  deleteSkill,
15
+ guardedNames,
13
16
  getSkill,
14
17
  installCount,
15
18
  installSkill,
16
19
  listAllSkills,
17
20
  listFiles,
18
21
  parseSkillMd,
22
+ pendingHosts,
19
23
  prepareUpload,
20
24
  readSkillFile,
21
25
  readSkillMd,
22
26
  setSkillEnabled,
23
27
  setSkillVars,
24
28
  SKILL_LIMITS,
29
+ updatePending,
25
30
  updateSkill,
26
31
  userPrefs,
27
32
  type Skill,
@@ -34,6 +39,15 @@ import { HttpError, readJsonBody, sendJson } from "./http.js";
34
39
  function view(s: Skill, user: User) {
35
40
  const prefs = userPrefs(user.id);
36
41
  const mine = s.owner === user.id;
42
+ const installed = mine || prefs.installed.includes(s.id);
43
+ // 受保护的密钥:这个技能能发往哪些地址(用户确认过、技能还声明着的),哪些是作者新加、还没确认的
44
+ const hosts: Record<string, { allowed: string[]; pending: string[] }> = {};
45
+ if (installed) {
46
+ for (const v of s.vars) {
47
+ if (!v.secret || !v.hosts?.length) continue;
48
+ hosts[v.name] = { allowed: allowedHosts(prefs, [s], v.name), pending: pendingHosts(prefs, s, v.name) };
49
+ }
50
+ }
37
51
  return {
38
52
  id: s.id,
39
53
  name: s.name,
@@ -45,38 +59,30 @@ function view(s: Skill, user: User) {
45
59
  // 分享给了谁只有作者看得到
46
60
  ...(mine ? { sharedWith: s.sharedWith, installs: installCount(s.id) } : {}),
47
61
  vars: s.vars,
62
+ hosts,
48
63
  source: s.source,
49
64
  createdAt: s.createdAt,
50
65
  updatedAt: s.updatedAt,
51
- installed: mine || prefs.installed.includes(s.id),
66
+ installed,
67
+ // 管理员能看到没指名给他的分享(为了审查、下架),但装不了
68
+ canInstall: !mine && canSee(user, s),
69
+ // 作者改了内容,确认新版之前不加载
70
+ updatePending: updatePending(user.id, s, prefs),
52
71
  enabled: !prefs.disabled.includes(s.id),
53
72
  canDelete: canDelete({ id: user.id, role: user.role }, s),
54
73
  };
55
74
  }
56
75
 
57
76
  /**
58
- * 变量:值按名字存;密钥(任何一个看得到的技能把它标成密钥)不回显,只说填没填。
59
- * 受保护的密钥再带上确认过的地址(hosts),作者后来加了没确认过的地址就列在 pending 里。
77
+ * 变量:值按名字存;密钥(任何一个看得到的技能把它标成密钥,或者按受保护密钥填的)不回显,只说填没填。
78
+ * 受保护的密钥能发往哪些地址按技能分开,在各技能的 hosts 里。
60
79
  */
61
80
  function varsView(user: User, skills: Skill[]) {
62
- const secret = new Set(skills.flatMap((s) => s.vars.filter((v) => v.secret).map((v) => v.name)));
81
+ const secret = new Set([...skills.flatMap((s) => s.vars.filter((v) => v.secret).map((v) => v.name)), ...guardedNames(user.id)]);
82
+ const guarded = guardedNames(user.id);
63
83
  const prefs = userPrefs(user.id);
64
- const mineOrInstalled = skills.filter((s) => s.owner === user.id || prefs.installed.includes(s.id));
65
84
  return Object.fromEntries(
66
- Object.entries(prefs.vars).map(([k, v]) => {
67
- const declared = declaredHosts(mineOrInstalled, k);
68
- const approved = prefs.approved[k] ?? [];
69
- const pending = declared.filter((h) => !approved.includes(h));
70
- return [
71
- k,
72
- {
73
- set: true,
74
- ...(secret.has(k) ? {} : { value: v }),
75
- ...(declared.length ? { hosts: approved } : {}),
76
- ...(pending.length ? { pending } : {}),
77
- },
78
- ];
79
- }),
85
+ Object.entries(prefs.vars).map(([k, v]) => [k, { set: true, ...(secret.has(k) ? {} : { value: v }), ...(guarded.has(k) ? { guarded: true } : {}) }]),
80
86
  );
81
87
  }
82
88
 
@@ -105,7 +111,7 @@ export async function handleSkillsApi(req: IncomingMessage, res: ServerResponse,
105
111
  const viewer = { id: user.id, role: user.role };
106
112
 
107
113
  if (p === "/api/skills" && method === "GET") {
108
- const visible = listAllSkills().filter((s) => canSee(viewer, s));
114
+ const visible = listAllSkills().filter((s) => canView(viewer, s));
109
115
  sendJson(res, 200, {
110
116
  skills: visible.map((s) => view(s, user)),
111
117
  vars: varsView(user, visible),
@@ -135,13 +141,13 @@ export async function handleSkillsApi(req: IncomingMessage, res: ServerResponse,
135
141
  }
136
142
 
137
143
  if (p === "/api/skills/vars" && method === "PUT") {
138
- const body = await readJsonBody<{ values?: Record<string, unknown>; approve?: unknown }>(req);
144
+ const body = await readJsonBody<{ values?: Record<string, unknown>; approve?: unknown; skill?: unknown }>(req);
139
145
  try {
140
- setSkillVars(user.id, body.values ?? {}, Array.isArray(body.approve) ? body.approve.map(String) : []);
146
+ setSkillVars(user.id, body.values ?? {}, Array.isArray(body.approve) ? body.approve.map(String) : [], typeof body.skill === "string" ? body.skill : undefined);
141
147
  } catch (err) {
142
148
  throw bad(err);
143
149
  }
144
- sendJson(res, 200, { vars: varsView(user, listAllSkills().filter((s) => canSee(viewer, s))) });
150
+ sendJson(res, 200, { vars: varsView(user, listAllSkills().filter((s) => canView(viewer, s))) });
145
151
  return true;
146
152
  }
147
153
 
@@ -159,10 +165,10 @@ export async function handleSkillsApi(req: IncomingMessage, res: ServerResponse,
159
165
  return true;
160
166
  }
161
167
 
162
- const m = /^\/api\/skills\/(s_[a-f0-9]+)(?:\/(install|enable|file))?$/.exec(p);
168
+ const m = /^\/api\/skills\/(s_[a-f0-9]+)(?:\/(install|enable|file|accept))?$/.exec(p);
163
169
  if (!m) return false;
164
170
  const skill = getSkill(m[1]!);
165
- if (!skill || !canSee(viewer, skill)) throw new HttpError(404, "这个技能不存在");
171
+ if (!skill || !canView(viewer, skill)) throw new HttpError(404, "这个技能不存在");
166
172
 
167
173
  if (!m[2] && method === "GET") {
168
174
  const md = parseSkillMd(readSkillMd(skill.id));
@@ -187,6 +193,15 @@ export async function handleSkillsApi(req: IncomingMessage, res: ServerResponse,
187
193
  sendJson(res, 200, view(skill, user));
188
194
  return true;
189
195
  }
196
+ if (m[2] === "accept" && method === "POST") {
197
+ try {
198
+ acceptSkillUpdate(user.id, skill.id);
199
+ } catch (err) {
200
+ throw bad(err);
201
+ }
202
+ sendJson(res, 200, view(skill, user));
203
+ return true;
204
+ }
190
205
  if (m[2] === "enable" && method === "POST") {
191
206
  const body = await readJsonBody<{ on?: boolean }>(req);
192
207
  setSkillEnabled(user.id, skill.id, body.on !== false);
@@ -307,7 +307,8 @@ export class WeixinBot {
307
307
  if (i.spec.kind === "approval") {
308
308
  const decision = parseApproval(text, i, this.admin);
309
309
  if (decision === undefined) {
310
- this.say(`还有一个授权在等你:回复 1 允许一次,回复 0 拒绝。这条消息已排队,处理完授权才会发给 agent。`);
310
+ // 不阻塞的卡(Codex 出完方案问开不开始做):另外发消息就是不用它了,照常发给 agent
311
+ if (!i.spec.detached) this.say(`还有一个授权在等你:回复 1 ${i.spec.allowLabel ?? "允许一次"},回复 0 ${i.spec.denyLabel ?? "拒绝"}。这条消息已排队,处理完授权才会发给 agent。`);
311
312
  return false;
312
313
  }
313
314
  if (tooSoon) {
@@ -66,12 +66,12 @@ export function approvalPrompt(i: Interaction, isAdmin: boolean, timeoutMin: num
66
66
  clip(spec.detail, 2500),
67
67
  "",
68
68
  "回复数字:",
69
- "1 允许一次",
69
+ `1 ${spec.allowLabel ?? "允许一次"}`,
70
70
  ...(spec.allowSession ? ["2 本会话全部允许"] : []),
71
71
  ...(canAlways(spec, isAdmin) ? [`3 ${spec.alwaysLabel}`] : []),
72
- "0 拒绝",
72
+ `0 ${spec.denyLabel ?? "拒绝"}`,
73
73
  "",
74
- `网页上也能处理。${timeoutMin} 分钟没回应按拒绝。`,
74
+ spec.detached ? "网页上也能处理。直接发消息就是不用这张卡。" : `网页上也能处理。${timeoutMin} 分钟没回应按拒绝。`,
75
75
  ].join("\n");
76
76
  }
77
77
 
@@ -80,8 +80,8 @@ export function parseApproval(text: string, i: Interaction, isAdmin: boolean): A
80
80
  const spec = i.spec;
81
81
  if (spec.kind !== "approval") return undefined;
82
82
  const t = text.trim();
83
- if (t === "1" || t === "允许") return "allow-once";
84
- if (t === "0" || t === "拒绝") return "deny";
83
+ if (t === "1" || t === "允许" || (!!spec.allowLabel && t === spec.allowLabel)) return "allow-once";
84
+ if (t === "0" || t === "拒绝" || (!!spec.denyLabel && t === spec.denyLabel)) return "deny";
85
85
  if (t === "2" && spec.allowSession) return "allow-session";
86
86
  if (t === "3" && canAlways(spec, isAdmin)) return "allow-always";
87
87
  return undefined;
@@ -3,11 +3,12 @@ import path from "node:path";
3
3
  import { EventEmitter } from "node:events";
4
4
  import { dataDir, readJson, writeJsonAtomic } from "../home.js";
5
5
  import { ENGINES, resolveMcp, type Engine } from "./experts.js";
6
- import { getMcp, isMachineId, machineName } from "./mcp.js";
6
+ import { canUseMcp, getMcp, isMachineId, machineName } from "./mcp.js";
7
7
  import { activeSkills } from "./skills.js";
8
8
  import { sessionSkills } from "./skill-runtime.js";
9
9
  import { getUser } from "./users.js";
10
10
  import type { SessionOptions } from "./types.js";
11
+ import { DEFAULT_PERMISSION_LEVELS, engineSupports, type PermissionLevel } from "./permission.js";
11
12
 
12
13
  export type BuiltinAgentDefaults = {
13
14
  /** null = 全部已启用的个人技能;[] = 不加载个人技能 */
@@ -15,18 +16,42 @@ export type BuiltinAgentDefaults = {
15
16
  machineSkills: boolean;
16
17
  /** null = 沿用机器配置;[] = 不加载 MCP(系统工具除外) */
17
18
  mcp: string[] | null;
19
+ /**
20
+ * 这个人用这个引擎的对话默认按哪一级权限(没单独选过级别的对话都按它,专家照样按自己的权限封顶)。
21
+ * null = 跟随引擎(Claude 逐次询问,Codex 按设置里的沙箱)。和技能、MCP 不同,自定义专家的对话也按它
22
+ */
23
+ permission: PermissionLevel | null;
18
24
  };
19
25
  type Defaults = Record<Engine, BuiltinAgentDefaults>;
20
26
  const file = path.join(dataDir, "builtin-agents.json");
21
27
  export const builtinAgentEvents = new EventEmitter<{ changed: [owner: string] }>();
22
28
 
29
+ // 对话列表里每条都要算默认权限,不能每次都读盘。只有本文件写它
30
+ let cache: Record<string, Partial<Defaults>> | null = null;
31
+ function readAll(): Record<string, Partial<Defaults>> {
32
+ return (cache ??= readJson<Record<string, Partial<Defaults>>>(file, {}));
33
+ }
34
+ function writeAll(all: Record<string, Partial<Defaults>>): void {
35
+ writeJsonAtomic(file, all);
36
+ cache = all;
37
+ }
38
+
39
+ function storedPermission(value: unknown, engine: Engine, admin: boolean): PermissionLevel | null {
40
+ if (!(DEFAULT_PERMISSION_LEVELS as readonly unknown[]).includes(value)) return null;
41
+ const level = value as PermissionLevel;
42
+ // 成员最高到自动改文件(见 hub.permissionMax);管理员降级成成员后,以前存的高一级不再算数
43
+ if (!engineSupports(engine, level) || (level === "auto" && !admin)) return null;
44
+ return level;
45
+ }
46
+
23
47
  export function builtinAgentDefaults(owner: string): Defaults {
24
48
  const admin = getUser(owner)?.role === "admin";
25
- const stored = readJson<Record<string, Partial<Defaults>>>(file, {})[owner];
49
+ const stored = readAll()[owner];
26
50
  const defaults = (engine: Engine): BuiltinAgentDefaults => ({
27
51
  skills: stored?.[engine]?.skills ?? null,
28
52
  machineSkills: admin && stored?.[engine]?.machineSkills !== false,
29
53
  mcp: stored?.[engine]?.mcp ?? (admin ? null : []),
54
+ permission: storedPermission(stored?.[engine]?.permission, engine, admin),
30
55
  });
31
56
  return { claude: defaults("claude"), codex: defaults("codex") };
32
57
  }
@@ -64,16 +89,22 @@ export function setBuiltinAgentDefaults(owner: string, patch: unknown): Defaults
64
89
  for (const id of ids ?? []) {
65
90
  const server = getMcp(id);
66
91
  const name = isMachineId(id) ? machineName(id) : server?.name;
67
- if (isMachineId(id) ? user.role !== "admin" || !name || !/^[A-Za-z0-9_-]{1,100}$/.test(name) : !server || server.owner !== owner) throw new Error("只能选择自己的 MCP(机器 MCP 仅管理员可选)");
92
+ if (isMachineId(id) ? user.role !== "admin" || !name || !/^[A-Za-z0-9_-]{1,100}$/.test(name) : !canUseMcp(owner, server)) throw new Error("只能选择自己的或别人共享的 MCP(机器 MCP 仅管理员可选)");
68
93
  if (names.has(name!)) throw new Error(`MCP 服务名重复:${name}`);
69
94
  names.add(name!);
70
95
  }
71
96
  current.mcp = ids;
72
97
  }
98
+ if (p.permission !== undefined) {
99
+ if (p.permission !== null && !(DEFAULT_PERMISSION_LEVELS as readonly unknown[]).includes(p.permission)) throw new Error("默认权限只能是逐次询问、自动改文件或自动判断");
100
+ const level = p.permission as PermissionLevel | null;
101
+ if (level && !engineSupports(engine, level)) throw new Error("「自动判断」只有 Claude Code 能用");
102
+ if (level === "auto" && user.role !== "admin") throw new Error("只有管理员能把「自动判断」设成默认");
103
+ current.permission = level;
104
+ }
73
105
  }
74
- const all = readJson<Record<string, Defaults>>(file, {});
75
- all[owner] = next;
76
- writeJsonAtomic(file, all);
106
+ const all = { ...readAll(), [owner]: next };
107
+ writeAll(all);
77
108
  builtinAgentEvents.emit("changed", owner);
78
109
  return next;
79
110
  }
@@ -88,9 +119,19 @@ export function builtinAgentSession(owner: string | undefined, engine: Engine):
88
119
  };
89
120
  }
90
121
 
122
+ /** 对话没单独选过级别时按哪一级(没主人的对话没有默认) */
123
+ export function defaultPermissionOf(owner: string | undefined, engine: string): PermissionLevel | undefined {
124
+ if (!owner || !getUser(owner) || !(ENGINES as readonly string[]).includes(engine)) return undefined;
125
+ return builtinAgentDefaults(owner)[engine as Engine].permission ?? undefined;
126
+ }
127
+
91
128
  export function deleteBuiltinAgentDefaults(owner: string): void {
92
- const all = readJson<Record<string, Defaults>>(file, {});
129
+ const all = { ...readAll() };
93
130
  if (!(owner in all)) return;
94
131
  delete all[owner];
95
- writeJsonAtomic(file, all);
132
+ writeAll(all);
133
+ }
134
+
135
+ export function resetBuiltinAgentCacheForTest(): void {
136
+ cache = null;
96
137
  }
@@ -30,7 +30,8 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
30
30
  { name: "cd", args: "<相对目录>", description: "切换工作目录(限 workspace 内)" },
31
31
  { name: "pwd", description: "显示当前工作目录" },
32
32
  { name: "fork", description: "从当前会话分叉,原会话保留" },
33
- { name: "permission", args: "[ask|edit|full|default]", description: "查看 / 切换本对话的权限级别(逐次询问、自动改文件、完全允许)" },
33
+ { name: "permission", args: "[ask|edit|auto|full|default]", description: "查看 / 切换本对话的权限级别(逐次询问、自动改文件、自动判断、完全允许)" },
34
+ { name: "planmode", args: "[on|off]", description: "开关计划模式:先出方案,批准了再动手" },
34
35
  { name: "autoedit", args: "[on|off]", description: "本对话自动允许改工作目录内的文件(等于 /permission edit)" },
35
36
  // 网页上的对话中途不能换专家(新建对话时选),这几个只在飞书、微信里有
36
37
  { name: "expert", args: "[名称]", description: "查看 / 换专家(换了会开新会话)", chatOnly: true },
@@ -19,6 +19,8 @@ export type ParsedCommand =
19
19
  | { kind: "status" }
20
20
  | { kind: "pwd" }
21
21
  | { kind: "autoedit"; on?: boolean }
22
+ /** 计划模式;on 不给就是切换 */
23
+ | { kind: "plan"; on?: boolean }
22
24
  /** default:恢复默认;不给就是看当前级别 */
23
25
  | { kind: "permission"; level?: PermissionLevel | "default" }
24
26
  | { kind: "help" }
@@ -30,6 +32,7 @@ export type ParsedCommand =
30
32
  const PERMISSION_ARGS: Record<string, PermissionLevel | "default"> = {
31
33
  ask: "ask", 询问: "ask", 逐次询问: "ask",
32
34
  edit: "edit", 自动改文件: "edit",
35
+ auto: "auto", 自动判断: "auto",
33
36
  full: "full", 完全允许: "full",
34
37
  default: "default", 默认: "default",
35
38
  };
@@ -81,6 +84,14 @@ export function parseCommand(raw: string): ParsedCommand {
81
84
  if (["off", "关", "0", "false"].includes(v)) return { kind: "autoedit", on: false };
82
85
  return { kind: "chat", text };
83
86
  }
87
+ // 不叫 /plan:那是很常见的自定义命令名,内置了会把用户已有的挤掉
88
+ case "planmode": {
89
+ const v = arg.toLowerCase();
90
+ if (!v) return { kind: "plan" };
91
+ if (["on", "开", "1", "true"].includes(v)) return { kind: "plan", on: true };
92
+ if (["off", "关", "0", "false"].includes(v)) return { kind: "plan", on: false };
93
+ return { kind: "chat", text };
94
+ }
84
95
  case "permission": {
85
96
  if (!arg) return { kind: "permission" };
86
97
  const level = Object.hasOwn(PERMISSION_ARGS, arg.toLowerCase()) ? PERMISSION_ARGS[arg.toLowerCase()] : undefined;
@@ -12,7 +12,7 @@ import fs from "node:fs";
12
12
  import path from "node:path";
13
13
  import { dataDir, readJson, writeJsonAtomic } from "../home.js";
14
14
  import { resolveWorkspacePath } from "./config.js";
15
- import { claudeMachineMcp, getMcp, isMachineId, machineName, specOf, type McpSpec } from "./mcp.js";
15
+ import { canUseMcp, claudeMachineMcp, getMcp, isMachineId, machineName, specOf, type McpSpec } from "./mcp.js";
16
16
  import { activeSkills, canSee, getSkill } from "./skills.js";
17
17
  import { canUseResource, getUser } from "./users.js";
18
18
 
@@ -205,11 +205,18 @@ export function canUseExpert(owner: string | undefined, id: string): boolean {
205
205
  return e.shared === true && !!creator && !creator.disabled && canUseResource(user, "experts", id);
206
206
  }
207
207
 
208
- /** 发布者沿用专家原有的工具选择;其他人未配置时不加载技能和 MCP。 */
208
+ /**
209
+ * 发布者沿用专家原有的工具选择。其他人自己配过就用自己的;没配过就沿用发布者选的里面他也能用的:
210
+ * 他自己启用着的技能(装了发布者共享的技能才算),发布者共享出来的 MCP(调用前会问,密钥用他自己的)。
211
+ * 发布者私有的 MCP、机器上的 MCP 不会带给别人。
212
+ */
209
213
  export function expertTools(owner: string, expert: Expert): ExpertTools {
210
214
  if (!canUseExpert(owner, expert.id)) throw new Error("这个专家不存在或已取消共享");
211
215
  if (expert.owner === owner) return { skills: expert.skills, mcp: expert.mcp };
212
- return readJson<PersonalTools>(toolsPath, {})[owner]?.[expert.id] ?? { skills: [], mcp: [] };
216
+ const own = readJson<PersonalTools>(toolsPath, {})[owner]?.[expert.id];
217
+ if (own) return own;
218
+ const active = new Set(activeSkills(owner).map((s) => s.id));
219
+ return { skills: expert.skills.filter((id) => active.has(id)), mcp: expert.mcp.filter((id) => !isMachineId(id) && canUseMcp(owner, id)) };
213
220
  }
214
221
 
215
222
  export function setExpertTools(owner: string, id: string, input: unknown): ExpertTools {
@@ -229,7 +236,7 @@ export function setExpertTools(owner: string, id: string, input: unknown): Exper
229
236
  for (const id of next.mcp) {
230
237
  const server = getMcp(id);
231
238
  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 仅管理员可选)");
239
+ if (isMachineId(id) ? !admin || !name || !/^[A-Za-z0-9_-]{1,100}$/.test(name) : !canUseMcp(owner, server)) throw new Error("只能选择自己的或别人共享的 MCP(机器 MCP 仅管理员可选)");
233
240
  if (names.has(name!)) throw new Error(`MCP 服务名重复:${name}`);
234
241
  names.add(name!);
235
242
  }
@@ -309,8 +316,8 @@ function validate(owner: string, input: ExpertInput, prev?: Expert, selfId?: str
309
316
  return !!s && canSee({ id: owner }, s);
310
317
  });
311
318
 
312
- // MCP:自己的;机器上的只有管理员能选
313
- const mcp = ids(pick("mcp")).filter((id) => (isMachineId(id) ? admin && machineName(id).length > 0 : getMcp(id)?.owner === owner));
319
+ // MCP:自己的和别人共享的;机器上的只有管理员能选
320
+ const mcp = ids(pick("mcp")).filter((id) => (isMachineId(id) ? admin && machineName(id).length > 0 : canUseMcp(owner, id)));
314
321
 
315
322
  // 子智能体:自己的 Claude 专家,权限不能比自己高,不能是自己
316
323
  const subRaw = engine === "claude" ? ids(pick("subagents")) : [];
@@ -473,10 +480,12 @@ export function resolveMcp(expert: Pick<Expert, "owner" | "engine" | "mcp">, adm
473
480
  else if (claudeMachine[name]) mcp[name] = claudeMachine[name]!;
474
481
  continue;
475
482
  }
483
+ // expert.owner 在这里是用这个专家的人(见 expertRuntime)
476
484
  const s = getMcp(id);
477
- if (!s || s.owner !== expert.owner) continue;
478
- mcp[s.name] = specOf(s);
479
- if (s.ask) ask.push(s.name);
485
+ if (!s || !canUseMcp(expert.owner, s)) continue;
486
+ mcp[s.name] = specOf(s, expert.owner);
487
+ // 别人共享的:调用前一律先问
488
+ if (s.ask || s.owner !== expert.owner) ask.push(s.name);
480
489
  }
481
490
  return { mcp, ask, machine };
482
491
  }
package/src/core/hub.ts CHANGED
@@ -37,7 +37,7 @@ import {
37
37
  import { formatDateTime } from "./task-schedule.js";
38
38
  import { attachmentInfo, ensureUploadsDir, KIND_LABEL } from "./uploads.js";
39
39
  import { memoryOwnerOf, sessionMemory } from "./personal.js";
40
- import { exceedsPermission, minPermission, PERMISSION_LABEL, permissionCapOfAccess, permissionOfSandbox, type PermissionLevel } from "./permission.js";
40
+ import { engineSupports, exceedsPermission, forEngine, minPermission, PERMISSION_LABEL, permissionCapOfAccess, permissionOfSandbox, type PermissionLevel } from "./permission.js";
41
41
  import { readMemory } from "./memory.js";
42
42
  import { canUseFiles, getUser, userEvents } from "./users.js";
43
43
  import type {
@@ -61,7 +61,7 @@ import { helpText, type ParsedCommand } from "./commands.js";
61
61
  import { listScheduled } from "./scheduled.js";
62
62
  import { expertSystemPrompt, searchLabel, stripContext, wrapContext } from "./expert-prompt.js";
63
63
  import { availableExperts, avatarUrl, canUseExpert, expertEvents, expertToolEvents, expertRuntime, getExpert, isBuiltin, type ExpertRuntime } from "./experts.js";
64
- import { builtinAgentDefaults, builtinAgentEvents, builtinAgentSession } from "./builtin-agents.js";
64
+ import { builtinAgentDefaults, builtinAgentEvents, builtinAgentSession, defaultPermissionOf } from "./builtin-agents.js";
65
65
  import { mcpEvents } from "./mcp.js";
66
66
  import { isMachineCommand, sessionSkills } from "./skill-runtime.js";
67
67
  import { skillEvents } from "./skills.js";
@@ -204,6 +204,8 @@ export type ConversationInfo = {
204
204
  permission: PermissionLevel;
205
205
  /** 这条对话最高能选到哪一级 */
206
206
  permissionMax: PermissionLevel;
207
+ /** 计划模式开着:先出方案,批准了再动手 */
208
+ plan?: boolean;
207
209
  /** 这条对话的专家 */
208
210
  expert: ExpertBadge;
209
211
  /** 这条对话有主人、会用上主人的记忆(主人自己关了记忆的话实际不会注入,见 personal.ts) */
@@ -364,7 +366,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
364
366
  this.dropIfStale(key);
365
367
  }
366
368
  });
367
- mcpEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
369
+ mcpEvents.on("changed", (users) => this.personalChanged(new Set(users)));
368
370
  builtinAgentEvents.on("changed", (owner) => this.personalChanged(new Set([owner])));
369
371
  // workspaceRoot 改了:store 会把没显式 /cd 过的会话目录重置,正在跑的旧目录会话要作废
370
372
  onConfigChange((next, prev) => {
@@ -683,6 +685,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
683
685
  ...(binding.sessionId || binding.forkFrom || binding.parked || binding.pastSessions?.length ? { canHandoff: true } : {}),
684
686
  permission: this.permissionOf(conv),
685
687
  permissionMax: this.permissionMax(conv),
688
+ ...(conv.plan ? { plan: true } : {}),
686
689
  expert: this.expertBadge(conv),
687
690
  ...(memoryOwnerOf(conv) ? { personal: true } : {}),
688
691
  ...(conv.taskId ? { taskId: conv.taskId } : {}),
@@ -788,6 +791,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
788
791
  ...(resumeId ? { resumeId } : {}),
789
792
  ...(fork ? { fork: true } : {}),
790
793
  ...(permission ? { permission } : {}),
794
+ ...(conv.plan ? { plan: true } : {}),
791
795
  ...(taskOwner && getUser(taskOwner)?.role !== "admin" ? { noSessionGrant: true } : {}),
792
796
  ...(expert ? { expert } : {}),
793
797
  ...(memory ? { memory } : {}),
@@ -809,6 +813,11 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
809
813
  onTodos: (todos) => alive() && this.emitEvent(key, { type: "todos", todos }),
810
814
  onTextDelta: (text) => alive() && this.emitEvent(key, { type: "delta", text }),
811
815
  onText: (text) => alive() && this.emitEvent(key, { type: "text", text }),
816
+ onPlanMode: (on) => {
817
+ if (!alive() || !!getConversation(key)?.plan === on) return;
818
+ updateConversation(key, { plan: on || undefined });
819
+ this.emitEvent(key, { type: "meta" });
820
+ },
812
821
  onFollowUp: (text) => {
813
822
  if (!alive()) return;
814
823
  try {
@@ -1499,7 +1508,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
1499
1508
  channel: "weixin", channelId: conv.channelId,
1500
1509
  agent: conv.agent, expert: conv.expert, owner: conv.owner,
1501
1510
  cwd: conv.cwd, cwdExplicit: conv.cwdExplicit,
1502
- ...(requestedPermission(conv) === "edit" ? { permission: "edit" } : {}),
1511
+ ...carriedPermission(conv),
1503
1512
  perAgent: {}, createdAt: now, activeAt: now,
1504
1513
  ...patch,
1505
1514
  };
@@ -1635,10 +1644,14 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
1635
1644
  return !admin && conv.agent === "codex" ? minPermission(max, permissionOfSandbox(config().agents.codex.sandbox)) : max;
1636
1645
  }
1637
1646
 
1638
- /** 交给 session 的级别:选过的按上限封顶;没选过就是 undefined,走引擎默认 */
1647
+ /**
1648
+ * 交给 session 的级别:选过的按上限封顶,引擎不认的降一级(Codex 没有自动判断);
1649
+ * 没选过就按主人在设置里定的默认,也没有就是 undefined,走引擎默认。
1650
+ * 定时任务的专用对话不用默认:级别只跟着任务走
1651
+ */
1639
1652
  private effectivePermission(conv: Conversation): PermissionLevel | undefined {
1640
- const wanted = requestedPermission(conv);
1641
- return wanted ? minPermission(wanted, this.permissionMax(conv)) : undefined;
1653
+ const wanted = requestedPermission(conv) ?? (conv.taskId ? undefined : defaultPermissionOf(memoryOwnerOf(conv), conv.agent));
1654
+ return wanted ? forEngine(conv.agent, minPermission(wanted, this.permissionMax(conv))) : undefined;
1642
1655
  }
1643
1656
 
1644
1657
  /** 给人看的级别:没选过就换算引擎默认(Claude 逐次询问,Codex 看设置里的沙箱,不超过专家) */
@@ -1687,12 +1700,14 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
1687
1700
  private describePermission(key: string): string {
1688
1701
  const conv = getConversation(key)!;
1689
1702
  return [
1690
- `当前权限:${PERMISSION_LABEL[this.permissionOf(conv)]}。`,
1703
+ `当前权限:${PERMISSION_LABEL[this.permissionOf(conv)]}${conv.plan ? ",计划模式开着" : ""}。`,
1691
1704
  "",
1692
1705
  "- `/permission ask`:逐次询问",
1693
1706
  "- `/permission edit`:自动改文件",
1707
+ ...(engineSupports(conv.agent, "auto") ? ["- `/permission auto`:自动判断(Claude 逐个判断安不安全,拿不准再问你)"] : []),
1694
1708
  "- `/permission full`:完全允许",
1695
- "- `/permission default`:恢复默认",
1709
+ "- `/permission default`:恢复默认(设置 → Agent 里定的默认权限)",
1710
+ "- `/planmode on` / `/planmode off`:开关计划模式(先出方案,你批准了再动手)",
1696
1711
  "",
1697
1712
  `这条对话最高能到「${PERMISSION_LABEL[this.permissionMax(conv)]}」。`,
1698
1713
  ].join("\n");
@@ -1705,6 +1720,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
1705
1720
  return `⚠️ 已切换为「完全允许」:agent 的操作不再询问,可以跑任意命令、改任意文件。提问和标了「调用前询问」的 MCP 照常询问;开新会话后恢复默认。${nextTurn}`;
1706
1721
  }
1707
1722
  if (level === "ask") return `已切换为「逐次询问」:改文件、跑命令都要先问你。${nextTurn}`;
1723
+ if (level === "auto") return "已切换为「自动判断」:Claude 逐个判断操作安不安全,安全的直接做,拿不准的再问你。";
1708
1724
  return conv.agent === "codex"
1709
1725
  ? `已切换为「自动改文件」:工作目录(${conv.cwd})内可以直接改文件、跑命令,超出沙箱的要先问你。${nextTurn}`
1710
1726
  : `已切换为「自动改文件」:修改工作目录(${conv.cwd})内的文件不再询问;目录外的文件、Bash 命令照常询问。`;
@@ -1714,6 +1730,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
1714
1730
  const conv = getConversation(key)!;
1715
1731
  if (conv.taskId) return "这是定时任务的专用对话,权限跟着任务走。到定时任务页面编辑这个任务来改。";
1716
1732
  if (level === "full" && !allowFull) return "只有管理员本人能选「完全允许」。飞书上要在私聊里、并且绑定了管理员账号。";
1733
+ if (level && !engineSupports(conv.agent, level)) return `「${PERMISSION_LABEL[level]}」只有 Claude Code 能用。`;
1717
1734
  const max = this.permissionMax(conv);
1718
1735
  if (level && exceedsPermission(level, max)) return `这条对话最高只能到「${PERMISSION_LABEL[max]}」(看对话的主人和专家的权限)。`;
1719
1736
  this.applyPermission(key, level);
@@ -1725,6 +1742,31 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
1725
1742
  return this.serial(key, async () => this.setPermissionNow(key, level, allowFull));
1726
1743
  }
1727
1744
 
1745
+ /** 计划模式。on 不给就是切换。不动权限级别:批准方案后按原来的级别干活 */
1746
+ private setPlanNow(key: string, on: boolean | undefined): string {
1747
+ const conv = getConversation(key)!;
1748
+ if (conv.taskId) return "定时任务的专用对话到点就要直接干活,不能开计划模式。";
1749
+ const next = on ?? !conv.plan;
1750
+ if (next === !!conv.plan) return next ? "计划模式本来就开着。" : "计划模式本来就关着。";
1751
+ updateConversation(key, { plan: next || undefined });
1752
+ const live = this.live.get(key);
1753
+ live?.session.setPlan?.(next)?.catch((err) => {
1754
+ // 没切过去:不能让它照旧动手(或一直只出方案),空闲下来按新开关重新拉起
1755
+ console.warn(`[${conv.agent}] ${key} 切换计划模式失败:`, err instanceof Error ? err.message : err);
1756
+ this.staleLive.add(live.id);
1757
+ this.dropIfStale(key);
1758
+ });
1759
+ this.emitEvent(key, { type: "meta" });
1760
+ const nextTurn = conv.agent === "codex" ? "下一轮起生效。" : "";
1761
+ return next
1762
+ ? `已打开计划模式:先只读、出方案,你批准了再按「${PERMISSION_LABEL[this.permissionOf(conv)]}」动手。${nextTurn}`
1763
+ : `已关闭计划模式。${nextTurn}`;
1764
+ }
1765
+
1766
+ setPlan(key: string, on?: boolean): Promise<string> {
1767
+ return this.serial(key, async () => this.setPlanNow(key, on));
1768
+ }
1769
+
1728
1770
  /** /autoedit:on 不给就是切换。「自动改文件」的旧叫法,关掉就是恢复默认 */
1729
1771
  private setAutoEditNow(key: string, on: boolean | undefined): string {
1730
1772
  const conv = getConversation(key)!;
@@ -2017,7 +2059,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
2017
2059
  `目录:${conv.cwd}`,
2018
2060
  `模型:${runtime.model ?? "默认"}`,
2019
2061
  ...(runtime.effort ? [`思考程度:${runtime.effort}`] : []),
2020
- `权限:${PERMISSION_LABEL[this.permissionOf(conv)]}(/permission 切换)`,
2062
+ `权限:${PERMISSION_LABEL[this.permissionOf(conv)]}${conv.plan ? ",计划模式" : ""}(/permission、/planmode 切换)`,
2021
2063
  ...(extra.length > 0 ? ["", ...extra] : []),
2022
2064
  ].join("\n");
2023
2065
  }
@@ -2081,7 +2123,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
2081
2123
  cwd: conv.cwd,
2082
2124
  ...(conv.cwdExplicit ? { cwdExplicit: true } : {}),
2083
2125
  // 「完全允许」不跟着分叉过去
2084
- ...(requestedPermission(conv) === "edit" ? { permission: "edit" as const } : {}),
2126
+ ...carriedPermission(conv),
2085
2127
  ...(conv.expert ? { expert: conv.expert } : {}),
2086
2128
  forkOf: key,
2087
2129
  perAgent: {
@@ -2161,7 +2203,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
2161
2203
  cwd: conv.cwd,
2162
2204
  ...(conv.cwdExplicit ? { cwdExplicit: true } : {}),
2163
2205
  // 和分叉一样,「完全允许」不跟过去
2164
- ...(requestedPermission(conv) === "edit" ? { permission: "edit" as const } : {}),
2206
+ ...carriedPermission(conv),
2165
2207
  forkOf: key,
2166
2208
  handoff: true,
2167
2209
  });
@@ -2250,6 +2292,8 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
2250
2292
  return text(getConversation(key)!.cwd);
2251
2293
  case "autoedit":
2252
2294
  return text(await this.setAutoEdit(key, cmd.on));
2295
+ case "plan":
2296
+ return text(await this.setPlan(key, cmd.on));
2253
2297
  case "permission":
2254
2298
  return text(cmd.level ? await this.setPermission(key, cmd.level === "default" ? undefined : cmd.level, ctx.allowFullAccess === true) : this.describePermission(key));
2255
2299
  case "status":
@@ -2337,3 +2381,9 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd]; "p
2337
2381
  }
2338
2382
 
2339
2383
  export const hub = new Hub();
2384
+
2385
+ /** 分叉、交接、微信开新对话时带过去的级别:「完全允许」不跟过去,放手只是对原来那件事说的 */
2386
+ function carriedPermission(conv: Conversation): { permission?: PermissionLevel } {
2387
+ const level = requestedPermission(conv);
2388
+ return level && level !== "full" ? { permission: level } : {};
2389
+ }
@@ -232,7 +232,7 @@ function publicView(entry: Entry | Interaction): Interaction {
232
232
  }
233
233
 
234
234
  export function isDetached(interaction: Interaction): boolean {
235
- return interaction.spec.kind === "question" && !!interaction.spec.detached;
235
+ return !!interaction.spec.detached;
236
236
  }
237
237
 
238
238
  export function unansweredCount(entry: Interaction): number {