Repository navigation
Expand file tree
/
Copy pathzusage.py
More file actions
7478 lines (6904 loc) · 361 KB
/
Copy pathzusage.py
File metadata and controls
7478 lines (6904 loc) · 361 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""Token 用量查询库(多宿主,只读)。
宿主(--host / 配置 host / ZUSAGE_HOST,见 §宿主适配):
- zcode(默认)= 本地用量库的 model_usage 逐请求表(路径经 resolve_db_path 镜像宿主 agent 会话库解析,兼容 dataBaseDir 迁移目录并仲裁陈旧候选);
- workbuddy = ~/.workbuddy/workbuddy.db 的 session_usage 会话级表(上下文用量 + credit)。
既可作 CLI(python zusage.py [now|today|days N|sessions [N]|models [days]|workspace 关键词|session id前缀|watch [sec]|host]),
也可被 usage_mcp.py import 为查询库。
"""
import hashlib
import fnmatch
import json
import os
import re
import shlex
import shutil
import sqlite3
import subprocess
import sys
import time
from bisect import bisect_right
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta
from pathlib import Path
# 宿主路径合法值:绝对路径(POSIX 绝对 / Windows 盘符 / UNC)——相对值宿主无稳定基准,不采纳
_DB_BASE_ABS_RE = re.compile(r"^(?:[a-z]:[\\/]|\\\\|/)", re.IGNORECASE)
def _mirror_agent_db_path(value, home):
"""宿主 localUsageEvidence.resolveMirroredSessionDbPath 镜像:~/ 展开与绝对
路径采纳;相对路径按 agent 工作区 cwd 解析、宿主视为无法镜像,返回 None 逐级回落。"""
v = str(value or "").strip()
if not v:
return None
if v.startswith("~/"):
return home / v[2:]
if _DB_BASE_ABS_RE.match(v):
return Path(v)
return None
def _db_write_fresh(path):
"""库写入新鲜度:db.sqlite 与 -wal 的最新 mtime;-shm 只读连接也会更新,不入仲裁。"""
fresh = 0.0
for suffix in ("", "-wal"):
try:
fresh = max(fresh, Path(str(path) + suffix).stat().st_mtime)
except OSError:
pass
return fresh
def _adopt_migration_candidate(candidate, home):
"""issue #294 陈旧迁移库仲裁:3.18.0 宿主源码复核写库方(agent 链)恒写 HOME
默认库、不消费 dataBaseDir,迁移目录库与 HOME 库并存时可能是历史遗留(候选
「存在」不再等于「真实写入位」)。两库并存按写入新鲜度取舍:候选不落后(>=)
才采纳;HOME 库未建仍采纳候选(#279 真迁移:那种用户的候选库才是被持续写入
的一边,或全部数据只在迁移目录)。token_rate.py 内联同款,改动两处同步。"""
home_db = home / ".zcode" / "cli" / "db" / "db.sqlite"
if not home_db.exists():
return True
return _db_write_fresh(candidate) >= _db_write_fresh(home_db)
def _data_base_dir(env=None, home=None):
"""宿主数据根(dataBaseDir)迁移标记:setting.json 的绝对 dataBaseDir 优先,否则 env
ZCODE_DATA_BASE_DIR;读不出/非绝对路径返回空串。resolve_db_path 第 3 级与受管 worktree
根候选(_managed_worktree_roots)共用,改次序三处同步。"""
env = os.environ if env is None else env
home = Path.home() if home is None else Path(home)
try:
file = home / ".zcode" / "v2" / "setting.json"
if file.exists():
raw = json.loads(file.read_text(encoding="utf-8-sig"))
base = str((raw.get("dataBaseDir") if isinstance(raw, dict) else "") or "").strip()
else:
base = ""
except Exception:
base = "" # 损坏按无迁移处理;env 迁移标记不受其连累(与 Node 侧同构)
if not base or not _DB_BASE_ABS_RE.match(base):
base = str(env.get("ZCODE_DATA_BASE_DIR") or "").strip()
return base if base and _DB_BASE_ABS_RE.match(base) else ""
def resolve_db_path(env=None, home=None):
"""本地用量库路径(issue #279 及查漏补缺):镜像宿主 agent 会话库解析
(v3.17.1 onboarding/localUsageEvidence.resolveAgentSessionDbPath——写库方是
agent 进程,其链不消费 dataBaseDir),并兼容 3.17.x 迁移目录两态:
1) env ZCODE_SESSION_DB_PATH / ZCODE_SESSION_DB(宿主双别名按 env 键序取后)
2) <home>/.zcode/cli/config.json 的 storage.sessionDbPath(CLI config 恒在
HOME 不随迁移;缺文件/损坏/相对值忽略继续)
3) setting.json dataBaseDir(绝对)或 ZCODE_DATA_BASE_DIR,且
<base>/.zcode/cli/db/db.sqlite 已存在、写入新鲜度不落后 HOME 默认库——
3.17.x 实测迁移用户库在迁移目录(宿主 copyDataDirectory 不搬 .zcode/cli);
但 3.18.0 宿主源码复核写库方恒写 HOME,「存在」不等于「真实写入位」
(issue #294 陈旧迁移库),两库并存按 db.sqlite/-wal mtime 仲裁(-shm 不算)
4) 默认 <home>/.zcode/cli/db/db.sqlite
与宿主的差异:宿主「无法确定」(相对路径/project 级覆盖)按未知跳过证据源,
本查询链必须落到一个库,故逐级回落;project 级覆盖同宿主属已知限制。
token_rate.py 的默认路径与本函数同源,改动两处同步。"""
env = os.environ if env is None else env
home = Path.home() if home is None else Path(home)
picked = ""
for key, value in env.items():
if key in ("ZCODE_SESSION_DB_PATH", "ZCODE_SESSION_DB"):
picked = value or "" # 宿主双别名按 env 键序取后(含空值,空即弃用该来源)
candidate = _mirror_agent_db_path(picked, home)
if candidate:
return candidate
try:
file = home / ".zcode" / "cli" / "config.json"
if file.exists():
raw = json.loads(file.read_text(encoding="utf-8-sig"))
storage = raw.get("storage") if isinstance(raw, dict) else None
candidate = _mirror_agent_db_path(
storage.get("sessionDbPath") if isinstance(storage, dict) else None, home)
if candidate:
return candidate
except Exception:
pass # 缺文件/损坏忽略(宿主读不出按默认),不拖垮查询链
base = _data_base_dir(env, home)
if base:
candidate = Path(base) / ".zcode" / "cli" / "db" / "db.sqlite"
if candidate.exists() and _adopt_migration_candidate(candidate, home):
return candidate
return home / ".zcode" / "cli" / "db" / "db.sqlite"
DB_PATH = resolve_db_path()
CONFIG_PATH = Path(__file__).parent / "config.json"
try:
import token_pricing as _pricing
except ImportError: # 旧运行目录未部署新文件:预估费用整特性降级,快照无 cost/fx 字段
_pricing = None
try:
from usage_stats import (
MIN_GEN_MS as _TPS_MIN_GEN_MS,
MAX_GEN_MS as _TPS_MAX_GEN_MS,
hides_reasoning as _shared_hides_reasoning,
query_first_token_covers as _query_first_token_covers,
row_gen_ms as _shared_row_gen_ms,
)
except ImportError: # 远端单文件直跑等无 usage_stats.py 场景:本模块内联兜底
_TPS_MIN_GEN_MS = 200
_TPS_MAX_GEN_MS = 3_600_000
_shared_hides_reasoning = None
_query_first_token_covers = None
_shared_row_gen_ms = None
def load_config():
cfg = {"context_window": 128000, "poll_ms": 2000}
if CONFIG_PATH.exists():
try:
cfg.update(json.loads(CONFIG_PATH.read_text(encoding="utf-8")))
except Exception:
pass
return cfg
# ---------- 宿主适配(host):ZCode / WorkBuddy ----------
# 本项目原生面向 ZCode:用量是 ~/.zcode/cli/db/db.sqlite 里 model_usage 的逐请求行
# (input/output/思考/缓存/耗时齐备,可算速度、工具调用与预估费用)。
# WorkBuddy 是另一套宿主:用量落在 ~/.workbuddy/workbuddy.db 的 session_usage 会话级表,
# 只有「当前上下文已用 token + 每请求 credit 累计」,**没有**逐请求 token 分项与耗时。
# 因此两个宿主的指标集合不同:由 HOST_CAPS 声明,快照/报表按能力降级,
# 不把「取不到的 0」当真实值展示(速度、工具、费用在 workbuddy 上标为不可用)。
HOST_ZCODE, HOST_WORKBUDDY = "zcode", "workbuddy"
HOSTS = (HOST_ZCODE, HOST_WORKBUDDY)
_HOST_ALIASES = {"zcode": HOST_ZCODE, "z-code": HOST_ZCODE, "workbuddy": HOST_WORKBUDDY,
"work-buddy": HOST_WORKBUDDY, "wb": HOST_WORKBUDDY}
_HOST_LABELS = {HOST_ZCODE: "ZCode", HOST_WORKBUDDY: "WorkBuddy"}
HOST_CAPS = {
HOST_ZCODE: {"tokens": True, "tps": True, "tools": True, "cost": True,
"context": True, "credits": False, "transcript": True},
# WorkBuddy 的逐请求用量在会话正文里(providerData.rawUsage),因此 token/速度/工具
# 都可得;费用靠 token_pricing 的牌价,未收录的模型按「不可得」处理(见 host_caps
# 的运行时回退与 wb_usage.model_cost)。
HOST_WORKBUDDY: {"tokens": True, "tps": True, "tools": True, "cost": True,
"context": True, "credits": True, "transcript": True},
}
_HOST_OVERRIDE = None # 进程内最高优先(CLI --host;MCP 的 host 参数按次走 connect,不经这里)
def normalize_host(value):
"""宿主名归一(大小写/别名);空值返回 None,未知值也返回 None(调用方给提示)。"""
key = str(value or "").strip().lower()
return _HOST_ALIASES.get(key) if key else None
def set_host(value):
"""进程内覆盖当前宿主(CLI --host、MCP 参数);None/"" 清除覆盖。"""
global _HOST_OVERRIDE
host = normalize_host(value)
if str(value or "").strip() and host is None:
raise ValueError(f"unknown host: {value!r} (expected one of {', '.join(HOSTS)})")
_HOST_OVERRIDE = host
def _sub_cfg(cfg, name):
"""config.<name> 下的对象;缺省/损坏一律当空 dict(不因坏配置整个查询失败)。"""
sub = cfg.get(name) if isinstance(cfg, dict) else None
return sub if isinstance(sub, dict) else {}
def host_config():
"""宿主相关配置(只取 host / hosts 两键):脚本目录 config.json → 标准数据目录
config.json,后者只补前者缺的键(与 _load_lang 同款两跳——标准安装的 config 在
运行目录,不在插件目录)。不改 load_config() 的既有语义:context_window / poll_ms
仍只读脚本目录,避免顺带改变老行为。"""
merged = {}
for base in (CONFIG_PATH, Path.home() / ".zcode" / "zcode-token-usage-statusbar" / "config.json"):
try:
data = json.loads(Path(base).read_text(encoding="utf-8"))
except (OSError, ValueError):
continue
if not isinstance(data, dict):
continue
if isinstance(data.get("host"), str): # 先到者优先,后面只补缺
merged.setdefault("host", data["host"])
for key in ("hosts", "agents"): # 同款逐键合并:先到者优先,后者只补缺
sub = data.get(key)
if isinstance(sub, dict):
acc = merged.setdefault(key, {})
for name, entry in sub.items():
if isinstance(entry, dict) and name not in acc:
acc[name] = entry
return merged
def _effective_host_cfg(cfg=None):
"""生效的宿主配置 = 文件两跳结果,再叠调用方显式传入的 cfg(MCP/快照自己的 cfg 优先)。"""
eff = host_config()
if isinstance(cfg, dict):
if isinstance(cfg.get("host"), str) and cfg["host"].strip():
eff["host"] = cfg["host"]
for key in ("hosts", "agents"):
sub = cfg.get(key)
if isinstance(sub, dict):
acc = dict(eff.get(key) or {})
acc.update({k: v for k, v in sub.items() if isinstance(v, dict)})
eff[key] = acc
return eff
def workbuddy_db_path(cfg=None):
"""WorkBuddy 用量库:环境变量 ZUSAGE_WORKBUDDY_DB > config.hosts.workbuddy.db_path > 默认。
允许带 ~ 与 %VAR%(Windows)/ $VAR(POSIX)展开,方便多机共用同一份配置。"""
raw = os.environ.get("ZUSAGE_WORKBUDDY_DB") or _sub_cfg(
_sub_cfg(_effective_host_cfg(cfg), "hosts"), "workbuddy").get("db_path")
if isinstance(raw, str) and raw.strip():
return Path(os.path.expandvars(raw.strip())).expanduser()
return Path.home() / ".workbuddy" / "workbuddy.db"
def zcode_db_path(cfg=None):
"""ZCode 用量库:config.hosts.zcode.db_path(可选,覆盖默认)> 模块级 DB_PATH。
默认路径仍走 DB_PATH 这个可被测试/调用方替换的模块量(既有约定,不改成不可变常量)。"""
raw = _sub_cfg(_sub_cfg(_effective_host_cfg(cfg), "hosts"), "zcode").get("db_path")
if isinstance(raw, str) and raw.strip():
return Path(os.path.expandvars(raw.strip())).expanduser()
return Path(DB_PATH)
def host_db_path(host=None, cfg=None):
host = normalize_host(host) or resolve_host(cfg=cfg)
return workbuddy_db_path(cfg) if host == HOST_WORKBUDDY else zcode_db_path(cfg)
def resolve_host(override=None, cfg=None):
"""宿主判定优先级:显式 override > 环境变量 ZUSAGE_HOST > config.host > 默认 zcode。
"auto" 是可选的自动探测(ZCode 库存在即选 zcode,否则 ZCode 库缺失且 WorkBuddy 库
存在时选 workbuddy)。**默认不用 auto**:装了 WorkBuddy 的机器上原 ZCode 行为必须
一字不变,想按机器自动选宿主的用户显式写 "host": "auto"。"""
host = normalize_host(override) or normalize_host(_HOST_OVERRIDE)
if host:
return host
host = normalize_host(os.environ.get("ZUSAGE_HOST"))
if host:
return host
eff = _effective_host_cfg(cfg)
choice = normalize_host(eff.get("host"))
if choice:
return choice
# 没有任何显式配置时跟随客户端:WorkBuddy 构建默认读 WorkBuddy 库
# (ZCode 构建里 detect_agent 恒为 zcode,行为与以前完全一致)。
if detect_agent() == AGENT_WORKBUDDY:
return HOST_WORKBUDDY
if str(eff.get("host") or "").strip().lower() == "auto":
if zcode_db_path(cfg).exists():
return HOST_ZCODE
if workbuddy_db_path(cfg).exists():
return HOST_WORKBUDDY
return HOST_ZCODE
def host_source(override=None, cfg=None):
"""当前宿主的判定来源(host 子命令/诊断用):cli | env | config | agent | auto | default。"""
if normalize_host(override) or normalize_host(_HOST_OVERRIDE):
return "cli"
if normalize_host(os.environ.get("ZUSAGE_HOST")):
return "env"
eff = _effective_host_cfg(cfg)
if normalize_host(eff.get("host")):
return "config"
if detect_agent() == AGENT_WORKBUDDY:
return "agent"
if str(eff.get("host") or "").strip().lower() == "auto":
return "auto"
return "default"
def host_label(host=None):
return _HOST_LABELS.get(normalize_host(host) or resolve_host(), HOST_ZCODE)
def host_caps(host=None):
"""宿主能力表。WorkBuddy 的逐请求指标依赖会话正文解析、费用还依赖价表,
两者都是可选文件(精简部署/旧包里可能没有)——按运行时实际可用性回退,
不承诺拿不到的指标。ZCode 侧全静态,与以前一致。"""
key = normalize_host(host) or resolve_host()
caps = dict(HOST_CAPS.get(key, HOST_CAPS[HOST_ZCODE]))
if key == HOST_WORKBUDDY:
if _wb_usage is None:
caps.update(tokens=False, tps=False, tools=False, transcript=False)
if _wb_usage is None or getattr(_wb_usage, "_pricing", None) is None:
caps["cost"] = False
return caps
def host_of(con):
"""连接所属宿主(连接由 connect() 打标记;外部自建连接按当前判定回退)。"""
return getattr(con, "zusage_host", None) or resolve_host()
class _HostConn(sqlite3.Connection):
"""带宿主标记的连接:render_*/snapshot 按连接分派,不按全局猜测——
serve 常驻进程复用同一连接跨请求,标记跟着连接走才不会张冠李戴。"""
zusage_host = HOST_ZCODE
def _open_ro(path, probe):
"""只读连接优先;WAL shm 不可用时退回普通连接(全程只 SELECT)。
fallback 前先确认文件存在:sqlite3.connect 对不存在的路径会新建空库,
可能与尚未初始化的宿主产生交互(v32 审查修复)。"""
path = Path(path)
try:
con = sqlite3.connect(f"file:{path.as_posix()}?mode=ro", uri=True, timeout=3,
factory=_HostConn)
try:
con.execute(probe).fetchone()
except BaseException:
# 探测失败就显式关掉这条连接再抛/再换:连接对象与语句缓存互相引用、只能等循环 GC 回收,
# Windows 下这段时间库文件保持占用(WinError 32),调用方的临时目录清理会炸。
con.close()
raise
except sqlite3.OperationalError:
if not path.exists():
raise
con = sqlite3.connect(str(path), timeout=3, factory=_HostConn)
con.row_factory = sqlite3.Row
return con
def connect(host=None):
"""按宿主打开只读连接;连接上带 zusage_host 标记供上层分派。"""
target = resolve_host(host)
if target == HOST_WORKBUDDY:
con = _open_ro(workbuddy_db_path(), "select 1 from session_usage limit 1")
else:
con = _open_ro(zcode_db_path(), "select 1 from model_usage limit 1")
con.zusage_host = target
return con
# ---------- 宿主客户端(agent)与启动策略 ----------
# host(读哪个库)与 agent(在哪个客户端里跑、用哪种展示)是两件事:
# 同一份代码被两个客户端安装,但浮层形态不同——ZCode 走原来的 asar 注入,
# WorkBuddy 没有 asar 注入链,改走 CDP(客户端自带 --remote-debugging-port)。
# 启动策略集中在这里,调用方(MCP/hook)只问「这个 agent 该干什么」。
AGENT_ZCODE, AGENT_WORKBUDDY, AGENT_CLI = "zcode", "workbuddy", "cli"
AGENTS = (AGENT_ZCODE, AGENT_WORKBUDDY)
AGENT_STRATEGY = {
AGENT_ZCODE: {"overlay": "asar", "mcp": True, "commands": True,
"rate_line": True, "updater": True},
AGENT_WORKBUDDY: {"overlay": "cdp", "mcp": True, "commands": True,
"rate_line": False, "updater": False},
AGENT_CLI: {"overlay": None, "mcp": True, "commands": True,
"rate_line": False, "updater": False},
}
_OVERLAY_MODES = ("asar", "cdp", "off")
def detect_agent(env=None):
"""当前客户端。判定顺序(前者优先,全部可解释):
1. ZUSAGE_AGENT 显式指定(调试/测试);
2. 插件根环境变量:CODEBUDDY_PLUGIN_ROOT → WorkBuddy,ZCODE_PLUGIN_ROOT → ZCode;
3. 插件目录里的 manifest 目录:.codebuddy-plugin → WorkBuddy,
.zcode-plugin/.claude-plugin → ZCode;
4. 默认 zcode——老安装(独立安装器 + 运行目录)没有 plugin 根变量,必须保持不变。
刻意不看 CLIENT_INFO_PLATFORM 这类客户端指纹:它会被子进程继承,
在 WorkBuddy 的终端里跑 ZCode 那份代码时会造成误判。"""
env = env if env is not None else os.environ
explicit = _agent_key(env.get("ZUSAGE_AGENT"))
if explicit:
return explicit
if str(env.get("CODEBUDDY_PLUGIN_ROOT") or "").strip():
return AGENT_WORKBUDDY
if str(env.get("ZCODE_PLUGIN_ROOT") or "").strip():
return AGENT_ZCODE
here = Path(__file__).parent
if (here / ".codebuddy-plugin").is_dir():
return AGENT_WORKBUDDY
if (here / ".zcode-plugin").is_dir() or (here / ".claude-plugin").is_dir():
return AGENT_ZCODE
return AGENT_ZCODE
def _agent_key(value):
"""agent 名归一:zcode/workbuddy 走别名表,cli/terminal 单列(不在 host 别名里)。"""
key = str(value or "").strip().lower()
if key in ("cli", "terminal", "none", "headless"):
return AGENT_CLI
return normalize_host(key)
def agent_strategy(agent=None):
"""该客户端的启动策略(副本,调用方可改):overlay=asar|cdp|None、mcp、commands、
rate_line(逐问速率行只有 ZCode 有渲染桥)、updater(插件更新器只有 ZCode 插件链有)。"""
key = _agent_key(agent) or detect_agent()
return dict(AGENT_STRATEGY.get(key, AGENT_STRATEGY[AGENT_CLI]))
def overlay_mode(agent=None, cfg=None):
"""生效的浮层模式:config.agents.<agent>.overlay(true/false/asar/cdp/off)覆盖策略表。
false/off → None(不启动);true → 策略表默认值。"""
key = _agent_key(agent) or detect_agent()
raw = _sub_cfg(_sub_cfg(_effective_host_cfg(cfg), "agents"), key).get("overlay")
default = AGENT_STRATEGY.get(key, AGENT_STRATEGY[AGENT_CLI])["overlay"]
if isinstance(raw, bool):
return default if raw else None
if isinstance(raw, str):
value = raw.strip().lower()
if value in ("off", "none", "no", "false", "0"):
return None
if value in ("asar", "cdp"):
return value
if value in ("on", "auto", "true", "1"):
return default
return default
def node_candidates():
"""node 可执行候选:PATH 优先,其次 WorkBuddy 自带(版本目录降序)。
浮层注入器只在 WorkBuddy 用,自带 node 一定存在且带全局 WebSocket(22+)。"""
found, seen = [], set()
def add(path):
key = os.path.normcase(os.path.abspath(str(path)))
if key not in seen and os.path.isfile(str(path)):
seen.add(key)
found.append(str(path))
add(shutil.which("node") or "")
home = Path(os.environ.get("WORKBUDDY_HOME") or (Path.home() / ".workbuddy"))
versions = home / "binaries" / "node" / "versions"
if versions.is_dir():
for d in sorted(versions.iterdir(), reverse=True):
add(d / ("node.exe" if os.name == "nt" else "bin/node"))
return found
def overlay_entrypoint():
"""CDP 浮层注入器路径(与 usage_mcp.py 同目录;ZCode 构建里不存在)。"""
return Path(__file__).parent / "wb-overlay.cjs"
def _ts(ms):
return datetime.fromtimestamp(ms / 1000) if ms else None
def _day_start(d=None):
d = d or datetime.now()
return d.replace(hour=0, minute=0, second=0, microsecond=0)
def _epoch_ms(dt):
return int(dt.timestamp() * 1000)
def _speed_day_bounds(start_date, n_days):
"""速度日历的本地自然日边界表:[start_date 00:00 … start_date+n_days 00:00] 共
n_days+1 个 epoch ms,升序。逐行 `datetime.fromtimestamp(ct/1000).date()` 的等价
替换:按 ct 二分定位日序号(bisect_right(bounds, ct) - 1),省掉每行一次本地时区
datetime 构造。边界必须经本地日历推导(_epoch_ms=本地墙钟反向),禁止固定
86400000 整除推日——DST/月末/跨年 correctness 由标准库保证(_speed_days 同一口径)。"""
day = datetime(start_date.year, start_date.month, start_date.day)
bounds = []
for _ in range(n_days + 1):
bounds.append(_epoch_ms(day))
day += timedelta(days=1)
return bounds
def _load_lang():
"""CLI/MCP 输出语言:config.json 的 "lang"(zh/en,缺省 zh)——与安装器/监控窗口同源。
查找顺序:脚本目录(--dev/仓库直跑)→ 标准数据目录(标准安装的 config 不在脚本目录)。"""
for base in (CONFIG_PATH,
Path.home() / ".zcode" / "zcode-token-usage-statusbar" / "config.json"):
try:
lang = json.loads(base.read_text(encoding="utf-8")).get("lang")
if lang in ("zh", "en"):
return lang
except (OSError, ValueError):
pass
return "zh"
_LANG = _load_lang()
def L(zh, en):
"""双语输出(与 install.py / overlay.js 的 L 同款约定)。"""
return en if _LANG == "en" else zh
def fmt(n):
n = n or 0
if n >= 1_000_000_000:
return f"{n / 1e9:.2f}B"
if n >= 1_000_000:
return f"{n / 1e6:.2f}M"
if n >= 1_000:
return f"{n / 1e3:.1f}K"
return str(n)
SESSION_TIMEOUT_MS = 30 * 60 * 1000 # 最近30分钟有请求视为活跃会话
# _TPS_MIN_GEN_MS / _TPS_MAX_GEN_MS 已从 usage_stats 导入(远端单文件直跑带内联兜底)
_TPS_LOOKBACK = 20 # first_token_at 缺失时向前找有效请求的扫描条数上限
_SPEED_SEGS_MAX = 10 # 速度柱状图分段上限(v240 用户规格:17→10)
# v253 速度 Tooltip 范围/时间/维度筛选:一次有界扫描出统一轮表(真实库),渲染端据此
# 推导全部 20 种组合,快照帧不随 hover 反复查询。上限是性能护栏,不是伪造补位数据。
_SPEED_HISTORY_MAX_TURNS = 6000 # 扫描窗口数与输出轮数上限(防超大库把 JSON 帧撑大)
_SPEED_HISTORY_TTL_MS = 2000 # 2s 短缓存(常驻泵 1.5s 拉一次,同帧同库免重扫)
# v257:全库扫描偶发失败(完成轮瞬间的 WAL 写窗口/连接重建)时回退最近一次成功轮表的
# 陈旧上限。轮表是历史统计,分钟级陈旧远好于整帧缺字段让 Tooltip 闪回旧版;下一帧成功即刷新。
_SPEED_HISTORY_STALE_MS = 10 * 60 * 1000
_SPEED_CACHE = {} # 独立缓存:不与 _cached_agg 的 scan/today 共用上限 8 的 _AGG_CACHE
_SPEED_WM = {} # 轮表缓存的 model_usage 水位(TTL 过期后水位未变续用,见 _WM_MAX_AGE_MS)
# v384(specs/speed-tooltip-v3.md §1.2):全历史按本地自然日聚合,解决 6000 轮截断。
_SPEED_DAYS_MAX_DAYS = 550 # 覆盖窗口:截至今天(含)往前 N 个本地日;truncated 时渲染端明示
_SPEED_DAYS_MAX_MODELS = 8 # 日桶 msl 每模型条目上限(超出 capFlag=1,日级总量仍精确)
_SPEED_DAYS_TK_DAYS = 90 # v457:日桶 tk 每模型 token 只带最近 N 个本地日(spec §8 帧体积预算)
_DAYS_CACHE = {} # speed_days 缓存:与轮表 _SPEED_CACHE 同款独立缓存(不挤 _AGG_CACHE)
_DAYS_WM = {} # speed_days 缓存的 model_usage 水位(同款续用语义)
_AGG_TTL_MS = 2000 # 聚合短缓存:今日合计/会话池是慢变量,2s 陈旧无感;泵 1.5s 拉一次省约一半全表聚合
_AGG_CACHE = {}
# 卡顿治理(specs/perf-lag-reduction.md §8):model_usage 水位延长聚合缓存。
# 宿主请求完成才一次性 INSERT、运行中无行(实测零 running 行),流式生成期间 model_usage 恒定不变,
# 但纯 TTL(2s) 仍每 ~3s 全量重算项目累计/速度轮表/今日合计(大库未命中帧 0.7~1.1s,占 25~45% 单核)。
# 现在 TTL 过期后若水位 (库身份, max(rowid)) 未变且距上次计算 <_WM_MAX_AGE_MS,继续复用;一旦有新请求
# 完成水位即变、TTL 一过立即重算(TTL 内行为不变)。水位未覆盖的变化(会话改名、尾行被删后 rowid 复用等)
# 由 _WM_MAX_AGE_MS 兜底。max(rowid) 是 B 树末端查找(微秒级),不做额外记忆——精确优先。
# 内存库/桩连接取不到水位 → 退回纯 TTL。
_WM_MAX_AGE_MS = 20 * 1000
_AGG_WM = {}
def _usage_watermark(con):
"""(库身份, max(rowid));取不到(内存库/列漂移/桩连接)返回 None。"""
try:
dbkey = _db_cache_key(con)
if dbkey is None:
return None
return (dbkey, con.execute("select max(rowid) from model_usage").fetchone()[0])
except Exception:
return None
def _wm_alive(wm_store, key, hit, con, now):
"""TTL 已过期后的二次判定:水位未变且未超 _WM_MAX_AGE_MS 则缓存仍可复用。"""
if con is None or now - hit[0] >= _WM_MAX_AGE_MS:
return False
old = wm_store.get(key)
return old is not None and _usage_watermark(con) == old
class _WmFn:
"""携带连接的计算闭包:让 _cached_agg 保持 (key, fn) 二参签名(既有测试以二参 lambda 替身该函数),
同时把水位校验所需的连接带进来。未包装的 fn(无连接)退回纯 TTL。"""
__slots__ = ("fn", "wm_con")
def __init__(self, fn, con):
self.fn = fn
self.wm_con = con
def __call__(self):
return self.fn()
def _cached_agg(key, fn):
con = getattr(fn, "wm_con", None)
now = int(time.time() * 1000)
hit = _AGG_CACHE.get(key)
if hit:
if now - hit[0] < _AGG_TTL_MS:
return hit[1]
if _wm_alive(_AGG_WM, key, hit, con, now):
return hit[1]
wm = _usage_watermark(con) if con is not None else None # 必须先于 fn():期间新写入只会让存下的水位偏旧→下次重算(安全方向)
val = fn()
if len(_AGG_CACHE) > 8:
_AGG_CACHE.clear() # 键固定只有几个,正常到不了;保险防膨胀
_AGG_WM.clear()
_AGG_CACHE[key] = (now, val)
if wm is None:
_AGG_WM.pop(key, None)
else:
_AGG_WM[key] = wm
return val
_PROJ_CACHE = {}
_PROJ_WM = {}
def _db_cache_key(con):
"""v177:项目累计缓存的库身份键——文件库取 (path, dev, ino),同路径换文件(删除重建/
被替换)键随 stat 变化;内存库(:memory:,测试夹具)返回 None 不做跨调用缓存。
sqlite3.Connection 不支持弱引用,连接级缓存不可行;按文件身份跨连接共享是安全的
(同一文件即同一数据库,TTL 2s 约束陈旧度)。"""
try:
for row in con.execute("pragma database_list").fetchall():
if row[1] == "main":
path = row[2]
break
else:
return None
except (sqlite3.Error, AttributeError, TypeError):
# 桩连接(测试替身游标无 fetchall / Mock 返回非序列):契约本就是「取不到库身份→None→
# 调用方退回不缓存」。_usage_watermark 同款宽捕获;这里补上以免新增调用点击穿整帧快照。
return None
if not path:
return None
try:
st = os.stat(path)
except OSError:
return None
return (path, st.st_dev, st.st_ino)
def _cached_project(dbkey, key, fn, con=None):
"""v177:_project_usage 专用缓存,键挂库文件身份 + (project_id, 目录键)——v502 起键不再带 with_models 位
(轻量行与详细行共用一次基础聚合,轻量行在出口剥掉 models)——常驻泵
跨请求复用连接时吃到 2s TTL 的跨帧免重扫(实测无缓存大库单项目聚合 ~40ms,池内多行
一帧可达数百 ms)。独立于 _AGG_CACHE:项目键随使用增长,混进共享缓存会把它顶过上限
触发整体 clear、连带丢掉 scan/today 热条目。"""
now = int(time.time() * 1000)
full = (dbkey, key)
hit = _PROJ_CACHE.get(full)
if hit:
if now - hit[0] < _AGG_TTL_MS:
return hit[1]
if _wm_alive(_PROJ_WM, full, hit, con, now): # 流式期间 model_usage 恒定:水位未变续用(见 _WM_MAX_AGE_MS)
return hit[1]
wm = _usage_watermark(con) if con is not None else None
val = fn()
if len(_PROJ_CACHE) > 64:
_PROJ_CACHE.clear() # 保险防膨胀:清空只损失缓存,不损正确性
_PROJ_WM.clear()
_PROJ_CACHE[full] = (now, val)
if wm is None:
_PROJ_WM.pop(full, None)
else:
_PROJ_WM[full] = wm
return val
# ---------- 推送指纹(specs/perf-lag-reduction.md 规则 27) ----------
# speed_history(~160KB)与 all_projects(~6KB)是桌面快照帧里最大的两个可选字段,常驻进程
# 命中 _SPEED_CACHE / _PROJ_CACHE 时逐帧把同一对象原样重发。这里给值对象配一个不透明 rev:
# 同一常驻进程内「值被重算才变、命中缓存不变」——缓存命中返回同一对象 → 同一 rev;真算产出
# 新对象 → 新 rev;查询失败回退 _speed_history_stale 的旧对象 → 旧 rev。rev 绑定对象身份并持
# 强引用(每字段至多 _REV_MEM_MAX 条,超出丢最旧的,只影响「能否省一次全量」不影响正确性)。
# 进程启动随机量(pid + 首次使用时刻 + 随机字节)+ 进程内单调计数:常驻进程重启、一次性 json
# 与远端子进程之间绝不重复,新进程首帧必为全量。只进桌面快照帧(serve 与桌面 json),
# CLI 报表 / MCP / 远端子查询 / 手机中继 lean 请求的 stdout 契约不带。不落盘。
_REV_MEM_MAX = 4
_REV_NONCE = None
_REV_SEQ = 0
_REV_MEM = {} # 字段名 → [(val, rev), ...](新者在前)
def _rev_remember(field, val, rev):
lst = _REV_MEM.setdefault(field, [])
lst.insert(0, (val, rev))
del lst[_REV_MEM_MAX:]
def _rev_new(field, val):
"""为 val 分配一个新 rev 并登记(真算路径调用;返回 rev)。"""
global _REV_NONCE, _REV_SEQ
if _REV_NONCE is None: # 首次使用时取进程启动随机量(不新增顶层 import:os/time 已在)
try:
rand = os.urandom(4).hex()
except Exception:
rand = "%x" % id(_REV_MEM)
_REV_NONCE = "%x.%x.%s" % (os.getpid() & 0xFFFFFFFF, int(time.time() * 1000) & 0xFFFFFFFFFFFF, rand)
_REV_SEQ += 1
rev = "%s.%x" % (_REV_NONCE, _REV_SEQ)
if val is not None:
_rev_remember(field, val, rev)
return rev
def _rev_of(field, val):
"""val 当前的 rev:已登记的同一对象返回原 rev,未见过的对象(如被逐出登记表的旧缓存值)
现分配一个——分配只会让主进程多送一次全量,绝不会把新值说成旧值。"""
if val is None:
return None
for seen, rev in _REV_MEM.get(field, ()):
if seen is val:
return rev
return _rev_new(field, val)
def _with_rev(field, val):
"""{field: val[, field_rev: rev}];val 为 None(降级省略)时返回空映射,省略语义不变。"""
if val is None:
return {}
rev = _rev_of(field, val)
return {field: val} if rev is None else {field: val, field + "_rev": rev}
_SESS_CACHE = {}
_SESS_WM = {}
# ---------- 进程内增量聚合引擎(specs/perf-lag-reduction.md §20) ----------
# 针对 GB 级大库无 completed_at 索引导致水位变化后 7 项全表扫描冷帧 ~1s 的问题:
# 常驻进程按 dbkey 维护增量累加器,仅拉取 model_usage WHERE rowid > last_rowid 的新行。
# 发生 DELETE / 重建 / 跨日 / covers 变化 / 超期时自动全量重建;内存库或桩连接自动退回原全量路径。
_INCR_STATES = {}
_INCR_REBUILD_MS = 5 * 60 * 1000
_INCR_MAX_STATES = 4
_INCR_DELTA_COLS = (
"rowid, id, session_id, turn_id, model_id, provider_id, status, query_source, "
"input_tokens, output_tokens, reasoning_tokens, cache_read_input_tokens, "
"cache_creation_input_tokens, computed_total_tokens, tool_call_count, retry_count, "
"duration_ms, time_to_first_token_ms, started_at, first_token_at, completed_at"
)
class _IncrState:
__slots__ = (
"dbkey", "built_at", "last_rowid", "last_rowid_id", "row_count",
"today_start_ms", "today_end_ms", "today_date", "covers", "ready",
"scan_map", "provfbk",
"today_agg", "today_rate_out", "today_rate_ms", "today_per_model",
"today_models", "today_mnames",
"ap_sess_agg", "ap_sess_groups", "ap_sess_mnames",
"ap_rate_out", "ap_rate_ms", "ap_per_model",
"sh_turns", "sh_truncated",
"sd_days", "sd_truncated", "sd_start_ms", "sd_start_date", "sd_today_date",
"sd_bounds",
)
def __init__(self, dbkey, now_ms, last_rowid, last_rowid_id, row_count,
today_start_ms, today_end_ms, today_date, covers):
self.dbkey = dbkey
self.built_at = now_ms
self.last_rowid = last_rowid
self.last_rowid_id = last_rowid_id
self.row_count = row_count
self.today_start_ms = today_start_ms
self.today_end_ms = today_end_ms
self.today_date = today_date
self.covers = covers
self.ready = set()
self.scan_map = None
self.provfbk = (-1, -1, "")
self.today_agg = None
self.today_rate_out = 0
self.today_rate_ms = 0
self.today_per_model = None
self.today_models = None
self.today_mnames = None
self.ap_sess_agg = None
self.ap_sess_groups = None
self.ap_sess_mnames = None
self.ap_rate_out = 0
self.ap_rate_ms = 0
self.ap_per_model = None
self.sh_turns = None
self.sh_truncated = False
self.sd_days = None
self.sd_truncated = 0
self.sd_start_ms = 0
self.sd_start_date = None
self.sd_today_date = None
self.sd_bounds = None
def _probe(self, con, anchor_rowid=None):
"""一致性探针:max(rowid) / count(*) / 锚点 id 三标量子查询合并为一条语句
(一次读快照、一次往返;单语句内共享同一快照,一致性不弱于旧的多语句序列)。
anchor_rowid 缺省取建态锚点(max(rowid) 自身);sync 路径传 last_rowid——旧实现
先在 max(rowid) 处查锚点又在 sync 里重查 last_rowid 锚点,两次往返白花。删除检测
依赖 count(*)(覆盖索引全扫,必要成本保留)。"""
if anchor_rowid is None:
row = con.execute(
"""select (select max(rowid) from model_usage),
(select count(*) from model_usage),
(select id from model_usage
where rowid = (select max(rowid) from model_usage))""").fetchone()
else:
row = con.execute(
"""select (select max(rowid) from model_usage),
(select count(*) from model_usage),
(select id from model_usage where rowid = ?)""",
(anchor_rowid,)).fetchone()
max_rid = (row[0] or 0) if row else 0
cnt = (row[1] or 0) if row else 0
rid_id = row[2] if row else None
return max_rid, cnt, rid_id
def sync(self, con):
now_ms = int(time.time() * 1000)
day = _day_start()
t_start = _epoch_ms(day)
t_end = _epoch_ms(day + timedelta(days=1))
t_date = day.date()
covers = _provider_first_token_covers(con)
if (now_ms - self.built_at >= _INCR_REBUILD_MS
or t_date != self.today_date
or t_start != self.today_start_ms
or covers != self.covers):
return False
max_rid, cnt, anchor_id = self._probe(con, self.last_rowid)
if max_rid < self.last_rowid:
return False
if max_rid == self.last_rowid:
if cnt != self.row_count:
return False
if self.last_rowid > 0 and (anchor_id is None or anchor_id != self.last_rowid_id):
return False
return True
# max_rid > self.last_rowid: 校验旧水位锚点并拉取增量行
if self.last_rowid > 0 and (anchor_id is None or anchor_id != self.last_rowid_id):
return False
delta = con.execute(
f"select {_INCR_DELTA_COLS} from model_usage where rowid > ? and rowid <= ? order by rowid asc",
(self.last_rowid, max_rid),
).fetchall()
if self.row_count + len(delta) != cnt:
return False
if delta:
if "scan" in self.ready:
self._apply_scan(delta)
if "provfbk" in self.ready:
self._apply_provfbk(delta)
if "today" in self.ready:
self._apply_today(delta)
if "all_projects" in self.ready:
self._apply_all_projects(delta)
if "speed_history" in self.ready:
self._apply_speed_history(delta)
if "speed_days" in self.ready:
self._apply_speed_days(delta)
self.last_rowid_id = delta[-1][1]
self.last_rowid = max_rid
self.row_count = cnt
return True
# ---- 1. scan ----
def get_scan(self, con):
if "scan" not in self.ready:
m = {}
for r in con.execute(
"select session_id, max(coalesce(completed_at, 0)) from model_usage where rowid <= ? group by session_id",
(self.last_rowid,),
):
m[r[0]] = r[1]
self.scan_map = m
self.ready.add("scan")
return list(self.scan_map.items())
def _apply_scan(self, delta):
m = self.scan_map
for r in delta:
sid, ct = r[2], r[20] or 0
prev = m.get(sid)
if prev is None or ct > prev:
m[sid] = ct
# ---- 2. provfbk ----
def get_provfbk(self, con):
if "provfbk" not in self.ready:
row = con.execute(
"""select completed_at, rowid, provider_id from model_usage
where rowid <= ? and status='completed'
and (query_source is null or query_source='main_turn')
and provider_id like 'account:%'
order by completed_at desc, rowid desc limit 1""",
(self.last_rowid,),
).fetchone()
self.provfbk = ((row[0] or -1), row[1], row[2] or "") if row else (-1, -1, "")
self.ready.add("provfbk")
return self.provfbk[2]
def _apply_provfbk(self, delta):
best_ct, best_rid, best_pid = self.provfbk
for r in delta:
if r[6] != "completed":
continue
qs = r[7]
if qs is not None and qs != "main_turn":
continue
pid = r[5] or ""
if not pid.startswith("account:"):
continue
ct = r[20] or -1
rid = r[0]
if (ct, rid) > (best_ct, best_rid):
best_ct, best_rid, best_pid = ct, rid, pid
self.provfbk = (best_ct, best_rid, best_pid)
# ---- 3. today_usage & today_detail ----
def _ensure_today(self, con):
if "today" in self.ready:
return
rows = con.execute(
f"""select {_INCR_DELTA_COLS} from model_usage
where rowid <= ? and status='completed' and completed_at between ? and ?""",
(self.last_rowid, self.today_start_ms, self.today_end_ms),
).fetchall()
self.today_agg = [0, 0, 0, 0, 0, 0, 0, 0, 0, None, None, set(), 0, 0, 0, 0, set(), 0]
self.today_rate_out = 0
self.today_rate_ms = 0
self.today_per_model = {}
self.today_models = {}
self.today_mnames = {}
self._apply_today(rows)
self.ready.add("today")
def _apply_today(self, delta):
a = self.today_agg
turns_set = a[11]
sess_set = a[16]
s_ms, e_ms = self.today_start_ms, self.today_end_ms
covers = self.covers
pm = self.today_per_model
tm = self.today_models
tn = self.today_mnames
for r in delta:
if r[6] != "completed":
continue
ct = r[20]
if ct is None or ct < s_ms or ct > e_ms:
continue
inp = r[8] or 0
outp = r[9] or 0
reas = r[10] or 0
cr = r[11] or 0
cw = r[12] or 0
tot = r[13] or 0
tc = r[14] or 0
ret = r[15] or 0
dur = r[16] or 0
ttft = r[17] or 0
st = r[18]
a[0] += 1
a[1] += inp
a[2] += outp
a[3] += cr
a[4] += tot
a[5] += dur
a[6] += reas
a[7] += ret
a[8] += cw
if st is not None and (a[9] is None or st < a[9]):
a[9] = st
if a[10] is None or ct > a[10]:
a[10] = ct
if r[3] is not None:
turns_set.add(r[3])
sess_set.add(r[2])
a[17] += tc