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,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 },
@@ -18,9 +18,7 @@ export type ParsedCommand =
18
18
  | { kind: "status" }
19
19
  | { kind: "pwd" }
20
20
  | { kind: "autoedit"; on?: boolean }
21
- | { kind: "mode"; mode: "chat" | "work" }
22
21
  | { kind: "help" }
23
- | { kind: "skills" }
24
22
  /** 只发了一个「/」:列出可用命令 */
25
23
  | { kind: "commands" }
26
24
  | { kind: "approve"; requestId: string; decision: ApprovalDecision }
@@ -50,9 +48,11 @@ export function parseCommand(raw: string): ParsedCommand {
50
48
  return { kind: "model", ...(arg ? { model: arg } : {}) };
51
49
  case "effort":
52
50
  return { kind: "effort", ...(arg ? { effort: arg } : {}) };
51
+ // 换专家(会开新会话)。/agent 是以前的叫法,照样认
52
+ case "expert":
53
53
  case "agent":
54
- return { kind: "agent", ...(arg ? { agent: arg.toLowerCase() } : {}) };
55
- // 快捷切换
54
+ return { kind: "agent", ...(arg ? { agent: arg } : {}) };
55
+ // 快捷切换到内置专家
56
56
  case "claude":
57
57
  case "codex":
58
58
  return arg ? { kind: "chat", text } : { kind: "agent", agent: head.toLowerCase() };
@@ -71,13 +71,8 @@ export function parseCommand(raw: string): ParsedCommand {
71
71
  if (["off", "关", "0", "false"].includes(v)) return { kind: "autoedit", on: false };
72
72
  return { kind: "chat", text };
73
73
  }
74
- case "chat":
75
- case "work":
76
- return arg ? { kind: "chat", text } : { kind: "mode", mode: head.toLowerCase() as "chat" | "work" };
77
74
  case "help":
78
75
  return { kind: "help" };
79
- case "skills":
80
- return arg ? { kind: "chat", text } : { kind: "skills" };
81
76
  case "approve": {
82
77
  const [requestId, decision] = rest;
83
78
  if (!requestId || !decision) return { kind: "chat", text };
@@ -104,8 +99,8 @@ export function helpText(agents: string[], channel?: string): string {
104
99
  .filter((c) => !c.feishuOnly || channel === "feishu")
105
100
  .filter((c) => !["claude", "codex"].includes(c.name))
106
101
  .map((c) =>
107
- c.name === "agent"
108
- ? `\`${usageOf(c)}\` ${c.description}(可选:${agents.join("、")}),也可以直接发 ${agents.map((a) => `\`/${a}\``).join(" ")}`
102
+ c.name === "expert"
103
+ ? `\`${usageOf(c)}\` ${c.description}${multi ? `,也可以直接发 ${agents.map((a) => `\`/${a}\``).join(" ")}` : ""}`
109
104
  : `\`${usageOf(c)}\` ${c.description}`,
110
105
  ),
111
106
  ].join("\n");
