agent-loft 0.2.32 → 0.2.34

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
@@ -49,17 +49,22 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
49
49
  - 滚动和 ChatGPT 一样:发出的问题顶到最上面、下面留白,回复长到屏幕底部才跟着往下滚;回复过程中自己滚动了就不再自动滚,下次发消息再恢复。
50
50
  - 定时发送:右上角「更多」→「定时发送」,默认排在 5 小时额度重置后 5 分钟(弹窗里提示 5 小时 / 7 天额度的重置时间),由服务端到点发出,关掉页面也会发。适合额度用完、要等刷新才能接着干活的时候。
51
51
  - 侧栏分「最近」和「项目」两组:Web 会话按工作目录归类(目录可以拖动排序,右键可置顶),飞书机器人各占一行(右键看历史会话);分叉出来的会话用虚线挂在原会话下面;会话标题由 agent 自动生成,双击重命名。
52
- - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置)。
52
+ - 回复过程中接着发的消息排队,标着「排队中」,上一条回复完自动接着处理;点「打断并发送」停掉正在进行的回复、马上处理这条;点停止则连排着的一起取消(标「没有发出」)。
53
+ - 太长的消息先收起,点「展开显示」看全文;对话里有 3 条以上消息时,右边有一列快速定位,鼠标移上去列出每条消息的开头,点一下跳过去。
54
+ - 侧栏按页加载:「最近」先显示 10 条、每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
55
+ - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
56
+ - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。在桌面端里,这个菜单并进桌面端顶栏的「更多」,排在最上面。
57
+ - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
53
58
  - 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
54
59
  - **系统通知**:Web 会话回复完成、出错、需要授权或提问时推送到手机 / 电脑(设置 → 通知 → 「在此设备开启通知」,可以发测试通知)。飞书会话由飞书提醒,正在前台看着的会话不推。需要 HTTPS 访问,iPhone 需 iOS 16.4+ 且从主屏幕图标打开。
55
60
  - **跨渠道同步**:飞书里的会话在 Web 上也能打开接着聊。同一个授权请求同时出现在飞书卡片和网页上,哪边先点算哪边,另一边自动变成「已处理」。
56
61
  - **授权**:允许一次 / 本会话全部允许 / 总是允许(按钮上写明放行范围)/ 拒绝。`/autoedit on` 让 Claude Code 在这条会话里改工作目录内的文件不再询问(Bash 仍询问)。超时一律按拒绝处理。
57
62
  - **设置都在网页上**:工作目录、会话闲置过期时间、局域网访问和端口、各 agent 的默认模型和思考程度、可选模型、Codex 沙箱、飞书机器人、配对批准、Claude 的「总是允许」名单、通知设备、登录设备管理、用户管理、服务端升级。
58
63
  - **多用户**(信任型):管理员在 设置 → 用户 里给别人建账号。每个人只看得到自己的对话、授权和通知,设置只有管理员能改,见下面「安全」。
59
- - **聊天模式 / 工作模式**:右上角的「💬 聊天 / 🛠 工作」,或者发 `/chat`、`/work`,同一条对话随时切换、上下文接着。聊天模式换成精简的系统提示,只留联网搜索,不加载技能、MCP、插件,不执行命令、不读写本机文件(文本附件的内容直接放进消息),每轮的固定开销小得多:实测一句话 Claude 约 1.6 万 → 2 千 token,Codex 约 2 万 → 1.2 万(Codex 的基础指令改不了)。适合日常聊天、查资料;要动手干活时切回工作模式。切换后第一轮要重建提示缓存,会贵一些;在工作模式里读过的大段内容还留在历史里。
64
+ - **聊天模式 / 工作模式**:右上角「更多」里的「聊天模式」,或者发 `/chat`、`/work`,同一条对话随时切换、上下文接着。聊天模式换成精简的系统提示,只留联网搜索,不加载技能、MCP、插件,不执行命令、不读写本机文件(文本附件的内容直接放进消息),每轮的固定开销小得多:实测一句话 Claude 约 1.6 万 → 2 千 token,Codex 约 2 万 → 1.2 万(Codex 的基础指令改不了)。适合日常聊天、查资料;要动手干活时切回工作模式。切换后第一轮要重建提示缓存,会贵一些;在工作模式里读过的大段内容还留在历史里。
60
65
  - **记忆**:像 ChatGPT 的记忆,设置 → 记忆。「关于我」加上一条条记住的事,每次对话都带上;agent 在聊天里遇到长期有用的信息会自己用 `remember` 记一条(回复里会说),记错了用 `forget` 删。**自动整理**:把上次整理之后新说的话交给模型(不留会话记录的一次性调用),补充、更新或删掉过时的记忆,用户自己加的条目它不动。什么时候整理每个人自己定:每天一次(默认凌晨 4 点,把当天的对话合起来一次整理,最省)/每段对话聊完后(停多久可选,改了什么会在对话里说一声)/只在点「现在整理」时/不整理;整理哪些对话也能选:全部/只整理聊天模式的/只整理工作模式的;用哪个 agent 的哪个模型也能选,默认 Claude Haiku,没有 Claude 就用 Codex 的默认模型、思考程度 low。**参考以前的聊天**:agent 遇到「上次说的那个……」会用 `search_past_chats` 搜你以前的对话(关键词搜索,只有你自己的、没被删掉的对话;第一次用时会把已有对话收录进来)。两项都能在设置里单独关。每个用户一份,Claude 和 Codex、Web 和飞书共用。只用在有主人的对话里:你的 Web 对话,以及绑定了飞书账号后和机器人的私聊;飞书群聊不用。别人(包括管理员)看不到你的记忆,管理员只能清空它;删用户时记忆一起删,不转给管理员。
