chatcc-app 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. chatcc/__init__.py +76 -0
  2. chatcc/__main__.py +46 -0
  3. chatcc/accounts.py +266 -0
  4. chatcc/admin_page.py +217 -0
  5. chatcc/atomicio.py +58 -0
  6. chatcc/cleanup.py +241 -0
  7. chatcc/config.py +230 -0
  8. chatcc/conversations.py +247 -0
  9. chatcc/deploy.py +205 -0
  10. chatcc/export.py +184 -0
  11. chatcc/failover.py +64 -0
  12. chatcc/files.py +188 -0
  13. chatcc/guard.py +118 -0
  14. chatcc/ledger.py +210 -0
  15. chatcc/mailer.py +116 -0
  16. chatcc/oauth.py +175 -0
  17. chatcc/page.py +591 -0
  18. chatcc/pricing.py +195 -0
  19. chatcc/registration.py +194 -0
  20. chatcc/relay.py +383 -0
  21. chatcc/report.py +172 -0
  22. chatcc/scan.py +135 -0
  23. chatcc/search.py +189 -0
  24. chatcc/server.py +1224 -0
  25. chatcc/sse.py +177 -0
  26. chatcc/static/katex/LICENSE +21 -0
  27. chatcc/static/katex/auto-render.min.js +1 -0
  28. chatcc/static/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  29. chatcc/static/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  30. chatcc/static/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  31. chatcc/static/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  32. chatcc/static/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  33. chatcc/static/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  34. chatcc/static/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  35. chatcc/static/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  36. chatcc/static/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  37. chatcc/static/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  38. chatcc/static/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  39. chatcc/static/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  40. chatcc/static/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  41. chatcc/static/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  42. chatcc/static/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  43. chatcc/static/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  44. chatcc/static/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  45. chatcc/static/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  46. chatcc/static/katex/katex.min.css +1 -0
  47. chatcc/static/katex/katex.min.js +1 -0
  48. chatcc/static/marked/LICENSE +44 -0
  49. chatcc/static/marked/marked.min.js +6 -0
  50. chatcc_app-0.1.0.dist-info/METADATA +336 -0
  51. chatcc_app-0.1.0.dist-info/RECORD +55 -0
  52. chatcc_app-0.1.0.dist-info/WHEEL +5 -0
  53. chatcc_app-0.1.0.dist-info/entry_points.txt +4 -0
  54. chatcc_app-0.1.0.dist-info/licenses/LICENSE +21 -0
  55. chatcc_app-0.1.0.dist-info/top_level.txt +1 -0
