agent-loft 0.2.127 → 0.2.128
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 +3 -1
- package/bin/cli.js +40 -19
- package/package.json +1 -1
- package/src/agents/claude/session.ts +8 -5
- package/src/agents/codex/session.ts +5 -4
- package/src/agents/dsh/session.ts +3 -1
- package/src/agents/pi/session.ts +4 -3
- package/src/agents/workbuddy/session.ts +6 -3
- package/src/channels/web/api.ts +10 -1
- package/src/channels/web/memo-collab.ts +28 -0
- package/src/channels/web/memo-file.ts +30 -0
- package/src/channels/web/memo-storage.ts +15 -6
- package/src/channels/web/memos-api.ts +23 -21
- package/src/cli/service.ts +3 -1
- package/src/core/db.ts +12 -0
- package/src/core/expert-prompt.ts +2 -1
- package/src/core/hub.ts +4 -0
- package/src/core/mcp.ts +2 -2
- package/src/core/memo-index.ts +154 -0
- package/src/core/memo-sources.ts +33 -5
- package/src/core/memos-bridge.ts +63 -0
- package/src/core/tasks-bridge.ts +6 -0
- package/src/core/tasks-mcp.ts +7 -0
- package/src/core/types.ts +2 -0
- package/src/core/upgrade-health.ts +21 -0
- package/src/core/upgrade-launcher.ts +94 -0
- package/src/core/upgrade-releases.ts +103 -0
- package/src/core/upgrade.ts +54 -18
- package/src/main.ts +14 -0
- package/src/mcp/memo-tools.ts +26 -0
- package/src/mcp/tasks-server.ts +5 -4
- package/web/settings/users.js +41 -15
- package/web/views/memo-dialogs.js +48 -1
- package/web/views/memos.js +2 -2
package/src/core/hub.ts
CHANGED
|
@@ -37,6 +37,8 @@ import {
|
|
|
37
37
|
} from "./store.js";
|
|
38
38
|
import { formatDateTime } from "./task-schedule.js";
|
|
39
39
|
import { attachmentInfo, ensureUploadsDir, KIND_LABEL } from "./uploads.js";
|
|
40
|
+
import { memoAccessEvents, memoSources, hasWritableMemo } from "./memo-sources.js";
|
|
41
|
+
import { MEMO_WRITING_GUIDE } from "../mcp/memo-tools.js";
|
|
40
42
|
import { memoryOwnerOf, sessionMemory } from "./personal.js";
|
|
41
43
|
import { engineSupports, exceedsPermission, forEngine, minPermission, PERMISSION_LABEL, permissionCapOfAccess, permissionOfSandbox, type PermissionLevel } from "./permission.js";
|
|
42
44
|
import { readMemory } from "./memory.js";
|
|
@@ -372,6 +374,7 @@ class Hub extends EventEmitter<{
|
|
|
372
374
|
}
|
|
373
375
|
});
|
|
374
376
|
// 技能装了、改了、停用了、变量改了:受影响的人空闲的会话换上新的
|
|
377
|
+
memoAccessEvents.on("changed", owner => this.personalChanged(new Set([owner])));
|
|
375
378
|
skillEvents.on("changed", (users) => this.personalChanged(new Set(users)));
|
|
376
379
|
// 专家修改只影响自定义专家;MCP 和内置默认配置修改也更新该账号的内置会话。
|
|
377
380
|
expertEvents.on("changed", (_owner, id) => {
|
|
@@ -835,6 +838,7 @@ class Hub extends EventEmitter<{
|
|
|
835
838
|
...(taskOwner && getUser(taskOwner)?.role !== "admin" ? { noSessionGrant: true } : {}),
|
|
836
839
|
...(expert ? { expert } : {}),
|
|
837
840
|
...(memory ? { memory } : {}),
|
|
841
|
+
...(taskOwner && hasWritableMemo(memoSources(taskOwner)) ? { memoPrompt: MEMO_WRITING_GUIDE } : {}),
|
|
838
842
|
...(taskOwner ? { tasks: { userId: taskOwner, convKey: key } } : {}),
|
|
839
843
|
...(skills ? { skills } : {}),
|
|
840
844
|
...(builtin.builtinMcp ? { builtinMcp: builtin.builtinMcp } : {}),
|
package/src/core/mcp.ts
CHANGED
|
@@ -23,7 +23,7 @@ import path from "node:path";
|
|
|
23
23
|
import { EventEmitter } from "node:events";
|
|
24
24
|
import { dataDir, readJson, writeJsonAtomic } from "../home.js";
|
|
25
25
|
import { MEMORY_MCP_NAME } from "./memory-mcp.js";
|
|
26
|
-
import { SKILLS_MCP_NAME, TASKS_MCP_NAME } from "./tasks-mcp.js";
|
|
26
|
+
import { MEMOS_MCP_NAME, SKILLS_MCP_NAME, TASKS_MCP_NAME } from "./tasks-mcp.js";
|
|
27
27
|
import { getUser, listUsers } from "./users.js";
|
|
28
28
|
|
|
29
29
|
export type McpPair = { name: string; value: string; secret: boolean };
|
|
@@ -57,7 +57,7 @@ export type McpSpec =
|
|
|
57
57
|
|
|
58
58
|
export const MCP_NAME = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
59
59
|
const PAIR_NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/;
|
|
60
|
-
const RESERVED = new Set([MEMORY_MCP_NAME, TASKS_MCP_NAME, SKILLS_MCP_NAME]);
|
|
60
|
+
const RESERVED = new Set([MEMORY_MCP_NAME, TASKS_MCP_NAME, SKILLS_MCP_NAME, MEMOS_MCP_NAME]);
|
|
61
61
|
export const MACHINE_PREFIX = "machine:";
|
|
62
62
|
|
|
63
63
|
export const MCP_LIMITS = { perUser: 50, description: 500, command: 1000, args: 50, arg: 2000, pairs: 30, value: 4000, url: 2000 };
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { MemoStorage, editable } from "../channels/web/memo-storage.js";
|
|
2
|
+
import { withMemoLock } from "../channels/web/memo-collab.js";
|
|
3
|
+
import { HttpError } from "../channels/web/http.js";
|
|
4
|
+
import { sql, transaction } from "./db.js";
|
|
5
|
+
import { ftsIndexText, ftsMatch, terms } from "./fts.js";
|
|
6
|
+
import { memoSources, canReadMemo, validMemoPath, type MemoSource } from "./memo-sources.js";
|
|
7
|
+
import { getUser, isAdmin, listUsers } from "./users.js";
|
|
8
|
+
|
|
9
|
+
const scope = "owner = ? AND source = ?";
|
|
10
|
+
type Job = { scanned: number; error?: string; pending?: Promise<void> };
|
|
11
|
+
const jobs = new Map<string, Job>(); // Source IDs are UUIDs.
|
|
12
|
+
let timer: NodeJS.Timeout | undefined;
|
|
13
|
+
|
|
14
|
+
export function indexMemo(owner: string, source: string, path: string, text: string, version: string) {
|
|
15
|
+
const key = [owner, source, path];
|
|
16
|
+
if (sql(`SELECT version FROM memo_documents WHERE ${scope} AND path = ?`).get(...key)?.version === version) return;
|
|
17
|
+
transaction(() => {
|
|
18
|
+
sql(`DELETE FROM memo_documents WHERE ${scope} AND path = ?`).run(...key);
|
|
19
|
+
const { lastInsertRowid } = sql("INSERT INTO memo_documents(owner,source,path,version,body) VALUES(?,?,?,?,?)").run(...key, version, text);
|
|
20
|
+
sql("INSERT INTO memo_fts(rowid,path,body) VALUES(?,?,?)").run(lastInsertRowid, ftsIndexText(path), ftsIndexText(text));
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function clearMemoIndex(owner: string, source: string) {
|
|
25
|
+
jobs.delete(source);
|
|
26
|
+
transaction(() => {
|
|
27
|
+
sql(`DELETE FROM memo_documents WHERE ${scope}`).run(owner, source);
|
|
28
|
+
sql(`DELETE FROM memo_scans WHERE ${scope}`).run(owner, source);
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function memoIndexStatus(owner: string, source: string) {
|
|
33
|
+
const last = sql(`SELECT success FROM memo_scans WHERE ${scope}`).get(owner, source);
|
|
34
|
+
const job = jobs.get(source);
|
|
35
|
+
return { success: Number(last?.success ?? 0), scanned: job?.scanned ?? 0, running: !!job?.pending, error: job?.error };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// A failed local index update must not turn a successful remote PUT into a
|
|
39
|
+
// failed edit. The periodic scan retries it using the remote file as truth.
|
|
40
|
+
export function indexSavedMemo(owner: string, source: string, path: string, text: string, version: string) {
|
|
41
|
+
try { indexMemo(owner, source, path, text, version); }
|
|
42
|
+
catch {
|
|
43
|
+
const job = jobs.get(source) ?? { scanned: 0 };
|
|
44
|
+
job.error = "最近保存的笔记尚未完成索引,请刷新索引";
|
|
45
|
+
jobs.set(source, job);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function* listTextFiles(storage: MemoStorage, current: () => boolean) {
|
|
50
|
+
const folders = new Set([""]);
|
|
51
|
+
for (const folder of folders) {
|
|
52
|
+
let cursor = "";
|
|
53
|
+
const cursors = new Set<string>();
|
|
54
|
+
do {
|
|
55
|
+
if (!current()) return;
|
|
56
|
+
const page = await storage.list(folder, cursor);
|
|
57
|
+
for (const entry of page.entries) {
|
|
58
|
+
const path = folder ? folder + "/" + entry.name : entry.name;
|
|
59
|
+
if (!validMemoPath(path)) continue;
|
|
60
|
+
if (entry.directory) folders.add(path);
|
|
61
|
+
else if (editable(path)) yield { path, etag: entry.etag };
|
|
62
|
+
}
|
|
63
|
+
cursor = page.next;
|
|
64
|
+
if (cursor && cursors.has(cursor)) throw new HttpError(502, "存储服务返回了重复的分页标记");
|
|
65
|
+
cursors.add(cursor);
|
|
66
|
+
} while (cursor);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function refreshMemoIndex(owner: string, source: MemoSource) {
|
|
71
|
+
const pending = jobs.get(source.id)?.pending;
|
|
72
|
+
if (pending || !canReadMemo(source)) return pending;
|
|
73
|
+
const user = getUser(owner);
|
|
74
|
+
if (!user || user.disabled) return;
|
|
75
|
+
const role = user.role;
|
|
76
|
+
const job: Job = { scanned: 0 };
|
|
77
|
+
jobs.set(source.id, job);
|
|
78
|
+
const storage = new MemoStorage(source, isAdmin(user));
|
|
79
|
+
const current = () => {
|
|
80
|
+
const active = getUser(owner);
|
|
81
|
+
return jobs.get(source.id) === job && !!active && !active.disabled && active.role === role &&
|
|
82
|
+
memoSources(owner).some(s => s.id === source.id && canReadMemo(s));
|
|
83
|
+
};
|
|
84
|
+
job.pending = scanMemoSource(owner, source.id, storage, job, current).finally(() => { job.pending = undefined; });
|
|
85
|
+
return job.pending;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
async function scanMemoSource(owner: string, source: string, storage: MemoStorage, job: Job, current: () => boolean) {
|
|
89
|
+
try {
|
|
90
|
+
// Only prune rows present at the start. Concurrent saves get a new row ID.
|
|
91
|
+
const old = sql(`SELECT id,path,version FROM memo_documents WHERE ${scope}`).all(owner, source);
|
|
92
|
+
const missing = new Map(old.map(row => [String(row.path), row]));
|
|
93
|
+
for await (const { path, etag } of listTextFiles(storage, current)) {
|
|
94
|
+
if (!current()) return;
|
|
95
|
+
const previous = missing.get(path);
|
|
96
|
+
missing.delete(path);
|
|
97
|
+
job.scanned++;
|
|
98
|
+
if (etag && etag === previous?.version) continue;
|
|
99
|
+
await withMemoLock(storage.objectURL(path).href, async () => {
|
|
100
|
+
if (!current()) return;
|
|
101
|
+
try {
|
|
102
|
+
const file = await storage.readText(path);
|
|
103
|
+
if (current()) indexMemo(owner, source, path, file.text, file.version);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
if (!(err instanceof HttpError && [404, 413, 415].includes(err.status))) throw err;
|
|
106
|
+
if (previous) missing.set(path, previous);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
if (!current()) return;
|
|
111
|
+
transaction(() => {
|
|
112
|
+
for (const row of missing.values()) sql("DELETE FROM memo_documents WHERE id = ?").run(row.id!);
|
|
113
|
+
sql("INSERT OR REPLACE INTO memo_scans VALUES(?,?,?)").run(owner, source, Date.now());
|
|
114
|
+
});
|
|
115
|
+
} catch (err) {
|
|
116
|
+
job.error = err instanceof HttpError ? err.message : "索引更新失败,请重新刷新";
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function startMemoIndexer() {
|
|
121
|
+
if (timer) return;
|
|
122
|
+
const refresh = () => {
|
|
123
|
+
for (const user of listUsers()) {
|
|
124
|
+
if (!user.disabled) for (const source of memoSources(user.id)) {
|
|
125
|
+
if (canReadMemo(source)) void refreshMemoIndex(user.id, source);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
refresh();
|
|
130
|
+
timer = setInterval(refresh, 10 * 60_000);
|
|
131
|
+
timer.unref();
|
|
132
|
+
}
|
|
133
|
+
export function stopMemoIndexer() { clearInterval(timer); timer = undefined; jobs.clear(); }
|
|
134
|
+
|
|
135
|
+
export function searchMemos(owner: string, sources: MemoSource[], query: string, folder: string) {
|
|
136
|
+
if (query.length > 512) throw new HttpError(400, "搜索关键词限 512 字符");
|
|
137
|
+
const match = ftsMatch(query);
|
|
138
|
+
if (!match) throw new HttpError(400, "请输入搜索关键词");
|
|
139
|
+
const libraries = sources.map(s => ({ id: s.id, name: s.name, ...memoIndexStatus(owner, s.id) }));
|
|
140
|
+
if (!sources.length) return { libraries, hits: [] };
|
|
141
|
+
const slots = sources.map(() => "?").join(",");
|
|
142
|
+
const prefix = folder ? folder + "/" : "";
|
|
143
|
+
const rows = sql(`SELECT d.source,d.path,d.body FROM memo_fts JOIN memo_documents d ON d.id = memo_fts.rowid
|
|
144
|
+
WHERE memo_fts MATCH ? AND d.owner = ? AND d.source IN (${slots}) AND substr(d.path,1,length(?)) = ?
|
|
145
|
+
ORDER BY bm25(memo_fts, 4, 1), d.path LIMIT 20`).all(match, owner, ...sources.map(s => s.id), prefix, prefix);
|
|
146
|
+
const words = terms(query);
|
|
147
|
+
const hits = rows.map(row => {
|
|
148
|
+
const body = String(row.body), lower = body.toLowerCase();
|
|
149
|
+
const at = words.map(w => lower.indexOf(w)).find(i => i >= 0) ?? 0;
|
|
150
|
+
return { source: row.source, library: sources.find(s => s.id === row.source)?.name, path: row.path,
|
|
151
|
+
snippet: body.slice(Math.max(0, at - 60), at + 140) };
|
|
152
|
+
});
|
|
153
|
+
return { libraries, hits };
|
|
154
|
+
}
|
package/src/core/memo-sources.ts
CHANGED
|
@@ -1,17 +1,25 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
|
+
import { EventEmitter } from "node:events";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import { dataDir, readJson, writeJsonAtomic } from "../home.js";
|
|
5
6
|
import { sql } from "./db.js";
|
|
6
7
|
|
|
8
|
+
export type MemoAccess = "off" | "read" | "write";
|
|
9
|
+
export function parseMemoAccess(value: unknown): MemoAccess {
|
|
10
|
+
if (value === "off" || value === "read" || value === "write") return value;
|
|
11
|
+
throw new Error("智能体访问权限无效");
|
|
12
|
+
}
|
|
13
|
+
export const canReadMemo = (source: MemoSource) => source.access === "read" || source.access === "write";
|
|
14
|
+
|
|
7
15
|
export type MemoSource = {
|
|
8
|
-
id: string; name: string; kind: "webdav" | "s3"; endpoint: string;
|
|
16
|
+
access?: MemoAccess; id: string; name: string; kind: "webdav" | "s3"; endpoint: string;
|
|
9
17
|
username: string; secret: string; bucket: string; region: string; prefix: string;
|
|
10
18
|
};
|
|
11
19
|
|
|
12
20
|
const file = (user: string) => path.join(dataDir, "memo-sources", encodeURIComponent(user) + ".json");
|
|
13
21
|
export const memoSources = (user: string) => readJson<MemoSource[]>(file(user), []);
|
|
14
|
-
export const publicSource = ({ id, name, kind }: MemoSource) => ({ id, name, kind });
|
|
22
|
+
export const publicSource = ({ id, name, kind, access }: MemoSource) => ({ id, name, kind, access: access ?? "off" });
|
|
15
23
|
// A connection can be removed and re-added with a new password or display name.
|
|
16
24
|
export function memoHistoryKey(s: MemoSource): string {
|
|
17
25
|
const library = [s.kind, s.endpoint, s.username];
|
|
@@ -21,6 +29,8 @@ export function memoHistoryKey(s: MemoSource): string {
|
|
|
21
29
|
|
|
22
30
|
export function deleteMemoSources(user: string) {
|
|
23
31
|
fs.rmSync(file(user), { force: true });
|
|
32
|
+
sql("DELETE FROM memo_documents WHERE owner = ?").run(user);
|
|
33
|
+
sql("DELETE FROM memo_scans WHERE owner = ?").run(user);
|
|
24
34
|
sql("DELETE FROM memo_versions WHERE owner = ?").run(user);
|
|
25
35
|
}
|
|
26
36
|
|
|
@@ -41,14 +51,32 @@ export function parseMemoSource(input: Record<string, unknown>): MemoSource {
|
|
|
41
51
|
const url = new URL(str("endpoint").trim() || (kind === "s3" ? `https://s3.${region}.amazonaws.com` : ""));
|
|
42
52
|
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("请输入 HTTP(S) 服务地址,凭据请单独填写");
|
|
43
53
|
url.pathname = url.pathname.replace(/\/*$/, "/");
|
|
44
|
-
return { id: randomUUID(), name, kind, endpoint: url.href, username, secret, region, bucket, prefix };
|
|
54
|
+
return { access: parseMemoAccess(input.access ?? "off"), id: randomUUID(), name, kind, endpoint: url.href, username, secret, region, bucket, prefix };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export const memoAccessEvents = new EventEmitter<{ changed: [string] }>();
|
|
58
|
+
export const hasWritableMemo = (sources: MemoSource[]) => sources.some(s => s.access === "write");
|
|
59
|
+
|
|
60
|
+
function saveSources(user: string, previous: MemoSource[], next: MemoSource[]) {
|
|
61
|
+
writeJsonAtomic(file(user), next);
|
|
62
|
+
if (hasWritableMemo(previous) !== hasWritableMemo(next)) memoAccessEvents.emit("changed", user);
|
|
45
63
|
}
|
|
46
64
|
|
|
47
65
|
export function addMemoSource(user: string, source: MemoSource) {
|
|
48
66
|
const sources = memoSources(user);
|
|
49
|
-
|
|
67
|
+
saveSources(user, sources, [...sources, source]);
|
|
50
68
|
}
|
|
51
69
|
|
|
52
70
|
export function removeMemoSource(user: string, id: string) {
|
|
53
|
-
|
|
71
|
+
const sources = memoSources(user);
|
|
72
|
+
saveSources(user, sources, sources.filter(s => s.id !== id));
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function setMemoAccess(user: string, id: string, access: MemoAccess) {
|
|
76
|
+
const sources = memoSources(user);
|
|
77
|
+
const source = sources.find(s => s.id === id);
|
|
78
|
+
if (!source) throw new Error("笔记库已断开");
|
|
79
|
+
const updated = { ...source, access };
|
|
80
|
+
saveSources(user, sources, sources.map(s => s.id === id ? updated : s));
|
|
81
|
+
return updated;
|
|
54
82
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { HttpError } from "../channels/web/http.js";
|
|
2
|
+
import { editMemoRange, invalidateMemo, withMemoLock } from "../channels/web/memo-collab.js";
|
|
3
|
+
import { memoFile } from "../channels/web/memo-file.js";
|
|
4
|
+
import { MemoStorage } from "../channels/web/memo-storage.js";
|
|
5
|
+
import { MEMO_TOOLS } from "../mcp/memo-tools.js";
|
|
6
|
+
import { searchMemos } from "./memo-index.js";
|
|
7
|
+
import { canReadMemo, memoSources, publicSource, validMemoPath } from "./memo-sources.js";
|
|
8
|
+
import { memoryOwnerOf } from "./personal.js";
|
|
9
|
+
import { getConversation } from "./store.js";
|
|
10
|
+
import { getUser, isAdmin } from "./users.js";
|
|
11
|
+
|
|
12
|
+
export async function memoToolCall(owner: string, convKey: string, name: string, args: Record<string, unknown>) {
|
|
13
|
+
const tool = MEMO_TOOLS.find(t => t.name === name);
|
|
14
|
+
if (!tool) throw new HttpError(400, "未知备忘录操作");
|
|
15
|
+
const { properties, required } = tool.inputSchema;
|
|
16
|
+
if (Object.keys(args).some(k => !Object.hasOwn(properties, k) || typeof args[k] !== "string") ||
|
|
17
|
+
required.some(k => typeof args[k] !== "string")) throw new HttpError(400, "备忘录工具参数无效");
|
|
18
|
+
const { source: id, path, version, text, original, folder = "", query, cursor } = args as Record<string, string>;
|
|
19
|
+
if (folder && !validMemoPath(folder)) throw new HttpError(400, "笔记目录无效");
|
|
20
|
+
const authorize = () => {
|
|
21
|
+
const conv = getConversation(convKey), user = getUser(owner);
|
|
22
|
+
if (!conv || !user || user.disabled || memoryOwnerOf(conv) !== owner) throw new HttpError(403, "当前对话无权访问备忘录");
|
|
23
|
+
const sources = memoSources(owner).filter(canReadMemo);
|
|
24
|
+
const source = sources.find(s => s.id === id);
|
|
25
|
+
if (id !== undefined && !source) throw new HttpError(404, "未找到已授权的笔记库");
|
|
26
|
+
if (!tool.annotations.readOnlyHint && (source?.access !== "write" || conv.plan)) throw new HttpError(403, "当前笔记库或对话仅允许读取");
|
|
27
|
+
return { user, sources, source };
|
|
28
|
+
};
|
|
29
|
+
const { user, sources, source } = authorize();
|
|
30
|
+
if (name === "list_memo_sources") return sources.map(publicSource);
|
|
31
|
+
if (name === "search_memos") return searchMemos(owner, source ? [source] : sources, query!, folder);
|
|
32
|
+
if (!source) throw new HttpError(400, "请选择笔记库");
|
|
33
|
+
const role = user.role;
|
|
34
|
+
const check = () => {
|
|
35
|
+
if (authorize().user.role !== role) throw new HttpError(403, "账号权限已变更");
|
|
36
|
+
};
|
|
37
|
+
if (name === "list_memo_files") {
|
|
38
|
+
const page = await new MemoStorage(source, isAdmin(user)).list(folder, cursor);
|
|
39
|
+
check();
|
|
40
|
+
return page;
|
|
41
|
+
}
|
|
42
|
+
const file = memoFile(user, source, path!, check);
|
|
43
|
+
return withMemoLock(file.lockKey, async () => {
|
|
44
|
+
check();
|
|
45
|
+
if (name === "create_memo") {
|
|
46
|
+
const saved = await file.persist(text!, null);
|
|
47
|
+
invalidateMemo(file.key);
|
|
48
|
+
return { version: saved };
|
|
49
|
+
}
|
|
50
|
+
const latest = await file.read();
|
|
51
|
+
check();
|
|
52
|
+
if (name === "read_memo") return latest;
|
|
53
|
+
if (version !== latest.version) throw new HttpError(409, "笔记版本已变更,请重新读取后修改");
|
|
54
|
+
let start = latest.text.length, end = start;
|
|
55
|
+
if (name === "edit_memo") {
|
|
56
|
+
if (!original) throw new HttpError(400, "请选择一段非空原文");
|
|
57
|
+
start = latest.text.indexOf(original);
|
|
58
|
+
if (start < 0 || latest.text.indexOf(original, start + 1) >= 0) throw new HttpError(409, "原文未找到或出现多次,请重新选择唯一片段");
|
|
59
|
+
end = start + original.length;
|
|
60
|
+
}
|
|
61
|
+
return { version: await editMemoRange(file.key, file.account, latest.text, version, start, end, text!, file.persist) };
|
|
62
|
+
});
|
|
63
|
+
}
|
package/src/core/tasks-bridge.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { memoToolCall } from "./memos-bridge.js";
|
|
2
|
+
import { MEMO_TOOLS } from "../mcp/memo-tools.js";
|
|
1
3
|
// 主进程这头的定时任务工具:mcp/tasks-server.ts 经 unix socket 把 agent 的调用转过来,这里核对身份、
|
|
2
4
|
// 弹授权卡、真正增删改。
|
|
3
5
|
//
|
|
@@ -119,6 +121,10 @@ function card(fields: { schedule?: TaskSchedule; notify?: string; push?: PushCha
|
|
|
119
121
|
}
|
|
120
122
|
|
|
121
123
|
async function call(userId: string, convKey: string, tool: string, args: Record<string, unknown>): Promise<Reply> {
|
|
124
|
+
if (MEMO_TOOLS.some(t => t.name === tool)) {
|
|
125
|
+
try { return { text: JSON.stringify(await memoToolCall(userId, convKey, tool, args)) }; }
|
|
126
|
+
catch (err) { return fail(err instanceof Error ? err.message : "备忘录操作失败"); }
|
|
127
|
+
}
|
|
122
128
|
const user = getUser(userId);
|
|
123
129
|
if (!user || user.disabled) return fail("账号已停用。");
|
|
124
130
|
const conv = getConversation(convKey);
|
package/src/core/tasks-mcp.ts
CHANGED
|
@@ -42,6 +42,13 @@ export function verifyTaskCaller(userId: string, convKey: string, sig: string):
|
|
|
42
42
|
*/
|
|
43
43
|
export const SKILLS_MCP_NAME = "agent_loft_skills";
|
|
44
44
|
|
|
45
|
+
export const MEMOS_MCP_NAME = "agent_loft_memos";
|
|
46
|
+
|
|
47
|
+
export function memosMcpSpawn(userId: string, convKey: string, via: string): StdioSpawn {
|
|
48
|
+
const base = tasksMcpSpawn(userId, convKey, via);
|
|
49
|
+
return { ...base, env: { ...base.env, AGENT_LOFT_TOOLSET: "memos" } };
|
|
50
|
+
}
|
|
51
|
+
|
|
45
52
|
export function skillsMcpSpawn(userId: string, convKey: string, via: string): StdioSpawn {
|
|
46
53
|
const base = tasksMcpSpawn(userId, convKey, via);
|
|
47
54
|
return { ...base, env: { ...base.env, AGENT_LOFT_TOOLSET: "skills" } };
|
package/src/core/types.ts
CHANGED
|
@@ -260,6 +260,8 @@ export type SessionOptions = {
|
|
|
260
260
|
* 不给就是内置专家:原装提示词和工具,技能与 MCP 按账号的内置默认配置加载。
|
|
261
261
|
*/
|
|
262
262
|
expert?: ExpertRuntime;
|
|
263
|
+
/** 当前主人有授权的可写笔记库时提供的整理说明。 */
|
|
264
|
+
memoPrompt?: string;
|
|
263
265
|
/** 这条对话主人的记忆:prompt 拼进系统提示,userId 交给记忆工具(记给谁由这里定死) */
|
|
264
266
|
memory?: {
|
|
265
267
|
userId: string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
|
|
3
|
+
export async function verifyUpgradeWeb(host: string, port: number): Promise<void> {
|
|
4
|
+
if (host === "0.0.0.0") host = "127.0.0.1";
|
|
5
|
+
if (host === "::") host = "::1";
|
|
6
|
+
const base = `http://${isIP(host) === 6 ? "[" + host + "]" : host}:${port}`;
|
|
7
|
+
async function get(url: string, type: RegExp): Promise<Response> {
|
|
8
|
+
const res = await fetch(base + url, { signal: AbortSignal.timeout(10_000), redirect: "error" });
|
|
9
|
+
if (res.status !== 200 || !type.test(res.headers.get("content-type") || "")) {
|
|
10
|
+
throw new Error(`${url} 响应异常(HTTP ${res.status})`);
|
|
11
|
+
}
|
|
12
|
+
return res;
|
|
13
|
+
}
|
|
14
|
+
const html = await (await get("/", /text\/html/)).text();
|
|
15
|
+
for (const [file, type] of [["app.js", /javascript/], ["css/base.css", /text\/css/]] as const) {
|
|
16
|
+
const asset = [...html.matchAll(/(?:src|href)="(\/[^"]+)"/g)].find(([, url]) => url?.endsWith("/" + file))?.[1];
|
|
17
|
+
if (!asset || !(await (await get(asset, type)).text()).trim()) throw new Error(`网页资源缺失:${file}`);
|
|
18
|
+
}
|
|
19
|
+
const me = await (await get("/api/me", /application\/json/)).json();
|
|
20
|
+
if (!me || typeof me !== "object" || !("authed" in me) || typeof me.authed !== "boolean") throw new Error("/api/me 响应异常");
|
|
21
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// 由原 npm 命令入口加载。试运行期间由旧版监督启动,候选进程即使无法加载 tsx 也能回退。
|
|
2
|
+
import { fork } from "node:child_process";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { markInUse, pidAlive, readRelease, releaseRoot, type Release } from "./upgrade-releases.js";
|
|
7
|
+
|
|
8
|
+
async function tryRelease(store: string, pending: Release): Promise<boolean> {
|
|
9
|
+
const dir = path.join(store, pending.slot);
|
|
10
|
+
const marker = path.join(dir, "trial");
|
|
11
|
+
try {
|
|
12
|
+
fs.linkSync(markInUse(dir), marker);
|
|
13
|
+
} catch (err) {
|
|
14
|
+
if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
|
|
15
|
+
const pid = Number(fs.readFileSync(marker, "utf8"));
|
|
16
|
+
if (pid !== process.pid && pidAlive(pid)) return false;
|
|
17
|
+
recordFailure("上次验证被中断");
|
|
18
|
+
return false;
|
|
19
|
+
}
|
|
20
|
+
function recordFailure(reason: string) {
|
|
21
|
+
const message = `${pending.version} 启动验证失败,已回退:${reason}`;
|
|
22
|
+
console.error("[升级]", message);
|
|
23
|
+
if (readRelease(store, "pending")?.slot !== pending.slot) return;
|
|
24
|
+
fs.renameSync(path.join(store, "pending.json"), path.join(dir, "failed.json"));
|
|
25
|
+
try { fs.writeFileSync(path.join(store, "last-error"), message); }
|
|
26
|
+
catch (err) { console.error("[升级] 保存错误信息失败", err); }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const child = fork(path.join(releaseRoot(store, pending), "bin/cli.js"), process.argv.slice(2), {
|
|
30
|
+
execArgv: [], stdio: ["inherit", "inherit", "inherit", "ipc"],
|
|
31
|
+
env: { ...process.env, AGENT_LOFT_UPGRADE_TRIAL: pending.slot },
|
|
32
|
+
});
|
|
33
|
+
let ready = false;
|
|
34
|
+
let stopping = false;
|
|
35
|
+
let failure = "新版进程在验证前退出";
|
|
36
|
+
const stop = (signal: NodeJS.Signals) => { stopping = true; child.kill(signal); };
|
|
37
|
+
process.on("SIGINT", stop);
|
|
38
|
+
process.on("SIGTERM", stop);
|
|
39
|
+
const timer = setTimeout(() => { failure = "启动验证超时"; child.kill("SIGKILL"); }, 120_000);
|
|
40
|
+
try {
|
|
41
|
+
child.on("message", (msg) => {
|
|
42
|
+
const result = msg as { type?: string; version?: string; error?: string };
|
|
43
|
+
if (ready || stopping || result?.type !== "upgrade-health") return;
|
|
44
|
+
if (result.version !== pending.version || result.error) {
|
|
45
|
+
failure = result.error || "运行版本不匹配";
|
|
46
|
+
child.kill("SIGTERM");
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
fs.rmSync(path.join(store, "last-error"), { force: true });
|
|
51
|
+
fs.renameSync(path.join(store, "pending.json"), path.join(store, "active.json"));
|
|
52
|
+
ready = true;
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
console.log(`[升级] 已验证并启用 ${pending.version}`);
|
|
55
|
+
} catch (err) {
|
|
56
|
+
failure = String(err);
|
|
57
|
+
child.kill("SIGTERM");
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
const code = await new Promise<number>((resolve) => {
|
|
61
|
+
child.once("error", (err) => { failure = err.message; });
|
|
62
|
+
child.once("close", (code) => resolve(code ?? 1));
|
|
63
|
+
});
|
|
64
|
+
if (ready || stopping) {
|
|
65
|
+
process.exitCode = code;
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
recordFailure(failure);
|
|
69
|
+
return false;
|
|
70
|
+
} finally {
|
|
71
|
+
clearTimeout(timer);
|
|
72
|
+
process.off("SIGINT", stop);
|
|
73
|
+
process.off("SIGTERM", stop);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function launchRelease(store: string): Promise<boolean> {
|
|
78
|
+
if ((process.argv[2] ?? "start") === "start") {
|
|
79
|
+
const pending = readRelease(store, "pending");
|
|
80
|
+
if (pending) {
|
|
81
|
+
try {
|
|
82
|
+
if (await tryRelease(store, pending)) return true;
|
|
83
|
+
} catch (err) {
|
|
84
|
+
console.error("[升级] 无法开始或完成验证,启动已验证版本", err);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const active = readRelease(store, "active");
|
|
89
|
+
if (!active) return false;
|
|
90
|
+
try { markInUse(path.join(store, active.slot)); }
|
|
91
|
+
catch (err) { console.warn("[升级] 无法记录版本占用", err); }
|
|
92
|
+
await import(pathToFileURL(path.join(releaseRoot(store, active), "bin/cli.js")).href);
|
|
93
|
+
return true;
|
|
94
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// 全局安装保留最初的 CLI 入口。npm 只写独立 prefix,重启验证通过后原子切换版本记录。
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
|
|
5
|
+
const storeName = ".agent-loft-releases";
|
|
6
|
+
const modules = process.platform === "win32" ? "node_modules" : path.join("lib", "node_modules");
|
|
7
|
+
const slotPattern = /^release-[a-zA-Z0-9]{6}$/;
|
|
8
|
+
|
|
9
|
+
export function releaseStore(packageRoot: string): string {
|
|
10
|
+
const prefix = path.resolve(packageRoot, process.platform === "win32" ? "../.." : "../../..");
|
|
11
|
+
if (slotPattern.test(path.basename(prefix)) && path.basename(path.dirname(prefix)) === storeName) {
|
|
12
|
+
return path.dirname(prefix);
|
|
13
|
+
}
|
|
14
|
+
return path.join(packageRoot, storeName);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type Release = { slot: string; version: string };
|
|
18
|
+
export type ReleaseRecord = "pending" | "active";
|
|
19
|
+
|
|
20
|
+
export function releaseRoot(store: string, release: Release): string {
|
|
21
|
+
if (!slotPattern.test(release.slot)) throw new Error("更新目录无效");
|
|
22
|
+
return path.join(store, release.slot, modules, "agent-loft");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function readRelease(store: string, record: ReleaseRecord): Release | undefined {
|
|
26
|
+
try {
|
|
27
|
+
const release = JSON.parse(fs.readFileSync(path.join(store, record + ".json"), "utf8"));
|
|
28
|
+
releaseRoot(store, release);
|
|
29
|
+
return release;
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function pidAlive(pid: number): boolean {
|
|
36
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false;
|
|
37
|
+
try {
|
|
38
|
+
process.kill(pid, 0);
|
|
39
|
+
return true;
|
|
40
|
+
} catch (err) {
|
|
41
|
+
return (err as NodeJS.ErrnoException).code !== "ESRCH";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function markInUse(dir: string): string {
|
|
46
|
+
const file = path.join(dir, "pid-" + process.pid);
|
|
47
|
+
fs.writeFileSync(file, String(process.pid));
|
|
48
|
+
return file;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// 清理中断的下载和已替换的版本。其他实例还在使用的目录要留到以后。
|
|
52
|
+
async function pruneReleases(store: string): Promise<void> {
|
|
53
|
+
for (const slot of fs.readdirSync(store).filter(name => slotPattern.test(name))) {
|
|
54
|
+
const dir = path.join(store, slot);
|
|
55
|
+
try {
|
|
56
|
+
const pids = fs.readdirSync(dir).filter(name => name.startsWith("pid-"));
|
|
57
|
+
if (!pids.length || pids.some(name => pidAlive(Number(name.slice(4))))) continue;
|
|
58
|
+
if (readRelease(store, "active")?.slot === slot || readRelease(store, "pending")?.slot === slot) continue;
|
|
59
|
+
await fs.promises.rm(dir, { recursive: true, force: true });
|
|
60
|
+
} catch (err) {
|
|
61
|
+
if ((err as NodeJS.ErrnoException).code !== "ENOENT") console.warn("[升级] 无法清理旧版本", err);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// link 在同一文件系统内一次性发布完整记录,另一个进程先提交时不会覆盖它。
|
|
67
|
+
function queueRelease(store: string, release: Release): void {
|
|
68
|
+
const manifest = path.join(store, release.slot, "release.json");
|
|
69
|
+
fs.writeFileSync(manifest, JSON.stringify(release));
|
|
70
|
+
fs.linkSync(manifest, path.join(store, "pending.json"));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function stageRelease(
|
|
74
|
+
root: string, version: string,
|
|
75
|
+
install: (prefix: string) => Promise<string>,
|
|
76
|
+
checkCli: (cli: string) => Promise<void>,
|
|
77
|
+
): Promise<string> {
|
|
78
|
+
const store = releaseStore(root);
|
|
79
|
+
fs.mkdirSync(store, { recursive: true });
|
|
80
|
+
if (readRelease(store, "pending")) throw new Error("已有更新等待重启验证");
|
|
81
|
+
const active = readRelease(store, "active");
|
|
82
|
+
if ((active ? releaseRoot(store, active) : path.dirname(store)) !== root) throw new Error("运行版本已变更,请先重启服务");
|
|
83
|
+
await pruneReleases(store);
|
|
84
|
+
const prefix = fs.mkdtempSync(path.join(store, "release-"));
|
|
85
|
+
const release = { slot: path.basename(prefix), version };
|
|
86
|
+
try {
|
|
87
|
+
markInUse(prefix);
|
|
88
|
+
const output = await install(prefix);
|
|
89
|
+
const candidate = releaseRoot(store, release);
|
|
90
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(candidate, "package.json"), "utf8"));
|
|
91
|
+
if (pkg.name !== "agent-loft" || pkg.version !== version) throw new Error("安装包名称或版本不匹配");
|
|
92
|
+
for (const file of ["src/main.ts", "web/index.html", "web/app.js", "web/css/base.css"]) {
|
|
93
|
+
if (!fs.statSync(path.join(candidate, file)).size) throw new Error(`更新包文件为空:${file}`);
|
|
94
|
+
}
|
|
95
|
+
await checkCli(path.join(candidate, "bin/cli.js"));
|
|
96
|
+
if (readRelease(store, "active")?.slot !== active?.slot) throw new Error("运行版本已变更,请先重启服务");
|
|
97
|
+
queueRelease(store, release);
|
|
98
|
+
return output;
|
|
99
|
+
} catch (err) {
|
|
100
|
+
await fs.promises.rm(prefix, { recursive: true, force: true }).catch(cleanup => console.warn("[升级] 清理安装目录失败", cleanup));
|
|
101
|
+
throw err;
|
|
102
|
+
}
|
|
103
|
+
}
|