@njuptlzf/agent-chat-server 0.1.0 → 0.1.2
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/package.json +58 -54
- package/scripts/agentchat-integrate.mjs +608 -0
package/package.json
CHANGED
|
@@ -1,54 +1,58 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@njuptlzf/agent-chat-server",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "agentChat platform kernel: sessions, authz, billing, audit, model/MCP/persona config planes, and the product-directory loader.",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"license": "Apache-2.0",
|
|
7
|
-
"main": "./src/index.ts",
|
|
8
|
-
"types": "./src/index.ts",
|
|
9
|
-
"
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
"
|
|
23
|
-
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
"
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
"url": "https://github.com/njuptlzf/agent-chat
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
"
|
|
34
|
-
"agent-chat"
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
"
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
"
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
"
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
"
|
|
52
|
-
"pi-
|
|
53
|
-
|
|
54
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@njuptlzf/agent-chat-server",
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "agentChat platform kernel: sessions, authz, billing, audit, model/MCP/persona config planes, and the product-directory loader.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"main": "./src/index.ts",
|
|
8
|
+
"types": "./src/index.ts",
|
|
9
|
+
"bin": {
|
|
10
|
+
"agentchat-integrate": "./scripts/agentchat-integrate.mjs"
|
|
11
|
+
},
|
|
12
|
+
"exports": {
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./src/index.ts",
|
|
15
|
+
"default": "./src/index.ts"
|
|
16
|
+
},
|
|
17
|
+
"./main": "./src/main.ts",
|
|
18
|
+
"./testing": {
|
|
19
|
+
"types": "./src/testing.ts",
|
|
20
|
+
"default": "./src/testing.ts"
|
|
21
|
+
},
|
|
22
|
+
"./package.json": "./package.json"
|
|
23
|
+
},
|
|
24
|
+
"files": [
|
|
25
|
+
"src",
|
|
26
|
+
"scripts/agentchat-integrate.mjs"
|
|
27
|
+
],
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "git+https://github.com/njuptlzf/agent-chat.git",
|
|
31
|
+
"directory": "packages/server"
|
|
32
|
+
},
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/njuptlzf/agent-chat/issues"
|
|
35
|
+
},
|
|
36
|
+
"homepage": "https://github.com/njuptlzf/agent-chat#readme",
|
|
37
|
+
"keywords": [
|
|
38
|
+
"agent-chat",
|
|
39
|
+
"chat-server",
|
|
40
|
+
"authz",
|
|
41
|
+
"billing",
|
|
42
|
+
"audit"
|
|
43
|
+
],
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=22.13"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@njuptlzf/agent-chat-protocol": "^0.1.0",
|
|
52
|
+
"@earendil-works/pi-coding-agent": "1.2.0",
|
|
53
|
+
"casbin": "^5.51.1",
|
|
54
|
+
"typebox": "^1.3.27",
|
|
55
|
+
"yaml": "^2.8.0",
|
|
56
|
+
"pi-scoped-memory": "^0.2.0"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* agentchat-integrate —— 「一句话对接 agentChat」的机械入口。
|
|
4
|
+
*
|
|
5
|
+
* 设计约束(改动前先读):
|
|
6
|
+
* ① 零第三方依赖:只用 Node 内置模块,不 import `yaml`,不 import 平台 `.ts` 源码。
|
|
7
|
+
* 装进产品仓 node_modules 后仍能独立运行;模板全部内嵌为字符串。
|
|
8
|
+
* ② 产品无关:脚本正文与生成物不含任何具体产品名 / 私有词 / 业务断言。
|
|
9
|
+
* ③ 平台只守契约:`check` 只对形状契约报 FAIL;业务 UT / 接口 / UI 用例缺失
|
|
10
|
+
* 只出 WARN + 建议,绝不产生非零退出。
|
|
11
|
+
* ④ 完整口径不复制:AppDef 的 20 条动态契约由产品 vite.config.ts 的 appDefGuard
|
|
12
|
+
* (复用 @njuptlzf/agent-chat-web/app-def-check)把关,这里只查声明存在性。
|
|
13
|
+
*/
|
|
14
|
+
import fs from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { createRequire } from "node:module";
|
|
17
|
+
import { spawnSync } from "node:child_process";
|
|
18
|
+
import { pathToFileURL } from "node:url";
|
|
19
|
+
import process from "node:process";
|
|
20
|
+
|
|
21
|
+
const CLI_VERSION = "0.1.2";
|
|
22
|
+
const MIN_SERVER = "0.1.1";
|
|
23
|
+
const PKG = {
|
|
24
|
+
protocol: "@njuptlzf/agent-chat-protocol",
|
|
25
|
+
server: "@njuptlzf/agent-chat-server",
|
|
26
|
+
web: "@njuptlzf/agent-chat-web",
|
|
27
|
+
};
|
|
28
|
+
const ID_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
29
|
+
const PLACEHOLDERS = ["<PROVIDER>", "<MODEL_ID>", "<产品标题>", "<组名>"];
|
|
30
|
+
const VALUE_FLAGS = new Set(["--dir", "--id", "--title", "--provider", "--model"]);
|
|
31
|
+
|
|
32
|
+
const HELP = `agentchat-integrate ${CLI_VERSION} — AI 产品接入 agentChat 的机械入口
|
|
33
|
+
|
|
34
|
+
用法(在产品仓根目录执行):
|
|
35
|
+
npx agentchat-integrate init [选项] 生成产品侧骨架
|
|
36
|
+
npx agentchat-integrate check [选项] 输出接入体检报告
|
|
37
|
+
|
|
38
|
+
选项:
|
|
39
|
+
--dir <path> 产品仓根目录,默认当前工作目录
|
|
40
|
+
--id <id> 产品 id(小写字母/数字/连字符),默认取 package.json 的 name 或目录名
|
|
41
|
+
--title <text> branding.title,默认 "<id> 助手"
|
|
42
|
+
--provider <p> agent.model.provider,默认 <PROVIDER>(待填)
|
|
43
|
+
--model <m> agent.model.id,默认 <MODEL_ID>(待填)
|
|
44
|
+
--force 覆盖已存在的生成文件(package.json 永远不覆盖)
|
|
45
|
+
--dry-run 只打印将要生成的文件,不落盘
|
|
46
|
+
--json check 输出结构化 JSON
|
|
47
|
+
--deep check 额外尝试用产品仓的 tsx 跑一次真实 AppDef 校验(失败只记 INFO)
|
|
48
|
+
--help / --version
|
|
49
|
+
|
|
50
|
+
退出码:0 = 无契约违规(WARN/INFO 允许);1 = 存在契约违规;2 = 参数错误 / 平台仓误跑护栏
|
|
51
|
+
|
|
52
|
+
注意:别在 agentChat 平台仓根目录跑 init——那会把骨架生成进平台仓。
|
|
53
|
+
规范见平台仓 docs/specs/产品接入与测试规范.md;AI 执行流程见 agentchat-onboarding Skill。`;
|
|
54
|
+
|
|
55
|
+
// ── 参数 ──────────────────────────────────────────────────────────────────
|
|
56
|
+
|
|
57
|
+
function parseArgs(argv) {
|
|
58
|
+
const opts = {
|
|
59
|
+
cmd: argv[0] ?? "",
|
|
60
|
+
dir: null,
|
|
61
|
+
id: null,
|
|
62
|
+
title: null,
|
|
63
|
+
provider: null,
|
|
64
|
+
model: null,
|
|
65
|
+
force: false,
|
|
66
|
+
dryRun: false,
|
|
67
|
+
json: false,
|
|
68
|
+
deep: false,
|
|
69
|
+
help: false,
|
|
70
|
+
version: false,
|
|
71
|
+
};
|
|
72
|
+
const keyOf = {
|
|
73
|
+
"--dir": "dir", "--id": "id", "--title": "title",
|
|
74
|
+
"--provider": "provider", "--model": "model",
|
|
75
|
+
};
|
|
76
|
+
for (let i = 1; i < argv.length; i++) {
|
|
77
|
+
const a = argv[i];
|
|
78
|
+
if (a === "--help" || a === "-h") opts.help = true;
|
|
79
|
+
else if (a === "--version" || a === "-V") opts.version = true;
|
|
80
|
+
else if (a === "--force") opts.force = true;
|
|
81
|
+
else if (a === "--dry-run") opts.dryRun = true;
|
|
82
|
+
else if (a === "--json") opts.json = true;
|
|
83
|
+
else if (a === "--deep") opts.deep = true;
|
|
84
|
+
else if (VALUE_FLAGS.has(a)) {
|
|
85
|
+
const value = argv[++i];
|
|
86
|
+
if (value === undefined || value.startsWith("--")) return { error: `${a} 缺少取值` };
|
|
87
|
+
opts[keyOf[a]] = value;
|
|
88
|
+
} else return { error: `未知参数:${a}` };
|
|
89
|
+
}
|
|
90
|
+
return { opts };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function usageError(msg) {
|
|
94
|
+
process.stderr.write(`agentchat-integrate: ${msg}\n运行 --help 查看用法。\n`);
|
|
95
|
+
process.exit(2);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 防误跑:平台仓根目录不允许 init(否则骨架会污染平台仓)。 */
|
|
99
|
+
function looksLikePlatformRepo(dir) {
|
|
100
|
+
const pj = path.join(dir, "package.json");
|
|
101
|
+
if (!fs.existsSync(pj)) return false;
|
|
102
|
+
try {
|
|
103
|
+
const name = JSON.parse(fs.readFileSync(pj, "utf8")).name;
|
|
104
|
+
return name === "agent-chat" && fs.existsSync(path.join(dir, "packages/server/src/main.ts"));
|
|
105
|
+
} catch {
|
|
106
|
+
return false;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function readText(dir, rel) {
|
|
111
|
+
const file = path.join(dir, rel);
|
|
112
|
+
try { return fs.readFileSync(file, "utf8"); } catch { return ""; }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function defaultId(dir) {
|
|
116
|
+
const pj = readText(dir, "package.json");
|
|
117
|
+
let name = "";
|
|
118
|
+
try { name = JSON.parse(pj).name ?? ""; } catch { /* 目录名兜底 */ }
|
|
119
|
+
name = String(name).split("/").pop() || path.basename(dir);
|
|
120
|
+
return name.replace(/[^a-z0-9-]/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() || path.basename(dir);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ── init 模板(全部产品无关,形状对齐平台真实契约) ────────────────────────
|
|
124
|
+
|
|
125
|
+
function manifestTemplate(o) {
|
|
126
|
+
return `# 由 agentchat-integrate init 生成。按产品事实补全其余字段。
|
|
127
|
+
# 契约:id / branding.title / agent.systemPrompt / agent.model.{provider,id} 必填;
|
|
128
|
+
# server.routes 必须 ./ 开头、.ts 结尾、文件留在产品目录内。
|
|
129
|
+
id: ${o.id}
|
|
130
|
+
|
|
131
|
+
branding:
|
|
132
|
+
title: ${JSON.stringify(o.title)}
|
|
133
|
+
|
|
134
|
+
agent:
|
|
135
|
+
systemPrompt: ./prompt.md
|
|
136
|
+
model:
|
|
137
|
+
provider: ${o.provider}
|
|
138
|
+
id: ${o.model}
|
|
139
|
+
defaultPersona: default
|
|
140
|
+
|
|
141
|
+
server:
|
|
142
|
+
routes: ./server/routes.ts
|
|
143
|
+
`;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function promptTemplate(o) {
|
|
147
|
+
return `# 系统提示词(产品事实,由产品仓维护)
|
|
148
|
+
|
|
149
|
+
你是 ${o.title} 的 AI 助手。按产品自己的口径回答;平台不解释业务语义。
|
|
150
|
+
`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function packageTemplate(o) {
|
|
154
|
+
return `${JSON.stringify({
|
|
155
|
+
name: o.id,
|
|
156
|
+
private: true,
|
|
157
|
+
type: "module",
|
|
158
|
+
dependencies: {
|
|
159
|
+
[PKG.protocol]: "^0.1.0",
|
|
160
|
+
[PKG.server]: "^0.1.1",
|
|
161
|
+
[PKG.web]: "^0.1.0",
|
|
162
|
+
},
|
|
163
|
+
}, null, 2)}\n`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function routesTemplate(o) {
|
|
167
|
+
return `/**
|
|
168
|
+
* 产品业务路由(由 agentchat-integrate init 生成)。
|
|
169
|
+
*
|
|
170
|
+
* 接缝契约:
|
|
171
|
+
* - manifest 声明 server.routes: "./server/routes.ts";
|
|
172
|
+
* - 本模块导出 createRoutes(),返回 { routes, admin, init? };
|
|
173
|
+
* - 命中就写响应并结束,没命中就 return,core 继续走自己的链(统一 404);
|
|
174
|
+
* - init 抛错 = 启动失败(fail-closed),不是首个请求才 500。
|
|
175
|
+
* core 只认形状,不认任何具体路径——下面的路径全是产品事实,请替换。
|
|
176
|
+
*/
|
|
177
|
+
import { sendJson, type ProductAdminRoute, type ProductRoute, type ServerDeps } from "${PKG.server}";
|
|
178
|
+
|
|
179
|
+
const itemsRoute: ProductRoute = async ({ req, res, url }) => {
|
|
180
|
+
if (req.method !== "GET" || url.pathname !== "/api/${o.id}/items") return;
|
|
181
|
+
sendJson(res, 200, { items: [] });
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
const adminRoute: ProductAdminRoute = {
|
|
185
|
+
match: (pathname) => pathname === "/api/admin/${o.id}/stats",
|
|
186
|
+
group: "<组名>",
|
|
187
|
+
handle: async (_deps: ServerDeps, _req, res) => {
|
|
188
|
+
sendJson(res, 200, { ok: true });
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
export function createRoutes(): {
|
|
193
|
+
routes: ProductRoute[];
|
|
194
|
+
admin: ProductAdminRoute[];
|
|
195
|
+
init?(deps: ServerDeps): void;
|
|
196
|
+
} {
|
|
197
|
+
return {
|
|
198
|
+
routes: [itemsRoute],
|
|
199
|
+
admin: [adminRoute],
|
|
200
|
+
// init(_deps) { /* 启动期装配自己的存储/索引;抛错 = 启动失败 */ },
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function appDefTemplate() {
|
|
207
|
+
return `/**
|
|
208
|
+
* 导航注册表(由 agentchat-integrate init 生成)。
|
|
209
|
+
* 动态 20 条结构契约由产品 vite.config.ts 的 appDefGuard 把关
|
|
210
|
+
* (复用 @njuptlzf/agent-chat-web/app-def-check 的 validateAppDef / sampleHostContexts)。
|
|
211
|
+
* 路由键只能是小写字母:core 用 /^#\\/([a-z]+)/ 从 hash 取键。
|
|
212
|
+
* 这里故意不放 JSX,便于 node --import tsx 直接 import 做契约自检。
|
|
213
|
+
*/
|
|
214
|
+
import type { AppDef } from "${PKG.web}";
|
|
215
|
+
|
|
216
|
+
export const appDef: AppDef = {
|
|
217
|
+
home: "home",
|
|
218
|
+
chatRoute: "chat",
|
|
219
|
+
routes: {
|
|
220
|
+
chat: "助手",
|
|
221
|
+
home: "首页",
|
|
222
|
+
records: "我的记录",
|
|
223
|
+
},
|
|
224
|
+
navItems: () => [
|
|
225
|
+
{ route: "chat", label: "助手" },
|
|
226
|
+
{ route: "home", label: "首页" },
|
|
227
|
+
{ route: "records", label: "我的记录" },
|
|
228
|
+
],
|
|
229
|
+
page: () => null,
|
|
230
|
+
};
|
|
231
|
+
`;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function entryTemplate() {
|
|
235
|
+
return `/**
|
|
236
|
+
* 产品组合根(由 agentchat-integrate init 生成)。
|
|
237
|
+
* 必须导出 appDef(给 vite.config.ts 的构建期守卫)与 App。
|
|
238
|
+
*/
|
|
239
|
+
import { AgentApp } from "${PKG.web}";
|
|
240
|
+
import { appDef } from "./app-def.tsx";
|
|
241
|
+
|
|
242
|
+
export { appDef };
|
|
243
|
+
|
|
244
|
+
export function App() {
|
|
245
|
+
return (
|
|
246
|
+
<AgentApp
|
|
247
|
+
def={appDef}
|
|
248
|
+
texts={() => ({ title: "<产品标题>", assistantLabel: "助手" })}
|
|
249
|
+
/>
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const TEST_TEMPLATES = {
|
|
256
|
+
"test/templates/unit.example.ts": `// 业务 UT 模板 —— 产品仓自己写断言,平台不代判绿。
|
|
257
|
+
// 复制成 test/<name>.test.ts 后,换成产品自己的纯逻辑用例;本文件不是用例。
|
|
258
|
+
//
|
|
259
|
+
// import { test } from "node:test";
|
|
260
|
+
// import assert from "node:assert/strict";
|
|
261
|
+
// test("示例:某段业务逻辑", () => { assert.equal(1 + 1, 2); });
|
|
262
|
+
`,
|
|
263
|
+
"test/templates/api.example.ts": `// 业务接口用例模板 —— 产品仓自己写断言,平台不代判绿。
|
|
264
|
+
// 建议用 @njuptlzf/agent-chat-server/testing 搭真 server 的依赖,
|
|
265
|
+
// 再针对产品自己的路由写请求/响应断言;不要 import 平台 src 深路径。
|
|
266
|
+
//
|
|
267
|
+
// import { createChatServer } from "@njuptlzf/agent-chat-server/testing";
|
|
268
|
+
// import { createRoutes } from "../server/routes.ts";
|
|
269
|
+
`,
|
|
270
|
+
"test/templates/ui.example.ts": `// 业务 UI 用例模板 —— 产品仓自己写断言,平台不代判绿。
|
|
271
|
+
// 产品页面的浏览器验收、截图基线、活体脚本归产品仓维护
|
|
272
|
+
// (见产品仓 docs/验收与提交规范.md)。平台 CI 只跑通用壳的样板活体。
|
|
273
|
+
`,
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
function buildFiles(o) {
|
|
277
|
+
const files = [
|
|
278
|
+
["manifest.yaml", manifestTemplate(o)],
|
|
279
|
+
["prompt.md", promptTemplate(o)],
|
|
280
|
+
["package.json", packageTemplate(o)],
|
|
281
|
+
["server/routes.ts", routesTemplate(o)],
|
|
282
|
+
["web/app-def.tsx", appDefTemplate()],
|
|
283
|
+
["web/entry.tsx", entryTemplate()],
|
|
284
|
+
];
|
|
285
|
+
for (const [rel, content] of Object.entries(TEST_TEMPLATES)) files.push([rel, content]);
|
|
286
|
+
return files;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function init(opts, dir) {
|
|
290
|
+
if (looksLikePlatformRepo(dir)) {
|
|
291
|
+
process.stderr.write(
|
|
292
|
+
"agentchat-integrate: 当前目录是 agentChat 平台仓,init 会污染平台仓。\n" +
|
|
293
|
+
"请在产品仓根目录执行(或用 --dir 指向产品仓 / 被忽略的临时目录)。\n",
|
|
294
|
+
);
|
|
295
|
+
return 2;
|
|
296
|
+
}
|
|
297
|
+
const id = opts.id ?? defaultId(dir);
|
|
298
|
+
if (!ID_RE.test(id)) {
|
|
299
|
+
process.stderr.write(`agentchat-integrate: --id "${id}" 不合规则(只允许小写字母、数字、连字符)\n`);
|
|
300
|
+
return 2;
|
|
301
|
+
}
|
|
302
|
+
const o = {
|
|
303
|
+
id,
|
|
304
|
+
title: opts.title ?? `${id} 助手`,
|
|
305
|
+
provider: opts.provider ?? "<PROVIDER>",
|
|
306
|
+
model: opts.model ?? "<MODEL_ID>",
|
|
307
|
+
};
|
|
308
|
+
let written = 0;
|
|
309
|
+
let skipped = 0;
|
|
310
|
+
for (const [rel, content] of buildFiles(o)) {
|
|
311
|
+
const target = path.join(dir, rel);
|
|
312
|
+
const exists = fs.existsSync(target);
|
|
313
|
+
// package.json 永不覆盖:里面是产品自己的依赖与脚本。
|
|
314
|
+
if (exists && (rel === "package.json" || !opts.force)) {
|
|
315
|
+
process.stdout.write(`[skip] ${rel}${rel === "package.json" ? "(已存在,永不覆盖)" : "(加 --force 覆盖)"}\n`);
|
|
316
|
+
skipped++;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (opts.dryRun) {
|
|
320
|
+
process.stdout.write(`[would-write] ${rel}\n`);
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
324
|
+
fs.writeFileSync(target, content, "utf8");
|
|
325
|
+
process.stdout.write(`[write] ${rel}\n`);
|
|
326
|
+
written++;
|
|
327
|
+
}
|
|
328
|
+
if (!opts.dryRun) {
|
|
329
|
+
process.stdout.write(
|
|
330
|
+
`\n生成 ${written} 个文件、跳过 ${skipped} 个 → ${dir}\n` +
|
|
331
|
+
`下一步:填掉 <PROVIDER> / <MODEL_ID> / <产品标题> / <组名> 占位符,` +
|
|
332
|
+
`在产品 vite.config.ts 接 appDefGuard,然后跑 npx agentchat-integrate check。\n` +
|
|
333
|
+
`业务 UT / 接口 / UI 用例由产品仓按模板自行编写、自跑自判;平台不代判绿。\n`,
|
|
334
|
+
);
|
|
335
|
+
}
|
|
336
|
+
return 0;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// ── check ─────────────────────────────────────────────────────────────────
|
|
340
|
+
|
|
341
|
+
function versionAtLeast(a, b) {
|
|
342
|
+
const pa = String(a).split(".").map(Number);
|
|
343
|
+
const pb = String(b).split(".").map(Number);
|
|
344
|
+
for (let i = 0; i < 3; i++) {
|
|
345
|
+
if ((pa[i] ?? 0) > (pb[i] ?? 0)) return true;
|
|
346
|
+
if ((pa[i] ?? 0) < (pb[i] ?? 0)) return false;
|
|
347
|
+
}
|
|
348
|
+
return true;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function checkDeps(add, dir) {
|
|
352
|
+
const raw = readText(dir, "package.json");
|
|
353
|
+
if (!raw) {
|
|
354
|
+
add("FAIL", "deps", "缺 package.json", "先 npm init 或补一份产品仓 package.json");
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
let pj;
|
|
358
|
+
try { pj = JSON.parse(raw); } catch {
|
|
359
|
+
add("FAIL", "deps", "package.json 不是合法 JSON", "修好 JSON 后重跑");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
const all = { ...(pj.dependencies ?? {}), ...(pj.devDependencies ?? {}) };
|
|
363
|
+
const missing = Object.values(PKG).filter((n) => !(n in all));
|
|
364
|
+
if (missing.length) add("FAIL", "deps", `未声明平台依赖:${missing.join("、")}`,
|
|
365
|
+
`npm i ${PKG.protocol}@^0.1.0 ${PKG.server}@^0.1.1 ${PKG.web}@^0.1.0`);
|
|
366
|
+
else add("OK", "deps", "三个平台包依赖已声明");
|
|
367
|
+
|
|
368
|
+
try {
|
|
369
|
+
const req = createRequire(path.join(dir, "package.json"));
|
|
370
|
+
const file = req.resolve(`${PKG.server}/package.json`);
|
|
371
|
+
const v = JSON.parse(fs.readFileSync(file, "utf8")).version;
|
|
372
|
+
if (versionAtLeast(v, MIN_SERVER)) add("OK", "installed", `已安装 ${PKG.server} ${v}`);
|
|
373
|
+
else add("WARN", "installed", `已安装 ${v} < ${MIN_SERVER},可能没有 npx 入口`,
|
|
374
|
+
`npm i ${PKG.server}@^0.1.1 刷新 lockfile`);
|
|
375
|
+
} catch {
|
|
376
|
+
add("WARN", "installed", "node_modules 未安装或平台包不可解析", "npm install 后重跑 check");
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 从 manifest 文本里取 server.routes 的相对路径(不解析 YAML)。 */
|
|
381
|
+
function serverRoutesOf(text) {
|
|
382
|
+
let inServer = false;
|
|
383
|
+
for (const line of text.split(/\r?\n/)) {
|
|
384
|
+
if (/^server:\s*(#.*)?$/.test(line)) { inServer = true; continue; }
|
|
385
|
+
if (inServer && /^\S/.test(line)) inServer = false;
|
|
386
|
+
const m = inServer && line.match(/^\s+routes:\s*["']?([^"'\s#]+)["']?/);
|
|
387
|
+
if (m) return m[1];
|
|
388
|
+
}
|
|
389
|
+
return null;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function checkManifest(add, dir) {
|
|
393
|
+
const text = readText(dir, "manifest.yaml");
|
|
394
|
+
if (!text) {
|
|
395
|
+
add("FAIL", "manifest", "缺 manifest.yaml", "跑 agentchat-integrate init 生成");
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const problems = [];
|
|
399
|
+
if (!/^id:\s*\S+/m.test(text)) problems.push("缺 id");
|
|
400
|
+
if (!/^branding:\s*(#.*)?$/m.test(text) || !/^\s+title:\s*\S+/m.test(text)) problems.push("缺 branding.title");
|
|
401
|
+
if (!/^\s+systemPrompt:\s*\S+/m.test(text)) problems.push("缺 agent.systemPrompt");
|
|
402
|
+
// model 支持两种写法:块式(provider/id 各占一行)与内联花括号(夹具用的写法)。
|
|
403
|
+
const inlineModel = text.match(/^\s+model:\s*\{([^}]*)\}/m)?.[1] ?? "";
|
|
404
|
+
const hasProvider = /^\s+provider:\s*\S+/m.test(text) || /\bprovider:\s*\S+/.test(inlineModel);
|
|
405
|
+
const hasModelId = /^\s+id:\s*\S+/m.test(text) || /\bid:\s*\S+/.test(inlineModel);
|
|
406
|
+
if (!hasProvider) problems.push("缺 agent.model.provider");
|
|
407
|
+
if (!hasModelId) problems.push("缺 agent.model.id");
|
|
408
|
+
const rel = serverRoutesOf(text);
|
|
409
|
+
if (!rel) problems.push("缺 server.routes 声明");
|
|
410
|
+
else if (!rel.startsWith("./") || !rel.endsWith(".ts")) problems.push(`server.routes "${rel}" 必须 ./ 开头、.ts 结尾`);
|
|
411
|
+
else {
|
|
412
|
+
const resolved = path.resolve(dir, rel);
|
|
413
|
+
if (!resolved.startsWith(path.resolve(dir) + path.sep) || !fs.existsSync(resolved)) {
|
|
414
|
+
problems.push(`server.routes "${rel}" 必须存在且留在产品目录内`);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (!fs.existsSync(path.join(dir, "prompt.md"))) problems.push("缺 prompt.md(loadProduct 会读 systemPrompt 指向的文件)");
|
|
418
|
+
if (problems.length) add("FAIL", "manifest", problems.join(";"), "对照 packages/server/src/manifest.ts 的硬校验补齐");
|
|
419
|
+
else add("OK", "manifest", "必填字段 + server.routes 三道闸 + prompt.md");
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function checkRoutes(add, dir) {
|
|
423
|
+
const text = readText(dir, "server/routes.ts");
|
|
424
|
+
if (!text) { add("FAIL", "routes.ts", "缺 server/routes.ts", "跑 init 生成,或按 ProductRouteModule 形状补上"); return; }
|
|
425
|
+
const problems = [];
|
|
426
|
+
if (!/export\s+(?:async\s+)?function\s+createRoutes\b|export\s+const\s+createRoutes\b/.test(text)) {
|
|
427
|
+
problems.push("未导出 createRoutes()");
|
|
428
|
+
}
|
|
429
|
+
if (!/\broutes\s*:/.test(text)) problems.push("返回值缺 routes");
|
|
430
|
+
if (!/\badmin\s*:/.test(text)) problems.push("返回值缺 admin");
|
|
431
|
+
if (problems.length) add("FAIL", "routes.ts", problems.join(";"), "返回 { routes, admin, init? };落空要 return 让 core 接手");
|
|
432
|
+
else add("OK", "routes.ts", "createRoutes() → { routes, admin }");
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function checkAppDef(add, dir) {
|
|
436
|
+
const entry = readText(dir, "web/entry.tsx");
|
|
437
|
+
const def = readText(dir, "web/app-def.tsx");
|
|
438
|
+
const problems = [];
|
|
439
|
+
if (!entry) problems.push("缺 web/entry.tsx");
|
|
440
|
+
if (!def) problems.push("缺 web/app-def.tsx");
|
|
441
|
+
if (entry) {
|
|
442
|
+
if (!/export\s*\{[^}]*\bappDef\b|export\s+const\s+appDef\b/.test(entry)) problems.push("entry 未导出 appDef");
|
|
443
|
+
if (!/export\s+(?:function|const)\s+App\b/.test(entry)) problems.push("entry 未导出 App");
|
|
444
|
+
}
|
|
445
|
+
if (def) {
|
|
446
|
+
for (const field of ["home", "chatRoute", "routes", "navItems", "page"]) {
|
|
447
|
+
// 两种合法写法都要认:冒号属性(`navItems: () => [...]`)与 ES 简写
|
|
448
|
+
// (`navItems,`,值来自模块作用域的 const)。只用冒号正则会把简写误判成
|
|
449
|
+
// 「缺字段」——真实产品就这么写,属于假红。
|
|
450
|
+
// 简写只认行首,避免把 `import { guard, navItems, ROUTES }` 当成已声明。
|
|
451
|
+
const declared =
|
|
452
|
+
new RegExp(`\\b${field}\\s*:`).test(def) || new RegExp(`^\\s*${field}\\s*(?:,|\\}|$)`, "m").test(def);
|
|
453
|
+
if (!declared) problems.push(`app-def 缺 ${field}`);
|
|
454
|
+
}
|
|
455
|
+
const block = def.match(/routes:\s*\{([\s\S]*?)\}/);
|
|
456
|
+
if (block) {
|
|
457
|
+
const keys = [...block[1].matchAll(/^\s*([A-Za-z0-9_-]+)\s*:/gm)].map((m) => m[1]);
|
|
458
|
+
const bad = keys.filter((k) => !/^[a-z]+$/.test(k));
|
|
459
|
+
if (bad.length) problems.push(`路由键只能小写字母:${bad.join("、")}`);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (problems.length) add("FAIL", "app-def", problems.join(";"), "对照 apps/web/test/app-def-check.test.ts 的最小 def 样板");
|
|
463
|
+
else add("OK", "app-def", "appDef / App 导出、字段齐全、路由键小写");
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function checkPlaceholders(add, dir) {
|
|
467
|
+
const rels = ["manifest.yaml", "server/routes.ts", "web/entry.tsx", "prompt.md"];
|
|
468
|
+
const hits = [];
|
|
469
|
+
for (const rel of rels) {
|
|
470
|
+
const text = readText(dir, rel);
|
|
471
|
+
for (const p of PLACEHOLDERS) if (text.includes(p)) hits.push(`${rel}: ${p}`);
|
|
472
|
+
}
|
|
473
|
+
if (hits.length) add("WARN", "placeholders", `还有 ${hits.length} 处占位符未替换`, `替换 ${[...new Set(PLACEHOLDERS)].join(" / ")} 后重跑`);
|
|
474
|
+
else add("OK", "placeholders", "无未替换占位符");
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function walkFiles(dir, out = []) {
|
|
478
|
+
let entries;
|
|
479
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
|
|
480
|
+
for (const e of entries) {
|
|
481
|
+
const full = path.join(dir, e.name);
|
|
482
|
+
if (e.isDirectory()) walkFiles(full, out);
|
|
483
|
+
else out.push(full);
|
|
484
|
+
}
|
|
485
|
+
return out;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function checkTests(add, dir) {
|
|
489
|
+
const roots = ["test", "tests", "e2e", path.join("web", "test")];
|
|
490
|
+
const files = roots.flatMap((r) => walkFiles(path.join(dir, r)));
|
|
491
|
+
const real = files.filter((f) => /\.(test|spec)\.(ts|tsx|mjs|js)$/.test(f) && !f.includes(`${path.sep}templates${path.sep}`));
|
|
492
|
+
if (real.length) add("OK", "tests", `发现 ${real.length} 个非模板测试文件`);
|
|
493
|
+
else add("WARN", "tests", "未发现业务 UT / 接口 / UI 用例(test/templates 只是骨架)",
|
|
494
|
+
"按 test/templates/*.example.ts 自行编写并自跑自判;平台不代判绿、此项不阻断");
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function checkTooling(add, dir) {
|
|
498
|
+
const wf = path.join(dir, ".github", "workflows");
|
|
499
|
+
const hasCi = fs.existsSync(wf) && fs.readdirSync(wf).some((f) => /\.ya?ml$/.test(f));
|
|
500
|
+
if (hasCi) add("OK", "ci", "存在 CI 工作流");
|
|
501
|
+
else add("WARN", "ci", "未发现 .github/workflows/*.yml", "产品仓自己加 CI,至少跑 typecheck / test / build");
|
|
502
|
+
|
|
503
|
+
let scripts = {};
|
|
504
|
+
try { scripts = JSON.parse(readText(dir, "package.json")).scripts ?? {}; } catch { /* 上面已报过 */ }
|
|
505
|
+
const liveFiles = walkFiles(path.join(dir, "scripts")).filter((f) => /live|e2e/i.test(path.basename(f)));
|
|
506
|
+
const hasLive = Object.keys(scripts).some((s) => /live|e2e/i.test(s)) || liveFiles.length > 0;
|
|
507
|
+
if (hasLive) add("OK", "live", "存在活体 / e2e 入口");
|
|
508
|
+
else add("WARN", "live", "未发现 live / e2e 入口", "产品页面验收需要真浏览器,入口由产品仓维护");
|
|
509
|
+
|
|
510
|
+
const vite = ["vite.config.ts", "vite.config.mts", "vite.config.js", "web/vite.config.ts"]
|
|
511
|
+
.map((r) => readText(dir, r)).join("\n");
|
|
512
|
+
if (/validateAppDef|appDefGuard/.test(vite)) add("OK", "appdef-guard", "vite.config 已接构建期 AppDef 守卫");
|
|
513
|
+
else add("INFO", "appdef-guard", "未检测到 validateAppDef / appDefGuard",
|
|
514
|
+
"在产品 vite.config.ts 复用 @njuptlzf/agent-chat-web/app-def-check;20 条动态契约由它把关,CLI 不复制口径");
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function checkDeep(add, dir) {
|
|
518
|
+
const code = `
|
|
519
|
+
import { pathToFileURL } from "node:url";
|
|
520
|
+
import { sampleHostContexts, validateAppDef } from "${PKG.web}/app-def-check";
|
|
521
|
+
const { appDef } = await import(pathToFileURL(${JSON.stringify(path.join(dir, "web/app-def.tsx"))}).href);
|
|
522
|
+
for (const { name, ctx } of sampleHostContexts()) {
|
|
523
|
+
const problems = validateAppDef(appDef, ctx);
|
|
524
|
+
if (problems.length) {
|
|
525
|
+
console.error(name + ": " + problems.map((p) => p.where + ": " + p.message).join("; "));
|
|
526
|
+
process.exit(1);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
console.log("deep ok");
|
|
530
|
+
`;
|
|
531
|
+
const r = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", code], {
|
|
532
|
+
cwd: dir, encoding: "utf8", timeout: 60_000,
|
|
533
|
+
});
|
|
534
|
+
if (r.status === 0) add("OK", "deep", "真实 validateAppDef 五上下文校验通过");
|
|
535
|
+
else add("INFO", "deep", "deep 校验未完成(缺 tsx / 依赖 / AppDef 不可用)",
|
|
536
|
+
`改由产品 npm run build 的 appDefGuard 把关;详情:${String(r.stderr ?? r.error ?? "").trim().slice(0, 300)}`);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function check(opts, dir) {
|
|
540
|
+
const results = [];
|
|
541
|
+
const add = (level, code, message, suggestion) => {
|
|
542
|
+
results.push({ level, code, message, ...(suggestion ? { suggestion } : {}) });
|
|
543
|
+
};
|
|
544
|
+
checkDeps(add, dir);
|
|
545
|
+
checkManifest(add, dir);
|
|
546
|
+
checkRoutes(add, dir);
|
|
547
|
+
checkAppDef(add, dir);
|
|
548
|
+
checkPlaceholders(add, dir);
|
|
549
|
+
checkTests(add, dir);
|
|
550
|
+
checkTooling(add, dir);
|
|
551
|
+
if (opts.deep) checkDeep(add, dir);
|
|
552
|
+
|
|
553
|
+
const failures = results.filter((r) => r.level === "FAIL");
|
|
554
|
+
const warnings = results.filter((r) => r.level === "WARN");
|
|
555
|
+
const suggestions = results.filter((r) => r.suggestion).map((r) => `[${r.code}] ${r.suggestion}`);
|
|
556
|
+
const report = {
|
|
557
|
+
ok: failures.length === 0,
|
|
558
|
+
dir,
|
|
559
|
+
failures: failures.map((r) => ({ code: r.code, message: r.message })),
|
|
560
|
+
warnings: warnings.map((r) => ({ code: r.code, message: r.message })),
|
|
561
|
+
suggestions,
|
|
562
|
+
results,
|
|
563
|
+
};
|
|
564
|
+
if (opts.json) {
|
|
565
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
566
|
+
} else {
|
|
567
|
+
process.stdout.write(`agentchat-integrate check — ${dir}\n`);
|
|
568
|
+
for (const r of results) {
|
|
569
|
+
process.stdout.write(`[${r.level.padEnd(4)}] ${r.code.padEnd(14)} ${r.message}\n`);
|
|
570
|
+
}
|
|
571
|
+
process.stdout.write(
|
|
572
|
+
`---\n结论:契约违规 ${failures.length} 条;建议 ${warnings.length} 条;` +
|
|
573
|
+
`退出码 ${failures.length ? 1 : 0}${failures.length ? "" : "(建议不阻断)"}\n`,
|
|
574
|
+
);
|
|
575
|
+
if (suggestions.length) process.stdout.write(`建议:\n${suggestions.map((s) => ` - ${s}`).join("\n")}\n`);
|
|
576
|
+
}
|
|
577
|
+
return failures.length ? 1 : 0;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
// ── 入口 ──────────────────────────────────────────────────────────────────
|
|
581
|
+
|
|
582
|
+
function main() {
|
|
583
|
+
const raw = process.argv.slice(2);
|
|
584
|
+
// 全局开关优先于子命令:没有子命令时也要能看帮助/版本。
|
|
585
|
+
if (raw.includes("--help") || raw.includes("-h")) { process.stdout.write(`${HELP}\n`); return 0; }
|
|
586
|
+
if (raw.includes("--version") || raw.includes("-V")) { process.stdout.write(`${CLI_VERSION}\n`); return 0; }
|
|
587
|
+
const parsed = parseArgs(raw);
|
|
588
|
+
if (parsed.error) usageError(parsed.error);
|
|
589
|
+
const opts = parsed.opts;
|
|
590
|
+
if (opts.help) { process.stdout.write(`${HELP}\n`); return 0; }
|
|
591
|
+
if (opts.version) { process.stdout.write(`${CLI_VERSION}\n`); return 0; }
|
|
592
|
+
if (opts.cmd !== "init" && opts.cmd !== "check") {
|
|
593
|
+
usageError(opts.cmd ? `未知子命令:${opts.cmd}` : "缺子命令(init / check)");
|
|
594
|
+
}
|
|
595
|
+
const dir = path.resolve(opts.dir ?? process.cwd());
|
|
596
|
+
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) {
|
|
597
|
+
usageError(`不是目录:${dir}`);
|
|
598
|
+
}
|
|
599
|
+
if (opts.cmd === "check" && !fs.existsSync(dir)) {
|
|
600
|
+
usageError(`目录不存在:${dir}`);
|
|
601
|
+
}
|
|
602
|
+
if (opts.cmd === "init" && !fs.existsSync(dir)) {
|
|
603
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
604
|
+
}
|
|
605
|
+
return opts.cmd === "init" ? init(opts, dir) : check(opts, dir);
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
process.exitCode = main();
|