agent-loft 0.2.67 → 0.2.69

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 CHANGED
@@ -28,7 +28,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
28
28
  | 🤖 | **同时管理多个 agent** | Claude Code(官方 Claude Agent SDK)和 Codex(官方 `codex app-server`)共用会话列表、工作目录和授权。新建对话时选专家:内置的 Claude Code / Codex,或者自己配的专家 |
29
29
  | 🧑‍🏫 | **专家** | 自己配专家:选引擎、写提示词,定它能做什么(只能联网 / 读文件 / 改文件 / 跑命令),挂哪些技能和 MCP,能把活派给哪些子智能体。新对话、定时任务都能选 |
30
30
  | 🔀 | **飞书机器人灵活绑定 agent** | 机器人数量不限,每个机器人可以直接勾选内置或共享专家,并选择默认专家(可在会话里切换)。网页上扫码就能创建,改完立即生效;由服务端主动连向飞书,家里没有公网 IP 也能在外面用 |
31
- | 🔗 | **飞书续接 Web 任务** | 飞书里发 `/web` 接上一条 Web 会话,或者在网页侧栏右键会话选「在飞书继续…」。之后回复、授权、提问都发到飞书,发 `/detach` 回来 |
31
+ | 🔗 | **飞书续接 Web 任务** | 飞书里发 `/web` 接上一条 Web 会话,或者在网页聊天右上角「更多」或侧栏会话右键菜单里选「在飞书继续」。之后回复、授权、提问都发到飞书,发 `/detach` 回来 |
32
32
  | 🖥️ | **完整的 Web 工作台** | 流式回复、附件、语音输入、模型和思考程度切换、上下文占用、从任意回复分叉、按项目分组的侧栏、搜索会话、全部设置,电脑和手机(PWA)都能用 |
33
33
  | 🔔 | **飞书 + 苹果系统推送** | 除了飞书消息,Web 会话还能推送到 iPhone、iPad 锁屏和 Mac 通知中心(标准 Web Push,不需要开发者账号),图标上显示未读数 |
34
34
  | 🗂️ | **桌面端同时接入多台设备** | 桌面端(macOS / Windows / Linux)同时连多台服务器,菜单栏 / 托盘一眼看完各台的额度、待处理和运行中的会话 |
@@ -47,6 +47,8 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
47
47
  - 附件:粘贴、拖拽,手机上可以拍照;可以预览和下载。附件存在服务端的专用上传目录里,发出去的都收进资料库,开新会话、切换目录也不删。
48
48
  - 回复里提到的文件(链接、`路径`、正文里的绝对路径,Claude 和 Codex 都认)点一下就能预览:图片、PDF、音视频、markdown、代码和文本直接看,网页渲染出来看(也能切到源码),其它的下载。Codex 的 visualize 插件画的图表(回复里的 `visualize{"path":…}`)和官方客户端一样直接嵌在回复里。网页和图表放在沙箱里显示,碰不到登录态和本站接口。
49
49
  - **回复里的图**:专家和 agent 在回复里写 ```` ```chart ````(一段 JSON:折线、面积、柱状、饼图、散点)就画成可悬停的图,可以切到表格看具体数字;写 ```` ```mermaid ```` 画流程图、时序图等。跟着系统深浅色走,图库用到时才加载;飞书上 chart 换成表格。写法自动附在每个专家(包括内置的 Claude Code、Codex)的提示词里。只认这条对话里 agent 回复写过的路径;私钥、`.ssh`、`.env`、各种凭据和 agent-loft 自己的配置数据一律不给看。
