@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.
Files changed (55) hide show
  1. package/dist/branding-ui.d.ts +16 -0
  2. package/dist/branding-ui.js +119 -0
  3. package/dist/checkpoint-store.d.ts +78 -0
  4. package/dist/checkpoint-store.js +52 -0
  5. package/dist/components.d.ts +15 -0
  6. package/dist/components.js +50 -0
  7. package/dist/extension-admission.d.ts +32 -0
  8. package/dist/extension-admission.js +155 -0
  9. package/dist/flows.d.ts +49 -0
  10. package/dist/flows.js +208 -0
  11. package/dist/ledger.d.ts +90 -0
  12. package/dist/ledger.js +115 -0
  13. package/dist/main.js +14 -2
  14. package/dist/manifest.js +27 -1
  15. package/dist/orchestrator/engine.d.ts +132 -0
  16. package/dist/orchestrator/engine.js +1 -0
  17. package/dist/orchestrator/engines/fake.d.ts +14 -0
  18. package/dist/orchestrator/engines/fake.js +282 -0
  19. package/dist/orchestrator/engines/taskflow.d.ts +4 -0
  20. package/dist/orchestrator/engines/taskflow.js +541 -0
  21. package/dist/orchestrator/run-spec.d.ts +154 -0
  22. package/dist/orchestrator/run-spec.js +11 -0
  23. package/dist/persona-config.js +12 -0
  24. package/dist/server.d.ts +27 -2
  25. package/dist/server.js +595 -187
  26. package/dist/session.js +2 -1
  27. package/dist/sqlite-stores.d.ts +46 -6
  28. package/dist/sqlite-stores.js +292 -33
  29. package/dist/stores.d.ts +0 -36
  30. package/dist/stores.js +0 -27
  31. package/dist/suggestions.d.ts +60 -0
  32. package/dist/suggestions.js +107 -0
  33. package/dist/testing.d.ts +5 -4
  34. package/dist/testing.js +5 -4
  35. package/package.json +65 -64
  36. package/scripts/agentchat-integrate.mjs +852 -852
  37. package/src/branding-ui.ts +126 -0
  38. package/src/checkpoint-store.ts +122 -0
  39. package/src/components.ts +66 -0
  40. package/src/extension-admission.ts +131 -0
  41. package/src/flows.ts +244 -0
  42. package/src/ledger.ts +171 -0
  43. package/src/main.ts +16 -2
  44. package/src/manifest.ts +27 -1
  45. package/src/orchestrator/engine.ts +134 -0
  46. package/src/orchestrator/engines/fake.ts +330 -0
  47. package/src/orchestrator/engines/taskflow.ts +626 -0
  48. package/src/orchestrator/run-spec.ts +171 -0
  49. package/src/persona-config.ts +12 -1
  50. package/src/server.ts +611 -183
  51. package/src/session.ts +2 -1
  52. package/src/sqlite-stores.ts +343 -35
  53. package/src/stores.ts +0 -41
  54. package/src/suggestions.ts +146 -0
  55. package/src/testing.ts +4 -4