chatcc/__init__.py ADDED
@@ -0,0 +1,76 @@
1
+ """chat-cc:面向 C 端的聊天计费产品,也是一个可直接 import 的计费内核。
2
+
3
+ 两层用法:
4
+
5
+ **当服务用**(完整产品)
6
+
7
+ ```bash
8
+ python -m chatcc.deploy --home .
9
+ ./start.sh
10
+ ```
11
+
12
+ **当库用**(只要计费与转发)
13
+
14
+ ```python
15
+ from decimal import Decimal
16
+ from chatcc import Catalog, Ledger, Model, Price, Wallet, quote
17
+
18
+ ledger = Ledger({"u1": Wallet(user_id="u1", balance=Decimal("10"))})
19
+ model = Model(model_id="m",
20
+ official=Price(price_in_per_1k=0.001, price_out_per_1k=0.002),
21
+ cost=Price(price_in_per_1k=0.0006, price_out_per_1k=0.0012))
22
+ rated = quote(model, tokens_in=1200, tokens_out=800)
23
+ ledger.charge("u1", rated.display, free=False)
24
+ ```
25
+
26
+ ## 稳定承诺
27
+
28
+ 只有 `__all__` 里列出的名字是**公开 API**:升级时保证向后兼容。
29
+ 其余模块与函数(`chatcc.server`、`chatcc.page` 等)属于实现细节,
30
+ 可能在小版本里调整。
31
+
32
+ 计费口径的稳定性比 API 更重要:展示价/成本价、两条通道、快照语义
33
+ 一旦对外承诺就不改——改了会让用户的历史账单对不上。
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ from .accounts import Account, AccountError, AccountStore, Sessions
39
+ from .conversations import ConversationStore, Message
40
+ from .export import build as build_export
41
+ from .export import render as render_export
42
+ from .files import FileError, FileStore, StoredFile
43
+ from .guard import Guard, GuardError
44
+ from .ledger import (
45
+ GrantExhausted,
46
+ InsufficientFunds,
47
+ Ledger,
48
+ LedgerError,
49
+ Split,
50
+ Wallet,
51
+ money,
52
+ )
53
+ from .pricing import Catalog, Model, Price, Quote, quote
54
+ from .relay import CallRecord, Relay, RelayError, UpstreamClient
55
+ from .report import Report, build as build_report, to_csv
56
+
57
+ __version__ = "0.1.0"
58
+
59
+ __all__ = [
60
+ "__version__",
61
+ # 账务
62
+ "Ledger", "Wallet", "Split", "money",
63
+ "LedgerError", "InsufficientFunds", "GrantExhausted",
64
+ # 计价
65
+ "Catalog", "Model", "Price", "Quote", "quote",
66
+ # 转发
67
+ "Relay", "UpstreamClient", "RelayError", "CallRecord",
68
+ # 存储
69
+ "ConversationStore", "Message", "FileStore", "StoredFile", "FileError",
70
+ # 安全
71
+ "Guard", "GuardError",
72
+ # 账号
73
+ "Account", "AccountStore", "Sessions", "AccountError",
74
+ # 对账与导出
75
+ "Report", "build_report", "to_csv", "build_export", "render_export",
76
+ ]
chatcc/__main__.py ADDED
@@ -0,0 +1,46 @@
1
+ """python -m chatcc:起一个能用的最小服务。
2
+
3
+ 管理口令优先取环境变量 `CHATCC_ADMIN_TOKEN`——命令行参数会进 shell 历史,
4
+ 而历史文件经常被同步到别的机器。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import os
11
+ import sys
12
+ from pathlib import Path
13
+
14
+ from .server import serve
15
+
16
+
17
+ def main(argv: list[str] | None = None) -> int:
18
+ parser = argparse.ArgumentParser(prog="chatcc", description="C 端聊天计费服务")
19
+ parser.add_argument("--host", default="127.0.0.1")
20
+ parser.add_argument("--port", type=int, default=8099)
21
+ parser.add_argument("--config", default="chatcc.json")
22
+ parser.add_argument("--data-dir", default=".data")
23
+ args = parser.parse_args(argv)
24
+
25
+ config_path = Path(args.config)
26
+ if not config_path.exists():
27
+ print(f"找不到配置 {config_path};先写一份 upstream + models 再启动", file=sys.stderr)
28
+ return 2
29
+ token = os.environ.get("CHATCC_ADMIN_TOKEN", "")
30
+ if not token:
31
+ print("提醒:未设 CHATCC_ADMIN_TOKEN,管理接口将一律 403", file=sys.stderr)
32
+
33
+ httpd = serve(host=args.host, port=args.port, config_path=config_path,
34
+ data_dir=Path(args.data_dir), admin_token=token)
35
+ print(f"chat-cc 监听 http://{args.host}:{args.port} (Ctrl+C 停止)", file=sys.stderr)
36
+ try:
37
+ httpd.serve_forever()
38
+ except KeyboardInterrupt:
39
+ pass
40
+ finally:
41
+ httpd.server_close()
42
+ return 0
43
+
44
+
45
+ if __name__ == "__main__":
46
+ raise SystemExit(main())
chatcc/accounts.py ADDED
@@ -0,0 +1,266 @@
1
+ """C 端账号与会话。
2
+
3
+ 三条边界(与 relay-hub 的 API 用户体系**完全隔离**):
4
+
5
+ 1. **不发 API 凭证**:C 端用户只有会话 cookie,没有长期 key;
6
+ 2. **只认管理员发号**:一期不开放注册,避免被扫号与批量注册;
7
+ 3. **口令用 PBKDF2**:迭代次数写在哈希里,将来提高可平滑迁移。
8
+
9
+ 会话存内存:进程重启后需要重新登录。C 端用户能接受,而我们省掉了一份
10
+ "会话落盘"的敏感数据。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import secrets
18
+ import threading
19
+ import time
20
+ import uuid
21
+ from dataclasses import asdict, dataclass, field
22
+ from pathlib import Path
23
+ from typing import Any
24
+
25
+ from .atomicio import write_json_atomic
26
+
27
+ PBKDF2_ITERATIONS = 210_000
28
+ SESSION_TTL = 7 * 86400.0
29
+ STATUS_OK = "ok"
30
+ STATUS_BANNED = "banned"
31
+
32
+
33
+ class AccountError(RuntimeError):
34
+ """账号操作失败(重名、口令太弱、凭据错误等)。"""
35
+ pass
36
+
37
+
38
+ def hash_password(password: str, *, iterations: int = PBKDF2_ITERATIONS) -> str:
39
+ """生成 PBKDF2 口令哈希(迭代次数写在哈希里)。"""
40
+ if len(password) < 8:
41
+ raise AccountError("密码至少 8 位")
42
+ salt = secrets.token_bytes(16)
43
+ digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
44
+ return f"pbkdf2${iterations}${salt.hex()}${digest.hex()}"
45
+
46
+
47
+ def verify_password(password: str, stored: str) -> bool:
48
+ """校验口令,用 compare_digest 防时序侧信道。"""
49
+ try:
50
+ scheme, iterations, salt_hex, hash_hex = stored.split("$", 3)
51
+ if scheme != "pbkdf2":
52
+ return False
53
+ digest = hashlib.pbkdf2_hmac("sha256", password.encode(),
54
+ bytes.fromhex(salt_hex), int(iterations))
55
+ return secrets.compare_digest(digest.hex(), hash_hex)
56
+ except (ValueError, TypeError):
57
+ return False
58
+
59
+
60
+ @dataclass
61
+ class Account:
62
+ """一个账号:账号名、口令哈希、状态、邮箱、GitHub id。"""
63
+ user_id: str
64
+ username: str
65
+ password_hash: str
66
+ status: str = STATUS_OK
67
+ created_at: float = field(default_factory=time.time)
68
+ note: str = ""
69
+ email: str = ""
70
+ github_id: str = ""
71
+
72
+ def to_dict(self) -> dict[str, Any]:
73
+ return asdict(self)
74
+
75
+
76
+ @dataclass
77
+ class Sessions:
78
+ """内存会话表。`sid` 是随机串,只放 cookie,不放 URL。"""
79
+
80
+ ttl: float = SESSION_TTL
81
+ _lock: Any = field(default_factory=threading.Lock, repr=False)
82
+ _items: dict[str, tuple[str, float]] = field(default_factory=dict, repr=False)
83
+
84
+ def issue(self, user_id: str) -> str:
85
+ sid = secrets.token_urlsafe(32)
86
+ with self._lock:
87
+ now = time.time()
88
+ self._items = {k: v for k, v in self._items.items() if v[1] > now}
89
+ self._items[sid] = (user_id, now + self.ttl)
90
+ return sid
91
+
92
+ def resolve(self, sid: str) -> str | None:
93
+ if not sid:
94
+ return None
95
+ with self._lock:
96
+ item = self._items.get(sid)
97
+ if item is None:
98
+ return None
99
+ user_id, expires = item
100
+ if expires <= time.time():
101
+ self._items.pop(sid, None)
102
+ return None
103
+ return user_id
104
+
105
+ def revoke(self, sid: str) -> None:
106
+ with self._lock:
107
+ self._items.pop(sid, None)
108
+
109
+ def revoke_user(self, user_id: str, *, keep: str = "") -> int:
110
+ """踢掉某个账号的所有会话(可保留当前这一个)。
111
+
112
+ 改密/重置后必须做这件事:旧会话如果还活着,改密就等于没改。
113
+ """
114
+ with self._lock:
115
+ victims = [sid for sid, (uid, _exp) in self._items.items()
116
+ if uid == user_id and sid != keep]
117
+ for sid in victims:
118
+ self._items.pop(sid, None)
119
+ return len(victims)
120
+
121
+
122
+ class AccountStore:
123
+ """账号表:CRUD + 登录校验,落盘原子写。"""
124
+ def __init__(self, path: Path) -> None:
125
+ self.path = Path(path)
126
+ self._lock = threading.Lock()
127
+ self._accounts: dict[str, Account] = {}
128
+ self._by_name: dict[str, str] = {}
129
+ self._load()
130
+
131
+ def _load(self) -> None:
132
+ try:
133
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
134
+ except (OSError, ValueError):
135
+ return
136
+ for item in raw.get("accounts") or []:
137
+ if not isinstance(item, dict):
138
+ continue
139
+ account = Account(
140
+ user_id=str(item.get("user_id") or ""),
141
+ username=str(item.get("username") or ""),
142
+ password_hash=str(item.get("password_hash") or ""),
143
+ status=str(item.get("status") or STATUS_OK),
144
+ created_at=float(item.get("created_at") or 0.0),
145
+ note=str(item.get("note") or ""),
146
+ email=str(item.get("email") or ""),
147
+ github_id=str(item.get("github_id") or ""),
148
+ )
149
+ if account.user_id and account.username:
150
+ self._accounts[account.user_id] = account
151
+ self._by_name[account.username] = account.user_id
152
+
153
+ def _save(self) -> None:
154
+ write_json_atomic(self.path, {"accounts": [a.to_dict() for a in self._accounts.values()]})
155
+
156
+ # -- 查询 --------------------------------------------------------
157
+
158
+ def get(self, user_id: str) -> Account | None:
159
+ with self._lock:
160
+ return self._accounts.get(user_id)
161
+
162
+ def by_email(self, email: str) -> Account | None:
163
+ target = str(email or "").strip().lower()
164
+ if not target:
165
+ return None
166
+ with self._lock:
167
+ for account in self._accounts.values():
168
+ if account.email and account.email.lower() == target:
169
+ return account
170
+ return None
171
+
172
+ def by_github(self, github_id: str) -> Account | None:
173
+ target = str(github_id or "").strip()
174
+ if not target:
175
+ return None
176
+ with self._lock:
177
+ for account in self._accounts.values():
178
+ if account.github_id == target:
179
+ return account
180
+ return None
181
+
182
+ def link_github(self, user_id: str, github_id: str) -> bool:
183
+ with self._lock:
184
+ account = self._accounts.get(user_id)
185
+ if account is None:
186
+ return False
187
+ account.github_id = str(github_id)
188
+ self._save()
189
+ return True
190
+
191
+ def by_username(self, username: str) -> Account | None:
192
+ with self._lock:
193
+ user_id = self._by_name.get(username)
194
+ return self._accounts.get(user_id) if user_id else None
195
+
196
+ def list(self) -> list[Account]:
197
+ with self._lock:
198
+ return sorted(self._accounts.values(), key=lambda a: a.created_at)
199
+
200
+ # -- 写入 --------------------------------------------------------
201
+
202
+ def create(self, username: str, password: str, *, note: str = "") -> Account:
203
+ username = username.strip()
204
+ if not username or len(username) > 40:
205
+ raise AccountError("账号名不合法")
206
+ with self._lock:
207
+ if username in self._by_name:
208
+ raise AccountError("账号已存在")
209
+ account = Account(user_id=uuid.uuid4().hex, username=username,
210
+ password_hash=hash_password(password), note=note[:100])
211
+ self._accounts[account.user_id] = account
212
+ self._by_name[username] = account.user_id
213
+ self._save()
214
+ return account
215
+
216
+ def create_hashed(self, username: str, password_hash: str, *,
217
+ email: str = "", github_id: str = "") -> Account:
218
+ """用**已算好的**哈希建号:注册流程在发码时就算过,没必要再算一次。
219
+
220
+ PBKDF2 21 万次约 100ms,重复计算不只是浪费——它让"注册"这个
221
+ 本来就慢的操作再慢一倍。
222
+ """
223
+ username = username.strip()
224
+ if not username or len(username) > 60:
225
+ raise AccountError("账号名不合法")
226
+ with self._lock:
227
+ if username in self._by_name:
228
+ raise AccountError("账号已存在")
229
+ account = Account(user_id=uuid.uuid4().hex, username=username,
230
+ password_hash=password_hash, email=email[:120],
231
+ github_id=github_id[:40])
232
+ self._accounts[account.user_id] = account
233
+ self._by_name[username] = account.user_id
234
+ self._save()
235
+ return account
236
+
237
+ def set_status(self, user_id: str, status: str) -> bool:
238
+ if status not in (STATUS_OK, STATUS_BANNED):
239
+ raise AccountError("状态只能是 ok / banned")
240
+ with self._lock:
241
+ account = self._accounts.get(user_id)
242
+ if account is None:
243
+ return False
244
+ account.status = status
245
+ self._save()
246
+ return True
247
+
248
+ def set_password(self, user_id: str, password: str) -> bool:
249
+ with self._lock:
250
+ account = self._accounts.get(user_id)
251
+ if account is None:
252
+ return False
253
+ account.password_hash = hash_password(password)
254
+ self._save()
255
+ return True
256
+
257
+ # -- 登录 --------------------------------------------------------
258
+
259
+ def authenticate(self, username: str, password: str) -> Account:
260
+ account = self.by_username(username.strip())
261
+ if account is None or not verify_password(password, account.password_hash):
262
+ # 账号不存在与密码错误给同一句话:不泄露"这个账号存在"
263
+ raise AccountError("账号或密码错误")
264
+ if account.status != STATUS_OK:
265
+ raise AccountError("账号已被停用")
266
+ return account
chatcc/admin_page.py ADDED
@@ -0,0 +1,217 @@
1
+ """管理页:发号、改余额、封禁、看调用日志(含成本与毛利)。
2
+
3
+ 只有一屏,没有前端框架。管理口令走 `X-Admin-Token` header,
4
+ 存在 sessionStorage——刷新还在,关标签页即失效,不落 localStorage。
5
+ """
6
+
7
+ ADMIN_PAGE = r"""<!doctype html>
8
+ <html lang="zh-CN"><head><meta charset="utf-8">
9
+ <meta name="viewport" content="width=device-width,initial-scale=1">
10
+ <title>chat-cc · 管理</title>
11
+ <style>
12
+ :root{--bg:#f7f6f3;--panel:#fff;--fg:#26215c;--muted:#6b6a8f;--line:#e3e1da;
13
+ --accent:#185fa5;--bad:#a32d2d;--ok:#0f6e56}
14
+ @media(prefers-color-scheme:dark){:root{--bg:#16151c;--panel:#1e1d26;--fg:#e8e6f2;
15
+ --muted:#a09fba;--line:#33314a;--accent:#7fb0e8;--bad:#f09595;--ok:#5dcaa5}}
16
+ *{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--fg);
17
+ font:13px/1.7 -apple-system,"Segoe UI","Microsoft YaHei",system-ui,sans-serif}
18
+ .wrap{max-width:1040px;margin:0 auto;padding:20px 16px 60px}
19
+ h1{font-size:15px;margin:0 0 14px}
20
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;
21
+ padding:14px;margin-bottom:14px;overflow-x:auto}
22
+ input,select,button{font:inherit;padding:7px 10px;border-radius:8px;
23
+ border:1px solid var(--line);background:var(--bg);color:var(--fg)}
24
+ button{background:var(--accent);color:#fff;border:0;cursor:pointer}
25
+ button.ghost{background:transparent;color:var(--muted);border:1px solid var(--line)}
26
+ button.danger{background:transparent;color:var(--bad);border:1px solid var(--line)}
27
+ table{width:100%;border-collapse:collapse}th,td{text-align:left;padding:6px 8px;
28
+ border-bottom:1px solid var(--line);white-space:nowrap}
29
+ th{color:var(--muted);font-weight:500;font-size:12px}
30
+ .mono{font-variant-numeric:tabular-nums}
31
+ .tag{font-size:11px;padding:1px 6px;border-radius:999px}
32
+ .tag.ok{background:rgba(15,110,86,.12);color:var(--ok)}
33
+ .tag.bad{background:rgba(163,45,45,.12);color:var(--bad)}
34
+ .row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}
35
+ .hint{color:var(--muted);font-size:12px;margin:6px 0 0}
36
+ #gate{max-width:320px;margin:80px auto}
37
+ </style></head><body><div class="wrap">
38
+ <div id="gate" class="panel">
39
+ <h1>管理口令</h1>
40
+ <div class="row"><input id="tok" type="password" placeholder="X-Admin-Token" style="flex:1">
41
+ <button id="enter">进入</button></div>
42
+ <p class="hint">口令来自环境变量 CHATCC_ADMIN_TOKEN,只存在本标签页。</p>
43
+ </div>
44
+ <div id="main" style="display:none">
45
+ <h1>chat-cc 管理</h1>
46
+
47
+ <section class="panel">
48
+ <div class="row">
49
+ <input id="n-name" placeholder="账号">
50
+ <input id="n-pass" type="password" placeholder="密码(至少 8 位)">
51
+ <input id="n-bal" placeholder="初始余额" size="8">
52
+ <input id="n-grant" placeholder="公益日上限(token, 0=不限)" size="20">
53
+ <button id="create">发号</button>
54
+ <button id="refresh" class="ghost">刷新</button>
55
+ <button id="cleanup" class="ghost" title="预演:只统计不删除">清理预演</button>
56
+ </div>
57
+ <p id="msg" class="hint"></p>
58
+ </section>
59
+
60
+ <section class="panel">
61
+ <h1>用户</h1>
62
+ <table><thead><tr><th>账号</th><th>状态</th><th>余额</th><th>公益已用</th>
63
+ <th>公益日上限</th><th>付费累计</th><th>操作</th></tr></thead>
64
+ <tbody id="users"></tbody></table>
65
+ </section>
66
+
67
+ <section class="panel">
68
+ <h1>对账</h1>
69
+ <div class="row" style="margin-bottom:10px">
70
+ <select id="r-by">
71
+ <option value="day">按天</option>
72
+ <option value="user">按用户</option>
73
+ <option value="model">按模型</option>
74
+ </select>
75
+ <input id="r-days" value="30" size="4" title="最近多少天">
76
+ <button id="r-go">刷新</button>
77
+ <a id="r-csv" href="#" class="hint">下载 CSV</a>
78
+ <span id="r-bad" class="hint"></span>
79
+ </div>
80
+ <table><thead><tr><th>维度</th><th>调用</th><th>失败</th><th>免费</th>
81
+ <th>展示价</th><th>成本</th><th>毛利</th><th>毛利率</th><th>tokens</th></tr></thead>
82
+ <tbody id="report"></tbody></table>
83
+ </section>
84
+
85
+ <section class="panel">
86
+ <h1>调用日志(最近 200 条,含成本与毛利)</h1>
87
+ <table><thead><tr><th>时间</th><th>账号</th><th>模型</th><th>展示价</th>
88
+ <th>成本</th><th>毛利</th><th>tokens</th><th>类型</th></tr></thead>
89
+ <tbody id="calls"></tbody></table>
90
+ </section>
91
+ </div></div>
92
+ <script>
93
+ const $=id=>document.getElementById(id);
94
+ let token=sessionStorage.getItem('cc_admin')||'';
95
+ let users=[];
96
+ function api(path,body){
97
+ return fetch(path,{method:body?'POST':'GET',
98
+ headers:Object.assign({'X-Admin-Token':token},
99
+ body?{'Content-Type':'application/json'}:{}),
100
+ body:body?JSON.stringify(body):undefined})
101
+ .then(async r=>[r.status, await r.json().catch(()=>({}))]);
102
+ }
103
+ $('enter').onclick=()=>{token=$('tok').value.trim();
104
+ sessionStorage.setItem('cc_admin',token);boot();};
105
+ async function boot(){
106
+ if(!token)return;
107
+ const res=await api('/api/admin/users');
108
+ const st=res[0], d=res[1];
109
+ if(st!==200){$('gate').style.display='block';$('main').style.display='none';
110
+ $('msg').textContent=d.error||'口令无效';return;}
111
+ $('gate').style.display='none';$('main').style.display='block';
112
+ users=d.users||[];paintUsers();loadCalls();loadReport();
113
+ }
114
+ function money(v){return v==null?'-':'¥'+v;}
115
+ function paintUsers(){
116
+ $('users').innerHTML=users.map(function(u){
117
+ const w=u.wallet||{};
118
+ const grant=(w.grant_left<0)?'不限':(w.grant_left||0);
119
+ return '<tr><td>'+u.username+'</td>'
120
+ +'<td><span class="tag '+(u.status==='ok'?'ok':'bad')+'">'+
121
+ (u.status==='ok'?'正常':'已停用')+'</span></td>'
122
+ +'<td class="mono">'+money(w.balance)+'</td>'
123
+ +'<td class="mono">'+(w.grant_used||0)+' / '+grant+'</td>'
124
+ +'<td class="mono">'+(w.grant_day_limit||0)+'</td>'
125
+ +'<td class="mono">'+money(w.paid_used)+'</td>'
126
+ +'<td><button class="ghost" data-topup="'+u.user_id+'">改余额</button> '
127
+ +'<button class="'+(u.status==='ok'?'danger':'ghost')+'" data-ban="'+u.user_id+
128
+ '" data-to="'+(u.status==='ok'?'banned':'ok')+'">'+
129
+ (u.status==='ok'?'停用':'恢复')+'</button></td></tr>';
130
+ }).join('')||'<tr><td colspan="7" style="color:var(--muted)">还没有用户</td></tr>';
131
+
132
+ document.querySelectorAll('[data-topup]').forEach(function(b){
133
+ b.onclick=async function(){
134
+ const v=prompt('改余额为(元,留空不改)');
135
+ if(v===null)return;
136
+ const g=prompt('公益日上限 token(0=不限,留空不改)');
137
+ const body={user_id:b.dataset.topup};
138
+ if(v.trim()!=='')body.balance=v.trim();
139
+ if(g!==null&&g.trim()!=='')body.grant_day_limit=g.trim();
140
+ await api('/api/admin/wallet',body);boot();
141
+ };
142
+ });
143
+ document.querySelectorAll('[data-ban]').forEach(function(b){
144
+ b.onclick=async function(){
145
+ await api('/api/admin/status',{user_id:b.dataset.ban,status:b.dataset.to});
146
+ boot();
147
+ };
148
+ });
149
+ }
150
+ async function loadCalls(){
151
+ const res=await api('/api/admin/calls?limit=200');
152
+ const st=res[0], d=res[1];
153
+ if(st!==200)return;
154
+ const name=function(id){const u=users.find(x=>x.user_id===id);
155
+ return u?u.username:String(id).slice(0,6);};
156
+ $('calls').innerHTML=(d.calls||[]).map(function(c){
157
+ const ts=(c.snapshot&&c.snapshot.rated_at)||c.ts||0;
158
+ const t=ts?new Date(ts*1000).toLocaleString():'-';
159
+ return '<tr><td>'+t+'</td><td>'+name(c.user_id)+'</td><td>'+c.model+'</td>'
160
+ +'<td class="mono">'+money(c.display)+'</td>'
161
+ +'<td class="mono">'+money(c.cost)+'</td>'
162
+ +'<td class="mono">'+money(c.margin)+'</td>'
163
+ +'<td class="mono">'+(c.tokens_in||0)+'/'+(c.tokens_out||0)+'</td>'
164
+ +'<td>'+(c.free?'免费':'付费')+'</td></tr>';
165
+ }).join('')||'<tr><td colspan="8" style="color:var(--muted)">还没有调用</td></tr>';
166
+ }
167
+ $('create').onclick=async function(){
168
+ const body={username:$('n-name').value.trim(),password:$('n-pass').value};
169
+ if($('n-bal').value.trim()!=='')body.balance=$('n-bal').value.trim();
170
+ if($('n-grant').value.trim()!=='')body.grant_day_limit=parseInt($('n-grant').value,10)||0;
171
+ const res=await api('/api/admin/accounts',body);
172
+ const st=res[0], d=res[1];
173
+ $('msg').textContent=(st===200)?('已发号:'+d.username):(d.error||'发号失败');
174
+ if(st===200){$('n-name').value='';$('n-pass').value='';$('n-bal').value='';
175
+ $('n-grant').value='';boot();}
176
+ };
177
+ $('refresh').onclick=boot;
178
+ $('cleanup').onclick=async function(){
179
+ const res=await api('/api/admin/cleanup',{dry_run:true,calls_days:30,files_days:30});
180
+ const st=res[0], d=res[1];
181
+ if(st!==200){alert(d.error||'失败');return;}
182
+ const c=d.calls||{}, f=d.files||{};
183
+ alert('预演结果(未删除任何东西)
184
+ '
185
+ +'日志:将删除 '+c.calls_removed+' 行,保留 '+c.calls_kept+' 行
186
+ '
187
+ +'附件:将删除 '+f.files_removed+' 个('+(f.files_bytes||0)+' 字节),'
188
+ +'因被引用跳过 '+(f.files_skipped_referenced||0)+' 个
189
+
190
+ '
191
+ +'确认要执行?请用命令行:python -m chatcc.cleanup --yes');
192
+ };
193
+ $('r-go').onclick=loadReport;
194
+ $('r-by').onchange=loadReport;
195
+ async function loadReport(){
196
+ const by=$('r-by').value, days=$('r-days').value||'30';
197
+ $('r-csv').href='/api/admin/report?by='+by+'&days='+days+'&format=csv';
198
+ const res=await api('/api/admin/report?by='+by+'&days='+days);
199
+ const st=res[0], d=res[1];
200
+ if(st!==200)return;
201
+ $('r-bad').textContent=d.bad_lines?('坏行 '+d.bad_lines+' 条(有调用未能入账)'):'';
202
+ const rows=(d.buckets||[]).concat([d.summary]);
203
+ $('report').innerHTML=rows.map(function(b){
204
+ const strong=b.key==='合计'?' style="font-weight:600"':'';
205
+ return '<tr'+strong+'><td>'+b.key+'</td><td class="mono">'+b.calls+'</td>'
206
+ +'<td class="mono">'+(b.failed||0)+'</td>'
207
+ +'<td class="mono">'+(b.free_calls||0)+'</td>'
208
+ +'<td class="mono">¥'+b.display+'</td>'
209
+ +'<td class="mono">¥'+b.cost+'</td>'
210
+ +'<td class="mono">¥'+b.margin+'</td>'
211
+ +'<td class="mono">'+(b.margin_rate||'0')+'</td>'
212
+ +'<td class="mono">'+(b.tokens_in||0)+'/'+(b.tokens_out||0)+'</td></tr>';
213
+ }).join('');
214
+ }
215
+ boot();
216
+ </script></body></html>
217
+ """
chatcc/atomicio.py ADDED
@@ -0,0 +1,58 @@
1
+ """原子写:临时文件 + os.replace,落盘后收紧权限。
2
+
3
+ 为什么单独一个模块:配置里有上游 key、账本里有余额,
4
+ 写到一半崩掉会留下半截 JSON,下次启动直接解析失败——
5
+ 那是最难查的一类故障(错误信息指向解析,真因是磁盘上只有半个文件)。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import threading
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+
17
+ def replace_with_retry(src: Path, dst: Path, attempts: int = 6,
18
+ backoff: float = 0.003) -> None:
19
+ """Windows 上 os.replace 会被读者句柄顶回 WinError 5,重试几次。"""
20
+ last: OSError | None = None
21
+ for i in range(attempts):
22
+ try:
23
+ os.replace(src, dst)
24
+ return
25
+ except OSError as exc: # noqa: PERF203 - 就是这个用途
26
+ last = exc
27
+ if i + 1 < attempts:
28
+ import time
29
+
30
+ time.sleep(backoff * (i + 1))
31
+ if last is not None:
32
+ raise last
33
+
34
+
35
+ def ensure_private(path: Path) -> None:
36
+ """把文件收紧到 0600(POSIX 有效;Windows 上 chmod 不映射 ACL)。"""
37
+ try:
38
+ if os.name == "posix":
39
+ os.chmod(Path(path), 0o600)
40
+ except OSError:
41
+ pass
42
+
43
+
44
+ def write_json_atomic(path: Path, payload: Any) -> None:
45
+ path = Path(path)
46
+ path.parent.mkdir(parents=True, exist_ok=True)
47
+ tmp = path.with_name(f"{path.name}.{os.getpid()}.{threading.get_ident():x}.tmp")
48
+ try:
49
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n",
50
+ encoding="utf-8")
51
+ replace_with_retry(tmp, path)
52
+ ensure_private(path)
53
+ finally:
54
+ if tmp.exists():
55
+ try:
56
+ tmp.unlink()
57
+ except OSError:
58
+ pass