agent-loft 0.2.60 → 0.2.62

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
@@ -63,7 +63,7 @@ Logo 就是这个意思:一大两小几颗星(多个 agent)站在同一张
63
63
  - 侧栏按页加载:每个项目目录先显示 5 条,点「展开显示」每次再拉 10 条。
64
64
  - 侧栏底部显示 Claude / Codex 的订阅额度(5 小时 / 7 天窗口,以及多久后重置);关了额度查询就整块不显示。
65
65
  - 右上角「更多」最下面显示当前会话累计消耗的 token 分布(输入 / 缓存写入 / 缓存读取 / 输出,Claude 还有按 API 价格估算的费用)。设置也在「更多」里。
66
- - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。金额都是按 API 价格算的参考值:Claude 用它自己报的费用,Codex 不报费用,按模型单价(LiteLLM 公开价格表,内置一份快照、联网时每天更新)× token 估算。从 0.2.34 开始记录,之前的用量没有日期,不计入。
66
+ - 设置 → 用量:按日 / 月 / 年(默认按月)统计 token 和金额,有每天(每月)的柱状图,按 agent、模型、用户(管理员才有)分开看;成员只看到自己的。管理员还可查看服务端本机直接使用的 Claude Code、Codex 桌面端和 CLI 用量,和 Agent Loft 的用量分开显示、避免重复计算。金额都是按 API 价格算的参考值:Agent Loft 的 Claude 用它自己报的费用,Codex 和直接用的 Claude Code 按模型单价 × token 估算(OpenAI 单价来自 LiteLLM 公开价格表,内置快照、联网时每天更新)。Agent Loft 的账从 0.2.34 开始记录;本机直接使用的用量可回溯已有会话记录。
67
67
  - 「添加到主屏幕」后当 App 用;切到后台再回来会自动重连,补上错过的内容。