@@ -0,0 +1,16 @@
1
+ import type { Branding } from "@njuptlzf/agent-chat-protocol";
2
+ type BrandingUi = NonNullable<Branding["ui"]>;
3
+ /** 「下一步建议」的三态。全局(branding.ui.followUp.mode)与人格(PersonaUi.followUpMode)共用这一份。 */
4
+ export declare const FOLLOW_UP_MODES: readonly ["off", "static", "llm"];
5
+ export type FollowUpMode = (typeof FOLLOW_UP_MODES)[number];
6
+ /** 图标语义槽白名单:键是平台定义的槽名,不是组件名。新增视觉件时在这里登记。 */
7
+ export declare const ICON_SLOTS: readonly ["attachment"];
8
+ /**
9
+ * 校验并规范化 `branding.ui`(图标值 + 下一步建议配置)。
10
+ *
11
+ * 分级与人格 ui 同一套口径:未知键 / 形状错 = 启动期 fail-fast(manifest 是签入文件,
12
+ * 错别字必须响);单个图标值非法(如非 http(s) 的 url: 前缀)= 丢弃该键回落默认,不因
13
+ * 一个坏图标让服务起不来。返回 undefined 表示产品没配(或全被丢弃)。
14
+ */
15
+ export declare function parseBrandingUi(file: string, at: string, raw: unknown): BrandingUi | undefined;
16
+ export {};
@@ -0,0 +1,119 @@
1
+ /** 「下一步建议」的三态。全局(branding.ui.followUp.mode)与人格(PersonaUi.followUpMode)共用这一份。 */
2
+ export const FOLLOW_UP_MODES = ["off", "static", "llm"];
3
+ /** 图标语义槽白名单:键是平台定义的槽名,不是组件名。新增视觉件时在这里登记。 */
4
+ export const ICON_SLOTS = ["attachment"];
5
+ const FOLLOW_UP_KEYS = ["mode", "count", "static", "systemPrompt", "maxMessages", "timeoutMs"];
6
+ const MAX_ICON_VALUE = 512;
7
+ const MAX_STATIC_ITEMS = 10;
8
+ const MAX_STATIC_CHARS = 200;
9
+ const MAX_PROMPT_CHARS = 2000;
10
+ const MAX_COUNT = 5;
11
+ const MAX_MESSAGES = 20;
12
+ const MAX_TIMEOUT_MS = 30_000;
13
+ function deny(file, msg) {
14
+ throw new Error(`Invalid manifest ${file}: ${msg}`);
15
+ }
16
+ function isRecord(v) {
17
+ return !!v && typeof v === "object" && !Array.isArray(v);
18
+ }
19
+ function isMode(v) {
20
+ return typeof v === "string" && FOLLOW_UP_MODES.includes(v);
21
+ }
22
+ /**
23
+ * 校验并规范化 `branding.ui`(图标值 + 下一步建议配置)。
24
+ *
25
+ * 分级与人格 ui 同一套口径:未知键 / 形状错 = 启动期 fail-fast(manifest 是签入文件,
26
+ * 错别字必须响);单个图标值非法(如非 http(s) 的 url: 前缀)= 丢弃该键回落默认,不因
27
+ * 一个坏图标让服务起不来。返回 undefined 表示产品没配(或全被丢弃)。
28
+ */
29
+ export function parseBrandingUi(file, at, raw) {
30
+ if (raw === undefined)
31
+ return undefined;
32
+ if (!isRecord(raw))
33
+ deny(file, `\`${at}\` must be a mapping`);
34
+ const src = raw;
35
+ for (const key of Object.keys(src)) {
36
+ if (key !== "icons" && key !== "followUp") {
37
+ deny(file, `\`${at}.${key}\` is not a branding ui field (allowed: icons, followUp)`);
38
+ }
39
+ }
40
+ let icons;
41
+ if (src.icons !== undefined) {
42
+ if (!isRecord(src.icons))
43
+ deny(file, `\`${at}.icons\` must be a mapping`);
44
+ const srcIcons = src.icons;
45
+ for (const [key, value] of Object.entries(srcIcons)) {
46
+ if (!ICON_SLOTS.includes(key)) {
47
+ deny(file, `\`${at}.icons.${key}\` is not a known icon slot (allowed: ${ICON_SLOTS.join(", ")})`);
48
+ }
49
+ if (typeof value !== "string" || value.trim() === "") {
50
+ deny(file, `\`${at}.icons.${key}\` must be a non-empty string`);
51
+ }
52
+ if (value.length > MAX_ICON_VALUE) {
53
+ deny(file, `\`${at}.icons.${key}\` must be at most ${MAX_ICON_VALUE} characters`);
54
+ }
55
+ // url: 前缀只放行 http(s);别的协议(如 javascript:)丢弃该键回落默认,不 fail。
56
+ if (value.startsWith("url:") && !/^url:https?:\/\/\S+$/i.test(value))
57
+ continue;
58
+ (icons ??= {})[key] = value;
59
+ }
60
+ if (icons && Object.keys(icons).length === 0)
61
+ icons = undefined;
62
+ }
63
+ let followUp;
64
+ if (src.followUp !== undefined) {
65
+ if (!isRecord(src.followUp))
66
+ deny(file, `\`${at}.followUp\` must be a mapping`);
67
+ const fu = src.followUp;
68
+ for (const key of Object.keys(fu)) {
69
+ if (!FOLLOW_UP_KEYS.includes(key)) {
70
+ deny(file, `\`${at}.followUp.${key}\` is not a known field (allowed: ${FOLLOW_UP_KEYS.join(", ")})`);
71
+ }
72
+ }
73
+ followUp = {};
74
+ if (fu.mode !== undefined) {
75
+ if (!isMode(fu.mode))
76
+ deny(file, `\`${at}.followUp.mode\` must be one of ${FOLLOW_UP_MODES.join(" | ")}`);
77
+ followUp.mode = fu.mode;
78
+ }
79
+ if (fu.count !== undefined) {
80
+ const n = fu.count;
81
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_COUNT) {
82
+ deny(file, `\`${at}.followUp.count\` must be an integer between 1 and ${MAX_COUNT}`);
83
+ }
84
+ followUp.count = n;
85
+ }
86
+ if (fu.static !== undefined) {
87
+ const list = fu.static;
88
+ if (!Array.isArray(list) || list.length > MAX_STATIC_ITEMS || list.some((s) => typeof s !== "string" || !s.trim())) {
89
+ deny(file, `\`${at}.followUp.static\` must be a list of at most ${MAX_STATIC_ITEMS} non-empty strings`);
90
+ }
91
+ followUp.static = list.map((s) => (s.length > MAX_STATIC_CHARS ? s.slice(0, MAX_STATIC_CHARS) : s));
92
+ }
93
+ if (fu.systemPrompt !== undefined) {
94
+ if (typeof fu.systemPrompt !== "string" || fu.systemPrompt.trim() === "") {
95
+ deny(file, `\`${at}.followUp.systemPrompt\` must be a non-empty string`);
96
+ }
97
+ followUp.systemPrompt = fu.systemPrompt.length > MAX_PROMPT_CHARS ? fu.systemPrompt.slice(0, MAX_PROMPT_CHARS) : fu.systemPrompt;
98
+ }
99
+ if (fu.maxMessages !== undefined) {
100
+ const n = fu.maxMessages;
101
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_MESSAGES) {
102
+ deny(file, `\`${at}.followUp.maxMessages\` must be an integer between 1 and ${MAX_MESSAGES}`);
103
+ }
104
+ followUp.maxMessages = n;
105
+ }
106
+ if (fu.timeoutMs !== undefined) {
107
+ const n = fu.timeoutMs;
108
+ if (typeof n !== "number" || !Number.isInteger(n) || n < 1 || n > MAX_TIMEOUT_MS) {
109
+ deny(file, `\`${at}.followUp.timeoutMs\` must be an integer between 1 and ${MAX_TIMEOUT_MS}`);
110
+ }
111
+ followUp.timeoutMs = n;
112
+ }
113
+ if (Object.keys(followUp).length === 0)
114
+ followUp = undefined;
115
+ }
116
+ if (!icons && !followUp)
117
+ return undefined;
118
+ return { ...(icons ? { icons } : {}), ...(followUp ? { followUp } : {}) };
119
+ }
@@ -0,0 +1,78 @@
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
+ /** 一次 Run 的断点集合。 */
22
+ export interface RunCheckpoint {
23
+ readonly runId: string;
24
+ /** 按 phaseId 索引。 */
25
+ readonly phases: Readonly<Record<string, PhaseCheckpoint>>;
26
+ }
27
+ /** `run_jobs` 的一行:一个子会话的状态。 */
28
+ export interface RunJobRow {
29
+ readonly runId: string;
30
+ readonly phaseId: string;
31
+ readonly jobId: string;
32
+ /** 六态里的一个;写库时一定是 `queued` / `running` / 终态之一。 */
33
+ readonly state: string;
34
+ readonly usage: TokenUsage;
35
+ /** 第几次尝试(模型切换等)。 */
36
+ readonly attempt?: number;
37
+ /**
38
+ * 租约到期时刻(epoch ms)。运行中的 job 靠它判断「写这条记录的进程还活着吗」;
39
+ * 过期即视为孤儿,可被回收。这是跨进程安全的条件写基础(与 ledger 同手法)。
40
+ */
41
+ readonly leaseUntil?: number;
42
+ }
43
+ export interface CheckpointStore {
44
+ /**
45
+ * 记一个 phase 的断点。**幂等**:同一 `(runId, phaseId)` 重复写覆盖旧值
46
+ * (续跑成功后产物应该更新为最新一次的结果)。
47
+ */
48
+ saveJob(runId: string, job: RunJobRow): Promise<void>;
49
+ /** 记一个 phase 完成的产物(I7 的数据源)。 */
50
+ savePhase(checkpoint: PhaseCheckpoint & {
51
+ runId: string;
52
+ }): Promise<void>;
53
+ /** 读一次 Run 的全部断点;无记录返回 `undefined`(而不是空对象——两者语义不同)。 */
54
+ load(runId: string): Promise<RunCheckpoint | undefined>;
55
+ /** 该 Run 的 job 行(诊断 / 对账 / 回收孤儿)。 */
56
+ jobs(runId: string): Promise<RunJobRow[]>;
57
+ /** 把租约过期的在飞 job 标成 `blocked`(进程崩了的痕迹)。返回改动行数。 */
58
+ reclaimOrphans(runId: string, now?: number): Promise<number>;
59
+ }
60
+ /**
61
+ * 进程内实现(开发态 / 测试)。语义与 SQLite 版一致,只是不持久化——
62
+ * 所以它**不能**用来验「进程重启后还能续跑」,那条只能在 SQLite 版上验。
63
+ */
64
+ export declare class MemoryCheckpointStore implements CheckpointStore {
65
+ private readonly phases;
66
+ private readonly jobRows;
67
+ saveJob(runId: string, job: RunJobRow): Promise<void>;
68
+ savePhase(checkpoint: PhaseCheckpoint & {
69
+ runId: string;
70
+ }): Promise<void>;
71
+ load(runId: string): Promise<RunCheckpoint | undefined>;
72
+ jobs(runId: string): Promise<RunJobRow[]>;
73
+ reclaimOrphans(runId: string, now?: number): Promise<number>;
74
+ }
75
+ /** 把引擎产出的 `RunOutcome.checkpoints` 落库的便捷封装。 */
76
+ export declare function persistCheckpoints(store: CheckpointStore, runId: string, checkpoints: readonly PhaseCheckpoint[] | undefined): Promise<void>;
77
+ /** 读回一个 Run 的 `resumeFrom`(`RunSpec.resumeFrom` 的形状)。 */
78
+ export declare function resumeFrom(store: CheckpointStore, runId: string): Promise<Record<string, PhaseCheckpoint> | undefined>;
@@ -0,0 +1,52 @@
1
+ /**
2
+ * 进程内实现(开发态 / 测试)。语义与 SQLite 版一致,只是不持久化——
3
+ * 所以它**不能**用来验「进程重启后还能续跑」,那条只能在 SQLite 版上验。
4
+ */
5
+ export class MemoryCheckpointStore {
6
+ phases = new Map();
7
+ jobRows = new Map();
8
+ async saveJob(runId, job) {
9
+ const m = this.jobRows.get(runId) ?? new Map();
10
+ m.set(job.jobId, job);
11
+ this.jobRows.set(runId, m);
12
+ }
13
+ async savePhase(checkpoint) {
14
+ const m = this.phases.get(checkpoint.runId) ?? new Map();
15
+ const { runId: _runId, ...rest } = checkpoint;
16
+ m.set(checkpoint.phaseId, rest);
17
+ this.phases.set(checkpoint.runId, m);
18
+ }
19
+ async load(runId) {
20
+ const m = this.phases.get(runId);
21
+ if (!m || m.size === 0)
22
+ return undefined;
23
+ return { runId, phases: Object.fromEntries(m) };
24
+ }
25
+ async jobs(runId) {
26
+ return [...(this.jobRows.get(runId)?.values() ?? [])];
27
+ }
28
+ async reclaimOrphans(runId, now = Date.now()) {
29
+ let n = 0;
30
+ for (const row of this.jobRows.get(runId)?.values() ?? []) {
31
+ if (row.state === "running" && row.leaseUntil !== undefined && row.leaseUntil <= now) {
32
+ // 就地替换:`readonly` 只在类型层,运行时换成一个新对象更清晰。
33
+ this.jobRows.get(runId).set(row.jobId, { ...row, state: "blocked" });
34
+ n += 1;
35
+ }
36
+ }
37
+ return n;
38
+ }
39
+ }
40
+ /** 把引擎产出的 `RunOutcome.checkpoints` 落库的便捷封装。 */
41
+ export async function persistCheckpoints(store, runId, checkpoints) {
42
+ if (!checkpoints)
43
+ return;
44
+ for (const cp of checkpoints) {
45
+ await store.savePhase({ ...cp, runId });
46
+ }
47
+ }
48
+ /** 读回一个 Run 的 `resumeFrom`(`RunSpec.resumeFrom` 的形状)。 */
49
+ export async function resumeFrom(store, runId) {
50
+ const cp = await store.load(runId);
51
+ return cp === undefined ? undefined : { ...cp.phases };
52
+ }
@@ -0,0 +1,15 @@
1
+ import type { LoadedProduct } from "./manifest.ts";
2
+ export interface AssembledComponent {
3
+ /** 来源类别,便于按类过滤。 */
4
+ readonly kind: "mcp" | "confirm" | "memory" | "extension";
5
+ /** 标识:MCP 用 server 名,扩展用文件名,其余用固定词。 */
6
+ readonly name: string;
7
+ /** 附加说明(如 MCP 的传输方式),没有就不带。 */
8
+ readonly detail?: string;
9
+ }
10
+ /**
11
+ * 列出该产品声明装配的生态组件。
12
+ *
13
+ * 顺序固定(mcp → confirm → memory → extension),保证日志可比对、测试可断言。
14
+ */
15
+ export declare function describeComponents(product: LoadedProduct): AssembledComponent[];
@@ -0,0 +1,50 @@
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
+ /**
15
+ * 列出该产品声明装配的生态组件。
16
+ *
17
+ * 顺序固定(mcp → confirm → memory → extension),保证日志可比对、测试可断言。
18
+ */
19
+ export function describeComponents(product) {
20
+ const out = [];
21
+ // MCP:manifest 的 `mcp:` 块声明了哪些 server。运行期可被 mcp-config 覆盖,
22
+ // 这里只描述出厂声明——那是产品作者写下的东西。
23
+ for (const [name, decl] of Object.entries(product.manifest.mcp ?? {})) {
24
+ const transport = decl.transport;
25
+ out.push({
26
+ kind: "mcp",
27
+ name,
28
+ ...(transport !== undefined ? { detail: transport } : {}),
29
+ });
30
+ }
31
+ // 工具确认门:只在声明了 `confirmTools` 时装配。
32
+ const confirmTools = product.manifest.confirmTools ?? [];
33
+ if (confirmTools.length > 0) {
34
+ out.push({
35
+ kind: "confirm",
36
+ name: "confirmTools",
37
+ detail: `${confirmTools.length} tool(s)`,
38
+ });
39
+ }
40
+ // 作用域记忆:`agent.memory` 缺省为开(manifest.ts 的 `!== false` 口径),
41
+ // 所以这里只在显式关闭时不出现,避免把「默认开」说成「产品声明了」。
42
+ if (product.memoryEnabled) {
43
+ out.push({ kind: "memory", name: "scoped-memory", detail: "autoCapture" });
44
+ }
45
+ // 产品自带扩展文件:用文件名(不含目录),避免把部署路径写进日志。
46
+ for (const p of product.extensionPaths) {
47
+ out.push({ kind: "extension", name: path.basename(p) });
48
+ }
49
+ return out;
50
+ }
@@ -0,0 +1,32 @@
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
+ export interface AdmissionViolation {
22
+ /** 命中的判据编号,便于运维按文档查。 */
23
+ readonly criterion: 1 | 2 | 3 | 4;
24
+ /** 人类可读的原因,会直接进启动错误。 */
25
+ readonly reason: string;
26
+ }
27
+ /**
28
+ * 扫一个扩展文件,返回违反的判据。空数组 = 通过静态检查。
29
+ *
30
+ * `source` 传文件原文;`label` 只用于错误信息(一般是 manifest 里的相对路径)。
31
+ */
32
+ export declare function auditExtensionSource(source: string, label: string): AdmissionViolation[];
@@ -0,0 +1,155 @@
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
+ * 归一化源码,供扫描用。
23
+ *
24
+ * 两种模式,因为两类检查的对象不同:
25
+ * - `keepStrings: true`:只剥注释。用于**模块说明符**检查(`from "child_process"`
26
+ * 的说明符本身就在字符串里,剥了字符串就永远查不到)。
27
+ * - `keepStrings: false`:注释与字符串都剥。用于**标识符**检查(`process.env`、
28
+ * `registerCommand`),避免文案里提到这些词就误报。
29
+ */
30
+ function normalize(source, keepStrings) {
31
+ let out = "";
32
+ let i = 0;
33
+ let state = "code";
34
+ while (i < source.length) {
35
+ const ch = source[i];
36
+ const next = source[i + 1];
37
+ if (state === "code") {
38
+ if (ch === "/" && next === "/") {
39
+ state = "line";
40
+ i += 2;
41
+ continue;
42
+ }
43
+ if (ch === "/" && next === "*") {
44
+ state = "block";
45
+ i += 2;
46
+ continue;
47
+ }
48
+ if (ch === "'") {
49
+ state = "single";
50
+ if (keepStrings)
51
+ out += ch;
52
+ i += 1;
53
+ continue;
54
+ }
55
+ if (ch === '"') {
56
+ state = "double";
57
+ if (keepStrings)
58
+ out += ch;
59
+ i += 1;
60
+ continue;
61
+ }
62
+ if (ch === "`") {
63
+ state = "template";
64
+ if (keepStrings)
65
+ out += ch;
66
+ i += 1;
67
+ continue;
68
+ }
69
+ out += ch;
70
+ i += 1;
71
+ continue;
72
+ }
73
+ if (state === "line") {
74
+ if (ch === "\n") {
75
+ state = "code";
76
+ out += ch;
77
+ }
78
+ i += 1;
79
+ continue;
80
+ }
81
+ if (state === "block") {
82
+ if (ch === "*" && next === "/") {
83
+ state = "code";
84
+ i += 2;
85
+ continue;
86
+ }
87
+ if (ch === "\n")
88
+ out += ch; // 保留行号
89
+ i += 1;
90
+ continue;
91
+ }
92
+ // 字符串态
93
+ if (ch === "\\") {
94
+ if (keepStrings)
95
+ out += ch + (next ?? "");
96
+ i += 2;
97
+ continue;
98
+ }
99
+ if (ch === "\n")
100
+ out += ch;
101
+ const closing = (state === "single" && ch === "'") || (state === "double" && ch === '"') || (state === "template" && ch === "`");
102
+ if (keepStrings)
103
+ out += ch;
104
+ if (closing)
105
+ state = "code";
106
+ i += 1;
107
+ }
108
+ return out;
109
+ }
110
+ /**
111
+ * 扫一个扩展文件,返回违反的判据。空数组 = 通过静态检查。
112
+ *
113
+ * `source` 传文件原文;`label` 只用于错误信息(一般是 manifest 里的相对路径)。
114
+ */
115
+ export function auditExtensionSource(source, label) {
116
+ // 标识符检查用「剥注释+剥字符串」;模块说明符检查用「只剥注释」。
117
+ const code = normalize(source, false);
118
+ const withStrings = normalize(source, true);
119
+ const violations = [];
120
+ // ① 形状:必须有默认导出(`export default ...`)。
121
+ if (!/\bexport\s+default\b/.test(code)) {
122
+ violations.push({
123
+ criterion: 1,
124
+ reason: `${label}: no default export (an extension must export a (pi) => void factory)`,
125
+ });
126
+ }
127
+ // ② 读环境 / HOME:宿主拥有全部外部资源,组件不该自己去摸。
128
+ if (/\bprocess\s*\.\s*env\b/.test(code)) {
129
+ violations.push({
130
+ criterion: 2,
131
+ reason: `${label}: reads process.env (the host owns configuration; pass options in instead)`,
132
+ });
133
+ }
134
+ if (/\bhomedir\s*\(\s*\)|process\s*\.\s*env\s*\.\s*HOME\b/.test(code) || /\bos\s*\.\s*homedir\b/.test(code)) {
135
+ violations.push({
136
+ criterion: 2,
137
+ reason: `${label}: reads the user home directory (pass a host-computed dir instead)`,
138
+ });
139
+ }
140
+ // ③ 自行 spawn:服务端进程不该被组件拉出子进程。
141
+ if (/["'](?:node:)?child_process["']/.test(withStrings)) {
142
+ violations.push({
143
+ criterion: 3,
144
+ reason: `${label}: spawns or imports child_process (the host owns process lifetime)`,
145
+ });
146
+ }
147
+ // ④ TUI-only:rpc 模式下这些注册本来就是 no-op,收进来只会误导。
148
+ if (/["']@earendil-works\/pi-tui["']/.test(withStrings) || /\bpi\s*\.\s*register(?:Command|Theme|Component)\b/.test(code)) {
149
+ violations.push({
150
+ criterion: 4,
151
+ reason: `${label}: registers TUI-only surface (commands/themes/components are no-ops in rpc mode)`,
152
+ });
153
+ }
154
+ return violations;
155
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * 把产品 manifest 声明的 `agent.flows` 翻成平台内部的 `RunSpec`(M-14 / R-010 W4)。
3
+ *
4
+ * ## 为什么这一层必须存在
5
+ *
6
+ * 平台给「机制」,产品给「编制」——`ProductFlow` 是产品的声明面(它只填
7
+ * 成员、任务、依赖),`RunSpec` 是平台的执行面(编排层认的形状)。两者刻意不同:
8
+ * 产品不该知道 `JobSpec.tools`、`PhaseKind`、`ResumePoint` 这些东西,
9
+ * 那是平台实现细节;平台也不该被产品的字段名绑死(改个 yaml 键就动内核)。
10
+ *
11
+ * 于是这个文件是**唯一的翻译点**:产品改声明 → 这里翻译 → 编排层照旧。
12
+ *
13
+ * ## 校验的口径:启动期 fail-closed,运行期不再猜
14
+ *
15
+ * `validateFlows` 在 `loadProduct` 时跑(写坏一个 flow 产品就起不来),
16
+ * 与「prompt 文件缺失就启动失败」同一条纪律。运行期 `toRunSpec` 只做无脑翻译,
17
+ * 不再校验——已经验过一次的东西,第二次校验只会让错误位置变模糊。
18
+ *
19
+ * 唯一在运行期还要判的是**「flow 里引用的成员是不是已声明人格」**——那条也在
20
+ * 启动期验了,所以运行期只负责报一个说得清的 400(而不是抛栈)。
21
+ */
22
+ import type { LoadedProduct } from "./manifest.ts";
23
+ import type { RunSpec } from "./orchestrator/run-spec.ts";
24
+ /** 校验失败一律抛这个,让 `loadProduct` 的报错带上可定位的位置。 */
25
+ export declare function flowFail(manifestFile: string, msg: string): never;
26
+ /** 已声明的人格 id 集合(默认助手 ∪ personas.*)——流程的成员只能从这里取。 */
27
+ export declare function legalMembers(product: LoadedProduct): Set<string>;
28
+ /**
29
+ * 启动期校验全部 flow。**写坏一个就起不来**——理由与 personas 写坏 prompt 路径
30
+ * 一样:等到第一次请求才炸,用户看到的是「服务不可用」,运维看到的是空日志。
31
+ */
32
+ export declare function validateFlows(product: LoadedProduct): void;
33
+ /** 抽出 `{steps.<id>.output}` 里的 `<id>`。 */
34
+ export declare function stepRefs(task: string): string[];
35
+ /**
36
+ * 运行期翻译:`ProductFlow` + 用户消息 → `RunSpec`。
37
+ *
38
+ * **不做校验**(启动期已验),但有一个运行期必须处理的语义:
39
+ * 用户消息要能进 flow。做法是把它作为 `{input}` 占位符的来源——
40
+ *
41
+ * - 若某个入口 phase(无 dependsOn)的 task 里写了 `{input}`,就替换成用户消息;
42
+ * - 否则把用户消息**附在**入口 phase 的 task 后面(换行分隔)。
43
+ *
44
+ * 为什么不是「总是追加」:有的流程是纯定时的(比如「体检一下当前状态」),
45
+ * 用户那句话只是触发词,塞进 prompt 反而干扰。声明方用 `{input}` 精确控制。
46
+ */
47
+ export declare function toRunSpec(product: LoadedProduct, flowId: string, input: string, runId: string): RunSpec | {
48
+ readonly error: string;
49
+ };