@njuptlzf/agent-chat-server 0.1.2 → 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.
Files changed (44) hide show
  1. package/dist/audit.d.ts +54 -0
  2. package/dist/audit.js +133 -0
  3. package/dist/authz.d.ts +134 -0
  4. package/dist/authz.js +238 -0
  5. package/dist/events.d.ts +33 -0
  6. package/dist/events.js +169 -0
  7. package/dist/index.d.ts +16 -0
  8. package/dist/index.js +4 -0
  9. package/dist/main.d.ts +1 -0
  10. package/dist/main.js +126 -0
  11. package/dist/manifest.d.ts +147 -0
  12. package/dist/manifest.js +491 -0
  13. package/dist/mcp-config.d.ts +87 -0
  14. package/dist/mcp-config.js +353 -0
  15. package/dist/model-config.d.ts +123 -0
  16. package/dist/model-config.js +371 -0
  17. package/dist/model-failover.d.ts +42 -0
  18. package/dist/model-failover.js +82 -0
  19. package/dist/models-api.d.ts +98 -0
  20. package/dist/models-api.js +326 -0
  21. package/dist/persona-config.d.ts +112 -0
  22. package/dist/persona-config.js +368 -0
  23. package/dist/persona-trial.d.ts +50 -0
  24. package/dist/persona-trial.js +77 -0
  25. package/dist/product-routes.d.ts +35 -0
  26. package/dist/product-routes.js +92 -0
  27. package/dist/server.d.ts +162 -0
  28. package/dist/server.js +2572 -0
  29. package/dist/session.d.ts +218 -0
  30. package/dist/session.js +545 -0
  31. package/dist/sqlite-stores.d.ts +173 -0
  32. package/dist/sqlite-stores.js +921 -0
  33. package/dist/stores.d.ts +506 -0
  34. package/dist/stores.js +614 -0
  35. package/dist/testing.d.ts +42 -0
  36. package/dist/testing.js +47 -0
  37. package/dist/trial-grant.d.ts +40 -0
  38. package/dist/trial-grant.js +24 -0
  39. package/dist/usage-report.d.ts +23 -0
  40. package/dist/usage-report.js +68 -0
  41. package/dist/util.d.ts +3 -0
  42. package/dist/util.js +5 -0
  43. package/package.json +16 -10
  44. package/scripts/agentchat-integrate.mjs +852 -607
