@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.
- 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 +14 -1
- package/dist/orchestrator/engine.d.ts +132 -0
- package/dist/orchestrator/engine.js +1 -0
- package/dist/orchestrator/engines/fake.d.ts +14 -0
- package/dist/orchestrator/engines/fake.js +282 -0
- package/dist/orchestrator/engines/taskflow.d.ts +4 -0
- package/dist/orchestrator/engines/taskflow.js +541 -0
- package/dist/orchestrator/run-spec.d.ts +154 -0
- package/dist/orchestrator/run-spec.js +11 -0
- package/dist/server.d.ts +21 -2
- package/dist/server.js +543 -187
- package/dist/sqlite-stores.d.ts +46 -6
- package/dist/sqlite-stores.js +292 -33
- package/dist/stores.d.ts +0 -36
- package/dist/stores.js +0 -27
- package/dist/testing.d.ts +5 -4
- package/dist/testing.js +5 -4
- package/package.json +7 -6
- package/scripts/agentchat-integrate.mjs +853 -853
- package/src/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 +14 -1
- package/src/orchestrator/engine.ts +134 -0
- package/src/orchestrator/engines/fake.ts +330 -0
- package/src/orchestrator/engines/taskflow.ts +626 -0
- package/src/orchestrator/run-spec.ts +171 -0
- package/src/server.ts +553 -183
- package/src/session.ts +689 -689
- package/src/sqlite-stores.ts +343 -35
- package/src/stores.ts +0 -41
- package/src/testing.ts +4 -4
package/dist/server.js
CHANGED
|
@@ -14,6 +14,9 @@ import { MCP_SPEC_ALLOWLIST_ENV, checkMcpDecl, mergedToolLabels, probeMcpProxy,
|
|
|
14
14
|
import { baseUrlFromModelsJson, deleteProvider, keyEnvOf, modelToProbe, patchProvider, patchRouting, patchTiers, refreshProvider, testProvider, toModelsResponse } from "./models-api.js";
|
|
15
15
|
import { buildCommands, compileSystemPrompt, createProductSession, disposeProductSession, expandCommand, exportHistory, loadProductSkills, narrowMcpExposure } from "./session.js";
|
|
16
16
|
import { auditPageWindow, toHistoryMessages, truncateLastTurn } from "./stores.js";
|
|
17
|
+
import { createTaskflowEngine } from "./orchestrator/engines/taskflow.js";
|
|
18
|
+
import { persistCheckpoints, resumeFrom as loadResumeFrom } from "./checkpoint-store.js";
|
|
19
|
+
import { toRunSpec } from "./flows.js";
|
|
17
20
|
const MAX_BODY_BYTES = 64 * 1024;
|
|
18
21
|
/** 封号闸白名单:品牌壳与申诉入口在被封状态下仍要可用。 */
|
|
19
22
|
const BAN_EXEMPT = new Set(["/api/branding", "/api/whoami"]);
|
|
@@ -1377,6 +1380,27 @@ export function createChatServer(deps) {
|
|
|
1377
1380
|
// 记下这一轮用的是第几版人格配置(0 = manifest)。与 persona 同一时刻
|
|
1378
1381
|
// 定死——用户投诉「昨天不是这么说的」时,要查的是**当时生效的那一版**,不是现在这版。
|
|
1379
1382
|
const personaVersion = deps.personaConfig ? effectivePersonaVersion(deps.personaConfig.get(), persona) : undefined;
|
|
1383
|
+
// 多 phase 入口(W4):`flow` 指向 manifest 声明的 `agent.flows.<id>`。
|
|
1384
|
+
// 不传 = 单 phase 老路径(档 1 字节流不变)。传了但 id 不存在 = 400(fail-closed,
|
|
1385
|
+
// 不让一个拼错的流程名静默退化成单助手回答——用户会以为流程跑过了)。
|
|
1386
|
+
if (body.flow !== undefined && (typeof body.flow !== "string" || !/^[a-z][a-z0-9_-]*$/.test(body.flow))) {
|
|
1387
|
+
return sendError(res, 400, "bad_request", "`flow` has an invalid format");
|
|
1388
|
+
}
|
|
1389
|
+
const flow = body.flow;
|
|
1390
|
+
if (flow !== undefined && !product.manifest.agent.flows?.[flow]) {
|
|
1391
|
+
return sendError(res, 400, "bad_request", `unknown flow "${flow}"`);
|
|
1392
|
+
}
|
|
1393
|
+
// resume 归属:`runId` 形如 `<sessionId>:<timestamp>`,前缀必须是**本会话**,
|
|
1394
|
+
// 否则等于用一个猜来的 id 把别人的产物塞进自己的回答(跨会话注入)。
|
|
1395
|
+
// 只在 flow 请求上有意义——单 phase 没有 phase checkpoint 可恢复。
|
|
1396
|
+
if (body.resumeRunId !== undefined) {
|
|
1397
|
+
if (flow === undefined) {
|
|
1398
|
+
return sendError(res, 400, "bad_request", "`resumeRunId` requires `flow`");
|
|
1399
|
+
}
|
|
1400
|
+
if (typeof body.resumeRunId !== "string" || !body.resumeRunId.startsWith(`${sessionId}:`)) {
|
|
1401
|
+
return sendError(res, 400, "bad_request", "`resumeRunId` does not belong to this session");
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1380
1404
|
// A leading "/" is UI semantics: expand it here so the command name (and the
|
|
1381
1405
|
// skill's file path) never reaches the model. Checked before quota/billing so
|
|
1382
1406
|
// a typo costs nothing and never opens a run. The surface is the scope's: an
|
|
@@ -1385,6 +1409,39 @@ export function createChatServer(deps) {
|
|
|
1385
1409
|
const expanded = expandCommand(body.message, surface.commands, surface.skills);
|
|
1386
1410
|
if ("error" in expanded)
|
|
1387
1411
|
return sendError(res, 400, "bad_request", expanded.error);
|
|
1412
|
+
// prompt 文本在**建 RunSpec 之前**就要定下来:RunSpec 的 `JobSpec.task` 会被
|
|
1413
|
+
// 引擎的 validate 检查「agent phase 必须有 task」,算晚了就恒被拒(见下方注释)。
|
|
1414
|
+
// 附件/上下文的编织是纯函数,提前算不改变任何行为。
|
|
1415
|
+
const promptText = withContext(withAttachments(expanded.message, att.attachments), body.context);
|
|
1416
|
+
// ---- RunSpec 提前构造(W4)----
|
|
1417
|
+
// 提前到 reserve / writeHead 之前,是为了让 flow 的非法声明与无断点 resume
|
|
1418
|
+
// 能以 **400** 拒绝(开了 SSE 流就改不了状态码了)。档 1(无 flow)的形状
|
|
1419
|
+
// 与接入编排层之前逐字相同——这是 I8 字节流基线的另一半保证。
|
|
1420
|
+
const startedAt = new Date();
|
|
1421
|
+
const runId = `${sessionId}:${startedAt.getTime()}`;
|
|
1422
|
+
const engine = deps.engine ?? createTaskflowEngine({ cwd: deps.dataDir });
|
|
1423
|
+
const translated = flow === undefined
|
|
1424
|
+
? { runId, phases: [{ id: "chat", kind: "agent", job: { persona, task: promptText }, final: true }] }
|
|
1425
|
+
: toRunSpec(product, flow, promptText, runId);
|
|
1426
|
+
// flow 声明的 phase 形状非法 ⇒ 400 fail-closed,而不是回退成单助手回答让用户误以为跑过。
|
|
1427
|
+
// (启动期 validateFlows 已拦过绝大多数;这里是第二道闸,也覆盖运行时注入。)
|
|
1428
|
+
if ("error" in translated)
|
|
1429
|
+
return sendError(res, 400, "bad_request", translated.error);
|
|
1430
|
+
let runSpec = translated;
|
|
1431
|
+
if (flow !== undefined && body.resumeRunId !== undefined) {
|
|
1432
|
+
if (!deps.checkpoints) {
|
|
1433
|
+
return sendError(res, 400, "bad_request", "resume is unavailable (no checkpoint store configured)");
|
|
1434
|
+
}
|
|
1435
|
+
const cp = await loadResumeFrom(deps.checkpoints, body.resumeRunId);
|
|
1436
|
+
if (!cp)
|
|
1437
|
+
return sendError(res, 400, "bad_request", "`resumeRunId` has no checkpoints to resume from");
|
|
1438
|
+
runSpec = { ...translated, resumeFrom: cp };
|
|
1439
|
+
}
|
|
1440
|
+
if (flow !== undefined) {
|
|
1441
|
+
const report = engine.validate(runSpec);
|
|
1442
|
+
if (!report.ok)
|
|
1443
|
+
return sendError(res, 400, "bad_request", `invalid flow: ${report.errors.join("; ")}`);
|
|
1444
|
+
}
|
|
1388
1445
|
// 角色决定当日上限与池。authz 未装配 = 全员
|
|
1389
1446
|
// user、caps 不传(现状);池只在会员在期时 lazy 发满当月。
|
|
1390
1447
|
const limits = product.manifest.agent.limits ?? {};
|
|
@@ -1396,22 +1453,30 @@ export function createChatServer(deps) {
|
|
|
1396
1453
|
const memberActive = memberUntil !== null && Date.parse(memberUntil) > Date.now();
|
|
1397
1454
|
const personaMember = !!deps.authz && (roles.includes("admin") || memberActive);
|
|
1398
1455
|
const poolCfg = deps.memberPool && memberActive ? (limitsForPersona(limits, persona).memberMonthlyTokenPool ?? 0) : 0;
|
|
1399
|
-
const
|
|
1400
|
-
|
|
1401
|
-
|
|
1456
|
+
const caps = deps.authz ? capsForPersona(limits, persona, personaMember) : undefined;
|
|
1457
|
+
// 预留(I4):占位成功才允许调模型。operationId 一请求一个,是幂等键(I6)。
|
|
1458
|
+
const operationId = randomUUID();
|
|
1459
|
+
const reserved = await deps.ledger.reserve({ userId, persona, caps, operationId });
|
|
1460
|
+
if (!reserved.ok)
|
|
1461
|
+
return sendError(res, 429, "quota_exceeded", reserved.reason);
|
|
1402
1462
|
// Billing gate: starting costs money, so a depleted (or never topped-up) balance stops here —
|
|
1403
1463
|
// 但池内免余额:只要当月池还有剩,余额见底也能开跑,池尽才提示充值。
|
|
1464
|
+
// 以下三条早退都在**占位之后**,所以必须先归还占位——否则用户被 402/409 拒一次,
|
|
1465
|
+
// 额度要被白占一小时(预留 TTL)。
|
|
1404
1466
|
if (billingActive && poolCfg <= 0 && (await deps.billing.balance(userId)) <= 0) {
|
|
1467
|
+
await deps.ledger.release(operationId);
|
|
1405
1468
|
return sendError(res, 402, "payment_required", "余额不足,请先充值");
|
|
1406
1469
|
}
|
|
1407
1470
|
if (billingActive && poolCfg > 0) {
|
|
1408
1471
|
const row = await deps.memberPool.getOrGrant(userId, persona, monthNow(), poolCfg);
|
|
1409
1472
|
if (Math.max(0, row.granted - row.used) <= 0 && (await deps.billing.balance(userId)) <= 0) {
|
|
1473
|
+
await deps.ledger.release(operationId);
|
|
1410
1474
|
return sendError(res, 402, "payment_required", "本月发放池已用尽且余额不足,请先充值");
|
|
1411
1475
|
}
|
|
1412
1476
|
}
|
|
1413
1477
|
const runKey = `${userId}\u0000${sessionId}`;
|
|
1414
1478
|
if (running.has(runKey)) {
|
|
1479
|
+
await deps.ledger.release(operationId);
|
|
1415
1480
|
return sendError(res, 409, "bad_request", "this session already has a run in progress");
|
|
1416
1481
|
}
|
|
1417
1482
|
running.add(runKey);
|
|
@@ -1437,7 +1502,6 @@ export function createChatServer(deps) {
|
|
|
1437
1502
|
let aborted = false;
|
|
1438
1503
|
let limitSent = false;
|
|
1439
1504
|
let runError;
|
|
1440
|
-
const startedAt = new Date();
|
|
1441
1505
|
const confirms = new Map();
|
|
1442
1506
|
pendingRuns.set(runKey, confirms);
|
|
1443
1507
|
const uiPrompts = new Map();
|
|
@@ -1452,203 +1516,439 @@ export function createChatServer(deps) {
|
|
|
1452
1516
|
console.error("[audit] run.start failed (fail-open):", err);
|
|
1453
1517
|
}
|
|
1454
1518
|
}
|
|
1455
|
-
try
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
persona
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
const cooldownSeconds = modelCfg?.routing.cooldownSeconds ?? 120;
|
|
1493
|
-
const promptText = withContext(withAttachments(expanded.message, att.attachments), body.context);
|
|
1494
|
-
const promptImages = parsed.images.length > 0 ? { images: parsed.images } : undefined;
|
|
1495
|
-
const buildSession = (candidate) => createProductSession({
|
|
1496
|
-
product,
|
|
1497
|
-
modelRuntime: deps.modelRuntime,
|
|
1498
|
-
tools,
|
|
1499
|
-
userId,
|
|
1500
|
-
personaConfig: deps.personaConfig,
|
|
1501
|
-
dataDir: deps.dataDir,
|
|
1502
|
-
// 档位语义(label/thinking/multiplier)仍来自 manifest,只有物理模型跟着候选走。
|
|
1503
|
-
tier: candidate.provider === tier.provider && candidate.model === tier.model
|
|
1504
|
-
? tier
|
|
1505
|
-
: { ...tier, provider: candidate.provider, model: candidate.model },
|
|
1506
|
-
qual: scope,
|
|
1507
|
-
persona,
|
|
1508
|
-
history,
|
|
1509
|
-
mcpConfig: deps.mcpConfig,
|
|
1510
|
-
requestConfirm: (info) => new Promise((resolve) => {
|
|
1511
|
-
const settle = (allow) => {
|
|
1512
|
-
clearTimeout(timer);
|
|
1513
|
-
confirms.delete(info.toolCallId);
|
|
1514
|
-
resolve(allow);
|
|
1515
|
-
};
|
|
1516
|
-
const timer = setTimeout(() => settle(false), CONFIRM_TIMEOUT_MS);
|
|
1517
|
-
confirms.set(info.toolCallId, settle);
|
|
1518
|
-
send({ type: "tool_confirm", toolCallId: info.toolCallId, name: info.name, args: info.args });
|
|
1519
|
-
}),
|
|
1520
|
-
// Extension dialogs (batch 3-4b): same pause-and-answer shape as the
|
|
1521
|
-
// confirm gate, but answered through POST /api/ui-response. Nobody
|
|
1522
|
-
// answering means the fail-closed default, never a hung run.
|
|
1523
|
-
requestUI: (info, signal) => new Promise((resolve) => {
|
|
1524
|
-
const settle = (answer) => {
|
|
1525
|
-
clearTimeout(timer);
|
|
1526
|
-
signal?.removeEventListener("abort", onAbort);
|
|
1527
|
-
uiPrompts.delete(info.id);
|
|
1528
|
-
resolve(answer);
|
|
1529
|
-
};
|
|
1530
|
-
const onAbort = () => settle({ cancelled: true });
|
|
1531
|
-
const timeoutMs = info.timeoutMs
|
|
1532
|
-
? Math.min(Math.max(info.timeoutMs, UI_TIMEOUT_MIN_MS), UI_TIMEOUT_MAX_MS)
|
|
1533
|
-
: UI_TIMEOUT_MS;
|
|
1534
|
-
const timer = setTimeout(() => settle({ cancelled: true }), timeoutMs);
|
|
1535
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1536
|
-
uiPrompts.set(info.id, settle);
|
|
1537
|
-
send({
|
|
1538
|
-
type: "ui_prompt",
|
|
1539
|
-
id: info.id,
|
|
1540
|
-
kind: info.kind,
|
|
1541
|
-
title: info.title,
|
|
1542
|
-
...(info.message !== undefined ? { message: info.message } : {}),
|
|
1543
|
-
...(info.options !== undefined ? { options: info.options } : {}),
|
|
1544
|
-
...(info.placeholder !== undefined ? { placeholder: info.placeholder } : {}),
|
|
1545
|
-
});
|
|
1546
|
-
}),
|
|
1547
|
-
onUINotify: (message, level) => send({ type: "ui_notify", message, level }),
|
|
1548
|
-
});
|
|
1549
|
-
// Client went away: stop spending tokens(读的是当前那一次尝试的会话)。
|
|
1550
|
-
res.on("close", () => {
|
|
1551
|
-
if (!res.writableEnded)
|
|
1552
|
-
void session?.abort();
|
|
1553
|
-
});
|
|
1554
|
-
for (let attempt = 0;; attempt++) {
|
|
1555
|
-
const candidate = chain[attempt];
|
|
1556
|
-
session = await buildSession(candidate);
|
|
1557
|
-
// 一次尝试内只有「还没吐字、还没跑工具」才允许换候选:重发会把已经流出去的
|
|
1558
|
-
// 半句话再发一遍,或把已经发生的工具副作用再执行一遍。这条边界是 v1 的口径。
|
|
1559
|
-
let pendingFailover;
|
|
1560
|
-
let attemptText = false;
|
|
1561
|
-
const toolRoundsAtStart = accounting.toolRounds();
|
|
1562
|
-
session.subscribe((event) => {
|
|
1563
|
-
const outs = mapper.map(event);
|
|
1564
|
-
// 同一批里出现 model_error 且这次还能切:**整批吞掉**——包括那条空的
|
|
1565
|
-
// message_end,否则前端会先落一个空气泡再被真正的回答顶下去。
|
|
1566
|
-
const errOut = outs.find((o) => o.type === "error" && o.code === "model_error");
|
|
1567
|
-
if (errOut && errOut.type === "error") {
|
|
1568
|
-
// 判定用 pi 原始报错(rawModelError),不是折叠后的用户文案——文案里
|
|
1569
|
-
// 已经没有 JSON/网络词,拿它匹配会让 failover 失明(2026-11-04)。
|
|
1570
|
-
const canSwitch = failoverOn && attempt < chain.length - 1 && !attemptText && accounting.toolRounds() === toolRoundsAtStart;
|
|
1571
|
-
if (canSwitch && isRetryableModelError(rawModelError(event))) {
|
|
1572
|
-
// 用户不该看到一次注定会被掩盖的失败(也不显示模型名)。
|
|
1573
|
-
pendingFailover = { message: rawModelError(event) };
|
|
1574
|
-
void session?.abort();
|
|
1575
|
-
return;
|
|
1519
|
+
// 单 phase 通路:把原来这一整段 try 体原样搬进 runSingleJob(缩进变了、语义没变)。
|
|
1520
|
+
// 为什么搬而不重写:里面的 pendingFailover 吞批、toolRoundsAtStart 判定、
|
|
1521
|
+
// limitSent 后 abort 都是逐次修出来的,重写必回退旧 bug。
|
|
1522
|
+
// runSingleJob 不发任何编排事件,SSE 字节流与接入编排层之前完全一致(I8)。
|
|
1523
|
+
let lastText = "";
|
|
1524
|
+
/** runSingleJob 是否已跑过——引擎抛错时据此判断要不要 fail-open 补跑一次。 */
|
|
1525
|
+
let started = false;
|
|
1526
|
+
const runSingleJob = async () => {
|
|
1527
|
+
started = true;
|
|
1528
|
+
try {
|
|
1529
|
+
send({ type: "ready", v: PROTOCOL_VERSION, sessionId, product: product.manifest.id });
|
|
1530
|
+
// 工具中文名随首帧一次性下发(用户视角不显示 mcp__ 声明名)。
|
|
1531
|
+
send({ type: "tools_meta", labels: mergedToolLabels(deps.mcpConfig?.get(), product.manifest.agent.toolLabels) });
|
|
1532
|
+
const history = await deps.history.load(userId, scope, sessionId);
|
|
1533
|
+
// persona 与 createFeedback 一起注入:产品据此决定造哪些工具,工具本身碰不到 store。
|
|
1534
|
+
// 工单正文由服务端截断、补 ref、按 roles 定优先级——模型只能递内容,改不了归属。
|
|
1535
|
+
const feedbackSink = deps.feedback;
|
|
1536
|
+
const tools = deps.toolFactory({
|
|
1537
|
+
productId: product.manifest.id,
|
|
1538
|
+
productDir: product.dir,
|
|
1539
|
+
userId,
|
|
1540
|
+
dataDir: deps.dataDir,
|
|
1541
|
+
qual: scope,
|
|
1542
|
+
persona,
|
|
1543
|
+
...(feedbackSink
|
|
1544
|
+
? {
|
|
1545
|
+
createFeedback: async (content) => {
|
|
1546
|
+
const row = await feedbackSink.submit({
|
|
1547
|
+
userId,
|
|
1548
|
+
kind: "other",
|
|
1549
|
+
content,
|
|
1550
|
+
sessionId,
|
|
1551
|
+
ref: `${persona}:${sessionId}`,
|
|
1552
|
+
priority: roles.includes("member") || roles.includes("admin") ? "high" : "normal",
|
|
1553
|
+
});
|
|
1554
|
+
return { id: row.id ?? 0 };
|
|
1555
|
+
},
|
|
1576
1556
|
}
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1557
|
+
: {}),
|
|
1558
|
+
});
|
|
1559
|
+
// ---- 失败切换(设计稿):run 开始定一条有序候选链,模型调用失败换下一条。
|
|
1560
|
+
// 链来自 model-config 的档位绑定;没配置就是 manifest 的单模型(链长 1 ⇒ 永不切换)。
|
|
1561
|
+
const modelCfg = deps.modelConfig?.get();
|
|
1562
|
+
const cooldown = deps.modelCooldown ?? processCooldown;
|
|
1563
|
+
const chain = orderChain(resolveChain(product, body.tier, modelCfg), cooldown);
|
|
1564
|
+
const failoverOn = modelCfg?.routing.failover ?? true;
|
|
1565
|
+
const cooldownSeconds = modelCfg?.routing.cooldownSeconds ?? 120;
|
|
1566
|
+
const promptImages = parsed.images.length > 0 ? { images: parsed.images } : undefined;
|
|
1567
|
+
const buildSession = (candidate) => createProductSession({
|
|
1568
|
+
product,
|
|
1569
|
+
modelRuntime: deps.modelRuntime,
|
|
1570
|
+
tools,
|
|
1571
|
+
userId,
|
|
1572
|
+
personaConfig: deps.personaConfig,
|
|
1573
|
+
dataDir: deps.dataDir,
|
|
1574
|
+
// 档位语义(label/thinking/multiplier)仍来自 manifest,只有物理模型跟着候选走。
|
|
1575
|
+
tier: candidate.provider === tier.provider && candidate.model === tier.model
|
|
1576
|
+
? tier
|
|
1577
|
+
: { ...tier, provider: candidate.provider, model: candidate.model },
|
|
1578
|
+
qual: scope,
|
|
1579
|
+
persona,
|
|
1580
|
+
history,
|
|
1581
|
+
mcpConfig: deps.mcpConfig,
|
|
1582
|
+
requestConfirm: (info) => new Promise((resolve) => {
|
|
1583
|
+
const settle = (allow) => {
|
|
1584
|
+
clearTimeout(timer);
|
|
1585
|
+
confirms.delete(info.toolCallId);
|
|
1586
|
+
resolve(allow);
|
|
1587
|
+
};
|
|
1588
|
+
const timer = setTimeout(() => settle(false), CONFIRM_TIMEOUT_MS);
|
|
1589
|
+
confirms.set(info.toolCallId, settle);
|
|
1590
|
+
send({ type: "tool_confirm", toolCallId: info.toolCallId, name: info.name, args: info.args });
|
|
1591
|
+
}),
|
|
1592
|
+
// Extension dialogs (batch 3-4b): same pause-and-answer shape as the
|
|
1593
|
+
// confirm gate, but answered through POST /api/ui-response. Nobody
|
|
1594
|
+
// answering means the fail-closed default, never a hung run.
|
|
1595
|
+
requestUI: (info, signal) => new Promise((resolve) => {
|
|
1596
|
+
const settle = (answer) => {
|
|
1597
|
+
clearTimeout(timer);
|
|
1598
|
+
signal?.removeEventListener("abort", onAbort);
|
|
1599
|
+
uiPrompts.delete(info.id);
|
|
1600
|
+
resolve(answer);
|
|
1601
|
+
};
|
|
1602
|
+
const onAbort = () => settle({ cancelled: true });
|
|
1603
|
+
const timeoutMs = info.timeoutMs
|
|
1604
|
+
? Math.min(Math.max(info.timeoutMs, UI_TIMEOUT_MIN_MS), UI_TIMEOUT_MAX_MS)
|
|
1605
|
+
: UI_TIMEOUT_MS;
|
|
1606
|
+
const timer = setTimeout(() => settle({ cancelled: true }), timeoutMs);
|
|
1607
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
1608
|
+
uiPrompts.set(info.id, settle);
|
|
1609
|
+
send({
|
|
1610
|
+
type: "ui_prompt",
|
|
1611
|
+
id: info.id,
|
|
1612
|
+
kind: info.kind,
|
|
1613
|
+
title: info.title,
|
|
1614
|
+
...(info.message !== undefined ? { message: info.message } : {}),
|
|
1615
|
+
...(info.options !== undefined ? { options: info.options } : {}),
|
|
1616
|
+
...(info.placeholder !== undefined ? { placeholder: info.placeholder } : {}),
|
|
1617
|
+
});
|
|
1618
|
+
}),
|
|
1619
|
+
onUINotify: (message, level) => send({ type: "ui_notify", message, level }),
|
|
1620
|
+
});
|
|
1621
|
+
// Client went away: stop spending tokens(读的是当前那一次尝试的会话)。
|
|
1622
|
+
res.on("close", () => {
|
|
1623
|
+
if (!res.writableEnded)
|
|
1624
|
+
void session?.abort();
|
|
1625
|
+
});
|
|
1626
|
+
for (let attempt = 0;; attempt++) {
|
|
1627
|
+
const candidate = chain[attempt];
|
|
1628
|
+
session = await buildSession(candidate);
|
|
1629
|
+
// 一次尝试内只有「还没吐字、还没跑工具」才允许换候选:重发会把已经流出去的
|
|
1630
|
+
// 半句话再发一遍,或把已经发生的工具副作用再执行一遍。这条边界是 v1 的口径。
|
|
1631
|
+
let pendingFailover;
|
|
1632
|
+
let attemptText = false;
|
|
1633
|
+
const toolRoundsAtStart = accounting.toolRounds();
|
|
1634
|
+
session.subscribe((event) => {
|
|
1635
|
+
const outs = mapper.map(event);
|
|
1636
|
+
// 同一批里出现 model_error 且这次还能切:**整批吞掉**——包括那条空的
|
|
1637
|
+
// message_end,否则前端会先落一个空气泡再被真正的回答顶下去。
|
|
1638
|
+
const errOut = outs.find((o) => o.type === "error" && o.code === "model_error");
|
|
1639
|
+
if (errOut && errOut.type === "error") {
|
|
1640
|
+
// 判定用 pi 原始报错(rawModelError),不是折叠后的用户文案——文案里
|
|
1641
|
+
// 已经没有 JSON/网络词,拿它匹配会让 failover 失明(2026-11-04)。
|
|
1642
|
+
const canSwitch = failoverOn && attempt < chain.length - 1 && !attemptText && accounting.toolRounds() === toolRoundsAtStart;
|
|
1643
|
+
if (canSwitch && isRetryableModelError(rawModelError(event))) {
|
|
1644
|
+
// 用户不该看到一次注定会被掩盖的失败(也不显示模型名)。
|
|
1645
|
+
pendingFailover = { message: rawModelError(event) };
|
|
1646
|
+
void session?.abort();
|
|
1647
|
+
return;
|
|
1648
|
+
}
|
|
1586
1649
|
}
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1650
|
+
for (const out of outs) {
|
|
1651
|
+
if (out.type === "text_delta" || out.type === "thinking_delta")
|
|
1652
|
+
attemptText = true;
|
|
1653
|
+
// 引擎的 RunOutcome.output 要能反映这轮回答;取最后一条 message_end 的全文。
|
|
1654
|
+
if (out.type === "message_end")
|
|
1655
|
+
lastText = out.text;
|
|
1656
|
+
if (out.type === "done") {
|
|
1657
|
+
if (pendingFailover)
|
|
1658
|
+
return; // abort 带出来的 done 不发——真正的收口在最后一次尝试
|
|
1659
|
+
doneSent = true;
|
|
1660
|
+
aborted = out.aborted;
|
|
1661
|
+
}
|
|
1662
|
+
accounting.observe(out);
|
|
1663
|
+
if (out.type === "tool_end")
|
|
1664
|
+
toolCalls[out.name] = (toolCalls[out.name] ?? 0) + 1;
|
|
1665
|
+
send(out);
|
|
1666
|
+
if (accounting.limitHit() && !limitSent) {
|
|
1667
|
+
// One prompt must not loop forever: stop it at the cap, with a reason.
|
|
1668
|
+
limitSent = true;
|
|
1669
|
+
send({
|
|
1670
|
+
type: "error",
|
|
1671
|
+
code: "limit_exceeded",
|
|
1672
|
+
message: `已达到单次运行 ${limits.maxToolRounds} 轮工具调用上限,已中止`,
|
|
1673
|
+
retryable: false,
|
|
1674
|
+
});
|
|
1675
|
+
void session?.abort();
|
|
1676
|
+
}
|
|
1601
1677
|
}
|
|
1678
|
+
});
|
|
1679
|
+
try {
|
|
1680
|
+
await session.prompt(promptText, promptImages);
|
|
1681
|
+
await session.waitForIdle();
|
|
1682
|
+
}
|
|
1683
|
+
catch (err) {
|
|
1684
|
+
// abort 引起的抛出是切换路径的一部分;没有待切换的错误就照旧冒泡。
|
|
1685
|
+
if (!pendingFailover)
|
|
1686
|
+
throw err;
|
|
1602
1687
|
}
|
|
1603
|
-
});
|
|
1604
|
-
try {
|
|
1605
|
-
await session.prompt(promptText, promptImages);
|
|
1606
|
-
await session.waitForIdle();
|
|
1607
|
-
}
|
|
1608
|
-
catch (err) {
|
|
1609
|
-
// abort 引起的抛出是切换路径的一部分;没有待切换的错误就照旧冒泡。
|
|
1610
1688
|
if (!pendingFailover)
|
|
1611
|
-
|
|
1689
|
+
break;
|
|
1690
|
+
// 换下一条:打冷却、留痕、告知用户,然后**重建会话**重发同一个 prompt。
|
|
1691
|
+
// 不用 session.setModel 原地重发——会话里已经记了这次失败的用户消息,重发会让
|
|
1692
|
+
// 历史多一条一模一样的提问;重建用的是 run 开始时那份 history,干净。
|
|
1693
|
+
cooldown.mark(candidate, cooldownSeconds);
|
|
1694
|
+
send({ type: "ui_notify", message: FAILOVER_NOTICE, level: "warning" });
|
|
1695
|
+
if (deps.audit) {
|
|
1696
|
+
void deps.audit
|
|
1697
|
+
.append({
|
|
1698
|
+
actor: userId,
|
|
1699
|
+
result: "ok",
|
|
1700
|
+
action: MODEL_SWITCH,
|
|
1701
|
+
target: `session:${sessionId}`,
|
|
1702
|
+
meta: { from: candidateKey(candidate), to: candidateKey(chain[attempt + 1]), reason: pendingFailover.message.slice(0, 200) },
|
|
1703
|
+
})
|
|
1704
|
+
.catch((err) => console.error("[audit] model.switch failed (fail-open):", err));
|
|
1705
|
+
}
|
|
1706
|
+
disposeProductSession(session);
|
|
1707
|
+
session = undefined;
|
|
1612
1708
|
}
|
|
1613
|
-
|
|
1709
|
+
}
|
|
1710
|
+
catch (err) {
|
|
1711
|
+
runError = err instanceof Error ? err.message : String(err);
|
|
1712
|
+
console.error("[chat] run failed:", err);
|
|
1713
|
+
send({
|
|
1714
|
+
type: "error",
|
|
1715
|
+
code: "internal",
|
|
1716
|
+
message: "服务暂时不可用,请稍后重试",
|
|
1717
|
+
retryable: true,
|
|
1718
|
+
});
|
|
1719
|
+
}
|
|
1720
|
+
return {
|
|
1721
|
+
output: lastText,
|
|
1722
|
+
ok: runError === undefined,
|
|
1723
|
+
usage: mapper.totalUsage(),
|
|
1724
|
+
stopReason: runError === undefined ? "end_turn" : "error",
|
|
1725
|
+
...(runError !== undefined ? { error: runError } : {}),
|
|
1726
|
+
};
|
|
1727
|
+
};
|
|
1728
|
+
// 一次 Run = 一个 agent phase。引擎只负责「校验 + 调 runJob + 汇总 usage」,
|
|
1729
|
+
// 真正的会话逻辑全在 runSingleJob 里,所以档 1 的行为与接入前逐字节一致。
|
|
1730
|
+
//
|
|
1731
|
+
// `JobSpec.task` 必须是真实的 prompt:它是 `RunSpec` 里唯一描述「这个 phase
|
|
1732
|
+
// 要干什么」的字段,引擎的静态校验会拒空 task。曾经这里是 `promptForEngine`
|
|
1733
|
+
// 变量、在 runSingleJob 内部才赋值,于是构造 runSpec 时它恒为空串 ⇒ validate
|
|
1734
|
+
// 恒拒 ⇒ 每次都静默 fail-open 回直连,**编排层在 W1/W2/W3 期间一次都没真正执行过**。
|
|
1735
|
+
// 由 `wire-baseline.test.ts` 的快照基线抓出来(它同时钉住档 1 的字节流)。
|
|
1736
|
+
const runAbort = new AbortController();
|
|
1737
|
+
const isFlow = flow !== undefined;
|
|
1738
|
+
/** 多 phase 的成员会话各自独立;档 1 恒为空(单 phase 仍用上面的 `session`)。 */
|
|
1739
|
+
const memberSessions = [];
|
|
1740
|
+
/** 入口 phase(无 dependsOn)才继承会话历史,其余成员从空上下文起跑。 */
|
|
1741
|
+
const entryPhaseIds = new Set(runSpec.phases.filter((p) => (p.dependsOn ?? []).length === 0).map((p) => p.id));
|
|
1742
|
+
/** 引擎收口产物;档 1 不用它,多 phase 的 usage/run_done 都从这里出。 */
|
|
1743
|
+
let runOutcome;
|
|
1744
|
+
/**
|
|
1745
|
+
* 多 phase 的一个成员 worker(W4)。与 `runSingleJob` 刻意分开写:
|
|
1746
|
+
* 那一路的每一帧都被 `wire-baseline.test.ts` 逐字节钉住,塞分支进来必回退。
|
|
1747
|
+
*
|
|
1748
|
+
* 成员路径的四条纪律:
|
|
1749
|
+
* ① 每个 job 一个独立 `createProductSession`(persona/task 来自 JobSpec);
|
|
1750
|
+
* ② 文本只走 `ctx.onDelta`(→ `member_delta`),**不发** text_delta / thinking_delta——
|
|
1751
|
+
* 多 phase 的用户视图是成员卡片,不是一根合并的气泡;
|
|
1752
|
+
* ③ 工具/确认/UI 事件一律不转发主线程(成员是后台 worker,不该弹确认卡);
|
|
1753
|
+
* ④ usage 只记在**局部** mapper 上,由引擎汇总,不碰主 `mapper`/`accounting`。
|
|
1754
|
+
*/
|
|
1755
|
+
const runMemberJob = async (job, ctx) => {
|
|
1756
|
+
const memberMapper = createEventMapper();
|
|
1757
|
+
let memberText = "";
|
|
1758
|
+
let memberError;
|
|
1759
|
+
try {
|
|
1760
|
+
const history = entryPhaseIds.has(ctx.phaseId) ? ((await deps.history.load(userId, scope, sessionId)) ?? []) : [];
|
|
1761
|
+
const feedbackSink = deps.feedback;
|
|
1762
|
+
const tools = deps.toolFactory({
|
|
1763
|
+
productId: product.manifest.id,
|
|
1764
|
+
productDir: product.dir,
|
|
1765
|
+
userId,
|
|
1766
|
+
dataDir: deps.dataDir,
|
|
1767
|
+
qual: scope,
|
|
1768
|
+
persona: job.persona,
|
|
1769
|
+
...(feedbackSink
|
|
1770
|
+
? {
|
|
1771
|
+
createFeedback: async (content) => {
|
|
1772
|
+
const row = await feedbackSink.submit({
|
|
1773
|
+
userId,
|
|
1774
|
+
kind: "other",
|
|
1775
|
+
content,
|
|
1776
|
+
sessionId,
|
|
1777
|
+
ref: `${job.persona}:${sessionId}`,
|
|
1778
|
+
priority: roles.includes("member") || roles.includes("admin") ? "high" : "normal",
|
|
1779
|
+
});
|
|
1780
|
+
return { id: row.id ?? 0 };
|
|
1781
|
+
},
|
|
1782
|
+
}
|
|
1783
|
+
: {}),
|
|
1784
|
+
});
|
|
1785
|
+
const ms = await createProductSession({
|
|
1786
|
+
product,
|
|
1787
|
+
modelRuntime: deps.modelRuntime,
|
|
1788
|
+
tools,
|
|
1789
|
+
userId,
|
|
1790
|
+
personaConfig: deps.personaConfig,
|
|
1791
|
+
dataDir: deps.dataDir,
|
|
1792
|
+
tier,
|
|
1793
|
+
qual: scope,
|
|
1794
|
+
persona: job.persona,
|
|
1795
|
+
history,
|
|
1796
|
+
mcpConfig: deps.mcpConfig,
|
|
1797
|
+
// 成员是后台 worker:没人盯着确认卡,fail-closed 拒绝才是正确默认。
|
|
1798
|
+
requestConfirm: async () => false,
|
|
1799
|
+
});
|
|
1800
|
+
memberSessions.push(ms);
|
|
1801
|
+
const onAbort = () => void ms.abort();
|
|
1802
|
+
if (ctx.signal.aborted)
|
|
1803
|
+
onAbort();
|
|
1804
|
+
else
|
|
1805
|
+
ctx.signal.addEventListener("abort", onAbort, { once: true });
|
|
1806
|
+
ms.subscribe((event) => {
|
|
1807
|
+
for (const out of memberMapper.map(event)) {
|
|
1808
|
+
if (out.type === "text_delta" || out.type === "thinking_delta")
|
|
1809
|
+
ctx.onDelta?.(out.delta);
|
|
1810
|
+
if (out.type === "message_end")
|
|
1811
|
+
memberText = out.text;
|
|
1812
|
+
// tool_* / done / error:不转发,成员气泡只显示文本与状态。
|
|
1813
|
+
}
|
|
1814
|
+
});
|
|
1815
|
+
await ms.prompt(job.task, undefined);
|
|
1816
|
+
await ms.waitForIdle();
|
|
1817
|
+
ctx.signal.removeEventListener("abort", onAbort);
|
|
1818
|
+
}
|
|
1819
|
+
catch (err) {
|
|
1820
|
+
memberError = err instanceof Error ? err.message : String(err);
|
|
1821
|
+
console.error("[orchestrator] member job failed:", err);
|
|
1822
|
+
send({ type: "error", code: "internal", message: `成员 ${job.persona} 执行失败`, retryable: false });
|
|
1823
|
+
}
|
|
1824
|
+
const usage = memberMapper.totalUsage();
|
|
1825
|
+
return {
|
|
1826
|
+
output: memberText,
|
|
1827
|
+
ok: memberError === undefined,
|
|
1828
|
+
usage: {
|
|
1829
|
+
input: usage.input,
|
|
1830
|
+
output: usage.output,
|
|
1831
|
+
cacheRead: usage.cacheRead,
|
|
1832
|
+
cacheWrite: usage.cacheWrite,
|
|
1833
|
+
total: usage.total,
|
|
1834
|
+
costUsd: usage.costUsd,
|
|
1835
|
+
},
|
|
1836
|
+
stopReason: memberError === undefined ? "end_turn" : "error",
|
|
1837
|
+
...(memberError !== undefined ? { error: memberError } : {}),
|
|
1838
|
+
};
|
|
1839
|
+
};
|
|
1840
|
+
/** EngineEvent(内部)→ ChatEvent(协议)+ runId。单 phase 时引擎不发事件,这个桥用不到。 */
|
|
1841
|
+
const bridgeEngineEvent = (ev) => {
|
|
1842
|
+
switch (ev.type) {
|
|
1843
|
+
case "member_started":
|
|
1844
|
+
send({ type: "member_started", runId, phaseId: ev.phaseId, memberId: ev.memberId, task: ev.task });
|
|
1845
|
+
if (deps.checkpoints) {
|
|
1846
|
+
void deps.checkpoints
|
|
1847
|
+
.saveJob(runId, {
|
|
1848
|
+
runId,
|
|
1849
|
+
phaseId: ev.phaseId,
|
|
1850
|
+
jobId: ev.jobId,
|
|
1851
|
+
state: "running",
|
|
1852
|
+
usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, costUsd: 0 },
|
|
1853
|
+
leaseUntil: Date.now() + 5 * 60_000,
|
|
1854
|
+
})
|
|
1855
|
+
.catch((err) => console.error("[checkpoint] saveJob(running) failed:", err));
|
|
1856
|
+
}
|
|
1857
|
+
break;
|
|
1858
|
+
case "member_delta":
|
|
1859
|
+
send({ type: "member_delta", runId, phaseId: ev.phaseId, memberId: ev.memberId, delta: ev.delta });
|
|
1860
|
+
break;
|
|
1861
|
+
case "member_done": {
|
|
1862
|
+
const u = ev.usage;
|
|
1863
|
+
const usage = {
|
|
1864
|
+
input: u.input,
|
|
1865
|
+
output: u.output,
|
|
1866
|
+
cacheRead: u.cacheRead ?? 0,
|
|
1867
|
+
cacheWrite: u.cacheWrite ?? 0,
|
|
1868
|
+
total: u.total,
|
|
1869
|
+
costUsd: u.costUsd ?? 0,
|
|
1870
|
+
};
|
|
1871
|
+
send({ type: "member_done", runId, phaseId: ev.phaseId, memberId: ev.memberId, state: ev.state, usage });
|
|
1872
|
+
if (deps.checkpoints) {
|
|
1873
|
+
void deps.checkpoints
|
|
1874
|
+
.saveJob(runId, { runId, phaseId: ev.phaseId, jobId: ev.jobId, state: ev.state, usage })
|
|
1875
|
+
.catch((err) => console.error("[checkpoint] saveJob(done) failed:", err));
|
|
1876
|
+
}
|
|
1614
1877
|
break;
|
|
1615
|
-
// 换下一条:打冷却、留痕、告知用户,然后**重建会话**重发同一个 prompt。
|
|
1616
|
-
// 不用 session.setModel 原地重发——会话里已经记了这次失败的用户消息,重发会让
|
|
1617
|
-
// 历史多一条一模一样的提问;重建用的是 run 开始时那份 history,干净。
|
|
1618
|
-
cooldown.mark(candidate, cooldownSeconds);
|
|
1619
|
-
send({ type: "ui_notify", message: FAILOVER_NOTICE, level: "warning" });
|
|
1620
|
-
if (deps.audit) {
|
|
1621
|
-
void deps.audit
|
|
1622
|
-
.append({
|
|
1623
|
-
actor: userId,
|
|
1624
|
-
result: "ok",
|
|
1625
|
-
action: MODEL_SWITCH,
|
|
1626
|
-
target: `session:${sessionId}`,
|
|
1627
|
-
meta: { from: candidateKey(candidate), to: candidateKey(chain[attempt + 1]), reason: pendingFailover.message.slice(0, 200) },
|
|
1628
|
-
})
|
|
1629
|
-
.catch((err) => console.error("[audit] model.switch failed (fail-open):", err));
|
|
1630
1878
|
}
|
|
1631
|
-
|
|
1632
|
-
|
|
1879
|
+
default:
|
|
1880
|
+
// phase_started / phase_settled:协议里没有对应事件,刻意不下发。
|
|
1881
|
+
break;
|
|
1882
|
+
}
|
|
1883
|
+
};
|
|
1884
|
+
// 客户端断开 → abort 所有成员会话(单 phase 的会话由 runSingleJob 内部的 close 监听处理)。
|
|
1885
|
+
if (isFlow) {
|
|
1886
|
+
res.on("close", () => {
|
|
1887
|
+
if (!res.writableEnded)
|
|
1888
|
+
for (const ms of memberSessions)
|
|
1889
|
+
void ms.abort();
|
|
1890
|
+
});
|
|
1891
|
+
}
|
|
1892
|
+
try {
|
|
1893
|
+
if (isFlow) {
|
|
1894
|
+
// 多 phase 也发 ready/tools_meta 作为传输头——前端的 sessionId 绑定与工具名
|
|
1895
|
+
// 都依赖它们;但成员事件从 member_started 开始,不给单 phase 气泡添帧。
|
|
1896
|
+
send({ type: "ready", v: PROTOCOL_VERSION, sessionId, product: product.manifest.id });
|
|
1897
|
+
send({ type: "tools_meta", labels: mergedToolLabels(deps.mcpConfig?.get(), product.manifest.agent.toolLabels) });
|
|
1898
|
+
const outcome = await engine.execute(runSpec, {
|
|
1899
|
+
runJob: runMemberJob,
|
|
1900
|
+
signal: runAbort.signal,
|
|
1901
|
+
emit: bridgeEngineEvent,
|
|
1902
|
+
...(deps.checkpoints
|
|
1903
|
+
? { persist: (o) => void persistCheckpoints(deps.checkpoints, o.runId, o.checkpoints).catch((err) => console.error("[checkpoint] persist failed:", err)) }
|
|
1904
|
+
: {}),
|
|
1905
|
+
});
|
|
1906
|
+
runOutcome = outcome;
|
|
1907
|
+
doneSent = true;
|
|
1908
|
+
aborted = outcome.state === "stopped";
|
|
1909
|
+
runError = outcome.error;
|
|
1910
|
+
lastText = outcome.output;
|
|
1911
|
+
send({
|
|
1912
|
+
type: "run_done",
|
|
1913
|
+
runId,
|
|
1914
|
+
state: outcome.state,
|
|
1915
|
+
usage: outcome.usage,
|
|
1916
|
+
output: outcome.output,
|
|
1917
|
+
durationMs: Date.now() - startedAt.getTime(),
|
|
1918
|
+
});
|
|
1919
|
+
}
|
|
1920
|
+
else {
|
|
1921
|
+
const report = engine.validate(runSpec);
|
|
1922
|
+
if (!report.ok) {
|
|
1923
|
+
// 单 phase 恒能通过;真不通过说明调用方给了非法组合。
|
|
1924
|
+
// **fail-open 回旧路径**:不能让客户端收到一个没有 ready 的空连接。
|
|
1925
|
+
console.error("[orchestrator] rejected run, falling back to direct path:", report.errors.join("; "));
|
|
1926
|
+
await runSingleJob();
|
|
1927
|
+
}
|
|
1928
|
+
else {
|
|
1929
|
+
await engine.execute(runSpec, { runJob: runSingleJob, signal: runAbort.signal });
|
|
1930
|
+
}
|
|
1633
1931
|
}
|
|
1634
1932
|
}
|
|
1635
1933
|
catch (err) {
|
|
1636
|
-
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1934
|
+
// 编排层自身出错不得破坏已经流出去的响应:业务错误已由 runSingleJob 内部
|
|
1935
|
+
// 发成 error 事件,这里只留痕。
|
|
1936
|
+
console.error("[orchestrator] execute failed (fail-open):", err);
|
|
1937
|
+
if (!started && !isFlow)
|
|
1938
|
+
await runSingleJob();
|
|
1939
|
+
if (isFlow && !doneSent) {
|
|
1940
|
+
runError = err instanceof Error ? err.message : String(err);
|
|
1941
|
+
send({ type: "error", code: "internal", message: "流程执行失败", retryable: true });
|
|
1942
|
+
}
|
|
1644
1943
|
}
|
|
1645
1944
|
finally {
|
|
1646
1945
|
clearInterval(heartbeat);
|
|
1647
|
-
|
|
1946
|
+
// 多 phase 的账走引擎汇总(含 resume 恢复的历史消耗,I3);档 1 仍走主 mapper。
|
|
1947
|
+
const usage = isFlow && runOutcome ? runOutcome.usage : mapper.totalUsage();
|
|
1648
1948
|
const durationMs = Date.now() - startedAt.getTime();
|
|
1649
1949
|
try {
|
|
1650
|
-
|
|
1651
|
-
|
|
1950
|
+
// 结算(I4):把占位换成实际消耗,多退少补。条件更新保证幂等(I6)。
|
|
1951
|
+
await deps.ledger.settle({ operationId, userId, persona, tokens: usage.total });
|
|
1652
1952
|
// Charge after the fact: the run already spent the tokens; the balance gate stops the next one.
|
|
1653
1953
|
if (billingActive) {
|
|
1654
1954
|
// 池优先拆账(结算=发放检查点之二):结算时**重读**池——
|
|
@@ -1674,8 +1974,51 @@ export function createChatServer(deps) {
|
|
|
1674
1974
|
}
|
|
1675
1975
|
// persona 在这里首次落库(与 scope 同一行、同一时刻):没跑起来的会话不该有绑定。
|
|
1676
1976
|
// persona_version 与它同一次写入、同样只绑一次。
|
|
1677
|
-
|
|
1977
|
+
//
|
|
1978
|
+
// 多 phase 的历史只落「用户原话 + Run 汇总输出」两条:成员的内部转录是后台
|
|
1979
|
+
// worker 的中间产物,混进用户历史会让下次续聊把整段分工都重放一遍。成员会话
|
|
1980
|
+
// 各自 dispose,不 exportHistory——它们的 token 已经记在 runOutcome.usage 里。
|
|
1981
|
+
if (isFlow) {
|
|
1982
|
+
if (runOutcome) {
|
|
1983
|
+
const now = new Date(startedAt.getTime()).toISOString();
|
|
1984
|
+
const entries = [
|
|
1985
|
+
{
|
|
1986
|
+
type: "message",
|
|
1987
|
+
id: `${runId}:user`,
|
|
1988
|
+
parentId: null,
|
|
1989
|
+
timestamp: now,
|
|
1990
|
+
message: { role: "user", content: promptText, timestamp: startedAt.getTime() },
|
|
1991
|
+
},
|
|
1992
|
+
{
|
|
1993
|
+
type: "message",
|
|
1994
|
+
id: `${runId}:answer`,
|
|
1995
|
+
parentId: `${runId}:user`,
|
|
1996
|
+
timestamp: now,
|
|
1997
|
+
message: {
|
|
1998
|
+
role: "assistant",
|
|
1999
|
+
content: [{ type: "text", text: runOutcome.output }],
|
|
2000
|
+
api: "openai-completions",
|
|
2001
|
+
provider: tier.provider,
|
|
2002
|
+
model: tier.model,
|
|
2003
|
+
usage: {
|
|
2004
|
+
input: usage.input,
|
|
2005
|
+
output: usage.output,
|
|
2006
|
+
cacheRead: usage.cacheRead,
|
|
2007
|
+
cacheWrite: usage.cacheWrite,
|
|
2008
|
+
totalTokens: usage.total,
|
|
2009
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: usage.costUsd },
|
|
2010
|
+
},
|
|
2011
|
+
stopReason: "stop",
|
|
2012
|
+
timestamp: startedAt.getTime(),
|
|
2013
|
+
},
|
|
2014
|
+
},
|
|
2015
|
+
];
|
|
2016
|
+
await deps.history.save(userId, scope, sessionId, entries, persona, personaVersion);
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
else if (session) {
|
|
1678
2020
|
await deps.history.save(userId, scope, sessionId, exportHistory(session), persona, personaVersion);
|
|
2021
|
+
}
|
|
1679
2022
|
if (deps.runLog) {
|
|
1680
2023
|
await deps.runLog.record({
|
|
1681
2024
|
userId,
|
|
@@ -1729,6 +2072,8 @@ export function createChatServer(deps) {
|
|
|
1729
2072
|
uiPrompts.clear();
|
|
1730
2073
|
if (session)
|
|
1731
2074
|
await disposeProductSession(session);
|
|
2075
|
+
for (const ms of memberSessions)
|
|
2076
|
+
await disposeProductSession(ms);
|
|
1732
2077
|
running.delete(runKey);
|
|
1733
2078
|
pendingRuns.delete(runKey);
|
|
1734
2079
|
pendingUI.delete(runKey);
|
|
@@ -1806,6 +2151,17 @@ export function createChatServer(deps) {
|
|
|
1806
2151
|
// 默认助手的人格 id(通用化):前端靠它把「老会话(persona 为 null)」
|
|
1807
2152
|
// 认成默认助手那一批。只是一个 id,不带能力信息。
|
|
1808
2153
|
defaultPersona: product.defaultPersona,
|
|
2154
|
+
// 多 phase 流程的**展示字段**(W4):前端据此渲染流程选择器。
|
|
2155
|
+
// 只出 id/label/description——phase/member/task 这些编制细节永不下发。
|
|
2156
|
+
...(product.manifest.agent.flows
|
|
2157
|
+
? {
|
|
2158
|
+
flows: Object.entries(product.manifest.agent.flows).map(([id, f]) => ({
|
|
2159
|
+
id,
|
|
2160
|
+
...(f?.label ? { label: f.label } : {}),
|
|
2161
|
+
...(f?.description ? { description: f.description } : {}),
|
|
2162
|
+
})),
|
|
2163
|
+
}
|
|
2164
|
+
: {}),
|
|
1809
2165
|
};
|
|
1810
2166
|
return sendJson(res, 200, body);
|
|
1811
2167
|
}
|
|
@@ -2294,7 +2650,7 @@ export function createChatServer(deps) {
|
|
|
2294
2650
|
const memberActive = memberUntil !== null && Date.parse(memberUntil) > Date.now();
|
|
2295
2651
|
const isMember = roles.includes("admin") || memberActive;
|
|
2296
2652
|
// 配额展示看的是**这个人格**那本账(产品声明的 id)——core 不假定它叫什么。
|
|
2297
|
-
const stats = (await deps.
|
|
2653
|
+
const stats = (await deps.ledger.todayStats(auth.userId, personaParam)) ?? { runsToday: 0, tokensToday: 0 };
|
|
2298
2654
|
const caps = capsForPersona(limits, personaParam, isMember);
|
|
2299
2655
|
// 池视图:whoami 本身就是「检查点」——会员打开订阅页即 lazy 发满当月池。
|
|
2300
2656
|
let pool = null;
|