@njuptlzf/agent-chat-server 0.3.0 → 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 (46) hide show
  1. package/dist/checkpoint-store.d.ts +78 -0
  2. package/dist/checkpoint-store.js +52 -0
  3. package/dist/components.d.ts +15 -0
  4. package/dist/components.js +50 -0
  5. package/dist/extension-admission.d.ts +32 -0
  6. package/dist/extension-admission.js +155 -0
  7. package/dist/flows.d.ts +49 -0
  8. package/dist/flows.js +208 -0
  9. package/dist/ledger.d.ts +90 -0
  10. package/dist/ledger.js +115 -0
  11. package/dist/main.js +14 -2
  12. package/dist/manifest.js +14 -1
  13. package/dist/orchestrator/engine.d.ts +132 -0
  14. package/dist/orchestrator/engine.js +1 -0
  15. package/dist/orchestrator/engines/fake.d.ts +14 -0
  16. package/dist/orchestrator/engines/fake.js +282 -0
  17. package/dist/orchestrator/engines/taskflow.d.ts +4 -0
  18. package/dist/orchestrator/engines/taskflow.js +541 -0
  19. package/dist/orchestrator/run-spec.d.ts +154 -0
  20. package/dist/orchestrator/run-spec.js +11 -0
  21. package/dist/server.d.ts +21 -2
  22. package/dist/server.js +543 -187
  23. package/dist/sqlite-stores.d.ts +46 -6
  24. package/dist/sqlite-stores.js +292 -33
  25. package/dist/stores.d.ts +0 -36
  26. package/dist/stores.js +0 -27
  27. package/dist/testing.d.ts +5 -4
  28. package/dist/testing.js +5 -4
  29. package/package.json +7 -6
  30. package/scripts/agentchat-integrate.mjs +853 -853
  31. package/src/checkpoint-store.ts +122 -0
  32. package/src/components.ts +66 -0
  33. package/src/extension-admission.ts +131 -0
  34. package/src/flows.ts +244 -0
  35. package/src/ledger.ts +171 -0
  36. package/src/main.ts +16 -2
  37. package/src/manifest.ts +14 -1
  38. package/src/orchestrator/engine.ts +134 -0
  39. package/src/orchestrator/engines/fake.ts +330 -0
  40. package/src/orchestrator/engines/taskflow.ts +626 -0
  41. package/src/orchestrator/run-spec.ts +171 -0
  42. package/src/server.ts +553 -183
  43. package/src/session.ts +689 -689
  44. package/src/sqlite-stores.ts +343 -35
  45. package/src/stores.ts +0 -41
  46. package/src/testing.ts +4 -4
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Ledger:**预留-结算**额度账本(M-14 / R-010 W3)。
3
+ *
4
+ * 替换旧的 `QuotaGate.check/record`(先查后跑、事后记账)。旧模型在并发下必然超发:
5
+ * N 个请求同时 `check` 时都还没 `record`,于是全部通过——实测超发 140%。
6
+ *
7
+ * 新模型只有一条规则:**先占位,再开跑;跑完按实际多退少补。**
8
+ *
9
+ * ```
10
+ * reserve(operationId, caps) ── 事务内「今日已完成 + 在飞预留」对上限,占 1 个 run 位
11
+ * ├─ ok → 允许调模型
12
+ * └─ !ok → 429,一个 token 都不花
13
+ * settle(operationId, tokens) ── 释放占位并记入 quota;**幂等**(重复调用只生效一次)
14
+ * release(operationId) ── 开跑前失败(如余额不足)时归还占位
15
+ * ```
16
+ *
17
+ * 崩溃安全:预留带 `expires_at`,读路径一律只认未过期的预留。
18
+ * 进程崩了不会永久占着额度——不需要「启动时清理孤儿」这种容易漏的逻辑。
19
+ *
20
+ * **明确的能力边界**:跑的次数(run 位)在并发下是精确的;**token 上限做不到精确**,
21
+ * 因为一次 run 会花多少 token 事前不可知。reserve 只能保证「已达上限就不再开新 run」,
22
+ * 在飞的那几个仍可能把它顶过去。要精确,得先有「单次 run 的 token 上限」这一配置
23
+ * (见架构稿 §6.1 待办 T3)。
24
+ */
25
+ import { type QuotaCaps } from "./stores.ts";
26
+ /** 一次预留的句柄。`operationId` 由调用方生成(一请求一个),是幂等键。 */
27
+ export interface LedgerReservation {
28
+ readonly operationId: string;
29
+ /** 过期时刻(epoch ms)。过期后该占位不再计入在飞量。 */
30
+ readonly expiresAt: number;
31
+ }
32
+ export type ReserveOutcome = {
33
+ readonly ok: true;
34
+ readonly reservation: LedgerReservation;
35
+ } | {
36
+ readonly ok: false;
37
+ readonly reason: string;
38
+ };
39
+ export interface ReserveInput {
40
+ readonly userId: string;
41
+ readonly persona: string;
42
+ /** 现算上限(角色 × 会员档)。缺省项 = 不限。 */
43
+ readonly caps: QuotaCaps | undefined;
44
+ /** 幂等键:同一 operationId 重复 reserve 返回同一预留。 */
45
+ readonly operationId: string;
46
+ /** 预留存活时间,默认 1 小时(长会话不至于中途失效)。 */
47
+ readonly ttlMs?: number;
48
+ }
49
+ export interface SettleInput {
50
+ readonly operationId: string;
51
+ readonly userId: string;
52
+ readonly persona: string;
53
+ /** 实际消耗的 token;`0` 也照常收口(只释放占位)。 */
54
+ readonly tokens: number;
55
+ }
56
+ export type SettleOutcome = "settled" | "already";
57
+ export interface Ledger {
58
+ reserve(input: ReserveInput): Promise<ReserveOutcome>;
59
+ settle(input: SettleInput): Promise<SettleOutcome>;
60
+ /** 归还预留(开跑前失败时用)。已结算的预留不受影响。 */
61
+ release(operationId: string): Promise<void>;
62
+ /** whoami 的配额展示。 */
63
+ todayStats(userId: string, persona: string): Promise<{
64
+ runsToday: number;
65
+ tokensToday: number;
66
+ }>;
67
+ /** 把过期的在飞预留标成 expired。读路径已按时间过滤,调用它不是正确性所需。 */
68
+ sweepExpired?(now?: number): Promise<number>;
69
+ }
70
+ /** 预留默认存活时间:1 小时。 */
71
+ export declare const RESERVATION_TTL_MS: number;
72
+ /** 进程内实现(开发态 / 测试)。并发语义与 SQLite 版一致,只是没有持久化。 */
73
+ export declare class MemoryLedger implements Ledger {
74
+ private readonly dailyTokens;
75
+ private readonly now;
76
+ private readonly rows;
77
+ private readonly used;
78
+ private readonly runs;
79
+ constructor(dailyTokens: number | undefined, now?: () => number);
80
+ private static day;
81
+ private static key;
82
+ reserve(input: ReserveInput): Promise<ReserveOutcome>;
83
+ settle(input: SettleInput): Promise<SettleOutcome>;
84
+ release(operationId: string): Promise<void>;
85
+ todayStats(userId: string, persona: string): Promise<{
86
+ runsToday: number;
87
+ tokensToday: number;
88
+ }>;
89
+ sweepExpired(now?: number): Promise<number>;
90
+ }
package/dist/ledger.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Ledger:**预留-结算**额度账本(M-14 / R-010 W3)。
3
+ *
4
+ * 替换旧的 `QuotaGate.check/record`(先查后跑、事后记账)。旧模型在并发下必然超发:
5
+ * N 个请求同时 `check` 时都还没 `record`,于是全部通过——实测超发 140%。
6
+ *
7
+ * 新模型只有一条规则:**先占位,再开跑;跑完按实际多退少补。**
8
+ *
9
+ * ```
10
+ * reserve(operationId, caps) ── 事务内「今日已完成 + 在飞预留」对上限,占 1 个 run 位
11
+ * ├─ ok → 允许调模型
12
+ * └─ !ok → 429,一个 token 都不花
13
+ * settle(operationId, tokens) ── 释放占位并记入 quota;**幂等**(重复调用只生效一次)
14
+ * release(operationId) ── 开跑前失败(如余额不足)时归还占位
15
+ * ```
16
+ *
17
+ * 崩溃安全:预留带 `expires_at`,读路径一律只认未过期的预留。
18
+ * 进程崩了不会永久占着额度——不需要「启动时清理孤儿」这种容易漏的逻辑。
19
+ *
20
+ * **明确的能力边界**:跑的次数(run 位)在并发下是精确的;**token 上限做不到精确**,
21
+ * 因为一次 run 会花多少 token 事前不可知。reserve 只能保证「已达上限就不再开新 run」,
22
+ * 在飞的那几个仍可能把它顶过去。要精确,得先有「单次 run 的 token 上限」这一配置
23
+ * (见架构稿 §6.1 待办 T3)。
24
+ */
25
+ import { quotaBlockedReason } from "./stores.js";
26
+ /** 预留默认存活时间:1 小时。 */
27
+ export const RESERVATION_TTL_MS = 60 * 60 * 1000;
28
+ /** 进程内实现(开发态 / 测试)。并发语义与 SQLite 版一致,只是没有持久化。 */
29
+ export class MemoryLedger {
30
+ dailyTokens;
31
+ now;
32
+ rows = new Map();
33
+ used = new Map();
34
+ runs = new Map();
35
+ constructor(dailyTokens, now = () => Date.now()) {
36
+ this.dailyTokens = dailyTokens;
37
+ this.now = now;
38
+ }
39
+ static day(now) {
40
+ return new Date(now).toISOString().slice(0, 10);
41
+ }
42
+ static key(userId, persona, day) {
43
+ return `${userId}\u0000${persona}\u0000${day}`;
44
+ }
45
+ async reserve(input) {
46
+ const now = this.now();
47
+ const day = MemoryLedger.day(now);
48
+ const key = MemoryLedger.key(input.userId, input.persona, day);
49
+ const existing = this.rows.get(input.operationId);
50
+ if (existing) {
51
+ if (existing.state === "reserved" && existing.expiresAt > now) {
52
+ return { ok: true, reservation: { operationId: input.operationId, expiresAt: existing.expiresAt } };
53
+ }
54
+ return { ok: false, reason: "this operation already ran (duplicate request)" };
55
+ }
56
+ // 今日已完成 + 在飞(未过期)对 run 上限。
57
+ const runCap = input.caps?.runCap;
58
+ if (runCap !== undefined && runCap > 0) {
59
+ const inFlight = [...this.rows.values()].filter((r) => r.day === day && r.state === "reserved" && r.expiresAt > now).length;
60
+ const used = this.runs.get(key) ?? 0;
61
+ if (used + inFlight >= runCap) {
62
+ return {
63
+ ok: false,
64
+ reason: quotaBlockedReason("runs", { runCap, tokenCap: input.caps?.tokenCap ?? this.dailyTokens }),
65
+ };
66
+ }
67
+ }
68
+ const tokenCap = input.caps?.tokenCap ?? this.dailyTokens;
69
+ if (tokenCap !== undefined && (this.used.get(key) ?? 0) >= tokenCap) {
70
+ return { ok: false, reason: quotaBlockedReason("tokens", { runCap, tokenCap }) };
71
+ }
72
+ const expiresAt = now + (input.ttlMs ?? RESERVATION_TTL_MS);
73
+ this.rows.set(input.operationId, {
74
+ userId: input.userId,
75
+ persona: input.persona,
76
+ day,
77
+ state: "reserved",
78
+ expiresAt,
79
+ });
80
+ return { ok: true, reservation: { operationId: input.operationId, expiresAt } };
81
+ }
82
+ async settle(input) {
83
+ const row = this.rows.get(input.operationId);
84
+ // 没有预留 → 不记账(与 SQLite 版的条件更新一致):结算必须对应一次真实占位,
85
+ // 否则「settle 一个不存在的 operationId」就成了绕开额度的后门。
86
+ if (!row || row.state !== "reserved")
87
+ return "already";
88
+ row.state = "settled";
89
+ const key = MemoryLedger.key(input.userId, input.persona, MemoryLedger.day(this.now()));
90
+ if (input.tokens > 0)
91
+ this.used.set(key, (this.used.get(key) ?? 0) + input.tokens);
92
+ this.runs.set(key, (this.runs.get(key) ?? 0) + 1);
93
+ return "settled";
94
+ }
95
+ async release(operationId) {
96
+ const row = this.rows.get(operationId);
97
+ if (row && row.state === "reserved")
98
+ row.state = "released";
99
+ }
100
+ async todayStats(userId, persona) {
101
+ const day = MemoryLedger.day(this.now());
102
+ const key = MemoryLedger.key(userId, persona, day);
103
+ return { runsToday: this.runs.get(key) ?? 0, tokensToday: this.used.get(key) ?? 0 };
104
+ }
105
+ async sweepExpired(now = this.now()) {
106
+ let n = 0;
107
+ for (const row of this.rows.values()) {
108
+ if (row.state === "reserved" && row.expiresAt <= now) {
109
+ row.state = "released";
110
+ n += 1;
111
+ }
112
+ }
113
+ return n;
114
+ }
115
+ }
package/dist/main.js CHANGED
@@ -7,9 +7,10 @@ import { createMcpConfigStore } from "./mcp-config.js";
7
7
  import { createPersonaConfigStore } from "./persona-config.js";
