@njuptlzf/agent-chat-server 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/authz.d.ts +9 -9
- package/dist/authz.js +6 -1
- package/dist/checkpoint-store.d.ts +78 -0
- package/dist/checkpoint-store.js +52 -0
- package/dist/components.d.ts +15 -0
- package/dist/components.js +50 -0
- package/dist/extension-admission.d.ts +32 -0
- package/dist/extension-admission.js +155 -0
- package/dist/flows.d.ts +49 -0
- package/dist/flows.js +208 -0
- package/dist/ledger.d.ts +90 -0
- package/dist/ledger.js +130 -0
- package/dist/main.js +14 -2
- package/dist/manifest.js +14 -1
- package/dist/orchestrator/engine.d.ts +132 -0
- package/dist/orchestrator/engine.js +1 -0
- package/dist/orchestrator/engines/fake.d.ts +14 -0
- package/dist/orchestrator/engines/fake.js +282 -0
- package/dist/orchestrator/engines/taskflow.d.ts +4 -0
- package/dist/orchestrator/engines/taskflow.js +541 -0
- package/dist/orchestrator/run-spec.d.ts +154 -0
- package/dist/orchestrator/run-spec.js +11 -0
- package/dist/server.d.ts +21 -2
- package/dist/server.js +543 -187
- package/dist/sqlite-stores.d.ts +46 -6
- package/dist/sqlite-stores.js +297 -33
- package/dist/stores.d.ts +3 -34
- package/dist/stores.js +0 -27
- package/dist/testing.d.ts +5 -4
- package/dist/testing.js +5 -4
- package/package.json +7 -6
- package/scripts/agentchat-integrate.mjs +853 -853
- package/src/authz.ts +15 -8
- package/src/checkpoint-store.ts +122 -0
- package/src/components.ts +66 -0
- package/src/extension-admission.ts +131 -0
- package/src/flows.ts +244 -0
- package/src/ledger.ts +193 -0
- package/src/main.ts +16 -2
- package/src/manifest.ts +14 -1
- package/src/orchestrator/engine.ts +134 -0
- package/src/orchestrator/engines/fake.ts +330 -0
- package/src/orchestrator/engines/taskflow.ts +626 -0
- package/src/orchestrator/run-spec.ts +171 -0
- package/src/server.ts +553 -183
- package/src/session.ts +689 -689
- package/src/sqlite-stores.ts +347 -35
- package/src/stores.ts +3 -39
- package/src/testing.ts +4 -4
|
@@ -1,853 +1,853 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
/**
|
|
3
|
-
* agentchat-integrate —— 「一句话对接 agentChat」的机械入口。
|
|
4
|
-
*
|
|
5
|
-
* 设计约束(改动前先读):
|
|
6
|
-
* ① 零第三方依赖:只用 Node 内置模块,不 import `yaml`,不 import 平台 `.ts` 源码。
|
|
7
|
-
* 装进产品仓 node_modules 后仍能独立运行;模板与能力注册表全部内嵌。
|
|
8
|
-
* ② 产品无关:脚本正文与生成物不含任何具体产品名 / 私有词 / 业务断言。
|
|
9
|
-
* ③ 平台守两类门禁:契约形状(FAIL)+ 能力声明与准出(capabilities / 四脚本 / 真跑)。
|
|
10
|
-
* 测试内容**不由平台预制**——每个产品用法不同,用例由产品(或其 AI)按能力注册表
|
|
11
|
-
* 现场生成;check 只验「声明完整、脚本齐、跑绿」,不解析测试写了什么断言。
|
|
12
|
-
* ④ 完整口径不复制:AppDef 的 20 条动态契约由产品 vite.config.ts 的 appDefGuard
|
|
13
|
-
* (复用 @njuptlzf/agent-chat-web/app-def-check)把关,这里只查声明存在性;
|
|
14
|
-
* 能力的准出要求全文以 docs/specs/能力注册表.md 为人读权威,CLI 内嵌机读最小集
|
|
15
|
-
* (id/中文名/触发声明),单测钉两侧 ID 集合一致。
|
|
16
|
-
*/
|
|
17
|
-
import fs from "node:fs";
|
|
18
|
-
import path from "node:path";
|
|
19
|
-
import { createRequire } from "node:module";
|
|
20
|
-
import { spawnSync } from "node:child_process";
|
|
21
|
-
import process from "node:process";
|
|
22
|
-
|
|
23
|
-
const CLI_VERSION = "0.
|
|
24
|
-
const MIN_SERVER = "0.2.0";
|
|
25
|
-
const PKG = {
|
|
26
|
-
protocol: "@njuptlzf/agent-chat-protocol",
|
|
27
|
-
server: "@njuptlzf/agent-chat-server",
|
|
28
|
-
web: "@njuptlzf/agent-chat-web",
|
|
29
|
-
};
|
|
30
|
-
const ID_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
31
|
-
const PLACEHOLDERS = ["<PROVIDER>", "<MODEL_ID>", "<产品标题>"];
|
|
32
|
-
const VALUE_FLAGS = new Set(["--dir", "--id", "--title", "--provider", "--model", "--timeout"]);
|
|
33
|
-
|
|
34
|
-
/**
|
|
35
|
-
* 能力注册表(机读最小集;人读权威 = docs/specs/能力注册表.md,一致性由 CLI 单测钉住)。
|
|
36
|
-
* always = 恒开能力,任何产品都在用,**不写进 capabilities**(写了判 FAIL);
|
|
37
|
-
* optIn = 声明式能力,用了必须声明;trigger 为人读触发声明摘要。
|
|
38
|
-
*/
|
|
39
|
-
const CAP_ALWAYS = [
|
|
40
|
-
{ id: "chat", name: "对话与流式事件、会话历史" },
|
|
41
|
-
{ id: "auth-quota", name: "鉴权与日额度" },
|
|
42
|
-
{ id: "branding", name: "品牌与人格文案下发" },
|
|
43
|
-
{ id: "audit", name: "审计哈希链" },
|
|
44
|
-
{ id: "admin-plane", name: "管理面配置与用量报表" },
|
|
45
|
-
];
|
|
46
|
-
const CAP_OPT_IN = [
|
|
47
|
-
{ id: "product-routes", name: "产品业务路由", trigger: "manifest `server.routes`" },
|
|
48
|
-
{ id: "product-admin-routes", name: "产品管理面路由", trigger: "代码出现 ProductAdminRoute" },
|
|
49
|
-
{ id: "inline-tools", name: "内联工具", trigger: "manifest `tools.inline`" },
|
|
50
|
-
{ id: "mcp-tools", name: "MCP 工具", trigger: "manifest `mcp`" },
|
|
51
|
-
{ id: "tool-confirm", name: "工具确认", trigger: "manifest `confirmTools`" },
|
|
52
|
-
{ id: "personas", name: "多人格", trigger: "manifest `agent.personas`" },
|
|
53
|
-
{ id: "skills", name: "技能目录", trigger: "manifest `agent.skills`" },
|
|
54
|
-
{ id: "extensions", name: "pi 扩展加载", trigger: "manifest `agent.extensions`" },
|
|
55
|
-
{ id: "scoped-memory", name: "作用域记忆", trigger: "manifest 未写 `agent.memory: false` 即默认开启" },
|
|
56
|
-
{ id: "tiers", name: "质量档位", trigger: "manifest `agent.tiers`" },
|
|
57
|
-
{ id: "billing", name: "计费 / 订单 / 套餐 / 充值", trigger: "manifest `billing` 或代码调 /api/orders、/api/recharge" },
|
|
58
|
-
{ id: "authz-seed", name: "权限种子策略", trigger: "manifest `agent.authz.seedPolicies`" },
|
|
59
|
-
{ id: "quals", name: "多资格内容组织", trigger: "manifest `quals`" },
|
|
60
|
-
{ id: "appdef-extensions", name: "前端扩展点", trigger: "app-def/entry 用 navAlias/cardRenderer/guard/footer/extras 或代码调 sendToChat" },
|
|
61
|
-
{ id: "feedback", name: "反馈通道", trigger: "代码调 /api/feedback 或 ctx.createFeedback" },
|
|
62
|
-
{ id: "attachments", name: "附件图片", trigger: "代码调 /api/attachments、/api/images" },
|
|
63
|
-
];
|
|
64
|
-
const CAP_IDS = new Set(CAP_OPT_IN.map((c) => c.id));
|
|
65
|
-
const ALWAYS_IDS = new Set(CAP_ALWAYS.map((c) => c.id));
|
|
66
|
-
|
|
67
|
-
const HELP = `agentchat-integrate ${CLI_VERSION} — AI 产品接入 agentChat 的机械入口
|
|
68
|
-
|
|
69
|
-
用法(在产品仓根目录执行):
|
|
70
|
-
npx agentchat-integrate init [选项] 生成产品侧骨架(不生成测试——测试按能力声明现场写)
|
|
71
|
-
npx agentchat-integrate check [选项] 接入体检:契约形状 + 能力声明对账 + 四脚本真跑
|
|
72
|
-
npx agentchat-integrate capabilities [--json] 打印能力注册表(机读最小集)
|
|
73
|
-
|
|
74
|
-
选项:
|
|
75
|
-
--dir <path> 产品仓根目录,默认当前工作目录
|
|
76
|
-
--id <id> 产品 id(小写字母/数字/连字符),默认取 package.json 的 name 或目录名
|
|
77
|
-
--title <text> branding.title,默认 "<id> 助手"
|
|
78
|
-
--provider <p> agent.model.provider,默认 <PROVIDER>(待填)
|
|
79
|
-
--model <m> agent.model.id,默认 <MODEL_ID>(待填)
|
|
80
|
-
--force 覆盖已存在的生成文件(package.json 永远不覆盖)
|
|
81
|
-
--dry-run 只打印将要生成的文件,不落盘
|
|
82
|
-
--json check / capabilities 输出结构化 JSON
|
|
83
|
-
--deep check 额外用产品仓的 tsx 跑一次真实 AppDef 校验(失败只记 INFO)
|
|
84
|
-
--no-run check 不执行 test:agentchat:* 脚本(只验存在;本地提速用,CI 别用)
|
|
85
|
-
--timeout <秒> 每个测试脚本的执行超时,默认 600
|
|
86
|
-
--help / --version
|
|
87
|
-
|
|
88
|
-
退出码:0 = 无违规(WARN/INFO 允许);1 = 有违规(含能力未声明、缺脚本、脚本跑挂);
|
|
89
|
-
2 = 参数错误 / 平台仓误跑护栏
|
|
90
|
-
|
|
91
|
-
门禁口径:用了哪些平台能力必须在 manifest 的 capabilities: 显式声明;声明的能力要由
|
|
92
|
-
test:agentchat:unit / :api / :ui 三个脚本承载并跑绿(内容由产品按 docs/specs/能力注册表.md
|
|
93
|
-
的准出要求自行编写,平台不预制、不代写业务断言)。init 后直接 check 会红是预期——测试还没写。
|
|
94
|
-
规范见平台仓 docs/specs/产品接入与测试规范.md;AI 执行流程见 agentchat-onboarding Skill。`;
|
|
95
|
-
|
|
96
|
-
// ── 参数 ──────────────────────────────────────────────────────────────────
|
|
97
|
-
|
|
98
|
-
function parseArgs(argv) {
|
|
99
|
-
const opts = {
|
|
100
|
-
cmd: argv[0] ?? "",
|
|
101
|
-
dir: null,
|
|
102
|
-
id: null,
|
|
103
|
-
title: null,
|
|
104
|
-
provider: null,
|
|
105
|
-
model: null,
|
|
106
|
-
force: false,
|
|
107
|
-
dryRun: false,
|
|
108
|
-
json: false,
|
|
109
|
-
deep: false,
|
|
110
|
-
noRun: false,
|
|
111
|
-
timeout: 600,
|
|
112
|
-
help: false,
|
|
113
|
-
version: false,
|
|
114
|
-
};
|
|
115
|
-
const keyOf = {
|
|
116
|
-
"--dir": "dir", "--id": "id", "--title": "title",
|
|
117
|
-
"--provider": "provider", "--model": "model",
|
|
118
|
-
};
|
|
119
|
-
for (let i = 1; i < argv.length; i++) {
|
|
120
|
-
const a = argv[i];
|
|
121
|
-
if (a === "--help" || a === "-h") opts.help = true;
|
|
122
|
-
else if (a === "--version" || a === "-V") opts.version = true;
|
|
123
|
-
else if (a === "--force") opts.force = true;
|
|
124
|
-
else if (a === "--dry-run") opts.dryRun = true;
|
|
125
|
-
else if (a === "--json") opts.json = true;
|
|
126
|
-
else if (a === "--deep") opts.deep = true;
|
|
127
|
-
else if (a === "--no-run") opts.noRun = true;
|
|
128
|
-
else if (a === "--timeout") {
|
|
129
|
-
const value = argv[++i];
|
|
130
|
-
const n = Number(value);
|
|
131
|
-
if (value === undefined || !Number.isFinite(n) || n <= 0) return { error: `--timeout 要正整数秒,收到 "${value}"` };
|
|
132
|
-
opts.timeout = n;
|
|
133
|
-
}
|
|
134
|
-
else if (VALUE_FLAGS.has(a)) {
|
|
135
|
-
const value = argv[++i];
|
|
136
|
-
if (value === undefined || value.startsWith("--")) return { error: `${a} 缺少取值` };
|
|
137
|
-
opts[keyOf[a]] = value;
|
|
138
|
-
} else return { error: `未知参数:${a}` };
|
|
139
|
-
}
|
|
140
|
-
return { opts };
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function usageError(msg) {
|
|
144
|
-
process.stderr.write(`agentchat-integrate: ${msg}\n运行 --help 查看用法。\n`);
|
|
145
|
-
process.exit(2);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** 防误跑:平台仓根目录不允许 init(否则骨架会污染平台仓)。 */
|
|
149
|
-
function looksLikePlatformRepo(dir) {
|
|
150
|
-
const pj = path.join(dir, "package.json");
|
|
151
|
-
if (!fs.existsSync(pj)) return false;
|
|
152
|
-
try {
|
|
153
|
-
const name = JSON.parse(fs.readFileSync(pj, "utf8")).name;
|
|
154
|
-
return name === "agent-chat" && fs.existsSync(path.join(dir, "packages/server/src/main.ts"));
|
|
155
|
-
} catch {
|
|
156
|
-
return false;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
function readText(dir, rel) {
|
|
161
|
-
const file = path.join(dir, rel);
|
|
162
|
-
try { return fs.readFileSync(file, "utf8"); } catch { return ""; }
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
function defaultId(dir) {
|
|
166
|
-
const pj = readText(dir, "package.json");
|
|
167
|
-
let name = "";
|
|
168
|
-
try { name = JSON.parse(pj).name ?? ""; } catch { /* 目录名兜底 */ }
|
|
169
|
-
name = String(name).split("/").pop() || path.basename(dir);
|
|
170
|
-
return name.replace(/[^a-z0-9-]/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() || path.basename(dir);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// ── init 模板(全部产品无关,形状对齐平台真实契约) ────────────────────────
|
|
174
|
-
|
|
175
|
-
function manifestTemplate(o) {
|
|
176
|
-
return `# 由 agentchat-integrate init 生成。按产品事实补全其余字段。
|
|
177
|
-
# 契约:id / branding.title / agent.systemPrompt / agent.model.{provider,id} 必填;
|
|
178
|
-
# server.routes 必须 ./ 开头、.ts 结尾、文件留在产品目录内。
|
|
179
|
-
id: ${o.id}
|
|
180
|
-
|
|
181
|
-
branding:
|
|
182
|
-
title: ${JSON.stringify(o.title)}
|
|
183
|
-
|
|
184
|
-
# 准出声明:本产品实际用到的平台能力,用了就必须写在这里(恒开能力 chat/auth-quota/
|
|
185
|
-
# branding/audit/admin-plane 不列——列了 check 判 FAIL)。下面两份是按当前骨架推导的
|
|
186
|
-
# 初始值:声明了 server.routes ⇒ product-routes;未关 agent.memory ⇒ scoped-memory。
|
|
187
|
-
# 每加一项 manifest 字段 / 代码用法,同步增删这里。ID 表与准出要求:
|
|
188
|
-
# 平台仓 docs/specs/能力注册表.md(npx agentchat-integrate capabilities 可查)。
|
|
189
|
-
capabilities:
|
|
190
|
-
- product-routes
|
|
191
|
-
- scoped-memory
|
|
192
|
-
|
|
193
|
-
agent:
|
|
194
|
-
systemPrompt: ./prompt.md
|
|
195
|
-
model:
|
|
196
|
-
provider: ${o.provider}
|
|
197
|
-
id: ${o.model}
|
|
198
|
-
defaultPersona: default
|
|
199
|
-
|
|
200
|
-
server:
|
|
201
|
-
routes: ./server/routes.ts
|
|
202
|
-
`;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
function promptTemplate(o) {
|
|
206
|
-
return `# 系统提示词(产品事实,由产品仓维护)
|
|
207
|
-
|
|
208
|
-
你是 ${o.title} 的 AI 助手。按产品自己的口径回答;平台不解释业务语义。
|
|
209
|
-
`;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function packageTemplate(o) {
|
|
213
|
-
return `${JSON.stringify({
|
|
214
|
-
name: o.id,
|
|
215
|
-
private: true,
|
|
216
|
-
type: "module",
|
|
217
|
-
dependencies: {
|
|
218
|
-
[PKG.protocol]: "^0.
|
|
219
|
-
[PKG.server]: "^0.
|
|
220
|
-
[PKG.web]: "^0.
|
|
221
|
-
},
|
|
222
|
-
devDependencies: {
|
|
223
|
-
tsx: "^4.20.0",
|
|
224
|
-
typescript: "^5.9.0",
|
|
225
|
-
},
|
|
226
|
-
}, null, 2)}\n`;
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
function routesTemplate(o) {
|
|
230
|
-
return `/**
|
|
231
|
-
* 产品业务路由(由 agentchat-integrate init 生成)。
|
|
232
|
-
*
|
|
233
|
-
* 接缝契约:
|
|
234
|
-
* - manifest 声明 server.routes: "./server/routes.ts";
|
|
235
|
-
* - 本模块导出 createRoutes(),返回 { routes, admin, init? };
|
|
236
|
-
* - 命中就写响应并结束,没命中就 return,core 继续走自己的链(统一 404);
|
|
237
|
-
* - init 抛错 = 启动失败(fail-closed),不是首个请求才 500。
|
|
238
|
-
* core 只认形状,不认任何具体路径——下面的路径全是产品事实,请替换。
|
|
239
|
-
*/
|
|
240
|
-
import { sendJson, type ProductRoute, type ServerDeps } from "${PKG.server}";
|
|
241
|
-
|
|
242
|
-
const itemsRoute: ProductRoute = async ({ req, res, url }) => {
|
|
243
|
-
if (req.method !== "GET" || url.pathname !== "/api/${o.id}/items") return;
|
|
244
|
-
sendJson(res, 200, { items: [] });
|
|
245
|
-
};
|
|
246
|
-
|
|
247
|
-
/*
|
|
248
|
-
* 管理面路由样板:真的用它时(import ProductAdminRoute 并取消下面的注释),
|
|
249
|
-
* 要在 manifest 的 capabilities 里声明 product-admin-routes,并给 group 配一条
|
|
250
|
-
* {sub:"admin",obj:"admin-api",act:<group>} 种子(authz-seed 也要声明)。
|
|
251
|
-
*
|
|
252
|
-
* import type { ProductAdminRoute } from "${PKG.server}";
|
|
253
|
-
* const adminRoute: ProductAdminRoute = {
|
|
254
|
-
* match: (pathname) => pathname === "/api/admin/${o.id}/stats",
|
|
255
|
-
* group: "${o.id}-admin",
|
|
256
|
-
* handle: async (_deps: ServerDeps, _req, res) => { sendJson(res, 200, { ok: true }); },
|
|
257
|
-
* };
|
|
258
|
-
*/
|
|
259
|
-
|
|
260
|
-
export function createRoutes() {
|
|
261
|
-
return {
|
|
262
|
-
routes: [itemsRoute],
|
|
263
|
-
admin: [],
|
|
264
|
-
// init(_deps: ServerDeps) { /* 启动期装配自己的存储/索引;抛错 = 启动失败 */ },
|
|
265
|
-
};
|
|
266
|
-
}
|
|
267
|
-
`;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
function appDefTemplate() {
|
|
271
|
-
return `/**
|
|
272
|
-
* 导航注册表(由 agentchat-integrate init 生成)。
|
|
273
|
-
* 动态 20 条结构契约由产品 vite.config.ts 的 appDefGuard 把关
|
|
274
|
-
* (复用 @njuptlzf/agent-chat-web/app-def-check 的 validateAppDef / sampleHostContexts)。
|
|
275
|
-
* 路由键只能是小写字母:core 用 /^#\\/([a-z]+)/ 从 hash 取键。
|
|
276
|
-
* 这里故意不放 JSX,便于 node --import tsx 直接 import 做契约自检。
|
|
277
|
-
*/
|
|
278
|
-
import type { AppDef } from "${PKG.web}";
|
|
279
|
-
|
|
280
|
-
export const appDef: AppDef = {
|
|
281
|
-
home: "home",
|
|
282
|
-
chatRoute: "chat",
|
|
283
|
-
routes: {
|
|
284
|
-
chat: "助手",
|
|
285
|
-
home: "首页",
|
|
286
|
-
records: "我的记录",
|
|
287
|
-
},
|
|
288
|
-
navItems: () => [
|
|
289
|
-
{ route: "chat", label: "助手" },
|
|
290
|
-
{ route: "home", label: "首页" },
|
|
291
|
-
{ route: "records", label: "我的记录" },
|
|
292
|
-
],
|
|
293
|
-
page: () => null,
|
|
294
|
-
};
|
|
295
|
-
`;
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
function entryTemplate() {
|
|
299
|
-
return `/**
|
|
300
|
-
* 产品组合根(由 agentchat-integrate init 生成)。
|
|
301
|
-
* 必须导出 appDef(给 vite.config.ts 的构建期守卫)与 App。
|
|
302
|
-
*/
|
|
303
|
-
import { AgentApp } from "${PKG.web}";
|
|
304
|
-
import { appDef } from "./app-def.tsx";
|
|
305
|
-
|
|
306
|
-
export { appDef };
|
|
307
|
-
|
|
308
|
-
export function App() {
|
|
309
|
-
return (
|
|
310
|
-
<AgentApp
|
|
311
|
-
def={appDef}
|
|
312
|
-
texts={() => ({ title: "<产品标题>", assistantLabel: "助手" })}
|
|
313
|
-
/>
|
|
314
|
-
);
|
|
315
|
-
}
|
|
316
|
-
`;
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
// init 不生成任何测试文件:用例内容由产品的实际用法决定,平台不预制、不代写。
|
|
320
|
-
// 准出测试由产品(或其 AI)按 docs/specs/能力注册表.md 的准出要求现场生成,
|
|
321
|
-
// check 只验「声明完整 + 四脚本齐 + 跑绿」。
|
|
322
|
-
function buildFiles(o) {
|
|
323
|
-
return [
|
|
324
|
-
["manifest.yaml", manifestTemplate(o)],
|
|
325
|
-
["prompt.md", promptTemplate(o)],
|
|
326
|
-
["package.json", packageTemplate(o)],
|
|
327
|
-
["server/routes.ts", routesTemplate(o)],
|
|
328
|
-
["web/app-def.tsx", appDefTemplate()],
|
|
329
|
-
["web/entry.tsx", entryTemplate()],
|
|
330
|
-
];
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
function init(opts, dir) {
|
|
334
|
-
if (looksLikePlatformRepo(dir)) {
|
|
335
|
-
process.stderr.write(
|
|
336
|
-
"agentchat-integrate: 当前目录是 agentChat 平台仓,init 会污染平台仓。\n" +
|
|
337
|
-
"请在产品仓根目录执行(或用 --dir 指向产品仓 / 被忽略的临时目录)。\n",
|
|
338
|
-
);
|
|
339
|
-
return 2;
|
|
340
|
-
}
|
|
341
|
-
const id = opts.id ?? defaultId(dir);
|
|
342
|
-
if (!ID_RE.test(id)) {
|
|
343
|
-
process.stderr.write(`agentchat-integrate: --id "${id}" 不合规则(只允许小写字母、数字、连字符)\n`);
|
|
344
|
-
return 2;
|
|
345
|
-
}
|
|
346
|
-
const o = {
|
|
347
|
-
id,
|
|
348
|
-
title: opts.title ?? `${id} 助手`,
|
|
349
|
-
provider: opts.provider ?? "<PROVIDER>",
|
|
350
|
-
model: opts.model ?? "<MODEL_ID>",
|
|
351
|
-
};
|
|
352
|
-
let written = 0;
|
|
353
|
-
let skipped = 0;
|
|
354
|
-
for (const [rel, content] of buildFiles(o)) {
|
|
355
|
-
const target = path.join(dir, rel);
|
|
356
|
-
const exists = fs.existsSync(target);
|
|
357
|
-
// package.json 永不覆盖:里面是产品自己的依赖与脚本。
|
|
358
|
-
if (exists && (rel === "package.json" || !opts.force)) {
|
|
359
|
-
process.stdout.write(`[skip] ${rel}${rel === "package.json" ? "(已存在,永不覆盖)" : "(加 --force 覆盖)"}\n`);
|
|
360
|
-
skipped++;
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
if (opts.dryRun) {
|
|
364
|
-
process.stdout.write(`[would-write] ${rel}\n`);
|
|
365
|
-
continue;
|
|
366
|
-
}
|
|
367
|
-
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
368
|
-
fs.writeFileSync(target, content, "utf8");
|
|
369
|
-
process.stdout.write(`[write] ${rel}\n`);
|
|
370
|
-
written++;
|
|
371
|
-
}
|
|
372
|
-
if (!opts.dryRun) {
|
|
373
|
-
process.stdout.write(
|
|
374
|
-
`\n生成 ${written} 个文件、跳过 ${skipped} 个 → ${dir}\n` +
|
|
375
|
-
`下一步:填掉 <PROVIDER> / <MODEL_ID> / <产品标题> 占位符;核对 manifest 的 capabilities 声明\n` +
|
|
376
|
-
`(恒开能力不列,ID 表见 npx agentchat-integrate capabilities 或 docs/specs/能力注册表.md)。\n` +
|
|
377
|
-
`然后**按声明的能力现场写 UT / 接口 / UI 测试并写入 package.json 的 test:agentchat{,:unit,:api,:ui} 四脚本**\n` +
|
|
378
|
-
`(平台不预制用例——每个产品用法不同;准出要求逐条参考能力注册表,别把示例抄成断言)。\n` +
|
|
379
|
-
`写完再跑 npx agentchat-integrate check;现在跑会因缺测试/缺脚本判红,这是预期。\n`,
|
|
380
|
-
);
|
|
381
|
-
}
|
|
382
|
-
return 0;
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
// ── check ─────────────────────────────────────────────────────────────────
|
|
386
|
-
|
|
387
|
-
function versionAtLeast(a, b) {
|
|
388
|
-
const pa = String(a).split(".").map(Number);
|
|
389
|
-
const pb = String(b).split(".").map(Number);
|
|
390
|
-
for (let i = 0; i < 3; i++) {
|
|
391
|
-
if ((pa[i] ?? 0) > (pb[i] ?? 0)) return true;
|
|
392
|
-
if ((pa[i] ?? 0) < (pb[i] ?? 0)) return false;
|
|
393
|
-
}
|
|
394
|
-
return true;
|
|
395
|
-
}
|
|
396
|
-
|
|
397
|
-
function checkDeps(add, dir) {
|
|
398
|
-
const raw = readText(dir, "package.json");
|
|
399
|
-
if (!raw) {
|
|
400
|
-
add("FAIL", "deps", "缺 package.json", "先 npm init 或补一份产品仓 package.json");
|
|
401
|
-
return;
|
|
402
|
-
}
|
|
403
|
-
let pj;
|
|
404
|
-
try { pj = JSON.parse(raw); } catch {
|
|
405
|
-
add("FAIL", "deps", "package.json 不是合法 JSON", "修好 JSON 后重跑");
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
const all = { ...(pj.dependencies ?? {}), ...(pj.devDependencies ?? {}) };
|
|
409
|
-
const missing = Object.values(PKG).filter((n) => !(n in all));
|
|
410
|
-
if (missing.length) add("FAIL", "deps", `未声明平台依赖:${missing.join("、")}`,
|
|
411
|
-
`npm i ${PKG.protocol}@^0.
|
|
412
|
-
else add("OK", "deps", "三个平台包依赖已声明");
|
|
413
|
-
|
|
414
|
-
try {
|
|
415
|
-
const req = createRequire(path.join(dir, "package.json"));
|
|
416
|
-
const file = req.resolve(`${PKG.server}/package.json`);
|
|
417
|
-
const v = JSON.parse(fs.readFileSync(file, "utf8")).version;
|
|
418
|
-
if (versionAtLeast(v, MIN_SERVER)) add("OK", "installed", `已安装 ${PKG.server} ${v}`);
|
|
419
|
-
else add("WARN", "installed", `已安装 ${v} < ${MIN_SERVER}(能力门禁与准出脚本检查从 ${MIN_SERVER} 起)`,
|
|
420
|
-
`npm i ${PKG.server}@^${MIN_SERVER} 刷新 lockfile`);
|
|
421
|
-
} catch {
|
|
422
|
-
add("WARN", "installed", "node_modules 未安装或平台包不可解析", "npm install 后重跑 check");
|
|
423
|
-
}
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
/** 从 manifest 文本里取 server.routes 的相对路径(不解析 YAML)。 */
|
|
427
|
-
function serverRoutesOf(text) {
|
|
428
|
-
let inServer = false;
|
|
429
|
-
for (const line of text.split(/\r?\n/)) {
|
|
430
|
-
if (/^server:\s*(#.*)?$/.test(line)) { inServer = true; continue; }
|
|
431
|
-
if (inServer && /^\S/.test(line)) inServer = false;
|
|
432
|
-
const m = inServer && line.match(/^\s+routes:\s*["']?([^"'\s#]+)["']?/);
|
|
433
|
-
if (m) return m[1];
|
|
434
|
-
}
|
|
435
|
-
return null;
|
|
436
|
-
}
|
|
437
|
-
|
|
438
|
-
function checkManifest(add, dir) {
|
|
439
|
-
const text = readText(dir, "manifest.yaml");
|
|
440
|
-
if (!text) {
|
|
441
|
-
add("FAIL", "manifest", "缺 manifest.yaml", "跑 agentchat-integrate init 生成");
|
|
442
|
-
return;
|
|
443
|
-
}
|
|
444
|
-
const problems = [];
|
|
445
|
-
if (!/^id:\s*\S+/m.test(text)) problems.push("缺 id");
|
|
446
|
-
if (!/^branding:\s*(#.*)?$/m.test(text) || !/^\s+title:\s*\S+/m.test(text)) problems.push("缺 branding.title");
|
|
447
|
-
if (!/^\s+systemPrompt:\s*\S+/m.test(text)) problems.push("缺 agent.systemPrompt");
|
|
448
|
-
// model 支持两种写法:块式(provider/id 各占一行)与内联花括号(夹具用的写法)。
|
|
449
|
-
const inlineModel = text.match(/^\s+model:\s*\{([^}]*)\}/m)?.[1] ?? "";
|
|
450
|
-
const hasProvider = /^\s+provider:\s*\S+/m.test(text) || /\bprovider:\s*\S+/.test(inlineModel);
|
|
451
|
-
const hasModelId = /^\s+id:\s*\S+/m.test(text) || /\bid:\s*\S+/.test(inlineModel);
|
|
452
|
-
if (!hasProvider) problems.push("缺 agent.model.provider");
|
|
453
|
-
if (!hasModelId) problems.push("缺 agent.model.id");
|
|
454
|
-
const rel = serverRoutesOf(text);
|
|
455
|
-
if (!rel) problems.push("缺 server.routes 声明");
|
|
456
|
-
else if (!rel.startsWith("./") || !rel.endsWith(".ts")) problems.push(`server.routes "${rel}" 必须 ./ 开头、.ts 结尾`);
|
|
457
|
-
else {
|
|
458
|
-
const resolved = path.resolve(dir, rel);
|
|
459
|
-
if (!resolved.startsWith(path.resolve(dir) + path.sep) || !fs.existsSync(resolved)) {
|
|
460
|
-
problems.push(`server.routes "${rel}" 必须存在且留在产品目录内`);
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
if (!fs.existsSync(path.join(dir, "prompt.md"))) problems.push("缺 prompt.md(loadProduct 会读 systemPrompt 指向的文件)");
|
|
464
|
-
if (problems.length) add("FAIL", "manifest", problems.join(";"), "对照 packages/server/src/manifest.ts 的硬校验补齐");
|
|
465
|
-
else add("OK", "manifest", "必填字段 + server.routes 三道闸 + prompt.md");
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
function checkRoutes(add, dir) {
|
|
469
|
-
const text = readText(dir, "server/routes.ts");
|
|
470
|
-
if (!text) { add("FAIL", "routes.ts", "缺 server/routes.ts", "跑 init 生成,或按 ProductRouteModule 形状补上"); return; }
|
|
471
|
-
const problems = [];
|
|
472
|
-
if (!/export\s+(?:async\s+)?function\s+createRoutes\b|export\s+const\s+createRoutes\b/.test(text)) {
|
|
473
|
-
problems.push("未导出 createRoutes()");
|
|
474
|
-
}
|
|
475
|
-
if (!/\broutes\s*:/.test(text)) problems.push("返回值缺 routes");
|
|
476
|
-
if (!/\badmin\s*:/.test(text)) problems.push("返回值缺 admin");
|
|
477
|
-
if (problems.length) add("FAIL", "routes.ts", problems.join(";"), "返回 { routes, admin, init? };落空要 return 让 core 接手");
|
|
478
|
-
else add("OK", "routes.ts", "createRoutes() → { routes, admin }");
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
function checkAppDef(add, dir) {
|
|
482
|
-
const entry = readText(dir, "web/entry.tsx");
|
|
483
|
-
const def = readText(dir, "web/app-def.tsx");
|
|
484
|
-
const problems = [];
|
|
485
|
-
if (!entry) problems.push("缺 web/entry.tsx");
|
|
486
|
-
if (!def) problems.push("缺 web/app-def.tsx");
|
|
487
|
-
if (entry) {
|
|
488
|
-
if (!/export\s*\{[^}]*\bappDef\b|export\s+const\s+appDef\b/.test(entry)) problems.push("entry 未导出 appDef");
|
|
489
|
-
if (!/export\s+(?:function|const)\s+App\b/.test(entry)) problems.push("entry 未导出 App");
|
|
490
|
-
}
|
|
491
|
-
if (def) {
|
|
492
|
-
for (const field of ["home", "chatRoute", "routes", "navItems", "page"]) {
|
|
493
|
-
// 两种合法写法都要认:冒号属性(`navItems: () => [...]`)与 ES 简写
|
|
494
|
-
// (`navItems,`,值来自模块作用域的 const)。只用冒号正则会把简写误判成
|
|
495
|
-
// 「缺字段」——真实产品就这么写,属于假红。
|
|
496
|
-
// 简写只认行首,避免把 `import { guard, navItems, ROUTES }` 当成已声明。
|
|
497
|
-
const declared =
|
|
498
|
-
new RegExp(`\\b${field}\\s*:`).test(def) || new RegExp(`^\\s*${field}\\s*(?:,|\\}|$)`, "m").test(def);
|
|
499
|
-
if (!declared) problems.push(`app-def 缺 ${field}`);
|
|
500
|
-
}
|
|
501
|
-
const block = def.match(/routes:\s*\{([\s\S]*?)\}/);
|
|
502
|
-
if (block) {
|
|
503
|
-
const keys = [...block[1].matchAll(/^\s*([A-Za-z0-9_-]+)\s*:/gm)].map((m) => m[1]);
|
|
504
|
-
const bad = keys.filter((k) => !/^[a-z]+$/.test(k));
|
|
505
|
-
if (bad.length) problems.push(`路由键只能小写字母:${bad.join("、")}`);
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
if (problems.length) add("FAIL", "app-def", problems.join(";"), "对照 apps/web/test/app-def-check.test.ts 的最小 def 样板");
|
|
509
|
-
else add("OK", "app-def", "appDef / App 导出、字段齐全、路由键小写");
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
function checkPlaceholders(add, dir) {
|
|
513
|
-
const rels = ["manifest.yaml", "server/routes.ts", "web/entry.tsx", "prompt.md"];
|
|
514
|
-
const hits = [];
|
|
515
|
-
for (const rel of rels) {
|
|
516
|
-
const text = readText(dir, rel);
|
|
517
|
-
for (const p of PLACEHOLDERS) if (text.includes(p)) hits.push(`${rel}: ${p}`);
|
|
518
|
-
}
|
|
519
|
-
if (hits.length) add("WARN", "placeholders", `还有 ${hits.length} 处占位符未替换`, `替换 ${[...new Set(PLACEHOLDERS)].join(" / ")} 后重跑`);
|
|
520
|
-
else add("OK", "placeholders", "无未替换占位符");
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
function walkFiles(dir, out = []) {
|
|
524
|
-
let entries;
|
|
525
|
-
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
|
|
526
|
-
for (const e of entries) {
|
|
527
|
-
if (e.name === "node_modules" || e.name === "dist" || e.name.startsWith(".")) continue;
|
|
528
|
-
const full = path.join(dir, e.name);
|
|
529
|
-
if (e.isDirectory()) walkFiles(full, out);
|
|
530
|
-
else out.push(full);
|
|
531
|
-
}
|
|
532
|
-
return out;
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
// ── 能力声明与对账 ─────────────────────────────────────────────────────────
|
|
536
|
-
|
|
537
|
-
/** 解析 manifest 的 capabilities 段。返回 null=缺失段;{ids}=已声明(可为空列表)。 */
|
|
538
|
-
function capabilitiesOf(text) {
|
|
539
|
-
const inline = text.match(/^capabilities:\s*\[([^\]]*)\]\s*(#.*)?$/m);
|
|
540
|
-
if (inline) {
|
|
541
|
-
const ids = inline[1].split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
|
|
542
|
-
return { ids };
|
|
543
|
-
}
|
|
544
|
-
const m = text.match(/^capabilities:\s*(#.*)?$/m);
|
|
545
|
-
if (!m) return null;
|
|
546
|
-
const ids = [];
|
|
547
|
-
for (const line of text.slice(m.index + m[0].length).split(/\r?\n/)) {
|
|
548
|
-
if (line.trim() === "" || /^\s*#/.test(line)) continue;
|
|
549
|
-
const item = line.match(/^\s+-\s+["']?([A-Za-z0-9_-]+)["']?\s*(#.*)?$/);
|
|
550
|
-
if (!item) break;
|
|
551
|
-
ids.push(item[1]);
|
|
552
|
-
}
|
|
553
|
-
return { ids };
|
|
554
|
-
}
|
|
555
|
-
|
|
556
|
-
/** manifest 结构化推导(确定性,零误报):字段声明即使用。返回触发中的能力 ID。 */
|
|
557
|
-
function deriveFromManifest(text) {
|
|
558
|
-
const hit = [];
|
|
559
|
-
const t = text;
|
|
560
|
-
if (serverRoutesOf(t)) hit.push("product-routes");
|
|
561
|
-
if (/^\s+inline:\s*["']?\./m.test(t)) hit.push("inline-tools");
|
|
562
|
-
if (/^mcp:/m.test(t)) hit.push("mcp-tools");
|
|
563
|
-
if (/^confirmTools:\s*\S/m.test(t)) hit.push("tool-confirm");
|
|
564
|
-
if (/^\s+personas:/m.test(t)) hit.push("personas");
|
|
565
|
-
if (/^\s+skills:\s*(#.*)?$|^\s+skills:\s*\[/m.test(t)) hit.push("skills");
|
|
566
|
-
if (/^\s+extensions:\s*(#.*)?$|^\s+extensions:\s*\[/m.test(t)) hit.push("extensions");
|
|
567
|
-
if (!/^\s+memory:\s*false\s*(#.*)?$/m.test(t)) hit.push("scoped-memory");
|
|
568
|
-
if (/^\s+tiers:/m.test(t)) hit.push("tiers");
|
|
569
|
-
if (/^billing:/m.test(t)) hit.push("billing");
|
|
570
|
-
if (/^\s+seedPolicies:/m.test(t)) hit.push("authz-seed");
|
|
571
|
-
if (/^quals:/m.test(t)) hit.push("quals");
|
|
572
|
-
return hit;
|
|
573
|
-
}
|
|
574
|
-
|
|
575
|
-
/** 粗剥 JS/TS 注释(启发式,够用于痕迹扫描;字符串里的 // 可能被误剥,但只影响 WARN 级判定)。 */
|
|
576
|
-
function stripComments(s) {
|
|
577
|
-
return s.replace(/\/\*[\s\S]*?\*\//g, " ").split("\n").map((l) => l.replace(/(^|[^:"'`])\/\/[^\r\n]*/, "$1")).join("\n");
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
/** 代码痕迹扫描(启发式,只给 WARN):manifest 无痕迹、代码里真调了端点/类型。 */
|
|
581
|
-
function scanCodeTraces(dir) {
|
|
582
|
-
const hit = new Set();
|
|
583
|
-
const srcFiles = walkFiles(dir).filter((f) => /\.(ts|tsx)$/.test(f));
|
|
584
|
-
const appdefFiles = srcFiles.filter((f) => /[\\/]app-def\.tsx$|[\\/]entry\.tsx$/.test(f));
|
|
585
|
-
for (const f of srcFiles) {
|
|
586
|
-
if (/[\\/](test|tests|e2e)[\\/]/.test(f)) continue; // 测试里的 fetch 不算产品用法
|
|
587
|
-
const text = stripComments(readText(path.dirname(f), path.basename(f)));
|
|
588
|
-
if (!text) continue;
|
|
589
|
-
if (/\bProductAdminRoute\b/.test(text)) hit.add("product-admin-routes");
|
|
590
|
-
if (/\/api\/(orders|recharge)\b/.test(text)) hit.add("billing");
|
|
591
|
-
if (/\/api\/feedback\b|\bcreateFeedback\b/.test(text)) hit.add("feedback");
|
|
592
|
-
if (/\/api\/(attachments|images)\b/.test(text)) hit.add("attachments");
|
|
593
|
-
if (/\bsendToChat\b/.test(text)) hit.add("appdef-extensions");
|
|
594
|
-
}
|
|
595
|
-
// AppDef 可选键只在注册表文件里判——guard/footer 是通用词,全仓扫必误报。
|
|
596
|
-
for (const f of appdefFiles) {
|
|
597
|
-
const text = stripComments(fs.readFileSync(f, "utf8"));
|
|
598
|
-
if (/\b(navAlias|cardRenderer|rewrites)\s*:/.test(text) || /^\s*(guard|footer|extras)\s*[:(]/m.test(text)) {
|
|
599
|
-
hit.add("appdef-extensions");
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
return [...hit];
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
function checkCapabilities(add, dir) {
|
|
606
|
-
const text = readText(dir, "manifest.yaml");
|
|
607
|
-
if (!text) return null; // manifest 缺失由 checkManifest 报 FAIL,这里不重复
|
|
608
|
-
const caps = capabilitiesOf(text);
|
|
609
|
-
if (caps === null) {
|
|
610
|
-
add("FAIL", "capabilities", "manifest 缺 capabilities 段(空列表 [] 也合法,缺失不合法)",
|
|
611
|
-
"声明本产品用到的平台能力;恒开能力不列;npx agentchat-integrate capabilities 查 ID 表");
|
|
612
|
-
return null;
|
|
613
|
-
}
|
|
614
|
-
const problems = [];
|
|
615
|
-
const unknown = caps.ids.filter((id) => !CAP_IDS.has(id));
|
|
616
|
-
const alwaysOn = caps.ids.filter((id) => ALWAYS_IDS.has(id));
|
|
617
|
-
const dup = caps.ids.filter((id, i) => caps.ids.indexOf(id) !== i);
|
|
618
|
-
if (unknown.length) problems.push(`注册表外的能力 ID:${unknown.join("、")}`);
|
|
619
|
-
if (alwaysOn.length) problems.push(`恒开能力不该写进声明:${alwaysOn.join("、")}`);
|
|
620
|
-
if (dup.length) problems.push(`重复声明:${[...new Set(dup)].join("、")}`);
|
|
621
|
-
|
|
622
|
-
const derived = deriveFromManifest(text);
|
|
623
|
-
const traced = scanCodeTraces(dir);
|
|
624
|
-
const undeclaredDerived = derived.filter((id) => !caps.ids.includes(id));
|
|
625
|
-
const undeclaredTraced = traced.filter((id) => !caps.ids.includes(id) && !undeclaredDerived.includes(id));
|
|
626
|
-
const unused = caps.ids.filter((id) => !derived.includes(id) && !traced.includes(id));
|
|
627
|
-
|
|
628
|
-
if (problems.length) {
|
|
629
|
-
add("FAIL", "capabilities", problems.join(";"), "对照 docs/specs/能力注册表.md 修正声明");
|
|
630
|
-
} else {
|
|
631
|
-
add("OK", "capabilities", `已声明 ${caps.ids.length} 项增量能力:${caps.ids.join("、") || "(无)"}`);
|
|
632
|
-
}
|
|
633
|
-
if (undeclaredDerived.length) {
|
|
634
|
-
add("FAIL", "capabilities-derived",
|
|
635
|
-
`manifest 已触发但未声明:${undeclaredDerived.join("、")}`,
|
|
636
|
-
`加进 capabilities(触发条件见注册表),或删掉对应字段声明`);
|
|
637
|
-
} else if (undeclaredTraced.length) {
|
|
638
|
-
add("WARN", "capabilities-derived",
|
|
639
|
-
`代码痕迹检出但未声明(启发式,可能误报):${undeclaredTraced.join("、")}`,
|
|
640
|
-
"确实用了就声明;没用到的写法删掉;确认误报可忽略本条");
|
|
641
|
-
} else {
|
|
642
|
-
add("OK", "capabilities-derived", `双向对账干净(推导命中 ${derived.length}、痕迹命中 ${traced.length})`);
|
|
643
|
-
}
|
|
644
|
-
if (unused.length) {
|
|
645
|
-
add("WARN", "capabilities-unused", `声明了但 manifest/代码都没检出:${unused.join("、")}`,
|
|
646
|
-
"要么补上用法,要么从 capabilities 删掉");
|
|
647
|
-
}
|
|
648
|
-
return { declared: caps.ids, derived, traced, undeclaredDerived, undeclaredTraced, unused };
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
// ── 准出四脚本:存在 + 真跑 ────────────────────────────────────────────────
|
|
652
|
-
|
|
653
|
-
const TEST_SCRIPTS = ["test:agentchat", "test:agentchat:unit", "test:agentchat:api", "test:agentchat:ui"];
|
|
654
|
-
|
|
655
|
-
function runNpmScript(dir, script, timeoutSec) {
|
|
656
|
-
const r = spawnSync("npm", ["run", script], {
|
|
657
|
-
cwd: dir, encoding: "utf8", timeout: timeoutSec * 1000,
|
|
658
|
-
shell: process.platform === "win32", // Windows 上 npm 是 .cmd,必须走 shell
|
|
659
|
-
});
|
|
660
|
-
if (r.error) {
|
|
661
|
-
const kind = r.error.code === "ETIMEDOUT" ? "timeout" : r.error.code === "ENOENT" ? "no-npm" : "spawn-error";
|
|
662
|
-
return { kind, exitCode: null, output: String(r.error.message ?? "") };
|
|
663
|
-
}
|
|
664
|
-
return {
|
|
665
|
-
kind: r.status === 0 ? "ok" : "fail",
|
|
666
|
-
exitCode: r.status,
|
|
667
|
-
output: `${r.stdout ?? ""}\n${r.stderr ?? ""}`.trim().slice(-1200),
|
|
668
|
-
};
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
function checkTestScripts(add, dir, opts) {
|
|
672
|
-
let scripts = {};
|
|
673
|
-
try { scripts = JSON.parse(readText(dir, "package.json")).scripts ?? {}; } catch { return; }
|
|
674
|
-
const missing = TEST_SCRIPTS.filter((s) => !scripts[s] || !String(scripts[s]).trim());
|
|
675
|
-
if (missing.length) {
|
|
676
|
-
add("FAIL", "test-scripts", `缺准出脚本:${missing.join("、")}`,
|
|
677
|
-
"按 agentchat-onboarding Skill 生成 UT/接口/UI 三组测试后写入这四个脚本(内容由产品按能力注册表自行编写,平台不预制)");
|
|
678
|
-
return;
|
|
679
|
-
}
|
|
680
|
-
const agg = String(scripts["test:agentchat"]);
|
|
681
|
-
const subs = ["test:agentchat:unit", "test:agentchat:api", "test:agentchat:ui"];
|
|
682
|
-
const notAggregated = subs.filter((s) => !agg.includes(s));
|
|
683
|
-
if (notAggregated.length) {
|
|
684
|
-
add("WARN", "test-scripts", `test:agentchat 未引用:${notAggregated.join("、")}`,
|
|
685
|
-
"汇总脚本应跑全三个子脚本,否则 CI/门禁会漏层");
|
|
686
|
-
} else {
|
|
687
|
-
add("OK", "test-scripts", "准出四脚本齐备且汇总完整");
|
|
688
|
-
}
|
|
689
|
-
if (opts.noRun) {
|
|
690
|
-
add("WARN", "test-run", "--no-run:本次未执行测试脚本", "CI 与验收必须真跑,本地提速才用 --no-run");
|
|
691
|
-
return;
|
|
692
|
-
}
|
|
693
|
-
const runs = [];
|
|
694
|
-
let failed = false;
|
|
695
|
-
for (const s of subs) {
|
|
696
|
-
const r = runNpmScript(dir, s, opts.timeout);
|
|
697
|
-
runs.push({ script: s, ...r });
|
|
698
|
-
if (r.kind === "timeout") {
|
|
699
|
-
add("FAIL", "test-run", `${s} 超时(>${opts.timeout}s)`, `调 --timeout 或拆分用例;报告尾部:${r.output.slice(-300)}`);
|
|
700
|
-
failed = true;
|
|
701
|
-
} else if (r.kind === "no-npm") {
|
|
702
|
-
add("FAIL", "test-run", "npm 不可用,无法执行测试脚本", "确认 PATH 里有 npm");
|
|
703
|
-
failed = true;
|
|
704
|
-
} else if (r.kind !== "ok") {
|
|
705
|
-
const hint = /Cannot find package 'tsx'/.test(r.output) ? "先 npm i -D tsx;" :
|
|
706
|
-
/Cannot find package '@njuptlzf\//.test(r.output) ? "先 npm install;" : "";
|
|
707
|
-
add("FAIL", "test-run", `${s} 未通过(exit ${r.exitCode})`, `${hint}报告尾部:${r.output.slice(-300)}`);
|
|
708
|
-
failed = true;
|
|
709
|
-
}
|
|
710
|
-
}
|
|
711
|
-
if (!failed) add("OK", "test-run", `三组准出脚本真跑通过(unit/api/ui @ ${opts.timeout}s 上限)`);
|
|
712
|
-
return runs;
|
|
713
|
-
}
|
|
714
|
-
|
|
715
|
-
function checkTooling(add, dir) {
|
|
716
|
-
const wf = path.join(dir, ".github", "workflows");
|
|
717
|
-
const wfFiles = fs.existsSync(wf) ? fs.readdirSync(wf).filter((f) => /\.ya?ml$/.test(f)) : [];
|
|
718
|
-
if (wfFiles.length === 0) {
|
|
719
|
-
add("WARN", "ci", "未发现 .github/workflows/*.yml", "产品仓自己加 CI,至少跑 typecheck / test / build");
|
|
720
|
-
} else if (!wfFiles.some((f) => /test:agentchat/.test(fs.readFileSync(path.join(wf, f), "utf8")))) {
|
|
721
|
-
add("WARN", "ci", "CI 存在但未引用 test:agentchat", "把 `npm run test:agentchat` 加进产品仓 CI 的门禁步骤");
|
|
722
|
-
} else {
|
|
723
|
-
add("OK", "ci", "存在 CI 工作流且引用 test:agentchat");
|
|
724
|
-
}
|
|
725
|
-
|
|
726
|
-
const vite = ["vite.config.ts", "vite.config.mts", "vite.config.js", "web/vite.config.ts"]
|
|
727
|
-
.map((r) => readText(dir, r)).join("\n");
|
|
728
|
-
if (/validateAppDef|appDefGuard/.test(vite)) add("OK", "appdef-guard", "vite.config 已接构建期 AppDef 守卫");
|
|
729
|
-
else add("INFO", "appdef-guard", "未检测到 validateAppDef / appDefGuard",
|
|
730
|
-
"在产品 vite.config.ts 复用 @njuptlzf/agent-chat-web/app-def-check;20 条动态契约由它把关,CLI 不复制口径");
|
|
731
|
-
}
|
|
732
|
-
|
|
733
|
-
function checkDeep(add, dir) {
|
|
734
|
-
const code = `
|
|
735
|
-
import { pathToFileURL } from "node:url";
|
|
736
|
-
import { sampleHostContexts, validateAppDef } from "${PKG.web}/app-def-check";
|
|
737
|
-
const { appDef } = await import(pathToFileURL(${JSON.stringify(path.join(dir, "web/app-def.tsx"))}).href);
|
|
738
|
-
for (const { name, ctx } of sampleHostContexts()) {
|
|
739
|
-
const problems = validateAppDef(appDef, ctx);
|
|
740
|
-
if (problems.length) {
|
|
741
|
-
console.error(name + ": " + problems.map((p) => p.where + ": " + p.message).join("; "));
|
|
742
|
-
process.exit(1);
|
|
743
|
-
}
|
|
744
|
-
}
|
|
745
|
-
console.log("deep ok");
|
|
746
|
-
`;
|
|
747
|
-
const r = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", code], {
|
|
748
|
-
cwd: dir, encoding: "utf8", timeout: 60_000,
|
|
749
|
-
});
|
|
750
|
-
if (r.status === 0) add("OK", "deep", "真实 validateAppDef 五上下文校验通过");
|
|
751
|
-
else add("INFO", "deep", "deep 校验未完成(缺 tsx / 依赖 / AppDef 不可用)",
|
|
752
|
-
`改由产品 npm run build 的 appDefGuard 把关;详情:${String(r.stderr ?? r.error ?? "").trim().slice(0, 300)}`);
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
function check(opts, dir) {
|
|
756
|
-
const results = [];
|
|
757
|
-
const add = (level, code, message, suggestion) => {
|
|
758
|
-
results.push({ level, code, message, ...(suggestion ? { suggestion } : {}) });
|
|
759
|
-
};
|
|
760
|
-
checkDeps(add, dir);
|
|
761
|
-
checkManifest(add, dir);
|
|
762
|
-
checkRoutes(add, dir);
|
|
763
|
-
checkAppDef(add, dir);
|
|
764
|
-
checkPlaceholders(add, dir);
|
|
765
|
-
const caps = checkCapabilities(add, dir);
|
|
766
|
-
const runs = checkTestScripts(add, dir, opts);
|
|
767
|
-
checkTooling(add, dir);
|
|
768
|
-
if (opts.deep) checkDeep(add, dir);
|
|
769
|
-
|
|
770
|
-
const failures = results.filter((r) => r.level === "FAIL");
|
|
771
|
-
const warnings = results.filter((r) => r.level === "WARN");
|
|
772
|
-
const suggestions = results.filter((r) => r.suggestion).map((r) => `[${r.code}] ${r.suggestion}`);
|
|
773
|
-
const report = {
|
|
774
|
-
ok: failures.length === 0,
|
|
775
|
-
dir,
|
|
776
|
-
failures: failures.map((r) => ({ code: r.code, message: r.message })),
|
|
777
|
-
warnings: warnings.map((r) => ({ code: r.code, message: r.message })),
|
|
778
|
-
suggestions,
|
|
779
|
-
results,
|
|
780
|
-
capabilities: caps && {
|
|
781
|
-
declared: caps.declared,
|
|
782
|
-
detected: [...new Set([...caps.derived, ...caps.traced])],
|
|
783
|
-
undeclaredManifest: caps.undeclaredDerived,
|
|
784
|
-
undeclaredCode: caps.undeclaredTraced,
|
|
785
|
-
unused: caps.unused,
|
|
786
|
-
alwaysRequired: CAP_ALWAYS.map((c) => c.id),
|
|
787
|
-
},
|
|
788
|
-
runs: runs ?? null,
|
|
789
|
-
};
|
|
790
|
-
if (opts.json) {
|
|
791
|
-
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
792
|
-
} else {
|
|
793
|
-
process.stdout.write(`agentchat-integrate check — ${dir}\n`);
|
|
794
|
-
for (const r of results) {
|
|
795
|
-
process.stdout.write(`[${r.level.padEnd(4)}] ${r.code.padEnd(14)} ${r.message}\n`);
|
|
796
|
-
}
|
|
797
|
-
process.stdout.write(
|
|
798
|
-
`---\n结论:违规 ${failures.length} 条;建议 ${warnings.length} 条;` +
|
|
799
|
-
`退出码 ${failures.length ? 1 : 0}${failures.length ? "" : "(建议不阻断)"}\n`,
|
|
800
|
-
);
|
|
801
|
-
if (caps) {
|
|
802
|
-
process.stdout.write(`恒开必测(不写声明):${CAP_ALWAYS.map((c) => `${c.id}(${c.name})`).join("、")}\n`);
|
|
803
|
-
}
|
|
804
|
-
if (suggestions.length) process.stdout.write(`建议:\n${suggestions.map((s) => ` - ${s}`).join("\n")}\n`);
|
|
805
|
-
}
|
|
806
|
-
return failures.length ? 1 : 0;
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
// ── capabilities 子命令 ────────────────────────────────────────────────────
|
|
810
|
-
|
|
811
|
-
function capabilitiesCmd(opts) {
|
|
812
|
-
if (opts.json) {
|
|
813
|
-
process.stdout.write(`${JSON.stringify({ always: CAP_ALWAYS, optIn: CAP_OPT_IN }, null, 2)}\n`);
|
|
814
|
-
return 0;
|
|
815
|
-
}
|
|
816
|
-
process.stdout.write("恒开能力(任何产品都在用,**不写进 capabilities**,准出必测):\n");
|
|
817
|
-
for (const c of CAP_ALWAYS) process.stdout.write(` ${c.id.padEnd(22)} ${c.name}\n`);
|
|
818
|
-
process.stdout.write("\n声明式能力(用了必须写进 manifest capabilities):\n");
|
|
819
|
-
for (const c of CAP_OPT_IN) process.stdout.write(` ${c.id.padEnd(22)} ${c.name} 触发:${c.trigger}\n`);
|
|
820
|
-
process.stdout.write("\n准出要求(UT/接口/UI 各层的断言方向)见平台仓 docs/specs/能力注册表.md。\n");
|
|
821
|
-
return 0;
|
|
822
|
-
}
|
|
823
|
-
|
|
824
|
-
// ── 入口 ──────────────────────────────────────────────────────────────────
|
|
825
|
-
|
|
826
|
-
function main() {
|
|
827
|
-
const raw = process.argv.slice(2);
|
|
828
|
-
// 全局开关优先于子命令:没有子命令时也要能看帮助/版本。
|
|
829
|
-
if (raw.includes("--help") || raw.includes("-h")) { process.stdout.write(`${HELP}\n`); return 0; }
|
|
830
|
-
if (raw.includes("--version") || raw.includes("-V")) { process.stdout.write(`${CLI_VERSION}\n`); return 0; }
|
|
831
|
-
const parsed = parseArgs(raw);
|
|
832
|
-
if (parsed.error) usageError(parsed.error);
|
|
833
|
-
const opts = parsed.opts;
|
|
834
|
-
if (opts.help) { process.stdout.write(`${HELP}\n`); return 0; }
|
|
835
|
-
if (opts.version) { process.stdout.write(`${CLI_VERSION}\n`); return 0; }
|
|
836
|
-
if (opts.cmd === "capabilities") return capabilitiesCmd(opts);
|
|
837
|
-
if (opts.cmd !== "init" && opts.cmd !== "check") {
|
|
838
|
-
usageError(opts.cmd ? `未知子命令:${opts.cmd}` : "缺子命令(init / check / capabilities)");
|
|
839
|
-
}
|
|
840
|
-
const dir = path.resolve(opts.dir ?? process.cwd());
|
|
841
|
-
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) {
|
|
842
|
-
usageError(`不是目录:${dir}`);
|
|
843
|
-
}
|
|
844
|
-
if (opts.cmd === "check" && !fs.existsSync(dir)) {
|
|
845
|
-
usageError(`目录不存在:${dir}`);
|
|
846
|
-
}
|
|
847
|
-
if (opts.cmd === "init" && !fs.existsSync(dir)) {
|
|
848
|
-
fs.mkdirSync(dir, { recursive: true });
|
|
849
|
-
}
|
|
850
|
-
return opts.cmd === "init" ? init(opts, dir) : check(opts, dir);
|
|
851
|
-
}
|
|
852
|
-
|
|
853
|
-
process.exitCode = main();
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* agentchat-integrate —— 「一句话对接 agentChat」的机械入口。
|
|
4
|
+
*
|
|
5
|
+
* 设计约束(改动前先读):
|
|
6
|
+
* ① 零第三方依赖:只用 Node 内置模块,不 import `yaml`,不 import 平台 `.ts` 源码。
|
|
7
|
+
* 装进产品仓 node_modules 后仍能独立运行;模板与能力注册表全部内嵌。
|
|
8
|
+
* ② 产品无关:脚本正文与生成物不含任何具体产品名 / 私有词 / 业务断言。
|
|
9
|
+
* ③ 平台守两类门禁:契约形状(FAIL)+ 能力声明与准出(capabilities / 四脚本 / 真跑)。
|
|
10
|
+
* 测试内容**不由平台预制**——每个产品用法不同,用例由产品(或其 AI)按能力注册表
|
|
11
|
+
* 现场生成;check 只验「声明完整、脚本齐、跑绿」,不解析测试写了什么断言。
|
|
12
|
+
* ④ 完整口径不复制:AppDef 的 20 条动态契约由产品 vite.config.ts 的 appDefGuard
|
|
13
|
+
* (复用 @njuptlzf/agent-chat-web/app-def-check)把关,这里只查声明存在性;
|
|
14
|
+
* 能力的准出要求全文以 docs/specs/能力注册表.md 为人读权威,CLI 内嵌机读最小集
|
|
15
|
+
* (id/中文名/触发声明),单测钉两侧 ID 集合一致。
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { createRequire } from "node:module";
|
|
20
|
+
import { spawnSync } from "node:child_process";
|
|
21
|
+
import process from "node:process";
|
|
22
|
+
|
|
23
|
+
const CLI_VERSION = "0.4.1";
|
|
24
|
+
const MIN_SERVER = "0.2.0";
|
|
25
|
+
const PKG = {
|
|
26
|
+
protocol: "@njuptlzf/agent-chat-protocol",
|
|
27
|
+
server: "@njuptlzf/agent-chat-server",
|
|
28
|
+
web: "@njuptlzf/agent-chat-web",
|
|
29
|
+
};
|
|
30
|
+
const ID_RE = /^[a-z0-9][a-z0-9-]*$/;
|
|
31
|
+
const PLACEHOLDERS = ["<PROVIDER>", "<MODEL_ID>", "<产品标题>"];
|
|
32
|
+
const VALUE_FLAGS = new Set(["--dir", "--id", "--title", "--provider", "--model", "--timeout"]);
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 能力注册表(机读最小集;人读权威 = docs/specs/能力注册表.md,一致性由 CLI 单测钉住)。
|
|
36
|
+
* always = 恒开能力,任何产品都在用,**不写进 capabilities**(写了判 FAIL);
|
|
37
|
+
* optIn = 声明式能力,用了必须声明;trigger 为人读触发声明摘要。
|
|
38
|
+
*/
|
|
39
|
+
const CAP_ALWAYS = [
|
|
40
|
+
{ id: "chat", name: "对话与流式事件、会话历史" },
|
|
41
|
+
{ id: "auth-quota", name: "鉴权与日额度" },
|
|
42
|
+
{ id: "branding", name: "品牌与人格文案下发" },
|
|
43
|
+
{ id: "audit", name: "审计哈希链" },
|
|
44
|
+
{ id: "admin-plane", name: "管理面配置与用量报表" },
|
|
45
|
+
];
|
|
46
|
+
const CAP_OPT_IN = [
|
|
47
|
+
{ id: "product-routes", name: "产品业务路由", trigger: "manifest `server.routes`" },
|
|
48
|
+
{ id: "product-admin-routes", name: "产品管理面路由", trigger: "代码出现 ProductAdminRoute" },
|
|
49
|
+
{ id: "inline-tools", name: "内联工具", trigger: "manifest `tools.inline`" },
|
|
50
|
+
{ id: "mcp-tools", name: "MCP 工具", trigger: "manifest `mcp`" },
|
|
51
|
+
{ id: "tool-confirm", name: "工具确认", trigger: "manifest `confirmTools`" },
|
|
52
|
+
{ id: "personas", name: "多人格", trigger: "manifest `agent.personas`" },
|
|
53
|
+
{ id: "skills", name: "技能目录", trigger: "manifest `agent.skills`" },
|
|
54
|
+
{ id: "extensions", name: "pi 扩展加载", trigger: "manifest `agent.extensions`" },
|
|
55
|
+
{ id: "scoped-memory", name: "作用域记忆", trigger: "manifest 未写 `agent.memory: false` 即默认开启" },
|
|
56
|
+
{ id: "tiers", name: "质量档位", trigger: "manifest `agent.tiers`" },
|
|
57
|
+
{ id: "billing", name: "计费 / 订单 / 套餐 / 充值", trigger: "manifest `billing` 或代码调 /api/orders、/api/recharge" },
|
|
58
|
+
{ id: "authz-seed", name: "权限种子策略", trigger: "manifest `agent.authz.seedPolicies`" },
|
|
59
|
+
{ id: "quals", name: "多资格内容组织", trigger: "manifest `quals`" },
|
|
60
|
+
{ id: "appdef-extensions", name: "前端扩展点", trigger: "app-def/entry 用 navAlias/cardRenderer/guard/footer/extras 或代码调 sendToChat" },
|
|
61
|
+
{ id: "feedback", name: "反馈通道", trigger: "代码调 /api/feedback 或 ctx.createFeedback" },
|
|
62
|
+
{ id: "attachments", name: "附件图片", trigger: "代码调 /api/attachments、/api/images" },
|
|
63
|
+
];
|
|
64
|
+
const CAP_IDS = new Set(CAP_OPT_IN.map((c) => c.id));
|
|
65
|
+
const ALWAYS_IDS = new Set(CAP_ALWAYS.map((c) => c.id));
|
|
66
|
+
|
|
67
|
+
const HELP = `agentchat-integrate ${CLI_VERSION} — AI 产品接入 agentChat 的机械入口
|
|
68
|
+
|
|
69
|
+
用法(在产品仓根目录执行):
|
|
70
|
+
npx agentchat-integrate init [选项] 生成产品侧骨架(不生成测试——测试按能力声明现场写)
|
|
71
|
+
npx agentchat-integrate check [选项] 接入体检:契约形状 + 能力声明对账 + 四脚本真跑
|
|
72
|
+
npx agentchat-integrate capabilities [--json] 打印能力注册表(机读最小集)
|
|
73
|
+
|
|
74
|
+
选项:
|
|
75
|
+
--dir <path> 产品仓根目录,默认当前工作目录
|
|
76
|
+
--id <id> 产品 id(小写字母/数字/连字符),默认取 package.json 的 name 或目录名
|
|
77
|
+
--title <text> branding.title,默认 "<id> 助手"
|
|
78
|
+
--provider <p> agent.model.provider,默认 <PROVIDER>(待填)
|
|
79
|
+
--model <m> agent.model.id,默认 <MODEL_ID>(待填)
|
|
80
|
+
--force 覆盖已存在的生成文件(package.json 永远不覆盖)
|
|
81
|
+
--dry-run 只打印将要生成的文件,不落盘
|
|
82
|
+
--json check / capabilities 输出结构化 JSON
|
|
83
|
+
--deep check 额外用产品仓的 tsx 跑一次真实 AppDef 校验(失败只记 INFO)
|
|
84
|
+
--no-run check 不执行 test:agentchat:* 脚本(只验存在;本地提速用,CI 别用)
|
|
85
|
+
--timeout <秒> 每个测试脚本的执行超时,默认 600
|
|
86
|
+
--help / --version
|
|
87
|
+
|
|
88
|
+
退出码:0 = 无违规(WARN/INFO 允许);1 = 有违规(含能力未声明、缺脚本、脚本跑挂);
|
|
89
|
+
2 = 参数错误 / 平台仓误跑护栏
|
|
90
|
+
|
|
91
|
+
门禁口径:用了哪些平台能力必须在 manifest 的 capabilities: 显式声明;声明的能力要由
|
|
92
|
+
test:agentchat:unit / :api / :ui 三个脚本承载并跑绿(内容由产品按 docs/specs/能力注册表.md
|
|
93
|
+
的准出要求自行编写,平台不预制、不代写业务断言)。init 后直接 check 会红是预期——测试还没写。
|
|
94
|
+
规范见平台仓 docs/specs/产品接入与测试规范.md;AI 执行流程见 agentchat-onboarding Skill。`;
|
|
95
|
+
|
|
96
|
+
// ── 参数 ──────────────────────────────────────────────────────────────────
|
|
97
|
+
|
|
98
|
+
function parseArgs(argv) {
|
|
99
|
+
const opts = {
|
|
100
|
+
cmd: argv[0] ?? "",
|
|
101
|
+
dir: null,
|
|
102
|
+
id: null,
|
|
103
|
+
title: null,
|
|
104
|
+
provider: null,
|
|
105
|
+
model: null,
|
|
106
|
+
force: false,
|
|
107
|
+
dryRun: false,
|
|
108
|
+
json: false,
|
|
109
|
+
deep: false,
|
|
110
|
+
noRun: false,
|
|
111
|
+
timeout: 600,
|
|
112
|
+
help: false,
|
|
113
|
+
version: false,
|
|
114
|
+
};
|
|
115
|
+
const keyOf = {
|
|
116
|
+
"--dir": "dir", "--id": "id", "--title": "title",
|
|
117
|
+
"--provider": "provider", "--model": "model",
|
|
118
|
+
};
|
|
119
|
+
for (let i = 1; i < argv.length; i++) {
|
|
120
|
+
const a = argv[i];
|
|
121
|
+
if (a === "--help" || a === "-h") opts.help = true;
|
|
122
|
+
else if (a === "--version" || a === "-V") opts.version = true;
|
|
123
|
+
else if (a === "--force") opts.force = true;
|
|
124
|
+
else if (a === "--dry-run") opts.dryRun = true;
|
|
125
|
+
else if (a === "--json") opts.json = true;
|
|
126
|
+
else if (a === "--deep") opts.deep = true;
|
|
127
|
+
else if (a === "--no-run") opts.noRun = true;
|
|
128
|
+
else if (a === "--timeout") {
|
|
129
|
+
const value = argv[++i];
|
|
130
|
+
const n = Number(value);
|
|
131
|
+
if (value === undefined || !Number.isFinite(n) || n <= 0) return { error: `--timeout 要正整数秒,收到 "${value}"` };
|
|
132
|
+
opts.timeout = n;
|
|
133
|
+
}
|
|
134
|
+
else if (VALUE_FLAGS.has(a)) {
|
|
135
|
+
const value = argv[++i];
|
|
136
|
+
if (value === undefined || value.startsWith("--")) return { error: `${a} 缺少取值` };
|
|
137
|
+
opts[keyOf[a]] = value;
|
|
138
|
+
} else return { error: `未知参数:${a}` };
|
|
139
|
+
}
|
|
140
|
+
return { opts };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function usageError(msg) {
|
|
144
|
+
process.stderr.write(`agentchat-integrate: ${msg}\n运行 --help 查看用法。\n`);
|
|
145
|
+
process.exit(2);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 防误跑:平台仓根目录不允许 init(否则骨架会污染平台仓)。 */
|
|
149
|
+
function looksLikePlatformRepo(dir) {
|
|
150
|
+
const pj = path.join(dir, "package.json");
|
|
151
|
+
if (!fs.existsSync(pj)) return false;
|
|
152
|
+
try {
|
|
153
|
+
const name = JSON.parse(fs.readFileSync(pj, "utf8")).name;
|
|
154
|
+
return name === "agent-chat" && fs.existsSync(path.join(dir, "packages/server/src/main.ts"));
|
|
155
|
+
} catch {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function readText(dir, rel) {
|
|
161
|
+
const file = path.join(dir, rel);
|
|
162
|
+
try { return fs.readFileSync(file, "utf8"); } catch { return ""; }
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function defaultId(dir) {
|
|
166
|
+
const pj = readText(dir, "package.json");
|
|
167
|
+
let name = "";
|
|
168
|
+
try { name = JSON.parse(pj).name ?? ""; } catch { /* 目录名兜底 */ }
|
|
169
|
+
name = String(name).split("/").pop() || path.basename(dir);
|
|
170
|
+
return name.replace(/[^a-z0-9-]/gi, "-").replace(/^-+|-+$/g, "").toLowerCase() || path.basename(dir);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ── init 模板(全部产品无关,形状对齐平台真实契约) ────────────────────────
|
|
174
|
+
|
|
175
|
+
function manifestTemplate(o) {
|
|
176
|
+
return `# 由 agentchat-integrate init 生成。按产品事实补全其余字段。
|
|
177
|
+
# 契约:id / branding.title / agent.systemPrompt / agent.model.{provider,id} 必填;
|
|
178
|
+
# server.routes 必须 ./ 开头、.ts 结尾、文件留在产品目录内。
|
|
179
|
+
id: ${o.id}
|
|
180
|
+
|
|
181
|
+
branding:
|
|
182
|
+
title: ${JSON.stringify(o.title)}
|
|
183
|
+
|
|
184
|
+
# 准出声明:本产品实际用到的平台能力,用了就必须写在这里(恒开能力 chat/auth-quota/
|
|
185
|
+
# branding/audit/admin-plane 不列——列了 check 判 FAIL)。下面两份是按当前骨架推导的
|
|
186
|
+
# 初始值:声明了 server.routes ⇒ product-routes;未关 agent.memory ⇒ scoped-memory。
|
|
187
|
+
# 每加一项 manifest 字段 / 代码用法,同步增删这里。ID 表与准出要求:
|
|
188
|
+
# 平台仓 docs/specs/能力注册表.md(npx agentchat-integrate capabilities 可查)。
|
|
189
|
+
capabilities:
|
|
190
|
+
- product-routes
|
|
191
|
+
- scoped-memory
|
|
192
|
+
|
|
193
|
+
agent:
|
|
194
|
+
systemPrompt: ./prompt.md
|
|
195
|
+
model:
|
|
196
|
+
provider: ${o.provider}
|
|
197
|
+
id: ${o.model}
|
|
198
|
+
defaultPersona: default
|
|
199
|
+
|
|
200
|
+
server:
|
|
201
|
+
routes: ./server/routes.ts
|
|
202
|
+
`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function promptTemplate(o) {
|
|
206
|
+
return `# 系统提示词(产品事实,由产品仓维护)
|
|
207
|
+
|
|
208
|
+
你是 ${o.title} 的 AI 助手。按产品自己的口径回答;平台不解释业务语义。
|
|
209
|
+
`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function packageTemplate(o) {
|
|
213
|
+
return `${JSON.stringify({
|
|
214
|
+
name: o.id,
|
|
215
|
+
private: true,
|
|
216
|
+
type: "module",
|
|
217
|
+
dependencies: {
|
|
218
|
+
[PKG.protocol]: "^0.4.0",
|
|
219
|
+
[PKG.server]: "^0.4.0",
|
|
220
|
+
[PKG.web]: "^0.4.0",
|
|
221
|
+
},
|
|
222
|
+
devDependencies: {
|
|
223
|
+
tsx: "^4.20.0",
|
|
224
|
+
typescript: "^5.9.0",
|
|
225
|
+
},
|
|
226
|
+
}, null, 2)}\n`;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function routesTemplate(o) {
|
|
230
|
+
return `/**
|
|
231
|
+
* 产品业务路由(由 agentchat-integrate init 生成)。
|
|
232
|
+
*
|
|
233
|
+
* 接缝契约:
|
|
234
|
+
* - manifest 声明 server.routes: "./server/routes.ts";
|
|
235
|
+
* - 本模块导出 createRoutes(),返回 { routes, admin, init? };
|
|
236
|
+
* - 命中就写响应并结束,没命中就 return,core 继续走自己的链(统一 404);
|
|
237
|
+
* - init 抛错 = 启动失败(fail-closed),不是首个请求才 500。
|
|
238
|
+
* core 只认形状,不认任何具体路径——下面的路径全是产品事实,请替换。
|
|
239
|
+
*/
|
|
240
|
+
import { sendJson, type ProductRoute, type ServerDeps } from "${PKG.server}";
|
|
241
|
+
|
|
242
|
+
const itemsRoute: ProductRoute = async ({ req, res, url }) => {
|
|
243
|
+
if (req.method !== "GET" || url.pathname !== "/api/${o.id}/items") return;
|
|
244
|
+
sendJson(res, 200, { items: [] });
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
/*
|
|
248
|
+
* 管理面路由样板:真的用它时(import ProductAdminRoute 并取消下面的注释),
|
|
249
|
+
* 要在 manifest 的 capabilities 里声明 product-admin-routes,并给 group 配一条
|
|
250
|
+
* {sub:"admin",obj:"admin-api",act:<group>} 种子(authz-seed 也要声明)。
|
|
251
|
+
*
|
|
252
|
+
* import type { ProductAdminRoute } from "${PKG.server}";
|
|
253
|
+
* const adminRoute: ProductAdminRoute = {
|
|
254
|
+
* match: (pathname) => pathname === "/api/admin/${o.id}/stats",
|
|
255
|
+
* group: "${o.id}-admin",
|
|
256
|
+
* handle: async (_deps: ServerDeps, _req, res) => { sendJson(res, 200, { ok: true }); },
|
|
257
|
+
* };
|
|
258
|
+
*/
|
|
259
|
+
|
|
260
|
+
export function createRoutes() {
|
|
261
|
+
return {
|
|
262
|
+
routes: [itemsRoute],
|
|
263
|
+
admin: [],
|
|
264
|
+
// init(_deps: ServerDeps) { /* 启动期装配自己的存储/索引;抛错 = 启动失败 */ },
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
`;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function appDefTemplate() {
|
|
271
|
+
return `/**
|
|
272
|
+
* 导航注册表(由 agentchat-integrate init 生成)。
|
|
273
|
+
* 动态 20 条结构契约由产品 vite.config.ts 的 appDefGuard 把关
|
|
274
|
+
* (复用 @njuptlzf/agent-chat-web/app-def-check 的 validateAppDef / sampleHostContexts)。
|
|
275
|
+
* 路由键只能是小写字母:core 用 /^#\\/([a-z]+)/ 从 hash 取键。
|
|
276
|
+
* 这里故意不放 JSX,便于 node --import tsx 直接 import 做契约自检。
|
|
277
|
+
*/
|
|
278
|
+
import type { AppDef } from "${PKG.web}";
|
|
279
|
+
|
|
280
|
+
export const appDef: AppDef = {
|
|
281
|
+
home: "home",
|
|
282
|
+
chatRoute: "chat",
|
|
283
|
+
routes: {
|
|
284
|
+
chat: "助手",
|
|
285
|
+
home: "首页",
|
|
286
|
+
records: "我的记录",
|
|
287
|
+
},
|
|
288
|
+
navItems: () => [
|
|
289
|
+
{ route: "chat", label: "助手" },
|
|
290
|
+
{ route: "home", label: "首页" },
|
|
291
|
+
{ route: "records", label: "我的记录" },
|
|
292
|
+
],
|
|
293
|
+
page: () => null,
|
|
294
|
+
};
|
|
295
|
+
`;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function entryTemplate() {
|
|
299
|
+
return `/**
|
|
300
|
+
* 产品组合根(由 agentchat-integrate init 生成)。
|
|
301
|
+
* 必须导出 appDef(给 vite.config.ts 的构建期守卫)与 App。
|
|
302
|
+
*/
|
|
303
|
+
import { AgentApp } from "${PKG.web}";
|
|
304
|
+
import { appDef } from "./app-def.tsx";
|
|
305
|
+
|
|
306
|
+
export { appDef };
|
|
307
|
+
|
|
308
|
+
export function App() {
|
|
309
|
+
return (
|
|
310
|
+
<AgentApp
|
|
311
|
+
def={appDef}
|
|
312
|
+
texts={() => ({ title: "<产品标题>", assistantLabel: "助手" })}
|
|
313
|
+
/>
|
|
314
|
+
);
|
|
315
|
+
}
|
|
316
|
+
`;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// init 不生成任何测试文件:用例内容由产品的实际用法决定,平台不预制、不代写。
|
|
320
|
+
// 准出测试由产品(或其 AI)按 docs/specs/能力注册表.md 的准出要求现场生成,
|
|
321
|
+
// check 只验「声明完整 + 四脚本齐 + 跑绿」。
|
|
322
|
+
function buildFiles(o) {
|
|
323
|
+
return [
|
|
324
|
+
["manifest.yaml", manifestTemplate(o)],
|
|
325
|
+
["prompt.md", promptTemplate(o)],
|
|
326
|
+
["package.json", packageTemplate(o)],
|
|
327
|
+
["server/routes.ts", routesTemplate(o)],
|
|
328
|
+
["web/app-def.tsx", appDefTemplate()],
|
|
329
|
+
["web/entry.tsx", entryTemplate()],
|
|
330
|
+
];
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function init(opts, dir) {
|
|
334
|
+
if (looksLikePlatformRepo(dir)) {
|
|
335
|
+
process.stderr.write(
|
|
336
|
+
"agentchat-integrate: 当前目录是 agentChat 平台仓,init 会污染平台仓。\n" +
|
|
337
|
+
"请在产品仓根目录执行(或用 --dir 指向产品仓 / 被忽略的临时目录)。\n",
|
|
338
|
+
);
|
|
339
|
+
return 2;
|
|
340
|
+
}
|
|
341
|
+
const id = opts.id ?? defaultId(dir);
|
|
342
|
+
if (!ID_RE.test(id)) {
|
|
343
|
+
process.stderr.write(`agentchat-integrate: --id "${id}" 不合规则(只允许小写字母、数字、连字符)\n`);
|
|
344
|
+
return 2;
|
|
345
|
+
}
|
|
346
|
+
const o = {
|
|
347
|
+
id,
|
|
348
|
+
title: opts.title ?? `${id} 助手`,
|
|
349
|
+
provider: opts.provider ?? "<PROVIDER>",
|
|
350
|
+
model: opts.model ?? "<MODEL_ID>",
|
|
351
|
+
};
|
|
352
|
+
let written = 0;
|
|
353
|
+
let skipped = 0;
|
|
354
|
+
for (const [rel, content] of buildFiles(o)) {
|
|
355
|
+
const target = path.join(dir, rel);
|
|
356
|
+
const exists = fs.existsSync(target);
|
|
357
|
+
// package.json 永不覆盖:里面是产品自己的依赖与脚本。
|
|
358
|
+
if (exists && (rel === "package.json" || !opts.force)) {
|
|
359
|
+
process.stdout.write(`[skip] ${rel}${rel === "package.json" ? "(已存在,永不覆盖)" : "(加 --force 覆盖)"}\n`);
|
|
360
|
+
skipped++;
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (opts.dryRun) {
|
|
364
|
+
process.stdout.write(`[would-write] ${rel}\n`);
|
|
365
|
+
continue;
|
|
366
|
+
}
|
|
367
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
368
|
+
fs.writeFileSync(target, content, "utf8");
|
|
369
|
+
process.stdout.write(`[write] ${rel}\n`);
|
|
370
|
+
written++;
|
|
371
|
+
}
|
|
372
|
+
if (!opts.dryRun) {
|
|
373
|
+
process.stdout.write(
|
|
374
|
+
`\n生成 ${written} 个文件、跳过 ${skipped} 个 → ${dir}\n` +
|
|
375
|
+
`下一步:填掉 <PROVIDER> / <MODEL_ID> / <产品标题> 占位符;核对 manifest 的 capabilities 声明\n` +
|
|
376
|
+
`(恒开能力不列,ID 表见 npx agentchat-integrate capabilities 或 docs/specs/能力注册表.md)。\n` +
|
|
377
|
+
`然后**按声明的能力现场写 UT / 接口 / UI 测试并写入 package.json 的 test:agentchat{,:unit,:api,:ui} 四脚本**\n` +
|
|
378
|
+
`(平台不预制用例——每个产品用法不同;准出要求逐条参考能力注册表,别把示例抄成断言)。\n` +
|
|
379
|
+
`写完再跑 npx agentchat-integrate check;现在跑会因缺测试/缺脚本判红,这是预期。\n`,
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
return 0;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ── check ─────────────────────────────────────────────────────────────────
|
|
386
|
+
|
|
387
|
+
function versionAtLeast(a, b) {
|
|
388
|
+
const pa = String(a).split(".").map(Number);
|
|
389
|
+
const pb = String(b).split(".").map(Number);
|
|
390
|
+
for (let i = 0; i < 3; i++) {
|
|
391
|
+
if ((pa[i] ?? 0) > (pb[i] ?? 0)) return true;
|
|
392
|
+
if ((pa[i] ?? 0) < (pb[i] ?? 0)) return false;
|
|
393
|
+
}
|
|
394
|
+
return true;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
function checkDeps(add, dir) {
|
|
398
|
+
const raw = readText(dir, "package.json");
|
|
399
|
+
if (!raw) {
|
|
400
|
+
add("FAIL", "deps", "缺 package.json", "先 npm init 或补一份产品仓 package.json");
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
let pj;
|
|
404
|
+
try { pj = JSON.parse(raw); } catch {
|
|
405
|
+
add("FAIL", "deps", "package.json 不是合法 JSON", "修好 JSON 后重跑");
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
const all = { ...(pj.dependencies ?? {}), ...(pj.devDependencies ?? {}) };
|
|
409
|
+
const missing = Object.values(PKG).filter((n) => !(n in all));
|
|
410
|
+
if (missing.length) add("FAIL", "deps", `未声明平台依赖:${missing.join("、")}`,
|
|
411
|
+
`npm i ${PKG.protocol}@^0.4.0 ${PKG.server}@^0.4.0 ${PKG.web}@^0.4.0`);
|
|
412
|
+
else add("OK", "deps", "三个平台包依赖已声明");
|
|
413
|
+
|
|
414
|
+
try {
|
|
415
|
+
const req = createRequire(path.join(dir, "package.json"));
|
|
416
|
+
const file = req.resolve(`${PKG.server}/package.json`);
|
|
417
|
+
const v = JSON.parse(fs.readFileSync(file, "utf8")).version;
|
|
418
|
+
if (versionAtLeast(v, MIN_SERVER)) add("OK", "installed", `已安装 ${PKG.server} ${v}`);
|
|
419
|
+
else add("WARN", "installed", `已安装 ${v} < ${MIN_SERVER}(能力门禁与准出脚本检查从 ${MIN_SERVER} 起)`,
|
|
420
|
+
`npm i ${PKG.server}@^${MIN_SERVER} 刷新 lockfile`);
|
|
421
|
+
} catch {
|
|
422
|
+
add("WARN", "installed", "node_modules 未安装或平台包不可解析", "npm install 后重跑 check");
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** 从 manifest 文本里取 server.routes 的相对路径(不解析 YAML)。 */
|
|
427
|
+
function serverRoutesOf(text) {
|
|
428
|
+
let inServer = false;
|
|
429
|
+
for (const line of text.split(/\r?\n/)) {
|
|
430
|
+
if (/^server:\s*(#.*)?$/.test(line)) { inServer = true; continue; }
|
|
431
|
+
if (inServer && /^\S/.test(line)) inServer = false;
|
|
432
|
+
const m = inServer && line.match(/^\s+routes:\s*["']?([^"'\s#]+)["']?/);
|
|
433
|
+
if (m) return m[1];
|
|
434
|
+
}
|
|
435
|
+
return null;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function checkManifest(add, dir) {
|
|
439
|
+
const text = readText(dir, "manifest.yaml");
|
|
440
|
+
if (!text) {
|
|
441
|
+
add("FAIL", "manifest", "缺 manifest.yaml", "跑 agentchat-integrate init 生成");
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
const problems = [];
|
|
445
|
+
if (!/^id:\s*\S+/m.test(text)) problems.push("缺 id");
|
|
446
|
+
if (!/^branding:\s*(#.*)?$/m.test(text) || !/^\s+title:\s*\S+/m.test(text)) problems.push("缺 branding.title");
|
|
447
|
+
if (!/^\s+systemPrompt:\s*\S+/m.test(text)) problems.push("缺 agent.systemPrompt");
|
|
448
|
+
// model 支持两种写法:块式(provider/id 各占一行)与内联花括号(夹具用的写法)。
|
|
449
|
+
const inlineModel = text.match(/^\s+model:\s*\{([^}]*)\}/m)?.[1] ?? "";
|
|
450
|
+
const hasProvider = /^\s+provider:\s*\S+/m.test(text) || /\bprovider:\s*\S+/.test(inlineModel);
|
|
451
|
+
const hasModelId = /^\s+id:\s*\S+/m.test(text) || /\bid:\s*\S+/.test(inlineModel);
|
|
452
|
+
if (!hasProvider) problems.push("缺 agent.model.provider");
|
|
453
|
+
if (!hasModelId) problems.push("缺 agent.model.id");
|
|
454
|
+
const rel = serverRoutesOf(text);
|
|
455
|
+
if (!rel) problems.push("缺 server.routes 声明");
|
|
456
|
+
else if (!rel.startsWith("./") || !rel.endsWith(".ts")) problems.push(`server.routes "${rel}" 必须 ./ 开头、.ts 结尾`);
|
|
457
|
+
else {
|
|
458
|
+
const resolved = path.resolve(dir, rel);
|
|
459
|
+
if (!resolved.startsWith(path.resolve(dir) + path.sep) || !fs.existsSync(resolved)) {
|
|
460
|
+
problems.push(`server.routes "${rel}" 必须存在且留在产品目录内`);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
if (!fs.existsSync(path.join(dir, "prompt.md"))) problems.push("缺 prompt.md(loadProduct 会读 systemPrompt 指向的文件)");
|
|
464
|
+
if (problems.length) add("FAIL", "manifest", problems.join(";"), "对照 packages/server/src/manifest.ts 的硬校验补齐");
|
|
465
|
+
else add("OK", "manifest", "必填字段 + server.routes 三道闸 + prompt.md");
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function checkRoutes(add, dir) {
|
|
469
|
+
const text = readText(dir, "server/routes.ts");
|
|
470
|
+
if (!text) { add("FAIL", "routes.ts", "缺 server/routes.ts", "跑 init 生成,或按 ProductRouteModule 形状补上"); return; }
|
|
471
|
+
const problems = [];
|
|
472
|
+
if (!/export\s+(?:async\s+)?function\s+createRoutes\b|export\s+const\s+createRoutes\b/.test(text)) {
|
|
473
|
+
problems.push("未导出 createRoutes()");
|
|
474
|
+
}
|
|
475
|
+
if (!/\broutes\s*:/.test(text)) problems.push("返回值缺 routes");
|
|
476
|
+
if (!/\badmin\s*:/.test(text)) problems.push("返回值缺 admin");
|
|
477
|
+
if (problems.length) add("FAIL", "routes.ts", problems.join(";"), "返回 { routes, admin, init? };落空要 return 让 core 接手");
|
|
478
|
+
else add("OK", "routes.ts", "createRoutes() → { routes, admin }");
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function checkAppDef(add, dir) {
|
|
482
|
+
const entry = readText(dir, "web/entry.tsx");
|
|
483
|
+
const def = readText(dir, "web/app-def.tsx");
|
|
484
|
+
const problems = [];
|
|
485
|
+
if (!entry) problems.push("缺 web/entry.tsx");
|
|
486
|
+
if (!def) problems.push("缺 web/app-def.tsx");
|
|
487
|
+
if (entry) {
|
|
488
|
+
if (!/export\s*\{[^}]*\bappDef\b|export\s+const\s+appDef\b/.test(entry)) problems.push("entry 未导出 appDef");
|
|
489
|
+
if (!/export\s+(?:function|const)\s+App\b/.test(entry)) problems.push("entry 未导出 App");
|
|
490
|
+
}
|
|
491
|
+
if (def) {
|
|
492
|
+
for (const field of ["home", "chatRoute", "routes", "navItems", "page"]) {
|
|
493
|
+
// 两种合法写法都要认:冒号属性(`navItems: () => [...]`)与 ES 简写
|
|
494
|
+
// (`navItems,`,值来自模块作用域的 const)。只用冒号正则会把简写误判成
|
|
495
|
+
// 「缺字段」——真实产品就这么写,属于假红。
|
|
496
|
+
// 简写只认行首,避免把 `import { guard, navItems, ROUTES }` 当成已声明。
|
|
497
|
+
const declared =
|
|
498
|
+
new RegExp(`\\b${field}\\s*:`).test(def) || new RegExp(`^\\s*${field}\\s*(?:,|\\}|$)`, "m").test(def);
|
|
499
|
+
if (!declared) problems.push(`app-def 缺 ${field}`);
|
|
500
|
+
}
|
|
501
|
+
const block = def.match(/routes:\s*\{([\s\S]*?)\}/);
|
|
502
|
+
if (block) {
|
|
503
|
+
const keys = [...block[1].matchAll(/^\s*([A-Za-z0-9_-]+)\s*:/gm)].map((m) => m[1]);
|
|
504
|
+
const bad = keys.filter((k) => !/^[a-z]+$/.test(k));
|
|
505
|
+
if (bad.length) problems.push(`路由键只能小写字母:${bad.join("、")}`);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (problems.length) add("FAIL", "app-def", problems.join(";"), "对照 apps/web/test/app-def-check.test.ts 的最小 def 样板");
|
|
509
|
+
else add("OK", "app-def", "appDef / App 导出、字段齐全、路由键小写");
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function checkPlaceholders(add, dir) {
|
|
513
|
+
const rels = ["manifest.yaml", "server/routes.ts", "web/entry.tsx", "prompt.md"];
|
|
514
|
+
const hits = [];
|
|
515
|
+
for (const rel of rels) {
|
|
516
|
+
const text = readText(dir, rel);
|
|
517
|
+
for (const p of PLACEHOLDERS) if (text.includes(p)) hits.push(`${rel}: ${p}`);
|
|
518
|
+
}
|
|
519
|
+
if (hits.length) add("WARN", "placeholders", `还有 ${hits.length} 处占位符未替换`, `替换 ${[...new Set(PLACEHOLDERS)].join(" / ")} 后重跑`);
|
|
520
|
+
else add("OK", "placeholders", "无未替换占位符");
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function walkFiles(dir, out = []) {
|
|
524
|
+
let entries;
|
|
525
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return out; }
|
|
526
|
+
for (const e of entries) {
|
|
527
|
+
if (e.name === "node_modules" || e.name === "dist" || e.name.startsWith(".")) continue;
|
|
528
|
+
const full = path.join(dir, e.name);
|
|
529
|
+
if (e.isDirectory()) walkFiles(full, out);
|
|
530
|
+
else out.push(full);
|
|
531
|
+
}
|
|
532
|
+
return out;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
// ── 能力声明与对账 ─────────────────────────────────────────────────────────
|
|
536
|
+
|
|
537
|
+
/** 解析 manifest 的 capabilities 段。返回 null=缺失段;{ids}=已声明(可为空列表)。 */
|
|
538
|
+
function capabilitiesOf(text) {
|
|
539
|
+
const inline = text.match(/^capabilities:\s*\[([^\]]*)\]\s*(#.*)?$/m);
|
|
540
|
+
if (inline) {
|
|
541
|
+
const ids = inline[1].split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean);
|
|
542
|
+
return { ids };
|
|
543
|
+
}
|
|
544
|
+
const m = text.match(/^capabilities:\s*(#.*)?$/m);
|
|
545
|
+
if (!m) return null;
|
|
546
|
+
const ids = [];
|
|
547
|
+
for (const line of text.slice(m.index + m[0].length).split(/\r?\n/)) {
|
|
548
|
+
if (line.trim() === "" || /^\s*#/.test(line)) continue;
|
|
549
|
+
const item = line.match(/^\s+-\s+["']?([A-Za-z0-9_-]+)["']?\s*(#.*)?$/);
|
|
550
|
+
if (!item) break;
|
|
551
|
+
ids.push(item[1]);
|
|
552
|
+
}
|
|
553
|
+
return { ids };
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/** manifest 结构化推导(确定性,零误报):字段声明即使用。返回触发中的能力 ID。 */
|
|
557
|
+
function deriveFromManifest(text) {
|
|
558
|
+
const hit = [];
|
|
559
|
+
const t = text;
|
|
560
|
+
if (serverRoutesOf(t)) hit.push("product-routes");
|
|
561
|
+
if (/^\s+inline:\s*["']?\./m.test(t)) hit.push("inline-tools");
|
|
562
|
+
if (/^mcp:/m.test(t)) hit.push("mcp-tools");
|
|
563
|
+
if (/^confirmTools:\s*\S/m.test(t)) hit.push("tool-confirm");
|
|
564
|
+
if (/^\s+personas:/m.test(t)) hit.push("personas");
|
|
565
|
+
if (/^\s+skills:\s*(#.*)?$|^\s+skills:\s*\[/m.test(t)) hit.push("skills");
|
|
566
|
+
if (/^\s+extensions:\s*(#.*)?$|^\s+extensions:\s*\[/m.test(t)) hit.push("extensions");
|
|
567
|
+
if (!/^\s+memory:\s*false\s*(#.*)?$/m.test(t)) hit.push("scoped-memory");
|
|
568
|
+
if (/^\s+tiers:/m.test(t)) hit.push("tiers");
|
|
569
|
+
if (/^billing:/m.test(t)) hit.push("billing");
|
|
570
|
+
if (/^\s+seedPolicies:/m.test(t)) hit.push("authz-seed");
|
|
571
|
+
if (/^quals:/m.test(t)) hit.push("quals");
|
|
572
|
+
return hit;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** 粗剥 JS/TS 注释(启发式,够用于痕迹扫描;字符串里的 // 可能被误剥,但只影响 WARN 级判定)。 */
|
|
576
|
+
function stripComments(s) {
|
|
577
|
+
return s.replace(/\/\*[\s\S]*?\*\//g, " ").split("\n").map((l) => l.replace(/(^|[^:"'`])\/\/[^\r\n]*/, "$1")).join("\n");
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
/** 代码痕迹扫描(启发式,只给 WARN):manifest 无痕迹、代码里真调了端点/类型。 */
|
|
581
|
+
function scanCodeTraces(dir) {
|
|
582
|
+
const hit = new Set();
|
|
583
|
+
const srcFiles = walkFiles(dir).filter((f) => /\.(ts|tsx)$/.test(f));
|
|
584
|
+
const appdefFiles = srcFiles.filter((f) => /[\\/]app-def\.tsx$|[\\/]entry\.tsx$/.test(f));
|
|
585
|
+
for (const f of srcFiles) {
|
|
586
|
+
if (/[\\/](test|tests|e2e)[\\/]/.test(f)) continue; // 测试里的 fetch 不算产品用法
|
|
587
|
+
const text = stripComments(readText(path.dirname(f), path.basename(f)));
|
|
588
|
+
if (!text) continue;
|
|
589
|
+
if (/\bProductAdminRoute\b/.test(text)) hit.add("product-admin-routes");
|
|
590
|
+
if (/\/api\/(orders|recharge)\b/.test(text)) hit.add("billing");
|
|
591
|
+
if (/\/api\/feedback\b|\bcreateFeedback\b/.test(text)) hit.add("feedback");
|
|
592
|
+
if (/\/api\/(attachments|images)\b/.test(text)) hit.add("attachments");
|
|
593
|
+
if (/\bsendToChat\b/.test(text)) hit.add("appdef-extensions");
|
|
594
|
+
}
|
|
595
|
+
// AppDef 可选键只在注册表文件里判——guard/footer 是通用词,全仓扫必误报。
|
|
596
|
+
for (const f of appdefFiles) {
|
|
597
|
+
const text = stripComments(fs.readFileSync(f, "utf8"));
|
|
598
|
+
if (/\b(navAlias|cardRenderer|rewrites)\s*:/.test(text) || /^\s*(guard|footer|extras)\s*[:(]/m.test(text)) {
|
|
599
|
+
hit.add("appdef-extensions");
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
return [...hit];
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
function checkCapabilities(add, dir) {
|
|
606
|
+
const text = readText(dir, "manifest.yaml");
|
|
607
|
+
if (!text) return null; // manifest 缺失由 checkManifest 报 FAIL,这里不重复
|
|
608
|
+
const caps = capabilitiesOf(text);
|
|
609
|
+
if (caps === null) {
|
|
610
|
+
add("FAIL", "capabilities", "manifest 缺 capabilities 段(空列表 [] 也合法,缺失不合法)",
|
|
611
|
+
"声明本产品用到的平台能力;恒开能力不列;npx agentchat-integrate capabilities 查 ID 表");
|
|
612
|
+
return null;
|
|
613
|
+
}
|
|
614
|
+
const problems = [];
|
|
615
|
+
const unknown = caps.ids.filter((id) => !CAP_IDS.has(id));
|
|
616
|
+
const alwaysOn = caps.ids.filter((id) => ALWAYS_IDS.has(id));
|
|
617
|
+
const dup = caps.ids.filter((id, i) => caps.ids.indexOf(id) !== i);
|
|
618
|
+
if (unknown.length) problems.push(`注册表外的能力 ID:${unknown.join("、")}`);
|
|
619
|
+
if (alwaysOn.length) problems.push(`恒开能力不该写进声明:${alwaysOn.join("、")}`);
|
|
620
|
+
if (dup.length) problems.push(`重复声明:${[...new Set(dup)].join("、")}`);
|
|
621
|
+
|
|
622
|
+
const derived = deriveFromManifest(text);
|
|
623
|
+
const traced = scanCodeTraces(dir);
|
|
624
|
+
const undeclaredDerived = derived.filter((id) => !caps.ids.includes(id));
|
|
625
|
+
const undeclaredTraced = traced.filter((id) => !caps.ids.includes(id) && !undeclaredDerived.includes(id));
|
|
626
|
+
const unused = caps.ids.filter((id) => !derived.includes(id) && !traced.includes(id));
|
|
627
|
+
|
|
628
|
+
if (problems.length) {
|
|
629
|
+
add("FAIL", "capabilities", problems.join(";"), "对照 docs/specs/能力注册表.md 修正声明");
|
|
630
|
+
} else {
|
|
631
|
+
add("OK", "capabilities", `已声明 ${caps.ids.length} 项增量能力:${caps.ids.join("、") || "(无)"}`);
|
|
632
|
+
}
|
|
633
|
+
if (undeclaredDerived.length) {
|
|
634
|
+
add("FAIL", "capabilities-derived",
|
|
635
|
+
`manifest 已触发但未声明:${undeclaredDerived.join("、")}`,
|
|
636
|
+
`加进 capabilities(触发条件见注册表),或删掉对应字段声明`);
|
|
637
|
+
} else if (undeclaredTraced.length) {
|
|
638
|
+
add("WARN", "capabilities-derived",
|
|
639
|
+
`代码痕迹检出但未声明(启发式,可能误报):${undeclaredTraced.join("、")}`,
|
|
640
|
+
"确实用了就声明;没用到的写法删掉;确认误报可忽略本条");
|
|
641
|
+
} else {
|
|
642
|
+
add("OK", "capabilities-derived", `双向对账干净(推导命中 ${derived.length}、痕迹命中 ${traced.length})`);
|
|
643
|
+
}
|
|
644
|
+
if (unused.length) {
|
|
645
|
+
add("WARN", "capabilities-unused", `声明了但 manifest/代码都没检出:${unused.join("、")}`,
|
|
646
|
+
"要么补上用法,要么从 capabilities 删掉");
|
|
647
|
+
}
|
|
648
|
+
return { declared: caps.ids, derived, traced, undeclaredDerived, undeclaredTraced, unused };
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
// ── 准出四脚本:存在 + 真跑 ────────────────────────────────────────────────
|
|
652
|
+
|
|
653
|
+
const TEST_SCRIPTS = ["test:agentchat", "test:agentchat:unit", "test:agentchat:api", "test:agentchat:ui"];
|
|
654
|
+
|
|
655
|
+
function runNpmScript(dir, script, timeoutSec) {
|
|
656
|
+
const r = spawnSync("npm", ["run", script], {
|
|
657
|
+
cwd: dir, encoding: "utf8", timeout: timeoutSec * 1000,
|
|
658
|
+
shell: process.platform === "win32", // Windows 上 npm 是 .cmd,必须走 shell
|
|
659
|
+
});
|
|
660
|
+
if (r.error) {
|
|
661
|
+
const kind = r.error.code === "ETIMEDOUT" ? "timeout" : r.error.code === "ENOENT" ? "no-npm" : "spawn-error";
|
|
662
|
+
return { kind, exitCode: null, output: String(r.error.message ?? "") };
|
|
663
|
+
}
|
|
664
|
+
return {
|
|
665
|
+
kind: r.status === 0 ? "ok" : "fail",
|
|
666
|
+
exitCode: r.status,
|
|
667
|
+
output: `${r.stdout ?? ""}\n${r.stderr ?? ""}`.trim().slice(-1200),
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
function checkTestScripts(add, dir, opts) {
|
|
672
|
+
let scripts = {};
|
|
673
|
+
try { scripts = JSON.parse(readText(dir, "package.json")).scripts ?? {}; } catch { return; }
|
|
674
|
+
const missing = TEST_SCRIPTS.filter((s) => !scripts[s] || !String(scripts[s]).trim());
|
|
675
|
+
if (missing.length) {
|
|
676
|
+
add("FAIL", "test-scripts", `缺准出脚本:${missing.join("、")}`,
|
|
677
|
+
"按 agentchat-onboarding Skill 生成 UT/接口/UI 三组测试后写入这四个脚本(内容由产品按能力注册表自行编写,平台不预制)");
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
const agg = String(scripts["test:agentchat"]);
|
|
681
|
+
const subs = ["test:agentchat:unit", "test:agentchat:api", "test:agentchat:ui"];
|
|
682
|
+
const notAggregated = subs.filter((s) => !agg.includes(s));
|
|
683
|
+
if (notAggregated.length) {
|
|
684
|
+
add("WARN", "test-scripts", `test:agentchat 未引用:${notAggregated.join("、")}`,
|
|
685
|
+
"汇总脚本应跑全三个子脚本,否则 CI/门禁会漏层");
|
|
686
|
+
} else {
|
|
687
|
+
add("OK", "test-scripts", "准出四脚本齐备且汇总完整");
|
|
688
|
+
}
|
|
689
|
+
if (opts.noRun) {
|
|
690
|
+
add("WARN", "test-run", "--no-run:本次未执行测试脚本", "CI 与验收必须真跑,本地提速才用 --no-run");
|
|
691
|
+
return;
|
|
692
|
+
}
|
|
693
|
+
const runs = [];
|
|
694
|
+
let failed = false;
|
|
695
|
+
for (const s of subs) {
|
|
696
|
+
const r = runNpmScript(dir, s, opts.timeout);
|
|
697
|
+
runs.push({ script: s, ...r });
|
|
698
|
+
if (r.kind === "timeout") {
|
|
699
|
+
add("FAIL", "test-run", `${s} 超时(>${opts.timeout}s)`, `调 --timeout 或拆分用例;报告尾部:${r.output.slice(-300)}`);
|
|
700
|
+
failed = true;
|
|
701
|
+
} else if (r.kind === "no-npm") {
|
|
702
|
+
add("FAIL", "test-run", "npm 不可用,无法执行测试脚本", "确认 PATH 里有 npm");
|
|
703
|
+
failed = true;
|
|
704
|
+
} else if (r.kind !== "ok") {
|
|
705
|
+
const hint = /Cannot find package 'tsx'/.test(r.output) ? "先 npm i -D tsx;" :
|
|
706
|
+
/Cannot find package '@njuptlzf\//.test(r.output) ? "先 npm install;" : "";
|
|
707
|
+
add("FAIL", "test-run", `${s} 未通过(exit ${r.exitCode})`, `${hint}报告尾部:${r.output.slice(-300)}`);
|
|
708
|
+
failed = true;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
if (!failed) add("OK", "test-run", `三组准出脚本真跑通过(unit/api/ui @ ${opts.timeout}s 上限)`);
|
|
712
|
+
return runs;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function checkTooling(add, dir) {
|
|
716
|
+
const wf = path.join(dir, ".github", "workflows");
|
|
717
|
+
const wfFiles = fs.existsSync(wf) ? fs.readdirSync(wf).filter((f) => /\.ya?ml$/.test(f)) : [];
|
|
718
|
+
if (wfFiles.length === 0) {
|
|
719
|
+
add("WARN", "ci", "未发现 .github/workflows/*.yml", "产品仓自己加 CI,至少跑 typecheck / test / build");
|
|
720
|
+
} else if (!wfFiles.some((f) => /test:agentchat/.test(fs.readFileSync(path.join(wf, f), "utf8")))) {
|
|
721
|
+
add("WARN", "ci", "CI 存在但未引用 test:agentchat", "把 `npm run test:agentchat` 加进产品仓 CI 的门禁步骤");
|
|
722
|
+
} else {
|
|
723
|
+
add("OK", "ci", "存在 CI 工作流且引用 test:agentchat");
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
const vite = ["vite.config.ts", "vite.config.mts", "vite.config.js", "web/vite.config.ts"]
|
|
727
|
+
.map((r) => readText(dir, r)).join("\n");
|
|
728
|
+
if (/validateAppDef|appDefGuard/.test(vite)) add("OK", "appdef-guard", "vite.config 已接构建期 AppDef 守卫");
|
|
729
|
+
else add("INFO", "appdef-guard", "未检测到 validateAppDef / appDefGuard",
|
|
730
|
+
"在产品 vite.config.ts 复用 @njuptlzf/agent-chat-web/app-def-check;20 条动态契约由它把关,CLI 不复制口径");
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function checkDeep(add, dir) {
|
|
734
|
+
const code = `
|
|
735
|
+
import { pathToFileURL } from "node:url";
|
|
736
|
+
import { sampleHostContexts, validateAppDef } from "${PKG.web}/app-def-check";
|
|
737
|
+
const { appDef } = await import(pathToFileURL(${JSON.stringify(path.join(dir, "web/app-def.tsx"))}).href);
|
|
738
|
+
for (const { name, ctx } of sampleHostContexts()) {
|
|
739
|
+
const problems = validateAppDef(appDef, ctx);
|
|
740
|
+
if (problems.length) {
|
|
741
|
+
console.error(name + ": " + problems.map((p) => p.where + ": " + p.message).join("; "));
|
|
742
|
+
process.exit(1);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
console.log("deep ok");
|
|
746
|
+
`;
|
|
747
|
+
const r = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", code], {
|
|
748
|
+
cwd: dir, encoding: "utf8", timeout: 60_000,
|
|
749
|
+
});
|
|
750
|
+
if (r.status === 0) add("OK", "deep", "真实 validateAppDef 五上下文校验通过");
|
|
751
|
+
else add("INFO", "deep", "deep 校验未完成(缺 tsx / 依赖 / AppDef 不可用)",
|
|
752
|
+
`改由产品 npm run build 的 appDefGuard 把关;详情:${String(r.stderr ?? r.error ?? "").trim().slice(0, 300)}`);
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function check(opts, dir) {
|
|
756
|
+
const results = [];
|
|
757
|
+
const add = (level, code, message, suggestion) => {
|
|
758
|
+
results.push({ level, code, message, ...(suggestion ? { suggestion } : {}) });
|
|
759
|
+
};
|
|
760
|
+
checkDeps(add, dir);
|
|
761
|
+
checkManifest(add, dir);
|
|
762
|
+
checkRoutes(add, dir);
|
|
763
|
+
checkAppDef(add, dir);
|
|
764
|
+
checkPlaceholders(add, dir);
|
|
765
|
+
const caps = checkCapabilities(add, dir);
|
|
766
|
+
const runs = checkTestScripts(add, dir, opts);
|
|
767
|
+
checkTooling(add, dir);
|
|
768
|
+
if (opts.deep) checkDeep(add, dir);
|
|
769
|
+
|
|
770
|
+
const failures = results.filter((r) => r.level === "FAIL");
|
|
771
|
+
const warnings = results.filter((r) => r.level === "WARN");
|
|
772
|
+
const suggestions = results.filter((r) => r.suggestion).map((r) => `[${r.code}] ${r.suggestion}`);
|
|
773
|
+
const report = {
|
|
774
|
+
ok: failures.length === 0,
|
|
775
|
+
dir,
|
|
776
|
+
failures: failures.map((r) => ({ code: r.code, message: r.message })),
|
|
777
|
+
warnings: warnings.map((r) => ({ code: r.code, message: r.message })),
|
|
778
|
+
suggestions,
|
|
779
|
+
results,
|
|
780
|
+
capabilities: caps && {
|
|
781
|
+
declared: caps.declared,
|
|
782
|
+
detected: [...new Set([...caps.derived, ...caps.traced])],
|
|
783
|
+
undeclaredManifest: caps.undeclaredDerived,
|
|
784
|
+
undeclaredCode: caps.undeclaredTraced,
|
|
785
|
+
unused: caps.unused,
|
|
786
|
+
alwaysRequired: CAP_ALWAYS.map((c) => c.id),
|
|
787
|
+
},
|
|
788
|
+
runs: runs ?? null,
|
|
789
|
+
};
|
|
790
|
+
if (opts.json) {
|
|
791
|
+
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
|
|
792
|
+
} else {
|
|
793
|
+
process.stdout.write(`agentchat-integrate check — ${dir}\n`);
|
|
794
|
+
for (const r of results) {
|
|
795
|
+
process.stdout.write(`[${r.level.padEnd(4)}] ${r.code.padEnd(14)} ${r.message}\n`);
|
|
796
|
+
}
|
|
797
|
+
process.stdout.write(
|
|
798
|
+
`---\n结论:违规 ${failures.length} 条;建议 ${warnings.length} 条;` +
|
|
799
|
+
`退出码 ${failures.length ? 1 : 0}${failures.length ? "" : "(建议不阻断)"}\n`,
|
|
800
|
+
);
|
|
801
|
+
if (caps) {
|
|
802
|
+
process.stdout.write(`恒开必测(不写声明):${CAP_ALWAYS.map((c) => `${c.id}(${c.name})`).join("、")}\n`);
|
|
803
|
+
}
|
|
804
|
+
if (suggestions.length) process.stdout.write(`建议:\n${suggestions.map((s) => ` - ${s}`).join("\n")}\n`);
|
|
805
|
+
}
|
|
806
|
+
return failures.length ? 1 : 0;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
// ── capabilities 子命令 ────────────────────────────────────────────────────
|
|
810
|
+
|
|
811
|
+
function capabilitiesCmd(opts) {
|
|
812
|
+
if (opts.json) {
|
|
813
|
+
process.stdout.write(`${JSON.stringify({ always: CAP_ALWAYS, optIn: CAP_OPT_IN }, null, 2)}\n`);
|
|
814
|
+
return 0;
|
|
815
|
+
}
|
|
816
|
+
process.stdout.write("恒开能力(任何产品都在用,**不写进 capabilities**,准出必测):\n");
|
|
817
|
+
for (const c of CAP_ALWAYS) process.stdout.write(` ${c.id.padEnd(22)} ${c.name}\n`);
|
|
818
|
+
process.stdout.write("\n声明式能力(用了必须写进 manifest capabilities):\n");
|
|
819
|
+
for (const c of CAP_OPT_IN) process.stdout.write(` ${c.id.padEnd(22)} ${c.name} 触发:${c.trigger}\n`);
|
|
820
|
+
process.stdout.write("\n准出要求(UT/接口/UI 各层的断言方向)见平台仓 docs/specs/能力注册表.md。\n");
|
|
821
|
+
return 0;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
// ── 入口 ──────────────────────────────────────────────────────────────────
|
|
825
|
+
|
|
826
|
+
function main() {
|
|
827
|
+
const raw = process.argv.slice(2);
|
|
828
|
+
// 全局开关优先于子命令:没有子命令时也要能看帮助/版本。
|
|
829
|
+
if (raw.includes("--help") || raw.includes("-h")) { process.stdout.write(`${HELP}\n`); return 0; }
|
|
830
|
+
if (raw.includes("--version") || raw.includes("-V")) { process.stdout.write(`${CLI_VERSION}\n`); return 0; }
|
|
831
|
+
const parsed = parseArgs(raw);
|
|
832
|
+
if (parsed.error) usageError(parsed.error);
|
|
833
|
+
const opts = parsed.opts;
|
|
834
|
+
if (opts.help) { process.stdout.write(`${HELP}\n`); return 0; }
|
|
835
|
+
if (opts.version) { process.stdout.write(`${CLI_VERSION}\n`); return 0; }
|
|
836
|
+
if (opts.cmd === "capabilities") return capabilitiesCmd(opts);
|
|
837
|
+
if (opts.cmd !== "init" && opts.cmd !== "check") {
|
|
838
|
+
usageError(opts.cmd ? `未知子命令:${opts.cmd}` : "缺子命令(init / check / capabilities)");
|
|
839
|
+
}
|
|
840
|
+
const dir = path.resolve(opts.dir ?? process.cwd());
|
|
841
|
+
if (fs.existsSync(dir) && !fs.statSync(dir).isDirectory()) {
|
|
842
|
+
usageError(`不是目录:${dir}`);
|
|
843
|
+
}
|
|
844
|
+
if (opts.cmd === "check" && !fs.existsSync(dir)) {
|
|
845
|
+
usageError(`目录不存在:${dir}`);
|
|
846
|
+
}
|
|
847
|
+
if (opts.cmd === "init" && !fs.existsSync(dir)) {
|
|
848
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
849
|
+
}
|
|
850
|
+
return opts.cmd === "init" ? init(opts, dir) : check(opts, dir);
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
process.exitCode = main();
|