agent-loft 0.2.127 → 0.2.129

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.
Files changed (41) hide show
  1. package/README.md +5 -2
  2. package/bin/cli.js +40 -19
  3. package/package.json +1 -1
  4. package/src/agents/claude/session.ts +8 -5
  5. package/src/agents/codex/session.ts +5 -4
  6. package/src/agents/dsh/session.ts +3 -1
  7. package/src/agents/pi/session.ts +4 -3
  8. package/src/agents/workbuddy/session.ts +6 -3
  9. package/src/channels/web/api.ts +10 -1
  10. package/src/channels/web/experts-api.ts +32 -8
  11. package/src/channels/web/memo-collab.ts +28 -0
  12. package/src/channels/web/memo-file.ts +30 -0
  13. package/src/channels/web/memo-storage.ts +15 -6
  14. package/src/channels/web/memos-api.ts +96 -37
  15. package/src/cli/service.ts +3 -1
  16. package/src/core/db.ts +12 -0
  17. package/src/core/expert-prompt.ts +2 -1
  18. package/src/core/experts.ts +2 -0
  19. package/src/core/hub.ts +13 -0
  20. package/src/core/mcp.ts +2 -2
  21. package/src/core/memo-index.ts +167 -0
  22. package/src/core/memo-sources.ts +113 -5
  23. package/src/core/memos-bridge.ts +69 -0
  24. package/src/core/tasks-bridge.ts +6 -0
  25. package/src/core/tasks-mcp.ts +7 -0
  26. package/src/core/types.ts +2 -0
  27. package/src/core/upgrade-health.ts +21 -0
  28. package/src/core/upgrade-launcher.ts +94 -0
  29. package/src/core/upgrade-releases.ts +103 -0
  30. package/src/core/upgrade.ts +54 -18
  31. package/src/main.ts +14 -0
  32. package/src/mcp/memo-tools.ts +26 -0
  33. package/src/mcp/tasks-server.ts +5 -4
  34. package/web/css/memos.css +3 -1
  35. package/web/lib/memo-access.js +28 -0
  36. package/web/settings/agent-defaults.js +4 -1
  37. package/web/settings/experts.js +7 -2
  38. package/web/settings/users.js +41 -15
  39. package/web/views/file-editor.js +2 -1
  40. package/web/views/memo-dialogs.js +88 -4
  41. package/web/views/memos.js +50 -15
@@ -1,38 +1,112 @@
1
+ import { memoFile } from "./memo-file.js";
2
+ import { clearMemoIndex, memoIndexStatus, refreshMemoIndex, syncMemoIndexAccess } from "../../core/memo-index.js";
1
3
  import type { IncomingMessage, ServerResponse } from "node:http";
2
- import { createHash, randomUUID } from "node:crypto";
4
+ import { randomUUID } from "node:crypto";
3
5
  import { invalidateMemo, joinMemo, pullMemo, pushMemo, withMemoLock } from "./memo-collab.js";
4
6
  import { posix } from "node:path";
5
- import { addMemoSource, memoHistoryKey, memoSources, parseMemoSource, publicSource, removeMemoSource, validMemoPath } from "../../core/memo-sources.js";
6
- import { memoVersions, memoVersionText, rememberMemoVersion } from "../../core/memo-versions.js";
7
+ import { addMemoSource, canReadMemo, parseMemoAccess, setMemoAccess, memberAccess, memoHistoryKey, memoSources, parseMemoSource, sourceSettings, removeMemoSource, setMemoSharing, validMemoPath, visibleMemoSources, type MemoAccess } from "../../core/memo-sources.js";
8
+ import { canUseExpert } from "../../core/experts.js";
9
+ import { memoVersions, memoVersionText } from "../../core/memo-versions.js";
7
10
  import { sniff } from "../../core/uploads.js";
