agent-loft 0.2.128 → 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.
- package/README.md +4 -3
- package/package.json +1 -1
- package/src/channels/web/experts-api.ts +32 -8
- package/src/channels/web/memo-file.ts +5 -5
- package/src/channels/web/memos-api.ts +84 -27
- package/src/core/experts.ts +2 -0
- package/src/core/hub.ts +11 -2
- package/src/core/memo-index.ts +14 -1
- package/src/core/memo-sources.ts +86 -6
- package/src/core/memos-bridge.ts +10 -4
- package/web/css/memos.css +3 -1
- package/web/lib/memo-access.js +28 -0
- package/web/settings/agent-defaults.js +4 -1
- package/web/settings/experts.js +7 -2
- package/web/views/file-editor.js +2 -1
- package/web/views/memo-dialogs.js +50 -13
- package/web/views/memos.js +50 -15
package/README.md
CHANGED
|
@@ -102,9 +102,10 @@ Logo 是白底的三向汇合:橘红、暖橙和珊瑚红三个单元,表达
|
|
|
102
102
|
- **工作区面板**:会话右上角「更多 → 文件」打开或折叠,菜单中用绿色新增行数、红色删除行数显示当前分支的改动,在对话旁边(手机上全屏)看和改这条会话工作目录里的文件。「文件」页签是一棵按需展开的文件树,图片、PDF、音视频、Markdown、网页、代码直接预览,CSV / TSV 显示成表格;文本文件(1 MB 以内、UTF-8)可以编辑,Ctrl / ⌘ + S 保存,Markdown 和 CSV 能预览没保存的内容。还能新建、重命名、上传(点按钮或拖到面板上)、删除。保存时如果文件在你编辑期间被 agent 或别人改过,不会覆盖,由你选覆盖还是重新加载;没保存的内容存在本机,换会话、刷新页面都不丢。「改动」页签是 Git 仓库的已暂存 / 未暂存 / 未跟踪文件,点开看 diff,宽度够时可以切并排;顶栏的分支标记显示当前分支和改动数,点面板里的分支行能查看和切换本地、远程分支,也能新建分支。文件行上可以暂存、取消暂存、丢弃改动,写好说明提交已暂存的内容(默认不运行 Git 钩子,要用的话勾上);「历史」页签看提交记录和每个提交的 diff。推送、拉取、合并、变基请交给 agent 或终端。一轮结束、切回窗口时自动刷新。
|
|
103
103
|
- 管理员能用;成员要管理员在 设置 → 用户 里单独「开通工作区面板」。
|
|
104
104
|
- 分支栏下面可以获取、拉取、推送,用的是服务器上配置的 Git 凭据。拉取只做快进,推送从不强制。成员默认没有这个权限,要管理员再单独「开通 Git 远程操作」。
|
|
105
|
-
- **备忘录**。从侧栏进入「备忘录 → 连接笔记库」,选择 WebDAV 目录,或填写 S3 存储桶、区域和可选前缀。可连接多个笔记库,按文件夹浏览、新建和编辑 Markdown、TXT、JSON、YAML、CSV 等 UTF-8 文本。编辑时粘贴图片会写入当前文件夹的 `assets
|
|
106
|
-
-
|
|
107
|
-
-
|
|
105
|
+
- **备忘录**。从侧栏进入「备忘录 → 连接笔记库」,选择 WebDAV 目录,或填写 S3 存储桶、区域和可选前缀。可连接多个笔记库,按文件夹浏览、新建和编辑 Markdown、TXT、JSON、YAML、CSV 等 UTF-8 文本。编辑时粘贴图片会写入当前文件夹的 `assets/`,并插入相对链接。拥有读写权限的成员可以实时合写同一文件,阅读视图也会跟随更新。预览支持相对链接。「版本历史」可以查看并恢复这条连接下每份文本最近 50 个修改前的版本,保存在 Agent Loft 的本地数据库。浏览器通过 Agent Loft 的 HTTP 接口提交修改,用长轮询接收协作更新。Obsidian 等外部客户端直接写入存储时,重新打开文件会读取最新正文,写回冲突时可保留草稿并另存副本。文本上限 2 MB,每张图片上限 12 MB。连接凭据按账号保存在服务端,内网端点可用管理员账号连接。
|
|
106
|
+
- **共享给成员**。在「备忘录」选中自己的笔记库,点击「共享给成员」,为同一台 Agent Loft 上的账号选择「只读」或「读写」并保存。对方重新进入「备忘录」即可看到共享库,无需填写存储凭据。只读成员可以查看文件和版本历史,读写成员还可以编辑和新建文件。只有库主可以修改共享范围。把成员改为「关闭」即可撤回访问。成员的专家不会自动获得权限。
|
|
107
|
+
- **让智能体查笔记或改笔记**。在「设置 → 专家」中新建或编辑专家,在「权限和能力 → 备忘录权限」为每个自己的笔记库选择「沿用笔记库默认」「关闭」「只读」或「读写」,随专家一起保存。内置专家在卡片的「设置」里配置,别人共享的专家在「我的工具」里配置。库的默认权限和全文索引仍在「备忘录 → 智能体访问」里管理。已有库沿用原设置,新库默认关闭。备忘录工具随个人对话自动接入,直接在聊天里说「帮我搜笔记」即可。授权后可在自己的对话里按文件名和正文搜索、浏览目录、读取笔记;读写库还支持新建、追加和精确替换一处原文。只有你表达了留存或更新笔记的意图,智能体才会写入。比如你说「把刚才的排查过程留着下次用」,智能体会根据对话整理正文,优先更新已有笔记,也可以自己起名新建,并在保存后告诉你位置。保存后,正在编辑的网页会收到更新,原文可在版本历史中查看。计划模式只读。
|
|
108
|
+
- 授权后服务器在本地建立全文索引。网页和智能体保存后更新索引;外部修改每 10 分钟扫描一次,也可以在「智能体访问」里查看进度和最近成功时间,或立即刷新。首次扫描期间搜索只覆盖已收录内容。默认权限和所有专家权限都关闭后,或断开连接时,会清除该库的搜索索引。
|
|
108
109
|
- **资料库**:像 ChatGPT 的资料库,侧栏的「资料库」。对话里发过的附件、agent 回复里给出的、这一轮新写出来的图片 / 文档 / 音视频(复制一份收进来,之后原文件改了删了不影响)都汇总在这里:按图片 / 文档 / 音视频筛、按文件名搜,点开看大图或下载,「在新对话里用」,单个或批量删除(文件从磁盘上删掉)。从资料库拿到对话里的文件硬链接进那条对话的上传目录,不占双份空间,agent 照常能读。按人隔离,规则同对话:自己的;没主人的对话(飞书群聊等)的归管理员。上传了一直没发出去的一天后清掉;删除会话时立即清理该会话的上传文件和资料库记录,删除原件也会清理复用到其他会话的副本。agent 侧的会话记录仍保留,恢复会话不会恢复已删除的文件。
|
|
109
110
|
- **远程控制**:侧栏「定时任务」下面的「远程控制」,直接操作这台机器的**桌面**和**终端**,上面一键切换;切回对话时连接留在后台(侧栏入口上亮个小绿点),再进来接着用。这台机器没有图形桌面(服务器、NAS)时只有终端。
|
|
110
111
|
- 桌面:走 VNC 协议,网页里用 noVNC 显示,鼠标、键盘、剪贴板都能用,进来时不自动连、点「连接桌面」才连,工具栏上选画质:流畅 / 标准(默认)/ 高清由服务端把画面缩小到长边 1280 / 1920 / 2560、只把变了的地方压成 JPEG 发过来(macOS 屏幕共享只给无损的 ZRLE,5K 屏一整屏 30MB,原样转发隔着公网几秒一帧),原画是原样转发、只适合局域网;远程那边接了几块屏时可以只看其中一块(按系统里的显示器名称选,服务端只截那块再缩,比几块屏拼在一起缩小清楚得多;macOS 的各块屏位置要从屏幕共享发来的画面里学,第一次连上要几秒,原画下不能选);可以缩放到窗口或按原始大小看、全屏(手机上也能,iPhone 上是铺满页面)、「只看不控制」、发送 Ctrl+Alt+Del 之类的组合键。手机上有两种手势(右上角切换,「?」看说明):**触控板模式**(默认)屏幕上有个指针,单指滑动移动、轻点单击、双指轻点右键、长按后拖动是按住左键拖、双指滑动滚动;**触摸模式**点哪就点哪。两种模式都能双指捏合在本地放大画面(放大后小按钮也点得准,右下角「还原」),画面下面一排 Esc / Tab / Ctrl / Alt / Win / 方向键,Ctrl、Alt、Win 点一下会粘住,带给下一个按键或点击;键盘按钮弹出软键盘打字,中文输入法也能用。Linux 上 agent-loft 在有人连时用 x11vnc 共享当前的桌面(Xorg 会话;只听 127.0.0.1、随机端口、每次随机密码,需要 `sudo apt install x11vnc`),没人连着 30 分钟后停掉;macOS 上在 设置 → 远程控制 里改用「已有的 VNC 服务」,接系统自带的屏幕共享:填 VNC 密码,或者屏幕共享没开 VNC 密码时填 Mac 的用户名和登录密码(苹果认证,由服务端登录)。
|
package/package.json
CHANGED
|
@@ -26,12 +26,21 @@ import { config } from "../../core/config.js";
|
|
|
26
26
|
import { shellInfo } from "../../core/servers.js";
|
|
27
27
|
import { canUseMcp, claudeMachineMcp, createMcp, deleteMcp, getMcp, listUsableMcp, MACHINE_PREFIX, MCP_LIMITS, mcpView, setMcpUserValues, updateMcp, type McpInput, type McpServer } from "../../core/mcp.js";
|
|
28
28
|
import { activeSkills } from "../../core/skills.js";
|
|
29
|
+
import { memoSources, parseExpertMemoChanges, setExpertMemoAccess, sourceSettings } from "../../core/memo-sources.js";
|
|
30
|
+
import { syncMemoIndexAccess } from "../../core/memo-index.js";
|
|
29
31
|
import { getUser, isAdmin, type User } from "../../core/users.js";
|
|
30
32
|
import { getExpertOrder, setExpertOrder } from "../../core/ui-prefs.js";
|
|
31
33
|
import { HttpError, readJsonBody, sendJson } from "./http.js";
|
|
32
34
|
|
|
33
35
|
const bad = (err: unknown) => (err instanceof HttpError ? err : new HttpError(400, err instanceof Error ? err.message : String(err)));
|
|
34
36
|
|
|
37
|
+
function prepareMemoAccess(owner: string, raw: unknown) {
|
|
38
|
+
const changes = parseExpertMemoChanges(owner, raw);
|
|
39
|
+
return (expert: string) => {
|
|
40
|
+
for (const { before, after } of setExpertMemoAccess(owner, expert, changes)) syncMemoIndexAccess(owner, before, after);
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
35
44
|
function expertView(e: Expert, viewer: string) {
|
|
36
45
|
const tools = expertTools(viewer, e);
|
|
37
46
|
return {
|
|
@@ -112,6 +121,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
112
121
|
if (p === "/api/agents/defaults" && method === "GET") {
|
|
113
122
|
sendJson(res, 200, {
|
|
114
123
|
agents: Object.fromEntries(Object.entries(builtinAgentDefaults(user.id)).filter(([id]) => canUseExpert(user.id, id))),
|
|
124
|
+
memoLibraries: memoSources(user.id).map(sourceSettings),
|
|
115
125
|
skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
|
|
116
126
|
mcp: mcpChoices(user),
|
|
117
127
|
...(await machineMcp(user).then((m) => m ? { machineMcp: m, machinePrefix: MACHINE_PREFIX } : {})),
|
|
@@ -119,10 +129,13 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
119
129
|
return true;
|
|
120
130
|
}
|
|
121
131
|
if (p === "/api/agents/defaults" && method === "PUT") {
|
|
122
|
-
const body = await readJsonBody<{ agents?: unknown }>(req);
|
|
132
|
+
const body = await readJsonBody<{ agents?: Record<string, { memoAccess?: unknown }> }>(req);
|
|
123
133
|
if (body.agents && typeof body.agents === "object" && Object.keys(body.agents).some((id) => !canUseExpert(user.id, id))) throw new HttpError(403, "没有使用这个内置 Agent 的权限");
|
|
124
134
|
try {
|
|
125
|
-
|
|
135
|
+
const saves = Object.entries(body.agents ?? {}).map(([id, prefs]) => ({ id, apply: prepareMemoAccess(user.id, prefs?.memoAccess) }));
|
|
136
|
+
const agents = setBuiltinAgentDefaults(user.id, body.agents);
|
|
137
|
+
for (const { id, apply } of saves) apply(id);
|
|
138
|
+
sendJson(res, 200, { agents: Object.fromEntries(Object.entries(agents).filter(([id]) => canUseExpert(user.id, id))) });
|
|
126
139
|
} catch (err) {
|
|
127
140
|
throw bad(err);
|
|
128
141
|
}
|
|
@@ -133,6 +146,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
133
146
|
const enabled = hub.enabledAgents().map((d) => d.id);
|
|
134
147
|
sendJson(res, 200, {
|
|
135
148
|
expertOrder: getExpertOrder(user.id),
|
|
149
|
+
memoLibraries: memoSources(user.id).map(sourceSettings),
|
|
136
150
|
experts: availableExperts(user.id).map((e) => expertView(e, user.id)),
|
|
137
151
|
builtin: enabled.filter((id) => canUseExpert(user.id, id)).map((id) => ({ id, name: hub.label(id), engine: id })),
|
|
138
152
|
// 能建自定义专家的引擎(WorkBuddy、pi 只有内置专家)
|
|
@@ -169,9 +183,13 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
169
183
|
}
|
|
170
184
|
|
|
171
185
|
if (p === "/api/experts" && method === "POST") {
|
|
172
|
-
const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
|
|
186
|
+
const body = await readJsonBody<ExpertInput & { memoAccess?: unknown }>(req, 1024 * 1024);
|
|
173
187
|
try {
|
|
174
|
-
|
|
188
|
+
const apply = prepareMemoAccess(user.id, body.memoAccess);
|
|
189
|
+
const expert = createExpert(user.id, body);
|
|
190
|
+
try { apply(expert.id); }
|
|
191
|
+
catch (err) { deleteExpert(user.id, expert.id); throw err; }
|
|
192
|
+
sendJson(res, 200, expertView(expert, user.id));
|
|
175
193
|
} catch (err) {
|
|
176
194
|
throw bad(err);
|
|
177
195
|
}
|
|
@@ -192,9 +210,12 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
192
210
|
const tm = /^\/api\/experts\/(e_[a-f0-9]+)\/tools$/.exec(p);
|
|
193
211
|
if (tm && method === "PUT") {
|
|
194
212
|
if (!canUseExpert(user.id, tm[1]!)) throw new HttpError(404, "这个专家不存在");
|
|
195
|
-
const body = await readJsonBody
|
|
213
|
+
const body = await readJsonBody(req);
|
|
196
214
|
try {
|
|
197
|
-
|
|
215
|
+
const apply = prepareMemoAccess(user.id, body.memoAccess);
|
|
216
|
+
const tools = setExpertTools(user.id, tm[1]!, body);
|
|
217
|
+
apply(tm[1]!);
|
|
218
|
+
sendJson(res, 200, tools);
|
|
198
219
|
} catch (err) {
|
|
199
220
|
throw bad(err);
|
|
200
221
|
}
|
|
@@ -211,9 +232,12 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
|
|
|
211
232
|
}
|
|
212
233
|
if (expert.owner !== user.id) throw new HttpError(403, "只有创建者能修改或删除共享专家;你的工具可单独配置");
|
|
213
234
|
if (method === "PATCH") {
|
|
214
|
-
const body = await readJsonBody<ExpertInput>(req, 1024 * 1024);
|
|
235
|
+
const body = await readJsonBody<ExpertInput & { memoAccess?: unknown }>(req, 1024 * 1024);
|
|
215
236
|
try {
|
|
216
|
-
|
|
237
|
+
const apply = prepareMemoAccess(user.id, body.memoAccess);
|
|
238
|
+
const updated = updateExpert(user.id, expert.id, body);
|
|
239
|
+
apply(updated.id);
|
|
240
|
+
sendJson(res, 200, expertView(updated, user.id));
|
|
217
241
|
} catch (err) {
|
|
218
242
|
throw bad(err);
|
|
219
243
|
}
|
|
@@ -6,9 +6,9 @@ import { isAdmin, type User } from "../../core/users.js";
|
|
|
6
6
|
import { HttpError } from "./http.js";
|
|
7
7
|
import { editable, MemoStorage, TEXT_LIMIT } from "./memo-storage.js";
|
|
8
8
|
|
|
9
|
-
export function memoFile(user: User, source: MemoSource, path: string, check: () => void) {
|
|
9
|
+
export function memoFile(user: User, source: MemoSource, path: string, check: () => void, owner = user) {
|
|
10
10
|
if (!validMemoPath(path) || !editable(path)) throw new HttpError(400, "请选择可编辑的文本文件");
|
|
11
|
-
const storage = new MemoStorage(source, isAdmin(
|
|
11
|
+
const storage = new MemoStorage(source, isAdmin(owner));
|
|
12
12
|
const lockKey = storage.objectURL(path).href;
|
|
13
13
|
const key = createHash("sha256").update(JSON.stringify([source.kind, lockKey, source.username, source.secret])).digest("hex");
|
|
14
14
|
const account = JSON.stringify([user.id, source.id, user.role]);
|
|
@@ -20,10 +20,10 @@ export function memoFile(user: User, source: MemoSource, path: string, check: ()
|
|
|
20
20
|
const saved = await storage.put(path, bytes, /\.md$/i.test(path) ? "text/markdown; charset=utf-8" : "text/plain; charset=utf-8", version, previous => {
|
|
21
21
|
check();
|
|
22
22
|
if (expected !== undefined && !previous.equals(Buffer.from(expected))) throw new HttpError(409, "远端正文已被修改");
|
|
23
|
-
rememberMemoVersion(
|
|
23
|
+
rememberMemoVersion(owner.id, memoHistoryKey(source), path, previous);
|
|
24
24
|
});
|
|
25
|
-
const active = memoSources(
|
|
26
|
-
if (active && canReadMemo(active)) indexSavedMemo(
|
|
25
|
+
const active = memoSources(owner.id).find(s => s.id === source.id);
|
|
26
|
+
if (active && canReadMemo(active)) indexSavedMemo(owner.id, source.id, path, text, saved);
|
|
27
27
|
return saved;
|
|
28
28
|
};
|
|
29
29
|
return { key, lockKey, account, persist, read: () => storage.readText(path) };
|
|
@@ -1,56 +1,112 @@
|
|
|
1
1
|
import { memoFile } from "./memo-file.js";
|
|
2
|
-
import { clearMemoIndex, memoIndexStatus, refreshMemoIndex } from "../../core/memo-index.js";
|
|
2
|
+
import { clearMemoIndex, memoIndexStatus, refreshMemoIndex, syncMemoIndexAccess } from "../../core/memo-index.js";
|
|
3
3
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
import { invalidateMemo, joinMemo, pullMemo, pushMemo, withMemoLock } from "./memo-collab.js";
|
|
6
6
|
import { posix } from "node:path";
|
|
7
|
-
import { addMemoSource, canReadMemo, parseMemoAccess, setMemoAccess, memoHistoryKey, memoSources, parseMemoSource,
|
|
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";
|
|
8
9
|
import { memoVersions, memoVersionText } from "../../core/memo-versions.js";
|
|
9
10
|
import { sniff } from "../../core/uploads.js";
|
|
10
|
-
import { isAdmin, type User } from "../../core/users.js";
|
|
11
|
+
import { getUser, isAdmin, listUsers, type User } from "../../core/users.js";
|
|
11
12
|
import { HttpError, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
|
|
12
13
|
import { editable, IMAGE_LIMIT, MemoStorage, TEXT_LIMIT } from "./memo-storage.js";
|
|
13
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
|
+
|
|
14
23
|
export async function handleMemosApi(req: IncomingMessage, res: ServerResponse, url: URL, user: User, current: () => User | undefined) {
|
|
15
24
|
const action = url.pathname.slice("/api/memos/".length);
|
|
16
25
|
const method = req.method;
|
|
17
|
-
if (action === "sources" && method === "GET") return sendJson(res, 200,
|
|
26
|
+
if (action === "sources" && method === "GET") return sendJson(res, 200, visibleMemoSources(user));
|
|
18
27
|
if (action === "sources" && method === "POST") {
|
|
19
28
|
const body = await readJsonBody(req, 16_384);
|
|
20
29
|
let source;
|
|
21
|
-
try {
|
|
30
|
+
try {
|
|
31
|
+
source = parseMemoSource(body);
|
|
32
|
+
if (body.expertAccess !== undefined) source.expertAccess = parseExpertAccess(body.expertAccess, user.id);
|
|
33
|
+
}
|
|
22
34
|
catch (err) { throw new HttpError(400, err instanceof Error ? err.message : "数据源配置无效"); }
|
|
23
35
|
await new MemoStorage(source, isAdmin(user)).list("");
|
|
24
36
|
addMemoSource(user.id, source);
|
|
25
37
|
if (canReadMemo(source)) void refreshMemoIndex(user.id, source);
|
|
26
|
-
return sendJson(res, 201,
|
|
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 });
|
|
27
74
|
}
|
|
28
|
-
const source = memoSources(user.id).find(s => s.id === url.searchParams.get("source"));
|
|
29
|
-
if (!source) throw new HttpError(404, "笔记库不存在");
|
|
30
75
|
if (action === "sources" && method === "DELETE") {
|
|
31
76
|
clearMemoIndex(user.id, source.id);
|
|
32
77
|
removeMemoSource(user.id, source.id);
|
|
33
78
|
return sendJson(res, 200, { ok: true });
|
|
34
79
|
}
|
|
80
|
+
if (action === "access" && method === "GET") return sendJson(res, 200, sourceSettings(source));
|
|
35
81
|
if (action === "access" && method === "PUT") {
|
|
36
|
-
const body = await readJsonBody(req,
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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));
|
|
44
96
|
}
|
|
45
97
|
if (action === "index" && (method === "GET" || method === "POST")) {
|
|
46
98
|
if (method === "POST" && canReadMemo(source)) void refreshMemoIndex(user.id, source);
|
|
47
99
|
return sendJson(res, 200, memoIndexStatus(user.id, source.id));
|
|
48
100
|
}
|
|
49
|
-
const storage = new MemoStorage(source, isAdmin(
|
|
101
|
+
const storage = new MemoStorage(source, isAdmin(owner));
|
|
50
102
|
const path = url.searchParams.get("path") ?? "";
|
|
51
103
|
const listing = action === "tree" && method === "GET";
|
|
52
104
|
if (!(listing && path === "") && !validMemoPath(path)) throw new HttpError(400, "笔记路径无效");
|
|
53
|
-
if (listing)
|
|
105
|
+
if (listing) {
|
|
106
|
+
const page = await storage.list(path, url.searchParams.get("cursor") ?? "");
|
|
107
|
+
checkAccess();
|
|
108
|
+
return sendJson(res, 200, page);
|
|
109
|
+
}
|
|
54
110
|
if (action === "folder" && method === "POST") {
|
|
55
111
|
await storage.mkdir(path);
|
|
56
112
|
return sendJson(res, 201, { ok: true });
|
|
@@ -58,6 +114,7 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
|
|
|
58
114
|
if (action === "image" && method === "GET") {
|
|
59
115
|
if (!/\.(png|jpe?g|gif|webp)$/i.test(path)) throw new HttpError(415, "不支持此图片格式");
|
|
60
116
|
const { bytes } = await storage.read(path, IMAGE_LIMIT);
|
|
117
|
+
checkAccess();
|
|
61
118
|
const type = sniff(bytes)?.mediaType;
|
|
62
119
|
if (!type?.startsWith("image/")) throw new HttpError(415, "图片格式无效");
|
|
63
120
|
res.writeHead(200, { ...SECURITY_HEADERS, "Content-Type": type, "Cache-Control": "private, no-store" });
|
|
@@ -67,36 +124,34 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
|
|
|
67
124
|
if (!editable(path)) throw new HttpError(415, "此格式暂不支持编辑");
|
|
68
125
|
if (action === "history" && method === "GET") {
|
|
69
126
|
const id = url.searchParams.get("id");
|
|
70
|
-
if (id === null) return sendJson(res, 200, memoVersions(
|
|
127
|
+
if (id === null) return sendJson(res, 200, memoVersions(owner.id, memoHistoryKey(source), path));
|
|
71
128
|
if (!/^[1-9]\d*$/.test(id) || !Number.isSafeInteger(Number(id))) throw new HttpError(400, "版本编号无效");
|
|
72
|
-
const text = memoVersionText(
|
|
129
|
+
const text = memoVersionText(owner.id, memoHistoryKey(source), path, Number(id));
|
|
73
130
|
if (text === null) throw new HttpError(404, "历史版本不存在");
|
|
74
131
|
return sendJson(res, 200, { text });
|
|
75
132
|
}
|
|
76
133
|
if (action === "attachment" && method === "POST") {
|
|
77
134
|
const bytes = await readBody(req, IMAGE_LIMIT);
|
|
135
|
+
checkAccess();
|
|
78
136
|
const type = sniff(bytes);
|
|
79
137
|
if (!type?.mediaType.startsWith("image/")) throw new HttpError(415, "请选择 PNG、JPEG、GIF 或 WebP 图片");
|
|
80
138
|
const dir = posix.join(posix.dirname(path), "assets");
|
|
81
139
|
const name = `image-${randomUUID()}.${type.ext}`;
|
|
82
140
|
await storage.mkdir(dir, true);
|
|
141
|
+
checkAccess();
|
|
83
142
|
await storage.put(posix.join(dir, name), bytes, type.mediaType, null);
|
|
84
143
|
return sendJson(res, 201, { relative: "assets/" + name });
|
|
85
144
|
}
|
|
86
145
|
const joining = url.searchParams.get("collab") === "1";
|
|
87
|
-
const
|
|
88
|
-
const active = current();
|
|
89
|
-
if (active?.id !== user.id || active.role !== user.role || !memoSources(user.id).some(s => s.id === source.id)) throw new HttpError(403, "协作连接已失效");
|
|
90
|
-
};
|
|
91
|
-
const { lockKey, key, account, persist, read } = memoFile(user, source, path, checkAccess);
|
|
146
|
+
const { lockKey, key, account, persist, read } = memoFile(user, source, path, checkAccess, owner);
|
|
92
147
|
if (action === "changes") {
|
|
93
148
|
const token = String(req.headers["x-memo-client"] ?? "");
|
|
94
149
|
const since = Number(url.searchParams.get("since") ?? NaN);
|
|
95
150
|
if (method === "GET") {
|
|
96
151
|
const result = await pullMemo(key, token, account, since, res);
|
|
97
152
|
if (!result) return;
|
|
98
|
-
checkAccess();
|
|
99
|
-
return sendJson(res, 200, result);
|
|
153
|
+
const activeSource = checkAccess();
|
|
154
|
+
return sendJson(res, 200, mine ? result : { ...result, permission: memberAccess(activeSource, user.id) });
|
|
100
155
|
}
|
|
101
156
|
if (method === "POST") {
|
|
102
157
|
const body = await readJsonBody(req, TEXT_LIMIT * 8);
|
|
@@ -104,12 +159,14 @@ export async function handleMemosApi(req: IncomingMessage, res: ServerResponse,
|
|
|
104
159
|
checkAccess();
|
|
105
160
|
return pushMemo(key, token, account, since, body?.updates, persist);
|
|
106
161
|
});
|
|
162
|
+
checkAccess();
|
|
107
163
|
return sendJson(res, 200, result);
|
|
108
164
|
}
|
|
109
165
|
}
|
|
110
166
|
if (action === "file" && method === "GET") {
|
|
111
167
|
const result = await withMemoLock(lockKey, async () => {
|
|
112
168
|
const { text, version } = await read();
|
|
169
|
+
checkAccess();
|
|
113
170
|
return { text, version, collab: joining ? joinMemo(key, account, text, version) : undefined };
|
|
114
171
|
});
|
|
115
172
|
return sendJson(res, 200, result);
|
package/src/core/experts.ts
CHANGED
|
@@ -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
|
@@ -374,7 +374,16 @@ class Hub extends EventEmitter<{
|
|
|
374
374
|
}
|
|
375
375
|
});
|
|
376
376
|
// 技能装了、改了、停用了、变量改了:受影响的人空闲的会话换上新的
|
|
377
|
-
memoAccessEvents.on("changed", owner =>
|
|
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
|
+
});
|
|
378
387
|
skillEvents.on("changed", (users) => this.personalChanged(new Set(users)));
|
|
379
388
|
// 专家修改只影响自定义专家;MCP 和内置默认配置修改也更新该账号的内置会话。
|
|
380
389
|
expertEvents.on("changed", (_owner, id) => {
|
|
@@ -838,7 +847,7 @@ class Hub extends EventEmitter<{
|
|
|
838
847
|
...(taskOwner && getUser(taskOwner)?.role !== "admin" ? { noSessionGrant: true } : {}),
|
|
839
848
|
...(expert ? { expert } : {}),
|
|
840
849
|
...(memory ? { memory } : {}),
|
|
841
|
-
...(taskOwner && hasWritableMemo(memoSources(taskOwner)) ? { memoPrompt: MEMO_WRITING_GUIDE } : {}),
|
|
850
|
+
...(taskOwner && !conv.plan && hasWritableMemo(memoSources(taskOwner), expertIdOf(conv)) ? { memoPrompt: MEMO_WRITING_GUIDE } : {}),
|
|
842
851
|
...(taskOwner ? { tasks: { userId: taskOwner, convKey: key } } : {}),
|
|
843
852
|
...(skills ? { skills } : {}),
|
|
844
853
|
...(builtin.builtinMcp ? { builtinMcp: builtin.builtinMcp } : {}),
|
package/src/core/memo-index.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { withMemoLock } from "../channels/web/memo-collab.js";
|
|
|
3
3
|
import { HttpError } from "../channels/web/http.js";
|
|
4
4
|
import { sql, transaction } from "./db.js";
|
|
5
5
|
import { ftsIndexText, ftsMatch, terms } from "./fts.js";
|
|
6
|
-
import { memoSources, canReadMemo, validMemoPath, type MemoSource } from "./memo-sources.js";
|
|
6
|
+
import { memoSources, canReadMemo, setExpertMemoAccess, validMemoPath, type MemoSource } from "./memo-sources.js";
|
|
7
7
|
import { getUser, isAdmin, listUsers } from "./users.js";
|
|
8
8
|
|
|
9
9
|
const scope = "owner = ? AND source = ?";
|
|
@@ -67,6 +67,19 @@ async function* listTextFiles(storage: MemoStorage, current: () => boolean) {
|
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
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
|
+
|
|
70
83
|
export function refreshMemoIndex(owner: string, source: MemoSource) {
|
|
71
84
|
const pending = jobs.get(source.id)?.pending;
|
|
72
85
|
if (pending || !canReadMemo(source)) return pending;
|
package/src/core/memo-sources.ts
CHANGED
|
@@ -4,15 +4,25 @@ import { EventEmitter } from "node:events";
|
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { dataDir, readJson, writeJsonAtomic } from "../home.js";
|
|
6
6
|
import { sql } from "./db.js";
|
|
7
|
+
import { getUser, listUsers, type User } from "./users.js";
|
|
7
8
|
|
|
8
9
|
export type MemoAccess = "off" | "read" | "write";
|
|
9
10
|
export function parseMemoAccess(value: unknown): MemoAccess {
|
|
10
11
|
if (value === "off" || value === "read" || value === "write") return value;
|
|
11
12
|
throw new Error("智能体访问权限无效");
|
|
12
13
|
}
|
|
13
|
-
export
|
|
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");
|
|
14
22
|
|
|
15
23
|
export type MemoSource = {
|
|
24
|
+
sharedWith?: Record<string, "read" | "write">;
|
|
25
|
+
expertAccess?: Record<string, MemoAccess>;
|
|
16
26
|
access?: MemoAccess; id: string; name: string; kind: "webdav" | "s3"; endpoint: string;
|
|
17
27
|
username: string; secret: string; bucket: string; region: string; prefix: string;
|
|
18
28
|
};
|
|
@@ -20,6 +30,39 @@ export type MemoSource = {
|
|
|
20
30
|
const file = (user: string) => path.join(dataDir, "memo-sources", encodeURIComponent(user) + ".json");
|
|
21
31
|
export const memoSources = (user: string) => readJson<MemoSource[]>(file(user), []);
|
|
22
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
|
+
}
|
|
23
66
|
// A connection can be removed and re-added with a new password or display name.
|
|
24
67
|
export function memoHistoryKey(s: MemoSource): string {
|
|
25
68
|
const library = [s.kind, s.endpoint, s.username];
|
|
@@ -29,6 +72,12 @@ export function memoHistoryKey(s: MemoSource): string {
|
|
|
29
72
|
|
|
30
73
|
export function deleteMemoSources(user: string) {
|
|
31
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
|
+
}
|
|
32
81
|
sql("DELETE FROM memo_documents WHERE owner = ?").run(user);
|
|
33
82
|
sql("DELETE FROM memo_scans WHERE owner = ?").run(user);
|
|
34
83
|
sql("DELETE FROM memo_versions WHERE owner = ?").run(user);
|
|
@@ -54,12 +103,12 @@ export function parseMemoSource(input: Record<string, unknown>): MemoSource {
|
|
|
54
103
|
return { access: parseMemoAccess(input.access ?? "off"), id: randomUUID(), name, kind, endpoint: url.href, username, secret, region, bucket, prefix };
|
|
55
104
|
}
|
|
56
105
|
|
|
57
|
-
export const memoAccessEvents = new EventEmitter<{ changed: [string] }>();
|
|
58
|
-
export const hasWritableMemo = (sources: MemoSource[]) => sources.some(s => s
|
|
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");
|
|
59
108
|
|
|
60
109
|
function saveSources(user: string, previous: MemoSource[], next: MemoSource[]) {
|
|
61
110
|
writeJsonAtomic(file(user), next);
|
|
62
|
-
|
|
111
|
+
memoAccessEvents.emit("changed", user, previous, next);
|
|
63
112
|
}
|
|
64
113
|
|
|
65
114
|
export function addMemoSource(user: string, source: MemoSource) {
|
|
@@ -72,11 +121,42 @@ export function removeMemoSource(user: string, id: string) {
|
|
|
72
121
|
saveSources(user, sources, sources.filter(s => s.id !== id));
|
|
73
122
|
}
|
|
74
123
|
|
|
75
|
-
export function setMemoAccess(user: string, id: string, access: MemoAccess) {
|
|
124
|
+
export function setMemoAccess(user: string, id: string, access: MemoAccess, expertAccess: Record<string, MemoAccess>) {
|
|
76
125
|
const sources = memoSources(user);
|
|
77
126
|
const source = sources.find(s => s.id === id);
|
|
78
127
|
if (!source) throw new Error("笔记库已断开");
|
|
79
|
-
const updated = { ...source, access };
|
|
128
|
+
const updated = { ...source, access, expertAccess };
|
|
80
129
|
saveSources(user, sources, sources.map(s => s.id === id ? updated : s));
|
|
81
130
|
return updated;
|
|
82
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;
|
|
162
|
+
}
|
package/src/core/memos-bridge.ts
CHANGED
|
@@ -4,9 +4,10 @@ import { memoFile } from "../channels/web/memo-file.js";
|
|
|
4
4
|
import { MemoStorage } from "../channels/web/memo-storage.js";
|
|
5
5
|
import { MEMO_TOOLS } from "../mcp/memo-tools.js";
|
|
6
6
|
import { searchMemos } from "./memo-index.js";
|
|
7
|
-
import {
|
|
7
|
+
import { canUseExpert } from "./experts.js";
|
|
8
|
+
import { memoAccessFor, memoSources, publicSource, validMemoPath } from "./memo-sources.js";
|
|
8
9
|
import { memoryOwnerOf } from "./personal.js";
|
|
9
|
-
import { getConversation } from "./store.js";
|
|
10
|
+
import { expertIdOf, getConversation } from "./store.js";
|
|
10
11
|
import { getUser, isAdmin } from "./users.js";
|
|
11
12
|
|
|
12
13
|
export async function memoToolCall(owner: string, convKey: string, name: string, args: Record<string, unknown>) {
|
|
@@ -20,10 +21,15 @@ export async function memoToolCall(owner: string, convKey: string, name: string,
|
|
|
20
21
|
const authorize = () => {
|
|
21
22
|
const conv = getConversation(convKey), user = getUser(owner);
|
|
22
23
|
if (!conv || !user || user.disabled || memoryOwnerOf(conv) !== owner) throw new HttpError(403, "当前对话无权访问备忘录");
|
|
23
|
-
const
|
|
24
|
+
const expert = expertIdOf(conv);
|
|
25
|
+
if (!canUseExpert(owner, expert)) throw new HttpError(403, "当前对话无权使用此专家");
|
|
26
|
+
const sources = memoSources(owner).map(s => {
|
|
27
|
+
const access = memoAccessFor(s, expert);
|
|
28
|
+
return { ...s, access: conv.plan && access === "write" ? "read" as const : access };
|
|
29
|
+
}).filter(s => s.access !== "off");
|
|
24
30
|
const source = sources.find(s => s.id === id);
|
|
25
31
|
if (id !== undefined && !source) throw new HttpError(404, "未找到已授权的笔记库");
|
|
26
|
-
if (!tool.annotations.readOnlyHint &&
|
|
32
|
+
if (!tool.annotations.readOnlyHint && source?.access !== "write") throw new HttpError(403, "当前笔记库或对话仅允许读取");
|
|
27
33
|
return { user, sources, source };
|
|
28
34
|
};
|
|
29
35
|
const { user, sources, source } = authorize();
|
package/web/css/memos.css
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
.memo-side, .memo-pane { display: flex; flex-direction: column; min-width: 0; min-height: 0; }
|
|
5
5
|
.memo-side { background: var(--bg-side); border-right: 1px solid var(--border); }
|
|
6
6
|
.memo-sources, .memo-tree-tools, .memo-bar, .memo-blankbar { display: flex; align-items: center; gap: 6px; padding: 8px; }
|
|
7
|
-
.memo-sources
|
|
7
|
+
.memo-sources { flex-wrap: wrap; }
|
|
8
|
+
.memo-sources .input { width: 100%; min-width: 0; }
|
|
8
9
|
.memo-side .icon-btn { width: 30px; height: 30px; flex-shrink: 0; }
|
|
9
10
|
.memo-tree { overflow: auto; flex: 1; padding: 0 6px 12px; }
|
|
10
11
|
.memo-tree .memo-branch { margin-left: 10px; padding-left: 3px; border-left: 1px solid var(--border); }
|
|
@@ -35,6 +36,7 @@
|
|
|
35
36
|
.memo-fields { gap: 12px; }
|
|
36
37
|
.memo-fields label { font-size: 13px; }
|
|
37
38
|
.memo-fields .input { width: 100%; }
|
|
39
|
+
.memo-fields .memo-expert-access { display: grid; grid-template-columns: minmax(0, 1fr) minmax(8em, 40%); align-items: center; overflow-wrap: anywhere; }
|
|
38
40
|
.memo-fields .btn { align-self: flex-end; }
|
|
39
41
|
.memo-error { color: var(--danger); }
|
|
40
42
|
.memo-page [hidden], .memo-fields[hidden], .memo-blankbar, .memo-bar > button:first-child, .memo-return { display: none; }
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { h } from "./dom.js";
|
|
2
|
+
|
|
3
|
+
const labels = { off: "关闭", read: "只读", write: "读写" };
|
|
4
|
+
|
|
5
|
+
export function memoAccessSelect(label, value, libraryDefault) {
|
|
6
|
+
const select = h("select", { class: "input", "aria-label": label },
|
|
7
|
+
libraryDefault ? h("option", { value: "" }, `沿用笔记库默认(${labels[libraryDefault]})`) : null,
|
|
8
|
+
Object.entries(labels).map(([id, name]) => h("option", { value: id }, name)));
|
|
9
|
+
select.value = value;
|
|
10
|
+
return select;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function expertMemoField(libraries = [], expert) {
|
|
14
|
+
const rows = libraries.map(source => {
|
|
15
|
+
const initial = source.expertAccess?.[expert] ?? "";
|
|
16
|
+
const input = memoAccessSelect(source.name, initial, source.access ?? "off");
|
|
17
|
+
return { id: source.id, input, initial, row: h("label", { class: "memo-expert-access" }, h("span", {}, source.name), input) };
|
|
18
|
+
});
|
|
19
|
+
return {
|
|
20
|
+
el: h("div", { class: "field" }, h("span", {}, "备忘录权限"),
|
|
21
|
+
rows.length ? h("div", { class: "memo-fields" }, rows.map(r => r.row))
|
|
22
|
+
: h("small", {}, "可先在「备忘录」连接自己的笔记库。")),
|
|
23
|
+
changes() {
|
|
24
|
+
const entries = rows.filter(r => r.input.value !== r.initial).map(r => [r.id, r.input.value || null]);
|
|
25
|
+
return entries.length ? Object.fromEntries(entries) : undefined;
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { fill, h, toast } from "../lib/dom.js";
|
|
2
2
|
import { api } from "../lib/api.js";
|
|
3
|
+
import { expertMemoField } from "../lib/memo-access.js";
|
|
3
4
|
import { modal, confirmDialog } from "../lib/overlay.js";
|
|
4
5
|
import { isAdmin, S } from "../state.js";
|
|
5
6
|
import { renderContext } from "../views/topbar.js";
|
|
@@ -83,6 +84,7 @@ export function openAgentDefaults(engine, label) {
|
|
|
83
84
|
const pick = server ? modelPicker(engine, server.defaultModel ?? "", server.defaultEffort ?? "", DEFAULT_MODEL_LABEL[engine] ?? "跟随默认") : null;
|
|
84
85
|
|
|
85
86
|
const skills = loadPicker(`${label} 技能`, data.skills, prefs.skills, "全部已启用的个人技能(含以后新增)");
|
|
87
|
+
const memos = expertMemoField(data.memoLibraries, engine);
|
|
86
88
|
const machine = (data.machineMcp?.[engine] ?? []).map((name) => ({ id: `${data.machinePrefix}${name}`, name: `${name}(本机)` }));
|
|
87
89
|
const mcp = loadPicker(`${label} MCP`, [...data.mcp, ...machine], prefs.mcp, data.machineMcp ? "沿用机器上的 MCP 配置" : null);
|
|
88
90
|
const machineSkills = h("input", { type: "checkbox", checked: prefs.machineSkills });
|
|
@@ -115,6 +117,7 @@ export function openAgentDefaults(engine, label) {
|
|
|
115
117
|
skills.el,
|
|
116
118
|
data.machineMcp ? h("label", { class: "check-item" }, machineSkills, "同时加载机器上的技能") : null,
|
|
117
119
|
mcp.el,
|
|
120
|
+
memos.el,
|
|
118
121
|
h("small", {}, "技能和 MCP 可分别全部取消。记忆、定时任务、技能管理等系统工具仍按功能设置提供。"),
|
|
119
122
|
);
|
|
120
123
|
fill(
|
|
@@ -122,7 +125,7 @@ export function openAgentDefaults(engine, label) {
|
|
|
122
125
|
saveButton(async () => {
|
|
123
126
|
const res = await api("/api/agents/defaults", {
|
|
124
127
|
method: "PUT",
|
|
125
|
-
body: { agents: { [engine]: { permission: permission.value || null, skills: skills.value(), machineSkills: machineSkills.checked, mcp: mcp.value() } } },
|
|
128
|
+
body: { agents: { [engine]: { permission: permission.value || null, skills: skills.value(), machineSkills: machineSkills.checked, mcp: mcp.value(), memoAccess: memos.changes() } } },
|
|
126
129
|
});
|
|
127
130
|
S.defaultPermission = { ...S.defaultPermission, [engine]: res.agents?.[engine]?.permission ?? null };
|
|
128
131
|
const changed = pick && (pick.model() !== (server.defaultModel ?? "") || pick.effort() !== (server.defaultEffort ?? ""));
|
package/web/settings/experts.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { agentIcon, fill, h, icon, toast } from "../lib/dom.js";
|
|
2
2
|
import { api } from "../lib/api.js";
|
|
3
|
+
import { expertMemoField } from "../lib/memo-access.js";
|
|
3
4
|
import { confirmDialog, modal, showMenu } from "../lib/overlay.js";
|
|
4
5
|
import { isAdmin, S } from "../state.js";
|
|
5
6
|
import { openAgentDefaults } from "./agent-defaults.js";
|
|
@@ -205,18 +206,19 @@ function viewSharedExpert(e) {
|
|
|
205
206
|
}
|
|
206
207
|
|
|
207
208
|
function openTools(data, e, reload) {
|
|
209
|
+
const memos = expertMemoField(data.memoLibraries, e.id);
|
|
208
210
|
const skills = checkList(data.skills.map((s) => ({ id: s.id, label: s.name, hint: s.description })), e.skills, "还没有启用的技能(设置 → 技能)");
|
|
209
211
|
const machine = (data.machineMcp?.[e.engine] ?? []).map((name) => ({ id: `${data.machinePrefix}${name}`, label: `${name}(本机)` }));
|
|
210
212
|
const mcp = checkList([...data.mcp.map((s) => ({ id: s.id, label: s.name, hint: s.description })), ...machine], e.mcp, "还没有 MCP(设置 → MCP)");
|
|
211
213
|
const save = h("button", { class: "btn primary" }, "保存我的工具");
|
|
212
214
|
const close = modal({ title: `${e.name} · 我的工具`, body: h("div", { class: "modal-body" },
|
|
213
215
|
h("p", { class: "muted" }, "只影响你使用这个专家时加载的工具,网页和绑定账号后的飞书私聊共用。未选择时不加载技能或 MCP;记忆使用你自己的设置。子智能体的工具需在对应专家中单独配置。"),
|
|
214
|
-
field("我的技能", skills.el), field("我的 MCP", mcp.el),
|
|
216
|
+
field("我的技能", skills.el), field("我的 MCP", mcp.el), memos.el,
|
|
215
217
|
), foot: h("div", { class: "modal-foot" }, save) });
|
|
216
218
|
save.onclick = async () => {
|
|
217
219
|
save.disabled = true;
|
|
218
220
|
try {
|
|
219
|
-
await api(`/api/experts/${e.id}/tools`, { method: "PUT", body: { skills: skills.value(), mcp: mcp.value() } });
|
|
221
|
+
await api(`/api/experts/${e.id}/tools`, { method: "PUT", body: { skills: skills.value(), mcp: mcp.value(), memoAccess: memos.changes() } });
|
|
220
222
|
close();
|
|
221
223
|
toast("已保存,你的对话下一条消息起使用新的工具");
|
|
222
224
|
void reload();
|
|
@@ -296,6 +298,7 @@ function checkList(items, picked, empty) {
|
|
|
296
298
|
/** e:编辑这个;preset:新建时预填(模板、复制) */
|
|
297
299
|
function openEditor(data, e, reload, preset) {
|
|
298
300
|
const src = e ?? preset ?? {};
|
|
301
|
+
const memos = expertMemoField(data.memoLibraries, e?.id);
|
|
299
302
|
const name = h("input", { value: src.name ?? "", maxlength: "40", placeholder: "比如:证券观察员" });
|
|
300
303
|
const avatar = avatarPicker(src, !e);
|
|
301
304
|
const desc = h("input", { value: src.description ?? "", maxlength: "500", placeholder: "一句话说它是干什么的(选专家时、当子智能体时都看这句)" });
|
|
@@ -409,6 +412,7 @@ function openEditor(data, e, reload, preset) {
|
|
|
409
412
|
section(
|
|
410
413
|
"权限和能力",
|
|
411
414
|
field("权限", perms.el, "改文件包含读文件,跑命令包含改文件。什么都不勾就是只能聊天"),
|
|
415
|
+
memos.el,
|
|
412
416
|
cwdField,
|
|
413
417
|
codexField,
|
|
414
418
|
),
|
|
@@ -454,6 +458,7 @@ function openEditor(data, e, reload, preset) {
|
|
|
454
458
|
subagents: engine.value === "claude" ? subs.value() : [],
|
|
455
459
|
codexTools: engine.value === "codex" ? codexTools.value() : [],
|
|
456
460
|
memory: memory.checked,
|
|
461
|
+
memoAccess: memos.changes(),
|
|
457
462
|
welcome: welcome.value,
|
|
458
463
|
quickPrompts,
|
|
459
464
|
};
|
package/web/views/file-editor.js
CHANGED
|
@@ -88,7 +88,7 @@ function languageFor(name, CM) {
|
|
|
88
88
|
* 在 parent 里建一个编辑器。onChange:内容变了;onSave:按了 Ctrl / ⌘ + S。
|
|
89
89
|
* 返回 { text, setText, focus, measure, destroy };text() 给的是还原了换行符、可以直接存的内容
|
|
90
90
|
*/
|
|
91
|
-
export async function createEditor({ parent, text, name, onChange, onSave, collaboration }) {
|
|
91
|
+
export async function createEditor({ parent, text, name, onChange, onSave, collaboration, readOnly = false }) {
|
|
92
92
|
const CM = await loadCodeMirror();
|
|
93
93
|
const dark = matchMedia("(prefers-color-scheme: dark)");
|
|
94
94
|
const theme = new CM.Compartment();
|
|
@@ -117,6 +117,7 @@ export async function createEditor({ parent, text, name, onChange, onSave, colla
|
|
|
117
117
|
CM.indentWithTab,
|
|
118
118
|
]),
|
|
119
119
|
...(collaboration ? [CM.collab(collaboration)] : []),
|
|
120
|
+
...(readOnly ? [CM.EditorState.readOnly.of(true), CM.EditorView.editable.of(false)] : []),
|
|
120
121
|
CM.basicSetup,
|
|
121
122
|
CM.EditorView.lineWrapping,
|
|
122
123
|
theme.of(themeOf()),
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { h } from "../lib/dom.js";
|
|
1
|
+
import { h, toast } from "../lib/dom.js";
|
|
2
2
|
import { modal } from "../lib/overlay.js";
|
|
3
3
|
import { api } from "../lib/api.js";
|
|
4
|
+
import { memoAccessSelect } from "../lib/memo-access.js";
|
|
4
5
|
|
|
5
|
-
function memoAccessField(
|
|
6
|
-
const select =
|
|
7
|
-
|
|
8
|
-
select.value = value;
|
|
6
|
+
function memoAccessField() {
|
|
7
|
+
const select = memoAccessSelect("智能体访问", "off");
|
|
8
|
+
select.name = "access";
|
|
9
9
|
const hint = h("small", {}, "授权后,Agent Loft 会在服务器建立本库的全文索引。");
|
|
10
10
|
const update = () => { hint.hidden = select.value === "off"; };
|
|
11
11
|
select.addEventListener("change", update);
|
|
@@ -13,18 +13,23 @@ function memoAccessField(value = "off") {
|
|
|
13
13
|
return { select, field: h("label", {}, "智能体访问", select, hint) };
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
-
export function memoAccessSettings(source) {
|
|
17
|
-
const
|
|
16
|
+
export async function memoAccessSettings(source) {
|
|
17
|
+
const url = action => "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id });
|
|
18
|
+
Object.assign(source, await api(url("access")));
|
|
19
|
+
const select = memoAccessSelect("默认权限", source.access ?? "off");
|
|
18
20
|
const status = h("p", { role: "status" });
|
|
19
21
|
const refresh = h("button", { class: "btn", type: "button" }, "立即刷新索引");
|
|
20
22
|
const save = h("button", { class: "btn primary", type: "submit" }, "保存权限");
|
|
21
|
-
const form = h("form", { class: "modal-body memo-fields" },
|
|
23
|
+
const form = h("form", { class: "modal-body memo-fields" },
|
|
24
|
+
h("label", {}, "默认权限", select),
|
|
25
|
+
h("small", {}, "专家默认沿用此权限。可在「设置 → 专家」中为指定专家单独设置。"),
|
|
26
|
+
h("small", {}, "授权后会建立全文索引。在专家对话里直接说「帮我搜笔记」或「把这段记到笔记里」即可。"),
|
|
27
|
+
status, refresh, save);
|
|
22
28
|
let timer, sequence = 0;
|
|
23
|
-
const url = action => "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id });
|
|
24
29
|
async function load(method = "GET") {
|
|
25
30
|
clearTimeout(timer);
|
|
26
31
|
const request = ++sequence;
|
|
27
|
-
refresh.hidden = source.access === "
|
|
32
|
+
refresh.hidden = ![source.access, ...Object.values(source.expertAccess ?? {})].some(a => a === "read" || a === "write");
|
|
28
33
|
if (refresh.hidden) { status.textContent = ""; return; }
|
|
29
34
|
try {
|
|
30
35
|
const index = await api(url("index"), { method });
|
|
@@ -39,9 +44,10 @@ export function memoAccessSettings(source) {
|
|
|
39
44
|
refresh.onclick = () => void load("POST");
|
|
40
45
|
form.onsubmit = async e => {
|
|
41
46
|
e.preventDefault();
|
|
47
|
+
if (save.disabled) return;
|
|
42
48
|
save.disabled = true;
|
|
43
49
|
try {
|
|
44
|
-
Object.assign(source, await api(url("access"), { method: "PUT", body: { access: select.value } }));
|
|
50
|
+
Object.assign(source, await api(url("access"), { method: "PUT", body: { access: select.value, defaultOnly: true } }));
|
|
45
51
|
await load();
|
|
46
52
|
} catch (err) { status.textContent = err.message; }
|
|
47
53
|
finally { save.disabled = false; }
|
|
@@ -49,6 +55,37 @@ export function memoAccessSettings(source) {
|
|
|
49
55
|
void load();
|
|
50
56
|
}
|
|
51
57
|
|
|
58
|
+
export async function shareMemoSource(source) {
|
|
59
|
+
const url = "/api/memos/sharing?" + new URLSearchParams({ source: source.id });
|
|
60
|
+
const members = await api(url);
|
|
61
|
+
const fields = members.map(member => {
|
|
62
|
+
const select = memoAccessSelect(member.name, member.access);
|
|
63
|
+
if (member.disabled) for (const option of select.options) option.disabled = option.value !== "off" && option.value !== member.access;
|
|
64
|
+
return { member, select };
|
|
65
|
+
});
|
|
66
|
+
const error = h("div", { class: "memo-error", role: "alert" });
|
|
67
|
+
const save = h("button", { class: "btn primary", type: "submit", disabled: !fields.length }, "保存共享");
|
|
68
|
+
const form = h("form", { class: "modal-body memo-fields" },
|
|
69
|
+
h("small", {}, "成员可在自己的备忘录里打开整个笔记库,包括文件和版本历史。共享给成员不会同时授权给对方的专家。"),
|
|
70
|
+
fields.length ? fields.map(({ member, select }) => h("label", { class: "memo-expert-access" },
|
|
71
|
+
member.name + (member.disabled ? "(已停用)" : ""), select)) : h("p", {}, "还没有其他可共享的账号。"), error, save);
|
|
72
|
+
let saving = false;
|
|
73
|
+
const close = modal({ title: source.name + " · 共享给成员", body: form, beforeClose: () => !saving });
|
|
74
|
+
form.onsubmit = async e => {
|
|
75
|
+
e.preventDefault();
|
|
76
|
+
if (saving) return;
|
|
77
|
+
saving = save.disabled = true;
|
|
78
|
+
try {
|
|
79
|
+
const changes = Object.fromEntries(fields.filter(({ member, select }) => member.access !== select.value)
|
|
80
|
+
.map(({ member, select }) => [member.id, select.value]));
|
|
81
|
+
await api(url, { method: "PUT", body: { changes } });
|
|
82
|
+
close();
|
|
83
|
+
toast("共享设置已保存");
|
|
84
|
+
} catch (err) { error.textContent = err.message; }
|
|
85
|
+
finally { saving = save.disabled = false; }
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
52
89
|
export function connectSource(onConnect) {
|
|
53
90
|
const kind = h("select", { class: "input" }, h("option", { value: "webdav" }, "WebDAV"), h("option", { value: "s3" }, "S3 / 兼容存储"));
|
|
54
91
|
const input = (name, placeholder = "", type = "text") => h("input", { class: "input", name, placeholder, type, autocomplete: "off" });
|
|
@@ -117,7 +154,7 @@ export function askMemoName(title, initial, directory) {
|
|
|
117
154
|
}
|
|
118
155
|
|
|
119
156
|
/** Only fetch the selected snapshot. Restoring returns its text to the normal conditional save path. */
|
|
120
|
-
export async function chooseMemoVersion(url) {
|
|
157
|
+
export async function chooseMemoVersion(url, readOnly = false) {
|
|
121
158
|
const versions = await api(url);
|
|
122
159
|
return new Promise(resolve => {
|
|
123
160
|
let request = 0, selected = null;
|
|
@@ -126,7 +163,7 @@ export async function chooseMemoVersion(url) {
|
|
|
126
163
|
const preview = h("pre", { class: "memo-snapshot", "aria-label": "版本正文" });
|
|
127
164
|
const apply = h("button", { class: "btn primary", disabled: true, onclick: () => { close(); resolve(selected); } }, "恢复此版本");
|
|
128
165
|
const body = h("div", { class: "modal-body memo-fields" },
|
|
129
|
-
versions.length ? [select, preview, apply] : h("p", {}, "还没有历史版本。下次保存修改时,会保留修改前的正文。"));
|
|
166
|
+
versions.length ? [select, preview, readOnly ? null : apply] : h("p", {}, "还没有历史版本。下次保存修改时,会保留修改前的正文。"));
|
|
130
167
|
const close = modal({ title: "版本历史", body, beforeClose: () => { resolve(null); } });
|
|
131
168
|
async function load() {
|
|
132
169
|
const seq = ++request;
|
package/web/views/memos.js
CHANGED
|
@@ -5,7 +5,7 @@ import { confirmDialog } from "../lib/overlay.js";
|
|
|
5
5
|
import { WS } from "../lib/ws.js";
|
|
6
6
|
import { S, setContentHash, ui } from "../state.js";
|
|
7
7
|
import { createEditor } from "./file-editor.js";
|
|
8
|
-
import { askMemoName, chooseMemoVersion, connectSource, memoAccessSettings } from "./memo-dialogs.js";
|
|
8
|
+
import { askMemoName, chooseMemoVersion, connectSource, memoAccessSettings, shareMemoSource } from "./memo-dialogs.js";
|
|
9
9
|
import { closeSide, renderSidebar } from "./sidebar.js";
|
|
10
10
|
import { renderTopbar } from "./topbar.js";
|
|
11
11
|
|
|
@@ -78,8 +78,15 @@ function notebook() {
|
|
|
78
78
|
const side = h("aside", { class: "memo-side" });
|
|
79
79
|
const pathLabel = h("strong", { class: "memo-path" });
|
|
80
80
|
const entryButton = button("连接笔记库", () => addSource());
|
|
81
|
+
const accessButton = h("button", { class: "btn", onclick: () => run(() => memoAccessSettings(source)) }, icon("gear"), "智能体访问");
|
|
82
|
+
const shareButton = button("共享给成员", () => run(() => shareMemoSource(source)));
|
|
83
|
+
const disconnectButton = button("断开笔记库", () => run(disconnect), "unplug");
|
|
84
|
+
const newNote = button("新建笔记", () => run(() => create(false)));
|
|
85
|
+
const newFolder = button("新建文件夹", () => run(() => create(true)), "folder");
|
|
86
|
+
const readOnly = () => source?.permission === "read";
|
|
81
87
|
function endpoint(action, file = "", cursor = "") {
|
|
82
|
-
return "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id, path: file,
|
|
88
|
+
return "/api/memos/" + action + "?" + new URLSearchParams({ source: source.id, path: file,
|
|
89
|
+
...(source.sharedBy ? { owner: source.sharedBy.id } : {}), ...(action === "file" ? { collab: "1" } : {}), ...(cursor ? { cursor } : {}) });
|
|
83
90
|
}
|
|
84
91
|
function sync() {
|
|
85
92
|
retryButton.hidden = !saveError || conflict;
|
|
@@ -87,9 +94,10 @@ function notebook() {
|
|
|
87
94
|
status.title = saveError;
|
|
88
95
|
toggle.disabled = busy;
|
|
89
96
|
choose.disabled = busy;
|
|
90
|
-
|
|
97
|
+
shareButton.disabled = accessButton.disabled = busy;
|
|
98
|
+
copyButton.hidden = !conflict || readOnly();
|
|
91
99
|
status.textContent = conflict ? "远端已更改" : saving ? "正在保存…" : saveError ? "保存失败" :
|
|
92
|
-
busy ? "处理中…" : dirty ? "待自动保存" : editor ? "已保存" : "";
|
|
100
|
+
busy ? "处理中…" : dirty ? "待自动保存" : readOnly() ? "只读" : editor ? "已保存" : "";
|
|
93
101
|
}
|
|
94
102
|
async function run(fn) {
|
|
95
103
|
if (busy) return;
|
|
@@ -147,17 +155,35 @@ function notebook() {
|
|
|
147
155
|
expanded = new Set();
|
|
148
156
|
root.classList.add("show-tree");
|
|
149
157
|
if (s) localStorage.setItem(chooseKey, s.id);
|
|
150
|
-
|
|
158
|
+
fillChoices();
|
|
151
159
|
if (s) choose.value = s.id;
|
|
160
|
+
accessButton.hidden = shareButton.hidden = disconnectButton.hidden = !!s?.sharedBy;
|
|
161
|
+
toggle.hidden = newNote.hidden = newFolder.hidden = readOnly();
|
|
152
162
|
side.hidden = !s;
|
|
153
163
|
root.classList.toggle("no-source", !s);
|
|
154
164
|
if (!s) {
|
|
155
165
|
fill(pane, h("div", { class: "memo-empty" }, icon("clipboard"), h("h2", {}, "连接你的笔记库"), h("p", {}, "从 WebDAV 目录或 S3 存储桶打开笔记。"), entryButton));
|
|
156
166
|
return;
|
|
157
167
|
}
|
|
158
|
-
fill(pane, h("div", { class: "memo-blankbar" }, toggleTree), h("div", { class: "memo-empty" }, icon("file"), h("p", {}, "选择文件,或在当前目录新建笔记。")));
|
|
168
|
+
fill(pane, h("div", { class: "memo-blankbar" }, toggleTree), h("div", { class: "memo-empty" }, icon("file"), h("p", {}, readOnly() ? "选择文件查看。" : "选择文件,或在当前目录新建笔记。")));
|
|
159
169
|
refreshTree();
|
|
160
170
|
}
|
|
171
|
+
function fillChoices() {
|
|
172
|
+
fill(choose, sources.map(item => h("option", { value: item.id }, item.sharedBy
|
|
173
|
+
? item.name + " · " + item.sharedBy.name + "共享(" + (item.permission === "read" ? "只读" : "读写") + ")" : item.name)));
|
|
174
|
+
}
|
|
175
|
+
async function reloadSources() {
|
|
176
|
+
const list = await api("/api/memos/sources");
|
|
177
|
+
if (busy || dirty || saving) return;
|
|
178
|
+
sources = list;
|
|
179
|
+
const latest = sources.find(s => s.id === source?.id);
|
|
180
|
+
if (!latest || latest.permission !== source.permission) select(latest ?? sources[0]);
|
|
181
|
+
else {
|
|
182
|
+
Object.assign(source, latest);
|
|
183
|
+
fillChoices();
|
|
184
|
+
choose.value = latest.id;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
161
187
|
function addSource() {
|
|
162
188
|
void run(async () => {
|
|
163
189
|
if (!(await discardable())) return;
|
|
@@ -166,9 +192,9 @@ function notebook() {
|
|
|
166
192
|
}
|
|
167
193
|
async function disconnect() {
|
|
168
194
|
if (!(await discardable())) return;
|
|
169
|
-
if (!(await confirmDialog({ title: "断开笔记库?", message: `将移除「${source.name}
|
|
195
|
+
if (!(await confirmDialog({ title: "断开笔记库?", message: `将移除「${source.name}」的连接,并撤回这个库的所有共享。远端文件和本地版本历史会保留。${dirty ? "当前草稿尚未保存。" : ""}`, confirmText: "断开连接" }))) return;
|
|
170
196
|
await api(endpoint("sources"), { method: "DELETE" });
|
|
171
|
-
sources = sources.filter(s => s !== source);
|
|
197
|
+
sources = sources.filter(s => s.id !== source.id);
|
|
172
198
|
select(sources[0]);
|
|
173
199
|
}
|
|
174
200
|
|
|
@@ -279,7 +305,7 @@ function notebook() {
|
|
|
279
305
|
fill(toolbar, toggleTree, pathLabel, status, toggle, historyButton, copyButton, retryButton);
|
|
280
306
|
fill(pane, toolbar, editorHost, reading);
|
|
281
307
|
session = conflict ? null : data.collab;
|
|
282
|
-
editor = await createEditor({ parent: editorHost, collaboration: session, text: session ? original : draft?.text ?? original, name: file, onSave: () => void saveNow().catch(err => toast(err.message)), onChange: () => {
|
|
308
|
+
editor = await createEditor({ parent: editorHost, readOnly: readOnly(), collaboration: session, text: session ? original : draft?.text ?? original, name: file, onSave: () => void saveNow().catch(err => toast(err.message)), onChange: () => {
|
|
283
309
|
if (receiving) return;
|
|
284
310
|
dirty = editor.collaboration ? !!editor.collaboration.pending() : editor.text() !== original;
|
|
285
311
|
if (!conflict) { saveError = ""; retryMs = 0; }
|
|
@@ -341,10 +367,18 @@ function notebook() {
|
|
|
341
367
|
const packet = await api(changesURL(current.collaboration.revision()), { headers, signal: controller.signal });
|
|
342
368
|
if (controller.signal.aborted) break;
|
|
343
369
|
applyPacket(current, packet);
|
|
370
|
+
if (source.sharedBy && packet.permission !== source.permission && !dirty && !saving && !busy) {
|
|
371
|
+
await reloadSources();
|
|
372
|
+
if (current !== editor) break;
|
|
373
|
+
}
|
|
344
374
|
retry = 1000;
|
|
345
375
|
} catch (err) {
|
|
346
376
|
if (controller.signal.aborted) break;
|
|
347
377
|
if ([401, 403, 404, 409].includes(err.status)) {
|
|
378
|
+
if (source.sharedBy && (err.status === 403 || err.status === 404) && !dirty && !saving && !busy) {
|
|
379
|
+
await reloadSources().catch(error => toast(error.message));
|
|
380
|
+
if (current !== editor) break;
|
|
381
|
+
}
|
|
348
382
|
if (!dirty && !saving && !busy && err.status === 409) {
|
|
349
383
|
await run(async () => {
|
|
350
384
|
const fresh = await api(endpoint("file", path));
|
|
@@ -431,7 +465,7 @@ function notebook() {
|
|
|
431
465
|
async function openHistory() {
|
|
432
466
|
if (saving) await saving.catch(() => {});
|
|
433
467
|
if (dirty && !conflict) await saveNow();
|
|
434
|
-
const text = await chooseMemoVersion(endpoint("history", path));
|
|
468
|
+
const text = await chooseMemoVersion(endpoint("history", path), readOnly());
|
|
435
469
|
if (text === null) return;
|
|
436
470
|
if (conflict) throw new Error("请先另存草稿并重新打开文件,再恢复旧版");
|
|
437
471
|
editor.setText(text);
|
|
@@ -478,8 +512,8 @@ function notebook() {
|
|
|
478
512
|
refreshTree();
|
|
479
513
|
});
|
|
480
514
|
}, true);
|
|
481
|
-
fill(side, h("div", { class: "memo-sources" }, choose,
|
|
482
|
-
h("div", { class: "memo-tree-tools" },
|
|
515
|
+
fill(side, h("div", { class: "memo-sources" }, choose, accessButton, shareButton, button("连接其他笔记库", addSource, "plus"), disconnectButton),
|
|
516
|
+
h("div", { class: "memo-tree-tools" }, newNote, newFolder, button("刷新目录", refreshTree, "refresh"), h("button", { class: "btn memo-return", onclick: () => root.classList.remove("show-tree") }, "返回文件")), tree);
|
|
483
517
|
fill(root, side, pane);
|
|
484
518
|
async function init() {
|
|
485
519
|
fill(pane, h("div", { class: "memo-empty" }, "正在读取笔记库…"));
|
|
@@ -487,11 +521,11 @@ function notebook() {
|
|
|
487
521
|
sources = await api("/api/memos/sources");
|
|
488
522
|
const draft = savedDraft();
|
|
489
523
|
select(sources.find(s => s.id === (draft?.source ?? localStorage.getItem(chooseKey))) ?? sources[0]);
|
|
490
|
-
if (source && draft?.source === source.id && typeof draft.text === "string") {
|
|
524
|
+
if (source && !readOnly() && draft?.source === source.id && typeof draft.text === "string") {
|
|
491
525
|
await run(async () => {
|
|
492
526
|
let data;
|
|
493
527
|
try { data = await api(endpoint("file", draft.path)); }
|
|
494
|
-
catch { data = { text: null, version: null }; }
|
|
528
|
+
catch (err) { if (source.sharedBy) throw err; data = { text: null, version: null }; }
|
|
495
529
|
for (let p = parent(draft.path); p; p = parent(p)) expanded.add(p);
|
|
496
530
|
await showText(draft.path, data, true, draft);
|
|
497
531
|
refreshTree();
|
|
@@ -502,7 +536,7 @@ function notebook() {
|
|
|
502
536
|
}
|
|
503
537
|
side.hidden = true;
|
|
504
538
|
void init();
|
|
505
|
-
return { owner, root, persistDraft, pausePoll, resumePoll, flush: () => {
|
|
539
|
+
return { owner, root, reloadSources, persistDraft, pausePoll, resumePoll, flush: () => {
|
|
506
540
|
if (!busy && !conflict) void saveNow().catch(() => {});
|
|
507
541
|
}, pending: () => dirty || busy || !!saving, destroy: resetDocument, measure: () => editor?.measure() };
|
|
508
542
|
}
|
|
@@ -531,6 +565,7 @@ export function openMemos() {
|
|
|
531
565
|
renderTopbar();
|
|
532
566
|
renderSidebar();
|
|
533
567
|
if (page?.owner !== S.user.id) { page?.destroy(); page = notebook(); }
|
|
568
|
+
else void page.reloadSources().catch(err => toast(err.message));
|
|
534
569
|
fill(ui.msgInner, page.root);
|
|
535
570
|
page.measure();
|
|
536
571
|
page.resumePoll();
|