@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.
Files changed (49) hide show
  1. package/dist/authz.d.ts +9 -9
  2. package/dist/authz.js +6 -1
  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 +130 -0
  13. package/dist/main.js +14 -2
  14. package/dist/manifest.js +14 -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/server.d.ts +21 -2
  24. package/dist/server.js +543 -187
  25. package/dist/sqlite-stores.d.ts +46 -6
  26. package/dist/sqlite-stores.js +297 -33
  27. package/dist/stores.d.ts +3 -34
  28. package/dist/stores.js +0 -27
  29. package/dist/testing.d.ts +5 -4
  30. package/dist/testing.js +5 -4
  31. package/package.json +7 -6
  32. package/scripts/agentchat-integrate.mjs +853 -853
  33. package/src/authz.ts +15 -8
  34. package/src/checkpoint-store.ts +122 -0
  35. package/src/components.ts +66 -0
  36. package/src/extension-admission.ts +131 -0
  37. package/src/flows.ts +244 -0
  38. package/src/ledger.ts +193 -0
  39. package/src/main.ts +16 -2
  40. package/src/manifest.ts +14 -1
  41. package/src/orchestrator/engine.ts +134 -0
  42. package/src/orchestrator/engines/fake.ts +330 -0
  43. package/src/orchestrator/engines/taskflow.ts +626 -0
  44. package/src/orchestrator/run-spec.ts +171 -0
  45. package/src/server.ts +553 -183
  46. package/src/session.ts +689 -689
  47. package/src/sqlite-stores.ts +347 -35
  48. package/src/stores.ts +3 -39
  49. package/src/testing.ts +4 -4
package/src/server.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
3
- import type { ModelRuntime } from "@earendil-works/pi-coding-agent";
4
- import { PROTOCOL_VERSION, type BrandingResponse, type BillingUsageReport, type ChatEvent, type ChatRequest, type ErrorCode, type ProductManifest, type WhoamiResponse } from "@njuptlzf/agent-chat-protocol";
3
+ import type { FileEntry, ModelRuntime } from "@earendil-works/pi-coding-agent";
4
+ import { PROTOCOL_VERSION, type BrandingResponse, type BillingUsageReport, type ChatEvent, type ChatRequest, type ErrorCode, type ProductManifest, type TokenUsage, type WhoamiResponse } from "@njuptlzf/agent-chat-protocol";
5
5
  import { capsForPersona, limitsForPersona, poolSplit, type AuthzLike } from "./authz.ts";
6
6
  import type { McpServerDecl, PersonaUi } from "@njuptlzf/agent-chat-protocol";
7
7
  import { createEventMapper, createRunAccounting } from "./events.ts";
