agent-loft 0.2.48 → 0.2.50
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 +32 -15
- package/package.json +1 -1
- package/src/agents/claude/driver.ts +1 -1
- package/src/agents/claude/session.ts +140 -47
- package/src/agents/codex/driver.ts +1 -1
- package/src/agents/codex/session.ts +90 -58
- package/src/channels/feishu/bot.ts +1 -3
- package/src/channels/feishu/cards.ts +2 -2
- package/src/channels/web/api.ts +49 -19
- package/src/channels/web/conv-pages.ts +37 -0
- package/src/channels/web/experts-api.ts +203 -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 +438 -0
- package/src/core/hub.ts +137 -102
- package/src/core/mcp.ts +253 -0
- package/src/core/memory-curator.ts +14 -19
- 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 +4 -7
- package/src/core/uploads.ts +7 -7
- package/src/mcp/tasks-server.ts +1 -2
- package/web/css/experts.css +225 -0
- package/web/css/messages.css +43 -0
- package/web/css/overlay.css +12 -0
- package/web/css/search.css +214 -0
- package/web/css/sidebar.css +79 -56
- package/web/css/skills.css +0 -11
- package/web/css/topbar.css +135 -5
- package/web/index.html +2 -0
- package/web/lib/dom.js +6 -14
- package/web/settings/experts.js +622 -0
- package/web/settings/index.js +3 -0
- package/web/settings/memory.js +23 -7
- package/web/settings/skills.js +3 -3
- package/web/state.js +7 -2
- package/web/views/composer.js +31 -29
- package/web/views/conv-actions.js +8 -9
- package/web/views/conv-search.js +206 -0
- package/web/views/experts.js +74 -0
- package/web/views/layout.js +9 -4
- package/web/views/messages.js +44 -11
- package/web/views/quota.js +13 -10
- package/web/views/sidebar.js +71 -19
- package/web/views/tasks.js +21 -36
- package/web/views/topbar.js +148 -74
- package/src/core/chat-mode.ts +0 -62
- package/web/views/mention.js +0 -202
|
@@ -5,7 +5,8 @@
|
|
|
5
5
|
import { appServer } from "./app-server.js";
|
|
6
6
|
import { refusalFor, UnsupportedRequest } from "./refusals.js";
|
|
7
7
|
import { config } from "../../core/config.js";
|
|
8
|
-
import { contextBlock } from "../../core/
|
|
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" };
|
|
@@ -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
|
@@ -42,7 +42,7 @@ import {
|
|
|
42
42
|
} from "../../core/memory.js";
|
|
43
43
|
import { createLinkCode, listLinks, unlink, unlinkUser } from "../../core/feishu-links.js";
|
|
44
44
|
import { purgeUserData } from "../../core/personal.js";
|
|
45
|
-
import { purgeHistory, readMeta, readRecords, writeMeta } from "../../core/chat-history.js";
|
|
45
|
+
import { purgeHistory, readMeta, readRecords, searchHistory, writeMeta } from "../../core/chat-history.js";
|
|
46
46
|
import { curateNow, pendingCount } from "../../core/memory-curator.js";
|
|
47
47
|
import { listAllowlist, setAllowlist } from "../../agents/claude/permissions.js";
|
|
48
48
|
import { agentAvailability, agentHealth, invalidateHealth } from "../../agents/health.js";
|
|
@@ -67,10 +67,13 @@ import {
|
|
|
67
67
|
takeAttempt,
|
|
68
68
|
} from "./auth.js";
|
|
69
69
|
import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
|
|
70
|
-
import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor } from "./conv-pages.js";
|
|
70
|
+
import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor, searchConvs } from "./conv-pages.js";
|
|
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
|
|
|
@@ -753,26 +759,53 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
753
759
|
sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 10)));
|
|
754
760
|
return;
|
|
755
761
|
}
|
|
762
|
+
// 搜索会话(侧栏「搜索」弹窗):标题、目录名,再搜聊天内容(聊天记录索引,见 chat-history.ts)。
|
|
763
|
+
// expert:只看这个专家的对话(内置的就是 claude / codex)
|
|
764
|
+
if (p === "/api/conversations/search" && method === "GET") {
|
|
765
|
+
const q = (url.searchParams.get("q") ?? "").slice(0, 200);
|
|
766
|
+
const expert = url.searchParams.get("expert");
|
|
767
|
+
const all = hub.list(visible).filter((c) => !c.hidden && (!expert || c.expert.id === expert));
|
|
768
|
+
const keys = new Set(all.map((c) => c.key));
|
|
769
|
+
let content: { key: string; text: string }[] = [];
|
|
770
|
+
if (q.trim()) {
|
|
771
|
+
try {
|
|
772
|
+
// 一条对话可能命中很多句,多要一些,保证别的对话也排得上
|
|
773
|
+
content = searchHistory(user.id, q, { limit: 300, skip: (k) => !keys.has(k) }).map((hit) => {
|
|
774
|
+
const lower = q.trim().toLowerCase();
|
|
775
|
+
const text = [hit.user, hit.assistant].find((t) => t?.toLowerCase().includes(lower)) ?? hit.user ?? hit.assistant ?? "";
|
|
776
|
+
return { key: hit.key, text };
|
|
777
|
+
});
|
|
778
|
+
} catch {
|
|
779
|
+
// 没有索引、读不了:只按标题搜
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
sendJson(res, 200, { results: searchConvs(all, q, content) });
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
756
785
|
if (p === "/api/conversations" && method === "GET") {
|
|
757
786
|
sendJson(res, 200, hub.list(visible));
|
|
758
787
|
return;
|
|
759
788
|
}
|
|
760
789
|
if (p === "/api/conversations" && method === "POST") {
|
|
761
|
-
|
|
790
|
+
// expert:新对话页上选的专家(内置的 claude / codex,或者自己的专家 id)。agent 是以前的叫法
|
|
791
|
+
const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
|
|
762
792
|
const enabled = hub.enabledAgents().map((d) => d.id);
|
|
763
|
-
const
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
793
|
+
const wanted = body.expert ?? body.agent;
|
|
794
|
+
let expertId = wanted && canUseExpert(user.id, wanted) ? wanted : enabled[0];
|
|
795
|
+
if (!expertId) throw new HttpError(400, "没有可用的 agent");
|
|
796
|
+
const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
|
|
797
|
+
const agent = custom ? custom.engine : expertId;
|
|
798
|
+
if (!enabled.includes(agent)) throw new HttpError(400, `${hub.label(agent)} 没有启用,用不了这个专家`);
|
|
799
|
+
// 新对话发第一条消息前在页面上选的工作目录;和 /cd 一样只能在工作区之内。没选就用专家默认的
|
|
800
|
+
let cwd: string | undefined;
|
|
801
|
+
const rawCwd = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : custom?.cwd;
|
|
802
|
+
if (rawCwd) {
|
|
803
|
+
const resolved = resolveWorkspacePath(rawCwd);
|
|
804
|
+
if (!resolved) throw new HttpError(400, `目录必须存在,且在 ${config().workspaceRoot} 之内`);
|
|
805
|
+
cwd = resolved;
|
|
770
806
|
}
|
|
771
807
|
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" });
|
|
808
|
+
hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, ...(custom ? { expert: custom.id } : {}), ...(cwd ? { cwd } : {}), owner: user.id });
|
|
776
809
|
sendJson(res, 200, hub.info(key));
|
|
777
810
|
return;
|
|
778
811
|
}
|
|
@@ -976,8 +1009,9 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
976
1009
|
case "effort":
|
|
977
1010
|
text = await hub.setEffort(key, value);
|
|
978
1011
|
break;
|
|
1012
|
+
// 换专家(开新会话):只有飞书的对话能换,网页上的 hub 会拒绝
|
|
979
1013
|
case "agent":
|
|
980
|
-
text = await hub.
|
|
1014
|
+
text = await hub.setExpert(key, value, allowedAgentsFor(key));
|
|
981
1015
|
break;
|
|
982
1016
|
case "stop":
|
|
983
1017
|
text = await hub.stop(key);
|
|
@@ -989,10 +1023,6 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
989
1023
|
case "cd":
|
|
990
1024
|
text = await hub.cd(key, value);
|
|
991
1025
|
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
1026
|
default:
|
|
997
1027
|
throw new HttpError(400, "未知操作");
|
|
998
1028
|
}
|
|
@@ -66,3 +66,40 @@ export const clampLimit = (v: unknown, def: number): number => {
|
|
|
66
66
|
const n = Math.floor(Number(v));
|
|
67
67
|
return Number.isFinite(n) && n > 0 ? Math.min(n, 200) : def;
|
|
68
68
|
};
|
|
69
|
+
|
|
70
|
+
export type SearchResult = { conv: ConversationInfo; snippet?: string };
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* 搜索会话:标题(和工作目录名)里每个词都出现的排前面,整句出现的更靠前,同样的按活跃时间;
|
|
74
|
+
* 再接上聊天内容里搜到的(contentHits,按相关程度排好的,同一条对话只取第一句)。
|
|
75
|
+
* 没输入查询:给最近活跃的。
|
|
76
|
+
*/
|
|
77
|
+
export function searchConvs(
|
|
78
|
+
list: ConversationInfo[],
|
|
79
|
+
query: string,
|
|
80
|
+
contentHits: { key: string; text: string }[] = [],
|
|
81
|
+
limit = 50,
|
|
82
|
+
): SearchResult[] {
|
|
83
|
+
const q = query.trim().toLowerCase();
|
|
84
|
+
if (!q) return [...list].sort((a, b) => b.activeAt - a.activeAt).slice(0, limit).map((conv) => ({ conv }));
|
|
85
|
+
const words = q.split(/\s+/);
|
|
86
|
+
const byTitle = list
|
|
87
|
+
.map((c) => {
|
|
88
|
+
const title = (c.title ?? "").toLowerCase();
|
|
89
|
+
const hay = `${title} ${c.cwd.split(/[\\/]/).filter(Boolean).pop() ?? ""}`.toLowerCase();
|
|
90
|
+
if (!words.every((w) => hay.includes(w))) return null;
|
|
91
|
+
return { c, rank: title.includes(q) ? 2 : 1 };
|
|
92
|
+
})
|
|
93
|
+
.filter((x) => x !== null)
|
|
94
|
+
.sort((a, b) => b.rank - a.rank || b.c.activeAt - a.c.activeAt);
|
|
95
|
+
const out: SearchResult[] = byTitle.map((x) => ({ conv: x.c }));
|
|
96
|
+
const seen = new Set(out.map((r) => r.conv.key));
|
|
97
|
+
const byKey = new Map(list.map((c) => [c.key, c]));
|
|
98
|
+
for (const hit of contentHits) {
|
|
99
|
+
const conv = byKey.get(hit.key);
|
|
100
|
+
if (!conv || seen.has(hit.key)) continue;
|
|
101
|
+
seen.add(hit.key);
|
|
102
|
+
out.push({ conv, snippet: hit.text });
|
|
103
|
+
}
|
|
104
|
+
return out.slice(0, limit);
|
|
105
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
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
|
+
avatarImage,
|
|
8
|
+
avatarUrl,
|
|
9
|
+
createExpert,
|
|
10
|
+
deleteExpert,
|
|
11
|
+
EXPERT_LIMITS,
|
|
12
|
+
EXPERT_TEMPLATES,
|
|
13
|
+
getExpert,
|
|
14
|
+
listExperts,
|
|
15
|
+
updateExpert,
|
|
16
|
+
type Expert,
|
|
17
|
+
type ExpertInput,
|
|
18
|
+
} from "../../core/experts.js";
|
|
19
|
+
import { hub } from "../../core/hub.js";
|
|
20
|
+
import { claudeMachineMcp, createMcp, deleteMcp, getMcp, listMcp, MACHINE_PREFIX, MCP_LIMITS, mcpView, updateMcp, type McpInput } from "../../core/mcp.js";
|
|
21
|
+
import { activeSkills } from "../../core/skills.js";
|
|
22
|
+
import { isAdmin, type User } from "../../core/users.js";
|
|
23
|
+
import { HttpError, readJsonBody, sendJson } from "./http.js";
|
|
24
|
+
|
|
25
|
+
const bad = (err: unknown) => (err instanceof HttpError ? err : new HttpError(400, err instanceof Error ? err.message : String(err)));
|
|
26
|
+
|
|
27
|
+
function expertView(e: Expert) {
|
|
28
|
+
return {
|
|
29
|
+
id: e.id,
|
|
30
|
+
name: e.name,
|
|
31
|
+
description: e.description,
|
|
32
|
+
icon: e.icon,
|
|
33
|
+
avatar: avatarUrl(e),
|
|
34
|
+
color: e.color,
|
|
35
|
+
welcome: e.welcome,
|
|
36
|
+
quickPrompts: e.quickPrompts,
|
|
37
|
+
engine: e.engine,
|
|
38
|
+
model: e.model ?? "",
|
|
39
|
+
effort: e.effort ?? "",
|
|
40
|
+
prompt: e.prompt,
|
|
41
|
+
basePrompt: e.basePrompt,
|
|
42
|
+
access: e.access,
|
|
43
|
+
cwd: e.cwd ?? "",
|
|
44
|
+
webSearch: e.webSearch,
|
|
45
|
+
webFetch: e.webFetch,
|
|
46
|
+
skills: e.skills,
|
|
47
|
+
mcp: e.mcp,
|
|
48
|
+
subagents: e.subagents,
|
|
49
|
+
memory: e.memory,
|
|
50
|
+
updatedAt: e.updatedAt,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 选专家时要的那点信息(bootstrap 里给,/api/experts/brief 刷新) */
|
|
55
|
+
export function expertBrief(e: Expert) {
|
|
56
|
+
return {
|
|
57
|
+
id: e.id,
|
|
58
|
+
name: e.name,
|
|
59
|
+
description: e.description,
|
|
60
|
+
icon: e.icon,
|
|
61
|
+
avatar: avatarUrl(e),
|
|
62
|
+
color: e.color,
|
|
63
|
+
engine: e.engine,
|
|
64
|
+
access: e.access,
|
|
65
|
+
webSearch: e.webSearch,
|
|
66
|
+
webFetch: e.webFetch,
|
|
67
|
+
memory: e.memory,
|
|
68
|
+
cwd: e.cwd ?? "",
|
|
69
|
+
model: e.model ?? "",
|
|
70
|
+
effort: e.effort ?? "",
|
|
71
|
+
welcome: e.welcome,
|
|
72
|
+
quickPrompts: e.quickPrompts,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 机器上原有的 MCP,只给管理员。Codex 的要问 app-server,没启用就不问(问一次就会拉起它) */
|
|
77
|
+
async function machineMcp(user: User): Promise<{ claude: string[]; codex: string[] } | undefined> {
|
|
78
|
+
if (!isAdmin(user)) return undefined;
|
|
79
|
+
const enabled = new Set(hub.enabledAgents().map((d) => d.id));
|
|
80
|
+
const codex = enabled.has("codex") ? await userMcpServers().catch(() => [] as string[]) : [];
|
|
81
|
+
return { claude: enabled.has("claude") ? Object.keys(claudeMachineMcp()) : [], codex };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** 处理了就返回 true */
|
|
85
|
+
export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse, p: string, user: User): Promise<boolean> {
|
|
86
|
+
const method = req.method ?? "GET";
|
|
87
|
+
|
|
88
|
+
if (p === "/api/experts" && method === "GET") {
|
|
89
|
+
const enabled = hub.enabledAgents().map((d) => d.id);
|
|
90
|
+
sendJson(res, 200, {
|
|
91
|
+
experts: listExperts(user.id).map(expertView),
|
|
92
|
+
builtin: enabled.map((id) => ({ id, name: hub.label(id), engine: id })),
|
|
93
|
+
engines: enabled,
|
|
94
|
+
templates: EXPERT_TEMPLATES.map((t) => ({ id: t.id, label: t.label, expert: t.expert })),
|
|
95
|
+
access: ACCESS_LEVELS.map((id) => ({ id, label: ACCESS_LABEL[id] })),
|
|
96
|
+
skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
|
|
97
|
+
mcp: listMcp(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description, type: s.type })),
|
|
98
|
+
...(await machineMcp(user).then((m) => (m ? { machineMcp: m, machinePrefix: MACHINE_PREFIX } : {}))),
|
|
99
|
+
limits: EXPERT_LIMITS,
|
|
100
|
+
});
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
if (p === "/api/experts/brief" && method === "GET") {
|
|
105
|
+
sendJson(res, 200, { experts: listExperts(user.id).map(expertBrief) });
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (p === "/api/experts" && method === "POST") {
|
|
110
|
+
const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
|
|
111
|
+
try {
|
|
112
|
+
sendJson(res, 200, expertView(createExpert(user.id, body)));
|
|
113
|
+
} catch (err) {
|
|
114
|
+
throw bad(err);
|
|
115
|
+
}
|
|
116
|
+
return true;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// 头像:登录了就能看(管理员看别人的对话时也要显示)。地址带版本号,可以长期缓存
|
|
120
|
+
const am = /^\/api\/experts\/(e_[a-f0-9]+)\/avatar$/.exec(p);
|
|
121
|
+
if (am && method === "GET") {
|
|
122
|
+
const expert = getExpert(am[1]!);
|
|
123
|
+
const img = expert && avatarImage(expert);
|
|
124
|
+
if (!img) throw new HttpError(404, "没有头像");
|
|
125
|
+
res.writeHead(200, { "Content-Type": img.type, "Content-Length": img.data.length, "Cache-Control": "private, max-age=31536000, immutable" });
|
|
126
|
+
res.end(img.data);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const em = /^\/api\/experts\/(e_[a-f0-9]+)$/.exec(p);
|
|
131
|
+
if (em) {
|
|
132
|
+
const expert = getExpert(em[1]!);
|
|
133
|
+
if (!expert || expert.owner !== user.id) throw new HttpError(404, "这个专家不存在");
|
|
134
|
+
if (method === "GET") {
|
|
135
|
+
sendJson(res, 200, expertView(expert));
|
|
136
|
+
return true;
|
|
137
|
+
}
|
|
138
|
+
if (method === "PATCH") {
|
|
139
|
+
const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
|
|
140
|
+
try {
|
|
141
|
+
sendJson(res, 200, expertView(updateExpert(user.id, expert.id, body)));
|
|
142
|
+
} catch (err) {
|
|
143
|
+
throw bad(err);
|
|
144
|
+
}
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
if (method === "DELETE") {
|
|
148
|
+
try {
|
|
149
|
+
deleteExpert(user.id, expert.id);
|
|
150
|
+
} catch (err) {
|
|
151
|
+
throw bad(err);
|
|
152
|
+
}
|
|
153
|
+
sendJson(res, 200, { ok: true });
|
|
154
|
+
return true;
|
|
155
|
+
}
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (p === "/api/mcp" && method === "GET") {
|
|
160
|
+
const experts = listExperts(user.id);
|
|
161
|
+
sendJson(res, 200, {
|
|
162
|
+
servers: listMcp(user.id).map((s) => ({ ...mcpView(s), usedBy: experts.filter((e) => e.mcp.includes(s.id)).map((e) => e.name) })),
|
|
163
|
+
limits: MCP_LIMITS,
|
|
164
|
+
});
|
|
165
|
+
return true;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (p === "/api/mcp" && method === "POST") {
|
|
169
|
+
const body = await readJsonBody<McpInput>(req, 256 * 1024);
|
|
170
|
+
try {
|
|
171
|
+
sendJson(res, 200, mcpView(createMcp(user.id, body)));
|
|
172
|
+
} catch (err) {
|
|
173
|
+
throw bad(err);
|
|
174
|
+
}
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const mm = /^\/api\/mcp\/(m_[a-f0-9]+)$/.exec(p);
|
|
179
|
+
if (mm) {
|
|
180
|
+
const server = getMcp(mm[1]!);
|
|
181
|
+
if (!server || server.owner !== user.id) throw new HttpError(404, "这个 MCP 不存在");
|
|
182
|
+
if (method === "PATCH") {
|
|
183
|
+
const body = await readJsonBody<McpInput>(req, 256 * 1024);
|
|
184
|
+
try {
|
|
185
|
+
sendJson(res, 200, mcpView(updateMcp(user.id, server.id, body)));
|
|
186
|
+
} catch (err) {
|
|
187
|
+
throw bad(err);
|
|
188
|
+
}
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
if (method === "DELETE") {
|
|
192
|
+
try {
|
|
193
|
+
deleteMcp(user.id, server.id);
|
|
194
|
+
} catch (err) {
|
|
195
|
+
throw bad(err);
|
|
196
|
+
}
|
|
197
|
+
sendJson(res, 200, { ok: true });
|
|
198
|
+
return true;
|
|
199
|
+
}
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
return false;
|
|
203
|
+
}
|