agent-loft 0.2.122 → 0.2.123
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 +0 -15
- package/package.json +1 -1
- package/src/channels/feishu/bot.ts +12 -29
- package/src/channels/feishu/cards.ts +2 -6
- package/src/channels/feishu/client.ts +3 -3
- package/src/channels/web/api.ts +3 -64
- package/src/channels/web/server.ts +0 -9
- package/src/channels/web/tasks-api.ts +2 -6
- package/src/core/backup.ts +0 -6
- package/src/core/command-catalog.ts +0 -1
- package/src/core/db.ts +1 -16
- package/src/core/hub.ts +11 -13
- package/src/core/personal.ts +0 -2
- package/src/core/store.ts +3 -3
- package/src/core/tasks-bridge.ts +2 -8
- package/src/core/tasks.ts +2 -8
- package/src/core/ui-prefs.ts +1 -1
- package/src/main.ts +0 -3
- package/web/css/tasks.css +0 -8
- package/web/lib/ws.js +0 -3
- package/web/views/layout.js +4 -11
- package/web/views/sidebar-nav.js +0 -1
- package/web/views/tasks.js +4 -7
- package/src/bot-event-runner.ts +0 -131
- package/src/channels/web/bot-events-api.ts +0 -82
- package/src/core/bot-events.ts +0 -88
- package/web/views/assistants.js +0 -82
- package/web/views/bot-events.js +0 -96
package/src/core/tasks.ts
CHANGED
|
@@ -70,7 +70,7 @@ export type Task = {
|
|
|
70
70
|
updatedAt: number;
|
|
71
71
|
/** 谁建的:用户在页面上建的,还是 agent 在对话里建的 */
|
|
72
72
|
createdBy: "user" | "agent";
|
|
73
|
-
/**
|
|
73
|
+
/** 旧版私人会话创建的任务,生成专用对话时沿用其可见范围。 */
|
|
74
74
|
assistantKey?: string;
|
|
75
75
|
nextRunAt?: number;
|
|
76
76
|
/** 最近的在前 */
|
|
@@ -136,11 +136,6 @@ export function listTasks(owner: string): Task[] {
|
|
|
136
136
|
.sort((a, b) => b.createdAt - a.createdAt);
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
-
/** 调用方先按 owner 取任务,再按交办来源或投递会话找到相关事项。 */
|
|
140
|
-
export function taskBelongsToAssistant(task: Task, key: string): boolean {
|
|
141
|
-
return task.assistantKey === key || task.target.key === key;
|
|
142
|
-
}
|
|
143
|
-
|
|
144
139
|
/** 只认主人:别人的任务一律当不存在 */
|
|
145
140
|
export function getTask(owner: string, id: string): Task | undefined {
|
|
146
141
|
return load().find((t) => t.id === id && t.owner === owner);
|
|
@@ -240,7 +235,7 @@ function cleanTarget(v: unknown, prev?: TaskTarget): TaskTarget {
|
|
|
240
235
|
return prev?.kind === "dedicated" ? prev : { kind: "dedicated" };
|
|
241
236
|
}
|
|
242
237
|
|
|
243
|
-
export function createTask(owner: string, input: TaskInput, by: "user" | "agent", now = Date.now()
|
|
238
|
+
export function createTask(owner: string, input: TaskInput, by: "user" | "agent", now = Date.now()): Task {
|
|
244
239
|
if (listTasks(owner).length >= TASKS_PER_USER) throw new Error(`每人最多 ${TASKS_PER_USER} 个定时任务,先删掉几个不用的`);
|
|
245
240
|
const prompt = cleanPrompt(input.prompt);
|
|
246
241
|
const schedule = normalizeSchedule(input.schedule, now);
|
|
@@ -266,7 +261,6 @@ export function createTask(owner: string, input: TaskInput, by: "user" | "agent"
|
|
|
266
261
|
createdAt: now,
|
|
267
262
|
updatedAt: now,
|
|
268
263
|
createdBy: by,
|
|
269
|
-
...(assistantKey ? { assistantKey } : {}),
|
|
270
264
|
runs: [],
|
|
271
265
|
};
|
|
272
266
|
task.nextRunAt = task.enabled ? nextRun(schedule, now) : undefined;
|
package/src/core/ui-prefs.ts
CHANGED
|
@@ -4,7 +4,7 @@ import path from "node:path";
|
|
|
4
4
|
import { dataDir, readJson, writeJsonAtomic } from "../home.js";
|
|
5
5
|
|
|
6
6
|
export type SidebarNavItem = { id: string; visible: boolean };
|
|
7
|
-
const NAV_IDS = ["search", "tasks", "
|
|
7
|
+
const NAV_IDS = ["search", "tasks", "library", "remote", "settings"];
|
|
8
8
|
type Prefs = { dirOrder?: string[]; sidebarNav?: SidebarNavItem[]; expertOrder?: string[] };
|
|
9
9
|
|
|
10
10
|
const prefsPath = path.join(dataDir, "ui-prefs.json");
|
package/src/main.ts
CHANGED
|
@@ -20,7 +20,6 @@ import { buildHistoryIndex } from "./core/chat-history.js";
|
|
|
20
20
|
import { migrateAllMemoryItems, migrateMemoryDefault } from "./core/memory.js";
|
|
21
21
|
import { listUsers } from "./core/users.js";
|
|
22
22
|
import { startScheduler, stopScheduler } from "./core/scheduled.js";
|
|
23
|
-
import { startBotEvents, stopBotEvents } from "./bot-event-runner.js";
|
|
24
23
|
import { startTaskRunner, stopTaskRunner } from "./core/task-runner.js";
|
|
25
24
|
import { startTasksBridge, stopTasksBridge } from "./core/tasks-bridge.js";
|
|
26
25
|
|
|
@@ -102,7 +101,6 @@ async function main(): Promise<void> {
|
|
|
102
101
|
// 定时任务:agent 用的工具通道先开,再开始按点运行(停机期间错过的补跑)
|
|
103
102
|
startTasksBridge();
|
|
104
103
|
startTaskRunner();
|
|
105
|
-
startBotEvents();
|
|
106
104
|
// 先查一遍 agent 装没装、登没登录,网页打开时新对话里就只列出能用的
|
|
107
105
|
void agentHealth().catch(() => {});
|
|
108
106
|
// 读一次 Claude 的命令表:成员会话的技能白名单要带上 Claude Code 自带的那些(见 claude/session.ts 的 claudeBuiltins)
|
|
@@ -122,7 +120,6 @@ async function main(): Promise<void> {
|
|
|
122
120
|
console.log(`[退出] 收到 ${signal},正在收尾…`);
|
|
123
121
|
const force = setTimeout(() => process.exit(0), 8000);
|
|
124
122
|
force.unref();
|
|
125
|
-
stopBotEvents();
|
|
126
123
|
stopScheduler();
|
|
127
124
|
stopFeishu();
|
|
128
125
|
stopWeixin();
|
package/web/css/tasks.css
CHANGED
|
@@ -544,11 +544,3 @@ button.task-run:hover {
|
|
|
544
544
|
text-overflow: ellipsis;
|
|
545
545
|
white-space: nowrap;
|
|
546
546
|
}
|
|
547
|
-
|
|
548
|
-
.assistant-list, .assistant-card { display: grid; gap: 12px; }
|
|
549
|
-
.assistant-card { border: 1px solid var(--border); border-radius: 12px; padding: 12px; }
|
|
550
|
-
.assistant-row, .assistant-task { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
|
551
|
-
.assistant-list .grow { flex: 1 1 8em; min-width: 0; overflow-wrap: anywhere; }
|
|
552
|
-
.assistant-row select { flex: 1; min-width: 0; }
|
|
553
|
-
.assistant-list small { display: block; color: var(--muted); overflow-wrap: anywhere; }
|
|
554
|
-
.assistant-task { padding-top: 8px; border-top: 1px solid var(--border); }
|
package/web/lib/ws.js
CHANGED
|
@@ -285,9 +285,6 @@ function onWsMessage(msg) {
|
|
|
285
285
|
case "ix":
|
|
286
286
|
upsertInteraction(msg.interaction);
|
|
287
287
|
return;
|
|
288
|
-
case "bot-events":
|
|
289
|
-
document.dispatchEvent(new Event("aim:bot-events"));
|
|
290
|
-
break;
|
|
291
288
|
case "tasks":
|
|
292
289
|
// 自己的定时任务变了:定时任务页开着的话会去重新拉(views/tasks.js)
|
|
293
290
|
document.dispatchEvent(new Event("aim:tasks"));
|
package/web/views/layout.js
CHANGED
|
@@ -100,17 +100,11 @@ window.addEventListener("keydown", (e) => {
|
|
|
100
100
|
|
|
101
101
|
// 多服务器(lib/shell.js):外壳让打开某条对话(点了这台的通知)、点了「管理服务器…」、切到别的服务器
|
|
102
102
|
document.addEventListener("aim:shell-open", (e) => {
|
|
103
|
-
|
|
103
|
+
if (e.detail && e.detail !== S.current) void openConversation(e.detail);
|
|
104
104
|
});
|
|
105
105
|
document.addEventListener("aim:open-settings", (e) => openSettings(e.detail));
|
|
106
106
|
document.addEventListener("aim:server-leave", () => closeSide());
|
|
107
107
|
|
|
108
|
-
function openNoticeTarget(key) {
|
|
109
|
-
if (key?.startsWith("bot-events/")) {
|
|
110
|
-
import("./bot-events.js").then((m) => m.openBotEvents({ watch: key.slice("bot-events/".length) })).catch((err) => toast(err.message));
|
|
111
|
-
} else if (key && key !== S.current) void openConversation(key);
|
|
112
|
-
}
|
|
113
|
-
|
|
114
108
|
/**
|
|
115
109
|
* 通知点开的地址:别的服务器的带着 srv=那台的 id(服务端 push.ts 的 relay),交给外壳切过去。
|
|
116
110
|
* 返回 true 表示已经交出去了
|
|
@@ -188,12 +182,11 @@ export async function boot() {
|
|
|
188
182
|
else newDraft();
|
|
189
183
|
preloadCommands();
|
|
190
184
|
// 以前的技能页地址:技能现在在设置里
|
|
191
|
-
if (fromHash.startsWith("bot-events/")) openNoticeTarget(fromHash);
|
|
192
185
|
if (fromHash === "skills") openSettings("技能");
|
|
193
186
|
// 点了桌面端的系统通知 / 菜单栏里的待处理项:跳到对应会话
|
|
194
187
|
desktop?.onOpen((key) => {
|
|
195
188
|
// 不要求在 S.convs 里:侧栏分页,那条可能还没拉到;openConversation 会去服务端拿
|
|
196
|
-
|
|
189
|
+
if (key && key !== S.current) void openConversation(key);
|
|
197
190
|
});
|
|
198
191
|
// 页面的「更多」菜单在桌面端顶栏的「更多」里:点了哪项
|
|
199
192
|
if (desktopMenu) desktop.onMenu(runDesktopMenu);
|
|
@@ -218,7 +211,7 @@ export async function boot() {
|
|
|
218
211
|
// 这台自己的通知:外壳正显示着别的服务器的话切回来
|
|
219
212
|
switchServer(HOME);
|
|
220
213
|
const key = decodeURIComponent(url.hash.slice(1));
|
|
221
|
-
|
|
214
|
+
if (key && key !== S.current) void openConversation(key);
|
|
222
215
|
});
|
|
223
216
|
}
|
|
224
217
|
shellBooted();
|
|
@@ -283,7 +276,7 @@ function renderLayout() {
|
|
|
283
276
|
{ class: "side-top" },
|
|
284
277
|
h("button", { class: "btn new-chat", onclick: () => (newDraft({ inheritLatest: true }), closeSide()) }, icon("plus"), "新建"),
|
|
285
278
|
),
|
|
286
|
-
createSidebarNav({
|
|
279
|
+
createSidebarNav({ search: openSearch, tasks: openTasksView, library: openLibraryView, remote: openRemoteView, settings: openSettings }),
|
|
287
280
|
ui.convList,
|
|
288
281
|
// 底部只有额度:没有额度可显示(关了查询、还没查到)时整块藏起来,连分隔线一起
|
|
289
282
|
(ui.sideBottom = h(
|
package/web/views/sidebar-nav.js
CHANGED
|
@@ -6,7 +6,6 @@ import { remoteTabs, S, ui } from "../state.js";
|
|
|
6
6
|
const ITEMS = [
|
|
7
7
|
{ id: "search", label: "搜索", icon: "search" },
|
|
8
8
|
{ id: "tasks", label: "定时任务", icon: "clock" },
|
|
9
|
-
{ id: "assistants", label: "bot", icon: "chat" },
|
|
10
9
|
{ id: "library", label: "资料库", icon: "library" },
|
|
11
10
|
{ id: "remote", label: "远程控制", icon: "monitor" },
|
|
12
11
|
{ id: "settings", label: "设置", icon: "gear" },
|
package/web/views/tasks.js
CHANGED
|
@@ -36,8 +36,6 @@ const STATUS = {
|
|
|
36
36
|
interrupted: { text: "中断", cls: "bad" },
|
|
37
37
|
};
|
|
38
38
|
|
|
39
|
-
export const runStatusText = (status) => STATUS[status]?.text ?? status;
|
|
40
|
-
|
|
41
39
|
const FREQS = [
|
|
42
40
|
["once", "一次"],
|
|
43
41
|
["daily", "每天"],
|
|
@@ -466,12 +464,12 @@ export function openTaskForm(task, preset) {
|
|
|
466
464
|
if (!T.channels) void api("/api/tasks").then((d) => ((T.channels = d.channels ?? null), renderPush()), () => {});
|
|
467
465
|
|
|
468
466
|
// ---- 结果发到哪 ----
|
|
469
|
-
const currentTarget =
|
|
467
|
+
const currentTarget = task?.target?.kind === "conv" ? task.target.key : "dedicated";
|
|
470
468
|
const target = h(
|
|
471
469
|
"select",
|
|
472
470
|
{ class: "task-target" },
|
|
473
471
|
h("option", { value: "dedicated", selected: currentTarget === "dedicated" }, task?.target?.kind === "dedicated" && task.convKey ? `专用对话「${task.convTitle || "对话"}」` : "专用对话(第一次运行时新建,之后都发到这条)"),
|
|
474
|
-
currentTarget !== "dedicated" ? h("option", { value: currentTarget, selected: true }, `对话「${convTargetInfo(currentTarget,
|
|
472
|
+
currentTarget !== "dedicated" ? h("option", { value: currentTarget, selected: true }, `对话「${convTargetInfo(currentTarget, task)?.title || "对话"}」`) : null,
|
|
475
473
|
targetChoices(currentTarget).map((c) => h("option", { value: c.key }, `对话「${c.title || "未命名"}」`)),
|
|
476
474
|
);
|
|
477
475
|
const picked = src.expert ?? src.agent ?? S.draftExpert;
|
|
@@ -540,7 +538,7 @@ export function openTaskForm(task, preset) {
|
|
|
540
538
|
let convPermission = null;
|
|
541
539
|
const syncConvBox = () => {
|
|
542
540
|
convPermission = null;
|
|
543
|
-
const info = target.value === "dedicated" ? null : convTargetInfo(target.value,
|
|
541
|
+
const info = target.value === "dedicated" ? null : convTargetInfo(target.value, task);
|
|
544
542
|
if (!info) return fill(convBox);
|
|
545
543
|
const label = PERMISSIONS[info.permission]?.label ?? "默认";
|
|
546
544
|
const levels = info.max ? permissionsUpTo(info.max, info.expert?.engine) : [];
|
|
@@ -624,7 +622,7 @@ export function openTaskForm(task, preset) {
|
|
|
624
622
|
return;
|
|
625
623
|
}
|
|
626
624
|
const convLevel = convPermission?.value;
|
|
627
|
-
const convInfo = dedicated ? null : convTargetInfo(target.value,
|
|
625
|
+
const convInfo = dedicated ? null : convTargetInfo(target.value, task);
|
|
628
626
|
const convLevelChanged = !!convLevel && convLevel !== convInfo?.permission;
|
|
629
627
|
if (convLevelChanged && convLevel === "full" && !(await confirmDialog(FULL_WARNING))) return;
|
|
630
628
|
const fresh = context.value === "fresh";
|
|
@@ -641,7 +639,6 @@ export function openTaskForm(task, preset) {
|
|
|
641
639
|
return;
|
|
642
640
|
}
|
|
643
641
|
const payload = {
|
|
644
|
-
...(!task && preset?.assistantKey ? { assistantKey: preset.assistantKey } : {}),
|
|
645
642
|
title: title.value,
|
|
646
643
|
prompt: prompt.value,
|
|
647
644
|
schedule,
|
package/src/bot-event-runner.ts
DELETED
|
@@ -1,131 +0,0 @@
|
|
|
1
|
-
// 外部投递在事件落盘后执行。网络重试不重新分析,进程重启也不重放已发起的模型轮次。
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { backupEvents } from "./core/backup.js";
|
|
4
|
-
import { acceptResult, botEvents, getWatch, reasons, type Incident, type Watch } from "./core/bot-events.js";
|
|
5
|
-
import { sql, transaction } from "./core/db.js";
|
|
6
|
-
import { listLinks } from "./core/feishu-links.js";
|
|
7
|
-
import { hub } from "./core/hub.js";
|
|
8
|
-
import { flushStore, getConversation, updateConversation } from "./core/store.js";
|
|
9
|
-
import { getUser } from "./core/users.js";
|
|
10
|
-
import { feishuBots } from "./channels/feishu/index.js";
|
|
11
|
-
import { pushToAll } from "./channels/web/push.js";
|
|
12
|
-
|
|
13
|
-
export function watchAvailable(w: Watch): boolean {
|
|
14
|
-
const user = getUser(w.owner);
|
|
15
|
-
const c = getConversation(w.conv);
|
|
16
|
-
return !!user && !user.disabled && (w.source !== "backup" || user.role === "admin")
|
|
17
|
-
&& !!c && c.owner === user.id && c.assistant === "active" && !c.hidden && !hub.assistantUnavailable(c);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
function onBackup(runId: string, ok: boolean, error = ""): void {
|
|
21
|
-
const reason = /ENOSPC/i.test(error) ? "disk_full" : /EACCES|EPERM/i.test(error) ? "permission" : /EIO/i.test(error) ? "io" : "unknown";
|
|
22
|
-
try {
|
|
23
|
-
const ids = sql("SELECT id FROM bot_watches WHERE source='backup'").all() as { id: string }[];
|
|
24
|
-
for (const { id } of ids) {
|
|
25
|
-
const w = getWatch(id);
|
|
26
|
-
if (w && watchAvailable(w)) {
|
|
27
|
-
try { acceptResult(w, { runId, status: ok ? "ok" : "failed", reason }); }
|
|
28
|
-
catch (err) { console.error("[bot] 记录本机备份事件失败", err); }
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
} catch (err) { console.error("[bot] 读取备份监听失败", err); }
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
async function notify(w: Watch, e: Incident): Promise<void> {
|
|
35
|
-
const title = w.name + " · 备份失败";
|
|
36
|
-
const body = reasons[e.reason] + "(" + e.run + ")";
|
|
37
|
-
if (w.destination === "web") {
|
|
38
|
-
const sent = await pushToAll({ title, body, tag: "bot-event-" + e.id, url: "/#bot-events/" + w.id }, (owner) => owner === w.owner);
|
|
39
|
-
if (!sent) throw new Error("没有设备接受 Web 推送");
|
|
40
|
-
return;
|
|
41
|
-
}
|
|
42
|
-
const link = listLinks(w.owner).find((l) => "feishu:" + l.botId === w.destination);
|
|
43
|
-
const bot = link && feishuBots().find((b) => b.id === link.botId);
|
|
44
|
-
if (!bot || !link) throw new Error("飞书绑定或机器人不可用");
|
|
45
|
-
if (!await bot.client.sendText(link.openId, title + "\n" + body, "open_id", w.id + "-" + e.id)) throw new Error("飞书未确认接收");
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function analyze(w: Watch, e: Incident): void {
|
|
49
|
-
const parent = getConversation(w.conv)!;
|
|
50
|
-
const key = "web:" + randomUUID();
|
|
51
|
-
// 先保存独立对话与派发记录。外部上报的自由文本和运行编号均不进入模型指令。
|
|
52
|
-
const claimed = transaction(() => {
|
|
53
|
-
const claim = sql("UPDATE bot_incidents SET analysis='submitted',analysis_key=? WHERE id=? AND analysis='pending'").run(key, e.id);
|
|
54
|
-
if (!claim.changes) return false;
|
|
55
|
-
hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: parent.agent, expert: parent.expert,
|
|
56
|
-
owner: w.owner, assistant: "related", cwd: parent.cwd, title: w.name + " · 故障分析" });
|
|
57
|
-
updateConversation(key, { permission: "ask", titleAuto: false });
|
|
58
|
-
flushStore();
|
|
59
|
-
return true;
|
|
60
|
-
});
|
|
61
|
-
if (!claimed) return;
|
|
62
|
-
hub.send(key, { text: "备份失败。监听名称:" + w.name + "。已知原因:" + reasons[e.reason] +
|
|
63
|
-
"。根据这些已知信息说明可能原因和排查步骤,区分推测和事实。这次只给分析建议,不修改系统。", attachments: [] },
|
|
64
|
-
{ channel: "bot-event", channelId: w.id, name: "bot 事件" });
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
let timer: NodeJS.Timeout | undefined;
|
|
68
|
-
let draining = false;
|
|
69
|
-
let again = false;
|
|
70
|
-
let generation = 0;
|
|
71
|
-
export async function drainBotEvents(): Promise<void> {
|
|
72
|
-
if (draining) { again = true; return; }
|
|
73
|
-
draining = true;
|
|
74
|
-
const started = generation;
|
|
75
|
-
try {
|
|
76
|
-
const now = Date.now();
|
|
77
|
-
const events = sql("SELECT * FROM bot_incidents WHERE (delivery='pending' AND next_try<=?) OR analysis='pending' ORDER BY id LIMIT 32").all(now) as Incident[];
|
|
78
|
-
for (const event of events) {
|
|
79
|
-
if (started !== generation) break;
|
|
80
|
-
const w = getWatch(event.watch);
|
|
81
|
-
if (!w) continue;
|
|
82
|
-
if (!watchAvailable(w)) {
|
|
83
|
-
sql("UPDATE bot_incidents SET delivery=CASE WHEN delivery='pending' THEN 'cancelled' ELSE delivery END, analysis=CASE WHEN analysis='pending' THEN 'cancelled' ELSE analysis END WHERE id=?").run(event.id);
|
|
84
|
-
botEvents.emit("changed", w.owner);
|
|
85
|
-
continue;
|
|
86
|
-
}
|
|
87
|
-
if (event.analysis === "pending") {
|
|
88
|
-
try { analyze(w, event); }
|
|
89
|
-
catch { sql("UPDATE bot_incidents SET analysis='error' WHERE id=?").run(event.id); }
|
|
90
|
-
}
|
|
91
|
-
if (event.delivery === "pending" && event.next_try <= now) {
|
|
92
|
-
// 先认领再交给渠道。进程在发送途中退出时,租约到期即可继续投递。
|
|
93
|
-
const lease = Date.now() + 120_000;
|
|
94
|
-
const claimed = sql("UPDATE bot_incidents SET attempts=attempts+1,next_try=? WHERE id=? AND delivery='pending' AND attempts=? AND next_try<=?")
|
|
95
|
-
.run(lease, event.id, event.attempts, now);
|
|
96
|
-
if (!claimed.changes) continue;
|
|
97
|
-
try {
|
|
98
|
-
await notify(w, event);
|
|
99
|
-
sql("UPDATE bot_incidents SET delivery='sent',error=NULL WHERE id=? AND next_try=?").run(event.id, lease);
|
|
100
|
-
} catch (err) {
|
|
101
|
-
const attempts = event.attempts + 1;
|
|
102
|
-
sql("UPDATE bot_incidents SET delivery=?,error=?,next_try=? WHERE id=? AND next_try=?")
|
|
103
|
-
.run(attempts >= 4 ? "failed" : "pending", err instanceof Error ? err.message : "投递失败", Date.now() + 30_000 * 2 ** (attempts - 1), event.id, lease);
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
botEvents.emit("changed", w.owner);
|
|
107
|
-
}
|
|
108
|
-
} finally {
|
|
109
|
-
draining = false;
|
|
110
|
-
if (again && timer) { again = false; wake(); }
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
function wake(): void {
|
|
114
|
-
void drainBotEvents().catch((err) => console.error("[bot] 处理事件失败", err));
|
|
115
|
-
}
|
|
116
|
-
export function startBotEvents(): void {
|
|
117
|
-
if (timer) return;
|
|
118
|
-
timer = setInterval(wake, 15_000);
|
|
119
|
-
timer.unref();
|
|
120
|
-
botEvents.on("ready", wake);
|
|
121
|
-
backupEvents.on("finished", onBackup);
|
|
122
|
-
wake();
|
|
123
|
-
}
|
|
124
|
-
export function stopBotEvents(): void {
|
|
125
|
-
generation++;
|
|
126
|
-
again = false;
|
|
127
|
-
clearInterval(timer);
|
|
128
|
-
timer = undefined;
|
|
129
|
-
botEvents.off("ready", wake);
|
|
130
|
-
backupEvents.off("finished", onBackup);
|
|
131
|
-
}
|
|
@@ -1,82 +0,0 @@
|
|
|
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/core/bot-events.ts
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
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
|
-
}
|
package/web/views/assistants.js
DELETED
|
@@ -1,82 +0,0 @@
|
|
|
1
|
-
import { api } from "../lib/api.js";
|
|
2
|
-
import { fill, h, toast } from "../lib/dom.js";
|
|
3
|
-
import { confirmDialog, modal } from "../lib/overlay.js";
|
|
4
|
-
import { expertChoices, expertIcon } from "./experts.js";
|
|
5
|
-
import { openConversation } from "./messages.js";
|
|
6
|
-
import { closeSide } from "./sidebar.js";
|
|
7
|
-
import { openBotEvents } from "./bot-events.js";
|
|
8
|
-
import { editTaskById, openTaskForm, runStatusText } from "./tasks.js";
|
|
9
|
-
|
|
10
|
-
/** 每次打开读取本账号的联系人。多设备改变任务时刷新正在查看的列表。 */
|
|
11
|
-
export function openAssistants() {
|
|
12
|
-
closeSide();
|
|
13
|
-
const body = h("div", { class: "modal-body assistant-list", "aria-live": "polite" });
|
|
14
|
-
const controller = new AbortController();
|
|
15
|
-
const dismiss = modal({ title: "bot", body, beforeClose: () => controller.abort() });
|
|
16
|
-
const close = () => { controller.abort(); dismiss(); };
|
|
17
|
-
let generation = 0;
|
|
18
|
-
|
|
19
|
-
const open = (key) => { close(); void openConversation(key); };
|
|
20
|
-
const button = (label, action, disabled = false) => h("button", { class: "btn", disabled, onclick: action }, label);
|
|
21
|
-
|
|
22
|
-
async function remove(assistant) {
|
|
23
|
-
if (!await confirmDialog({ title: "移除这个 bot?", message: "将删除这个 bot 的事件监听和事件记录。已有定时任务继续运行,聊天记录会保留。重新添加这个专家可以接着聊。", confirmText: "移除" })) return;
|
|
24
|
-
try {
|
|
25
|
-
await api("/api/assistants", { method: "DELETE", body: { key: assistant.key } });
|
|
26
|
-
await load();
|
|
27
|
-
} catch (err) { toast(err.message); }
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
function taskRow(t) {
|
|
31
|
-
const state = t.pending ? "待你处理" : t.last ? runStatusText(t.last.status) : "尚未运行";
|
|
32
|
-
const next = t.enabled && t.nextRunAt ? "下次 " + new Date(t.nextRunAt).toLocaleString() : "已停用";
|
|
33
|
-
return h("div", { class: "assistant-task" },
|
|
34
|
-
h("div", { class: "grow" }, h("strong", {}, t.title), h("small", {}, state + " · " + next),
|
|
35
|
-
t.last?.preview || t.last?.note ? h("small", {}, t.last.preview || t.last.note) : null),
|
|
36
|
-
t.resultKey ? button("查看对话", () => open(t.resultKey)) : null,
|
|
37
|
-
button("编辑", () => { close(); void editTaskById(t.id); }));
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
function contact(a) {
|
|
41
|
-
const label = a.expert.missing ? a.title || "已失效的 bot" : a.expert.name;
|
|
42
|
-
return h("section", { class: "assistant-card" },
|
|
43
|
-
h("div", { class: "assistant-row" }, expertIcon({ ...a.expert, engine: a.agent }),
|
|
44
|
-
h("strong", { class: "grow" }, label),
|
|
45
|
-
button(a.pending ? "待你处理 · " + a.pending : a.unavailable ? "查看历史" : "打开对话", () => open(a.key)),
|
|
46
|
-
button("移除", () => void remove(a))),
|
|
47
|
-
a.unavailable || a.busy ? h("small", {}, a.unavailable || "正在回复") : null,
|
|
48
|
-
h("div", { class: "assistant-row" }, h("span", { class: "grow" }, "定时任务(" + a.tasks.length + ")"),
|
|
49
|
-
button("事件监听", () => { close(); openBotEvents({ key: a.key }); }),
|
|
50
|
-
button("新建任务", () => {
|
|
51
|
-
close();
|
|
52
|
-
openTaskForm(null, { assistantKey: a.key, expert: a.expert.id, cwd: a.cwd, target: { kind: "conv", key: a.key }, convKey: a.key, convTitle: label, convExpert: { ...a.expert, engine: a.agent }, convCwd: a.cwd, convPermission: a.permission, convPermissionMax: a.permissionMax });
|
|
53
|
-
}, !!a.unavailable)),
|
|
54
|
-
a.tasks.map(taskRow));
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
async function load() {
|
|
58
|
-
const current = ++generation;
|
|
59
|
-
try {
|
|
60
|
-
const { assistants } = await api("/api/assistants");
|
|
61
|
-
if (current !== generation || !body.isConnected) return;
|
|
62
|
-
const choices = expertChoices().filter((e) => !assistants.some((a) => a.expert.id === e.id));
|
|
63
|
-
const select = h("select", { "aria-label": "选择 bot 专家" }, choices.map((e) => h("option", { value: e.id }, e.name)));
|
|
64
|
-
if (!choices.length) select.append(h("option", {}, "没有更多可添加的专家"));
|
|
65
|
-
const add = button("添加 bot", async () => {
|
|
66
|
-
add.disabled = true;
|
|
67
|
-
try {
|
|
68
|
-
await api("/api/assistants", { method: "POST", body: { expert: select.value } });
|
|
69
|
-
await load();
|
|
70
|
-
} catch (err) { toast(err.message); add.disabled = false; }
|
|
71
|
-
}, !choices.length);
|
|
72
|
-
fill(body, h("div", { class: "assistant-row" }, select, add),
|
|
73
|
-
assistants.length ? assistants.map(contact) : h("p", {}, "选一个专家作为 bot,即可在这里找到它的对话和定时任务。"),
|
|
74
|
-
h("small", {}, "在已绑定账号的飞书私聊发送 /bot,可接着和 bot 聊。"));
|
|
75
|
-
} catch (err) {
|
|
76
|
-
if (body.isConnected && current === generation) fill(body, h("p", {}, err.message), button("重试", load));
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
for (const event of ["aim:tasks", "aim:experts"]) document.addEventListener(event, load, { signal: controller.signal });
|
|
81
|
-
void load();
|
|
82
|
-
}
|