agent-loft 0.2.30 → 0.2.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +11 -1
  2. package/package.json +1 -1
  3. package/src/agents/claude/driver.ts +13 -8
  4. package/src/agents/claude/session.ts +38 -6
  5. package/src/agents/codex/session.ts +32 -5
  6. package/src/channels/feishu/bot.ts +8 -4
  7. package/src/channels/feishu/turn-stream.ts +3 -2
  8. package/src/channels/web/api.ts +8 -0
  9. package/src/channels/web/http.ts +2 -2
  10. package/src/channels/web/server.ts +21 -1
  11. package/src/channels/web/skills-api.ts +225 -0
  12. package/src/channels/web/tasks-api.ts +94 -0
  13. package/src/core/chat-mode.ts +16 -16
  14. package/src/core/command-catalog.ts +8 -1
  15. package/src/core/commands.ts +3 -0
  16. package/src/core/hub.ts +147 -19
  17. package/src/core/memory-mcp.ts +1 -1
  18. package/src/core/personal.ts +5 -1
  19. package/src/core/skill-runtime.ts +359 -0
  20. package/src/core/skills-bridge.ts +288 -0
  21. package/src/core/skills.ts +675 -0
  22. package/src/core/store.ts +2 -0
  23. package/src/core/task-prompt.ts +38 -0
  24. package/src/core/task-runner.ts +232 -0
  25. package/src/core/task-schedule.ts +250 -0
  26. package/src/core/tasks-bridge.ts +256 -0
  27. package/src/core/tasks-mcp.ts +66 -0
  28. package/src/core/tasks.ts +281 -0
  29. package/src/core/types.ts +21 -0
  30. package/src/core/zip.ts +98 -0
  31. package/src/main.ts +12 -0
  32. package/src/mcp/tasks-server.ts +327 -0
  33. package/web/css/skills.css +368 -0
  34. package/web/css/tasks.css +455 -0
  35. package/web/index.html +2 -0
  36. package/web/lib/dom.js +1 -0
  37. package/web/lib/ws.js +8 -0
  38. package/web/state.js +2 -0
  39. package/web/views/composer.js +15 -3
  40. package/web/views/conv-actions.js +15 -7
  41. package/web/views/layout.js +22 -1
  42. package/web/views/mention.js +193 -0
  43. package/web/views/messages.js +23 -2
  44. package/web/views/sidebar.js +4 -0
  45. package/web/views/skills.js +703 -0
  46. package/web/views/tasks.js +469 -0
  47. package/web/views/topbar.js +9 -3
package/README.md CHANGED
@@ -58,6 +58,8 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
58
58
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
59
59
  - **聊天模式 / 工作模式**:右上角的「💬 聊天 / 🛠 工作」,或者发 `/chat`、`/work`,同一条对话随时切换、上下文接着。聊天模式换成精简的系统提示,只留联网搜索,不加载技能、MCP、插件,不执行命令、不读写本机文件(文本附件的内容直接放进消息),每轮的固定开销小得多:实测一句话 Claude 约 1.6 万 → 2 千 token,Codex 约 2 万 → 1.2 万(Codex 的基础指令改不了)。适合日常聊天、查资料;要动手干活时切回工作模式。切换后第一轮要重建提示缓存,会贵一些;在工作模式里读过的大段内容还留在历史里。
60
60
  - **记忆**:像 ChatGPT 的记忆,设置 → 记忆。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 4 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理聊天模式的/只整理工作模式的;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话;第一次用时会把已有对话收录进来)。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