@@ -0,0 +1,173 @@
1
+ import { DatabaseSync } from "node:sqlite";
2
+ import type { FileEntry } from "@earendil-works/pi-coding-agent";
3
+ import type { SessionSummary, TokenUsage } from "@njuptlzf/agent-chat-protocol";
4
+ 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";
5
+ import type { VerifyResult } from "./audit.ts";
6
+ /**
7
+ * SQLite-backed stores (node:sqlite, no extra dependency). One connection per
8
+ * process: SQLite serializes writes, so quota increments are atomic and never
9
+ * lost. The quota cap is enforced at run start; a concurrent run may still
10
+ * overshoot by its own usage before its record lands — same semantics as the
11
+ * in-memory gate, and enough to bound spend.
12
+ *
13
+ * `scope` partitions user data:
14
+ * history is keyed by (user, scope, …). Balance and quota deliberately stay
15
+ * global — cost is a property of the person, not the scope.
16
+ *
17
+ * 业务表(attempts / essays / …)由产品侧独立迁移链负责,本链只建 12 张通用表。
18
+ */
19
+ export declare function openDatabase(file: string, defaultScope?: string, defaultPersona?: string): DatabaseSync;
20
+ /**
21
+ * 给「钱与权益」加产品(人格)维度。
22
+ *
23
+ * **先演练、后接线**:这份函数先独立存在,演练脚本直接对旧库副本调用;
24
+ * 结论没问题后再由 `openDatabase` 调它(接线)。
25
+ *
26
+ * 四件事:
27
+ * 1. `membership`:PK `(user_id)` → `(user_id, product)` ⇒ 只能重建表,老行落默认助手;
28
+ * 2. `member_pool`:PK `(user_id, month)` → `(user_id, product, month)` ⇒ 重建;
29
+ * 3. `billing_orders`:+ `kind` / `product` / `days`(幂等 ALTER;充值单 `product` 留空);
30
+ * 4. `activities`:+ `reward_product`(幂等 ALTER;老活动回填默认助手)。
31
+ *
32
+ * 三条保证:
33
+ * - **幂等**:已经是新形状就跳过,重复调用不改任何东西;
34
+ * - **不丢行**:重建时在事务内比对行数,不等就抛错并回滚;
35
+ * - **不留半个表**:建新表 → 复制 → 删旧 → 改名全在一个事务里,失败整体回滚。
36
+ *
37
+ * 回滚路径:这是**启动期结构迁移**,没有"运行时回滚按钮"。出事就恢复备份/快照,
38
+ * 或用 `billing_orders`/`activities` 的旧形状重建表(数据仍在旧列里,见演练脚本)。
39
+ */
40
+ export interface ProductMigrationReport {
41
+ /** 这次真的重建了哪些表(空 = 已经是新形状)。 */
42
+ rebuilt: Array<"membership" | "member_pool">;
43
+ /** 这次真的加上的列(`表.列`)。 */
44
+ addedColumns: string[];
45
+ /** 迁移后的行数(给演练脚本比对,部署后也可打日志)。 */
46
+ counts: {
47
+ membership: number;
48
+ memberPool: number;
49
+ activities: number;
50
+ };
51
+ }
52
+ export declare function migrateProductDimension(db: DatabaseSync, defaultPersona: string): ProductMigrationReport;
53
+ export declare class SqliteHistoryStore implements HistoryStore {
54
+ private readonly db;
55
+ constructor(db: DatabaseSync);
56
+ load(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined>;
57
+ save(userId: string, scope: string, sessionId: string, entries: FileEntry[], persona?: string, personaVersion?: number): Promise<void>;
58
+ personaOf(userId: string, sessionId: string): Promise<string | null>;
59
+ scopeOf(userId: string, sessionId: string): Promise<string | undefined>;
60
+ list(userId: string, scope?: string): Promise<SessionSummary[]>;
61
+ }
62
+ /** Per-user token budget per day, persisted in the quota table. */
63
+ export declare class SqliteQuotaGate implements QuotaGate {
64
+ private readonly db;
65
+ private readonly dailyTokens;
66
+ private readonly now;
67
+ constructor(db: DatabaseSync, dailyTokens: number | undefined, now?: () => Date);
68
+ private day;
69
+ check(userId: string, caps: QuotaCaps | undefined, persona: string): Promise<QuotaDecision>;
70
+ todayStats(userId: string, persona: string): Promise<{
71
+ runsToday: number;
72
+ tokensToday: number;
73
+ }>;
74
+ record(userId: string, usage: TokenUsage, persona: string): Promise<void>;
75
+ }
76
+ /** 会员有效期,SQLite 实现。 */
77
+ export declare class SqliteMembership implements MembershipStore {
78
+ private readonly db;
79
+ constructor(db: DatabaseSync);
80
+ get(userId: string, product: string): Promise<string | null>;
81
+ set(userId: string, product: string, memberUntil: string, grantedBy?: string): Promise<void>;
82
+ /**
83
+ * 原子续期:一条 SQL 完成 `max(now, 现到期) + days`。
84
+ * 为什么不先 get 再 set:并发发放(购买 + 活动奖励)会互相覆盖。
85
+ * `strftime('%Y-%m-%dT%H:%M:%fZ', …)` 保住 ISO 形状——`datetime()` 会吐出
86
+ * "YYYY-MM-DD HH:MM:SS"(无 T/Z),前端 `Date.parse` 会按本地时区解释。
87
+ */
88
+ extend(userId: string, product: string, days: number, grantedBy?: string): Promise<string>;
89
+ remove(userId: string, product: string): Promise<void>;
90
+ list(): Promise<{
91
+ userId: string;
92
+ product: string;
93
+ memberUntil: string;
94
+ grantedBy: string | null;
95
+ }[]>;
96
+ hasAnyActive(userId: string): Promise<boolean>;
97
+ }
98
+ /** 封号状态,SQLite 实现。 */
99
+ export declare class SqliteAccountState implements AccountStateStore {
100
+ private readonly db;
101
+ private readonly now;
102
+ constructor(db: DatabaseSync, now?: () => Date);
103
+ activeBan(userId: string): Promise<string | null>;
104
+ get(userId: string): Promise<{
105
+ bannedUntil: string | null;
106
+ reason: string | null;
107
+ }>;
108
+ setBan(userId: string, bannedUntil: string, reason: string): Promise<void>;
109
+ removeBan(userId: string): Promise<void>;
110
+ auditRevoked(userId: string): Promise<boolean>;
111
+ setAuditRevoked(userId: string, revoked: boolean): Promise<void>;
112
+ digestSeenAt(userId: string): Promise<string | null>;
113
+ markDigestSeen(userId: string, at: string): Promise<void>;
114
+ list(): Promise<{
115
+ userId: string;
116
+ bannedUntil: string | null;
117
+ reason: string | null;
118
+ auditRevoked: boolean;
119
+ }[]>;
120
+ }
121
+ /** 会员月度池:INSERT OR IGNORE 让 lazy 发放幂等——当月只发一次。 */
122
+ export declare class SqliteMemberPool implements MemberPoolStore {
123
+ private readonly db;
124
+ constructor(db: DatabaseSync);
125
+ getOrGrant(userId: string, product: string, month: string, grantAmount: number): Promise<MemberPoolRow>;
126
+ addUsed(userId: string, product: string, month: string, tokens: number): Promise<void>;
127
+ }
128
+ /** Persisted run log; backs GET /api/usage and the admin report. */
129
+ export declare class SqliteRunLog implements RunLogStore {
130
+ private readonly db;
131
+ constructor(db: DatabaseSync);
132
+ record(run: RunLogRecord): Promise<void>;
133
+ summary(userId: string): Promise<RunUsageSummary>;
134
+ report(): Promise<RunUsageReport>;
135
+ }
136
+ /** Balance + ledger in cents; adjust is one atomic upsert, so concurrent runs never lose a deduction. */
137
+ export declare class SqliteBilling implements BillingStore {
138
+ private readonly db;
139
+ constructor(db: DatabaseSync);
140
+ balance(userId: string): Promise<number>;
141
+ adjust(userId: string, deltaCents: number, kind: BillingEntry["kind"], ref?: string, opts?: BillingAdjustOpts): Promise<number | null>;
142
+ ledger(userId: string, limit?: number): Promise<BillingEntry[]>;
143
+ createOrder(userId: string, amountCents: number, meta?: NewOrderMeta): Promise<string>;
144
+ getOrder(orderId: string): Promise<BillingOrder | null>;
145
+ pendingOrders(userId: string): Promise<Array<BillingOrder & {
146
+ createdAt: string | null;
147
+ }>>;
148
+ claimOrder(orderId: string): Promise<"claimed" | "already" | "cancelled" | "expired" | "unknown">;
149
+ cancelOrder(orderId: string, userId: string): Promise<"cancelled" | "not_pending" | "unknown">;
150
+ expireStaleOrders(ttlMs: number, nowMs?: number): Promise<number>;
151
+ releaseOrder(orderId: string): Promise<boolean>;
152
+ fulfillOrder(orderId: string): Promise<"credited" | "already" | "unknown" | "wrong_kind" | "closed">;
153
+ }
154
+ /**
155
+ * 审计哈希链的 SQLite 实现(/;表见 openDatabase DDL 块)。
156
+ * append 全程同步:读链尾与 INSERT 之间没有 await,单事件循环内不会有两个 append 交错;
157
+ * purge 同理(①读齐+白名单入链 ②删除,两步不反, 5B)。
158
+ */
159
+ export declare class SqliteAudit implements AuditStore {
160
+ private readonly db;
161
+ private readonly now;
162
+ constructor(db: DatabaseSync, now?: () => Date);
163
+ append(e: AuditEvent): Promise<number>;
164
+ /** 同步内核:purge 要在同一同步段里「白名单先入链、再删行」,不能经 await 让出。 */
165
+ private appendSync;
166
+ query(q: AuditQuery): Promise<{
167
+ rows: AuditRow[];
168
+ total: number;
169
+ }>;
170
+ get(id: number): Promise<AuditRow | null>;
171
+ verify(): Promise<VerifyResult>;
172
+ purge(cutoffIso: string): Promise<number>;
173
+ }