agent-loft 0.2.47 → 0.2.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +27 -12
  2. package/package.json +1 -1
  3. package/src/agents/claude/driver.ts +11 -9
  4. package/src/agents/claude/session.ts +162 -46
  5. package/src/agents/claude/todos.ts +124 -0
  6. package/src/agents/codex/driver.ts +1 -1
  7. package/src/agents/codex/session.ts +104 -58
  8. package/src/channels/feishu/bot.ts +1 -3
  9. package/src/channels/feishu/cards.ts +2 -2
  10. package/src/channels/web/api.ts +24 -17
  11. package/src/channels/web/experts-api.ts +185 -0
  12. package/src/channels/web/skills-api.ts +1 -7
  13. package/src/channels/web/tasks-api.ts +9 -5
  14. package/src/core/command-catalog.ts +4 -6
  15. package/src/core/commands.ts +6 -11
  16. package/src/core/expert-prompt.ts +119 -0
  17. package/src/core/experts.ts +416 -0
  18. package/src/core/hub.ts +138 -102
  19. package/src/core/mcp.ts +253 -0
  20. package/src/core/memory-curator.ts +8 -9
  21. package/src/core/memory.ts +11 -4
  22. package/src/core/personal.ts +5 -1
  23. package/src/core/skill-runtime.ts +11 -114
  24. package/src/core/store.ts +30 -11
  25. package/src/core/task-prompt.ts +1 -1
  26. package/src/core/task-runner.ts +24 -11
  27. package/src/core/tasks-bridge.ts +7 -7
  28. package/src/core/tasks.ts +49 -14
  29. package/src/core/types.ts +11 -7
  30. package/src/core/uploads.ts +7 -7
  31. package/src/mcp/tasks-server.ts +1 -2
  32. package/web/css/experts.css +103 -0
  33. package/web/css/messages.css +193 -19
  34. package/web/css/overlay.css +12 -0
  35. package/web/css/sidebar.css +3 -2
  36. package/web/css/skills.css +0 -11
  37. package/web/css/todos.css +144 -0
  38. package/web/css/topbar.css +2 -2
  39. package/web/index.html +2 -0
  40. package/web/settings/experts.js +444 -0
  41. package/web/settings/index.js +3 -0
  42. package/web/settings/memory.js +21 -5
  43. package/web/settings/skills.js +3 -3
  44. package/web/state.js +5 -2
  45. package/web/views/composer.js +9 -17
  46. package/web/views/conv-actions.js +7 -9
  47. package/web/views/experts.js +73 -0
  48. package/web/views/interaction.js +65 -19
  49. package/web/views/layout.js +4 -3
  50. package/web/views/messages.js +52 -11
  51. package/web/views/sidebar.js +2 -2
  52. package/web/views/tasks.js +21 -36
  53. package/web/views/todos.js +71 -0
  54. package/web/views/topbar.js +43 -74
  55. package/src/core/chat-mode.ts +0 -62
  56. package/web/views/mention.js +0 -202