61
+ - **定时任务**:像 ChatGPT 的 Tasks,侧栏「最近」上面的「定时任务」。到点把一段提示词交给 agent,结果发回对话:一次 / 每天 / 工作日 / 每周 / 每月 / 每隔几小时 / 自定义 cron,按服务端时区,两次至少隔 15 分钟。**有需要才提醒**(默认):agent 自己判断这次有没有要告诉你的事(比如「有新版本才告诉我」),没有就在回复第一行写 `[[静默]]`,推送、飞书都不发,对话里折叠成一行;没写暗号一律照常提醒。结果发到**专用对话**(任务自己的一条对话,第一次运行时新建、之后续用,可选聊天 / 工作模式和目录),或者**原来的对话**。也能直接在对话里说「每天早上 9 点帮我……」:agent 用 `create_task` / `update_task` / `delete_task` / `list_tasks` 工具管理,新建、修改、删除都会先弹授权卡让你确认(只有暂停不用;没有「总是允许」),任务自己运行的那一轮里不能再建、改、删任务。按人隔离:每人只看得到、改得了自己的任务(最多 30 个),删用户时一起删;到点再核对一次对话还是不是他的,对话被删或换了主人就暂停任务。到点对话在忙(正在回复或挂着授权)就等它,最多 30 分钟;服务停着时错过 2 小时以内的启动后补跑一次。工具和记忆一样只给有主人的对话,飞书群聊里没有。
62
+ - **技能(skills)**:侧栏「定时任务」下面的「技能」。技能就是 Claude Code / Codex 用的那种 SKILL.md(可以带脚本和资料),由 agent-loft 按人管理,两个 agent 都能用。**来源**:在页面上写、上传技能包(`.zip` / `.skill` / 单个 SKILL.md / 整个文件夹),或者在对话里让 agent「把刚才的做法存成技能」(agent 用 `create_skill` / `update_skill`,先弹授权卡)。**分享**:作者选谁看得到——仅自己 / 指定的人 / 所有人;看得到的人在「技能广场」里安装。装的是作者那一份本身,作者改了,装了的人下一条消息起就用上新的;作者取消分享或删掉,装了的人也就没了。管理员能下架别人分享出来的技能,看不到别人私有的。**使用**:工作模式下 agent 遇到对得上的事自己用;在输入框或定时任务的「要做的事」里打 `@` 选技能,点名这次用哪个(聊天模式下会把技能内容直接附上);飞书里发 `/skills` 看能 @ 哪些。**变量**:技能可以声明要用的环境变量(接口地址、密钥),每个人填自己的值,只注入自己的会话;密钥再写上「只允许发往」的地址就成了**受保护的密钥**——不进环境变量,agent 看不到值,只能用 `skill_request` 工具让 agent-loft 代发请求(在地址、请求头、请求体里写 `{{变量名}}`),只发往你确认过的地址、不跟随跳转、响应里出现的值会被抹掉;作者后来改了地址,要你再确认一次才放行。**机器上原有的技能**(`~/.claude/skills`、`~/.agents/skills`、插件市场和 claude.ai 同步的)只给管理员:成员的会话里看不到、调不了(Claude 用技能白名单,`/技能名` 也会被拦下;Codex 关掉它自己的技能清单),管理员在技能页的「本机技能」里能看到。
61
63
  - **飞书账号绑定**:设置 → 账号 → 飞书账号 →「生成绑定码」,再在飞书私聊机器人发 `/bind 绑定码`(10 分钟内有效,群里发不算)。绑定后这个私聊就是你的个人会话:用你的记忆,`/sessions` 只列你的会话,`/web` 只能接上你自己的 Web 会话,管理员在 Web 上也看不到它。必须本人在两边各操作一次,管理员不能替人绑定(只能解除),否则就能借飞书读到别人的记忆。
62
64
 
63
65
  ## 安装
@@ -128,7 +130,7 @@ agent-loft service install
128
130
 
129
131
  `aloft` 是 `agent-loft` 的简写。
130
132
 
131
- 聊天里的命令(飞书和 Web 通用;Web 输入框打 `/` 会弹出命令补全,飞书里打 `/` 会弹出机器人的指令面板(agent-loft 自动注册,约 5~8 分钟生效;只发一个 `/` 也会回一张可点击的命令卡片),顺序和显示项在 设置 → 命令 里调整):`/new` `/fork` `/sessions [all]` `/resume <id>` `/model [名称]` `/effort <程度>` `/agent [名称]`(或者直接发 `/claude`、`/codex`)`/stop` `/cd <目录>` `/pwd` `/status` `/autoedit [on|off]` `/approve <id> allow-once|allow-always|allow-session|deny` `/chat` `/work` `/help`;只在飞书里有的:`/web` `/detach` `/bind <绑定码>`
133
+ 聊天里的命令(飞书和 Web 通用;Web 输入框打 `/` 会弹出命令补全,飞书里打 `/` 会弹出机器人的指令面板(agent-loft 自动注册,约 5~8 分钟生效;只发一个 `/` 也会回一张可点击的命令卡片),顺序和显示项在 设置 → 命令 里调整):`/new` `/fork` `/sessions [all]` `/resume <id>` `/model [名称]` `/effort <程度>` `/agent [名称]`(或者直接发 `/claude`、`/codex`)`/stop` `/cd <目录>` `/pwd` `/status` `/autoedit [on|off]` `/approve <id> allow-once|allow-always|allow-session|deny` `/chat` `/work` `/skills` `/help`;只在飞书里有的:`/web` `/detach` `/bind <绑定码>`
132
134
 
133
135
  自定义命令:设置 → 命令 → 「添加命令」,填命令名、说明和一段提示词,之后发 `/命令名 参数` 就会把这段提示词发给 agent(提示词里的 `$ARGUMENTS` 换成参数,没写就把参数接在后面)。按 agent 分开存,可以编辑、删除,也会同步到飞书指令面板。
134
136
 
@@ -143,6 +145,7 @@ agent-loft service install
143
145
  - 暴露到公网时,只通过 HTTPS 反向代理(比如 Lucky)或 Cloudflare Tunnel 访问,并把不在本机的反代 IP 加进 `web.trustedProxies`(只有从这些地址来的连接才采信 `X-Forwarded-*`)。不要直接把 8800 端口映射出去。局域网访问可以在 设置 → 系统 → 网络访问 里关掉。