68
68
  - **网页多服务器切换**:在 设置 → 服务器 添加其他 agent-loft,再点「授权」到对方页面确认,侧栏左上角就能切换;各台分别登录,切走后保持连接,列表显示待处理数和运行状态,刷新后保留选择。几台需使用同一主域名下的 HTTPS 地址(例如 `mac.example.com`、`nas.example.com`)。在外层页面开启系统通知后,各台的提醒都能推到同一个主屏幕 App,点通知自动切到对应服务器和对话。见[使用指南](docs/产品介绍.md#在网页和手机上切换多台服务器)。
69
69
  - **系统通知**:Web 会话回复完成、出错、需要授权或提问时推送到手机 / 电脑(设置 → 通知 → 「在此设备开启通知」,可以发测试通知)。飞书会话由飞书提醒,正在前台看着的会话不推。需要 HTTPS 访问,iPhone 需 iOS 16.4+ 且从主屏幕图标打开。
@@ -123,7 +123,7 @@ agent-loft service install # 注册为开机自启服务(systemd / laun
123
123
  - 菜单栏图标可以换成额度条:Claude、Codex 各是一只像素小宠物,看样子就知道是谁,身子是 5 小时额度,下面一条是周额度。桌面端设置 → 额度显示 →「菜单栏显示额度」,选所有服务器合起来(取最高),或者按服务器分别选 Claude / Codex(图标上不写服务器名);都不选就只显示图标。「额度条显示」选实心表示剩余额度(默认,像电池)还是已用额度。只有 macOS 有,Windows / Linux 的托盘图标太小放不下。
124
124
  - 支持前面挡着 Cloudflare Access 的服务器:验证页直接在窗口里完成,过期会提醒;也可以配 Service Token 免验证。
125
125
  - 首次打开可以选「这台 Mac 也作为服务端」:一键在终端里安装 agent-loft(没有 Node.js 会先用 Homebrew 装)并开机自启,装好自动连上;设置里可以改成「只在桌面端运行时运行」(不开机自启,打开桌面端时启动、退出时停止)。Linux 上一样(需要先装好 Node.js 22.13+,开机自启用 systemd 用户服务);Windows 上服务端还没有开机自启,可以在 WSL 里装,桌面端会自动检测到 `127.0.0.1` 上的它。防休眠:本机有会话在跑时不休眠;另有永不休眠、定时休眠(设休眠时段,时段外不休眠,时段内本机没有会话在跑、屏幕锁上后让 Mac 睡下去)和合盖不休眠(macOS,第一次开关要输管理员密码,之后不用;开着时闲置也不睡,定时休眠到点会临时关掉它让 Mac 睡下去,醒来再打开)。
126
- - 顶栏服务器标签后面的用量按钮(柱状图图标)打开「用量汇总」:把所有已添加服务器的用量,加上这台电脑上直接用的 Claude Code、Codex(桌面端和 CLI,读它们自己的会话记录),合在一起看。按日 / 月 / 年统计 token 和金额,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按来源。本机直接用的金额按模型单价估算;Agent Loft 自己跑的会话只算在服务器里,不重复算。不在线、没登录或服务端太旧的服务器不计入,页面上会注明。
126
+ - 顶栏服务器标签后面的用量按钮(柱状图图标)打开「用量汇总」:从所有已添加服务器拉取 token 和费用,包括各服务器本机直接使用的 Claude Code、Codex 桌面端和 CLI(仅管理员可见)。按日 / 月 / 年统计,和网页设置 → 用量一样有柱状图和按 agent、模型、用户的分项,另外多一栏按服务器来源。采集在各服务端完成:读取运行服务的系统用户下 `~/.claude/projects`、`~/.codex/sessions` 和 `archived_sessions`(支持 `CLAUDE_CONFIG_DIR` / `CODEX_HOME`),按服务器时区记日期,并跳过 Agent Loft 已记账的会话。桌面端不再扫描本机文件;这台电脑的直接用量也需要添加本机服务端才能统计。不在线、没登录或缺少用量接口的服务器不计入,页面上会注明;有旧版用量接口但不支持本机采集的,会提示升级。
127
127
  - 设置(`⌘,`)的服务器列表里展开某台服务器,能看它的 Agent 环境和版本,有新版本时点「升级服务端」;桌面端自己的更新在同一页的「更新」里点「更新并重启」。
128
128
 
129
129
  桌面端只是个壳(代码在 `desktop/`),服务端照常用 npm 安装和升级。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-loft",
3
- "version": "0.2.60",
3
+ "version": "0.2.62",
4
4
  "type": "module",
5
5
  "description": "多个 agent 的工作台:把本机 Claude Code / Codex 放到一处统一管理,用飞书和 Web 页面随时驱动——会话、审批、模型切换都共用",
6
6
  "keywords": [
@@ -17,6 +17,7 @@ import {
17
17
  type SDKUserMessage,
18
18
  } from "@anthropic-ai/claude-agent-sdk";
19
19
  import { agentEnvironment } from "../../core/agent-env.js";
20
+ import { usageOf } from "../../core/usage.js";
20
21
  import { expertAppend, expertSystemPrompt, RICH_REPLY_LINES, searchLabel } from "../../core/expert-prompt.js";
21
22
  import { ACCESS_LEVELS, type ExpertAccess } from "../../core/experts.js";
22
23
  import { MEMORY_MCP_NAME, memoryMcpSpawn } from "../../core/memory-mcp.js";
@@ -313,6 +314,8 @@ export class ClaudeSession implements AgentSession {
313
314
  * 恢复 / 分叉来的会话第一轮不知道之前累计了多少,这一轮先不报费用
314
315
  */
315
316
  private costSoFar: number | undefined;
317
+ /** 上一轮的累计 Token;恢复 / 分叉时优先从已保存的会话用量建立起点。 */
318
+ private tokensSoFar: number | undefined;
316
319
  /** 任务清单(见 todos.ts)。只记主线的,子 agent 自己列的不算 */
317
320
  private todos = new TodoTracker();
318
321
 
@@ -322,6 +325,10 @@ export class ClaudeSession implements AgentSession {
322
325
  private readonly host: InteractionHost,
323
326
  ) {
324
327
  this.costSoFar = opts.resumeId ? undefined : 0;
328
+ const previousUsage = usageOf(opts.resumeId);
329
+ this.tokensSoFar = previousUsage
330
+ ? previousUsage.input + previousUsage.cacheRead + previousUsage.cacheWrite + previousUsage.output
331
+ : opts.resumeId ? undefined : 0;
325
332
  // 接着老会话说:之前列的任务后面可能接着改(TaskUpdate 只给编号),先读回来。
326
333
  // 读一个本地文件,比模型第一次调工具快得多
327
334
  if (opts.resumeId) void readTodos(opts.resumeId, opts.cwd).then((items) => this.todos.seed(items));
@@ -449,11 +456,12 @@ export class ClaudeSession implements AgentSession {
449
456
 
450
457
  if (message.type === "result") {
451
458
  const costUsd = this.turnCost(message.total_cost_usd);
452
- this.reportUsage(message.modelUsage);
459
+ const tokens = this.reportUsage(message.modelUsage);
453
460
  if (message.subtype === "success") {
454
461
  this.events.onResult({
455
462
  text: message.result,
456
463
  ...(costUsd !== undefined ? { costUsd } : {}),
464
+ ...(tokens !== undefined ? { tokens } : {}),
457
465
  durationMs: message.duration_ms,
458
466
  ...(this.lastAssistantUuid ? { anchor: this.lastAssistantUuid } : {}),
459
467
  });
@@ -477,7 +485,7 @@ export class ClaudeSession implements AgentSession {
477
485
  * 报这个会话到目前的累计用量。用 modelUsage 而不是 usage:usage 只有主循环这一轮的,
478
486
  * modelUsage 含子 agent、压缩等所有调用,而且是累计值(恢复的会话接着原来的总数算)
479
487
  */
480
- private reportUsage(modelUsage: Record<string, ModelUsage> | undefined): void {
488
+ private reportUsage(modelUsage: Record<string, ModelUsage> | undefined): number | undefined {
481
489
  const sum: TokenUsage = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, reasoning: 0, costUsd: 0 };
482
490
  for (const m of Object.values(modelUsage ?? {})) {
483
491
  sum.input += m.inputTokens || 0;
@@ -487,8 +495,14 @@ export class ClaudeSession implements AgentSession {
487
495
  sum.reasoning! += m.thinkingTokens || 0;
488
496
  sum.costUsd! += m.costUSD || 0;
489
497
  }
490
- // 崩溃时的 result 全是 0
491
- if (sum.input + sum.cacheRead + sum.cacheWrite + sum.output > 0) this.events.onUsage?.(sum, true);
498
+ const total = sum.input + sum.cacheRead + sum.cacheWrite + sum.output;
499
+ // 崩溃时的 result 全是 0,不覆盖上一轮的起点。
500
+ if (!(total > 0)) return undefined;
501
+ const prev = this.tokensSoFar;
502
+ this.tokensSoFar = total;
503
+ this.events.onUsage?.(sum, true);
504
+ // 没有历史起点或累计值倒退时,先建立起点,避免把旧用量当成本轮的。
505
+ return prev !== undefined && total >= prev ? total - prev : undefined;
492
506
  }
493
507
 
494
508
  /**
@@ -284,10 +284,11 @@ export class CodexSession implements AgentSession {
284
284
  /** 用户点过「本会话全部允许」。只在内存里,会话对象一换就重新逐条询问。 */
285
285
  private allowAll = false;
286
286
  private replyText = "";
287
- private lastTokens: number | undefined;
287
+ /** 本轮所有模型请求的用量,和会话汇总使用相同的输入 / 缓存 / 输出口径。 */
288
+ private turnTokens: number | undefined;
288
289
  /** 上次看到的 thread 累计 token 数:变了才说明有新的模型请求(同一次请求可能报好几遍) */
289
290
  private seenTotal: number | undefined;
290
- /** 这个对象里开始过轮次:恢复 thread 时补报的旧用量不算新的消耗 */
291
+ /** 当前轮次已开始:恢复 thread 时补报的旧用量不算新的消耗 */
291
292
  private turnSeen = false;
292
293
  /** 分叉已经真正完成(拿到并接管了新 thread)。失败了不算,重试还要接着分叉 */
293
294
  private forked = false;
@@ -360,6 +361,7 @@ export class CodexSession implements AgentSession {
360
361
  if (this.endedTurns.size > 50) this.endedTurns.delete(this.endedTurns.values().next().value!);
361
362
  }
362
363
  this.phase = "idle";
364
+ this.turnSeen = false;
363
365
  this.turnId = undefined;
364
366
  this.stopRequested = false;
365
367
  this.turnSeq += 1;
@@ -554,6 +556,8 @@ export class CodexSession implements AgentSession {
554
556
  private startTurn(input: UserInput): void {
555
557
  this.currentInput = input;
556
558
  this.replyText = "";
559
+ this.turnTokens = undefined;
560
+ this.turnSeen = false;
557
561
  this.phase = "starting";
558
562
  this.turnId = undefined;
559
563
  this.stopRequested = false;
@@ -854,7 +858,7 @@ export class CodexSession implements AgentSession {
854
858
  }
855
859
 
856
860
  case "thread/tokenUsage/updated": {
857
- // last 是最近一次模型请求的用量,total 是整条 thread 的累计;页脚显示最近一次的
861
+ // last 是最近一次模型请求的用量,total 是整条 thread 的累计;去重后累加到本轮页脚和会话汇总
858
862
  const usage = (params as { tokenUsage?: { total?: TokenBreakdown; last?: TokenBreakdown; modelContextWindow?: number | null } })
859
863
  .tokenUsage;
860
864
  const total = usage?.total?.totalTokens;
@@ -863,21 +867,22 @@ export class CodexSession implements AgentSession {
863
867
  // OpenAI 的 inputTokens 含命中缓存的部分,拆出来
864
868
  const cached = l.cachedInputTokens ?? 0;
865
869
  const written = l.cacheWriteInputTokens ?? 0;
866
- this.events.onUsage?.({
870
+ const delta = {
867
871
  input: Math.max(0, (l.inputTokens ?? 0) - cached - written),
868
872
  cacheRead: cached,
869
873
  cacheWrite: written,
870
874
  output: l.outputTokens ?? 0,
871
875
  reasoning: l.reasoningOutputTokens ?? 0,
872
- });
876
+ };
877
+ this.turnTokens = (this.turnTokens ?? 0) + delta.input + delta.cacheRead + delta.cacheWrite + delta.output;
878
+ this.events.onUsage?.(delta);
873
879
  }
874
880
  if (typeof total === "number") this.seenTotal = total;
875
- const turnTokens = usage?.last?.totalTokens;
876
- if (typeof turnTokens === "number") this.lastTokens = turnTokens;
881
+ const requestTokens = usage?.last?.totalTokens;
877
882
  // 最近一次请求的用量 ≈ 当前上下文大小(Codex 自己的「剩余上下文」也是这么算的)
878
883
  const window = usage?.modelContextWindow;
879
- if (typeof turnTokens === "number" && window) {
880
- this.events.onContext?.({ used: turnTokens, window, percent: Math.round((turnTokens / window) * 100) });
884
+ if (typeof requestTokens === "number" && window) {
885
+ this.events.onContext?.({ used: requestTokens, window, percent: Math.round((requestTokens / window) * 100) });
881
886
  }
882
887
  return;
883
888
  }
@@ -902,7 +907,7 @@ export class CodexSession implements AgentSession {
902
907
  this.events.onResult({
903
908
  text,
904
909
  durationMs: turn.durationMs ?? 0,
905
- ...(this.lastTokens !== undefined ? { tokens: this.lastTokens } : {}),
910
+ ...(this.turnTokens !== undefined ? { tokens: this.turnTokens } : {}),
906
911
  ...(turn.id ? { anchor: turn.id } : {}),
907
912
  });
908
913
  }
@@ -29,6 +29,7 @@ import {
29
29
  } from "../../core/users.js";
30
30
  import type { AttachmentInfo, SavedAttachment } from "../../core/types.js";
31
31
  import { dailyUsage } from "../../core/usage.js";
32
+ import { localUsage } from "../../core/local-usage.js";
32
33
  import { appendDirOrder, getDirOrder, setDirOrder } from "../../core/ui-prefs.js";
33
34
  import {
34
35
  addMemoryItem,
@@ -1158,16 +1159,18 @@ export async function handleApi(req: IncomingMessage, res: ServerResponse, url:
1158
1159
  }
1159
1160
  if (p === "/api/usage" && method === "GET") {
1160
1161
  // 按天的 token / 费用账(设置 →「用量」)。?from=&to= 是 YYYY-MM-DD(含两头)。
1161
- // 管理员看所有人的(只有数字,看不到内容),成员只看自己对话的
1162
+ // 管理员看所有人的,以及服务端本机直接用的桌面端 / CLI;成员只看自己对话的。
1163
+ // 本机记录不属于任何 Web 用户,不能当作未归属的对话暴露给成员。
1162
1164
  const day = /^\d{4}-\d{2}-\d{2}$/;
1163
1165
  const from = url.searchParams.get("from") ?? "";
1164
1166
  const to = url.searchParams.get("to") ?? "";
1165
1167
  if (!day.test(from) || !day.test(to)) throw new HttpError(400, "from / to 要是 YYYY-MM-DD");
1166
1168
  const admin = isAdmin(user);
1167
1169
  const rows = dailyUsage(from, to, admin ? undefined : (owner) => ownedBy(user, owner));
1170
+ if (admin) rows.push(...await localUsage(from, to));
1168
1171
  const names: Record<string, string> = {};
1169
1172
  for (const r of rows) if (r.owner && !(r.owner in names)) names[r.owner] = getUser(r.owner)?.name ?? "已删除的用户";
1170
- sendJson(res, 200, { rows, users: names, admin });
1173
+ sendJson(res, 200, { rows, users: names, admin, localUsageIncluded: admin });
1171
1174
  return;
1172
1175
  }
1173
1176
  if (p === "/api/quota" && method === "GET") {
@@ -0,0 +1,23 @@
1
+ {
2
+ "claude-fable-5-1": [10,0.25,50],
3
+ "claude-mythos-5-1": [10,0.25,50],
4
+ "claude-fable-5": [10,1,50],
5
+ "claude-mythos-5": [10,1,50],
6
+ "claude-opus-5-5": [4,0.2,20],
7
+ "claude-opus-5": [5,0.5,25],
8
+ "claude-opus-4-8": [5,0.5,25],
9
+ "claude-opus-4-7": [5,0.5,25],
10
+ "claude-opus-4-6": [5,0.5,25],
11
+ "claude-opus-4-5": [5,0.5,25],
12
+ "claude-opus-4-1": [15,1.5,75],
13
+ "claude-opus-4": [15,1.5,75],
14
+ "claude-sonnet-5-5": [2,0.2,10],
15
+ "claude-sonnet-5": [2,0.2,10],
16
+ "claude-sonnet-4-6": [3,0.3,15],
17
+ "claude-sonnet-4-5": [3,0.3,15],
18
+ "claude-sonnet-4": [3,0.3,15],
19
+ "claude-3-7-sonnet": [3,0.3,15],
20
+ "claude-haiku-5-5": [0.1,0.01,0.5,100000,0.5,0.05,2.5],
21
+ "claude-haiku-4-5": [1,0.1,5],
22
+ "claude-3-5-haiku": [0.8,0.08,4]
23
+ }
@@ -0,0 +1,275 @@
1
+ // 服务端所在机器上直接用的 Claude Code、Codex(各自的桌面端、命令行)的用量,通过 /api/usage 给网页和桌面端的用量汇总用。
2
+ //
3
+ // 不经过 agent-loft,只能读它们自己落盘的会话记录:
4
+ // - Claude Code(命令行和 Claude 桌面端里的 Code 都写这里):~/.claude/projects/**/*.jsonl,每条 assistant
5
+ // 消息带 usage。同一条消息按内容块拆成好几行、恢复 / 分叉的会话还会把旧消息抄进新文件,按 message.id + requestId 去重。
6
+ // entrypoint 区分来源:claude-desktop 是桌面端,cli 是命令行,sdk-ts 是 Agent SDK(agent-loft 就是用它跑的)。
7
+ // - Codex:~/.codex/sessions/**/*.jsonl(和 archived_sessions),每次模型请求一条 token_count,带这次的
8
+ // last_token_usage 和整条会话的累计 total。第一行 session_meta 的 originator 区分来源,agent-loft 跑的是 "agent-loft"。
9
+ // agent-loft 自己跑的会话已经记在服务器的账里,这里跳过,免得算两遍(别的用 Agent SDK 的程序也一起跳过了)。
10
+ //
11
+ // 新版 Claude Code 不再记费用,金额都按模型单价估(Claude 用内置快照,OpenAI 共用 pricing.ts 每天更新的价格表)。解析过的文件按 mtime + 大小缓存在内存里,没变的不再读。
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { priceOf as openaiPriceOf } from "./pricing.js";
16
+ import { dayOf, type DailyRow } from "./usage.js";
17
+
18
+ type Source = "desktop" | "cli" | "other";
19
+ type Agent = "claude" | "codex";
20
+ type UsageEvent = [key: string, at: number, source: Source, model: string, input: number, cacheRead: number,
21
+ write5m: number, write1h: number, output: number, reasoning: number, fast: number];
22
+ type Price = [number, number | null, number, ...number[]];
23
+ export type LocalUsageRow = DailyRow & { source: Source };
24
+ export type UsageRoots = { claude: string[]; codex: string[] };
25
+
26
+ const CLAUDE_PRICES: Record<string, Price> = JSON.parse(fs.readFileSync(new URL("./claude-model-prices.json", import.meta.url), "utf8"));
27
+ /** 缓存写入相对输入单价的倍数:5 分钟 1.25 倍,1 小时 2 倍 */
28
+ const WRITE_5M = 1.25;
29
+ const WRITE_1H = 2;
30
+ /** 快速模式按两倍价 */
31
+ const FAST = 2;
32
+
33
+ const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0);
34
+
35
+ /** Claude 的 entrypoint → 来源;null 是 agent-loft(Agent SDK)跑的,跳过 */
36
+ export function claudeSource(entrypoint: string | undefined): Source | null {
37
+ if (entrypoint === "sdk-ts") return null;
38
+ if (entrypoint === "claude-desktop") return "desktop";
39
+ // 老版本没有 entrypoint,那时只有命令行
40
+ if (!entrypoint || entrypoint === "cli") return "cli";
41
+ return "other";
42
+ }
43
+
44
+ /** Codex 的 originator → 来源;null 是 agent-loft 跑的 */
45
+ export function codexSource(originator: string | undefined): Source | null {
46
+ if (originator === "agent-loft") return null;
47
+ if (/desktop/i.test(originator ?? "")) return "desktop";
48
+ if (!originator || /^codex[_-](exec|cli|tui)/i.test(originator)) return "cli";
49
+ return "other";
50
+ }
51
+
52
+ /**
53
+ * 一个 Claude 会话文件里的用量。每条:
54
+ * [去重键, 时间 ms, 来源, 模型, 输入, 缓存读取, 缓存写入(5 分钟), 缓存写入(1 小时), 输出, 推理, 快速模式]
55
+ */
56
+ export function parseClaude(text: string): UsageEvent[] {
57
+ const out: UsageEvent[] = [];
58
+ for (const line of text.split("\n")) {
59
+ if (!line.includes('"usage"')) continue;
60
+ let d;
61
+ try {
62
+ d = JSON.parse(line);
63
+ } catch {
64
+ continue;
65
+ }
66
+ const m = d?.message;
67
+ const u = m?.usage;
68
+ if (d.type !== "assistant" || !u || !m.id) continue;
69
+ // 本地报错、被打断时的占位消息
70
+ if (m.model === "<synthetic>") continue;
71
+ const source = claudeSource(d.entrypoint);
72
+ const at = Date.parse(d.timestamp);
73
+ if (!source || !Number.isFinite(at)) continue;
74
+ const write = num(u.cache_creation_input_tokens);
75
+ const w1h = Math.min(write, num(u.cache_creation?.ephemeral_1h_input_tokens));
76
+ out.push([
77
+ `${m.id}\t${d.requestId ?? ""}`,
78
+ at,
79
+ source,
80
+ m.model ?? "",
81
+ num(u.input_tokens),
82
+ num(u.cache_read_input_tokens),
83
+ write - w1h,
84
+ w1h,
85
+ num(u.output_tokens),
86
+ num(u.output_tokens_details?.thinking_tokens),
87
+ u.speed === "fast" ? 1 : 0,
88
+ ]);
89
+ }
90
+ return out;
91
+ }
92
+
93
+ /** 一个 Codex 会话文件里的用量,格式同 parseClaude(Codex 不分缓存时长,都记在 5 分钟那格) */
94
+ export function parseCodex(text: string): UsageEvent[] {
95
+ const out: UsageEvent[] = [];
96
+ let source: Source | null | undefined;
97
+ let sessionId = "";
98
+ let model = "";
99
+ let seenTotal: number | undefined;
100
+ for (const line of text.split("\n")) {
101
+ const meta = source === undefined && line.includes('"session_meta"');
102
+ if (!meta && !line.includes('"turn_context"') && !line.includes('"token_count"')) continue;
103
+ let d;
104
+ try {
105
+ d = JSON.parse(line);
106
+ } catch {
107
+ continue;
108
+ }
109
+ const p = d?.payload;
110
+ if (d.type === "session_meta") {
111
+ source = codexSource(p?.originator);
112
+ if (source === null) return [];
113
+ if (typeof p?.id === "string") sessionId = p.id;
114
+ continue;
115
+ }
116
+ if (d.type === "turn_context") {
117
+ if (typeof p?.model === "string") model = p.model;
118
+ continue;
119
+ }
120
+ if (p?.type !== "token_count") continue;
121
+ const total = p.info?.total_token_usage?.total_tokens;
122
+ const l = p.info?.last_token_usage;
123
+ // 同一次请求会报好几遍(累计值没变),只认第一遍
124
+ if (!l || typeof total !== "number" || total === seenTotal) continue;
125
+ seenTotal = total;
126
+ const at = Date.parse(d.timestamp);
127
+ if (!Number.isFinite(at)) continue;
128
+ // OpenAI 的 input_tokens 含命中缓存的部分,拆出来(和 src/agents/codex/session.ts 一样)
129
+ const cached = num(l.cached_input_tokens);
130
+ const written = num(l.cache_write_input_tokens);
131
+ out.push([
132
+ `${sessionId}\t${d.timestamp}\t${total}`,
133
+ at,
134
+ source ?? "cli",
135
+ model,
136
+ Math.max(0, num(l.input_tokens) - cached - written),
137
+ cached,
138
+ written,
139
+ 0,
140
+ num(l.output_tokens),
141
+ num(l.reasoning_output_tokens),
142
+ 0,
143
+ ]);
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /** 模型的单价(美元 / 百万 token):[输入, 缓存读取(null 按输入算), 输出, 长提示词门槛?, 输入, 缓存读取, 输出]。认不出返回 undefined */
149
+ export function priceOf(agent: Agent, model: string): Price | undefined {
150
+ if (!model) return undefined;
151
+ if (agent === "claude") {
152
+ // claude-opus-5-5[1m]、claude-haiku-4-5-20251001、us.anthropic.claude-…-v1:0 都认
153
+ const base = model
154
+ .toLowerCase()
155
+ .replace(/\[.*\]$/, "")
156
+ .replace(/^(\w+\.)?anthropic\./, "")
157
+ .replace(/-v\d+:\d+$/, "")
158
+ .replace(/[-@]\d{8}$/, "");
159
+ return CLAUDE_PRICES[base];
160
+ }
161
+ return openaiPriceOf(model);
162
+ }
163
+
164
+ /** 一条用量的金额(美元),认不出模型是 0 */
165
+ export function costOf(agent: Agent, e: UsageEvent): number {
166
+ const p = priceOf(agent, e[3]);
167
+ if (!p) return 0;
168
+ const [, , , , input, cacheRead, w5, w1h, output, , fast] = e;
169
+ // Haiku 5.5 这类:一次请求的提示词超过门槛就整次按另一档算
170
+ const long = p[3] !== undefined && input + cacheRead + w5 + w1h > p[3];
171
+ const [pi, pr, po] = long ? [p[4]!, p[5]!, p[6]!] : p;
172
+ const cost = input * pi + cacheRead * (pr ?? pi) + w5 * pi * (agent === "claude" ? WRITE_5M : 1) + w1h * pi * WRITE_1H + output * po;
173
+ return (cost / 1e6) * (fast ? FAST : 1);
174
+ }
175
+
176
+ /** 会话记录在哪:尊重 CLAUDE_CONFIG_DIR / CODEX_HOME,默认在家目录下 */
177
+ export function usageRoots(): UsageRoots {
178
+ const home = os.homedir();
179
+ const claude = [...new Set([process.env.CLAUDE_CONFIG_DIR, path.join(home, ".claude")].filter((d): d is string => !!d))];
180
+ const codexHome = process.env.CODEX_HOME || path.join(home, ".codex");
181
+ return {
182
+ claude: claude.map((d) => path.join(d, "projects")),
183
+ codex: [path.join(codexHome, "sessions"), path.join(codexHome, "archived_sessions")],
184
+ };
185
+ }
186
+
187
+ async function listJsonl(dir: string): Promise<string[]> {
188
+ let entries;
189
+ try {
190
+ entries = await fs.promises.readdir(dir, { recursive: true, withFileTypes: true });
191
+ } catch {
192
+ return [];
193
+ }
194
+ return entries.filter((e) => e.isFile() && e.name.endsWith(".jsonl")).map((e) => path.join(e.parentPath, e.name));
195
+ }
196
+
197
+ /** 路径 → { mtimeMs, size, events } */
198
+ const cache = new Map<string, { mtimeMs: number; size: number; events: UsageEvent[] }>();
199
+ /** 同时只扫一遍,后来的排队等 */
200
+ let queue: Promise<unknown> = Promise.resolve();
201
+
202
+ async function eventsOf(file: string, parse: (text: string) => UsageEvent[], sinceMs: number): Promise<UsageEvent[]> {
203
+ let st;
204
+ try {
205
+ st = await fs.promises.stat(file);
206
+ } catch {
207
+ cache.delete(file);
208
+ return [];
209
+ }
210
+ // 最后改动在这段时间之前的文件不会有这段时间的用量
211
+ if (st.mtimeMs < sinceMs) return [];
212
+ const hit = cache.get(file);
213
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.events;
214
+ let events: UsageEvent[] = [];
215
+ try {
216
+ events = parse(await fs.promises.readFile(file, "utf8"));
217
+ } catch {
218
+ // 读的时候正好被删了之类,跳过
219
+ }
220
+ cache.set(file, { mtimeMs: st.mtimeMs, size: st.size, events });
221
+ // 一个文件一个文件来,别把主进程卡住
222
+ await new Promise((r) => setImmediate(r));
223
+ return events;
224
+ }
225
+
226
+ /**
227
+ * from ~ to(含两头,YYYY-MM-DD,本地时间)的用量,按「日期 + agent + 来源 + 模型」合计,
228
+ * 格式和服务端 /api/usage 的 rows 一样,多一个 source(desktop / cli / other)。金额都是估算的
229
+ */
230
+ export function localUsage(from: string, to: string, dirs = usageRoots()): Promise<LocalUsageRow[]> {
231
+ const run = queue.then(() => scan(from, to, dirs));
232
+ queue = run.catch(() => {});
233
+ return run;
234
+ }
235
+
236
+ async function scan(from: string, to: string, dirs: UsageRoots): Promise<LocalUsageRow[]> {
237
+ // 往前多留一天,时区、跨零点的会话不至于漏
238
+ const sinceMs = new Date(`${from}T00:00:00`).getTime() - 86400_000;
239
+ const groups = new Map<string, LocalUsageRow>();
240
+ for (const [agent, parse, list] of [
241
+ ["claude", parseClaude, dirs.claude],
242
+ ["codex", parseCodex, dirs.codex],
243
+ ] as const) {
244
+ /** 去重键 → 这条用量(重复的取输出多的那条,流式中途写下的那行输出可能还没写全) */
245
+ const seen = new Map<string, UsageEvent>();
246
+ for (const dir of list) {
247
+ for (const file of await listJsonl(dir)) {
248
+ for (const e of await eventsOf(file, parse, sinceMs)) {
249
+ const day = dayOf(e[1]);
250
+ if (day < from || day > to) continue;
251
+ const prev = seen.get(e[0]);
252
+ if (!prev || e[8] > prev[8]) seen.set(e[0], e);
253
+ }
254
+ }
255
+ }
256
+ for (const e of seen.values()) {
257
+ const day = dayOf(e[1]);
258
+ const key = `${day}\t${e[2]}\t${e[3]}`;
259
+ let g = groups.get(`${agent}\t${key}`);
260
+ if (!g) {
261
+ g = { day, agent, source: e[2], ...(e[3] ? { model: e[3] } : {}), input: 0, cacheRead: 0, cacheWrite: 0, output: 0, reasoning: 0, costUsd: 0 };
262
+ groups.set(`${agent}\t${key}`, g);
263
+ }
264
+ g.input += e[4];
265
+ g.cacheRead += e[5];
266
+ g.cacheWrite += e[6] + e[7];
267
+ g.output += e[8];
268
+ g.reasoning = (g.reasoning ?? 0) + e[9];
269
+ g.costUsd = (g.costUsd ?? 0) + costOf(agent, e);
270
+ }
271
+ }
272
+ return [...groups.values()]
273
+ .map(({ costUsd, ...g }) => (costUsd ? { ...g, costUsd, estimated: true as const } : g))
274
+ .sort((a, b) => a.day.localeCompare(b.day));
275
+ }
@@ -228,7 +228,7 @@ export function describeSchedule(s: TaskSchedule): string {
228
228
  case "weekdays":
229
229
  return `工作日 ${s.time}`;
230
230
  case "weekly":
231
- return s.days.length === 7 ? `每天 ${s.time}` : `每周${s.days.map((d) => WEEK[d]).join("、")} ${s.time}`;
231
+ return s.days.length === 7 ? `每天 ${s.time}` : `每周${[...s.days].sort((a, b) => (a || 7) - (b || 7)).map((d) => WEEK[d]).join("、")} ${s.time}`;
232
232
  case "monthly":
233
233
  return `每月 ${s.day} 日 ${s.time}`;
234
234
  case "hourly":
package/src/core/usage.ts CHANGED
@@ -19,7 +19,7 @@ export type UsageTotals = Required<Omit<TokenUsage, "costUsd">> & { costUsd?: nu
19
19
  /** 一天里某个人用某个 agent 的合计 */
20
20
  export type DailyTotals = Required<Omit<TokenUsage, "costUsd">> & { costUsd?: number };
21
21
  /** 查询结果的一行。estimated:costUsd 是按单价估的,不是 agent 报的 */
22
- export type DailyRow = DailyTotals & { day: string; owner?: string; agent: string; model?: string; estimated?: true };
22
+ export type DailyRow = DailyTotals & { day: string; owner?: string; agent: string; model?: string; estimated?: true; source?: "desktop" | "cli" | "other" };
23
23
 
24
24
  type TotalsRow = { input: number; cache_read: number; cache_write: number; output: number; reasoning: number; cost_usd: number | null };
25
25
 
package/web/css/tasks.css CHANGED
@@ -351,13 +351,7 @@ button.task-run:hover {
351
351
  gap: 12px;
352
352
  }
353
353
 
354
- /* 频率:上面选种类,下面填具体时间 */
355
- .task-freq-row {
356
- display: flex;
357
- flex-direction: column;
358
- gap: 8px;
359
- }
360
-
354
+ /* 执行时间:选择星期和当天的时间 */
361
355
  .task-freq {
362
356
  display: flex;
363
357
  flex-wrap: wrap;
@@ -391,13 +385,16 @@ button.task-run:hover {
391
385
 
392
386
  .day-chips {
393
387
  display: flex;
388
+ flex-wrap: wrap;
389
+ width: 100%;
394
390
  gap: 4px;
395
391
  }
396
392
 
397
393
  .day-chip {
398
- width: 34px;
394
+ min-width: 44px;
395
+ padding: 0 8px;
399
396
  height: 34px;
400
- border-radius: 50%;
397
+ border-radius: 8px;
401
398
  border: 1px solid var(--border);
402
399
  font-size: 13px;
403
400
  }
@@ -408,6 +405,11 @@ button.task-run:hover {
408
405
  color: var(--accent-fg);
409
406
  }
410
407
 
408
+ .day-chip:focus-visible {
409
+ outline: 2px solid var(--accent);
410
+ outline-offset: 2px;
411
+ }
412
+
411
413
  .task-static {
412
414
  font-size: 14px;
413
415
  color: var(--fg-soft);
@@ -135,7 +135,8 @@ export async function usageTab(panel) {
135
135
  const note = h(
136
136
  "div",
137
137
  { class: "muted" },
138
- "金额都是按 API 价格算的参考值,订阅用户实际不按这个扣费:Claude 用它自己报的费用;Codex 不报费用,按模型单价(LiteLLM 公开价格表,每天更新)× Token 估算,不含长上下文加价。从这个版本开始记录,之前的用量没有日期,不计入。",
138
+ "金额都是按 API 价格算的参考值,订阅用户实际不按这个扣费:Agent Loft 的 Claude 用它自己报的费用;Codex 和直接使用的 Claude Code 按模型单价 × Token 估算。Agent Loft 的用量从启用记账起记录。",
139
+ data.localUsageIncluded ? " 包含服务端运行用户下 Claude Code、Codex 桌面端和 CLI 的历史会话记录,按服务器时区统计,Agent Loft 跑的会话不重复算;本机直接用量仅管理员可见。" : "",
139
140
  unpriced ? ` 有 ${fmtCount(unpriced)} Token 认不出模型单价,没算进金额。` : "",
140
141
  );
141
142
  if (!tokens) {
@@ -178,10 +179,15 @@ export async function usageTab(panel) {
178
179
  );
179
180
 
180
181
  const agentName = (id) => S.agents.find((a) => a.id === id)?.label ?? id;
181
- const byAgent = groupBy(rows, (r) => r.agent).map((g) => ({ ...g, label: agentName(g.key) }));
182
+ const sourceNames = { desktop: "桌面端", cli: "CLI", other: "其他" };
183
+ const hasLocal = rows.some((r) => r.source);
184
+ const byAgent = groupBy(rows, (r) => `${r.agent}\n${r.source ?? ""}`).map((g) => {
185
+ const [agent, source] = g.key.split("\n");
186
+ return { ...g, label: `${agentName(agent)}${source ? ` ${sourceNames[source] ?? source}` : hasLocal ? " · Agent Loft" : ""}` };
187
+ });
182
188
  const byModel = groupBy(rows, (r) => r.model ?? "").map((g) => ({ ...g, label: g.key || "未记录模型" }));
183
189
  const byUser = data.admin
184
- ? groupBy(rows, (r) => r.owner ?? "").map((g) => ({ ...g, label: g.key ? data.users[g.key] : "未归属(飞书等)" }))
190
+ ? groupBy(rows.filter((r) => !r.source), (r) => r.owner ?? "").map((g) => ({ ...g, label: g.key ? data.users[g.key] : "未归属(飞书等)" }))
185
191
  : [];
186
192
 
187
193
  fill(
@@ -29,7 +29,7 @@ const FREQS = [
29
29
  ["once", "一次"],
30
30
  ["daily", "每天"],
31
31
  ["weekdays", "工作日(周一到周五)"],
32
- ["weekly", "每周"],
32
+ ["weekly", "每周(可多选)"],
33
33
  ["monthly", "每月"],
34
34
  ["hourly", "每隔几小时"],
35
35
  ["cron", "自定义(cron)"],
@@ -288,7 +288,8 @@ export function openTaskForm(task, preset) {
288
288
 
289
289
  // ---- 频率 ----
290
290
  const sch = { kind: "daily", time: "09:00", days: [1], day: 1, every: 2, minute: 0, expr: "0 9 * * *", at: Date.now() + 3600_000, ...(src.schedule ?? {}) };
291
- if (sch.kind === "weekdays" || sch.kind === "daily") sch.days = sch.days ?? [1];
291
+ if (sch.kind === "daily") sch.days = [...WEEK_ORDER];
292
+ else if (sch.kind === "weekdays") sch.days = [1, 2, 3, 4, 5];
292
293
  const freq = h("select", {}, FREQS.map(([v, label]) => h("option", { value: v, selected: v === sch.kind }, label)));
293
294
  const freqBox = h("div", { class: "task-freq" });
294
295
  const timeInput = () => {
@@ -303,23 +304,25 @@ export function openTaskForm(task, preset) {
303
304
  const at = h("input", { type: "datetime-local", value: toLocalInput(sch.at) });
304
305
  at.oninput = () => (sch.at = new Date(at.value).getTime());
305
306
  parts.push(at);
306
- } else if (sch.kind === "daily" || sch.kind === "weekdays") {
307
- parts.push(timeInput());
308
- } else if (sch.kind === "weekly") {
307
+ } else if (["daily", "weekdays", "weekly"].includes(sch.kind)) {
309
308
  parts.push(
310
309
  h(
311
310
  "div",
312
- { class: "day-chips" },
311
+ { class: "day-chips", role: "group", "aria-label": "执行星期(可多选)" },
313
312
  WEEK_ORDER.map((d) => {
314
- const b = h("button", { type: "button", class: `day-chip${sch.days.includes(d) ? " on" : ""}` }, WEEK_NAME[d]);
313
+ const b = h("button", { type: "button", class: `day-chip${sch.days.includes(d) ? " on" : ""}`, "aria-pressed": String(sch.days.includes(d)) }, `周${WEEK_NAME[d]}`);
315
314
  b.onclick = () => {
316
315
  sch.days = sch.days.includes(d) ? sch.days.filter((x) => x !== d) : [...sch.days, d];
316
+ // 改了预设的星期,就按自选的每周计划保存。
317
+ sch.kind = freq.value = "weekly";
317
318
  b.classList.toggle("on", sch.days.includes(d));
319
+ b.setAttribute("aria-pressed", String(sch.days.includes(d)));
318
320
  };
319
321
  return b;
320
322
  }),
321
323
  ),
322
324
  timeInput(),
325
+ h("span", { class: "freq-word" }, "在选中的星期执行,可多选"),
323
326
  );
324
327
  } else if (sch.kind === "monthly") {
325
328
  const day = h("input", { type: "number", min: "1", max: "31", value: String(sch.day), class: "narrow" });
@@ -338,7 +341,11 @@ export function openTaskForm(task, preset) {
338
341
  }
339
342
  fill(freqBox, parts);
340
343
  };
341
- freq.onchange = renderFreq;
344
+ freq.onchange = () => {
345
+ if (freq.value === "daily") sch.days = [...WEEK_ORDER];
346
+ else if (freq.value === "weekdays") sch.days = [1, 2, 3, 4, 5];
347
+ renderFreq();
348
+ };
342
349
  renderFreq();
343
350
  const freqHint = `按服务端时区(${T.tz || "本地时间"})。两次运行至少隔 15 分钟。`;
344
351
 
@@ -401,7 +408,8 @@ export function openTaskForm(task, preset) {
401
408
  { class: "modal-body task-form" },
402
409
  field("名称", title),
403
410
  field("要做的事", prompt, "需要对比的写清楚怎么判断,比如「和上次的结果比」「版本号比当前的新才算更新」。"),
404
- field("频率", h("div", { class: "task-freq-row" }, freq, freqBox), freqHint),
411
+ field("频率", freq),
412
+ field("执行时间", freqBox, freqHint),
405
413
  field("提醒", notify),
406
414
  target ? field("结果发到", target) : field("结果发到", h("div", { class: "task-static" }, task?.convKey ? `专用对话「${task.convTitle || "对话"}」` : "专用对话(第一次运行时新建,之后都发到这条)")),
407
415
  dedicatedBox,
@@ -425,6 +433,7 @@ export function openTaskForm(task, preset) {
425
433
  ? { kind: "hourly", every: sch.every, minute: sch.minute }
426
434
  : { kind: "cron", expr: sch.expr };
427
435
  if (schedule.kind === "once" && !(schedule.at > Date.now())) return toast("运行时间要在现在之后");
436
+ if (schedule.kind === "weekly" && !schedule.days.length) return toast("至少选择一个执行星期");
428
437
  const dedicated = !target || target.value === "dedicated";
429
438
  if (dedicated && !expert.value) return toast("选一个专家");
430
439
  const payload = {