50
+ - **回复里的相册**:agent 用 ```` ```album ```` JSON 描述多张本地照片,网页显示缩略图网格,每页 12 张、懒加载;点开大图可左右切换,也支持方向键和 Esc。可附名称、拍摄日期、说明和查询总数,每个相册最多 200 张;飞书显示简短摘要。写法自动附在所有专家的提示词里,图片沿用会话文件权限。
51
+ - 聊天右上角「更多」和侧栏会话右键菜单共用分叉、重命名、在飞书继续、删除操作,按会话类型和可用机器人显示。
50
52
  - 语音输入:用浏览器自带的语音识别(Chrome / Edge / Safari,需要 HTTPS)。
51
53
  - 新对话页:点大标题里的目录名,在固定高度的目录弹窗里逐层选工作目录,也能新建文件夹;输入框上方选专家,鼠标停在专家上看简介,右下角选模型和思考程度。对话从头到尾一个专家,要换专家就新建对话;模型和思考程度随时可换。
52
54
  - 输入框里的小圆环显示上下文窗口占用;模型按钮显示实际的模型和思考程度(如「Opus 5.5 high」)。
@@ -62,6 +64,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
62
64
  - 太长的消息先收起,点「展开显示」看全文;对话里有至少 3 条用户消息时,右侧显示快速定位尺,电脑上鼠标移入查看消息开头、点击跳转;手机上手动滚动时显示短轨道,按住拖动可预览问题和位置,松手跳转,停止操作约 1.6 秒后隐藏。
63
65
  - 回复底部的 token 数自动按大小显示为 K、M 等单位。
64
66
  - 侧栏按页加载:每个项目目录和飞书机器人分组先显示 5 条,点「展开显示」每次再拉 10 条。
67
+ - 项目和飞书分组可混合拖拽排序,飞书可以放在项目前面或项目之间;右键(触屏长按)可置顶、上移、下移或按最近活跃重排。顺序按账号保存,刷新、换设备后保留,新消息不会改变已排好的位置。
65
68
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
66
69
  - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。
67
70
  - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。管理员还可查看服务端本机直接使用的 Claude Code、Codex 桌面端和 CLI 用量,和 Agent Loft 的用量分开显示、避免重复计算。金额都是按 API 价格算的参考值:Agent Loft 的 Claude 用它自己报的费用,Codex 和直接用的 Claude Code 按模型单价 × token 估算(OpenAI 单价来自 LiteLLM 公开价格表,内置快照、联网时每天更新)。Agent Loft 的账从 0.2.34 开始记录;本机直接使用的用量可回溯已有会话记录。
@@ -172,6 +175,7 @@ agent-loft service install
172
175
  这个服务能让 agent 在你的机器上执行命令,等于一个远程 shell。
173
176
 
174
177
  - Web 登录密码用 scrypt 哈希保存。首次建管理员必须用启动日志里的一次性设置码,防止「谁先打开页面谁就成了主人」。
178
+ - 管理员在 设置 → 用户 添加成员时,或点已有成员的「使用权限」,可以分别设置共享专家、内置 Agent、服务器切换为「全部允许(含以后新增)」或指定列表(可全部取消);旧账号沿用全部允许。共享专家和内置 Agent 分别授权,成员自己创建的专家仍可使用;收回权限后旧对话可查看,但不能继续调用,相关定时任务会暂停。服务器权限控制本机切换列表,当前服务器保持可用,各台服务器仍各自登录和管理账号。每个用户都可以在 设置 → 账号 修改自己的账号名称(也是登录名),修改不影响原有对话和登录设备。
175
179
  - 多用户只隔开**界面上**的东西:会话列表、授权 / 提问卡、通知、记忆、`/sessions` 能列出和恢复的 agent 会话;设置、飞书机器人和飞书会话只给管理员(绑定了账号的飞书私聊除外,它归绑定的人);会落盘、对所有人生效的「总是允许」(Claude 的总是允许名单、Codex 的 execpolicy)只有管理员能点。**它不是安全边界**:所有 agent 都以同一个系统用户运行,任何用户都能让 agent 读到这台机器上的文件(别人的对话记录、配置里的密钥),用的也是同一个 Claude / Codex 订阅。只给信任的人开账号;要真正隔离,就每人用自己的系统用户各跑一份 agent-loft。
176
180
  - 从老版本升级:原来的登录密码自动变成管理员 `admin`,已登录的设备不用重新登录。
177
181
  - 登录态通过 HttpOnly cookie 保存,服务端只存它的哈希。同一 IP 连续输错 5 次锁 15 分钟。所有写请求和 WebSocket 都校验 Origin。页面开启了严格的 CSP。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.67",
3
+ "version": "0.2.69",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -8,6 +8,7 @@ import { createEnvelope, type CardCtx, type EnvelopeAction } from "./envelope.js
8
8
  import { answerTextOf, SETTLEMENT_LABEL, type Interaction } from "../../core/interactions.js";
9
9
  import { usageOf, type CommandEntry } from "../../core/command-catalog.js";
10
10
  import { chartsToTables } from "../../core/charts.js";
11
+ import { albumsToText } from "../../core/albums.js";
11
12
  import type { ModelInfo, SessionSummary } from "../../core/types.js";
12
13
 
13
14
  function button(
@@ -174,9 +175,9 @@ export function progressCard(params: { steps: string[]; done?: boolean; footer?:
174
175
  ]);
175
176
  }
176
177
 
177
- /** 回复卡:飞书纯文本不渲染 markdown,所以回复必须走卡片。刻意做到最简。```chart 画不了,换成表格 */
178
+ /** 回复卡:飞书纯文本不渲染 markdown,所以回复走卡片。图表换成表格,相册换成摘要。 */
178
179
  export function replyCard(text: string) {
179
- return card([{ tag: "markdown", content: clip(chartsToTables(text), 4000) }]);
180
+ return card([{ tag: "markdown", content: clip(chartsToTables(albumsToText(text)), 4000) }]);
180
181
  }
181
182
 
182
183
  // ---------- 命令结果 ----------
@@ -499,7 +499,7 @@ function adminOnly(p: string): boolean {
499
499
  );
500
500
  }
501
501
 
502
- function publicMe(user: User) {
502
+ function publicMe(user: Pick<User, "id" | "name" | "role">) {
503
503
  return { id: user.id, name: user.name, role: user.role };
504
504
  }
505
505
 
@@ -680,6 +680,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
680
680
  id,
681
681
  label: d?.label ?? id,
682
682
  enabled: hub.enabledAgents().some((e) => e.id === id),
683
+ allowed: canUseExpert(user.id, id),
683
684
  capabilities: d?.capabilities ?? {},
684
685
  // 输入框模型列表里显示哪些,空 = 全部
685
686
  models: config().agents[id].models.filter((m) => typeof m === "string"),
@@ -700,20 +701,20 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
700
701
  // 展开着的目录带上翻页游标(没带 next 的目录前端还没拉过)
701
702
  dirs: dirsOf(all).map((d) => (dirPages.has(d.dir) ? { ...d, next: dirPages.get(d.dir)!.next } : d)),
702
703
  },
703
- // 「项目」目录的顺序(拖拽排的),跟着账号走;null = 还没存过
704
+ // 项目和飞书分组的混合顺序,跟着账号走;沿用目录排序字段兼容旧数据
704
705
  dirOrder: getDirOrder(user.id) ?? null,
705
706
  sidebarNav: getSidebarNav(user.id),
706
707
  pending,
707
708
  user: publicMe(user),
708
709
  remote: remoteStatus(user),
709
710
  // 左上角切换服务器:没加别的服务器是 null
710
- servers: shellInfo(config().servers),
711
+ servers: shellInfo(config().servers, user),
711
712
  serverTime: Date.now(),
