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.
- package/README.md +27 -12
- package/package.json +1 -1
- package/src/agents/claude/driver.ts +11 -9
- package/src/agents/claude/session.ts +162 -46
- package/src/agents/claude/todos.ts +124 -0
- package/src/agents/codex/driver.ts +1 -1
- package/src/agents/codex/session.ts +104 -58
- package/src/channels/feishu/bot.ts +1 -3
- package/src/channels/feishu/cards.ts +2 -2
- package/src/channels/web/api.ts +24 -17
- package/src/channels/web/experts-api.ts +185 -0
- package/src/channels/web/skills-api.ts +1 -7
- package/src/channels/web/tasks-api.ts +9 -5
- package/src/core/command-catalog.ts +4 -6
- package/src/core/commands.ts +6 -11
- package/src/core/expert-prompt.ts +119 -0
- package/src/core/experts.ts +416 -0
- package/src/core/hub.ts +138 -102
- package/src/core/mcp.ts +253 -0
- package/src/core/memory-curator.ts +8 -9
- package/src/core/memory.ts +11 -4
- package/src/core/personal.ts +5 -1
- package/src/core/skill-runtime.ts +11 -114
- package/src/core/store.ts +30 -11
- package/src/core/task-prompt.ts +1 -1
- package/src/core/task-runner.ts +24 -11
- package/src/core/tasks-bridge.ts +7 -7
- package/src/core/tasks.ts +49 -14
- package/src/core/types.ts +11 -7
- package/src/core/uploads.ts +7 -7
- package/src/mcp/tasks-server.ts +1 -2
- package/web/css/experts.css +103 -0
- package/web/css/messages.css +193 -19
- package/web/css/overlay.css +12 -0
- package/web/css/sidebar.css +3 -2
- package/web/css/skills.css +0 -11
- package/web/css/todos.css +144 -0
- package/web/css/topbar.css +2 -2
- package/web/index.html +2 -0
- package/web/settings/experts.js +444 -0
- package/web/settings/index.js +3 -0
- package/web/settings/memory.js +21 -5
- package/web/settings/skills.js +3 -3
- package/web/state.js +5 -2
- package/web/views/composer.js +9 -17
- package/web/views/conv-actions.js +7 -9
- package/web/views/experts.js +73 -0
- package/web/views/interaction.js +65 -19
- package/web/views/layout.js +4 -3
- package/web/views/messages.js +52 -11
- package/web/views/sidebar.js +2 -2
- package/web/views/tasks.js +21 -36
- package/web/views/todos.js +71 -0
- package/web/views/topbar.js +43 -74
- package/src/core/chat-mode.ts +0 -62
- package/web/views/mention.js +0 -202
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Claude 的任务清单:从工具调用里还原出「列了哪些事、做到哪一步」。
|
|
2
|
+
//
|
|
3
|
+
// 两套工具都认:TodoWrite 每次给整份清单;TaskCreate / TaskUpdate 一条条加、一条条改,
|
|
4
|
+
// 新建的那条编号多少要等工具结果("Task #3 created successfully: …")才知道。
|
|
5
|
+
// 实时(session.ts)和翻历史(driver.ts)用的是同一套规则,两边看到的才一样。
|
|
6
|
+
import { getSessionMessages } from "@anthropic-ai/claude-agent-sdk";
|
|
7
|
+
import type { TodoItem } from "../../core/types.js";
|
|
8
|
+
import { summarize } from "./session.js";
|
|
9
|
+
|
|
10
|
+
type Tracked = TodoItem & { id?: string };
|
|
11
|
+
|
|
12
|
+
const STATUSES = new Set(["pending", "in_progress", "completed"]);
|
|
13
|
+
|
|
14
|
+
export class TodoTracker {
|
|
15
|
+
private items: Tracked[] = [];
|
|
16
|
+
/** 新建了、还没拿到编号的:tool_use id → 那一条 */
|
|
17
|
+
private creating = new Map<string, Tracked>();
|
|
18
|
+
|
|
19
|
+
get list(): TodoItem[] {
|
|
20
|
+
return this.items.map(({ content, status, activeForm }) => ({ content, status, ...(activeForm ? { activeForm } : {}) }));
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 一次工具调用。不是任务工具返回 null;是的话返回过程里显示的那一行,changed = 清单变了。
|
|
25
|
+
*/
|
|
26
|
+
use(name: string, input: unknown, toolUseId?: string): { step: string; changed: boolean } | null {
|
|
27
|
+
const r = (input ?? {}) as Record<string, unknown>;
|
|
28
|
+
if (name === "TodoWrite") {
|
|
29
|
+
if (!Array.isArray(r.todos)) return { step: "📋 更新任务清单", changed: false };
|
|
30
|
+
this.items = r.todos.flatMap((t) => {
|
|
31
|
+
const item = t as Record<string, unknown>;
|
|
32
|
+
if (typeof item.content !== "string" || !STATUSES.has(item.status as string)) return [];
|
|
33
|
+
return [{ content: item.content, status: item.status as TodoItem["status"], ...(typeof item.activeForm === "string" ? { activeForm: item.activeForm } : {}) }];
|
|
34
|
+
});
|
|
35
|
+
const done = this.items.filter((t) => t.status === "completed").length;
|
|
36
|
+
return { step: `📋 更新任务清单(${done}/${this.items.length})`, changed: true };
|
|
37
|
+
}
|
|
38
|
+
if (name === "TaskCreate") {
|
|
39
|
+
if (typeof r.subject !== "string") return { step: "📋 新增任务", changed: false };
|
|
40
|
+
// 上一批全做完了又开始列新的:当成新的一批,旧的不再挂着
|
|
41
|
+
if (this.items.length && this.items.every((t) => t.status === "completed")) this.items = [];
|
|
42
|
+
const item: Tracked = { content: r.subject, status: "pending", ...(typeof r.activeForm === "string" ? { activeForm: r.activeForm } : {}) };
|
|
43
|
+
this.items.push(item);
|
|
44
|
+
if (toolUseId) this.creating.set(toolUseId, item);
|
|
45
|
+
return { step: `📋 新增任务:${summarize(r.subject, 50)}`, changed: true };
|
|
46
|
+
}
|
|
47
|
+
if (name === "TaskUpdate") {
|
|
48
|
+
const id = r.taskId === undefined ? "" : String(r.taskId);
|
|
49
|
+
const item = this.items.find((t) => t.id === id);
|
|
50
|
+
if (!item) return { step: `📋 更新任务 #${id}`, changed: false };
|
|
51
|
+
if (r.status === "deleted") {
|
|
52
|
+
this.items = this.items.filter((t) => t !== item);
|
|
53
|
+
return { step: `📋 删除任务:${summarize(item.content, 50)}`, changed: true };
|
|
54
|
+
}
|
|
55
|
+
if (typeof r.subject === "string") item.content = r.subject;
|
|
56
|
+
if (typeof r.activeForm === "string") item.activeForm = r.activeForm;
|
|
57
|
+
if (STATUSES.has(r.status as string)) item.status = r.status as TodoItem["status"];
|
|
58
|
+
const verb = r.status === "completed" ? "完成" : r.status === "in_progress" ? "开始" : "更新任务";
|
|
59
|
+
return { step: `📋 ${verb}:${summarize(item.content, 50)}`, changed: true };
|
|
60
|
+
}
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 工具结果:补上新建任务的编号。建失败了就拿掉,返回 true 表示清单变了 */
|
|
65
|
+
result(toolUseId: string, text: string, structured: unknown, isError: boolean): boolean {
|
|
66
|
+
const item = this.creating.get(toolUseId);
|
|
67
|
+
if (!item) return false;
|
|
68
|
+
this.creating.delete(toolUseId);
|
|
69
|
+
if (isError) {
|
|
70
|
+
this.items = this.items.filter((t) => t !== item);
|
|
71
|
+
return true;
|
|
72
|
+
}
|
|
73
|
+
const id = (structured as { task?: { id?: unknown } } | null)?.task?.id ?? /Task #(\S+) created/.exec(text)?.[1];
|
|
74
|
+
if (id !== undefined) item.id = String(id);
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 接着老会话说:之前列过的先放进来(已经有同编号的不重复放) */
|
|
79
|
+
seed(items: Tracked[]): void {
|
|
80
|
+
const known = new Set(this.items.map((t) => t.id).filter(Boolean));
|
|
81
|
+
this.items = [...items.filter((t) => !t.id || !known.has(t.id)), ...this.items];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
snapshot(): Tracked[] {
|
|
85
|
+
return this.items.map((t) => ({ ...t }));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
type Block = { type?: string; name?: string; input?: unknown; id?: string; tool_use_id?: string; content?: unknown; is_error?: boolean };
|
|
90
|
+
|
|
91
|
+
/** tool_result 的内容:字符串,或者一组 text 块 */
|
|
92
|
+
export function resultText(content: unknown): string {
|
|
93
|
+
if (typeof content === "string") return content;
|
|
94
|
+
if (!Array.isArray(content)) return "";
|
|
95
|
+
return content.map((b) => (typeof b?.text === "string" ? b.text : "")).join("");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 把一条记录里的工具调用 / 工具结果喂给 tracker。返回这条里有没有改过清单 */
|
|
99
|
+
export function feedTodos(tracker: TodoTracker, msg: { type: string; message?: unknown; tool_use_result?: unknown }): boolean {
|
|
100
|
+
const content = (msg.message as { content?: unknown } | null)?.content;
|
|
101
|
+
if (!Array.isArray(content)) return false;
|
|
102
|
+
let changed = false;
|
|
103
|
+
for (const b of content as Block[]) {
|
|
104
|
+
if (msg.type === "assistant" && b.type === "tool_use" && b.name) {
|
|
105
|
+
changed = !!tracker.use(b.name, b.input, b.id)?.changed || changed;
|
|
106
|
+
} else if (msg.type === "user" && b.type === "tool_result" && b.tool_use_id) {
|
|
107
|
+
changed = tracker.result(b.tool_use_id, resultText(b.content), msg.tool_use_result, !!b.is_error) || changed;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return changed;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 老会话最后的任务清单(恢复会话时接着用)。读不到就当没有 */
|
|
114
|
+
export async function readTodos(sessionId: string, cwd: string): Promise<Tracked[]> {
|
|
115
|
+
try {
|
|
116
|
+
const tracker = new TodoTracker();
|
|
117
|
+
for (const msg of await getSessionMessages(sessionId, { dir: cwd })) {
|
|
118
|
+
if (!msg.parent_tool_use_id) feedTodos(tracker, msg as never);
|
|
119
|
+
}
|
|
120
|
+
return tracker.snapshot();
|
|
121
|
+
} catch {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
}
|
|
@@ -8,7 +8,7 @@ import { CHAT_CONFIG, CodexSession, summarize, userMcpServers } from "./session.
|
|
|
8
8
|
import os from "node:os";
|
|
9
9
|
import { config, onConfigChange } from "../../core/config.js";
|
|
10
10
|
import { splitAttachmentNote } from "../../core/uploads.js";
|
|
11
|
-
import { stripContext } from "../../core/
|
|
11
|
+
import { stripContext } from "../../core/expert-prompt.js";
|
|
12
12
|
import type {
|
|
13
13
|
AgentDriver,
|
|
14
14
|
AgentEvents,
|
|
@@ -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/
|
|
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
|
-
*
|
|
92
|
-
* 降到约 1.1 万,大头是技能清单(约 2.5 万字符)和权限说明(约 1.1
|
|
93
|
-
*
|
|
94
|
-
* 不认识的 feature 名 Codex
|
|
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
|
-
|
|
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
|
-
|
|
365
|
-
|
|
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
|
-
|
|
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
|
-
*
|
|
375
|
-
*
|
|
402
|
+
* 按专家给 thread 的配置覆盖。thread/start、resume、fork 三条路都带上:配置是每次 resume 现给的,
|
|
403
|
+
* 专家改了以后旧会话先退订(dispose),再 resume 回来就换上了(实测)。
|
|
376
404
|
*
|
|
377
|
-
* 不动 baseInstructions / developerInstructions:Codex 把它们钉在 thread
|
|
378
|
-
* (见 core/
|
|
379
|
-
*
|
|
405
|
+
* 不动 baseInstructions / developerInstructions:Codex 把它们钉在 thread 上,改了专家也还原不了
|
|
406
|
+
* (见 core/expert-prompt.ts)。专家和记忆走 contextBlock,附在第一条消息后面。
|
|
407
|
+
* 自定义专家:机器上的 MCP 除了它选的都关掉,再挂上它选的 agent-loft 管的 MCP。
|
|
380
408
|
*/
|
|
381
|
-
private async modeParams(
|
|
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
|
-
|
|
395
|
-
|
|
396
|
-
|
|
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, ...
|
|
428
|
+
const work = { ...mcp, ...this.skillConfig() };
|
|
399
429
|
return Object.keys(work).length ? { config: work } : {};
|
|
400
430
|
}
|
|
401
431
|
|
|
402
432
|
/**
|
|
403
|
-
*
|
|
404
|
-
* 一个个键写不会冲掉用户 config.toml
|
|
405
|
-
*
|
|
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
|
|
418
|
-
*
|
|
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 && (
|
|
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(
|
|
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
|
|
537
|
-
const textMap =
|
|
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,
|
|
540
|
-
const texts =
|
|
556
|
+
const note = input.attachments.length ? describeAttachments(input.attachments, inlined, noRead) : "";
|
|
557
|
+
const texts = noRead ? inlineTextBlocks(input.attachments, textMap) : "";
|
|
541
558
|
// 放在最后:Codex 拿第一条消息的开头当会话预览,不能被这段背景占掉
|
|
542
|
-
const
|
|
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" };
|
|
@@ -791,6 +823,20 @@ export class CodexSession implements AgentSession {
|
|
|
791
823
|
this.onItem((params as ItemNotification).item, "completed");
|
|
792
824
|
return;
|
|
793
825
|
|
|
826
|
+
case "turn/plan/updated": {
|
|
827
|
+
// Codex 的计划(update_plan):每次给整份,状态叫法和 Claude 不一样
|
|
828
|
+
const plan = (params as { plan?: { step?: unknown; status?: unknown }[] }).plan;
|
|
829
|
+
if (!this.turnSeen || !Array.isArray(plan)) return;
|
|
830
|
+
const todos = plan.flatMap((p) =>
|
|
831
|
+
typeof p.step === "string"
|
|
832
|
+
? [{ content: p.step, status: p.status === "completed" ? ("completed" as const) : p.status === "inProgress" ? ("in_progress" as const) : ("pending" as const) }]
|
|
833
|
+
: [],
|
|
834
|
+
);
|
|
835
|
+
this.events.onStep("note", `📋 更新计划(${todos.filter((t) => t.status === "completed").length}/${todos.length})`);
|
|
836
|
+
this.events.onTodos?.(todos);
|
|
837
|
+
return;
|
|
838
|
+
}
|
|
839
|
+
|
|
794
840
|
case "item/agentMessage/delta": {
|
|
795
841
|
const p = params as AgentMessageDeltaNotification;
|
|
796
842
|
if (!this.commentaryItems.has(p.itemId) && p.delta) this.events.onTextDelta(p.delta);
|
|
@@ -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,
|
|
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: "
|
|
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: "
|
|
305
|
+
{ title: "换专家", template: "blue" },
|
|
306
306
|
);
|
|
307
307
|
}
|
|
308
308
|
|
package/src/channels/web/api.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
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.
|
|
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
|
}
|