8
- import { isAdmin, type User } from "../../core/users.js";
11
+ import { getUser, isAdmin, listUsers, type User } from "../../core/users.js";
9
12
  import { HttpError, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
10
13
  import { editable, IMAGE_LIMIT, MemoStorage, TEXT_LIMIT } from "./memo-storage.js";
11
14
 
15
+ function parseExpertAccess(value: unknown, owner: string, previous: Record<string, MemoAccess> = {}) {
16
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new HttpError(400, "专家权限无效");
17
+ return Object.fromEntries(Object.entries(value).map(([id, access]) => {
18
+ if (!Object.hasOwn(previous, id) && !canUseExpert(owner, id)) throw new HttpError(400, "专家不可用,请刷新后重试");
19
+ return [id, parseMemoAccess(access)] as const;
20
+ }));
21
+ }
22
+
12
23
  export async function handleMemosApi(req: IncomingMessage, res: ServerResponse, url: URL, user: User, current: () => User | undefined) {
13
24
  const action = url.pathname.slice("/api/memos/".length);
14
25
  const method = req.method;
15
- if (action === "sources" && method === "GET") return sendJson(res, 200, memoSources(user.id).map(publicSource));
26
+ if (action === "sources" && method === "GET") return sendJson(res, 200, visibleMemoSources(user));
16
27
  if (action === "sources" && method === "POST") {
17
28
  const body = await readJsonBody(req, 16_384);
18
29
  let source;
19
- try { source = parseMemoSource(body); }
30
+ try {
31
+ source = parseMemoSource(body);
32
+ if (body.expertAccess !== undefined) source.expertAccess = parseExpertAccess(body.expertAccess, user.id);
33
+ }
20
34
  catch (err) { throw new HttpError(400, err instanceof Error ? err.message : "数据源配置无效"); }
21
35
  await new MemoStorage(source, isAdmin(user)).list("");
22
36
  addMemoSource(user.id, source);
23
- return sendJson(res, 201, publicSource(source));
37
+ if (canReadMemo(source)) void refreshMemoIndex(user.id, source);
38
+ return sendJson(res, 201, sourceSettings(source));
39
+ }
40
+ const owner = getUser(url.searchParams.get("owner") ?? user.id);
41
+ const id = url.searchParams.get("source");
42
+ if (!owner || owner.disabled) throw new HttpError(404, "笔记库不存在");
43
+ const mine = owner.id === user.id;
44
+ const ownerId = owner.id;
45
+ const ownerRole = owner.role;
46
+ const writing = method !== "GET";
47
+ function authorize() {
48
+ const source = memoSources(ownerId).find(s => s.id === id);
49
+ if (!source) throw new HttpError(404, "笔记库不存在");
50
+ if (!mine) {
51
+ const permission = memberAccess(source, user.id);
52
+ if (!permission) throw new HttpError(404, "笔记库不存在或共享已撤回");
53
+ if (!["tree", "file", "changes", "history", "image", "folder", "attachment"].includes(action)) throw new HttpError(403, "只有库主可以管理笔记库");
54
+ if (writing && permission !== "write") throw new HttpError(403, "此笔记库共享为只读");
55
+ }
56
+ return source;
57
+ }
58
+ const source = authorize();
59
+ const checkAccess = () => {
60
+ const active = current(), activeOwner = getUser(owner.id);
61
+ if (active?.id !== user.id || active.disabled || active.role !== user.role || !activeOwner || activeOwner.disabled || activeOwner.role !== ownerRole) throw new HttpError(403, "笔记库访问权限已变更");
62
+ return authorize();
63
+ };
64
+ if (action === "sharing" && method === "GET") {
65
+ const members = listUsers().filter(u => u.id !== user.id && (!u.disabled || memberAccess(source, u.id)));
66
+ return sendJson(res, 200, members.map(u => ({ id: u.id, name: u.name, disabled: u.disabled, access: memberAccess(source, u.id) ?? "off" })));
67
+ }
68
+ if (action === "sharing" && method === "PUT") {
69
+ const body = await readJsonBody(req, 65_536);
70
+ checkAccess();
71
+ try { setMemoSharing(owner.id, source.id, body?.changes); }
72
+ catch (err) { throw new HttpError(400, err instanceof Error ? err.message : "共享设置无效"); }
73
+ return sendJson(res, 200, { ok: true });
24
74
  }
25
- const source = memoSources(user.id).find(s => s.id === url.searchParams.get("source"));
26
- if (!source) throw new HttpError(404, "笔记库不存在");
27
75
  if (action === "sources" && method === "DELETE") {
76
+ clearMemoIndex(user.id, source.id);
28
77
  removeMemoSource(user.id, source.id);
29
78
  return sendJson(res, 200, { ok: true });
30
79
  }
31
- const storage = new MemoStorage(source, isAdmin(user));
80
+ if (action === "access" && method === "GET") return sendJson(res, 200, sourceSettings(source));
81
+ if (action === "access" && method === "PUT") {
82
+ const body = await readJsonBody(req, 65_536);
83
+ const latest = memoSources(user.id).find(s => s.id === source.id);
84
+ if (!latest) throw new HttpError(404, "笔记库不存在");
85
+ let access, expertAccess;
86
+ try {
87
+ access = parseMemoAccess(body.access);
88
+ // Older clients only send the library-wide setting. Their off switch revokes all grants.
89
+ expertAccess = body.defaultOnly === true ? latest.expertAccess ?? {}
90
+ : body.expertAccess === undefined ? (access === "off" ? {} : latest.expertAccess ?? {})
91
+ : parseExpertAccess(body.expertAccess, user.id, latest.expertAccess);
92
+ } catch (err) { throw new HttpError(400, err instanceof Error ? err.message : "智能体访问权限无效"); }
93
+ const updated = setMemoAccess(user.id, source.id, access, expertAccess);
94
+ syncMemoIndexAccess(user.id, latest, updated);
95
+ return sendJson(res, 200, sourceSettings(updated));
96
+ }
97
+ if (action === "index" && (method === "GET" || method === "POST")) {
98
+ if (method === "POST" && canReadMemo(source)) void refreshMemoIndex(user.id, source);
99
+ return sendJson(res, 200, memoIndexStatus(user.id, source.id));
100
+ }
101
+ const storage = new MemoStorage(source, isAdmin(owner));
32
102
  const path = url.searchParams.get("path") ?? "";
33
103
  const listing = action === "tree" && method === "GET";
34
104
  if (!(listing && path === "") && !validMemoPath(path)) throw new HttpError(400, "笔记路径无效");
35
- if (listing) return sendJson(res, 200, await storage.list(path, url.searchParams.get("cursor") ?? ""));
105
+ if (listing) {
106
+ const page = await storage.list(path, url.searchParams.get("cursor") ?? "");
107
+ checkAccess();
108
+ return sendJson(res, 200, page);
109
+ }
36
110
  if (action === "folder" && method === "POST") {
37
111
  await storage.mkdir(path);
38
112
  return sendJson(res, 201, { ok: true });
@@ -40,6 +114,7 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
40
114
  if (action === "image" && method === "GET") {
41
115
  if (!/\.(png|jpe?g|gif|webp)$/i.test(path)) throw new HttpError(415, "不支持此图片格式");
42
116
  const { bytes } = await storage.read(path, IMAGE_LIMIT);
117
+ checkAccess();
43
118
  const type = sniff(bytes)?.mediaType;
44
119
  if (!type?.startsWith("image/")) throw new HttpError(415, "图片格式无效");
45
120
  res.writeHead(200, { ...SECURITY_HEADERS, "Content-Type": type, "Cache-Control": "private, no-store" });
@@ -49,46 +124,34 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
49
124
  if (!editable(path)) throw new HttpError(415, "此格式暂不支持编辑");
50
125
  if (action === "history" && method === "GET") {
51
126
  const id = url.searchParams.get("id");
52
- if (id === null) return sendJson(res, 200, memoVersions(user.id, memoHistoryKey(source), path));
127
+ if (id === null) return sendJson(res, 200, memoVersions(owner.id, memoHistoryKey(source), path));
53
128
  if (!/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id))) throw new HttpError(400, "版本编号无效");
54
- const text = memoVersionText(user.id, memoHistoryKey(source), path, Number(id));
129
+ const text = memoVersionText(owner.id, memoHistoryKey(source), path, Number(id));
55
130
  if (text === null) throw new HttpError(404, "历史版本不存在");
56
131
  return sendJson(res, 200, { text });
57
132
  }
58
133
  if (action === "attachment" && method === "POST") {
59
134
  const bytes = await readBody(req, IMAGE_LIMIT);
135
+ checkAccess();
60
136
  const type = sniff(bytes);
61
137
  if (!type?.mediaType.startsWith("image/")) throw new HttpError(415, "请选择 PNG、JPEG、GIF 或 WebP 图片");
62
138
  const dir = posix.join(posix.dirname(path), "assets");
63
139
  const name = `image-${randomUUID()}.${type.ext}`;
64
140
  await storage.mkdir(dir, true);
141
+ checkAccess();
65
142
  await storage.put(posix.join(dir, name), bytes, type.mediaType, null);
66
143
  return sendJson(res, 201, { relative: "assets/" + name });
67
144
  }
68
- // The same storage identity and relative path identify a shared file across Loft accounts.
69
- // An editor token is issued only after a successful remote read or write with that account's source.
70
- const lockKey = storage.objectURL(path).href;
71
- const key = createHash("sha256").update(JSON.stringify([source.kind, lockKey, source.username, source.secret])).digest("hex");
72
- const account = JSON.stringify([user.id, source.id, user.role]);
73
145
  const joining = url.searchParams.get("collab") === "1";
74
- const checkAccess = () => {
75
- const active = current();
76
- if (active?.id !== user.id || active.role !== user.role || !memoSources(user.id).some(s => s.id === source.id)) throw new HttpError(403, "协作连接已失效");
77
- };
78
- const persist = (text: string, version: string | null, expected?: string) =>
79
- storage.put(path, Buffer.from(text), /\.md$/i.test(path) ? "text/markdown; charset=utf-8" : "text/plain; charset=utf-8", version, previous => {
80
- if (!memoSources(user.id).some(s => s.id === source.id)) throw new HttpError(404, "笔记库已断开");
81
- if (expected !== undefined && !previous.equals(Buffer.from(expected))) throw new HttpError(409, "远端正文已被修改");
82
- rememberMemoVersion(user.id, memoHistoryKey(source), path, previous);
83
- });
146
+ const { lockKey, key, account, persist, read } = memoFile(user, source, path, checkAccess, owner);
84
147
  if (action === "changes") {
85
148
  const token = String(req.headers["x-memo-client"] ?? "");
86
149
  const since = Number(url.searchParams.get("since") ?? NaN);
87
150
  if (method === "GET") {
88
151
  const result = await pullMemo(key, token, account, since, res);
89
152
  if (!result) return;
90
- checkAccess();
91
- return sendJson(res, 200, result);
153
+ const activeSource = checkAccess();
154
+ return sendJson(res, 200, mine ? result : { ...result, permission: memberAccess(activeSource, user.id) });
92
155
  }
93
156
  if (method === "POST") {
94
157
  const body = await readJsonBody(req, TEXT_LIMIT * 8);
@@ -96,16 +159,14 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
96
159
  checkAccess();
97
160
  return pushMemo(key, token, account, since, body?.updates, persist);
98
161
  });
162
+ checkAccess();
99
163
  return sendJson(res, 200, result);
100
164
  }
101
165
  }