144
146
  - 审批超时一律按拒绝处理。Codex 默认沙箱为 `workspace-write`,不会因为 `~/.codex/config.toml` 里配了 `never` 或 `danger-full-access` 就绕过审批。
145
147
  - agent 子进程拿不到本服务自己的凭据(`FEISHU_*`、`AGENT_LOFT_*` 等环境变量会被剔除)。
148
+ - 技能存在 `data/skills/`:技能本体在 `files/<技能 id>/`,每个人装了哪些、变量的值在 `users/<用户 id>.json`(0600)。普通变量注入到会话环境里,agent 能读到;受保护的密钥 agent 看不到值,但和多用户一样不是安全边界——工作模式下 agent 能直接读这些文件。别人分享的技能会在你的会话里照着执行,装之前在技能页点开看一眼它要做什么、要哪些变量。
146
149
  - 记忆存在 `data/memory/<用户 id>.json`,聊天记录索引在 `data/history/<用户 id>.jsonl`。记给谁由 agent-loft 在拉起记忆工具时定死(工具参数里没有用户),模型想写别人的记忆也写不了;但和多用户一样不是安全边界:工作模式下 agent 能读到这些文件。聊天模式没有读写本机文件的工具,网页里的提示注入也骗不走本机文件。
147
150
 
148
151
  ## 结构
@@ -160,9 +163,16 @@ src/
160
163
  memory-curator.ts 录入聊天、回填已有对话、聊完后自动整理记忆
161
164
  feishu-links.ts 飞书账号 ↔ 用户的绑定和绑定码
162
165
  chat-mode.ts 聊天模式告诉 agent 的话(Claude 换系统提示,Codex 附在消息后面)
166
+ tasks.ts 定时任务的存储(按人隔离);task-schedule.ts 频率和 cron;task-prompt.ts 每次运行附给 agent 的说明和静默暗号
167
+ task-runner.ts 定时任务的调度:到点核对主人和对话、送进对话、记下结果
168
+ tasks-bridge.ts 定时任务工具在主进程这头:核对签名、弹授权卡、增删改(tasks-mcp.ts 定怎么拉起);技能工具也走这条通道
169
+ skills.ts 技能的存储:可见性、安装、停用、变量和受保护密钥确认过的地址;zip.ts 解技能包
170
+ skill-runtime.ts 技能怎么交给 agent:Claude 的插件目录和成员白名单、Codex 的清单、@ 技能、机器上原有的技能
171
+ skills-bridge.ts 技能工具在主进程这头:建 / 改技能(弹授权卡)、skill_request 代发带密钥的请求
163
172
  pairing.ts uploads.ts commands.ts …
164
173
  mcp/
165
174
  memory-server.ts 记忆工具(remember / forget / search_past_chats)的 stdio MCP 服务,两个 agent 共用
175
+ tasks-server.ts 定时任务工具的 stdio MCP 服务:只传话,经 unix socket 转给主进程;AGENT_LOFT_TOOLSET=skills 时是技能工具
166
176
  agents/
167
177
  claude/ Claude Agent SDK 驱动
168
178
  codex/ codex app-server 驱动
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.30",
3
+ "version": "0.2.32",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -13,6 +13,7 @@ import { agentEnvironment } from "../../core/agent-env.js";
13
13
  import os from "node:os";
14
14
  import type { AgentCommand } from "../../core/command-catalog.js";
15
15
  import { splitAttachmentNote } from "../../core/uploads.js";
16
+ import { stripContext } from "../../core/chat-mode.js";
16
17
  import { config } from "../../core/config.js";
