@njuptlzf/agent-chat-server 0.2.0 → 0.3.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.
@@ -0,0 +1,146 @@
1
+ /**
2
+ * 「下一步建议」的生成层:一轮对话结束后,把最近的**文本**消息拍平交给产品
3
+ * 默认模型,产出 N 条用户可能发出的简短追问。
4
+ *
5
+ * 定位与 `persona-trial` 不同:这是 run 结束后的附属产物——不建会话、不走 SSE、
6
+ * 不接配额与计费、不写 runLog。调用方(server.ts 路由)负责按人格复核生效模式,
7
+ * 并在**任何失败**时回落 `branding.ui.followUp.static`,绝不 4xx/5xx 冒泡。
8
+ *
9
+ * 与 `@assistant-ui/react` 的接法:前端实现自定义 `SuggestionAdapter.generate`
10
+ * 直接发结构化 messages(库自带的 `createSuggestionAdapter` 会把消息拍成单个
11
+ * prompt 字符串,服务端无法按 role 分离、无法强制中文指令,裁剪也不可测)。
12
+ */
13
+ import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
14
+ import { resolveTier, type LoadedProduct } from "./manifest.ts";
15
+
16
+ /** 裁剪后的单条对话消息:只有文本,图片/附件/工具细节从不离开前端。 */
17
+ export interface ClippedMessage {
18
+ role: "user" | "assistant";
19
+ text: string;
20
+ }
21
+
22
+ /** 生成层的输入。`personaId` 由路由用于复核生效模式,生成层本身不用它。 */
23
+ export interface SuggestionsInput {
24
+ messages: ClippedMessage[];
25
+ count: number;
26
+ /** 生成失败时的回落内容(`branding.ui.followUp.static`)。 */
27
+ staticFallback: string[];
28
+ /** 覆盖内置生成指令(`branding.ui.followUp.systemPrompt`)。 */
29
+ systemPrompt?: string;
30
+ timeoutMs: number;
31
+ }
32
+
33
+ /** 生成层的依赖。真实现读 `deps.modelRuntime`;测试注入替身避免真花钱。 */
34
+ export interface SuggestionsEnv {
35
+ product: LoadedProduct;
36
+ modelRuntime: ModelRuntime;
37
+ }
38
+
39
+ export type SuggestionsRunner = (env: SuggestionsEnv, input: SuggestionsInput) => Promise<string[]>;
40
+
41
+ /**
42
+ * 缺省值与硬上限。前端 `followUpConfigOf` 各持一份同名缺省(两个包不共享模块,
43
+ * 单测钉住两边一致)——改这里要同步那边。
44
+ */
45
+ export const SUGGESTIONS_DEFAULTS = {
46
+ count: 3,
47
+ maxMessages: 10,
48
+ timeoutMs: 8000,
49
+ maxTokens: 200,
50
+ /** 单条消息文本上限(超出截断)。 */
51
+ messageChars: 500,
52
+ /** 整段对话字符上限(从最新往回收)。 */
53
+ totalChars: 4000,
54
+ /** 单条建议字符上限。 */
55
+ suggestionChars: 80,
56
+ } as const;
57
+
58
+ /** 内置生成指令:中性、产品无关;`followUp.systemPrompt` 可整体覆盖。 */
59
+ function defaultSystemPrompt(count: number): string {
60
+ return (
61
+ `根据下面这段用户与助手的对话,推测用户接下来最可能发出的 ${count} 条简短追问。` +
62
+ "每行一条:不要编号、不要任何解释或前后缀,不要复述对话内容,每条不超过 30 个字。"
63
+ );
64
+ }
65
+
66
+ const NUMBERED = /^\s*(?:\d{1,3}[.)、]|[•*·-])\s*/;
67
+
68
+ /** 模型回复 → 建议列表:按行拆、去编号前缀、去空行、截到 count 条。 */
69
+ export function parseSuggestions(text: string, count: number): string[] {
70
+ const cap = Math.max(1, Math.min(count, 20));
71
+ const out: string[] = [];
72
+ for (const line of text.split(/\r?\n/)) {
73
+ const s = line.replace(NUMBERED, "").trim();
74
+ if (!s) continue;
75
+ out.push(s.length > SUGGESTIONS_DEFAULTS.suggestionChars ? s.slice(0, SUGGESTIONS_DEFAULTS.suggestionChars) : s);
76
+ if (out.length >= cap) break;
77
+ }
78
+ return out;
79
+ }
80
+
81
+ /**
82
+ * 服务端强制的输入裁剪——前端已裁一道,这里是权威层:
83
+ * 只留 user/assistant 的非空文本、单条截断、取最近 maxMessages 条、整段不超 totalChars。
84
+ */
85
+ export function clipMessages(raw: unknown, maxMessages: number): ClippedMessage[] {
86
+ if (!Array.isArray(raw)) return [];
87
+ const kept: ClippedMessage[] = [];
88
+ for (const entry of raw) {
89
+ if (!entry || typeof entry !== "object") continue;
90
+ const role = (entry as { role?: unknown }).role;
91
+ const text = (entry as { text?: unknown }).text;
92
+ if ((role !== "user" && role !== "assistant") || typeof text !== "string") continue;
93
+ const trimmed = text.trim();
94
+ if (!trimmed) continue;
95
+ kept.push({ role, text: trimmed.slice(0, SUGGESTIONS_DEFAULTS.messageChars) });
96
+ }
97
+ const window = kept.slice(-Math.max(1, maxMessages));
98
+ let total = 0;
99
+ const out: ClippedMessage[] = [];
100
+ for (let i = window.length - 1; i >= 0; i--) {
101
+ total += window[i]!.text.length;
102
+ if (total > SUGGESTIONS_DEFAULTS.totalChars) break;
103
+ out.unshift(window[i]!);
104
+ }
105
+ return out;
106
+ }
107
+
108
+ /** 真调模型。任何失败都抛给路由(统一 catch 后回落 static)。 */
109
+ export async function runSuggestions(env: SuggestionsEnv, input: SuggestionsInput): Promise<string[]> {
110
+ // 模型来源与建会话同源(manifest `agent.model`);model-config 的档位链是聊天主链
111
+ // 的东西,这条旁路不参与——失败静默,不值得为它引一整套 failover。
112
+ const tier = resolveTier(env.product);
113
+ if (!tier) throw new Error("product has no default model");
114
+ const model = env.modelRuntime.getModel(tier.provider, tier.model);
115
+ if (!model) throw new Error(`unknown model ${tier.provider}/${tier.model}`);
116
+
117
+ const dialogue = input.messages.map((m) => `${m.role}: ${m.text}`).join("\n");
118
+ const systemPrompt = input.systemPrompt?.trim() || defaultSystemPrompt(input.count);
119
+ const controller = new AbortController();
120
+ let timer: ReturnType<typeof setTimeout> | undefined;
121
+ try {
122
+ // 双保险:signal 传进 provider 请求;不遵守 signal 的底层由 Promise.race 兜底超时。
123
+ const timeout = new Promise<never>((_, reject) => {
124
+ timer = setTimeout(() => {
125
+ controller.abort();
126
+ reject(new Error("suggestions timeout"));
127
+ }, Math.max(1, input.timeoutMs));
128
+ });
129
+ // 只构造一条 UserMessage 把对话拍平——AssistantMessage 必填字段太多,别手工造。
130
+ const reply = await Promise.race([
131
+ env.modelRuntime.completeSimple(
132
+ model,
133
+ { systemPrompt, messages: [{ role: "user", content: `最近一段对话:\n${dialogue}`, timestamp: Date.now() }] },
134
+ { signal: controller.signal, maxTokens: SUGGESTIONS_DEFAULTS.maxTokens },
135
+ ),
136
+ timeout,
137
+ ]);
138
+ const parts: string[] = [];
139
+ for (const c of reply.content) {
140
+ if (c.type === "text") parts.push(c.text);
141
+ }
142
+ return parseSuggestions(parts.join("\n"), input.count);
143
+ } finally {
144
+ if (timer !== undefined) clearTimeout(timer);
145
+ }
146
+ }
package/src/testing.ts CHANGED
@@ -1,81 +1,81 @@
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
-
34
- // ── store 实现(内存版:测试首选,无 IO) ──────────────────────────────
35
- export {
36
- DailyTokenQuota,
37
- MemoryAccountState,
38
- MemoryAudit,
39
- MemoryBilling,
40
- MemoryHistoryStore,
41
- MemoryMembership,
42
- createAdminAuth,
43
- createJwtAuth,
44
- insecureHeaderAuth,
45
- } from "./stores.ts";
46
- export type {
47
- AccountStateStore,
48
- MembershipStore,
49
- } from "./stores.ts";
50
-
51
- // ── store 实现(SQLite 版:验真实迁移/约束/事务时才用) ────────────────
52
- export {
53
- SqliteBilling,
54
- SqliteHistoryStore,
55
- SqliteMemberPool,
56
- SqliteMembership,
57
- SqliteQuotaGate,
58
- } from "./sqlite-stores.ts";
59
-
60
- // ── 授权 ────────────────────────────────────────────────────────────────
61
- export { Authz, UnavailableAuthz } from "./authz.ts";
62
- export { capsForPersona, capsForRoles, limitsForPersona } from "./authz.ts";
63
-
64
- // ── 产品装配与产品加载 ──────────────────────────────────────────────────
65
- export { agentFor, loadProduct, loadToolFactory } from "./manifest.ts";
66
- export { loadProductAssembly } from "./product-routes.ts";
67
- export { validatePersona } from "./persona-config.ts";
68
-
69
- // ── 会话 ────────────────────────────────────────────────────────────────
70
- export {
71
- buildCommands,
72
- createModelRuntime,
73
- createProductSession,
74
- disposeProductSession,
75
- expandCommand,
76
- exportHistory,
77
- loadProductSkills,
78
- } from "./session.ts";
79
-
80
- // ── server 构造 ─────────────────────────────────────────────────────────
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
+
34
+ // ── store 实现(内存版:测试首选,无 IO) ──────────────────────────────
35
+ export {
36
+ DailyTokenQuota,
37
+ MemoryAccountState,
38
+ MemoryAudit,
39
+ MemoryBilling,
40
+ MemoryHistoryStore,
41
+ MemoryMembership,
42
+ createAdminAuth,
43
+ createJwtAuth,
44
+ insecureHeaderAuth,
45
+ } from "./stores.ts";
46
+ export type {
47
+ AccountStateStore,
48
+ MembershipStore,
49
+ } from "./stores.ts";
50
+
51
+ // ── store 实现(SQLite 版:验真实迁移/约束/事务时才用) ────────────────
52
+ export {
53
+ SqliteBilling,
54
+ SqliteHistoryStore,
55
+ SqliteMemberPool,
56
+ SqliteMembership,
57
+ SqliteQuotaGate,
58
+ } from "./sqlite-stores.ts";
59
+
60
+ // ── 授权 ────────────────────────────────────────────────────────────────
61
+ export { Authz, UnavailableAuthz } from "./authz.ts";
62
+ export { capsForPersona, capsForRoles, limitsForPersona } from "./authz.ts";
63
+
64
+ // ── 产品装配与产品加载 ──────────────────────────────────────────────────
65
+ export { agentFor, loadProduct, loadToolFactory } from "./manifest.ts";
66
+ export { loadProductAssembly } from "./product-routes.ts";
67
+ export { validatePersona } from "./persona-config.ts";
68
+
69
+ // ── 会话 ────────────────────────────────────────────────────────────────
70
+ export {
71
+ buildCommands,
72
+ createModelRuntime,
73
+ createProductSession,
74
+ disposeProductSession,
75
+ expandCommand,
76
+ exportHistory,
77
+ loadProductSkills,
78
+ } from "./session.ts";
79
+
80
+ // ── server 构造 ─────────────────────────────────────────────────────────
81
81
  export { createChatServer } from "./server.ts";
