dsh-expert-group 0.1.1 → 0.1.2
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/README.md +131 -10
- package/client-bundle.js +1611 -147
- package/client-expert-group-model.js +4 -1
- package/client-expert-group-sidebar.js +1307 -86
- package/client.js +300 -60
- package/desktop-uninstall.ps1 +679 -0
- package/host/fanout-runtime.js +34 -7
- package/host/system-toast.js +1 -1
- package/host/turn-wait.js +465 -0
- package/index.js +1409 -1022
- package/orchestrator.js +36 -29
- package/package.json +5 -3
- package/prompt-contracts.js +9 -7
- package/role-registry.js +6 -6
- package/shared.js +125 -784
- package/{install.ps1 → web-install.ps1} +2 -2
- package/web-uninstall.ps1 +962 -0
- package/uninstall.ps1 +0 -47
package/index.js
CHANGED
|
@@ -30,9 +30,6 @@ import {
|
|
|
30
30
|
createRequestRetryState, resetRequestRetryState, markRequestRetryEvent,
|
|
31
31
|
isTransientRequestFailure, recoveryDelayForCount, requestRetryPolicyCoversFailure,
|
|
32
32
|
appendRecoveryRetryCount, buildRecoveryMessage, classifyTurnOutcome, lastTurnErrorMessage,
|
|
33
|
-
pauseGoalForHandoff, pauseGoalForHandoffSync, registerPausedGoalHandoff,
|
|
34
|
-
releaseGoalHandoff, releaseGoalHandoffState, fanoutHandoffReasonKey,
|
|
35
|
-
clearGoalHandoff, adoptablePausedGoalRef,
|
|
36
33
|
subagentFeedbackChildId, createAdmissionBatchCoordinator, createHandoffAdmissionCohort,
|
|
37
34
|
rootStructuredPathGuard,
|
|
38
35
|
messageIdsOfTurnWithClaimed, shouldAutoRecover, turnHasNonEmptyText,
|
|
@@ -58,6 +55,7 @@ import {
|
|
|
58
55
|
import { createHostComposition } from "./host/composition.js";
|
|
59
56
|
import { createSettingsRuntimeModule, SettingsDirectoryChangedError } from "./host/settings-runtime.js";
|
|
60
57
|
import { createRecoveryModule } from "./host/recovery.js";
|
|
58
|
+
import { createRootTurnWaitRegistry } from "./host/turn-wait.js";
|
|
61
59
|
import { createFanoutRuntimeModule } from "./host/fanout-runtime.js";
|
|
62
60
|
import { createExpertGroupRuntime, rootNotificationLabel } from "./host/expert-group-runtime.js";
|
|
63
61
|
import { createPersistenceHealth } from "./host/persistence-health.js";
|
|
@@ -244,6 +242,34 @@ function isSettingsConsumerUnloading(ctx) {
|
|
|
244
242
|
}
|
|
245
243
|
}
|
|
246
244
|
|
|
245
|
+
// ── root turn 等待:后代查询的 sentinel ─────────────────────────────────────
|
|
246
|
+
/**
|
|
247
|
+
* `workspace/session-activity` waterfall 的**无 provider sentinel**。
|
|
248
|
+
*
|
|
249
|
+
* 为什么必须有它(P0):Cordis 的 `waterfall` 实现在**没有任何 listener** 时是
|
|
250
|
+
* `(cbs.shift() ?? inner)(...args)`——即直接调用调用方传入的最内层回调。而宿主的
|
|
251
|
+
* subagent provider 在「没有 running 后代」时是 `return rest`(**原样透传**最内层
|
|
252
|
+
* 返回值)。因此若最内层返回 `[]`,「topic 没有 provider」与「provider 明确报告空」
|
|
253
|
+
* 的返回值完全同形,会被误判成「可证明没有 running 后代」。
|
|
254
|
+
*
|
|
255
|
+
* 语义(模块唯一、对象身份相等才算命中):
|
|
256
|
+
* - 结果 **=== 本 sentinel** ⟹ 没有任何 listener 产出新数组 ⟹ 链路没有贡献任何事实
|
|
257
|
+
* (没有 provider,或 provider 原样透传)⟹ **无法证明**静止 ⟹ `known:false`;
|
|
258
|
+
* - 结果 **不是** sentinel 的数组 ⟹ 至少有一个 listener 产出了新数组(provider 只有
|
|
259
|
+
* 在真的贡献自己的族时才 `[own, ...rest]`)⟹ 链路确实跑过,可以按族解析。
|
|
260
|
+
*
|
|
261
|
+
* **sentinel 不足以覆盖的第二个洞(P1)**:`workspace/session-activity` 是**非专属**
|
|
262
|
+
* 扩展点,任何第三方 listener 都可以返回一个**新的空数组**(既不 spread 最内层值,也
|
|
263
|
+
* 不检查 subagent 血缘)。这种结果与「provider 明确报告没有 running 后代」在返回值上
|
|
264
|
+
* 依旧同形,而 sentinel 只能识别「链路完全没有贡献」,识别不了「贡献者是谁」。因此
|
|
265
|
+
* 判定层**不得**把任何空数组当作静止证明:waterfall 只能提供**正向**证据(确有
|
|
266
|
+
* `kind === "subagent"` 的 running 条目),静止证明只来自权威 listing。
|
|
267
|
+
*
|
|
268
|
+
* 冻结空数组既保证 spread 安全(`[own, ...sentinel]` 不会抛错、也不会引入假条目),
|
|
269
|
+
* 又保证身份唯一(`Object.freeze` 后的模块级单例不可能被外部复制)。
|
|
270
|
+
*/
|
|
271
|
+
const SESSION_ACTIVITY_NO_PROVIDER = Object.freeze([]);
|
|
272
|
+
|
|
247
273
|
// ── 只读能力矩阵与运行时诊断 ────────────────────────────────────────────────
|
|
248
274
|
/**
|
|
249
275
|
* 诊断报告 schema 版本。
|
|
@@ -251,7 +277,7 @@ function isSettingsConsumerUnloading(ctx) {
|
|
|
251
277
|
* capabilities / diagnostics 是给用户与维护者看的只读投影,不参与任何业务判定。
|
|
252
278
|
* 字段语义变化时递增版本;客户端遇到未知版本必须整体忽略,绝不猜测字段含义。
|
|
253
279
|
*/
|
|
254
|
-
const CAPABILITY_REPORT_VERSION =
|
|
280
|
+
const CAPABILITY_REPORT_VERSION = 2;
|
|
255
281
|
|
|
256
282
|
/** 最近 RPC 错误类别的保留上限;记录有界,绝不随失败次数增长。 */
|
|
257
283
|
const RPC_ERROR_CATEGORY_LIMIT = 8;
|
|
@@ -990,8 +1016,11 @@ export default {
|
|
|
990
1016
|
const agents = ctx.agents;
|
|
991
1017
|
const settings = ctx.settings;
|
|
992
1018
|
const webServer = ctx.webServer;
|
|
993
|
-
// goals
|
|
994
|
-
//
|
|
1019
|
+
// 注意:本插件**不再调用 goals.pause / goals.resume**(旧 goal handoff 已整体删除)。
|
|
1020
|
+
// root 等待语义完全由「保持当前 turn 打开」实现(见 host/turn-wait.js)。
|
|
1021
|
+
// 这里读取的 goals 服务只用于**只读**快照投影:Expert Group 侧边栏展示每个 root 的
|
|
1022
|
+
// 目标阶段(host/expert-group-runtime.js 的 goals.get 读取)。它不参与任何等待、
|
|
1023
|
+
// 收口或状态变更,缺失时投影为空,绝不影响派发与等待语义。
|
|
995
1024
|
const goals = ctx.get("goals");
|
|
996
1025
|
/**
|
|
997
1026
|
* 最近 RPC 错误类别记录器:两条传输共用 mapRpcError,因此这里是同一份只读视图。
|
|
@@ -1013,20 +1042,17 @@ export default {
|
|
|
1013
1042
|
/** 同父代理 + 同角色的委派跟踪器:串行临界区 / child 复用 / 任务去重(LRU 32)。 */
|
|
1014
1043
|
const delegationTracker = createDelegationTracker({ taskLimit: 32 });
|
|
1015
1044
|
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
*/
|
|
1020
|
-
const goalHandoffs = new Map();
|
|
1021
|
-
// child turn/end 可能早于父 inbox feedback;先保存终态,等 handoff 真正释放后再消费。
|
|
1045
|
+
// 注意:旧的 root goal handoff 记录表(goalHandoffs)已整体删除。等待原因与
|
|
1046
|
+
// 静止判定由 host/turn-wait.js 的登记表按 exact root Agent 对象持有。
|
|
1047
|
+
// child turn/end 可能早于父 inbox feedback;先保存终态,等 exact settlement 到达后再消费。
|
|
1022
1048
|
// 这些状态以 exact root Agent 为键;同 id 的新旧 root 不共享 generation。
|
|
1023
1049
|
const pendingChildTurnEnds = new Map();
|
|
1024
1050
|
// 自动恢复期间,DSH 仍会先把异常 settlement/report 插进父 inbox。每个
|
|
1025
1051
|
// recovery record 自己持有已同步撤回的消息,绝不能按 childId 全局合并:
|
|
1026
1052
|
// replacement、cold Session 与同 child 的后续任务都可能在同一父代理下并存。
|
|
1027
|
-
// 每个 accepted admission 独立保留 token/messageId/feedbackSeen
|
|
1028
|
-
//
|
|
1029
|
-
// pending
|
|
1053
|
+
// 每个 accepted admission 独立保留 token/messageId/feedbackSeen,直到该 token 的
|
|
1054
|
+
// settlement 状态已确定;不会因另一个同 child admission 完成而提前删除。
|
|
1055
|
+
// pending admission 由 host/handoff 持有;下列调用为兼容投影。
|
|
1030
1056
|
// Host admission 复用共享 helper 的 token/turn-group 状态;数组只作为本地 owner 索引。
|
|
1031
1057
|
const handoffAdmissionCohort = createHandoffAdmissionCohort();
|
|
1032
1058
|
// resume/CAS 失败只禁止对应 exact root 的自动恢复,不能影响同 id 的新 root。
|
|
@@ -1048,7 +1074,7 @@ export default {
|
|
|
1048
1074
|
getAgent: (id) => agents.get(id),
|
|
1049
1075
|
getTask: (id) => fanoutHost?.getTask(id) ?? null,
|
|
1050
1076
|
listTasks: () => fanoutHost?.listTasks() ?? [],
|
|
1051
|
-
isGenerationBlocked: () =>
|
|
1077
|
+
isGenerationBlocked: () => turnWaitStopping,
|
|
1052
1078
|
},
|
|
1053
1079
|
notifications: {
|
|
1054
1080
|
// 终止快照状态由 host/notifications 持有;Host 只注入 live Agent 查询,
|
|
@@ -1076,7 +1102,7 @@ export default {
|
|
|
1076
1102
|
|
|
1077
1103
|
/**
|
|
1078
1104
|
* 系统通知开关:与设置页写的是同一个值;缺失/读不到(含 settings 尚未就绪)一律按开启。
|
|
1079
|
-
*
|
|
1105
|
+
* 关闭时不发送、不补发——开关只影响投递,不影响任何快照、admission 或等待语义。
|
|
1080
1106
|
*/
|
|
1081
1107
|
function systemToastEnabled() {
|
|
1082
1108
|
try {
|
|
@@ -1159,9 +1185,15 @@ export default {
|
|
|
1159
1185
|
// host/notifications 持有并按 root generation 隔离。
|
|
1160
1186
|
// 用户问题/计划确认在返回前可能长期等待;按 exact root/session/generation 保留其门控。
|
|
1161
1187
|
const pendingUserWaits = new WeakMap();
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1188
|
+
/**
|
|
1189
|
+
* 插件卸载闩:置位后所有等待登记/监听安装/结算路径一律 no-op,避免在
|
|
1190
|
+
* fiber 正在清理时又建立新的等待或监听。
|
|
1191
|
+
*/
|
|
1192
|
+
let turnWaitStopping = false;
|
|
1193
|
+
/** 等待登记表的统一异常记录(只记错误名与固定前缀,不泄漏工作负载)。 */
|
|
1194
|
+
function logTurnWaitError(action, error) {
|
|
1195
|
+
ctx.logger.warn("dsh-expert-group: root turn wait " + action + " failed: "
|
|
1196
|
+
+ (error instanceof Error ? error.message : String(error)));
|
|
1165
1197
|
}
|
|
1166
1198
|
function isRootAgentIdentity(agent) {
|
|
1167
1199
|
return agent !== void 0
|
|
@@ -1174,6 +1206,389 @@ export default {
|
|
|
1174
1206
|
return host.lineage.isLiveRoot(agent);
|
|
1175
1207
|
}
|
|
1176
1208
|
|
|
1209
|
+
// ── root turn 等待:root-scoped 后代查询与活动监听 ────────────────────────
|
|
1210
|
+
/**
|
|
1211
|
+
* rootId -> 该 root 等待记录的「作废」回调集合。
|
|
1212
|
+
*
|
|
1213
|
+
* 用一张按 root id 索引的表而不是「每个 root 装三份监听器」:全局监听只装一次,
|
|
1214
|
+
* 事件到达时按血缘链向上找出真正受影响的 root,因此 N 个并发 root 也只有一份监听。
|
|
1215
|
+
*/
|
|
1216
|
+
const rootWaitInvalidators = new Map();
|
|
1217
|
+
let rootWaitActivityListenersInstalled = false;
|
|
1218
|
+
|
|
1219
|
+
/** 通知某个 id 上登记的全部作废回调;回调异常不影响事件派发。 */
|
|
1220
|
+
function invalidateRootWaitId(id) {
|
|
1221
|
+
const listeners = rootWaitInvalidators.get(id);
|
|
1222
|
+
if (listeners === void 0) return;
|
|
1223
|
+
for (const listener of [...listeners]) {
|
|
1224
|
+
try { listener(); } catch (error) { logTurnWaitError("invalidate", error); }
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
/**
|
|
1229
|
+
* 某个 live Agent 上发生活动(创建 / 转入 running / 销毁)时,作废**它自己及其
|
|
1230
|
+
* 全部祖先 root** 的等待结论。
|
|
1231
|
+
*
|
|
1232
|
+
* 为什么按血缘链向上而不是只看 id:child 的 parentSession 可能指向另一个 child
|
|
1233
|
+
* (fan-out 分片、嵌套委派),真正需要重新判定的是整条链上仍在等待的 root。
|
|
1234
|
+
* 链上出现环或父级不可解析时按 id 逐级命中后停止,绝不无限回溯。
|
|
1235
|
+
*/
|
|
1236
|
+
function invalidateWaitersForAgentActivity(agent) {
|
|
1237
|
+
if (rootWaitInvalidators.size === 0) return;
|
|
1238
|
+
const visited = new Set();
|
|
1239
|
+
let currentId = typeof agent?.id === "string" ? agent.id : void 0;
|
|
1240
|
+
let parentId = agent?.session?.header?.parentSession;
|
|
1241
|
+
// 起点自身也要作废:root 自己的记录同样可能已经放行,需要重新判定。
|
|
1242
|
+
while (typeof currentId === "string" && currentId.length > 0 && !visited.has(currentId)) {
|
|
1243
|
+
visited.add(currentId);
|
|
1244
|
+
invalidateRootWaitId(currentId);
|
|
1245
|
+
if (typeof parentId !== "string" || parentId.length === 0) break;
|
|
1246
|
+
const parent = agents.get(parentId);
|
|
1247
|
+
currentId = parentId;
|
|
1248
|
+
parentId = parent?.session?.header?.parentSession;
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/**
|
|
1253
|
+
* 安装本 root 的活动监听(登记表的 subscribe 契约:必须在首次状态查询**之前**
|
|
1254
|
+
* 同步完成)。
|
|
1255
|
+
*
|
|
1256
|
+
* 监听面(全部是宿主公开事件):
|
|
1257
|
+
* - `agent/created`:新 child 出现即作废静止结论;
|
|
1258
|
+
* - `agent/status`:转入 running 即作废(状态转 idle/ready 不产生新工作,但同样
|
|
1259
|
+
* 作废一次是安全且廉价的——判定会重新读 root-scoped 事实);
|
|
1260
|
+
* - `agent/disposed`:child 消失后重新判定。
|
|
1261
|
+
*
|
|
1262
|
+
* @returns {() => void} 移除本次订阅(不动全局监听器:它们由插件 effect 统一释放)。
|
|
1263
|
+
*/
|
|
1264
|
+
function subscribeRootActivity(agent, invalidate) {
|
|
1265
|
+
if (turnWaitStopping || typeof agent?.id !== "string" || agent.id.length === 0) return () => {};
|
|
1266
|
+
const rootId = agent.id;
|
|
1267
|
+
let listeners = rootWaitInvalidators.get(rootId);
|
|
1268
|
+
if (listeners === void 0) {
|
|
1269
|
+
listeners = new Set();
|
|
1270
|
+
rootWaitInvalidators.set(rootId, listeners);
|
|
1271
|
+
}
|
|
1272
|
+
listeners.add(invalidate);
|
|
1273
|
+
installRootWaitActivityListeners();
|
|
1274
|
+
return () => {
|
|
1275
|
+
const current = rootWaitInvalidators.get(rootId);
|
|
1276
|
+
if (current === undefined) return;
|
|
1277
|
+
current.delete(invalidate);
|
|
1278
|
+
if (current.size === 0) rootWaitInvalidators.delete(rootId);
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
|
|
1282
|
+
/**
|
|
1283
|
+
* 新建子代理时把它的祖先 root 登记进等待体系。
|
|
1284
|
+
*
|
|
1285
|
+
* 只沿 `session.header.parentSession` 血缘链向上找**最近的一个 root 身份 Agent**;
|
|
1286
|
+
* 链上出现环、父级不在 live registry 或链条结束都直接停止(绝不臆造归属)。
|
|
1287
|
+
* root 自身不 engage 自己(root 创建不意味着有子代理在跑)。
|
|
1288
|
+
*
|
|
1289
|
+
* @param {object} agent - 刚创建的 Agent。
|
|
1290
|
+
*/
|
|
1291
|
+
function engageRootTurnWaitForCreatedAgent(agent) {
|
|
1292
|
+
if (turnWaitStopping) return;
|
|
1293
|
+
if (agent === null || typeof agent !== "object") return;
|
|
1294
|
+
if (isRootAgentIdentity(agent)) return;
|
|
1295
|
+
const visited = new Set();
|
|
1296
|
+
let parentId = agent.session?.header?.parentSession;
|
|
1297
|
+
while (typeof parentId === "string" && parentId.length > 0 && !visited.has(parentId)) {
|
|
1298
|
+
visited.add(parentId);
|
|
1299
|
+
const parent = agents.get(parentId);
|
|
1300
|
+
if (parent === void 0) return;
|
|
1301
|
+
if (isRootAgentIdentity(parent)) {
|
|
1302
|
+
if (isLiveRootAgent(parent)) rootTurnWaits.engage(parent);
|
|
1303
|
+
return;
|
|
1304
|
+
}
|
|
1305
|
+
parentId = parent.session?.header?.parentSession;
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1309
|
+
/** 全局活动监听只装一次;由插件 effect 在卸载时释放。 */
|
|
1310
|
+
function installRootWaitActivityListeners() {
|
|
1311
|
+
if (rootWaitActivityListenersInstalled || turnWaitStopping) return;
|
|
1312
|
+
rootWaitActivityListenersInstalled = true;
|
|
1313
|
+
ctx.effect(() => {
|
|
1314
|
+
const stopCreated = ctx.on("agent/created", ({ agent }) => {
|
|
1315
|
+
invalidateWaitersForAgentActivity(agent);
|
|
1316
|
+
});
|
|
1317
|
+
const stopStatus = ctx.on("agent/status", ({ agent }) => {
|
|
1318
|
+
invalidateWaitersForAgentActivity(agent);
|
|
1319
|
+
});
|
|
1320
|
+
const stopDisposed = ctx.on("agent/disposed", ({ agent }) => {
|
|
1321
|
+
invalidateWaitersForAgentActivity(agent);
|
|
1322
|
+
});
|
|
1323
|
+
return () => {
|
|
1324
|
+
rootWaitActivityListenersInstalled = false;
|
|
1325
|
+
stopDisposed?.();
|
|
1326
|
+
stopStatus?.();
|
|
1327
|
+
stopCreated?.();
|
|
1328
|
+
};
|
|
1329
|
+
}, "dsh-expert-group: root turn wait activity listeners");
|
|
1330
|
+
}
|
|
1331
|
+
|
|
1332
|
+
/**
|
|
1333
|
+
* root-scoped 的 running 后代查询(等待释放的唯一外部事实来源)。
|
|
1334
|
+
*
|
|
1335
|
+
* 两条 seam,优先级严格:**权威 listing 优先,waterfall 仅作降级回退**。
|
|
1336
|
+
*
|
|
1337
|
+
* ### 1) 权威 seam:`subagents.listDescendants(rootSessionId)`
|
|
1338
|
+
* `@deepseek-ai/dsh-subagent` 在 `SubagentService` 上公开的递归后代枚举
|
|
1339
|
+
* (`listChildren`/`listDescendants`):按 durable parent catalog 递归遍历,
|
|
1340
|
+
* child 行的必填字段是 `kind`、`id`、`mode: "one-shot" | "continuable"`、
|
|
1341
|
+
* `activity: "running" | "inactive"`、`hasChildren`、`parentId`、`depth`
|
|
1342
|
+
* (`mode: "continuable"` 时另有必填的 `label`)。
|
|
1343
|
+
* 它天然只覆盖被询问的 root,并且**失败语义是显式的**:
|
|
1344
|
+
* - 整条 listing reject(root catalog 不可读 / 缺少 sessionQuery、sessions、
|
|
1345
|
+
* projection / 被取消)→ 未知;
|
|
1346
|
+
* - 某个分支不可读或 catalog 里 `mode: "unknown"` → 该行是
|
|
1347
|
+
* `kind: "diagnostic"` → 无法证明那条分支里没有 running 后代 → 未知
|
|
1348
|
+
* (fail-closed);未知 `kind` 同样未知;
|
|
1349
|
+
* - child 行**不满足公开必填契约**(缺 `mode` / `mode` 非法 / 缺
|
|
1350
|
+
* `hasChildren`、`parentId`、`depth` / continuable 行缺 `label`)→ 整次
|
|
1351
|
+
* listing 不可信 → 未知(fail-closed);
|
|
1352
|
+
* - 正常 resolve、行全部合法且没有任何 diagnostic 行 → `known:true`,此时
|
|
1353
|
+
* 「没有 running 后代」是**可证明**的结论。
|
|
1354
|
+
*
|
|
1355
|
+
* 为什么它是权威 seam:它是唯一一个「没有 provider」与「provider 明确报告空」
|
|
1356
|
+
* 在返回结构上就不同(reject / diagnostic vs. 干净的空列表)的公开 API。
|
|
1357
|
+
*
|
|
1358
|
+
* ### 2) 降级 seam:`workspace/session-activity` waterfall + 独特 sentinel
|
|
1359
|
+
* 宿主没有 listing 时退回 waterfall。这条链路**只能提供正向证据,永远不能证明静止**,
|
|
1360
|
+
* 两个独立原因都必须处理:
|
|
1361
|
+
*
|
|
1362
|
+
* **(a) 无 provider(P0)**:Cordis 的 `waterfall` 在**没有任何 listener** 时会
|
|
1363
|
+
* 直接调用调用方传入的最内层回调(`(cbs.shift() ?? inner)(...args)`),而宿主
|
|
1364
|
+
* subagent provider 在「没有 running 后代」时是 `return rest`(**原样透传**最内层
|
|
1365
|
+
* 返回值)。因此「没有 provider」与「provider 报告空」在返回值上完全同形——传空数组
|
|
1366
|
+
* 做兜底会把前者误判成 `known:true`。这里用**模块唯一的 sentinel**
|
|
1367
|
+
* (`SESSION_ACTIVITY_NO_PROVIDER`,冻结空数组)作为最内层返回值:
|
|
1368
|
+
* - 结果 **是** sentinel(对象身份相等)⟹ 没有任何 listener 产生新数组,即
|
|
1369
|
+
* 「链路没有贡献任何事实」——既可能是 topic 没有 provider,也可能是 provider
|
|
1370
|
+
* 原样透传。两者都无法证明「没有 running 后代」,一律 `known:false`;
|
|
1371
|
+
* - 结果 **不是** sentinel 的数组 ⟹ 至少有一个 listener 产出了新数组。注意:解析时
|
|
1372
|
+
* 必须跳过 sentinel 自身的元素(它可能被 spread 进结果)。
|
|
1373
|
+
*
|
|
1374
|
+
* **(b) 其他 listener 的空数组(P1)**:`workspace/session-activity` 是**非专属**
|
|
1375
|
+
* 扩展点,任何第三方 listener 都可以返回一个全新的空数组(既不 spread 最内层值,也
|
|
1376
|
+
* 不检查 subagent 血缘)。sentinel 只能识别「链路完全没有贡献」,识别不了「是谁贡献
|
|
1377
|
+
* 的」,因此非 sentinel 的空数组同样**不能**证明静止。判定层的口径必须是:
|
|
1378
|
+
* **任何**空数组(含 fresh `[]`)⟹ `known:false`。
|
|
1379
|
+
*
|
|
1380
|
+
* 综合结论(不夸大):waterfall 回退只可能给出「known + running 非空」这一种明确
|
|
1381
|
+
* 结论,其余所有形状(sentinel、任意空数组、非空但无 subagent 族、malformed)都是
|
|
1382
|
+
* `known:false`。真正可证明的静止**只**来自权威 listing 的干净完整回答。
|
|
1383
|
+
*
|
|
1384
|
+
* @param {string} rootId - exact root session id。
|
|
1385
|
+
* @returns {Promise<{known:boolean,running:object[],runningIds?:Set<string>,reason:string}>}
|
|
1386
|
+
*/
|
|
1387
|
+
async function snapshotRootTurnDescendants(rootId) {
|
|
1388
|
+
if (typeof rootId !== "string" || rootId.length === 0) {
|
|
1389
|
+
return { known: false, running: [], reason: "root-id-unknown" };
|
|
1390
|
+
}
|
|
1391
|
+
const listed = await snapshotRootTurnDescendantsFromListing(rootId);
|
|
1392
|
+
if (listed !== void 0) return listed;
|
|
1393
|
+
return snapshotRootTurnDescendantsFromActivity(rootId);
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* `kind: "child"` 行是否满足公开契约(`SubagentDescendantListEntry`)。
|
|
1398
|
+
*
|
|
1399
|
+
* 公开 schema 定义在 `@deepseek-ai/dsh-subagent` 的 `control-types` 与
|
|
1400
|
+
* `list-children`:child 行 = `SubagentCatalogRow`(`id`、`mode`、`activity`,
|
|
1401
|
+
* 以及 `mode:"continuable"` 时**必填**的 `label`)
|
|
1402
|
+
* `& { kind:"child"; hasChildren:boolean }` `& { parentId; depth }`。因此这里只校验
|
|
1403
|
+
* **必填**字段,可选字段(`one-shot` 的 `label`)出现时必须是字符串,其余扩展字段
|
|
1404
|
+
* 一概不参与判定——避免把合法 listing 误判成非法而永久等待。
|
|
1405
|
+
*
|
|
1406
|
+
* **为什么 `mode` 必须校验(P2)**:`mode` 是这条行的生命周期判别字段
|
|
1407
|
+
* (`one-shot` | `continuable`)。真实 `listDescendants` 会把 catalog 里
|
|
1408
|
+
* `mode:"unknown"` 的条目转成 `kind:"diagnostic"`,所以 child 行出现**缺失**或
|
|
1409
|
+
* **非法** `mode` 只可能说明这份 listing 不是公开契约的形状(伪造 / 截断 / 跨版本
|
|
1410
|
+
* 错配)。此时 `activity:"inactive"` **不能**作为静止证据:整次结果按未知处理,
|
|
1411
|
+
* 等待继续。
|
|
1412
|
+
*
|
|
1413
|
+
* @param {object} row - listing 里 `kind:"child"` 的一行。
|
|
1414
|
+
* @returns {boolean} 满足必填字段契约时为 true。
|
|
1415
|
+
*/
|
|
1416
|
+
function isContractChildRow(row) {
|
|
1417
|
+
if (typeof row.id !== "string" || row.id.length === 0) return false;
|
|
1418
|
+
// mode 枚举:只有这两个取值属于公开契约;缺失 / "unknown" / 任意字符串都非法。
|
|
1419
|
+
if (row.mode !== "one-shot" && row.mode !== "continuable") return false;
|
|
1420
|
+
// activity 是二值枚举;任何其他取值都说明契约不成立。
|
|
1421
|
+
if (row.activity !== "running" && row.activity !== "inactive") return false;
|
|
1422
|
+
// label:continuable 行必填;one-shot 行可选,但出现时必须是字符串。
|
|
1423
|
+
if (row.mode === "continuable") {
|
|
1424
|
+
if (typeof row.label !== "string") return false;
|
|
1425
|
+
} else if (row.label !== void 0 && typeof row.label !== "string") {
|
|
1426
|
+
return false;
|
|
1427
|
+
}
|
|
1428
|
+
if (typeof row.hasChildren !== "boolean") return false;
|
|
1429
|
+
if (typeof row.parentId !== "string" || row.parentId.length === 0) return false;
|
|
1430
|
+
// depth 是从被询问 root 起算的边距离;直接子代为 1,因此必须是正整数。
|
|
1431
|
+
if (!Number.isInteger(row.depth) || row.depth < 1) return false;
|
|
1432
|
+
return true;
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
/**
|
|
1436
|
+
* 权威 seam:`subagents.listDescendants`。
|
|
1437
|
+
*
|
|
1438
|
+
* @returns {Promise<object|undefined>} 明确回答;seam 不可用时返回 undefined
|
|
1439
|
+
* 让调用方回退到 waterfall。
|
|
1440
|
+
*/
|
|
1441
|
+
async function snapshotRootTurnDescendantsFromListing(rootId) {
|
|
1442
|
+
let listing;
|
|
1443
|
+
try {
|
|
1444
|
+
listing = subagents?.listDescendants;
|
|
1445
|
+
} catch (error) {
|
|
1446
|
+
logTurnWaitError("descendant-listing-probe", error);
|
|
1447
|
+
return void 0;
|
|
1448
|
+
}
|
|
1449
|
+
if (typeof listing !== "function") return void 0;
|
|
1450
|
+
let rows;
|
|
1451
|
+
try {
|
|
1452
|
+
rows = await listing.call(subagents, rootId);
|
|
1453
|
+
} catch (error) {
|
|
1454
|
+
// root catalog 不可读 / 缺少依赖 / 被取消:**未知**,绝不当作「没人跑」。
|
|
1455
|
+
logTurnWaitError("descendant-listing", error);
|
|
1456
|
+
return { known: false, running: [], reason: "descendant-listing-failed" };
|
|
1457
|
+
}
|
|
1458
|
+
if (!Array.isArray(rows)) {
|
|
1459
|
+
return { known: false, running: [], reason: "descendant-listing-malformed" };
|
|
1460
|
+
}
|
|
1461
|
+
const running = [];
|
|
1462
|
+
const runningIds = new Set();
|
|
1463
|
+
for (const row of rows) {
|
|
1464
|
+
if (row === null || typeof row !== "object" || Array.isArray(row)) {
|
|
1465
|
+
return { known: false, running: [], reason: "descendant-listing-malformed" };
|
|
1466
|
+
}
|
|
1467
|
+
// 分支不可读 / catalog 里 mode 未知:那条分支里是否有 running 后代无法证明
|
|
1468
|
+
// → 未知(fail-closed)。未知 kind 同样按 malformed 处理。
|
|
1469
|
+
if (row.kind === "diagnostic") {
|
|
1470
|
+
return { known: false, running: [], reason: "descendant-listing-diagnostic" };
|
|
1471
|
+
}
|
|
1472
|
+
if (row.kind !== "child") {
|
|
1473
|
+
return { known: false, running: [], reason: "descendant-listing-malformed" };
|
|
1474
|
+
}
|
|
1475
|
+
// child 行的公开契约校验(含 mode 枚举):任一必填字段不成立 ⟹ 整次 listing
|
|
1476
|
+
// 都不可信,绝不能拿其中某行的 activity:"inactive" 当静止证据。
|
|
1477
|
+
if (!isContractChildRow(row)) {
|
|
1478
|
+
return { known: false, running: [], reason: "descendant-listing-malformed" };
|
|
1479
|
+
}
|
|
1480
|
+
if (row.activity === "running") {
|
|
1481
|
+
running.push({ id: row.id });
|
|
1482
|
+
runningIds.add(row.id);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
return {
|
|
1486
|
+
known: true,
|
|
1487
|
+
running,
|
|
1488
|
+
runningIds,
|
|
1489
|
+
reason: running.length > 0 ? "running-descendants" : "no-running-descendants",
|
|
1490
|
+
};
|
|
1491
|
+
}
|
|
1492
|
+
|
|
1493
|
+
/**
|
|
1494
|
+
* 降级 seam:`workspace/session-activity` waterfall + 独特 sentinel。
|
|
1495
|
+
*
|
|
1496
|
+
* **本路径只做正向证据**:唯一可能返回的明确结论是「确有 running 的 subagent 后代」
|
|
1497
|
+
* (`known:true` 且 `running` 非空),调用方据此**继续等待**。它**永远不返回**
|
|
1498
|
+
* `known:true` + 空 `running`——即永远不会证明静止:
|
|
1499
|
+
* - 结果 === sentinel ⟹ 链路没有贡献任何事实(无 provider / provider 原样透传);
|
|
1500
|
+
* - 结果是非 sentinel 的**任意空数组** ⟹ 非专属扩展点上无法识别贡献者,可能是任何
|
|
1501
|
+
* 第三方 listener 返回的全新 `[]`,它并不保证检查过 subagent 血缘;
|
|
1502
|
+
* - 结果非空但没有 `kind === "subagent"` 的 running 条目 ⟹ 贡献事实的是别的族,
|
|
1503
|
+
* 或 subagent 族本身为空;
|
|
1504
|
+
* - 结果不是数组、或条目结构不合法 ⟹ malformed。
|
|
1505
|
+
* 以上四种一律 `known:false`(fail-closed,继续等待)。
|
|
1506
|
+
*
|
|
1507
|
+
* @returns {Promise<object>} 只有「known + running 非空」或 `known:false` 两种可能。
|
|
1508
|
+
*/
|
|
1509
|
+
async function snapshotRootTurnDescendantsFromActivity(rootId) {
|
|
1510
|
+
// 严格 Cordis Context 对未声明属性直接抛错,因此这里的读取也必须包在 try 内:
|
|
1511
|
+
// 「读取 waterfall 失败」与「宿主没有该服务」是同一件事(未知),一律继续等待。
|
|
1512
|
+
let waterfall;
|
|
1513
|
+
try {
|
|
1514
|
+
waterfall = ctx.waterfall;
|
|
1515
|
+
} catch {
|
|
1516
|
+
return { known: false, running: [], reason: "session-activity-unavailable" };
|
|
1517
|
+
}
|
|
1518
|
+
if (typeof waterfall !== "function") {
|
|
1519
|
+
return { known: false, running: [], reason: "session-activity-unavailable" };
|
|
1520
|
+
}
|
|
1521
|
+
let activity;
|
|
1522
|
+
try {
|
|
1523
|
+
activity = await waterfall.call(ctx, "workspace/session-activity", { sessionId: rootId }, () => SESSION_ACTIVITY_NO_PROVIDER);
|
|
1524
|
+
} catch (error) {
|
|
1525
|
+
// 任一 provider 抛错都会让整条 waterfall reject:这是**未知**,不是「没人跑」。
|
|
1526
|
+
logTurnWaitError("descendant-query", error);
|
|
1527
|
+
return { known: false, running: [], reason: "session-activity-failed" };
|
|
1528
|
+
}
|
|
1529
|
+
if (activity === SESSION_ACTIVITY_NO_PROVIDER) {
|
|
1530
|
+
// P0:没有任何 listener 贡献事实——既可能是没有 provider,也可能是 provider
|
|
1531
|
+
// 原样透传。两者都无法证明「没有 running 后代」,必须继续等待。
|
|
1532
|
+
return { known: false, running: [], reason: "session-activity-no-provider" };
|
|
1533
|
+
}
|
|
1534
|
+
if (!Array.isArray(activity)) {
|
|
1535
|
+
return { known: false, running: [], reason: "session-activity-malformed" };
|
|
1536
|
+
}
|
|
1537
|
+
if (activity.length === 0) {
|
|
1538
|
+
// P1:**任何**非 sentinel 的空数组都不能证明静止。`workspace/session-activity`
|
|
1539
|
+
// 是非专属扩展点,任意第三方 listener 都可以返回一个全新的 `[]`(既不 spread
|
|
1540
|
+
// 最内层值,也不检查 subagent 血缘);sentinel 只能识别「链路没有贡献」,识别不了
|
|
1541
|
+
// 「贡献者是谁」。因此这里与 sentinel 同档 fail-closed,绝不能放行等待。
|
|
1542
|
+
return { known: false, running: [], reason: "session-activity-empty-not-authoritative" };
|
|
1543
|
+
}
|
|
1544
|
+
const running = [];
|
|
1545
|
+
for (const entry of activity) {
|
|
1546
|
+
// 数组同样不是合法的族条目:与权威 listing 的结构校验保持同一严格度。
|
|
1547
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
|
|
1548
|
+
return { known: false, running: [], reason: "session-activity-malformed" };
|
|
1549
|
+
}
|
|
1550
|
+
// 只消费 subagent 族;其他族(job/schedule/turn)不属于专家后代判定范围。
|
|
1551
|
+
if (entry.kind !== "subagent") continue;
|
|
1552
|
+
const items = entry.items;
|
|
1553
|
+
if (!Array.isArray(items)) {
|
|
1554
|
+
return { known: false, running: [], reason: "session-activity-malformed" };
|
|
1555
|
+
}
|
|
1556
|
+
for (const item of items) {
|
|
1557
|
+
if (item === null || typeof item !== "object"
|
|
1558
|
+
|| typeof item.id !== "string" || item.id.length === 0) {
|
|
1559
|
+
return { known: false, running: [], reason: "session-activity-malformed" };
|
|
1560
|
+
}
|
|
1561
|
+
running.push(item);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
if (running.length > 0) {
|
|
1565
|
+
// 确有 running 后代:这是**正向**事实,可以放心作为「继续等待」的依据。
|
|
1566
|
+
// 注意这里只用于「继续等待」,绝不用作静止证明。
|
|
1567
|
+
const runningIds = new Set();
|
|
1568
|
+
for (const item of running) runningIds.add(item.id);
|
|
1569
|
+
return { known: true, running, runningIds, reason: "running-descendants" };
|
|
1570
|
+
}
|
|
1571
|
+
// 非空、但没有任何 running 的 subagent 条目:贡献事实的是别的族
|
|
1572
|
+
// (turn/job/schedule…),或者 subagent 族本身是空 items。由于 subagent provider
|
|
1573
|
+
// 在空闲时是**原样透传**,这里既无法证明它装载过,也无法证明它报告了空——
|
|
1574
|
+
// 必须 fail-closed 继续等待。
|
|
1575
|
+
return { known: false, running: [], reason: "session-activity-foreign-families" };
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
/**
|
|
1580
|
+
* 唯一的 root turn 等待登记表:finalize 与 agent/turn-stopping 兜底共用。
|
|
1581
|
+
*
|
|
1582
|
+
* 释放条件见 host/turn-wait.js 的模块文档;本处只负责把宿主事实接进来。
|
|
1583
|
+
*/
|
|
1584
|
+
const rootTurnWaits = createRootTurnWaitRegistry({
|
|
1585
|
+
isLiveRoot: (agent) => isLiveRootAgent(agent),
|
|
1586
|
+
snapshotDescendants: (rootId) => snapshotRootTurnDescendants(rootId),
|
|
1587
|
+
subscribe: (agent, invalidate) => subscribeRootActivity(agent, invalidate),
|
|
1588
|
+
onKnownSnapshot: (agent, snapshot) => settleFinishedChildTurnWaits(agent, snapshot),
|
|
1589
|
+
onError: (error) => logTurnWaitError("check", error),
|
|
1590
|
+
});
|
|
1591
|
+
|
|
1177
1592
|
/**
|
|
1178
1593
|
* 释放一个已收到终态 feedback 但没有成功关联到 turn/messageId 的活动范围。
|
|
1179
1594
|
*
|
|
@@ -1241,21 +1656,6 @@ export default {
|
|
|
1241
1656
|
notificationHost.activateRoot({ rootId: root.id, generation: rootGenerationRegistry.generationOf(root.id) });
|
|
1242
1657
|
}
|
|
1243
1658
|
}
|
|
1244
|
-
function handoffReasonChildKey(childId, admissionId) {
|
|
1245
|
-
if (typeof childId !== "string" || childId.length === 0) return void 0;
|
|
1246
|
-
return typeof admissionId === "string" && admissionId.length > 0
|
|
1247
|
-
? "child:" + childId + ":" + admissionId
|
|
1248
|
-
: "child:" + childId;
|
|
1249
|
-
}
|
|
1250
|
-
function childHandoffIds(handoff) {
|
|
1251
|
-
const ids = new Set();
|
|
1252
|
-
if (!(handoff?.reasons instanceof Map)) return [];
|
|
1253
|
-
for (const key of handoff.reasons.keys()) {
|
|
1254
|
-
if (typeof key !== "string" || !key.startsWith("child:") || key.length <= 6) continue;
|
|
1255
|
-
ids.add(key.slice(6).split(":", 1)[0]);
|
|
1256
|
-
}
|
|
1257
|
-
return [...ids];
|
|
1258
|
-
}
|
|
1259
1659
|
function failureDescriptorForAdmission(parent, admission) {
|
|
1260
1660
|
const record = recoveryRecords.get(admission?.childId);
|
|
1261
1661
|
const terminal = pendingChildTurnEnds.get(parent)?.find((item) => item.admission === admission);
|
|
@@ -1304,10 +1704,22 @@ export default {
|
|
|
1304
1704
|
if (binding?.messageId === messageId && entry.messageId === void 0) entry.messageId = messageId;
|
|
1305
1705
|
}
|
|
1306
1706
|
}
|
|
1707
|
+
/**
|
|
1708
|
+
* 摘除一个 pending admission,并把它对应的等待工作**精确结算**。
|
|
1709
|
+
*
|
|
1710
|
+
* 结算边界就是「exact admission 真正离开 host.handoff」:无论它是被相关
|
|
1711
|
+
* settlement 释放、被 fail-closed 清理,还是被 root 退休路径摘除,都只有这一次
|
|
1712
|
+
* 真实的移除。等待登记表按 token 精确结算,因此重复调用与迟到事件都是幂等空操作
|
|
1713
|
+
* (登记表只认未结算项),绝不会释放别的 admission。
|
|
1714
|
+
*/
|
|
1307
1715
|
function removePendingHandoffAdmission(entry) {
|
|
1308
1716
|
if (entry === void 0) return;
|
|
1309
|
-
if (host.handoff.remove(entry))
|
|
1310
|
-
|
|
1717
|
+
if (!host.handoff.remove(entry)) return;
|
|
1718
|
+
handoffAdmissionCohort.remove(entry);
|
|
1719
|
+
const parent = entry.parent;
|
|
1720
|
+
const token = typeof entry.token === "string" && entry.token.length > 0 ? entry.token : void 0;
|
|
1721
|
+
if (parent !== void 0 && token !== void 0) {
|
|
1722
|
+
rootTurnWaits.settle(parent, { kind: "admission", token });
|
|
1311
1723
|
}
|
|
1312
1724
|
}
|
|
1313
1725
|
/**
|
|
@@ -1318,7 +1730,6 @@ export default {
|
|
|
1318
1730
|
function failPendingHandoffAdmission(parent, entry, record) {
|
|
1319
1731
|
if (entry === void 0 || !host.handoff.contains(entry)) return;
|
|
1320
1732
|
entry.failed = true;
|
|
1321
|
-
entry.pauseDone = true;
|
|
1322
1733
|
entry.feedbackSeen = true;
|
|
1323
1734
|
entry.releaseQueued = true;
|
|
1324
1735
|
const queued = pendingChildTurnEnds.get(parent)?.some((item) => item.admission === entry) === true;
|
|
@@ -1330,18 +1741,14 @@ export default {
|
|
|
1330
1741
|
if (!queued && messageId === void 0) removePendingHandoffAdmission(entry);
|
|
1331
1742
|
}
|
|
1332
1743
|
function clearPendingHandoffAdmissions(parent) {
|
|
1744
|
+
// 统一走 removePendingHandoffAdmission:它同时负责等待工作的精确结算。
|
|
1333
1745
|
for (const entry of host.handoff.filter((item) => item.parent === parent)) {
|
|
1334
|
-
|
|
1335
|
-
host.handoff.remove(entry);
|
|
1746
|
+
removePendingHandoffAdmission(entry);
|
|
1336
1747
|
}
|
|
1337
1748
|
// 失败路径先把可反查 descriptor 写入 registry;这里仅移除无法按
|
|
1338
1749
|
// messageId/turn 反查的非终态记录,绝不删除仍可能迟到的 exact tombstone。
|
|
1339
1750
|
failedHandoffChildren.pruneUnmatchable(parent);
|
|
1340
1751
|
}
|
|
1341
|
-
function allHandoffAdmissionsPaused(parent) {
|
|
1342
|
-
const entries = handoffAdmissionCohort.entriesFor(parent);
|
|
1343
|
-
return entries.length === 0 || handoffAdmissionCohort.allPaused(parent);
|
|
1344
|
-
}
|
|
1345
1752
|
function pendingHandoffAdmissionFor(parent, childId, admission) {
|
|
1346
1753
|
if (admission !== void 0) return host.handoff.contains(admission) && admission.parent === parent ? admission : void 0;
|
|
1347
1754
|
return host.handoff.find((item) => item.parent === parent && item.childId === childId);
|
|
@@ -1380,7 +1787,7 @@ export default {
|
|
|
1380
1787
|
// (后续合法 settlement 的消费判定依赖它),但不得按 activation 级 snapshot 把
|
|
1381
1788
|
// 本轮 token 直接标成 feedbackSeen——那会在 recovery operation 尚未完成时消耗掉
|
|
1382
1789
|
// token,父 inbox 之后到达的合法 UUID settlement 就再也找不到未消费 entry,child
|
|
1383
|
-
//
|
|
1790
|
+
// token 永不结算(root 永久等待)。
|
|
1384
1791
|
//
|
|
1385
1792
|
// A:判定只用**当前这一个 event/turn** 的 reason/output,不扫描 session.events 的
|
|
1386
1793
|
// 最新 turn/end(同一同步批次里更晚的普通 turn/end 会让 gate 误判为关闭)。
|
|
@@ -1403,7 +1810,7 @@ export default {
|
|
|
1403
1810
|
//
|
|
1404
1811
|
// item 2/P1:recoverable failure 的 gate 尚未关闭时,本 turn/end **不是**终态边界:
|
|
1405
1812
|
// 已排队的 marker(包含无 message.id 的 early delivery)绝不能在这里消费 token,
|
|
1406
|
-
// 否则 recovery operation
|
|
1813
|
+
// 否则 recovery operation 尚未建立/完成就消费 token 并提前放行 root。marker 保留到 recovery
|
|
1407
1814
|
// 完成后的真实终态边界(或由 releaseGatedRecoveryFeedback 重新投递的带 UUID 最终
|
|
1408
1815
|
// 通知走 exact/wildcard 正常路径消费)。
|
|
1409
1816
|
if (recoveryGateOpen) {
|
|
@@ -1470,8 +1877,9 @@ export default {
|
|
|
1470
1877
|
if (consumedMarkers.length > 0) {
|
|
1471
1878
|
record.pendingFeedbacks = pendingFeedbacks.filter((item) => !consumedMarkers.includes(item));
|
|
1472
1879
|
}
|
|
1473
|
-
// feedback 可能已经在本 turn/end
|
|
1474
|
-
|
|
1880
|
+
// feedback 可能已经在本 turn/end 前到达:本 turn/end 边界本身也可能让 cohort 就绪,
|
|
1881
|
+
// 因此这里重新检查一次精确结算(不改变任何 release/清理语义)。
|
|
1882
|
+
settleFinishedChildTurnWaits(record.parentAgent);
|
|
1475
1883
|
// 一个 turn 的所有 admission 共用一次 deferred recovery 结算。
|
|
1476
1884
|
return matches[0];
|
|
1477
1885
|
}
|
|
@@ -1508,7 +1916,7 @@ export default {
|
|
|
1508
1916
|
* 宿主会以**同一个 message.id** 重复投递同一条 child settlement(重放/重入的 inserted)。
|
|
1509
1917
|
* 这条副本不是新结论:它一旦进入 cohort 消费/排队,就会用上一轮早已结算的 feedback 去
|
|
1510
1918
|
* 消费本轮新登记的 token,把本轮 token 的 feedbackSeen 提前置 true → cohort.ready()
|
|
1511
|
-
* 提前成立 →
|
|
1919
|
+
* 提前成立 → root 在本轮结果真正回来之前提前放行。
|
|
1512
1920
|
*
|
|
1513
1921
|
* 账本生命周期与 child recovery record 一致(record 被 drop/owner 变更时随之丢弃):
|
|
1514
1922
|
* message.id 是 DSH 为每条消息新铸的 UUID,不存在「同 id 被合法复用为下一轮真实
|
|
@@ -1589,7 +1997,7 @@ export default {
|
|
|
1589
1997
|
* `source.kind = "subagent-settled"` + `form = "notice"` 且经 createUserMessage 铸 UUID;
|
|
1590
1998
|
* `subagent-report`(form=relay) 只存在于 legacy session-format 的 payload 校验/迁移里,
|
|
1591
1999
|
* runtime 不会为同一逻辑结算双投递。按「计数领先即副本」做全局配对没有身份证据,反而会把
|
|
1592
|
-
* 真正新一轮的 notice 误判成副本丢弃(该轮
|
|
2000
|
+
* 真正新一轮的 notice 误判成副本丢弃(该轮 token 永不结算 → root 永久等待)。
|
|
1593
2001
|
* 因此跨形态去重只保留可证明的部分:message.id 去重(A1)、到达快照收紧(A2/A3)与
|
|
1594
2002
|
* 无 id fail-closed(item 1)。legacy relay 仍按独立结算通道接受,但不与 notice 配对。
|
|
1595
2003
|
*/
|
|
@@ -1664,9 +2072,8 @@ export default {
|
|
|
1664
2072
|
if (!isCurrentRecoveryFeedbackIdentity(agent, record, childId)) return void 0;
|
|
1665
2073
|
const feedbackMessageId = typeof message?.id === "string" && message.id.length > 0 ? message.id : void 0;
|
|
1666
2074
|
const identity = claimFeedbackIdentity(record, feedbackMessageId);
|
|
1667
|
-
// 同 id 副本:不消费、不排队。调用方(inbox/inserted microtask
|
|
1668
|
-
//
|
|
1669
|
-
// `child:<id>:<token>`,裸键在 `reasons.has(reasonKey)` 上不命中 → 安全 no-op。
|
|
2075
|
+
// 同 id 副本:不消费、不排队。调用方(inbox/inserted microtask)随后仍会走一次
|
|
2076
|
+
// 「已就绪 admission 的精确结算」检查,但副本不会让任何 token 就绪,因此是安全空操作。
|
|
1670
2077
|
if (identity.duplicate) return void 0;
|
|
1671
2078
|
const admissionId = feedbackAdmissionId(message);
|
|
1672
2079
|
const candidates = host.handoff.filter((item) =>
|
|
@@ -1765,30 +2172,59 @@ export default {
|
|
|
1765
2172
|
});
|
|
1766
2173
|
return entry;
|
|
1767
2174
|
}
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
2175
|
+
/**
|
|
2176
|
+
* 把 cohort 已就绪的 admission 从等待登记表里**精确结算**。
|
|
2177
|
+
*
|
|
2178
|
+
* 就绪 = 该 admission 的 turn 已经结束(child turn/end 边界)且收到了精确关联的
|
|
2179
|
+
* 父 inbox settlement(cohort.ready 的判定)。这是「exact 完成通知」这条释放通道:
|
|
2180
|
+
* 只有精确关联的通知才结算对应的 token,重复/错误/他 root/旧代际的通知都不会命中
|
|
2181
|
+
* 未结算项,因此是安全的幂等空操作。
|
|
2182
|
+
*
|
|
2183
|
+
* entry 本身**不**在这里摘除:它仍由既有的 release/清理路径负责,保证「同一 child
|
|
2184
|
+
* 的后续 admission 不会绕过 cohort」的既有语义不变。
|
|
2185
|
+
*/
|
|
2186
|
+
/** 精确结算一个 admission 的等待工作(token 非法 / 已结算时是安全空操作)。 */
|
|
2187
|
+
function settleAdmissionTurnWait(agent, entry) {
|
|
2188
|
+
const token = typeof entry?.token === "string" && entry.token.length > 0 ? entry.token : void 0;
|
|
2189
|
+
if (token === void 0) return false;
|
|
2190
|
+
return rootTurnWaits.settle(agent, { kind: "admission", token });
|
|
2191
|
+
}
|
|
2192
|
+
|
|
2193
|
+
/**
|
|
2194
|
+
* 把已经真正结束的 admission 从等待登记表里**精确结算**。
|
|
2195
|
+
*
|
|
2196
|
+
* 两条结算通道,严格区分「精确」与「猜测」:
|
|
2197
|
+
* 1. **exact 完成通知**:该 admission 的 child turn 已结束,且收到了精确关联的父
|
|
2198
|
+
* inbox settlement(cohort.ready 的判定)。重复 / 错误 / 他 root / 旧代际的通知
|
|
2199
|
+
* 都不会让任何 token 就绪,因此是安全的幂等空操作;
|
|
2200
|
+
* 2. **完成通知缺失时的回退**(只在拿到**明确**快照时可用):该 admission 的 turn
|
|
2201
|
+
* 已结束,且它的 exact child 明确不在 running 后代列表里。unknown / 查询失败 /
|
|
2202
|
+
* 血缘无法确定时绝不会走到这里——调用方只在 `known === true` 的快照上调用。
|
|
2203
|
+
*
|
|
2204
|
+
* entry 本身**不**在这里摘除:它仍由既有的 release/清理路径负责,保证「同一 child
|
|
2205
|
+
* 的后续 admission 不会绕过 cohort」的既有语义不变。
|
|
2206
|
+
*
|
|
2207
|
+
* @param {object} agent - exact root Agent。
|
|
2208
|
+
* @param {{known:boolean,runningIds?:Set<string>}} [snapshot] - 明确的后代快照;
|
|
2209
|
+
* 省略时只走通道 1(不启用回退)。
|
|
2210
|
+
*/
|
|
2211
|
+
function settleFinishedChildTurnWaits(agent, snapshot) {
|
|
1779
2212
|
if (!isLiveRootAgent(agent)) return;
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
// 当前 root cohort 的 pause 屏障,且 release/resume 失败仍可精确收口。
|
|
1788
|
-
entry.releaseQueued = true;
|
|
1789
|
-
releaseRootGoalHandoff(agent, { kind: "child", id: entry.childId, admissionId: entry.token }, entry);
|
|
2213
|
+
const known = snapshot?.known === true;
|
|
2214
|
+
const runningIds = known && snapshot.runningIds instanceof Set ? snapshot.runningIds : void 0;
|
|
2215
|
+
for (const entry of host.handoff.entries()) {
|
|
2216
|
+
if (entry.parent !== agent || entry.failed === true) continue;
|
|
2217
|
+
if (handoffAdmissionCohort.ready(agent, entry)) {
|
|
2218
|
+
settleAdmissionTurnWait(agent, entry);
|
|
2219
|
+
continue;
|
|
1790
2220
|
}
|
|
1791
|
-
|
|
2221
|
+
if (runningIds === void 0) continue;
|
|
2222
|
+
if (entry.turnEnded !== true) continue;
|
|
2223
|
+
const childId = entry.childId;
|
|
2224
|
+
if (typeof childId !== "string" || childId.length === 0) continue;
|
|
2225
|
+
if (runningIds.has(childId)) continue;
|
|
2226
|
+
settleAdmissionTurnWait(agent, entry);
|
|
2227
|
+
}
|
|
1792
2228
|
}
|
|
1793
2229
|
|
|
1794
2230
|
/**
|
|
@@ -1947,7 +2383,7 @@ export default {
|
|
|
1947
2383
|
*
|
|
1948
2384
|
* item 2:**无 message.id 的 delivery 同样必须被门控**。旧实现在缺 id 时直接返回
|
|
1949
2385
|
* false,于是它继续走普通队列,可能在 recoverable failure 的 recovery operation
|
|
1950
|
-
*
|
|
2386
|
+
* 尚未建立/完成时就消费 token 并提前放行 root。无 id 时协议不提供任何可寻址身份:
|
|
1951
2387
|
* - 不能用 inbox.remove(id) 撤回(没有 id);
|
|
1952
2388
|
* - 只能用 **exact message 对象身份**登记 gated marker,并把该对象写入对象身份
|
|
1953
2389
|
* tombstone(WeakSet,随 GC 回收,不做无界 Set);
|
|
@@ -2127,11 +2563,11 @@ export default {
|
|
|
2127
2563
|
}
|
|
2128
2564
|
|
|
2129
2565
|
/**
|
|
2130
|
-
* 已确认属于当前 child/session/turn 的正常终态,不能因父
|
|
2131
|
-
* 而继续占用 root 的文件范围。通常 admission 是 exact
|
|
2132
|
-
*
|
|
2566
|
+
* 已确认属于当前 child/session/turn 的正常终态,不能因父 inbox 尚未收到 settlement
|
|
2567
|
+
* 而继续占用 root 的文件范围。通常 admission 是 exact token;mixed admission 时当前
|
|
2568
|
+
* turn 可能是 continue_parent_turn(没有 admission token),仍按该 turn 的稳定
|
|
2133
2569
|
* messageId/taskKey 精确释放 activity。这里只释放 activity,不消费 pending turn/end、
|
|
2134
|
-
* 不改变
|
|
2570
|
+
* 不改变 admission;可恢复异常仍保留 activity,交给恢复链终态处理。
|
|
2135
2571
|
*/
|
|
2136
2572
|
function releaseTerminalActivitiesBeforeHandoffFeedback(record, session, event, admission) {
|
|
2137
2573
|
if (admission?.failed === true || record?.session !== session) return;
|
|
@@ -2232,17 +2668,6 @@ export default {
|
|
|
2232
2668
|
}
|
|
2233
2669
|
function migrateChildHandoff(parent, previousChildId, nextChildId, nextActivation, previousActivation) {
|
|
2234
2670
|
if (!isRootAgentIdentity(parent) || previousChildId === nextChildId) return;
|
|
2235
|
-
const oldPrefix = handoffReasonChildKey(previousChildId);
|
|
2236
|
-
const nextPrefix = handoffReasonChildKey(nextChildId);
|
|
2237
|
-
const handoff = goalHandoffs.get(parent.id);
|
|
2238
|
-
if (oldPrefix !== void 0 && nextPrefix !== void 0 && handoff?.agent === parent && handoff.reasons instanceof Map) {
|
|
2239
|
-
for (const [key, value] of [...handoff.reasons]) {
|
|
2240
|
-
if (key !== oldPrefix && !key.startsWith(oldPrefix + ":")) continue;
|
|
2241
|
-
const suffix = key.slice(oldPrefix.length);
|
|
2242
|
-
handoff.reasons.delete(key);
|
|
2243
|
-
handoff.reasons.set(nextPrefix + suffix, value);
|
|
2244
|
-
}
|
|
2245
|
-
}
|
|
2246
2671
|
for (const entry of host.handoff.entries()) {
|
|
2247
2672
|
if (entry.parent === parent && entry.childId === previousChildId) {
|
|
2248
2673
|
handoffAdmissionCohort.rebindChild(entry, nextChildId);
|
|
@@ -2263,173 +2688,103 @@ export default {
|
|
|
2263
2688
|
});
|
|
2264
2689
|
}
|
|
2265
2690
|
}
|
|
2266
|
-
|
|
2691
|
+
/**
|
|
2692
|
+
* root 用户等待(ask_user_question / exit_plan_mode)的同步 guard。
|
|
2693
|
+
*
|
|
2694
|
+
* 改造后的职责边界:
|
|
2695
|
+
* - **不再**暂停/恢复任何 durable goal。用户等待本身由宿主保持 root turn 打开
|
|
2696
|
+
* (宿主完整 await 工具 execute 的返回),goal round driver 只在 root idle 时
|
|
2697
|
+
* 推进,因此这里没有任何 goal API 调用,也不需要 barrier;
|
|
2698
|
+
* - 保留非 goal 的 pending-user-wait 记账与一次性提示音:按 exact root Agent 记录
|
|
2699
|
+
* 当前等待的工具名,同一次等待重复进入 guard(重试/重复调用)不重复提示,
|
|
2700
|
+
* 等待被清理后再次登记才再提示一次;
|
|
2701
|
+
* - root 已销毁 / 代际被替换 / 插件卸载中一律拒绝:此时不能开始一个没有归属的等待。
|
|
2702
|
+
*
|
|
2703
|
+
* @param {object} agent - guard 所属的 exact root Agent。
|
|
2704
|
+
* @param {object} execution - 待执行的 ToolExecution。
|
|
2705
|
+
* @returns {string|undefined} 拒绝原因;undefined 表示放行。
|
|
2706
|
+
*/
|
|
2707
|
+
function rootUserWaitGuard(agent, execution) {
|
|
2267
2708
|
if (execution?.agent !== agent || (execution?.name !== "ask_user_question" && execution?.name !== "exit_plan_mode")) return void 0;
|
|
2268
|
-
if (
|
|
2269
|
-
//
|
|
2270
|
-
|
|
2271
|
-
|
|
2272
|
-
|
|
2273
|
-
|
|
2274
|
-
|
|
2275
|
-
|
|
2276
|
-
|
|
2277
|
-
|
|
2278
|
-
|
|
2279
|
-
|
|
2280
|
-
});
|
|
2281
|
-
// 同一次等待里重复进入 guard(重试/重复调用)不重复提示;等待被清理后再次登记才再提示一次。
|
|
2282
|
-
if (previousWait === void 0 || previousWait.tool !== execution.name) {
|
|
2283
|
-
sendSystemToast(userWaitToastText(execution.name, rootNotificationLabel(agent.session)));
|
|
2284
|
-
}
|
|
2285
|
-
}
|
|
2286
|
-
return paused === false ? "Cannot start user wait because the durable root goal could not be paused." : void 0;
|
|
2287
|
-
}
|
|
2288
|
-
function pauseRootGoalForChild(agent, childId, admission) {
|
|
2289
|
-
if (goalHandoffStopping || !isLiveRootAgent(agent) || typeof childId !== "string" || childId.length === 0) return false;
|
|
2290
|
-
const pendingAdmission = pendingHandoffAdmissionFor(agent, childId, admission);
|
|
2291
|
-
// 显式传入 admission 对象时,它必须是 host.handoff 里仍有效的 exact 记录
|
|
2292
|
-
// (pendingHandoffAdmissionFor 内部已做 contains + parent 校验)。已失效
|
|
2293
|
-
// (release 成功、fail-closed 清理、parent 不匹配)时绝不能降级为裸
|
|
2294
|
-
// `child:<id>` reason:那个键没有 token 后缀,没有任何释放边界,会把 goal
|
|
2295
|
-
// 永久钉在 paused。这里 fail-closed 返回 false,并保留可诊断的 warn。
|
|
2296
|
-
// 注意:admission === undefined 的既有语义(按 childId 查找当前 admission)
|
|
2297
|
-
// 保持不变——只有「调用方明确给了一个对象、但对象已不在册」才拦截。
|
|
2298
|
-
if (admission !== void 0 && pendingAdmission === void 0) {
|
|
2299
|
-
logGoalHandoffError("pause", new Error("handoff admission is no longer live for child " + childId));
|
|
2300
|
-
return false;
|
|
2709
|
+
if (turnWaitStopping || !isLiveRootAgent(agent)) return "Cannot start user wait because the exact root Agent is no longer live.";
|
|
2710
|
+
// 统一登记点:root 用户等待只有这一处写入,因此通知也接在这里,避免出现第二份登记。
|
|
2711
|
+
const previousWait = pendingUserWaits.get(agent);
|
|
2712
|
+
pendingUserWaits.set(agent, {
|
|
2713
|
+
agent,
|
|
2714
|
+
session: agent.session,
|
|
2715
|
+
generation: rootGenerationRegistry.generationOf(agent.id),
|
|
2716
|
+
tool: execution.name,
|
|
2717
|
+
});
|
|
2718
|
+
// 同一次等待里重复进入 guard(重试/重复调用)不重复提示;等待被清理后再次登记才再提示一次。
|
|
2719
|
+
if (previousWait === void 0 || previousWait.tool !== execution.name) {
|
|
2720
|
+
sendSystemToast(userWaitToastText(execution.name, rootNotificationLabel(agent.session)));
|
|
2301
2721
|
}
|
|
2302
|
-
|
|
2303
|
-
|
|
2304
|
-
|
|
2305
|
-
|
|
2306
|
-
|
|
2307
|
-
|
|
2308
|
-
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2312
|
-
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
|
|
2316
|
-
|
|
2317
|
-
|
|
2318
|
-
|
|
2319
|
-
|
|
2320
|
-
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2324
|
-
if (
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
2328
|
-
const settlePaused = (onValue, onFailure) => {
|
|
2329
|
-
let promise;
|
|
2330
|
-
try {
|
|
2331
|
-
if (!isThenable(paused)) return settleOnce(onValue, permission());
|
|
2332
|
-
promise = Promise.resolve(paused);
|
|
2333
|
-
} catch (error) {
|
|
2334
|
-
return settleOnce(onFailure, error);
|
|
2722
|
+
return void 0;
|
|
2723
|
+
}
|
|
2724
|
+
|
|
2725
|
+
/**
|
|
2726
|
+
* 把一批已 settle 的 accepted admission 登记进唯一的 root turn 等待登记表。
|
|
2727
|
+
*
|
|
2728
|
+
* 判定必须与 finalize 的 acceptedEntries 完全一致:reused / continue_parent_turn
|
|
2729
|
+
* 的 admission 不产生"未结算工作",但它们**仍然可能留下正在运行的子代理**
|
|
2730
|
+
* (continue_parent_turn 的 child 就是典型的后台运行),因此这里对它们只做
|
|
2731
|
+
* `engage`(保证该 root 已进入等待体系,让 turn-stopping 兜底参与判定),
|
|
2732
|
+
* 不登记工作项。
|
|
2733
|
+
*
|
|
2734
|
+
* @param {object} parent - exact root Agent。
|
|
2735
|
+
* @param {object[]} entries - 开放批次里的 accepted admission entry。
|
|
2736
|
+
* @returns {{tracked:number, engaged:number, invalid:number}} 登记统计。
|
|
2737
|
+
*/
|
|
2738
|
+
function registerRootTurnWaitWork(parent, entries) {
|
|
2739
|
+
let tracked = 0;
|
|
2740
|
+
let engaged = 0;
|
|
2741
|
+
let invalid = 0;
|
|
2742
|
+
for (const entry of entries) {
|
|
2743
|
+
const outcome = entry?.outcome;
|
|
2744
|
+
if (outcome?.kind !== "continuable") continue;
|
|
2745
|
+
if (outcome.reused === true || outcome.continueParentTurn === true) {
|
|
2746
|
+
if (rootTurnWaits.engage(parent)) engaged += 1;
|
|
2747
|
+
continue;
|
|
2335
2748
|
}
|
|
2336
|
-
|
|
2337
|
-
|
|
2338
|
-
|
|
2339
|
-
|
|
2340
|
-
|
|
2341
|
-
|
|
2342
|
-
// 非规范 Promise 实现的 then 同步抛错时回调尚未登记,按失败收口。
|
|
2343
|
-
return settleOnce(onFailure, error);
|
|
2749
|
+
const admission = outcome.handoffAdmission;
|
|
2750
|
+
// admission 已失效(被其他路径释放/清理):没有可结算的工作,也不登记——
|
|
2751
|
+
// 登记一个永远不会结算的键会让 root 永久等待。
|
|
2752
|
+
if (admission === void 0 || host.handoff.contains(admission) !== true || admission.parent !== parent) {
|
|
2753
|
+
invalid += 1;
|
|
2754
|
+
continue;
|
|
2344
2755
|
}
|
|
2345
|
-
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2349
|
-
logGoalHandoffError("pause", error);
|
|
2350
|
-
return finish(false);
|
|
2351
|
-
};
|
|
2352
|
-
const finishResuming = () => {
|
|
2353
|
-
if (!isLiveRootAgent(agent)) return false;
|
|
2354
|
-
const current = goalHandoffs.get(agent.id);
|
|
2355
|
-
if (current === resumingRecord && current.agent === agent
|
|
2356
|
-
&& current.state === "paused" && pendingAdmission !== void 0) {
|
|
2357
|
-
pendingAdmission.pauseDone = true;
|
|
2358
|
-
handoffAdmissionCohort.markPauseDone(pendingAdmission);
|
|
2359
|
-
tryReleaseReadyChildHandoffs(agent);
|
|
2360
|
-
}
|
|
2361
|
-
// resume in-flight 无论成功重暂停还是失败,都禁止当前 child conclude;
|
|
2362
|
-
// failed 分支由 releaseRootGoalHandoff 的 exact admission 收口处理。
|
|
2363
|
-
return false;
|
|
2364
|
-
};
|
|
2365
|
-
const finish = (permissionResult) => {
|
|
2366
|
-
const pauseFailed = failed || permissionResult === false;
|
|
2367
|
-
if (!isLiveRootAgent(agent)) {
|
|
2368
|
-
clearGoalHandoff(goalHandoffs, agent);
|
|
2369
|
-
clearPendingHandoffAdmissions(agent);
|
|
2370
|
-
failedHandoffChildren.delete(agent);
|
|
2371
|
-
settlePendingChildTurnEnds(agent, false);
|
|
2372
|
-
return false;
|
|
2756
|
+
const token = typeof admission.token === "string" && admission.token.length > 0 ? admission.token : void 0;
|
|
2757
|
+
if (token === void 0) {
|
|
2758
|
+
invalid += 1;
|
|
2759
|
+
continue;
|
|
2373
2760
|
}
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2377
|
-
|
|
2378
|
-
|
|
2379
|
-
}
|
|
2380
|
-
const feedbackSeen = pendingAdmission?.feedbackSeen === true;
|
|
2381
|
-
if (pauseFailed) {
|
|
2382
|
-
// pause/get/CAS 失败时 fail closed:只清理当前 exact root,不再次自动恢复。
|
|
2383
|
-
// 同一 root 的 admission 共享一次 pause;该共享操作失败时所有已登记
|
|
2384
|
-
// admission 都必须 fail closed,避免任一后续 finish 误放行自动恢复。
|
|
2385
|
-
const pendingEntries = host.handoff.filter((item) => item.parent === agent);
|
|
2386
|
-
// 共享 pause 失败只记录 exact admission token;裸 child key 会压制
|
|
2387
|
-
// 同 child 的后续正常 admission,不能与 token fallback 同时写入。
|
|
2388
|
-
rememberFailedHandoffChildren(agent, pendingEntries);
|
|
2389
|
-
clearPendingHandoffAdmissions(agent);
|
|
2390
|
-
settlePendingChildTurnEnds(agent, false);
|
|
2391
|
-
} else if (hasHandoff) {
|
|
2392
|
-
if (pendingAdmission !== void 0 && feedbackSeen) pendingAdmission.feedbackSeen = true;
|
|
2393
|
-
tryReleaseReadyChildHandoffs(agent);
|
|
2394
|
-
} else {
|
|
2395
|
-
removePendingHandoffAdmission(pendingAdmission);
|
|
2396
|
-
// 没有 armed goal 时释放该 admission 的暂存终态,正常继续恢复链。
|
|
2397
|
-
settlePendingChildTurnEnds(agent, true, pendingAdmission);
|
|
2761
|
+
if (rootTurnWaits.track(parent, { kind: "admission", token }) !== void 0) {
|
|
2762
|
+
// 等待登记成功即「该 admission 的等待屏障已建立」——这正是 cohort 的 pauseDone
|
|
2763
|
+
// 在旧实现里表达的语义(字段名来自 goal pause 时代,这里保留以免扩大改动面)。
|
|
2764
|
+
handoffAdmissionCohort.markPauseDone(admission);
|
|
2765
|
+
tracked += 1;
|
|
2398
2766
|
}
|
|
2399
|
-
return permissionResult;
|
|
2400
|
-
};
|
|
2401
|
-
// resuming 判定必须读取 pause 调用**之后**的记录状态(与既有语义一致):
|
|
2402
|
-
// pause 可能新建记录,也必须在 resuming 记录上登记新 reason。
|
|
2403
|
-
let resumingRecord;
|
|
2404
|
-
try {
|
|
2405
|
-
paused = pauseGoalForHandoff(goals, agent, goalHandoffs, { kind: "child", id: childId, ...(admissionId === void 0 ? {} : { admissionId }) }, (error) => {
|
|
2406
|
-
failed = true;
|
|
2407
|
-
logGoalHandoffError("pause", error);
|
|
2408
|
-
});
|
|
2409
|
-
} catch (error) {
|
|
2410
|
-
// shared helper 自身抛错(损坏 adapter / 非规范 Promise 实现)同样按 pause 失败收口,
|
|
2411
|
-
// 绝不让异常逃出本函数。
|
|
2412
|
-
return failPause(error);
|
|
2413
|
-
}
|
|
2414
|
-
resumingRecord = goalHandoffs.get(agent.id);
|
|
2415
|
-
const wasResuming = resumingRecord?.agent === agent && resumingRecord.state === "resuming";
|
|
2416
|
-
if (wasResuming) {
|
|
2417
|
-
// resume in-flight:只等待在飞操作,成功/失败都不允许当前 child conclude。
|
|
2418
|
-
// 失败(含损坏 then getter)按 pause 失败记账并返回 false。
|
|
2419
|
-
return settlePaused(finishResuming, (error) => {
|
|
2420
|
-
failed = true;
|
|
2421
|
-
logGoalHandoffError("pause", error);
|
|
2422
|
-
return false;
|
|
2423
|
-
});
|
|
2424
2767
|
}
|
|
2425
|
-
return
|
|
2768
|
+
return { tracked, engaged, invalid };
|
|
2426
2769
|
}
|
|
2427
2770
|
|
|
2428
2771
|
/**
|
|
2429
|
-
* root-only
|
|
2430
|
-
*
|
|
2431
|
-
*
|
|
2432
|
-
*
|
|
2772
|
+
* root-only 显式收口:登记调用方明确列出的、已经返回结果的 admission,然后等待
|
|
2773
|
+
* 这些工作真正结束。
|
|
2774
|
+
*
|
|
2775
|
+
* 用户确认的 A 方案语义:
|
|
2776
|
+
* 1. 校验阶段与旧实现完全一致(token 集完整性、outcome 已 settle、
|
|
2777
|
+
* continue_parent_turn / safeParallelWork 等拒绝条件);
|
|
2778
|
+
* 2. 把每个 accepted admission 登记进**唯一的** root turn 等待登记表;
|
|
2779
|
+
* 3. 等待该 root 精确关联的工作全部结束——**不设任何超时**(子代理可能运行数小时)。
|
|
2780
|
+
* 释放条件见 host/turn-wait.js:无未结算工作 + root-scoped 查询明确无 running
|
|
2781
|
+
* 后代;unknown / 查询失败一律继续等待;
|
|
2782
|
+
* 4. 等待成立后正常返回,工具 execute 的 Promise 收口,root turn 随之结束。
|
|
2783
|
+
*
|
|
2784
|
+
* 与旧实现的两个关键差异:
|
|
2785
|
+
* - **不再调用 exec.concludeTurn()**:turn 由宿主在工具返回后自然关闭,插件不再
|
|
2786
|
+
* 主动结束它;保持 turn 打开本身就是"阻止 goal round 推进"的手段;
|
|
2787
|
+
* - **不再暂停/恢复任何 goal**:不再有 paused/concluded 之类的回执字段。
|
|
2433
2788
|
*/
|
|
2434
2789
|
async function finalizeRootAdmissionBatch(parent, exec, args, rootToken) {
|
|
2435
2790
|
const epoch = args?.admissionEpoch;
|
|
@@ -2437,8 +2792,6 @@ export default {
|
|
|
2437
2792
|
const base = {
|
|
2438
2793
|
admissionEpoch: Number.isSafeInteger(epoch) ? epoch : 0,
|
|
2439
2794
|
acceptedCount: 0,
|
|
2440
|
-
paused: false,
|
|
2441
|
-
concluded: false,
|
|
2442
2795
|
};
|
|
2443
2796
|
if (args?.summaryCompleted !== true || args?.outcomesChecked !== true) {
|
|
2444
2797
|
return { kind: "rejected", ...base, reason: "summary-or-outcome-check-required" };
|
|
@@ -2449,10 +2802,9 @@ export default {
|
|
|
2449
2802
|
if (!Number.isSafeInteger(epoch) || !Array.isArray(tokens)) {
|
|
2450
2803
|
return { kind: "rejected", ...base, reason: "invalid-admission-token-set" };
|
|
2451
2804
|
}
|
|
2452
|
-
//
|
|
2453
|
-
//
|
|
2454
|
-
//
|
|
2455
|
-
// message 字段,不需要改 output 契约。
|
|
2805
|
+
// 拒绝/不完整回执必须带上可自诊断的 message。reason 仍是稳定机器码(契约与既有
|
|
2806
|
+
// 测试都按 reason 断言),message 只补充「当前真实状态是什么」,让模型不必再靠猜
|
|
2807
|
+
// 去补齐 admissionTokens / admissionEpoch。
|
|
2456
2808
|
const batch = rootAdmissionBatches.get(parent);
|
|
2457
2809
|
if (batch === void 0) {
|
|
2458
2810
|
if (epoch === 0 && tokens.length === 0) return { kind: "noop", ...base, reason: "no-admission" };
|
|
@@ -2463,6 +2815,14 @@ export default {
|
|
|
2463
2815
|
message: "no open admission batch",
|
|
2464
2816
|
};
|
|
2465
2817
|
}
|
|
2818
|
+
// 已关闭批次上的「无 admission」调用(epoch 0 + 空 token 集)是幂等 no-admission,
|
|
2819
|
+
// 不是 stale:模型在没有调用任何 role 工具时被要求用这个凭据收口,重复调用必须与
|
|
2820
|
+
// 首次调用(没有开放批次时的 no-admission)得到同一个结论。这个判定必须早于 epoch
|
|
2821
|
+
// 比较——0 永远不等于任何真实 epoch,放在后面会被 stale 分支抢先。**非零** epoch
|
|
2822
|
+
// 仍然按 stale-admission-epoch 拒绝(那是真的过期凭据)。
|
|
2823
|
+
if (batch.closed === true && epoch === 0 && tokens.length === 0) {
|
|
2824
|
+
return { kind: "noop", ...base, reason: "no-admission" };
|
|
2825
|
+
}
|
|
2466
2826
|
if (batch.epoch !== epoch) {
|
|
2467
2827
|
return {
|
|
2468
2828
|
kind: "rejected",
|
|
@@ -2504,69 +2864,46 @@ export default {
|
|
|
2504
2864
|
batch.closed = true;
|
|
2505
2865
|
return { kind: "noop", ...base, reason: "no-accepted-admission" };
|
|
2506
2866
|
}
|
|
2867
|
+
// 两阶段收口:① 登记等待工作(同步、无副作用);② 等待静止(**不设超时**)。
|
|
2868
|
+
// 登记必须在任何 await 之前完成,否则「登记前到达的 child 完成通知」会找不到
|
|
2869
|
+
// 工作项而变成空操作。
|
|
2507
2870
|
batch.finalizing = true;
|
|
2508
2871
|
try {
|
|
2509
|
-
|
|
2510
|
-
let skippedCount = 0;
|
|
2511
|
-
for (const entry of acceptedEntries) {
|
|
2512
|
-
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
2513
|
-
batch.closed = true;
|
|
2514
|
-
return { kind: "rejected", ...base, acceptedCount: acceptedEntries.length, reason: "root-generation-retired" };
|
|
2515
|
-
}
|
|
2516
|
-
// 每个 admission 在 pause 前重新校验它仍是 host.handoff 里的 exact 活动记录:
|
|
2517
|
-
// 自动兜底 pause 之后的 release(child feedback)或 fail-closed 清理都可能已经
|
|
2518
|
-
// 把它摘除。此时它已经没有任何释放边界,再 pause 会退化成裸 child:<id> reason
|
|
2519
|
-
// → goal 永久 paused。因此「已释放」是跳过语义,绝不是失败(fail-closed 只针对
|
|
2520
|
-
// 真实 pause/get/CAS 失败)。
|
|
2521
|
-
const admission = entry.outcome.handoffAdmission;
|
|
2522
|
-
if (host.handoff.contains(admission) !== true || admission.parent !== parent) {
|
|
2523
|
-
skippedCount += 1;
|
|
2524
|
-
continue;
|
|
2525
|
-
}
|
|
2526
|
-
const paused = await pauseRootGoalForChild(parent, entry.outcome.subagentId, admission);
|
|
2527
|
-
if (paused === false) {
|
|
2528
|
-
batch.closed = true;
|
|
2529
|
-
return { kind: "rejected", ...base, acceptedCount: acceptedEntries.length, reason: "goal-pause-failed" };
|
|
2530
|
-
}
|
|
2531
|
-
pausedCount += 1;
|
|
2532
|
-
}
|
|
2533
|
-
if (pausedCount === 0) {
|
|
2534
|
-
// 全部 accepted admission 都已被其他路径收口/释放:按 no-accepted-admission
|
|
2535
|
-
// 的 noop 语义关闭本 epoch(不 conclude:没有留下任何需要 barrier 的等待)。
|
|
2536
|
-
batch.closed = true;
|
|
2537
|
-
return { kind: "noop", ...base, acceptedCount: acceptedEntries.length, reason: "admissions-already-released" };
|
|
2538
|
-
}
|
|
2539
|
-
if (typeof exec?.concludeTurn !== "function") {
|
|
2872
|
+
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
2540
2873
|
batch.closed = true;
|
|
2541
|
-
return { kind: "rejected", ...base, acceptedCount: acceptedEntries.length, reason: "
|
|
2874
|
+
return { kind: "rejected", ...base, acceptedCount: acceptedEntries.length, reason: "root-generation-retired" };
|
|
2875
|
+
}
|
|
2876
|
+
const registered = registerRootTurnWaitWork(parent, acceptedEntries);
|
|
2877
|
+
const waitOutcome = await rootTurnWaits.wait(parent, exec?.signal);
|
|
2878
|
+
if (waitOutcome.released !== true) {
|
|
2879
|
+
// signal-aborted 只取消本次 waiter,批次与已登记工作仍可由同一凭据重试。
|
|
2880
|
+
// root 退休、代际替换或插件卸载等生命周期取消仍按原语义关闭批次。
|
|
2881
|
+
if (waitOutcome.reason !== "signal-aborted") batch.closed = true;
|
|
2882
|
+
return {
|
|
2883
|
+
kind: "rejected",
|
|
2884
|
+
...base,
|
|
2885
|
+
acceptedCount: acceptedEntries.length,
|
|
2886
|
+
reason: "root-wait-cancelled",
|
|
2887
|
+
message: "root turn wait was cancelled (" + waitOutcome.reason + ")",
|
|
2888
|
+
};
|
|
2542
2889
|
}
|
|
2543
2890
|
batch.closed = true;
|
|
2544
|
-
exec.concludeTurn();
|
|
2545
2891
|
return {
|
|
2546
2892
|
kind: "finalized",
|
|
2547
2893
|
...base,
|
|
2548
2894
|
acceptedCount: acceptedEntries.length,
|
|
2549
|
-
|
|
2550
|
-
concluded: true,
|
|
2551
|
-
reason: skippedCount > 0 ? "finalized-with-released-admissions" : "finalized",
|
|
2552
|
-
};
|
|
2553
|
-
} catch (error) {
|
|
2554
|
-
batch.closed = true;
|
|
2555
|
-
return {
|
|
2556
|
-
kind: "rejected",
|
|
2557
|
-
...base,
|
|
2558
|
-
acceptedCount: acceptedEntries.length,
|
|
2559
|
-
reason: "finalization-failed",
|
|
2560
|
-
message: error instanceof Error ? error.message : String(error),
|
|
2895
|
+
reason: "finalized",
|
|
2561
2896
|
};
|
|
2562
2897
|
} finally {
|
|
2563
2898
|
batch.finalizing = false;
|
|
2564
2899
|
}
|
|
2565
2900
|
}
|
|
2566
2901
|
|
|
2902
|
+
|
|
2903
|
+
|
|
2567
2904
|
ctx.effect(() => tools.register(defineTool({
|
|
2568
2905
|
name: "dsh_expert_group_finalize",
|
|
2569
|
-
description: "Finalize the current root turn only after every role-tool admission result named by admissionTokens has returned, the root agent has completed its summary and integration/review/verification check, and no safe non-overlapping parallel work remains. This root-only action
|
|
2906
|
+
description: "Finalize the current root turn only after every role-tool admission result named by admissionTokens has returned, the root agent has completed its summary and integration/review/verification check, and no safe non-overlapping parallel work remains. This root-only action then waits until every expert child it accepted has actually finished, keeping the root turn open meanwhile; it never waits with a timeout, because an expert may run for hours. Do not call it while safe parallel work remains; a pure continue_parent_turn batch has no accepted admission to finalize, while a later ordinary admission may finalize the complete checked token set.",
|
|
2570
2907
|
parameters: {
|
|
2571
2908
|
admissionEpoch: {
|
|
2572
2909
|
type: "number",
|
|
@@ -2603,15 +2940,13 @@ export default {
|
|
|
2603
2940
|
kind: { type: "string", required: true, enum: ["finalized", "noop", "rejected"] },
|
|
2604
2941
|
admissionEpoch: { type: "number", required: true },
|
|
2605
2942
|
acceptedCount: { type: "number", required: true },
|
|
2606
|
-
paused: { type: "boolean", required: true },
|
|
2607
|
-
concluded: { type: "boolean", required: true },
|
|
2608
2943
|
reason: { type: "string", required: true },
|
|
2609
2944
|
message: { type: "string" },
|
|
2610
2945
|
},
|
|
2611
2946
|
},
|
|
2612
2947
|
render(_args, value) {
|
|
2613
|
-
//
|
|
2614
|
-
//
|
|
2948
|
+
// render 必须带上 message,否则 rejected 的 self-diagnosis 文案在模型可见的
|
|
2949
|
+
// 工具输出里被丢弃(reason 是机器码,message 才是可执行提示)。
|
|
2615
2950
|
return [{ type: "text", text: "root finalization: " + value.reason + (value.message ? " — " + value.message : "") }];
|
|
2616
2951
|
},
|
|
2617
2952
|
},
|
|
@@ -2673,104 +3008,20 @@ export default {
|
|
|
2673
3008
|
},
|
|
2674
3009
|
})), "dsh-expert-group: stale scope release tool");
|
|
2675
3010
|
|
|
2676
|
-
function releaseRootGoalHandoffNow(agent, reason) {
|
|
2677
|
-
if (goalHandoffStopping || !isLiveRootAgent(agent)) return "none";
|
|
2678
|
-
const current = goalHandoffs.get(agent.id);
|
|
2679
|
-
if (current?.agent !== agent) return "none";
|
|
2680
|
-
// 让 shared helper 统一读取并校验 resume;这里不提前触发 remote adapter
|
|
2681
|
-
// 的 getter,避免 getter 异常绕过 pending 清理与 fail-closed 语义。
|
|
2682
|
-
return releaseGoalHandoffState(goals, goalHandoffs, agent, reason, (error) => logGoalHandoffError("resume", error));
|
|
2683
|
-
}
|
|
2684
|
-
/**
|
|
2685
|
-
* 在 DSH feedback/user 事件发布栈外释放 handoff;microtask 既避免 Session.append 重入,
|
|
2686
|
-
* 也让每个 admission token 的重复 feedback 落到 shared helper 的幂等 guard。
|
|
2687
|
-
*
|
|
2688
|
-
* @param {object} agent - exact root Agent。
|
|
2689
|
-
* @param {{kind:string,id?:string,admissionId?:string,attempt?:number}} reason - 已到达的等待原因。
|
|
2690
|
-
* @param {object} [admission] - executor 侧 admission 记录(可选,供清理语义使用)。
|
|
2691
|
-
* @param {(handoffState:string)=>void} [observer] - 可选收口回调:在**同一 generation 且
|
|
2692
|
-
* 旧 record 已结算**的边界上收到 "resumed"/"failed"/"none"/"waiting"/"resuming"。
|
|
2693
|
-
* fan-out 归属证据(item 5)据此在有归属证明时保留/刷新证据、归属消失时删除证据,
|
|
2694
|
-
* 避免把外部 pause 当成自己的 handoff。
|
|
2695
|
-
*/
|
|
2696
|
-
function releaseRootGoalHandoff(agent, reason, admission, observer) {
|
|
2697
|
-
if (goalHandoffStopping || !isLiveRootAgent(agent)) return;
|
|
2698
|
-
queueMicrotask(() => {
|
|
2699
|
-
if (!isLiveRootAgent(agent)) return;
|
|
2700
|
-
const current = goalHandoffs.get(agent.id);
|
|
2701
|
-
if (current?.agent !== agent) return;
|
|
2702
|
-
const expectedHandoff = current;
|
|
2703
|
-
const rootToken = host.lineage.tokenFor(agent);
|
|
2704
|
-
void Promise.resolve().then(() => releaseRootGoalHandoffNow(agent, reason)).then((handoffState) => {
|
|
2705
|
-
// 异步 resume 的结果只能影响发起它的 root generation 和 handoff record。
|
|
2706
|
-
// 成功/失败会删除旧 map,但若期间已有新 handoff,则不得碰新状态。
|
|
2707
|
-
const currentAfter = goalHandoffs.get(agent.id);
|
|
2708
|
-
const sameGeneration = host.lineage.isLiveGeneration(agent, rootToken);
|
|
2709
|
-
const oldRecordSettled = currentAfter === expectedHandoff
|
|
2710
|
-
|| ((handoffState === "resumed" || handoffState === "failed") && currentAfter === void 0);
|
|
2711
|
-
if (!sameGeneration || !oldRecordSettled) return;
|
|
2712
|
-
// waiting 只表示本原因已释放但 cohort/用户原因仍在;entry 必须保留,
|
|
2713
|
-
// 否则后续 admission 会绕过 barrier。全部恢复成功后才清掉该 generation。
|
|
2714
|
-
if (handoffState === "resumed") {
|
|
2715
|
-
for (const entry of host.handoff.entries()) {
|
|
2716
|
-
if (entry.parent === agent) removePendingHandoffAdmission(entry);
|
|
2717
|
-
}
|
|
2718
|
-
settlePendingChildTurnEnds(agent, true);
|
|
2719
|
-
}
|
|
2720
|
-
if (handoffState === "failed") {
|
|
2721
|
-
rememberFailedHandoffChildren(agent, host.handoff.filter((entry) => entry.parent === agent));
|
|
2722
|
-
clearPendingHandoffAdmissions(agent);
|
|
2723
|
-
settlePendingChildTurnEnds(agent, false);
|
|
2724
|
-
}
|
|
2725
|
-
// 收口回调必须在同一 generation + 旧 record 已结算的边界之后执行:
|
|
2726
|
-
// fan-out 归属证据的保留/刷新/删除都依赖这个判定,绝不让旧代际结果影响新记录。
|
|
2727
|
-
if (typeof observer === "function") {
|
|
2728
|
-
try {
|
|
2729
|
-
observer(handoffState);
|
|
2730
|
-
} catch (error) {
|
|
2731
|
-
logGoalHandoffError("resume", error);
|
|
2732
|
-
}
|
|
2733
|
-
}
|
|
2734
|
-
}).catch((error) => logGoalHandoffError("resume", error));
|
|
2735
|
-
});
|
|
2736
|
-
}
|
|
2737
|
-
|
|
2738
|
-
/**
|
|
2739
|
-
* turn 空闲边界兜底的处理账本:每个 root 只记「当前 turn 已经补过 pause 的
|
|
2740
|
-
* admission token」。
|
|
2741
|
-
*
|
|
2742
|
-
* 为什么按 token 而不是按 turn 整体去重:steer 之后同一个 turn 会再次发布
|
|
2743
|
-
* agent/turn-stopping,但 steer 期间新增的 admission 还没有任何 pause 屏障;
|
|
2744
|
-
* 按 turn 一刀切会让新 admission 逃过兜底。按 token 记账则保证同一 admission
|
|
2745
|
-
* 只补一次,同时不放过新 token。WeakMap 不持有 root,root 销毁后自然回收。
|
|
2746
|
-
*/
|
|
2747
|
-
const automaticHandoffLedger = new WeakMap();
|
|
2748
|
-
function automaticHandoffScope(parent, turn) {
|
|
2749
|
-
const current = automaticHandoffLedger.get(parent);
|
|
2750
|
-
if (current !== void 0 && current.turn === turn) return current;
|
|
2751
|
-
const next = { turn, tokens: new Set() };
|
|
2752
|
-
automaticHandoffLedger.set(parent, next);
|
|
2753
|
-
return next;
|
|
2754
|
-
}
|
|
2755
|
-
|
|
2756
3011
|
/**
|
|
2757
3012
|
* 收集「已接受、但还没有被 finalize 收口」的 role admission。
|
|
2758
3013
|
*
|
|
2759
3014
|
* 判定必须与 finalizeRootAdmissionBatch 的 acceptedEntries 完全一致(同一个
|
|
2760
|
-
* outcome 形状),否则兜底会漏掉或多算:reused/continueParentTurn
|
|
2761
|
-
* 未 settle 的 admission
|
|
2762
|
-
*
|
|
2763
|
-
*
|
|
2764
|
-
*
|
|
2765
|
-
* batch token 仍留在开放 epoch 里,但此时再 pause 只会产生一个没有释放边界的
|
|
2766
|
-
* 孤儿 reason(bare child:id),goal 会永久停在 paused;
|
|
2767
|
-
* 2. admission 已经排队释放(releaseQueued)——feedback 已消费,resume 可能正在飞。
|
|
2768
|
-
* 此时再登记新 reason 会让 resume 完成后触发 re-pause,而后续不会再有释放触发点。
|
|
3015
|
+
* outcome 形状),否则兜底会漏掉或多算:reused/continueParentTurn 不需要工作项,
|
|
3016
|
+
* 未 settle 的 admission 还在执行中、不能提前登记。
|
|
3017
|
+
*
|
|
3018
|
+
* 额外过滤:host.handoff 里已经没有这个 exact admission(典型是 release 成功后的
|
|
3019
|
+
* 清理)时不能登记——登记一个永远不会结算的键会让 root 永久等待。
|
|
2769
3020
|
*/
|
|
2770
3021
|
function pendingRootAutomaticAdmissions(parent) {
|
|
2771
3022
|
const batch = rootAdmissionBatches.get(parent);
|
|
2772
3023
|
// finalize 已经在收口(finalizing)或已收口(closed)时一律让路:那是模型必需
|
|
2773
|
-
//
|
|
3024
|
+
// 路径,等待结论都由它负责,兜底重复介入只会产生竞争。
|
|
2774
3025
|
if (batch === void 0 || batch.closed === true || batch.finalizing === true) return [];
|
|
2775
3026
|
const pending = [];
|
|
2776
3027
|
for (const entry of batch.entries.values()) {
|
|
@@ -2779,83 +3030,61 @@ export default {
|
|
|
2779
3030
|
if (outcome.kind !== "continuable" || outcome.reused === true || outcome.continueParentTurn === true) continue;
|
|
2780
3031
|
const admission = outcome.handoffAdmission;
|
|
2781
3032
|
if (admission === void 0 || host.handoff.contains(admission) !== true) continue;
|
|
2782
|
-
|
|
2783
|
-
if (
|
|
2784
|
-
pending.push({ token
|
|
3033
|
+
const token = typeof entry.token === "string" && entry.token.length > 0 ? entry.token : void 0;
|
|
3034
|
+
if (token === void 0) continue;
|
|
3035
|
+
pending.push({ token, admission });
|
|
2785
3036
|
}
|
|
2786
3037
|
return pending;
|
|
2787
3038
|
}
|
|
2788
3039
|
|
|
2789
3040
|
/**
|
|
2790
|
-
*
|
|
2791
|
-
*
|
|
2792
|
-
*
|
|
2793
|
-
*
|
|
2794
|
-
*
|
|
2795
|
-
*
|
|
2796
|
-
*
|
|
2797
|
-
*
|
|
2798
|
-
*
|
|
2799
|
-
*
|
|
2800
|
-
*
|
|
2801
|
-
*
|
|
2802
|
-
*
|
|
2803
|
-
*
|
|
2804
|
-
*
|
|
2805
|
-
*
|
|
2806
|
-
* shared helper 直接返回,绝不会产生第二次 goals.pause;
|
|
2807
|
-
* 3. 绝不调用 exec.concludeTurn():turn 本来就要关闭,兜底只补 pause;
|
|
2808
|
-
* 4. pause 失败只 warn(fail-open):turn 正常关闭;goal 仍 armed 时由
|
|
2809
|
-
* goal-round-driver 继续驱动,属可接受降级。这与 finalize 的 fail-closed
|
|
2810
|
-
* 语义(返回 rejected 并保持 root 收口)互不影响;pauseRootGoalForChild 内部
|
|
2811
|
-
* 自带的失败清理是既有 helper 语义,兜底不额外扩大它;
|
|
2812
|
-
* 5. goal 服务缺少 get/pause(宿主降级)时直接跳过:没有可暂停的目标,
|
|
2813
|
-
* 也不需要它做 admission 清理;
|
|
2814
|
-
* 6. 卸载中(goalHandoffStopping)一律 no-op。
|
|
3041
|
+
* root turn 即将关闭时的等待兜底(与 finalize 共用**同一个**等待账本/状态机)。
|
|
3042
|
+
*
|
|
3043
|
+
* 为什么需要它:`dsh_expert_group_finalize` 仍是模型必需路径(prompt 契约、工具
|
|
3044
|
+
* 描述都不改),但模型可能遗漏它;纯 `continue_parent_turn` 批次与 fan-out 也可能
|
|
3045
|
+
* 在 turn 结束时仍有子代理在跑。此时若直接关闭 turn,root 会变 idle。
|
|
3046
|
+
*
|
|
3047
|
+
* 本函数**不**暂停/恢复任何 goal,也不主动结束 turn:它只把「本 turn 已接受、
|
|
3048
|
+
* 但还没被 finalize 登记的 admission」补登记进同一张等待表,然后等同一张表的
|
|
3049
|
+
* 静止判定成立。DSH 的 `agent/turn-stopping` 是 serial 事件且会 await 监听器
|
|
3050
|
+
* 返回的 Promise,因此等待期间 turn 保持打开,其他 agent 事件照常推进。
|
|
3051
|
+
*
|
|
3052
|
+
* 兜底只做「补登记 + 等」:不清理 admission、不写任何终态结论——那些都属于
|
|
3053
|
+
* 正常的 feedback/release 路径。
|
|
3054
|
+
*
|
|
3055
|
+
* @param {object} parent - exact live root Agent。
|
|
3056
|
+
* @returns {Promise<void>} 静止或等待被取消后收口。
|
|
2815
3057
|
*/
|
|
2816
|
-
async function
|
|
2817
|
-
const parent
|
|
2818
|
-
|
|
2819
|
-
if (typeof goals?.get !== "function" || typeof goals?.pause !== "function") return;
|
|
2820
|
-
const ledger = automaticHandoffScope(parent, payload?.turn);
|
|
2821
|
-
const candidates = pendingRootAutomaticAdmissions(parent).filter((item) => !ledger.tokens.has(item.token));
|
|
2822
|
-
if (candidates.length === 0) {
|
|
2823
|
-
// 没有未收口的 role admission:只需确认在飞的异步 pause 早于 turn 关闭落地。
|
|
2824
|
-
const handoff = goalHandoffs.get(parent.id);
|
|
2825
|
-
if (handoff?.agent === parent && handoff.state === "pausing" && isThenable(handoff.operation)) {
|
|
2826
|
-
await Promise.resolve(handoff.operation).catch(() => {});
|
|
2827
|
-
}
|
|
2828
|
-
return;
|
|
3058
|
+
async function awaitRootTurnWaitFallback(parent, signal) {
|
|
3059
|
+
for (const candidate of pendingRootAutomaticAdmissions(parent)) {
|
|
3060
|
+
rootTurnWaits.track(parent, { kind: "admission", token: candidate.token });
|
|
2829
3061
|
}
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
// feedback 释放路径完全一致,成功时同时标记 cohort pauseDone,release 才可能发生。
|
|
2837
|
-
const paused = await pauseRootGoalForChild(parent, candidate.childId, candidate.admission);
|
|
2838
|
-
// 首个失败即停止本轮:pause 失败会走 fail-closed 清理并摘除该 root 的**全部**
|
|
2839
|
-
// admission,后续 candidate 都变成 stale 对象(再 pause 只会退化成裸 child:<id>
|
|
2840
|
-
// reason)。已记账的 token 保持记账,同一 turn 不重放;这里是防 stale,不是抛错。
|
|
2841
|
-
if (paused === false) break;
|
|
3062
|
+
// 即使没有补登记的工作项,只要该 root 曾经engage过等待体系(例如纯
|
|
3063
|
+
// continue_parent_turn 留下的正在运行的 child),也必须让同一状态机判定一次。
|
|
3064
|
+
if (!rootTurnWaits.isEngaged(parent)) return;
|
|
3065
|
+
const outcome = await rootTurnWaits.wait(parent, signal);
|
|
3066
|
+
if (outcome.released !== true) {
|
|
3067
|
+
ctx.logger.warn("dsh-expert-group: root turn wait fallback was cancelled (" + outcome.reason + ")");
|
|
2842
3068
|
}
|
|
2843
3069
|
}
|
|
2844
3070
|
|
|
2845
3071
|
/**
|
|
2846
|
-
* DSH 的 agent/turn-stopping 是 serial 事件:监听器可以返回 Promise,
|
|
2847
|
-
*
|
|
2848
|
-
*
|
|
2849
|
-
* 兜底必须 fail-open。
|
|
3072
|
+
* DSH 的 agent/turn-stopping 是 serial 事件:监听器可以返回 Promise,loop 会 await
|
|
3073
|
+
* 后再关闭 turn,因此这里可以安全地保持 turn 打开直到专家真正结束。监听器自身绝不
|
|
3074
|
+
* 抛错——DSH 会把 turn-stopping 的异常变成 turn 错误,兜底必须 fail-open。
|
|
2850
3075
|
*/
|
|
2851
3076
|
ctx.on("agent/turn-stopping", (payload) => {
|
|
2852
3077
|
const parent = payload?.agent;
|
|
2853
|
-
if (
|
|
2854
|
-
|
|
2855
|
-
|
|
3078
|
+
if (turnWaitStopping || !isRootAgentIdentity(parent) || !isLiveRootAgent(parent)) return;
|
|
3079
|
+
// 同步前置判定:既没有进入等待体系、也没有可补登记的 admission 时直接放行——
|
|
3080
|
+
// 绝不为了「形式上返回 Promise」而在每个 turn 边界插入一次多余的异步查询。
|
|
3081
|
+
if (!rootTurnWaits.isEngaged(parent) && pendingRootAutomaticAdmissions(parent).length === 0) return;
|
|
3082
|
+
return awaitRootTurnWaitFallback(parent, payload?.signal).catch((error) => {
|
|
3083
|
+
ctx.logger.warn("dsh-expert-group: root turn wait fallback failed: " + (error instanceof Error ? error.message : String(error)));
|
|
2856
3084
|
});
|
|
2857
3085
|
});
|
|
2858
3086
|
|
|
3087
|
+
|
|
2859
3088
|
/**
|
|
2860
3089
|
* root 专属结构化文件工具 guard 的 owner cleanup。必须挂在每个 root Agent
|
|
2861
3090
|
* 自身的 ctx 上,不能调用全局 ctx.tools.guard,否则会把 child 也挡住;guard
|
|
@@ -2886,7 +3115,7 @@ export default {
|
|
|
2886
3115
|
let ownerCleanup;
|
|
2887
3116
|
ownerCleanup = agent.ctx.effect(() => {
|
|
2888
3117
|
const disposeGuard = agent.ctx.tools.guard((execution) => {
|
|
2889
|
-
const handoffRejection =
|
|
3118
|
+
const handoffRejection = rootUserWaitGuard(agent, execution);
|
|
2890
3119
|
if (handoffRejection !== void 0) return handoffRejection;
|
|
2891
3120
|
return rootStructuredPathGuard(execution, delegationTracker.listActiveTasks(agent.id), agent.id, workspaceRoot);
|
|
2892
3121
|
});
|
|
@@ -3430,11 +3659,9 @@ export default {
|
|
|
3430
3659
|
// 事件历史与任务快照同代持久化;Host 自有查询缓存也必须先水合,避免冷启动 cursor 从 0 重置。
|
|
3431
3660
|
fanoutHost.restoreEvents(storageBinding.fanoutSnapshot()?.events);
|
|
3432
3661
|
host.lineage.restoreParentSessions(storageBinding.fanoutSnapshot());
|
|
3433
|
-
// item 5:先恢复 fan-out pause 归属证据,再 restore/reconcile —— reconcile 的
|
|
3434
|
-
// adopt/release 判定依赖它(证据缺失必须保持 paused)。
|
|
3435
|
-
restoreFanoutGoalHandoffEvidence(storageBinding.fanoutSnapshot());
|
|
3436
3662
|
fanoutHost.restore();
|
|
3437
|
-
//
|
|
3663
|
+
// 冷恢复:restore 之后为「已在运行、但本进程还没有登记」的 fan-out 父任务补登记
|
|
3664
|
+
// 等待工作。终态任务只标记已释放,绝不登记(它们不会再产生 task_settled)。
|
|
3438
3665
|
reconcileFanoutGoalHandoffs();
|
|
3439
3666
|
});
|
|
3440
3667
|
domainInitialization = Promise.race([initialize, cancelled]).catch(async (error) => {
|
|
@@ -3928,6 +4155,25 @@ export default {
|
|
|
3928
4155
|
return true;
|
|
3929
4156
|
}
|
|
3930
4157
|
|
|
4158
|
+
/**
|
|
4159
|
+
* root 代际退休时摘除它持有的 fan-out 等待登记。
|
|
4160
|
+
*
|
|
4161
|
+
* 为什么必须做:登记记录的归属凭据是注册当时捕获的 exact Agent 对象。旧代际退休后
|
|
4162
|
+
* 它的分片会随 agent/disposed 一起收敛,**不会再产生 task_settled**;若记录仍留在表里
|
|
4163
|
+
* 并保持 active,补建路径就可能(在极端的同 id replacement 场景下)被误导。这里统一
|
|
4164
|
+
* 标记 released 并删除:等待本身由 rootTurnWaits.retire 取消,登记表只负责「这个
|
|
4165
|
+
* parentTaskId 的当前代次是谁」,绝不继承旧代际的等待原因。
|
|
4166
|
+
*
|
|
4167
|
+
* @param {object} previous - 正在退休的 exact root Agent。
|
|
4168
|
+
*/
|
|
4169
|
+
function releaseFanoutHandoffRecordsForRetiredRoot(previous) {
|
|
4170
|
+
for (const [parentTaskId, record] of [...fanoutTurnWaitRecords]) {
|
|
4171
|
+
if (record?.agent !== previous) continue;
|
|
4172
|
+
record.state = "released";
|
|
4173
|
+
fanoutTurnWaitRecords.delete(parentTaskId);
|
|
4174
|
+
}
|
|
4175
|
+
}
|
|
4176
|
+
|
|
3931
4177
|
function retireRootGeneration(previous) {
|
|
3932
4178
|
if (!isRootAgentIdentity(previous) || typeof previous.id !== "string") return;
|
|
3933
4179
|
const previousGeneration = rootGenerationRegistry.generationOf(previous.id);
|
|
@@ -3940,7 +4186,12 @@ export default {
|
|
|
3940
4186
|
pendingUserWaits.delete(previous);
|
|
3941
4187
|
const previousToken = host.lineage.tokenOf(previous);
|
|
3942
4188
|
if (previousToken !== void 0) previousToken.active = false;
|
|
3943
|
-
|
|
4189
|
+
// 代际退休:取消该 root 的全部等待(等待者以 released:false 收口)、移除监听与引用。
|
|
4190
|
+
// 旧代际的迟到事件不会再命中任何记录,因此无法释放新 waiter。
|
|
4191
|
+
rootTurnWaits.retire(previous, "root-generation-retired");
|
|
4192
|
+
// 旧代际的分片不会再产生 task_settled:必须同时摘除它持有的 fan-out 登记,
|
|
4193
|
+
// 否则那些「永远等不到结算」的登记会让后续补建路径被误导。
|
|
4194
|
+
releaseFanoutHandoffRecordsForRetiredRoot(previous);
|
|
3944
4195
|
pendingChildTurnEnds.delete(previous);
|
|
3945
4196
|
failedHandoffChildren.delete(previous);
|
|
3946
4197
|
clearPendingHandoffAdmissions(previous);
|
|
@@ -3953,6 +4204,12 @@ export default {
|
|
|
3953
4204
|
dropParentRecoveryRecords(previous);
|
|
3954
4205
|
}
|
|
3955
4206
|
ctx.on("agent/created", ({ agent }) => {
|
|
4207
|
+
// root turn 等待的介入点:任何在某个 live root 之下新建的子代理(角色 child、fan-out
|
|
4208
|
+
// 分片、嵌套后代)都意味着「该 root 的当前 turn 可能还有工作没结束」。这里只登记
|
|
4209
|
+
// 「该 root 已进入等待体系」,是否真的等待仍由 host/turn-wait.js 的静止判定决定;
|
|
4210
|
+
// 因此纯 continue_parent_turn 与模型遗漏 finalize 的路径也能被 agent/turn-stopping
|
|
4211
|
+
// 兜底覆盖,而不需要为它们各写一套账本。
|
|
4212
|
+
engageRootTurnWaitForCreatedAgent(agent);
|
|
3956
4213
|
// fan-out child 必须先于旧 recovery 分支路由;marker 缺失的 cold child
|
|
3957
4214
|
// 只能在精确 child_models 记录具备完整 fan-out identity 时走同一条路径。
|
|
3958
4215
|
const recordedFanoutChild = typeof agent?.id === "string" ? source().childModels?.[agent.id] : void 0;
|
|
@@ -3978,8 +4235,8 @@ export default {
|
|
|
3978
4235
|
host.lineage.tokenFor(agent);
|
|
3979
4236
|
rootGenerationRegistry.activate(agent.id, agent);
|
|
3980
4237
|
notificationHost.activateRoot({ rootId: agent.id, generation: rootGenerationRegistry.generationOf(agent.id) });
|
|
3981
|
-
//
|
|
3982
|
-
//
|
|
4238
|
+
// root 重新出现(上面的 restore() 已把 deferred 任务恢复回来)且 lineage 绑定刚刚
|
|
4239
|
+
// 建立,此刻才能按 root 归属补登记 fan-out 等待工作。
|
|
3983
4240
|
reconcileFanoutGoalHandoffs();
|
|
3984
4241
|
}
|
|
3985
4242
|
if (typeof agent?.id === "string") {
|
|
@@ -4141,8 +4398,7 @@ export default {
|
|
|
4141
4398
|
// 先读取当前 exact Agent 的 generation,再退休完成状态;旧 disposed 事件不触碰新代次。
|
|
4142
4399
|
const disposedGeneration = rootGenerationRegistry.generationOf(agent.id);
|
|
4143
4400
|
const hasRootState = rootDisposed && (
|
|
4144
|
-
|
|
4145
|
-
|| host.handoff.some((entry) => entry.parent === agent)
|
|
4401
|
+
host.handoff.some((entry) => entry.parent === agent)
|
|
4146
4402
|
|| pendingChildTurnEnds.has(agent)
|
|
4147
4403
|
|| failedHandoffChildren.has(agent)
|
|
4148
4404
|
);
|
|
@@ -4157,7 +4413,11 @@ export default {
|
|
|
4157
4413
|
}
|
|
4158
4414
|
rootGenerationRegistry.retire(agent.id, agent);
|
|
4159
4415
|
}
|
|
4160
|
-
|
|
4416
|
+
// 与 retireRootGeneration 同一语义:root dispose 后它的分片不会再产生
|
|
4417
|
+
// task_settled。取消该 root 的全部等待,并摘除它的 fan-out 登记(旧代际的登记
|
|
4418
|
+
// 绝不能被新代际继承)。
|
|
4419
|
+
if (agent !== void 0) rootTurnWaits.retire(agent, "root-disposed");
|
|
4420
|
+
if (rootDisposed) releaseFanoutHandoffRecordsForRetiredRoot(agent);
|
|
4161
4421
|
if (typeof agent?.id === "string") {
|
|
4162
4422
|
const current = childActivationStates.get(agent.id);
|
|
4163
4423
|
// 只释放当前对象;旧 Activation 的迟到 disposed 不得删除新对象。
|
|
@@ -4439,7 +4699,7 @@ export default {
|
|
|
4439
4699
|
*
|
|
4440
4700
|
* 宿主会以同一 message.id 重复投递同一条 child settlement;副本不能被当作新结论
|
|
4441
4701
|
* 去消费 cohort 里的 token,否则会把本轮 token 的 feedbackSeen 提前置 true,
|
|
4442
|
-
* 导致
|
|
4702
|
+
* 导致 root 在结果真正回来之前提前放行。
|
|
4443
4703
|
*
|
|
4444
4704
|
* 生命周期与 record 一致,**不做插入序淘汰**(淘汰会让旧副本重新变成新
|
|
4445
4705
|
* settlement);达到 FEEDBACK_DELIVERY_LIMIT 时进入 fail-closed 饱和,
|
|
@@ -4635,7 +4895,7 @@ export default {
|
|
|
4635
4895
|
// 请求级 retry 已耗尽时,turn/end 只是同一次模型失败的终态;不能再把
|
|
4636
4896
|
// child continuation 当成另一轮失败计数,否则一次故障会消耗两套预算。
|
|
4637
4897
|
const requestRetryExhausted = requestRetryStateIsExhausted(record.agent, session, turn);
|
|
4638
|
-
//
|
|
4898
|
+
// 等待被取消时仍需清理任务/范围,但不得给原 child 再投递自动恢复。
|
|
4639
4899
|
const willRecover = allowRecovery === true
|
|
4640
4900
|
&& requestRetryExhausted !== true
|
|
4641
4901
|
&& outcome === "recoverable"
|
|
@@ -4729,8 +4989,13 @@ export default {
|
|
|
4729
4989
|
function forgetTaskIfCurrentChild(record, taskKey) {
|
|
4730
4990
|
if (record === null || typeof record !== "object") return false;
|
|
4731
4991
|
const scope = delegationScopeKey(record.parentId, record.role);
|
|
4732
|
-
|
|
4733
|
-
|
|
4992
|
+
// 多 child 语义:归属判定优先看「这个任务 key 绑定的 child」,而不是「本 scope
|
|
4993
|
+
// 最近一个 child」——同 route 下并存的独立 child 各自持有自己的任务指纹,较早
|
|
4994
|
+
// child 的确定失败同样必须能 forget 它自己的任务(否则相同 prompt 会被永久
|
|
4995
|
+
// 判为 reused 并等一个永远不会结算的 turn)。
|
|
4996
|
+
const bound = delegationTracker.getTaskChild(scope, taskKey);
|
|
4997
|
+
const owner = bound !== void 0 ? bound.childId : delegationTracker.getChild(scope)?.childId;
|
|
4998
|
+
if (!shouldForgetTask(owner, record.childId)) return false;
|
|
4734
4999
|
return delegationTracker.forgetTask(scope, taskKey);
|
|
4735
5000
|
}
|
|
4736
5001
|
|
|
@@ -5013,7 +5278,12 @@ export default {
|
|
|
5013
5278
|
let messageId;
|
|
5014
5279
|
const scope = delegationScopeKey(record.parentId, record.role);
|
|
5015
5280
|
const current = delegationTracker.getChild(scope);
|
|
5016
|
-
|
|
5281
|
+
// 多 child 语义:scope.current 只是「本 scope 最近一次新建/恢复的 child」,它可能
|
|
5282
|
+
// 是另一个独立任务的 child。同一个 route 下另一个 child 的自动恢复**不是**route
|
|
5283
|
+
// 变更,必须继续向 record 自己的 child 投递恢复消息;只有 route 真的变了(或记录
|
|
5284
|
+
// 没有 route 信息、只能退回 child 身份比较的旧记录)才走重建。
|
|
5285
|
+
const routeChanged = current !== void 0
|
|
5286
|
+
&& (record.routeKey !== void 0 ? current.routeKey !== record.routeKey : current.childId !== record.childId);
|
|
5017
5287
|
try {
|
|
5018
5288
|
if (shouldRebuildRecoveryChild(void 0, { routeChanged })) {
|
|
5019
5289
|
// route 改变时不再向旧 child sendMessage,直接以保存的原 route 重建。
|
|
@@ -5114,10 +5384,10 @@ export default {
|
|
|
5114
5384
|
if (relayFeedbackWarnings.has(key)) return;
|
|
5115
5385
|
relayFeedbackWarnings.add(key);
|
|
5116
5386
|
ctx.logger.warn("dsh-expert-group: legacy subagent-report feedback has no settlement correlation id"
|
|
5117
|
-
+ " (child " + key + "); keeping
|
|
5387
|
+
+ " (child " + key + "); keeping the admission fail-closed and treating it as an ordinary message");
|
|
5118
5388
|
}
|
|
5119
5389
|
|
|
5120
|
-
// 触发通道 1:父 Agent 的 inbox
|
|
5390
|
+
// 触发通道 1:父 Agent 的 inbox 注入是精确完成通知的到达边界。
|
|
5121
5391
|
// DSH 先处理 child turn/end,随后把 subagent-settled feedback 注入父 inbox;
|
|
5122
5392
|
// 只有 exact root Agent 收到匹配 senderSessionId 的**标准 notice** 才释放对应 child 原因。
|
|
5123
5393
|
//
|
|
@@ -5165,16 +5435,11 @@ export default {
|
|
|
5165
5435
|
const gatedChildId = subagentFeedbackChildId(message);
|
|
5166
5436
|
if (gatedChildId === void 0 || wasGatedRecoveryFeedback(agent, gatedChildId, message?.id, message)) return;
|
|
5167
5437
|
const childId = gatedChildId;
|
|
5168
|
-
|
|
5169
|
-
|
|
5170
|
-
|
|
5171
|
-
|
|
5172
|
-
|
|
5173
|
-
}
|
|
5174
|
-
const handoff = goalHandoffs.get(agent.id);
|
|
5175
|
-
if (handoff?.agent === agent && hasChildGoalHandoff(agent, childId)) {
|
|
5176
|
-
releaseRootGoalHandoff(agent, { kind: "child", id: childId });
|
|
5177
|
-
}
|
|
5438
|
+
markPendingHandoffFeedback(agent, childId, message);
|
|
5439
|
+
// 无论本次 feedback 是否命中 admission,都重新检查一次精确结算:命中时这是
|
|
5440
|
+
// release 边界;未命中(重复副本 / 无身份 / 迟到通知)时它是幂等空操作,
|
|
5441
|
+
// 绝不会结算别的 token。
|
|
5442
|
+
settleFinishedChildTurnWaits(agent);
|
|
5178
5443
|
} catch (error) {
|
|
5179
5444
|
ctx.logger.warn("dsh-expert-group: inbox/inserted handoff handler failed: " + (error instanceof Error ? error.message : String(error)));
|
|
5180
5445
|
}
|
|
@@ -5226,7 +5491,6 @@ export default {
|
|
|
5226
5491
|
generation: rootGenerationRegistry.generationOf(liveAgent.id),
|
|
5227
5492
|
});
|
|
5228
5493
|
clearRootUserWait(liveAgent, session);
|
|
5229
|
-
releaseRootGoalHandoff(liveAgent, { kind: "user" });
|
|
5230
5494
|
return;
|
|
5231
5495
|
}
|
|
5232
5496
|
if (event?.type === "user/message") {
|
|
@@ -5239,7 +5503,9 @@ export default {
|
|
|
5239
5503
|
// 延迟 microtask 中必须确认事件仍属于当前 root Session;同 id 新 root
|
|
5240
5504
|
// 不能被旧代际 user/message 误当作本次等待的用户回答。
|
|
5241
5505
|
clearRootUserWait(liveAgent, session);
|
|
5242
|
-
|
|
5506
|
+
// 真实用户输入开启新的 root run:为「已在运行、但本进程还没有登记等待」的
|
|
5507
|
+
// fan-out 任务补登记。判定完全基于当前事实,重复触发是幂等的。
|
|
5508
|
+
reconcileUnbarrieredFanoutHandoffs();
|
|
5243
5509
|
// 真实用户输入开启新的 root run:只有这里会重置"本 run 至多一次"的终止
|
|
5244
5510
|
// 通知资格。subagent-settled/agent-message 等注入消息不进入该分支,
|
|
5245
5511
|
// 因此子代理结算回唤出的续接 turn 仍然属于同一 run,不会重复提示。
|
|
@@ -5269,8 +5535,8 @@ export default {
|
|
|
5269
5535
|
if (admission !== void 0) deferChildTurnEnd(record, session, event, admission);
|
|
5270
5536
|
return;
|
|
5271
5537
|
}
|
|
5272
|
-
if (
|
|
5273
|
-
// DSH 的 report/feedback 发布仍按原顺序交给
|
|
5538
|
+
if (admission !== void 0) {
|
|
5539
|
+
// DSH 的 report/feedback 发布仍按原顺序交给 admission bookkeeping;
|
|
5274
5540
|
// 但成功/确定失败的 exact activity 在此窗口先释放,避免 root guard
|
|
5275
5541
|
// 因父 inbox 尚未消费而错误拦截同范围读取。
|
|
5276
5542
|
releaseTerminalActivitiesBeforeHandoffFeedback(record, session, event, admission);
|
|
@@ -5335,8 +5601,11 @@ export default {
|
|
|
5335
5601
|
// 插件卸载:清理恢复状态与全部活动范围,防止状态泄漏;
|
|
5336
5602
|
// dropRecoveryRecord 内部会清理所有 pending op(B7)。
|
|
5337
5603
|
ctx.effect(() => () => {
|
|
5338
|
-
|
|
5339
|
-
|
|
5604
|
+
turnWaitStopping = true;
|
|
5605
|
+
// 卸载:取消全部 root 的等待(等待者以 released:false 收口)、移除监听与引用。
|
|
5606
|
+
rootTurnWaits.dispose();
|
|
5607
|
+
rootWaitInvalidators.clear();
|
|
5608
|
+
fanoutTurnWaitRecords.clear();
|
|
5340
5609
|
pendingChildTurnEnds.clear();
|
|
5341
5610
|
// pendingHandoffAdmissions 只是 host 索引;cohort 另外持有 root/entry 引用,
|
|
5342
5611
|
// 卸载时必须先遍历所有 known root 并清空共享 entries,再丢弃数组索引。
|
|
@@ -5551,363 +5820,128 @@ export default {
|
|
|
5551
5820
|
}
|
|
5552
5821
|
|
|
5553
5822
|
/**
|
|
5554
|
-
* fan-out
|
|
5555
|
-
*
|
|
5556
|
-
*
|
|
5557
|
-
*
|
|
5558
|
-
*
|
|
5559
|
-
*
|
|
5560
|
-
*
|
|
5561
|
-
*
|
|
5562
|
-
*
|
|
5563
|
-
*
|
|
5564
|
-
*
|
|
5565
|
-
* 只命中旧键,绝不会释放新代次。
|
|
5566
|
-
*
|
|
5567
|
-
* item 4(代次不可复用):attempt 取自**插件进程级全局单调序号**,不再从「可能被
|
|
5568
|
-
* 淘汰的 per-task 记录」推导。原因:本表有资源上界(FANOUT_HANDOFF_LIMIT,只淘汰
|
|
5569
|
-
* 已释放记录),若父任务 A 的 attempt 1 已 settle、但它的异步 resume 仍在飞时 A 的
|
|
5570
|
-
* record 被大量新登记挤出,而 retry A 时把代次重新从 1 开始,旧迟到 release 就会与
|
|
5571
|
-
* 新登记复用 `fanout:A:1` → 提前恢复 retry 期间的 goal。全局序号保证**同一进程内**
|
|
5572
|
-
* 任何 key 都不可复用,因此不需要额外的不可重用 tombstone,也不依赖任何会被 prune
|
|
5573
|
-
* 的内存 record。
|
|
5574
|
-
*
|
|
5575
|
-
* 跨进程/跨插件重载后序号从 1 重新开始是安全的:重载会同时丢弃 goalHandoffs 内存
|
|
5576
|
-
* 记录与所有在飞的 pause/resume operation,进程内不存在「同 key 的旧异步操作」可以
|
|
5577
|
-
* 复用来误释放新代次;durable pause 的归属由 fanoutPauseEvidence 证据链负责。
|
|
5823
|
+
* fan-out 等待登记表:parentTaskId -> { attempt, agent, state }。
|
|
5824
|
+
*
|
|
5825
|
+
* 为什么需要**登记代次**:manager 的 retryShard / continuation 会把已终态任务带回
|
|
5826
|
+
* pending,而首次 settle 已经结算过旧代次的工作项。若 retry 复用同一个键,等待登记表
|
|
5827
|
+
* 会把「retry 期间的新工作」误认为「旧工作仍未结算」,从而在分片跑完前就放行。
|
|
5828
|
+
* 因此每次登记取**独立代次**,键编码为 fanout:<id>:<attempt>;旧代次的迟到结算只命中
|
|
5829
|
+
* 旧键,绝不会结算新代次。
|
|
5830
|
+
*
|
|
5831
|
+
* state 三态:pending(刚登记,尚未确认任务仍在跑)→ active(任务确实非终态,工作项已登记)
|
|
5832
|
+
* → released(已结算,不可复活)。用三态而不是 boolean:异步窗口里的迟到回调不能把已经
|
|
5833
|
+
* 释放的记录重新置回 active。
|
|
5578
5834
|
*/
|
|
5579
|
-
const
|
|
5580
|
-
let
|
|
5835
|
+
const fanoutTurnWaitRecords = new Map();
|
|
5836
|
+
let fanoutTurnWaitSequence = 0;
|
|
5581
5837
|
// 24 是纯资源上界(只淘汰已释放记录);代次分配不依赖本表,因此小上限不影响正确性。
|
|
5582
5838
|
const FANOUT_HANDOFF_LIMIT = 24;
|
|
5583
5839
|
|
|
5584
|
-
/**
|
|
5840
|
+
/** 分配一个**不可复用**的全局登记代次。 */
|
|
5585
5841
|
function nextFanoutHandoffSequence() {
|
|
5586
|
-
|
|
5587
|
-
return
|
|
5842
|
+
fanoutTurnWaitSequence += 1;
|
|
5843
|
+
return fanoutTurnWaitSequence;
|
|
5588
5844
|
}
|
|
5589
5845
|
|
|
5590
5846
|
/** 释放后按资源边界清理:只淘汰「已释放且 manager 已无该任务」的旧记录。 */
|
|
5591
5847
|
function pruneFanoutHandoffRecords() {
|
|
5592
|
-
if (
|
|
5593
|
-
for (const [parentTaskId, record] of [...
|
|
5594
|
-
if (
|
|
5848
|
+
if (fanoutTurnWaitRecords.size <= FANOUT_HANDOFF_LIMIT) return;
|
|
5849
|
+
for (const [parentTaskId, record] of [...fanoutTurnWaitRecords]) {
|
|
5850
|
+
if (fanoutTurnWaitRecords.size <= FANOUT_HANDOFF_LIMIT) return;
|
|
5595
5851
|
if (record?.state !== "released") continue;
|
|
5596
5852
|
if (fanoutHost?.getTask(parentTaskId) !== null) continue;
|
|
5597
|
-
|
|
5853
|
+
fanoutTurnWaitRecords.delete(parentTaskId);
|
|
5598
5854
|
}
|
|
5599
5855
|
// 极端情况(全部任务都还在 manager 表里且都是已释放记录)下仍按插入序淘汰最旧的
|
|
5600
|
-
//
|
|
5601
|
-
//
|
|
5602
|
-
for (const [parentTaskId, record] of [...
|
|
5603
|
-
if (
|
|
5856
|
+
// 已释放项。淘汰是安全的:代次来自全局序号(不复用),被淘汰记录的迟到 settle 只会
|
|
5857
|
+
// 走安全 no-op。
|
|
5858
|
+
for (const [parentTaskId, record] of [...fanoutTurnWaitRecords]) {
|
|
5859
|
+
if (fanoutTurnWaitRecords.size <= FANOUT_HANDOFF_LIMIT) return;
|
|
5604
5860
|
if (record?.state !== "released") continue;
|
|
5605
|
-
|
|
5606
|
-
}
|
|
5607
|
-
}
|
|
5608
|
-
|
|
5609
|
-
// ── item 5:fanout pause 归属证据(持久化到 fanout snapshot) ──────────────
|
|
5610
|
-
|
|
5611
|
-
/**
|
|
5612
|
-
* 插件自有的 fanout pause 归属证据:rootId -> { goalId, revision, tasks }。
|
|
5613
|
-
*
|
|
5614
|
-
* 为什么必须有证据:C7 冷恢复后 goalHandoffs 是空 Map,只有 fanout manager 从快照
|
|
5615
|
-
* 恢复。仅凭「某 root 的 goal 现在是 paused+disarmed」**不足以**证明这个 pause 是
|
|
5616
|
-
* 本插件为该 fanout 任务建立的——用户 ask_user_question、其他插件或人工 /goal pause
|
|
5617
|
-
* 都会产生同样的视图。旧实现直接 adopt 任意 paused 视图,会把这些外部暂停错误地
|
|
5618
|
-
* resume。
|
|
5619
|
-
*
|
|
5620
|
-
* 证据内容与证明力:
|
|
5621
|
-
* - goalId:我们暂停的那个 goal 的 durable id;
|
|
5622
|
-
* - revision:**我们自己执行 pause 得到的那份 paused 视图 revision**。DSH 的
|
|
5623
|
-
* GoalView revision 是 CAS 单调的,因此只有当前视图 revision 与该值**完全相等**
|
|
5624
|
-
* 时才说明「自我们暂停之后没有任何人改动过这个 goal」;一旦被 edit/resume/pause
|
|
5625
|
-
* 过(revision 前进),归属就无法证明,必须 fail-closed 保持 paused;
|
|
5626
|
-
* - tasks:本插件为该 root 的哪些父任务暂停过 goal(含每次登记时的 reason 键与代次),
|
|
5627
|
-
* 用于确认「这个父任务确实由本插件登记过」,也便于诊断。
|
|
5628
|
-
*
|
|
5629
|
-
* 证据只在两个时刻变化(登记成功 / 释放完成),因此显式 flush 的频率与 fanout 任务
|
|
5630
|
-
* 数量同阶,不构成写放大。持久化位置是既有 fanout snapshot 负载(键 goalHandoffs),
|
|
5631
|
-
* 不动 storage domain 表结构。
|
|
5632
|
-
*/
|
|
5633
|
-
const fanoutPauseEvidence = new Map();
|
|
5634
|
-
const FANOUT_PAUSE_EVIDENCE_VERSION = 1;
|
|
5635
|
-
|
|
5636
|
-
/** 校验 handoff record 的 paused ref;返回稳定副本或 undefined。 */
|
|
5637
|
-
function handoffPausedRef(record) {
|
|
5638
|
-
try {
|
|
5639
|
-
const ref = record?.ref;
|
|
5640
|
-
if (ref === null || typeof ref !== "object") return void 0;
|
|
5641
|
-
if (typeof ref.id !== "string" || ref.id.length === 0) return void 0;
|
|
5642
|
-
if (!Number.isSafeInteger(ref.revision) || ref.revision <= 0) return void 0;
|
|
5643
|
-
return { id: ref.id, revision: ref.revision };
|
|
5644
|
-
} catch {
|
|
5645
|
-
return void 0;
|
|
5861
|
+
fanoutTurnWaitRecords.delete(parentTaskId);
|
|
5646
5862
|
}
|
|
5647
5863
|
}
|
|
5648
5864
|
|
|
5649
5865
|
/**
|
|
5650
|
-
*
|
|
5651
|
-
*
|
|
5652
|
-
* ref 直接取自 live handoff record:re-pause(resume 在飞期间登记新代次后由
|
|
5653
|
-
* shared.accept() 重新暂停)会推进 revision,因此每次调用都重新读取,保证证据与
|
|
5654
|
-
* 真实 pause 对齐,而不是留下过期 revision 让冷恢复 fail-closed。
|
|
5655
|
-
*
|
|
5656
|
-
* @returns {boolean} 是否成功记录(record 不存在/不是 paused/ref 非法时为 false)。
|
|
5657
|
-
*/
|
|
5658
|
-
function rememberFanoutPauseEvidence(agent, parentTaskId, attempt) {
|
|
5659
|
-
const handoff = goalHandoffs.get(agent?.id);
|
|
5660
|
-
if (handoff?.agent !== agent || handoff.state !== "paused") return false;
|
|
5661
|
-
const ref = handoffPausedRef(handoff);
|
|
5662
|
-
if (ref === void 0) return false;
|
|
5663
|
-
const entry = fanoutPauseEvidence.get(agent.id) ?? { goalId: ref.id, revision: ref.revision, tasks: new Map() };
|
|
5664
|
-
entry.goalId = ref.id;
|
|
5665
|
-
entry.revision = ref.revision;
|
|
5666
|
-
entry.tasks.set(parentTaskId, {
|
|
5667
|
-
attempt: Number.isSafeInteger(attempt) && attempt > 0 ? attempt : void 0,
|
|
5668
|
-
reason: fanoutHandoffReasonKey(parentTaskId, attempt),
|
|
5669
|
-
});
|
|
5670
|
-
fanoutPauseEvidence.set(agent.id, entry);
|
|
5671
|
-
return true;
|
|
5672
|
-
}
|
|
5673
|
-
|
|
5674
|
-
/** 释放一个父任务对证据的占用;该 root 再无占用时整条证据移除。 */
|
|
5675
|
-
function forgetFanoutPauseEvidence(rootId, parentTaskId) {
|
|
5676
|
-
const entry = fanoutPauseEvidence.get(rootId);
|
|
5677
|
-
if (entry === void 0) return false;
|
|
5678
|
-
const removed = entry.tasks.delete(parentTaskId);
|
|
5679
|
-
if (entry.tasks.size === 0) fanoutPauseEvidence.delete(rootId);
|
|
5680
|
-
return removed;
|
|
5681
|
-
}
|
|
5682
|
-
|
|
5683
|
-
/**
|
|
5684
|
-
* 归属证据匹配(item 5 的唯一放行条件)。
|
|
5866
|
+
* 该 parentTaskId 的当前登记是否仍由 **exact live root** 持有。
|
|
5685
5867
|
*
|
|
5686
|
-
* 三个条件缺一不可:
|
|
5687
|
-
*
|
|
5688
|
-
*
|
|
5689
|
-
* 3. goalId 相同且当前 paused 视图 revision **等于**我们暂停时的 revision。
|
|
5690
|
-
* 任何一条不满足都不能 adopt/release —— 证据缺失时保持 paused(fail-closed)。
|
|
5868
|
+
* 三个条件缺一不可:record.agent 是注册当时捕获的 exact Agent 对象(对象身份无法被
|
|
5869
|
+
* 同 id 伪造);它仍是当前 live root;fanoutHost.ownsTask 能证明「活动绑定 + 绑定代际
|
|
5870
|
+
* token 仍 live」。记录的三态不参与身份判定。
|
|
5691
5871
|
*/
|
|
5692
|
-
function
|
|
5693
|
-
|
|
5694
|
-
if (
|
|
5695
|
-
|
|
5696
|
-
if (
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
5700
|
-
/** 证据的持久化投影(JSON 安全、只含必要字段;损坏数据在读取侧 fail-closed 忽略)。 */
|
|
5701
|
-
function fanoutPauseEvidenceSnapshot() {
|
|
5702
|
-
const roots = {};
|
|
5703
|
-
for (const [rootId, entry] of fanoutPauseEvidence) {
|
|
5704
|
-
const tasks = [];
|
|
5705
|
-
for (const [parentTaskId, meta] of entry.tasks) {
|
|
5706
|
-
tasks.push({
|
|
5707
|
-
parentTaskId,
|
|
5708
|
-
attempt: Number.isSafeInteger(meta?.attempt) ? meta.attempt : null,
|
|
5709
|
-
reason: typeof meta?.reason === "string" ? meta.reason : null,
|
|
5710
|
-
});
|
|
5711
|
-
}
|
|
5712
|
-
roots[rootId] = { goalId: entry.goalId, revision: entry.revision, tasks };
|
|
5713
|
-
}
|
|
5714
|
-
return { version: FANOUT_PAUSE_EVIDENCE_VERSION, roots };
|
|
5715
|
-
}
|
|
5716
|
-
|
|
5717
|
-
/** 写入 fanout snapshot 负载前附加证据(每次写都带上,避免 manager 合并路径丢字段)。 */
|
|
5718
|
-
function withFanoutPauseEvidence(snapshot) {
|
|
5719
|
-
if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot)) return snapshot;
|
|
5720
|
-
return { ...snapshot, goalHandoffs: fanoutPauseEvidenceSnapshot() };
|
|
5721
|
-
}
|
|
5722
|
-
|
|
5723
|
-
/** 显式落盘一次快照(证据变化后调用);失败只 warn,不影响调度与 goal 语义。 */
|
|
5724
|
-
function flushFanoutGoalHandoffEvidence() {
|
|
5725
|
-
if (goalHandoffStopping || typeof fanoutHost?.flushSnapshot !== "function") return;
|
|
5726
|
-
void Promise.resolve(fanoutHost.flushSnapshot()).catch((error) => {
|
|
5727
|
-
logGoalHandoffError("snapshot", error);
|
|
5728
|
-
});
|
|
5729
|
-
}
|
|
5730
|
-
|
|
5731
|
-
/**
|
|
5732
|
-
* 从持久化 snapshot 恢复证据(冷恢复)。
|
|
5733
|
-
*
|
|
5734
|
-
* 严格校验:version 必须匹配,goalId/revision/parentTaskId 必须是合法字符串/正整数;
|
|
5735
|
-
* 任何非法项一律忽略(等价于「没有证据」→ 不 adopt、不 release,保持 paused)。
|
|
5736
|
-
* @returns {number} 恢复的 root 证据条数。
|
|
5737
|
-
*/
|
|
5738
|
-
function restoreFanoutGoalHandoffEvidence(stored) {
|
|
5739
|
-
fanoutPauseEvidence.clear();
|
|
5740
|
-
const payload = stored?.goalHandoffs;
|
|
5741
|
-
if (payload === null || typeof payload !== "object" || Array.isArray(payload)) return 0;
|
|
5742
|
-
if (payload.version !== FANOUT_PAUSE_EVIDENCE_VERSION) return 0;
|
|
5743
|
-
const roots = payload.roots;
|
|
5744
|
-
if (roots === null || typeof roots !== "object" || Array.isArray(roots)) return 0;
|
|
5745
|
-
let restored = 0;
|
|
5746
|
-
for (const [rootId, raw] of Object.entries(roots)) {
|
|
5747
|
-
if (typeof rootId !== "string" || rootId.length === 0) continue;
|
|
5748
|
-
const goalId = raw?.goalId;
|
|
5749
|
-
const revision = raw?.revision;
|
|
5750
|
-
if (typeof goalId !== "string" || goalId.length === 0) continue;
|
|
5751
|
-
if (!Number.isSafeInteger(revision) || revision <= 0) continue;
|
|
5752
|
-
const tasks = new Map();
|
|
5753
|
-
for (const task of Array.isArray(raw?.tasks) ? raw.tasks : []) {
|
|
5754
|
-
const parentTaskId = task?.parentTaskId;
|
|
5755
|
-
if (typeof parentTaskId !== "string" || parentTaskId.length === 0) continue;
|
|
5756
|
-
const attempt = Number.isSafeInteger(task?.attempt) && task.attempt > 0 ? task.attempt : void 0;
|
|
5757
|
-
const reason = typeof task?.reason === "string" && task.reason.length > 0
|
|
5758
|
-
? task.reason
|
|
5759
|
-
: (attempt === void 0 ? void 0 : fanoutHandoffReasonKey(parentTaskId, attempt));
|
|
5760
|
-
tasks.set(parentTaskId, { attempt, reason });
|
|
5761
|
-
}
|
|
5762
|
-
if (tasks.size === 0) continue;
|
|
5763
|
-
fanoutPauseEvidence.set(rootId, { goalId, revision, tasks });
|
|
5764
|
-
restored += 1;
|
|
5765
|
-
}
|
|
5766
|
-
return restored;
|
|
5872
|
+
function fanoutHandoffRecordIsOwnedByLiveRoot(agent, parentTaskId) {
|
|
5873
|
+
if (turnWaitStopping || !isLiveRootAgent(agent)) return void 0;
|
|
5874
|
+
if (typeof parentTaskId !== "string" || parentTaskId.length === 0) return void 0;
|
|
5875
|
+
const record = fanoutTurnWaitRecords.get(parentTaskId);
|
|
5876
|
+
if (record === void 0 || record.agent !== agent) return void 0;
|
|
5877
|
+
if (typeof fanoutHost?.ownsTask !== "function" || fanoutHost.ownsTask(agent, parentTaskId) !== true) return void 0;
|
|
5878
|
+
return record;
|
|
5767
5879
|
}
|
|
5768
5880
|
|
|
5769
5881
|
/**
|
|
5770
|
-
* fan-out
|
|
5771
|
-
*
|
|
5772
|
-
* fanout 的语义是「root 结束 turn,任务在后台按自己的调度推进,整体 settle 后回唤
|
|
5773
|
-
* root」,因此它和 role admission 一样必须先暂停 armed durable goal:否则 root 变
|
|
5774
|
-
* idle 时 goal-round-driver 会立刻注入新的 <goal_round>,与「等待 fan-out 结果」冲突。
|
|
5775
|
-
* 原因键是 "fanout:<parentTaskId>:<attempt>",与同一 root 的 child/user 原因共享一次
|
|
5776
|
-
* pause,全部释放后才 resume(见 releaseGoalHandoff)。
|
|
5777
|
-
*
|
|
5778
|
-
* 边界:
|
|
5779
|
-
* 1. 只有真实 accepted 且拿到 parentTaskId 才登记;RUNTIME_CLOSED 等拒绝结果不登记;
|
|
5780
|
-
* 2. requestId 命中(duplicate: true)时第一次 submit 已经登记了同一代次,这里直接
|
|
5781
|
-
* 跳过,绝不重复发起 pause(duplicate submit 不得重复登记);
|
|
5782
|
-
* 3. 该任务已有**活动**登记(active === true)时不重复登记(幂等),例如并发
|
|
5783
|
-
* duplicate 检测失败或 restore reconcile 与 submit 竞争;
|
|
5784
|
-
* 4. 未终态任务才登记;已终态快照直接跳过——未来不会再有 task_settled,登记会永远
|
|
5785
|
-
* 无法释放;
|
|
5786
|
-
* 5. 卸载中(goalHandoffStopping)no-op,销毁路径不得重新武装 goal;
|
|
5787
|
-
* 6. pause 失败/无目标时只 warn 并把登记标记为**非活动**(不留 active 孤儿,后续
|
|
5788
|
-
* retry/reconcile 可重新登记);
|
|
5789
|
-
* 7. 只有真正建立了 reason(pause 返回 true)才记录归属证据并落盘。
|
|
5882
|
+
* 为一个 fan-out 父任务登记等待工作。
|
|
5790
5883
|
*
|
|
5791
5884
|
* @param {object} parent - exact live root Agent。
|
|
5792
5885
|
* @param {{parentTaskId?:string,task?:object,accepted?:boolean,duplicate?:boolean}} result - submit/retry 结果。
|
|
5793
|
-
* @
|
|
5794
|
-
* @returns {boolean} 是否登记成功(同步可得时)。
|
|
5886
|
+
* @returns {boolean} 是否登记成功。
|
|
5795
5887
|
*/
|
|
5796
|
-
function registerFanoutGoalHandoff(parent, result
|
|
5797
|
-
if (
|
|
5888
|
+
function registerFanoutGoalHandoff(parent, result) {
|
|
5889
|
+
if (turnWaitStopping || !isLiveRootAgent(parent)) return false;
|
|
5798
5890
|
if (result?.accepted === false || result?.duplicate === true) return false;
|
|
5799
5891
|
const parentTaskId = result?.parentTaskId;
|
|
5800
5892
|
if (typeof parentTaskId !== "string" || parentTaskId.length === 0) return false;
|
|
5801
|
-
// 已终态快照:未来不会再有 task_settled
|
|
5893
|
+
// 已终态快照:未来不会再有 task_settled,登记等待工作会永远无法结算。
|
|
5802
5894
|
if (fanoutTaskIsTerminal(result?.task)) return false;
|
|
5803
|
-
const existing =
|
|
5895
|
+
const existing = fanoutTurnWaitRecords.get(parentTaskId);
|
|
5804
5896
|
// 未释放的既有登记(pending/active)幂等短路:duplicate submit 或 restore 竞争都不得重复登记。
|
|
5805
5897
|
if (existing !== void 0 && existing.state !== "released") return true;
|
|
5806
|
-
const attempt =
|
|
5807
|
-
|
|
5808
|
-
: nextFanoutHandoffSequence();
|
|
5809
|
-
// state 三态:pending(pause 在飞/结果未知)→ active(reason 已登记)→ released(已释放,
|
|
5810
|
-
// 不可复活)。用三态而不是 boolean 的原因:异步 pause 的 resolve 可能晚于 release,
|
|
5811
|
-
// boolean 会被迟到的 settle 重新置回 true(复活已释放记录),使 retry 被幂等短路跳过。
|
|
5812
|
-
const record = { attempt, ownerId: parent.id, agent: parent, state: "pending" };
|
|
5813
|
-
fanoutHandoffRecords.set(parentTaskId, record);
|
|
5898
|
+
const attempt = nextFanoutHandoffSequence();
|
|
5899
|
+
fanoutTurnWaitRecords.set(parentTaskId, { attempt, agent: parent, state: "active" });
|
|
5814
5900
|
pruneFanoutHandoffRecords();
|
|
5815
|
-
|
|
5816
|
-
const reasonKey = fanoutHandoffReasonKey(parentTaskId, attempt);
|
|
5817
|
-
const settle = () => {
|
|
5818
|
-
// 判定标准不是 pause 的返回值,而是「reason 是否真的登记进了 live record」:
|
|
5819
|
-
// resuming/pausing 期间 pauseGoalForHandoff 会把新 reason 挂到同一 record 并返回
|
|
5820
|
-
// 在飞 operation,其 resolve 值可能是 false(accept() 的 re-pause 分支返回 false),
|
|
5821
|
-
// 但那并不表示登记失败——reason 仍在,re-pause 完成后 goal 仍被暂停。
|
|
5822
|
-
const handoff = goalHandoffs.get(parent.id);
|
|
5823
|
-
const registered = handoff?.agent === parent && handoff.reasons instanceof Map
|
|
5824
|
-
&& reasonKey !== void 0 && handoff.reasons.has(reasonKey);
|
|
5825
|
-
if (!registered) {
|
|
5826
|
-
// 没有建立任何 reason(无 goal 服务 / 目标不存在 / pause 失败):
|
|
5827
|
-
// 标记 released,不留 active 孤儿,后续 retry 或 reconcile 可以重新登记。
|
|
5828
|
-
if (record.state !== "released") record.state = "released";
|
|
5829
|
-
return false;
|
|
5830
|
-
}
|
|
5831
|
-
// 已被 release 抢先收口(任务在 pause resolve 之前就 settle 了):不得复活记录。
|
|
5832
|
-
if (record.state === "released") return false;
|
|
5833
|
-
record.state = "active";
|
|
5834
|
-
// 只有真正暂停过(state === "paused")才记录归属证据:这是冷恢复能够区分
|
|
5835
|
-
// 「本插件的 pause」与「外部 paused/disarmed」的唯一依据。
|
|
5836
|
-
if (rememberFanoutPauseEvidence(parent, parentTaskId, attempt)) flushFanoutGoalHandoffEvidence();
|
|
5837
|
-
return true;
|
|
5838
|
-
};
|
|
5839
|
-
let paused;
|
|
5840
|
-
try {
|
|
5841
|
-
paused = pauseGoalForHandoff(goals, parent, goalHandoffs, reason, (error) => {
|
|
5842
|
-
logGoalHandoffError("pause", error);
|
|
5843
|
-
});
|
|
5844
|
-
} catch (error) {
|
|
5845
|
-
logGoalHandoffError("pause", error);
|
|
5846
|
-
return settle();
|
|
5847
|
-
}
|
|
5848
|
-
if (isThenable(paused)) {
|
|
5849
|
-
// remote adapter 的异步 pause 不能阻塞工具返回;结果只影响登记/证据,不影响任务受理。
|
|
5850
|
-
void Promise.resolve(paused).then(settle, (error) => {
|
|
5851
|
-
logGoalHandoffError("pause", error);
|
|
5852
|
-
settle();
|
|
5853
|
-
});
|
|
5854
|
-
return true;
|
|
5855
|
-
}
|
|
5856
|
-
return settle();
|
|
5901
|
+
return rootTurnWaits.track(parent, { kind: "fanout", parentTaskId, attempt }) !== void 0;
|
|
5857
5902
|
}
|
|
5858
5903
|
|
|
5859
5904
|
/**
|
|
5860
|
-
* fan-out
|
|
5905
|
+
* fan-out 父任务真实终态时**精确结算**它的等待工作。
|
|
5861
5906
|
*
|
|
5862
|
-
*
|
|
5863
|
-
*
|
|
5864
|
-
* 为安全 no-op,绝不凭空构造 reason。
|
|
5907
|
+
* 只结算当前登记的代次:旧代次的迟到结算命中的键与新代次不同,因此不会提前放行仍在
|
|
5908
|
+
* retry 的任务。没有登记记录时为安全 no-op。
|
|
5865
5909
|
*
|
|
5866
|
-
*
|
|
5867
|
-
* 不再由本插件的该任务持有 → 释放归属证据并落盘;waiting/resuming 说明其他等待原因
|
|
5868
|
-
* 仍持有同一个 pause → 保留证据(并刷新 revision,覆盖 re-pause)。
|
|
5869
|
-
*
|
|
5870
|
-
* @returns {boolean} 是否确实发起了释放。
|
|
5910
|
+
* @returns {boolean} 是否确实结算。
|
|
5871
5911
|
*/
|
|
5872
5912
|
function releaseFanoutGoalHandoff(agent, parentTaskId) {
|
|
5873
|
-
if (
|
|
5874
|
-
const record =
|
|
5875
|
-
// pending(pause 在飞)也允许释放:reason 可能在 async get/pause 之前就已登记,
|
|
5876
|
-
// releaseGoalHandoff 会在 pausing 状态等待 operation 落地后再释放。
|
|
5913
|
+
if (turnWaitStopping) return false;
|
|
5914
|
+
const record = fanoutTurnWaitRecords.get(parentTaskId);
|
|
5877
5915
|
if (record === void 0 || record.state === "released") return false;
|
|
5878
5916
|
record.state = "released";
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
forgetFanoutPauseEvidence(agent.id, parentTaskId);
|
|
5882
|
-
flushFanoutGoalHandoffEvidence();
|
|
5883
|
-
return;
|
|
5884
|
-
}
|
|
5885
|
-
// waiting/resuming:pause 仍由本插件持有(可能别的 child 原因也在等),
|
|
5886
|
-
// 用 live record 的最新 ref 刷新证据 revision。
|
|
5887
|
-
if (rememberFanoutPauseEvidence(agent, parentTaskId, record.attempt)) flushFanoutGoalHandoffEvidence();
|
|
5888
|
-
});
|
|
5889
|
-
return true;
|
|
5917
|
+
if (record.agent !== agent) return false;
|
|
5918
|
+
return rootTurnWaits.settle(agent, { kind: "fanout", parentTaskId, attempt: record.attempt });
|
|
5890
5919
|
}
|
|
5891
5920
|
|
|
5892
5921
|
/**
|
|
5893
|
-
* fan-out 任务「重新回到 pending
|
|
5922
|
+
* fan-out 任务「重新回到 pending」时的等待工作再登记入口。
|
|
5894
5923
|
*
|
|
5895
|
-
* 两个触发源共用同一语义(任务重新变成 pending
|
|
5896
|
-
* - 手工重试(RPC fanout-retry-shard / fanout-retry
|
|
5924
|
+
* 两个触发源共用同一语义(任务重新变成 pending,root 必须继续等待):
|
|
5925
|
+
* - 手工重试(RPC fanout-retry-shard / fanout-retry);
|
|
5897
5926
|
* - 多轮复用(fanout 工具的 continuation 参数,同一 parentTaskId 的新一轮)。
|
|
5898
|
-
*
|
|
5899
|
-
* 首次 settle 已经释放过旧代次 reason。这里用重新变成 pending 后的 manager 权威任务
|
|
5900
|
-
* 快照登记**新代次**(全局序号,不复用旧 key),保证:
|
|
5901
|
-
* - 新一轮运行期间 goal 保持 paused(resume 在飞时按新 reason 触发 re-pause);
|
|
5902
|
-
* - 新一轮成功/失败/取消最终都通过 task_settled → releaseFanoutGoalHandoff 释放
|
|
5903
|
-
* 它自己的代次。
|
|
5904
5927
|
*/
|
|
5905
5928
|
function registerFanoutRetryGoalHandoff(parent, parentTaskId, task) {
|
|
5906
|
-
if (
|
|
5929
|
+
if (turnWaitStopping || !isLiveRootAgent(parent)) return false;
|
|
5907
5930
|
if (typeof parentTaskId !== "string" || parentTaskId.length === 0) return false;
|
|
5908
5931
|
return registerFanoutGoalHandoff(parent, { accepted: true, parentTaskId, task });
|
|
5909
5932
|
}
|
|
5910
5933
|
|
|
5934
|
+
/**
|
|
5935
|
+
* fan-out 提交入口:只调用 manager 并登记 root turn 等待工作。
|
|
5936
|
+
*
|
|
5937
|
+
* 改造后这里**不再暂停 durable goal**:任务在后台按自己的调度推进,root 的当前
|
|
5938
|
+
* turn 由 finalize 保持打开(见 host/turn-wait.js),因此「任务运行期间 root 不会
|
|
5939
|
+
* 抢跑」这一语义由等待登记表承担。
|
|
5940
|
+
*
|
|
5941
|
+
* @param {object} parent - exact live root Agent。
|
|
5942
|
+
* @param {object} args - fanout 工具的已校验入参(含 role)。
|
|
5943
|
+
* @returns {object} manager 的提交结果。
|
|
5944
|
+
*/
|
|
5911
5945
|
function submitFanoutTask(parent, args) {
|
|
5912
5946
|
const result = fanoutHost.submit(parent, args);
|
|
5913
5947
|
registerFanoutGoalHandoff(parent, result);
|
|
@@ -5980,7 +6014,7 @@ export default {
|
|
|
5980
6014
|
* 上一轮 wait-all 已完成,任一不满足即结构化拒绝(不改状态、不建 attempt);
|
|
5981
6015
|
* - 每个既有 shard 追加一个新 attempt,保留原 childId,旧 attempt 历史原样保留;
|
|
5982
6016
|
* - 提交成功后任务立即回到 pending(投影 = running,侧边栏不再显示上一轮 stale ready),
|
|
5983
|
-
*
|
|
6017
|
+
* 并**重新登记 root turn 等待工作**(新一轮运行期间 root 不会抢跑)。
|
|
5984
6018
|
*
|
|
5985
6019
|
* 失败一律抛带 code/reason 的错误:工具调用方(主代理)能直接读到拒绝原因,而 manager
|
|
5986
6020
|
* 侧已经保证「校验先于任何状态修改」,因此不存在半写。
|
|
@@ -6002,9 +6036,9 @@ export default {
|
|
|
6002
6036
|
error.detail = result;
|
|
6003
6037
|
throw error;
|
|
6004
6038
|
}
|
|
6005
|
-
// 任务重新 pending
|
|
6006
|
-
// 幂等重放(duplicate=true
|
|
6007
|
-
//
|
|
6039
|
+
// 任务重新 pending:立刻重新登记等待工作(新代次),与 retry 同一语义。
|
|
6040
|
+
// 幂等重放(duplicate=true)不改变任何状态,因此绝不能重新登记——
|
|
6041
|
+
// 那会把一个已经结算的轮次又挂成等待项。
|
|
6008
6042
|
if (result.duplicate !== true) {
|
|
6009
6043
|
registerFanoutRetryGoalHandoff(parent, result.parentTaskId, result.task);
|
|
6010
6044
|
}
|
|
@@ -6053,166 +6087,69 @@ export default {
|
|
|
6053
6087
|
}
|
|
6054
6088
|
|
|
6055
6089
|
/**
|
|
6056
|
-
*
|
|
6057
|
-
*
|
|
6058
|
-
*
|
|
6059
|
-
*
|
|
6060
|
-
*
|
|
6061
|
-
*
|
|
6062
|
-
*
|
|
6063
|
-
*
|
|
6064
|
-
*
|
|
6065
|
-
* 但重建**必须带归属证据**:只有持久化证据证明「这个 pause 是本插件为该父任务建立、
|
|
6066
|
-
* 且之后无人改动过该 goal」时才 adopt/release;否则一律保持 paused(绝不把用户
|
|
6067
|
-
* ask_user_question / 其他插件 / 人工 pause 当成自己的 handoff 恢复)。
|
|
6068
|
-
*
|
|
6069
|
-
* 覆盖四种情况:
|
|
6070
|
-
* 1. root 存活 + 任务 pending → 目标 armed 时执行本插件自己的真实 pause;目标已 paused
|
|
6071
|
-
* 时必须证据匹配才托管,否则保持 paused 不登记;
|
|
6072
|
-
* 2. root 存活 + 任务已终态 → 证据匹配才显式 release 一次,否则保持 paused;
|
|
6073
|
-
* 3. root 已销毁 + 任务 pending → 不凭空为不存在的 root 登记 reason;任务由 lineage
|
|
6074
|
-
* 的 deferred 表保留,root 重新出现时 agent/created 会再次 restore 并重建;
|
|
6075
|
-
* 4. root 已销毁 + 任务已终态 → 无法寻址不可 resume,保持 no-op(不登记 reason),
|
|
6076
|
-
* 避免产生永远无法释放的孤儿原因。
|
|
6077
|
-
*
|
|
6078
|
-
* 只处理本进程尚未登记的父任务(records 缺失或已释放),因此重复调用幂等,也不会
|
|
6079
|
-
* 覆盖当前活动代次。
|
|
6090
|
+
* 冷恢复/重启后为「已在运行、但本进程还没有登记」的 fan-out 任务补登记等待工作。
|
|
6091
|
+
*
|
|
6092
|
+
* 判定完全基于当前事实(manager 权威任务 + exact live root 归属),因此可重入、
|
|
6093
|
+
* 可合并:registerFanoutGoalHandoff 自己对未释放记录幂等短路。
|
|
6094
|
+
*
|
|
6095
|
+
* 只处理本进程尚无活动登记的父任务;owner 已销毁时跳过(不凭空为不存在的 root 登记)。
|
|
6096
|
+
*
|
|
6097
|
+
* @returns {number} 本次补登记的任务数。
|
|
6080
6098
|
*/
|
|
6081
6099
|
function reconcileFanoutGoalHandoffs() {
|
|
6082
|
-
if (
|
|
6083
|
-
if (typeof goals?.get !== "function") return 0;
|
|
6100
|
+
if (turnWaitStopping || !fanoutHost) return 0;
|
|
6084
6101
|
let reconciled = 0;
|
|
6085
6102
|
for (const task of fanoutHost.listTasks()) {
|
|
6086
6103
|
const parentTaskId = task?.parentTaskId;
|
|
6087
6104
|
if (typeof parentTaskId !== "string" || parentTaskId.length === 0) continue;
|
|
6088
|
-
const existing =
|
|
6105
|
+
const existing = fanoutTurnWaitRecords.get(parentTaskId);
|
|
6089
6106
|
if (existing !== void 0 && existing.state !== "released") continue;
|
|
6090
6107
|
const ownerId = fanoutHost.ownerOf(parentTaskId);
|
|
6091
6108
|
if (typeof ownerId !== "string" || ownerId.length === 0) continue;
|
|
6092
6109
|
const agent = agents.get(ownerId);
|
|
6093
|
-
// root 已销毁:不凭空恢复不存在的 root
|
|
6110
|
+
// root 已销毁:不凭空恢复不存在的 root。
|
|
6094
6111
|
if (agent === void 0 || !isLiveRootAgent(agent)) continue;
|
|
6095
|
-
|
|
6096
|
-
|
|
6112
|
+
// 终态任务不会再有 task_settled:只标记已释放,绝不登记等待工作。
|
|
6113
|
+
if (fanoutTaskIsTerminal(task)) {
|
|
6114
|
+
if (existing !== void 0) existing.state = "released";
|
|
6097
6115
|
continue;
|
|
6098
6116
|
}
|
|
6099
|
-
|
|
6100
|
-
if (existing !== void 0) continue;
|
|
6101
|
-
if (releaseRestoredFanoutGoalHandoff(agent, parentTaskId)) reconciled += 1;
|
|
6117
|
+
if (registerFanoutGoalHandoff(agent, { accepted: true, parentTaskId, task })) reconciled += 1;
|
|
6102
6118
|
}
|
|
6103
6119
|
return reconciled;
|
|
6104
6120
|
}
|
|
6105
6121
|
|
|
6106
|
-
/** 读一次 goal 视图并按归属证据决定 pending 任务的登记方式(同步/异步同源判定)。 */
|
|
6107
|
-
function registerRestoredFanoutHandoff(agent, parentTaskId) {
|
|
6108
|
-
let view;
|
|
6109
|
-
try {
|
|
6110
|
-
view = goals.get(agent);
|
|
6111
|
-
} catch (error) {
|
|
6112
|
-
logGoalHandoffError("get", error);
|
|
6113
|
-
return false;
|
|
6114
|
-
}
|
|
6115
|
-
if (isThenable(view)) {
|
|
6116
|
-
void Promise.resolve(view).then((resolved) => {
|
|
6117
|
-
applyRestoredFanoutRegistration(agent, parentTaskId, resolved);
|
|
6118
|
-
}, (error) => logGoalHandoffError("get", error));
|
|
6119
|
-
return true;
|
|
6120
|
-
}
|
|
6121
|
-
return applyRestoredFanoutRegistration(agent, parentTaskId, view);
|
|
6122
|
-
}
|
|
6123
|
-
|
|
6124
|
-
/**
|
|
6125
|
-
* pending 恢复任务的登记判定:
|
|
6126
|
-
* - armed+active:目标仍在本插件掌控之外(未被任何人暂停),走真实 pause(我们自己的
|
|
6127
|
-
* pause,无需归属证据);
|
|
6128
|
-
* - paused+disarmed:必须有匹配的归属证据才能托管(registerPausedGoalHandoff),否则
|
|
6129
|
-
* fail-closed 保持 paused 不登记(settle 时也不会 resume);
|
|
6130
|
-
* - 无目标/非法/blocked/complete:不登记,绝不留下没有释放边界的 record。
|
|
6131
|
-
*
|
|
6132
|
-
* 注意:不在这里调用 adoptPausedGoalForHandoff —— 它只按视图形状接管,会把外部
|
|
6133
|
-
* pause 当成自己的。证据匹配后直接用已校验的 exact ref 登记。
|
|
6134
|
-
*/
|
|
6135
|
-
function applyRestoredFanoutRegistration(agent, parentTaskId, view) {
|
|
6136
|
-
if (goalHandoffStopping || !isLiveRootAgent(agent)) return false;
|
|
6137
|
-
const existing = fanoutHandoffRecords.get(parentTaskId);
|
|
6138
|
-
if (existing !== void 0 && existing.state !== "released") return true;
|
|
6139
|
-
const armed = view?.phase === "active" && view?.activation === "armed";
|
|
6140
|
-
if (armed) {
|
|
6141
|
-
return registerFanoutGoalHandoff(agent, { accepted: true, parentTaskId, task: { status: "pending" } });
|
|
6142
|
-
}
|
|
6143
|
-
const pausedRef = adoptablePausedGoalRef(view);
|
|
6144
|
-
if (pausedRef === void 0) return false;
|
|
6145
|
-
if (!fanoutPauseEvidenceMatches(agent.id, parentTaskId, pausedRef, view.id)) {
|
|
6146
|
-
ctx.logger.warn("dsh-expert-group: fan-out handoff evidence missing for " + parentTaskId
|
|
6147
|
-
+ "; keeping goal paused instead of adopting an unproven pause");
|
|
6148
|
-
return false;
|
|
6149
|
-
}
|
|
6150
|
-
const attempt = nextFanoutHandoffSequence();
|
|
6151
|
-
const reason = { kind: "fanout", id: parentTaskId, attempt };
|
|
6152
|
-
const record = { attempt, ownerId: agent.id, agent, state: "active", restored: true };
|
|
6153
|
-
fanoutHandoffRecords.set(parentTaskId, record);
|
|
6154
|
-
pruneFanoutHandoffRecords();
|
|
6155
|
-
if (!registerPausedGoalHandoff(agent, goalHandoffs, reason, pausedRef)) {
|
|
6156
|
-
record.state = "released";
|
|
6157
|
-
return false;
|
|
6158
|
-
}
|
|
6159
|
-
if (rememberFanoutPauseEvidence(agent, parentTaskId, attempt)) flushFanoutGoalHandoffEvidence();
|
|
6160
|
-
return true;
|
|
6161
|
-
}
|
|
6162
|
-
|
|
6163
6122
|
/**
|
|
6164
|
-
*
|
|
6123
|
+
* 为「已在运行、但还没有任何等待登记」的 fan-out 任务补登记(兜底路径)。
|
|
6165
6124
|
*
|
|
6166
|
-
*
|
|
6167
|
-
*
|
|
6168
|
-
*
|
|
6125
|
+
* 触发方式刻意做成「最小、可重入、可合并」:本函数不做任何自己的状态记账,只把当前
|
|
6126
|
+
* 事实合起来判定,因此可以被 root run 边界事件反复调用而不产生副作用放大。
|
|
6127
|
+
*
|
|
6128
|
+
* 归属边界:只处理本进程真实登记过的 parentTaskId(没有 record 就不猜);record.agent
|
|
6129
|
+
* 必须是 exact live root 对象,且 fanoutHost.ownsTask 能证明活动绑定与绑定代际 token
|
|
6130
|
+
* 仍 live;任务必须是 manager 的**非终态**任务。
|
|
6131
|
+
*
|
|
6132
|
+
* @returns {number} 本次补登记的任务数。
|
|
6169
6133
|
*/
|
|
6170
|
-
function
|
|
6171
|
-
|
|
6172
|
-
|
|
6173
|
-
|
|
6174
|
-
|
|
6175
|
-
|
|
6176
|
-
|
|
6177
|
-
|
|
6178
|
-
|
|
6179
|
-
|
|
6180
|
-
|
|
6181
|
-
|
|
6182
|
-
|
|
6134
|
+
function reconcileUnbarrieredFanoutHandoffs() {
|
|
6135
|
+
if (turnWaitStopping || !fanoutHost) return 0;
|
|
6136
|
+
if (fanoutTurnWaitRecords.size === 0) return 0;
|
|
6137
|
+
let reconciled = 0;
|
|
6138
|
+
for (const [parentTaskId, record] of [...fanoutTurnWaitRecords]) {
|
|
6139
|
+
if (record?.state !== "pending" && record?.state !== "released") continue;
|
|
6140
|
+
const agent = record.agent;
|
|
6141
|
+
const owned = fanoutHandoffRecordIsOwnedByLiveRoot(agent, parentTaskId);
|
|
6142
|
+
if (owned === void 0 || owned !== record) continue;
|
|
6143
|
+
const task = fanoutHost.getTask(parentTaskId);
|
|
6144
|
+
if (task === null || fanoutTaskIsTerminal(task)) continue;
|
|
6145
|
+
// 复用提交路径的登记入口:记录已被标记 released 时不会被幂等短路,因此这是一次
|
|
6146
|
+
// 真实的新代次登记。传入**权威任务快照**而不是伪造的 pending 视图。
|
|
6147
|
+
if (record.state === "released") fanoutTurnWaitRecords.delete(parentTaskId);
|
|
6148
|
+
if (registerFanoutGoalHandoff(agent, { accepted: true, parentTaskId, task })) reconciled += 1;
|
|
6183
6149
|
}
|
|
6184
|
-
return
|
|
6150
|
+
return reconciled;
|
|
6185
6151
|
}
|
|
6186
6152
|
|
|
6187
|
-
/** 终态恢复任务的 release 判定(证据门控;缺失即保持 paused)。 */
|
|
6188
|
-
function applyRestoredFanoutRelease(agent, parentTaskId, view) {
|
|
6189
|
-
if (goalHandoffStopping || !isLiveRootAgent(agent)) return false;
|
|
6190
|
-
const existing = fanoutHandoffRecords.get(parentTaskId);
|
|
6191
|
-
if (existing !== void 0 && existing.state !== "released") return false;
|
|
6192
|
-
const pausedRef = adoptablePausedGoalRef(view);
|
|
6193
|
-
if (pausedRef === void 0) {
|
|
6194
|
-
// 目标不再是「已暂停且未武装」:本插件不再持有任何 pending pause,清掉陈旧证据。
|
|
6195
|
-
if (forgetFanoutPauseEvidence(agent.id, parentTaskId)) flushFanoutGoalHandoffEvidence();
|
|
6196
|
-
return false;
|
|
6197
|
-
}
|
|
6198
|
-
if (!fanoutPauseEvidenceMatches(agent.id, parentTaskId, pausedRef, view.id)) {
|
|
6199
|
-
ctx.logger.warn("dsh-expert-group: fan-out handoff evidence missing for " + parentTaskId
|
|
6200
|
-
+ "; keeping goal paused instead of resuming an unproven pause");
|
|
6201
|
-
return false;
|
|
6202
|
-
}
|
|
6203
|
-
const attempt = nextFanoutHandoffSequence();
|
|
6204
|
-
const reason = { kind: "fanout", id: parentTaskId, attempt };
|
|
6205
|
-
const record = { attempt, ownerId: agent.id, agent, state: "active", restored: true };
|
|
6206
|
-
fanoutHandoffRecords.set(parentTaskId, record);
|
|
6207
|
-
pruneFanoutHandoffRecords();
|
|
6208
|
-
if (!registerPausedGoalHandoff(agent, goalHandoffs, reason, pausedRef)) {
|
|
6209
|
-
record.state = "released";
|
|
6210
|
-
return false;
|
|
6211
|
-
}
|
|
6212
|
-
// 证据已匹配:这次托管 + 释放是合法的(该 pause 确实由本插件为该任务建立)。
|
|
6213
|
-
releaseFanoutGoalHandoff(agent, parentTaskId);
|
|
6214
|
-
return true;
|
|
6215
|
-
}
|
|
6216
6153
|
|
|
6217
6154
|
fanoutHost = createFanoutRuntimeModule({
|
|
6218
6155
|
createRuntime: (options) => createFanoutRuntime(options),
|
|
@@ -6365,19 +6302,18 @@ export default {
|
|
|
6365
6302
|
getAgent: (id) => agents.get(id),
|
|
6366
6303
|
buildFeedback: buildFanoutFeedback,
|
|
6367
6304
|
/**
|
|
6368
|
-
* fan-out
|
|
6305
|
+
* fan-out 父任务真实终态时的等待结算入口。
|
|
6369
6306
|
*
|
|
6370
6307
|
* 任务整体 settle(completed / completed_with_errors / cancelled)时按**当前登记
|
|
6371
|
-
*
|
|
6372
|
-
*
|
|
6373
|
-
* 因为回调是在 manager 的状态写入路径里同步触发的。
|
|
6308
|
+
* 代次**结算 "fanout:<parentTaskId>:<attempt>" 工作项。回调是在 manager 的状态写入
|
|
6309
|
+
* 路径里同步触发的,因此这里只做同步的精确结算(登记表内部会按需重新判定静止)。
|
|
6374
6310
|
*
|
|
6375
|
-
* exact Agent 优先用 fanout-runtime 在释放 lineage
|
|
6376
|
-
*
|
|
6377
|
-
* 不可用时才退回 id
|
|
6311
|
+
* exact Agent 优先用 fanout-runtime 在释放 lineage 绑定前捕获的对象:登记记录的
|
|
6312
|
+
* 归属校验是对象身份,按 id 重新解析可能拿到 replacement 代际。只有 exact 对象
|
|
6313
|
+
* 不可用时才退回 id,交由对象身份校验 fail-closed。
|
|
6378
6314
|
*/
|
|
6379
6315
|
onParentSettled: (parentTaskId, parentAgent, parentAgentId) => {
|
|
6380
|
-
if (
|
|
6316
|
+
if (turnWaitStopping) return;
|
|
6381
6317
|
const agent = parentAgent ?? (typeof parentAgentId === "string" ? agents.get(parentAgentId) : void 0);
|
|
6382
6318
|
if (agent === void 0) return;
|
|
6383
6319
|
releaseFanoutGoalHandoff(agent, parentTaskId);
|
|
@@ -6406,9 +6342,7 @@ export default {
|
|
|
6406
6342
|
});
|
|
6407
6343
|
parent.inject(message);
|
|
6408
6344
|
},
|
|
6409
|
-
|
|
6410
|
-
// 重新构造 payload,因此必须在最后一跳注入,不能只在某一条写入路径上加)。
|
|
6411
|
-
writeSnapshot: (snapshot) => persistFanoutSnapshot(withFanoutPauseEvidence(snapshot)),
|
|
6345
|
+
writeSnapshot: (snapshot) => persistFanoutSnapshot(snapshot),
|
|
6412
6346
|
getPersistenceGeneration: () => host.storage.active()?.generation,
|
|
6413
6347
|
readSnapshot: () => storageBinding.fanoutSnapshot(),
|
|
6414
6348
|
persistenceHealth,
|
|
@@ -6438,31 +6372,315 @@ export default {
|
|
|
6438
6372
|
// 因此这里不再缓存角色人格快照。
|
|
6439
6373
|
if (ROLE_META[role] === void 0) return;
|
|
6440
6374
|
|
|
6375
|
+
/**
|
|
6376
|
+
* 校验显式续作句柄(role tool 的 childId):必须存在、属于当前 root,
|
|
6377
|
+
* 并且是本 scope 记录过的 expert child。
|
|
6378
|
+
*
|
|
6379
|
+
* 只接受显式传入的 childId —— 没有任何输入时绝不把「当前 scope 最近一个
|
|
6380
|
+
* child」当成续作目标,避免不同 prompt 被静默当成旧任务的续作。
|
|
6381
|
+
* @returns {{target:object|undefined, warning:string}} 校验结果。
|
|
6382
|
+
*/
|
|
6383
|
+
function resolveContinueTarget({ childId, parent, scope, taskKey, currentRouteKey }) {
|
|
6384
|
+
if (typeof childId !== "string" || childId.length === 0) {
|
|
6385
|
+
return { target: void 0, warning: role + " 续作需要显式 childId" };
|
|
6386
|
+
}
|
|
6387
|
+
if (!trackerChildIdsForScope(scope, taskKey, { parent }).includes(childId)) {
|
|
6388
|
+
return {
|
|
6389
|
+
target: void 0,
|
|
6390
|
+
warning: role + " 续作被拒绝:childId 「" + childId + "」不是本 root(" + parent.id + ") 下该角色的已知专家 child;"
|
|
6391
|
+
+ "请使用 role 工具返回的 subagentId,或省略 childId 派发一个新任务",
|
|
6392
|
+
};
|
|
6393
|
+
}
|
|
6394
|
+
const record = recoveryRecords.get(childId);
|
|
6395
|
+
// 记录存在时进一步校验 owner:跨父代理/跨角色的 childId 不得被当作续作目标。
|
|
6396
|
+
if (record !== void 0 && (record.parentId !== parent.id || (record.role !== void 0 && record.role !== role))) {
|
|
6397
|
+
return {
|
|
6398
|
+
target: void 0,
|
|
6399
|
+
warning: role + " 续作被拒绝:childId 「" + childId + "」不属于当前 root 的该角色专家 child",
|
|
6400
|
+
};
|
|
6401
|
+
}
|
|
6402
|
+
const bound = delegationTracker.getTaskChild(scope, taskKey);
|
|
6403
|
+
return {
|
|
6404
|
+
target: {
|
|
6405
|
+
childId,
|
|
6406
|
+
record,
|
|
6407
|
+
routeKey: bound?.childId === childId && typeof bound.routeKey === "string" ? bound.routeKey : currentRouteKey,
|
|
6408
|
+
},
|
|
6409
|
+
warning: "",
|
|
6410
|
+
};
|
|
6411
|
+
}
|
|
6412
|
+
|
|
6413
|
+
/**
|
|
6414
|
+
* 本 scope 已知的 expert child id(最近 child + 任务绑定指向的 child +
|
|
6415
|
+
* 本父代理该角色尚未结算的活动任务指向的 child)。
|
|
6416
|
+
*
|
|
6417
|
+
* 覆盖面刻意完整:显式 childId 的归属校验会拒绝任何不在此集合中的 id,
|
|
6418
|
+
* 因此这里必须包含所有**本 root 该角色**真实创建过的 child,同时绝不包含
|
|
6419
|
+
* 其他父代理、fan-out 或不属于该角色的 child。
|
|
6420
|
+
* @param {string} scope - delegationScopeKey(parentId, role)。
|
|
6421
|
+
* @param {string} [candidateTaskKey] - 可选的归一化任务 key(其绑定 child 也算已知)。
|
|
6422
|
+
* @param {{parent?:object}} [owner] - 可选的 exact root Agent:给出时额外要求 recovery
|
|
6423
|
+
* record 的 parentAgent 与它一致(同 id 的另一代 root 不得接管该 record)。
|
|
6424
|
+
* @returns {Array<string>} 去重后的 child id 列表。
|
|
6425
|
+
*/
|
|
6426
|
+
function trackerChildIdsForScope(scope, candidateTaskKey, owner) {
|
|
6427
|
+
const ids = new Set(delegationTracker.listChildIds(scope));
|
|
6428
|
+
const bound = delegationTracker.getChild(scope);
|
|
6429
|
+
if (bound !== void 0) ids.add(bound.childId);
|
|
6430
|
+
if (typeof candidateTaskKey === "string" && candidateTaskKey.length > 0) {
|
|
6431
|
+
const taskChild = delegationTracker.getTaskChild(scope, candidateTaskKey);
|
|
6432
|
+
if (taskChild !== void 0) ids.add(taskChild.childId);
|
|
6433
|
+
}
|
|
6434
|
+
// 活动任务指向的 child:任务绑定可能已被上限淘汰/结算,但 child 仍属于本 scope。
|
|
6435
|
+
const separator = String(scope ?? "").lastIndexOf("::");
|
|
6436
|
+
const parentId = separator === -1 ? void 0 : String(scope).slice(0, separator);
|
|
6437
|
+
if (parentId === void 0) return [...ids];
|
|
6438
|
+
for (const task of delegationTracker.listActiveTasks(parentId)) {
|
|
6439
|
+
if (task.role !== role) continue;
|
|
6440
|
+
if (typeof task.childId === "string" && task.childId.length > 0) ids.add(task.childId);
|
|
6441
|
+
}
|
|
6442
|
+
// 仍存活的 recovery record 持有的 expert child:task 记忆被 LRU 淘汰、route 切换
|
|
6443
|
+
// 清表、记录重建或活动范围已结算后,receipt 里的 childId 仍必须能被显式续作/取消
|
|
6444
|
+
// 定位;否则 root 只能改派新任务,而旧 child 还在跑(变成无人收口的孤儿任务)。
|
|
6445
|
+
// route 刻意不作为识别过滤条件:record.routeKey 是「创建时那条 route」,切换 route
|
|
6446
|
+
// 之后 receipt 句柄必须继续有效;route 的校验留在投递与恢复路径(续作使用当前
|
|
6447
|
+
// route、恢复按 routeChanged 判定重建),识别阶段只认 root+role 归属与有效性。
|
|
6448
|
+
const parentAgent = owner?.parent;
|
|
6449
|
+
for (const [recordChildId, record] of recoveryRecords) {
|
|
6450
|
+
if (record === null || typeof record !== "object") continue;
|
|
6451
|
+
// 归属:只认本 parent+role 的 record;同 id 的另一代 root generation 不得接管。
|
|
6452
|
+
if (record.parentId !== parentId || record.role !== role) continue;
|
|
6453
|
+
if (parentAgent !== void 0 && record.parentAgent !== void 0 && record.parentAgent !== parentAgent) continue;
|
|
6454
|
+
// 有效性:只有可续接、且确实成功 acceptance 过的专家 child 才是合法目标。
|
|
6455
|
+
if (record.continuable !== true || record.invalidAcceptance === true) continue;
|
|
6456
|
+
// fan-out child 属于另一条恢复链:普通 role 工具绝不显式续作/取消它。
|
|
6457
|
+
if (isFanoutChildId(recordChildId)) continue;
|
|
6458
|
+
ids.add(recordChildId);
|
|
6459
|
+
}
|
|
6460
|
+
return [...ids];
|
|
6461
|
+
}
|
|
6462
|
+
|
|
6463
|
+
/**
|
|
6464
|
+
* childId 是否属于 fan-out 链路:内存 Agent 与持久化 child_models 快照任一侧命中
|
|
6465
|
+
* 即算(与 agent/created 的 fan-out 判定同源),fan-out 目标永不由普通 role 工具续作。
|
|
6466
|
+
*/
|
|
6467
|
+
function isFanoutChildId(childId) {
|
|
6468
|
+
return isFanoutAgent(agents.get(childId)) || isFanoutIdentity(source().childModels?.[childId]);
|
|
6469
|
+
}
|
|
6470
|
+
|
|
6471
|
+
/**
|
|
6472
|
+
* 读取显式句柄参数(childId / cancelChildId)。
|
|
6473
|
+
*
|
|
6474
|
+
* 约定:字段**完全缺省**(undefined)才算「没有提供」;只要字段存在,就必须是
|
|
6475
|
+
* 非空且非纯空白的字符串。空串、纯空白与非字符串一律 fail-closed,绝不被当作
|
|
6476
|
+
* 「未提供」而继续普通派发/新建 child —— 那会让 root 以为在续作或取消,实际却
|
|
6477
|
+
* 启动了新任务(线上最危险的静默分叉)。
|
|
6478
|
+
*
|
|
6479
|
+
* 非字符串输入通常已被 DSH 工具入参校验(defineTool → INVALID_ARGS)拦在 handler
|
|
6480
|
+
* 之外;这里保留同一判定作为 handler 边界的第二道防线。合法的非空白字符串**不做
|
|
6481
|
+
* trim**:childId 是 opaque id,精确匹配失败会走 CHILD_NOT_FOUND 的可读拒绝,
|
|
6482
|
+
* 不扩大匹配面。
|
|
6483
|
+
* @returns {{present:boolean, value:string|undefined, invalid:boolean}}
|
|
6484
|
+
*/
|
|
6485
|
+
function readExplicitHandle(args, name) {
|
|
6486
|
+
const raw = args === null || typeof args !== "object" ? void 0 : args[name];
|
|
6487
|
+
if (raw === void 0) return { present: false, value: void 0, invalid: false };
|
|
6488
|
+
if (typeof raw !== "string" || raw.trim().length === 0) return { present: true, value: void 0, invalid: true };
|
|
6489
|
+
return { present: true, value: raw, invalid: false };
|
|
6490
|
+
}
|
|
6491
|
+
|
|
6492
|
+
/** 非法句柄的简短类型描述:只报类型/形态,绝不复述可能很长的原始内容。 */
|
|
6493
|
+
function describeHandleValue(value) {
|
|
6494
|
+
if (value === null) return "null";
|
|
6495
|
+
if (typeof value === "string") return value.length === 0 ? "空字符串" : "仅含空白的字符串";
|
|
6496
|
+
return typeof value;
|
|
6497
|
+
}
|
|
6498
|
+
|
|
6499
|
+
/**
|
|
6500
|
+
* 构造「显式句柄在 admission 之前被拒绝」的公开结果。
|
|
6501
|
+
*
|
|
6502
|
+
* 该结果**不携带** admissionEpoch/admissionToken:被拒绝的句柄没有登记新 admission、
|
|
6503
|
+
* 没有创建或投递任何 child,凭据会伪造出「真实 child admission」的假象并让模型把它
|
|
6504
|
+
* 拿去 finalize。因此使用独立 kind `rejected`(输出 schema 中的无凭据变体),与带凭据
|
|
6505
|
+
* 的 advisory/continuable 明确区分;同时保持 fail-closed:绝不 interrupt、绝不派发。
|
|
6506
|
+
*/
|
|
6507
|
+
function rejectedHandleResult(reason, code, warning) {
|
|
6508
|
+
return { kind: "rejected", started: false, accepted: false, reason, code, warning };
|
|
6509
|
+
}
|
|
6510
|
+
|
|
6511
|
+
/**
|
|
6512
|
+
* 显式续作:向指定 child 投递本轮 prompt。
|
|
6513
|
+
*
|
|
6514
|
+
* 走既有公开 continuation seam(reuseOrSteer → subagents.sendMessage/interrupt):
|
|
6515
|
+
* lineage/root generation 校验、message admission 与 disposal 都由 Host 负责。
|
|
6516
|
+
* 语义保留既有边界:
|
|
6517
|
+
* - queue=true 只排队(公开 sendMessage 投递,不请求 cancel);
|
|
6518
|
+
* - queue=false 允许先请求公开 interrupt(用户显式要求暂停/重定向才由 root 显式续作);
|
|
6519
|
+
* - 投递失败不得回落到新建 child,只有 NOT_RESUMABLE 才由既有重建路径处理。
|
|
6520
|
+
* @returns {Promise<object>} admission 结果(continuable/reused)。
|
|
6521
|
+
*/
|
|
6522
|
+
async function continueExplicitChild({ scope, taskKey, routeKey, request, parent, signal, label, queue, handoffExpected, rootToken, target }) {
|
|
6523
|
+
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
6524
|
+
let outcome;
|
|
6525
|
+
try {
|
|
6526
|
+
outcome = await reuseOrSteer({
|
|
6527
|
+
scope,
|
|
6528
|
+
childId: target.childId,
|
|
6529
|
+
taskKey,
|
|
6530
|
+
promptText: request.prompt[0].text,
|
|
6531
|
+
promptContent: request.prompt,
|
|
6532
|
+
parent,
|
|
6533
|
+
signal,
|
|
6534
|
+
queue,
|
|
6535
|
+
handoffExpected,
|
|
6536
|
+
rootToken,
|
|
6537
|
+
explicit: true,
|
|
6538
|
+
continuationRouteKey: routeKey,
|
|
6539
|
+
});
|
|
6540
|
+
} catch (error) {
|
|
6541
|
+
// 容量耗尽必须在这里就带上 DEG 自有稳定 code:后续的 lineage 检查会抛普通
|
|
6542
|
+
// 错误,那会覆盖分类信息,让上层把「容量」误判成泛化 admission 失败。
|
|
6543
|
+
const capacityError = createSubagentCapacityError(error);
|
|
6544
|
+
if (capacityError !== undefined) throw capacityError;
|
|
6545
|
+
throw error;
|
|
6546
|
+
}
|
|
6547
|
+
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
6548
|
+
const lateRecord = recoveryRecords.get(target.childId);
|
|
6549
|
+
if (lateRecord?.parentAgent === parent) dropRecoveryRecord(target.childId, "root generation retired", lateRecord);
|
|
6550
|
+
throw new Error("root generation is no longer live");
|
|
6551
|
+
}
|
|
6552
|
+
if (outcome !== null) {
|
|
6553
|
+
recovery.rememberContext(recoveryRecords.get(outcome.subagentId), { routeKey, request, label, taskKey });
|
|
6554
|
+
return outcome;
|
|
6555
|
+
}
|
|
6556
|
+
// 显式续作遇到 NOT_RESUMABLE:按既有恢复语义重建一个 continuable child,
|
|
6557
|
+
// 原 child 的 pending recovery 由此接管(与自动恢复的 rebuild 同一路径)。
|
|
6558
|
+
return rebuildExistingChildForContinuation({
|
|
6559
|
+
record: target.record,
|
|
6560
|
+
childId: target.childId,
|
|
6561
|
+
parent,
|
|
6562
|
+
scope,
|
|
6563
|
+
routeKey,
|
|
6564
|
+
request,
|
|
6565
|
+
label,
|
|
6566
|
+
taskKey,
|
|
6567
|
+
rootToken,
|
|
6568
|
+
});
|
|
6569
|
+
}
|
|
6570
|
+
|
|
6571
|
+
/**
|
|
6572
|
+
* 显式续作触发的 child 重建:把原 child 的任务绑定迁移到替代 child。
|
|
6573
|
+
* 只接受仍可验证的 exact record(parent/role/owner 一致),其他情况 fail-closed
|
|
6574
|
+
* 上抛,绝不静默新建一个与旧任务无关的 child。
|
|
6575
|
+
*/
|
|
6576
|
+
async function rebuildExistingChildForContinuation({ record, childId, parent, scope, routeKey, request, label, taskKey, rootToken }) {
|
|
6577
|
+
if (record === void 0 || record.parentId !== parent.id || record.role !== role) {
|
|
6578
|
+
throw new Error(role + " 续作失败:child " + childId + " 已不可恢复且缺少可验证的恢复记录");
|
|
6579
|
+
}
|
|
6580
|
+
const durableSession = record.agent?.session ?? record.session;
|
|
6581
|
+
if (durableSession === void 0) {
|
|
6582
|
+
// 既没有 durable Session 也没有 live Activation 时,Host 无法冷恢复同一任务链,
|
|
6583
|
+
// 重建出的 child 只会拿到「本轮 follow-up 文本」而丢掉原任务上下文;此时明确
|
|
6584
|
+
// 失败并请 root 改派新任务,绝不静默把旧任务替换成一个内容不完整的 child。
|
|
6585
|
+
throw new Error(role + " 续作失败:child " + childId + " 已不可恢复且缺少 durable Session,请作为新任务重新派发");
|
|
6586
|
+
}
|
|
6587
|
+
let rebuiltChildId;
|
|
6588
|
+
let messageId;
|
|
6589
|
+
try {
|
|
6590
|
+
({ childId: rebuiltChildId, messageId } = await subagents.startContinuable({
|
|
6591
|
+
provider: "spawn",
|
|
6592
|
+
label,
|
|
6593
|
+
request,
|
|
6594
|
+
signal: void 0,
|
|
6595
|
+
}));
|
|
6596
|
+
} catch (error) {
|
|
6597
|
+
const capacityError = createSubagentCapacityError(error);
|
|
6598
|
+
if (capacityError !== undefined) throw capacityError;
|
|
6599
|
+
throw error;
|
|
6600
|
+
}
|
|
6601
|
+
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
6602
|
+
const lateRecord = recoveryRecords.get(rebuiltChildId);
|
|
6603
|
+
if (lateRecord?.parentAgent === parent) dropRecoveryRecord(rebuiltChildId, "root generation retired", lateRecord);
|
|
6604
|
+
throw new Error("root generation is no longer live");
|
|
6605
|
+
}
|
|
6606
|
+
if (typeof rebuiltChildId !== "string" || rebuiltChildId.length === 0
|
|
6607
|
+
|| typeof messageId !== "string" || messageId.length === 0) {
|
|
6608
|
+
throw new Error("startContinuable returned an invalid acceptance");
|
|
6609
|
+
}
|
|
6610
|
+
// 旧 child 的未接受 recovery 由此被替代;旧 Agent 的迟到事件按 id 自然忽略。
|
|
6611
|
+
supersedePendingRecoveryOps(record);
|
|
6612
|
+
const replacement = ensureRecoveryRecord(rebuiltChildId, parent.id, role, parent, void 0, true);
|
|
6613
|
+
delegationTracker.setChild(scope, { childId: rebuiltChildId, routeKey });
|
|
6614
|
+
delegationTracker.rememberTask(scope, taskKey, { childId: rebuiltChildId, routeKey });
|
|
6615
|
+
delegationTracker.rebindActiveTasks({
|
|
6616
|
+
parentId: parent.id,
|
|
6617
|
+
role,
|
|
6618
|
+
oldChildId: childId,
|
|
6619
|
+
newChildId: rebuiltChildId,
|
|
6620
|
+
messageId,
|
|
6621
|
+
taskKeys: [taskKey],
|
|
6622
|
+
});
|
|
6623
|
+
replacement.tasks.set(taskKey, { messageId, childId: rebuiltChildId });
|
|
6624
|
+
evictOldestEntries(replacement.tasks, TASK_BINDING_LIMIT);
|
|
6625
|
+
delete replacement.invalidAcceptance;
|
|
6626
|
+
recovery.rememberContext(replacement, { routeKey, request, label, taskKey });
|
|
6627
|
+
persistChildDispatch(rebuiltChildId, replacement, request, label, messageId);
|
|
6628
|
+
return { kind: "continuable", subagentId: rebuiltChildId, messageId };
|
|
6629
|
+
}
|
|
6630
|
+
|
|
6631
|
+
/**
|
|
6632
|
+
* 显式取消(role tool 的 cancelChildId):按 childId 精确定位,只请求该 child
|
|
6633
|
+
* 的取消,不派发新任务、不投递消息。
|
|
6634
|
+
*
|
|
6635
|
+
* 严格边界:不接受「按 parent+role 猜目标」,因此同 scope 的其他独立 child
|
|
6636
|
+
* 不会被误取消。使用公开 subagents.interrupt(childId, { kind: "ancestor", agent })。
|
|
6637
|
+
*/
|
|
6638
|
+
async function cancelExplicitChild({ childId, parent, scope }) {
|
|
6639
|
+
const resolved = resolveContinueTarget({ childId, parent, scope, taskKey: "" });
|
|
6640
|
+
if (resolved.target === void 0) return { ok: false, warning: resolved.warning };
|
|
6641
|
+
if (typeof subagents?.interrupt !== "function") {
|
|
6642
|
+
return { ok: false, warning: role + " 取消失败:当前 Host 未提供公开 subagents.interrupt" };
|
|
6643
|
+
}
|
|
6644
|
+
await subagents.interrupt(childId, { kind: "ancestor", agent: parent });
|
|
6645
|
+
return { ok: true, childId };
|
|
6646
|
+
}
|
|
6441
6647
|
/**
|
|
6442
6648
|
* 复用或投递到既有 child;判定为需要新建时返回 null。
|
|
6443
|
-
* 复用(reused)时不发送任何新 prompt
|
|
6444
|
-
*
|
|
6445
|
-
*
|
|
6446
|
-
*
|
|
6447
|
-
*
|
|
6649
|
+
* 复用(reused)时不发送任何新 prompt;续作(queued)时返回同一 childId。
|
|
6650
|
+
*
|
|
6651
|
+
* 调用边界(多 child 语义):本函数只处理**已经确定目标 child** 的两种情形——
|
|
6652
|
+
* 归一化后完全相同的任务复用其原 child,或 root 显式给出 childId 的续作
|
|
6653
|
+
* (explicit=true)。不同 prompt 的普通派发不再走到这里,而是新建独立 child,
|
|
6654
|
+
* 因此本函数不会因为没有 childId 就把新任务静默当成旧任务的续作。
|
|
6655
|
+
* NOT_RESUMABLE 走新建分支;容量耗尽抛可读提示(不重建:撞上限时重建必然
|
|
6656
|
+
* 再失败),其他错误(UNAUTHORIZED/DRAINING 等)必须原样上抛,不能吞掉。
|
|
6657
|
+
* B3/S1-D:投递成功后写任务绑定 record.tasks(taskKey -> { messageId,
|
|
6448
6658
|
* childId });reused 分支返回原绑定(含 messageId),供任务终态关联原 turn
|
|
6449
6659
|
* 的最终结果或命中成功缓存。binding 在 admission **之前**以
|
|
6450
6660
|
* pendingMessage:true 预登记(消息 id 未知),admission 返回后回填
|
|
6451
6661
|
* messageId 并清标记——claimed 补绑可覆盖回调晚于认领事件的竞态。
|
|
6452
6662
|
*/
|
|
6453
|
-
async function reuseOrSteer({ scope, childId, taskKey, promptText, promptContent, parent, signal, activityId, queue = false, handoffExpected = false, rootToken }) {
|
|
6663
|
+
async function reuseOrSteer({ scope, childId, taskKey, promptText, promptContent, parent, signal, activityId, queue = false, handoffExpected = false, rootToken, explicit = false, continuationRouteKey }) {
|
|
6454
6664
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
6455
6665
|
if (delegationTracker.hasTask(scope, taskKey)) {
|
|
6456
|
-
//
|
|
6666
|
+
// 归一化后完全相同的任务已记录:默认不发送新 prompt,直接复用同一 child。
|
|
6457
6667
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
6458
6668
|
const record = recoveryRecords.get(childId);
|
|
6459
6669
|
if (record?.invalidAcceptance === true) return null;
|
|
6460
6670
|
const binding = record?.tasks?.get(taskKey);
|
|
6461
|
-
|
|
6462
|
-
|
|
6671
|
+
// 显式续作(root 给出 childId)必须真的把本轮 prompt 投递给**那个** child:
|
|
6672
|
+
// 该 child 上没有本任务绑定、或绑定指向别的 child 时都不能静默「复用」——
|
|
6673
|
+
// 否则回执的 subagentId/messageId 与请求矛盾,root 以为已投递却发给了别的 child。
|
|
6674
|
+
// 只有「绑定正好就是这个 child」才复用;不带 childId 的普通重复派发保持旧语义
|
|
6675
|
+
// (复用其绑定 child;没有绑定时返回无 messageId 的 reused)。
|
|
6676
|
+
const boundHere = binding !== void 0 && binding.childId === childId;
|
|
6677
|
+
if (explicit !== true || boundHere) {
|
|
6678
|
+
if (binding !== void 0) {
|
|
6679
|
+
return { kind: "continuable", subagentId: binding.childId, reused: true, messageId: binding.messageId };
|
|
6680
|
+
}
|
|
6681
|
+
// 没有任务绑定(旧版记录/记录已被上限淘汰):保持旧行为,无 messageId。
|
|
6682
|
+
return { kind: "continuable", subagentId: childId, reused: true };
|
|
6463
6683
|
}
|
|
6464
|
-
// 没有任务绑定(旧版记录/记录已被上限淘汰):保持旧行为,无 messageId。
|
|
6465
|
-
return { kind: "continuable", subagentId: childId, reused: true };
|
|
6466
6684
|
}
|
|
6467
6685
|
|
|
6468
6686
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
@@ -6487,9 +6705,9 @@ export default {
|
|
|
6487
6705
|
content: Array.isArray(promptContent) ? promptContent : [{ type: "text", text: promptText }],
|
|
6488
6706
|
signal,
|
|
6489
6707
|
rootToken,
|
|
6490
|
-
//
|
|
6491
|
-
//
|
|
6492
|
-
interrupt: queue !== true,
|
|
6708
|
+
// 只有「显式续作且未要求排队」才允许先请求公开 interrupt(用户显式要求
|
|
6709
|
+
// 暂停/重定向)。普通新任务永远不会走到这里;即使走到也不得取消既有 child。
|
|
6710
|
+
interrupt: explicit === true && queue !== true,
|
|
6493
6711
|
queue: queue === true,
|
|
6494
6712
|
});
|
|
6495
6713
|
if (typeof messageId !== "string" || messageId.length === 0) throw new Error("existing child admission returned an invalid messageId");
|
|
@@ -6535,8 +6753,10 @@ export default {
|
|
|
6535
6753
|
// messageId 已返回即新任务 admission 边界:此后才允许取代旧 recovery。
|
|
6536
6754
|
// 先 supersede 再重写当前 binding,避免旧 op 恰好拥有相同 taskKey 时把
|
|
6537
6755
|
// 刚接受的新消息标成 superseded;accepted recovery op 会被 helper 跳过。
|
|
6756
|
+
// 取代与任务记忆都只针对本次续作的目标 child:其他独立 child 的 recovery
|
|
6757
|
+
// 和任务绑定不受影响(多 child 语义)。
|
|
6538
6758
|
supersedePendingRecoveryOps(record);
|
|
6539
|
-
delegationTracker.rememberTask(scope, taskKey);
|
|
6759
|
+
delegationTracker.rememberTask(scope, taskKey, { childId, routeKey: continuationRouteKey });
|
|
6540
6760
|
record.tasks.set(taskKey, { messageId, childId });
|
|
6541
6761
|
evictOldestEntries(record.tasks, TASK_BINDING_LIMIT);
|
|
6542
6762
|
if (activityId !== void 0) delegationTracker.bindActiveTask(activityId, childId, messageId);
|
|
@@ -6545,36 +6765,40 @@ export default {
|
|
|
6545
6765
|
|
|
6546
6766
|
/**
|
|
6547
6767
|
* scope 临界区内执行后台委派(唯一入口,保证同父同角色串行):
|
|
6548
|
-
*
|
|
6549
|
-
*
|
|
6550
|
-
*
|
|
6551
|
-
*
|
|
6768
|
+
* 判定顺序(多 child 语义):
|
|
6769
|
+
* 0. root 显式给出 childId → 只向该 child 续作(找不到目标由上层 advisory 拒绝);
|
|
6770
|
+
* 1. 任务 key 已绑定到本 scope 的某个 child(归一化后完全相同的任务)→ 复用它,
|
|
6771
|
+
* 不新建、不投递;绑定的不是最近 child 时同样按绑定续作;
|
|
6772
|
+
* ⚠ 没有该任务绑定时**不再**投向「最近一个 child」——不同 prompt 必须新建独立
|
|
6773
|
+
* child,绝不隐式 steer;
|
|
6552
6774
|
* 2. 内存无 child:尝试从持久化 childModels 恢复同 parentId+role+route 的
|
|
6553
|
-
* continuable child
|
|
6554
|
-
* 3.
|
|
6555
|
-
*
|
|
6775
|
+
* continuable child(重启恢复;旧记录无标记时忽略),恢复后走统一投递分支;
|
|
6776
|
+
* 3. 其余情况(不同 prompt / route 已变 / 恢复失败 / NOT_RESUMABLE)→ 新建独立
|
|
6777
|
+
* child,并记录「本任务 key -> 新 child」绑定;新建不再清空同 route 其他 child
|
|
6778
|
+
* 的任务记忆,也不再取代它们的 recovery。
|
|
6556
6779
|
*/
|
|
6557
|
-
async function delegateBackground({ scope, taskKey, routeKey, request, parent, signal, label, queue = false, activityId, handoffExpected = false, rootToken }) {
|
|
6780
|
+
async function delegateBackground({ scope, taskKey, routeKey, request, parent, signal, label, queue = false, activityId, handoffExpected = false, rootToken, explicitChildId, continuationChildId }) {
|
|
6558
6781
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
6782
|
+
// 只有「指向既有 child 的路径」才允许取代该 child 未接受的 recovery;
|
|
6783
|
+
// 新建独立 child 必须保留其他 child 的自愈链(多 child 语义)。
|
|
6784
|
+
const explicitContinue = explicitChildId !== void 0 || continuationChildId !== void 0;
|
|
6559
6785
|
const current = delegationTracker.getChild(scope);
|
|
6560
6786
|
// 记录可能被替换的旧 child;只有新 child 的 startContinuable 返回
|
|
6561
6787
|
// accepted messageId 后,才会对其未接受 recovery 做 supersede。
|
|
6562
|
-
|
|
6788
|
+
// 显式续作/相同任务复用不新建 child,因此不会取代任何其他 child 的 recovery。
|
|
6789
|
+
let retiredChildId = explicitChildId ?? continuationChildId ?? current?.childId;
|
|
6563
6790
|
let retiredRecord = retiredChildId === void 0 ? void 0 : recoveryRecords.get(retiredChildId);
|
|
6564
|
-
if (
|
|
6565
|
-
|
|
6566
|
-
|
|
6567
|
-
|
|
6568
|
-
|
|
6569
|
-
|
|
6570
|
-
|
|
6571
|
-
|
|
6572
|
-
|
|
6573
|
-
|
|
6574
|
-
|
|
6575
|
-
if (reused.reused !== true) persistChildDispatch(reused.subagentId, reusedRecord, request, label, reused.messageId);
|
|
6576
|
-
return reused;
|
|
6577
|
-
}
|
|
6791
|
+
if (explicitChildId !== void 0) {
|
|
6792
|
+
// root 显式指定 childId:续作只发给该 child,绝不落到新建分支。
|
|
6793
|
+
const continued = await continueExplicitChild({ scope, taskKey, routeKey, request, parent, signal, label, queue, handoffExpected, rootToken, target: { childId: explicitChildId, record: retiredRecord, routeKey } });
|
|
6794
|
+
if (continued !== null) return continued;
|
|
6795
|
+
} else if (continuationChildId !== void 0) {
|
|
6796
|
+
// 相同 prompt 复用它自己的 child(可能是同 scope 下更早的独立 child,也可能
|
|
6797
|
+
// 就是最近一个 child):两种情况都必须先解析出那个 child,绝不新建。
|
|
6798
|
+
const boundRecord = recoveryRecords.get(continuationChildId);
|
|
6799
|
+
const boundRouteKey = delegationTracker.getTaskChild(scope, taskKey)?.routeKey ?? routeKey;
|
|
6800
|
+
const reusedEarlier = await continueExplicitChild({ scope, taskKey, routeKey: boundRouteKey, request, parent, signal, label, queue, handoffExpected, rootToken, target: { childId: continuationChildId, record: boundRecord, routeKey: boundRouteKey } });
|
|
6801
|
+
if (reusedEarlier !== null) return reusedEarlier;
|
|
6578
6802
|
} else if (current === void 0) {
|
|
6579
6803
|
// 重启后内存为空:从持久化快照按 parentId+role+route 恢复可复用 child。
|
|
6580
6804
|
const restored = restoreChildFromSnapshot(parent.id, role, routeKey);
|
|
@@ -6584,7 +6808,7 @@ export default {
|
|
|
6584
6808
|
// 只恢复 child 与 route,不恢复任务记录:重启后无法确认旧任务是否已执行,
|
|
6585
6809
|
// 相同任务也走 steer 排队(明确告知父代理),而不是静默复用。
|
|
6586
6810
|
delegationTracker.setChild(scope, { childId: restored, routeKey });
|
|
6587
|
-
const reused = await reuseOrSteer({ scope, childId: restored, taskKey, promptText: request.prompt[0].text, promptContent: request.prompt, parent, signal, queue, activityId, handoffExpected, rootToken });
|
|
6811
|
+
const reused = await reuseOrSteer({ scope, childId: restored, taskKey, promptText: request.prompt[0].text, promptContent: request.prompt, parent, signal, queue, activityId, handoffExpected, rootToken, continuationRouteKey: routeKey });
|
|
6588
6812
|
if (reused !== null) {
|
|
6589
6813
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
6590
6814
|
if (activityId !== void 0) delegationTracker.releaseActiveTask(activityId);
|
|
@@ -6616,12 +6840,22 @@ export default {
|
|
|
6616
6840
|
pendingCreations.push(pendingCreation);
|
|
6617
6841
|
let acceptedChildId;
|
|
6618
6842
|
try {
|
|
6619
|
-
|
|
6620
|
-
|
|
6621
|
-
|
|
6622
|
-
|
|
6623
|
-
|
|
6624
|
-
|
|
6843
|
+
let childId;
|
|
6844
|
+
let messageId;
|
|
6845
|
+
try {
|
|
6846
|
+
({ childId, messageId } = await subagents.startContinuable({
|
|
6847
|
+
provider: "spawn",
|
|
6848
|
+
label,
|
|
6849
|
+
request,
|
|
6850
|
+
signal,
|
|
6851
|
+
}));
|
|
6852
|
+
} catch (error) {
|
|
6853
|
+
// 容量耗尽在 admission 边界就翻译成 DEG 自有可读错误:后续清理/回滚错误
|
|
6854
|
+
// 一旦覆盖原始 code,上层就无法再归入「可重试的容量」而是泛化失败。
|
|
6855
|
+
const capacityError = createSubagentCapacityError(error);
|
|
6856
|
+
if (capacityError !== undefined) throw capacityError;
|
|
6857
|
+
throw error;
|
|
6858
|
+
}
|
|
6625
6859
|
acceptedChildId = childId;
|
|
6626
6860
|
if (typeof childId !== "string" || childId.length === 0 || typeof messageId !== "string" || messageId.length === 0) throw new Error("startContinuable returned an invalid acceptance");
|
|
6627
6861
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
@@ -6634,15 +6868,18 @@ export default {
|
|
|
6634
6868
|
throw new Error("root generation is no longer live");
|
|
6635
6869
|
}
|
|
6636
6870
|
if (pendingHandoffAdmission !== void 0) bindPendingHandoffAdmission(pendingHandoffAdmission, childId, messageId);
|
|
6637
|
-
//
|
|
6638
|
-
//
|
|
6639
|
-
//
|
|
6640
|
-
|
|
6871
|
+
// 多 child 边界:不同任务的独立 child 并存,因此**只有显式指定/复用同一
|
|
6872
|
+
// child 的路径**才取代该 child 未 acceptance 的 recovery。新建独立 child
|
|
6873
|
+
// 绝不 supersede 其他 child 的 recovery(否则会打断那个 child 的自愈链)。
|
|
6874
|
+
// 复用/续作路径由 reuseOrSteer / continueExplicitChild 自己完成取代。
|
|
6875
|
+
if (explicitContinue === true && retiredChildId !== void 0 && retiredChildId !== childId) {
|
|
6641
6876
|
supersedePendingRecoveryOps(retiredRecord ?? recoveryRecords.get(retiredChildId));
|
|
6642
6877
|
}
|
|
6643
6878
|
delegationTracker.setChild(scope, { childId, routeKey });
|
|
6644
6879
|
if (activityId !== void 0) delegationTracker.bindActiveTask(activityId, childId, messageId);
|
|
6645
|
-
|
|
6880
|
+
// 任务记忆必须带上它自己的 child:相同 prompt 之后复用的是这个 child,
|
|
6881
|
+
// 而不是本 scope 最近一次新建的 child。
|
|
6882
|
+
delegationTracker.rememberTask(scope, taskKey, { childId, routeKey });
|
|
6646
6883
|
// P3 防御:agent/created 应已消费预登记项;异常路径(未命中)时清理
|
|
6647
6884
|
// 残留,防止下次同 scope 新建误匹配旧 taskKey。
|
|
6648
6885
|
const staleIdx = pendingCreations.indexOf(pendingCreation);
|
|
@@ -6707,15 +6944,29 @@ export default {
|
|
|
6707
6944
|
/**
|
|
6708
6945
|
* 在同父代理的短临界区内完成范围预检和活动登记,再释放该锁执行实际
|
|
6709
6946
|
* start/sendMessage。这样不同角色的独立任务仍并行,但相交范围无法
|
|
6710
|
-
*
|
|
6711
|
-
*
|
|
6947
|
+
* 同时穿过空登记表。同一任务(或显式 childId 续作)沿用既有复用/续作语义,
|
|
6948
|
+
* 不再登记第二个活动项;**不同任务**则各自登记独立活动项并新建独立 child,
|
|
6949
|
+
* 因此多个独立 child 的范围冲突仍由 affectedPaths 预检覆盖。
|
|
6950
|
+
* admission 失败会立即释放本次预登记。
|
|
6712
6951
|
*/
|
|
6713
|
-
async function delegateWithScopeAdmission({ scope, taskKey, routeKey, request, parent, signal, label, queue = false, affectedPaths, allowOverlap = false, handoffExpected = false, rootToken }) {
|
|
6952
|
+
async function delegateWithScopeAdmission({ scope, taskKey, routeKey, request, parent, signal, label, queue = false, affectedPaths, allowOverlap = false, handoffExpected = false, rootToken, explicitChildId }) {
|
|
6714
6953
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
6715
6954
|
const current = delegationTracker.getChild(scope);
|
|
6716
|
-
|
|
6955
|
+
// 显式 childId 在上层已经校验过归属,因此它天然是「已存在目标」;其余情况
|
|
6956
|
+
// 只有「同一归一化任务仍绑定到本 scope 的 child」才算重复任务。绑定指向的
|
|
6957
|
+
// child 已从本 scope 退出(重建/清理过)时按新任务处理,避免对消失的 child
|
|
6958
|
+
// 反复返回无法续作的 advisory。
|
|
6959
|
+
const bound = delegationTracker.getTaskChild(scope, taskKey);
|
|
6960
|
+
const boundIsLive = bound !== void 0 && trackerChildIdsForScope(scope, taskKey, { parent }).includes(bound.childId);
|
|
6961
|
+
const knownDuplicate = explicitChildId !== void 0
|
|
6962
|
+
|| (boundIsLive && bound.routeKey === routeKey);
|
|
6717
6963
|
if (knownDuplicate) {
|
|
6718
|
-
return delegateBackground({
|
|
6964
|
+
return delegateBackground({
|
|
6965
|
+
scope, taskKey, routeKey, request, parent, signal, label, queue, handoffExpected, rootToken,
|
|
6966
|
+
explicitChildId,
|
|
6967
|
+
// 相同任务一律按「它自己绑定的 child」续作(可能就是最近 child)。
|
|
6968
|
+
continuationChildId: explicitChildId === void 0 && boundIsLive ? bound.childId : void 0,
|
|
6969
|
+
});
|
|
6719
6970
|
}
|
|
6720
6971
|
const admission = await delegationTracker.serializeParent(parent.id, () => {
|
|
6721
6972
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) throw new Error("root generation is no longer live");
|
|
@@ -6741,7 +6992,7 @@ export default {
|
|
|
6741
6992
|
}
|
|
6742
6993
|
try {
|
|
6743
6994
|
const outcome = await delegateBackground({
|
|
6744
|
-
scope, taskKey, routeKey, request, parent, signal, label, queue, activityId: admission.activityId, handoffExpected, rootToken,
|
|
6995
|
+
scope, taskKey, routeKey, request, parent, signal, label, queue, activityId: admission.activityId, handoffExpected, rootToken, explicitChildId,
|
|
6745
6996
|
});
|
|
6746
6997
|
if (!host.lineage.isLiveGeneration(parent, rootToken)) {
|
|
6747
6998
|
delegationTracker.releaseActiveTask(admission.activityId);
|
|
@@ -6904,7 +7155,15 @@ export default {
|
|
|
6904
7155
|
queue: {
|
|
6905
7156
|
type: "boolean",
|
|
6906
7157
|
default: false,
|
|
6907
|
-
description: "
|
|
7158
|
+
description: "Only meaningful together with childId (an explicit continuation): queue=true delivers the follow-up through the public subagents.sendMessage path and never requests a cancel; queue=false may first request a public interrupt for an explicit pause/redirect. Without childId the value is ignored because a different prompt always starts an independent child. This is not a waiting mechanism; DSH delivers feedback later.",
|
|
7159
|
+
},
|
|
7160
|
+
childId: {
|
|
7161
|
+
type: "string",
|
|
7162
|
+
description: "Optional explicit continuation handle: the subagentId returned by an earlier role-tool admission. When set, this prompt is delivered to exactly that child. Omit it to dispatch a brand-new independent task: a different prompt never continues or redirects an existing child on its own.",
|
|
7163
|
+
},
|
|
7164
|
+
cancelChildId: {
|
|
7165
|
+
type: "string",
|
|
7166
|
+
description: "Optional explicit cancel handle: request cancellation of exactly this child (public subagents.interrupt) without dispatching a task or sending any message. Takes precedence over childId. Cancelling is always addressed by an exact childId; this tool never guesses a target from the parent session and role, so other independent children stay running.",
|
|
6908
7167
|
},
|
|
6909
7168
|
},
|
|
6910
7169
|
output: {
|
|
@@ -6958,17 +7217,56 @@ export default {
|
|
|
6958
7217
|
message: { type: "string", required: true },
|
|
6959
7218
|
},
|
|
6960
7219
|
},
|
|
7220
|
+
{
|
|
7221
|
+
// 显式句柄(childId / cancelChildId)在 admission 之前被拒绝:没有登记新
|
|
7222
|
+
// admission、没有创建或投递任何 child,因此**不带** admissionEpoch/
|
|
7223
|
+
// admissionToken。用独立 kind 与带凭据的 advisory/continuable 明确区分:
|
|
7224
|
+
// 伪造凭据会让模型把它当成真实 child admission 并拿去 finalize。
|
|
7225
|
+
type: "object",
|
|
7226
|
+
additionalProperties: false,
|
|
7227
|
+
properties: {
|
|
7228
|
+
kind: { type: "string", required: true, const: "rejected" },
|
|
7229
|
+
started: { type: "boolean", required: true, const: false },
|
|
7230
|
+
accepted: { type: "boolean", required: true, const: false },
|
|
7231
|
+
reason: { type: "string", required: true },
|
|
7232
|
+
code: { type: "string", required: true },
|
|
7233
|
+
warning: { type: "string", required: true },
|
|
7234
|
+
},
|
|
7235
|
+
},
|
|
7236
|
+
{
|
|
7237
|
+
// 显式取消(cancelChildId)的结果:只报告按 childId 定位的取消请求,
|
|
7238
|
+
// 既不是新 admission 也不是失败,因此保持独立变体。
|
|
7239
|
+
type: "object",
|
|
7240
|
+
additionalProperties: false,
|
|
7241
|
+
properties: {
|
|
7242
|
+
kind: { type: "string", required: true, const: "cancelled" },
|
|
7243
|
+
started: { type: "boolean", required: true, const: false },
|
|
7244
|
+
accepted: { type: "boolean", required: true, const: true },
|
|
7245
|
+
cancelled: { type: "boolean", required: true, const: true },
|
|
7246
|
+
childId: { type: "string", required: true },
|
|
7247
|
+
},
|
|
7248
|
+
},
|
|
6961
7249
|
],
|
|
6962
7250
|
},
|
|
6963
7251
|
render(_args, value) {
|
|
6964
7252
|
// admissionEpoch/admissionToken 是 root-only finalize 收口必需的公开凭据,必须
|
|
6965
7253
|
// 出现在模型可见的 render 文本里:epoch 是模块级单调计数器(跨会话累计、重启
|
|
6966
|
-
// 归零),模型既无法从其他工具返回中读到、也无法推断;schema
|
|
6967
|
-
//
|
|
7254
|
+
// 归零),模型既无法从其他工具返回中读到、也无法推断;schema 的 continuable/
|
|
7255
|
+
// advisory/failure 三个变体都把它们标注为 required,但只渲染人性化文案会让模型
|
|
7256
|
+
// 只能靠猜 token 反复调用 finalize
|
|
6968
7257
|
// (线上实测:连续 5 次匹配失败)。这里统一追加,保持单行紧凑文本。
|
|
6969
|
-
|
|
7258
|
+
// 取消结果不携带 admission 凭据(它不进 admission 批次),因此只在凭据
|
|
7259
|
+
// 确实存在时追加后缀;其余变体保持既有文案与凭据位置不变。
|
|
7260
|
+
const admission = Number.isSafeInteger(value.admissionEpoch)
|
|
7261
|
+
? ' (admissionEpoch: ' + value.admissionEpoch + ', admissionToken: "' + value.admissionToken + '")'
|
|
7262
|
+
: "";
|
|
6970
7263
|
if (value.kind === "advisory") return [{ type: "text", text: value.warning + admission }];
|
|
7264
|
+
// 显式句柄在 admission 之前被拒绝:没有 admission 凭据可渲染,只报可读原因。
|
|
7265
|
+
if (value.kind === "rejected") return [{ type: "text", text: value.warning }];
|
|
6971
7266
|
if (value.kind === "failure") return [{ type: "text", text: `${role} admission failed: ${value.message}${admission}` }];
|
|
7267
|
+
// 取消是按 childId 定位的独立动作:文案必须点名被取消的 child,避免模型
|
|
7268
|
+
// 以为这是对「当前角色」的批量操作。
|
|
7269
|
+
if (value.kind === "cancelled") return [{ type: "text", text: `cancelled ${role} subagent ${value.childId}: cancel requested for the exact childId${admission}` }];
|
|
6972
7270
|
const notice = typeof value.scopeWarning === "string" && value.scopeWarning.length > 0
|
|
6973
7271
|
? [{ type: "text", text: value.scopeWarning }]
|
|
6974
7272
|
: [];
|
|
@@ -6996,6 +7294,48 @@ export default {
|
|
|
6996
7294
|
if (parent.session?.header?.parentSession !== void 0) {
|
|
6997
7295
|
throw new Error(`${role} is root-only; child agents are leaf workers and must report to their parent`);
|
|
6998
7296
|
}
|
|
7297
|
+
// 显式句柄(cancelChildId / childId)的输入边界:字段只要**存在**就必须是合法的
|
|
7298
|
+
// 非空、非纯空白字符串。空串/纯空白/非字符串一律 fail-closed,绝不被当作「未提供」
|
|
7299
|
+
// 而继续普通派发或新建 child。校验发生在 beginRootAdmission 之前:被拒绝的句柄不
|
|
7300
|
+
// 登记任何 admission、不产生凭据、也绝不 interrupt 或派发(见 rejectedHandleResult)。
|
|
7301
|
+
const cancelHandle = readExplicitHandle(args, "cancelChildId");
|
|
7302
|
+
if (cancelHandle.invalid === true) {
|
|
7303
|
+
return rejectedHandleResult(
|
|
7304
|
+
"invalid-child-id",
|
|
7305
|
+
"INVALID_CANCEL_CHILD_ID",
|
|
7306
|
+
role + " 取消被拒绝:cancelChildId 必须是非空字符串(收到 " + describeHandleValue(args?.cancelChildId)
|
|
7307
|
+
+ ");本次调用没有取消任何 child、也没有派发任何任务。要取消请传入此前回执里的 subagentId,"
|
|
7308
|
+
+ "或者完全省略 cancelChildId",
|
|
7309
|
+
);
|
|
7310
|
+
}
|
|
7311
|
+
const continueHandle = readExplicitHandle(args, "childId");
|
|
7312
|
+
if (continueHandle.invalid === true) {
|
|
7313
|
+
return rejectedHandleResult(
|
|
7314
|
+
"invalid-child-id",
|
|
7315
|
+
"INVALID_CHILD_ID",
|
|
7316
|
+
role + " 续作被拒绝:childId 必须是非空字符串(收到 " + describeHandleValue(args?.childId)
|
|
7317
|
+
+ ");本条 prompt 没有派发。要续作请传入此前回执里的 subagentId,或完全省略 childId 派发新任务",
|
|
7318
|
+
);
|
|
7319
|
+
}
|
|
7320
|
+
// 显式取消(cancelChildId)优先于续作 childId,并且在 beginRootAdmission **之前**
|
|
7321
|
+
// 处理:它只按 childId 精确定位并请求取消,不派发任务、不投递消息、不登记新
|
|
7322
|
+
// admission,因此既不产生 finalize 需要收口的 token,也不会把 root 的当前
|
|
7323
|
+
// admission 批次留成未结算状态。缺少前置条件时 fail-closed。
|
|
7324
|
+
// 未知/越权目标返回无凭据的 rejected:它同样没有登记 admission,用带凭据的
|
|
7325
|
+
// advisory 会伪造出「已为这个 child 开了一批要 finalize 的 admission」的假象。
|
|
7326
|
+
if (cancelHandle.present === true) {
|
|
7327
|
+
if (!spawnProviderReady()) {
|
|
7328
|
+
throw new Error(`subagent provider "spawn" is not available (missing depthLimit/toolFilter/persona/prepareContinuable); the ${role} expert tool cannot cancel a child`);
|
|
7329
|
+
}
|
|
7330
|
+
const cancelled = await cancelExplicitChild({
|
|
7331
|
+
childId: cancelHandle.value,
|
|
7332
|
+
parent,
|
|
7333
|
+
scope: delegationScopeKey(parent.id, role),
|
|
7334
|
+
});
|
|
7335
|
+
return cancelled.ok === true
|
|
7336
|
+
? { kind: "cancelled", started: false, accepted: true, cancelled: true, childId: cancelled.childId }
|
|
7337
|
+
: rejectedHandleResult("child-not-found", "CHILD_NOT_FOUND", cancelled.warning);
|
|
7338
|
+
}
|
|
6999
7339
|
const admissionTicket = beginRootAdmission(parent);
|
|
7000
7340
|
let failurePhase = "provider";
|
|
7001
7341
|
try {
|
|
@@ -7105,6 +7445,27 @@ export default {
|
|
|
7105
7445
|
// run_in_background 只保留为兼容输入;省略、true、false 都统一走
|
|
7106
7446
|
// 非阻塞 admission。是否结束当前 root turn 只由 continue_parent_turn 决定。
|
|
7107
7447
|
const handoffExpected = args.continue_parent_turn !== true;
|
|
7448
|
+
// 显式续作句柄:只接受本 root 该角色已登记的 childId。校验失败直接返回
|
|
7449
|
+
// advisory,绝不回落到「当前 scope 最近 child」或新建 child。
|
|
7450
|
+
// 续作句柄的存在性/合法性已在上面的 pre-admission 边界判定:这里 present 即
|
|
7451
|
+
// 一定是合法的非空字符串,非法形态永远不会走到这一步(不会静默变成新建)。
|
|
7452
|
+
const continueRequested = continueHandle.present === true;
|
|
7453
|
+
const resolvedContinue = continueRequested
|
|
7454
|
+
? resolveContinueTarget({ childId: continueHandle.value, parent, scope, taskKey, currentRouteKey: routeKey })
|
|
7455
|
+
: { target: void 0, warning: "" };
|
|
7456
|
+
if (continueRequested && resolvedContinue.target === void 0) {
|
|
7457
|
+
const warning = resolvedContinue.warning;
|
|
7458
|
+
return {
|
|
7459
|
+
kind: "advisory",
|
|
7460
|
+
started: false,
|
|
7461
|
+
accepted: false,
|
|
7462
|
+
reason: "child-not-found",
|
|
7463
|
+
code: "CHILD_NOT_FOUND",
|
|
7464
|
+
warning,
|
|
7465
|
+
admissionEpoch: admissionTicket.epoch,
|
|
7466
|
+
admissionToken: admissionTicket.token,
|
|
7467
|
+
};
|
|
7468
|
+
}
|
|
7108
7469
|
|
|
7109
7470
|
// 所有输入形态都只等待 scope/admission、必要的 child 投递和 Goal pause CAS,
|
|
7110
7471
|
// 绝不等待 child 的最终文本、turn/end、自动恢复或 feedback。
|
|
@@ -7113,9 +7474,10 @@ export default {
|
|
|
7113
7474
|
scope, taskKey, routeKey, request, parent, signal: exec.signal, label: args.description,
|
|
7114
7475
|
queue: args.queue === true, affectedPaths: args.affectedPaths, allowOverlap: args.allowOverlap === true,
|
|
7115
7476
|
handoffExpected, rootToken,
|
|
7477
|
+
explicitChildId: resolvedContinue.target?.childId,
|
|
7116
7478
|
})
|
|
7117
7479
|
).then((outcome) => {
|
|
7118
|
-
// role tool 只返回 admission 结果;
|
|
7480
|
+
// role tool 只返回 admission 结果;root turn 等待由显式 finalize 处理。
|
|
7119
7481
|
const admissionFields = { admissionEpoch: admissionTicket.epoch, admissionToken: admissionTicket.token };
|
|
7120
7482
|
const visibleOutcome = outcome.kind === "advisory"
|
|
7121
7483
|
? { ...outcome, ...admissionFields }
|
|
@@ -7391,7 +7753,7 @@ export default {
|
|
|
7391
7753
|
const text = [
|
|
7392
7754
|
`Enabled expert tools: ${routingToolsText || "none"}.`,
|
|
7393
7755
|
...(config.enableObserver === true ? [
|
|
7394
|
-
"Image tasks may use observer
|
|
7756
|
+
"Image tasks may use observer only when the current image routing policy allows it, and observer accepts only the Host-provided durable image attachment for that task; a client file path is never a substitute. Automatic image routing follows the fixed visual-only task contract; any role tool may receive a direct image attachment when its selected model explicitly supports image; preserve durable PNG attachment boundaries. Only pass the image parameter when forwarding a real image attachment; omit it entirely otherwise and never fabricate placeholder attachment metadata.",
|
|
7395
7757
|
] : []),
|
|
7396
7758
|
].join(" ");
|
|
7397
7759
|
routingDisposer = systemPrompt.section({ name: "dsh-expert-group:routing", order: 117, text: rootPromptText(text) });
|
|
@@ -8555,16 +8917,14 @@ export default {
|
|
|
8555
8917
|
}
|
|
8556
8918
|
const retriedTask = fanoutHost.getTask(parentTaskId);
|
|
8557
8919
|
// 手工重试会把已终态任务带回 pending(fanout.js 的 retryShard 是唯一入口,
|
|
8558
|
-
// 只有本 RPC 调用它),而首次 settle
|
|
8559
|
-
//
|
|
8560
|
-
// 驱动 <goal_round> 续跑,与「等待 fan-out 结果」冲突。
|
|
8920
|
+
// 只有本 RPC 调用它),而首次 settle 时该父任务**上一代次**的等待工作已经结算。
|
|
8921
|
+
// 若这里不重新登记,root turn 就没有任何等待依据,会在重试的分片跑完前收口。
|
|
8561
8922
|
//
|
|
8562
|
-
//
|
|
8563
|
-
//
|
|
8564
|
-
// cutoff 判定为「不是新原因」,从而立刻把 goal 恢复 armed(retry 任务没有屏障)。
|
|
8923
|
+
// 登记走**新代次**(fanout:<parentTaskId>:<attempt+1>),而不是复用旧键:复用旧键
|
|
8924
|
+
// 会让「retry 期间的新工作」与「已结算的旧工作」无法区分,从而在分片跑完前放行。
|
|
8565
8925
|
// retry 成功后的任务是 pending,不会被终态守卫跳过;同 root 的 duplicate submit
|
|
8566
|
-
// 仍由 records
|
|
8567
|
-
//
|
|
8926
|
+
// 仍由 records 的未释放状态幂等短路。retry 任务成功/失败/取消都会由 manager 聚合
|
|
8927
|
+
// 出 task_settled → releaseFanoutGoalHandoff 结算它自己的代次。
|
|
8568
8928
|
if (result?.accepted === true && (body.action === "fanout-retry-shard" || body.action === "fanout-retry")) {
|
|
8569
8929
|
registerFanoutRetryGoalHandoff(parent, parentTaskId, retriedTask);
|
|
8570
8930
|
}
|
|
@@ -9078,9 +9438,11 @@ export default {
|
|
|
9078
9438
|
/**
|
|
9079
9439
|
* 宿主能力矩阵。
|
|
9080
9440
|
*
|
|
9081
|
-
* -
|
|
9082
|
-
*
|
|
9083
|
-
*
|
|
9441
|
+
* - rootTurnWait 描述 root turn 等待所依赖的宿主 seam:权威档是
|
|
9442
|
+
* `subagents.listDescendants`(**唯一**能证明「没有 running 后代」的 seam),
|
|
9443
|
+
* 降级档是 `workspace/session-activity` waterfall(只能报告 activity,不能证明
|
|
9444
|
+
* quiet)。两档都无法证明静止时一律继续等待(fail-closed,绝不把未知当成无人
|
|
9445
|
+
* 运行);专家派发与设置页继续可用,降级由 status/degradation 字段显式说明。
|
|
9084
9446
|
* - Connection RPC 是**可选能力**:缺失时回落 legacy exact route,无法建立通道时
|
|
9085
9447
|
* fail-closed(legacy 拒绝并返回 503),状态与失败类别都从固定枚举取值。
|
|
9086
9448
|
* - storageDomain 是运行期硬依赖;attachments / sessionQuery 是可选能力,缺失时
|
|
@@ -9089,8 +9451,28 @@ export default {
|
|
|
9089
9451
|
* 只读:不调用任何业务方法、不触发注册、不写入任何状态。
|
|
9090
9452
|
*/
|
|
9091
9453
|
function describeHostCapabilities() {
|
|
9092
|
-
const goalCapability = probeServiceCapability(goals, ["get", "pause", "resume"]);
|
|
9093
9454
|
const storageState = storageBinding.describe();
|
|
9455
|
+
// root turn 等待的后代查询能力**分两档**,绝不能只把「ctx.waterfall 是函数」当成
|
|
9456
|
+
// provider 可用(那只能证明 Cordis 事件服务在,不能证明有任何 provider):
|
|
9457
|
+
// - `available`:`subagents.listDescendants` 存在——权威、可证明「没有 running 后代」;
|
|
9458
|
+
// - `degraded`:只有 waterfall——它**只能报告 activity,不能证明 quiet**:
|
|
9459
|
+
// 唯一可用的明确结论是「确有 running 后代」(用于继续等待);sentinel、任何
|
|
9460
|
+
// 空数组(含其他 listener 返回的 fresh `[]`)、无 subagent 族与 malformed 都
|
|
9461
|
+
// 是未知,等待继续;
|
|
9462
|
+
// - `unavailable`:两者都没有,等待一律 fail-closed。
|
|
9463
|
+
// 严格 Context 对未声明属性抛错,因此读取本身也要 fail-closed。
|
|
9464
|
+
let descendantListingAvailable = false;
|
|
9465
|
+
try {
|
|
9466
|
+
descendantListingAvailable = typeof subagents?.listDescendants === "function";
|
|
9467
|
+
} catch {
|
|
9468
|
+
descendantListingAvailable = false;
|
|
9469
|
+
}
|
|
9470
|
+
let sessionActivityAvailable = false;
|
|
9471
|
+
try {
|
|
9472
|
+
sessionActivityAvailable = typeof ctx.waterfall === "function";
|
|
9473
|
+
} catch {
|
|
9474
|
+
sessionActivityAvailable = false;
|
|
9475
|
+
}
|
|
9094
9476
|
const connectionStatus = connectionChannelTransport === "handle"
|
|
9095
9477
|
? "available"
|
|
9096
9478
|
: connectionChannelTransport === "route"
|
|
@@ -9109,12 +9491,17 @@ export default {
|
|
|
9109
9491
|
webServer: hardDependencyCapability(webServer),
|
|
9110
9492
|
systemPrompt: hardDependencyCapability(systemPrompt),
|
|
9111
9493
|
llm: hardDependencyCapability(llm),
|
|
9112
|
-
//
|
|
9113
|
-
|
|
9494
|
+
// rootTurnWait:可选宿主 seam;缺失时等待判定一律 fail-closed(继续等待)。
|
|
9495
|
+
rootTurnWait: {
|
|
9114
9496
|
required: false,
|
|
9115
|
-
status:
|
|
9116
|
-
|
|
9117
|
-
|
|
9497
|
+
status: descendantListingAvailable
|
|
9498
|
+
? "available"
|
|
9499
|
+
: sessionActivityAvailable ? "degraded" : "unavailable",
|
|
9500
|
+
degradation: descendantListingAvailable
|
|
9501
|
+
? null
|
|
9502
|
+
: sessionActivityAvailable
|
|
9503
|
+
? "root-turn-wait-descendant-listing-unavailable"
|
|
9504
|
+
: "root-turn-wait-descendant-query-unavailable",
|
|
9118
9505
|
},
|
|
9119
9506
|
// Connection RPC:可选能力,缺失时回落 legacy route。
|
|
9120
9507
|
connectionRpc: {
|