@njuptlzf/agent-chat-server 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/branding-ui.d.ts +16 -0
- package/dist/branding-ui.js +119 -0
- 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 +115 -0
- package/dist/main.js +14 -2
- package/dist/manifest.js +27 -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/persona-config.js +12 -0
- package/dist/server.d.ts +27 -2
- package/dist/server.js +595 -187
- package/dist/session.js +2 -1
- package/dist/sqlite-stores.d.ts +46 -6
- package/dist/sqlite-stores.js +292 -33
- package/dist/stores.d.ts +0 -36
- package/dist/stores.js +0 -27
- package/dist/suggestions.d.ts +60 -0
- package/dist/suggestions.js +107 -0
- package/dist/testing.d.ts +5 -4
- package/dist/testing.js +5 -4
- package/package.json +65 -64
- package/scripts/agentchat-integrate.mjs +852 -852
- package/src/branding-ui.ts +126 -0
- 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 +171 -0
- package/src/main.ts +16 -2
- package/src/manifest.ts +27 -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/persona-config.ts +12 -1
- package/src/server.ts +611 -183
- package/src/session.ts +2 -1
- package/src/sqlite-stores.ts +343 -35
- package/src/stores.ts +0 -41
- package/src/suggestions.ts +146 -0
- package/src/testing.ts +4 -4
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import type { Branding } from "@njuptlzf/agent-chat-protocol";
|
|
2
|
+
|
|
3
|
+
type BrandingUi = NonNullable<Branding["ui"]>;
|
|
4
|
+
type BrandingFollowUp = NonNullable<BrandingUi["followUp"]>;
|
|
5
|
+
|
|
6
|
+
/** 「下一步建议」的三态。全局(branding.ui.followUp.mode)与人格(PersonaUi.followUpMode)共用这一份。 */
|
|
7
|
+
export const FOLLOW_UP_MODES = ["off", "static", "llm"] as const;
|
|
8
|
+
export type FollowUpMode = (typeof FOLLOW_UP_MODES)[number];
|
|
9
|
+
|
|
10
|
+
/** 图标语义槽白名单:键是平台定义的槽名,不是组件名。新增视觉件时在这里登记。 */
|
|
11
|
+
export const ICON_SLOTS = ["attachment"] as const;
|
|
12
|
+
|
|
13
|
+
const FOLLOW_UP_KEYS: readonly string[] = ["mode", "count", "static", "systemPrompt", "maxMessages", "timeoutMs"];
|
|
14
|
+
|
|
15
|
+
const MAX_ICON_VALUE = 512;
|
|
16
|
+
const MAX_STATIC_ITEMS = 10;
|
|
17
|
+
const MAX_STATIC_CHARS = 200;
|
|
18
|
+
const MAX_PROMPT_CHARS = 2000;
|
|
19
|
+
const MAX_COUNT = 5;
|
|
20
|
+
const MAX_MESSAGES = 20;
|
|
21
|
+
const MAX_TIMEOUT_MS = 30_000;
|
|
22
|
+
|
|
23
|
+
function deny(file: string, msg: string): never {
|
|
24
|
+
throw new Error(`Invalid manifest ${file}: ${msg}`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isRecord(v: unknown): v is Record<string, unknown> {
|
|
28
|
+
return !!v && typeof v === "object" && !Array.isArray(v);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isMode(v: unknown): v is FollowUpMode {
|
|
32
|
+
return typeof v === "string" && (FOLLOW_UP_MODES as readonly string[]).includes(v);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 校验并规范化 `branding.ui`(图标值 + 下一步建议配置)。
|
|
37
|
+
*
|
|
38
|
+
* 分级与人格 ui 同一套口径:未知键 / 形状错 = 启动期 fail-fast(manifest 是签入文件,
|
|
39
|
+
* 错别字必须响);单个图标值非法(如非 http(s) 的 url: 前缀)= 丢弃该键回落默认,不因
|
|
40
|
+
* 一个坏图标让服务起不来。返回 undefined 表示产品没配(或全被丢弃)。
|
|
41
|
+
*/
|
|
42
|
+
export function parseBrandingUi(file: string, at: string, raw: unknown): BrandingUi | undefined {
|
|
43
|
+
if (raw === undefined) return undefined;
|
|
44
|
+
if (!isRecord(raw)) deny(file, `\`${at}\` must be a mapping`);
|
|
45
|
+
const src = raw as Record<string, unknown>;
|
|
46
|
+
for (const key of Object.keys(src)) {
|
|
47
|
+
if (key !== "icons" && key !== "followUp") {
|
|
48
|
+
deny(file, `\`${at}.${key}\` is not a branding ui field (allowed: icons, followUp)`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let icons: Record<string, string> | undefined;
|
|
53
|
+
if (src.icons !== undefined) {
|
|
54
|
+
if (!isRecord(src.icons)) deny(file, `\`${at}.icons\` must be a mapping`);
|
|
55
|
+
const srcIcons = src.icons as Record<string, unknown>;
|
|
56
|
+
for (const [key, value] of Object.entries(srcIcons)) {
|
|
57
|
+
if (!(ICON_SLOTS as readonly string[]).includes(key)) {
|
|
58
|
+
deny(file, `\`${at}.icons.${key}\` is not a known icon slot (allowed: ${ICON_SLOTS.join(", ")})`);
|
|
59
|
+
}
|
|
60
|
+
if (typeof value !== "string" || value.trim() === "") {
|
|
61
|
+
deny(file, `\`${at}.icons.${key}\` must be a non-empty string`);
|
|
62
|
+
}
|
|
63
|
+
if (value.length > MAX_ICON_VALUE) {
|
|
64
|
+
deny(file, `\`${at}.icons.${key}\` must be at most ${MAX_ICON_VALUE} characters`);
|
|
65
|
+
}
|
|
66
|
+
// url: 前缀只放行 http(s);别的协议(如 javascript:)丢弃该键回落默认,不 fail。
|
|
67
|
+
if (value.startsWith("url:") && !/^url:https?:\/\/\S+$/i.test(value)) continue;
|
|
68
|
+
(icons ??= {})[key] = value;
|
|
69
|
+
}
|
|
70
|
+
if (icons && Object.keys(icons).length === 0) icons = undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
let followUp: BrandingFollowUp | undefined;
|
|
74
|
+
if (src.followUp !== undefined) {
|
|
75
|
+
if (!isRecord(src.followUp)) deny(file, `\`${at}.followUp\` must be a mapping`);
|
|
76
|
+
const fu = src.followUp as Record<string, unknown>;
|
|
77
|
+
for (const key of Object.keys(fu)) {
|
|
78
|
+
if (!FOLLOW_UP_KEYS.includes(key)) {
|
|
79
|
+
deny(file, `\`${at}.followUp.${key}\` is not a known field (allowed: ${FOLLOW_UP_KEYS.join(", ")})`);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
followUp = {};
|
|
83
|
+
if (fu.mode !== undefined) {
|
|
84
|
+
if (!isMode(fu.mode)) deny(file, `\`${at}.followUp.mode\` must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
|
|
85
|
+
followUp.mode = fu.mode;
|
|
86
|
+
}
|
|
87
|
+
if (fu.count !== undefined) {
|
|
88
|
+
const n = fu.count;
|
|
89
|
+
if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_COUNT) {
|
|
90
|
+
deny(file, `\`${at}.followUp.count\` must be an integer between 1 and ${MAX_COUNT}`);
|
|
91
|
+
}
|
|
92
|
+
followUp.count = n;
|
|
93
|
+
}
|
|
94
|
+
if (fu.static !== undefined) {
|
|
95
|
+
const list = fu.static;
|
|
96
|
+
if (!Array.isArray(list) || list.length > MAX_STATIC_ITEMS || list.some((s) => typeof s !== "string" || !s.trim())) {
|
|
97
|
+
deny(file, `\`${at}.followUp.static\` must be a list of at most ${MAX_STATIC_ITEMS} non-empty strings`);
|
|
98
|
+
}
|
|
99
|
+
followUp.static = (list as string[]).map((s) => (s.length > MAX_STATIC_CHARS ? s.slice(0, MAX_STATIC_CHARS) : s));
|
|
100
|
+
}
|
|
101
|
+
if (fu.systemPrompt !== undefined) {
|
|
102
|
+
if (typeof fu.systemPrompt !== "string" || fu.systemPrompt.trim() === "") {
|
|
103
|
+
deny(file, `\`${at}.followUp.systemPrompt\` must be a non-empty string`);
|
|
104
|
+
}
|
|
105
|
+
followUp.systemPrompt = fu.systemPrompt.length > MAX_PROMPT_CHARS ? fu.systemPrompt.slice(0, MAX_PROMPT_CHARS) : fu.systemPrompt;
|
|
106
|
+
}
|
|
107
|
+
if (fu.maxMessages !== undefined) {
|
|
108
|
+
const n = fu.maxMessages;
|
|
109
|
+
if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_MESSAGES) {
|
|
110
|
+
deny(file, `\`${at}.followUp.maxMessages\` must be an integer between 1 and ${MAX_MESSAGES}`);
|
|
111
|
+
}
|
|
112
|
+
followUp.maxMessages = n;
|
|
113
|
+
}
|
|
114
|
+
if (fu.timeoutMs !== undefined) {
|
|
115
|
+
const n = fu.timeoutMs;
|
|
116
|
+
if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_TIMEOUT_MS) {
|
|
117
|
+
deny(file, `\`${at}.followUp.timeoutMs\` must be an integer between 1 and ${MAX_TIMEOUT_MS}`);
|
|
118
|
+
}
|
|
119
|
+
followUp.timeoutMs = n;
|
|
120
|
+
}
|
|
121
|
+
if (Object.keys(followUp).length === 0) followUp = undefined;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (!icons && !followUp) return undefined;
|
|
125
|
+
return { ...(icons ? { icons } : {}), ...(followUp ? { followUp } : {}) };
|
|
126
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Checkpoint 存储:一次 Run 的**已完成 phase 产物**(M-14 / R-010 W4)。
|
|
3
|
+
*
|
|
4
|
+
* 它与 `run_jobs` 表分工明确,两者**不是同一个东西**:
|
|
5
|
+
*
|
|
6
|
+
* | | 粒度 | 谁写 | 用途 |
|
|
7
|
+
* | --- | --- | --- | --- |
|
|
8
|
+
* | `run_jobs` | 每个子会话一行 | 引擎派发前后 | 「跑到哪了」——进程被杀时靠它知道哪些 job 在飞 |
|
|
9
|
+
* | `run_checkpoints` | 每个已完成 phase 一份产物 | Run 收口 / 每 phase 完成 | 「续跑时跳过谁」——`resumeFrom` 的数据源(I7) |
|
|
10
|
+
*
|
|
11
|
+
* 为什么不合成一张表:`run_jobs` 要给**审计与对账**看(一行一个子会话,含失败原因),
|
|
12
|
+
* `run_checkpoints` 要给**续跑**用(一份产物可能对应多个子会话,如 parallel 的分支)。
|
|
13
|
+
* 两者基数不同(一个 phase 可能 1 行 checkpoint、N 行 job),合成就会有人被压扁。
|
|
14
|
+
*
|
|
15
|
+
* 崩溃语义:checkpoint 是「追加式」的——一次 Run 的每个 phase 完成后落一行,
|
|
16
|
+
* 不等 Run 结束。所以进程被杀时,已完成的 phase 全都留得住,续跑只重跑剩下的。
|
|
17
|
+
* 这正是 I7「续跑不重跑」在数据面成立的条件。
|
|
18
|
+
*/
|
|
19
|
+
import type { PhaseCheckpoint } from "./orchestrator/run-spec.ts";
|
|
20
|
+
import type { TokenUsage } from "@njuptlzf/agent-chat-protocol";
|
|
21
|
+
|
|
22
|
+
/** 一次 Run 的断点集合。 */
|
|
23
|
+
export interface RunCheckpoint {
|
|
24
|
+
readonly runId: string;
|
|
25
|
+
/** 按 phaseId 索引。 */
|
|
26
|
+
readonly phases: Readonly<Record<string, PhaseCheckpoint>>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** `run_jobs` 的一行:一个子会话的状态。 */
|
|
30
|
+
export interface RunJobRow {
|
|
31
|
+
readonly runId: string;
|
|
32
|
+
readonly phaseId: string;
|
|
33
|
+
readonly jobId: string;
|
|
34
|
+
/** 六态里的一个;写库时一定是 `queued` / `running` / 终态之一。 */
|
|
35
|
+
readonly state: string;
|
|
36
|
+
readonly usage: TokenUsage;
|
|
37
|
+
/** 第几次尝试(模型切换等)。 */
|
|
38
|
+
readonly attempt?: number;
|
|
39
|
+
/**
|
|
40
|
+
* 租约到期时刻(epoch ms)。运行中的 job 靠它判断「写这条记录的进程还活着吗」;
|
|
41
|
+
* 过期即视为孤儿,可被回收。这是跨进程安全的条件写基础(与 ledger 同手法)。
|
|
42
|
+
*/
|
|
43
|
+
readonly leaseUntil?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export interface CheckpointStore {
|
|
47
|
+
/**
|
|
48
|
+
* 记一个 phase 的断点。**幂等**:同一 `(runId, phaseId)` 重复写覆盖旧值
|
|
49
|
+
* (续跑成功后产物应该更新为最新一次的结果)。
|
|
50
|
+
*/
|
|
51
|
+
saveJob(runId: string, job: RunJobRow): Promise<void>;
|
|
52
|
+
/** 记一个 phase 完成的产物(I7 的数据源)。 */
|
|
53
|
+
savePhase(checkpoint: PhaseCheckpoint & { runId: string }): Promise<void>;
|
|
54
|
+
/** 读一次 Run 的全部断点;无记录返回 `undefined`(而不是空对象——两者语义不同)。 */
|
|
55
|
+
load(runId: string): Promise<RunCheckpoint | undefined>;
|
|
56
|
+
/** 该 Run 的 job 行(诊断 / 对账 / 回收孤儿)。 */
|
|
57
|
+
jobs(runId: string): Promise<RunJobRow[]>;
|
|
58
|
+
/** 把租约过期的在飞 job 标成 `blocked`(进程崩了的痕迹)。返回改动行数。 */
|
|
59
|
+
reclaimOrphans(runId: string, now?: number): Promise<number>;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 进程内实现(开发态 / 测试)。语义与 SQLite 版一致,只是不持久化——
|
|
64
|
+
* 所以它**不能**用来验「进程重启后还能续跑」,那条只能在 SQLite 版上验。
|
|
65
|
+
*/
|
|
66
|
+
export class MemoryCheckpointStore implements CheckpointStore {
|
|
67
|
+
private readonly phases = new Map<string, Map<string, PhaseCheckpoint>>();
|
|
68
|
+
private readonly jobRows = new Map<string, Map<string, RunJobRow>>();
|
|
69
|
+
|
|
70
|
+
async saveJob(runId: string, job: RunJobRow): Promise<void> {
|
|
71
|
+
const m = this.jobRows.get(runId) ?? new Map();
|
|
72
|
+
m.set(job.jobId, job);
|
|
73
|
+
this.jobRows.set(runId, m);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async savePhase(checkpoint: PhaseCheckpoint & { runId: string }): Promise<void> {
|
|
77
|
+
const m = this.phases.get(checkpoint.runId) ?? new Map();
|
|
78
|
+
const { runId: _runId, ...rest } = checkpoint;
|
|
79
|
+
m.set(checkpoint.phaseId, rest);
|
|
80
|
+
this.phases.set(checkpoint.runId, m);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async load(runId: string): Promise<RunCheckpoint | undefined> {
|
|
84
|
+
const m = this.phases.get(runId);
|
|
85
|
+
if (!m || m.size === 0) return undefined;
|
|
86
|
+
return { runId, phases: Object.fromEntries(m) };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async jobs(runId: string): Promise<RunJobRow[]> {
|
|
90
|
+
return [...(this.jobRows.get(runId)?.values() ?? [])];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async reclaimOrphans(runId: string, now = Date.now()): Promise<number> {
|
|
94
|
+
let n = 0;
|
|
95
|
+
for (const row of this.jobRows.get(runId)?.values() ?? []) {
|
|
96
|
+
if (row.state === "running" && row.leaseUntil !== undefined && row.leaseUntil <= now) {
|
|
97
|
+
// 就地替换:`readonly` 只在类型层,运行时换成一个新对象更清晰。
|
|
98
|
+
this.jobRows.get(runId)!.set(row.jobId, { ...row, state: "blocked" });
|
|
99
|
+
n += 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return n;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 把引擎产出的 `RunOutcome.checkpoints` 落库的便捷封装。 */
|
|
107
|
+
export async function persistCheckpoints(
|
|
108
|
+
store: CheckpointStore,
|
|
109
|
+
runId: string,
|
|
110
|
+
checkpoints: readonly PhaseCheckpoint[] | undefined,
|
|
111
|
+
): Promise<void> {
|
|
112
|
+
if (!checkpoints) return;
|
|
113
|
+
for (const cp of checkpoints) {
|
|
114
|
+
await store.savePhase({ ...cp, runId });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 读回一个 Run 的 `resumeFrom`(`RunSpec.resumeFrom` 的形状)。 */
|
|
119
|
+
export async function resumeFrom(store: CheckpointStore, runId: string): Promise<Record<string, PhaseCheckpoint> | undefined> {
|
|
120
|
+
const cp = await store.load(runId);
|
|
121
|
+
return cp === undefined ? undefined : { ...cp.phases };
|
|
122
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 生态组件清单(M-14 / R-010 W2):把「这个产品到底装配了什么」变成可观测事实。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:装配面此前对运维是黑盒——manifest 里写了什么、实际装上了什么、
|
|
5
|
+
* 哪个组件被准入判据拦下,全都只能靠读代码猜。启动时打一行清单,把这件事变成日志事实。
|
|
6
|
+
*
|
|
7
|
+
* 刻意做成**纯函数**(输入 `LoadedProduct`,输出清单),不读全局、不碰进程:
|
|
8
|
+
* 这样它能在测试里直接断言,而不是靠抓 `console.log`。
|
|
9
|
+
*
|
|
10
|
+
* 注意:清单描述的是「声明面」(manifest 说了什么),不是「运行期实际加载成功」。
|
|
11
|
+
* 实际失败由 pi 的 loader 报错兜住——本仓的原则是启动失败要响,不要静默降级。
|
|
12
|
+
*/
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import type { LoadedProduct } from "./manifest.ts";
|
|
15
|
+
|
|
16
|
+
export interface AssembledComponent {
|
|
17
|
+
/** 来源类别,便于按类过滤。 */
|
|
18
|
+
readonly kind: "mcp" | "confirm" | "memory" | "extension";
|
|
19
|
+
/** 标识:MCP 用 server 名,扩展用文件名,其余用固定词。 */
|
|
20
|
+
readonly name: string;
|
|
21
|
+
/** 附加说明(如 MCP 的传输方式),没有就不带。 */
|
|
22
|
+
readonly detail?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 列出该产品声明装配的生态组件。
|
|
27
|
+
*
|
|
28
|
+
* 顺序固定(mcp → confirm → memory → extension),保证日志可比对、测试可断言。
|
|
29
|
+
*/
|
|
30
|
+
export function describeComponents(product: LoadedProduct): AssembledComponent[] {
|
|
31
|
+
const out: AssembledComponent[] = [];
|
|
32
|
+
|
|
33
|
+
// MCP:manifest 的 `mcp:` 块声明了哪些 server。运行期可被 mcp-config 覆盖,
|
|
34
|
+
// 这里只描述出厂声明——那是产品作者写下的东西。
|
|
35
|
+
for (const [name, decl] of Object.entries(product.manifest.mcp ?? {})) {
|
|
36
|
+
const transport = (decl as { transport?: string }).transport;
|
|
37
|
+
out.push({
|
|
38
|
+
kind: "mcp",
|
|
39
|
+
name,
|
|
40
|
+
...(transport !== undefined ? { detail: transport } : {}),
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// 工具确认门:只在声明了 `confirmTools` 时装配。
|
|
45
|
+
const confirmTools = product.manifest.confirmTools ?? [];
|
|
46
|
+
if (confirmTools.length > 0) {
|
|
47
|
+
out.push({
|
|
48
|
+
kind: "confirm",
|
|
49
|
+
name: "confirmTools",
|
|
50
|
+
detail: `${confirmTools.length} tool(s)`,
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 作用域记忆:`agent.memory` 缺省为开(manifest.ts 的 `!== false` 口径),
|
|
55
|
+
// 所以这里只在显式关闭时不出现,避免把「默认开」说成「产品声明了」。
|
|
56
|
+
if (product.memoryEnabled) {
|
|
57
|
+
out.push({ kind: "memory", name: "scoped-memory", detail: "autoCapture" });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// 产品自带扩展文件:用文件名(不含目录),避免把部署路径写进日志。
|
|
61
|
+
for (const p of product.extensionPaths) {
|
|
62
|
+
out.push({ kind: "extension", name: path.basename(p) });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 生态组件的**准入判据**(M-14 / R-010 W2)。
|
|
3
|
+
*
|
|
4
|
+
* 背景:产品在自己仓里写一个适配文件、在 manifest 的 `agent.extensions` 声明路径,
|
|
5
|
+
* 就能把 pi 生态组件(含第三方 npm 包)装进会话,**平台仓零改动**。这条通道本来就有,
|
|
6
|
+
* 缺的是闸门——在此之前任何被声明的文件都会被直接加载,四条判据只写在设计稿里。
|
|
7
|
+
*
|
|
8
|
+
* 四条判据(设计稿 §1.1):
|
|
9
|
+
* ① 导出 `(pi: ExtensionAPI) => void` 工厂
|
|
10
|
+
* ② 不读 `process.env` / 不读 HOME、不写全局目录
|
|
11
|
+
* ③ 不自行 spawn 子进程
|
|
12
|
+
* ④ 不注册 TUI-only 组件(`rpc` 模式下本就是 no-op)
|
|
13
|
+
*
|
|
14
|
+
* **这里只做静态扫描,是启发式**:它能挡住「明显不该进服务端」的写法,
|
|
15
|
+
* 不能证明一个包绝对安全。所以措辞是「拒绝明显违反」,不是「认证安全」。
|
|
16
|
+
* 判据 ① 只能查有没有默认导出(形状对),真正是不是工厂由加载期报错兜住。
|
|
17
|
+
*
|
|
18
|
+
* 为什么扫源码文本而不是靠 tsc:跨层能力(读 env、spawn)在类型上完全合法,
|
|
19
|
+
* 编译器不会报错——与本仓 `boundary.test.ts` 同一条理由。
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
export interface AdmissionViolation {
|
|
23
|
+
/** 命中的判据编号,便于运维按文档查。 */
|
|
24
|
+
readonly criterion: 1 | 2 | 3 | 4;
|
|
25
|
+
/** 人类可读的原因,会直接进启动错误。 */
|
|
26
|
+
readonly reason: string;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 归一化源码,供扫描用。
|
|
31
|
+
*
|
|
32
|
+
* 两种模式,因为两类检查的对象不同:
|
|
33
|
+
* - `keepStrings: true`:只剥注释。用于**模块说明符**检查(`from "child_process"`
|
|
34
|
+
* 的说明符本身就在字符串里,剥了字符串就永远查不到)。
|
|
35
|
+
* - `keepStrings: false`:注释与字符串都剥。用于**标识符**检查(`process.env`、
|
|
36
|
+
* `registerCommand`),避免文案里提到这些词就误报。
|
|
37
|
+
*/
|
|
38
|
+
function normalize(source: string, keepStrings: boolean): string {
|
|
39
|
+
let out = "";
|
|
40
|
+
let i = 0;
|
|
41
|
+
let state: "code" | "line" | "block" | "single" | "double" | "template" = "code";
|
|
42
|
+
while (i < source.length) {
|
|
43
|
+
const ch = source[i]!;
|
|
44
|
+
const next = source[i + 1];
|
|
45
|
+
if (state === "code") {
|
|
46
|
+
if (ch === "/" && next === "/") { state = "line"; i += 2; continue; }
|
|
47
|
+
if (ch === "/" && next === "*") { state = "block"; i += 2; continue; }
|
|
48
|
+
if (ch === "'") { state = "single"; if (keepStrings) out += ch; i += 1; continue; }
|
|
49
|
+
if (ch === '"') { state = "double"; if (keepStrings) out += ch; i += 1; continue; }
|
|
50
|
+
if (ch === "`") { state = "template"; if (keepStrings) out += ch; i += 1; continue; }
|
|
51
|
+
out += ch;
|
|
52
|
+
i += 1;
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (state === "line") {
|
|
56
|
+
if (ch === "\n") { state = "code"; out += ch; }
|
|
57
|
+
i += 1;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
if (state === "block") {
|
|
61
|
+
if (ch === "*" && next === "/") { state = "code"; i += 2; continue; }
|
|
62
|
+
if (ch === "\n") out += ch; // 保留行号
|
|
63
|
+
i += 1;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
// 字符串态
|
|
67
|
+
if (ch === "\\") {
|
|
68
|
+
if (keepStrings) out += ch + (next ?? "");
|
|
69
|
+
i += 2;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
if (ch === "\n") out += ch;
|
|
73
|
+
const closing = (state === "single" && ch === "'") || (state === "double" && ch === '"') || (state === "template" && ch === "`");
|
|
74
|
+
if (keepStrings) out += ch;
|
|
75
|
+
if (closing) state = "code";
|
|
76
|
+
i += 1;
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 扫一个扩展文件,返回违反的判据。空数组 = 通过静态检查。
|
|
83
|
+
*
|
|
84
|
+
* `source` 传文件原文;`label` 只用于错误信息(一般是 manifest 里的相对路径)。
|
|
85
|
+
*/
|
|
86
|
+
export function auditExtensionSource(source: string, label: string): AdmissionViolation[] {
|
|
87
|
+
// 标识符检查用「剥注释+剥字符串」;模块说明符检查用「只剥注释」。
|
|
88
|
+
const code = normalize(source, false);
|
|
89
|
+
const withStrings = normalize(source, true);
|
|
90
|
+
const violations: AdmissionViolation[] = [];
|
|
91
|
+
|
|
92
|
+
// ① 形状:必须有默认导出(`export default ...`)。
|
|
93
|
+
if (!/\bexport\s+default\b/.test(code)) {
|
|
94
|
+
violations.push({
|
|
95
|
+
criterion: 1,
|
|
96
|
+
reason: `${label}: no default export (an extension must export a (pi) => void factory)`,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// ② 读环境 / HOME:宿主拥有全部外部资源,组件不该自己去摸。
|
|
101
|
+
if (/\bprocess\s*\.\s*env\b/.test(code)) {
|
|
102
|
+
violations.push({
|
|
103
|
+
criterion: 2,
|
|
104
|
+
reason: `${label}: reads process.env (the host owns configuration; pass options in instead)`,
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
if (/\bhomedir\s*\(\s*\)|process\s*\.\s*env\s*\.\s*HOME\b/.test(code) || /\bos\s*\.\s*homedir\b/.test(code)) {
|
|
108
|
+
violations.push({
|
|
109
|
+
criterion: 2,
|
|
110
|
+
reason: `${label}: reads the user home directory (pass a host-computed dir instead)`,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ③ 自行 spawn:服务端进程不该被组件拉出子进程。
|
|
115
|
+
if (/["'](?:node:)?child_process["']/.test(withStrings)) {
|
|
116
|
+
violations.push({
|
|
117
|
+
criterion: 3,
|
|
118
|
+
reason: `${label}: spawns or imports child_process (the host owns process lifetime)`,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// ④ TUI-only:rpc 模式下这些注册本来就是 no-op,收进来只会误导。
|
|
123
|
+
if (/["']@earendil-works\/pi-tui["']/.test(withStrings) || /\bpi\s*\.\s*register(?:Command|Theme|Component)\b/.test(code)) {
|
|
124
|
+
violations.push({
|
|
125
|
+
criterion: 4,
|
|
126
|
+
reason: `${label}: registers TUI-only surface (commands/themes/components are no-ops in rpc mode)`,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
return violations;
|
|
131
|
+
}
|