@@ -1,62 +1,62 @@
1
- import type { DatabaseSync } from "node:sqlite";
2
- import { SqliteMembership } from "./sqlite-stores.ts";
3
-
4
- /**
5
- * 存量会员的「新品类试用」发放(决策①,2026-11-02)。
6
- *
7
- * 背景:老会员当年付的钱买的是默认人格那本账,不含后来才新增的人格账本。不补试用会变成
8
- * 「老会员用新品类要再付一次钱」的体感降级;补一份**统一 30 天**(不按剩余天数等比——
9
- * 3 天/7 天这种碎值难解释,成本也没上界收益)。
10
- *
11
- * 三条语义:
12
- * - **只给在期会员**(`member_until > now`):已经过期的人不是"存量会员";
13
- * - **只给还没有目标账本的人**:有行就跳过(哪怕已过期)⇒ 重复执行不会叠加天数;
14
- * - 默认 **dry-run**,`apply: true` 才写;写走 `extend`(原子续期,和购买/活动同一口径)。
15
- *
16
- * core 不认识任何具体人格名:`from` / `to` 都由运维从产品 manifest 取。
17
- */
18
- export interface TrialGrantOptions {
19
- /** 谁算「老会员」:读哪本账的在期记录。 */
20
- from: string;
21
- /** 发给哪本账。 */
22
- to: string;
23
- days: number;
24
- /** 写进 `granted_by`,事后能回答"这份试用哪来的"。 */
25
- grantedBy: string;
26
- /** false = 只算不发(默认)。 */
27
- apply?: boolean;
28
- }
29
-
30
- export interface TrialGrantReport {
31
- /** 在期老会员数(from 账本)。 */
32
- scanned: number;
33
- /** 其中还没有 to 账本、本次会/已发放的人数。 */
34
- eligible: number;
35
- /** 已有 to 账本而跳过的人数(含过期——幂等的关键)。 */
36
- skipped: number;
37
- /** apply 时逐人结果;dry-run 为空。 */
38
- granted: Array<{ userId: string; memberUntil: string }>;
39
- }
40
-
41
- export async function grantTrial(db: DatabaseSync, opts: TrialGrantOptions): Promise<TrialGrantReport> {
42
- if (!Number.isInteger(opts.days) || opts.days < 1) throw new Error(`days must be a positive integer, got ${opts.days}`);
43
- const now = new Date().toISOString();
44
- const rows = db
45
- .prepare("SELECT user_id FROM membership WHERE product = ? AND member_until > ? ORDER BY user_id")
46
- .all(opts.from, now) as Array<{ user_id: string }>;
47
- const hasTarget = db.prepare("SELECT 1 AS ok FROM membership WHERE user_id = ? AND product = ?");
48
- const membership = new SqliteMembership(db);
49
-
50
- const report: TrialGrantReport = { scanned: rows.length, eligible: 0, skipped: 0, granted: [] };
51
- for (const row of rows) {
52
- if (hasTarget.get(row.user_id, opts.to)) {
53
- report.skipped += 1;
54
- continue;
55
- }
56
- report.eligible += 1;
57
- if (!opts.apply) continue;
58
- const memberUntil = await membership.extend(row.user_id, opts.to, opts.days, opts.grantedBy);
59
- report.granted.push({ userId: row.user_id, memberUntil });
60
- }
61
- return report;
62
- }
1
+ import type { DatabaseSync } from "node:sqlite";
2
+ import { SqliteMembership } from "./sqlite-stores.ts";
3
+
4
+ /**
5
+ * 存量会员的「新品类试用」发放(决策①,2026-11-02)。
6
+ *
7
+ * 背景:老会员当年付的钱买的是默认人格那本账,不含后来才新增的人格账本。不补试用会变成
8
+ * 「老会员用新品类要再付一次钱」的体感降级;补一份**统一 30 天**(不按剩余天数等比——
9
+ * 3 天/7 天这种碎值难解释,成本也没上界收益)。
10
+ *
11
+ * 三条语义:
12
+ * - **只给在期会员**(`member_until > now`):已经过期的人不是"存量会员";
13
+ * - **只给还没有目标账本的人**:有行就跳过(哪怕已过期)⇒ 重复执行不会叠加天数;
14
+ * - 默认 **dry-run**,`apply: true` 才写;写走 `extend`(原子续期,和购买/活动同一口径)。
15
+ *
16
+ * core 不认识任何具体人格名:`from` / `to` 都由运维从产品 manifest 取。
17
+ */
18
+ export interface TrialGrantOptions {
19
+ /** 谁算「老会员」:读哪本账的在期记录。 */
20
+ from: string;
21
+ /** 发给哪本账。 */
22
+ to: string;
23
+ days: number;
24
+ /** 写进 `granted_by`,事后能回答"这份试用哪来的"。 */
25
+ grantedBy: string;
26
+ /** false = 只算不发(默认)。 */
27
+ apply?: boolean;
28
+ }
29
+
30
+ export interface TrialGrantReport {
31
+ /** 在期老会员数(from 账本)。 */
32
+ scanned: number;
33
+ /** 其中还没有 to 账本、本次会/已发放的人数。 */
34
+ eligible: number;
35
+ /** 已有 to 账本而跳过的人数(含过期——幂等的关键)。 */
36
+ skipped: number;
37
+ /** apply 时逐人结果;dry-run 为空。 */
38
+ granted: Array<{ userId: string; memberUntil: string }>;
39
+ }
40
+
41
+ export async function grantTrial(db: DatabaseSync, opts: TrialGrantOptions): Promise<TrialGrantReport> {
42
+ if (!Number.isInteger(opts.days) || opts.days < 1) throw new Error(`days must be a positive integer, got ${opts.days}`);
43
+ const now = new Date().toISOString();
44
+ const rows = db
45
+ .prepare("SELECT user_id FROM membership WHERE product = ? AND member_until > ? ORDER BY user_id")
46
+ .all(opts.from, now) as Array<{ user_id: string }>;
47
+ const hasTarget = db.prepare("SELECT 1 AS ok FROM membership WHERE user_id = ? AND product = ?");
48
+ const membership = new SqliteMembership(db);
49
+
50
+ const report: TrialGrantReport = { scanned: rows.length, eligible: 0, skipped: 0, granted: [] };
51
+ for (const row of rows) {
52
+ if (hasTarget.get(row.user_id, opts.to)) {
53
+ report.skipped += 1;
54
+ continue;
55
+ }
56
+ report.eligible += 1;
57
+ if (!opts.apply) continue;
58
+ const memberUntil = await membership.extend(row.user_id, opts.to, opts.days, opts.grantedBy);
59
+ report.granted.push({ userId: row.user_id, memberUntil });
60
+ }
61
+ return report;
62
+ }
@@ -1,86 +1,86 @@
1
- import type { DatabaseSync } from "node:sqlite";
2
- import type { BillingUsageDay, BillingUsageReport, BillingUsageScope } from "@njuptlzf/agent-chat-protocol";
3
- import { localDay } from "./util.ts";
4
-
5
- /** Window cap: a year of daily buckets is still a readable chart, 10 years is not. */
6
- const MAX_DAYS = 365;
7
- const DEFAULT_DAYS = 30;
8
-
9
- /**
10
- * Spend rolled up by qualification and by **用户的本地日**(B 批次: 消费明细看不出是哪个
11
- * 选项花的钱)。
12
- *
13
- * 日界口径(2026-11-03 统一):与 `/api/progress` 的 `tzOffset` 同源(`localDay`)——
14
- * 中国用户 00:00–08:00 的消费落在「今天」,不再落进 UTC 的昨天。不传 `tzOffsetMinutes`
15
- * = 0(UTC 日界),老调用方行为不变。学习记录的进度分桶早就按本地日,两边从此一致。
16
- *
17
- * Zero migration: `billing_ledger.ref` holds the chat sessionId for every spend,
18
- * and `history` has carried a `scope` column since S0. Joining the two recovers
19
- * the qualification without touching the schema — measured against the dev
20
- * database, 23/23 spend rows matched. Recharges are excluded on purpose: they
21
- * are account-level top-ups, not something a qualification consumed.
22
- *
23
- * The join is on (user_id, session_id) because a session id is only unique per
24
- * user; matching on session_id alone would let one user's spend borrow
25
- * another's scope. A spend whose session row is gone (history wiped) still
26
- * counts — it lands in the "" bucket instead of vanishing, so the totals always
27
- * agree with the ledger.
28
- */
29
- export function billingUsage(
30
- db: DatabaseSync,
31
- userId: string,
32
- days = DEFAULT_DAYS,
33
- tzOffsetMinutes = 0,
34
- nowMs = Date.now(),
35
- ): BillingUsageReport {
36
- const window = Math.min(Math.max(Math.trunc(days) || DEFAULT_DAYS, 1), MAX_DAYS);
37
- // tzOffset 防守与路由同口径:非法值回落 UTC(不 500),这里兜第二道。
38
- const tz = Number.isInteger(tzOffsetMinutes) && tzOffsetMinutes >= -840 && tzOffsetMinutes <= 840 ? tzOffsetMinutes : 0;
39
- // 窗口按**本地日**对齐:从「今天(本地)的 0 点」往回数 window-1 天,
40
- // 而不是 now - window*24h——否则窗口两端各缺半天,图表第一/最后一根柱子永远缺一块。
41
- const todayLocal = localDay(nowMs, tz);
42
- const since = new Date(Date.parse(`${todayLocal}T00:00:00.000Z`) - tz * 60_000 - (window - 1) * 86_400_000).toISOString();
43
-
44
- const byScope = db
45
- .prepare(
46
- `SELECT COALESCE(h.scope, '') AS scope,
47
- COALESCE(SUM(l.amount_cents), 0) AS spend,
48
- COUNT(*) AS charges
49
- FROM billing_ledger l
50
- LEFT JOIN history h ON h.session_id = l.ref AND h.user_id = l.user_id
51
- WHERE l.user_id = ? AND l.kind = 'spend' AND l.at >= ?
52
- GROUP BY COALESCE(h.scope, '')
53
- ORDER BY spend DESC`,
54
- )
55
- .all(userId, since) as Array<{ scope: string; spend: number; charges: number }>;
56
-
57
- // 日键 = localDay(at):SQL 里按偏移平移再切日期,与 progress 的分桶同一算法。
58
- const dayMod = `${tz >= 0 ? "+" : "-"}${Math.abs(tz)} minutes`;
59
- const byDay = db
60
- .prepare(
61
- `SELECT substr(datetime(at, ?), 1, 10) AS day,
62
- COALESCE(SUM(amount_cents), 0) AS spend,
63
- COUNT(*) AS charges
64
- FROM billing_ledger
65
- WHERE user_id = ? AND kind = 'spend' AND at >= ?
66
- GROUP BY day
67
- ORDER BY day`,
68
- )
69
- .all(dayMod, userId, since) as Array<{ day: string; spend: number; charges: number }>;
70
-
71
- const scopes: BillingUsageScope[] = byScope.map((r) => ({
72
- scope: r.scope,
73
- spendCents: r.spend,
74
- charges: r.charges,
75
- }));
76
- const dayList: BillingUsageDay[] = byDay.map((r) => ({ day: r.day, spendCents: r.spend, charges: r.charges }));
77
-
78
- return {
79
- days: window,
80
- // 回显给前端:SpendTrend 的 x 轴标签要用同一套日键补零。
81
- tzOffset: tz,
82
- totalSpendCents: scopes.reduce((sum, s) => sum + s.spendCents, 0),
83
- byScope: scopes,
84
- byDay: dayList,
85
- };
86
- }
1
+ import type { DatabaseSync } from "node:sqlite";
2
+ import type { BillingUsageDay, BillingUsageReport, BillingUsageScope } from "@njuptlzf/agent-chat-protocol";
3
+ import { localDay } from "./util.ts";
4
+
5
+ /** Window cap: a year of daily buckets is still a readable chart, 10 years is not. */
6
+ const MAX_DAYS = 365;
7
+ const DEFAULT_DAYS = 30;
8
+
9
+ /**
10
+ * Spend rolled up by qualification and by **用户的本地日**(B 批次: 消费明细看不出是哪个
11
+ * 选项花的钱)。
12
+ *
13
+ * 日界口径(2026-11-03 统一):与 `/api/progress` 的 `tzOffset` 同源(`localDay`)——
14
+ * 中国用户 00:00–08:00 的消费落在「今天」,不再落进 UTC 的昨天。不传 `tzOffsetMinutes`
15
+ * = 0(UTC 日界),老调用方行为不变。学习记录的进度分桶早就按本地日,两边从此一致。
16
+ *
17
+ * Zero migration: `billing_ledger.ref` holds the chat sessionId for every spend,
18
+ * and `history` has carried a `scope` column since S0. Joining the two recovers
19
+ * the qualification without touching the schema — measured against the dev
20
+ * database, 23/23 spend rows matched. Recharges are excluded on purpose: they
21
+ * are account-level top-ups, not something a qualification consumed.
22
+ *
23
+ * The join is on (user_id, session_id) because a session id is only unique per
24
+ * user; matching on session_id alone would let one user's spend borrow
25
+ * another's scope. A spend whose session row is gone (history wiped) still
26
+ * counts — it lands in the "" bucket instead of vanishing, so the totals always
27
+ * agree with the ledger.
28
+ */
29
+ export function billingUsage(
30
+ db: DatabaseSync,
31
+ userId: string,
32
+ days = DEFAULT_DAYS,
33
+ tzOffsetMinutes = 0,
34
+ nowMs = Date.now(),
35
+ ): BillingUsageReport {
36
+ const window = Math.min(Math.max(Math.trunc(days) || DEFAULT_DAYS, 1), MAX_DAYS);
37
+ // tzOffset 防守与路由同口径:非法值回落 UTC(不 500),这里兜第二道。
38
+ const tz = Number.isInteger(tzOffsetMinutes) && tzOffsetMinutes >= -840 && tzOffsetMinutes <= 840 ? tzOffsetMinutes : 0;
39
+ // 窗口按**本地日**对齐:从「今天(本地)的 0 点」往回数 window-1 天,
40
+ // 而不是 now - window*24h——否则窗口两端各缺半天,图表第一/最后一根柱子永远缺一块。
41
+ const todayLocal = localDay(nowMs, tz);
42
+ const since = new Date(Date.parse(`${todayLocal}T00:00:00.000Z`) - tz * 60_000 - (window - 1) * 86_400_000).toISOString();
43
+
44
+ const byScope = db
45
+ .prepare(
46
+ `SELECT COALESCE(h.scope, '') AS scope,
47
+ COALESCE(SUM(l.amount_cents), 0) AS spend,
48
+ COUNT(*) AS charges
49
+ FROM billing_ledger l
50
+ LEFT JOIN history h ON h.session_id = l.ref AND h.user_id = l.user_id
51
+ WHERE l.user_id = ? AND l.kind = 'spend' AND l.at >= ?
52
+ GROUP BY COALESCE(h.scope, '')
53
+ ORDER BY spend DESC`,
54
+ )
55
+ .all(userId, since) as Array<{ scope: string; spend: number; charges: number }>;
56
+
57
+ // 日键 = localDay(at):SQL 里按偏移平移再切日期,与 progress 的分桶同一算法。
58
+ const dayMod = `${tz >= 0 ? "+" : "-"}${Math.abs(tz)} minutes`;
59
+ const byDay = db
60
+ .prepare(
61
+ `SELECT substr(datetime(at, ?), 1, 10) AS day,
62
+ COALESCE(SUM(amount_cents), 0) AS spend,
63
+ COUNT(*) AS charges
64
+ FROM billing_ledger
65
+ WHERE user_id = ? AND kind = 'spend' AND at >= ?
66
+ GROUP BY day
67
+ ORDER BY day`,
68
+ )
69
+ .all(dayMod, userId, since) as Array<{ day: string; spend: number; charges: number }>;
70
+
71
+ const scopes: BillingUsageScope[] = byScope.map((r) => ({
72
+ scope: r.scope,
73
+ spendCents: r.spend,
74
+ charges: r.charges,
75
+ }));
76
+ const dayList: BillingUsageDay[] = byDay.map((r) => ({ day: r.day, spendCents: r.spend, charges: r.charges }));
77
+
78
+ return {
79
+ days: window,
80
+ // 回显给前端:SpendTrend 的 x 轴标签要用同一套日键补零。
81
+ tzOffset: tz,
82
+ totalSpendCents: scopes.reduce((sum, s) => sum + s.spendCents, 0),
83
+ byScope: scopes,
84
+ byDay: dayList,
85
+ };
86
+ }
package/src/util.ts CHANGED
@@ -1,6 +1,6 @@
1
- /** 平台通用小工具:不含任何产品事实,产品模块与平台模块都可复用。 */
2
-
3
- /** 当地日 `YYYY-MM-DD`:先按偏移平移再切日期,与 /api/progress 的分桶同一算法。 */
4
- export function localDay(ms: number, tzOffsetMinutes: number): string {
5
- return new Date(ms + tzOffsetMinutes * 60_000).toISOString().slice(0, 10);
6
- }
1
+ /** 平台通用小工具:不含任何产品事实,产品模块与平台模块都可复用。 */
2
+
3
+ /** 当地日 `YYYY-MM-DD`:先按偏移平移再切日期,与 /api/progress 的分桶同一算法。 */
4
+ export function localDay(ms: number, tzOffsetMinutes: number): string {
5
+ return new Date(ms + tzOffsetMinutes * 60_000).toISOString().slice(0, 10);
6
+ }