agent-loft 0.2.120 → 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/messages.js +14 -1
- package/web/views/sidebar-nav.js +1 -0
- package/web/views/tasks.js +7 -4
package/README.md
CHANGED
|
@@ -36,6 +36,21 @@ Logo 是白底的三向汇合:橘红、暖橙和珊瑚红三个单元,表达
|
|
|
36
36
|
|
|
37
37
|
## 能做什么
|
|
38
38
|
|
|
39
|
+
**bot** 打开 Web 侧栏的「bot」,选择已有专家并点击「添加 bot」。每个 bot 有固定聊天,可以查看交给它的定时任务、最近结果和待处理请求。在已绑定账号的飞书私聊发送 `/bot` 接着聊,发送 `/detach` 退出续聊。定时任务沿用各自的推送设置。移除 bot 联系人后,已有任务继续运行。
|
|
40
|
+
|
|
41
|
+
**备份事件监听** 在「bot → 事件监听 → 新增监听」选择作业来源。管理员可以直接监听 agent-loft 的数据库备份。外部作业选择「外部备份 Webhook」,在上报端将地址保存为 `BOT_EVENT_URL`,将仅显示一次的令牌保存为 `BOT_EVENT_TOKEN`。作业结束时可这样上报。
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
curl --fail-with-body "$BOT_EVENT_URL" \
|
|
45
|
+
-H "Authorization: Bearer $BOT_EVENT_TOKEN" \
|
|
46
|
+
-H 'Content-Type: application/json' \
|
|
47
|
+
--data '{"runId":"nas-nightly-20261118","status":"failed","reason":"disk_full"}'
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`runId` 由作业生成,同一次运行的重投沿用同一个值。成功上报 `status: "ok"`,失败上报 `"failed"`。可选的 `reason` 支持 `disk_full`、`offline`、`permission`、`io` 和 `unknown`。网络失败、HTTP 429 或 5xx 时,上报端应保留未确认结果并延后重试。
|
|
51
|
+
|
|
52
|
+
每条监听默认只记录新失败。也可选择 Web 系统推送或已绑定的飞书私聊,并独立勾选「同时让 bot 分析故障」。成功和重复失败均不调用模型。事件页显示最近一次上报和最近 12 条失败。作业停止上报时,仍显示最后一次收到的时间。投递失败最多自动尝试四次,之后可在事件页手动重试。删除监听或移除 bot 会使令牌失效并清除对应事件记录。
|
|
53
|
+
|
|
39
54
|
- **多个 agent**:Claude Code、Codex、WorkBuddy、pi、dsh。几个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
|
|
40
55
|
- **WorkBuddy(腾讯)**:默认不启用。调用这台服务器上 **WorkBuddy 桌面版自带的 CLI**(官方 Agent SDK `@tencent-ai/agent-sdk` 驱动,账号站点 www.workbuddy.cn),也可以改用 CodeBuddy 国内版 / 国际版 / 腾讯 iOA 的账号(用 SDK 自带的 CLI,不用装桌面版)。到 设置 → Agent → WorkBuddy 勾上「启用」、选账号站点后保存,再在「运行环境」里点「登录 WorkBuddy」:在你自己的浏览器里打开登录页,**1 分钟内**登录完(CLI 只等这么久,超时重新点),整台服务器登一次就行,所有人共用。桌面版里登录过也要在这里再登一次(同一个账号):桌面版的登录由它自己保管,不交给单独跑的 CLI;这边的令牌存在 `data/workbuddy-auth.json`(0600),不碰桌面版的数据。也可以给服务设 `CODEBUDDY_API_KEY`。支持流式回复、授权卡(逐次询问 / 自动改文件 / 完全允许)、提问卡、计划模式、中途换模型、图片附件、`/sessions` 恢复以前的会话、记忆和定时任务工具、个人技能和 MCP;管理员的会话读机器上的 `~/.codebuddy` 配置,成员只读项目里的。暂不支持自定义专家、分叉 / 回退、思考程度和额度显示;令牌过期后要回设置页重新登录。
|
|
41
56
|
- **pi**:默认不启用。开源编程 agent [pi](https://pi.dev),用官方 TypeScript SDK(`@earendil-works/pi-coding-agent`)在 agent-loft 进程里运行(需要 Node 22.19 以上)。按**模型服务商**配凭据,整台服务器共用:到 设置 → Agent → pi 勾上「启用」,在「模型服务商」里选一家(DeepSeek、智谱 Coding Plan、Kimi、通义 Token Plan、MiniMax、OpenRouter、Anthropic、OpenAI……)粘贴 API Key 保存;或者点「登录」用**订阅账号**(Claude Pro/Max、ChatGPT Plus/Pro、GitHub Copilot、Kimi Code、xAI……),在你自己的浏览器里完成,设备码直接显示在页面上,浏览器登录完跳到打不开的 127.0.0.1 地址时把地址栏整个粘贴回来即可(订阅能否用在第三方工具里以各家条款为准);也可以给服务设对应的环境变量(如 `DEEPSEEK_API_KEY`)。本地模型和 OpenAI 兼容网关在「自定义服务商」里加(Ollama、LM Studio、vLLM、llama.cpp、one-api……,填地址、接口类型、Key,能「从服务读取模型列表」),写在 `data/pi/models.json`(0600,Key 按字面值保存,不会被当成环境变量或命令)。凭据、会话记录都存在 `data/pi/` 下(`auth.json` 0600、`sessions/`),不读也不写机器上的 `~/.pi`;项目里的 `.pi/` 扩展不加载。pi 自己没有权限系统,授权卡(逐次询问 / 自动改文件 / 完全允许)、计划模式、提问卡由 agent-loft 补上,「自动改文件」只放行工作目录和附件目录里的文件;跑命令(bash)没有沙箱。支持流式回复、中途换模型和思考程度、图片附件(模型支持时)、`/compact` 压缩上下文、`/sessions` 恢复、分叉 / 回退、费用显示、记忆和定时任务工具、个人技能和 MCP,记忆整理也可选 pi。可以建 pi 引擎的自定义专家(见下面「专家」)。
|
package/package.json
CHANGED
|
@@ -0,0 +1,131 @@
|
|
|
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
|
+
}
|
|
@@ -9,12 +9,12 @@ import path from "node:path";
|
|
|
9
9
|
import * as Lark from "@larksuiteoapi/node-sdk";
|
|
10
10
|
import { config, type FeishuBotConfig } from "../../core/config.js";
|
|
11
11
|
import { botAgentIds, botExpertIds } from "../../core/feishu-experts.js";
|
|
12
|
-
import { hub, type CommandReply, type EventEnvelope } from "../../core/hub.js";
|
|
12
|
+
import { GLOBAL_ALWAYS_DENIED, hub, type CommandReply, type EventEnvelope } from "../../core/hub.js";
|
|
13
13
|
import { interactions, type Interaction } from "../../core/interactions.js";
|
|
14
14
|
import { parseCommand } from "../../core/commands.js";
|
|
15
15
|
import { Dedup } from "../../core/dedup.js";
|
|
16
16
|
import { isPaired, requestPairing } from "../../core/pairing.js";
|
|
17
|
-
import { getConversation, listConversations, sessionOwner, updateConversation } from "../../core/store.js";
|
|
17
|
+
import { assistantSessionOwner, getConversation, listConversations, sessionOwner, updateConversation, type Conversation } from "../../core/store.js";
|
|
18
18
|
import { adminVisible, getUser, hasMembers, ownedBy, type User } from "../../core/users.js";
|
|
19
19
|
import { linkedUser, redeemLinkCode } from "../../core/feishu-links.js";
|
|
20
20
|
import { adoptFile, KIND_LABEL } from "../../core/uploads.js";
|
|
@@ -48,12 +48,14 @@ type CardResponse = {
|
|
|
48
48
|
|
|
49
49
|
export type BotStatus = { state: string; since: number; error?: string };
|
|
50
50
|
|
|
51
|
-
type FeishuCommand = { kind: "web" } | { kind: "detach" } | { kind: "bind"; code: string };
|
|
51
|
+
type FeishuCommand = { kind: "bot"; page: number } | { kind: "web" } | { kind: "detach" } | { kind: "bind"; code: string };
|
|
52
52
|
|
|
53
53
|
/** 只在飞书里认的命令:挂到 Web 会话上 / 退回来 / 绑定账号。整条消息只有命令才算 */
|
|
54
54
|
function feishuCommandOf(text: string): FeishuCommand | null {
|
|
55
55
|
const t = text.trim().replace(/^//, "/");
|
|
56
56
|
const lower = t.toLowerCase();
|
|
57
|
+
const bot = /^\/bot(?:\s+([1-9]\d{0,5}))?$/.exec(lower);
|
|
58
|
+
if (bot) return { kind: "bot", page: Number(bot[1] ?? 1) };
|
|
57
59
|
if (lower === "/web") return { kind: "web" };
|
|
58
60
|
if (lower === "/detach") return { kind: "detach" };
|
|
59
61
|
const bind = /^\/bind\s+([A-Za-z0-9]{4,16})$/i.exec(t);
|
|
@@ -151,6 +153,7 @@ export class FeishuBot {
|
|
|
151
153
|
const [key] = args;
|
|
152
154
|
const selected = this.expertsFor(key);
|
|
153
155
|
const conv = getConversation(key);
|
|
156
|
+
if (conv?.assistant && !this.controls(key, args[2].chatId)) return;
|
|
154
157
|
if (selected !== undefined && (!conv || !selected.includes(conv.expert ?? conv.agent))) {
|
|
155
158
|
hub.notice(key, "这个聊天的专家已不在机器人的可用列表中,请重新发消息以选择默认专家。");
|
|
156
159
|
return;
|
|
@@ -171,21 +174,26 @@ export class FeishuBot {
|
|
|
171
174
|
}
|
|
172
175
|
|
|
173
176
|
/** feishuKey 这个聊天能不能碰主人是 owner 的东西(Web 会话、agent 会话) */
|
|
174
|
-
private canSee(feishuKey: string,
|
|
177
|
+
private canSee(feishuKey: string, conv: Conversation | undefined): boolean {
|
|
178
|
+
if (!conv) return false;
|
|
175
179
|
const viewer = this.viewerOf(feishuKey);
|
|
176
|
-
|
|
180
|
+
if (conv.assistant) {
|
|
181
|
+
const openId = getConversation(feishuKey)?.boundOpenId;
|
|
182
|
+
return !!viewer && viewer.id === conv.owner && linkedUser(this.cfg.id, openId)?.id === viewer.id;
|
|
183
|
+
}
|
|
184
|
+
return viewer ? ownedBy(viewer, conv.owner) : adminVisible(conv.owner);
|
|
177
185
|
}
|
|
178
186
|
|
|
179
|
-
/** 命令里要用的可见范围:/sessions 列哪些、/resume 能恢复哪些、/approve 能处理哪些 */
|
|
180
187
|
private commandScope(feishuKey: string) {
|
|
181
188
|
const viewer = this.viewerOf(feishuKey);
|
|
189
|
+
const members = hasMembers();
|
|
182
190
|
return {
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
convVisible: (k: string) => this.canSee(feishuKey, getConversation(k)
|
|
191
|
+
sessionVisible: (id: string) => {
|
|
192
|
+
const owner = assistantSessionOwner(id);
|
|
193
|
+
if (owner) return viewer?.id === owner && linkedUser(this.cfg.id, getConversation(feishuKey)?.boundOpenId)?.id === owner;
|
|
194
|
+
return viewer ? ownedBy(viewer, sessionOwner(id)) : !members || adminVisible(sessionOwner(id));
|
|
195
|
+
},
|
|
196
|
+
convVisible: (k: string) => this.canSee(feishuKey, getConversation(k)),
|
|
189
197
|
};
|
|
190
198
|
}
|
|
191
199
|
|
|
@@ -197,13 +205,20 @@ export class FeishuBot {
|
|
|
197
205
|
if (!target) return undefined;
|
|
198
206
|
const conv = getConversation(target);
|
|
199
207
|
// 这个聊天不再能碰它了(主人被降成了普通成员、私聊换了主人):当它没了(下条消息时自动退回来)
|
|
200
|
-
return conv && !conv.hidden && this.canSee(feishuKey, conv
|
|
208
|
+
return conv && !conv.hidden && this.canSee(feishuKey, conv) ? target : undefined;
|
|
201
209
|
}
|
|
202
210
|
|
|
203
211
|
/** 挂在 Web 会话 key 上的本机器人聊天(只算还能碰它的) */
|
|
204
212
|
private watchers(key: string): string[] {
|
|
205
|
-
const
|
|
206
|
-
|
|
213
|
+
const conv = getConversation(key);
|
|
214
|
+
if (!conv || conv.hidden) return [];
|
|
215
|
+
return watchersOf(key, this.prefix).filter((k) => this.canSee(k, conv));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 绑定私聊已经通过续聊收到这次回复时,免去第二条任务推送。 */
|
|
219
|
+
deliversAssistantReply(key: string, openId: string): boolean {
|
|
220
|
+
return !!getConversation(key)?.assistant && this.watchers(key).some((k) =>
|
|
221
|
+
getConversation(k)?.boundOpenId?.trim().toLowerCase() === openId.trim().toLowerCase());
|
|
207
222
|
}
|
|
208
223
|
|
|
209
224
|
/** 这条会话的事件该画到哪些飞书聊天里:自己的那个聊天,加上挂着它的聊天 */
|
|
@@ -270,7 +285,11 @@ export class FeishuBot {
|
|
|
270
285
|
async attachTo(feishuKey: string, webKey: string, operatorOpenId?: string): Promise<string> {
|
|
271
286
|
const conv = getConversation(webKey);
|
|
272
287
|
// 只能接上这个聊天的主人自己的 Web 会话(没主人的聊天:管理员能看的)
|
|
273
|
-
if (!conv || conv.channel !== "web" || conv.hidden || !this.canSee(feishuKey, conv
|
|
288
|
+
if (!conv || conv.channel !== "web" || conv.hidden || !this.canSee(feishuKey, conv)) throw new Error("这条 Web 会话已不存在");
|
|
289
|
+
if (conv.assistant) {
|
|
290
|
+
const issue = hub.assistantUnavailable(conv);
|
|
291
|
+
if (issue) throw new Error(issue);
|
|
292
|
+
}
|
|
274
293
|
const chatId = this.chatIdOf(feishuKey);
|
|
275
294
|
// 本聊天自己的会话也得有:之后 /detach 回来、侧栏里显示机器人都要它
|
|
276
295
|
const allowed = this.allowedAgents();
|
|
@@ -289,6 +308,7 @@ export class FeishuBot {
|
|
|
289
308
|
console.log(`${this.tag} ${feishuKey} 接上 Web 会话 ${webKey}`);
|
|
290
309
|
// 最近几句:读历史可能要一会儿,读不到也不影响接上
|
|
291
310
|
const history = await hub.history(webKey).catch(() => []);
|
|
311
|
+
if (conv.assistant && this.attachedWeb(feishuKey) !== webKey) throw new Error("bot 绑定已变化");
|
|
292
312
|
const recent = history
|
|
293
313
|
.filter((m) => m.role !== "question" && m.text.trim())
|
|
294
314
|
.slice(-4)
|
|
@@ -309,21 +329,30 @@ export class FeishuBot {
|
|
|
309
329
|
const prev = detach(feishuKey);
|
|
310
330
|
if (!prev) return "这个聊天没有接着 Web 会话,本来就在用自己的会话。";
|
|
311
331
|
console.log(`${this.tag} ${feishuKey} 不再接着 Web 会话 ${prev}`);
|
|
312
|
-
const
|
|
332
|
+
const conv = getConversation(prev);
|
|
333
|
+
const title = this.canSee(feishuKey, conv) ? conv?.title : undefined;
|
|
313
334
|
return `已回到这个聊天自己的会话${title ? `,不再接着「${title}」` : ""}。之后发 \`/web\` 可以再接上。`;
|
|
314
335
|
}
|
|
315
336
|
|
|
316
|
-
/**
|
|
317
|
-
private async sendWebList(feishuKey: string, chatId: string): Promise<void> {
|
|
337
|
+
/** /web 列最近的聊天;/bot 的联系人可以翻页。 */
|
|
338
|
+
private async sendWebList(feishuKey: string, chatId: string, assistantPage?: number): Promise<void> {
|
|
339
|
+
const assistants = assistantPage !== undefined;
|
|
318
340
|
const current = this.attachedWeb(feishuKey);
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
341
|
+
const visible = listConversations().filter((c) => c.channel === "web" && !c.hidden
|
|
342
|
+
&& (!assistants || c.assistant === "active") && this.canSee(feishuKey, c));
|
|
343
|
+
const pages = Math.max(1, Math.ceil(visible.length / 10));
|
|
344
|
+
const page = Math.min(assistantPage ?? 1, pages);
|
|
345
|
+
visible.sort(assistants ? (a, b) => a.createdAt - b.createdAt || a.key.localeCompare(b.key) : (a, b) => b.activeAt - a.activeAt);
|
|
346
|
+
const convs = visible.slice((page - 1) * 10, page * 10).map((c) => this.webEntry(c.key)!);
|
|
347
|
+
if (assistants && visible.length === 1) {
|
|
348
|
+
await this.attachTo(feishuKey, convs[0]!.key, getConversation(feishuKey)?.boundOpenId);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
324
351
|
await this.client.sendCard(
|
|
325
352
|
chatId,
|
|
326
353
|
webListCard({
|
|
354
|
+
assistants,
|
|
355
|
+
...(assistants && pages > 1 ? { page, pages } : {}),
|
|
327
356
|
convs,
|
|
328
357
|
...(current ? { current } : {}),
|
|
329
358
|
sessionKey: feishuKey,
|
|
@@ -339,7 +368,7 @@ export class FeishuBot {
|
|
|
339
368
|
detach(feishuKey);
|
|
340
369
|
void this.client.sendCard(
|
|
341
370
|
this.chatIdOf(feishuKey),
|
|
342
|
-
replyCard("之前接着的 Web 会话已经被删除,已回到这个聊天自己的会话。"),
|
|
371
|
+
replyCard(getConversation(target)?.assistant ? "之前接着的 bot 已不可用,已回到这个聊天自己的会话。" : "之前接着的 Web 会话已经被删除,已回到这个聊天自己的会话。"),
|
|
343
372
|
);
|
|
344
373
|
return true;
|
|
345
374
|
}
|
|
@@ -492,11 +521,12 @@ export class FeishuBot {
|
|
|
492
521
|
const id = pairKey(key, chatId);
|
|
493
522
|
let stream = this.streams.get(id);
|
|
494
523
|
if (stream) return stream;
|
|
524
|
+
const allowed = () => !getConversation(key)?.assistant || this.controls(key, chatId);
|
|
495
525
|
stream = new TurnStream({
|
|
496
|
-
sendCard: (card) => this.client.sendCard(chatId, card),
|
|
497
|
-
updateCard: (messageId, card) => this.client.updateCard(messageId, card),
|
|
526
|
+
sendCard: async (card) => allowed() ? this.client.sendCard(chatId, card) : undefined,
|
|
527
|
+
updateCard: async (messageId, card) => allowed() && this.client.updateCard(messageId, card),
|
|
498
528
|
renderProgress: (steps, done, footer) => progressCard({ steps, done, ...(footer ? { footer } : {}) }),
|
|
499
|
-
sendReply: (text) => this.client.sendCard(chatId, replyCard(text)),
|
|
529
|
+
sendReply: async (text) => allowed() ? this.client.sendCard(chatId, replyCard(text)) : undefined,
|
|
500
530
|
onError: (err) => console.error(`${this.tag} 卡片更新失败:`, err),
|
|
501
531
|
});
|
|
502
532
|
this.streams.set(id, stream);
|
|
@@ -571,6 +601,7 @@ export class FeishuBot {
|
|
|
571
601
|
}
|
|
572
602
|
|
|
573
603
|
private async showInteractionIn(i: Interaction, chatId: string): Promise<void> {
|
|
604
|
+
if (getConversation(i.convKey)?.assistant && !this.controls(i.convKey, chatId)) return;
|
|
574
605
|
const messageId = await this.client.sendCard(chatId, this.interactionCard(i, chatId));
|
|
575
606
|
if (!messageId) return;
|
|
576
607
|
const list = this.cards.get(i.id) ?? [];
|
|
@@ -585,7 +616,7 @@ export class FeishuBot {
|
|
|
585
616
|
const list = this.cards.get(i.id);
|
|
586
617
|
if (!list) return;
|
|
587
618
|
if (i.settled) this.cards.delete(i.id);
|
|
588
|
-
await Promise.all(list.map((c) => this.client.updateCard(c.messageId, this.interactionCard(i, c.chatId))));
|
|
619
|
+
await Promise.all(list.filter((c) => !getConversation(i.convKey)?.assistant || this.controls(i.convKey, c.chatId)).map((c) => this.client.updateCard(c.messageId, this.interactionCard(i, c.chatId))));
|
|
589
620
|
}
|
|
590
621
|
|
|
591
622
|
|
|
@@ -671,6 +702,7 @@ export class FeishuBot {
|
|
|
671
702
|
// 群聊不动:群里不止一个人
|
|
672
703
|
const p2p = message.chat_type === "p2p";
|
|
673
704
|
const ownerChanged = p2p && hub.reassignOwner(ownKey, linkedUser(this.cfg.id, operator)?.id);
|
|
705
|
+
if (p2p && conv.owner && conv.boundOpenId !== operator) updateConversation(ownKey, { boundOpenId: operator });
|
|
674
706
|
if (ownerChanged) {
|
|
675
707
|
const owner = this.viewerOf(ownKey);
|
|
676
708
|
console.log(`${this.tag} 私聊 ${ownKey} 的主人变为 ${owner?.name ?? "(无,归管理员)"}`);
|
|
@@ -783,7 +815,14 @@ export class FeishuBot {
|
|
|
783
815
|
sender?: { openId: string; p2p: boolean },
|
|
784
816
|
): Promise<void> {
|
|
785
817
|
try {
|
|
786
|
-
if (cmd.kind === "
|
|
818
|
+
if (cmd.kind === "bot") {
|
|
819
|
+
const own = getConversation(ownKey);
|
|
820
|
+
if (sender?.p2p === false || !own?.owner || linkedUser(this.cfg.id, own.boundOpenId)?.id !== own.owner) {
|
|
821
|
+
await this.client.sendText(chatId, "请先在 Web 添加 bot,再到已绑定账号的飞书私聊发送 /bot。");
|
|
822
|
+
return;
|
|
823
|
+
}
|
|
824
|
+
await this.sendWebList(ownKey, chatId, cmd.page);
|
|
825
|
+
} else if (cmd.kind === "web") await this.sendWebList(ownKey, chatId);
|
|
787
826
|
else if (cmd.kind === "detach") await this.client.sendCard(chatId, replyCard(this.detachFrom(ownKey)));
|
|
788
827
|
else await this.client.sendCard(chatId, replyCard(await this.bind(cmd.code, ownKey, sender)));
|
|
789
828
|
} catch (err) {
|
|
@@ -798,6 +837,7 @@ export class FeishuBot {
|
|
|
798
837
|
if (!sender.p2p) return "请在和我的私聊里发 `/bind 绑定码`(群里别人也看得到绑定码)。绑定码已经露出来了的话,到 Web 上重新生成一个。";
|
|
799
838
|
const user = redeemLinkCode(code, this.cfg.id, sender.openId);
|
|
800
839
|
hub.reassignOwner(ownKey, user.id);
|
|
840
|
+
updateConversation(ownKey, { boundOpenId: sender.openId });
|
|
801
841
|
const selected = this.expertsFor(ownKey);
|
|
802
842
|
if (selected !== undefined) {
|
|
803
843
|
const choices = hub.expertChoices(user.id, this.allowedAgents(), selected);
|
|
@@ -815,6 +855,7 @@ export class FeishuBot {
|
|
|
815
855
|
}
|
|
816
856
|
|
|
817
857
|
private async renderReply(key: string, chatId: string, reply: CommandReply): Promise<void> {
|
|
858
|
+
if (getConversation(key)?.assistant && !this.controls(key, chatId)) return;
|
|
818
859
|
const ctx = this.cardCtx(key, chatId);
|
|
819
860
|
switch (reply.type) {
|
|
820
861
|
case "text":
|
|
@@ -920,6 +961,16 @@ export class FeishuBot {
|
|
|
920
961
|
...(i?.settled ? { card: { type: "raw", data: settledCard(i) } } : {}),
|
|
921
962
|
});
|
|
922
963
|
|
|
964
|
+
const denied = { toast: { type: "error" as const, content: "此聊天已不能操作该 bot" } };
|
|
965
|
+
const request = "r" in envelope ? interactions.get(envelope.r) : undefined;
|
|
966
|
+
const targetKey = "k" in envelope ? envelope.k : request?.convKey;
|
|
967
|
+
const target = targetKey ? getConversation(targetKey) : undefined;
|
|
968
|
+
if (target?.assistant && (!this.controls(target.key, chatId) || linkedUser(this.id, operatorOpenId)?.id !== target.owner)) return denied;
|
|
969
|
+
|
|
970
|
+
if (target?.assistant && envelope.a === "approval" && envelope.d === "allow-always"
|
|
971
|
+
&& request?.spec.kind === "approval" && request.spec.alwaysGlobal && getUser(target.owner)?.role !== "admin") {
|
|
972
|
+
return { toast: { type: "error", content: GLOBAL_ALWAYS_DENIED } };
|
|
973
|
+
}
|
|
923
974
|
switch (envelope.a) {
|
|
924
975
|
case "approval": {
|
|
925
976
|
const settled = interactions.decide(envelope.r, envelope.d, by);
|
|
@@ -1033,7 +1084,7 @@ export class FeishuBot {
|
|
|
1033
1084
|
}
|
|
1034
1085
|
const chat = chatId!;
|
|
1035
1086
|
void task()
|
|
1036
|
-
.then((text) => this.
|
|
1087
|
+
.then((text) => this.renderReply(key, chat, { type: "text", text }))
|
|
1037
1088
|
.catch((err) => this.client.sendText(chat, `出错了:${err instanceof Error ? err.message : String(err)}`));
|
|
1038
1089
|
return { toast: { type: "info", content: toast } };
|
|
1039
1090
|
}
|
|
@@ -385,6 +385,9 @@ export type WebConvEntry = {
|
|
|
385
385
|
/** /web:最近的 Web 会话,点「接上」后这个聊天就接着它聊 */
|
|
386
386
|
export function webListCard(params: {
|
|
387
387
|
convs: WebConvEntry[];
|
|
388
|
+
assistants?: boolean;
|
|
389
|
+
page?: number;
|
|
390
|
+
pages?: number;
|
|
388
391
|
/** 当前挂着的 Web 会话 */
|
|
389
392
|
current?: string;
|
|
390
393
|
/** 这个飞书聊天自己的会话键 */
|
|
@@ -402,8 +405,9 @@ export function webListCard(params: {
|
|
|
402
405
|
if (params.current) {
|
|
403
406
|
elements.push(buttonRow([button("回到本聊天", { a: "detach", k: params.sessionKey }, params.ctx)]));
|
|
404
407
|
}
|
|
408
|
+
if (params.page && params.pages) elements.push({ tag: "markdown", content: `第 ${params.page} / ${params.pages} 页。发送 \`/bot 页码\` 翻页。` });
|
|
405
409
|
if (params.convs.length === 0) {
|
|
406
|
-
elements.push({ tag: "hr" }, { tag: "markdown", content: "还没有 Web 会话。" });
|
|
410
|
+
elements.push({ tag: "hr" }, { tag: "markdown", content: params.assistants ? "还没有 bot,请在 Web 侧栏「bot」添加。" : "还没有 Web 会话。" });
|
|
407
411
|
}
|
|
408
412
|
params.convs.forEach((c, index) => {
|
|
409
413
|
const isCurrent = c.key === params.current;
|
|
@@ -435,7 +439,7 @@ export function webListCard(params: {
|
|
|
435
439
|
],
|
|
436
440
|
});
|
|
437
441
|
});
|
|
438
|
-
return card(elements, { title: "Web 会话", template: "blue" });
|
|
442
|
+
return card(elements, { title: params.assistants ? "bot" : "Web 会话", template: "blue" });
|
|
439
443
|
}
|
|
440
444
|
|
|
441
445
|
/** 接上之后发一张:接的是哪条、最近聊到哪,以及回来的按钮 */
|
|
@@ -33,11 +33,11 @@ export class FeishuClient {
|
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
async sendText(chatId: string, text: string): Promise<string | undefined> {
|
|
36
|
+
async sendText(chatId: string, text: string, idType: "chat_id" | "open_id" = "chat_id", uuid?: string): Promise<string | undefined> {
|
|
37
37
|
try {
|
|
38
38
|
const res = await this.lark.im.v1.message.create({
|
|
39
|
-
params: { receive_id_type:
|
|
40
|
-
data: { receive_id: chatId, msg_type: "text", content: JSON.stringify({ text }) },
|
|
39
|
+
params: { receive_id_type: idType },
|
|
40
|
+
data: { ...(uuid ? { uuid } : {}), receive_id: chatId, msg_type: "text", content: JSON.stringify({ text }) },
|
|
41
41
|
});
|
|
42
42
|
return res.data?.message_id;
|
|
43
43
|
} catch (err) {
|
|
@@ -55,7 +55,9 @@ function onTaskResult(e: TaskTurnEnd): void {
|
|
|
55
55
|
console.warn(`[飞书] 定时任务「${task.title}」要推送到飞书,但${task.feishuBot ? "指定的机器人不在线或已解绑" : "主人没有绑定在线的飞书机器人"}`);
|
|
56
56
|
return;
|
|
57
57
|
}
|
|
58
|
-
|
|
58
|
+
const bot = bots.get(link.botId)!;
|
|
59
|
+
if (bot.deliversAssistantReply(e.key, link.openId)) return;
|
|
60
|
+
void bot.client.sendCard(link.openId, replyCard(`⏰ **${e.title}**\n\n${e.text}`), "open_id");
|
|
59
61
|
}
|
|
60
62
|
|
|
61
63
|
export function startFeishu(): void {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Web 上「这个用户能碰哪些东西」。规则本身在 core/users.ts 的 ownedBy。
|
|
2
|
-
import { getConversation, sessionOwner, type Conversation } from "../../core/store.js";
|
|
2
|
+
import { assistantSessionOwner, getConversation, sessionOwner, type Conversation } from "../../core/store.js";
|
|
3
3
|
import { legacyOwnerId, listUsers, ownedBy, type User } from "../../core/users.js";
|
|
4
4
|
import type { OwnerFilter } from "./push.js";
|
|
5
5
|
|
|
6
6
|
export function canSeeConv(user: User, conv: Conversation | undefined): conv is Conversation {
|
|
7
|
-
return !!conv && ownedBy(user, conv.owner);
|
|
7
|
+
return !!conv && (conv.assistant ? conv.owner === user.id : ownedBy(user, conv.owner));
|
|
8
8
|
}
|
|
9
9
|
|
|
10
10
|
export function canSeeKey(user: User, key: string): boolean {
|
|
@@ -13,11 +13,14 @@ export function canSeeKey(user: User, key: string): boolean {
|
|
|
13
13
|
|
|
14
14
|
/**
|
|
15
15
|
* 这个用户能看到、能恢复哪些 agent 会话。
|
|
16
|
-
*
|
|
16
|
+
* 单用户可恢复旧的无主会话,bot 的历史始终属于原来的账号。
|
|
17
17
|
*/
|
|
18
18
|
export function sessionVisibleTo(user: User): ((sessionId: string) => boolean) | undefined {
|
|
19
|
-
|
|
20
|
-
return (
|
|
19
|
+
const alone = listUsers().every((u) => u.id === user.id);
|
|
20
|
+
return (id) => {
|
|
21
|
+
const owner = assistantSessionOwner(id);
|
|
22
|
+
return owner ? owner === user.id : alone || ownedBy(user, sessionOwner(id));
|
|
23
|
+
};
|
|
21
24
|
}
|
|
22
25
|
|
|
23
26
|
/** 推送订阅是不是这个用户的。升级前的订阅没记主人,算迁移出来的那个管理员的 */
|