17
18
  import type {
18
19
  AgentDriver,
@@ -30,7 +31,7 @@ import type {
30
31
  import { describeUsage, readUsage, toQuota } from "./account.js";
31
32
  import { cachedProbe, withProbe } from "./probe.js";
32
33
  import { diagnose } from "./errors.js";
33
- import { ClaudeSession, describeToolUse, summarize, toModelInfo } from "./session.js";
34
+ import { claudeBuiltins, ClaudeSession, describeToolUse, summarize, toModelInfo } from "./session.js";
34
35
 
35
36
  /** 模型列表几乎不变,缓存 10 分钟;读失败抛给设置页,让它退回手填 */
36
37
  const readCatalog = cachedProbe(10 * 60_000, "模型列表", () => withProbe(async (q) => toModelInfo(await q.supportedModels())));
@@ -51,11 +52,15 @@ function readCommands(cwd: string): Promise<AgentCommand[]> {
51
52
  () =>
52
53
  withProbe(
53
54
  async (q) =>
54
- (await q.supportedCommands()).map((c) => ({
55
- name: c.name,
56
- description: c.description,
57
- ...(c.argumentHint ? { args: c.argumentHint } : {}),
58
- })),
55
+ (await q.supportedCommands()).map((c) => {
56
+ if (c.builtin) claudeBuiltins.add(c.name);
57
+ return {
58
+ name: c.name,
59
+ description: c.description,
60
+ ...(c.argumentHint ? { args: c.argumentHint } : {}),
61
+ ...(c.builtin ? { builtin: true } : {}),
62
+ };
63
+ }),
59
64
  cwd,
60
65
  ),
61
66
  [] as AgentCommand[],
@@ -69,7 +74,7 @@ function readCommands(cwd: string): Promise<AgentCommand[]> {
69
74
  const SESSION_ID = /^[A-Za-z0-9_-]{8,64}$/;
70
75
 
71
76
  function titleOf(info: { customTitle?: string; summary?: string; firstPrompt?: string }): string {
72
- const raw = (info.customTitle || info.summary || info.firstPrompt || "").replace(/\s+/g, " ").trim();
77
+ const raw = stripContext(info.customTitle || info.summary || info.firstPrompt || "").replace(/\s+/g, " ").trim();
73
78
  if (!raw) return "(无标题)";
74
79
  return raw.length > 60 ? `${raw.slice(0, 60)}…` : raw;
75
80
  }
@@ -157,7 +162,7 @@ export class ClaudeDriver implements AgentDriver {
157
162
  const texts = blocks.filter((b) => b.type === "text" && b.text).map((b) => b.text!);
158
163
  if (texts.length === 0) continue; // 纯 tool_result
159
164
  // 我们自己拼进去的附件清单:从正文里拆出来,单独作为附件给前端展示
160
- const { text, attachments } = splitAttachmentNote(texts.join("\n"));
165
+ const { text, attachments } = splitAttachmentNote(stripContext(texts.join("\n")));
161
166
  if (!text && attachments.length === 0) continue;
162
167
  if (text.startsWith("<command-") || text.startsWith("<local-command")) continue;
163
168
  if (text.startsWith("<task-notification>")) {
@@ -16,6 +16,8 @@ import {
16
16
  import { agentEnvironment } from "../../core/agent-env.js";
17
17
  import { chatSystemPrompt } from "../../core/chat-mode.js";
18
18
  import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
19
+ import { SKILLS_MCP_NAME, skillsMcpSpawn, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
20
+ import { PLUGIN_NAME, projectCommandNames } from "../../core/skill-runtime.js";
19
21
  import { describeAttachments, inlineTextBlocks, readTextAttachments } from "../../core/uploads.js";
20
22
  import type {
21
23
  AgentEvents,
@@ -127,6 +129,15 @@ function buildContent(input: UserInput, chat: boolean): string | ContentBlock[]
127
129
 
128
130
  /** 记忆工具在 Claude 里的全名 */
129
131
  const MEMORY_TOOLS = new Set(["remember", "forget", "search_past_chats"].map((t) => `mcp__${MEMORY_MCP_NAME}__${t}`));
132
+ /** 定时任务工具:要用户确认的那几个由 agent-loft 自己弹卡(tasks-bridge.ts),这里不再问一遍 */
133
+ const TASK_TOOLS = new Set(["list_tasks", "create_task", "update_task", "delete_task"].map((t) => `mcp__${TASKS_MCP_NAME}__${t}`));
134
+ /** 技能工具:建、改技能前由 agent-loft 自己弹卡(skills-bridge.ts) */
135
+ const SKILL_TOOLS = new Set(["list_skills", "get_skill", "create_skill", "update_skill", "skill_request"].map((t) => `mcp__${SKILLS_MCP_NAME}__${t}`));
136
+ /**
137
+ * Claude Code 自带的命令和技能名(supportedCommands 里标了 builtin 的),driver 读命令表时顺手记下。
138
+ * 成员会话的技能白名单要带上它们;还没读到过就先不带(只少了 /simplify 这类自带技能)。
139
+ */
140
+ export const claudeBuiltins = new Set<string>();
130
141
  /** 聊天模式的全部工具:只能联网,碰不到本机 */
131
142
  const CHAT_TOOLS = ["WebSearch", "WebFetch"];
132
143
 
@@ -145,9 +156,17 @@ const CHAT_TOOLS = ["WebSearch", "WebFetch"];
145
156
  */
146
157
  export function modeOptions(opts: SessionOptions): Partial<Options> {
147
158
  const memory = opts.memory;
148
- const mcpServers: Record<string, McpServerConfig> = memory
149
- ? { [MEMORY_MCP_NAME]: { type: "stdio", ...memoryMcpSpawn(memory.userId, "claude", { search: !!memory.search, ...(memory.convKey ? { convKey: memory.convKey } : {}) }) } }
150
- : {};
159
+ const mcpServers: Record<string, McpServerConfig> = {
160
+ ...(memory
161
+ ? { [MEMORY_MCP_NAME]: { type: "stdio", ...memoryMcpSpawn(memory.userId, "claude", { search: !!memory.search, ...(memory.convKey ? { convKey: memory.convKey } : {}) }) } }
162
+ : {}),
163
+ ...(opts.tasks
164
+ ? {
165
+ [TASKS_MCP_NAME]: { type: "stdio", ...tasksMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "claude") },
166
+ [SKILLS_MCP_NAME]: { type: "stdio", ...skillsMcpSpawn(opts.tasks.userId, opts.tasks.convKey, "claude") },
167
+ }
168
+ : {}),
169
+ };
151
170
  if (opts.mode === "chat") {
152
171
  return {
153
172
  systemPrompt: { type: "custom", prompt: chatSystemPrompt("WebSearch(搜索)和 WebFetch(读网页)", memory?.prompt), snapshot: false },
@@ -162,13 +181,24 @@ export function modeOptions(opts: SessionOptions): Partial<Options> {
162
181
  const switched = opts.announceMode
163
182
  ? "这条对话刚从「聊天模式」切到「工作模式」:之前聊天模式下不能执行命令、不能读写文件的限制已经解除,现在可以正常干活。不用为之前说做不到而道歉。"
164
183
  : "";
165
- const append = [memory?.prompt, switched].filter(Boolean).join("\n\n");
184
+ const skills = opts.skills;
185
+ const append = [memory?.prompt, skills?.prompt, switched].filter(Boolean).join("\n\n");
166
186
  return {
167
187
  systemPrompt: { type: "preset", preset: "claude_code", ...(append ? { append } : {}), snapshot: false },
168
- ...(memory ? { mcpServers } : {}),
188
+ ...(Object.keys(mcpServers).length ? { mcpServers } : {}),
189
+ ...(skills?.pluginDir ? { plugins: [{ type: "local" as const, path: skills.pluginDir, skipMcpDiscovery: true }] } : {}),
190
+ ...(skills && !skills.admin ? { skills: memberSkillAllowlist(skills, opts.cwd) } : {}),
169
191
  };
170
192
  }
171
193
 
194
+ /**
195
+ * 成员会话能用的技能:agent-loft 里启用的、Claude Code 自带的、项目目录里的。机器上另外装的
196
+ * (~/.claude/skills、插件市场、claude.ai 同步的)不在里面:模型看不到,Skill 工具也调不了。
197
+ */
198
+ function memberSkillAllowlist(skills: NonNullable<SessionOptions["skills"]>, cwd: string): string[] {
199
+ return [...new Set([...skills.list.map((s) => `${PLUGIN_NAME}:${s.name}`), ...claudeBuiltins, ...projectCommandNames(cwd)])];
200
+ }
201
+
172
202
  export class ClaudeSession implements AgentSession {
173
203
  private queue = new AsyncQueue<SDKUserMessage>();
174
204
  private q: Query | null = null;
@@ -222,7 +252,8 @@ export class ClaudeSession implements AgentSession {
222
252
  prompt: input.stream(),
223
253
  options: {
224
254
  cwd: this.opts.cwd,
225
- env: agentEnvironment(),
255
+ // 技能变量只在工作模式注入:聊天模式没有执行命令的工具,用不上
256
+ env: { ...agentEnvironment(), ...(this.opts.mode === "chat" ? {} : (this.opts.skills?.env ?? {})) },
226
257
  // 只能是 default 或 acceptEdits:bypassPermissions 会让 canUseTool 变成死代码。
227
258
  // acceptEdits 只放行工作目录(含附件目录)内的改文件,其它照样走 canUseTool
228
259
  permissionMode: this.opts.autoEdit ? "acceptEdits" : "default",
@@ -351,6 +382,7 @@ export class ClaudeSession implements AgentSession {
351
382
  // 自家的记忆工具,以及聊天模式下的联网工具:不问。
352
383
  // 不用 allowedTools 放行 —— SDK 会对每个会话打一条「canUseTool 被绕过」的警告
353
384
  if (MEMORY_TOOLS.has(toolName) && this.opts.memory) return { behavior: "allow", updatedInput: input };
385
+ if ((TASK_TOOLS.has(toolName) || SKILL_TOOLS.has(toolName)) && this.opts.tasks) return { behavior: "allow", updatedInput: input };
354
386
  if (this.opts.mode === "chat" && CHAT_TOOLS.includes(toolName)) return { behavior: "allow", updatedInput: input };
355
387
 
356
388
  // 提问不是授权:它问的是「你选哪个」
@@ -7,6 +7,8 @@ import { refusalFor, UnsupportedRequest } from "./refusals.js";
7
7
  import { config } from "../../core/config.js";
8
8
  import { contextBlock } from "../../core/chat-mode.js";
9
9
  import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
10
+ import { SKILLS_MCP_NAME, skillsMcpSpawn, TASK_TOOL_TIMEOUT_SEC, TASKS_MCP_NAME, tasksMcpSpawn } from "../../core/tasks-mcp.js";
11
+ import { codexSkillLines } from "../../core/skill-runtime.js";
10
12
  import { describeAttachments, inlineTextBlocks, readTextAttachments } from "../../core/uploads.js";
11
13
  import type {
12
14
  AgentEvents,
@@ -130,7 +132,7 @@ export async function userMcpServers(): Promise<string[]> {
130
132
  if (userMcpCache && Date.now() - userMcpCache.at < 60_000) return userMcpCache.names;
131
133
  try {
132
134
  const res = await appServer.call<{ config?: { mcp_servers?: Record<string, unknown> | null } }>("config/read", {});
133
- const names = Object.keys(res.config?.mcp_servers ?? {}).filter((n) => n !== MEMORY_MCP_NAME);
135
+ const names = Object.keys(res.config?.mcp_servers ?? {}).filter((n) => n !== MEMORY_MCP_NAME && n !== TASKS_MCP_NAME && n !== SKILLS_MCP_NAME);
134
136
  userMcpCache = { names, at: Date.now() };
135
137
  return names;
136
138
  } catch (err) {
@@ -363,12 +365,37 @@ export class CodexSession implements AgentSession {
363
365
  */
364
366
  private async modeParams(minimal = false): Promise<Record<string, unknown>> {
365
367
  const memory = this.opts.memory;
366
- const mcp = memory ? { [`mcp_servers.${MEMORY_MCP_NAME}`]: memoryMcpSpawn(memory.userId, "codex", { search: !!memory.search, ...(memory.convKey ? { convKey: memory.convKey } : {}) }) } : {};
368
+ const tasks = this.opts.tasks;
369
+ const mcp = {
370
+ ...(memory ? { [`mcp_servers.${MEMORY_MCP_NAME}`]: memoryMcpSpawn(memory.userId, "codex", { search: !!memory.search, ...(memory.convKey ? { convKey: memory.convKey } : {}) }) } : {}),
371
+ // 新建 / 修改任务要等用户点授权卡,Codex 默认 60 秒就算工具超时
372
+ ...(tasks
373
+ ? {
374
+ [`mcp_servers.${TASKS_MCP_NAME}`]: { ...tasksMcpSpawn(tasks.userId, tasks.convKey, "codex"), tool_timeout_sec: TASK_TOOL_TIMEOUT_SEC },
375
+ [`mcp_servers.${SKILLS_MCP_NAME}`]: { ...skillsMcpSpawn(tasks.userId, tasks.convKey, "codex"), tool_timeout_sec: TASK_TOOL_TIMEOUT_SEC },
376
+ }
377
+ : {}),
378
+ };
367
379
  if (this.chat && !minimal) {
368
380
  const off = Object.fromEntries((await userMcpServers()).map((n) => [`mcp_servers.${n}.enabled`, false]));
369
381
  return { config: { ...CHAT_CONFIG, ...off, ...mcp } };
370
382
  }
371
- return memory ? { config: mcp } : {};
383
+ const work = { ...mcp, ...(minimal ? {} : this.skillConfig()) };
384
+ return Object.keys(work).length ? { config: work } : {};
385
+ }
386
+
387
+ /**
388
+ * 工作模式的技能设置:变量逐个写进 shell_environment_policy.set(只作用于这个 thread 里跑的命令,
389
+ * 一个个键写不会冲掉用户 config.toml 里本来设的);成员关掉 Codex 自己的技能清单 ——
390
+ * 那里面是机器上装的技能,只给管理员。成员的技能走 contextBlock 里的清单。
391
+ */
392
+ private skillConfig(): Record<string, unknown> {
393
+ const skills = this.opts.skills;
394
+ if (!skills) return {};
395
+ return {
396
+ ...Object.fromEntries(Object.entries(skills.env).map(([k, v]) => [`shell_environment_policy.set.${k}`, v])),
397
+ ...(skills.admin ? {} : { "skills.include_instructions": false, "features.skill_search": false }),
398
+ };
372
399
  }
373
400
 
374
401
  /**
@@ -379,7 +406,7 @@ export class CodexSession implements AgentSession {
379
406
  private contextSent = false;
380
407
 
381
408
  private get contextPending(): boolean {
382
- return !this.contextSent && (this.chat || !!this.opts.memory || !!this.opts.announceMode);
409
+ return !this.contextSent && (this.chat || !!this.opts.memory || !!this.opts.announceMode || codexSkillLines(this.opts.skills).length > 0);
383
410
  }
384
411
 
385
412
  private async openOnce(): Promise<string> {
@@ -497,7 +524,7 @@ export class CodexSession implements AgentSession {
497
524
  const note = input.attachments.length ? describeAttachments(input.attachments, inlined, chat) : "";
498
525
  const texts = chat ? inlineTextBlocks(input.attachments, textMap) : "";
499
526
  // 放在最后:Codex 拿第一条消息的开头当会话预览,不能被这段背景占掉
500
- const context = this.contextPending ? contextBlock(chat ? "chat" : "work", this.opts.memory?.prompt, "联网搜索") : "";
527
+ const context = this.contextPending ? contextBlock(chat ? "chat" : "work", this.opts.memory?.prompt, "联网搜索", codexSkillLines(this.opts.skills)) : "";
501
528
  const text = [input.text, note, texts, context].filter(Boolean).join("\n\n");
502
529
  const images = input.attachments.filter((a) => a.kind === "image").map((a) => a.path);
503
530
  let startedOn: string | undefined;
@@ -492,22 +492,26 @@ export class FeishuBot {
492
492
  // 别处(Web、别的飞书聊天)说的话,同步一句过来,不然这边看着没头没尾
493
493
  const o = ev.origin;
494
494
  const here = o.channel === "feishu" && o.channelId === this.cfg.id && (!o.chatId || o.chatId === chatId);
495
- if (!here) {
495
+ // 定时任务的提示词不同步过来:每次运行都发一条,飞书里就全是它了。结果出来时再带上任务名
496
+ if (!here && o.channel !== "task") {
496
497
  const files = ev.attachments.length ? `\n\n📎 ${ev.attachments.join("、")}` : "";
497
498
  const icon = o.channel === "web" ? "💻" : "💬";
498
499
  void this.client.sendCard(chatId, replyCard(`${icon} **${o.name ?? "Web"}**:${ev.text}${files}`));
499
500
  }
500
501
  return;
501
502
  }
503
+ // 定时任务这一轮不画过程卡:跑完之前不知道要不要提醒,卡片一发出去飞书就响了
502
504
  case "step":
503
- this.stream(key, chatId).addStep(ev.text);
505
+ if (!hub.currentTaskTurn(key)) this.stream(key, chatId).addStep(ev.text);
504
506
  return;
505
507
  case "text":
506
- this.stream(key, chatId).addText(ev.text);
508
+ if (!hub.currentTaskTurn(key)) this.stream(key, chatId).addText(ev.text);
507
509
  return;
508
510
  case "result": {
509
511
  const stream = this.stream(key, chatId);
510
- stream.finish(ev.text, ev.footer);
512
+ if (ev.silent) stream.finish("", ev.footer, true);
513
+ else if (ev.task) stream.finish(`⏰ **${ev.task.title}**\n\n${ev.text}`, ev.footer);
514
+ else stream.finish(ev.text, ev.footer);
511
515
  void stream.drain().then(() => this.clearTyping(key));
512
516
  return;
513
517
  }
@@ -69,8 +69,9 @@ export class TurnStream {
69
69
  /**
70
70
  * 收尾:过程卡定格为完成态,然后把最终回复作为普通消息发出去。
71
71
  * 整轮没有过程时不会留下任何卡片 —— 简单问答就该只有一条回复。
72
+ * quiet:不发回复(定时任务判断这次不用提醒),只把过程卡定格。
72
73
  */
73
- finish(finalText: string, footer?: string): void {
74
+ finish(finalText: string, footer?: string, quiet = false): void {
74
75
  this.enqueue(async () => {
75
76
  if (this.messageId) {
76
77
  await this.deps.updateCard(
@@ -79,7 +80,7 @@ export class TurnStream {
79
80
  );
80
81
  }
81
82
  const reply = finalText.trim() || this.text.trim();
82
- if (reply) await this.deps.sendReply(reply);
83
+ if (reply && !quiet) await this.deps.sendReply(reply);
83
84
  this.reset();
84
85
  });
85
86
  }
@@ -62,6 +62,8 @@ import {
62
62
  } from "./auth.js";
63
63
  import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
64
64
  import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
65
+ import { handleTasksApi } from "./tasks-api.js";
66
+ import { handleSkillsApi } from "./skills-api.js";
65
67
  import { addSubscription, listSubscriptions, pushToAll, removeSubscription, removeSubscriptionsOf, vapidPublicKey } from "./push.js";
66
68
 
67
69
  export const COOKIE = "aim_session";
@@ -524,6 +526,10 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
524
526
  return;
525
527
  }
526
528
 
529
+ // ----- 定时任务 -----
530
+ if (p.startsWith("/api/tasks") && (await handleTasksApi(req, res, p, user))) return;
531
+ if (p.startsWith("/api/skills") && (await handleSkillsApi(req, res, url, user))) return;
532
+
527
533
  // ----- 目录选择器:列工作区内的子目录 -----
528
534
  if (p === "/api/dirs" && method === "GET") {
529
535
  const listing = listWorkspaceDirs(url.searchParams.get("path") ?? "");
@@ -840,6 +846,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
840
846
  allowedAgents: hub.enabledAgents().map((d) => d.id),
841
847
  // 带 key 是输入框补全:只列 Web 能用的;不带是设置页排序,全列
842
848
  ...(conv ? { channel: "web" } : {}),
849
+ // 成员看不到机器上装的技能
850
+ ...(admin ? {} : { member: true }),
843
851
  });
844
852
  sendJson(res, 200, { commands });
845
853
  return;
@@ -89,8 +89,8 @@ export async function readBody(req: IncomingMessage, limit: number): Promise<Buf
89
89
  return Buffer.concat(chunks);
90
90
  }
91
91
 
92
- export async function readJsonBody<T = Record<string, unknown>>(req: IncomingMessage): Promise<T> {
93
- const raw = await readBody(req, 1024 * 1024);
92
+ export async function readJsonBody<T = Record<string, unknown>>(req: IncomingMessage, limit = 1024 * 1024): Promise<T> {
93
+ const raw = await readBody(req, limit);
94
94
  if (raw.length === 0) return {} as T;
95
95
  try {
96
96
  return JSON.parse(raw.toString("utf8")) as T;
@@ -13,6 +13,8 @@ import { parseCommand } from "../../core/commands.js";
13
13
  import { GLOBAL_ALWAYS_DENIED, hub, type EventEnvelope } from "../../core/hub.js";
14
14
  import { interactions, type Interaction } from "../../core/interactions.js";
15
15
  import { getConversation } from "../../core/store.js";
16
+ import { taskEvents } from "../../core/tasks.js";
17
+ import { skillEvents } from "../../core/skills.js";
16
18
  import { RUNNING_VERSION } from "../../core/upgrade.js";
17
19
  import type { Settlement } from "../../core/types.js";
18
20
  import { getUser, isAdmin, legacyOwnerId, type User } from "../../core/users.js";
@@ -180,6 +182,16 @@ function broadcastInteraction(i: Interaction): void {
180
182
  for (const client of clients) if (canSeeKey(client.user, i.convKey)) send(client, { t: "ix", interaction: i });
181
183
  }
182
184
 
185
+ /** 某人的定时任务变了(增删改、跑完一次):只告诉他自己开着的页面,页面自己去重新拉 */
186
+ function broadcastTasks(owner: string): void {
187
+ for (const client of clients) if (client.user.id === owner) send(client, { t: "tasks" });
188
+ }
189
+
190
+ /** 技能变了:技能广场谁都可能在看,通知所有人重新拉(列表很小) */
191
+ function broadcastSkills(): void {
192
+ for (const client of clients) send(client, { t: "skills" });
193
+ }
194
+
183
195
  // ---------- 系统通知(Web Push) ----------
184
196
 
185
197
  /** 有页面正在前台看着这条会话:人就在眼前,不用推 */
@@ -235,10 +247,14 @@ function pushEvent(env: EventEnvelope): void {
235
247
  const ev = env.ev;
236
248
  if (ev.type !== "result" && ev.type !== "error") return;
237
249
  if (!isWebConv(env.key)) return;
250
+ // 定时任务这次判断不用提醒
251
+ if (ev.type === "result" && ev.silent) return;
238
252
  const name = convName(env.key);
239
253
  const payload =
240
254
  ev.type === "result"
241
- ? { title: `${name} · 回复完成`, body: plainPreview(ev.text) || "(没有文字回复)" }
255
+ ? ev.task
256
+ ? { title: `⏰ ${ev.task.title}`, body: plainPreview(ev.text) || "(没有文字回复)" }
257
+ : { title: `${name} · 回复完成`, body: plainPreview(ev.text) || "(没有文字回复)" }
242
258
  : { title: `${name} · 出错了`, body: plainPreview(ev.message) };
243
259
  notify(env.key, { ...payload, tag: `reply:${env.key}` });
244
260
  }
@@ -474,6 +490,8 @@ export async function startWeb(): Promise<void> {
474
490
  interactions.on("created", pushInteraction);
475
491
  interactions.on("updated", broadcastInteraction);
476
492
  interactions.on("settled", broadcastInteraction);
493
+ taskEvents.on("changed", broadcastTasks);
494
+ skillEvents.on("changed", broadcastSkills);
477
495
 
478
496
  await listen(server, host, port);
479
497
  console.log(`[web] 已监听 http://${host}:${port}`);
@@ -503,6 +521,8 @@ export async function stopWeb(): Promise<void> {
503
521
  interactions.off("created", pushInteraction);
504
522
  interactions.off("updated", broadcastInteraction);
505
523
  interactions.off("settled", broadcastInteraction);
524
+ taskEvents.off("changed", broadcastTasks);
525
+ skillEvents.off("changed", broadcastSkills);
506
526
  if (heartbeat) clearInterval(heartbeat);
507
527
  for (const client of clients) client.ws.close(1001, "服务重启");
508
528
  clients.clear();