@@ -0,0 +1,119 @@
1
+ // 专家要告诉 agent 的话(人设、能做什么、记忆),以及怎么告诉。
2
+ //
3
+ // 两个 agent 的「换系统提示」能力不一样(都实测过):
4
+ // - Claude:系统提示每次拉起进程时整个给。自定义专家默认用 expertSystemPrompt 换掉 Claude Code 原装的
5
+ // 那一大段(约 1.6 万 token);专家选了「Claude Code 原装」就用 expertAppend 追加在原装提示后面。
6
+ // - Codex:thread 的基础指令一旦设了就钉在 thread 上(resume 时不传就沿用,传 null 也一样),
7
+ // 开发者指令只在 thread 开头写一次、resume 时给新的会被忽略。所以 Codex 不动它的指令,
8
+ // 专家和记忆用 contextBlock 附在「这个会话进程的第一条消息」后面 —— 它按时间顺序进历史,
9
+ // 模型以最新的为准。读历史、列会话时用 stripContext 把它剥掉。
10
+ //
11
+ // 日期写进去是因为模型不知道今天几号;它在一条会话里不变,不影响提示缓存。
12
+ import type { ExpertAccess, ExpertRuntime } from "./experts.js";
13
+
14
+ function today(): string {
15
+ const d = new Date();
16
+ const pad = (n: number) => String(n).padStart(2, "0");
17
+ const tz = Intl.DateTimeFormat().resolvedOptions().timeZone;
18
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}(${tz})`;
19
+ }
20
+
21
+ /** 拼提示词要知道的专家配置(主专家用 ExpertRuntime,子智能体只给一部分) */
22
+ export type PromptExpert = Pick<ExpertRuntime, "name" | "prompt" | "access" | "webSearch" | "webFetch"> & {
23
+ subagents?: { key: string; name: string; description: string }[];
24
+ };
25
+
26
+ /**
27
+ * 这个专家能做什么、不能做什么,由 agent-loft 按配置生成。
28
+ * search:联网搜索 / 读网页的工具在这个 agent 里怎么称呼;不能联网就是 undefined。
29
+ */
30
+ export function capabilityLines(expert: PromptExpert, search: string | undefined, cwd: string): string[] {
31
+ const lines: string[] = [];
32
+ lines.push(
33
+ search
34
+ ? `- 涉及最新信息、新闻、价格、版本、事实核查时,先用${search}查,回答里附上来源链接;不要凭记忆编造。`
35
+ : "- 你不能联网。涉及最新信息时说明你知道的可能已经过时,不要编造。",
36
+ );
37
+ const access: Record<ExpertAccess, string> = {
38
+ web: "- 你不能读写这台机器上的文件,也不能执行命令。用户发来的图片、PDF 和文本文件内容会直接附在消息里。",
39
+ read: `- 你可以读这台机器上的文件(工作目录 ${cwd}),但不能修改文件,也不能执行命令。`,
40
+ edit: `- 你可以读写工作目录 ${cwd} 里的文件,但不能执行命令。`,
41
+ exec: `- 你可以在工作目录 ${cwd} 里读写文件、执行命令。`,
42
+ };
43
+ lines.push(access[expert.access]);
44
+ if (expert.access !== "exec") {
45
+ lines.push("- 用户要你做超出这些能力的事时,直接说明做不到;需要的话建议他新开一个对话,换一个有这项能力的专家。");
46
+ }
47
+ if (expert.subagents?.length) {
48
+ lines.push(
49
+ "- 遇到合适的子任务,可以用 Agent 工具交给下面的子智能体(subagent_type 写括号里的名字)。它们看不到这段对话,交代任务时把目标、约束和需要的背景写清楚:",
50
+ ...expert.subagents.map((s) => ` - ${s.name}(${s.key}):${s.description}`),
51
+ );
52
+ }
53
+ return lines;
54
+ }
55
+
56
+ /** 这个专家能用的联网工具在提示词里怎么称呼;一个都没开就是 undefined(Codex 只有搜索) */
57
+ export function searchLabel(engine: "claude" | "codex", expert: Pick<PromptExpert, "webSearch" | "webFetch">): string | undefined {
58
+ if (engine === "codex") return expert.webSearch ? "联网搜索" : undefined;
59
+ const parts = [expert.webSearch ? "WebSearch(搜索)" : "", expert.webFetch ? "WebFetch(读网页)" : ""].filter(Boolean);
60
+ return parts.length ? parts.join("和") : undefined;
61
+ }
62
+
63
+ function persona(expert: PromptExpert): string[] {
64
+ return [`你是「${expert.name}」,用户通过 agent-loft 的网页或飞书和你对话。`, ...(expert.prompt ? ["", expert.prompt] : [])];
65
+ }
66
+
67
+ /** Claude 自定义专家的整段系统提示(lean:换掉 Claude Code 原装的) */
68
+ export function expertSystemPrompt(expert: PromptExpert, search: string | undefined, cwd: string, memory?: string): string {
69
+ const base = [
70
+ ...persona(expert),
71
+ "",
72
+ "## 你能做什么(agent-loft 按这个专家的配置生成)",
73
+ "",
74
+ ...capabilityLines(expert, search, cwd),
75
+ "",
76
+ `今天是 ${today()}。`,
77
+ ].join("\n");
78
+ return memory ? `${base}\n\n${memory}` : base;
79
+ }
80
+
81
+ /** Claude 自定义专家选了「Claude Code 原装」:追加在原装提示后面的部分 */
82
+ export function expertAppend(expert: PromptExpert, search: string | undefined, cwd: string): string {
83
+ return [...persona(expert), "", "## 这个专家能做什么(agent-loft 按配置生成)", "", ...capabilityLines(expert, search, cwd)].join("\n");
84
+ }
85
+
86
+ const OPEN = "<agent-loft-context>";
87
+ const CLOSE = "</agent-loft-context>";
88
+
89
+ /**
90
+ * Codex:附在会话进程第一条消息后面的背景。
91
+ * expert 不给就是内置的 Codex 专家:只有记忆和技能清单,都没有就不附(返回空串)。
92
+ */
93
+ export function contextBlock(
94
+ expert: { prompt: PromptExpert; cwd: string } | undefined,
95
+ memory: string | undefined,
96
+ skills: string[] = [],
97
+ ): string {
98
+ const head = expert
99
+ ? [...persona(expert.prompt), "", "## 你能做什么(agent-loft 按这个专家的配置生成)", "", ...capabilityLines(expert.prompt, searchLabel("codex", expert.prompt), expert.cwd)]
100
+ : [];
101
+ const sections = [head, memory ? [memory] : [], skills].filter((s) => s.length > 0);
102
+ return sections.length ? wrapContext(sections.flatMap((s, i) => (i ? ["", ...s] : s))) : "";
103
+ }
104
+
105
+ /** 包成 agent-loft 附上的背景:用户看不到(读历史、实时显示时都剥掉),agent 照着做 */
106
+ export function wrapContext(lines: string[]): string {
107
+ return [OPEN, "(这段是 agent-loft 自动附上的背景,不是用户写的。照着做,但不要在回复里提到它。)", "", ...lines, CLOSE].join("\n");
108
+ }
109
+
110
+ /** 剥掉 contextBlock(读历史、列会话标题时用)。一条消息里可能有好几段(定时任务的说明 + Codex 的专家说明) */
111
+ export function stripContext(text: string): string {
112
+ let out = text;
113
+ for (let start = out.indexOf(OPEN); start >= 0; start = out.indexOf(OPEN)) {
114
+ const end = out.indexOf(CLOSE, start);
115
+ const rest = end < 0 ? "" : out.slice(end + CLOSE.length);
116
+ out = `${out.slice(0, start)}${rest}`;
117
+ }
118
+ return out === text ? text : out.trim();
119
+ }