@njuptlzf/agent-chat-server 0.2.0 → 0.2.1

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.
@@ -1,1040 +1,1040 @@
1
- import { randomUUID } from "node:crypto";
2
- import { DatabaseSync } from "node:sqlite";
3
- import type { FileEntry } from "@earendil-works/pi-coding-agent";
4
- import type { FeedbackEntry, FeedbackKind, FeedbackRating, FeedbackStatus, SessionSummary, TokenUsage } from "@njuptlzf/agent-chat-protocol";
5
- import { DEFAULT_PERSONA_ID } from "@njuptlzf/agent-chat-protocol";
6
- import { assertMembershipWrite, assertProductId, summarizeHistory, quotaBlockedReason } from "./stores.ts";
7
- import type { AccountStateStore, AuditEvent, AuditQuery, AuditRow, AuditStore, BillingAdjustOpts, BillingEntry, BillingOrder, BillingStore, NewOrderMeta, HistoryStore, MembershipStore, MemberPoolRow, MemberPoolStore, QuotaCaps, QuotaDecision, QuotaGate, RunLogRecord, RunLogStore, RunUsageReport, RunUsageSummary } from "./stores.ts";
8
- import { auditPageWindow } from "./stores.ts";
9
- import { GENESIS_HASH, assertNoSensitiveKeys, canonicalize, rowHash, segmentsFrom, verifyChain } from "./audit.ts";
10
- import type { VerifyResult } from "./audit.ts";
11
-
12
- /**
13
- * SQLite-backed stores (node:sqlite, no extra dependency). One connection per
14
- * process: SQLite serializes writes, so quota increments are atomic and never
15
- * lost. The quota cap is enforced at run start; a concurrent run may still
16
- * overshoot by its own usage before its record lands — same semantics as the
17
- * in-memory gate, and enough to bound spend.
18
- *
19
- * `scope` partitions user data:
20
- * history is keyed by (user, scope, …). Balance and quota deliberately stay
21
- * global — cost is a property of the person, not the scope.
22
- *
23
- * 业务表(attempts / essays / …)由产品侧独立迁移链负责,本链只建 12 张通用表。
24
- */
25
- export function openDatabase(file: string, defaultScope = "", defaultPersona = DEFAULT_PERSONA_ID): DatabaseSync {
26
- const db = new DatabaseSync(file);
27
- db.exec(`
28
- PRAGMA journal_mode = WAL;
29
- CREATE TABLE IF NOT EXISTS history (
30
- user_id TEXT NOT NULL,
31
- scope TEXT NOT NULL DEFAULT '',
32
- session_id TEXT NOT NULL,
33
- entries TEXT NOT NULL,
34
- updated_at TEXT NOT NULL,
35
- -- 人格:可空 = 未绑定(新会话、或更早的老行)。
36
- -- 不进主键 ⇒ 老库 ALTER ADD COLUMN 就够,不用重建(scope 当年要重建是因为它进了主键)。
37
- persona TEXT,
38
- -- 建会话时生效的人格配置版本;0 = manifest,NULL = 更早的老行(不编历史)。
39
- persona_version INTEGER,
40
- PRIMARY KEY (user_id, scope, session_id)
41
- );
42
- -- persona 进主键:各个人格各算各的。老库由 migrateScope 重建。
43
- -- **不给列默认值**:账本键必须显式写入,core 不发明任何人格 id。
44
- CREATE TABLE IF NOT EXISTS quota (
45
- user_id TEXT NOT NULL,
46
- persona TEXT NOT NULL,
47
- day TEXT NOT NULL,
48
- tokens INTEGER NOT NULL,
49
- PRIMARY KEY (user_id, persona, day)
50
- );
51
- CREATE TABLE IF NOT EXISTS runs (
52
- id INTEGER PRIMARY KEY AUTOINCREMENT,
53
- user_id TEXT NOT NULL,
54
- session_id TEXT NOT NULL,
55
- product TEXT NOT NULL,
56
- started_at TEXT NOT NULL,
57
- duration_ms INTEGER NOT NULL,
58
- tool_rounds INTEGER NOT NULL,
59
- aborted INTEGER NOT NULL,
60
- tokens INTEGER NOT NULL,
61
- cost_usd REAL NOT NULL,
62
- error TEXT
63
- );
64
- CREATE INDEX IF NOT EXISTS runs_user_day ON runs (user_id, started_at);
65
- CREATE TABLE IF NOT EXISTS billing_balance (
66
- user_id TEXT PRIMARY KEY,
67
- balance INTEGER NOT NULL DEFAULT 0
68
- );
69
- CREATE TABLE IF NOT EXISTS billing_ledger (
70
- id INTEGER PRIMARY KEY AUTOINCREMENT,
71
- user_id TEXT NOT NULL,
72
- at TEXT NOT NULL,
73
- kind TEXT NOT NULL,
74
- amount_cents INTEGER NOT NULL,
75
- balance_after INTEGER NOT NULL,
76
- ref TEXT
77
- );
78
- CREATE TABLE IF NOT EXISTS billing_orders (
79
- id TEXT PRIMARY KEY,
80
- user_id TEXT NOT NULL,
81
- amount_cents INTEGER NOT NULL,
82
- status TEXT NOT NULL,
83
- -- 下单时间。没有它,「钱到账没」只能回一个 pending/paid,
84
- -- 模型没法说「这笔是刚下的、还在处理」。老库由下方幂等 ALTER 补列(值留空)。
85
- created_at TEXT,
86
- -- 订单品类与产品(分开买)。老行一律 recharge + product NULL + days NULL。
87
- kind TEXT NOT NULL DEFAULT 'recharge',
88
- product TEXT,
89
- days INTEGER
90
- );
91
- CREATE INDEX IF NOT EXISTS billing_ledger_user ON billing_ledger (user_id, id);
92
- CREATE TABLE IF NOT EXISTS feedback (
93
- id INTEGER PRIMARY KEY AUTOINCREMENT,
94
- at TEXT NOT NULL,
95
- user_id TEXT NOT NULL,
96
- session_id TEXT NOT NULL,
97
- -- rating 行写 up/down;工单行写 'none'(列是 NOT NULL,工单本来就没有赞/踩)
98
- rating TEXT NOT NULL,
99
- ref TEXT,
100
- priority TEXT NOT NULL DEFAULT 'normal',
101
- -- 反馈分两条腿——rating(信号)与四种工单(有正文/状态/处理人)
102
- kind TEXT NOT NULL DEFAULT 'rating',
103
- content TEXT,
104
- status TEXT NOT NULL DEFAULT 'new',
105
- reply TEXT,
106
- handled_by TEXT,
107
- handled_at TEXT,
108
- reward_days INTEGER
109
- );
110
- CREATE INDEX IF NOT EXISTS feedback_at ON feedback (id);
111
- -- 权限内核:casbin 标准策略表,管理页可编辑的「策略即数据」。
112
- CREATE TABLE IF NOT EXISTS casbin_rule (
113
- id INTEGER PRIMARY KEY AUTOINCREMENT,
114
- ptype TEXT NOT NULL,
115
- v0 TEXT NOT NULL DEFAULT '',
116
- v1 TEXT NOT NULL DEFAULT '',
117
- v2 TEXT NOT NULL DEFAULT '',
118
- v3 TEXT NOT NULL DEFAULT '',
119
- v4 TEXT NOT NULL DEFAULT '',
120
- v5 TEXT NOT NULL DEFAULT ''
121
- );
122
- CREATE UNIQUE INDEX IF NOT EXISTS casbin_rule_uniq ON casbin_rule (ptype, v0, v1, v2, v3, v4, v5);
123
- -- 会员 = 订阅制有效期,与余额解耦。member 角色由这张表现算,不进 g 表。
124
- -- 会员按**产品(= 人格 id)**分账(分开买)。product 进主键 ⇒ 老库由
125
- -- migrateProductDimension 重建;新库直接是新形状。
126
- CREATE TABLE IF NOT EXISTS membership (
127
- user_id TEXT NOT NULL,
128
- product TEXT NOT NULL,
129
- member_until TEXT NOT NULL,
130
- granted_by TEXT,
131
- updated_at TEXT NOT NULL,
132
- PRIMARY KEY (user_id, product)
133
- );
134
- -- 封号 = 身份闸,先于 casbin;付费与否同规。
135
- -- audit_revoked:审计可见性取消名单——登录默认全开,admin 可按用户取消。
136
- CREATE TABLE IF NOT EXISTS account_state (
137
- user_id TEXT PRIMARY KEY,
138
- banned_until TEXT,
139
- reason TEXT,
140
- audit_revoked INTEGER NOT NULL DEFAULT 0,
141
- -- 序列 4:上次「看过每日总结」的时刻(ISO)。存这里而不是 localStorage——
142
- -- 换设备要能记住(V6b 那条教训)。
143
- last_digest_at TEXT,
144
- updated_at TEXT NOT NULL
145
- );
146
- -- 会员月度池:池内 token 不产生余额账;(user,月) 一行,lazy 发满。
147
- -- 每月 token 池也按产品拆(不拆的话一个产品会把另一个的池用光)。
148
- CREATE TABLE IF NOT EXISTS member_pool (
149
- user_id TEXT NOT NULL,
150
- product TEXT NOT NULL,
151
- month TEXT NOT NULL,
152
- granted INTEGER NOT NULL,
153
- used INTEGER NOT NULL DEFAULT 0,
154
- PRIMARY KEY (user_id, product, month)
155
- );
156
- -- 审计与操作留痕:append-only 哈希链,全库唯一「读时也验」的表。
157
- CREATE TABLE IF NOT EXISTS audit_log (
158
- id INTEGER PRIMARY KEY AUTOINCREMENT,
159
- at TEXT NOT NULL,
160
- actor TEXT NOT NULL,
161
- roles TEXT NOT NULL DEFAULT '[]',
162
- action TEXT NOT NULL,
163
- target TEXT,
164
- result TEXT NOT NULL,
165
- reason TEXT,
166
- meta TEXT NOT NULL DEFAULT '{}',
167
- prev_hash TEXT NOT NULL,
168
- hash TEXT NOT NULL
169
- );
170
- CREATE INDEX IF NOT EXISTS audit_at ON audit_log (at);
171
- CREATE INDEX IF NOT EXISTS audit_action ON audit_log (action, id);
172
- CREATE INDEX IF NOT EXISTS audit_actor ON audit_log (actor, id);
173
- `);
174
- migrateScope(db, defaultScope, defaultPersona);
175
- return db;
176
- }
177
-
178
- /**
179
- * v6 → v7 migration: history used to be keyed by (user, id) with no scope column. SQLite cannot alter a primary key, so rebuild the table, copy
180
- * the rows under the default scope and swap the names. Idempotent: it only runs
181
- * when the old shape is detected.
182
- *
183
- * `defaultScope` is the caller's default scope for the ledger key; business
184
- * tables are migrated by the product chain (see apps/<product>/stores/product-db.ts).
185
- */
186
- function migrateScope(db: DatabaseSync, defaultScope: string, defaultPersona: string): void {
187
- const columns = (table: string) =>
188
- (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);
189
-
190
- // 老行的账本键 = **产品当时那个默认助手**的 id(旧库里只有它一个助手)。
191
- // 这个 id 是产品事实,所以由调用方传进来,不在这里写死(通用化)。
192
- const scopeOfDefault = defaultScope.replace(/'/g, "''");
193
- const personaOfDefault = defaultPersona.replace(/'/g, "''");
194
-
195
- // quota 主键要加 persona,只能重建(同 history 的 v6 做法)。
196
- if (!columns("quota").includes("persona")) {
197
- db.exec(`
198
- BEGIN;
199
- CREATE TABLE quota_v7 (
200
- user_id TEXT NOT NULL,
201
- persona TEXT NOT NULL,
202
- day TEXT NOT NULL,
203
- tokens INTEGER NOT NULL,
204
- PRIMARY KEY (user_id, persona, day)
205
- );
206
- INSERT INTO quota_v7 (user_id, persona, day, tokens)
207
- SELECT user_id, '${personaOfDefault}', day, tokens FROM quota;
208
- DROP TABLE quota;
209
- ALTER TABLE quota_v7 RENAME TO quota;
210
- COMMIT;
211
- `);
212
- }
213
-
214
- if (!columns("history").includes("scope")) {
215
- db.exec(`
216
- BEGIN;
217
- ALTER TABLE history RENAME TO history_v6;
218
- CREATE TABLE history (
219
- user_id TEXT NOT NULL,
220
- scope TEXT NOT NULL DEFAULT '',
221
- session_id TEXT NOT NULL,
222
- entries TEXT NOT NULL,
223
- updated_at TEXT NOT NULL,
224
- persona TEXT,
225
- PRIMARY KEY (user_id, scope, session_id)
226
- );
227
- INSERT INTO history (user_id, scope, session_id, entries, updated_at)
228
- SELECT user_id, '${scopeOfDefault.replace(/'/g, "''")}', session_id, entries, updated_at FROM history_v6;
229
- DROP TABLE history_v6;
230
- COMMIT;
231
- `);
232
- }
233
- // 会员权益:反馈分处理优先级(会员=high,report 置顶)。「会员优先」是
234
- // 排队顺序不是门槛——老行回填 normal,语义与「当时没人排队」一致。
235
- if (!columns("feedback").includes("priority")) {
236
- db.exec("ALTER TABLE feedback ADD COLUMN priority TEXT NOT NULL DEFAULT 'normal'");
237
- }
238
- // (反馈闭环):老库补工单列。老行一律回填 kind='rating' / status='new'——
239
- // 它们本来就是赞/踩,**不能**猜成工单,否则一上线队列里全是历史噪音。
240
- // 人格绑进 history(与 scope 同一张表、同一生命周期)。
241
- // **只是加列,不重建**——它不进主键。老行留空 = 未绑定,端点按请求值处理。
242
- if (!columns("history").includes("persona")) {
243
- db.exec("ALTER TABLE history ADD COLUMN persona TEXT");
244
- }
245
- // 这一行会话用的是第几版人格配置。加列不重建(不进主键)。
246
- // **老行留空是诚实的**——那时没有版本概念,回填任何数字都是在编历史。
247
- if (!columns("history").includes("persona_version")) {
248
- db.exec("ALTER TABLE history ADD COLUMN persona_version INTEGER");
249
- }
250
- // 轮数闸也要分账(默认助手的 10 轮不该被声明人格吃掉)。老行一律回填默认人格——
251
- // 它们本来就是默认助手会话,猜成别的会把历史算到声明人格头上。
252
- if (!columns("runs").includes("persona")) {
253
- db.exec(`ALTER TABLE runs ADD COLUMN persona TEXT NOT NULL DEFAULT '${personaOfDefault}'`);
254
- }
255
- if (!columns("feedback").includes("kind")) {
256
- db.exec("ALTER TABLE feedback ADD COLUMN kind TEXT NOT NULL DEFAULT 'rating'");
257
- }
258
- if (!columns("feedback").includes("content")) db.exec("ALTER TABLE feedback ADD COLUMN content TEXT");
259
- if (!columns("feedback").includes("status")) {
260
- db.exec("ALTER TABLE feedback ADD COLUMN status TEXT NOT NULL DEFAULT 'new'");
261
- }
262
- if (!columns("feedback").includes("reply")) db.exec("ALTER TABLE feedback ADD COLUMN reply TEXT");
263
- if (!columns("feedback").includes("handled_by")) db.exec("ALTER TABLE feedback ADD COLUMN handled_by TEXT");
264
- if (!columns("feedback").includes("handled_at")) db.exec("ALTER TABLE feedback ADD COLUMN handled_at TEXT");
265
- if (!columns("feedback").includes("reward_days")) db.exec("ALTER TABLE feedback ADD COLUMN reward_days INTEGER");
266
- // 审计可见性取消名单。老库回填 0=默认可见(新口径本就默认全开)。
267
- if (!columns("account_state").includes("audit_revoked")) {
268
- db.exec("ALTER TABLE account_state ADD COLUMN audit_revoked INTEGER NOT NULL DEFAULT 0");
269
- }
270
- // 序列 4:每日总结的「看过了」标记。老库补列,值留空(= 从没弹过,符合预期)。
271
- if (!columns("account_state").includes("last_digest_at")) {
272
- db.exec("ALTER TABLE account_state ADD COLUMN last_digest_at TEXT");
273
- }
274
- // 充值订单的下单时间。老行留空是**诚实**的——那时没记过,回填
275
- // 成 updated_at 或「今天」都是在编数据;工具侧把 null 当「时间未记录」展示。
276
- if (!columns("billing_orders").includes("created_at")) {
277
- db.exec("ALTER TABLE billing_orders ADD COLUMN created_at TEXT");
278
- }
279
- // 钱与权益加产品维度(membership/member_pool 重建 + 两处加列)。
280
- // 迁移本身是幂等的:新库走 CREATE 已是新形状,这里直接跳过。
281
- migrateProductDimension(db, defaultPersona);
282
- }
283
-
284
- /**
285
- * 给「钱与权益」加产品(人格)维度。
286
- *
287
- * **先演练、后接线**:这份函数先独立存在,演练脚本直接对旧库副本调用;
288
- * 结论没问题后再由 `openDatabase` 调它(接线)。
289
- *
290
- * 四件事:
291
- * 1. `membership`:PK `(user_id)` → `(user_id, product)` ⇒ 只能重建表,老行落默认助手;
292
- * 2. `member_pool`:PK `(user_id, month)` → `(user_id, product, month)` ⇒ 重建;
293
- * 3. `billing_orders`:+ `kind` / `product` / `days`(幂等 ALTER;充值单 `product` 留空);
294
- * 4. `activities`:+ `reward_product`(幂等 ALTER;老活动回填默认助手)。
295
- *
296
- * 三条保证:
297
- * - **幂等**:已经是新形状就跳过,重复调用不改任何东西;
298
- * - **不丢行**:重建时在事务内比对行数,不等就抛错并回滚;
299
- * - **不留半个表**:建新表 → 复制 → 删旧 → 改名全在一个事务里,失败整体回滚。
300
- *
301
- * 回滚路径:这是**启动期结构迁移**,没有"运行时回滚按钮"。出事就恢复备份/快照,
302
- * 或用 `billing_orders`/`activities` 的旧形状重建表(数据仍在旧列里,见演练脚本)。
303
- */
304
- export interface ProductMigrationReport {
305
- /** 这次真的重建了哪些表(空 = 已经是新形状)。 */
306
- rebuilt: Array<"membership" | "member_pool">;
307
- /** 这次真的加上的列(`表.列`)。 */
308
- addedColumns: string[];
309
- /** 迁移后的行数(给演练脚本比对,部署后也可打日志)。 */
310
- counts: { membership: number; memberPool: number; activities: number };
311
- }
312
-
313
- export function migrateProductDimension(db: DatabaseSync, defaultPersona: string): ProductMigrationReport {
314
- const columns = (table: string) =>
315
- (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);
316
- const exists = (table: string) =>
317
- db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table) !== undefined;
318
- const count = (table: string) => {
319
- try {
320
- return (db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n;
321
- } catch {
322
- return 0;
323
- }
324
- };
325
- // 账本键由调用方给(core 不认识任何具体人格名);单引号转义防注入。
326
- const product = defaultPersona.replace(/'/g, "''");
327
- const report: ProductMigrationReport = { rebuilt: [], addedColumns: [], counts: { membership: 0, memberPool: 0, activities: 0 } };
328
-
329
- const rebuild = (table: "membership" | "member_pool", createSql: string, copySql: string) => {
330
- if (!exists(table) || columns(table).includes("product")) return;
331
- const before = count(table);
332
- db.exec("BEGIN");
333
- try {
334
- db.exec(createSql);
335
- db.exec(copySql);
336
- const copied = (db.prepare(`SELECT COUNT(*) AS n FROM ${table}_`).get() as { n: number }).n;
337
- if (copied !== before) throw new Error(`${table}: copied ${copied} rows, expected ${before}`);
338
- db.exec(`DROP TABLE ${table}`);
339
- db.exec(`ALTER TABLE ${table}_ RENAME TO ${table}`);
340
- db.exec("COMMIT");
341
- } catch (err) {
342
- db.exec("ROLLBACK");
343
- throw err;
344
- }
345
- report.rebuilt.push(table);
346
- };
347
-
348
- rebuild(
349
- "membership",
350
- `CREATE TABLE membership_(
351
- user_id TEXT NOT NULL,
352
- product TEXT NOT NULL DEFAULT '${product}',
353
- member_until TEXT NOT NULL,
354
- granted_by TEXT,
355
- updated_at TEXT NOT NULL,
356
- PRIMARY KEY (user_id, product)
357
- )`,
358
- `INSERT INTO membership_(user_id, product, member_until, granted_by, updated_at)
359
- SELECT user_id, '${product}', member_until, granted_by, updated_at FROM membership`,
360
- );
361
- rebuild(
362
- "member_pool",
363
- `CREATE TABLE member_pool_(
364
- user_id TEXT NOT NULL,
365
- product TEXT NOT NULL DEFAULT '${product}',
366
- month TEXT NOT NULL,
367
- granted INTEGER NOT NULL,
368
- used INTEGER NOT NULL DEFAULT 0,
369
- PRIMARY KEY (user_id, product, month)
370
- )`,
371
- `INSERT INTO member_pool_(user_id, product, month, granted, used)
372
- SELECT user_id, '${product}', month, granted, used FROM member_pool`,
373
- );
374
-
375
- const add = (table: string, column: string, ddl: string) => {
376
- if (!exists(table) || columns(table).includes(column)) return;
377
- db.exec(`ALTER TABLE ${table} ADD COLUMN ${ddl}`);
378
- report.addedColumns.push(`${table}.${column}`);
379
- };
380
- // 充值订单没有产品(钱包一本);`kind` 老行一律回填 recharge——它们本来就是充值。
381
- add("billing_orders", "kind", "kind TEXT NOT NULL DEFAULT 'recharge'");
382
- add("billing_orders", "product", "product TEXT");
383
- add("billing_orders", "days", "days INTEGER");
384
- // 老活动发放的都是默认助手那本账(当年只有它)。
385
- add("activities", "reward_product", `reward_product TEXT NOT NULL DEFAULT '${product}'`);
386
-
387
- report.counts = { membership: count("membership"), memberPool: count("member_pool"), activities: count("activities") };
388
- return report;
389
- }
390
-
391
- export class SqliteHistoryStore implements HistoryStore {
392
- constructor(private readonly db: DatabaseSync) {}
393
-
394
- async load(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined> {
395
- const row = this.db
396
- .prepare("SELECT entries FROM history WHERE user_id = ? AND scope = ? AND session_id = ?")
397
- .get(userId, scope, sessionId) as { entries: string } | undefined;
398
- return row ? (JSON.parse(row.entries) as FileEntry[]) : undefined;
399
- }
400
-
401
- async save(userId: string, scope: string, sessionId: string, entries: FileEntry[], persona?: string, personaVersion?: number): Promise<void> {
402
- this.db
403
- .prepare(
404
- `INSERT INTO history (user_id, scope, session_id, entries, updated_at, persona, persona_version) VALUES (?, ?, ?, ?, ?, ?, ?)
405
- ON CONFLICT (user_id, scope, session_id) DO UPDATE
406
- SET entries = excluded.entries,
407
- updated_at = excluded.updated_at,
408
- -- 首次绑定后不再改写:中途换人格该由端点拦(persona_mismatch),这里是第二道。
409
- persona = COALESCE(history.persona, excluded.persona),
410
- -- 版本与人格同一生命周期:第一轮落库那一刻定死,之后改配置也不追认。
411
- persona_version = COALESCE(history.persona_version, excluded.persona_version)`,
412
- )
413
- .run(userId, scope, sessionId, JSON.stringify(entries), new Date().toISOString(), persona ?? null, personaVersion ?? null);
414
- }
415
-
416
- async personaOf(userId: string, sessionId: string): Promise<string | null> {
417
- const row = this.db
418
- .prepare("SELECT persona FROM history WHERE user_id = ? AND session_id = ? LIMIT 1")
419
- .get(userId, sessionId) as { persona: string | null } | undefined;
420
- return row?.persona ?? null;
421
- }
422
-
423
- async scopeOf(userId: string, sessionId: string): Promise<string | undefined> {
424
- const row = this.db
425
- .prepare("SELECT scope FROM history WHERE user_id = ? AND session_id = ? LIMIT 1")
426
- .get(userId, sessionId) as { scope: string } | undefined;
427
- return row?.scope;
428
- }
429
-
430
- // ponytail: parses every stored session blob per list (newest 50); ceiling ~hundreds of
431
- // sessions per user. Upgrade path: persist `title`/`message_count` columns at save time.
432
- async list(userId: string, scope?: string): Promise<SessionSummary[]> {
433
- const where = scope === undefined ? "user_id = ?" : "user_id = ? AND scope = ?";
434
- const args = scope === undefined ? [userId] : [userId, scope];
435
- const rows = this.db
436
- .prepare(`SELECT session_id, scope, entries, updated_at, persona FROM history WHERE ${where} ORDER BY updated_at DESC LIMIT 50`)
437
- .all(...args) as { session_id: string; scope: string; entries: string; updated_at: string; persona: string | null }[];
438
- return rows.map((r) => {
439
- const { title, messageCount } = summarizeHistory(JSON.parse(r.entries) as FileEntry[]);
440
- return { sessionId: r.session_id, scope: r.scope, title, updatedAt: r.updated_at, messageCount, persona: r.persona };
441
- });
442
- }
443
- }
444
-
445
- /** Per-user token budget per day, persisted in the quota table. */
446
- export class SqliteQuotaGate implements QuotaGate {
447
- constructor(
448
- private readonly db: DatabaseSync,
449
- private readonly dailyTokens: number | undefined,
450
- private readonly now: () => Date = () => new Date(),
451
- ) {}
452
-
453
- private day(): string {
454
- return this.now().toISOString().slice(0, 10);
455
- }
456
-
457
- async check(userId: string, caps: QuotaCaps | undefined, persona: string): Promise<QuotaDecision> {
458
- // 轮数闸先查(429 文案要区分「次数到」与「额度到」);runCap<=0 视为不限。
459
- if (caps?.runCap !== undefined && caps.runCap > 0) {
460
- const runs = this.db
461
- .prepare("SELECT COUNT(*) AS n FROM runs WHERE user_id = ? AND persona = ? AND substr(started_at, 1, 10) = ?")
462
- .get(userId, persona, this.day()) as { n: number };
463
- if (runs.n >= caps.runCap)
464
- return {
465
- ok: false,
466
- reason: quotaBlockedReason("runs", { runCap: caps.runCap, tokenCap: caps?.tokenCap ?? this.dailyTokens }),
467
- };
468
- }
469
- const tokenCap = caps?.tokenCap ?? this.dailyTokens;
470
- if (tokenCap === undefined) return { ok: true };
471
- const row = this.db
472
- .prepare("SELECT tokens FROM quota WHERE user_id = ? AND persona = ? AND day = ?")
473
- .get(userId, persona, this.day()) as { tokens: number } | undefined;
474
- return (row?.tokens ?? 0) >= tokenCap
475
- ? { ok: false, reason: quotaBlockedReason("tokens", { runCap: caps?.runCap, tokenCap }) }
476
- : { ok: true };
477
- }
478
-
479
- async todayStats(userId: string, persona: string): Promise<{ runsToday: number; tokensToday: number }> {
480
- const runs = this.db
481
- .prepare("SELECT COUNT(*) AS n FROM runs WHERE user_id = ? AND persona = ? AND substr(started_at, 1, 10) = ?")
482
- .get(userId, persona, this.day()) as { n: number };
483
- const quota = this.db
484
- .prepare("SELECT tokens FROM quota WHERE user_id = ? AND persona = ? AND day = ?")
485
- .get(userId, persona, this.day()) as { tokens: number } | undefined;
486
- return { runsToday: runs.n, tokensToday: quota?.tokens ?? 0 };
487
- }
488
-
489
- async record(userId: string, usage: TokenUsage, persona: string): Promise<void> {
490
- this.db
491
- .prepare(
492
- `INSERT INTO quota (user_id, persona, day, tokens) VALUES (?, ?, ?, ?)
493
- ON CONFLICT (user_id, persona, day) DO UPDATE SET tokens = tokens + excluded.tokens`,
494
- )
495
- .run(userId, persona, this.day(), usage.total);
496
- }
497
- }
498
-
499
- /** 会员有效期,SQLite 实现。 */
500
- export class SqliteMembership implements MembershipStore {
501
- constructor(private readonly db: DatabaseSync) {}
502
-
503
- async get(userId: string, product: string): Promise<string | null> {
504
- assertProductId(product);
505
- const row = this.db.prepare("SELECT member_until FROM membership WHERE user_id = ? AND product = ?").get(userId, product) as
506
- | { member_until: string }
507
- | undefined;
508
- return row?.member_until ?? null;
509
- }
510
- async set(userId: string, product: string, memberUntil: string, grantedBy?: string): Promise<void> {
511
- assertMembershipWrite(product, memberUntil);
512
- this.db
513
- .prepare(
514
- `INSERT INTO membership (user_id, product, member_until, granted_by, updated_at) VALUES (?, ?, ?, ?, ?)
515
- ON CONFLICT (user_id, product) DO UPDATE SET member_until = excluded.member_until,
516
- granted_by = excluded.granted_by, updated_at = excluded.updated_at`,
517
- )
518
- .run(userId, product, memberUntil, grantedBy ?? null, new Date().toISOString());
519
- }
520
- /**
521
- * 原子续期:一条 SQL 完成 `max(now, 现到期) + days`。
522
- * 为什么不先 get 再 set:并发发放(购买 + 活动奖励)会互相覆盖。
523
- * `strftime('%Y-%m-%dT%H:%M:%fZ', …)` 保住 ISO 形状——`datetime()` 会吐出
524
- * "YYYY-MM-DD HH:MM:SS"(无 T/Z),前端 `Date.parse` 会按本地时区解释。
525
- */
526
- async extend(userId: string, product: string, days: number, grantedBy?: string): Promise<string> {
527
- assertProductId(product);
528
- if (!Number.isInteger(days) || days < 1) throw new Error(`membership days must be a positive integer, got ${days}`);
529
- const now = new Date().toISOString();
530
- const row = this.db
531
- .prepare(
532
- `INSERT INTO membership (user_id, product, member_until, granted_by, updated_at)
533
- VALUES (?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', ?, '+' || ? || ' days'), ?, ?)
534
- ON CONFLICT (user_id, product) DO UPDATE SET
535
- member_until = strftime('%Y-%m-%dT%H:%M:%fZ', MAX(membership.member_until, ?), '+' || ? || ' days'),
536
- granted_by = excluded.granted_by,
537
- updated_at = excluded.updated_at
538
- RETURNING member_until`,
539
- )
540
- .get(userId, product, now, days, grantedBy ?? null, now, now, days) as { member_until: string };
541
- return row.member_until;
542
- }
543
- async remove(userId: string, product: string): Promise<void> {
544
- assertProductId(product);
545
- this.db.prepare("DELETE FROM membership WHERE user_id = ? AND product = ?").run(userId, product);
546
- }
547
- async list() {
548
- return this.db
549
- .prepare("SELECT user_id, product, member_until, granted_by FROM membership ORDER BY updated_at DESC")
550
- .all()
551
- .map((r) => ({
552
- userId: String((r as Record<string, unknown>).user_id),
553
- product: String((r as Record<string, unknown>).product),
554
- memberUntil: String((r as Record<string, unknown>).member_until),
555
- grantedBy: ((r as Record<string, unknown>).granted_by as string | null) ?? null,
556
- }));
557
- }
558
- async hasAnyActive(userId: string): Promise<boolean> {
559
- // 粗粒度标记(authz 的 member 角色):任一本账在期即为真。额度不走这里。
560
- return this.db
561
- .prepare("SELECT 1 AS ok FROM membership WHERE user_id = ? AND member_until > ? LIMIT 1")
562
- .get(userId, new Date().toISOString()) !== undefined;
563
- }
564
- }
565
-
566
- /** 封号状态,SQLite 实现。 */
567
- export class SqliteAccountState implements AccountStateStore {
568
- constructor(
569
- private readonly db: DatabaseSync,
570
- private readonly now: () => Date = () => new Date(),
571
- ) {}
572
-
573
- async activeBan(userId: string): Promise<string | null> {
574
- const row = this.db.prepare("SELECT banned_until FROM account_state WHERE user_id = ?").get(userId) as
575
- | { banned_until: string | null }
576
- | undefined;
577
- return row?.banned_until && new Date(row.banned_until) > this.now() ? row.banned_until : null;
578
- }
579
- async get(userId: string) {
580
- const row = this.db.prepare("SELECT banned_until, reason FROM account_state WHERE user_id = ?").get(userId) as
581
- | { banned_until: string | null; reason: string | null }
582
- | undefined;
583
- return { bannedUntil: row?.banned_until ?? null, reason: row?.reason ?? null };
584
- }
585
- async setBan(userId: string, bannedUntil: string, reason: string): Promise<void> {
586
- this.db
587
- .prepare(
588
- `INSERT INTO account_state (user_id, banned_until, reason, updated_at) VALUES (?, ?, ?, ?)
589
- ON CONFLICT (user_id) DO UPDATE SET banned_until = excluded.banned_until,
590
- reason = excluded.reason, updated_at = excluded.updated_at`,
591
- )
592
- .run(userId, bannedUntil, reason, new Date().toISOString());
593
- }
594
- async removeBan(userId: string): Promise<void> {
595
- this.db
596
- .prepare(
597
- `INSERT INTO account_state (user_id, banned_until, reason, updated_at) VALUES (?, NULL, NULL, ?)
598
- ON CONFLICT (user_id) DO UPDATE SET banned_until = NULL, reason = NULL, updated_at = excluded.updated_at`,
599
- )
600
- .run(userId, new Date().toISOString());
601
- }
602
- async auditRevoked(userId: string): Promise<boolean> {
603
- const row = this.db.prepare("SELECT audit_revoked FROM account_state WHERE user_id = ?").get(userId) as
604
- | { audit_revoked: number }
605
- | undefined;
606
- return (row?.audit_revoked ?? 0) === 1;
607
- }
608
- async setAuditRevoked(userId: string, revoked: boolean): Promise<void> {
609
- this.db
610
- .prepare(
611
- `INSERT INTO account_state (user_id, audit_revoked, updated_at) VALUES (?, ?, ?)
612
- ON CONFLICT (user_id) DO UPDATE SET audit_revoked = excluded.audit_revoked, updated_at = excluded.updated_at`,
613
- )
614
- .run(userId, revoked ? 1 : 0, new Date().toISOString());
615
- }
616
- async digestSeenAt(userId: string): Promise<string | null> {
617
- const row = this.db.prepare("SELECT last_digest_at FROM account_state WHERE user_id = ?").get(userId) as
618
- | { last_digest_at: string | null }
619
- | undefined;
620
- return row?.last_digest_at ?? null;
621
- }
622
- async markDigestSeen(userId: string, at: string): Promise<void> {
623
- this.db
624
- .prepare(
625
- `INSERT INTO account_state (user_id, last_digest_at, updated_at) VALUES (?, ?, ?)
626
- ON CONFLICT (user_id) DO UPDATE SET last_digest_at = excluded.last_digest_at, updated_at = excluded.updated_at`,
627
- )
628
- .run(userId, at, new Date().toISOString());
629
- }
630
- async list() {
631
- return this.db
632
- .prepare("SELECT user_id, banned_until, reason, audit_revoked FROM account_state ORDER BY updated_at DESC")
633
- .all()
634
- .map((r) => ({
635
- userId: String((r as Record<string, unknown>).user_id),
636
- bannedUntil: ((r as Record<string, unknown>).banned_until as string | null) ?? null,
637
- reason: ((r as Record<string, unknown>).reason as string | null) ?? null,
638
- auditRevoked: ((r as Record<string, unknown>).audit_revoked as number) === 1,
639
- }));
640
- }
641
- }
642
-
643
- /** 会员月度池:INSERT OR IGNORE 让 lazy 发放幂等——当月只发一次。 */
644
- export class SqliteMemberPool implements MemberPoolStore {
645
- constructor(private readonly db: DatabaseSync) {}
646
-
647
- async getOrGrant(userId: string, product: string, month: string, grantAmount: number): Promise<MemberPoolRow> {
648
- if (grantAmount > 0) {
649
- this.db
650
- .prepare("INSERT OR IGNORE INTO member_pool (user_id, product, month, granted, used) VALUES (?, ?, ?, ?, 0)")
651
- .run(userId, product, month, grantAmount);
652
- }
653
- const row = this.db
654
- .prepare("SELECT granted, used FROM member_pool WHERE user_id = ? AND product = ? AND month = ?")
655
- .get(userId, product, month) as { granted: number; used: number } | undefined;
656
- return { product, month, granted: row?.granted ?? 0, used: row?.used ?? 0 };
657
- }
658
-
659
- async addUsed(userId: string, product: string, month: string, tokens: number): Promise<void> {
660
- this.db
661
- .prepare("UPDATE member_pool SET used = used + ? WHERE user_id = ? AND product = ? AND month = ?")
662
- .run(tokens, userId, product, month);
663
- }
664
- }
665
-
666
-
667
- /** Persisted run log; backs GET /api/usage and the admin report. */
668
- export class SqliteRunLog implements RunLogStore {
669
- constructor(private readonly db: DatabaseSync) {}
670
-
671
- async record(run: RunLogRecord): Promise<void> {
672
- this.db
673
- .prepare(
674
- `INSERT INTO runs (user_id, session_id, product, persona, started_at, duration_ms, tool_rounds, aborted, tokens, cost_usd, error)
675
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
676
- )
677
- .run(
678
- run.userId,
679
- run.sessionId,
680
- run.product,
681
- run.persona,
682
- run.startedAt,
683
- run.durationMs,
684
- run.toolRounds,
685
- run.aborted ? 1 : 0,
686
- run.usage.total,
687
- run.usage.costUsd,
688
- run.error ?? null,
689
- );
690
- }
691
-
692
- async summary(userId: string): Promise<RunUsageSummary> {
693
- const day = new Date().toISOString().slice(0, 10);
694
- const tot = this.db
695
- .prepare("SELECT COUNT(*) AS runs, COALESCE(SUM(tokens),0) AS tokens, COALESCE(SUM(cost_usd),0) AS cost FROM runs WHERE user_id = ?")
696
- .get(userId) as { runs: number; tokens: number; cost: number };
697
- const today = this.db
698
- .prepare("SELECT COALESCE(SUM(tokens),0) AS tokens FROM runs WHERE user_id = ? AND started_at >= ? AND started_at < ?")
699
- .get(userId, `${day}T00:00:00.000Z`, `${day}T23:59:59.999Z`) as { tokens: number };
700
- const rows = this.db
701
- .prepare("SELECT * FROM runs WHERE user_id = ? ORDER BY id DESC LIMIT 10")
702
- .all(userId) as Array<Record<string, string | number | null>>;
703
- return {
704
- day,
705
- tokensToday: today.tokens,
706
- totalRuns: tot.runs,
707
- totalTokens: tot.tokens,
708
- totalCostUsd: tot.cost,
709
- recent: rows.map((r) => ({
710
- userId: String(r.user_id),
711
- sessionId: String(r.session_id),
712
- product: String(r.product),
713
- // 老行由迁移时的 DEFAULT 回填成"当时的默认助手",不会是 NULL。
714
- persona: String(r.persona),
715
- startedAt: String(r.started_at),
716
- durationMs: Number(r.duration_ms),
717
- toolRounds: Number(r.tool_rounds),
718
- aborted: r.aborted === 1,
719
- usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: Number(r.tokens), costUsd: Number(r.cost_usd) },
720
- error: r.error == null ? undefined : String(r.error),
721
- })),
722
- };
723
- }
724
-
725
- async report(): Promise<RunUsageReport> {
726
- const users = this.db
727
- .prepare("SELECT user_id, COUNT(*) AS runs, SUM(tokens) AS tokens, SUM(cost_usd) AS cost FROM runs GROUP BY user_id ORDER BY tokens DESC")
728
- .all() as Array<{ user_id: string; runs: number; tokens: number; cost: number }>;
729
- const products = this.db
730
- .prepare("SELECT product, COUNT(*) AS runs, SUM(tokens) AS tokens, SUM(cost_usd) AS cost FROM runs GROUP BY product ORDER BY tokens DESC")
731
- .all() as Array<{ product: string; runs: number; tokens: number; cost: number }>;
732
- return {
733
- users: users.map((u) => ({ userId: u.user_id, runs: u.runs, tokens: u.tokens, costUsd: u.cost })),
734
- products: products.map((p) => ({ product: p.product, runs: p.runs, tokens: p.tokens, costUsd: p.cost })),
735
- };
736
- }
737
- }
738
-
739
- /** Balance + ledger in cents; adjust is one atomic upsert, so concurrent runs never lose a deduction. */
740
- export class SqliteBilling implements BillingStore {
741
- constructor(private readonly db: DatabaseSync) {}
742
-
743
- async balance(userId: string) {
744
- const row = this.db.prepare("SELECT balance FROM billing_balance WHERE user_id = ?").get(userId) as { balance: number } | undefined;
745
- return row?.balance ?? 0;
746
- }
747
-
748
- async adjust(userId: string, deltaCents: number, kind: BillingEntry["kind"], ref?: string, opts?: BillingAdjustOpts) {
749
- // kind="adjust"(管理端调整)的 ledger 行存**带符号**金额:这类行的方向没有
750
- // kind 可推断(正负都合法),前端靠符号画 +/−。其余 kind 维持 abs(协议:
751
- // recharge/spend/membership 行金额恒为正,方向由 kind 给出)。
752
- const ledgerAmount = kind === "adjust" ? deltaCents : Math.abs(deltaCents);
753
- // 负 delta 走条件 UPDATE(余额闸):`ON CONFLICT … WHERE` 只约束 UPDATE 分支,
754
- // 直接 upsert 的话「用户无行 + 负 delta」会从 INSERT 直插一个负余额。
755
- // 正 delta 维持原来的原子 upsert(并发扣款不会互相吃掉对方的写入)。
756
- // 条件 UPDATE 是同步语句,两条语句之间事件循环不让出,无中途穿插。
757
- if (deltaCents < 0 && !opts?.allowNegative) {
758
- const gated = this.db
759
- .prepare(
760
- `UPDATE billing_balance SET balance = balance + ? WHERE user_id = ? AND balance + ? >= 0 RETURNING balance`,
761
- )
762
- .get(deltaCents, userId, deltaCents) as { balance: number } | undefined;
763
- if (!gated) return null; // 闸住:余额不够,一个字节都没写(含 ledger)
764
- this.db
765
- .prepare("INSERT INTO billing_ledger (user_id, at, kind, amount_cents, balance_after, ref) VALUES (?, ?, ?, ?, ?, ?)")
766
- .run(userId, new Date().toISOString(), kind, ledgerAmount, gated.balance, ref ?? null);
767
- return gated.balance;
768
- }
769
- const { balance } = this.db
770
- .prepare(
771
- `INSERT INTO billing_balance (user_id, balance) VALUES (?, ?)
772
- ON CONFLICT (user_id) DO UPDATE SET balance = balance + excluded.balance
773
- RETURNING balance`,
774
- )
775
- .get(userId, deltaCents) as { balance: number };
776
- this.db
777
- .prepare("INSERT INTO billing_ledger (user_id, at, kind, amount_cents, balance_after, ref) VALUES (?, ?, ?, ?, ?, ?)")
778
- .run(userId, new Date().toISOString(), kind, ledgerAmount, balance, ref ?? null);
779
- return balance;
780
- }
781
-
782
- async ledger(userId: string, limit = 20): Promise<BillingEntry[]> {
783
- const rows = this.db
784
- .prepare("SELECT * FROM billing_ledger WHERE user_id = ? ORDER BY id DESC LIMIT ?")
785
- .all(userId, limit) as Array<Record<string, string | number | null>>;
786
- return rows.map((r) => ({
787
- at: String(r.at),
788
- kind: String(r.kind) as BillingEntry["kind"],
789
- amountCents: Number(r.amount_cents),
790
- balanceAfter: Number(r.balance_after),
791
- ref: r.ref == null ? undefined : String(r.ref),
792
- }));
793
- }
794
-
795
- async createOrder(userId: string, amountCents: number, meta: NewOrderMeta = {}) {
796
- const id = `ord_${randomUUID().slice(0, 8)}`;
797
- this.db
798
- .prepare(
799
- `INSERT INTO billing_orders (id, user_id, amount_cents, status, created_at, kind, product, days)
800
- VALUES (?, ?, ?, 'pending', ?, ?, ?, ?)`,
801
- )
802
- .run(
803
- id,
804
- userId,
805
- amountCents,
806
- new Date().toISOString(),
807
- meta.kind ?? "recharge",
808
- meta.product ?? null,
809
- meta.days ?? null,
810
- );
811
- return id;
812
- }
813
-
814
- async getOrder(orderId: string): Promise<BillingOrder | null> {
815
- const r = this.db
816
- .prepare("SELECT id, user_id, amount_cents, status, kind, product, days FROM billing_orders WHERE id = ?")
817
- .get(orderId) as Record<string, unknown> | undefined;
818
- if (!r) return null;
819
- const status = String(r.status);
820
- return {
821
- id: String(r.id),
822
- userId: String(r.user_id),
823
- amountCents: Number(r.amount_cents),
824
- // 四种状态原样透出:把 cancelled/expired 折成 pending 会让"已关闭的单"看起来
825
- // 还能付,正是这次要堵的洞。
826
- status:
827
- status === "paid" ? "paid" : status === "cancelled" ? "cancelled" : status === "expired" ? "expired" : "pending",
828
- kind: r.kind === "membership" ? "membership" : "recharge",
829
- product: r.product == null ? null : String(r.product),
830
- days: r.days == null ? null : Number(r.days),
831
- };
832
- }
833
-
834
- async pendingOrders(userId: string): Promise<Array<BillingOrder & { createdAt: string | null }>> {
835
- // created_at IS NULL 排最后(老库补列前的行没有可信时间),新单在前。
836
- const rows = this.db
837
- .prepare(
838
- "SELECT id, amount_cents, kind, product, days, created_at FROM billing_orders WHERE user_id = ? AND status = 'pending' ORDER BY (created_at IS NULL), created_at DESC",
839
- )
840
- .all(userId) as Array<Record<string, unknown>>;
841
- return rows.map((r) => ({
842
- id: String(r.id),
843
- userId,
844
- amountCents: Number(r.amount_cents),
845
- status: "pending" as const,
846
- kind: r.kind === "membership" ? ("membership" as const) : ("recharge" as const),
847
- product: r.product == null ? null : String(r.product),
848
- days: r.days == null ? null : Number(r.days),
849
- createdAt: r.created_at == null ? null : String(r.created_at),
850
- }));
851
- }
852
-
853
- async claimOrder(orderId: string): Promise<"claimed" | "already" | "cancelled" | "expired" | "unknown"> {
854
- // Conditional flip claims the order; a racing fulfill that loses it reports the real state.
855
- const claimed = this.db.prepare("UPDATE billing_orders SET status = 'paid' WHERE id = ? AND status = 'pending'").run(orderId);
856
- if (claimed.changes === 0) {
857
- const row = this.db.prepare("SELECT status FROM billing_orders WHERE id = ?").get(orderId) as { status?: string } | undefined;
858
- if (!row) return "unknown";
859
- if (row.status === "cancelled") return "cancelled";
860
- if (row.status === "expired") return "expired";
861
- return "already"; // paid(或历史脏值)
862
- }
863
- return "claimed";
864
- }
865
-
866
- async cancelOrder(orderId: string, userId: string): Promise<"cancelled" | "not_pending" | "unknown"> {
867
- const done = this.db
868
- .prepare("UPDATE billing_orders SET status = 'cancelled' WHERE id = ? AND user_id = ? AND status = 'pending'")
869
- .run(orderId, userId);
870
- if (done.changes > 0) return "cancelled";
871
- // 没改到:要么不是他的单(连存在性都不该告诉他),要么已经付了/关了。
872
- const row = this.db.prepare("SELECT user_id, status FROM billing_orders WHERE id = ?").get(orderId) as
873
- | { user_id?: string; status?: string }
874
- | undefined;
875
- if (!row || row.user_id !== userId) return "unknown";
876
- return "not_pending";
877
- }
878
-
879
- async expireStaleOrders(ttlMs: number, nowMs = Date.now()): Promise<number> {
880
- // 只清 pending:已付的单不管多久都不能动(那是账,不是垃圾)。
881
- const cutoff = new Date(nowMs - ttlMs).toISOString();
882
- const res = this.db
883
- .prepare("UPDATE billing_orders SET status = 'expired' WHERE status = 'pending' AND created_at IS NOT NULL AND created_at < ?")
884
- .run(cutoff);
885
- return Number(res.changes);
886
- }
887
-
888
- async releaseOrder(orderId: string): Promise<boolean> {
889
- // 只放回「刚被认领、业务还没做成」的单;对已完成的单是 no-op。
890
- return this.db.prepare("UPDATE billing_orders SET status = 'pending' WHERE id = ? AND status = 'paid'").run(orderId).changes > 0;
891
- }
892
-
893
- async fulfillOrder(orderId: string): Promise<"credited" | "already" | "unknown" | "wrong_kind" | "closed"> {
894
- const order = await this.getOrder(orderId);
895
- if (!order) return "unknown";
896
- if (order.kind !== "recharge") return "wrong_kind";
897
- if (order.status === "paid") return "already";
898
- if (order.status === "cancelled" || order.status === "expired") return "closed";
899
- const claim = await this.claimOrder(orderId);
900
- if (claim === "cancelled" || claim === "expired") return "closed";
901
- if (claim !== "claimed") return "already";
902
- await this.adjust(order.userId, order.amountCents, "recharge", orderId);
903
- return "credited";
904
- }
905
- }
906
-
907
-
908
- /** audit_log 行 → 领域行(roles/meta 反序列化;hash 重算侧再做规范化,存储串格式不参与)。 */
909
- function mapAuditRow(r: Record<string, string | number | null>): AuditRow {
910
- return {
911
- id: Number(r.id),
912
- at: String(r.at),
913
- actor: String(r.actor),
914
- roles: JSON.parse(String(r.roles)) as string[],
915
- action: String(r.action),
916
- target: r.target == null ? null : String(r.target),
917
- result: String(r.result) as AuditRow["result"],
918
- reason: r.reason == null ? null : String(r.reason),
919
- meta: JSON.parse(String(r.meta)) as Record<string, unknown>,
920
- prevHash: String(r.prev_hash),
921
- hash: String(r.hash),
922
- };
923
- }
924
-
925
- /**
926
- * 审计哈希链的 SQLite 实现(/;表见 openDatabase DDL 块)。
927
- * append 全程同步:读链尾与 INSERT 之间没有 await,单事件循环内不会有两个 append 交错;
928
- * purge 同理(①读齐+白名单入链 ②删除,两步不反, 5B)。
929
- */
930
- export class SqliteAudit implements AuditStore {
931
- constructor(private readonly db: DatabaseSync, private readonly now: () => Date = () => new Date()) {}
932
-
933
- async append(e: AuditEvent): Promise<number> {
934
- return this.appendSync(e);
935
- }
936
-
937
- /** 同步内核:purge 要在同一同步段里「白名单先入链、再删行」,不能经 await 让出。 */
938
- private appendSync(e: AuditEvent): number {
939
- const meta = e.meta ?? {};
940
- assertNoSensitiveKeys(meta);
941
- const body = {
942
- at: e.at ?? this.now().toISOString(),
943
- actor: e.actor,
944
- roles: e.roles ?? [],
945
- action: e.action,
946
- target: e.target ?? null,
947
- result: e.result,
948
- reason: e.reason ?? null,
949
- meta,
950
- };
951
- const last = this.db.prepare("SELECT hash FROM audit_log ORDER BY id DESC LIMIT 1").get() as { hash: string } | undefined;
952
- const prevHash = last?.hash ?? GENESIS_HASH;
953
- const info = this.db
954
- .prepare(
955
- `INSERT INTO audit_log (at, actor, roles, action, target, result, reason, meta, prev_hash, hash)
956
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
957
- )
958
- .run(
959
- body.at,
960
- body.actor,
961
- canonicalize(body.roles),
962
- body.action,
963
- body.target,
964
- body.result,
965
- body.reason,
966
- canonicalize(body.meta),
967
- prevHash,
968
- rowHash(prevHash, body),
969
- );
970
- return Number(info.lastInsertRowid);
971
- }
972
-
973
- async query(q: AuditQuery): Promise<{ rows: AuditRow[]; total: number }> {
974
- const clauses: string[] = [];
975
- const args: Array<string | number> = [];
976
- if (q.from) {
977
- clauses.push("at >= ?");
978
- args.push(q.from);
979
- }
980
- if (q.to) {
981
- clauses.push("at <= ?");
982
- args.push(q.to);
983
- }
984
- if (q.actionPrefix) {
985
- clauses.push("action LIKE ? || '%'");
986
- args.push(q.actionPrefix);
987
- }
988
- if (q.actor) {
989
- clauses.push("actor = ?");
990
- args.push(q.actor);
991
- }
992
- if (q.subject) {
993
- // 「我做的 + 针对我的」。ponytail: OR 走 actor/target 两索引的
994
- // or-optimization,v1 量级够用;升级路径=物化 subject 列或 UNION 查询。
995
- clauses.push("(actor = ? OR target = ?)");
996
- args.push(q.subject, `user:${q.subject}`);
997
- }
998
- if (q.result) {
999
- clauses.push("result = ?");
1000
- args.push(q.result);
1001
- }
1002
- const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
1003
- const total = Number((this.db.prepare(`SELECT COUNT(*) AS n FROM audit_log ${where}`).get(...args) as { n: number }).n);
1004
- const { limit, offset } = auditPageWindow(q);
1005
- const rows = this.db.prepare(`SELECT * FROM audit_log ${where} ORDER BY id DESC LIMIT ? OFFSET ?`).all(...args, limit, offset) as Array<Record<string, string | number | null>>;
1006
- return { rows: rows.map(mapAuditRow), total };
1007
- }
1008
-
1009
- async get(id: number): Promise<AuditRow | null> {
1010
- const r = this.db.prepare("SELECT * FROM audit_log WHERE id = ?").get(id) as Record<string, string | number | null> | undefined;
1011
- return r ? mapAuditRow(r) : null;
1012
- }
1013
-
1014
- async verify(): Promise<VerifyResult> {
1015
- // 全表升序扫:v1 量级下 SQLite 顺序扫足够快。
1016
- const rows = this.db.prepare("SELECT * FROM audit_log ORDER BY id ASC").all() as Array<Record<string, string | number | null>>;
1017
- return verifyChain(rows.map(mapAuditRow));
1018
- }
1019
-
1020
- async purge(cutoffIso: string): Promise<number> {
1021
- const doomed = this.db
1022
- .prepare("SELECT id, hash FROM audit_log WHERE at < ? AND (action LIKE 'run.%' OR action LIKE 'biz.%') ORDER BY id ASC")
1023
- .all(cutoffIso) as Array<{ id: number | bigint; hash: string }>;
1024
- if (!doomed.length) return 0;
1025
- const ids = doomed.map((d) => Number(d.id));
1026
- // ①白名单行先入链(last_hash=段尾行存储 hash,删前读取)。
1027
- this.appendSync({
1028
- actor: "system",
1029
- action: "ops.audit.purge",
1030
- result: "ok",
1031
- meta: { cutoff: cutoffIso, count: ids.length, segments: segmentsFrom(doomed.map((d) => ({ id: Number(d.id), hash: d.hash }))) },
1032
- });
1033
- // ②再物理删(IN 分块,防变量数上限)。
1034
- for (let i = 0; i < ids.length; i += 500) {
1035
- const chunk = ids.slice(i, i + 500);
1036
- this.db.prepare(`DELETE FROM audit_log WHERE id IN (${chunk.map(() => "?").join(",")})`).run(...chunk);
1037
- }
1038
- return ids.length;
1039
- }
1040
- }
1
+ import { randomUUID } from "node:crypto";
2
+ import { DatabaseSync } from "node:sqlite";
3
+ import type { FileEntry } from "@earendil-works/pi-coding-agent";
4
+ import type { FeedbackEntry, FeedbackKind, FeedbackRating, FeedbackStatus, SessionSummary, TokenUsage } from "@njuptlzf/agent-chat-protocol";
5
+ import { DEFAULT_PERSONA_ID } from "@njuptlzf/agent-chat-protocol";
6
+ import { assertMembershipWrite, assertProductId, summarizeHistory, quotaBlockedReason } from "./stores.ts";
7
+ import type { AccountStateStore, AuditEvent, AuditQuery, AuditRow, AuditStore, BillingAdjustOpts, BillingEntry, BillingOrder, BillingStore, NewOrderMeta, HistoryStore, MembershipStore, MemberPoolRow, MemberPoolStore, QuotaCaps, QuotaDecision, QuotaGate, RunLogRecord, RunLogStore, RunUsageReport, RunUsageSummary } from "./stores.ts";
8
+ import { auditPageWindow } from "./stores.ts";
9
+ import { GENESIS_HASH, assertNoSensitiveKeys, canonicalize, rowHash, segmentsFrom, verifyChain } from "./audit.ts";
10
+ import type { VerifyResult } from "./audit.ts";
11
+
12
+ /**
13
+ * SQLite-backed stores (node:sqlite, no extra dependency). One connection per
14
+ * process: SQLite serializes writes, so quota increments are atomic and never
15
+ * lost. The quota cap is enforced at run start; a concurrent run may still
16
+ * overshoot by its own usage before its record lands — same semantics as the
17
+ * in-memory gate, and enough to bound spend.
18
+ *
19
+ * `scope` partitions user data:
20
+ * history is keyed by (user, scope, …). Balance and quota deliberately stay
21
+ * global — cost is a property of the person, not the scope.
22
+ *
23
+ * 业务表(attempts / essays / …)由产品侧独立迁移链负责,本链只建 12 张通用表。
24
+ */
25
+ export function openDatabase(file: string, defaultScope = "", defaultPersona = DEFAULT_PERSONA_ID): DatabaseSync {
26
+ const db = new DatabaseSync(file);
27
+ db.exec(`
28
+ PRAGMA journal_mode = WAL;
29
+ CREATE TABLE IF NOT EXISTS history (
30
+ user_id TEXT NOT NULL,
31
+ scope TEXT NOT NULL DEFAULT '',
32
+ session_id TEXT NOT NULL,
33
+ entries TEXT NOT NULL,
34
+ updated_at TEXT NOT NULL,
35
+ -- 人格:可空 = 未绑定(新会话、或更早的老行)。
36
+ -- 不进主键 ⇒ 老库 ALTER ADD COLUMN 就够,不用重建(scope 当年要重建是因为它进了主键)。
37
+ persona TEXT,
38
+ -- 建会话时生效的人格配置版本;0 = manifest,NULL = 更早的老行(不编历史)。
39
+ persona_version INTEGER,
40
+ PRIMARY KEY (user_id, scope, session_id)
41
+ );
42
+ -- persona 进主键:各个人格各算各的。老库由 migrateScope 重建。
43
+ -- **不给列默认值**:账本键必须显式写入,core 不发明任何人格 id。
44
+ CREATE TABLE IF NOT EXISTS quota (
45
+ user_id TEXT NOT NULL,
46
+ persona TEXT NOT NULL,
47
+ day TEXT NOT NULL,
48
+ tokens INTEGER NOT NULL,
49
+ PRIMARY KEY (user_id, persona, day)
50
+ );
51
+ CREATE TABLE IF NOT EXISTS runs (
52
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
53
+ user_id TEXT NOT NULL,
54
+ session_id TEXT NOT NULL,
55
+ product TEXT NOT NULL,
56
+ started_at TEXT NOT NULL,
57
+ duration_ms INTEGER NOT NULL,
58
+ tool_rounds INTEGER NOT NULL,
59
+ aborted INTEGER NOT NULL,
60
+ tokens INTEGER NOT NULL,
61
+ cost_usd REAL NOT NULL,
62
+ error TEXT
63
+ );
64
+ CREATE INDEX IF NOT EXISTS runs_user_day ON runs (user_id, started_at);
65
+ CREATE TABLE IF NOT EXISTS billing_balance (
66
+ user_id TEXT PRIMARY KEY,
67
+ balance INTEGER NOT NULL DEFAULT 0
68
+ );
69
+ CREATE TABLE IF NOT EXISTS billing_ledger (
70
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
71
+ user_id TEXT NOT NULL,
72
+ at TEXT NOT NULL,
73
+ kind TEXT NOT NULL,
74
+ amount_cents INTEGER NOT NULL,
75
+ balance_after INTEGER NOT NULL,
76
+ ref TEXT
77
+ );
78
+ CREATE TABLE IF NOT EXISTS billing_orders (
79
+ id TEXT PRIMARY KEY,
80
+ user_id TEXT NOT NULL,
81
+ amount_cents INTEGER NOT NULL,
82
+ status TEXT NOT NULL,
83
+ -- 下单时间。没有它,「钱到账没」只能回一个 pending/paid,
84
+ -- 模型没法说「这笔是刚下的、还在处理」。老库由下方幂等 ALTER 补列(值留空)。
85
+ created_at TEXT,
86
+ -- 订单品类与产品(分开买)。老行一律 recharge + product NULL + days NULL。
87
+ kind TEXT NOT NULL DEFAULT 'recharge',
88
+ product TEXT,
89
+ days INTEGER
90
+ );
91
+ CREATE INDEX IF NOT EXISTS billing_ledger_user ON billing_ledger (user_id, id);
92
+ CREATE TABLE IF NOT EXISTS feedback (
93
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
94
+ at TEXT NOT NULL,
95
+ user_id TEXT NOT NULL,
96
+ session_id TEXT NOT NULL,
97
+ -- rating 行写 up/down;工单行写 'none'(列是 NOT NULL,工单本来就没有赞/踩)
98
+ rating TEXT NOT NULL,
99
+ ref TEXT,
100
+ priority TEXT NOT NULL DEFAULT 'normal',
101
+ -- 反馈分两条腿——rating(信号)与四种工单(有正文/状态/处理人)
102
+ kind TEXT NOT NULL DEFAULT 'rating',
103
+ content TEXT,
104
+ status TEXT NOT NULL DEFAULT 'new',
105
+ reply TEXT,
106
+ handled_by TEXT,
107
+ handled_at TEXT,
108
+ reward_days INTEGER
109
+ );
110
+ CREATE INDEX IF NOT EXISTS feedback_at ON feedback (id);
111
+ -- 权限内核:casbin 标准策略表,管理页可编辑的「策略即数据」。
112
+ CREATE TABLE IF NOT EXISTS casbin_rule (
113
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
114
+ ptype TEXT NOT NULL,
115
+ v0 TEXT NOT NULL DEFAULT '',
116
+ v1 TEXT NOT NULL DEFAULT '',
117
+ v2 TEXT NOT NULL DEFAULT '',
118
+ v3 TEXT NOT NULL DEFAULT '',
119
+ v4 TEXT NOT NULL DEFAULT '',
120
+ v5 TEXT NOT NULL DEFAULT ''
121
+ );
122
+ CREATE UNIQUE INDEX IF NOT EXISTS casbin_rule_uniq ON casbin_rule (ptype, v0, v1, v2, v3, v4, v5);
123
+ -- 会员 = 订阅制有效期,与余额解耦。member 角色由这张表现算,不进 g 表。
124
+ -- 会员按**产品(= 人格 id)**分账(分开买)。product 进主键 ⇒ 老库由
125
+ -- migrateProductDimension 重建;新库直接是新形状。
126
+ CREATE TABLE IF NOT EXISTS membership (
127
+ user_id TEXT NOT NULL,
128
+ product TEXT NOT NULL,
129
+ member_until TEXT NOT NULL,
130
+ granted_by TEXT,
131
+ updated_at TEXT NOT NULL,
132
+ PRIMARY KEY (user_id, product)
133
+ );
134
+ -- 封号 = 身份闸,先于 casbin;付费与否同规。
135
+ -- audit_revoked:审计可见性取消名单——登录默认全开,admin 可按用户取消。
136
+ CREATE TABLE IF NOT EXISTS account_state (
137
+ user_id TEXT PRIMARY KEY,
138
+ banned_until TEXT,
139
+ reason TEXT,
140
+ audit_revoked INTEGER NOT NULL DEFAULT 0,
141
+ -- 序列 4:上次「看过每日总结」的时刻(ISO)。存这里而不是 localStorage——
142
+ -- 换设备要能记住(V6b 那条教训)。
143
+ last_digest_at TEXT,
144
+ updated_at TEXT NOT NULL
145
+ );
146
+ -- 会员月度池:池内 token 不产生余额账;(user,月) 一行,lazy 发满。
147
+ -- 每月 token 池也按产品拆(不拆的话一个产品会把另一个的池用光)。
148
+ CREATE TABLE IF NOT EXISTS member_pool (
149
+ user_id TEXT NOT NULL,
150
+ product TEXT NOT NULL,
151
+ month TEXT NOT NULL,
152
+ granted INTEGER NOT NULL,
153
+ used INTEGER NOT NULL DEFAULT 0,
154
+ PRIMARY KEY (user_id, product, month)
155
+ );
156
+ -- 审计与操作留痕:append-only 哈希链,全库唯一「读时也验」的表。
157
+ CREATE TABLE IF NOT EXISTS audit_log (
158
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
159
+ at TEXT NOT NULL,
160
+ actor TEXT NOT NULL,
161
+ roles TEXT NOT NULL DEFAULT '[]',
162
+ action TEXT NOT NULL,
163
+ target TEXT,
164
+ result TEXT NOT NULL,
165
+ reason TEXT,
166
+ meta TEXT NOT NULL DEFAULT '{}',
167
+ prev_hash TEXT NOT NULL,
168
+ hash TEXT NOT NULL
169
+ );
170
+ CREATE INDEX IF NOT EXISTS audit_at ON audit_log (at);
171
+ CREATE INDEX IF NOT EXISTS audit_action ON audit_log (action, id);
172
+ CREATE INDEX IF NOT EXISTS audit_actor ON audit_log (actor, id);
173
+ `);
174
+ migrateScope(db, defaultScope, defaultPersona);
175
+ return db;
176
+ }
177
+
178
+ /**
179
+ * v6 → v7 migration: history used to be keyed by (user, id) with no scope column. SQLite cannot alter a primary key, so rebuild the table, copy
180
+ * the rows under the default scope and swap the names. Idempotent: it only runs
181
+ * when the old shape is detected.
182
+ *
183
+ * `defaultScope` is the caller's default scope for the ledger key; business
184
+ * tables are migrated by the product chain (see apps/<product>/stores/product-db.ts).
185
+ */
186
+ function migrateScope(db: DatabaseSync, defaultScope: string, defaultPersona: string): void {
187
+ const columns = (table: string) =>
188
+ (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);
189
+
190
+ // 老行的账本键 = **产品当时那个默认助手**的 id(旧库里只有它一个助手)。
191
+ // 这个 id 是产品事实,所以由调用方传进来,不在这里写死(通用化)。
192
+ const scopeOfDefault = defaultScope.replace(/'/g, "''");
193
+ const personaOfDefault = defaultPersona.replace(/'/g, "''");
194
+
195
+ // quota 主键要加 persona,只能重建(同 history 的 v6 做法)。
196
+ if (!columns("quota").includes("persona")) {
197
+ db.exec(`
198
+ BEGIN;
199
+ CREATE TABLE quota_v7 (
200
+ user_id TEXT NOT NULL,
201
+ persona TEXT NOT NULL,
202
+ day TEXT NOT NULL,
203
+ tokens INTEGER NOT NULL,
204
+ PRIMARY KEY (user_id, persona, day)
205
+ );
206
+ INSERT INTO quota_v7 (user_id, persona, day, tokens)
207
+ SELECT user_id, '${personaOfDefault}', day, tokens FROM quota;
208
+ DROP TABLE quota;
209
+ ALTER TABLE quota_v7 RENAME TO quota;
210
+ COMMIT;
211
+ `);
212
+ }
213
+
214
+ if (!columns("history").includes("scope")) {
215
+ db.exec(`
216
+ BEGIN;
217
+ ALTER TABLE history RENAME TO history_v6;
218
+ CREATE TABLE history (
219
+ user_id TEXT NOT NULL,
220
+ scope TEXT NOT NULL DEFAULT '',
221
+ session_id TEXT NOT NULL,
222
+ entries TEXT NOT NULL,
223
+ updated_at TEXT NOT NULL,
224
+ persona TEXT,
225
+ PRIMARY KEY (user_id, scope, session_id)
226
+ );
227
+ INSERT INTO history (user_id, scope, session_id, entries, updated_at)
228
+ SELECT user_id, '${scopeOfDefault.replace(/'/g, "''")}', session_id, entries, updated_at FROM history_v6;
229
+ DROP TABLE history_v6;
230
+ COMMIT;
231
+ `);
232
+ }
233
+ // 会员权益:反馈分处理优先级(会员=high,report 置顶)。「会员优先」是
234
+ // 排队顺序不是门槛——老行回填 normal,语义与「当时没人排队」一致。
235
+ if (!columns("feedback").includes("priority")) {
236
+ db.exec("ALTER TABLE feedback ADD COLUMN priority TEXT NOT NULL DEFAULT 'normal'");
237
+ }
238
+ // (反馈闭环):老库补工单列。老行一律回填 kind='rating' / status='new'——
239
+ // 它们本来就是赞/踩,**不能**猜成工单,否则一上线队列里全是历史噪音。
240
+ // 人格绑进 history(与 scope 同一张表、同一生命周期)。
241
+ // **只是加列,不重建**——它不进主键。老行留空 = 未绑定,端点按请求值处理。
242
+ if (!columns("history").includes("persona")) {
243
+ db.exec("ALTER TABLE history ADD COLUMN persona TEXT");
244
+ }
245
+ // 这一行会话用的是第几版人格配置。加列不重建(不进主键)。
246
+ // **老行留空是诚实的**——那时没有版本概念,回填任何数字都是在编历史。
247
+ if (!columns("history").includes("persona_version")) {
248
+ db.exec("ALTER TABLE history ADD COLUMN persona_version INTEGER");
249
+ }
250
+ // 轮数闸也要分账(默认助手的 10 轮不该被声明人格吃掉)。老行一律回填默认人格——
251
+ // 它们本来就是默认助手会话,猜成别的会把历史算到声明人格头上。
252
+ if (!columns("runs").includes("persona")) {
253
+ db.exec(`ALTER TABLE runs ADD COLUMN persona TEXT NOT NULL DEFAULT '${personaOfDefault}'`);
254
+ }
255
+ if (!columns("feedback").includes("kind")) {
256
+ db.exec("ALTER TABLE feedback ADD COLUMN kind TEXT NOT NULL DEFAULT 'rating'");
257
+ }
258
+ if (!columns("feedback").includes("content")) db.exec("ALTER TABLE feedback ADD COLUMN content TEXT");
259
+ if (!columns("feedback").includes("status")) {
260
+ db.exec("ALTER TABLE feedback ADD COLUMN status TEXT NOT NULL DEFAULT 'new'");
261
+ }
262
+ if (!columns("feedback").includes("reply")) db.exec("ALTER TABLE feedback ADD COLUMN reply TEXT");
263
+ if (!columns("feedback").includes("handled_by")) db.exec("ALTER TABLE feedback ADD COLUMN handled_by TEXT");
264
+ if (!columns("feedback").includes("handled_at")) db.exec("ALTER TABLE feedback ADD COLUMN handled_at TEXT");
265
+ if (!columns("feedback").includes("reward_days")) db.exec("ALTER TABLE feedback ADD COLUMN reward_days INTEGER");
266
+ // 审计可见性取消名单。老库回填 0=默认可见(新口径本就默认全开)。
267
+ if (!columns("account_state").includes("audit_revoked")) {
268
+ db.exec("ALTER TABLE account_state ADD COLUMN audit_revoked INTEGER NOT NULL DEFAULT 0");
269
+ }
270
+ // 序列 4:每日总结的「看过了」标记。老库补列,值留空(= 从没弹过,符合预期)。
271
+ if (!columns("account_state").includes("last_digest_at")) {
272
+ db.exec("ALTER TABLE account_state ADD COLUMN last_digest_at TEXT");
273
+ }
274
+ // 充值订单的下单时间。老行留空是**诚实**的——那时没记过,回填
275
+ // 成 updated_at 或「今天」都是在编数据;工具侧把 null 当「时间未记录」展示。
276
+ if (!columns("billing_orders").includes("created_at")) {
277
+ db.exec("ALTER TABLE billing_orders ADD COLUMN created_at TEXT");
278
+ }
279
+ // 钱与权益加产品维度(membership/member_pool 重建 + 两处加列)。
280
+ // 迁移本身是幂等的:新库走 CREATE 已是新形状,这里直接跳过。
281
+ migrateProductDimension(db, defaultPersona);
282
+ }
283
+
284
+ /**
285
+ * 给「钱与权益」加产品(人格)维度。
286
+ *
287
+ * **先演练、后接线**:这份函数先独立存在,演练脚本直接对旧库副本调用;
288
+ * 结论没问题后再由 `openDatabase` 调它(接线)。
289
+ *
290
+ * 四件事:
291
+ * 1. `membership`:PK `(user_id)` → `(user_id, product)` ⇒ 只能重建表,老行落默认助手;
292
+ * 2. `member_pool`:PK `(user_id, month)` → `(user_id, product, month)` ⇒ 重建;
293
+ * 3. `billing_orders`:+ `kind` / `product` / `days`(幂等 ALTER;充值单 `product` 留空);
294
+ * 4. `activities`:+ `reward_product`(幂等 ALTER;老活动回填默认助手)。
295
+ *
296
+ * 三条保证:
297
+ * - **幂等**:已经是新形状就跳过,重复调用不改任何东西;
298
+ * - **不丢行**:重建时在事务内比对行数,不等就抛错并回滚;
299
+ * - **不留半个表**:建新表 → 复制 → 删旧 → 改名全在一个事务里,失败整体回滚。
300
+ *
301
+ * 回滚路径:这是**启动期结构迁移**,没有"运行时回滚按钮"。出事就恢复备份/快照,
302
+ * 或用 `billing_orders`/`activities` 的旧形状重建表(数据仍在旧列里,见演练脚本)。
303
+ */
304
+ export interface ProductMigrationReport {
305
+ /** 这次真的重建了哪些表(空 = 已经是新形状)。 */
306
+ rebuilt: Array<"membership" | "member_pool">;
307
+ /** 这次真的加上的列(`表.列`)。 */
308
+ addedColumns: string[];
309
+ /** 迁移后的行数(给演练脚本比对,部署后也可打日志)。 */
310
+ counts: { membership: number; memberPool: number; activities: number };
311
+ }
312
+
313
+ export function migrateProductDimension(db: DatabaseSync, defaultPersona: string): ProductMigrationReport {
314
+ const columns = (table: string) =>
315
+ (db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[]).map((c) => c.name);
316
+ const exists = (table: string) =>
317
+ db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table) !== undefined;
318
+ const count = (table: string) => {
319
+ try {
320
+ return (db.prepare(`SELECT COUNT(*) AS n FROM ${table}`).get() as { n: number }).n;
321
+ } catch {
322
+ return 0;
323
+ }
324
+ };
325
+ // 账本键由调用方给(core 不认识任何具体人格名);单引号转义防注入。
326
+ const product = defaultPersona.replace(/'/g, "''");
327
+ const report: ProductMigrationReport = { rebuilt: [], addedColumns: [], counts: { membership: 0, memberPool: 0, activities: 0 } };
328
+
329
+ const rebuild = (table: "membership" | "member_pool", createSql: string, copySql: string) => {
330
+ if (!exists(table) || columns(table).includes("product")) return;
331
+ const before = count(table);
332
+ db.exec("BEGIN");
333
+ try {
334
+ db.exec(createSql);
335
+ db.exec(copySql);
336
+ const copied = (db.prepare(`SELECT COUNT(*) AS n FROM ${table}_`).get() as { n: number }).n;
337
+ if (copied !== before) throw new Error(`${table}: copied ${copied} rows, expected ${before}`);
338
+ db.exec(`DROP TABLE ${table}`);
339
+ db.exec(`ALTER TABLE ${table}_ RENAME TO ${table}`);
340
+ db.exec("COMMIT");
341
+ } catch (err) {
342
+ db.exec("ROLLBACK");
343
+ throw err;
344
+ }
345
+ report.rebuilt.push(table);
346
+ };
347
+
348
+ rebuild(
349
+ "membership",
350
+ `CREATE TABLE membership_(
351
+ user_id TEXT NOT NULL,
352
+ product TEXT NOT NULL DEFAULT '${product}',
353
+ member_until TEXT NOT NULL,
354
+ granted_by TEXT,
355
+ updated_at TEXT NOT NULL,
356
+ PRIMARY KEY (user_id, product)
357
+ )`,
358
+ `INSERT INTO membership_(user_id, product, member_until, granted_by, updated_at)
359
+ SELECT user_id, '${product}', member_until, granted_by, updated_at FROM membership`,
360
+ );
361
+ rebuild(
362
+ "member_pool",
363
+ `CREATE TABLE member_pool_(
364
+ user_id TEXT NOT NULL,
365
+ product TEXT NOT NULL DEFAULT '${product}',
366
+ month TEXT NOT NULL,
367
+ granted INTEGER NOT NULL,
368
+ used INTEGER NOT NULL DEFAULT 0,
369
+ PRIMARY KEY (user_id, product, month)
370
+ )`,
371
+ `INSERT INTO member_pool_(user_id, product, month, granted, used)
372
+ SELECT user_id, '${product}', month, granted, used FROM member_pool`,
373
+ );
374
+
375
+ const add = (table: string, column: string, ddl: string) => {
376
+ if (!exists(table) || columns(table).includes(column)) return;
377
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${ddl}`);
378
+ report.addedColumns.push(`${table}.${column}`);
379
+ };
380
+ // 充值订单没有产品(钱包一本);`kind` 老行一律回填 recharge——它们本来就是充值。
381
+ add("billing_orders", "kind", "kind TEXT NOT NULL DEFAULT 'recharge'");
382
+ add("billing_orders", "product", "product TEXT");
383
+ add("billing_orders", "days", "days INTEGER");
384
+ // 老活动发放的都是默认助手那本账(当年只有它)。
385
+ add("activities", "reward_product", `reward_product TEXT NOT NULL DEFAULT '${product}'`);
386
+
387
+ report.counts = { membership: count("membership"), memberPool: count("member_pool"), activities: count("activities") };
388
+ return report;
389
+ }
390
+
391
+ export class SqliteHistoryStore implements HistoryStore {
392
+ constructor(private readonly db: DatabaseSync) {}
393
+
394
+ async load(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined> {
395
+ const row = this.db
396
+ .prepare("SELECT entries FROM history WHERE user_id = ? AND scope = ? AND session_id = ?")
397
+ .get(userId, scope, sessionId) as { entries: string } | undefined;
398
+ return row ? (JSON.parse(row.entries) as FileEntry[]) : undefined;
399
+ }
400
+
401
+ async save(userId: string, scope: string, sessionId: string, entries: FileEntry[], persona?: string, personaVersion?: number): Promise<void> {
402
+ this.db
403
+ .prepare(
404
+ `INSERT INTO history (user_id, scope, session_id, entries, updated_at, persona, persona_version) VALUES (?, ?, ?, ?, ?, ?, ?)
405
+ ON CONFLICT (user_id, scope, session_id) DO UPDATE
406
+ SET entries = excluded.entries,
407
+ updated_at = excluded.updated_at,
408
+ -- 首次绑定后不再改写:中途换人格该由端点拦(persona_mismatch),这里是第二道。
409
+ persona = COALESCE(history.persona, excluded.persona),
410
+ -- 版本与人格同一生命周期:第一轮落库那一刻定死,之后改配置也不追认。
411
+ persona_version = COALESCE(history.persona_version, excluded.persona_version)`,
412
+ )
413
+ .run(userId, scope, sessionId, JSON.stringify(entries), new Date().toISOString(), persona ?? null, personaVersion ?? null);
414
+ }
415
+
416
+ async personaOf(userId: string, sessionId: string): Promise<string | null> {
417
+ const row = this.db
418
+ .prepare("SELECT persona FROM history WHERE user_id = ? AND session_id = ? LIMIT 1")
419
+ .get(userId, sessionId) as { persona: string | null } | undefined;
420
+ return row?.persona ?? null;
421
+ }
422
+
423
+ async scopeOf(userId: string, sessionId: string): Promise<string | undefined> {
424
+ const row = this.db
425
+ .prepare("SELECT scope FROM history WHERE user_id = ? AND session_id = ? LIMIT 1")
426
+ .get(userId, sessionId) as { scope: string } | undefined;
427
+ return row?.scope;
428
+ }
429
+
430
+ // ponytail: parses every stored session blob per list (newest 50); ceiling ~hundreds of
431
+ // sessions per user. Upgrade path: persist `title`/`message_count` columns at save time.
432
+ async list(userId: string, scope?: string): Promise<SessionSummary[]> {
433
+ const where = scope === undefined ? "user_id = ?" : "user_id = ? AND scope = ?";
434
+ const args = scope === undefined ? [userId] : [userId, scope];
435
+ const rows = this.db
436
+ .prepare(`SELECT session_id, scope, entries, updated_at, persona FROM history WHERE ${where} ORDER BY updated_at DESC LIMIT 50`)
437
+ .all(...args) as { session_id: string; scope: string; entries: string; updated_at: string; persona: string | null }[];
438
+ return rows.map((r) => {
439
+ const { title, messageCount } = summarizeHistory(JSON.parse(r.entries) as FileEntry[]);
440
+ return { sessionId: r.session_id, scope: r.scope, title, updatedAt: r.updated_at, messageCount, persona: r.persona };
441
+ });
442
+ }
443
+ }
444
+
445
+ /** Per-user token budget per day, persisted in the quota table. */
446
+ export class SqliteQuotaGate implements QuotaGate {
447
+ constructor(
448
+ private readonly db: DatabaseSync,
449
+ private readonly dailyTokens: number | undefined,
450
+ private readonly now: () => Date = () => new Date(),
451
+ ) {}
452
+
453
+ private day(): string {
454
+ return this.now().toISOString().slice(0, 10);
455
+ }
456
+
457
+ async check(userId: string, caps: QuotaCaps | undefined, persona: string): Promise<QuotaDecision> {
458
+ // 轮数闸先查(429 文案要区分「次数到」与「额度到」);runCap<=0 视为不限。
459
+ if (caps?.runCap !== undefined && caps.runCap > 0) {
460
+ const runs = this.db
461
+ .prepare("SELECT COUNT(*) AS n FROM runs WHERE user_id = ? AND persona = ? AND substr(started_at, 1, 10) = ?")
462
+ .get(userId, persona, this.day()) as { n: number };
463
+ if (runs.n >= caps.runCap)
464
+ return {
465
+ ok: false,
466
+ reason: quotaBlockedReason("runs", { runCap: caps.runCap, tokenCap: caps?.tokenCap ?? this.dailyTokens }),
467
+ };
468
+ }
469
+ const tokenCap = caps?.tokenCap ?? this.dailyTokens;
470
+ if (tokenCap === undefined) return { ok: true };
471
+ const row = this.db
472
+ .prepare("SELECT tokens FROM quota WHERE user_id = ? AND persona = ? AND day = ?")
473
+ .get(userId, persona, this.day()) as { tokens: number } | undefined;
474
+ return (row?.tokens ?? 0) >= tokenCap
475
+ ? { ok: false, reason: quotaBlockedReason("tokens", { runCap: caps?.runCap, tokenCap }) }
476
+ : { ok: true };
477
+ }
478
+
479
+ async todayStats(userId: string, persona: string): Promise<{ runsToday: number; tokensToday: number }> {
480
+ const runs = this.db
481
+ .prepare("SELECT COUNT(*) AS n FROM runs WHERE user_id = ? AND persona = ? AND substr(started_at, 1, 10) = ?")
482
+ .get(userId, persona, this.day()) as { n: number };
483
+ const quota = this.db
484
+ .prepare("SELECT tokens FROM quota WHERE user_id = ? AND persona = ? AND day = ?")
485
+ .get(userId, persona, this.day()) as { tokens: number } | undefined;
486
+ return { runsToday: runs.n, tokensToday: quota?.tokens ?? 0 };
487
+ }
488
+
489
+ async record(userId: string, usage: TokenUsage, persona: string): Promise<void> {
490
+ this.db
491
+ .prepare(
492
+ `INSERT INTO quota (user_id, persona, day, tokens) VALUES (?, ?, ?, ?)
493
+ ON CONFLICT (user_id, persona, day) DO UPDATE SET tokens = tokens + excluded.tokens`,
494
+ )
495
+ .run(userId, persona, this.day(), usage.total);
496
+ }
497
+ }
498
+
499
+ /** 会员有效期,SQLite 实现。 */
500
+ export class SqliteMembership implements MembershipStore {
501
+ constructor(private readonly db: DatabaseSync) {}
502
+
503
+ async get(userId: string, product: string): Promise<string | null> {
504
+ assertProductId(product);
505
+ const row = this.db.prepare("SELECT member_until FROM membership WHERE user_id = ? AND product = ?").get(userId, product) as
506
+ | { member_until: string }
507
+ | undefined;
508
+ return row?.member_until ?? null;
509
+ }
510
+ async set(userId: string, product: string, memberUntil: string, grantedBy?: string): Promise<void> {
511
+ assertMembershipWrite(product, memberUntil);
512
+ this.db
513
+ .prepare(
514
+ `INSERT INTO membership (user_id, product, member_until, granted_by, updated_at) VALUES (?, ?, ?, ?, ?)
515
+ ON CONFLICT (user_id, product) DO UPDATE SET member_until = excluded.member_until,
516
+ granted_by = excluded.granted_by, updated_at = excluded.updated_at`,
517
+ )
518
+ .run(userId, product, memberUntil, grantedBy ?? null, new Date().toISOString());
519
+ }
520
+ /**
521
+ * 原子续期:一条 SQL 完成 `max(now, 现到期) + days`。
522
+ * 为什么不先 get 再 set:并发发放(购买 + 活动奖励)会互相覆盖。
523
+ * `strftime('%Y-%m-%dT%H:%M:%fZ', …)` 保住 ISO 形状——`datetime()` 会吐出
524
+ * "YYYY-MM-DD HH:MM:SS"(无 T/Z),前端 `Date.parse` 会按本地时区解释。
525
+ */
526
+ async extend(userId: string, product: string, days: number, grantedBy?: string): Promise<string> {
527
+ assertProductId(product);
528
+ if (!Number.isInteger(days) || days < 1) throw new Error(`membership days must be a positive integer, got ${days}`);
529
+ const now = new Date().toISOString();
530
+ const row = this.db
531
+ .prepare(
532
+ `INSERT INTO membership (user_id, product, member_until, granted_by, updated_at)
533
+ VALUES (?, ?, strftime('%Y-%m-%dT%H:%M:%fZ', ?, '+' || ? || ' days'), ?, ?)
534
+ ON CONFLICT (user_id, product) DO UPDATE SET
535
+ member_until = strftime('%Y-%m-%dT%H:%M:%fZ', MAX(membership.member_until, ?), '+' || ? || ' days'),
536
+ granted_by = excluded.granted_by,
537
+ updated_at = excluded.updated_at
538
+ RETURNING member_until`,
539
+ )
540
+ .get(userId, product, now, days, grantedBy ?? null, now, now, days) as { member_until: string };
541
+ return row.member_until;
542
+ }
543
+ async remove(userId: string, product: string): Promise<void> {
544
+ assertProductId(product);
545
+ this.db.prepare("DELETE FROM membership WHERE user_id = ? AND product = ?").run(userId, product);
546
+ }
547
+ async list() {
548
+ return this.db
549
+ .prepare("SELECT user_id, product, member_until, granted_by FROM membership ORDER BY updated_at DESC")
550
+ .all()
551
+ .map((r) => ({
552
+ userId: String((r as Record<string, unknown>).user_id),
553
+ product: String((r as Record<string, unknown>).product),
554
+ memberUntil: String((r as Record<string, unknown>).member_until),
555
+ grantedBy: ((r as Record<string, unknown>).granted_by as string | null) ?? null,
556
+ }));
557
+ }
558
+ async hasAnyActive(userId: string): Promise<boolean> {
559
+ // 粗粒度标记(authz 的 member 角色):任一本账在期即为真。额度不走这里。
560
+ return this.db
561
+ .prepare("SELECT 1 AS ok FROM membership WHERE user_id = ? AND member_until > ? LIMIT 1")
562
+ .get(userId, new Date().toISOString()) !== undefined;
563
+ }
564
+ }
565
+
566
+ /** 封号状态,SQLite 实现。 */
567
+ export class SqliteAccountState implements AccountStateStore {
568
+ constructor(
569
+ private readonly db: DatabaseSync,
570
+ private readonly now: () => Date = () => new Date(),
571
+ ) {}
572
+
573
+ async activeBan(userId: string): Promise<string | null> {
574
+ const row = this.db.prepare("SELECT banned_until FROM account_state WHERE user_id = ?").get(userId) as
575
+ | { banned_until: string | null }
576
+ | undefined;
577
+ return row?.banned_until && new Date(row.banned_until) > this.now() ? row.banned_until : null;
578
+ }
579
+ async get(userId: string) {
580
+ const row = this.db.prepare("SELECT banned_until, reason FROM account_state WHERE user_id = ?").get(userId) as
581
+ | { banned_until: string | null; reason: string | null }
582
+ | undefined;
583
+ return { bannedUntil: row?.banned_until ?? null, reason: row?.reason ?? null };
584
+ }
585
+ async setBan(userId: string, bannedUntil: string, reason: string): Promise<void> {
586
+ this.db
587
+ .prepare(
588
+ `INSERT INTO account_state (user_id, banned_until, reason, updated_at) VALUES (?, ?, ?, ?)
589
+ ON CONFLICT (user_id) DO UPDATE SET banned_until = excluded.banned_until,
590
+ reason = excluded.reason, updated_at = excluded.updated_at`,
591
+ )
592
+ .run(userId, bannedUntil, reason, new Date().toISOString());
593
+ }
594
+ async removeBan(userId: string): Promise<void> {
595
+ this.db
596
+ .prepare(
597
+ `INSERT INTO account_state (user_id, banned_until, reason, updated_at) VALUES (?, NULL, NULL, ?)
598
+ ON CONFLICT (user_id) DO UPDATE SET banned_until = NULL, reason = NULL, updated_at = excluded.updated_at`,
599
+ )
600
+ .run(userId, new Date().toISOString());
601
+ }
602
+ async auditRevoked(userId: string): Promise<boolean> {
603
+ const row = this.db.prepare("SELECT audit_revoked FROM account_state WHERE user_id = ?").get(userId) as
604
+ | { audit_revoked: number }
605
+ | undefined;
606
+ return (row?.audit_revoked ?? 0) === 1;
607
+ }
608
+ async setAuditRevoked(userId: string, revoked: boolean): Promise<void> {
609
+ this.db
610
+ .prepare(
611
+ `INSERT INTO account_state (user_id, audit_revoked, updated_at) VALUES (?, ?, ?)
612
+ ON CONFLICT (user_id) DO UPDATE SET audit_revoked = excluded.audit_revoked, updated_at = excluded.updated_at`,
613
+ )
614
+ .run(userId, revoked ? 1 : 0, new Date().toISOString());
615
+ }
616
+ async digestSeenAt(userId: string): Promise<string | null> {
617
+ const row = this.db.prepare("SELECT last_digest_at FROM account_state WHERE user_id = ?").get(userId) as
618
+ | { last_digest_at: string | null }
619
+ | undefined;
620
+ return row?.last_digest_at ?? null;
621
+ }
622
+ async markDigestSeen(userId: string, at: string): Promise<void> {
623
+ this.db
624
+ .prepare(
625
+ `INSERT INTO account_state (user_id, last_digest_at, updated_at) VALUES (?, ?, ?)
626
+ ON CONFLICT (user_id) DO UPDATE SET last_digest_at = excluded.last_digest_at, updated_at = excluded.updated_at`,
627
+ )
628
+ .run(userId, at, new Date().toISOString());
629
+ }
630
+ async list() {
631
+ return this.db
632
+ .prepare("SELECT user_id, banned_until, reason, audit_revoked FROM account_state ORDER BY updated_at DESC")
633
+ .all()
634
+ .map((r) => ({
635
+ userId: String((r as Record<string, unknown>).user_id),
636
+ bannedUntil: ((r as Record<string, unknown>).banned_until as string | null) ?? null,
637
+ reason: ((r as Record<string, unknown>).reason as string | null) ?? null,
638
+ auditRevoked: ((r as Record<string, unknown>).audit_revoked as number) === 1,
639
+ }));
640
+ }
641
+ }
642
+
643
+ /** 会员月度池:INSERT OR IGNORE 让 lazy 发放幂等——当月只发一次。 */
644
+ export class SqliteMemberPool implements MemberPoolStore {
645
+ constructor(private readonly db: DatabaseSync) {}
646
+
647
+ async getOrGrant(userId: string, product: string, month: string, grantAmount: number): Promise<MemberPoolRow> {
648
+ if (grantAmount > 0) {
649
+ this.db
650
+ .prepare("INSERT OR IGNORE INTO member_pool (user_id, product, month, granted, used) VALUES (?, ?, ?, ?, 0)")
651
+ .run(userId, product, month, grantAmount);
652
+ }
653
+ const row = this.db
654
+ .prepare("SELECT granted, used FROM member_pool WHERE user_id = ? AND product = ? AND month = ?")
655
+ .get(userId, product, month) as { granted: number; used: number } | undefined;
656
+ return { product, month, granted: row?.granted ?? 0, used: row?.used ?? 0 };
657
+ }
658
+
659
+ async addUsed(userId: string, product: string, month: string, tokens: number): Promise<void> {
660
+ this.db
661
+ .prepare("UPDATE member_pool SET used = used + ? WHERE user_id = ? AND product = ? AND month = ?")
662
+ .run(tokens, userId, product, month);
663
+ }
664
+ }
665
+
666
+
667
+ /** Persisted run log; backs GET /api/usage and the admin report. */
668
+ export class SqliteRunLog implements RunLogStore {
669
+ constructor(private readonly db: DatabaseSync) {}
670
+
671
+ async record(run: RunLogRecord): Promise<void> {
672
+ this.db
673
+ .prepare(
674
+ `INSERT INTO runs (user_id, session_id, product, persona, started_at, duration_ms, tool_rounds, aborted, tokens, cost_usd, error)
675
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
676
+ )
677
+ .run(
678
+ run.userId,
679
+ run.sessionId,
680
+ run.product,
681
+ run.persona,
682
+ run.startedAt,
683
+ run.durationMs,
684
+ run.toolRounds,
685
+ run.aborted ? 1 : 0,
686
+ run.usage.total,
687
+ run.usage.costUsd,
688
+ run.error ?? null,
689
+ );
690
+ }
691
+
692
+ async summary(userId: string): Promise<RunUsageSummary> {
693
+ const day = new Date().toISOString().slice(0, 10);
694
+ const tot = this.db
695
+ .prepare("SELECT COUNT(*) AS runs, COALESCE(SUM(tokens),0) AS tokens, COALESCE(SUM(cost_usd),0) AS cost FROM runs WHERE user_id = ?")
696
+ .get(userId) as { runs: number; tokens: number; cost: number };
697
+ const today = this.db
698
+ .prepare("SELECT COALESCE(SUM(tokens),0) AS tokens FROM runs WHERE user_id = ? AND started_at >= ? AND started_at < ?")
699
+ .get(userId, `${day}T00:00:00.000Z`, `${day}T23:59:59.999Z`) as { tokens: number };
700
+ const rows = this.db
701
+ .prepare("SELECT * FROM runs WHERE user_id = ? ORDER BY id DESC LIMIT 10")
702
+ .all(userId) as Array<Record<string, string | number | null>>;
703
+ return {
704
+ day,
705
+ tokensToday: today.tokens,
706
+ totalRuns: tot.runs,
707
+ totalTokens: tot.tokens,
708
+ totalCostUsd: tot.cost,
709
+ recent: rows.map((r) => ({
710
+ userId: String(r.user_id),
711
+ sessionId: String(r.session_id),
712
+ product: String(r.product),
713
+ // 老行由迁移时的 DEFAULT 回填成"当时的默认助手",不会是 NULL。
714
+ persona: String(r.persona),
715
+ startedAt: String(r.started_at),
716
+ durationMs: Number(r.duration_ms),
717
+ toolRounds: Number(r.tool_rounds),
718
+ aborted: r.aborted === 1,
719
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: Number(r.tokens), costUsd: Number(r.cost_usd) },
720
+ error: r.error == null ? undefined : String(r.error),
721
+ })),
722
+ };
723
+ }
724
+
725
+ async report(): Promise<RunUsageReport> {
726
+ const users = this.db
727
+ .prepare("SELECT user_id, COUNT(*) AS runs, SUM(tokens) AS tokens, SUM(cost_usd) AS cost FROM runs GROUP BY user_id ORDER BY tokens DESC")
728
+ .all() as Array<{ user_id: string; runs: number; tokens: number; cost: number }>;
729
+ const products = this.db
730
+ .prepare("SELECT product, COUNT(*) AS runs, SUM(tokens) AS tokens, SUM(cost_usd) AS cost FROM runs GROUP BY product ORDER BY tokens DESC")
731
+ .all() as Array<{ product: string; runs: number; tokens: number; cost: number }>;
732
+ return {
733
+ users: users.map((u) => ({ userId: u.user_id, runs: u.runs, tokens: u.tokens, costUsd: u.cost })),
734
+ products: products.map((p) => ({ product: p.product, runs: p.runs, tokens: p.tokens, costUsd: p.cost })),
735
+ };
736
+ }
737
+ }
738
+
739
+ /** Balance + ledger in cents; adjust is one atomic upsert, so concurrent runs never lose a deduction. */
740
+ export class SqliteBilling implements BillingStore {
741
+ constructor(private readonly db: DatabaseSync) {}
742
+
743
+ async balance(userId: string) {
744
+ const row = this.db.prepare("SELECT balance FROM billing_balance WHERE user_id = ?").get(userId) as { balance: number } | undefined;
745
+ return row?.balance ?? 0;
746
+ }
747
+
748
+ async adjust(userId: string, deltaCents: number, kind: BillingEntry["kind"], ref?: string, opts?: BillingAdjustOpts) {
749
+ // kind="adjust"(管理端调整)的 ledger 行存**带符号**金额:这类行的方向没有
750
+ // kind 可推断(正负都合法),前端靠符号画 +/−。其余 kind 维持 abs(协议:
751
+ // recharge/spend/membership 行金额恒为正,方向由 kind 给出)。
752
+ const ledgerAmount = kind === "adjust" ? deltaCents : Math.abs(deltaCents);
753
+ // 负 delta 走条件 UPDATE(余额闸):`ON CONFLICT … WHERE` 只约束 UPDATE 分支,
754
+ // 直接 upsert 的话「用户无行 + 负 delta」会从 INSERT 直插一个负余额。
755
+ // 正 delta 维持原来的原子 upsert(并发扣款不会互相吃掉对方的写入)。
756
+ // 条件 UPDATE 是同步语句,两条语句之间事件循环不让出,无中途穿插。
757
+ if (deltaCents < 0 && !opts?.allowNegative) {
758
+ const gated = this.db
759
+ .prepare(
760
+ `UPDATE billing_balance SET balance = balance + ? WHERE user_id = ? AND balance + ? >= 0 RETURNING balance`,
761
+ )
762
+ .get(deltaCents, userId, deltaCents) as { balance: number } | undefined;
763
+ if (!gated) return null; // 闸住:余额不够,一个字节都没写(含 ledger)
764
+ this.db
765
+ .prepare("INSERT INTO billing_ledger (user_id, at, kind, amount_cents, balance_after, ref) VALUES (?, ?, ?, ?, ?, ?)")
766
+ .run(userId, new Date().toISOString(), kind, ledgerAmount, gated.balance, ref ?? null);
767
+ return gated.balance;
768
+ }
769
+ const { balance } = this.db
770
+ .prepare(
771
+ `INSERT INTO billing_balance (user_id, balance) VALUES (?, ?)
772
+ ON CONFLICT (user_id) DO UPDATE SET balance = balance + excluded.balance
773
+ RETURNING balance`,
774
+ )
775
+ .get(userId, deltaCents) as { balance: number };
776
+ this.db
777
+ .prepare("INSERT INTO billing_ledger (user_id, at, kind, amount_cents, balance_after, ref) VALUES (?, ?, ?, ?, ?, ?)")
778
+ .run(userId, new Date().toISOString(), kind, ledgerAmount, balance, ref ?? null);
779
+ return balance;
780
+ }
781
+
782
+ async ledger(userId: string, limit = 20): Promise<BillingEntry[]> {
783
+ const rows = this.db
784
+ .prepare("SELECT * FROM billing_ledger WHERE user_id = ? ORDER BY id DESC LIMIT ?")
785
+ .all(userId, limit) as Array<Record<string, string | number | null>>;
786
+ return rows.map((r) => ({
787
+ at: String(r.at),
788
+ kind: String(r.kind) as BillingEntry["kind"],
789
+ amountCents: Number(r.amount_cents),
790
+ balanceAfter: Number(r.balance_after),
791
+ ref: r.ref == null ? undefined : String(r.ref),
792
+ }));
793
+ }
794
+
795
+ async createOrder(userId: string, amountCents: number, meta: NewOrderMeta = {}) {
796
+ const id = `ord_${randomUUID().slice(0, 8)}`;
797
+ this.db
798
+ .prepare(
799
+ `INSERT INTO billing_orders (id, user_id, amount_cents, status, created_at, kind, product, days)
800
+ VALUES (?, ?, ?, 'pending', ?, ?, ?, ?)`,
801
+ )
802
+ .run(
803
+ id,
804
+ userId,
805
+ amountCents,
806
+ new Date().toISOString(),
807
+ meta.kind ?? "recharge",
808
+ meta.product ?? null,
809
+ meta.days ?? null,
810
+ );
811
+ return id;
812
+ }
813
+
814
+ async getOrder(orderId: string): Promise<BillingOrder | null> {
815
+ const r = this.db
816
+ .prepare("SELECT id, user_id, amount_cents, status, kind, product, days FROM billing_orders WHERE id = ?")
817
+ .get(orderId) as Record<string, unknown> | undefined;
818
+ if (!r) return null;
819
+ const status = String(r.status);
820
+ return {
821
+ id: String(r.id),
822
+ userId: String(r.user_id),
823
+ amountCents: Number(r.amount_cents),
824
+ // 四种状态原样透出:把 cancelled/expired 折成 pending 会让"已关闭的单"看起来
825
+ // 还能付,正是这次要堵的洞。
826
+ status:
827
+ status === "paid" ? "paid" : status === "cancelled" ? "cancelled" : status === "expired" ? "expired" : "pending",
828
+ kind: r.kind === "membership" ? "membership" : "recharge",
829
+ product: r.product == null ? null : String(r.product),
830
+ days: r.days == null ? null : Number(r.days),
831
+ };
832
+ }
833
+
834
+ async pendingOrders(userId: string): Promise<Array<BillingOrder & { createdAt: string | null }>> {
835
+ // created_at IS NULL 排最后(老库补列前的行没有可信时间),新单在前。
836
+ const rows = this.db
837
+ .prepare(
838
+ "SELECT id, amount_cents, kind, product, days, created_at FROM billing_orders WHERE user_id = ? AND status = 'pending' ORDER BY (created_at IS NULL), created_at DESC",
839
+ )
840
+ .all(userId) as Array<Record<string, unknown>>;
841
+ return rows.map((r) => ({
842
+ id: String(r.id),
843
+ userId,
844
+ amountCents: Number(r.amount_cents),
845
+ status: "pending" as const,
846
+ kind: r.kind === "membership" ? ("membership" as const) : ("recharge" as const),
847
+ product: r.product == null ? null : String(r.product),
848
+ days: r.days == null ? null : Number(r.days),
849
+ createdAt: r.created_at == null ? null : String(r.created_at),
850
+ }));
851
+ }
852
+
853
+ async claimOrder(orderId: string): Promise<"claimed" | "already" | "cancelled" | "expired" | "unknown"> {
854
+ // Conditional flip claims the order; a racing fulfill that loses it reports the real state.
855
+ const claimed = this.db.prepare("UPDATE billing_orders SET status = 'paid' WHERE id = ? AND status = 'pending'").run(orderId);
856
+ if (claimed.changes === 0) {
857
+ const row = this.db.prepare("SELECT status FROM billing_orders WHERE id = ?").get(orderId) as { status?: string } | undefined;
858
+ if (!row) return "unknown";
859
+ if (row.status === "cancelled") return "cancelled";
860
+ if (row.status === "expired") return "expired";
861
+ return "already"; // paid(或历史脏值)
862
+ }
863
+ return "claimed";
864
+ }
865
+
866
+ async cancelOrder(orderId: string, userId: string): Promise<"cancelled" | "not_pending" | "unknown"> {
867
+ const done = this.db
868
+ .prepare("UPDATE billing_orders SET status = 'cancelled' WHERE id = ? AND user_id = ? AND status = 'pending'")
869
+ .run(orderId, userId);
870
+ if (done.changes > 0) return "cancelled";
871
+ // 没改到:要么不是他的单(连存在性都不该告诉他),要么已经付了/关了。
872
+ const row = this.db.prepare("SELECT user_id, status FROM billing_orders WHERE id = ?").get(orderId) as
873
+ | { user_id?: string; status?: string }
874
+ | undefined;
875
+ if (!row || row.user_id !== userId) return "unknown";
876
+ return "not_pending";
877
+ }
878
+
879
+ async expireStaleOrders(ttlMs: number, nowMs = Date.now()): Promise<number> {
880
+ // 只清 pending:已付的单不管多久都不能动(那是账,不是垃圾)。
881
+ const cutoff = new Date(nowMs - ttlMs).toISOString();
882
+ const res = this.db
883
+ .prepare("UPDATE billing_orders SET status = 'expired' WHERE status = 'pending' AND created_at IS NOT NULL AND created_at < ?")
884
+ .run(cutoff);
885
+ return Number(res.changes);
886
+ }
887
+
888
+ async releaseOrder(orderId: string): Promise<boolean> {
889
+ // 只放回「刚被认领、业务还没做成」的单;对已完成的单是 no-op。
890
+ return this.db.prepare("UPDATE billing_orders SET status = 'pending' WHERE id = ? AND status = 'paid'").run(orderId).changes > 0;
891
+ }
892
+
893
+ async fulfillOrder(orderId: string): Promise<"credited" | "already" | "unknown" | "wrong_kind" | "closed"> {
894
+ const order = await this.getOrder(orderId);
895
+ if (!order) return "unknown";
896
+ if (order.kind !== "recharge") return "wrong_kind";
897
+ if (order.status === "paid") return "already";
898
+ if (order.status === "cancelled" || order.status === "expired") return "closed";
899
+ const claim = await this.claimOrder(orderId);
900
+ if (claim === "cancelled" || claim === "expired") return "closed";
901
+ if (claim !== "claimed") return "already";
902
+ await this.adjust(order.userId, order.amountCents, "recharge", orderId);
903
+ return "credited";
904
+ }
905
+ }
906
+
907
+
908
+ /** audit_log 行 → 领域行(roles/meta 反序列化;hash 重算侧再做规范化,存储串格式不参与)。 */
909
+ function mapAuditRow(r: Record<string, string | number | null>): AuditRow {
910
+ return {
911
+ id: Number(r.id),
912
+ at: String(r.at),
913
+ actor: String(r.actor),
914
+ roles: JSON.parse(String(r.roles)) as string[],
915
+ action: String(r.action),
916
+ target: r.target == null ? null : String(r.target),
917
+ result: String(r.result) as AuditRow["result"],
918
+ reason: r.reason == null ? null : String(r.reason),
919
+ meta: JSON.parse(String(r.meta)) as Record<string, unknown>,
920
+ prevHash: String(r.prev_hash),
921
+ hash: String(r.hash),
922
+ };
923
+ }
924
+
925
+ /**
926
+ * 审计哈希链的 SQLite 实现(/;表见 openDatabase DDL 块)。
927
+ * append 全程同步:读链尾与 INSERT 之间没有 await,单事件循环内不会有两个 append 交错;
928
+ * purge 同理(①读齐+白名单入链 ②删除,两步不反, 5B)。
929
+ */
930
+ export class SqliteAudit implements AuditStore {
931
+ constructor(private readonly db: DatabaseSync, private readonly now: () => Date = () => new Date()) {}
932
+
933
+ async append(e: AuditEvent): Promise<number> {
934
+ return this.appendSync(e);
935
+ }
936
+
937
+ /** 同步内核:purge 要在同一同步段里「白名单先入链、再删行」,不能经 await 让出。 */
938
+ private appendSync(e: AuditEvent): number {
939
+ const meta = e.meta ?? {};
940
+ assertNoSensitiveKeys(meta);
941
+ const body = {
942
+ at: e.at ?? this.now().toISOString(),
943
+ actor: e.actor,
944
+ roles: e.roles ?? [],
945
+ action: e.action,
946
+ target: e.target ?? null,
947
+ result: e.result,
948
+ reason: e.reason ?? null,
949
+ meta,
950
+ };
951
+ const last = this.db.prepare("SELECT hash FROM audit_log ORDER BY id DESC LIMIT 1").get() as { hash: string } | undefined;
952
+ const prevHash = last?.hash ?? GENESIS_HASH;
953
+ const info = this.db
954
+ .prepare(
955
+ `INSERT INTO audit_log (at, actor, roles, action, target, result, reason, meta, prev_hash, hash)
956
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
957
+ )
958
+ .run(
959
+ body.at,
960
+ body.actor,
961
+ canonicalize(body.roles),
962
+ body.action,
963
+ body.target,
964
+ body.result,
965
+ body.reason,
966
+ canonicalize(body.meta),
967
+ prevHash,
968
+ rowHash(prevHash, body),
969
+ );
970
+ return Number(info.lastInsertRowid);
971
+ }
972
+
973
+ async query(q: AuditQuery): Promise<{ rows: AuditRow[]; total: number }> {
974
+ const clauses: string[] = [];
975
+ const args: Array<string | number> = [];
976
+ if (q.from) {
977
+ clauses.push("at >= ?");
978
+ args.push(q.from);
979
+ }
980
+ if (q.to) {
981
+ clauses.push("at <= ?");
982
+ args.push(q.to);
983
+ }
984
+ if (q.actionPrefix) {
985
+ clauses.push("action LIKE ? || '%'");
986
+ args.push(q.actionPrefix);
987
+ }
988
+ if (q.actor) {
989
+ clauses.push("actor = ?");
990
+ args.push(q.actor);
991
+ }
992
+ if (q.subject) {
993
+ // 「我做的 + 针对我的」。ponytail: OR 走 actor/target 两索引的
994
+ // or-optimization,v1 量级够用;升级路径=物化 subject 列或 UNION 查询。
995
+ clauses.push("(actor = ? OR target = ?)");
996
+ args.push(q.subject, `user:${q.subject}`);
997
+ }
998
+ if (q.result) {
999
+ clauses.push("result = ?");
1000
+ args.push(q.result);
1001
+ }
1002
+ const where = clauses.length ? `WHERE ${clauses.join(" AND ")}` : "";
1003
+ const total = Number((this.db.prepare(`SELECT COUNT(*) AS n FROM audit_log ${where}`).get(...args) as { n: number }).n);
1004
+ const { limit, offset } = auditPageWindow(q);
1005
+ const rows = this.db.prepare(`SELECT * FROM audit_log ${where} ORDER BY id DESC LIMIT ? OFFSET ?`).all(...args, limit, offset) as Array<Record<string, string | number | null>>;
1006
+ return { rows: rows.map(mapAuditRow), total };
1007
+ }
1008
+
1009
+ async get(id: number): Promise<AuditRow | null> {
1010
+ const r = this.db.prepare("SELECT * FROM audit_log WHERE id = ?").get(id) as Record<string, string | number | null> | undefined;
1011
+ return r ? mapAuditRow(r) : null;
1012
+ }
1013
+
1014
+ async verify(): Promise<VerifyResult> {
1015
+ // 全表升序扫:v1 量级下 SQLite 顺序扫足够快。
1016
+ const rows = this.db.prepare("SELECT * FROM audit_log ORDER BY id ASC").all() as Array<Record<string, string | number | null>>;
1017
+ return verifyChain(rows.map(mapAuditRow));
1018
+ }
1019
+
1020
+ async purge(cutoffIso: string): Promise<number> {
1021
+ const doomed = this.db
1022
+ .prepare("SELECT id, hash FROM audit_log WHERE at < ? AND (action LIKE 'run.%' OR action LIKE 'biz.%') ORDER BY id ASC")
1023
+ .all(cutoffIso) as Array<{ id: number | bigint; hash: string }>;
1024
+ if (!doomed.length) return 0;
1025
+ const ids = doomed.map((d) => Number(d.id));
1026
+ // ①白名单行先入链(last_hash=段尾行存储 hash,删前读取)。
1027
+ this.appendSync({
1028
+ actor: "system",
1029
+ action: "ops.audit.purge",
1030
+ result: "ok",
1031
+ meta: { cutoff: cutoffIso, count: ids.length, segments: segmentsFrom(doomed.map((d) => ({ id: Number(d.id), hash: d.hash }))) },
1032
+ });
1033
+ // ②再物理删(IN 分块,防变量数上限)。
1034
+ for (let i = 0; i < ids.length; i += 500) {
1035
+ const chunk = ids.slice(i, i + 500);
1036
+ this.db.prepare(`DELETE FROM audit_log WHERE id IN (${chunk.map(() => "?").join(",")})`).run(...chunk);
1037
+ }
1038
+ return ids.length;
1039
+ }
1040
+ }