8
8
  import { initProductRoutes, loadProductAssembly, loadProductRoutes } from "./product-routes.js";
9
9
  import { createChatServer } from "./server.js";
10
+ import { describeComponents } from "./components.js";
10
11
  import { createModelRuntime } from "./session.js";
11
12
  import { createAdminAuth, createJwtAuth, insecureHeaderAuth } from "./stores.js";
12
- import { openDatabase, SqliteAccountState, SqliteAudit, SqliteBilling, SqliteHistoryStore, SqliteMembership, SqliteMemberPool, SqliteQuotaGate, SqliteRunLog } from "./sqlite-stores.js";
13
+ import { openDatabase, SqliteAccountState, SqliteAudit, SqliteBilling, SqliteCheckpointStore, SqliteHistoryStore, SqliteMembership, SqliteMemberPool, SqliteLedger, SqliteRunLog } from "./sqlite-stores.js";
13
14
  import { billingUsage } from "./usage-report.js";
14
15
  const productDir = process.env.PRODUCT_DIR;
15
16
  if (!productDir) {
@@ -100,10 +101,12 @@ const deps = {
100
101
  personaConfig,
101
102
  toolFactory,
102
103
  history: new SqliteHistoryStore(db),
103
- quota: new SqliteQuotaGate(db, product.manifest.agent.limits?.dailyTokenQuota),
104
+ ledger: new SqliteLedger(db, product.manifest.agent.limits?.dailyTokenQuota),
104
105
  authenticate: jwtSecret ? createJwtAuth(jwtSecret) : insecureHeaderAuth,
105
106
  dataDir,
106
107
  runLog: new SqliteRunLog(db),
108
+ // 多 phase 断点(W4):主链恒装配。单 phase 不读它,缺库也不会影响档 1。
109
+ checkpoints: new SqliteCheckpointStore(db),
107
110
  billing: new SqliteBilling(db),
108
111
  authz,
109
112
  membership,
@@ -123,4 +126,13 @@ const server = createChatServer(deps);
123
126
  const port = Number(process.env.PORT ?? 8787);
124
127
  server.listen(port, () => {
125
128
  console.log(`[agent-chat] ${product.manifest.id} listening on http://localhost:${port}`);
129
+ // 装配清单(M-14 W2):把「声明了哪些生态组件」变成启动日志事实。
130
+ // 描述的是 manifest 的声明面;实际加载失败由 loader 在启动期报错,不静默降级。
131
+ const components = describeComponents(product);
132
+ console.log(JSON.stringify({
133
+ ev: "components",
134
+ product: product.manifest.id,
135
+ count: components.length,
136
+ items: components.map((c) => ({ kind: c.kind, name: c.name })),
137
+ }));
126
138
  });
package/dist/manifest.js CHANGED
@@ -12,6 +12,8 @@ import { pathToFileURL } from "node:url";
12
12
  import { parse } from "yaml";
13
13
  import { DEFAULT_PERSONA_ID, PERSONA_UI_FIELDS } from "@njuptlzf/agent-chat-protocol";
14
14
  import { FOLLOW_UP_MODES, parseBrandingUi } from "./branding-ui.js";
15
+ import { auditExtensionSource } from "./extension-admission.js";
16
+ import { validateFlows } from "./flows.js";
15
17
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
16
18
  const TIER_ID = /^[a-z0-9][a-z0-9-]{0,31}$/;
17
19
  const QUAL_LEVELS = ["junior", "middle", "senior"];
@@ -326,6 +328,12 @@ export function loadProduct(dir) {
326
328
  if (!existsSync(abs) || !statSync(abs).isFile()) {
327
329
  fail(file, `\`agent.extensions\` entry "${p}" must be an existing file (resolved: ${abs})`);
328
330
  }
331
+ // 准入判据(设计稿 §1.1 四条):声明即加载,所以必须在加载前拦。
332
+ // 静态扫描是启发式,挡「明显不该进服务端」的写法;真正的工厂形状由加载期兜底。
333
+ const violations = auditExtensionSource(readFileSync(abs, "utf8"), `\`agent.extensions\` entry "${p}"`);
334
+ if (violations.length > 0) {
335
+ fail(file, violations.map((v) => `criterion ${v.criterion}: ${v.reason}`).join("; "));
336
+ }
329
337
  }
330
338
  }
331
339
  if (manifest.agent.memory !== undefined && typeof manifest.agent.memory !== "boolean") {
@@ -466,7 +474,7 @@ export function loadProduct(dir) {
466
474
  const figureDirs = new Map((manifest.quals ?? []).map((q) => [q.id, path.join(absDir, "figures", q.id)]));
467
475
  if (figureDirs.size === 0)
468
476
  figureDirs.set("", path.join(absDir, "figures"));
469
- return {
477
+ const loaded = {
470
478
  manifest,
471
479
  dir: absDir,
472
480
  manifestFile: file,
@@ -487,6 +495,11 @@ export function loadProduct(dir) {
487
495
  defaultQual: manifest.quals?.[0]?.id ?? "",
488
496
  toolsModulePath: manifest.tools?.inline ? resolve(manifest.tools.inline) : undefined,
489
497
  };
498
+ // 多 agent 流程的启动期校验(W4):写坏一个 flow 就起不来,与「prompt 文件
499
+ // 缺失即启动失败」同一条纪律。放在 return 之前是因为它要读 defaultPersona
500
+ // 与 personas 的合并结果——那两样上面才算完。
501
+ validateFlows(loaded);
502
+ return loaded;
490
503
  }
491
504
  /**
492
505
  * Load the product's inline tools. The module's default export is
@@ -0,0 +1,132 @@
1
+ /**
2
+ * `Engine` 端口:编排层的**全部对外承诺**(M-14 / R-010)。
3
+ *
4
+ * 接口只有一个用途:让「谁来调度」可替换。今天唯一实现是
5
+ * `engines/taskflow.ts`(依赖 `taskflow-core`),`engines/fake.ts` 作测试替身。
6
+ * 将来换实现(fork、自写、别的库)只改 `engines/` 下一个文件 + `registry` 一行。
7
+ *
8
+ * 三条纪律(E1–E3),越界由 `boundary.test.ts` 的源码扫描拦下:
9
+ * E1 本文件与 `run-spec.ts` 不得 import 任何引擎库的类型;
10
+ * E2 引擎实现只许在 `orchestrator/engines/<name>.ts`;
11
+ * E3 引擎一律经 `EngineDeps` 拿能力,不得自己读 env / 文件系统 / spawn。
12
+ *
13
+ * 反向纪律同样重要:**端口不许长。** 若 `Engine` 出现第三个方法、
14
+ * 或 `EngineDeps` 出现第六个字段,先回看设计稿 §3.4,确认不是「为将来预留」。
15
+ */
16
+ import type { JobSpec, RunOutcome, RunSpec, ValidationReport } from "./run-spec.ts";
17
+ /** 一次子会话的执行结果,由宿主侧 `runJob` 返回。 */
18
+ export interface JobRunResult {
19
+ /** 产出文本。 */
20
+ readonly output: string;
21
+ /** 是否成功。false 时 `error` 应给出可读原因。 */
22
+ readonly ok: boolean;
23
+ /** 这次子会话的 usage。省略按 0 计。 */
24
+ readonly usage?: JobUsage;
25
+ /** 停止原因(如 `end_turn` / `aborted` / `limit_exceeded`)。 */
26
+ readonly stopReason?: string;
27
+ /** 内部重试次数(模型切换等),用于对账。 */
28
+ readonly attempts?: number;
29
+ readonly error?: string;
30
+ }
31
+ /** `runJob` 报告的最小 usage 形状,避免与 pi / protocol 的细节耦合。 */
32
+ export interface JobUsage {
33
+ readonly input: number;
34
+ readonly output: number;
35
+ readonly cacheRead?: number;
36
+ readonly cacheWrite?: number;
37
+ readonly total: number;
38
+ readonly costUsd?: number;
39
+ }
40
+ /** 引擎执行期的一个 worker 的上下文。 */
41
+ export interface JobContext {
42
+ /** 子会话 signal:顶层 abort 或本 job 超时都落在这里(I5)。 */
43
+ readonly signal: AbortSignal;
44
+ /** 本 job 在 Run 内的唯一 id(`<runId>:<phaseId>[:<n>]`),用于幂等与对账(I6)。 */
45
+ readonly jobId: string;
46
+ /** 本 job 所属 phase。多 phase 时事件要带上它,前端据此归组。 */
47
+ readonly phaseId: string;
48
+ /** 本 job 的成员 id(= `JobSpec.persona`)。单 phase 时不下发,但 `runJob` 拿得到。 */
49
+ readonly memberId: string;
50
+ /**
51
+ * 流式输出通道:`runJob` 内部每产出一段文本就调它一次。
52
+ *
53
+ * **单 phase 时宿主传 `undefined`**——那时文本走既有的 `text_delta`,
54
+ * 一个字都不许从这条通道出来(I8:档 1 字节流等价)。
55
+ * 多 phase 时宿主把它接到 `member_delta` 上。
56
+ */
57
+ readonly onDelta?: (delta: string) => void;
58
+ }
59
+ /**
60
+ * 宿主注入给引擎的能力。**六项,不多不少。**
61
+ * 引擎不许自己拿模型、拿凭据、读配置——那些都在 `runJob` 背后。
62
+ */
63
+ export interface EngineDeps {
64
+ /** 执行一次子会话。这是引擎唯一能"干活"的出口。 */
65
+ readonly runJob: (job: JobSpec, ctx: JobContext) => Promise<JobRunResult>;
66
+ /**
67
+ * checkpoint 回调:每完成一个 phase 调一次,宿主写 SQLite。
68
+ * **失败不得中断 Run**(token 已经花了,中断只会让账更乱)——引擎应只上报。
69
+ */
70
+ readonly persist?: (outcome: RunOutcome) => void;
71
+ /** 顶层中止信号。引擎负责派生子 controller(I5)。 */
72
+ readonly signal: AbortSignal;
73
+ /**
74
+ * 平台事件出口。单 phase 下引擎**不得**发额外事件(保 SSE 字节流等价)。
75
+ * 多 phase 下引擎发 `member_started` / `member_done`(`member_delta` 走 `JobContext.onDelta`)。
76
+ */
77
+ readonly emit?: (event: EngineEvent) => void;
78
+ /** 时钟。测试注入可控时间,避免 sleep。 */
79
+ readonly now?: () => number;
80
+ }
81
+ /**
82
+ * 引擎允许发出的最小事件集。
83
+ *
84
+ * **注意分工**:`EngineEvent` 是引擎→宿主的**内部**类型,宿主再翻译成协议事件
85
+ * (`ChatEvent` 的 `member_*` / `run_done`)。两者刻意不同名、不同形状——
86
+ * 引擎不知道 SSE、不知道 `runId` 怎么拼,也不该知道。
87
+ *
88
+ * `phase_started` / `phase_settled` 保留给「phase 级」语义(含 parallel / reduce
89
+ * 这类没有单一成员的 phase),`member_*` 是「成员级」(一个 phase 可能有多个成员)。
90
+ */
91
+ export type EngineEvent = {
92
+ readonly type: "phase_started";
93
+ readonly phaseId: string;
94
+ readonly jobId: string;
95
+ } | {
96
+ readonly type: "phase_settled";
97
+ readonly phaseId: string;
98
+ readonly jobId: string;
99
+ readonly state: string;
100
+ } | {
101
+ readonly type: "member_started";
102
+ readonly phaseId: string;
103
+ readonly memberId: string;
104
+ readonly jobId: string;
105
+ /** 交给这个成员的任务文本。 */
106
+ readonly task: string;
107
+ } | {
108
+ readonly type: "member_done";
109
+ readonly phaseId: string;
110
+ readonly memberId: string;
111
+ readonly jobId: string;
112
+ readonly state: string;
113
+ readonly usage: JobUsage;
114
+ } | {
115
+ readonly type: "member_delta";
116
+ readonly phaseId: string;
117
+ readonly memberId: string;
118
+ readonly delta: string;
119
+ };
120
+ /** 引擎实现。 */
121
+ export interface Engine {
122
+ /** 实现名,用于 `registry` 与诊断。 */
123
+ readonly name: string;
124
+ /**
125
+ * 静态验证:**零 token、零 I/O**(I1)。
126
+ * 环、悬空依赖、重复 id、预算非正、kind 不在 `PHASE_KINDS`、
127
+ * `tools` 超出父级白名单(I2)——全部在这里拒。
128
+ */
129
+ validate(spec: RunSpec, parentTools?: readonly string[]): ValidationReport;
130
+ /** 执行一次 Run。 */
131
+ execute(spec: RunSpec, deps: EngineDeps): Promise<RunOutcome>;
132
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,14 @@
1
+ import type { Engine, EngineDeps, JobRunResult } from "../engine.ts";
2
+ /** 注入的 `runJob` 决定结局;假引擎只负责把它转成 `JobOutcome`。 */
3
+ export interface FakeEngineOptions {
4
+ /**
5
+ * 覆写某个 phase 的 `runJob` 行为。缺省 = 成功、输出 `<phaseId>`、
6
+ * usage `{input:1,output:1,total:2}`。
7
+ */
8
+ readonly runJob?: (jobId: string, deps: EngineDeps) => Promise<JobRunResult>;
9
+ }
10
+ export interface FakeEngine extends Engine {
11
+ /** 调用次序(`<runId>:<phaseId>`),供断言「谁被调过、调几次」。 */
12
+ readonly calls: readonly string[];
13
+ }
14
+ export declare function createFakeEngine(options?: FakeEngineOptions): FakeEngine;