@@ -16,7 +16,14 @@ import { MCP_SPEC_ALLOWLIST_ENV, checkMcpDecl, mergedToolLabels, probeMcpProxy,
16
16
  import { baseUrlFromModelsJson, deleteProvider, keyEnvOf, modelToProbe, patchProvider, patchRouting, patchTiers, refreshProvider, testProvider, toModelsResponse, type ApiError } from "./models-api.ts";
17
17
  import { buildCommands, compileSystemPrompt, createProductSession, disposeProductSession, expandCommand, exportHistory, loadProductSkills, narrowMcpExposure, type UIPromptAnswer } from "./session.ts";
18
18
  import { auditPageWindow, toHistoryMessages, truncateLastTurn } from "./stores.ts";
19
- import type { AccountStateStore, AuditEvent, AuditRow, AuditStore, Authenticator, BillingOrder, BillingStore, HistoryStore, MembershipStore, MemberPoolStore, QuotaGate, RunLogStore } from "./stores.ts";
19
+ import type { AccountStateStore, AuditEvent, AuditRow, AuditStore, Authenticator, BillingOrder, BillingStore, HistoryStore, MembershipStore, MemberPoolStore, RunLogStore } from "./stores.ts";
20
+ import type { Ledger } from "./ledger.ts";
21
+ import type { Engine, EngineEvent, JobContext, JobRunResult } from "./orchestrator/engine.ts";
22
+ import type { JobSpec, RunOutcome, RunSpec } from "./orchestrator/run-spec.ts";
23
+ import { createTaskflowEngine } from "./orchestrator/engines/taskflow.ts";
24
+ import type { CheckpointStore } from "./checkpoint-store.ts";
25
+ import { persistCheckpoints, resumeFrom as loadResumeFrom } from "./checkpoint-store.ts";
26
+ import { toRunSpec } from "./flows.ts";
20
27
 
21
28
  /**
22
29
  * 产品业务路由接缝。路由体住在 apps/<product>/server/routes.ts(manifest
@@ -79,7 +86,23 @@ export interface ServerDeps {
79
86
  modelCooldown?: CooldownRegistry;
80
87
  toolFactory: (ctx: ToolContext) => unknown[];
81
88
  history: HistoryStore;
82
- quota: QuotaGate;
89
+ /**
90
+ * 预留-结算额度账本(M-14 W3)。替换了旧的 `QuotaGate.check/record`:
91
+ * 先占位再开跑,并发下不会超发(旧模型实测超发 140%)。
92
+ */
93
+ ledger: Ledger;
94
+ /**
95
+ * 编排引擎。omitted ⇒ 默认 `taskflow` 适配器(W1:单 phase 通路)。
96
+ * 测试注入 `createFakeEngine()`,**不建 pi 会话、不调模型**——
97
+ * 与 `trial` / `suggestions` 的替身模式同源。
98
+ */
99
+ engine?: Engine;
100
+ /**
101
+ * 多 phase Run 的断点存储(W4)。omitted ⇒ resume 不可用(带 `resumeRunId`
102
+ * 的请求 400);主链 main.ts 恒装配 SQLite 版,测试注入 Memory 版。
103
+ * 单 phase 路径根本不读它,所以缺它不影响档 1 的任何行为。
104
+ */
105
+ checkpoints?: CheckpointStore;
83
106
  authenticate: Authenticator;
84
107
  dataDir: string;
85
108
  /** Optional per-run log backing GET /api/usage (-11). */
@@ -1540,6 +1563,28 @@ export function createChatServer(deps: ServerDeps): Server {
1540
1563
  // 定死——用户投诉「昨天不是这么说的」时,要查的是**当时生效的那一版**,不是现在这版。
1541
1564
  const personaVersion = deps.personaConfig ? effectivePersonaVersion(deps.personaConfig.get(), persona) : undefined;
1542
1565
 
1566
+ // 多 phase 入口(W4):`flow` 指向 manifest 声明的 `agent.flows.<id>`。
1567
+ // 不传 = 单 phase 老路径(档 1 字节流不变)。传了但 id 不存在 = 400(fail-closed,
1568
+ // 不让一个拼错的流程名静默退化成单助手回答——用户会以为流程跑过了)。
1569
+ if (body.flow !== undefined && (typeof body.flow !== "string" || !/^[a-z][a-z0-9_-]*$/.test(body.flow))) {
1570
+ return sendError(res, 400, "bad_request", "`flow` has an invalid format");
1571
+ }
1572
+ const flow = body.flow;
1573
+ if (flow !== undefined && !product.manifest.agent.flows?.[flow]) {
1574
+ return sendError(res, 400, "bad_request", `unknown flow "${flow}"`);
1575
+ }
1576
+ // resume 归属:`runId` 形如 `<sessionId>:<timestamp>`,前缀必须是**本会话**,
1577
+ // 否则等于用一个猜来的 id 把别人的产物塞进自己的回答(跨会话注入)。
1578
+ // 只在 flow 请求上有意义——单 phase 没有 phase checkpoint 可恢复。
1579
+ if (body.resumeRunId !== undefined) {
1580
+ if (flow === undefined) {
1581
+ return sendError(res, 400, "bad_request", "`resumeRunId` requires `flow`");
1582
+ }
1583
+ if (typeof body.resumeRunId !== "string" || !body.resumeRunId.startsWith(`${sessionId}:`)) {
1584
+ return sendError(res, 400, "bad_request", "`resumeRunId` does not belong to this session");
1585
+ }
1586
+ }
1587
+
1543
1588
  // A leading "/" is UI semantics: expand it here so the command name (and the
1544
1589
  // skill's file path) never reaches the model. Checked before quota/billing so
1545
1590
  // a typo costs nothing and never opens a run. The surface is the scope's: an
@@ -1547,6 +1592,39 @@ export function createChatServer(deps: ServerDeps): Server {
1547
1592
  const surface = surfaceOf(scope);
1548
1593
  const expanded = expandCommand(body.message, surface.commands, surface.skills);
1549
1594
  if ("error" in expanded) return sendError(res, 400, "bad_request", expanded.error);
1595
+ // prompt 文本在**建 RunSpec 之前**就要定下来:RunSpec 的 `JobSpec.task` 会被
1596
+ // 引擎的 validate 检查「agent phase 必须有 task」,算晚了就恒被拒(见下方注释)。
1597
+ // 附件/上下文的编织是纯函数,提前算不改变任何行为。
1598
+ const promptText = withContext(withAttachments(expanded.message, att.attachments), body.context);
1599
+
1600
+ // ---- RunSpec 提前构造(W4)----
1601
+ // 提前到 reserve / writeHead 之前,是为了让 flow 的非法声明与无断点 resume
1602
+ // 能以 **400** 拒绝(开了 SSE 流就改不了状态码了)。档 1(无 flow)的形状
1603
+ // 与接入编排层之前逐字相同——这是 I8 字节流基线的另一半保证。
1604
+ const startedAt = new Date();
1605
+ const runId = `${sessionId}:${startedAt.getTime()}`;
1606
+ const engine = deps.engine ?? createTaskflowEngine({ cwd: deps.dataDir });
1607
+
1608
+ const translated: RunSpec | { readonly error: string } =
1609
+ flow === undefined
1610
+ ? { runId, phases: [{ id: "chat", kind: "agent", job: { persona, task: promptText }, final: true }] }
1611
+ : toRunSpec(product, flow, promptText, runId);
1612
+ // flow 声明的 phase 形状非法 ⇒ 400 fail-closed,而不是回退成单助手回答让用户误以为跑过。
1613
+ // (启动期 validateFlows 已拦过绝大多数;这里是第二道闸,也覆盖运行时注入。)
1614
+ if ("error" in translated) return sendError(res, 400, "bad_request", translated.error);
1615
+ let runSpec: RunSpec = translated;
1616
+ if (flow !== undefined && body.resumeRunId !== undefined) {
1617
+ if (!deps.checkpoints) {
1618
+ return sendError(res, 400, "bad_request", "resume is unavailable (no checkpoint store configured)");
1619
+ }
1620
+ const cp = await loadResumeFrom(deps.checkpoints, body.resumeRunId);
1621
+ if (!cp) return sendError(res, 400, "bad_request", "`resumeRunId` has no checkpoints to resume from");
1622
+ runSpec = { ...translated, resumeFrom: cp };
1623
+ }
1624
+ if (flow !== undefined) {
1625
+ const report = engine.validate(runSpec);
1626
+ if (!report.ok) return sendError(res, 400, "bad_request", `invalid flow: ${report.errors.join("; ")}`);
1627
+ }
1550
1628
 
1551
1629
  // 角色决定当日上限与池。authz 未装配 = 全员
1552
1630
  // user、caps 不传(现状);池只在会员在期时 lazy 发满当月。
@@ -1559,23 +1637,31 @@ export function createChatServer(deps: ServerDeps): Server {
1559
1637
  const memberActive = memberUntil !== null && Date.parse(memberUntil) > Date.now();
1560
1638
  const personaMember = !!deps.authz && (roles.includes("admin") || memberActive);
1561
1639
  const poolCfg = deps.memberPool && memberActive ? (limitsForPersona(limits, persona).memberMonthlyTokenPool ?? 0) : 0;
1562
- const decision = await deps.quota.check(userId, deps.authz ? capsForPersona(limits, persona, personaMember) : undefined, persona);
1563
- if (!decision.ok) return sendError(res, 429, "quota_exceeded", decision.reason);
1640
+ const caps = deps.authz ? capsForPersona(limits, persona, personaMember) : undefined;
1641
+ // 预留(I4):占位成功才允许调模型。operationId 一请求一个,是幂等键(I6)。
1642
+ const operationId = randomUUID();
1643
+ const reserved = await deps.ledger.reserve({ userId, persona, caps, operationId });
1644
+ if (!reserved.ok) return sendError(res, 429, "quota_exceeded", reserved.reason);
1564
1645
 
1565
1646
  // Billing gate: starting costs money, so a depleted (or never topped-up) balance stops here —
1566
1647
  // 但池内免余额:只要当月池还有剩,余额见底也能开跑,池尽才提示充值。
1648
+ // 以下三条早退都在**占位之后**,所以必须先归还占位——否则用户被 402/409 拒一次,
1649
+ // 额度要被白占一小时(预留 TTL)。
1567
1650
  if (billingActive && poolCfg <= 0 && (await deps.billing!.balance(userId)) <= 0) {
1651
+ await deps.ledger.release(operationId);
1568
1652
  return sendError(res, 402, "payment_required", "余额不足,请先充值");
1569
1653
  }
1570
1654
  if (billingActive && poolCfg > 0) {
1571
1655
  const row = await deps.memberPool!.getOrGrant(userId, persona, monthNow(), poolCfg);
1572
1656
  if (Math.max(0, row.granted - row.used) <= 0 && (await deps.billing!.balance(userId)) <= 0) {
1657
+ await deps.ledger.release(operationId);
1573
1658
  return sendError(res, 402, "payment_required", "本月发放池已用尽且余额不足,请先充值");
1574
1659
  }
1575
1660
  }
1576
1661
 
1577
1662
  const runKey = `${userId}\u0000${sessionId}`;
1578
1663
  if (running.has(runKey)) {
1664
+ await deps.ledger.release(operationId);
1579
1665
  return sendError(res, 409, "bad_request", "this session already has a run in progress");
1580
1666
  }
1581
1667
  running.add(runKey);
@@ -1601,7 +1687,6 @@ export function createChatServer(deps: ServerDeps): Server {
1601
1687
  let aborted = false;
1602
1688
  let limitSent = false;
1603
1689
  let runError: string | undefined;
1604
- const startedAt = new Date();
1605
1690
  const confirms = new Map<string, (allow: boolean) => void>();
1606
1691
  pendingRuns.set(runKey, confirms);
1607
1692
  const uiPrompts = new Map<string, (answer: UIPromptAnswer) => void>();
@@ -1617,205 +1702,435 @@ export function createChatServer(deps: ServerDeps): Server {
1617
1702
  }
1618
1703
  }
1619
1704
 
1620
- try {
1621
- send({ type: "ready", v: PROTOCOL_VERSION, sessionId, product: product.manifest.id });
1622
- // 工具中文名随首帧一次性下发(用户视角不显示 mcp__ 声明名)。
1623
- send({ type: "tools_meta", labels: mergedToolLabels(deps.mcpConfig?.get(), product.manifest.agent.toolLabels) });
1624
-
1625
- const history = await deps.history.load(userId, scope, sessionId);
1626
- // persona 与 createFeedback 一起注入:产品据此决定造哪些工具,工具本身碰不到 store。
1627
- // 工单正文由服务端截断、补 ref、按 roles 定优先级——模型只能递内容,改不了归属。
1628
- const feedbackSink = deps.feedback as FeedbackSubmitSink | undefined;
1629
- const tools = deps.toolFactory({
1630
- productId: product.manifest.id,
1631
- productDir: product.dir,
1632
- userId,
1633
- dataDir: deps.dataDir,
1634
- qual: scope,
1635
- persona,
1636
- ...(feedbackSink
1637
- ? {
1638
- createFeedback: async (content: string) => {
1639
- const row = await feedbackSink.submit({
1640
- userId,
1641
- kind: "other",
1642
- content,
1643
- sessionId,
1644
- ref: `${persona}:${sessionId}`,
1645
- priority: roles.includes("member") || roles.includes("admin") ? "high" : "normal",
1705
+ // 单 phase 通路:把原来这一整段 try 体原样搬进 runSingleJob(缩进变了、语义没变)。
1706
+ // 为什么搬而不重写:里面的 pendingFailover 吞批、toolRoundsAtStart 判定、
1707
+ // limitSent 后 abort 都是逐次修出来的,重写必回退旧 bug。
1708
+ // runSingleJob 不发任何编排事件,SSE 字节流与接入编排层之前完全一致(I8)。
1709
+ let lastText = "";
1710
+ /** runSingleJob 是否已跑过——引擎抛错时据此判断要不要 fail-open 补跑一次。 */
1711
+ let started = false;
1712
+ const runSingleJob = async (): Promise<JobRunResult> => {
1713
+ started = true;
1714
+ try {
1715
+ send({ type: "ready", v: PROTOCOL_VERSION, sessionId, product: product.manifest.id });
1716
+ // 工具中文名随首帧一次性下发(用户视角不显示 mcp__ 声明名)。
1717
+ send({ type: "tools_meta", labels: mergedToolLabels(deps.mcpConfig?.get(), product.manifest.agent.toolLabels) });
1718
+
1719
+ const history = await deps.history.load(userId, scope, sessionId);
1720
+ // persona 与 createFeedback 一起注入:产品据此决定造哪些工具,工具本身碰不到 store。
1721
+ // 工单正文由服务端截断、补 ref、按 roles 定优先级——模型只能递内容,改不了归属。
1722
+ const feedbackSink = deps.feedback as FeedbackSubmitSink | undefined;
1723
+ const tools = deps.toolFactory({
1724
+ productId: product.manifest.id,
1725
+ productDir: product.dir,
1726
+ userId,
1727
+ dataDir: deps.dataDir,
1728
+ qual: scope,
1729
+ persona,
1730
+ ...(feedbackSink
1731
+ ? {
1732
+ createFeedback: async (content: string) => {
1733
+ const row = await feedbackSink.submit({
1734
+ userId,
1735
+ kind: "other",
1736
+ content,
1737
+ sessionId,
1738
+ ref: `${persona}:${sessionId}`,
1739
+ priority: roles.includes("member") || roles.includes("admin") ? "high" : "normal",
1740
+ });
1741
+ return { id: row.id ?? 0 };
1742
+ },
1743
+ }
1744
+ : {}),
1745
+ });
1746
+
1747
+ // ---- 失败切换(设计稿):run 开始定一条有序候选链,模型调用失败换下一条。
1748
+ // 链来自 model-config 的档位绑定;没配置就是 manifest 的单模型(链长 1 ⇒ 永不切换)。
1749
+ const modelCfg = deps.modelConfig?.get();
1750
+ const cooldown = deps.modelCooldown ?? processCooldown;
1751
+ const chain = orderChain(resolveChain(product, body.tier, modelCfg), cooldown);
1752
+ const failoverOn = modelCfg?.routing.failover ?? true;
1753
+ const cooldownSeconds = modelCfg?.routing.cooldownSeconds ?? 120;
1754
+ const promptImages = parsed.images.length > 0 ? { images: parsed.images } : undefined;
1755
+ const buildSession = (candidate: ModelCandidate) =>
1756
+ createProductSession({
1757
+ product,
1758
+ modelRuntime: deps.modelRuntime,
1759
+ tools,
1760
+ userId,
1761
+ personaConfig: deps.personaConfig,
1762
+ dataDir: deps.dataDir,
1763
+ // 档位语义(label/thinking/multiplier)仍来自 manifest,只有物理模型跟着候选走。
1764
+ tier: candidate.provider === tier.provider && candidate.model === tier.model
1765
+ ? tier
1766
+ : { ...tier, provider: candidate.provider, model: candidate.model },
1767
+ qual: scope,
1768
+ persona,
1769
+ history,
1770
+ mcpConfig: deps.mcpConfig,
1771
+ requestConfirm: (info) =>
1772
+ new Promise<boolean>((resolve) => {
1773
+ const settle = (allow: boolean) => {
1774
+ clearTimeout(timer);
1775
+ confirms.delete(info.toolCallId);
1776
+ resolve(allow);
1777
+ };
1778
+ const timer = setTimeout(() => settle(false), CONFIRM_TIMEOUT_MS);
1779
+ confirms.set(info.toolCallId, settle);
1780
+ send({ type: "tool_confirm", toolCallId: info.toolCallId, name: info.name, args: info.args });
1781
+ }),
1782
+ // Extension dialogs (batch 3-4b): same pause-and-answer shape as the
1783
+ // confirm gate, but answered through POST /api/ui-response. Nobody
1784
+ // answering means the fail-closed default, never a hung run.
1785
+ requestUI: (info, signal) =>
1786
+ new Promise<UIPromptAnswer>((resolve) => {
1787
+ const settle = (answer: UIPromptAnswer) => {
1788
+ clearTimeout(timer);
1789
+ signal?.removeEventListener("abort", onAbort);
1790
+ uiPrompts.delete(info.id);
1791
+ resolve(answer);
1792
+ };
1793
+ const onAbort = () => settle({ cancelled: true });
1794
+ const timeoutMs = info.timeoutMs
1795
+ ? Math.min(Math.max(info.timeoutMs, UI_TIMEOUT_MIN_MS), UI_TIMEOUT_MAX_MS)
1796
+ : UI_TIMEOUT_MS;
1797
+ const timer = setTimeout(() => settle({ cancelled: true }), timeoutMs);
1798
+ signal?.addEventListener("abort", onAbort, { once: true });
1799
+ uiPrompts.set(info.id, settle);
1800
+ send({
1801
+ type: "ui_prompt",
1802
+ id: info.id,
1803
+ kind: info.kind,
1804
+ title: info.title,
1805
+ ...(info.message !== undefined ? { message: info.message } : {}),
1806
+ ...(info.options !== undefined ? { options: info.options } : {}),
1807
+ ...(info.placeholder !== undefined ? { placeholder: info.placeholder } : {}),
1646
1808
  });
1647
- return { id: row.id ?? 0 };
1648
- },
1809
+ }),
1810
+ onUINotify: (message, level) => send({ type: "ui_notify", message, level }),
1811
+ });
1812
+
1813
+ // Client went away: stop spending tokens(读的是当前那一次尝试的会话)。
1814
+ res.on("close", () => {
1815
+ if (!res.writableEnded) void session?.abort();
1816
+ });
1817
+
1818
+ for (let attempt = 0; ; attempt++) {
1819
+ const candidate = chain[attempt]!;
1820
+ session = await buildSession(candidate);
1821
+
1822
+ // 一次尝试内只有「还没吐字、还没跑工具」才允许换候选:重发会把已经流出去的
1823
+ // 半句话再发一遍,或把已经发生的工具副作用再执行一遍。这条边界是 v1 的口径。
1824
+ let pendingFailover: { message: string } | undefined;
1825
+ let attemptText = false;
1826
+ const toolRoundsAtStart = accounting.toolRounds();
1827
+
1828
+ session.subscribe((event) => {
1829
+ const outs = mapper.map(event);
1830
+ // 同一批里出现 model_error 且这次还能切:**整批吞掉**——包括那条空的
1831
+ // message_end,否则前端会先落一个空气泡再被真正的回答顶下去。
1832
+ const errOut = outs.find((o) => o.type === "error" && o.code === "model_error");
1833
+ if (errOut && errOut.type === "error") {
1834
+ // 判定用 pi 原始报错(rawModelError),不是折叠后的用户文案——文案里
1835
+ // 已经没有 JSON/网络词,拿它匹配会让 failover 失明(2026-11-04)。
1836
+ const canSwitch =
1837
+ failoverOn && attempt < chain.length - 1 && !attemptText && accounting.toolRounds() === toolRoundsAtStart;
1838
+ if (canSwitch && isRetryableModelError(rawModelError(event))) {
1839
+ // 用户不该看到一次注定会被掩盖的失败(也不显示模型名)。
1840
+ pendingFailover = { message: rawModelError(event) };
1841
+ void session?.abort();
1842
+ return;
1843
+ }
1649
1844
  }
1650
- : {}),
1651
- });
1845
+ for (const out of outs) {
1846
+ if (out.type === "text_delta" || out.type === "thinking_delta") attemptText = true;
1847
+ // 引擎的 RunOutcome.output 要能反映这轮回答;取最后一条 message_end 的全文。
1848
+ if (out.type === "message_end") lastText = out.text;
1849
+ if (out.type === "done") {
1850
+ if (pendingFailover) return; // abort 带出来的 done 不发——真正的收口在最后一次尝试
1851
+ doneSent = true;
1852
+ aborted = out.aborted;
1853
+ }
1854
+ accounting.observe(out);
1855
+ if (out.type === "tool_end") toolCalls[out.name] = (toolCalls[out.name] ?? 0) + 1;
1856
+ send(out);
1857
+ if (accounting.limitHit() && !limitSent) {
1858
+ // One prompt must not loop forever: stop it at the cap, with a reason.
1859
+ limitSent = true;
1860
+ send({
1861
+ type: "error",
1862
+ code: "limit_exceeded",
1863
+ message: `已达到单次运行 ${limits.maxToolRounds} 轮工具调用上限,已中止`,
1864
+ retryable: false,
1865
+ });
1866
+ void session?.abort();
1867
+ }
1868
+ }
1869
+ });
1870
+
1871
+ try {
1872
+ await session.prompt(promptText, promptImages);
1873
+ await session.waitForIdle();
1874
+ } catch (err) {
1875
+ // abort 引起的抛出是切换路径的一部分;没有待切换的错误就照旧冒泡。
1876
+ if (!pendingFailover) throw err;
1877
+ }
1878
+ if (!pendingFailover) break;
1879
+
1880
+ // 换下一条:打冷却、留痕、告知用户,然后**重建会话**重发同一个 prompt。
1881
+ // 不用 session.setModel 原地重发——会话里已经记了这次失败的用户消息,重发会让
1882
+ // 历史多一条一模一样的提问;重建用的是 run 开始时那份 history,干净。
1883
+ cooldown.mark(candidate, cooldownSeconds);
1884
+ send({ type: "ui_notify", message: FAILOVER_NOTICE, level: "warning" });
1885
+ if (deps.audit) {
1886
+ void deps.audit
1887
+ .append({
1888
+ actor: userId,
1889
+ result: "ok",
1890
+ action: MODEL_SWITCH,
1891
+ target: `session:${sessionId}`,
1892
+ meta: { from: candidateKey(candidate), to: candidateKey(chain[attempt + 1]!), reason: pendingFailover.message.slice(0, 200) },
1893
+ })
1894
+ .catch((err) => console.error("[audit] model.switch failed (fail-open):", err));
1895
+ }
1896
+ disposeProductSession(session!);
1897
+ session = undefined;
1898
+ }
1899
+ } catch (err) {
1900
+ runError = err instanceof Error ? err.message : String(err);
1901
+ console.error("[chat] run failed:", err);
1902
+ send({
1903
+ type: "error",
1904
+ code: "internal",
1905
+ message: "服务暂时不可用,请稍后重试",
1906
+ retryable: true,
1907
+ });
1908
+ }
1909
+ return {
1910
+ output: lastText,
1911
+ ok: runError === undefined,
1912
+ usage: mapper.totalUsage(),
1913
+ stopReason: runError === undefined ? "end_turn" : "error",
1914
+ ...(runError !== undefined ? { error: runError } : {}),
1915
+ };
1916
+ };
1652
1917
 
1653
- // ---- 失败切换(设计稿):run 开始定一条有序候选链,模型调用失败换下一条。
1654
- // 链来自 model-config 的档位绑定;没配置就是 manifest 的单模型(链长 1 ⇒ 永不切换)。
1655
- const modelCfg = deps.modelConfig?.get();
1656
- const cooldown = deps.modelCooldown ?? processCooldown;
1657
- const chain = orderChain(resolveChain(product, body.tier, modelCfg), cooldown);
1658
- const failoverOn = modelCfg?.routing.failover ?? true;
1659
- const cooldownSeconds = modelCfg?.routing.cooldownSeconds ?? 120;
1660
- const promptText = withContext(withAttachments(expanded.message, att.attachments), body.context);
1661
- const promptImages = parsed.images.length > 0 ? { images: parsed.images } : undefined;
1662
- const buildSession = (candidate: ModelCandidate) =>
1663
- createProductSession({
1918
+ // 一次 Run = 一个 agent phase。引擎只负责「校验 + 调 runJob + 汇总 usage」,
1919
+ // 真正的会话逻辑全在 runSingleJob 里,所以档 1 的行为与接入前逐字节一致。
1920
+ //
1921
+ // `JobSpec.task` 必须是真实的 prompt:它是 `RunSpec` 里唯一描述「这个 phase
1922
+ // 要干什么」的字段,引擎的静态校验会拒空 task。曾经这里是 `promptForEngine`
1923
+ // 变量、在 runSingleJob 内部才赋值,于是构造 runSpec 时它恒为空串 ⇒ validate
1924
+ // 恒拒 ⇒ 每次都静默 fail-open 回直连,**编排层在 W1/W2/W3 期间一次都没真正执行过**。
1925
+ // 由 `wire-baseline.test.ts` 的快照基线抓出来(它同时钉住档 1 的字节流)。
1926
+ const runAbort = new AbortController();
1927
+ const isFlow = flow !== undefined;
1928
+ /** 多 phase 的成员会话各自独立;档 1 恒为空(单 phase 仍用上面的 `session`)。 */
1929
+ const memberSessions: Array<Awaited<ReturnType<typeof createProductSession>>> = [];
1930
+ /** 入口 phase(无 dependsOn)才继承会话历史,其余成员从空上下文起跑。 */
1931
+ const entryPhaseIds = new Set(runSpec.phases.filter((p) => (p.dependsOn ?? []).length === 0).map((p) => p.id));
1932
+ /** 引擎收口产物;档 1 不用它,多 phase 的 usage/run_done 都从这里出。 */
1933
+ let runOutcome: RunOutcome | undefined;
1934
+
1935
+ /**
1936
+ * 多 phase 的一个成员 worker(W4)。与 `runSingleJob` 刻意分开写:
1937
+ * 那一路的每一帧都被 `wire-baseline.test.ts` 逐字节钉住,塞分支进来必回退。
1938
+ *
1939
+ * 成员路径的四条纪律:
1940
+ * ① 每个 job 一个独立 `createProductSession`(persona/task 来自 JobSpec);
1941
+ * ② 文本只走 `ctx.onDelta`(→ `member_delta`),**不发** text_delta / thinking_delta——
1942
+ * 多 phase 的用户视图是成员卡片,不是一根合并的气泡;
1943
+ * ③ 工具/确认/UI 事件一律不转发主线程(成员是后台 worker,不该弹确认卡);
1944
+ * ④ usage 只记在**局部** mapper 上,由引擎汇总,不碰主 `mapper`/`accounting`。
1945
+ */
1946
+ const runMemberJob = async (job: JobSpec, ctx: JobContext): Promise<JobRunResult> => {
1947
+ const memberMapper = createEventMapper();
1948
+ let memberText = "";
1949
+ let memberError: string | undefined;
1950
+ try {
1951
+ const history = entryPhaseIds.has(ctx.phaseId) ? ((await deps.history.load(userId, scope, sessionId)) ?? []) : [];
1952
+ const feedbackSink = deps.feedback as FeedbackSubmitSink | undefined;
1953
+ const tools = deps.toolFactory({
1954
+ productId: product.manifest.id,
1955
+ productDir: product.dir,
1956
+ userId,
1957
+ dataDir: deps.dataDir,
1958
+ qual: scope,
1959
+ persona: job.persona,
1960
+ ...(feedbackSink
1961
+ ? {
1962
+ createFeedback: async (content: string) => {
1963
+ const row = await feedbackSink.submit({
1964
+ userId,
1965
+ kind: "other",
1966
+ content,
1967
+ sessionId,
1968
+ ref: `${job.persona}:${sessionId}`,
1969
+ priority: roles.includes("member") || roles.includes("admin") ? "high" : "normal",
1970
+ });
1971
+ return { id: row.id ?? 0 };
1972
+ },
1973
+ }
1974
+ : {}),
1975
+ });
1976
+ const ms = await createProductSession({
1664
1977
  product,
1665
1978
  modelRuntime: deps.modelRuntime,
1666
1979
  tools,
1667
1980
  userId,
1668
1981
  personaConfig: deps.personaConfig,
1669
1982
  dataDir: deps.dataDir,
1670
- // 档位语义(label/thinking/multiplier)仍来自 manifest,只有物理模型跟着候选走。
1671
- tier: candidate.provider === tier.provider && candidate.model === tier.model
1672
- ? tier
1673
- : { ...tier, provider: candidate.provider, model: candidate.model },
1983
+ tier,
1674
1984
  qual: scope,
1675
- persona,
1985
+ persona: job.persona,
1676
1986
  history,
1677
1987
  mcpConfig: deps.mcpConfig,
1678
- requestConfirm: (info) =>
1679
- new Promise<boolean>((resolve) => {
1680
- const settle = (allow: boolean) => {
1681
- clearTimeout(timer);
1682
- confirms.delete(info.toolCallId);
1683
- resolve(allow);
1684
- };
1685
- const timer = setTimeout(() => settle(false), CONFIRM_TIMEOUT_MS);
1686
- confirms.set(info.toolCallId, settle);
1687
- send({ type: "tool_confirm", toolCallId: info.toolCallId, name: info.name, args: info.args });
1688
- }),
1689
- // Extension dialogs (batch 3-4b): same pause-and-answer shape as the
1690
- // confirm gate, but answered through POST /api/ui-response. Nobody
1691
- // answering means the fail-closed default, never a hung run.
1692
- requestUI: (info, signal) =>
1693
- new Promise<UIPromptAnswer>((resolve) => {
1694
- const settle = (answer: UIPromptAnswer) => {
1695
- clearTimeout(timer);
1696
- signal?.removeEventListener("abort", onAbort);
1697
- uiPrompts.delete(info.id);
1698
- resolve(answer);
1699
- };
1700
- const onAbort = () => settle({ cancelled: true });
1701
- const timeoutMs = info.timeoutMs
1702
- ? Math.min(Math.max(info.timeoutMs, UI_TIMEOUT_MIN_MS), UI_TIMEOUT_MAX_MS)
1703
- : UI_TIMEOUT_MS;
1704
- const timer = setTimeout(() => settle({ cancelled: true }), timeoutMs);
1705
- signal?.addEventListener("abort", onAbort, { once: true });
1706
- uiPrompts.set(info.id, settle);
1707
- send({
1708
- type: "ui_prompt",
1709
- id: info.id,
1710
- kind: info.kind,
1711
- title: info.title,
1712
- ...(info.message !== undefined ? { message: info.message } : {}),
1713
- ...(info.options !== undefined ? { options: info.options } : {}),
1714
- ...(info.placeholder !== undefined ? { placeholder: info.placeholder } : {}),
1715
- });
1716
- }),
1717
- onUINotify: (message, level) => send({ type: "ui_notify", message, level }),
1988
+ // 成员是后台 worker:没人盯着确认卡,fail-closed 拒绝才是正确默认。
1989
+ requestConfirm: async () => false,
1718
1990
  });
1719
-
1720
- // Client went away: stop spending tokens(读的是当前那一次尝试的会话)。
1721
- res.on("close", () => {
1722
- if (!res.writableEnded) void session?.abort();
1723
- });
1724
-
1725
- for (let attempt = 0; ; attempt++) {
1726
- const candidate = chain[attempt]!;
1727
- session = await buildSession(candidate);
1728
-
1729
- // 一次尝试内只有「还没吐字、还没跑工具」才允许换候选:重发会把已经流出去的
1730
- // 半句话再发一遍,或把已经发生的工具副作用再执行一遍。这条边界是 v1 的口径。
1731
- let pendingFailover: { message: string } | undefined;
1732
- let attemptText = false;
1733
- const toolRoundsAtStart = accounting.toolRounds();
1734
-
1735
- session.subscribe((event) => {
1736
- const outs = mapper.map(event);
1737
- // 同一批里出现 model_error 且这次还能切:**整批吞掉**——包括那条空的
1738
- // message_end,否则前端会先落一个空气泡再被真正的回答顶下去。
1739
- const errOut = outs.find((o) => o.type === "error" && o.code === "model_error");
1740
- if (errOut && errOut.type === "error") {
1741
- // 判定用 pi 原始报错(rawModelError),不是折叠后的用户文案——文案里
1742
- // 已经没有 JSON/网络词,拿它匹配会让 failover 失明(2026-11-04)。
1743
- const canSwitch =
1744
- failoverOn && attempt < chain.length - 1 && !attemptText && accounting.toolRounds() === toolRoundsAtStart;
1745
- if (canSwitch && isRetryableModelError(rawModelError(event))) {
1746
- // 用户不该看到一次注定会被掩盖的失败(也不显示模型名)。
1747
- pendingFailover = { message: rawModelError(event) };
1748
- void session?.abort();
1749
- return;
1750
- }
1751
- }
1752
- for (const out of outs) {
1753
- if (out.type === "text_delta" || out.type === "thinking_delta") attemptText = true;
1754
- if (out.type === "done") {
1755
- if (pendingFailover) return; // abort 带出来的 done 不发——真正的收口在最后一次尝试
1756
- doneSent = true;
1757
- aborted = out.aborted;
1758
- }
1759
- accounting.observe(out);
1760
- if (out.type === "tool_end") toolCalls[out.name] = (toolCalls[out.name] ?? 0) + 1;
1761
- send(out);
1762
- if (accounting.limitHit() && !limitSent) {
1763
- // One prompt must not loop forever: stop it at the cap, with a reason.
1764
- limitSent = true;
1765
- send({
1766
- type: "error",
1767
- code: "limit_exceeded",
1768
- message: `已达到单次运行 ${limits.maxToolRounds} 轮工具调用上限,已中止`,
1769
- retryable: false,
1770
- });
1771
- void session?.abort();
1772
- }
1991
+ memberSessions.push(ms);
1992
+ const onAbort = () => void ms.abort();
1993
+ if (ctx.signal.aborted) onAbort();
1994
+ else ctx.signal.addEventListener("abort", onAbort, { once: true });
1995
+ ms.subscribe((event) => {
1996
+ for (const out of memberMapper.map(event)) {
1997
+ if (out.type === "text_delta" || out.type === "thinking_delta") ctx.onDelta?.(out.delta);
1998
+ if (out.type === "message_end") memberText = out.text;
1999
+ // tool_* / done / error:不转发,成员气泡只显示文本与状态。
1773
2000
  }
1774
2001
  });
2002
+ await ms.prompt(job.task, undefined);
2003
+ await ms.waitForIdle();
2004
+ ctx.signal.removeEventListener("abort", onAbort);
2005
+ } catch (err) {
2006
+ memberError = err instanceof Error ? err.message : String(err);
2007
+ console.error("[orchestrator] member job failed:", err);
2008
+ send({ type: "error", code: "internal", message: `成员 ${job.persona} 执行失败`, retryable: false });
2009
+ }
2010
+ const usage = memberMapper.totalUsage();
2011
+ return {
2012
+ output: memberText,
2013
+ ok: memberError === undefined,
2014
+ usage: {
2015
+ input: usage.input,
2016
+ output: usage.output,
2017
+ cacheRead: usage.cacheRead,
2018
+ cacheWrite: usage.cacheWrite,
2019
+ total: usage.total,
2020
+ costUsd: usage.costUsd,
2021
+ },
2022
+ stopReason: memberError === undefined ? "end_turn" : "error",
2023
+ ...(memberError !== undefined ? { error: memberError } : {}),
2024
+ };
2025
+ };
1775
2026
 
1776
- try {
1777
- await session.prompt(promptText, promptImages);
1778
- await session.waitForIdle();
1779
- } catch (err) {
1780
- // abort 引起的抛出是切换路径的一部分;没有待切换的错误就照旧冒泡。
1781
- if (!pendingFailover) throw err;
2027
+ /** EngineEvent(内部)→ ChatEvent(协议)+ runId。单 phase 时引擎不发事件,这个桥用不到。 */
2028
+ const bridgeEngineEvent = (ev: EngineEvent): void => {
2029
+ switch (ev.type) {
2030
+ case "member_started":
2031
+ send({ type: "member_started", runId, phaseId: ev.phaseId, memberId: ev.memberId, task: ev.task });
2032
+ if (deps.checkpoints) {
2033
+ void deps.checkpoints
2034
+ .saveJob(runId, {
2035
+ runId,
2036
+ phaseId: ev.phaseId,
2037
+ jobId: ev.jobId,
2038
+ state: "running",
2039
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 },
2040
+ leaseUntil: Date.now() + 5 * 60_000,
2041
+ })
2042
+ .catch((err) => console.error("[checkpoint] saveJob(running) failed:", err));
2043
+ }
2044
+ break;
2045
+ case "member_delta":
2046
+ send({ type: "member_delta", runId, phaseId: ev.phaseId, memberId: ev.memberId, delta: ev.delta });
2047
+ break;
2048
+ case "member_done": {
2049
+ const u = ev.usage;
2050
+ const usage: TokenUsage = {
2051
+ input: u.input,
2052
+ output: u.output,
2053
+ cacheRead: u.cacheRead ?? 0,
2054
+ cacheWrite: u.cacheWrite ?? 0,
2055
+ total: u.total,
2056
+ costUsd: u.costUsd ?? 0,
2057
+ };
2058
+ send({ type: "member_done", runId, phaseId: ev.phaseId, memberId: ev.memberId, state: ev.state as "completed" | "failed" | "stopped" | "blocked", usage });
2059
+ if (deps.checkpoints) {
2060
+ void deps.checkpoints
2061
+ .saveJob(runId, { runId, phaseId: ev.phaseId, jobId: ev.jobId, state: ev.state, usage })
2062
+ .catch((err) => console.error("[checkpoint] saveJob(done) failed:", err));
2063
+ }
2064
+ break;
1782
2065
  }
1783
- if (!pendingFailover) break;
2066
+ default:
2067
+ // phase_started / phase_settled:协议里没有对应事件,刻意不下发。
2068
+ break;
2069
+ }
2070
+ };
1784
2071
 
1785
- // 换下一条:打冷却、留痕、告知用户,然后**重建会话**重发同一个 prompt。
1786
- // 不用 session.setModel 原地重发——会话里已经记了这次失败的用户消息,重发会让
1787
- // 历史多一条一模一样的提问;重建用的是 run 开始时那份 history,干净。
1788
- cooldown.mark(candidate, cooldownSeconds);
1789
- send({ type: "ui_notify", message: FAILOVER_NOTICE, level: "warning" });
1790
- if (deps.audit) {
1791
- void deps.audit
1792
- .append({
1793
- actor: userId,
1794
- result: "ok",
1795
- action: MODEL_SWITCH,
1796
- target: `session:${sessionId}`,
1797
- meta: { from: candidateKey(candidate), to: candidateKey(chain[attempt + 1]!), reason: pendingFailover.message.slice(0, 200) },
1798
- })
1799
- .catch((err) => console.error("[audit] model.switch failed (fail-open):", err));
2072
+ // 客户端断开 → abort 所有成员会话(单 phase 的会话由 runSingleJob 内部的 close 监听处理)。
2073
+ if (isFlow) {
2074
+ res.on("close", () => {
2075
+ if (!res.writableEnded) for (const ms of memberSessions) void ms.abort();
2076
+ });
2077
+ }
2078
+
2079
+ try {
2080
+ if (isFlow) {
2081
+ // 多 phase 也发 ready/tools_meta 作为传输头——前端的 sessionId 绑定与工具名
2082
+ // 都依赖它们;但成员事件从 member_started 开始,不给单 phase 气泡添帧。
2083
+ send({ type: "ready", v: PROTOCOL_VERSION, sessionId, product: product.manifest.id });
2084
+ send({ type: "tools_meta", labels: mergedToolLabels(deps.mcpConfig?.get(), product.manifest.agent.toolLabels) });
2085
+ const outcome = await engine.execute(runSpec, {
2086
+ runJob: runMemberJob,
2087
+ signal: runAbort.signal,
2088
+ emit: bridgeEngineEvent,
2089
+ ...(deps.checkpoints
2090
+ ? { persist: (o) => void persistCheckpoints(deps.checkpoints!, o.runId, o.checkpoints).catch((err) => console.error("[checkpoint] persist failed:", err)) }
2091
+ : {}),
2092
+ });
2093
+ runOutcome = outcome;
2094
+ doneSent = true;
2095
+ aborted = outcome.state === "stopped";
2096
+ runError = outcome.error;
2097
+ lastText = outcome.output;
2098
+ send({
2099
+ type: "run_done",
2100
+ runId,
2101
+ state: outcome.state as "completed" | "failed" | "stopped" | "blocked",
2102
+ usage: outcome.usage,
2103
+ output: outcome.output,
2104
+ durationMs: Date.now() - startedAt.getTime(),
2105
+ });
2106
+ } else {
2107
+ const report = engine.validate(runSpec);
2108
+ if (!report.ok) {
2109
+ // 单 phase 恒能通过;真不通过说明调用方给了非法组合。
2110
+ // **fail-open 回旧路径**:不能让客户端收到一个没有 ready 的空连接。
2111
+ console.error("[orchestrator] rejected run, falling back to direct path:", report.errors.join("; "));
2112
+ await runSingleJob();
2113
+ } else {
2114
+ await engine.execute(runSpec, { runJob: runSingleJob, signal: runAbort.signal });
1800
2115
  }
1801
- disposeProductSession(session!);
1802
- session = undefined;
1803
2116
  }
1804
2117
  } catch (err) {
1805
- runError = err instanceof Error ? err.message : String(err);
1806
- console.error("[chat] run failed:", err);
1807
- send({
1808
- type: "error",
1809
- code: "internal",
1810
- message: "服务暂时不可用,请稍后重试",
1811
- retryable: true,
1812
- });
2118
+ // 编排层自身出错不得破坏已经流出去的响应:业务错误已由 runSingleJob 内部
2119
+ // 发成 error 事件,这里只留痕。
2120
+ console.error("[orchestrator] execute failed (fail-open):", err);
2121
+ if (!started && !isFlow) await runSingleJob();
2122
+ if (isFlow && !doneSent) {
2123
+ runError = err instanceof Error ? err.message : String(err);
2124
+ send({ type: "error", code: "internal", message: "流程执行失败", retryable: true });
2125
+ }
1813
2126
  } finally {
1814
2127
  clearInterval(heartbeat);
1815
- const usage = mapper.totalUsage();
2128
+ // 多 phase 的账走引擎汇总(含 resume 恢复的历史消耗,I3);档 1 仍走主 mapper。
2129
+ const usage = isFlow && runOutcome ? runOutcome.usage : mapper.totalUsage();
1816
2130
  const durationMs = Date.now() - startedAt.getTime();
1817
2131
  try {
1818
- if (usage.total > 0) await deps.quota.record(userId, usage, persona);
2132
+ // 结算(I4):把占位换成实际消耗,多退少补。条件更新保证幂等(I6)。
2133
+ await deps.ledger.settle({ operationId, userId, persona, tokens: usage.total });
1819
2134
  // Charge after the fact: the run already spent the tokens; the balance gate stops the next one.
1820
2135
  if (billingActive) {
1821
2136
  // 池优先拆账(结算=发放检查点之二):结算时**重读**池——
@@ -1839,7 +2154,50 @@ export function createChatServer(deps: ServerDeps): Server {
1839
2154
  }
1840
2155
  // persona 在这里首次落库(与 scope 同一行、同一时刻):没跑起来的会话不该有绑定。
1841
2156
  // persona_version 与它同一次写入、同样只绑一次。
1842
- if (session) await deps.history.save(userId, scope, sessionId, exportHistory(session), persona, personaVersion);
2157
+ //
2158
+ // 多 phase 的历史只落「用户原话 + Run 汇总输出」两条:成员的内部转录是后台
2159
+ // worker 的中间产物,混进用户历史会让下次续聊把整段分工都重放一遍。成员会话
2160
+ // 各自 dispose,不 exportHistory——它们的 token 已经记在 runOutcome.usage 里。
2161
+ if (isFlow) {
2162
+ if (runOutcome) {
2163
+ const now = new Date(startedAt.getTime()).toISOString();
2164
+ const entries: FileEntry[] = [
2165
+ {
2166
+ type: "message",
2167
+ id: `${runId}:user`,
2168
+ parentId: null,
2169
+ timestamp: now,
2170
+ message: { role: "user", content: promptText, timestamp: startedAt.getTime() } as never,
2171
+ },
2172
+ {
2173
+ type: "message",
2174
+ id: `${runId}:answer`,
2175
+ parentId: `${runId}:user`,
2176
+ timestamp: now,
2177
+ message: {
2178
+ role: "assistant",
2179
+ content: [{ type: "text", text: runOutcome.output }],
2180
+ api: "openai-completions",
2181
+ provider: tier.provider,
2182
+ model: tier.model,
2183
+ usage: {
2184
+ input: usage.input,
2185
+ output: usage.output,
2186
+ cacheRead: usage.cacheRead,
2187
+ cacheWrite: usage.cacheWrite,
2188
+ totalTokens: usage.total,
2189
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usage.costUsd },
2190
+ },
2191
+ stopReason: "stop",
2192
+ timestamp: startedAt.getTime(),
2193
+ } as never,
2194
+ },
2195
+ ];
2196
+ await deps.history.save(userId, scope, sessionId, entries, persona, personaVersion);
2197
+ }
2198
+ } else if (session) {
2199
+ await deps.history.save(userId, scope, sessionId, exportHistory(session), persona, personaVersion);
2200
+ }
1843
2201
  if (deps.runLog) {
1844
2202
  await deps.runLog.record({
1845
2203
  userId,
@@ -1890,6 +2248,7 @@ export function createChatServer(deps: ServerDeps): Server {
1890
2248
  for (const settle of uiPrompts.values()) settle({ cancelled: true });
1891
2249
  uiPrompts.clear();
1892
2250
  if (session) await disposeProductSession(session);
2251
+ for (const ms of memberSessions) await disposeProductSession(ms);
1893
2252
  running.delete(runKey);
1894
2253
  pendingRuns.delete(runKey);
1895
2254
  pendingUI.delete(runKey);
@@ -1965,6 +2324,17 @@ export function createChatServer(deps: ServerDeps): Server {
1965
2324
  // 默认助手的人格 id(通用化):前端靠它把「老会话(persona 为 null)」
1966
2325
  // 认成默认助手那一批。只是一个 id,不带能力信息。
1967
2326
  defaultPersona: product.defaultPersona,
2327
+ // 多 phase 流程的**展示字段**(W4):前端据此渲染流程选择器。
2328
+ // 只出 id/label/description——phase/member/task 这些编制细节永不下发。
2329
+ ...(product.manifest.agent.flows
2330
+ ? {
2331
+ flows: Object.entries(product.manifest.agent.flows).map(([id, f]) => ({
2332
+ id,
2333
+ ...(f?.label ? { label: f.label } : {}),
2334
+ ...(f?.description ? { description: f.description } : {}),
2335
+ })),
2336
+ }
2337
+ : {}),
1968
2338
  };
1969
2339
  return sendJson(res, 200, body);
1970
2340
  }
@@ -2417,7 +2787,7 @@ export function createChatServer(deps: ServerDeps): Server {
2417
2787
  const memberActive = memberUntil !== null && Date.parse(memberUntil) > Date.now();
2418
2788
  const isMember = roles.includes("admin") || memberActive;
2419
2789
  // 配额展示看的是**这个人格**那本账(产品声明的 id)——core 不假定它叫什么。
2420
- const stats = (await deps.quota.todayStats?.(auth.userId, personaParam)) ?? { runsToday: 0, tokensToday: 0 };
2790
+ const stats = (await deps.ledger.todayStats(auth.userId, personaParam)) ?? { runsToday: 0, tokensToday: 0 };
2421
2791
  const caps = capsForPersona(limits, personaParam, isMember);
2422
2792
  // 池视图:whoami 本身就是「检查点」——会员打开订阅页即 lazy 发满当月池。
2423
2793
  let pool: WhoamiResponse["pool"] = null;