61
66
  - **定时任务**:像 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 关掉它自己的技能清单),管理员在技能页的「本机技能」里能看到。
67
+ - **技能(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 关掉它自己的技能清单),管理员在「设置 → 技能 → 本机技能」里能看到。
63
68
  - **飞书账号绑定**:设置 → 账号 → 飞书账号 →「生成绑定码」,再在飞书私聊机器人发 `/bind 绑定码`(10 分钟内有效,群里发不算)。绑定后这个私聊就是你的个人会话:用你的记忆,`/sessions` 只列你的会话,`/web` 只能接上你自己的 Web 会话,管理员在 Web 上也看不到它。必须本人在两边各操作一次,管理员不能替人绑定(只能解除),否则就能借飞书读到别人的记忆。
64
69
 
65
70
  ## 安装
@@ -90,6 +95,7 @@ agent-loft service install # 注册为开机自启服务(systemd / laun
90
95
 
91
96
  - 同时连多台服务器,顶部标签栏切换、拖动排序;每台各自登录,切走了也在后台连着,回复完成、需要授权时弹系统通知,程序坞图标显示未读数。
92
97
  - 菜单栏图标:悬停看各服务器的 Claude / Codex 额度、待处理和运行中的会话;双击打开主窗口。同一个账号的额度只查一次。(Windows 上点托盘图标弹出;Linux 上在托盘菜单里点「额度和待处理」。)
98
+ - 菜单栏图标可以换成 5 小时额度读数(像「17% Claude | 76% Codex」):桌面端设置 →「菜单栏显示 5 小时额度」,选所有服务器合起来(取最高),或者按服务器分别选 Claude / Codex(小字带服务器名);都不选就只显示图标。只有 macOS 有,Windows / Linux 的托盘图标放不下字。
93
99
  - 支持前面挡着 Cloudflare Access 的服务器:验证页直接在窗口里完成,过期会提醒;也可以配 Service Token 免验证。
94
100
  - 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew 装)并开机自启,装好自动连上。Linux 上一样(需要先装好 Node.js 22+,开机自启用 systemd 用户服务);Windows 上服务端还没有开机自启,可以在 WSL 里装,桌面端会自动检测到 `127.0.0.1` 上的它。可选开启「本机有会话在跑时不休眠」。
95
101
  - 设置(`⌘,`)的服务器列表里展开某台服务器,能看它的 Agent 环境和版本,有新版本时点「升级服务端」;桌面端自己的更新在同一页的「更新」里点「更新并重启」。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.32",
