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.
- 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/settings.css +30 -0
- package/web/css/tasks.css +0 -8
- package/web/lib/ws.js +1 -4
- package/web/settings/general.js +2 -1
- package/web/settings/index.js +80 -78
- package/web/settings/tabs.js +53 -0
- package/web/state.js +13 -0
- package/web/views/layout.js +24 -40
- package/web/views/library.js +2 -2
- package/web/views/messages.js +3 -3
- package/web/views/remote.js +3 -3
- package/web/views/sidebar-nav.js +1 -2
- package/web/views/sidebar.js +6 -4
- package/web/views/tasks.js +6 -9
- package/web/views/topbar.js +11 -3
- 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/README.md
CHANGED
|
@@ -36,21 +36,6 @@ 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
|
-
|
|
54
39
|
- **多个 agent**:Claude Code、Codex、WorkBuddy、pi、dsh。几个 agent 共用工作目录,能看到对方改过的文件,但聊天记录各自独立。
|
|
55
40
|
- **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` 配置,成员只读项目里的。暂不支持自定义专家、分叉 / 回退、思考程度和额度显示;令牌过期后要回设置页重新登录。
|
|
56
41
|
- **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
|
@@ -48,14 +48,12 @@ type CardResponse = {
|
|
|
48
48
|
|
|
49
49
|
export type BotStatus = { state: string; since: number; error?: string };
|
|
50
50
|
|
|
51
|
-
type FeishuCommand = { kind: "
|
|
51
|
+
type FeishuCommand = { 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) };
|
|
59
57
|
if (lower === "/web") return { kind: "web" };
|
|
60
58
|
if (lower === "/detach") return { kind: "detach" };
|
|
61
59
|
const bind = /^\/bind\s+([A-Za-z0-9]{4,16})$/i.exec(t);
|
|
@@ -308,7 +306,7 @@ export class FeishuBot {
|
|
|
308
306
|
console.log(`${this.tag} ${feishuKey} 接上 Web 会话 ${webKey}`);
|
|
309
307
|
// 最近几句:读历史可能要一会儿,读不到也不影响接上
|
|
310
308
|
const history = await hub.history(webKey).catch(() => []);
|
|
311
|
-
if (conv.assistant && this.attachedWeb(feishuKey) !== webKey) throw new Error("
|
|
309
|
+
if (conv.assistant && this.attachedWeb(feishuKey) !== webKey) throw new Error("会话绑定已变化");
|
|
312
310
|
const recent = history
|
|
313
311
|
.filter((m) => m.role !== "question" && m.text.trim())
|
|
314
312
|
.slice(-4)
|
|
@@ -334,25 +332,17 @@ export class FeishuBot {
|
|
|
334
332
|
return `已回到这个聊天自己的会话${title ? `,不再接着「${title}」` : ""}。之后发 \`/web\` 可以再接上。`;
|
|
335
333
|
}
|
|
336
334
|
|
|
337
|
-
/** /web
|
|
338
|
-
private async sendWebList(feishuKey: string, chatId: string
|
|
339
|
-
const assistants = assistantPage !== undefined;
|
|
335
|
+
/** 发 /web:列最近的 Web 会话 */
|
|
336
|
+
private async sendWebList(feishuKey: string, chatId: string): Promise<void> {
|
|
340
337
|
const current = this.attachedWeb(feishuKey);
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
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
|
-
}
|
|
338
|
+
const convs = hub
|
|
339
|
+
.list((c) => c.channel === "web" && !c.hidden && this.canSee(feishuKey, c))
|
|
340
|
+
.slice(0, 10)
|
|
341
|
+
.map((c) => this.webEntry(c.key)!)
|
|
342
|
+
.filter(Boolean);
|
|
351
343
|
await this.client.sendCard(
|
|
352
344
|
chatId,
|
|
353
345
|
webListCard({
|
|
354
|
-
assistants,
|
|
355
|
-
...(assistants && pages > 1 ? { page, pages } : {}),
|
|
356
346
|
convs,
|
|
357
347
|
...(current ? { current } : {}),
|
|
358
348
|
sessionKey: feishuKey,
|
|
@@ -368,7 +358,7 @@ export class FeishuBot {
|
|
|
368
358
|
detach(feishuKey);
|
|
369
359
|
void this.client.sendCard(
|
|
370
360
|
this.chatIdOf(feishuKey),
|
|
371
|
-
replyCard(getConversation(target)?.assistant ? "
|
|
361
|
+
replyCard(getConversation(target)?.assistant ? "之前接着的私人会话已不可用,已回到这个聊天自己的会话。" : "之前接着的 Web 会话已经被删除,已回到这个聊天自己的会话。"),
|
|
372
362
|
);
|
|
373
363
|
return true;
|
|
374
364
|
}
|
|
@@ -815,14 +805,7 @@ export class FeishuBot {
|
|
|
815
805
|
sender?: { openId: string; p2p: boolean },
|
|
816
806
|
): Promise<void> {
|
|
817
807
|
try {
|
|
818
|
-
if (cmd.kind === "
|
|
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);
|
|
808
|
+
if (cmd.kind === "web") await this.sendWebList(ownKey, chatId);
|
|
826
809
|
else if (cmd.kind === "detach") await this.client.sendCard(chatId, replyCard(this.detachFrom(ownKey)));
|
|
827
810
|
else await this.client.sendCard(chatId, replyCard(await this.bind(cmd.code, ownKey, sender)));
|
|
828
811
|
} catch (err) {
|
|
@@ -961,7 +944,7 @@ export class FeishuBot {
|
|
|
961
944
|
...(i?.settled ? { card: { type: "raw", data: settledCard(i) } } : {}),
|
|
962
945
|
});
|
|
963
946
|
|
|
964
|
-
const denied = { toast: { type: "error" as const, content: "
|
|
947
|
+
const denied = { toast: { type: "error" as const, content: "此聊天已不能操作该私人会话" } };
|
|
965
948
|
const request = "r" in envelope ? interactions.get(envelope.r) : undefined;
|
|
966
949
|
const targetKey = "k" in envelope ? envelope.k : request?.convKey;
|
|
967
950
|
const target = targetKey ? getConversation(targetKey) : undefined;
|
|
@@ -385,9 +385,6 @@ 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;
|
|
391
388
|
/** 当前挂着的 Web 会话 */
|
|
392
389
|
current?: string;
|
|
393
390
|
/** 这个飞书聊天自己的会话键 */
|
|
@@ -405,9 +402,8 @@ export function webListCard(params: {
|
|
|
405
402
|
if (params.current) {
|
|
406
403
|
elements.push(buttonRow([button("回到本聊天", { a: "detach", k: params.sessionKey }, params.ctx)]));
|
|
407
404
|
}
|
|
408
|
-
if (params.page && params.pages) elements.push({ tag: "markdown", content: `第 ${params.page} / ${params.pages} 页。发送 \`/bot 页码\` 翻页。` });
|
|
409
405
|
if (params.convs.length === 0) {
|
|
410
|
-
elements.push({ tag: "hr" }, { tag: "markdown", content:
|
|
406
|
+
elements.push({ tag: "hr" }, { tag: "markdown", content: "还没有 Web 会话。" });
|
|
411
407
|
}
|
|
412
408
|
params.convs.forEach((c, index) => {
|
|
413
409
|
const isCurrent = c.key === params.current;
|
|
@@ -439,7 +435,7 @@ export function webListCard(params: {
|
|
|
439
435
|
],
|
|
440
436
|
});
|
|
441
437
|
});
|
|
442
|
-
return card(elements, { title:
|
|
438
|
+
return card(elements, { title: "Web 会话", template: "blue" });
|
|
443
439
|
}
|
|
444
440
|
|
|
445
441
|
/** 接上之后发一张:接的是哪条、最近聊到哪,以及回来的按钮 */
|
|
@@ -33,11 +33,11 @@ export class FeishuClient {
|
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
-
async sendText(chatId: string, text: string
|
|
36
|
+
async sendText(chatId: string, text: 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: {
|
|
39
|
+
params: { receive_id_type: "chat_id" },
|
|
40
|
+
data: { receive_id: chatId, msg_type: "text", content: JSON.stringify({ text }) },
|
|
41
41
|
});
|
|
42
42
|
return res.data?.message_id;
|
|
43
43
|
} catch (err) {
|
package/src/channels/web/api.ts
CHANGED
|
@@ -9,7 +9,7 @@ import { cleanCustomCommands } from "../../core/command-catalog.js";
|
|
|
9
9
|
import { hub } from "../../core/hub.js";
|
|
10
10
|
import { interactions } from "../../core/interactions.js";
|
|
11
11
|
import { approve, listApproved, listPending, revoke } from "../../core/pairing.js";
|
|
12
|
-
import { agentBinding, conversationLabels,
|
|
12
|
+
import { agentBinding, conversationLabels, getConversation, listConversations, touchConversation, updateConversation } from "../../core/store.js";
|
|
13
13
|
import { addScheduled, clearScheduled, removeScheduled } from "../../core/scheduled.js";
|
|
14
14
|
import { resolveUploadFile, saveBuffer, sniff, uploadKeyOf } from "../../core/uploads.js";
|
|
15
15
|
import { mentions, resolveReplyFile } from "../../core/reply-files.js";
|
|
@@ -96,9 +96,6 @@ import {
|
|
|
96
96
|
import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
|
|
97
97
|
import { clampLimit, dirsOf, inDir, pageOf, parseCursor, recentPageOf, searchConvs } from "./conv-pages.js";
|
|
98
98
|
import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson, setServerTiming } from "./http.js";
|
|
99
|
-
import { listTasks, taskBelongsToAssistant } from "../../core/tasks.js";
|
|
100
|
-
import { clearWatches } from "../../core/bot-events.js";
|
|
101
|
-
import { handleBotEventsApi, receiveBackup } from "./bot-events-api.js";
|
|
102
99
|
import { handleTasksApi } from "./tasks-api.js";
|
|
103
100
|
import { handleLibraryApi } from "./library-api.js";
|
|
104
101
|
import { attachToConversation, canSeeFile, deleteConversationFiles, getLibraryFile } from "../../core/library.js";
|
|
@@ -133,7 +130,6 @@ const uploads = new Map<string, { key: string; attachment: SavedAttachment; at:
|
|
|
133
130
|
/** 单条删除和项目批量删除共用清理规则,保留 agent 自己的文字记录。 */
|
|
134
131
|
function hideConversation(key: string): void {
|
|
135
132
|
const conv = getConversation(key);
|
|
136
|
-
if (conv?.assistant === "active" && conv.owner) clearWatches(conv.owner, key);
|
|
137
133
|
updateConversation(key, { hidden: true });
|
|
138
134
|
// 删对话:聊天记录索引和摘要真的删掉,不只是搜不到(agent 自己的文字记录还留着,它们不归这里管)
|
|
139
135
|
if (conv) {
|
|
@@ -628,8 +624,6 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
628
624
|
const p = url.pathname;
|
|
629
625
|
const ip = clientIp(req);
|
|
630
626
|
|
|
631
|
-
if (p === "/api/bot-events/receive" && method === "POST") return receiveBackup(req, res);
|
|
632
|
-
|
|
633
627
|
// ----- 无需登录 -----
|
|
634
628
|
if (p === "/api/me" && method === "GET") {
|
|
635
629
|
const user = currentUser(req);
|
|
@@ -677,7 +671,6 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
677
671
|
const user = currentUser(req);
|
|
678
672
|
if (!user) throw new HttpError(401, "请先登录");
|
|
679
673
|
if (adminOnly(p) && !isAdmin(user)) throw new HttpError(403, "只有管理员能做这个操作");
|
|
680
|
-
if (p === "/api/bot-events" || p.startsWith("/api/bot-events/")) return handleBotEventsApi(req, res, url, user);
|
|
681
674
|
const admin = isAdmin(user);
|
|
682
675
|
const visible = (c: Parameters<typeof canSeeConv>[1]) => canSeeConv(user, c);
|
|
683
676
|
|
|
@@ -979,48 +972,10 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
979
972
|
sendJson(res, 200, hub.list(visible));
|
|
980
973
|
return;
|
|
981
974
|
}
|
|
982
|
-
if (p === "/api/
|
|
983
|
-
const tasks = listTasks(user.id);
|
|
984
|
-
const assistants = listConversations().filter((c) => c.owner === user.id && c.assistant === "active" && !c.hidden).map((c) => {
|
|
985
|
-
const info = hub.info(c.key)!;
|
|
986
|
-
const assigned = tasks.filter((t) => taskBelongsToAssistant(t, c.key));
|
|
987
|
-
return {
|
|
988
|
-
key: c.key, expert: info.expert, agent: c.agent, cwd: c.cwd, title: c.title,
|
|
989
|
-
permission: info.permission, permissionMax: info.permissionMax,
|
|
990
|
-
unavailable: hub.assistantUnavailable(c), busy: info.busy, pending: interactions.listPending(c.key).length,
|
|
991
|
-
tasks: assigned.map((t) => {
|
|
992
|
-
const last = t.runs[0];
|
|
993
|
-
const key = last?.convKey ?? t.target.key;
|
|
994
|
-
const target = key ? getConversation(key) : undefined;
|
|
995
|
-
const resultKey = target?.owner === user.id && !target.hidden ? target.key : undefined;
|
|
996
|
-
const runningHere = resultKey && hub.currentTaskTurn(resultKey)?.taskId === t.id;
|
|
997
|
-
return {
|
|
998
|
-
id: t.id, title: t.title, enabled: t.enabled, nextRunAt: t.nextRunAt,
|
|
999
|
-
last, resultKey, pending: runningHere ? interactions.listPending(resultKey).length : 0,
|
|
1000
|
-
};
|
|
1001
|
-
}),
|
|
1002
|
-
};
|
|
1003
|
-
});
|
|
1004
|
-
sendJson(res, 200, { assistants });
|
|
1005
|
-
return;
|
|
1006
|
-
}
|
|
1007
|
-
if (p === "/api/assistants" && method === "DELETE") {
|
|
1008
|
-
const { key } = await readJsonBody<{ key?: string }>(req);
|
|
1009
|
-
const conv = typeof key === "string" ? getConversation(key) : undefined;
|
|
1010
|
-
if (!conv || conv.owner !== user.id || (conv.assistant !== "active" && conv.assistant !== "removed")) throw new HttpError(404, "找不到这个 bot");
|
|
1011
|
-
clearWatches(user.id, conv.key);
|
|
1012
|
-
updateConversation(conv.key, { assistant: "removed" });
|
|
1013
|
-
flushStore();
|
|
1014
|
-
hub.emitEvent(conv.key, { type: "meta" });
|
|
1015
|
-
sendJson(res, 200, { ok: true });
|
|
1016
|
-
return;
|
|
1017
|
-
}
|
|
1018
|
-
if ((p === "/api/conversations" || p === "/api/assistants") && method === "POST") {
|
|
975
|
+
if (p === "/api/conversations" && method === "POST") {
|
|
1019
976
|
// expert:新对话页上选的专家(内置的 claude / codex,或者自己的、共享的专家 id)。agent 是以前的叫法
|
|
1020
977
|
const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
|
|
1021
978
|
const enabled = hub.enabledAgents().map((d) => d.id);
|
|
1022
|
-
const assistant = p === "/api/assistants";
|
|
1023
|
-
if (assistant && (typeof body.expert !== "string" || !body.expert)) throw new HttpError(400, "请选择 bot 使用的专家");
|
|
1024
979
|
const wanted = body.expert ?? body.agent;
|
|
1025
980
|
if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家或 Agent 不存在、已取消共享或未获授权");
|
|
1026
981
|
const expertId = wanted || hub.expertChoices(user.id, enabled)[0]?.id;
|
|
@@ -1028,21 +983,6 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1028
983
|
const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
|
|
1029
984
|
const agent = custom ? custom.engine : expertId;
|
|
1030
985
|
if (!enabled.includes(agent)) throw new HttpError(400, `${hub.label(agent)} 没有启用,用不了这个专家`);
|
|
1031
|
-
if (assistant) {
|
|
1032
|
-
// 查询和创建在同一个同步区间,多个标签同时添加也只会创建一个联系人。
|
|
1033
|
-
const contacts = listConversations().filter((c) => c.owner === user.id && !c.hidden && expertIdOf(c) === expertId);
|
|
1034
|
-
const existing = contacts.find((c) => c.assistant === "active") ?? contacts.find((c) => c.assistant === "removed" && c.agent === agent);
|
|
1035
|
-
if (existing) {
|
|
1036
|
-
if (existing.agent !== agent) throw new HttpError(409, "专家已更换引擎,请移除旧 bot 后重新添加");
|
|
1037
|
-
if (existing.assistant !== "active") {
|
|
1038
|
-
updateConversation(existing.key, { assistant: "active" });
|
|
1039
|
-
flushStore();
|
|
1040
|
-
hub.emitEvent(existing.key, { type: "meta" });
|
|
1041
|
-
}
|
|
1042
|
-
sendJson(res, 200, hub.info(existing.key));
|
|
1043
|
-
return;
|
|
1044
|
-
}
|
|
1045
|
-
}
|
|
1046
986
|
// 新对话发第一条消息前在页面上选的工作目录;和 /cd 一样只能在工作区之内。没选就用专家默认的
|
|
1047
987
|
let cwd: string | undefined;
|
|
1048
988
|
const rawCwd = typeof body.cwd === "string" && body.cwd.trim() ? body.cwd.trim() : custom?.cwd;
|
|
@@ -1052,8 +992,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
|
|
|
1052
992
|
cwd = resolved;
|
|
1053
993
|
}
|
|
1054
994
|
const key = `web:${crypto.randomBytes(6).toString("hex")}`;
|
|
1055
|
-
hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, ...(custom ? { expert: custom.id } : {}), ...(cwd ? { cwd } : {}), owner: user.id
|
|
1056
|
-
...(assistant ? { assistant: "active", title: custom?.name ?? hub.label(agent) } : {}) });
|
|
995
|
+
hub.ensure({ key, channel: "web", channelId: "web", defaultAgent: agent, ...(custom ? { expert: custom.id } : {}), ...(cwd ? { cwd } : {}), owner: user.id });
|
|
1057
996
|
sendJson(res, 200, hub.info(key));
|
|
1058
997
|
return;
|
|
1059
998
|
}
|
|
@@ -14,7 +14,6 @@ import { GLOBAL_ALWAYS_DENIED, hub, type EventEnvelope } from "../../core/hub.js
|
|
|
14
14
|
import { interactions, type Interaction } from "../../core/interactions.js";
|
|
15
15
|
import { weixinEvents } from "../weixin/events.js";
|
|
16
16
|
import { getConversation } from "../../core/store.js";
|
|
17
|
-
import { botEvents } from "../../core/bot-events.js";
|
|
18
17
|
import { findTask, taskEvents, taskPush } from "../../core/tasks.js";
|
|
19
18
|
import { skillEvents } from "../../core/skills.js";
|
|
20
19
|
import { expertEvents } from "../../core/experts.js";
|
|
@@ -364,10 +363,6 @@ function broadcastTasks(owner: string): void {
|
|
|
364
363
|
for (const client of clients) if (client.user.id === owner) send(client, { t: "tasks" });
|
|
365
364
|
}
|
|
366
365
|
|
|
367
|
-
function broadcastBotEvents(owner: string): void {
|
|
368
|
-
for (const client of clients) if (client.user.id === owner) send(client, { t: "bot-events" });
|
|
369
|
-
}
|
|
370
|
-
|
|
371
366
|
function broadcastProjectDeleted(project: { owner: string; path: string; keys: string[] }): void {
|
|
372
367
|
for (const client of clients) if (client.user.id === project.owner) send(client, { t: "project-deleted", path: project.path, keys: project.keys });
|
|
373
368
|
}
|
|
@@ -470,8 +465,6 @@ function onWeixinUndelivered({ key, body }: { key: string; body: string }): void
|
|
|
470
465
|
function pushEvent(env: EventEnvelope): void {
|
|
471
466
|
const ev = env.ev;
|
|
472
467
|
if (ev.type !== "result" && ev.type !== "error") return;
|
|
473
|
-
// 自动故障分析的提醒由监听选择的渠道发;之后用户在同一聊天里追问照常提醒。
|
|
474
|
-
if (ev.botAnalysis) return;
|
|
475
468
|
// 定时任务这次判断不用提醒
|
|
476
469
|
if (ev.type === "result" && ev.silent) return;
|
|
477
470
|
// 定时任务的结果按任务选的推送渠道:没选 Web 就不推;选了的话发到飞书 / 微信对话里的也推
|
|
@@ -792,7 +785,6 @@ export async function startWeb(): Promise<void> {
|
|
|
792
785
|
interactions.on("created", pushInteraction);
|
|
793
786
|
interactions.on("updated", broadcastInteraction);
|
|
794
787
|
interactions.on("settled", broadcastInteraction);
|
|
795
|
-
botEvents.on("changed", broadcastBotEvents);
|
|
796
788
|
taskEvents.on("changed", broadcastTasks);
|
|
797
789
|
skillEvents.on("changed", broadcastSkills);
|
|
798
790
|
expertEvents.on("changed", broadcastExperts);
|
|
@@ -846,7 +838,6 @@ export async function stopWeb(): Promise<void> {
|
|
|
846
838
|
interactions.off("created", pushInteraction);
|
|
847
839
|
interactions.off("updated", broadcastInteraction);
|
|
848
840
|
interactions.off("settled", broadcastInteraction);
|
|
849
|
-
botEvents.off("changed", broadcastBotEvents);
|
|
850
841
|
taskEvents.off("changed", broadcastTasks);
|
|
851
842
|
skillEvents.off("changed", broadcastSkills);
|
|
852
843
|
expertEvents.off("changed", broadcastExperts);
|
|
@@ -33,7 +33,7 @@ function view(task: Task) {
|
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
/** convPermission:任务发到已有对话时,顺手改那条对话的权限(权限属于对话,不属于任务) */
|
|
36
|
-
type TaskBody = TaskInput & { convPermission?: unknown
|
|
36
|
+
type TaskBody = TaskInput & { convPermission?: unknown };
|
|
37
37
|
|
|
38
38
|
/** 表单 / 请求里的字段先在这里核一遍:专家要是自己能用的、引擎要启用着,目录要在工作区里,对话要是自己的 */
|
|
39
39
|
function checkInput(user: User, body: TaskBody): TaskInput {
|
|
@@ -102,11 +102,7 @@ export async function handleTasksApi(req: IncomingMessage, res: ServerResponse,
|
|
|
102
102
|
if (!body.expert && !body.agent) body.expert = hub.enabledAgents()[0]?.id;
|
|
103
103
|
let task: Task;
|
|
104
104
|
try {
|
|
105
|
-
|
|
106
|
-
if (body.assistantKey !== undefined && (!source || source.owner !== user.id || source.assistant !== "active" || source.hidden || hub.assistantUnavailable(source))) {
|
|
107
|
-
throw new HttpError(400, "交办这项任务的 bot 已不可用");
|
|
108
|
-
}
|
|
109
|
-
task = createTask(user.id, checkInput(user, body), "user", Date.now(), source?.key);
|
|
105
|
+
task = createTask(user.id, checkInput(user, body), "user");
|
|
110
106
|
} catch (err) {
|
|
111
107
|
throw bad(err);
|
|
112
108
|
}
|
package/src/core/backup.ts
CHANGED
|
@@ -8,8 +8,6 @@
|
|
|
8
8
|
//
|
|
9
9
|
// 恢复:停掉服务 → gunzip 备份文件 → 覆盖 data/agent-loft.db → 删掉 agent-loft.db-wal 和 -shm → 启动。
|
|
10
10
|
// 只备份数据库。配置和专家这些是 JSON 文件,不在这里面。
|
|
11
|
-
import { EventEmitter } from "node:events";
|
|
12
|
-
import { randomUUID } from "node:crypto";
|
|
13
11
|
import fs from "node:fs";
|
|
14
12
|
import path from "node:path";
|
|
15
13
|
import { Worker } from "node:worker_threads";
|
|
@@ -155,7 +153,6 @@ function prune(now: number): void {
|
|
|
155
153
|
}
|
|
156
154
|
|
|
157
155
|
/** 同一时间只做一份 */
|
|
158
|
-
export const backupEvents = new EventEmitter<{ finished: [runId: string, ok: boolean, error?: string] }>();
|
|
159
156
|
let running: Promise<BackupInfo> | undefined;
|
|
160
157
|
let lastError: { at: number; message: string } | undefined;
|
|
161
158
|
|
|
@@ -164,7 +161,6 @@ export function backupNow(now = Date.now()): Promise<BackupInfo> {
|
|
|
164
161
|
if (running) return running;
|
|
165
162
|
running = (async () => {
|
|
166
163
|
const dir = backupDir();
|
|
167
|
-
const runId = randomUUID();
|
|
168
164
|
const name = `${PREFIX}${dayName(now)}${SUFFIX}`;
|
|
169
165
|
const target = path.join(dir, name);
|
|
170
166
|
try {
|
|
@@ -176,12 +172,10 @@ export function backupNow(now = Date.now()): Promise<BackupInfo> {
|
|
|
176
172
|
lastError = undefined;
|
|
177
173
|
const size = fs.statSync(target).size;
|
|
178
174
|
console.log(`[备份] 数据库已备份到 ${target}(${(size / 1048576).toFixed(1)} MB)`);
|
|
179
|
-
backupEvents.emit("finished", runId, true);
|
|
180
175
|
return { name, at: Date.now(), size };
|
|
181
176
|
} catch (err) {
|
|
182
177
|
const message = err instanceof Error ? err.message : String(err);
|
|
183
178
|
lastError = { at: Date.now(), message };
|
|
184
|
-
backupEvents.emit("finished", runId, false, message);
|
|
185
179
|
console.error("[备份] 备份失败:", message);
|
|
186
180
|
throw err;
|
|
187
181
|
}
|
|
@@ -40,7 +40,6 @@ export const BUILTIN_COMMANDS: BuiltinSpec[] = [
|
|
|
40
40
|
{ name: "workbuddy", description: "换成 WorkBuddy 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
41
41
|
{ name: "pi", description: "换成 pi 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
42
42
|
{ name: "dsh", description: "换成 dsh 专家(开新会话)", multiAgentOnly: true, chatOnly: true },
|
|
43
|
-
{ name: "bot", description: "在绑定私聊打开 bot", feishuOnly: true },
|
|
44
43
|
{ name: "web", description: "接上一条 Web 会话,在飞书里查看和回复", feishuOnly: true },
|
|
45
44
|
{ name: "detach", description: "不再接着 Web 会话,回到这个聊天自己的会话", feishuOnly: true },
|
|
46
45
|
{ name: "bind", args: "<绑定码>", description: "把这个飞书账号绑定到你的 agent-loft 用户(绑定码在 Web 的「设置 → 账号」里生成)", feishuOnly: true },
|
package/src/core/db.ts
CHANGED
|
@@ -46,24 +46,9 @@ CREATE TABLE IF NOT EXISTS conversations (
|
|
|
46
46
|
data TEXT NOT NULL
|
|
47
47
|
);
|
|
48
48
|
|
|
49
|
+
-- 保留 0.2.122 创建的私人会话的历史归属。
|
|
49
50
|
CREATE TABLE IF NOT EXISTS assistant_sessions (session_id TEXT PRIMARY KEY, owner TEXT NOT NULL);
|
|
50
51
|
|
|
51
|
-
CREATE TABLE IF NOT EXISTS bot_watches (
|
|
52
|
-
id TEXT PRIMARY KEY, owner TEXT NOT NULL, conv TEXT NOT NULL, name TEXT NOT NULL,
|
|
53
|
-
source TEXT NOT NULL, destination TEXT NOT NULL, analyze INTEGER NOT NULL,
|
|
54
|
-
token_hash TEXT UNIQUE, last_seen INTEGER, last_status TEXT
|
|
55
|
-
);
|
|
56
|
-
CREATE INDEX IF NOT EXISTS bot_watches_owner ON bot_watches(owner, conv);
|
|
57
|
-
|
|
58
|
-
CREATE TABLE IF NOT EXISTS bot_incidents (
|
|
59
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT, watch TEXT NOT NULL, run TEXT NOT NULL, reason TEXT NOT NULL,
|
|
60
|
-
at INTEGER NOT NULL, delivery TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0,
|
|
61
|
-
next_try INTEGER NOT NULL DEFAULT 0, error TEXT, analysis TEXT NOT NULL, analysis_key TEXT,
|
|
62
|
-
UNIQUE(watch, run)
|
|
63
|
-
);
|
|
64
|
-
CREATE INDEX IF NOT EXISTS bot_incidents_pending ON bot_incidents(delivery, next_try);
|
|
65
|
-
CREATE INDEX IF NOT EXISTS bot_incidents_analysis ON bot_incidents(analysis);
|
|
66
|
-
|
|
67
52
|
CREATE TABLE IF NOT EXISTS session_owners (
|
|
68
53
|
session_id TEXT PRIMARY KEY,
|
|
69
54
|
user_id TEXT NOT NULL
|
package/src/core/hub.ts
CHANGED
|
@@ -109,8 +109,8 @@ export type ConvEvent =
|
|
|
109
109
|
* task:这一轮是定时任务发起的;silent:任务让 agent 自己判断要不要提醒,它判断这次不用 ——
|
|
110
110
|
* 推送、飞书都不发,网页上折叠显示
|
|
111
111
|
*/
|
|
112
|
-
| { type: "result"; text: string; footer: string; at: number; anchor?: string; task?: { id: string; title: string }; silent?: true
|
|
113
|
-
| { type: "error"; message: string
|
|
112
|
+
| { type: "result"; text: string; footer: string; at: number; anchor?: string; task?: { id: string; title: string }; silent?: true }
|
|
113
|
+
| { type: "error"; message: string }
|
|
114
114
|
| { type: "notice"; text: string }
|
|
115
115
|
| { type: "state"; busy: boolean }
|
|
116
116
|
| { type: "meta" };
|
|
@@ -316,7 +316,7 @@ class Hub extends EventEmitter<{
|
|
|
316
316
|
* 已经交给 agent 会话、还没出结果的消息,和 inflight、turnTags 一一对应:第一条在跑,后面的在排队。
|
|
317
317
|
* 用来告诉页面哪条消息轮到了 / 被丢了,以及「打断并发送」时把哪条挪到前面
|
|
318
318
|
*/
|
|
319
|
-
private turnFifo = new Map<string, { id: string; input: UserInput; queued: boolean
|
|
319
|
+
private turnFifo = new Map<string, { id: string; input: UserInput; queued: boolean }[]>();
|
|
320
320
|
private pendingInputs = new Map<string, Map<string, { input: UserInput; cancelled: boolean }>>();
|
|
321
321
|
private rewinding = new Set<string>();
|
|
322
322
|
/** 收到了、还在串行队列里没交给 agent 的消息数:这时再来的消息也算排队 */
|
|
@@ -663,7 +663,6 @@ class Hub extends EventEmitter<{
|
|
|
663
663
|
channel: string;
|
|
664
664
|
channelId: string;
|
|
665
665
|
defaultAgent: string;
|
|
666
|
-
assistant?: Conversation["assistant"];
|
|
667
666
|
/** 自定义专家的 id(新建时才用)。不给就是内置专家 defaultAgent */
|
|
668
667
|
expert?: string;
|
|
669
668
|
/** 新建时的工作目录。不给就是工作区根目录 */
|
|
@@ -677,7 +676,6 @@ class Hub extends EventEmitter<{
|
|
|
677
676
|
channel: params.channel,
|
|
678
677
|
channelId: params.channelId,
|
|
679
678
|
agent: params.defaultAgent,
|
|
680
|
-
assistant: params.assistant,
|
|
681
679
|
...(params.expert && !isBuiltin(params.expert) ? { expert: params.expert } : {}),
|
|
682
680
|
...(params.cwd ? { cwd: params.cwd } : {}),
|
|
683
681
|
...(params.title ? { title: params.title } : {}),
|
|
@@ -894,7 +892,6 @@ class Hub extends EventEmitter<{
|
|
|
894
892
|
...(result.anchor && !tag?.isolated ? { anchor: result.anchor } : {}),
|
|
895
893
|
...(tag ? { task: { id: tag.taskId, title: tag.title } } : {}),
|
|
896
894
|
...(silent ? { silent: true as const } : {}),
|
|
897
|
-
...(this.turnFifo.get(key)?.[0]?.botAnalysis ? { botAnalysis: true } : {}),
|
|
898
895
|
});
|
|
899
896
|
if (tag) this.emit("task", { ...tag, key, status: silent ? "silent" : "notified", text: result.text });
|
|
900
897
|
const conv = getConversation(key);
|
|
@@ -925,7 +922,7 @@ class Hub extends EventEmitter<{
|
|
|
925
922
|
// 用户自己点的停止:中断导致的「没能正常收尾」不是故障
|
|
926
923
|
this.emitEvent(key, { type: "notice", text: "已中断。" });
|
|
927
924
|
} else {
|
|
928
|
-
this.emitEvent(key, { type: "error", message: diagnosis.chatMessage
|
|
925
|
+
this.emitEvent(key, { type: "error", message: diagnosis.chatMessage });
|
|
929
926
|
}
|
|
930
927
|
this.setInflight(key, (this.inflight.get(key) ?? 1) - 1);
|
|
931
928
|
this.finishTurn(key);
|
|
@@ -1267,9 +1264,10 @@ class Hub extends EventEmitter<{
|
|
|
1267
1264
|
return;
|
|
1268
1265
|
}
|
|
1269
1266
|
// 收到之后发生过显式切换(恢复 / 分叉 / 新会话…):用户已经明确指定了会话,不再按旧的闲置时间作废它。
|
|
1270
|
-
//
|
|
1267
|
+
// 定时任务也不按闲置过期:每天跑一次的任务要接着上次的上下文
|
|
1268
|
+
const ttl = config().sessionTtlMs;
|
|
1271
1269
|
const switchedAfterEntry = (this.lastSwitch.get(key)?.at ?? 0) >= g.at;
|
|
1272
|
-
const expired = !task && !switchedAfterEntry &&
|
|
1270
|
+
const expired = !task && !switchedAfterEntry && ttl > 0 && Date.now() - lastActive > ttl;
|
|
1273
1271
|
if (expired) {
|
|
1274
1272
|
await this.expireNow(key);
|
|
1275
1273
|
if (waiting.cancelled) return;
|
|
@@ -1309,7 +1307,7 @@ class Hub extends EventEmitter<{
|
|
|
1309
1307
|
// 从这里到 sendNow 没有 await:换下去的会话一定等得到这一轮的结束(见 endIsolatedRun)
|
|
1310
1308
|
this.parkChatSession(key, task.runId);
|
|
1311
1309
|
}
|
|
1312
|
-
this.sendNow(key, task ? input : this.withTaskResults(key, input), task ?? null, { id: shown.id, queued: shown.queued
|
|
1310
|
+
this.sendNow(key, task ? input : this.withTaskResults(key, input), task ?? null, { id: shown.id, queued: shown.queued });
|
|
1313
1311
|
} finally {
|
|
1314
1312
|
pendingInputs.delete(shown.id);
|
|
1315
1313
|
if (!pendingInputs.size) this.pendingInputs.delete(key);
|
|
@@ -1491,10 +1489,10 @@ class Hub extends EventEmitter<{
|
|
|
1491
1489
|
}
|
|
1492
1490
|
|
|
1493
1491
|
/** msg:页面上那条消息的编号和收到时是否排队(见 send 里的 shown) */
|
|
1494
|
-
private sendNow(key: string, input: UserInput, tag: TaskTurn | null, msg: { id: string; queued: boolean
|
|
1492
|
+
private sendNow(key: string, input: UserInput, tag: TaskTurn | null, msg: { id: string; queued: boolean }): void {
|
|
1495
1493
|
const fail = (err: unknown) => {
|
|
1496
1494
|
const message = err instanceof Error ? err.message : String(err);
|
|
1497
|
-
this.emitEvent(key, { type: "error", message
|
|
1495
|
+
this.emitEvent(key, { type: "error", message });
|
|
1498
1496
|
if (tag) this.emit("task", { ...tag, key, status: "error", text: message });
|
|
1499
1497
|
};
|
|
1500
1498
|
let session: AgentSession;
|
|
@@ -1605,7 +1603,7 @@ class Hub extends EventEmitter<{
|
|
|
1605
1603
|
private async resumeNow(key: string, sessionId: string, originCwd: string | undefined, op: SwitchOp): Promise<string> {
|
|
1606
1604
|
const conv = getConversation(key)!;
|
|
1607
1605
|
const privateOwner = assistantSessionOwner(sessionId);
|
|
1608
|
-
if (privateOwner && (!conv.assistant || conv.owner !== privateOwner)) return "
|
|
1606
|
+
if (privateOwner && (!conv.assistant || conv.owner !== privateOwner)) return "请在本人的私人对话里恢复这段历史。";
|
|
1609
1607
|
const driver = this.requireDriver(conv.agent);
|
|
1610
1608
|
if (!(await withTimeout(driver.sessionExists(sessionId, conv.cwd), "查询会话"))) {
|
|
1611
1609
|
return `找不到会话 ${sessionId}。\n发 /sessions 看看有哪些可恢复的。`;
|
package/src/core/personal.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { clearWatches } from "./bot-events.js";
|
|
2
1
|
// 「这条对话是谁的」在个人数据(记忆、飞书绑定)上的落点。
|
|
3
2
|
import { deleteMemory, memoryPrompt, readMemory } from "./memory.js";
|
|
4
3
|
import { purgeConversationHistory, purgeHistory } from "./chat-history.js";
|
|
@@ -77,7 +76,6 @@ export function purgeHiddenConversationsOnce(): number {
|
|
|
77
76
|
|
|
78
77
|
/** 删用户时一起删掉的个人数据:记忆、聊天记录索引、飞书和微信绑定、定时任务、技能(他建的技能,装了的人也就没了)、专家和 MCP */
|
|
79
78
|
export function purgeUserData(userId: string): void {
|
|
80
|
-
clearWatches(userId);
|
|
81
79
|
deleteMemory(userId);
|
|
82
80
|
purgeHistory(userId);
|
|
83
81
|
unlinkUser(userId);
|
package/src/core/store.ts
CHANGED
|
@@ -53,7 +53,7 @@ export type Conversation = {
|
|
|
53
53
|
cwd: string;
|
|
54
54
|
/** cwd 是否用户显式指定。没指定过的跟随 workspaceRoot 变化 */
|
|
55
55
|
cwdExplicit?: boolean;
|
|
56
|
-
/**
|
|
56
|
+
/** 0.2.122 的个人 bot 及派生会话沿用仅主人可见的权限。 */
|
|
57
57
|
assistant?: "active" | "removed" | "related";
|
|
58
58
|
perAgent: Record<string, AgentBinding>;
|
|
59
59
|
/** 最后一次有人说话的时间,用于闲置过期 */
|
|
@@ -261,9 +261,9 @@ export function touchConversation(key: string): void {
|
|
|
261
261
|
persist();
|
|
262
262
|
}
|
|
263
263
|
|
|
264
|
-
export function isExpired(conv: Conversation, now = Date.now()
|
|
264
|
+
export function isExpired(conv: Conversation, now = Date.now()): boolean {
|
|
265
265
|
const ttl = config().sessionTtlMs;
|
|
266
|
-
return
|
|
266
|
+
return ttl > 0 && now - conv.activeAt > ttl;
|
|
267
267
|
}
|
|
268
268
|
|
|
269
269
|
export function listConversations(): Conversation[] {
|
package/src/core/tasks-bridge.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { expertIdOf, getConversation } from "./store.js";
|
|
|
18
18
|
import { forgetTask } from "./task-runner.js";
|
|
19
19
|
import { describeSchedule, formatDateTime, nextRun, normalizeSchedule, parseLocalDateTime, serverTimeZone, type TaskSchedule } from "./task-schedule.js";
|
|
20
20
|
import { TASK_TOOL_TIMEOUT_SEC, tasksSocketPath, verifyTaskCaller } from "./tasks-mcp.js";
|
|
21
|
-
import { createTask, DEFAULT_PUSH, deleteTask, getTask, listTasks,
|
|
21
|
+
import { createTask, DEFAULT_PUSH, deleteTask, getTask, listTasks, PUSH_CHANNELS, taskPush, TASKS_PER_USER, updateTask, type PushChannel, type Task, type TaskInput } from "./tasks.js";
|
|
22
22
|
import { getUser } from "./users.js";
|
|
23
23
|
import { SKILL_TOOL_NAMES, skillToolCall } from "./skills-bridge.js";
|
|
24
24
|
|
|
@@ -131,12 +131,6 @@ async function call(userId: string, convKey: string, tool: string, args: Record<
|
|
|
131
131
|
if (tool === "list_tasks") {
|
|
132
132
|
const tasks = listTasks(user.id);
|
|
133
133
|
const head = `现在是 ${formatDateTime(now)}(${serverTimeZone()})。`;
|
|
134
|
-
if (conv.assistant === "active") {
|
|
135
|
-
const assigned = tasks.filter((t) => taskBelongsToAssistant(t, convKey));
|
|
136
|
-
const rest = tasks.filter((t) => !taskBelongsToAssistant(t, convKey));
|
|
137
|
-
const section = (title: string, list: Task[]) => title + (list.length ? "\n" + list.map((t) => describeTask(t, convKey)).join("\n") : ":无");
|
|
138
|
-
return { text: head + "\n" + section("这个 bot 负责的定时任务", assigned) + "\n" + section("用户的其他定时任务", rest) };
|
|
139
|
-
}
|
|
140
134
|
if (tasks.length === 0) return { text: `${head}用户还没有定时任务。` };
|
|
141
135
|
return { text: `${head}用户有 ${tasks.length} 个定时任务(最多 ${TASKS_PER_USER} 个):\n\n${tasks.map((t) => describeTask(t, convKey)).join("\n")}` };
|
|
142
136
|
}
|
|
@@ -188,7 +182,7 @@ async function call(userId: string, convKey: string, tool: string, args: Record<
|
|
|
188
182
|
);
|
|
189
183
|
if (!ok) return fail("用户没有同意,任务没有建。");
|
|
190
184
|
try {
|
|
191
|
-
const task = createTask(user.id, input, "agent"
|
|
185
|
+
const task = createTask(user.id, input, "agent");
|
|
192
186
|
return {
|
|
193
187
|
text: `已建好 [${task.id}]「${task.title}」:${describeSchedule(task.schedule)},${task.nextRunAt ? `下次 ${formatDateTime(task.nextRunAt)}` : "没有下次"}。用户可以在网页侧栏「定时任务」里查看和修改。`,
|
|
194
188
|
};
|