@@ -0,0 +1,416 @@
1
+ // 专家:一份配置 —— 用哪个引擎(Claude / Codex)、什么提示词、能做什么(联网 / 读文件 / 改文件 / 跑命令)、
2
+ // 挂哪些技能和 MCP、能把活派给哪些子智能体。新建对话、定时任务时选一个专家,对话从头到尾都是它,
3
+ // 中途不能换(飞书里换专家等于开新会话)。
4
+ //
5
+ // 两个内置专家 claude、codex 不存盘:就是 agent 原装的样子(原装提示词、机器上的技能和 MCP、所有工具)。
6
+ // 对话和任务里没写 expert 的,专家就是它的 agent —— 升级前的数据不用迁移。
7
+ //
8
+ // 自定义专家每人管自己的,不分享。存储:data/experts.json,只有主进程读写。
9
+ import crypto from "node:crypto";
10
+ import { EventEmitter } from "node:events";
11
+ import path from "node:path";
12
+ import { dataDir, readJson, writeJsonAtomic } from "../home.js";
13
+ import { resolveWorkspacePath } from "./config.js";
14
+ import { claudeMachineMcp, getMcp, isMachineId, machineName, specOf, type McpSpec } from "./mcp.js";
15
+ import { activeSkills, canSee, getSkill } from "./skills.js";
16
+ import { getUser } from "./users.js";
17
+
18
+ export type Engine = "claude" | "codex";
19
+ export const ENGINES: readonly Engine[] = ["claude", "codex"];
20
+
21
+ /** 一级包含一级:能跑命令就等于能改任何文件 */
22
+ export type ExpertAccess = "web" | "read" | "edit" | "exec";
23
+ export const ACCESS_LEVELS: readonly ExpertAccess[] = ["web", "read", "edit", "exec"];
24
+ export const ACCESS_LABEL: Record<ExpertAccess, string> = {
25
+ web: "只能联网",
26
+ read: "能读文件",
27
+ edit: "能改文件",
28
+ exec: "能跑命令",
29
+ };
30
+
31
+ export type QuickPrompt = { title: string; prompt: string };
32
+
33
+ export type Expert = {
34
+ id: string;
35
+ owner: string;
36
+ name: string;
37
+ description: string;
38
+ /** emoji */
39
+ icon: string;
40
+ color: string;
41
+ welcome: string;
42
+ quickPrompts: QuickPrompt[];
43
+ engine: Engine;
44
+ model?: string;
45
+ effort?: string;
46
+ prompt: string;
47
+ /** 只对 Claude:lean = 只用专家自己的提示词(省 token);claude_code = Claude Code 原装提示词后面追加 */
48
+ basePrompt: "lean" | "claude_code";
49
+ access: ExpertAccess;
50
+ /** 新建对话、任务时默认的工作目录(能读文件时才有意义)。空 = 工作区根目录 */
51
+ cwd?: string;
52
+ webSearch: boolean;
53
+ webFetch: boolean;
54
+ /** 技能 id(core/skills.ts) */
55
+ skills: string[];
56
+ /** MCP id(core/mcp.ts),机器上的写成 machine:<名字>(只有管理员能选) */
57
+ mcp: string[];
58
+ /** 子智能体:别的专家的 id。只有 Claude 支持 */
59
+ subagents: string[];
60
+ /** 带不带主人的个人记忆 */
61
+ memory: boolean;
62
+ /** 每存一次加一 */
63
+ rev: number;
64
+ createdAt: number;
65
+ updatedAt: number;
66
+ };
67
+
68
+ export const BUILTIN_IDS: readonly Engine[] = ENGINES;
69
+
70
+ export function isBuiltin(id: string): id is Engine {
71
+ return (BUILTIN_IDS as readonly string[]).includes(id);
72
+ }
73
+
74
+ export const EXPERT_LIMITS = {
75
+ perUser: 50,
76
+ name: 40,
77
+ description: 500,
78
+ welcome: 500,
79
+ prompt: 20_000,
80
+ quickPrompts: 8,
81
+ quickTitle: 40,
82
+ quickPrompt: 2000,
83
+ };
84
+
85
+ const storePath = path.join(dataDir, "experts.json");
86
+
87
+ /** 专家改了 / 删了。owner:谁的。用着它的会话空闲下来要换上新的 */
88
+ export const expertEvents = new EventEmitter<{ changed: [owner: string, id: string] }>();
89
+
90
+ let cache: Expert[] | null = null;
91
+
92
+ function load(): Expert[] {
93
+ cache ??= readJson<Expert[]>(storePath, []).filter((e) => e && typeof e.id === "string" && typeof e.owner === "string" && !isBuiltin(e.id));
94
+ return cache;
95
+ }
96
+
97
+ function save(): void {
98
+ writeJsonAtomic(storePath, load());
99
+ }
100
+
101
+ export function resetExpertCache(): void {
102
+ cache = null;
103
+ }
104
+
105
+ export function listExperts(owner: string): Expert[] {
106
+ return load()
107
+ .filter((e) => e.owner === owner)
108
+ .sort((a, b) => a.createdAt - b.createdAt);
109
+ }
110
+
111
+ export function getExpert(id: string): Expert | undefined {
112
+ return load().find((e) => e.id === id);
113
+ }
114
+
115
+ /** 谁都能用的(内置)或者是他自己的 */
116
+ export function canUseExpert(owner: string | undefined, id: string): boolean {
117
+ if (isBuiltin(id)) return true;
118
+ const e = getExpert(id);
119
+ return !!e && !!owner && e.owner === owner;
120
+ }
121
+
122
+ export const accessRank = (a: ExpertAccess) => ACCESS_LEVELS.indexOf(a);
123
+
124
+ // ---------- 校验 ----------
125
+
126
+ export type ExpertInput = Partial<Record<keyof Omit<Expert, "id" | "owner" | "rev" | "createdAt" | "updatedAt">, unknown>>;
127
+
128
+ const text = (v: unknown, max: number, what: string): string => {
129
+ const s = typeof v === "string" ? v.trim() : "";
130
+ if (s.length > max) throw new Error(`${what}太长(最多 ${max} 个字)`);
131
+ return s;
132
+ };
133
+ const ids = (v: unknown): string[] => (Array.isArray(v) ? [...new Set(v.filter((x): x is string => typeof x === "string"))] : []);
134
+
135
+ function validate(owner: string, input: ExpertInput, prev?: Expert, selfId?: string): Omit<Expert, "id" | "owner" | "rev" | "createdAt" | "updatedAt"> {
136
+ const pick = <K extends keyof ExpertInput>(k: K): unknown => (input[k] === undefined && prev ? prev[k as keyof Expert] : input[k]);
137
+ const user = getUser(owner);
138
+ if (!user) throw new Error("用户不存在");
139
+ const admin = user.role === "admin";
140
+
141
+ const name = text(pick("name"), EXPERT_LIMITS.name, "名字");
142
+ if (!name) throw new Error("给专家起个名字");
143
+ const engine = pick("engine");
144
+ if (engine !== "claude" && engine !== "codex") throw new Error("引擎只能是 Claude 或 Codex");
145
+ if (prev && prev.engine !== engine) throw new Error("建好之后不能换引擎(用这个专家的对话都是这个引擎的会话)");
146
+ const access = pick("access");
147
+ if (!ACCESS_LEVELS.includes(access as ExpertAccess)) throw new Error("权限不对");
148
+
149
+ const quickRaw = pick("quickPrompts");
150
+ const quickPrompts: QuickPrompt[] = [];
151
+ if (Array.isArray(quickRaw)) {
152
+ if (quickRaw.length > EXPERT_LIMITS.quickPrompts) throw new Error(`快捷提问最多 ${EXPERT_LIMITS.quickPrompts} 个`);
153
+ for (const q of quickRaw as Record<string, unknown>[]) {
154
+ const prompt = text(q?.prompt, EXPERT_LIMITS.quickPrompt, "快捷提问");
155
+ if (!prompt) continue;
156
+ quickPrompts.push({ title: text(q?.title, EXPERT_LIMITS.quickTitle, "快捷提问的标题") || prompt.slice(0, 20), prompt });
157
+ }
158
+ }
159
+
160
+ const color = text(pick("color"), 20, "颜色");
161
+ if (color && !/^#[0-9a-fA-F]{6}$/.test(color)) throw new Error("颜色要写成 #rrggbb");
162
+
163
+ let cwd: string | undefined;
164
+ const cwdRaw = text(pick("cwd"), 4096, "工作目录");
165
+ if (cwdRaw && access !== "web") {
166
+ const resolved = resolveWorkspacePath(cwdRaw);
167
+ if (!resolved) throw new Error("工作目录必须存在,且在工作区之内");
168
+ cwd = resolved;
169
+ }
170
+
171
+ // 技能:自己看得到的
172
+ const skills = ids(pick("skills")).filter((id) => {
173
+ const s = getSkill(id);
174
+ return !!s && canSee({ id: owner }, s);
175
+ });
176
+
177
+ // MCP:自己的;机器上的只有管理员能选
178
+ const mcp = ids(pick("mcp")).filter((id) => (isMachineId(id) ? admin && machineName(id).length > 0 : getMcp(id)?.owner === owner));
179
+
180
+ // 子智能体:自己的 Claude 专家,权限不能比自己高,不能是自己
181
+ const subRaw = engine === "claude" ? ids(pick("subagents")) : [];
182
+ const subagents: string[] = [];
183
+ for (const id of subRaw) {
184
+ if (id === selfId) throw new Error("子智能体不能是它自己");
185
+ const sub = getExpert(id);
186
+ if (!sub || sub.owner !== owner) continue;
187
+ if (sub.engine !== "claude") throw new Error(`「${sub.name}」是 Codex 专家,子智能体只能用 Claude 专家`);
188
+ if (accessRank(sub.access) > accessRank(access as ExpertAccess)) {
189
+ throw new Error(`「${sub.name}」的权限(${ACCESS_LABEL[sub.access]})比这个专家高,子智能体的权限不能超过主专家`);
190
+ }
191
+ subagents.push(id);
192
+ }
193
+
194
+ const model = text(pick("model"), 100, "模型");
195
+ const effort = text(pick("effort"), 20, "思考程度");
196
+ return {
197
+ name,
198
+ description: text(pick("description"), EXPERT_LIMITS.description, "说明"),
199
+ icon: text(pick("icon"), 16, "图标"),
200
+ color,
201
+ welcome: text(pick("welcome"), EXPERT_LIMITS.welcome, "欢迎语"),
202
+ quickPrompts,
203
+ engine,
204
+ ...(model ? { model } : {}),
205
+ ...(effort ? { effort } : {}),
206
+ prompt: text(pick("prompt"), EXPERT_LIMITS.prompt, "提示词"),
207
+ basePrompt: pick("basePrompt") === "claude_code" && engine === "claude" ? "claude_code" : "lean",
208
+ access: access as ExpertAccess,
209
+ ...(cwd ? { cwd } : {}),
210
+ webSearch: pick("webSearch") !== false,
211
+ webFetch: pick("webFetch") !== false,
212
+ skills,
213
+ mcp,
214
+ subagents,
215
+ memory: pick("memory") !== false,
216
+ };
217
+ }
218
+
219
+ export function createExpert(owner: string, input: ExpertInput): Expert {
220
+ if (listExperts(owner).length >= EXPERT_LIMITS.perUser) throw new Error(`每人最多 ${EXPERT_LIMITS.perUser} 个专家`);
221
+ const id = `e_${crypto.randomBytes(6).toString("hex")}`;
222
+ const now = Date.now();
223
+ const expert: Expert = { id, owner, ...validate(owner, input, undefined, id), rev: 1, createdAt: now, updatedAt: now };
224
+ load().push(expert);
225
+ save();
226
+ expertEvents.emit("changed", owner, id);
227
+ return expert;
228
+ }
229
+
230
+ export function updateExpert(owner: string, id: string, input: ExpertInput): Expert {
231
+ const list = load();
232
+ const idx = list.findIndex((e) => e.id === id && e.owner === owner);
233
+ if (idx < 0) throw new Error("这个专家不存在");
234
+ const prev = list[idx]!;
235
+ // 不展开 prev:清空了的可选项(目录、模型)不能被旧值补回来。没传的字段 validate 已经按 prev 取了
236
+ const next: Expert = { id, owner, ...validate(owner, input, prev, id), rev: prev.rev + 1, createdAt: prev.createdAt, updatedAt: Date.now() };
237
+ list[idx] = next;
238
+ save();
239
+ expertEvents.emit("changed", owner, id);
240
+ return next;
241
+ }
242
+
243
+ export function deleteExpert(owner: string, id: string): void {
244
+ const list = load();
245
+ const idx = list.findIndex((e) => e.id === id && e.owner === owner);
246
+ if (idx < 0) throw new Error("这个专家不存在");
247
+ list.splice(idx, 1);
248
+ // 别的专家把它当子智能体的,一并去掉
249
+ for (const e of list) {
250
+ if (e.subagents.includes(id)) {
251
+ e.subagents = e.subagents.filter((s) => s !== id);
252
+ e.rev += 1;
253
+ expertEvents.emit("changed", e.owner, e.id);
254
+ }
255
+ }
256
+ save();
257
+ expertEvents.emit("changed", owner, id);
258
+ }
259
+
260
+ export function purgeUserExperts(owner: string): void {
261
+ const list = load();
262
+ const kept = list.filter((e) => e.owner !== owner);
263
+ if (kept.length === list.length) return;
264
+ cache = kept;
265
+ save();
266
+ }
267
+
268
+ // ---------- 开会话时 ----------
269
+
270
+ /** sse 只有 Claude 机器上的配置里会出现 */
271
+ export type ResolvedMcp = McpSpec | { type: "sse"; url: string; headers: Record<string, string> };
272
+
273
+ /** 一个子智能体(只有 Claude) */
274
+ export type SubagentRuntime = {
275
+ /** 子智能体的名字(Agent 工具里的 subagent_type):专家名转成的短名,同一个专家里不重复 */
276
+ key: string;
277
+ name: string;
278
+ description: string;
279
+ prompt: string;
280
+ access: ExpertAccess;
281
+ webSearch: boolean;
282
+ webFetch: boolean;
283
+ model?: string;
284
+ /** 技能名(loft:<name>) */
285
+ skills: string[];
286
+ mcp: Record<string, ResolvedMcp>;
287
+ };
288
+
289
+ /** 交给 driver 的专家(SessionOptions.expert)。内置专家不给 */
290
+ export type ExpertRuntime = {
291
+ id: string;
292
+ rev: number;
293
+ name: string;
294
+ prompt: string;
295
+ basePrompt: "lean" | "claude_code";
296
+ access: ExpertAccess;
297
+ webSearch: boolean;
298
+ webFetch: boolean;
299
+ /** 选中的技能 id;SessionOptions.skills 已经按它筛过 */
300
+ skills: string[];
301
+ /** 选中的 MCP:服务名 → 启动参数 */
302
+ mcp: Record<string, ResolvedMcp>;
303
+ /** 调用前要询问的 MCP 服务名 */
304
+ askMcp: string[];
305
+ /** 选中的机器上的 MCP 名字(Codex:除了这些,机器上的都关掉) */
306
+ machineMcp: string[];
307
+ subagents: SubagentRuntime[];
308
+ memory: boolean;
309
+ };
310
+
311
+ /** 专家选中的 MCP 解析成启动参数。机器上的:Claude 读 ~/.claude.json,Codex 只要名字(由它自己按 config.toml 起) */
312
+ function resolveMcp(expert: Expert, admin: boolean): { mcp: Record<string, ResolvedMcp>; ask: string[]; machine: string[] } {
313
+ const mcp: Record<string, ResolvedMcp> = {};
314
+ const ask: string[] = [];
315
+ const machine: string[] = [];
316
+ const claudeMachine = admin && expert.engine === "claude" && expert.mcp.some(isMachineId) ? claudeMachineMcp() : {};
317
+ for (const id of expert.mcp) {
318
+ if (isMachineId(id)) {
319
+ if (!admin) continue;
320
+ const name = machineName(id);
321
+ if (expert.engine === "codex") machine.push(name);
322
+ else if (claudeMachine[name]) mcp[name] = claudeMachine[name]!;
323
+ continue;
324
+ }
325
+ const s = getMcp(id);
326
+ if (!s || s.owner !== expert.owner) continue;
327
+ mcp[s.name] = specOf(s);
328
+ if (s.ask) ask.push(s.name);
329
+ }
330
+ return { mcp, ask, machine };
331
+ }
332
+
333
+ /** 专家名转成子智能体的短名:Agent 工具里模型用它来点名 */
334
+ function subagentKey(name: string, taken: Set<string>): string {
335
+ const base =
336
+ name
337
+ .toLowerCase()
338
+ .replace(/[^a-z0-9]+/g, "-")
339
+ .replace(/^-+|-+$/g, "")
340
+ .slice(0, 30) || "expert";
341
+ let key = base;
342
+ for (let i = 2; taken.has(key); i++) key = `${base}-${i}`;
343
+ taken.add(key);
344
+ return key;
345
+ }
346
+
347
+ /**
348
+ * 按专家配置拼出交给 driver 的样子。prompt:子智能体的完整提示词怎么拼(core/expert-prompt.ts 给)。
349
+ * 子智能体的权限封顶在主专家的权限:主专家后来降了权限也不会被子智能体绕过去。
350
+ */
351
+ export function expertRuntime(expert: Expert, subPrompt: (sub: Expert, access: ExpertAccess) => string): ExpertRuntime {
352
+ const admin = getUser(expert.owner)?.role === "admin";
353
+ const active = new Map(activeSkills(expert.owner).map((s) => [s.id, s]));
354
+ const { mcp, ask, machine } = resolveMcp(expert, admin);
355
+ const taken = new Set<string>();
356
+ const subagents: SubagentRuntime[] = [];
357
+ if (expert.engine === "claude") {
358
+ for (const id of expert.subagents) {
359
+ const sub = getExpert(id);
360
+ if (!sub || sub.owner !== expert.owner || sub.engine !== "claude" || sub.id === expert.id) continue;
361
+ const access = accessRank(sub.access) > accessRank(expert.access) ? expert.access : sub.access;
362
+ const subMcp = resolveMcp(sub, admin).mcp;
363
+ subagents.push({
364
+ key: subagentKey(sub.name, taken),
365
+ name: sub.name,
366
+ description: sub.description || sub.name,
367
+ prompt: subPrompt(sub, access),
368
+ access,
369
+ webSearch: sub.webSearch,
370
+ webFetch: sub.webFetch,
371
+ ...(sub.model ? { model: sub.model } : {}),
372
+ skills: sub.skills.map((s) => active.get(s)?.name).filter((n): n is string => !!n),
373
+ mcp: subMcp,
374
+ });
375
+ }
376
+ }
377
+ return {
378
+ id: expert.id,
379
+ rev: expert.rev,
380
+ name: expert.name,
381
+ prompt: expert.prompt,
382
+ basePrompt: expert.engine === "claude" ? expert.basePrompt : "lean",
383
+ access: expert.access,
384
+ webSearch: expert.webSearch,
385
+ webFetch: expert.webFetch,
386
+ skills: expert.skills.filter((id) => active.has(id)),
387
+ mcp,
388
+ askMcp: ask,
389
+ machineMcp: machine,
390
+ subagents,
391
+ memory: expert.memory,
392
+ };
393
+ }
394
+
395
+ // ---------- 模板 ----------
396
+
397
+ /** 「从模板新建」:和以前的聊天模式一样的效果 */
398
+ export const EXPERT_TEMPLATES: { id: string; label: string; expert: ExpertInput }[] = [
399
+ {
400
+ id: "chat",
401
+ label: "聊天助手(以前的聊天模式)",
402
+ expert: {
403
+ name: "聊天助手",
404
+ description: "日常聊天、查资料。只能联网搜索,不碰本机文件,每轮开销小",
405
+ icon: "💬",
406
+ engine: "claude",
407
+ basePrompt: "lean",
408
+ access: "web",
409
+ webSearch: true,
410
+ webFetch: true,
411
+ memory: true,
412
+ prompt: "你是用户的私人 AI 助手。用用户使用的语言回答,自然、直接、简洁;需要时用 Markdown 排版(列表、表格、代码块)。",
413
+ welcome: "想聊点什么?",
414
+ },
415
+ },
416
+ ];