@njuptlzf/agent-chat-server 0.0.0-stage → 0.1.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/src/events.ts ADDED
@@ -0,0 +1,206 @@
1
+ import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
2
+ import type { ChatEvent, TokenUsage, ToolResultView } from "@njuptlzf/agent-chat-protocol";
3
+
4
+ type PiUsage = {
5
+ input: number;
6
+ output: number;
7
+ cacheRead: number;
8
+ cacheWrite: number;
9
+ totalTokens: number;
10
+ cost: { total: number };
11
+ };
12
+
13
+ export function emptyUsage(): TokenUsage {
14
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 };
15
+ }
16
+
17
+ function toTokenUsage(u: PiUsage): TokenUsage {
18
+ return {
19
+ input: u.input,
20
+ output: u.output,
21
+ cacheRead: u.cacheRead,
22
+ cacheWrite: u.cacheWrite,
23
+ total: u.totalTokens,
24
+ costUsd: u.cost.total,
25
+ };
26
+ }
27
+
28
+ function addUsage(a: TokenUsage, b: TokenUsage): TokenUsage {
29
+ return {
30
+ input: a.input + b.input,
31
+ output: a.output + b.output,
32
+ cacheRead: a.cacheRead + b.cacheRead,
33
+ cacheWrite: a.cacheWrite + b.cacheWrite,
34
+ total: a.total + b.total,
35
+ costUsd: a.costUsd + b.costUsd,
36
+ };
37
+ }
38
+
39
+ /**
40
+ * 卡片数据:内联工具直接给 `details`;MCP 工具走 `structuredContent`
41
+ * (pi 的 convertMcpResult 把它设成整个 CallToolResult,业务负载在内层
42
+ * `structuredContent`,`details` 只剩 {server, tool})。前端只认负载,不认实现。
43
+ */
44
+ function cardOf(r: { details?: unknown; structuredContent?: unknown }): unknown {
45
+ const sc = r.structuredContent;
46
+ if (sc && typeof sc === "object") {
47
+ const inner = (sc as { structuredContent?: unknown }).structuredContent;
48
+ return inner && typeof inner === "object" ? inner : sc;
49
+ }
50
+ return r.details;
51
+ }
52
+
53
+ /** Flatten pi tool-result content into a text view the UI can show. */
54
+ function toResultView(result: unknown): ToolResultView {
55
+ const r = (result ?? {}) as {
56
+ content?: Array<{ type: string; text?: string }>;
57
+ details?: unknown;
58
+ structuredContent?: unknown;
59
+ };
60
+ const text = (r.content ?? [])
61
+ .filter((c) => c.type === "text" && typeof c.text === "string")
62
+ .map((c) => c.text as string)
63
+ .join("\n");
64
+ return { text, details: cardOf(r) };
65
+ }
66
+
67
+ function assistantText(content: unknown): string {
68
+ if (!Array.isArray(content)) return "";
69
+ return content
70
+ .filter((c: { type?: string }) => c?.type === "text")
71
+ .map((c: { text?: string }) => c.text ?? "")
72
+ .join("");
73
+ }
74
+
75
+ /**
76
+ * 模型报错的用户文案(2026-11-04):pi 的 errorMessage 是原始串(如
77
+ * `429: {"message":"inference exceeds tpm/rpm limit",...}`),直接下发会把
78
+ * 上游 JSON 露进气泡。这里折叠成一句人话 + 保留状态码数字便于口头报障。
79
+ * **failover 匹配不读这条文案**(见 server.ts 的 rawModelError)——它直接从
80
+ * pi 原始事件取 errorMessage 做正则,用户文案怎么改都不影响切换逻辑。
81
+ */
82
+ export function friendlyModelError(raw: string | undefined): string {
83
+ const msg = (raw ?? "").slice(0, 400);
84
+ const status = /\b(4\d\d|5\d\d)\b/.exec(msg)?.[1];
85
+ if (status === "429") return `模型限流中,请稍后再试,或在「管理 → 模型」调整档位(429)`;
86
+ if (status === "401" || status === "403") return `模型服务鉴权失败,请检查模型配置或联系管理员(${status})`;
87
+ if (status === "402") return "模型服务额度不足,请联系管理员(402)";
88
+ if (status) return `模型服务暂时不可用,请稍后重试(${status})`;
89
+ if (/timeout|timed out|ETIMEDOUT|ECONNRESET|ECONNREFUSED|socket hang up|fetch failed|network|ENOTFOUND|EAI_AGAIN/i.test(msg))
90
+ return "连接模型服务的网络异常,请稍后重试";
91
+ return "模型请求失败,请稍后重试";
92
+ }
93
+
94
+ export interface EventMapper {
95
+ map(event: AgentSessionEvent): ChatEvent[];
96
+ /** Usage accumulated across every assistant message seen so far. */
97
+ totalUsage(): TokenUsage;
98
+ }
99
+
100
+ /**
101
+ * Translate pi session events into the stable wire protocol.
102
+ * Stateful (message ids, usage totals), so create one mapper per run.
103
+ */
104
+ export function createEventMapper(): EventMapper {
105
+ let counter = 0;
106
+ let currentMessageId = "";
107
+ let total = emptyUsage();
108
+
109
+ return {
110
+ totalUsage: () => total,
111
+ map(event) {
112
+ switch (event.type) {
113
+ case "message_start": {
114
+ if ((event.message as { role?: string }).role === "assistant") {
115
+ currentMessageId = `m${++counter}`;
116
+ }
117
+ return [];
118
+ }
119
+ case "message_update": {
120
+ const ev = event.assistantMessageEvent;
121
+ if (ev.type === "text_delta") {
122
+ return [{ type: "text_delta", messageId: currentMessageId, delta: ev.delta }];
123
+ }
124
+ if (ev.type === "thinking_delta") {
125
+ return [{ type: "thinking_delta", messageId: currentMessageId, delta: ev.delta }];
126
+ }
127
+ return [];
128
+ }
129
+ case "message_end": {
130
+ const msg = event.message as {
131
+ role?: string;
132
+ content?: unknown;
133
+ usage?: PiUsage;
134
+ stopReason?: string;
135
+ errorMessage?: string;
136
+ };
137
+ if (msg.role !== "assistant") return [];
138
+ const out: ChatEvent[] = [];
139
+ const usage = msg.usage ? toTokenUsage(msg.usage) : undefined;
140
+ if (usage) total = addUsage(total, usage);
141
+ out.push({
142
+ type: "message_end",
143
+ messageId: currentMessageId,
144
+ text: assistantText(msg.content),
145
+ usage,
146
+ });
147
+ if (msg.stopReason === "error") {
148
+ out.push({
149
+ type: "error",
150
+ code: "model_error",
151
+ message: friendlyModelError(msg.errorMessage),
152
+ retryable: true,
153
+ });
154
+ }
155
+ return out;
156
+ }
157
+ case "tool_execution_start":
158
+ return [{ type: "tool_start", toolCallId: event.toolCallId, name: event.toolName, args: event.args }];
159
+ case "tool_execution_update":
160
+ return [{ type: "tool_update", toolCallId: event.toolCallId, partial: toResultView(event.partialResult) }];
161
+ case "tool_execution_end":
162
+ return [
163
+ {
164
+ type: "tool_end",
165
+ toolCallId: event.toolCallId,
166
+ name: event.toolName,
167
+ ok: !event.isError,
168
+ result: toResultView(event.result),
169
+ durationMs: event.durationMs,
170
+ },
171
+ ];
172
+ case "agent_settled":
173
+ return [{ type: "done", aborted: event.aborted, usage: total }];
174
+ default:
175
+ return [];
176
+ }
177
+ },
178
+ };
179
+ }
180
+
181
+ export interface RunAccounting {
182
+ /** Feed each outgoing protocol event; counts completed tool rounds. */
183
+ observe(ev: ChatEvent): void;
184
+ toolRounds(): number;
185
+ /** True once a completed tool round hit the configured cap. */
186
+ limitHit(): boolean;
187
+ }
188
+
189
+ /**
190
+ * Bounds one run's agentic loop: pi has no native turn cap, so the server
191
+ * counts tool rounds on the wire and aborts when the cap is hit.
192
+ */
193
+ export function createRunAccounting(maxToolRounds: number | undefined): RunAccounting {
194
+ let rounds = 0;
195
+ let hit = false;
196
+ return {
197
+ observe(ev) {
198
+ if (ev.type === "tool_end") {
199
+ rounds++;
200
+ if (maxToolRounds !== undefined && rounds >= maxToolRounds) hit = true;
201
+ }
202
+ },
203
+ toolRounds: () => rounds,
204
+ limitHit: () => hit,
205
+ };
206
+ }
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `@njuptlzf/agent-chat-server` 的公共入口。
3
+ *
4
+ * 只导出《[PUBLIC_API](../../../docs/design/PUBLIC_API.md)》登记的 18 项
5
+ * 「被产品侧具名 import」的符号。产品仓通过 `@njuptlzf/agent-chat-server` 消费平台,
6
+ * 不再走 `packages/server/src/*` 深路径;平台其余导出都是内部实现,随时可改。
7
+ *
8
+ * 增删导出必须同批改:PUBLIC_API.md、package.json 的 `exports`、
9
+ * `packages/server/test/public-api.test.ts`(那条测试会数条数)。
10
+ */
11
+ export type { LoadedProduct, ToolContext } from "./manifest.ts";
12
+ export { personaIdsOf } from "./manifest.ts";
13
+ export type { ProductAdminRoute, ProductRoute, ServerDeps } from "./server.ts";
14
+ export {
15
+ auditDeny,
16
+ auditedWrite,
17
+ DRAFT_ID,
18
+ deny401,
19
+ MAX_ESSAY_CHARS,
20
+ readJson,
21
+ sendError,
22
+ sendJson,
23
+ SESSION_ID,
24
+ } from "./server.ts";
25
+ export { openDatabase, SqliteAccountState } from "./sqlite-stores.ts";
26
+ export { localDay } from "./util.ts";
package/src/main.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { mkdirSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Authz, UnavailableAuthz } from "./authz.ts";
4
+ import { loadProduct, loadToolFactory } from "./manifest.ts";
5
+ import { createModelConfigStore } from "./model-config.ts";
6
+ import { createMcpConfigStore } from "./mcp-config.ts";
7
+ import { createPersonaConfigStore } from "./persona-config.ts";
8
+ import { initProductRoutes, loadProductAssembly, loadProductRoutes } from "./product-routes.ts";
9
+ import { createChatServer } from "./server.ts";
10
+ import { createModelRuntime } from "./session.ts";
11
+ import { createAdminAuth, createJwtAuth, insecureHeaderAuth } from "./stores.ts";
12
+ import { openDatabase, SqliteAccountState, SqliteAudit, SqliteBilling, SqliteHistoryStore, SqliteMembership, SqliteMemberPool, SqliteQuotaGate, SqliteRunLog } from "./sqlite-stores.ts";
13
+ import { billingUsage } from "./usage-report.ts";
14
+
15
+ const productDir = process.env.PRODUCT_DIR;
16
+ if (!productDir) {
17
+ console.error("Set PRODUCT_DIR to a product directory, e.g. PRODUCT_DIR=<product-dir>");
18
+ process.exit(1);
19
+ }
20
+
21
+ const product = loadProduct(productDir);
22
+ const dataDir = path.resolve(process.env.DATA_DIR ?? ".data", product.manifest.id);
23
+ mkdirSync(dataDir, { recursive: true });
24
+
25
+ const modelRuntime = await createModelRuntime(dataDir, product.manifest.agent.model.provider);
26
+ // 运营配置(provider 白名单、档位候选序列)落在 data 目录的 model-config.json,
27
+ // 不进 git、不重启生效;缺文件或坏 JSON 一律回落 manifest(设计稿 /)。
28
+ const modelConfig = createModelConfigStore(dataDir, product);
29
+ const initialModelConfig = modelConfig.get();
30
+ console.log(
31
+ `[agent-chat] model config: ${initialModelConfig.source === "file" ? modelConfig.path : "manifest 兜底(无 model-config.json)"} · maxCandidates ${initialModelConfig.maxCandidates}`,
32
+ );
33
+ // 业务接入配置同款(mcp-config.json 为准、manifest `mcp:` 段是种子,设计稿)。
34
+ const mcpConfig = createMcpConfigStore(dataDir, product);
35
+ const initialMcpConfig = mcpConfig.get();
36
+ console.log(
37
+ `[agent-chat] mcp config: ${initialMcpConfig.source === "file" ? mcpConfig.path : "manifest 兜底(无 mcp-config.json)"} · ${Object.keys(initialMcpConfig.servers).length} 个接入`,
38
+ );
39
+ // 人格配置(persona-config.json 为准、manifest 是种子)。改完不用重启——
40
+ // 每次建会话读一次,写接口 save 后 invalidate 即生效(设计稿)。
41
+ const personaConfig = createPersonaConfigStore(dataDir, product);
42
+ const initialPersonaConfig = personaConfig.get();
43
+ console.log(
44
+ `[agent-chat] persona config: ${initialPersonaConfig.source === "file" ? personaConfig.path : "manifest 兜底(无 persona-config.json)"} · ${Object.keys(initialPersonaConfig.personas).length} 个人格有覆盖`,
45
+ );
46
+ const toolFactory = await loadToolFactory(product);
47
+
48
+ // Pre-scope rows belong to the qualification this deployment used to serve.
49
+ const db = openDatabase(path.join(dataDir, "agent-chat.db"), product.defaultQual, product.defaultPersona);
50
+ // S4:产品 Store 由产品仓自己装配(manifest server.assembly 动态 import,形状不对即启动失败)。
51
+ const productAssembly = await loadProductAssembly(product);
52
+
53
+ const jwtSecret = process.env.AUTH_JWT_SECRET;
54
+ if (!jwtSecret) {
55
+ console.warn("[agent-chat] WARNING: AUTH_JWT_SECRET is not set; trusting the x-user-id header (development only).");
56
+ }
57
+ if (!process.env.ADMIN_TOKEN) {
58
+ console.warn("[agent-chat] ADMIN_TOKEN not set; GET /api/usage/report is disabled.");
59
+ }
60
+
61
+ // 权限内核:策略种子来自 manifest 的 agent.authz.seedPolicies(出核,
62
+ // core 不内置业务行),空表才种、幂等;enforcer 从 casbin_rule 载策略。加载失败不拦启动——
63
+ // 拿到 UnavailableAuthz 后业务数据 fail-closed(503)、其余闸 fail-open,运维可用 ADMIN_TOKEN 通道修库。
64
+ const membership = new SqliteMembership(db);
65
+ let authz: Authz | UnavailableAuthz;
66
+ try {
67
+ authz = await Authz.create(db, membership, undefined, product.manifest.agent.authz?.seedPolicies ?? []);
68
+ } catch (err) {
69
+ console.error("[agent-chat] casbin 授权内核加载失败(业务数据将 503,其余闸放行):", err);
70
+ authz = new UnavailableAuthz();
71
+ }
72
+
73
+ // 开发身份自举(「运维通道」的本地替代):AUTH_JWT_SECRET 未设 =
74
+ // insecureHeaderAuth,身份由 x-user-id 声明,token 里没有任何可信的「谁是管理员」。
75
+ // 不种这一行,本地永远没有 admin → #/admin 进不去、会员也没人发放,整个权限与
76
+ // 会员体系看起来像没做(实际是首任管理员只能靠 ADMIN_TOKEN 或手写 SQL)。
77
+ // 只在开发模式生效,id 可用 DEV_ADMIN_USERS=alice,bob 覆盖;授角色幂等。
78
+ if (!jwtSecret && authz.ready()) {
79
+ const devAdmins = (process.env.DEV_ADMIN_USERS ?? "dev-admin")
80
+ .split(",")
81
+ .map((s) => s.trim())
82
+ .filter((s) => /^[\w.@-]{1,64}$/.test(s));
83
+ for (const id of devAdmins) await authz.assignRole(id, "admin");
84
+ console.log(
85
+ `[agent-chat] dev identity: x-user-id ${devAdmins.join(" / ")} = admin(浏览器侧栏可切换;会员请在 #/admin 发放)`,
86
+ );
87
+ // 旧库补种子:casbin 种子**只在空表种**,所以给 manifest 新增一行
88
+ // (如 admin-api:models)不会自动出现在旧 dev 库里——模型页会 403,看起来像功能没做。
89
+ // 这里按 manifest 补齐缺的 p 行(只加不删;生产零影响,生产该走策略矩阵勾选或
90
+ // ADMIN_TOKEN 通道)。代价:dev 里手删的种子行重启会回来——开发环境要的就是这个。
91
+ const existing = new Set((await authz.listPolicies()).map((p) => `${p.sub}|${p.obj}|${p.act}`));
92
+ let backfilled = 0;
93
+ for (const r of product.manifest.agent.authz?.seedPolicies ?? []) {
94
+ if (existing.has(`${r.sub}|${r.obj}|${r.act}`)) continue;
95
+ await authz.addPolicy(r.sub, r.obj, r.act);
96
+ backfilled++;
97
+ }
98
+ if (backfilled > 0) console.log(`[agent-chat] dev policy backfill: +${backfilled} 行(旧库补 manifest 种子,仅 dev)`);
99
+ }
100
+
101
+ // 产品业务路由(manifest `server.routes` 声明,core 不认识任何具体路径)。
102
+ // 装配逻辑抽到 core 的 product-routes.ts(形状校验 + fail-closed),
103
+ // 这样接缝的失败语义能被进程内测试覆盖——入口脚本里的代码没人测得到。
104
+ // 动态 import 放在服务监听前:文件缺失/形状不对=启动失败;init() 立即装配业务数据,
105
+ // 坏卷单/坏 taxonomy 仍是启动期红(fail-closed 不随搬家降级)。
106
+ const productRoutes = await loadProductRoutes(product);
107
+
108
+ const deps = {
109
+ product,
110
+ modelRuntime,
111
+ modelConfig,
112
+ mcpConfig,
113
+ personaConfig,
114
+ toolFactory,
115
+ history: new SqliteHistoryStore(db),
116
+ quota: new SqliteQuotaGate(db, product.manifest.agent.limits?.dailyTokenQuota),
117
+ authenticate: jwtSecret ? createJwtAuth(jwtSecret) : insecureHeaderAuth,
118
+ dataDir,
119
+ runLog: new SqliteRunLog(db),
120
+ billing: new SqliteBilling(db),
121
+ authz,
122
+ membership,
123
+ accountState: new SqliteAccountState(db),
124
+ memberPool: new SqliteMemberPool(db),
125
+ // 审计哈希链:主链恒装配;写点接线在 ,读端点在 。
126
+ audit: new SqliteAudit(db),
127
+ billingUsage: async (userId: string, days: number, tzOffset?: number) => billingUsage(db, userId, days, tzOffset),
128
+ adminAuth: process.env.ADMIN_TOKEN ? createAdminAuth(process.env.ADMIN_TOKEN) : undefined,
129
+ ...(productAssembly ? productAssembly(db) : {}),
130
+ productRoutes: productRoutes?.routes,
131
+ productAdminRoutes: productRoutes?.admin,
132
+ };
133
+
134
+ // 坏卷单/坏 taxonomy ⇒ 这里就抛(启动失败),而不是首个请求 500。
135
+ await initProductRoutes(productRoutes, deps);
136
+
137
+ const server = createChatServer(deps);
138
+
139
+ const port = Number(process.env.PORT ?? 8787);
140
+ server.listen(port, () => {
141
+ console.log(`[agent-chat] ${product.manifest.id} listening on http://localhost:${port}`);
142
+ });