@njuptlzf/agent-chat-server 0.1.2 → 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 +15 -9
- package/scripts/agentchat-integrate.mjs +607 -607
- 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/events.js
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
export function emptyUsage() {
|
|
2
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 };
|
|
3
|
+
}
|
|
4
|
+
function toTokenUsage(u) {
|
|
5
|
+
return {
|
|
6
|
+
input: u.input,
|
|
7
|
+
output: u.output,
|
|
8
|
+
cacheRead: u.cacheRead,
|
|
9
|
+
cacheWrite: u.cacheWrite,
|
|
10
|
+
total: u.totalTokens,
|
|
11
|
+
costUsd: u.cost.total,
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function addUsage(a, b) {
|
|
15
|
+
return {
|
|
16
|
+
input: a.input + b.input,
|
|
17
|
+
output: a.output + b.output,
|
|
18
|
+
cacheRead: a.cacheRead + b.cacheRead,
|
|
19
|
+
cacheWrite: a.cacheWrite + b.cacheWrite,
|
|
20
|
+
total: a.total + b.total,
|
|
21
|
+
costUsd: a.costUsd + b.costUsd,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* 卡片数据:内联工具直接给 `details`;MCP 工具走 `structuredContent`
|
|
26
|
+
* (pi 的 convertMcpResult 把它设成整个 CallToolResult,业务负载在内层
|
|
27
|
+
* `structuredContent`,`details` 只剩 {server, tool})。前端只认负载,不认实现。
|
|
28
|
+
*/
|
|
29
|
+
function cardOf(r) {
|
|
30
|
+
const sc = r.structuredContent;
|
|
31
|
+
if (sc && typeof sc === "object") {
|
|
32
|
+
const inner = sc.structuredContent;
|
|
33
|
+
return inner && typeof inner === "object" ? inner : sc;
|
|
34
|
+
}
|
|
35
|
+
return r.details;
|
|
36
|
+
}
|
|
37
|
+
/** Flatten pi tool-result content into a text view the UI can show. */
|
|
38
|
+
function toResultView(result) {
|
|
39
|
+
const r = (result ?? {});
|
|
40
|
+
const text = (r.content ?? [])
|
|
41
|
+
.filter((c) => c.type === "text" && typeof c.text === "string")
|
|
42
|
+
.map((c) => c.text)
|
|
43
|
+
.join("\n");
|
|
44
|
+
return { text, details: cardOf(r) };
|
|
45
|
+
}
|
|
46
|
+
function assistantText(content) {
|
|
47
|
+
if (!Array.isArray(content))
|
|
48
|
+
return "";
|
|
49
|
+
return content
|
|
50
|
+
.filter((c) => c?.type === "text")
|
|
51
|
+
.map((c) => c.text ?? "")
|
|
52
|
+
.join("");
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* 模型报错的用户文案(2026-11-04):pi 的 errorMessage 是原始串(如
|
|
56
|
+
* `429: {"message":"inference exceeds tpm/rpm limit",...}`),直接下发会把
|
|
57
|
+
* 上游 JSON 露进气泡。这里折叠成一句人话 + 保留状态码数字便于口头报障。
|
|
58
|
+
* **failover 匹配不读这条文案**(见 server.ts 的 rawModelError)——它直接从
|
|
59
|
+
* pi 原始事件取 errorMessage 做正则,用户文案怎么改都不影响切换逻辑。
|
|
60
|
+
*/
|
|
61
|
+
export function friendlyModelError(raw) {
|
|
62
|
+
const msg = (raw ?? "").slice(0, 400);
|
|
63
|
+
const status = /\b(4\d\d|5\d\d)\b/.exec(msg)?.[1];
|
|
64
|
+
if (status === "429")
|
|
65
|
+
return `模型限流中,请稍后再试,或在「管理 → 模型」调整档位(429)`;
|
|
66
|
+
if (status === "401" || status === "403")
|
|
67
|
+
return `模型服务鉴权失败,请检查模型配置或联系管理员(${status})`;
|
|
68
|
+
if (status === "402")
|
|
69
|
+
return "模型服务额度不足,请联系管理员(402)";
|
|
70
|
+
if (status)
|
|
71
|
+
return `模型服务暂时不可用,请稍后重试(${status})`;
|
|
72
|
+
if (/timeout|timed out|ETIMEDOUT|ECONNRESET|ECONNREFUSED|socket hang up|fetch failed|network|ENOTFOUND|EAI_AGAIN/i.test(msg))
|
|
73
|
+
return "连接模型服务的网络异常,请稍后重试";
|
|
74
|
+
return "模型请求失败,请稍后重试";
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Translate pi session events into the stable wire protocol.
|
|
78
|
+
* Stateful (message ids, usage totals), so create one mapper per run.
|
|
79
|
+
*/
|
|
80
|
+
export function createEventMapper() {
|
|
81
|
+
let counter = 0;
|
|
82
|
+
let currentMessageId = "";
|
|
83
|
+
let total = emptyUsage();
|
|
84
|
+
return {
|
|
85
|
+
totalUsage: () => total,
|
|
86
|
+
map(event) {
|
|
87
|
+
switch (event.type) {
|
|
88
|
+
case "message_start": {
|
|
89
|
+
if (event.message.role === "assistant") {
|
|
90
|
+
currentMessageId = `m${++counter}`;
|
|
91
|
+
}
|
|
92
|
+
return [];
|
|
93
|
+
}
|
|
94
|
+
case "message_update": {
|
|
95
|
+
const ev = event.assistantMessageEvent;
|
|
96
|
+
if (ev.type === "text_delta") {
|
|
97
|
+
return [{ type: "text_delta", messageId: currentMessageId, delta: ev.delta }];
|
|
98
|
+
}
|
|
99
|
+
if (ev.type === "thinking_delta") {
|
|
100
|
+
return [{ type: "thinking_delta", messageId: currentMessageId, delta: ev.delta }];
|
|
101
|
+
}
|
|
102
|
+
return [];
|
|
103
|
+
}
|
|
104
|
+
case "message_end": {
|
|
105
|
+
const msg = event.message;
|
|
106
|
+
if (msg.role !== "assistant")
|
|
107
|
+
return [];
|
|
108
|
+
const out = [];
|
|
109
|
+
const usage = msg.usage ? toTokenUsage(msg.usage) : undefined;
|
|
110
|
+
if (usage)
|
|
111
|
+
total = addUsage(total, usage);
|
|
112
|
+
out.push({
|
|
113
|
+
type: "message_end",
|
|
114
|
+
messageId: currentMessageId,
|
|
115
|
+
text: assistantText(msg.content),
|
|
116
|
+
usage,
|
|
117
|
+
});
|
|
118
|
+
if (msg.stopReason === "error") {
|
|
119
|
+
out.push({
|
|
120
|
+
type: "error",
|
|
121
|
+
code: "model_error",
|
|
122
|
+
message: friendlyModelError(msg.errorMessage),
|
|
123
|
+
retryable: true,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return out;
|
|
127
|
+
}
|
|
128
|
+
case "tool_execution_start":
|
|
129
|
+
return [{ type: "tool_start", toolCallId: event.toolCallId, name: event.toolName, args: event.args }];
|
|
130
|
+
case "tool_execution_update":
|
|
131
|
+
return [{ type: "tool_update", toolCallId: event.toolCallId, partial: toResultView(event.partialResult) }];
|
|
132
|
+
case "tool_execution_end":
|
|
133
|
+
return [
|
|
134
|
+
{
|
|
135
|
+
type: "tool_end",
|
|
136
|
+
toolCallId: event.toolCallId,
|
|
137
|
+
name: event.toolName,
|
|
138
|
+
ok: !event.isError,
|
|
139
|
+
result: toResultView(event.result),
|
|
140
|
+
durationMs: event.durationMs,
|
|
141
|
+
},
|
|
142
|
+
];
|
|
143
|
+
case "agent_settled":
|
|
144
|
+
return [{ type: "done", aborted: event.aborted, usage: total }];
|
|
145
|
+
default:
|
|
146
|
+
return [];
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Bounds one run's agentic loop: pi has no native turn cap, so the server
|
|
153
|
+
* counts tool rounds on the wire and aborts when the cap is hit.
|
|
154
|
+
*/
|
|
155
|
+
export function createRunAccounting(maxToolRounds) {
|
|
156
|
+
let rounds = 0;
|
|
157
|
+
let hit = false;
|
|
158
|
+
return {
|
|
159
|
+
observe(ev) {
|
|
160
|
+
if (ev.type === "tool_end") {
|
|
161
|
+
rounds++;
|
|
162
|
+
if (maxToolRounds !== undefined && rounds >= maxToolRounds)
|
|
163
|
+
hit = true;
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
toolRounds: () => rounds,
|
|
167
|
+
limitHit: () => hit,
|
|
168
|
+
};
|
|
169
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
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 { auditDeny, auditedWrite, DRAFT_ID, deny401, MAX_ESSAY_CHARS, readJson, sendError, sendJson, SESSION_ID, } from "./server.ts";
|
|
15
|
+
export { openDatabase, SqliteAccountState } from "./sqlite-stores.ts";
|
|
16
|
+
export { localDay } from "./util.ts";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { personaIdsOf } from "./manifest.js";
|
|
2
|
+
export { auditDeny, auditedWrite, DRAFT_ID, deny401, MAX_ESSAY_CHARS, readJson, sendError, sendJson, SESSION_ID, } from "./server.js";
|
|
3
|
+
export { openDatabase, SqliteAccountState } from "./sqlite-stores.js";
|
|
4
|
+
export { localDay } from "./util.js";
|
package/dist/main.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/main.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { mkdirSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { Authz, UnavailableAuthz } from "./authz.js";
|
|
4
|
+
import { loadProduct, loadToolFactory } from "./manifest.js";
|
|
5
|
+
import { createModelConfigStore } from "./model-config.js";
|
|
6
|
+
import { createMcpConfigStore } from "./mcp-config.js";
|
|
7
|
+
import { createPersonaConfigStore } from "./persona-config.js";
|
|
8
|
+
import { initProductRoutes, loadProductAssembly, loadProductRoutes } from "./product-routes.js";
|
|
9
|
+
import { createChatServer } from "./server.js";
|
|
10
|
+
import { createModelRuntime } from "./session.js";
|
|
11
|
+
import { createAdminAuth, createJwtAuth, insecureHeaderAuth } from "./stores.js";
|
|
12
|
+
import { openDatabase, SqliteAccountState, SqliteAudit, SqliteBilling, SqliteHistoryStore, SqliteMembership, SqliteMemberPool, SqliteQuotaGate, SqliteRunLog } from "./sqlite-stores.js";
|
|
13
|
+
import { billingUsage } from "./usage-report.js";
|
|
14
|
+
const productDir = process.env.PRODUCT_DIR;
|
|
15
|
+
if (!productDir) {
|
|
16
|
+
console.error("Set PRODUCT_DIR to a product directory, e.g. PRODUCT_DIR=<product-dir>");
|
|
17
|
+
process.exit(1);
|
|
18
|
+
}
|
|
19
|
+
const product = loadProduct(productDir);
|
|
20
|
+
const dataDir = path.resolve(process.env.DATA_DIR ?? ".data", product.manifest.id);
|
|
21
|
+
mkdirSync(dataDir, { recursive: true });
|
|
22
|
+
const modelRuntime = await createModelRuntime(dataDir, product.manifest.agent.model.provider);
|
|
23
|
+
// 运营配置(provider 白名单、档位候选序列)落在 data 目录的 model-config.json,
|
|
24
|
+
// 不进 git、不重启生效;缺文件或坏 JSON 一律回落 manifest(设计稿 /)。
|
|
25
|
+
const modelConfig = createModelConfigStore(dataDir, product);
|
|
26
|
+
const initialModelConfig = modelConfig.get();
|
|
27
|
+
console.log(`[agent-chat] model config: ${initialModelConfig.source === "file" ? modelConfig.path : "manifest 兜底(无 model-config.json)"} · maxCandidates ${initialModelConfig.maxCandidates}`);
|
|
28
|
+
// 业务接入配置同款(mcp-config.json 为准、manifest `mcp:` 段是种子,设计稿)。
|
|
29
|
+
const mcpConfig = createMcpConfigStore(dataDir, product);
|
|
30
|
+
const initialMcpConfig = mcpConfig.get();
|
|
31
|
+
console.log(`[agent-chat] mcp config: ${initialMcpConfig.source === "file" ? mcpConfig.path : "manifest 兜底(无 mcp-config.json)"} · ${Object.keys(initialMcpConfig.servers).length} 个接入`);
|
|
32
|
+
// 人格配置(persona-config.json 为准、manifest 是种子)。改完不用重启——
|
|
33
|
+
// 每次建会话读一次,写接口 save 后 invalidate 即生效(设计稿)。
|
|
34
|
+
const personaConfig = createPersonaConfigStore(dataDir, product);
|
|
35
|
+
const initialPersonaConfig = personaConfig.get();
|
|
36
|
+
console.log(`[agent-chat] persona config: ${initialPersonaConfig.source === "file" ? personaConfig.path : "manifest 兜底(无 persona-config.json)"} · ${Object.keys(initialPersonaConfig.personas).length} 个人格有覆盖`);
|
|
37
|
+
const toolFactory = await loadToolFactory(product);
|
|
38
|
+
// Pre-scope rows belong to the qualification this deployment used to serve.
|
|
39
|
+
const db = openDatabase(path.join(dataDir, "agent-chat.db"), product.defaultQual, product.defaultPersona);
|
|
40
|
+
// S4:产品 Store 由产品仓自己装配(manifest server.assembly 动态 import,形状不对即启动失败)。
|
|
41
|
+
const productAssembly = await loadProductAssembly(product);
|
|
42
|
+
const jwtSecret = process.env.AUTH_JWT_SECRET;
|
|
43
|
+
if (!jwtSecret) {
|
|
44
|
+
console.warn("[agent-chat] WARNING: AUTH_JWT_SECRET is not set; trusting the x-user-id header (development only).");
|
|
45
|
+
}
|
|
46
|
+
if (!process.env.ADMIN_TOKEN) {
|
|
47
|
+
console.warn("[agent-chat] ADMIN_TOKEN not set; GET /api/usage/report is disabled.");
|
|
48
|
+
}
|
|
49
|
+
// 权限内核:策略种子来自 manifest 的 agent.authz.seedPolicies(出核,
|
|
50
|
+
// core 不内置业务行),空表才种、幂等;enforcer 从 casbin_rule 载策略。加载失败不拦启动——
|
|
51
|
+
// 拿到 UnavailableAuthz 后业务数据 fail-closed(503)、其余闸 fail-open,运维可用 ADMIN_TOKEN 通道修库。
|
|
52
|
+
const membership = new SqliteMembership(db);
|
|
53
|
+
let authz;
|
|
54
|
+
try {
|
|
55
|
+
authz = await Authz.create(db, membership, undefined, product.manifest.agent.authz?.seedPolicies ?? []);
|
|
56
|
+
}
|
|
57
|
+
catch (err) {
|
|
58
|
+
console.error("[agent-chat] casbin 授权内核加载失败(业务数据将 503,其余闸放行):", err);
|
|
59
|
+
authz = new UnavailableAuthz();
|
|
60
|
+
}
|
|
61
|
+
// 开发身份自举(「运维通道」的本地替代):AUTH_JWT_SECRET 未设 =
|
|
62
|
+
// insecureHeaderAuth,身份由 x-user-id 声明,token 里没有任何可信的「谁是管理员」。
|
|
63
|
+
// 不种这一行,本地永远没有 admin → #/admin 进不去、会员也没人发放,整个权限与
|
|
64
|
+
// 会员体系看起来像没做(实际是首任管理员只能靠 ADMIN_TOKEN 或手写 SQL)。
|
|
65
|
+
// 只在开发模式生效,id 可用 DEV_ADMIN_USERS=alice,bob 覆盖;授角色幂等。
|
|
66
|
+
if (!jwtSecret && authz.ready()) {
|
|
67
|
+
const devAdmins = (process.env.DEV_ADMIN_USERS ?? "dev-admin")
|
|
68
|
+
.split(",")
|
|
69
|
+
.map((s) => s.trim())
|
|
70
|
+
.filter((s) => /^[\w.@-]{1,64}$/.test(s));
|
|
71
|
+
for (const id of devAdmins)
|
|
72
|
+
await authz.assignRole(id, "admin");
|
|
73
|
+
console.log(`[agent-chat] dev identity: x-user-id ${devAdmins.join(" / ")} = admin(浏览器侧栏可切换;会员请在 #/admin 发放)`);
|
|
74
|
+
// 旧库补种子:casbin 种子**只在空表种**,所以给 manifest 新增一行
|
|
75
|
+
// (如 admin-api:models)不会自动出现在旧 dev 库里——模型页会 403,看起来像功能没做。
|
|
76
|
+
// 这里按 manifest 补齐缺的 p 行(只加不删;生产零影响,生产该走策略矩阵勾选或
|
|
77
|
+
// ADMIN_TOKEN 通道)。代价:dev 里手删的种子行重启会回来——开发环境要的就是这个。
|
|
78
|
+
const existing = new Set((await authz.listPolicies()).map((p) => `${p.sub}|${p.obj}|${p.act}`));
|
|
79
|
+
let backfilled = 0;
|
|
80
|
+
for (const r of product.manifest.agent.authz?.seedPolicies ?? []) {
|
|
81
|
+
if (existing.has(`${r.sub}|${r.obj}|${r.act}`))
|
|
82
|
+
continue;
|
|
83
|
+
await authz.addPolicy(r.sub, r.obj, r.act);
|
|
84
|
+
backfilled++;
|
|
85
|
+
}
|
|
86
|
+
if (backfilled > 0)
|
|
87
|
+
console.log(`[agent-chat] dev policy backfill: +${backfilled} 行(旧库补 manifest 种子,仅 dev)`);
|
|
88
|
+
}
|
|
89
|
+
// 产品业务路由(manifest `server.routes` 声明,core 不认识任何具体路径)。
|
|
90
|
+
// 装配逻辑抽到 core 的 product-routes.ts(形状校验 + fail-closed),
|
|
91
|
+
// 这样接缝的失败语义能被进程内测试覆盖——入口脚本里的代码没人测得到。
|
|
92
|
+
// 动态 import 放在服务监听前:文件缺失/形状不对=启动失败;init() 立即装配业务数据,
|
|
93
|
+
// 坏卷单/坏 taxonomy 仍是启动期红(fail-closed 不随搬家降级)。
|
|
94
|
+
const productRoutes = await loadProductRoutes(product);
|
|
95
|
+
const deps = {
|
|
96
|
+
product,
|
|
97
|
+
modelRuntime,
|
|
98
|
+
modelConfig,
|
|
99
|
+
mcpConfig,
|
|
100
|
+
personaConfig,
|
|
101
|
+
toolFactory,
|
|
102
|
+
history: new SqliteHistoryStore(db),
|
|
103
|
+
quota: new SqliteQuotaGate(db, product.manifest.agent.limits?.dailyTokenQuota),
|
|
104
|
+
authenticate: jwtSecret ? createJwtAuth(jwtSecret) : insecureHeaderAuth,
|
|
105
|
+
dataDir,
|
|
106
|
+
runLog: new SqliteRunLog(db),
|
|
107
|
+
billing: new SqliteBilling(db),
|
|
108
|
+
authz,
|
|
109
|
+
membership,
|
|
110
|
+
accountState: new SqliteAccountState(db),
|
|
111
|
+
memberPool: new SqliteMemberPool(db),
|
|
112
|
+
// 审计哈希链:主链恒装配;写点接线在 ,读端点在 。
|
|
113
|
+
audit: new SqliteAudit(db),
|
|
114
|
+
billingUsage: async (userId, days, tzOffset) => billingUsage(db, userId, days, tzOffset),
|
|
115
|
+
adminAuth: process.env.ADMIN_TOKEN ? createAdminAuth(process.env.ADMIN_TOKEN) : undefined,
|
|
116
|
+
...(productAssembly ? productAssembly(db) : {}),
|
|
117
|
+
productRoutes: productRoutes?.routes,
|
|
118
|
+
productAdminRoutes: productRoutes?.admin,
|
|
119
|
+
};
|
|
120
|
+
// 坏卷单/坏 taxonomy ⇒ 这里就抛(启动失败),而不是首个请求 500。
|
|
121
|
+
await initProductRoutes(productRoutes, deps);
|
|
122
|
+
const server = createChatServer(deps);
|
|
123
|
+
const port = Number(process.env.PORT ?? 8787);
|
|
124
|
+
server.listen(port, () => {
|
|
125
|
+
console.log(`[agent-chat] ${product.manifest.id} listening on http://localhost:${port}`);
|
|
126
|
+
});
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import type { PersonaUi, ProductManifest, ThinkingLevel } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
+
/** A manifest whose relative paths have been resolved to absolute ones. */
|
|
3
|
+
export interface LoadedProduct {
|
|
4
|
+
manifest: ProductManifest;
|
|
5
|
+
dir: string;
|
|
6
|
+
manifestFile: string;
|
|
7
|
+
systemPromptText: string;
|
|
8
|
+
skillDirs: string[];
|
|
9
|
+
extensionPaths: string[];
|
|
10
|
+
/** `agent.memory` (default true): scope the scopedMemory plugin per session (). */
|
|
11
|
+
memoryEnabled: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Question-bank directories keyed by qualification id (V0). A product with no
|
|
14
|
+
* `quals` gets the single conventional `<product>/questions` under the empty
|
|
15
|
+
* key, so the rest of the server never needs to branch on "has quals".
|
|
16
|
+
*/
|
|
17
|
+
questionDirs: Map<string, string>;
|
|
18
|
+
/** Case-analysis directories keyed by qualification id (V2), same shape as `questionDirs`. */
|
|
19
|
+
caseDirs: Map<string, string>;
|
|
20
|
+
/** Essay-topic directories keyed by qualification id (V4), same shape as `questionDirs`. */
|
|
21
|
+
essayDirs: Map<string, string>;
|
|
22
|
+
/** Paper (整卷) directories keyed by qualification id (V6), same shape as `questionDirs`. */
|
|
23
|
+
paperDirs: Map<string, string>;
|
|
24
|
+
/**
|
|
25
|
+
* 插图目录 keyed by qualification id(2026-11-05),同 `questionDirs` 形状。
|
|
26
|
+
* 存原图(png/jpg/webp/gif/svg),题里只写文件名;由产品路由
|
|
27
|
+
* `GET /api/question-figures/:qual/:file` 下发。
|
|
28
|
+
*/
|
|
29
|
+
figureDirs: Map<string, string>;
|
|
30
|
+
/**
|
|
31
|
+
* Per-qualification agent overrides (S1), keyed by qual id — only entries that
|
|
32
|
+
* declared `agent`. Values are fully resolved (a missing field already carries
|
|
33
|
+
* the product default), so `agentFor` is a plain lookup.
|
|
34
|
+
*/
|
|
35
|
+
qualAgents: Map<string, {
|
|
36
|
+
systemPromptText: string;
|
|
37
|
+
skillDirs: string[];
|
|
38
|
+
}>;
|
|
39
|
+
/**
|
|
40
|
+
* Per-persona overrides (), keyed by persona id — only entries declared
|
|
41
|
+
* under `agent.personas`. Same eager resolution as `qualAgents`: a missing
|
|
42
|
+
* prompt file fails at startup, not on the first assistant chat.
|
|
43
|
+
*/
|
|
44
|
+
personaAgents: Map<string, {
|
|
45
|
+
systemPromptText: string;
|
|
46
|
+
skillDirs: string[];
|
|
47
|
+
allowTools?: string[];
|
|
48
|
+
}>;
|
|
49
|
+
/**
|
|
50
|
+
* Per-persona **display copy** (), keyed by persona id. Deliberately a
|
|
51
|
+
* separate map from `personaAgents`: the UI layer reads only this one, so a
|
|
52
|
+
* future edit can never leak `allowTools`/`skills`/prompt text into
|
|
53
|
+
* `/api/branding` by accident (the split is structural, not a convention).
|
|
54
|
+
*/
|
|
55
|
+
personaUi: Map<string, PersonaUi>;
|
|
56
|
+
/**
|
|
57
|
+
* The id of the product's **default** assistant (`agent.defaultPersona`, ).
|
|
58
|
+
* Core never guesses an id of its own: it is either the product's declaration
|
|
59
|
+
* or `DEFAULT_PERSONA_ID`. It is also the accounting key for the default
|
|
60
|
+
* assistant's quota/run ledger, so the product's choice has to stay stable.
|
|
61
|
+
*/
|
|
62
|
+
defaultPersona: string;
|
|
63
|
+
/**
|
|
64
|
+
* 保存 prompt 时必须出现的段落标题,key = persona id(含默认助手)。
|
|
65
|
+
* 产品声明自己的红线,core 只做校验(「缺了不许存」是通用的,缺哪几段是产品的)。
|
|
66
|
+
*/
|
|
67
|
+
personaRequiredSections: Map<string, string[]>;
|
|
68
|
+
/** Convenience: the default qual id (`quals[0].id`), or "" for a single-track product. */
|
|
69
|
+
defaultQual: string;
|
|
70
|
+
toolsModulePath?: string;
|
|
71
|
+
}
|
|
72
|
+
/** The model settings a tier resolves to. `multiplier` scales the token price. */ export interface ResolvedTier {
|
|
73
|
+
/** Undefined for the implicit default (no tier picker / no tier requested). */
|
|
74
|
+
id?: string;
|
|
75
|
+
label?: string;
|
|
76
|
+
provider: string;
|
|
77
|
+
model: string;
|
|
78
|
+
thinking: ThinkingLevel;
|
|
79
|
+
multiplier: number;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Resolve a `ChatRequest.tier` against the manifest.
|
|
83
|
+
*
|
|
84
|
+
* Returns undefined when the id is unknown, which the caller turns into a 400.
|
|
85
|
+
* Omitting the id is always valid and means the manifest's `agent.model`.
|
|
86
|
+
*/
|
|
87
|
+
export declare function resolveTier(product: LoadedProduct, tierId?: string): ResolvedTier | undefined;
|
|
88
|
+
/**
|
|
89
|
+
* The effective default persona for one qualification (S1): its declared override when it
|
|
90
|
+
* has one (already resolved against the product defaults at load time), the
|
|
91
|
+
* product level otherwise. This is the only place that knows the fallback rule.
|
|
92
|
+
*/
|
|
93
|
+
/**
|
|
94
|
+
* Which prompt/skills a run uses. Precedence: **persona > qual > product**.
|
|
95
|
+
*
|
|
96
|
+
* Persona wins because a secondary assistant is not per-exam — it answers
|
|
97
|
+
* account questions, and giving it an exam-specific prompt would be wrong.
|
|
98
|
+
* Unknown persona falls back to the product default; validating the id is the
|
|
99
|
+
* endpoint's job (400), not this lookup's.
|
|
100
|
+
*
|
|
101
|
+
* The product's default assistant is addressed by `product.defaultPersona`
|
|
102
|
+
* (): that id is **not** a persona override, so it resolves to the
|
|
103
|
+
* product/qual default like "no persona at all" would.
|
|
104
|
+
*/
|
|
105
|
+
export declare function agentFor(product: LoadedProduct, qual?: string, persona?: string): {
|
|
106
|
+
systemPromptText: string;
|
|
107
|
+
skillDirs: string[];
|
|
108
|
+
allowTools?: string[];
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* The ids a client may send as `persona` (通用化): the product's default
|
|
112
|
+
* assistant plus every declared persona. The endpoint validates against this
|
|
113
|
+
* set — core knows no persona id of its own.
|
|
114
|
+
*/
|
|
115
|
+
export declare function personaIdsOf(product: LoadedProduct): Set<string>;
|
|
116
|
+
export declare function loadProduct(dir: string): LoadedProduct;
|
|
117
|
+
export interface ToolContext {
|
|
118
|
+
productId: string;
|
|
119
|
+
productDir: string;
|
|
120
|
+
userId: string;
|
|
121
|
+
/** Server-owned writable directory (per deployment); never the product source dir. */
|
|
122
|
+
dataDir: string;
|
|
123
|
+
/**
|
|
124
|
+
* Qualification the current run studies for (empty when the product has no
|
|
125
|
+
* `quals`). Tools use it to scope content — e.g. which kb subdirectory to load.
|
|
126
|
+
*/
|
|
127
|
+
qual: string;
|
|
128
|
+
/**
|
|
129
|
+
* 人格。产品据此决定给哪些工具:声明人格不该拿到业务工具。
|
|
130
|
+
* 与 `agent.personas[x].allowTools` 是两层——工厂决定「造不造」,白名单决定「留不留」。
|
|
131
|
+
*/
|
|
132
|
+
persona?: string;
|
|
133
|
+
/**
|
|
134
|
+
* 建工单。**服务端注入**:落库、优先级、审计都在服务端,
|
|
135
|
+
* 工具只负责把内容递上来,这样它永远碰不到 store 也改不了别人的工单。
|
|
136
|
+
* 未注入(未接 feedback 的部署)⇒ 工具不该被造出来。
|
|
137
|
+
*/
|
|
138
|
+
createFeedback?: (content: string) => Promise<{
|
|
139
|
+
id: number;
|
|
140
|
+
}>;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Load the product's inline tools. The module's default export is
|
|
144
|
+
* `(ctx: ToolContext) => ToolDefinition[]`, called once per session so tools
|
|
145
|
+
* can close over the current user.
|
|
146
|
+
*/
|
|
147
|
+
export declare function loadToolFactory(product: LoadedProduct): Promise<(ctx: ToolContext) => unknown[]>;
|