agent-loft 0.2.122 → 0.2.124

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.
@@ -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" },
@@ -29,7 +28,7 @@ function configuredItems() {
29
28
  }
30
29
 
31
30
  const available = (item) => item.id !== "remote" || remoteTabs().length > 0;
32
- const isActive = (item) => ["tasks", "library", "remote"].includes(item.id) && S.view === item.id;
31
+ const isActive = (item) => (ui.settings ? "settings" : S.view) === item.id;
33
32
  const remoteLive = () => S.remoteLive.desktop || S.remoteLive.terminals > 0;
34
33
 
35
34
  function navButton(item, inMenu = false) {
@@ -1,6 +1,6 @@
1
1
  import { fill, h, icon, ICON, toast } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
- import { desktop, S, ui } from "../state.js";
3
+ import { contentHash, desktop, S, ui } from "../state.js";
4
4
  import { baseName } from "./topbar.js";
5
5
  import { newDraft, openConversation } from "./messages.js";
6
6
  import { convExpert, expertIcon, setDraftExpert } from "./experts.js";
@@ -442,7 +442,7 @@ function weixinState(id) {
442
442
  export function bootstrapQuery() {
443
443
  const q = new URLSearchParams({ recent: String(pages.recent.show), open: JSON.stringify(sideState.open.map((d) => [d, dirState(d).show])) });
444
444
  // 正开着的会话;刚打开页面时是地址里带的那条(可能在后面几页)
445
- const current = S.current ?? decodeURIComponent(location.hash.slice(1));
445
+ const current = S.current ?? decodeURIComponent(contentHash().slice(1));
446
446
  if (current) q.set("current", current);
447
447
  return `?${q}`;
448
448
  }
@@ -558,7 +558,8 @@ export function renderSidebar() {
558
558
  : keys.some((k) => S.convs.get(k)?.busy)
559
559
  ? h("span", { class: "conv-spin", title: "进行中" })
560
560
  : null;
561
- const open = (key) => {
561
+ const open = async (key) => {
562
+ if (ui.settings && !(await ui.settings.close())) return;
562
563
  closeSide();
563
564
  if (key !== S.current) void openConversation(key);
564
565
  // 在远程控制页上点进来之前那条对话:对话没动过,退出远程控制就露出来了
@@ -570,7 +571,7 @@ export function renderSidebar() {
570
571
  h(
571
572
  "button",
572
573
  {
573
- class: `conv-item${cls}${c.key === S.current && !S.view ? " active" : ""}`,
574
+ class: `conv-item${cls}${c.key === S.current && !S.view && !ui.settings ? " active" : ""}`,
574
575
  "data-key": c.key,
575
576
  title: `${convTitle(c)}${forkNote(c)}\n${detail}\n双击重命名,右键更多操作`,
576
577
  onclick: () => open(c.key),
@@ -745,6 +746,7 @@ export function renderSidebar() {
745
746
  title: `在 ${baseName(dir)} 中开新对话`,
746
747
  onclick: async (e) => {
747
748
  const button = e.currentTarget;
749
+ if (ui.settings && !(await ui.settings.close())) return;
748
750
  button.disabled = true;
749
751
  try {
750
752
  let latest = convs[0];
@@ -2,7 +2,7 @@ import { fill, h, icon, starsLoader, toast } from "../lib/dom.js";
2
2
  import { api } from "../lib/api.js";
3
3
  import { clockTime } from "../lib/time.js";
4
4
  import { confirmDialog, modal, showMenu } from "../lib/overlay.js";
5
- import { isAdmin, S, ui } from "../state.js";
5
+ import { isAdmin, S, setContentHash, ui } from "../state.js";
6
6
  import { WS } from "../lib/ws.js";
7
7
  import { agentLabel, closeSide, renderSidebar } from "./sidebar.js";
8
8
  import { baseName, renderTopbar } from "./topbar.js";
@@ -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", "每天"],
@@ -99,7 +97,7 @@ export async function openTasks() {
99
97
  S.view = "tasks";
100
98
  S.items = [];
101
99
  S.turnAi = null;
102
- history.replaceState(history.state, "", "#tasks");
100
+ setContentHash("#tasks");
103
101
  WS.presence();
104
102
  ui.spacer.style.height = "0px";
105
103
  // 对话页的「贴底跟随」在这里不要:内容一变它就会滚到最底下
@@ -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 = src.target?.kind === "conv" ? src.target.key : "dedicated";
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, src)?.title || "对话"}」`) : null,
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, src);
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, src);
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,
@@ -250,9 +250,9 @@ let desktopActions = new Map();
250
250
  let desktopMenuSig = "";
251
251
 
252
252
  /** 会话操作菜单变了就报给桌面端。 */
253
- function syncDesktopMenu() {
253
+ export function syncDesktopMenu() {
254
254
  if (!desktopMenu) return;
255
- const items = topMenuItems();
255
+ const items = ui.settings ? [] : topMenuItems();
256
256
  desktopActions = new Map(items.filter((it) => it !== "sep").map((it) => [it.id, it.onclick]));
257
257
  const menu = {
258
258
  items: items.map((it) => (it === "sep" ? { type: "separator" } : { id: it.id, label: it.detail && !it.detail.hidden ? `${it.label} ${it.detail.textContent}` : it.label, ...(it.checked !== undefined ? { checked: it.checked } : {}) })),
@@ -521,7 +521,14 @@ function handoffItem(c) {
521
521
  icon: "handoff",
522
522
  disabled: !c.canHandoff,
523
523
  disabledReason: "这条对话还没有可以交接的内容",
524
- children: targets.map((e) => ({ label: e.name, leading: expertIcon(e), onclick: () => handoffConversation(e, c.key) })),
524
+ children: targets.map((e) => ({
525
+ label: e.name,
526
+ leading: expertIcon(e),
527
+ onclick: async () => {
528
+ if (ui.settings && !(await ui.settings.close())) return;
529
+ await handoffConversation(e, c.key);
530
+ },
531
+ })),
525
532
  },
526
533
  ];
527
534
  }
@@ -545,6 +552,7 @@ function convMenuItems(key) {
545
552
  label: "分叉",
546
553
  icon: "fork",
547
554
  onclick: async () => {
555
+ if (ui.settings && !(await ui.settings.close())) return;
548
556
  if (c.canFork) return forkConversation(undefined, key);
549
557
  // 不支持另开一条的:只能在原对话里分叉,先切过去
550
558
  if (key !== S.current) await openConversation(key);
@@ -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
- }
@@ -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
- }
@@ -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
- }
@@ -1,96 +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 { openConversation } from "./messages.js";
5
-
6
- const path = "/api/bot-events";
7
- const state = { inbox: "已记入事件记录", pending: "等待投递", sent: "已投递", failed: "投递失败", cancelled: "已取消" };
8
- const option = (value, label) => h("option", { value }, label);
9
- const button = (label, onclick) => h("button", { class: "btn", type: "button", onclick }, label);
10
-
11
- function credentials(token) {
12
- const field = h("input", { "aria-label": "Webhook 令牌", type: "password", readonly: true, value: token, autocomplete: "off" });
13
- const reveal = button("显示令牌", () => {
14
- field.type = field.type === "password" ? "text" : "password";
15
- reveal.textContent = field.type === "password" ? "显示令牌" : "隐藏令牌";
16
- field.select();
17
- });
18
- modal({ title: "接入备份作业", body: h("div", { class: "modal-body assistant-list" },
19
- h("label", {}, "上报地址", h("input", { readonly: true, value: location.origin + path + "/receive" })),
20
- h("label", {}, "Webhook 令牌(仅本次可查看)", field), reveal,
21
- h("small", {}, "作业结束时用 POST 提交 JSON,请求头使用 Authorization: Bearer <令牌>。同一次运行重试时沿用 runId。"),
22
- h("code", {}, '{"runId":"backup-001","status":"failed","reason":"disk_full"}')) });
23
- }
24
-
25
- function addForm(settings, reload) {
26
- const name = h("input", { required: true, maxlength: 60, placeholder: "例如:NAS 夜间备份" });
27
- const source = h("select", {}, option("webhook", "外部备份 Webhook"), settings.admin ? option("backup", "本机数据库备份") : null);
28
- const destination = h("select", {}, option("inbox", "只写入事件记录"), option("web", "Web 系统推送"),
29
- settings.feishu.map((b) => option("feishu:" + b.id, "飞书 · " + b.name)));
30
- const analyze = h("input", { type: "checkbox" });
31
- const save = h("button", { class: "btn primary", type: "submit" }, "创建监听");
32
- const form = h("form", { class: "modal-body assistant-list" },
33
- h("label", {}, "名称", name), h("label", {}, "来源", source), h("label", {}, "发现新失败时", destination),
34
- h("label", {}, analyze, " 同时让 bot 分析故障"), save);
35
- const close = modal({ title: "新增事件监听", body: form });
36
- form.addEventListener("submit", async (e) => {
37
- e.preventDefault();
38
- if (save.disabled) return;
39
- save.disabled = true;
40
- try {
41
- const { token } = await api(path, { method: "POST", body: { key: settings.key, name: name.value, source: source.value, destination: destination.value, analyze: analyze.checked } });
42
- close();
43
- if (token) credentials(token);
44
- void reload();
45
- } catch (err) { toast(err.message); save.disabled = false; }
46
- });
47
- }
48
-
49
- export function openBotEvents(query) {
50
- const body = h("div", { class: "modal-body assistant-list", "aria-live": "polite" }, "正在读取事件…");
51
- const controller = new AbortController();
52
- const dismiss = modal({ title: "bot 事件监听", body, beforeClose: () => controller.abort() });
53
- let generation = 0;
54
- async function retry(w, e) {
55
- try { await api(path + "/" + w.id + "/retry/" + e.id, { method: "POST" }); await load(); }
56
- catch (err) { toast(err.message); }
57
- }
58
- function incident(w, e) {
59
- return h("div", { class: "assistant-task" }, h("div", { class: "grow" },
60
- h("strong", {}, e.reason), h("small", {}, new Date(e.at).toLocaleString() + " · " + e.run),
61
- h("small", {}, [state[e.delivery], e.error, e.analysis === "error" ? "分析启动失败" : null].filter(Boolean).join(" · "))),
62
- e.analysisKey ? button("查看分析", () => { controller.abort(); dismiss(); void openConversation(e.analysisKey); }) : null,
63
- e.delivery === "failed" ? button("重试投递", () => void retry(w, e)) : null);
64
- }
65
- async function remove(w, key) {
66
- if (!await confirmDialog({ title: "删除监听?", message: "会停止接收这项作业的结果,并清除该监听的事件记录。", confirmText: "删除" })) return;
67
- try {
68
- await api(path + "/" + w.id, { method: "DELETE" });
69
- query = { key };
70
- await load();
71
- } catch (err) { toast(err.message); }
72
- }
73
- async function load() {
74
- const current = ++generation;
75
- try {
76
- const data = await api(path + "?" + new URLSearchParams(query));
77
- if (current !== generation || !body.isConnected) return;
78
- const watches = data.watches.slice().sort((a, b) => Number(b.id === query.watch) - Number(a.id === query.watch));
79
- fill(body, data.unavailable ? h("p", {}, data.unavailable) : button("新增监听", () => addForm(data, load)),
80
- watches.length ? watches.map((w) => {
81
- const dest = w.destination === "web" ? "Web 系统推送" : w.destination === "inbox" ? "只记入事件记录" :
82
- "飞书 · " + (data.feishu.find((b) => "feishu:" + b.id === w.destination)?.name || "绑定不可用");
83
- const latest = w.lastSeen ? "最近上报" + (w.lastStatus === "ok" ? "成功" : "失败") + " · " + new Date(w.lastSeen).toLocaleString() : "尚未收到上报";
84
- return h("section", { class: "assistant-card" }, h("div", { class: "assistant-row" },
85
- h("strong", { class: "grow" }, w.name), button("删除监听", () => void remove(w, data.key))),
86
- h("small", {}, [w.source === "backup" ? "本机数据库备份" : "外部备份 Webhook", dest, w.analyze ? "自动分析" : null].filter(Boolean).join(" · ")),
87
- h("small", {}, latest), w.events.map((e) => incident(w, e)));
88
- }) : h("p", {}, "暂无监听。添加备份作业后,可以在这里查看最近的失败记录。"),
89
- button("刷新记录", load));
90
- } catch (err) {
91
- if (body.isConnected && current === generation) fill(body, h("p", {}, err.message), button("重新加载", load));
92
- }
93
- }
94
- document.addEventListener("aim:bot-events", load, { signal: controller.signal });
95
- void load();
96
- }