@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.
- 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 +16 -10
- package/scripts/agentchat-integrate.mjs +852 -607
package/dist/stores.js
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { GENESIS_HASH, assertNoSensitiveKeys, rowHash, segmentsFrom, verifyChain } from "./audit.js";
|
|
3
|
+
const CONTEXT_MARK = "[/页面上下文]";
|
|
4
|
+
const ATTACH_MARK = "[文档附件:";
|
|
5
|
+
/** expandCommand's wrapper: `<skill name="x">\n…\n</skill>` + optional `\n\n${args}`. */
|
|
6
|
+
const SKILL_WRAP = /^<skill name="([^"]+)">\n[\s\S]*?\n<\/skill>(?:\n\n([\s\S]*))?$/;
|
|
7
|
+
function partText(content) {
|
|
8
|
+
if (typeof content === "string")
|
|
9
|
+
return content;
|
|
10
|
+
return content.filter((p) => p.type === "text").map((p) => p.text ?? "").join("");
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Recover the message the user actually typed from the stored turn:
|
|
14
|
+
* drop the host-context preamble (server prepends before storing), unfold a
|
|
15
|
+
* slash-command expansion back to `/name args`, and cut the attachment blocks
|
|
16
|
+
* that withAttachments appended. Without this, titles leak `<skill …>` bodies
|
|
17
|
+
* and `[文档附件:…]` tails into the session list.
|
|
18
|
+
*/
|
|
19
|
+
function userTurnText(content) {
|
|
20
|
+
let raw = partText(content);
|
|
21
|
+
const i = raw.lastIndexOf(CONTEXT_MARK);
|
|
22
|
+
if (i >= 0)
|
|
23
|
+
raw = raw.slice(i + CONTEXT_MARK.length);
|
|
24
|
+
const skill = SKILL_WRAP.exec(raw.trim());
|
|
25
|
+
if (skill)
|
|
26
|
+
raw = `/${skill[1]}${skill[2] ? ` ${skill[2]}` : ""}`;
|
|
27
|
+
const a = raw.indexOf(ATTACH_MARK);
|
|
28
|
+
if (a >= 0)
|
|
29
|
+
raw = raw.slice(0, a);
|
|
30
|
+
return raw.trim();
|
|
31
|
+
}
|
|
32
|
+
/** Title = first user message (collapsed whitespace); count = visible (user/assistant) turns. */
|
|
33
|
+
export function summarizeHistory(entries) {
|
|
34
|
+
let title = "";
|
|
35
|
+
let messageCount = 0;
|
|
36
|
+
for (const e of entries) {
|
|
37
|
+
if (e.type !== "message")
|
|
38
|
+
continue;
|
|
39
|
+
const msg = e.message;
|
|
40
|
+
if (msg.role === "user") {
|
|
41
|
+
if (!title)
|
|
42
|
+
title = userTurnText(msg.content);
|
|
43
|
+
messageCount++;
|
|
44
|
+
}
|
|
45
|
+
else if (msg.role === "assistant") {
|
|
46
|
+
if (partText(msg.content))
|
|
47
|
+
messageCount++;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const collapsed = title.replace(/\s+/g, " ").trim();
|
|
51
|
+
return { title: collapsed ? collapsed.slice(0, 60) : "新会话", messageCount };
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Drop the last user turn and everything after it, so an edited message can be
|
|
55
|
+
* re-sent without the superseded answer staying in the model's context.
|
|
56
|
+
*
|
|
57
|
+
* pi's SessionManager has no truncate API, but it is rebuilt from this blob on
|
|
58
|
+
* every run, so the blob *is* the server-side truth. Returns the same array
|
|
59
|
+
* when there is no user turn to drop.
|
|
60
|
+
*/
|
|
61
|
+
export function truncateLastTurn(entries) {
|
|
62
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
63
|
+
if (entries[i].type !== "message")
|
|
64
|
+
continue;
|
|
65
|
+
const msg = entries[i].message;
|
|
66
|
+
if (msg.role === "user")
|
|
67
|
+
return entries.slice(0, i);
|
|
68
|
+
}
|
|
69
|
+
return entries;
|
|
70
|
+
}
|
|
71
|
+
/** Display-only view of a stored conversation: text of user/assistant turns; tools and thinking are not replayed. */
|
|
72
|
+
export function toHistoryMessages(entries) {
|
|
73
|
+
const out = [];
|
|
74
|
+
for (const e of entries) {
|
|
75
|
+
if (e.type !== "message")
|
|
76
|
+
continue;
|
|
77
|
+
const entry = e;
|
|
78
|
+
const msg = entry.message;
|
|
79
|
+
if (msg.role === "user") {
|
|
80
|
+
const text = userTurnText(msg.content);
|
|
81
|
+
if (text)
|
|
82
|
+
out.push({ role: "user", text, at: entry.timestamp });
|
|
83
|
+
}
|
|
84
|
+
else if (msg.role === "assistant") {
|
|
85
|
+
const text = partText(msg.content);
|
|
86
|
+
if (text)
|
|
87
|
+
out.push({ role: "assistant", text, at: entry.timestamp });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
export class MemoryHistoryStore {
|
|
93
|
+
data = new Map();
|
|
94
|
+
async load(userId, scope, sessionId) {
|
|
95
|
+
return this.data.get(`${userId}\u0000${scope}\u0000${sessionId}`)?.entries;
|
|
96
|
+
}
|
|
97
|
+
async save(userId, scope, sessionId, entries, persona, personaVersion) {
|
|
98
|
+
const key = `${userId}\u0000${scope}\u0000${sessionId}`;
|
|
99
|
+
const prev = this.data.get(key);
|
|
100
|
+
this.data.set(key, {
|
|
101
|
+
entries,
|
|
102
|
+
updatedAt: new Date().toISOString(),
|
|
103
|
+
// 首次绑定后不再改写(同 SQL 的 COALESCE):中途换人格由端点拦,这里是第二道。
|
|
104
|
+
persona: prev?.persona ?? persona,
|
|
105
|
+
personaVersion: prev?.personaVersion ?? personaVersion,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
async personaOf(userId, sessionId) {
|
|
109
|
+
const prefix = `${userId}\u0000`;
|
|
110
|
+
for (const [key, rec] of this.data) {
|
|
111
|
+
if (key.startsWith(prefix) && key.endsWith(`\u0000${sessionId}`))
|
|
112
|
+
return rec.persona ?? null;
|
|
113
|
+
}
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
async scopeOf(userId, sessionId) {
|
|
117
|
+
const prefix = `${userId}\u0000`;
|
|
118
|
+
for (const key of this.data.keys()) {
|
|
119
|
+
if (!key.startsWith(prefix) || !key.endsWith(`\u0000${sessionId}`))
|
|
120
|
+
continue;
|
|
121
|
+
return key.slice(prefix.length, key.length - sessionId.length - 1);
|
|
122
|
+
}
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
async list(userId, scope) {
|
|
126
|
+
const prefix = `${userId}\u0000${scope === undefined ? "" : `${scope}\u0000`}`;
|
|
127
|
+
const rows = [];
|
|
128
|
+
for (const [key, rec] of this.data) {
|
|
129
|
+
if (!key.startsWith(prefix))
|
|
130
|
+
continue;
|
|
131
|
+
const rest = key.slice(prefix.length);
|
|
132
|
+
// With an explicit scope the prefix already ate the scope segment, so the
|
|
133
|
+
// remainder is the session id; without one the scope is the first segment.
|
|
134
|
+
const cut = scope === undefined ? rest.indexOf("\u0000") : -1;
|
|
135
|
+
if (scope === undefined && cut < 0)
|
|
136
|
+
continue;
|
|
137
|
+
const { title, messageCount } = summarizeHistory(rec.entries);
|
|
138
|
+
rows.push({
|
|
139
|
+
sessionId: cut < 0 ? rest : rest.slice(cut + 1),
|
|
140
|
+
scope: cut < 0 ? scope : rest.slice(0, cut),
|
|
141
|
+
title,
|
|
142
|
+
updatedAt: rec.updatedAt,
|
|
143
|
+
messageCount,
|
|
144
|
+
persona: rec.persona ?? null,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return rows.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** 万位读法:5000000 → 「500 万」(撞闸文案与权益卡共用,别在 UI 里二次造轮子)。 */
|
|
151
|
+
export function fmtTokensWan(n) {
|
|
152
|
+
return n >= 10000 ? `${(n / 10000).toLocaleString("zh-CN")} 万` : String(n);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* 日限额撞闸文案(「不要暗闸」):**两个额度的本数都写进提示词**——
|
|
156
|
+
* 「每天最多 N 次」与「每日用量不超过 X tokens」任一触顶都会拦,用户必须看见完整规则。
|
|
157
|
+
* 数字取自现算 caps,档位自适应(免费 10/会员 50、500 万),缺省项省略分句。
|
|
158
|
+
*/
|
|
159
|
+
export function quotaBlockedReason(hit, caps) {
|
|
160
|
+
const run = caps.runCap !== undefined && caps.runCap > 0 ? `每天最多 ${caps.runCap} 次对话` : undefined;
|
|
161
|
+
const tok = caps.tokenCap !== undefined && caps.tokenCap > 0 ? `每日总用量不超过 ${fmtTokensWan(caps.tokenCap)} tokens` : undefined;
|
|
162
|
+
const both = [run, tok].filter(Boolean).join("、");
|
|
163
|
+
if (hit === "runs") {
|
|
164
|
+
return `今日对话次数已用完${both ? `(${both},两者任一触顶即限,次日重置)` : ",次日重置"}`;
|
|
165
|
+
}
|
|
166
|
+
return `今日用量已达上限${both ? `(${both})` : ""}。触顶通常来自异常使用(脚本刷量或失控会话),次日自动重置;如认为判误请联系管理员`;
|
|
167
|
+
}
|
|
168
|
+
/** Per-user token budget per day. Replace with a database-backed gate for real billing. */
|
|
169
|
+
export class DailyTokenQuota {
|
|
170
|
+
dailyTokens;
|
|
171
|
+
used = new Map();
|
|
172
|
+
constructor(dailyTokens) {
|
|
173
|
+
this.dailyTokens = dailyTokens;
|
|
174
|
+
}
|
|
175
|
+
key(userId, persona) {
|
|
176
|
+
return `${userId}\u0000${persona}\u0000${new Date().toISOString().slice(0, 10)}`;
|
|
177
|
+
}
|
|
178
|
+
async check(userId, caps, persona) {
|
|
179
|
+
// 角色 token 上限优先于装配值(会员兜底更高时公平阀随之抬)。
|
|
180
|
+
const cap = caps?.tokenCap ?? this.dailyTokens;
|
|
181
|
+
if (cap === undefined)
|
|
182
|
+
return { ok: true };
|
|
183
|
+
const used = this.used.get(this.key(userId, persona)) ?? 0;
|
|
184
|
+
return used >= cap ? { ok: false, reason: quotaBlockedReason("tokens", { runCap: caps?.runCap, tokenCap: cap }) } : { ok: true };
|
|
185
|
+
}
|
|
186
|
+
async todayStats(userId, persona) {
|
|
187
|
+
// 内存实现没有 runs 表概念——轮数据在配额闸之外,报 0 轮如实(开发态展示)。
|
|
188
|
+
return { runsToday: 0, tokensToday: this.used.get(this.key(userId, persona)) ?? 0 };
|
|
189
|
+
}
|
|
190
|
+
async record(userId, usage, persona) {
|
|
191
|
+
const k = this.key(userId, persona);
|
|
192
|
+
this.used.set(k, (this.used.get(k) ?? 0) + usage.total);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* 会员有效期。会员是**时间态**不是余额态——「充钱是充钱,会员是
|
|
197
|
+
* 订阅制有效期」。存 member_until,rolesFor 每次现算,过期自动
|
|
198
|
+
* 不再是 member,没有需要跑的撤销任务。
|
|
199
|
+
*/
|
|
200
|
+
/**
|
|
201
|
+
* 会员(**按产品分账**)。`product` 就是人格 id(由产品声明,如 default / helper):
|
|
202
|
+
* 每个会话只读自己人格那本账,不串账。**必填**——core 不发明隐式默认,
|
|
203
|
+
* 否则一本账被两个产品悄悄共用(分开买就成了摆设)。
|
|
204
|
+
*/
|
|
205
|
+
/**
|
|
206
|
+
* 账本键/到期时刻的防守:`set(userId, product, memberUntil)` 全是字符串,
|
|
207
|
+
* 位置写错(把日期当 product)在类型上完全合法——那会静默写坏一本账。
|
|
208
|
+
* 所以两个引擎都在写入口验一次:product 必须是人格 id 形状,memberUntil 必须能解析。
|
|
209
|
+
*/
|
|
210
|
+
export function assertProductId(product) {
|
|
211
|
+
if (!/^[a-z][a-z0-9_-]*$/.test(product)) {
|
|
212
|
+
throw new Error(`membership product must be a persona id, got "${product}"`);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
export function assertMembershipWrite(product, memberUntil) {
|
|
216
|
+
assertProductId(product);
|
|
217
|
+
if (!Number.isFinite(Date.parse(memberUntil))) {
|
|
218
|
+
throw new Error(`membership memberUntil must be an ISO timestamp, got "${memberUntil}"`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** Development-only membership store. */
|
|
222
|
+
export class MemoryMembership {
|
|
223
|
+
rows = new Map();
|
|
224
|
+
key(userId, product) {
|
|
225
|
+
return `${userId}\u0000${product}`;
|
|
226
|
+
}
|
|
227
|
+
async get(userId, product) {
|
|
228
|
+
assertProductId(product);
|
|
229
|
+
return this.rows.get(this.key(userId, product))?.memberUntil ?? null;
|
|
230
|
+
}
|
|
231
|
+
async set(userId, product, memberUntil, grantedBy) {
|
|
232
|
+
assertMembershipWrite(product, memberUntil);
|
|
233
|
+
this.rows.set(this.key(userId, product), { memberUntil, grantedBy: grantedBy ?? null });
|
|
234
|
+
}
|
|
235
|
+
async extend(userId, product, days, grantedBy) {
|
|
236
|
+
assertProductId(product);
|
|
237
|
+
if (!Number.isInteger(days) || days < 1)
|
|
238
|
+
throw new Error(`membership days must be a positive integer, got ${days}`);
|
|
239
|
+
const cur = this.rows.get(this.key(userId, product))?.memberUntil;
|
|
240
|
+
const base = Math.max(Date.now(), cur ? Date.parse(cur) || 0 : 0);
|
|
241
|
+
const until = new Date(base + days * 86_400_000).toISOString();
|
|
242
|
+
this.rows.set(this.key(userId, product), { memberUntil: until, grantedBy: grantedBy ?? null });
|
|
243
|
+
return until;
|
|
244
|
+
}
|
|
245
|
+
async remove(userId, product) {
|
|
246
|
+
assertProductId(product);
|
|
247
|
+
this.rows.delete(this.key(userId, product));
|
|
248
|
+
}
|
|
249
|
+
async list() {
|
|
250
|
+
return [...this.rows].map(([key, r]) => {
|
|
251
|
+
const cut = key.indexOf("\u0000");
|
|
252
|
+
return { userId: key.slice(0, cut), product: key.slice(cut + 1), memberUntil: r.memberUntil, grantedBy: r.grantedBy };
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
async hasAnyActive(userId) {
|
|
256
|
+
const now = Date.now();
|
|
257
|
+
for (const [key, r] of this.rows) {
|
|
258
|
+
if (!key.startsWith(`${userId}\u0000`))
|
|
259
|
+
continue;
|
|
260
|
+
const ms = Date.parse(r.memberUntil);
|
|
261
|
+
if (Number.isFinite(ms) && ms > now)
|
|
262
|
+
return true;
|
|
263
|
+
}
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/** Development-only account-state store. */
|
|
268
|
+
export class MemoryAccountState {
|
|
269
|
+
now;
|
|
270
|
+
rows = new Map();
|
|
271
|
+
constructor(now = () => new Date()) {
|
|
272
|
+
this.now = now;
|
|
273
|
+
}
|
|
274
|
+
async activeBan(userId) {
|
|
275
|
+
const r = this.rows.get(userId);
|
|
276
|
+
return r?.bannedUntil && new Date(r.bannedUntil) > this.now() ? r.bannedUntil : null;
|
|
277
|
+
}
|
|
278
|
+
async get(userId) {
|
|
279
|
+
const r = this.rows.get(userId);
|
|
280
|
+
return { bannedUntil: r?.bannedUntil ?? null, reason: r?.reason ?? null };
|
|
281
|
+
}
|
|
282
|
+
async setBan(userId, bannedUntil, reason) {
|
|
283
|
+
const prev = this.rows.get(userId);
|
|
284
|
+
this.rows.set(userId, { bannedUntil, reason, auditRevoked: prev?.auditRevoked ?? false });
|
|
285
|
+
}
|
|
286
|
+
async removeBan(userId) {
|
|
287
|
+
const prev = this.rows.get(userId);
|
|
288
|
+
this.rows.set(userId, { bannedUntil: null, reason: null, auditRevoked: prev?.auditRevoked ?? false });
|
|
289
|
+
}
|
|
290
|
+
async auditRevoked(userId) {
|
|
291
|
+
return this.rows.get(userId)?.auditRevoked ?? false;
|
|
292
|
+
}
|
|
293
|
+
async setAuditRevoked(userId, revoked) {
|
|
294
|
+
const prev = this.rows.get(userId) ?? { bannedUntil: null, reason: null, auditRevoked: false };
|
|
295
|
+
this.rows.set(userId, { ...prev, auditRevoked: revoked });
|
|
296
|
+
}
|
|
297
|
+
async digestSeenAt(userId) {
|
|
298
|
+
return this.rows.get(userId)?.digestSeenAt ?? null;
|
|
299
|
+
}
|
|
300
|
+
async markDigestSeen(userId, at) {
|
|
301
|
+
const prev = this.rows.get(userId) ?? { bannedUntil: null, reason: null, auditRevoked: false };
|
|
302
|
+
this.rows.set(userId, { ...prev, digestSeenAt: at });
|
|
303
|
+
}
|
|
304
|
+
async list() {
|
|
305
|
+
return [...this.rows].map(([userId, r]) => ({
|
|
306
|
+
userId,
|
|
307
|
+
bannedUntil: r.bannedUntil,
|
|
308
|
+
reason: r.reason,
|
|
309
|
+
auditRevoked: r.auditRevoked,
|
|
310
|
+
}));
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
/** Development-only member pool. Replace with the SQLite store in production. */
|
|
314
|
+
export class MemoryMemberPool {
|
|
315
|
+
rows = new Map();
|
|
316
|
+
async getOrGrant(userId, product, month, grantAmount) {
|
|
317
|
+
const key = `${userId}\u0000${product}\u0000${month}`;
|
|
318
|
+
let r = this.rows.get(key);
|
|
319
|
+
if (!r) {
|
|
320
|
+
// 与 Sqlite 版同语义:只读(grantAmount<=0)不插行——否则「池尽检查」会把
|
|
321
|
+
// 一个从未发放的月占成 granted=0,之后真发放被幂等挡住。
|
|
322
|
+
if (grantAmount <= 0)
|
|
323
|
+
return { product, month, granted: 0, used: 0 };
|
|
324
|
+
r = { product, month, granted: grantAmount, used: 0 };
|
|
325
|
+
this.rows.set(key, r);
|
|
326
|
+
}
|
|
327
|
+
return { ...r };
|
|
328
|
+
}
|
|
329
|
+
async addUsed(userId, product, month, tokens) {
|
|
330
|
+
const key = `${userId}\u0000${product}\u0000${month}`;
|
|
331
|
+
const r = this.rows.get(key);
|
|
332
|
+
if (r)
|
|
333
|
+
this.rows.set(key, { ...r, used: r.used + tokens });
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const MAX_MEMORY_RUNS = 2000;
|
|
337
|
+
/** Development-only run log (bounded). Replace with the SQLite store in production. */
|
|
338
|
+
export class MemoryRunLog {
|
|
339
|
+
runs = [];
|
|
340
|
+
async record(run) {
|
|
341
|
+
this.runs.push(run);
|
|
342
|
+
if (this.runs.length > MAX_MEMORY_RUNS)
|
|
343
|
+
this.runs.splice(0, this.runs.length - MAX_MEMORY_RUNS);
|
|
344
|
+
}
|
|
345
|
+
async summary(userId) {
|
|
346
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
347
|
+
const mine = this.runs.filter((r) => r.userId === userId);
|
|
348
|
+
return {
|
|
349
|
+
day,
|
|
350
|
+
tokensToday: mine.filter((r) => r.startedAt.slice(0, 10) === day).reduce((s, r) => s + r.usage.total, 0),
|
|
351
|
+
totalRuns: mine.length,
|
|
352
|
+
totalTokens: mine.reduce((s, r) => s + r.usage.total, 0),
|
|
353
|
+
totalCostUsd: mine.reduce((s, r) => s + r.usage.costUsd, 0),
|
|
354
|
+
recent: [...mine].reverse().slice(0, 10),
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
async report() {
|
|
358
|
+
const byUser = new Map();
|
|
359
|
+
const byProduct = new Map();
|
|
360
|
+
for (const r of this.runs) {
|
|
361
|
+
const u = byUser.get(r.userId) ?? { runs: 0, tokens: 0, costUsd: 0 };
|
|
362
|
+
u.runs++;
|
|
363
|
+
u.tokens += r.usage.total;
|
|
364
|
+
u.costUsd += r.usage.costUsd;
|
|
365
|
+
byUser.set(r.userId, u);
|
|
366
|
+
const p = byProduct.get(r.product) ?? { runs: 0, tokens: 0, costUsd: 0 };
|
|
367
|
+
p.runs++;
|
|
368
|
+
p.tokens += r.usage.total;
|
|
369
|
+
p.costUsd += r.usage.costUsd;
|
|
370
|
+
byProduct.set(r.product, p);
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
users: [...byUser].map(([userId, v]) => ({ userId, ...v })),
|
|
374
|
+
products: [...byProduct].map(([product, v]) => ({ product, ...v })),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
/** Development-only billing store. Replace with the SQLite store in production. */
|
|
379
|
+
export class MemoryBilling {
|
|
380
|
+
balances = new Map();
|
|
381
|
+
entries = new Map();
|
|
382
|
+
orders = new Map();
|
|
383
|
+
/** 建单时刻(毫秒):BillingOrder 不带时间戳,超时清理需要它。 */
|
|
384
|
+
orderCreatedAt = new Map();
|
|
385
|
+
async balance(userId) {
|
|
386
|
+
return this.balances.get(userId) ?? 0;
|
|
387
|
+
}
|
|
388
|
+
async adjust(userId, deltaCents, kind, ref, opts) {
|
|
389
|
+
const next = (this.balances.get(userId) ?? 0) + deltaCents;
|
|
390
|
+
if (next < 0 && !opts?.allowNegative)
|
|
391
|
+
return null;
|
|
392
|
+
this.balances.set(userId, next);
|
|
393
|
+
// kind="adjust" 存带符号金额(方向无从推断,前端靠符号);其余 kind 存 abs。
|
|
394
|
+
const amountCents = kind === "adjust" ? deltaCents : Math.abs(deltaCents);
|
|
395
|
+
const list = this.entries.get(userId) ?? [];
|
|
396
|
+
list.push({ at: new Date().toISOString(), kind, amountCents, balanceAfter: next, ref });
|
|
397
|
+
this.entries.set(userId, list);
|
|
398
|
+
return next;
|
|
399
|
+
}
|
|
400
|
+
async ledger(userId, limit = 20) {
|
|
401
|
+
return [...(this.entries.get(userId) ?? [])].reverse().slice(0, limit);
|
|
402
|
+
}
|
|
403
|
+
async createOrder(userId, amountCents, meta = {}) {
|
|
404
|
+
const id = `ord_${randomUUID().slice(0, 8)}`;
|
|
405
|
+
this.orders.set(id, {
|
|
406
|
+
id,
|
|
407
|
+
userId,
|
|
408
|
+
amountCents,
|
|
409
|
+
status: "pending",
|
|
410
|
+
kind: meta.kind ?? "recharge",
|
|
411
|
+
product: meta.product ?? null,
|
|
412
|
+
days: meta.days ?? null,
|
|
413
|
+
});
|
|
414
|
+
this.orderCreatedAt.set(id, Date.now());
|
|
415
|
+
return id;
|
|
416
|
+
}
|
|
417
|
+
async getOrder(orderId) {
|
|
418
|
+
const order = this.orders.get(orderId);
|
|
419
|
+
return order ? { ...order } : null;
|
|
420
|
+
}
|
|
421
|
+
async pendingOrders(userId) {
|
|
422
|
+
const out = [];
|
|
423
|
+
for (const order of this.orders.values()) {
|
|
424
|
+
if (order.userId !== userId || order.status !== "pending")
|
|
425
|
+
continue;
|
|
426
|
+
const ms = this.orderCreatedAt.get(order.id);
|
|
427
|
+
out.push({ ...order, createdAt: ms === undefined ? null : new Date(ms).toISOString() });
|
|
428
|
+
}
|
|
429
|
+
out.sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
|
|
430
|
+
return out;
|
|
431
|
+
}
|
|
432
|
+
async claimOrder(orderId) {
|
|
433
|
+
const order = this.orders.get(orderId);
|
|
434
|
+
if (!order)
|
|
435
|
+
return "unknown";
|
|
436
|
+
if (order.status === "paid")
|
|
437
|
+
return "already";
|
|
438
|
+
if (order.status === "cancelled" || order.status === "expired")
|
|
439
|
+
return order.status;
|
|
440
|
+
order.status = "paid";
|
|
441
|
+
return "claimed";
|
|
442
|
+
}
|
|
443
|
+
async cancelOrder(orderId, userId) {
|
|
444
|
+
const order = this.orders.get(orderId);
|
|
445
|
+
if (!order || order.userId !== userId)
|
|
446
|
+
return "unknown";
|
|
447
|
+
if (order.status !== "pending")
|
|
448
|
+
return "not_pending";
|
|
449
|
+
order.status = "cancelled";
|
|
450
|
+
return "cancelled";
|
|
451
|
+
}
|
|
452
|
+
async expireStaleOrders(ttlMs, nowMs = Date.now()) {
|
|
453
|
+
let n = 0;
|
|
454
|
+
for (const [id, order] of this.orders) {
|
|
455
|
+
if (order.status !== "pending")
|
|
456
|
+
continue;
|
|
457
|
+
const created = this.orderCreatedAt.get(id);
|
|
458
|
+
if (created !== undefined && nowMs - created > ttlMs) {
|
|
459
|
+
order.status = "expired";
|
|
460
|
+
n++;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return n;
|
|
464
|
+
}
|
|
465
|
+
async releaseOrder(orderId) {
|
|
466
|
+
const order = this.orders.get(orderId);
|
|
467
|
+
if (!order || order.status !== "paid")
|
|
468
|
+
return false;
|
|
469
|
+
order.status = "pending";
|
|
470
|
+
return true;
|
|
471
|
+
}
|
|
472
|
+
async fulfillOrder(orderId) {
|
|
473
|
+
const order = this.orders.get(orderId);
|
|
474
|
+
if (!order)
|
|
475
|
+
return "unknown";
|
|
476
|
+
if (order.kind !== "recharge")
|
|
477
|
+
return "wrong_kind";
|
|
478
|
+
if (order.status === "paid")
|
|
479
|
+
return "already";
|
|
480
|
+
// 已取消/已超时的单不再充值(否则"取消"只是个摆设)。
|
|
481
|
+
if (order.status === "cancelled" || order.status === "expired")
|
|
482
|
+
return "closed";
|
|
483
|
+
order.status = "paid";
|
|
484
|
+
await this.adjust(order.userId, order.amountCents, "recharge", orderId);
|
|
485
|
+
return "credited";
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* DEVELOPMENT ONLY: trusts the `x-user-id` header. Anyone can claim any identity.
|
|
490
|
+
* Production must verify a signed token (e.g. the host system's JWT) instead.
|
|
491
|
+
*/
|
|
492
|
+
export const insecureHeaderAuth = async (req) => {
|
|
493
|
+
const id = req.headers["x-user-id"];
|
|
494
|
+
const userId = typeof id === "string" && /^[\w.@-]{1,64}$/.test(id) ? id : "anonymous";
|
|
495
|
+
return { userId };
|
|
496
|
+
};
|
|
497
|
+
/**
|
|
498
|
+
* Verifies an HS256 JWT from `Authorization: Bearer <token>`. The identity comes
|
|
499
|
+
* only from the signed `sub` claim; missing, malformed, forged or expired tokens
|
|
500
|
+
* return null, which the server turns into a 401. Swap in the host system's
|
|
501
|
+
* algorithm/key format when integrating — the Authenticator seam stays the same.
|
|
502
|
+
*/
|
|
503
|
+
export function createJwtAuth(secret) {
|
|
504
|
+
return async (req) => {
|
|
505
|
+
const header = req.headers.authorization;
|
|
506
|
+
if (typeof header !== "string" || !header.startsWith("Bearer "))
|
|
507
|
+
return null;
|
|
508
|
+
const parts = header.slice(7).trim().split(".");
|
|
509
|
+
if (parts.length !== 3)
|
|
510
|
+
return null;
|
|
511
|
+
const [signed, payload, signature] = parts;
|
|
512
|
+
try {
|
|
513
|
+
const alg = JSON.parse(Buffer.from(signed, "base64url").toString("utf8")).alg;
|
|
514
|
+
// Pinned: rejects "none" and RS256-pubkey-confusion tokens outright.
|
|
515
|
+
if (alg !== "HS256")
|
|
516
|
+
return null;
|
|
517
|
+
const expected = createHmac("sha256", secret).update(`${signed}.${payload}`).digest();
|
|
518
|
+
const given = Buffer.from(signature, "base64url");
|
|
519
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected))
|
|
520
|
+
return null;
|
|
521
|
+
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
|
|
522
|
+
if (typeof claims.exp !== "number" || claims.exp * 1000 <= Date.now())
|
|
523
|
+
return null;
|
|
524
|
+
if (typeof claims.sub !== "string" || !/^[\w.@-]{1,64}$/.test(claims.sub))
|
|
525
|
+
return null;
|
|
526
|
+
return { userId: claims.sub };
|
|
527
|
+
}
|
|
528
|
+
catch {
|
|
529
|
+
return null;
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Operator authenticator (ADMIN_TOKEN static bearer) for the usage report
|
|
535
|
+
* endpoint only. Keep it separate from user auth so a user token can never
|
|
536
|
+
* unlock cross-user views.
|
|
537
|
+
*/
|
|
538
|
+
export function createAdminAuth(token) {
|
|
539
|
+
return async (req) => {
|
|
540
|
+
const header = req.headers.authorization;
|
|
541
|
+
if (typeof header !== "string" || !header.startsWith("Bearer "))
|
|
542
|
+
return null;
|
|
543
|
+
const given = Buffer.from(header.slice(7).trim());
|
|
544
|
+
const want = Buffer.from(token);
|
|
545
|
+
if (given.length !== want.length || !timingSafeEqual(given, want))
|
|
546
|
+
return null;
|
|
547
|
+
return { userId: "__admin__" };
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
const AUDIT_PAGE_DEFAULT = 50;
|
|
551
|
+
const AUDIT_PAGE_MAX = 200;
|
|
552
|
+
/** 分页参数收口(两实现共用):page≥1,pageSize∈[1,200]。 */
|
|
553
|
+
export function auditPageWindow(q) {
|
|
554
|
+
const pageSize = Math.min(Math.max(1, Math.trunc(q.pageSize ?? AUDIT_PAGE_DEFAULT)), AUDIT_PAGE_MAX);
|
|
555
|
+
const page = Math.max(1, Math.trunc(q.page ?? 1));
|
|
556
|
+
return { limit: pageSize, offset: (page - 1) * pageSize };
|
|
557
|
+
}
|
|
558
|
+
/** 开发/测试实现。生产用 SqliteAudit;两者过同一组语义测试。 */
|
|
559
|
+
export class MemoryAudit {
|
|
560
|
+
now;
|
|
561
|
+
rows = [];
|
|
562
|
+
nextId = 1;
|
|
563
|
+
constructor(now = () => new Date()) {
|
|
564
|
+
this.now = now;
|
|
565
|
+
}
|
|
566
|
+
async append(e) {
|
|
567
|
+
const meta = e.meta ?? {};
|
|
568
|
+
assertNoSensitiveKeys(meta);
|
|
569
|
+
const body = {
|
|
570
|
+
at: e.at ?? this.now().toISOString(),
|
|
571
|
+
actor: e.actor,
|
|
572
|
+
roles: e.roles ?? [],
|
|
573
|
+
action: e.action,
|
|
574
|
+
target: e.target ?? null,
|
|
575
|
+
result: e.result,
|
|
576
|
+
reason: e.reason ?? null,
|
|
577
|
+
meta,
|
|
578
|
+
};
|
|
579
|
+
const prevHash = this.rows.length ? this.rows[this.rows.length - 1].hash : GENESIS_HASH;
|
|
580
|
+
this.rows.push({ id: this.nextId++, ...body, prevHash, hash: rowHash(prevHash, body) });
|
|
581
|
+
return this.nextId - 1;
|
|
582
|
+
}
|
|
583
|
+
async query(q) {
|
|
584
|
+
const matched = this.rows.filter((r) => (!q.from || r.at >= q.from) &&
|
|
585
|
+
(!q.to || r.at <= q.to) &&
|
|
586
|
+
(!q.actionPrefix || r.action.startsWith(q.actionPrefix)) &&
|
|
587
|
+
(!q.actor || r.actor === q.actor) &&
|
|
588
|
+
(!q.subject || r.actor === q.subject || r.target === `user:${q.subject}`) &&
|
|
589
|
+
(!q.result || r.result === q.result));
|
|
590
|
+
const { limit, offset } = auditPageWindow(q);
|
|
591
|
+
return { rows: matched.slice().sort((a, b) => b.id - a.id).slice(offset, offset + limit), total: matched.length };
|
|
592
|
+
}
|
|
593
|
+
async get(id) {
|
|
594
|
+
return this.rows.find((r) => r.id === id) ?? null;
|
|
595
|
+
}
|
|
596
|
+
async verify() {
|
|
597
|
+
return verifyChain(this.rows);
|
|
598
|
+
}
|
|
599
|
+
async purge(cutoffIso) {
|
|
600
|
+
const doomed = this.rows.filter((r) => (r.action.startsWith("run.") || r.action.startsWith("biz.")) && r.at < cutoffIso);
|
|
601
|
+
if (!doomed.length)
|
|
602
|
+
return 0;
|
|
603
|
+
// 顺序不可反:白名单行先入链,再物理删。
|
|
604
|
+
await this.append({
|
|
605
|
+
actor: "system",
|
|
606
|
+
action: "ops.audit.purge",
|
|
607
|
+
result: "ok",
|
|
608
|
+
meta: { cutoff: cutoffIso, count: doomed.length, segments: segmentsFrom(doomed) },
|
|
609
|
+
});
|
|
610
|
+
const gone = new Set(doomed.map((r) => r.id));
|
|
611
|
+
this.rows = this.rows.filter((r) => !gone.has(r.id));
|
|
612
|
+
return doomed.length;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@njuptlzf/agent-chat-server/testing` —— 产品测试用的平台接缝。
|
|
3
|
+
*
|
|
4
|
+
* ## 这个出口和 `.`(主出口)的区别
|
|
5
|
+
*
|
|
6
|
+
* `.` 只导出《[PUBLIC_API](../../../docs/design/PUBLIC_API.md)》登记的那 18 项
|
|
7
|
+
* **生产接缝**:产品在运行期必需的东西,每增一项都要说服守卫。
|
|
8
|
+
*
|
|
9
|
+
* 这个出口导出的是**测试基建**——内存版 store、SQLite 版 store、JWT/Authz
|
|
10
|
+
* 构造器、会话构造器。它们的共同点:产品测试要拿它们搭一个真跑得起来的
|
|
11
|
+
* server,但产品的生产代码一行都不该 import 它们。
|
|
12
|
+
*
|
|
13
|
+
* ## 稳定性承诺:没有
|
|
14
|
+
*
|
|
15
|
+
* 这里的符号**不承诺 API 稳定**。平台重构时可以改名、改签名、删掉——
|
|
16
|
+
* 只要同步改产品仓的测试即可(生产代码不会因为这里的变化编译不过)。
|
|
17
|
+
* 别在产品业务代码里 import 这个出口;守卫会发现(见 §边界)。
|
|
18
|
+
*
|
|
19
|
+
* ## 为什么不做成"产品自造替身"
|
|
20
|
+
*
|
|
21
|
+
* 曾考虑让产品自己写内存 store。否决理由:`createChatServer` 只认平台接口
|
|
22
|
+
* (`HistoryStore`/`QuotaGate`/…),产品手写的替身必须逐字段对齐这些接口的
|
|
23
|
+
* 行为——尤其是 `SqliteQuotaGate` 的"今日计数"、`SqliteMembership` 的幂等
|
|
24
|
+
* 写入这类带语义的。两侧各写一份,行为漂移时测试全绿而生产出问题。
|
|
25
|
+
* 复用平台的实现,测试才验的是**真代码路径**。
|
|
26
|
+
*
|
|
27
|
+
* ## 为什么不并入主出口
|
|
28
|
+
*
|
|
29
|
+
* 主出口的 `public-api.test.ts` 会数条数(18 项)。把测试基建混进去,
|
|
30
|
+
* "产品生产代码依赖了平台内部"和"产品测试依赖了平台测试基建"两类事实
|
|
31
|
+
* 就被同一个数字掩盖了——前者是边界事故,后者是正常需求。
|
|
32
|
+
*/
|
|
33
|
+
export { DailyTokenQuota, MemoryAccountState, MemoryAudit, MemoryBilling, MemoryHistoryStore, MemoryMembership, createAdminAuth, createJwtAuth, insecureHeaderAuth, } from "./stores.ts";
|
|
34
|
+
export type { AccountStateStore, MembershipStore, } from "./stores.ts";
|
|
35
|
+
export { SqliteBilling, SqliteHistoryStore, SqliteMemberPool, SqliteMembership, SqliteQuotaGate, } from "./sqlite-stores.ts";
|
|
36
|
+
export { Authz, UnavailableAuthz } from "./authz.ts";
|
|
37
|
+
export { capsForPersona, capsForRoles, limitsForPersona } from "./authz.ts";
|
|
38
|
+
export { agentFor, loadProduct, loadToolFactory } from "./manifest.ts";
|
|
39
|
+
export { loadProductAssembly } from "./product-routes.ts";
|
|
40
|
+
export { validatePersona } from "./persona-config.ts";
|
|
41
|
+
export { buildCommands, createModelRuntime, createProductSession, disposeProductSession, expandCommand, exportHistory, loadProductSkills, } from "./session.ts";
|
|
42
|
+
export { createChatServer } from "./server.ts";
|