102
166
  if (action === "file" && method === "GET") {
103
167
  const result = await withMemoLock(lockKey, async () => {
104
- const { bytes, version } = await storage.read(path);
105
- let text;
106
- try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); }
107
- catch { throw new HttpError(415, "仅支持 UTF-8 文本"); }
108
- if (text.includes("\0")) throw new HttpError(415, "此文件包含二进制数据");
168
+ const { text, version } = await read();
169
+ checkAccess();
109
170
  return { text, version, collab: joining ? joinMemo(key, account, text, version) : undefined };
110
171
  });
111
172
  return sendJson(res, 200, result);
@@ -114,8 +175,6 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
114
175
  const data = await readJsonBody(req, TEXT_LIMIT * 6 + 1024);
115
176
  const { text, version } = data ?? {};
116
177
  if (typeof text !== "string" || text.includes("\0") || (version !== null && typeof version !== "string")) throw new HttpError(400, "正文或版本无效");
117
- const bytes = Buffer.from(text);
118
- if (bytes.length > TEXT_LIMIT) throw new HttpError(413, "文本上限为 2 MB");
119
178
  const result = await withMemoLock(lockKey, async () => {
120
179
  const saved = await persist(text, version);
121
180
  invalidateMemo(key);
@@ -6,6 +6,7 @@ import fs from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
+ import { releaseStore } from "../core/upgrade-releases.js";
9
10
  import { home, logsDir } from "../home.js";
10
11
 
11
12
  const UNIT = "agent-loft";
@@ -13,7 +14,8 @@ const LABEL = "com.agent-loft";
13
14
  /** 改名前的服务名。装新服务时顺手卸掉,免得新旧两个进程抢同一个飞书机器人的消息 */
14
15
  const LEGACY_UNIT = "im-agent";
15
16
  const LEGACY_LABEL = "com.im-agent";
16
- const entry = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../bin/cli.js");
17
+ const packageRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../..");
18
+ const entry = path.join(path.dirname(releaseStore(packageRoot)), "bin/cli.js");
17
19
 
18
20
  function unitPath(): string {
19
21
  return process.platform === "darwin"
package/src/core/db.ts CHANGED
@@ -43,6 +43,18 @@ function loadSqlite(): typeof import("node:sqlite") {
43
43
  const SCHEMA = `
44
44
  CREATE TABLE IF NOT EXISTS migrations (name TEXT PRIMARY KEY, at INTEGER NOT NULL);
45
45
 
46
+ CREATE TABLE IF NOT EXISTS memo_scans (
47
+ owner TEXT NOT NULL, source TEXT NOT NULL, success INTEGER NOT NULL, PRIMARY KEY(owner,source)
48
+ );
49
+ CREATE TABLE IF NOT EXISTS memo_documents (
50
+ id INTEGER PRIMARY KEY AUTOINCREMENT, owner TEXT NOT NULL, source TEXT NOT NULL, path TEXT NOT NULL,
51
+ version TEXT NOT NULL, body TEXT NOT NULL, UNIQUE(owner,source,path)
52
+ );
53
+ CREATE VIRTUAL TABLE IF NOT EXISTS memo_fts USING fts5(path, body, content='', contentless_delete=1, tokenize='unicode61');
54
+ CREATE TRIGGER IF NOT EXISTS memo_documents_delete AFTER DELETE ON memo_documents BEGIN
55
+ DELETE FROM memo_fts WHERE rowid = old.id;
56
+ END;
57
+
46
58
  CREATE TABLE IF NOT EXISTS memo_versions (
47
59
  id INTEGER PRIMARY KEY, owner TEXT NOT NULL, source TEXT NOT NULL, path TEXT NOT NULL,
48
60
  at INTEGER NOT NULL, digest TEXT NOT NULL, content BLOB NOT NULL
@@ -126,11 +126,12 @@ export function contextBlock(
126
126
  expert: { prompt: PromptExpert; cwd: string } | undefined,
127
127
  memory: string | undefined,
128
128
  skills: string[] = [],
129
+ memoPrompt?: string,
129
130
  ): string {
130
131
  const head = expert
131
132
  ? [...persona(expert.prompt), "", "## 你能做什么(agent-loft 按这个专家的配置生成)", "", ...capabilityLines(expert.prompt, searchLabel("codex", expert.prompt), expert.cwd)]
132
133
  : [];
133
- const sections = [head, RICH_REPLY_LINES, memory ? [memory] : [], skills].filter((s) => s.length > 0);
134
+ const sections = [head, RICH_REPLY_LINES, memory ? [memory] : [], skills, memoPrompt ? [memoPrompt] : []].filter((s) => s.length > 0);
134
135
  return wrapContext(sections.flatMap((s, i) => (i ? ["", ...s] : s)));
135
136
  }
136
137
 
@@ -15,6 +15,7 @@ import { resolveWorkspacePath } from "./config.js";
15
15
  import { canUseMcp, claudeMachineMcp, getMcp, isMachineId, machineName, specOf, type McpSpec } from "./mcp.js";
16
16
  import { activeSkills, canSee, getSkill } from "./skills.js";
17
17
  import { canUseResource, getUser } from "./users.js";
18
+ import { purgeExpertMemoAccess } from "./memo-index.js";
18
19
 
19
20
  export type Engine = "claude" | "codex" | "workbuddy" | "pi" | "dsh";
20
21
  export const ENGINES: readonly Engine[] = ["claude", "codex", "workbuddy", "pi", "dsh"];
@@ -424,6 +425,7 @@ export function deleteExpert(owner: string, id: string): void {
424
425
  const idx = list.findIndex((e) => e.id === id && e.owner === owner);
425
426
  if (idx < 0) throw new Error("这个专家不存在");
426
427
  list.splice(idx, 1);
428
+ purgeExpertMemoAccess(id);
427
429
  purgeExpertTools(undefined, id);
428
430
  // 别的专家把它当子智能体的,一并去掉
429
431
  for (const e of list) {
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,16 @@ class Hub extends EventEmitter<{
372
374
  }
373
375
  });
374
376
  // 技能装了、改了、停用了、变量改了:受影响的人空闲的会话换上新的
377
+ memoAccessEvents.on("changed", (owner, previous, next) => {
378
+ for (const [key, live] of this.live) {
379
+ const conv = getConversation(key);
380
+ if (!conv || conv.plan || memoryOwnerOf(conv) !== owner) continue;
381
+ const expert = expertIdOf(conv);
382
+ if (hasWritableMemo(previous, expert) === hasWritableMemo(next, expert)) continue;
383
+ this.staleLive.add(live.id);
384
+ this.dropIfStale(key);
385
+ }
386
+ });
375
387
  skillEvents.on("changed", (users) => this.personalChanged(new Set(users)));
376
388
  // 专家修改只影响自定义专家;MCP 和内置默认配置修改也更新该账号的内置会话。
377
389
  expertEvents.on("changed", (_owner, id) => {
@@ -835,6 +847,7 @@ class Hub extends EventEmitter<{
835
847
  ...(taskOwner && getUser(taskOwner)?.role !== "admin" ? { noSessionGrant: true } : {}),
836
848
  ...(expert ? { expert } : {}),
837
849
  ...(memory ? { memory } : {}),
850
+ ...(taskOwner && !conv.plan && hasWritableMemo(memoSources(taskOwner), expertIdOf(conv)) ? { memoPrompt: MEMO_WRITING_GUIDE } : {}),
838
851
  ...(taskOwner ? { tasks: { userId: taskOwner, convKey: key } } : {}),
839
852
  ...(skills ? { skills } : {}),
840
853
  ...(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,167 @@
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, setExpertMemoAccess, 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 syncMemoIndexAccess(owner: string, before: MemoSource, after: MemoSource) {
71
+ if (!canReadMemo(after)) clearMemoIndex(owner, after.id);
72
+ else if (!canReadMemo(before)) void refreshMemoIndex(owner, after);
73
+ }
74
+
75
+ export function purgeExpertMemoAccess(expert: string) {
76
+ for (const user of listUsers()) {
77
+ const grants = memoSources(user.id).filter(s => Object.hasOwn(s.expertAccess ?? {}, expert));
78
+ const changes = new Map(grants.map(s => [s.id, null]));
79
+ for (const { before, after } of setExpertMemoAccess(user.id, expert, changes)) syncMemoIndexAccess(user.id, before, after);
80
+ }
81
+ }
82
+
83
+ export function refreshMemoIndex(owner: string, source: MemoSource) {
84
+ const pending = jobs.get(source.id)?.pending;
85
+ if (pending || !canReadMemo(source)) return pending;
86
+ const user = getUser(owner);
87
+ if (!user || user.disabled) return;
88
+ const role = user.role;
89
+ const job: Job = { scanned: 0 };
90
+ jobs.set(source.id, job);
91
+ const storage = new MemoStorage(source, isAdmin(user));
92
+ const current = () => {
93
+ const active = getUser(owner);
94
+ return jobs.get(source.id) === job && !!active && !active.disabled && active.role === role &&
95
+ memoSources(owner).some(s => s.id === source.id && canReadMemo(s));
96
+ };
97
+ job.pending = scanMemoSource(owner, source.id, storage, job, current).finally(() => { job.pending = undefined; });
98
+ return job.pending;
99
+ }
100
+
101
+ async function scanMemoSource(owner: string, source: string, storage: MemoStorage, job: Job, current: () => boolean) {
102
+ try {
103
+ // Only prune rows present at the start. Concurrent saves get a new row ID.
104
+ const old = sql(`SELECT id,path,version FROM memo_documents WHERE ${scope}`).all(owner, source);
105
+ const missing = new Map(old.map(row => [String(row.path), row]));
106
+ for await (const { path, etag } of listTextFiles(storage, current)) {
107
+ if (!current()) return;
108
+ const previous = missing.get(path);
109
+ missing.delete(path);
110
+ job.scanned++;
111
+ if (etag && etag === previous?.version) continue;
112
+ await withMemoLock(storage.objectURL(path).href, async () => {
113
+ if (!current()) return;
114
+ try {
115
+ const file = await storage.readText(path);
116
+ if (current()) indexMemo(owner, source, path, file.text, file.version);
117
+ } catch (err) {
118
+ if (!(err instanceof HttpError && [404, 413, 415].includes(err.status))) throw err;
119
+ if (previous) missing.set(path, previous);
120
+ }
121
+ });
122
+ }
123
+ if (!current()) return;
124
+ transaction(() => {
125
+ for (const row of missing.values()) sql("DELETE FROM memo_documents WHERE id = ?").run(row.id!);
126
+ sql("INSERT OR REPLACE INTO memo_scans VALUES(?,?,?)").run(owner, source, Date.now());
127
+ });
128
+ } catch (err) {
129
+ job.error = err instanceof HttpError ? err.message : "索引更新失败,请重新刷新";
130
+ }
131
+ }
132
+
133
+ export function startMemoIndexer() {
134
+ if (timer) return;
135
+ const refresh = () => {
136
+ for (const user of listUsers()) {
137
+ if (!user.disabled) for (const source of memoSources(user.id)) {
138
+ if (canReadMemo(source)) void refreshMemoIndex(user.id, source);
139
+ }
140
+ }
141
+ };
142
+ refresh();
143
+ timer = setInterval(refresh, 10 * 60_000);
144
+ timer.unref();
145
+ }
146
+ export function stopMemoIndexer() { clearInterval(timer); timer = undefined; jobs.clear(); }
147
+
148
+ export function searchMemos(owner: string, sources: MemoSource[], query: string, folder: string) {
149
+ if (query.length > 512) throw new HttpError(400, "搜索关键词限 512 字符");
150
+ const match = ftsMatch(query);
151
+ if (!match) throw new HttpError(400, "请输入搜索关键词");
152
+ const libraries = sources.map(s => ({ id: s.id, name: s.name, ...memoIndexStatus(owner, s.id) }));
153
+ if (!sources.length) return { libraries, hits: [] };
154
+ const slots = sources.map(() => "?").join(",");
155
+ const prefix = folder ? folder + "/" : "";
156
+ const rows = sql(`SELECT d.source,d.path,d.body FROM memo_fts JOIN memo_documents d ON d.id = memo_fts.rowid
157
+ WHERE memo_fts MATCH ? AND d.owner = ? AND d.source IN (${slots}) AND substr(d.path,1,length(?)) = ?
158
+ ORDER BY bm25(memo_fts, 4, 1), d.path LIMIT 20`).all(match, owner, ...sources.map(s => s.id), prefix, prefix);
159
+ const words = terms(query);
160
+ const hits = rows.map(row => {
161
+ const body = String(row.body), lower = body.toLowerCase();
162
+ const at = words.map(w => lower.indexOf(w)).find(i => i >= 0) ?? 0;
163
+ return { source: row.source, library: sources.find(s => s.id === row.source)?.name, path: row.path,
164
+ snippet: body.slice(Math.max(0, at - 60), at + 140) };
165
+ });
166
+ return { libraries, hits };
167
+ }
@@ -1,17 +1,68 @@
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";
7
+ import { getUser, listUsers, type User } from "./users.js";
8
+
9
+ export type MemoAccess = "off" | "read" | "write";
10
+ export function parseMemoAccess(value: unknown): MemoAccess {
11
+ if (value === "off" || value === "read" || value === "write") return value;
12
+ throw new Error("智能体访问权限无效");
13
+ }
14
+ export function memoAccessFor(source: MemoSource, expert: string): MemoAccess {
15
+ return source.expertAccess && Object.hasOwn(source.expertAccess, expert)
16
+ ? source.expertAccess[expert]! : source.access ?? "off";
17
+ }
18
+
19
+ /** Keep one index for the owner while any conversation may read this library. */
20
+ export const canReadMemo = (source: MemoSource) => source.access === "read" || source.access === "write" ||
21
+ Object.values(source.expertAccess ?? {}).some(access => access !== "off");
6
22
 
7
23
  export type MemoSource = {
8
- id: string; name: string; kind: "webdav" | "s3"; endpoint: string;
24
+ sharedWith?: Record<string, "read" | "write">;
25
+ expertAccess?: Record<string, MemoAccess>;
26
+ access?: MemoAccess; id: string; name: string; kind: "webdav" | "s3"; endpoint: string;
9
27
  username: string; secret: string; bucket: string; region: string; prefix: string;
10
28
  };
11
29
 
12
30
  const file = (user: string) => path.join(dataDir, "memo-sources", encodeURIComponent(user) + ".json");
13
31
  export const memoSources = (user: string) => readJson<MemoSource[]>(file(user), []);
14
- export const publicSource = ({ id, name, kind }: MemoSource) => ({ id, name, kind });
32
+ export const publicSource = ({ id, name, kind, access }: MemoSource) => ({ id, name, kind, access: access ?? "off" });
33
+ export const sourceSettings = (source: MemoSource) => ({ ...publicSource(source), expertAccess: source.expertAccess ?? {} });
34
+
35
+ export function memberAccess(source: MemoSource, member: string) {
36
+ return source.sharedWith && Object.hasOwn(source.sharedWith, member) ? source.sharedWith[member] : undefined;
37
+ }
38
+
39
+ /** Sharing a Web library never changes the recipient's personal expert grants. */
40
+ export function visibleMemoSources(user: User) {
41
+ const shared = listUsers().filter(other => other.id !== user.id && !other.disabled).flatMap(other =>
42
+ memoSources(other.id).flatMap(source => {
43
+ const permission = memberAccess(source, user.id);
44
+ return permission ? [{ id: source.id, name: source.name, kind: source.kind, permission,
45
+ sharedBy: { id: other.id, name: other.name } }] : [];
46
+ }));
47
+ return [...memoSources(user.id).map(sourceSettings), ...shared];
48
+ }
49
+
50
+ export function setMemoSharing(owner: string, id: string, changes: unknown) {
51
+ if (!changes || typeof changes !== "object" || Array.isArray(changes)) throw new Error("共享设置无效");
52
+ const sources = memoSources(owner);
53
+ const source = sources.find(s => s.id === id);
54
+ if (!source) throw new Error("笔记库已断开");
55
+ const sharedWith = { ...source.sharedWith };
56
+ for (const [member, access] of Object.entries(changes)) {
57
+ const user = getUser(member);
58
+ if (member === owner || !user || (user.disabled && access !== "off")) throw new Error("共享账号不可用");
59
+ if (access === "off") delete sharedWith[member];
60
+ else if (access === "read" || access === "write") sharedWith[member] = access;
61
+ else throw new Error("共享权限无效");
62
+ }
63
+ source.sharedWith = sharedWith;
64
+ writeJsonAtomic(file(owner), sources);
65
+ }
15
66
  // A connection can be removed and re-added with a new password or display name.
16
67
  export function memoHistoryKey(s: MemoSource): string {
17
68
  const library = [s.kind, s.endpoint, s.username];
@@ -21,6 +72,14 @@ export function memoHistoryKey(s: MemoSource): string {
21
72
 
22
73
  export function deleteMemoSources(user: string) {
23
74
  fs.rmSync(file(user), { force: true });
75
+ for (const other of listUsers()) {
76
+ const sources = memoSources(other.id);
77
+ if (!sources.some(s => memberAccess(s, user))) continue;
78
+ for (const source of sources) delete source.sharedWith?.[user];
79
+ writeJsonAtomic(file(other.id), sources);
80
+ }
81
+ sql("DELETE FROM memo_documents WHERE owner = ?").run(user);
82
+ sql("DELETE FROM memo_scans WHERE owner = ?").run(user);
24
83
  sql("DELETE FROM memo_versions WHERE owner = ?").run(user);
25
84
  }
26
85
 
@@ -41,14 +100,63 @@ export function parseMemoSource(input: Record<string, unknown>): MemoSource {
41
100
  const url = new URL(str("endpoint").trim() || (kind === "s3" ? `https://s3.${region}.amazonaws.com` : ""));
42
101
  if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error("请输入 HTTP(S) 服务地址,凭据请单独填写");
43
102
  url.pathname = url.pathname.replace(/\/*$/, "/");
44
- return { id: randomUUID(), name, kind, endpoint: url.href, username, secret, region, bucket, prefix };
103
+ return { access: parseMemoAccess(input.access ?? "off"), id: randomUUID(), name, kind, endpoint: url.href, username, secret, region, bucket, prefix };
104
+ }
105
+
106
+ export const memoAccessEvents = new EventEmitter<{ changed: [string, MemoSource[], MemoSource[]] }>();
107
+ export const hasWritableMemo = (sources: MemoSource[], expert: string) => sources.some(s => memoAccessFor(s, expert) === "write");
108
+
109
+ function saveSources(user: string, previous: MemoSource[], next: MemoSource[]) {
110
+ writeJsonAtomic(file(user), next);
111
+ memoAccessEvents.emit("changed", user, previous, next);
45
112
  }
46
113
 
47
114
  export function addMemoSource(user: string, source: MemoSource) {
48
115
  const sources = memoSources(user);
49
- writeJsonAtomic(file(user), [...sources, source]);
116
+ saveSources(user, sources, [...sources, source]);
50
117
  }
51
118
 
52
119
  export function removeMemoSource(user: string, id: string) {
53
- writeJsonAtomic(file(user), memoSources(user).filter(s => s.id !== id));
120
+ const sources = memoSources(user);
121
+ saveSources(user, sources, sources.filter(s => s.id !== id));
122
+ }
123
+
124
+ export function setMemoAccess(user: string, id: string, access: MemoAccess, expertAccess: Record<string, MemoAccess>) {
125
+ const sources = memoSources(user);
126
+ const source = sources.find(s => s.id === id);
127
+ if (!source) throw new Error("笔记库已断开");
128
+ const updated = { ...source, access, expertAccess };
129
+ saveSources(user, sources, sources.map(s => s.id === id ? updated : s));
130
+ return updated;
131
+ }
132
+
133
+ /** Validate before saving the expert form. Only the edited library/expert pairs are patched. */
134
+ export function parseExpertMemoChanges(owner: string, raw: unknown) {
135
+ const changes = new Map<string, MemoAccess | null>();
136
+ if (raw === undefined) return changes;
137
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("备忘录权限格式无效");
138
+ const own = new Set(memoSources(owner).map(s => s.id));
139
+ for (const [id, value] of Object.entries(raw)) {
140
+ if (!own.has(id)) throw new Error("笔记库已断开或无权授权,请刷新后重试");
141
+ changes.set(id, value === null ? null : parseMemoAccess(value));
142
+ }
143
+ return changes;
144
+ }
145
+
146
+ export function setExpertMemoAccess(owner: string, expert: string, changes: Map<string, MemoAccess | null>) {
147
+ const updated: { before: MemoSource; after: MemoSource }[] = [];
148
+ if (!changes.size) return updated;
149
+ const sources = memoSources(owner);
150
+ const next = sources.map(before => {
151
+ const access = changes.get(before.id);
152
+ if (access === undefined || access === (before.expertAccess?.[expert] ?? null)) return before;
153
+ const expertAccess = { ...before.expertAccess };
154
+ if (access === null) delete expertAccess[expert];
155
+ else expertAccess[expert] = access;
156
+ const after = { ...before, expertAccess };
157
+ updated.push({ before, after });
158
+ return after;
159
+ });
160
+ if (updated.length) saveSources(owner, sources, next);
161
+ return updated;
54
162
  }