3
+ "version": "0.2.34",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -23,6 +23,7 @@ import type {
23
23
  HistoryMessage,
24
24
  InteractionHost,
25
25
  ModelInfo,
26
+ QuestionSpec,
26
27
  QuotaInfo,
27
28
  RuntimeInfo,
28
29
  SessionOptions,
@@ -32,6 +33,7 @@ import { describeUsage, readUsage, toQuota } from "./account.js";
32
33
  import { cachedProbe, withProbe } from "./probe.js";
33
34
  import { diagnose } from "./errors.js";
34
35
  import { claudeBuiltins, ClaudeSession, describeToolUse, summarize, toModelInfo } from "./session.js";
36
+ import { parseQuestions } from "./permissions.js";
35
37
 
36
38
  /** 模型列表几乎不变,缓存 10 分钟;读失败抛给设置页,让它退回手填 */
37
39
  const readCatalog = cachedProbe(10 * 60_000, "模型列表", () => withProbe(async (q) => toModelInfo(await q.supportedModels())));
@@ -79,7 +81,55 @@ function titleOf(info: { customTitle?: string; summary?: string; firstPrompt?: s
79
81
  return raw.length > 60 ? `${raw.slice(0, 60)}…` : raw;
80
82
  }
81
83
 
82
- type Block = { type?: string; text?: string; name?: string; input?: unknown; thinking?: string };
84
+ type Block = {
85
+ type?: string;
86
+ text?: string;
87
+ name?: string;
88
+ input?: unknown;
89
+ thinking?: string;
90
+ id?: string;
91
+ tool_use_id?: string;
92
+ content?: unknown;
93
+ is_error?: boolean;
94
+ };
95
+
96
+ /** tool_result 的内容:字符串,或者一组 text 块 */
97
+ function resultText(content: unknown): string {
98
+ if (typeof content === "string") return content;
99
+ if (!Array.isArray(content)) return "";
100
+ return content.map((b) => (typeof b?.text === "string" ? b.text : "")).join("");
101
+ }
102
+
103
+ /**
104
+ * 从 AskUserQuestion 的工具结果里取回答。Claude Code 写的是
105
+ * Your questions have been answered: "问题1"="答案1", "问题2"="答案2". You can now continue…
106
+ * 问题原文已知(工具参数里有),按顺序切开,答案里有引号、逗号也不怕。多选的答案是「a, b」
107
+ */
108
+ export function parseQuestionAnswers(text: string, questions: QuestionSpec[]): { selections: number[][]; freeText: Record<number, string> } | null {
109
+ const body = text.replace(/^[\s\S]*?answered:\s*/, "").replace(/\.\s*You can now continue[\s\S]*$/, "");
110
+ const selections: number[][] = questions.map(() => []);
111
+ const freeText: Record<number, string> = {};
112
+ let found = false;
113
+ questions.forEach((q, i) => {
114
+ const head = `"${q.question}"="`;
115
+ const start = body.indexOf(head);
116
+ if (start < 0) return;
117
+ const from = start + head.length;
118
+ const nextQ = questions[i + 1];
119
+ const next = nextQ ? body.indexOf(`", "${nextQ.question}"="`, from) : -1;
120
+ const answer = body.slice(from, next >= 0 ? next : body.lastIndexOf('"')).trim();
121
+ if (!answer) return;
122
+ found = true;
123
+ const index = (label: string) => q.options.findIndex((o) => o.label === label);
124
+ // 整句就是一个选项(选项文字里本身带逗号)→ 按「, 」拆开都是选项(多选)→ 都不是就是自由作答
125
+ const whole = index(answer);
126
+ const parts = answer.split(", ").map(index);
127
+ if (whole >= 0) selections[i] = [whole];
128
+ else if (parts.every((n) => n >= 0)) selections[i] = parts;
129
+ else freeText[i] = answer;
130
+ });
131
+ return found ? { selections, freeText } : null;
132
+ }
83
133
 
84
134
  function blocksOf(message: unknown): Block[] {
85
135
  const content = (message as { content?: unknown } | null)?.content;
@@ -135,6 +185,8 @@ export class ClaudeDriver implements AgentDriver {
135
185
  * 把会话记录整理成「一问一答」:用户一条,助手把这一轮所有文本拼成一条,
136
186
  * 中间的工具调用作为过程摘要挂在助手那条上。工具结果(type=user 的 tool_result)
137
187
  * 和子 agent 的消息不算对话。
188
+ * 例外是 AskUserQuestion:在那里把这一轮切开,中间放一条 question(问了什么、你怎么答的),
189
+ * 和实时看到的一样;还没答的不放(它还挂着,页面从待处理里拿)。
138
190
  */
139
191
  async readHistory(id: string, cwd: string): Promise<HistoryMessage[]> {
140
192
  if (!SESSION_ID.test(id)) return [];
@@ -145,12 +197,22 @@ export class ClaudeDriver implements AgentDriver {
145
197
  if (assistant && (assistant.text.trim() || assistant.steps?.length)) out.push(assistant);
146
198
  assistant = null;
147
199
  };
200
+ /** 问了、还没对上回答的:tool_use id → 那条 question */
201
+ const asked = new Map<string, HistoryMessage>();
148
202
  for (const msg of raw) {
149
203
  if (msg.parent_tool_use_id) continue;
150
204
  const blocks = blocksOf(msg.message);
151
205
  // 运行时带着 timestamp(ISO 字符串),类型声明里没有
152
206
  const ts = Date.parse((msg as { timestamp?: string }).timestamp ?? "");
153
207
  if (msg.type === "user") {
208
+ for (const b of blocks) {
209
+ const q = b.type === "tool_result" && b.tool_use_id ? asked.get(b.tool_use_id) : undefined;
210
+ if (!q?.question) continue;
211
+ asked.delete(b.tool_use_id!);
212
+ const answers = b.is_error ? null : parseQuestionAnswers(resultText(b.content), q.question.questions);
213
+ if (answers) Object.assign(q.question, answers);
214
+ else q.question.skipped = true;
215
+ }
154
216
  // Claude Code 自己塞进记录的「用户消息」不是人发的:后台命令跑完的 <task-notification> 等,
155
217
  // 记录里 origin.kind 不是 human。老记录可能没有 origin,再按正文开头兜底
156
218
  const origin = (msg as { origin?: { kind?: string } }).origin;
@@ -184,6 +246,21 @@ export class ClaudeDriver implements AgentDriver {
184
246
  for (const b of blocks) {
185
247
  if (b.type === "text" && b.text?.trim()) {
186
248
  assistant.text += (assistant.text ? "\n\n" : "") + b.text;
249
+ } else if (b.type === "tool_use" && b.name === "AskUserQuestion" && b.id) {
250
+ const questions = parseQuestions((b.input ?? {}) as Record<string, unknown>);
251
+ if (!questions) continue;
252
+ // 前半段封口,提问卡放中间,之后的输出另起一条
253
+ assistant.segment = true;
254
+ flush();
255
+ const q: HistoryMessage = {
256
+ role: "question",
257
+ text: "",
258
+ question: { id: `hist:${b.id}`, title: "Claude 想确认一下", questions, selections: questions.map(() => []), freeText: {} },
259
+ ...(Number.isFinite(ts) ? { ts } : {}),
260
+ };
261
+ asked.set(b.id, q);
262
+ out.push(q);
263
+ assistant = { role: "assistant", text: "", steps: [] };
187
264
  } else if (b.type === "tool_use" && b.name) {
188
265
  assistant.steps!.push(`🔧 ${describeToolUse(b.name, b.input)}`);
189
266
  } else if (b.type === "thinking" && b.thinking) {
@@ -194,7 +271,8 @@ export class ClaudeDriver implements AgentDriver {
194
271
  }
195
272
  }
196
273
  flush();
197
- return out;
274
+ // 还没答的提问不放:它还挂着,页面从待处理里拿;进程挂了没答上的,也就不显示了
275
+ return out.filter((m) => m.role !== "question" || !asked.has(m.question!.id.slice(5)));
198
276
  }
199
277
 
200
278
  async forkAt(id: string, cwd: string, anchor?: string): Promise<string> {
@@ -7,6 +7,7 @@ import fs from "node:fs";
7
7
  import {
8
8
  query,
9
9
  type McpServerConfig,
10
+ type ModelUsage,
10
11
  type Options,
11
12
  type PermissionResult,
12
13
  type Query,
@@ -26,7 +27,9 @@ import type {
26
27
  ModelInfo,
27
28
  RuntimeInfo,
28
29
  SavedAttachment,
30
+ InterruptOptions,
29
31
  SessionOptions,
32
+ TokenUsage,
30
33
  UserInput,
31
34
  } from "../../core/types.js";
32
35
  import {
@@ -226,12 +229,19 @@ export class ClaudeSession implements AgentSession {
226
229
  * 恢复历史、进程重启),就重新逐条询问。
227
230
  */
228
231
  private allowAll = false;
232
+ /**
233
+ * 上一轮结束时的累计费用。result 里的 total_cost_usd 是这个会话到目前的累计值,这一轮的 = 差值。
234
+ * 恢复 / 分叉来的会话第一轮不知道之前累计了多少,这一轮先不报费用
235
+ */
236
+ private costSoFar: number | undefined;
229
237
 
230
238
  constructor(
231
239
  private readonly opts: SessionOptions,
232
240
  private readonly events: AgentEvents,
233
241
  private readonly host: InteractionHost,
234
- ) {}
242
+ ) {
243
+ this.costSoFar = opts.resumeId ? undefined : 0;
244
+ }
235
245
 
236
246
  get sessionId(): string | undefined {
237
247
  return this.currentId;
@@ -336,10 +346,12 @@ export class ClaudeSession implements AgentSession {
336
346
  }
337
347
 
338
348
  if (message.type === "result") {
349
+ const costUsd = this.turnCost(message.total_cost_usd);
350
+ this.reportUsage(message.modelUsage);
339
351
  if (message.subtype === "success") {
340
352
  this.events.onResult({
341
353
  text: message.result,
342
- costUsd: message.total_cost_usd,
354
+ ...(costUsd !== undefined ? { costUsd } : {}),
343
355
  durationMs: message.duration_ms,
344
356
  ...(this.lastAssistantUuid ? { anchor: this.lastAssistantUuid } : {}),
345
357
  });
@@ -351,6 +363,32 @@ export class ClaudeSession implements AgentSession {
351
363
  }
352
364
  }
353
365
 
366
+ /** 这一轮的费用 = 累计费用的差值。崩溃时的 result 费用是 0,不当成新的起点 */
367
+ private turnCost(total: number | undefined): number | undefined {
368
+ if (typeof total !== "number" || !(total > 0)) return undefined;
369
+ const prev = this.costSoFar;
370
+ this.costSoFar = total;
371
+ return prev !== undefined && total >= prev ? total - prev : undefined;
372
+ }
373
+
374
+ /**
375
+ * 报这个会话到目前的累计用量。用 modelUsage 而不是 usage:usage 只有主循环这一轮的,
376
+ * modelUsage 含子 agent、压缩等所有调用,而且是累计值(恢复的会话接着原来的总数算)
377
+ */
378
+ private reportUsage(modelUsage: Record<string, ModelUsage> | undefined): void {
379
+ const sum: TokenUsage = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, reasoning: 0, costUsd: 0 };
380
+ for (const m of Object.values(modelUsage ?? {})) {
381
+ sum.input += m.inputTokens || 0;
382
+ sum.cacheRead += m.cacheReadInputTokens || 0;
383
+ sum.cacheWrite += m.cacheCreationInputTokens || 0;
384
+ sum.output += m.outputTokens || 0;
385
+ sum.reasoning! += m.thinkingTokens || 0;
386
+ sum.costUsd! += m.costUSD || 0;
387
+ }
388
+ // 崩溃时的 result 全是 0
389
+ if (sum.input + sum.cacheRead + sum.cacheWrite + sum.output > 0) this.events.onUsage?.(sum, true);
390
+ }
391
+
354
392
  /**
355
393
  * 一轮结束后问一次上下文占用(和 /context 同一份数据)。summary 模式只用上一次响应的
356
394
  * usage 加本地估算,不额外调 token 计数接口,很便宜。读不到就算了,只是少个指示器。
@@ -537,11 +575,17 @@ export class ClaudeSession implements AgentSession {
537
575
  return this.runtime;
538
576
  }
539
577
 
540
- async interrupt(): Promise<void> {
541
- // 停止 = 这一轮和排着队的都不要了
542
- const dropped = this.pending.length + this.queue.clear();
543
- this.pending = [];
544
- if (dropped > 0) this.events.onDropped?.(dropped);
578
+ async interrupt(opts: InterruptOptions = {}): Promise<void> {
579
+ if (opts.keepQueue) {
580
+ // 打断并发送:排着的留着,选中的挪到最前面,这一轮出结果后 onTurnEnd 就交出它
581
+ const i = opts.first ? this.pending.indexOf(opts.first) : -1;
582
+ if (i > 0) this.pending.unshift(...this.pending.splice(i, 1));
583
+ } else {
584
+ // 停止 = 这一轮和排着队的都不要了
585
+ const dropped = this.pending.length + this.queue.clear();
586
+ this.pending = [];
587
+ if (dropped > 0) this.events.onDropped?.(dropped);
588
+ }
545
589
  if (!this.q) return;
546
590
  try {
547
591
  await this.q.interrupt();
@@ -16,6 +16,7 @@ import type {
16
16
  InteractionHost,
17
17
  InteractionOutcome,
18
18
  InteractionSpec,
19
+ InterruptOptions,
19
20
  QuestionSpec,
20
21
  RuntimeInfo,
21
22
  SavedAttachment,
@@ -182,6 +183,16 @@ function allowed(s: Settlement): boolean {
182
183
 
183
184
  type ParsedQuestion = QuestionSpec & { secret: boolean };
184
185
 
186
+ /** thread/tokenUsage/updated 里的一份用量(app-server 的 TokenUsageBreakdown) */
187
+ type TokenBreakdown = {
188
+ totalTokens?: number;
189
+ inputTokens?: number;
190
+ cachedInputTokens?: number;
191
+ cacheWriteInputTokens?: number;
192
+ outputTokens?: number;
193
+ reasoningOutputTokens?: number;
194
+ };
195
+
185
196
  function parseQuestions(raw: unknown): ParsedQuestion[] | null {
186
197
  if (!Array.isArray(raw) || raw.length === 0) return null;
187
198
  const specs: ParsedQuestion[] = [];
@@ -251,6 +262,10 @@ export class CodexSession implements AgentSession {
251
262
  private allowAll = false;
252
263
  private replyText = "";
253
264
  private lastTokens: number | undefined;
265
+ /** 上次看到的 thread 累计 token 数:变了才说明有新的模型请求(同一次请求可能报好几遍) */
266
+ private seenTotal: number | undefined;
267
+ /** 这个对象里开始过轮次:恢复 thread 时补报的旧用量不算新的消耗 */
268
+ private turnSeen = false;
254
269
  /** 分叉已经真正完成(拿到并接管了新 thread)。失败了不算,重试还要接着分叉 */
255
270
  private forked = false;
256
271
  /** agentMessage 的 itemId → 是不是旁白(commentary 属于过程,不流式到正文里) */
@@ -601,9 +616,15 @@ export class CodexSession implements AgentSession {
601
616
  return this.runtime;
602
617
  }
603
618
 
604
- async interrupt(): Promise<void> {
605
- // 停止 = 这一轮和排着队的都不要了
606
- this.queue = [];
619
+ async interrupt(opts: InterruptOptions = {}): Promise<void> {
620
+ if (opts.keepQueue) {
621
+ // 打断并发送:排着的留着,选中的挪到最前面,这一轮结束后 drainQueue 就开它
622
+ const i = opts.first ? this.queue.indexOf(opts.first) : -1;
623
+ if (i > 0) this.queue.unshift(...this.queue.splice(i, 1));
624
+ } else {
625
+ // 停止 = 这一轮和排着队的都不要了
626
+ this.queue = [];
627
+ }
607
628
  if (this.phase === "starting" && !this.turnId) {
608
629
  // 轮次还没真正开始:记下来,拿到轮次 id 立刻中断
609
630
  this.stopRequested = true;
@@ -757,6 +778,7 @@ export class CodexSession implements AgentSession {
757
778
  if (this.phase === "idle" || (id && this.endedTurns.has(id))) return;
758
779
  if (id) this.onTurnId(id);
759
780
  this.commentaryItems.clear();
781
+ this.turnSeen = true;
760
782
  this.events.onTurnStart?.();
761
783
  return;
762
784
  }
@@ -776,10 +798,24 @@ export class CodexSession implements AgentSession {
776
798
  }
777
799
 
778
800
  case "thread/tokenUsage/updated": {
779
- // last 是这一轮的用量,total 是整条 thread 的累计;页脚显示这一轮的
780
- const usage = (
781
- params as { tokenUsage?: { last?: { totalTokens?: number }; modelContextWindow?: number | null } }
782
- ).tokenUsage;
801
+ // last 是最近一次模型请求的用量,total 是整条 thread 的累计;页脚显示最近一次的
802
+ const usage = (params as { tokenUsage?: { total?: TokenBreakdown; last?: TokenBreakdown; modelContextWindow?: number | null } })
803
+ .tokenUsage;
804
+ const total = usage?.total?.totalTokens;
805
+ if (this.turnSeen && usage?.last && typeof total === "number" && total !== this.seenTotal) {
806
+ const l = usage.last;
807
+ // OpenAI 的 inputTokens 含命中缓存的部分,拆出来
808
+ const cached = l.cachedInputTokens ?? 0;
809
+ const written = l.cacheWriteInputTokens ?? 0;
810
+ this.events.onUsage?.({
811
+ input: Math.max(0, (l.inputTokens ?? 0) - cached - written),
812
+ cacheRead: cached,
813
+ cacheWrite: written,
814
+ output: l.outputTokens ?? 0,
815
+ reasoning: l.reasoningOutputTokens ?? 0,
816
+ });
817
+ }
818
+ if (typeof total === "number") this.seenTotal = total;
783
819
  const turnTokens = usage?.last?.totalTokens;
784
820
  if (typeof turnTokens === "number") this.lastTokens = turnTokens;
785
821
  // 最近一次请求的用量 ≈ 当前上下文大小(Codex 自己的「剩余上下文」也是这么算的)
@@ -272,9 +272,9 @@ export class FeishuBot {
272
272
  // 最近几句:读历史可能要一会儿,读不到也不影响接上
273
273
  const history = await hub.history(webKey).catch(() => []);
274
274
  const recent = history
275
- .filter((m) => m.text.trim())
275
+ .filter((m) => m.role !== "question" && m.text.trim())
276
276
  .slice(-4)
277
- .map((m) => ({ role: m.role, text: m.text }));
277
+ .map((m) => ({ role: m.role === "user" ? ("user" as const) : ("assistant" as const), text: m.text }));
278
278
  await this.client.sendCard(
279
279
  chatId,
280
280
  attachedCard({ conv: entry, recent, sessionKey: feishuKey, ctx: this.cardCtx(feishuKey, chatId) }),
@@ -17,6 +17,7 @@ import {
17
17
  isAdmin,
18
18
  legacyOwnerId,
19
19
  listUsers,
20
+ ownedBy,
20
21
  removeUser,
21
22
  verifyLogin,
22
23
  verifyPassword,
@@ -24,6 +25,7 @@ import {
24
25
  type User,
25
26
  } from "../../core/users.js";
26
27
  import type { SavedAttachment } from "../../core/types.js";
28
+ import { dailyUsage } from "../../core/usage.js";
27
29
  import {
28
30
  addMemoryItem,
29
31
  clearMemory,
@@ -61,6 +63,7 @@ import {
61
63
  takeAttempt,
62
64
  } from "./auth.js";
63
65
  import { canSeeConv, pushOwnedBy, sessionVisibleTo } from "./access.js";
66
+ import { clampLimit, dirsOf, inDir, inRecent, pageOf, parseCursor } from "./conv-pages.js";
64
67
  import { clientIp, cookies, HttpError, isHttps, readBody, readJsonBody, SECURITY_HEADERS, sendJson } from "./http.js";
65
68
  import { handleTasksApi } from "./tasks-api.js";
66
69
  import { handleSkillsApi } from "./skills-api.js";
@@ -469,6 +472,45 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
469
472
 
470
473
  // ----- 总览 -----
471
474
  if (p === "/api/bootstrap" && method === "GET") {
475
+ // 会话只给侧栏第一屏要的(见 conv-pages.ts):「最近」的前 recent 棵树、展开着的目录各自的前几棵,
476
+ // 每个飞书机器人最近的一条,再加上正在跑的、等你处理的(侧栏要显示状态)。其余点「展开显示」再拉
477
+ const all = hub.list(visible).filter((c) => !c.hidden);
478
+ const pending = interactions.listPending().filter((i) => visible(getConversation(i.convKey)));
479
+ const recent = pageOf(all.filter(inRecent), null, clampLimit(url.searchParams.get("recent"), 10));
480
+ let open: [string, number][] = [];
481
+ try {
482
+ const raw: unknown = JSON.parse(url.searchParams.get("open") ?? "[]");
483
+ if (Array.isArray(raw)) {
484
+ open = raw
485
+ .slice(0, 50)
486
+ .filter((x): x is [string, unknown] => Array.isArray(x) && typeof x[0] === "string")
487
+ .map(([dir, n]) => [dir, clampLimit(n, 5)]);
488
+ }
489
+ } catch {
490
+ // 参数坏了就当没有展开的目录
491
+ }
492
+ const dirPages = new Map(open.map(([dir, n]) => [dir, pageOf(all.filter(inDir(dir)), null, n)]));
493
+ const byKey = new Map(all.map((c) => [c.key, c]));
494
+ const keep = new Map(recent.conversations.map((c) => [c.key, c]));
495
+ for (const page of dirPages.values()) for (const c of page.conversations) keep.set(c.key, c);
496
+ const asking = new Set(pending.map((i) => i.convKey));
497
+ const bots = new Set<string>();
498
+ for (const c of all) {
499
+ // all 已按活跃时间从新到旧:每个机器人遇到的第一条就是它最近的
500
+ if (c.channel === "feishu" && !bots.has(c.channelId)) {
501
+ bots.add(c.channelId);
502
+ keep.set(c.key, c);
503
+ }
504
+ if (c.busy || asking.has(c.key)) keep.set(c.key, c);
505
+ }
506
+ // 正开着的会话(可能是后面几页里的,重连时页面上还显示着它)
507
+ const current = byKey.get(url.searchParams.get("current") ?? "");
508
+ if (current) keep.set(current.key, current);
509
+ // 分叉来源:提示里要写它的标题
510
+ for (const c of [...keep.values()]) {
511
+ const parent = c.forkOf ? byKey.get(c.forkOf) : undefined;
512
+ if (parent) keep.set(parent.key, parent);
513
+ }
472
514
  sendJson(res, 200, {
473
515
  agents: [...AGENT_IDS].map((id) => {
474
516
  const d = hub.driver(id);
@@ -488,8 +530,13 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
488
530
  workspaceRoot: config().workspaceRoot,
489
531
  quotaRefreshMin: config().web.quotaRefreshMin,
490
532
  quotaEnabled: config().web.quotaEnabled,
491
- conversations: hub.list(visible),
492
- pending: interactions.listPending().filter((i) => visible(getConversation(i.convKey))),
533
+ conversations: [...keep.values()],
534
+ sidebar: {
535
+ recent: { next: recent.next },
536
+ // 展开着的目录带上翻页游标(没带 next 的目录前端还没拉过)
537
+ dirs: dirsOf(all).map((d) => (dirPages.has(d.dir) ? { ...d, next: dirPages.get(d.dir)!.next } : d)),
538
+ },
539
+ pending,
493
540
  user: publicMe(user),
494
541
  serverTime: Date.now(),
495
542
  });
@@ -539,6 +586,21 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
539
586
  }
540
587
 
541
588
  // ----- 会话 -----
589
+ // 侧栏按页拉:scope=recent(最近)/ dir(某个项目目录)按树分页;bot(某个飞书机器人的全部聊天)平铺
590
+ if (p === "/api/conversations/page" && method === "GET") {
591
+ const all = hub.list(visible).filter((c) => !c.hidden);
592
+ const scope = url.searchParams.get("scope");
593
+ if (scope === "bot") {
594
+ const bot = url.searchParams.get("bot") ?? "";
595
+ sendJson(res, 200, { conversations: all.filter((c) => c.channel === "feishu" && c.channelId === bot).slice(0, 200), next: null });
596
+ return;
597
+ }
598
+ if (scope !== "recent" && scope !== "dir") throw new HttpError(400, "scope 只能是 recent / dir / bot");
599
+ const list = scope === "recent" ? all.filter(inRecent) : all.filter(inDir(url.searchParams.get("dir") ?? ""));
600
+ const before = parseCursor(url.searchParams.get("at"), url.searchParams.get("key"));
601
+ sendJson(res, 200, pageOf(list, before, clampLimit(url.searchParams.get("limit"), 10)));
602
+ return;
603
+ }
542
604
  if (p === "/api/conversations" && method === "GET") {
543
605
  sendJson(res, 200, hub.list(visible));
544
606
  return;
@@ -653,6 +715,8 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
653
715
  info: hub.info(key),
654
716
  messages,
655
717
  live,
718
+ // 进行中这一轮弹过的卡(已经处理了的也要):重放到 ix 事件时放回原位
719
+ interactions: live.flatMap((e) => (e.ev.type === "ix" ? [interactions.get(e.ev.id)].filter((i) => !!i) : [])),
656
720
  seq,
657
721
  pending: interactions.listPending(key),
658
722
  allowedAgents: allowedAgentsFor(key),
@@ -738,6 +802,10 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
738
802
  case "stop":
739
803
  text = await hub.stop(key);
740
804
  break;
805
+ // 打断并发送:value 是排队中那条消息的编号
806
+ case "jump":
807
+ text = await hub.jump(key, value);
808
+ break;
741
809
  case "cd":
742
810
  text = await hub.cd(key, value);
743
811
  break;
@@ -789,6 +857,20 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
789
857
  sendJson(res, 200, { agents: await agentHealth(url.searchParams.get("refresh") === "1") });
790
858
  return;
791
859
  }
860
+ if (p === "/api/usage" && method === "GET") {
861
+ // 按天的 token / 费用账(设置 →「用量」)。?from=&to= 是 YYYY-MM-DD(含两头)。
862
+ // 管理员看所有人的(只有数字,看不到内容),成员只看自己对话的
863
+ const day = /^\d{4}-\d{2}-\d{2}$/;
864
+ const from = url.searchParams.get("from") ?? "";
865
+ const to = url.searchParams.get("to") ?? "";
866
+ if (!day.test(from) || !day.test(to)) throw new HttpError(400, "from / to 要是 YYYY-MM-DD");
867
+ const admin = isAdmin(user);
868
+ const rows = dailyUsage(from, to, admin ? undefined : (owner) => ownedBy(user, owner));
869
+ const names: Record<string, string> = {};
870
+ for (const r of rows) if (r.owner && !(r.owner in names)) names[r.owner] = getUser(r.owner)?.name ?? "已删除的用户";
871
+ sendJson(res, 200, { rows, users: names, admin });
872
+ return;
873
+ }
792
874
  if (p === "/api/quota" && method === "GET") {
793
875
  // ?agent=claude,codex:只问这几个。桌面端连着多台同账号的服务器时,同一个账号只在一台上问
794
876
  // 设置里关了查额度:不去问任何 agent
@@ -0,0 +1,68 @@
1
+ // 侧栏会话列表分页:打开页面只拿第一页,点「展开显示」再按页拉。
2
+ //
3
+ // 一页按「树」算:主对话连同从它分叉出来的对话算一条(和前端 sidebar.js 的 forkForest 一样),
4
+ // 按整棵树里最近的活跃时间从新到旧排。翻页用游标(上一页最后一棵树的活跃时间 + 根的 key),
5
+ // 期间有会话变活跃、被删,也不会漏掉或重复一页的边界。
6
+ import type { ConversationInfo } from "../../core/hub.js";
7
+
8
+ export type Cursor = { at: number; key: string };
9
+ export type Page = { conversations: ConversationInfo[]; next: Cursor | null };
10
+ type Tree = { root: ConversationInfo; convs: ConversationInfo[]; at: number };
11
+
12
+ /** 最近:飞书以外的会话(飞书按机器人各占一行,另外给) */
13
+ export const inRecent = (c: ConversationInfo): boolean => c.channel !== "feishu";
14
+ /** 项目:Web 会话按工作目录分组 */
15
+ export const inDir = (dir: string) => (c: ConversationInfo): boolean => c.channel === "web" && c.cwd === dir;
16
+
17
+ /** 按分叉关系成树:父对话也在这一组里的挂到下面,其余的是根。父链绕回自己(数据坏了)就当根 */
18
+ export function forkTrees(list: ConversationInfo[]): Tree[] {
19
+ const byKey = new Map(list.map((c) => [c.key, c]));
20
+ const rootOf = (c: ConversationInfo): ConversationInfo => {
21
+ let cur = c;
22
+ for (let n = 0; n < 50; n++) {
23
+ const parent = cur.forkOf ? byKey.get(cur.forkOf) : undefined;
24
+ if (!parent || parent.key === c.key) return cur;
25
+ cur = parent;
26
+ }
27
+ return c;
28
+ };
29
+ const trees = new Map<string, Tree>();
30
+ for (const c of list) {
31
+ const root = rootOf(c);
32
+ let t = trees.get(root.key);
33
+ if (!t) trees.set(root.key, (t = { root, convs: [], at: 0 }));
34
+ t.convs.push(c);
35
+ t.at = Math.max(t.at, c.activeAt);
36
+ }
37
+ return [...trees.values()].sort((a, b) => b.at - a.at || (a.root.key < b.root.key ? 1 : -1));
38
+ }
39
+
40
+ /** 游标之后的 limit 棵树 */
41
+ export function pageOf(list: ConversationInfo[], before: Cursor | null, limit: number): Page {
42
+ const trees = forkTrees(list);
43
+ const start = before ? trees.findIndex((t) => t.at < before.at || (t.at === before.at && t.root.key < before.key)) : 0;
44
+ if (start < 0) return { conversations: [], next: null };
45
+ const slice = trees.slice(start, start + limit);
46
+ const last = slice[slice.length - 1];
47
+ return {
48
+ conversations: slice.flatMap((t) => t.convs),
49
+ next: last && start + limit < trees.length ? { at: last.at, key: last.root.key } : null,
50
+ };
51
+ }
52
+
53
+ /** 项目目录:每个目录最近的活跃时间(目录行本身要全部显示,会话再按需拉) */
54
+ export function dirsOf(list: ConversationInfo[]): { dir: string; at: number }[] {
55
+ const at = new Map<string, number>();
56
+ for (const c of list) if (c.channel === "web") at.set(c.cwd, Math.max(at.get(c.cwd) ?? 0, c.activeAt));
57
+ return [...at].map(([dir, t]) => ({ dir, at: t })).sort((a, b) => b.at - a.at);
58
+ }
59
+
60
+ export function parseCursor(at: string | null, key: string | null): Cursor | null {
61
+ const n = Number(at);
62
+ return key && Number.isFinite(n) ? { at: n, key } : null;
63
+ }
64
+
65
+ export const clampLimit = (v: unknown, def: number): number => {
66
+ const n = Math.floor(Number(v));
67
+ return Number.isFinite(n) && n > 0 ? Math.min(n, 200) : def;
68
+ };