712
713
  });
713
714
  return;
714
715
  }
715
716
 
716
- // ----- 侧栏「项目」目录顺序:order 整份换掉,append 只把新目录接在最后 -----
717
+ // ----- 侧栏分组顺序:order 整份换掉,append 只把新分组接在最后 -----
717
718
  if (p === "/api/ui/dir-order" && method === "PUT") {
718
719
  const body = await readJsonBody<{ order?: unknown; append?: unknown }>(req);
719
720
  const order = body.order !== undefined ? setDirOrder(user.id, body.order) : appendDirOrder(user.id, body.append);
@@ -746,7 +747,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
746
747
  // 多服务器(core/servers.ts):外壳把这个浏览器的订阅连同签名密钥转给嵌着的各台(web/lib/shell.js),
747
748
  // 各台直接推到手机上,不经过外壳。密钥只在加了别的服务器时给
748
749
  if (p === "/api/push/relay-key" && method === "GET") {
749
- if (!config().servers.list.length) throw new HttpError(404, "没有加别的服务器");
750
+ if (!shellInfo(config().servers, user)) throw new HttpError(404, "没有可用的其他服务器");
750
751
  sendJson(res, 200, vapidKeyPair());
751
752
  return;
752
753
  }
@@ -866,8 +867,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
866
867
  const body = await readJsonBody<{ expert?: string; agent?: string; cwd?: string }>(req);
867
868
  const enabled = hub.enabledAgents().map((d) => d.id);
868
869
  const wanted = body.expert ?? body.agent;
869
- if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家不存在或已取消共享");
870
- const expertId = wanted || enabled[0];
870
+ if (wanted && !canUseExpert(user.id, wanted)) throw new HttpError(400, "这个专家或 Agent 不存在、已取消共享或未获授权");
871
+ const expertId = wanted || hub.expertChoices(user.id, enabled)[0]?.id;
871
872
  if (!expertId) throw new HttpError(400, "没有可用的 agent");
872
873
  const custom = isBuiltin(expertId) ? undefined : getExpert(expertId);
873
874
  const agent = custom ? custom.engine : expertId;
@@ -1379,6 +1380,15 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1379
1380
  return;
1380
1381
  }
1381
1382
 
1383
+ // 修改自己的登录名:只允许改名称,沿用现有设备和会话归属。
1384
+ if (p === "/api/account" && method === "PATCH") {
1385
+ const body = await readJsonBody<{ name?: unknown }>(req);
1386
+ if (typeof body.name !== "string") throw new HttpError(400, "请填写账号名称");
1387
+ const updated = userOp(() => patchUser(user.id, { name: body.name as string }));
1388
+ sendJson(res, 200, { user: publicMe(updated) });
1389
+ return;
1390
+ }
1391
+
1382
1392
  // ----- 用户管理(管理员) -----
1383
1393
  if (p === "/api/users" && method === "GET") {
1384
1394
  const devices = listWebSessions();
@@ -1390,6 +1400,11 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1390
1400
  feishuLinks: listLinks(u.id).length,
1391
1401
  })),
1392
1402
  me: user.id,
1403
+ resources: {
1404
+ experts: availableExperts(user.id).filter((e) => e.shared).map((e) => ({ id: e.id, name: e.name })),
1405
+ agents: [...AGENT_IDS].map((id) => ({ id, name: hub.label(id) })),
1406
+ servers: config().servers.list.map(({ id, name }) => ({ id, name })),
1407
+ },
1393
1408
  });
1394
1409
  return;
1395
1410
  }
@@ -1412,11 +1427,11 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1412
1427
  }
1413
1428
  }
1414
1429
  if (p === "/api/users" && method === "POST") {
1415
- const body = await readJsonBody<{ name?: string; password?: string; role?: Role }>(req);
1430
+ const body = await readJsonBody<{ name?: string; password?: string; role?: Role; remote?: boolean; permissions?: unknown }>(req);
1416
1431
  sendJson(
1417
1432
  res,
1418
1433
  200,
1419
- userOp(() => createUser({ name: String(body.name ?? ""), password: String(body.password ?? ""), role: body.role === "admin" ? "admin" : "member" })),
1434
+ userOp(() => createUser({ name: String(body.name ?? ""), password: String(body.password ?? ""), role: body.role === "admin" ? "admin" : "member", ...(typeof body.remote === "boolean" ? { remote: body.remote } : {}), ...(body.permissions !== undefined ? { permissions: body.permissions } : {}) })),
1420
1435
  );
1421
1436
  return;
1422
1437
  }
@@ -1425,7 +1440,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1425
1440
  const id = userMatch[1]!;
1426
1441
  if (!getUser(id)) throw new HttpError(404, "用户不存在");
1427
1442
  if (method === "PATCH") {
1428
- const body = await readJsonBody<{ name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean }>(req);
1443
+ const body = await readJsonBody<{ name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean; permissions?: unknown }>(req);
1429
1444
  if (id === user.id && (body.disabled === true || (body.role !== undefined && body.role !== "admin"))) {
1430
1445
  throw new HttpError(400, "不能停用自己,也不能取消自己的管理员");
1431
1446
  }
@@ -1437,6 +1452,7 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1437
1452
  ...(typeof body.disabled === "boolean" ? { disabled: body.disabled } : {}),
1438
1453
  ...(typeof body.password === "string" ? { password: body.password } : {}),
1439
1454
  ...(typeof body.remote === "boolean" ? { remote: body.remote } : {}),
1455
+ ...(body.permissions !== undefined ? { permissions: body.permissions } : {}),
1440
1456
  }),
