agent-loft 0.2.121 → 0.2.122
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 +15 -0
- package/package.json +1 -1
- package/src/bot-event-runner.ts +131 -0
- package/src/channels/feishu/bot.ts +82 -31
- package/src/channels/feishu/cards.ts +6 -2
- package/src/channels/feishu/client.ts +3 -3
- package/src/channels/feishu/index.ts +3 -1
- package/src/channels/web/access.ts +8 -5
- package/src/channels/web/api.ts +64 -3
- package/src/channels/web/bot-events-api.ts +82 -0
- package/src/channels/web/http.ts +1 -1
- package/src/channels/web/server.ts +9 -0
- package/src/channels/web/tasks-api.ts +6 -2
- package/src/core/backup.ts +6 -0
- package/src/core/bot-events.ts +88 -0
- package/src/core/command-catalog.ts +1 -0
- package/src/core/db.ts +18 -0
- package/src/core/hub.ts +28 -15
- package/src/core/personal.ts +2 -0
- package/src/core/store.ts +15 -3
- package/src/core/task-runner.ts +1 -0
- package/src/core/tasks-bridge.ts +8 -2
- package/src/core/tasks.ts +9 -1
- package/src/core/ui-prefs.ts +1 -1
- package/src/main.ts +3 -0
- package/web/css/tasks.css +8 -0
- package/web/lib/ws.js +3 -0
- package/web/views/assistants.js +82 -0
- package/web/views/bot-events.js +96 -0
- package/web/views/layout.js +11 -4
- package/web/views/sidebar-nav.js +1 -0
- package/web/views/tasks.js +7 -4
package/src/channels/web/api.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { cleanCustomCommands } from "../../core/command-catalog.js";
|
|
|
9
9
|
import { hub } from "../../core/hub.js";
|
|
10
10
|
import { interactions } from "../../core/interactions.js";
|
|
11
11
|
import { approve, listApproved, listPending, revoke } from "../../core/pairing.js";
|
|
12
|
-
import { agentBinding, conversationLabels, getConversation, listConversations, touchConversation, updateConversation } from "../../core/store.js";
|
|
12
|
+
import { agentBinding, conversationLabels, expertIdOf, flushStore, getConversation, listConversations, touchConversation, updateConversation } from "../../core/store.js";
|
|
13
13
|
import { addScheduled, clearScheduled, removeScheduled } from "../../core/scheduled.js";
|
|
14
14
|
import { resolveUploadFile, saveBuffer, sniff, uploadKeyOf } from "../../core/uploads.js";
|
|
15
15
|
import { mentions, resolveReplyFile } from "../../core/reply-files.js";
|
|
@@ -96,6 +96,9 @@ import {
|
|
|
96
96
|
import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
|
|
97
97
|
import { clampLimit, dirsOf, inDir, pageOf, parseCursor, recentPageOf, searchConvs } from "./conv-pages.js";
|
|
98
98
|
import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson, setServerTiming } from "./http.js";
|
|
99
|
+
import { listTasks, taskBelongsToAssistant } from "../../core/tasks.js";
|
|
100
|
+
import { clearWatches } from "../../core/bot-events.js";
|
|
101
|
+
import { handleBotEventsApi, receiveBackup } from "./bot-events-api.js";
|
|
99
102
|
import { handleTasksApi } from "./tasks-api.js";
|
|
100
103
|
import { handleLibraryApi } from "./library-api.js";
|
|
101
104
|
import { attachToConversation, canSeeFile, deleteConversationFiles, getLibraryFile } from "../../core/library.js";
|
|
@@ -130,6 +133,7 @@ const uploads = new Map<string, { key: string; attachment: SavedAttachment; at:
|
|
|
130
133
|
/** 单条删除和项目批量删除共用清理规则,保留 agent 自己的文字记录。 */
|
|
131
134
|
function hideConversation(key: string): void {
|
|
132
135
|
const conv = getConversation(key);
|
|
136
|
+
if (conv?.assistant === "active" && conv.owner) clearWatches(conv.owner, key);
|
|
133
137
|
updateConversation(key, { hidden: true });
|
|
134
138
|
// 删对话:聊天记录索引和摘要真的删掉,不只是搜不到(agent 自己的文字记录还留着,它们不归这里管)
|
|
135
139
|
if (conv) {
|
|
@@ -624,6 +628,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
624
628
|
const p = url.pathname;
|
|
625
629
|
const ip = clientIp(req);
|
|
626
630
|
|
|
631
|
+
if (p === "/api/bot-events/receive" && method === "POST") return receiveBackup(req, res);
|
|
632
|
+
|
|
627
633
|
// ----- 无需登录 -----
|
|
628
634
|
if (p === "/api/me" && method === "GET") {
|
|
629
635
|
const user = currentUser(req);
|
|
@@ -671,6 +677,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
671
677
|
const user = currentUser(req);
|
|
672
678
|
if (!user) throw new HttpError(401, "请先登录");
|
|
673
679
|
if (adminOnly(p) && !isAdmin(user)) throw new HttpError(403, "只有管理员能做这个操作");
|
|
680
|
+
if (p === "/api/bot-events" || p.startsWith("/api/bot-events/")) return handleBotEventsApi(req, res, url, user);
|
|
674
681
|
const admin = isAdmin(user);
|
|
675
682
|
const visible = (c: Parameters<typeof canSeeConv>[1]) => canSeeConv(user, c);
|
|
676
683
|
|
|
@@ -972,10 +979,48 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
972
979
|
sendJson(res, 200, hub.list(visible));
|
|
973
980
|
return;
|
|
974
981
|
}
|
|
975
|
-
if (p === "/api/
|
|
982
|
+
if (p === "/api/assistants" && method === "GET") {
|
|
983
|
+
const tasks = listTasks(user.id);
|
|
984
|
+
const assistants = listConversations().filter((c) => c.owner === user.id && c.assistant === "active" && !c.hidden).map((c) => {
|
|
985
|
+
const info = hub.info(c.key)!;
|
|
986
|
+
const assigned = tasks.filter((t) => taskBelongsToAssistant(t, c.key));
|
|
987
|
+
return {
|
|
988
|
+
key: c.key, expert: info.expert, agent: c.agent, cwd: c.cwd, title: c.title,
|
|
989
|
+
permission: info.permission, permissionMax: info.permissionMax,
|
|
990
|
+
unavailable: hub.assistantUnavailable(c), busy: info.busy, pending: interactions.listPending(c.key).length,
|
|
991
|
+
tasks: assigned.map((t) => {
|
|
992
|
+
const last = t.runs[0];
|
|
993
|
+
const key = last?.convKey ?? t.target.key;
|
|
994
|
+
const target = key ? getConversation(key) : undefined;
|
|
995
|
+
const resultKey = target?.owner === user.id && !target.hidden ? target.key : undefined;
|
|
996
|
+
const runningHere = resultKey && hub.currentTaskTurn(resultKey)?.taskId === t.id;
|
|
997
|
+
return {
|
|
998
|
+
id: t.id, title: t.title, enabled: t.enabled, nextRunAt: t.nextRunAt,
|
|
999
|
+
last, resultKey, pending: runningHere ? interactions.listPending(resultKey).length : 0,
|
|
1000
|
+
};
|
|
1001
|
+
}),
|
|
1002
|
+
};
|
|
1003
|
+
});
|
|
1004
|
+
sendJson(res, 200, { assistants });
|
|
1005
|
+
return;
|
|
1006
|
+
}
|
|
1007
|
+
if (p === "/api/assistants" && method === "DELETE") {
|
|
1008
|
+
const { key } = await readJsonBody<{ key?: string }>(req);
|
|
1009
|
+
const conv = typeof key === "string" ? getConversation(key) : undefined;
|
|
1010
|
+
if (!conv || conv.owner !== user.id || (conv.assistant !== "active" && conv.assistant !== "removed")) throw new HttpError(404, "找不到这个 bot");
|
|
1011
|
+
clearWatches(user.id, conv.key);
|
|
1012
|
+
updateConversation(conv.key, { assistant: "removed" });
|
|
1013
|
+
flushStore();
|
|
1014
|
+
hub.emitEvent(conv.key, { type: "meta" });
|
|
1015
|
+
sendJson(res, 200, { ok: true });
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
if ((p === "/api/conversations" || p === "/api/assistants") && method === "POST") {
|
|
976
1019
|
// expert:新对话页上选的专家(内置的 claude / codex,或者自己的、共享的专家 id)。agent 是以前的叫法
|
|
977
1020
|
const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
|
|
978
1021
|
const enabled = hub.enabledAgents().map((d) => d.id);
|
|
1022
|
+
const assistant = p === "/api/assistants";
|
|
1023
|
+
if (assistant && (typeof body.expert !== "string" || !body.expert)) throw new HttpError(400, "请选择 bot 使用的专家");
|
|
979
1024
|
const wanted = body.expert ?? body.agent;
|
|
980
1025
|
if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家或 Agent 不存在、已取消共享或未获授权");
|
|
981
1026
|
const expertId = wanted || hub.expertChoices(user.id, enabled)[0]?.id;
|
|
@@ -983,6 +1028,21 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
983
1028
|
const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
|
|
984
1029
|
const agent = custom ? custom.engine : expertId;
|
|
985
1030
|
if (!enabled.includes(agent)) throw new HttpError(400, `${hub.label(agent)} 没有启用,用不了这个专家`);
|
|
1031
|
+
if (assistant) {
|
|
1032
|
+
// 查询和创建在同一个同步区间,多个标签同时添加也只会创建一个联系人。
|
|
1033
|
+
const contacts = listConversations().filter((c) => c.owner === user.id && !c.hidden && expertIdOf(c) === expertId);
|
|
1034
|
+
const existing = contacts.find((c) => c.assistant === "active") ?? contacts.find((c) => c.assistant === "removed" && c.agent === agent);
|
|
1035
|
+
if (existing) {
|
|
1036
|
+
if (existing.agent !== agent) throw new HttpError(409, "专家已更换引擎,请移除旧 bot 后重新添加");
|
|
1037
|
+
if (existing.assistant !== "active") {
|
|
1038
|
+
updateConversation(existing.key, { assistant: "active" });
|
|
1039
|
+
flushStore();
|
|
1040
|
+
hub.emitEvent(existing.key, { type: "meta" });
|
|
1041
|
+
}
|
|
1042
|
+
sendJson(res, 200, hub.info(existing.key));
|
|
1043
|
+
return;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
986
1046
|
// 新对话发第一条消息前在页面上选的工作目录;和 /cd 一样只能在工作区之内。没选就用专家默认的
|
|
987
1047
|
let cwd: string | undefined;
|
|
988
1048
|
const rawCwd = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : custom?.cwd;
|
|
@@ -992,7 +1052,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
992
1052
|
cwd = resolved;
|
|
993
1053
|
}
|
|
994
1054
|
const key = `web:${crypto.randomBytes(6).toString("hex")}`;
|
|
995
|
-
hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, ...(custom ? { expert: custom.id } : {}), ...(cwd ? { cwd } : {}), owner: user.id
|
|
1055
|
+
hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, ...(custom ? { expert: custom.id } : {}), ...(cwd ? { cwd } : {}), owner: user.id,
|
|
1056
|
+
...(assistant ? { assistant: "active", title: custom?.name ?? hub.label(agent) } : {}) });
|
|
996
1057
|
sendJson(res, 200, hub.info(key));
|
|
997
1058
|
return;
|
|
998
1059
|
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { watchAvailable } from "../../bot-event-runner.js";
|
|
3
|
+
import { acceptResult, botEvents, createWatch, deleteWatch, getWatch, hookWatch, incidentsFor, parseBackupResult, reasons, watchesFor } from "../../core/bot-events.js";
|
|
4
|
+
import { sql } from "../../core/db.js";
|
|
5
|
+
import { hub } from "../../core/hub.js";
|
|
6
|
+
import { getConversation } from "../../core/store.js";
|
|
7
|
+
import { pushOptions } from "../../core/tasks.js";
|
|
8
|
+
import type { User } from "../../core/users.js";
|
|
9
|
+
import { HttpError, readJsonBody, sendJson } from "./http.js";
|
|
10
|
+
|
|
11
|
+
export async function receiveBackup(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
|
12
|
+
const token = /^Bearer ([0-9a-f]{64})$/i.exec(req.headers.authorization ?? "")?.[1] ?? "";
|
|
13
|
+
if (!hookWatch(token)) throw new HttpError(401, "监听凭据无效");
|
|
14
|
+
const body = await readJsonBody(req, 4096);
|
|
15
|
+
const w = hookWatch(token);
|
|
16
|
+
if (!w || !watchAvailable(w)) throw new HttpError(403, "监听不可用");
|
|
17
|
+
let result;
|
|
18
|
+
try { result = parseBackupResult(body); }
|
|
19
|
+
catch (err) { throw new HttpError(400, (err as Error).message); }
|
|
20
|
+
try { sendJson(res, 200, { result: acceptResult(w, result) }); }
|
|
21
|
+
catch (err) {
|
|
22
|
+
if (err instanceof RangeError) throw new HttpError(429, err.message);
|
|
23
|
+
throw err;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function contact(user: User, key: unknown) {
|
|
28
|
+
const c = typeof key === "string" && getConversation(key);
|
|
29
|
+
if (!c || c.owner !== user.id || c.hidden || c.assistant !== "active") throw new HttpError(404, "找不到这个 bot");
|
|
30
|
+
return c;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function handleBotEventsApi(req: IncomingMessage, res: ServerResponse, url: URL, user: User): Promise<void> {
|
|
34
|
+
const method = req.method;
|
|
35
|
+
const root = "/api/bot-events";
|
|
36
|
+
if (url.pathname === root && method === "GET") {
|
|
37
|
+
const id = url.searchParams.get("watch");
|
|
38
|
+
const w = id ? getWatch(id) : undefined;
|
|
39
|
+
const c = contact(user, id ? w?.conv : url.searchParams.get("key"));
|
|
40
|
+
const watches = watchesFor(user.id, c.key).map((w) => ({
|
|
41
|
+
id: w.id, name: w.name, source: w.source, destination: w.destination, analyze: !!w.analyze, lastSeen: w.last_seen, lastStatus: w.last_status,
|
|
42
|
+
events: incidentsFor(w.id).map((e) => ({ id: e.id, run: e.run, reason: reasons[e.reason], at: e.at, delivery: e.delivery,
|
|
43
|
+
attempts: e.attempts, error: e.error, analysis: e.analysis, analysisKey: e.analysis_key })),
|
|
44
|
+
}));
|
|
45
|
+
sendJson(res, 200, { key: c.key, watches, admin: user.role === "admin", unavailable: hub.assistantUnavailable(c), feishu: pushOptions(user.id).feishu });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (url.pathname === root && method === "POST") {
|
|
49
|
+
const body = await readJsonBody(req);
|
|
50
|
+
const c = contact(user, body?.key);
|
|
51
|
+
if (hub.assistantUnavailable(c)) throw new HttpError(409, "这个 bot 当前不可用");
|
|
52
|
+
const { name, source, destination, analyze = false } = body;
|
|
53
|
+
if (typeof name !== "string" || !name.trim() || name.length > 60 || typeof analyze !== "boolean") throw new HttpError(400, "请检查监听名称和分析设置");
|
|
54
|
+
if (source !== "webhook" && source !== "backup") throw new HttpError(400, "事件来源无效");
|
|
55
|
+
if (source === "backup" && user.role !== "admin") throw new HttpError(403, "只有管理员可监听本机数据库备份");
|
|
56
|
+
if (typeof destination !== "string" || !(["inbox", "web", ...pushOptions(user.id).feishu.map((b) => "feishu:" + b.id)].includes(destination))) {
|
|
57
|
+
throw new HttpError(400, "请选择自己的通知渠道");
|
|
58
|
+
}
|
|
59
|
+
let created;
|
|
60
|
+
try { created = createWatch(user.id, c.key, name, source, destination, analyze); }
|
|
61
|
+
catch (err) {
|
|
62
|
+
if (err instanceof RangeError) throw new HttpError(400, err.message);
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
sendJson(res, 201, created);
|
|
66
|
+
botEvents.emit("changed", user.id);
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
const match = /^\/api\/bot-events\/([a-f0-9-]+)(?:\/retry\/(\d+))?$/.exec(url.pathname);
|
|
70
|
+
const w = match && getWatch(match[1]!);
|
|
71
|
+
if (!w || w.owner !== user.id) throw new HttpError(404, "监听不存在");
|
|
72
|
+
contact(user, w.conv);
|
|
73
|
+
if (method === "DELETE" && !match[2]) deleteWatch(w.id);
|
|
74
|
+
else if (method === "POST" && match[2]) {
|
|
75
|
+
if (!watchAvailable(w)) throw new HttpError(409, "这个 bot 当前不可用");
|
|
76
|
+
const changed = sql("UPDATE bot_incidents SET delivery='pending',attempts=0,next_try=0,error=NULL WHERE watch=? AND id=? AND delivery='failed'").run(w.id, Number(match[2])).changes;
|
|
77
|
+
if (!changed) throw new HttpError(409, "这条记录当前无法重试");
|
|
78
|
+
botEvents.emit("ready");
|
|
79
|
+
} else throw new HttpError(404, "接口不存在");
|
|
80
|
+
sendJson(res, 200, { ok: true });
|
|
81
|
+
botEvents.emit("changed", user.id);
|
|
82
|
+
}
|
package/src/channels/web/http.ts
CHANGED
|
@@ -85,7 +85,7 @@ export async function readBody(req: IncomingMessage, limit: number): Promise<Buf
|
|
|
85
85
|
let size = 0;
|
|
86
86
|
for await (const chunk of req) {
|
|
87
87
|
size += (chunk as Buffer).length;
|
|
88
|
-
if (size > limit) throw new HttpError(413, `内容太大(上限 ${Math.round(limit / 1024 / 1024)}
|
|
88
|
+
if (size > limit) throw new HttpError(413, `内容太大(上限 ${limit < 1024 * 1024 ? Math.ceil(limit / 1024) + " KB" : Math.round(limit / 1024 / 1024) + " MB"})`);
|
|
89
89
|
chunks.push(chunk as Buffer);
|
|
90
90
|
}
|
|
91
91
|
return Buffer.concat(chunks);
|
|
@@ -14,6 +14,7 @@ import { GLOBAL_ALWAYS_DENIED, hub, type EventEnvelope } from "../../core/hub.js
|
|
|
14
14
|
import { interactions, type Interaction } from "../../core/interactions.js";
|
|
15
15
|
import { weixinEvents } from "../weixin/events.js";
|
|
16
16
|
import { getConversation } from "../../core/store.js";
|
|
17
|
+
import { botEvents } from "../../core/bot-events.js";
|
|
17
18
|
import { findTask, taskEvents, taskPush } from "../../core/tasks.js";
|
|
18
19
|
import { skillEvents } from "../../core/skills.js";
|
|
19
20
|
import { expertEvents } from "../../core/experts.js";
|
|
@@ -363,6 +364,10 @@ function broadcastTasks(owner: string): void {
|
|
|
363
364
|
for (const client of clients) if (client.user.id === owner) send(client, { t: "tasks" });
|
|
364
365
|
}
|
|
365
366
|
|
|
367
|
+
function broadcastBotEvents(owner: string): void {
|
|
368
|
+
for (const client of clients) if (client.user.id === owner) send(client, { t: "bot-events" });
|
|
369
|
+
}
|
|
370
|
+
|
|
366
371
|
function broadcastProjectDeleted(project: { owner: string; path: string; keys: string[] }): void {
|
|
367
372
|
for (const client of clients) if (client.user.id === project.owner) send(client, { t: "project-deleted", path: project.path, keys: project.keys });
|
|
368
373
|
}
|
|
@@ -465,6 +470,8 @@ function onWeixinUndelivered({ key, body }: { key: string; body: string }): void
|
|
|
465
470
|
function pushEvent(env: EventEnvelope): void {
|
|
466
471
|
const ev = env.ev;
|
|
467
472
|
if (ev.type !== "result" && ev.type !== "error") return;
|
|
473
|
+
// 自动故障分析的提醒由监听选择的渠道发;之后用户在同一聊天里追问照常提醒。
|
|
474
|
+
if (ev.botAnalysis) return;
|
|
468
475
|
// 定时任务这次判断不用提醒
|
|
469
476
|
if (ev.type === "result" && ev.silent) return;
|
|
470
477
|
// 定时任务的结果按任务选的推送渠道:没选 Web 就不推;选了的话发到飞书 / 微信对话里的也推
|
|
@@ -785,6 +792,7 @@ export async function startWeb(): Promise<void> {
|
|
|
785
792
|
interactions.on("created", pushInteraction);
|
|
786
793
|
interactions.on("updated", broadcastInteraction);
|
|
787
794
|
interactions.on("settled", broadcastInteraction);
|
|
795
|
+
botEvents.on("changed", broadcastBotEvents);
|
|
788
796
|
taskEvents.on("changed", broadcastTasks);
|
|
789
797
|
skillEvents.on("changed", broadcastSkills);
|
|
790
798
|
expertEvents.on("changed", broadcastExperts);
|
|
@@ -838,6 +846,7 @@ export async function stopWeb(): Promise<void> {
|
|
|
838
846
|
interactions.off("created", pushInteraction);
|
|
839
847
|
interactions.off("updated", broadcastInteraction);
|
|
840
848
|
interactions.off("settled", broadcastInteraction);
|
|
849
|
+
botEvents.off("changed", broadcastBotEvents);
|
|
841
850
|
taskEvents.off("changed", broadcastTasks);
|
|
842
851
|
skillEvents.off("changed", broadcastSkills);
|
|
843
852
|
expertEvents.off("changed", broadcastExperts);
|
|
@@ -33,7 +33,7 @@ function view(task: Task) {
|
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
/** convPermission:任务发到已有对话时,顺手改那条对话的权限(权限属于对话,不属于任务) */
|
|
36
|
-
type TaskBody = TaskInput & { convPermission?: unknown };
|
|
36
|
+
type TaskBody = TaskInput & { convPermission?: unknown; assistantKey?: unknown };
|
|
37
37
|
|
|
38
38
|
/** 表单 / 请求里的字段先在这里核一遍:专家要是自己能用的、引擎要启用着,目录要在工作区里,对话要是自己的 */
|
|
39
39
|
function checkInput(user: User, body: TaskBody): TaskInput {
|
|
@@ -102,7 +102,11 @@ export async function handleTasksApi(req: IncomingMessage, res: ServerResponse,
|
|
|
102
102
|
if (!body.expert && !body.agent) body.expert = hub.enabledAgents()[0]?.id;
|
|
103
103
|
let task: Task;
|
|
104
104
|
try {
|
|
105
|
-
|
|
105
|
+
const source = typeof body.assistantKey === "string" ? getConversation(body.assistantKey) : undefined;
|
|
106
|
+
if (body.assistantKey !== undefined && (!source || source.owner !== user.id || source.assistant !== "active" || source.hidden || hub.assistantUnavailable(source))) {
|
|
107
|
+
throw new HttpError(400, "交办这项任务的 bot 已不可用");
|
|
108
|
+
}
|
|
109
|
+
task = createTask(user.id, checkInput(user, body), "user", Date.now(), source?.key);
|
|
106
110
|
} catch (err) {
|
|
107
111
|
throw bad(err);
|
|
108
112
|
}
|
package/src/core/backup.ts
CHANGED
|
@@ -8,6 +8,8 @@
|
|
|
8
8
|
//
|
|
9
9
|
// 恢复:停掉服务 → gunzip 备份文件 → 覆盖 data/agent-loft.db → 删掉 agent-loft.db-wal 和 -shm → 启动。
|
|
10
10
|
// 只备份数据库。配置和专家这些是 JSON 文件,不在这里面。
|
|
11
|
+
import { EventEmitter } from "node:events";
|
|
12
|
+
import { randomUUID } from "node:crypto";
|
|
11
13
|
import fs from "node:fs";
|
|
12
14
|
import path from "node:path";
|
|
13
15
|
import { Worker } from "node:worker_threads";
|
|
@@ -153,6 +155,7 @@ function prune(now: number): void {
|
|
|
153
155
|
}
|
|
154
156
|
|
|
155
157
|
/** 同一时间只做一份 */
|
|
158
|
+
export const backupEvents = new EventEmitter<{ finished: [runId: string, ok: boolean, error?: string] }>();
|
|
156
159
|
let running: Promise<BackupInfo> | undefined;
|
|
157
160
|
let lastError: { at: number; message: string } | undefined;
|
|
158
161
|
|
|
@@ -161,6 +164,7 @@ export function backupNow(now = Date.now()): Promise<BackupInfo> {
|
|
|
161
164
|
if (running) return running;
|
|
162
165
|
running = (async () => {
|
|
163
166
|
const dir = backupDir();
|
|
167
|
+
const runId = randomUUID();
|
|
164
168
|
const name = `${PREFIX}${dayName(now)}${SUFFIX}`;
|
|
165
169
|
const target = path.join(dir, name);
|
|
166
170
|
try {
|
|
@@ -172,10 +176,12 @@ export function backupNow(now = Date.now()): Promise<BackupInfo> {
|
|
|
172
176
|
lastError = undefined;
|
|
173
177
|
const size = fs.statSync(target).size;
|
|
174
178
|
console.log(`[备份] 数据库已备份到 ${target}(${(size / 1048576).toFixed(1)} MB)`);
|
|
179
|
+
backupEvents.emit("finished", runId, true);
|
|
175
180
|
return { name, at: Date.now(), size };
|
|
176
181
|
} catch (err) {
|
|
177
182
|
const message = err instanceof Error ? err.message : String(err);
|
|
178
183
|
lastError = { at: Date.now(), message };
|
|
184
|
+
backupEvents.emit("finished", runId, false, message);
|
|
179
185
|
console.error("[备份] 备份失败:", message);
|
|
180
186
|
throw err;
|
|
181
187
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// 备份作业只上报终态。原始凭据仅创建时返回,事件先提交到 SQLite,再交给投递进程。
|
|
2
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
4
|
+
import { sql, transaction } from "./db.js";
|
|
5
|
+
|
|
6
|
+
export type Watch = {
|
|
7
|
+
id: string; owner: string; conv: string; name: string; source: "backup" | "webhook";
|
|
8
|
+
destination: string; analyze: number; last_seen: number | null; last_status: string | null;
|
|
9
|
+
};
|
|
10
|
+
export type Incident = {
|
|
11
|
+
id: number; watch: string; run: string; reason: Reason; at: number; delivery: string;
|
|
12
|
+
attempts: number; next_try: number; error: string | null; analysis: string; analysis_key: string | null;
|
|
13
|
+
};
|
|
14
|
+
export const reasons = { unknown: "原因未提供", disk_full: "存储空间不足", offline: "备份目标离线", permission: "访问被拒绝", io: "读写失败" };
|
|
15
|
+
export type Reason = keyof typeof reasons;
|
|
16
|
+
export type BackupResult = { runId: string; status: "ok" | "failed"; reason: Reason };
|
|
17
|
+
export const botEvents = new EventEmitter<{ ready: []; changed: [owner: string] }>();
|
|
18
|
+
const fields = "id,owner,conv,name,source,destination,analyze,last_seen,last_status";
|
|
19
|
+
const hash = (value: string) => createHash("sha256").update(value).digest("hex");
|
|
20
|
+
|
|
21
|
+
export function parseBackupResult(input: unknown): BackupResult {
|
|
22
|
+
if (!input || typeof input !== "object") throw new Error("需要 JSON 对象");
|
|
23
|
+
const { runId, status, reason = "unknown" } = input as Record<string, unknown>;
|
|
24
|
+
if (typeof runId !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(runId)) throw new Error("runId 需要 1–128 位字母、数字、点、冒号、下划线或短横线");
|
|
25
|
+
if (status !== "ok" && status !== "failed") throw new Error("status 只能是 ok 或 failed");
|
|
26
|
+
if (typeof reason !== "string" || !Object.hasOwn(reasons, reason)) throw new Error("reason 必须是已知的备份状态码");
|
|
27
|
+
return { runId, status, reason: reason as Reason };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function getWatch(id: string): Watch | undefined {
|
|
31
|
+
return sql(`SELECT ${fields} FROM bot_watches WHERE id=?`).get(id) as Watch | undefined;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function watchesFor(owner: string, key: string): Watch[] {
|
|
35
|
+
return sql(`SELECT ${fields} FROM bot_watches WHERE owner=? AND conv=? ORDER BY rowid`).all(owner, key) as Watch[];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function createWatch(owner: string, conv: string, name: string, source: Watch["source"], destination: string, analyze: boolean) {
|
|
39
|
+
if (!name.trim() || name.length > 60) throw new Error("监听名称需要 1–60 个字符");
|
|
40
|
+
const id = randomUUID();
|
|
41
|
+
const token = source === "webhook" ? randomBytes(32).toString("hex") : undefined;
|
|
42
|
+
transaction(() => {
|
|
43
|
+
if (Number(sql("SELECT count(*) AS n FROM bot_watches WHERE owner=?").get(owner)?.n) >= 30) throw new RangeError("每个账号最多 30 条监听");
|
|
44
|
+
sql("INSERT INTO bot_watches(id,owner,conv,name,source,destination,analyze,token_hash) VALUES(?,?,?,?,?,?,?,?)")
|
|
45
|
+
.run(id, owner, conv, name.trim(), source, destination, Number(analyze), token ? hash(token) : null);
|
|
46
|
+
});
|
|
47
|
+
return { id, token };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function hookWatch(token: string): Watch | undefined {
|
|
51
|
+
if (!/^[0-9a-f]{64}$/.test(token)) return undefined;
|
|
52
|
+
return sql(`SELECT ${fields} FROM bot_watches WHERE token_hash=? AND source='webhook'`).get(hash(token)) as Watch | undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function incidentsFor(watch: string): Incident[] {
|
|
56
|
+
return sql("SELECT * FROM bot_incidents WHERE watch=? ORDER BY id DESC LIMIT 12").all(watch) as Incident[];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 成功只记最近收到的状态。失败由唯一约束去重,写入和推进接收位置同一事务。 */
|
|
60
|
+
export function acceptResult(w: Watch, result: BackupResult, now = Date.now()): "quiet" | "duplicate" | "accepted" {
|
|
61
|
+
const outcome = transaction(() => {
|
|
62
|
+
if (!getWatch(w.id)) throw new Error("监听已关闭");
|
|
63
|
+
if (result.status === "failed") {
|
|
64
|
+
if (sql("SELECT 1 FROM bot_incidents WHERE watch=? AND run=?").get(w.id, result.runId)) return "duplicate";
|
|
65
|
+
// 避免上报端配置错误时短时间大量唤起模型或发送通知。限流的事件可稍后重投。
|
|
66
|
+
if (Number(sql("SELECT count(*) AS n FROM bot_incidents WHERE watch=? AND at>=?").get(w.id, now - 3600_000)?.n) >= 60) throw new RangeError("该监听本小时失败事件已达上限");
|
|
67
|
+
sql("INSERT INTO bot_incidents(watch,run,reason,at,delivery,analysis) VALUES(?,?,?,?,?,?)")
|
|
68
|
+
.run(w.id, result.runId, result.reason, now, w.destination === "inbox" ? "inbox" : "pending", w.analyze ? "pending" : "off");
|
|
69
|
+
}
|
|
70
|
+
sql("UPDATE bot_watches SET last_seen=?,last_status=? WHERE id=?").run(now, result.status, w.id);
|
|
71
|
+
return result.status === "ok" ? "quiet" : "accepted";
|
|
72
|
+
});
|
|
73
|
+
if (outcome === "accepted" || (outcome === "quiet" && w.last_status !== "ok")) botEvents.emit("changed", w.owner);
|
|
74
|
+
if (outcome === "accepted") botEvents.emit("ready");
|
|
75
|
+
return outcome;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function deleteWatch(id: string): void {
|
|
79
|
+
transaction(() => {
|
|
80
|
+
sql("DELETE FROM bot_incidents WHERE watch=?").run(id);
|
|
81
|
+
sql("DELETE FROM bot_watches WHERE id=?").run(id);
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function clearWatches(owner: string, key?: string): void {
|
|
86
|
+
const watches = key ? watchesFor(owner, key) : sql("SELECT id FROM bot_watches WHERE owner=?").all(owner) as { id: string }[];
|
|
87
|
+
transaction(() => { for (const w of watches) deleteWatch(w.id); });
|
|
88
|
+
}
|
|
@@ -40,6 +40,7 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
|
|
|
40
40
|
{ name: "workbuddy", description: "换成 WorkBuddy 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
41
41
|
{ name: "pi", description: "换成 pi 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
42
42
|
{ name: "dsh", description: "换成 dsh 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
43
|
+
{ name: "bot", description: "在绑定私聊打开 bot", feishuOnly: true },
|
|
43
44
|
{ name: "web", description: "接上一条 Web 会话,在飞书里查看和回复", feishuOnly: true },
|
|
44
45
|
{ name: "detach", description: "不再接着 Web 会话,回到这个聊天自己的会话", feishuOnly: true },
|
|
45
46
|
{ name: "bind", args: "<绑定码>", description: "把这个飞书账号绑定到你的 agent-loft 用户(绑定码在 Web 的「设置 → 账号」里生成)", feishuOnly: true },
|
package/src/core/db.ts
CHANGED
|
@@ -46,6 +46,24 @@ CREATE TABLE IF NOT EXISTS conversations (
|
|
|
46
46
|
data TEXT NOT NULL
|
|
47
47
|
);
|
|
48
48
|
|
|
49
|
+
CREATE TABLE IF NOT EXISTS assistant_sessions (session_id TEXT PRIMARY KEY, owner TEXT NOT NULL);
|
|
50
|
+
|
|
51
|
+
CREATE TABLE IF NOT EXISTS bot_watches (
|
|
52
|
+
id TEXT PRIMARY KEY, owner TEXT NOT NULL, conv TEXT NOT NULL, name TEXT NOT NULL,
|
|
53
|
+
source TEXT NOT NULL, destination TEXT NOT NULL, analyze INTEGER NOT NULL,
|
|
54
|
+
token_hash TEXT UNIQUE, last_seen INTEGER, last_status TEXT
|
|
55
|
+
);
|
|
56
|
+
CREATE INDEX IF NOT EXISTS bot_watches_owner ON bot_watches(owner, conv);
|
|
57
|
+
|
|
58
|
+
CREATE TABLE IF NOT EXISTS bot_incidents (
|
|
59
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, watch TEXT NOT NULL, run TEXT NOT NULL, reason TEXT NOT NULL,
|
|
60
|
+
at INTEGER NOT NULL, delivery TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
|
|
61
|
+
next_try INTEGER NOT NULL DEFAULT 0, error TEXT, analysis TEXT NOT NULL, analysis_key TEXT,
|
|
62
|
+
UNIQUE(watch, run)
|
|
63
|
+
);
|
|
64
|
+
CREATE INDEX IF NOT EXISTS bot_incidents_pending ON bot_incidents(delivery, next_try);
|
|
65
|
+
CREATE INDEX IF NOT EXISTS bot_incidents_analysis ON bot_incidents(analysis);
|
|
66
|
+
|
|
49
67
|
CREATE TABLE IF NOT EXISTS session_owners (
|
|
50
68
|
session_id TEXT PRIMARY KEY,
|
|
51
69
|
user_id TEXT NOT NULL
|
package/src/core/hub.ts
CHANGED
|
@@ -20,6 +20,7 @@ import { recordUsage, usageOf, type UsageTotals } from "./usage.js";
|
|
|
20
20
|
import { interactions, SETTLEMENT_LABEL } from "./interactions.js";
|
|
21
21
|
import {
|
|
22
22
|
agentBinding,
|
|
23
|
+
assistantSessionOwner,
|
|
23
24
|
ensureConversation,
|
|
24
25
|
expertIdOf,
|
|
25
26
|
getConversation,
|
|
@@ -108,8 +109,8 @@ export type ConvEvent =
|
|
|
108
109
|
* task:这一轮是定时任务发起的;silent:任务让 agent 自己判断要不要提醒,它判断这次不用 ——
|
|
109
110
|
* 推送、飞书都不发,网页上折叠显示
|
|
110
111
|
*/
|
|
111
|
-
| { type: "result"; text: string; footer: string; at: number; anchor?: string; task?: { id: string; title: string }; silent?: true }
|
|
112
|
-
| { type: "error"; message: string }
|
|
112
|
+
| { type: "result"; text: string; footer: string; at: number; anchor?: string; task?: { id: string; title: string }; silent?: true; botAnalysis?: true }
|
|
113
|
+
| { type: "error"; message: string; botAnalysis?: true }
|
|
113
114
|
| { type: "notice"; text: string }
|
|
114
115
|
| { type: "state"; busy: boolean }
|
|
115
116
|
| { type: "meta" };
|
|
@@ -315,7 +316,7 @@ class Hub extends EventEmitter<{
|
|
|
315
316
|
* 已经交给 agent 会话、还没出结果的消息,和 inflight、turnTags 一一对应:第一条在跑,后面的在排队。
|
|
316
317
|
* 用来告诉页面哪条消息轮到了 / 被丢了,以及「打断并发送」时把哪条挪到前面
|
|
317
318
|
*/
|
|
318
|
-
private turnFifo = new Map<string, { id: string; input: UserInput; queued: boolean }[]>();
|
|
319
|
+
private turnFifo = new Map<string, { id: string; input: UserInput; queued: boolean; botAnalysis?: true }[]>();
|
|
319
320
|
private pendingInputs = new Map<string, Map<string, { input: UserInput; cancelled: boolean }>>();
|
|
320
321
|
private rewinding = new Set<string>();
|
|
321
322
|
/** 收到了、还在串行队列里没交给 agent 的消息数:这时再来的消息也算排队 */
|
|
@@ -512,6 +513,13 @@ class Hub extends EventEmitter<{
|
|
|
512
513
|
|
|
513
514
|
// ---------- 专家 ----------
|
|
514
515
|
|
|
516
|
+
assistantUnavailable(conv: Conversation): string | undefined {
|
|
517
|
+
if (!canUseExpert(conv.owner, expertIdOf(conv))) return "专家已删除或使用权限已撤销";
|
|
518
|
+
if (conv.expert && getExpert(conv.expert)?.engine !== conv.agent) return "专家已更换引擎";
|
|
519
|
+
if (!this.enabledAgents().some((driver) => driver.id === conv.agent)) return "引擎已停用";
|
|
520
|
+
return undefined;
|
|
521
|
+
}
|
|
522
|
+
|
|
515
523
|
/** 对话的专家,给顶栏和列表看 */
|
|
516
524
|
expertBadge(conv: Pick<Conversation, "agent" | "expert" | "owner" | "channel">): ExpertBadge {
|
|
517
525
|
if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true, ...(!canUseExpert(memoryOwnerOf(conv), conv.agent) ? { missing: true } : {}) };
|
|
@@ -655,6 +663,7 @@ class Hub extends EventEmitter<{
|
|
|
655
663
|
channel: string;
|
|
656
664
|
channelId: string;
|
|
657
665
|
defaultAgent: string;
|
|
666
|
+
assistant?: Conversation["assistant"];
|
|
658
667
|
/** 自定义专家的 id(新建时才用)。不给就是内置专家 defaultAgent */
|
|
659
668
|
expert?: string;
|
|
660
669
|
/** 新建时的工作目录。不给就是工作区根目录 */
|
|
@@ -668,6 +677,7 @@ class Hub extends EventEmitter<{
|
|
|
668
677
|
channel: params.channel,
|
|
669
678
|
channelId: params.channelId,
|
|
670
679
|
agent: params.defaultAgent,
|
|
680
|
+
assistant: params.assistant,
|
|
671
681
|
...(params.expert && !isBuiltin(params.expert) ? { expert: params.expert } : {}),
|
|
672
682
|
...(params.cwd ? { cwd: params.cwd } : {}),
|
|
673
683
|
...(params.title ? { title: params.title } : {}),
|
|
@@ -884,6 +894,7 @@ class Hub extends EventEmitter<{
|
|
|
884
894
|
...(result.anchor && !tag?.isolated ? { anchor: result.anchor } : {}),
|
|
885
895
|
...(tag ? { task: { id: tag.taskId, title: tag.title } } : {}),
|
|
886
896
|
...(silent ? { silent: true as const } : {}),
|
|
897
|
+
...(this.turnFifo.get(key)?.[0]?.botAnalysis ? { botAnalysis: true } : {}),
|
|
887
898
|
});
|
|
888
899
|
if (tag) this.emit("task", { ...tag, key, status: silent ? "silent" : "notified", text: result.text });
|
|
889
900
|
const conv = getConversation(key);
|
|
@@ -914,7 +925,7 @@ class Hub extends EventEmitter<{
|
|
|
914
925
|
// 用户自己点的停止:中断导致的「没能正常收尾」不是故障
|
|
915
926
|
this.emitEvent(key, { type: "notice", text: "已中断。" });
|
|
916
927
|
} else {
|
|
917
|
-
this.emitEvent(key, { type: "error", message: diagnosis.chatMessage });
|
|
928
|
+
this.emitEvent(key, { type: "error", message: diagnosis.chatMessage, ...(this.turnFifo.get(key)?.[0]?.botAnalysis ? { botAnalysis: true } : {}) });
|
|
918
929
|
}
|
|
919
930
|
this.setInflight(key, (this.inflight.get(key) ?? 1) - 1);
|
|
920
931
|
this.finishTurn(key);
|
|
@@ -964,7 +975,7 @@ class Hub extends EventEmitter<{
|
|
|
964
975
|
// 分叉中还报的是原会话 id:分叉尚未生效,什么都不改
|
|
965
976
|
if (forkFrom && sessionId === forkFrom) return;
|
|
966
977
|
updateAgentBinding(key, agent, { sessionId, forkFrom: undefined });
|
|
967
|
-
recordSessionOwner(sessionId, current?.owner);
|
|
978
|
+
recordSessionOwner(sessionId, current?.owner, !!current?.assistant);
|
|
968
979
|
this.emitEvent(key, { type: "meta" });
|
|
969
980
|
},
|
|
970
981
|
},
|
|
@@ -1256,10 +1267,9 @@ class Hub extends EventEmitter<{
|
|
|
1256
1267
|
return;
|
|
1257
1268
|
}
|
|
1258
1269
|
// 收到之后发生过显式切换(恢复 / 分叉 / 新会话…):用户已经明确指定了会话,不再按旧的闲置时间作废它。
|
|
1259
|
-
//
|
|
1260
|
-
const ttl = config().sessionTtlMs;
|
|
1270
|
+
// 定时任务和固定 bot 均可接续旧上下文,空闲的引擎进程仍按原规则释放。
|
|
1261
1271
|
const switchedAfterEntry = (this.lastSwitch.get(key)?.at ?? 0) >= g.at;
|
|
1262
|
-
const expired = !task && !switchedAfterEntry &&
|
|
1272
|
+
const expired = !task && !switchedAfterEntry && isExpired(conv, Date.now(), lastActive);
|
|
1263
1273
|
if (expired) {
|
|
1264
1274
|
await this.expireNow(key);
|
|
1265
1275
|
if (waiting.cancelled) return;
|
|
@@ -1299,7 +1309,7 @@ class Hub extends EventEmitter<{
|
|
|
1299
1309
|
// 从这里到 sendNow 没有 await:换下去的会话一定等得到这一轮的结束(见 endIsolatedRun)
|
|
1300
1310
|
this.parkChatSession(key, task.runId);
|
|
1301
1311
|
}
|
|
1302
|
-
this.sendNow(key, task ? input : this.withTaskResults(key, input), task ?? null, { id: shown.id, queued: shown.queued });
|
|
1312
|
+
this.sendNow(key, task ? input : this.withTaskResults(key, input), task ?? null, { id: shown.id, queued: shown.queued, ...(origin.channel === "bot-event" ? { botAnalysis: true } : {}) });
|
|
1303
1313
|
} finally {
|
|
1304
1314
|
pendingInputs.delete(shown.id);
|
|
1305
1315
|
if (!pendingInputs.size) this.pendingInputs.delete(key);
|
|
@@ -1481,10 +1491,10 @@ class Hub extends EventEmitter<{
|
|
|
1481
1491
|
}
|
|
1482
1492
|
|
|
1483
1493
|
/** msg:页面上那条消息的编号和收到时是否排队(见 send 里的 shown) */
|
|
1484
|
-
private sendNow(key: string, input: UserInput, tag: TaskTurn | null, msg: { id: string; queued: boolean }): void {
|
|
1494
|
+
private sendNow(key: string, input: UserInput, tag: TaskTurn | null, msg: { id: string; queued: boolean; botAnalysis?: true }): void {
|
|
1485
1495
|
const fail = (err: unknown) => {
|
|
1486
1496
|
const message = err instanceof Error ? err.message : String(err);
|
|
1487
|
-
this.emitEvent(key, { type: "error", message });
|
|
1497
|
+
this.emitEvent(key, { type: "error", message, ...(msg.botAnalysis ? { botAnalysis: true } : {}) });
|
|
1488
1498
|
if (tag) this.emit("task", { ...tag, key, status: "error", text: message });
|
|
1489
1499
|
};
|
|
1490
1500
|
let session: AgentSession;
|
|
@@ -1499,7 +1509,7 @@ class Hub extends EventEmitter<{
|
|
|
1499
1509
|
tags.push(tag);
|
|
1500
1510
|
this.turnTags.set(key, tags);
|
|
1501
1511
|
const fifo = this.turnFifo.get(key) ?? [];
|
|
1502
|
-
fifo.push({
|
|
1512
|
+
fifo.push({ ...msg, input });
|
|
1503
1513
|
this.turnFifo.set(key, fifo);
|
|
1504
1514
|
try {
|
|
1505
1515
|
session.send(input);
|
|
@@ -1594,6 +1604,8 @@ class Hub extends EventEmitter<{
|
|
|
1594
1604
|
|
|
1595
1605
|
private async resumeNow(key: string, sessionId: string, originCwd: string | undefined, op: SwitchOp): Promise<string> {
|
|
1596
1606
|
const conv = getConversation(key)!;
|
|
1607
|
+
const privateOwner = assistantSessionOwner(sessionId);
|
|
1608
|
+
if (privateOwner && (!conv.assistant || conv.owner !== privateOwner)) return "请在本人的 bot 对话里恢复这段历史。";
|
|
1597
1609
|
const driver = this.requireDriver(conv.agent);
|
|
1598
1610
|
if (!(await withTimeout(driver.sessionExists(sessionId, conv.cwd), "查询会话"))) {
|
|
1599
1611
|
return `找不到会话 ${sessionId}。\n发 /sessions 看看有哪些可恢复的。`;
|
|
@@ -2052,7 +2064,7 @@ class Hub extends EventEmitter<{
|
|
|
2052
2064
|
this.markSwitched(key, op.seq);
|
|
2053
2065
|
updateAgentBinding(key, conv.agent, { sessionId, forkFrom: undefined });
|
|
2054
2066
|
if (sessionId) {
|
|
2055
|
-
recordSessionOwner(sessionId, conv.owner);
|
|
2067
|
+
recordSessionOwner(sessionId, conv.owner, !!conv.assistant);
|
|
2056
2068
|
for (const m of kept) if (m.footer) recordFooter(sessionId, m.text, m.footer, m.changes);
|
|
2057
2069
|
}
|
|
2058
2070
|
const owner = memoryOwnerOf(conv);
|
|
@@ -2270,8 +2282,8 @@ class Hub extends EventEmitter<{
|
|
|
2270
2282
|
copyFooters(source, sessionId);
|
|
2271
2283
|
owner ??= conv.owner;
|
|
2272
2284
|
const newKey = `web:${crypto.randomBytes(6).toString("hex")}`;
|
|
2273
|
-
ensureConversation({ key: newKey, channel: "web", channelId: "web", agent: conv.agent, ...(owner ? { owner } : {}) });
|
|
2274
|
-
recordSessionOwner(sessionId, owner);
|
|
2285
|
+
ensureConversation({ key: newKey, channel: "web", channelId: "web", agent: conv.agent, ...(conv.assistant ? { assistant: "related" } : {}), ...(owner ? { owner } : {}) });
|
|
2286
|
+
recordSessionOwner(sessionId, owner, !!conv.assistant);
|
|
2275
2287
|
updateConversation(newKey, {
|
|
2276
2288
|
title: `${conv.title ?? "会话"} · 分叉`.slice(0, 80),
|
|
2277
2289
|
cwd: conv.cwd,
|
|
@@ -2348,6 +2360,7 @@ class Hub extends EventEmitter<{
|
|
|
2348
2360
|
channel: "web",
|
|
2349
2361
|
channelId: "web",
|
|
2350
2362
|
agent: target.agent,
|
|
2363
|
+
...(conv.assistant ? { assistant: "related" } : {}),
|
|
2351
2364
|
...(target.expert ? { expert: target.expert } : {}),
|
|
2352
2365
|
...(owner ? { owner } : {}),
|
|
2353
2366
|
});
|
package/src/core/personal.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { clearWatches } from "./bot-events.js";
|
|
1
2
|
// 「这条对话是谁的」在个人数据(记忆、飞书绑定)上的落点。
|
|
2
3
|
import { deleteMemory, memoryPrompt, readMemory } from "./memory.js";
|
|
3
4
|
import { purgeConversationHistory, purgeHistory } from "./chat-history.js";
|
|
@@ -76,6 +77,7 @@ export function purgeHiddenConversationsOnce(): number {
|
|
|
76
77
|
|
|
77
78
|
/** 删用户时一起删掉的个人数据:记忆、聊天记录索引、飞书和微信绑定、定时任务、技能(他建的技能,装了的人也就没了)、专家和 MCP */
|
|
78
79
|
export function purgeUserData(userId: string): void {
|
|
80
|
+
clearWatches(userId);
|
|
79
81
|
deleteMemory(userId);
|
|
80
82
|
purgeHistory(userId);
|
|
81
83
|
unlinkUser(userId);
|