@njuptlzf/agent-chat-server 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/audit.d.ts +54 -0
- package/dist/audit.js +133 -0
- package/dist/authz.d.ts +134 -0
- package/dist/authz.js +238 -0
- package/dist/events.d.ts +33 -0
- package/dist/events.js +169 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +4 -0
- package/dist/main.d.ts +1 -0
- package/dist/main.js +126 -0
- package/dist/manifest.d.ts +147 -0
- package/dist/manifest.js +491 -0
- package/dist/mcp-config.d.ts +87 -0
- package/dist/mcp-config.js +353 -0
- package/dist/model-config.d.ts +123 -0
- package/dist/model-config.js +371 -0
- package/dist/model-failover.d.ts +42 -0
- package/dist/model-failover.js +82 -0
- package/dist/models-api.d.ts +98 -0
- package/dist/models-api.js +326 -0
- package/dist/persona-config.d.ts +112 -0
- package/dist/persona-config.js +368 -0
- package/dist/persona-trial.d.ts +50 -0
- package/dist/persona-trial.js +77 -0
- package/dist/product-routes.d.ts +35 -0
- package/dist/product-routes.js +92 -0
- package/dist/server.d.ts +162 -0
- package/dist/server.js +2572 -0
- package/dist/session.d.ts +218 -0
- package/dist/session.js +545 -0
- package/dist/sqlite-stores.d.ts +173 -0
- package/dist/sqlite-stores.js +921 -0
- package/dist/stores.d.ts +506 -0
- package/dist/stores.js +614 -0
- package/dist/testing.d.ts +42 -0
- package/dist/testing.js +47 -0
- package/dist/trial-grant.d.ts +40 -0
- package/dist/trial-grant.js +24 -0
- package/dist/usage-report.d.ts +23 -0
- package/dist/usage-report.js +68 -0
- package/dist/util.d.ts +3 -0
- package/dist/util.js +5 -0
- package/package.json +64 -58
- package/scripts/agentchat-integrate.mjs +607 -601
- package/src/audit.ts +169 -169
- package/src/authz.ts +307 -307
- package/src/events.ts +206 -206
- package/src/index.ts +26 -26
- package/src/main.ts +142 -142
- package/src/manifest.ts +562 -562
- package/src/mcp-config.ts +385 -385
- package/src/model-config.ts +424 -424
- package/src/model-failover.ts +95 -95
- package/src/models-api.ts +360 -360
- package/src/persona-config.ts +436 -436
- package/src/persona-trial.ts +121 -121
- package/src/product-routes.ts +102 -102
- package/src/server.ts +2647 -2647
- package/src/session.ts +688 -688
- package/src/sqlite-stores.ts +1040 -1040
- package/src/stores.ts +899 -899
- package/src/testing.ts +80 -80
- package/src/trial-grant.ts +62 -62
- package/src/usage-report.ts +86 -86
- package/src/util.ts +6 -6
package/dist/stores.d.ts
ADDED
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import type { IncomingMessage } from "node:http";
|
|
2
|
+
import type { FileEntry } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { BillingLedgerEntry, HistoryMessage, SessionSummary, TokenUsage } from "@njuptlzf/agent-chat-protocol";
|
|
4
|
+
import type { ChainRow, VerifyResult } from "./audit.ts";
|
|
5
|
+
/**
|
|
6
|
+
* Seams for the parts that must become real infrastructure in production.
|
|
7
|
+
* The in-memory versions below are for local development and tests only.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Conversation history, keyed by (user, scope, session) so one user can never
|
|
11
|
+
* resume another's session, and a session can never be resumed under a different
|
|
12
|
+
* scope than the one it was created in (the default persona would silently change).
|
|
13
|
+
*/
|
|
14
|
+
export interface HistoryStore {
|
|
15
|
+
load(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* `persona` () is bound on the first save and never overwritten afterwards —
|
|
18
|
+
* omit it to keep whatever is stored. Same lifecycle as `scope`: both are
|
|
19
|
+
* session-level and immutable, so both live in this table (one row = one session).
|
|
20
|
+
*
|
|
21
|
+
* `personaVersion` () 是建会话那一刻生效的人格配置版本(0 = manifest),
|
|
22
|
+
* 与 persona 同一次写入、同样只绑一次——用户投诉"昨天不是这么说的"时要能查回来。
|
|
23
|
+
*/
|
|
24
|
+
save(userId: string, scope: string, sessionId: string, entries: FileEntry[], persona?: string, personaVersion?: number): Promise<void>;
|
|
25
|
+
/** Resumable sessions of this user, newest first; `scope` narrows to one scope. */
|
|
26
|
+
list(userId: string, scope?: string): Promise<SessionSummary[]>;
|
|
27
|
+
/** Scope a stored session is bound to, or undefined when it does not exist. */
|
|
28
|
+
scopeOf(userId: string, sessionId: string): Promise<string | undefined>;
|
|
29
|
+
/** Persona a stored session is bound to; null when unbound (new session or pre-row). */
|
|
30
|
+
personaOf(userId: string, sessionId: string): Promise<string | null>;
|
|
31
|
+
}
|
|
32
|
+
/** Title = first user message (collapsed whitespace); count = visible (user/assistant) turns. */
|
|
33
|
+
export declare function summarizeHistory(entries: FileEntry[]): Pick<SessionSummary, "title" | "messageCount">;
|
|
34
|
+
/**
|
|
35
|
+
* Drop the last user turn and everything after it, so an edited message can be
|
|
36
|
+
* re-sent without the superseded answer staying in the model's context.
|
|
37
|
+
*
|
|
38
|
+
* pi's SessionManager has no truncate API, but it is rebuilt from this blob on
|
|
39
|
+
* every run, so the blob *is* the server-side truth. Returns the same array
|
|
40
|
+
* when there is no user turn to drop.
|
|
41
|
+
*/
|
|
42
|
+
export declare function truncateLastTurn(entries: FileEntry[]): FileEntry[];
|
|
43
|
+
/** Display-only view of a stored conversation: text of user/assistant turns; tools and thinking are not replayed. */
|
|
44
|
+
export declare function toHistoryMessages(entries: FileEntry[]): HistoryMessage[];
|
|
45
|
+
export declare class MemoryHistoryStore implements HistoryStore {
|
|
46
|
+
private data;
|
|
47
|
+
load(userId: string, scope: string, sessionId: string): Promise<FileEntry[] | undefined>;
|
|
48
|
+
save(userId: string, scope: string, sessionId: string, entries: FileEntry[], persona?: string, personaVersion?: number): Promise<void>;
|
|
49
|
+
personaOf(userId: string, sessionId: string): Promise<string | null>;
|
|
50
|
+
scopeOf(userId: string, sessionId: string): Promise<string | undefined>;
|
|
51
|
+
list(userId: string, scope?: string): Promise<SessionSummary[]>;
|
|
52
|
+
}
|
|
53
|
+
export type QuotaDecision = {
|
|
54
|
+
ok: true;
|
|
55
|
+
} | {
|
|
56
|
+
ok: false;
|
|
57
|
+
reason: string;
|
|
58
|
+
};
|
|
59
|
+
/** 按角色现算的当日上限;缺省项 = 沿用装配时的全局值/不限。 */
|
|
60
|
+
export interface QuotaCaps {
|
|
61
|
+
runCap?: number;
|
|
62
|
+
tokenCap?: number;
|
|
63
|
+
}
|
|
64
|
+
export interface QuotaGate {
|
|
65
|
+
/**
|
|
66
|
+
* `persona` 分账:各个人格各算各的,互不吃对方的额度。
|
|
67
|
+
*
|
|
68
|
+
* **必填**(通用化):core 不设隐式默认键。账本键就是人格 id,谁省略谁就写进
|
|
69
|
+
* 另一本账——实测过,改默认值会让老数据整片读不出来。调用方一律显式传
|
|
70
|
+
* 产品 manifest 声明的 id(默认助手用 `product.defaultPersona`)。
|
|
71
|
+
*/
|
|
72
|
+
check(userId: string, caps: QuotaCaps | undefined, persona: string): Promise<QuotaDecision>;
|
|
73
|
+
record(userId: string, usage: TokenUsage, persona: string): Promise<void>;
|
|
74
|
+
/** whoami 的配额展示:今日已用轮数/token(默认助手那本账)。 */
|
|
75
|
+
todayStats?(userId: string, persona: string): Promise<{
|
|
76
|
+
runsToday: number;
|
|
77
|
+
tokensToday: number;
|
|
78
|
+
}>;
|
|
79
|
+
}
|
|
80
|
+
/** 万位读法:5000000 → 「500 万」(撞闸文案与权益卡共用,别在 UI 里二次造轮子)。 */
|
|
81
|
+
export declare function fmtTokensWan(n: number): string;
|
|
82
|
+
/**
|
|
83
|
+
* 日限额撞闸文案(「不要暗闸」):**两个额度的本数都写进提示词**——
|
|
84
|
+
* 「每天最多 N 次」与「每日用量不超过 X tokens」任一触顶都会拦,用户必须看见完整规则。
|
|
85
|
+
* 数字取自现算 caps,档位自适应(免费 10/会员 50、500 万),缺省项省略分句。
|
|
86
|
+
*/
|
|
87
|
+
export declare function quotaBlockedReason(hit: "runs" | "tokens", caps: QuotaCaps): string;
|
|
88
|
+
/** Per-user token budget per day. Replace with a database-backed gate for real billing. */
|
|
89
|
+
export declare class DailyTokenQuota implements QuotaGate {
|
|
90
|
+
private readonly dailyTokens;
|
|
91
|
+
private used;
|
|
92
|
+
constructor(dailyTokens: number | undefined);
|
|
93
|
+
private key;
|
|
94
|
+
check(userId: string, caps: QuotaCaps | undefined, persona: string): Promise<QuotaDecision>;
|
|
95
|
+
todayStats(userId: string, persona: string): Promise<{
|
|
96
|
+
runsToday: number;
|
|
97
|
+
tokensToday: number;
|
|
98
|
+
}>;
|
|
99
|
+
record(userId: string, usage: TokenUsage, persona: string): Promise<void>;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* 会员有效期。会员是**时间态**不是余额态——「充钱是充钱,会员是
|
|
103
|
+
* 订阅制有效期」。存 member_until,rolesFor 每次现算,过期自动
|
|
104
|
+
* 不再是 member,没有需要跑的撤销任务。
|
|
105
|
+
*/
|
|
106
|
+
/**
|
|
107
|
+
* 会员(**按产品分账**)。`product` 就是人格 id(由产品声明,如 default / helper):
|
|
108
|
+
* 每个会话只读自己人格那本账,不串账。**必填**——core 不发明隐式默认,
|
|
109
|
+
* 否则一本账被两个产品悄悄共用(分开买就成了摆设)。
|
|
110
|
+
*/
|
|
111
|
+
/**
|
|
112
|
+
* 账本键/到期时刻的防守:`set(userId, product, memberUntil)` 全是字符串,
|
|
113
|
+
* 位置写错(把日期当 product)在类型上完全合法——那会静默写坏一本账。
|
|
114
|
+
* 所以两个引擎都在写入口验一次:product 必须是人格 id 形状,memberUntil 必须能解析。
|
|
115
|
+
*/
|
|
116
|
+
export declare function assertProductId(product: string): void;
|
|
117
|
+
export declare function assertMembershipWrite(product: string, memberUntil: string): void;
|
|
118
|
+
export interface MembershipStore {
|
|
119
|
+
/** 该用户在某产品下的到期时刻(ISO);从未发放 → null。已过期也原样返回(展示/审计用)。 */
|
|
120
|
+
get(userId: string, product: string): Promise<string | null>;
|
|
121
|
+
/** 直接设定到期时刻(管理员改期、迁移用)。日常发放请走 `extend`。 */
|
|
122
|
+
set(userId: string, product: string, memberUntil: string, grantedBy?: string): Promise<void>;
|
|
123
|
+
/**
|
|
124
|
+
* 原子续期:`max(now, 现到期) + days`,返回新的到期时刻。
|
|
125
|
+
*
|
|
126
|
+
* 为什么要有它:先 `get` 再 `set` 会丢更新——两个人(或"购买 + 活动奖励")
|
|
127
|
+
* 同时发同一本账时,后写的那个会把前一个的天数覆盖掉。SQL 版是一条语句,
|
|
128
|
+
* 内存版靠单线程;两者语义一致:**在现值与今天之间取更晚的,再加天数**。
|
|
129
|
+
*/
|
|
130
|
+
extend(userId: string, product: string, days: number, grantedBy?: string): Promise<string>;
|
|
131
|
+
remove(userId: string, product: string): Promise<void>;
|
|
132
|
+
list(): Promise<{
|
|
133
|
+
userId: string;
|
|
134
|
+
product: string;
|
|
135
|
+
memberUntil: string;
|
|
136
|
+
grantedBy: string | null;
|
|
137
|
+
}[]>;
|
|
138
|
+
/**
|
|
139
|
+
* 任一产品处于会员态(authz 的粗粒度 `member` 角色用它)。**额度不走它**——
|
|
140
|
+
* 额度必须按当前会话的产品取,否则"买了 A 人格就解锁 B 人格的次数"。
|
|
141
|
+
*/
|
|
142
|
+
hasAnyActive(userId: string): Promise<boolean>;
|
|
143
|
+
}
|
|
144
|
+
/** Development-only membership store. */
|
|
145
|
+
export declare class MemoryMembership implements MembershipStore {
|
|
146
|
+
private rows;
|
|
147
|
+
private key;
|
|
148
|
+
get(userId: string, product: string): Promise<string | null>;
|
|
149
|
+
set(userId: string, product: string, memberUntil: string, grantedBy?: string): Promise<void>;
|
|
150
|
+
extend(userId: string, product: string, days: number, grantedBy?: string): Promise<string>;
|
|
151
|
+
remove(userId: string, product: string): Promise<void>;
|
|
152
|
+
list(): Promise<{
|
|
153
|
+
userId: string;
|
|
154
|
+
product: string;
|
|
155
|
+
memberUntil: string;
|
|
156
|
+
grantedBy: string | null;
|
|
157
|
+
}[]>;
|
|
158
|
+
hasAnyActive(userId: string): Promise<boolean>;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* 封号状态。「不管是不是付费用户,恶意行为一律可封」。
|
|
162
|
+
* 无 users 表(用户 = JWT sub),这是唯一一张按 user_id 主键的状态表。
|
|
163
|
+
*/
|
|
164
|
+
export interface AccountStateStore {
|
|
165
|
+
/** 只报**生效中**的封禁至时刻;未封/已到期 → null。 */
|
|
166
|
+
activeBan(userId: string): Promise<string | null>;
|
|
167
|
+
/** 无论是否生效都返回原始状态(whoami 申诉页要展示已到期信息时可用)。 */
|
|
168
|
+
get(userId: string): Promise<{
|
|
169
|
+
bannedUntil: string | null;
|
|
170
|
+
reason: string | null;
|
|
171
|
+
}>;
|
|
172
|
+
setBan(userId: string, bannedUntil: string, reason: string): Promise<void>;
|
|
173
|
+
removeBan(userId: string): Promise<void>;
|
|
174
|
+
/** 审计可见性=登录默认全开,admin 可按用户取消。true=已取消。 */
|
|
175
|
+
auditRevoked(userId: string): Promise<boolean>;
|
|
176
|
+
/**
|
|
177
|
+
* 序列 4:上次「看过每日总结」的时刻(ISO)。没看过 → null。
|
|
178
|
+
* 存服务端不存 localStorage——V6b 的教训:换设备就会重复弹。
|
|
179
|
+
*/
|
|
180
|
+
digestSeenAt(userId: string): Promise<string | null>;
|
|
181
|
+
/** 记「今天看过了」。时间由调用方(端点)盖戳,幂等。 */
|
|
182
|
+
markDigestSeen(userId: string, at: string): Promise<void>;
|
|
183
|
+
setAuditRevoked(userId: string, revoked: boolean): Promise<void>;
|
|
184
|
+
list(): Promise<{
|
|
185
|
+
userId: string;
|
|
186
|
+
bannedUntil: string | null;
|
|
187
|
+
reason: string | null;
|
|
188
|
+
auditRevoked: boolean;
|
|
189
|
+
}[]>;
|
|
190
|
+
}
|
|
191
|
+
/** Development-only account-state store. */
|
|
192
|
+
export declare class MemoryAccountState implements AccountStateStore {
|
|
193
|
+
private readonly now;
|
|
194
|
+
private rows;
|
|
195
|
+
constructor(now?: () => Date);
|
|
196
|
+
activeBan(userId: string): Promise<string | null>;
|
|
197
|
+
get(userId: string): Promise<{
|
|
198
|
+
bannedUntil: string | null;
|
|
199
|
+
reason: string | null;
|
|
200
|
+
}>;
|
|
201
|
+
setBan(userId: string, bannedUntil: string, reason: string): Promise<void>;
|
|
202
|
+
removeBan(userId: string): Promise<void>;
|
|
203
|
+
auditRevoked(userId: string): Promise<boolean>;
|
|
204
|
+
setAuditRevoked(userId: string, revoked: boolean): Promise<void>;
|
|
205
|
+
digestSeenAt(userId: string): Promise<string | null>;
|
|
206
|
+
markDigestSeen(userId: string, at: string): Promise<void>;
|
|
207
|
+
list(): Promise<{
|
|
208
|
+
userId: string;
|
|
209
|
+
bannedUntil: string | null;
|
|
210
|
+
reason: string | null;
|
|
211
|
+
auditRevoked: boolean;
|
|
212
|
+
}[]>;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* 会员月度 token 池(会员=发放池+余额加量)。
|
|
216
|
+
* 池与余额分列:池内 token 不产生余额账。行按 (user,月) lazy 发放——
|
|
217
|
+
* 在期即发满整月,不按天比例(月中开通占便宜、封顶 1× 月池,简化记录在)。
|
|
218
|
+
*/
|
|
219
|
+
export interface MemberPoolRow {
|
|
220
|
+
/** 账本产品(= 人格 id)。 */
|
|
221
|
+
product: string;
|
|
222
|
+
month: string;
|
|
223
|
+
granted: number;
|
|
224
|
+
used: number;
|
|
225
|
+
}
|
|
226
|
+
export interface MemberPoolStore {
|
|
227
|
+
/** 无行且 grantAmount>0 时插行发满(幂等:当月第二次调用只读不重发)。 */
|
|
228
|
+
getOrGrant(userId: string, product: string, month: string, grantAmount: number): Promise<MemberPoolRow>;
|
|
229
|
+
/** 结算拆账:把池内消耗累加进去。 */
|
|
230
|
+
addUsed(userId: string, product: string, month: string, tokens: number): Promise<void>;
|
|
231
|
+
}
|
|
232
|
+
/** Development-only member pool. Replace with the SQLite store in production. */
|
|
233
|
+
export declare class MemoryMemberPool implements MemberPoolStore {
|
|
234
|
+
private rows;
|
|
235
|
+
getOrGrant(userId: string, product: string, month: string, grantAmount: number): Promise<{
|
|
236
|
+
product: string;
|
|
237
|
+
month: string;
|
|
238
|
+
granted: number;
|
|
239
|
+
used: number;
|
|
240
|
+
}>;
|
|
241
|
+
addUsed(userId: string, product: string, month: string, tokens: number): Promise<void>;
|
|
242
|
+
}
|
|
243
|
+
/** One finished chat run, recorded for logging and usage reporting. */
|
|
244
|
+
export interface RunLogRecord {
|
|
245
|
+
userId: string;
|
|
246
|
+
sessionId: string;
|
|
247
|
+
product: string;
|
|
248
|
+
/** 人格:轮数闸按它分账。**必填**——账本键不接受隐式默认。 */
|
|
249
|
+
persona: string;
|
|
250
|
+
/** ISO timestamp when the run started. */
|
|
251
|
+
startedAt: string;
|
|
252
|
+
durationMs: number;
|
|
253
|
+
toolRounds: number;
|
|
254
|
+
aborted: boolean;
|
|
255
|
+
usage: TokenUsage;
|
|
256
|
+
error?: string;
|
|
257
|
+
}
|
|
258
|
+
export interface RunUsageSummary {
|
|
259
|
+
/** UTC day (YYYY-MM-DD) the "today" figures refer to. */
|
|
260
|
+
day: string;
|
|
261
|
+
tokensToday: number;
|
|
262
|
+
totalRuns: number;
|
|
263
|
+
totalTokens: number;
|
|
264
|
+
totalCostUsd: number;
|
|
265
|
+
/** Most recent runs, newest first (capped by the store). */
|
|
266
|
+
recent: RunLogRecord[];
|
|
267
|
+
}
|
|
268
|
+
export interface RunUsageReport {
|
|
269
|
+
users: Array<{
|
|
270
|
+
userId: string;
|
|
271
|
+
runs: number;
|
|
272
|
+
tokens: number;
|
|
273
|
+
costUsd: number;
|
|
274
|
+
}>;
|
|
275
|
+
products: Array<{
|
|
276
|
+
product: string;
|
|
277
|
+
runs: number;
|
|
278
|
+
tokens: number;
|
|
279
|
+
costUsd: number;
|
|
280
|
+
}>;
|
|
281
|
+
}
|
|
282
|
+
/** Per-run log with rollups, so usage is viewable per user and per product. */
|
|
283
|
+
export interface RunLogStore {
|
|
284
|
+
record(run: RunLogRecord): Promise<void>;
|
|
285
|
+
summary(userId: string): Promise<RunUsageSummary>;
|
|
286
|
+
report(): Promise<RunUsageReport>;
|
|
287
|
+
}
|
|
288
|
+
/** Development-only run log (bounded). Replace with the SQLite store in production. */
|
|
289
|
+
export declare class MemoryRunLog implements RunLogStore {
|
|
290
|
+
private runs;
|
|
291
|
+
record(run: RunLogRecord): Promise<void>;
|
|
292
|
+
summary(userId: string): Promise<RunUsageSummary>;
|
|
293
|
+
report(): Promise<RunUsageReport>;
|
|
294
|
+
}
|
|
295
|
+
export type Authenticator = (req: IncomingMessage) => Promise<{
|
|
296
|
+
userId: string;
|
|
297
|
+
} | null>;
|
|
298
|
+
/** One balance movement. `amountCents` is always positive; `kind` gives the direction. */
|
|
299
|
+
export type BillingEntry = BillingLedgerEntry;
|
|
300
|
+
/** 订单卖的是什么:充值进钱包;会员买某个产品(人格)的有效期。 */
|
|
301
|
+
export type BillingOrderKind = "recharge" | "membership";
|
|
302
|
+
export interface BillingOrder {
|
|
303
|
+
id: string;
|
|
304
|
+
userId: string;
|
|
305
|
+
amountCents: number;
|
|
306
|
+
/**
|
|
307
|
+
* `pending` 待付 → `paid` 已付。
|
|
308
|
+
* `cancelled` = 用户自己取消;`expired` = 超时未付被清理(见 expireStaleOrders)。
|
|
309
|
+
* 后两者都**不再可履约**——这正是它们存在的意义:没人付的 pending 单不该无限期
|
|
310
|
+
* 躺在那里,等哪天有人拿旧单号来"补付"。
|
|
311
|
+
*/
|
|
312
|
+
status: "pending" | "paid" | "cancelled" | "expired";
|
|
313
|
+
kind: BillingOrderKind;
|
|
314
|
+
/** 会员单的账本(人格 id);充值单为 null。 */
|
|
315
|
+
product: string | null;
|
|
316
|
+
/** 会员单买多少天;充值单为 null。 */
|
|
317
|
+
days: number | null;
|
|
318
|
+
}
|
|
319
|
+
/** 下单时带的品类信息;省略 = 老语义(充值)。 */
|
|
320
|
+
export interface NewOrderMeta {
|
|
321
|
+
kind?: BillingOrderKind;
|
|
322
|
+
product?: string;
|
|
323
|
+
days?: number;
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Balance + ledger in integer cents (-8). The payment provider is a seam:
|
|
327
|
+
* POST /api/orders creates a pending order, fulfillment credits it — the
|
|
328
|
+
* operator confirms bank transfers today, a verified webhook callback does the
|
|
329
|
+
* same tomorrow. A run may drive the balance negative (arrears); starting one
|
|
330
|
+
* requires balance > 0.
|
|
331
|
+
*
|
|
332
|
+
* 订单不只充值了。`claimOrder` 只做「pending → paid」的条件翻转,
|
|
333
|
+
* 业务(充余额 / 扣款 + 发会员)由调用方做——这样同一个 seam 既能被
|
|
334
|
+
* mockAutoFulfill 用,也能被 webhook 用,且不会双发。
|
|
335
|
+
*/
|
|
336
|
+
/**
|
|
337
|
+
* 负余额策略(review):
|
|
338
|
+
* - 默认(闸):负 delta 只在 `balance + delta >= 0` 时生效——并发履约两张会员单
|
|
339
|
+
* 时第二张会被闸住返回 null,而不是把余额扣成负数白送一个会员。
|
|
340
|
+
* - `allowNegative: true`(显式透支):结算扣款是过的「事后扣、余额闸挡下一次」
|
|
341
|
+
* (server.ts 结算注释),CLI 纠错扣款同理——这两处必须显式声明,行为不变,
|
|
342
|
+
* 但「允许透支」从隐式巧合变成写出来的语义。
|
|
343
|
+
*/
|
|
344
|
+
export interface BillingAdjustOpts {
|
|
345
|
+
allowNegative?: boolean;
|
|
346
|
+
}
|
|
347
|
+
export interface BillingStore {
|
|
348
|
+
balance(userId: string): Promise<number>;
|
|
349
|
+
/**
|
|
350
|
+
* Atomically applies a signed delta, appends a ledger row; returns the new
|
|
351
|
+
* balance, or `null` when the gate refused a negative result (see
|
|
352
|
+
* BillingAdjustOpts). Refusal writes no ledger row — a refused movement
|
|
353
|
+
* never happened.
|
|
354
|
+
*/
|
|
355
|
+
adjust(userId: string, deltaCents: number, kind: BillingEntry["kind"], ref?: string, opts?: BillingAdjustOpts): Promise<number | null>;
|
|
356
|
+
/** Newest first. */
|
|
357
|
+
ledger(userId: string, limit?: number): Promise<BillingEntry[]>;
|
|
358
|
+
/** Creates a pending order; returns its id. `meta` omitted = recharge. */
|
|
359
|
+
createOrder(userId: string, amountCents: number, meta?: NewOrderMeta): Promise<string>;
|
|
360
|
+
getOrder(orderId: string): Promise<BillingOrder | null>;
|
|
361
|
+
/**
|
|
362
|
+
* 本人的待付单(2026-11-04,订阅页「待付订单」列表用):只 pending,新单在前。
|
|
363
|
+
* `createdAt` 为 null = 老库补列前的行(显示「—」且永不过期语义由 expireStaleOrders 决定)。
|
|
364
|
+
*/
|
|
365
|
+
pendingOrders(userId: string): Promise<Array<BillingOrder & {
|
|
366
|
+
createdAt: string | null;
|
|
367
|
+
}>>;
|
|
368
|
+
/**
|
|
369
|
+
* 条件翻转(只有一个调用方能拿到 "claimed")。业务做完之前不要当成功。
|
|
370
|
+
* `cancelled` / `expired` = 这单已经关了,**不能再履约**(别退回成 "already",
|
|
371
|
+
* 那会让调用方以为"已发过货",实际一分钱没扣、一天没发)。
|
|
372
|
+
*/
|
|
373
|
+
claimOrder(orderId: string): Promise<"claimed" | "already" | "cancelled" | "expired" | "unknown">;
|
|
374
|
+
/** 用户取消自己的待付单。`not_pending` = 已付/已关,不能再取消(返回当前状态由调用方查)。 */
|
|
375
|
+
cancelOrder(orderId: string, userId: string): Promise<"cancelled" | "not_pending" | "unknown">;
|
|
376
|
+
/** 把超过 ttlMs 还没付的 pending 单标成 expired;返回处理的行数。 */
|
|
377
|
+
expireStaleOrders(ttlMs: number, nowMs?: number): Promise<number>;
|
|
378
|
+
/** 业务失败时把已认领的订单放回 pending,让重试还有机会(返回是否真放回)。 */
|
|
379
|
+
releaseOrder(orderId: string): Promise<boolean>;
|
|
380
|
+
/**
|
|
381
|
+
* 充值单:认领并充余额。`wrong_kind` = 这不是充值单(会员单要走履约流程)。
|
|
382
|
+
* "already" = 已履约;"unknown" = 无此单;`closed` = 已取消/已超时,**不充值**。
|
|
383
|
+
*/
|
|
384
|
+
fulfillOrder(orderId: string): Promise<"credited" | "already" | "unknown" | "wrong_kind" | "closed">;
|
|
385
|
+
}
|
|
386
|
+
/** Development-only billing store. Replace with the SQLite store in production. */
|
|
387
|
+
export declare class MemoryBilling implements BillingStore {
|
|
388
|
+
private balances;
|
|
389
|
+
private entries;
|
|
390
|
+
private orders;
|
|
391
|
+
/** 建单时刻(毫秒):BillingOrder 不带时间戳,超时清理需要它。 */
|
|
392
|
+
private orderCreatedAt;
|
|
393
|
+
balance(userId: string): Promise<number>;
|
|
394
|
+
adjust(userId: string, deltaCents: number, kind: BillingEntry["kind"], ref?: string, opts?: BillingAdjustOpts): Promise<number | null>;
|
|
395
|
+
ledger(userId: string, limit?: number): Promise<BillingLedgerEntry[]>;
|
|
396
|
+
createOrder(userId: string, amountCents: number, meta?: NewOrderMeta): Promise<string>;
|
|
397
|
+
getOrder(orderId: string): Promise<{
|
|
398
|
+
id: string;
|
|
399
|
+
userId: string;
|
|
400
|
+
amountCents: number;
|
|
401
|
+
/**
|
|
402
|
+
* `pending` 待付 → `paid` 已付。
|
|
403
|
+
* `cancelled` = 用户自己取消;`expired` = 超时未付被清理(见 expireStaleOrders)。
|
|
404
|
+
* 后两者都**不再可履约**——这正是它们存在的意义:没人付的 pending 单不该无限期
|
|
405
|
+
* 躺在那里,等哪天有人拿旧单号来"补付"。
|
|
406
|
+
*/
|
|
407
|
+
status: "pending" | "paid" | "cancelled" | "expired";
|
|
408
|
+
kind: BillingOrderKind;
|
|
409
|
+
/** 会员单的账本(人格 id);充值单为 null。 */
|
|
410
|
+
product: string | null;
|
|
411
|
+
/** 会员单买多少天;充值单为 null。 */
|
|
412
|
+
days: number | null;
|
|
413
|
+
} | null>;
|
|
414
|
+
pendingOrders(userId: string): Promise<(BillingOrder & {
|
|
415
|
+
createdAt: string | null;
|
|
416
|
+
})[]>;
|
|
417
|
+
claimOrder(orderId: string): Promise<"cancelled" | "expired" | "claimed" | "already" | "unknown">;
|
|
418
|
+
cancelOrder(orderId: string, userId: string): Promise<"cancelled" | "unknown" | "not_pending">;
|
|
419
|
+
expireStaleOrders(ttlMs: number, nowMs?: number): Promise<number>;
|
|
420
|
+
releaseOrder(orderId: string): Promise<boolean>;
|
|
421
|
+
fulfillOrder(orderId: string): Promise<"already" | "unknown" | "credited" | "wrong_kind" | "closed">;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* DEVELOPMENT ONLY: trusts the `x-user-id` header. Anyone can claim any identity.
|
|
425
|
+
* Production must verify a signed token (e.g. the host system's JWT) instead.
|
|
426
|
+
*/
|
|
427
|
+
export declare const insecureHeaderAuth: Authenticator;
|
|
428
|
+
/**
|
|
429
|
+
* Verifies an HS256 JWT from `Authorization: Bearer <token>`. The identity comes
|
|
430
|
+
* only from the signed `sub` claim; missing, malformed, forged or expired tokens
|
|
431
|
+
* return null, which the server turns into a 401. Swap in the host system's
|
|
432
|
+
* algorithm/key format when integrating — the Authenticator seam stays the same.
|
|
433
|
+
*/
|
|
434
|
+
export declare function createJwtAuth(secret: string): Authenticator;
|
|
435
|
+
/**
|
|
436
|
+
* Operator authenticator (ADMIN_TOKEN static bearer) for the usage report
|
|
437
|
+
* endpoint only. Keep it separate from user auth so a user token can never
|
|
438
|
+
* unlock cross-user views.
|
|
439
|
+
*/
|
|
440
|
+
export declare function createAdminAuth(token: string): Authenticator;
|
|
441
|
+
/**
|
|
442
|
+
* 审计与操作留痕:append-only 哈希链。写点统一 `deps.audit?.append`,
|
|
443
|
+
* 事件构造用 AuditEvent(领域形),链算法与敏感键守卫在 audit.ts 纯函数层,
|
|
444
|
+
* 与 SqliteAudit 共用语义。红线:meta 永不带对话正文/key(守卫兜底)。
|
|
445
|
+
*/
|
|
446
|
+
export interface AuditEvent {
|
|
447
|
+
/** ISO 8601 UTC;缺省取注入时钟的 now()(authz.ts 同款惯例)。 */
|
|
448
|
+
at?: string;
|
|
449
|
+
/** user id;无身份 "anonymous";服务端自发起 "system"。 */
|
|
450
|
+
actor: string;
|
|
451
|
+
/** 当时角色快照——入链冻结,不是查询时回表。 */
|
|
452
|
+
roles?: string[];
|
|
453
|
+
action: string;
|
|
454
|
+
target?: string | null;
|
|
455
|
+
result: "ok" | "denied" | "error";
|
|
456
|
+
reason?: string | null;
|
|
457
|
+
meta?: Record<string, unknown>;
|
|
458
|
+
}
|
|
459
|
+
/** 落库行 = 链字段(audit.ts ChainRow)+ result 收紧回领域域。 */
|
|
460
|
+
export interface AuditRow extends ChainRow {
|
|
461
|
+
result: "ok" | "denied" | "error";
|
|
462
|
+
}
|
|
463
|
+
export interface AuditQuery {
|
|
464
|
+
from?: string;
|
|
465
|
+
to?: string;
|
|
466
|
+
actionPrefix?: string;
|
|
467
|
+
actor?: string;
|
|
468
|
+
result?: string;
|
|
469
|
+
/** 两级可见:给了就只回「相关行」——actor=subject 或 target=`user:subject`。 */
|
|
470
|
+
subject?: string;
|
|
471
|
+
page?: number;
|
|
472
|
+
pageSize?: number;
|
|
473
|
+
}
|
|
474
|
+
export interface AuditStore {
|
|
475
|
+
/** 算链落库,返回 id。meta 含敏感键名抛错(红线②守卫)。 */
|
|
476
|
+
append(e: AuditEvent): Promise<number>;
|
|
477
|
+
/** id desc;pageSize 默认 50、上限 200。 */
|
|
478
|
+
query(q: AuditQuery): Promise<{
|
|
479
|
+
rows: AuditRow[];
|
|
480
|
+
total: number;
|
|
481
|
+
}>;
|
|
482
|
+
get(id: number): Promise<AuditRow | null>;
|
|
483
|
+
verify(): Promise<VerifyResult>;
|
|
484
|
+
/** 物理删 agent 平面(run./biz. 且 at<cutoff):先落 ops.audit.purge 段白名单再删,返回删除行数(5B)。 */
|
|
485
|
+
purge(cutoffIso: string): Promise<number>;
|
|
486
|
+
}
|
|
487
|
+
/** 分页参数收口(两实现共用):page≥1,pageSize∈[1,200]。 */
|
|
488
|
+
export declare function auditPageWindow(q: AuditQuery): {
|
|
489
|
+
limit: number;
|
|
490
|
+
offset: number;
|
|
491
|
+
};
|
|
492
|
+
/** 开发/测试实现。生产用 SqliteAudit;两者过同一组语义测试。 */
|
|
493
|
+
export declare class MemoryAudit implements AuditStore {
|
|
494
|
+
private readonly now;
|
|
495
|
+
private rows;
|
|
496
|
+
private nextId;
|
|
497
|
+
constructor(now?: () => Date);
|
|
498
|
+
append(e: AuditEvent): Promise<number>;
|
|
499
|
+
query(q: AuditQuery): Promise<{
|
|
500
|
+
rows: AuditRow[];
|
|
501
|
+
total: number;
|
|
502
|
+
}>;
|
|
503
|
+
get(id: number): Promise<AuditRow | null>;
|
|
504
|
+
verify(): Promise<VerifyResult>;
|
|
505
|
+
purge(cutoffIso: string): Promise<number>;
|
|
506
|
+
}
|