1441
1457
  );
1442
1458
  // 管理员在用户列表里重置了自己的密码:当前这台换个新登录态,别把自己踢出去
@@ -21,6 +21,8 @@ import {
21
21
  } from "../../core/experts.js";
22
22
  import { builtinAgentDefaults, setBuiltinAgentDefaults } from "../../core/builtin-agents.js";
23
23
  import { hub } from "../../core/hub.js";
24
+ import { config } from "../../core/config.js";
25
+ import { shellInfo } from "../../core/servers.js";
24
26
  import { claudeMachineMcp, createMcp, deleteMcp, getMcp, listMcp, MACHINE_PREFIX, MCP_LIMITS, mcpView, updateMcp, type McpInput } from "../../core/mcp.js";
25
27
  import { activeSkills } from "../../core/skills.js";
26
28
  import { isAdmin, type User } from "../../core/users.js";
@@ -95,7 +97,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
95
97
 
96
98
  if (p === "/api/agents/defaults" && method === "GET") {
97
99
  sendJson(res, 200, {
98
- agents: builtinAgentDefaults(user.id),
100
+ agents: Object.fromEntries(Object.entries(builtinAgentDefaults(user.id)).filter(([id]) => canUseExpert(user.id, id))),
99
101
  skills: activeSkills(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
100
102
  mcp: listMcp(user.id).map((s) => ({ id: s.id, name: s.name, description: s.description })),
101
103
  ...(await machineMcp(user).then((m) => m ? { machineMcp: m, machinePrefix: MACHINE_PREFIX } : {})),
@@ -104,8 +106,9 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
104
106
  }
105
107
  if (p === "/api/agents/defaults" && method === "PUT") {
106
108
  const body = await readJsonBody<{ agents?: unknown }>(req);
109
+ if (body.agents && typeof body.agents === "object" && Object.keys(body.agents).some((id) => !canUseExpert(user.id, id))) throw new HttpError(403, "没有使用这个内置 Agent 的权限");
107
110
  try {
108
- sendJson(res, 200, { agents: setBuiltinAgentDefaults(user.id, body.agents) });
111
+ sendJson(res, 200, { agents: Object.fromEntries(Object.entries(setBuiltinAgentDefaults(user.id, body.agents)).filter(([id]) => canUseExpert(user.id, id))) });
109
112
  } catch (err) {
110
113
  throw bad(err);
111
114
  }
@@ -116,7 +119,7 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
116
119
  const enabled = hub.enabledAgents().map((d) => d.id);
117
120
  sendJson(res, 200, {
118
121
  experts: availableExperts(user.id).map((e) => expertView(e, user.id)),
119
- builtin: enabled.map((id) => ({ id, name: hub.label(id), engine: id })),
122
+ builtin: enabled.filter((id) => canUseExpert(user.id, id)).map((id) => ({ id, name: hub.label(id), engine: id })),
120
123
  engines: enabled,
121
124
  templates: EXPERT_TEMPLATES.map((t) => ({ id: t.id, label: t.label, expert: t.expert })),
122
125
  access: ACCESS_LEVELS.map((id) => ({ id, label: ACCESS_LABEL[id] })),
@@ -129,7 +132,12 @@ export async function handleExpertsApi(req: IncomingMessage, res: ServerResponse
129
132
  }
130
133
 
131
134
  if (p === "/api/experts/brief" && method === "GET") {
132
- sendJson(res, 200, { experts: availableExperts(user.id).map(expertBrief) });
135
+ sendJson(res, 200, {
136
+ experts: availableExperts(user.id).map(expertBrief),
137
+ builtin: hub.enabledAgents().filter((d) => canUseExpert(user.id, d.id)).map((d) => d.id),
138
+ user: { id: user.id, name: user.name, role: user.role },
139
+ servers: shellInfo(config().servers, user),
140
+ });
133
141
  return true;
134
142
  }
135
143
 
@@ -0,0 +1,49 @@
1
+ // 回复里的 ```album:网页显示为相册;飞书降级为摘要。JSON 里的文件路径也算显式引用。
2
+ const FENCE = /^ {0,3}(`{3,}|~{3,})[ \t]*album[ \t]*\r?\n([\s\S]*?)\r?\n {0,3}\1[ \t]*$/gim;
3
+ type Photo = { src: string; preview?: string; name?: string; date?: string; caption?: string };
4
+ type Album = { title?: string; total: number; items: Photo[] };
5
+ const localPath = (p: unknown): p is string => typeof p === "string" && p.startsWith("/") && !p.startsWith("//") && !/[\0\r\n]/.test(p);
6
+ const str = (v: unknown): string | undefined => typeof v === "string" ? v : undefined;
7
+
8
+ function parseAlbum(json: string): Album | undefined {
9
+ try {
10
+ const raw = JSON.parse(json);
11
+ if (!raw || !Array.isArray(raw.items) || raw.items.length > 200) return;
12
+ const items: Photo[] = [];
13
+ for (const item of raw.items) {
14
+ if (!item || !localPath(item.src) || (item.preview !== undefined && !localPath(item.preview))) return;
15
+ items.push({ src: item.src, preview: item.preview, name: str(item.name), date: str(item.date), caption: str(item.caption) });
16
+ }
17
+ return { title: str(raw.title), total: Number.isSafeInteger(raw.total) && raw.total >= items.length ? raw.total : items.length, items };
18
+ } catch { return; }
19
+ }
20
+
21
+ /** JSON 转义过的中文、反斜杠等路径也能匹配;不放宽原有的会话文件权限。 */
22
+ export function albumReferences(text: string): { text: string; paths: string[] } {
23
+ const paths: string[] = [];
24
+ if (!/album/i.test(text)) return { text, paths };
25
+ const rest = text.replace(FENCE, (whole, _fence: string, json: string) => {
26
+ const album = parseAlbum(json);
27
+ if (!album) return whole;
28
+ for (const item of album.items) paths.push(item.src, ...(item.preview ? [item.preview] : []));
29
+ return "";
30
+ });
31
+ return { text: rest, paths };
32
+ }
33
+
34
+ const plain = (s: string) => s.replace(/[\r\n]/g, " ").replace(/[\\`*_{}[\]()<>!|#]/g, "\\$&").slice(0, 200);
35
+
36
+ /** 飞书不展示整段 JSON、服务器路径或数百条图片,只保留相册概况。 */
37
+ export function albumsToText(text: string): string {
38
+ if (!/album/i.test(text)) return text;
39
+ return text.replace(FENCE, (whole, _fence: string, json: string) => {
40
+ const album = parseAlbum(json);
41
+ if (!album) return whole;
42
+ const { items, total } = album;
43
+ const lines = [`**${plain(album.title || "相册")}** · 共 ${total} 张${total > items.length ? `(已载入 ${items.length} 张)` : ""}`];
44
+ for (const [i, item] of items.slice(0, 12).entries()) lines.push(`${i + 1}. ${[item.name || `照片 ${i + 1}`, item.date, item.caption].filter(Boolean).map((v) => plain(v!)).join(" · ")}`);
45
+ if (items.length > 12) lines.push(`还有 ${items.length - 12} 张。`);
46
+ lines.push(items.length ? "请在 Web 中打开相册查看照片。" : "没有照片。");
47
+ return lines.join("\n");
48
+ });
49
+ }
@@ -65,8 +65,8 @@ function persona(expert: PromptExpert): string[] {
65
65
  }
66
66
 
67
67
  /**
68
- * 回复里能画的图:网页把 ```chart / ```mermaid 画出来(web/lib/diagrams.js),飞书把 chart 换成表格(core/charts.ts)。
69
- * 所有专家、内置的 Claude Code / Codex 都给。格式改了这三处要一起改。
68
+ * 回复里的富内容:网页画图表和相册,飞书把图表换成表格、相册换成摘要。
69
+ * 所有专家、内置的 Claude Code / Codex 都给;格式改了,对应的 Web 渲染和飞书降级也要一起改。
70
70
  */
71
71
  export const RICH_REPLY_LINES = [
72
72
  "## 回复里的图表",
@@ -80,6 +80,16 @@ export const RICH_REPLY_LINES = [
80
80
  " - 一张图最多 8 组数据,饼图最多 8 块;量级差很多的两种数据分成两张图;缺的数据写 null。只写合法 JSON,不要注释,不要省略号。",
81
81
  "- 流程、时序、状态、结构关系可以用 ```mermaid 代码块画图。",
82
82
  "- 只在图比文字更清楚时才画;几个数字用文字或表格就够了。",
83
+ "",
84
+ "## 回复里的相册",
85
+ "",
86
+ "- 展示多张照片、图片搜索结果时,用 ```album JSON 代码块,Web 会显示缩略图网格、分页和大图预览,飞书显示摘要。例如:",
87
+ " ```album",
88
+ ' {"title":"家庭相片","total":30,"items":[{"src":"/tmp/photos/thumb.webp","preview":"/tmp/photos/preview.jpg","name":"海边合影","date":"2026-10-31","caption":"香港"}]}',
89
+ " ```",
90
+ "- items 每项 src 是已下载缩略图的本地绝对路径;preview 是可选的已下载大图路径,省略时预览缩略图。name、date、caption 可选。total 可选,表示查询结果总数,不能小于 items 数量。",
91
+ "- 每个相册最多 200 张,Web 每页 12 张。只填实际取得的照片和路径,不编造;不要批量下载原图。需要清晰预览时,只为相关照片下载 preview。",
92
+ "- 路径直接写在 JSON 字符串里,不做 URL 编码;不要填远程 URL、API 密钥或 auth_code。图片仍受当前会话的文件权限控制。多张照片优先用相册,单张图片可继续用 Markdown。",
83
93
  ];
84
94
 
85
95
  /** Claude 自定义专家的整段系统提示(lean:换掉 Claude Code 原装的) */
@@ -14,7 +14,7 @@ import { dataDir, readJson, writeJsonAtomic } from "../home.js";
14
14
  import { resolveWorkspacePath } from "./config.js";
15
15
  import { claudeMachineMcp, getMcp, isMachineId, machineName, specOf, type McpSpec } from "./mcp.js";
16
16
  import { activeSkills, canSee, getSkill } from "./skills.js";
17
- import { getUser } from "./users.js";
17
+ import { canUseResource, getUser } from "./users.js";
18
18
 
19
19
  export type Engine = "claude" | "codex";
20
20
  export const ENGINES: readonly Engine[] = ["claude", "codex"];
@@ -196,13 +196,13 @@ export function getExpert(id: string): Expert | undefined {
196
196
 
197
197
  /** 共享只开放使用权,不转移专家、工具或会话的所有权。无身份的飞书聊天不能用。 */
198
198
  export function canUseExpert(owner: string | undefined, id: string): boolean {
199
- if (isBuiltin(id)) return true;
199
+ if (isBuiltin(id)) return !owner || canUseResource(getUser(owner), "agents", id);
200
200
  const e = getExpert(id);
201
201
  if (!e || !owner) return false;
202
202
  if (e.owner === owner) return true;
203
203
  const creator = getUser(e.owner);
204
204
  const user = getUser(owner);
205
- return e.shared === true && !!creator && !creator.disabled && !!user && !user.disabled;
205
+ return e.shared === true && !!creator && !creator.disabled && canUseResource(user, "experts", id);
206
206
  }
207
207
 
208
208
  /** 发布者沿用专家原有的工具选择;其他人未配置时不加载技能和 MCP。 */
package/src/core/hub.ts CHANGED
@@ -292,10 +292,12 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
292
292
  }
293
293
  });
294
294
  expertToolEvents.on("changed", (owner) => this.personalChanged(new Set([owner]), true));
295
- userEvents.on("changed", () => {
295
+ userEvents.on("changed", (accessChanged) => {
296
+ if (!accessChanged) return;
297
+ // 自定义专家还可能加载了权限已变更的子智能体;空闲后重新构建工具。
296
298
  for (const [key, live] of this.live) {
297
299
  const conv = getConversation(key);
298
- if (!conv?.expert || canUseExpert(memoryOwnerOf(conv), conv.expert)) continue;
300
+ if (!conv || (!conv.expert && canUseExpert(memoryOwnerOf(conv), conv.agent))) continue;
299
301
  this.staleLive.add(live.id);
300
302
  this.dropIfStale(key);
301
303
  }
@@ -419,7 +421,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
419
421
 
420
422
  /** 对话的专家,给顶栏和列表看 */
421
423
  expertBadge(conv: Pick<Conversation, "agent" | "expert" | "owner" | "channel">): ExpertBadge {
422
- if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true };
424
+ if (!conv.expert) return { id: conv.agent, name: this.label(conv.agent), builtin: true, ...(!canUseExpert(memoryOwnerOf(conv), conv.agent) ? { missing: true } : {}) };
423
425
  const e = getExpert(conv.expert);
424
426
  if (!e || !canUseExpert(memoryOwnerOf(conv), e.id)) return { id: conv.expert, name: "(专家已删除或未共享)", missing: true };
425
427
  return {
@@ -456,7 +458,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
456
458
  */
457
459
  expertChoices(owner: string | undefined, allowedAgents: string[], allowedExperts?: string[]): { id: string; label: string; engine: string }[] {
458
460
  const usable = new Set(this.enabledAgents().map((d) => d.id).filter((a) => allowedAgents.includes(a)));
459
- const builtin = [...usable].map((a) => ({ id: a, label: this.label(a), engine: a }));
461
+ const builtin = [...usable].filter((a) => canUseExpert(owner, a)).map((a) => ({ id: a, label: this.label(a), engine: a }));
460
462
  const own = owner ? availableExperts(owner).filter((e) => usable.has(e.engine)) : [];
461
463
  return [...builtin, ...own.map((e) => ({ id: e.id, label: `${e.icon ? `${e.icon} ` : ""}${e.name}`, engine: e.engine }))].filter((e) => allowedExperts === undefined || allowedExperts.includes(e.id));
462
464
  }
@@ -665,7 +667,7 @@ class Hub extends EventEmitter<{ event: [EventEnvelope]; task: [TaskTurnEnd] }>
665
667
  // 先检查 agent 还启用着:设置里关掉了,已经打开的会话也不能再用
666
668
  const driver = this.requireDriver(conv.agent);
667
669
  // 撤回共享后,即使上一轮还在运行,也不能把新输入交给缓存着的会话。
668
- if (conv.expert && !canUseExpert(memoryOwnerOf(conv), conv.expert)) throw new Error("这条对话用的专家已经删除或取消共享了。新开一个对话,换个专家吧。");
670
+ if (!canUseExpert(memoryOwnerOf(conv), conv.expert ?? conv.agent)) throw new Error("这条对话用的专家或 Agent 已删除、取消共享或未获授权。新开一个对话,换个专家吧。");
669
671
  const existing = this.live.get(key);
670
672
  if (existing && existing.agent === conv.agent && existing.cwd === conv.cwd && !opts.resumeId) {
671
673
  return existing.session;
@@ -7,6 +7,7 @@ import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { home } from "../home.js";
9
9
  import { uploadsRoot } from "./uploads.js";
10
+ import { albumReferences } from "./albums.js";
10
11
 
11
12
  /** 路径里出现这些目录名就不给看(私钥、云凭据、密码库…) */
12
13
  const SENSITIVE_DIRS = new Set([".ssh", ".gnupg", ".aws", ".azure", ".kube", ".docker", ".password-store", ".gcloud"]);
@@ -100,7 +101,9 @@ const PATH_CHAR = /[\p{L}\p{N}_\-./~@+]/u;
100
101
  export function mentions(text: string, p: string): boolean {
101
102
  const needle = p.trim();
102
103
  if (!needle) return false;
103
- const hay = withDecoded(text);
104
+ const refs = albumReferences(text);
105
+ if (refs.paths.includes(needle)) return true;
106
+ const hay = withDecoded(refs.text);
104
107
  for (let i = hay.indexOf(needle); i >= 0; i = hay.indexOf(needle, i + 1)) {
105
108
  const before = hay[i - 1];
106
109
  const after = hay[i + needle.length];
@@ -11,6 +11,7 @@
11
11
  import crypto from "node:crypto";
12
12
  import os from "node:os";
13
13
  import type { AppConfig } from "./config.js";
14
+ import { canUseResource, type User } from "./users.js";
14
15
 
15
16
  export type ServerEntry = AppConfig["servers"]["list"][number];
16
17
 
@@ -106,11 +107,12 @@ export function selfName(cfg: AppConfig["servers"]): string {
106
107
  }
107
108
 
108
109
  /** 页面要的:左上角的切换列表。没加别的服务器就是 null(不显示切换) */
109
- export function shellInfo(cfg: AppConfig["servers"]) {
110
- if (cfg.list.length === 0) return null;
110
+ export function shellInfo(cfg: AppConfig["servers"], user?: User) {
111
+ const list = cfg.list.filter((s) => !user || canUseResource(user, "servers", s.id));
112
+ if (list.length === 0) return null;
111
113
  return {
112
114
  self: { id: SELF_ID, name: selfName(cfg), icon: cfg.selfIcon },
113
- list: cfg.list.map(({ id, name, icon, url }) => ({ id, name, icon, url })),
115
+ list: list.map(({ id, name, icon, url }) => ({ id, name, icon, url })),
114
116
  };
115
117
  }
116
118
 
@@ -51,18 +51,18 @@ type Resolved = { key: string } | { pause: string } | { error: string };
51
51
  /** 这次该发到哪条对话;专用对话还没有(或者被删了)就新建一条 */
52
52
  function resolveConv(task: Task): Resolved {
53
53
  const missingExpert = (id: string | undefined) => !!id && !canUseExpert(task.owner, id);
54
- const deletedExpert = { pause: "任务用的专家已经删除或取消共享了,任务已暂停。编辑任务换一个专家再启用。" };
54
+ const deletedExpert = { pause: "任务用的专家已经删除、取消共享,或专家 / Agent 未获授权,任务已暂停。编辑任务换一个专家再启用。" };
55
55
  if (task.target.kind === "conv") {
56
56
  const conv = getConversation(task.target.key);
57
57
  if (!conv || conv.hidden) return { pause: "回复的那条对话已经被删除,任务已暂停。可以改成「专用对话」后再启用。" };
58
58
  if (ownerOf(conv) !== task.owner) return { pause: "回复的那条对话已经不属于你了,任务已暂停。" };
59
- if (missingExpert(conv.expert)) return deletedExpert;
59
+ if (missingExpert(conv.expert ?? conv.agent)) return deletedExpert;
60
60
  return { key: conv.key };
61
61
  }
62
62
  // 复用专用对话前也要检查,不能等到新建对话时才发现专家已删除。
63
- if (missingExpert(task.expert)) return deletedExpert;
63
+ if (missingExpert(task.expert ?? task.agent)) return deletedExpert;
64
64
  const existing = task.target.key ? getConversation(task.target.key) : undefined;
65
- if (existing && !existing.hidden && existing.taskId === task.id && ownerOf(existing) === task.owner) return missingExpert(existing.expert) ? deletedExpert : { key: existing.key };
65
+ if (existing && !existing.hidden && existing.taskId === task.id && ownerOf(existing) === task.owner) return missingExpert(existing.expert ?? existing.agent) ? deletedExpert : { key: existing.key };
66
66
 
67
67
  // 专家被删了:不能换成别的专家去跑(权限可能大得多),暂停等用户改
68
68
  const expert = task.expert ? getExpert(task.expert) : undefined;
@@ -1,5 +1,5 @@
1
1
  // 每个用户的界面偏好,跟着账号走(换手机、换浏览器、桌面端都一样)。
2
- // 侧栏菜单的显示、顺序,以及「项目」目录的顺序。
2
+ // 侧栏菜单的显示、顺序,以及项目和飞书分组的混合顺序。
3
3
  import path from "node:path";
4
4
  import { dataDir, readJson, writeJsonAtomic } from "../home.js";
5
5
 
@@ -29,7 +29,7 @@ function cleanDirs(list: unknown): string[] {
29
29
  return [...new Set(list.filter((d): d is string => typeof d === "string" && d.length > 0 && d.length < 4096))].slice(0, MAX_DIRS);
30
30
  }
31
31
 
32
- /** 目录顺序;undefined = 这个用户还没在服务端存过(前端可以把本地的迁上来) */
32
+ /** 分组顺序:项目用目录路径,飞书用 feishu:<机器人 id>。沿用旧字段,兼容已有项目排序。 */
33
33
  export function getDirOrder(userId: string): string[] | undefined {
34
34
  return load()[userId]?.dirOrder;
35
35
  }
@@ -43,7 +43,7 @@ export function setDirOrder(userId: string, order: unknown): string[] {
43
43
  return dirOrder;
44
44
  }
45
45
 
46
- /** 新出现的目录接在最后。只追加没有的,不动已有的名次 —— 别的设备同时在拖也不会被盖掉 */
46
+ /** 新分组接在最后。只追加没有的,不动已有的名次 —— 别的设备同时在拖也不会被盖掉 */
47
47
  export function appendDirOrder(userId: string, dirs: unknown): string[] {
48
48
  const all = load();
49
49
  const cur = all[userId]?.dirOrder ?? [];
package/src/core/users.ts CHANGED
@@ -16,6 +16,9 @@ import { dataDir, readJson, writeJsonAtomic } from "../home.js";
16
16
  import { config } from "./config.js";
17
17
 
18
18
  export type Role = "admin" | "member";
19
+ export type ResourceKind = "experts" | "agents" | "servers";
20
+ /** 未设置 / null = 全部(含以后新增);[] = 不允许使用。只限制成员。 */
21
+ export type ResourcePermissions = Partial<Record<ResourceKind, string[] | null>>;
19
22
 
20
23
  export type User = {
21
24
  id: string;
@@ -27,6 +30,7 @@ export type User = {
27
30
  disabled?: boolean;
28
31
  /** 成员能不能用远程控制(终端、桌面)。管理员一直能用,不看这个 */
29
32
  remote?: boolean;
33
+ permissions?: ResourcePermissions;
30
34
  };
31
35
 
32
36
  export type PublicUser = Omit<User, "passwordHash">;
@@ -34,8 +38,8 @@ export type PublicUser = Omit<User, "passwordHash">;
34
38
  type StoreShape = { users: User[] };
35
39
 
36
40
  const usersPath = path.join(dataDir, "users.json");
37
- /** 用户增删改、停用、改密码:登录态要重新校验 */
38
- export const userEvents = new EventEmitter<{ changed: [] }>();
41
+ /** 登录态总要重新校验;accessChanged 只在使用权限、角色或可用账号发生变化时为 true。 */
42
+ export const userEvents = new EventEmitter<{ changed: [accessChanged: boolean] }>();
39
43
 
40
44
  let cache: User[] | null = null;
41
45
  let loadedMtime = 0;
@@ -67,11 +71,11 @@ function load(): User[] {
67
71
  return cache;
68
72
  }
69
73
 
70
- function save(list: User[]): void {
74
+ function save(list: User[], accessChanged = true): void {
71
75
  cache = list;
72
76
  writeJsonAtomic(usersPath, { users: list });
73
77
  loadedMtime = mtimeOf(usersPath);
74
- userEvents.emit("changed");
78
+ userEvents.emit("changed", accessChanged);
75
79
  }
76
80
 
77
81
  /**
@@ -99,7 +103,7 @@ function newId(): string {
99
103
 
100
104
  function publicUser(u: User): PublicUser {
101
105
  const { passwordHash: _hidden, ...rest } = u;
102
- return { ...rest };
106
+ return structuredClone(rest);
103
107
  }
104
108
 
105
109
  // ---------- 密码 ----------
@@ -173,6 +177,23 @@ export function canUseRemote(user: Pick<User, "role" | "disabled" | "remote"> |
173
177
  return user.role === "admin" || user.remote === true;
174
178
  }
175
179
 
180
+ export function canUseResource(user: Pick<User, "role" | "disabled" | "permissions"> | undefined, kind: ResourceKind, id: string): boolean {
181
+ if (!user || user.disabled) return false;
182
+ return user.role === "admin" || user.permissions?.[kind] == null || user.permissions[kind]!.includes(id);
183
+ }
184
+
185
+ function cleanPermissions(value: unknown, current: ResourcePermissions = {}): ResourcePermissions {
186
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("使用权限格式不对");
187
+ const next = structuredClone(current);
188
+ for (const [kind, ids] of Object.entries(value)) {
189
+ if (!["experts", "agents", "servers"].includes(kind)) throw new Error("未知的使用权限");
190
+ if (ids !== null && (!Array.isArray(ids) || ids.length > 200 || ids.some((id) => typeof id !== "string" || !/^[\w-]{1,100}$/.test(id)))) throw new Error("使用权限必须是 ID 列表或 null");
191
+ if (kind === "agents" && ids?.some((id: string) => !["claude", "codex"].includes(id))) throw new Error("未知的内置 Agent");
192
+ next[kind as ResourceKind] = ids === null ? null : [...new Set(ids as string[])];
193
+ }
194
+ return next;
195
+ }
196
+
176
197
  /**
177
198
  * 升级前的登录态、推送订阅没有记是谁的:都算最早的那个管理员的(就是迁移出来的 admin)。
178
199
  */
@@ -212,7 +233,7 @@ function assertAdminLeft(list: User[]): void {
212
233
  if (!list.some((u) => u.role === "admin" && !u.disabled)) throw new Error("至少要保留一个能登录的管理员");
213
234
  }
214
235
 
215
- export function createUser(params: { name: string; password: string; role?: Role }): PublicUser {
236
+ export function createUser(params: { name: string; password: string; role?: Role; remote?: boolean; permissions?: unknown }): PublicUser {
216
237
  const list = load();
217
238
  const name = checkName(params.name);
218
239
  if (list.some((u) => u.name.toLowerCase() === name.toLowerCase())) throw new Error(`用户名「${name}」已经有人用了`);
@@ -223,6 +244,8 @@ export function createUser(params: { name: string; password: string; role?: Role
223
244
  role: params.role === "admin" ? "admin" : "member",
224
245
  passwordHash: hashPassword(params.password),
225
246
  createdAt: Date.now(),
247
+ ...(params.remote === true ? { remote: true } : {}),
248
+ ...(params.permissions !== undefined ? { permissions: cleanPermissions(params.permissions) } : {}),
226
249
  };
227
250
  save([...list, user]);
228
251
  return publicUser(user);
@@ -230,7 +253,7 @@ export function createUser(params: { name: string; password: string; role?: Role
230
253
 
231
254
  export function updateUser(
232
255
  id: string,
233
- patch: { name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean },
256
+ patch: { name?: string; role?: Role; disabled?: boolean; password?: string; remote?: boolean; permissions?: unknown },
234
257
  ): PublicUser {
235
258
  const list = load().map((u) => ({ ...u }));
236
259
  const user = list.find((u) => u.id === id);
@@ -249,12 +272,13 @@ export function updateUser(
249
272
  if (patch.remote) user.remote = true;
250
273
  else delete user.remote;
251
274
  }
275
+ if (patch.permissions !== undefined) user.permissions = cleanPermissions(patch.permissions, user.permissions);
252
276
  if (patch.password !== undefined) {
253
277
  checkPassword(patch.password);
254
278
  user.passwordHash = hashPassword(patch.password);
255
279
  }
256
280
  assertAdminLeft(list);
257
- save(list);
281
+ save(list, patch.permissions !== undefined || patch.role !== undefined || patch.disabled !== undefined);
258
282
  return publicUser(user);
259
283
  }
260
284