@suifei/dsh-ai-team 0.4.137 → 0.4.139

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/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.4.139 - 2026-11-20
4
+
5
+ **Grok 4.7 不再在第一条回复前报 HTTP 400;热重载时归档修复只跑一次**
6
+
7
+ - Grok 4.7(#88,感谢 @TardisBooo):11 个 SkillOpt 工具的 `parameters` 是裸属性表(`{ project: { type: 'string' } }`),不是对象 JSON Schema。这种写法只对宿主的 `defineTool()` 有效(它会先编译);插件直接 `tools.register()`,内置 SkillOpt 的 `defineTool` 又是原样透传,所以裸属性表原样发给了模型。Grok 4.7 严格校验,整个请求 400;Qwen、DeepSeek 一直容忍。现在都包成 `{ type: 'object', properties }`;参数里没有 `required` / `enum`,参数名与含义不变。实测:直连 Grok 4.7,修复前 11 个工具单发各 400,修复后 12 个工具一起发 200;DSH 宿主里成员路由到 Grok 4.7,修复前第一步 `400 invalid_request_error`,修复后回合正常结束。Qwen 修复前后都正常,调 `skillopt_rubric` 时 `dim8` 从字符串 `"7"` 变成数字 `7`(模型现在看得懂参数类型)。
8
+ - 回归测试 `test/tool-schemas.test.js`:走插件真实的 `apply()`,捕获插件注册的**每一个**工具(含 index.js 自己注册的 `skillopt_rubric` / `judge` / `optimize` / `jobs`,以及以后新加的),逐个断言是对象 schema;单独断言按 Agent 注册的 `team` 工具。退掉 #88 任一处修复,测试都会失败。
9
+ - 归档修复只跑一次(`repairOnce`,`lib/runtime/host-repair.js`):启动 tick、取 PMO 会话、回合被拦会并发调用修复,旧写法在 `await` 之前只查「修好没」,几路都通过,同一批会话被解档、PMO 被归入工作区好几遍(il2c 每次热重载 3 行 `host.repair.ok`)。现在修好之前同一时刻只跑一次,并发调用共享这一次;没修成(如工作区注册服务未就绪)下次照常重跑。实测:隔离宿主热重载两次,0.4.138 写 2 / 5 / 2 行,现在 1 / 1 / 1 行。
10
+ - 测试:`test/host-repair.test.js` 新增并发共享与重跑、index.js 接线。
11
+
12
+ ## 0.4.138 - 2026-11-19
13
+
14
+ **热重载后「旧树未散」的唤醒:暂存,等成员旧回合结束再补投**
15
+
16
+ - 问题:il2c 在桌面版里把插件关再开(04:47)后,唤醒玄策连续 `UNAUTHORIZED target belongs to another subagent tree`,记成唤醒失败(11-10…11-18 零次,整机重启后零次)。
17
+ - 根因:宿主 Agent 的生命周期挂在创建它的插件作用域上,插件卸载即拆,新实例 resume 出新对象当子智能体树的根;成员重载前开的回合仍常驻在旧树下,宿主要求投递者与常驻成员同根(dsh-subagent `deliverToMember`),所以以新根投递一律被拒。官方 `subagents.prompt` 按旧根投递,旧根已不在线,同样被拒(实测)。成员回合结束、宿主把它收掉之后,下一次投递在新根下冷恢复(il2c:玄策旧回合 05:00:06 结束,14 秒后开出新回合,此后零失败)。
18
+ - 现在(`lib/runtime/stale-tree-wakes.js`):只认这一种拒绝(`isStaleTreeError`;「another parent session」血缘错配不在此列)。被拒的唤醒暂存,不往账本记失败;同一成员只留最新一条。成员会话 `turn/end` 后等 5 秒(宿主收尾)补投,另有退避定时器兜底(30 秒 → 1 → 2 → 5 → 10 分钟,封顶最后一档)。旧回合没结束时被拒不计入放弃次数;回合结束后仍连续被拒、退避用尽才放弃,按普通唤醒失败处理。补投与平时唤醒走同一段投递实现(`deliverWakePlans`);停止的项目不补投;卸载清掉全部定时器。
19
+ - 诊断日志:`wake.tree-stale`、`wake.tree-stale.redeliver`(trigger:`turn-end` / `timer`)、`wake.tree-stale.recovered`(最终投到,发布默认 `errors` 级别也落盘)、`wake.tree-stale.giveup.fail`、`wake.tree-stale.redeliver.fail`。
20
+ - 测试:新增 `test/stale-tree-wakes.test.js`(错误识别、turn/end 后补投最新计划、旧回合内被拒不耗尽、放弃只记一次、补投异常只记日志、卸载、index.js 接线)。全量 451。实机:隔离宿主里成员跑 120 秒的回合,中途关再开插件并发私信:被拒 3 次后旧回合结束,5 秒后补投成功,成员开新回合回复「三号收到」(`.ptc/rounds/r43-stale-tree.4.out`)。
21
+
3
22
  ## 0.4.137 - 2026-11-19
4
23
 
5
24
  **PMO 宿主会话里显示成员的收工汇报全文,带头像,不经模型**
package/README.md CHANGED
@@ -35,6 +35,8 @@
35
35
  - **在线人才库**(0.4.130–0.4.131):「同步在线库」从 [`@suifei/dsh-ai-team-catalog`](https://www.npmjs.com/package/@suifei/dsh-ai-team-catalog) 拉取最新的人才与团队。国内走 npmmirror 整包下载,约 1 秒同步完;逐个文件核对 sha256,失败不影响旧版本,可一键退回内置。
36
36
  - **头像**(0.4.135–0.4.136):人才市场、团队、成员卡片都有头像,由 [`@suifei/hash-avatar`](https://www.npmjs.com/package/@suifei/hash-avatar) 在本机按名字生成。这个库**不随插件打包**:插件运行时从 npm 取最新版并缓存在本机,库更新了插件不用重发,新增的种族、画风直接出现在挑选界面里。内置人才预置了参数(默认亚洲人),自定义成员和人才可以选性别、年龄、种族(人类 / 奇幻 / 动物 / 科幻共 88 种)和画风(扁平、像素、水墨等 10 种)。
37
37
  - **PMO 会话里的收工汇报**(0.4.137):成员收工后,「【项目】文渊阁·PMO」会话里直接显示它的收工汇报全文,开头带成员头像和名字,不经过模型。
38
+ - **热重载后的唤醒**(0.4.138):插件关再开(含升级)时正在跑回合的成员,暂时收不到唤醒;插件把这些唤醒暂存起来,等那个回合结束后自动补投,不再记成失败。
39
+ - **Grok 4.7 可用**(0.4.139):插件注册的工具参数都是标准的对象 JSON Schema,Grok 4.7 等严格校验工具定义的模型不再在第一条回复前报 HTTP 400(感谢 [@TardisBooo](https://github.com/TardisBooo),#88)。
38
40
  - **弹窗与人员池**(0.4.132–0.4.133):
39
41
  - 弹窗占主页面的 90%,功能按钮固定在右上角。
40
42
  - 成员资料按「资料 / 模型 / 技能 / 协作」分页签。
package/index.js CHANGED
@@ -25,7 +25,7 @@ import { ids } from './lib/domain/ids.js';
25
25
  import { MemberRuntime, validatePermissionProfile } from './lib/runtime/member-runtime.js';
26
26
  import { ensureHostAgent } from './lib/runtime/host-agent.js';
27
27
  import { activationSpec } from './lib/runtime/activation-spec.js';
28
- import { repairArchivedHosts as repairHostSessions } from './lib/runtime/host-repair.js';
28
+ import { repairArchivedHosts as repairHostSessions, repairOnce } from './lib/runtime/host-repair.js';
29
29
  import { classifyLlmFailure, nextRequestAttempt, retryDecision } from './lib/runtime/failure-policy.js';
30
30
  import { memberIdentity } from './lib/domain/member-profile.js';
31
31
  import { findSkill, findSkillText, loadSkillContext } from './lib/runtime/skill-loader.js';
@@ -57,7 +57,8 @@ import { buildModelCatalog, buildModelEfforts } from './lib/host/model-catalog.j
57
57
  import { createTeamTool } from './lib/host/member-tools.js';
58
58
  import { describeTaskContext, describeWake, planWakes } from './lib/host/waker.js';
59
59
  import { describeCauseChain } from './lib/runtime/error-chain.js';
60
- import { classifyWakeFailure, isMalformedTurnError } from './lib/runtime/wake-failure.js';
60
+ import { classifyWakeFailure, isMalformedTurnError, isStaleTreeError } from './lib/runtime/wake-failure.js';
61
+ import { createStaleTreeWakes } from './lib/runtime/stale-tree-wakes.js';
61
62
  import { registerShellGuard } from './lib/runtime/shell-guard.js';
62
63
  import { registerOneShotToolGuard, registerStopGuard } from './lib/runtime/stop-guard.js';
63
64
  import { registerTeamDiscipline } from './lib/runtime/deferral-guard.js';
@@ -792,6 +793,7 @@ export function apply(ctx, config = {}) {
792
793
  const offSessionEvent = typeof ctx.on === 'function'
793
794
  ? ctx.on('session/event', async (session, event) => {
794
795
  try { teamDiscipline.observe(session, event); } catch { /* 观察失败不影响事件流 */ }
796
+ try { staleTreeWakes.observe(session, event); } catch { /* 观察失败不影响事件流 */ }
795
797
  if (typeof session?.id === 'string') {
796
798
  if (event?.type === 'turn/start') turnsInFlight.add(session.id);
797
799
  else if (event?.type === 'turn/end') turnsInFlight.delete(session.id);
@@ -903,6 +905,18 @@ export function apply(ctx, config = {}) {
903
905
  diag.append({ ev: 'team.interrupt', projectId: projectRuntime.id, members: interrupted });
904
906
  };
905
907
  const wakeKeys = new Map();
908
+ // 热重载后「旧树未散」的唤醒:等宿主收掉成员旧回合 / 退避到点再投(lib/runtime/stale-tree-wakes.js)。
909
+ // 补投仍走 deliverWakePlans;停止的项目不补投(与自动派发同一停止门)。
910
+ const staleTreeWakes = createStaleTreeWakes({
911
+ diag,
912
+ redeliver: async ({ projectId, plan }) => {
913
+ if (disposed) return;
914
+ const runtime = projectRuntime(projectId);
915
+ if (runtime === null) return;
916
+ if (runtime.service.state.projects?.[projectId]?.runState === 'stopped') return;
917
+ await deliverWakePlans(runtime, [plan], { retry: true });
918
+ },
919
+ });
906
920
  // provider 探测状态去重:能力缺失/确认无 provider 只各记一次,避免每轮刷日志。
907
921
  let lastProviderState = '';
908
922
  // PMO tick 是 fire-and-forget:慢 tick(模型/IO)会被下一分钟的定时器再入,
@@ -1033,6 +1047,13 @@ export function apply(ctx, config = {}) {
1033
1047
  if (!key.endsWith(projectSuffix)) continue;
1034
1048
  if (Number.isSafeInteger(seq) && head - seq > 500) wakeKeys.delete(key);
1035
1049
  }
1050
+ await deliverWakePlans(projectRuntime, plans, { seq: result?.event?.seq ?? head });
1051
+ };
1052
+ /**
1053
+ * 投递一批唤醒计划(事件规划与「旧树未散」补投共用这一份实现)。
1054
+ * @param {{ seq?: number|null, retry?: boolean }} options retry:这是 staleTreeWakes 的补投
1055
+ */
1056
+ const deliverWakePlans = async (projectRuntime, plans, { seq = null, retry = false } = {}) => {
1036
1057
  const subagents = serviceOf(ctx, 'subagents');
1037
1058
  const sessions = serviceOf(ctx, 'sessions');
1038
1059
  const permissionPresets = serviceOf(ctx, 'permissionPresets');
@@ -1073,7 +1094,7 @@ export function apply(ctx, config = {}) {
1073
1094
  }
1074
1095
  // Reserve before the async delivery: the HTTP result and the ledger
1075
1096
  // event both schedule the same plan, and only one may deliver it.
1076
- wakeKeys.set(plan.key, result?.event?.seq ?? head);
1097
+ wakeKeys.set(plan.key, seq ?? projectRuntime?.ledger?.head?.seq ?? 0);
1077
1098
  const cwd = projectWorkspacePath;
1078
1099
  try {
1079
1100
  // Idle default members have no Agent session yet. A wake must
@@ -1133,6 +1154,7 @@ export function apply(ctx, config = {}) {
1133
1154
  await titleMemberSession(projectRuntime, member);
1134
1155
  persistModelSelection(member.sessionId, member.config, member.name);
1135
1156
  }
1157
+ staleTreeWakes.delivered(member.sessionId, { projectId: projectRuntime.id, memberId: plan.memberId, reason: plan.reason, messageId });
1136
1158
  await projectRuntime.service.recordWake(plan.memberId, {
1137
1159
  ok: true, taskId: plan.taskId, reason: plan.reason, messageId,
1138
1160
  }, projectRuntime.id);
@@ -1147,6 +1169,14 @@ export function apply(ctx, config = {}) {
1147
1169
  });
1148
1170
  } catch (error) {
1149
1171
  wakeKeys.delete(plan.key);
1172
+ // 热重载后「旧树未散」:成员重载前开的回合仍挂在旧插件实例的宿主 Agent 下,
1173
+ // 宿主拒绝以新宿主 Agent 投递(il2c 11-19 04:47 起 mem_coder 连续 UNAUTHORIZED)。
1174
+ // 不是会话坏了:暂存,等宿主收掉旧回合 / 退避到点再投,不记失败。
1175
+ const staleMember = projectRuntime.service.state.members?.[plan.memberId];
1176
+ if (isStaleTreeError(error) && typeof staleMember?.sessionId === 'string'
1177
+ && staleTreeWakes.defer({ sessionId: staleMember.sessionId, projectId: projectRuntime.id, memberId: plan.memberId, plan, retry })) {
1178
+ continue;
1179
+ }
1150
1180
  const causeChain = describeCauseChain(error);
1151
1181
  // 实机根因:成员会话的**写句柄没有释放**——`sessions.get()` 已取不到它,
1152
1182
  // 但 persistence 仍判定它「already owned by an active write handle」,
@@ -1593,10 +1623,13 @@ export function apply(ctx, config = {}) {
1593
1623
  name: 'skillopt_rubric',
1594
1624
  description: 'Score a SKILL.md against the 9-dimension Darwin rubric (triage only — absolute scores must not be used for keep/revert).',
1595
1625
  parameters: {
1596
- project: { type: 'string', description: 'Project directory (defaults to cwd)' },
1597
- skillPath: { type: 'string', description: 'Path to SKILL.md to score' },
1598
- dim8: { type: 'number', description: 'Measured effect score 1-10 (omit for dry-run)' },
1599
- measured: { type: 'boolean', description: 'Set when dim8 came from a real prompt run' },
1626
+ type: 'object',
1627
+ properties: {
1628
+ project: { type: 'string', description: 'Project directory (defaults to cwd)' },
1629
+ skillPath: { type: 'string', description: 'Path to SKILL.md to score' },
1630
+ dim8: { type: 'number', description: 'Measured effect score 1-10 (omit for dry-run)' },
1631
+ measured: { type: 'boolean', description: 'Set when dim8 came from a real prompt run' },
1632
+ },
1600
1633
  },
1601
1634
  // DSH 工具输出协议:render 必须返回 content 数组(与 vendored 一致)。
1602
1635
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
@@ -1618,9 +1651,12 @@ export function apply(ctx, config = {}) {
1618
1651
  name: 'skillopt_judge',
1619
1652
  description: 'Paired independent-judge verdict (N odd votes, majority) for before/after SKILL.md — the authoritative keep/revert signal.',
1620
1653
  parameters: {
1621
- project: { type: 'string', description: 'Project directory' },
1622
- beforePath: { type: 'string', description: 'Baseline file path (default: current live SKILL.md)' },
1623
- afterPath: { type: 'string', description: 'Candidate file path (default: latest staged proposal)' },
1654
+ type: 'object',
1655
+ properties: {
1656
+ project: { type: 'string', description: 'Project directory' },
1657
+ beforePath: { type: 'string', description: 'Baseline file path (default: current live SKILL.md)' },
1658
+ afterPath: { type: 'string', description: 'Candidate file path (default: latest staged proposal)' },
1659
+ },
1624
1660
  },
1625
1661
  // DSH 工具输出协议:render 必须返回 content 数组(与 vendored 一致)。
1626
1662
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
@@ -1651,9 +1687,12 @@ export function apply(ctx, config = {}) {
1651
1687
  name: 'skillopt_optimize',
1652
1688
  description: 'Start a Darwin hill-climbing job for one SKILL.md (diagnose, generate candidate, paired judge, keep/revert). The PMO tick harvests it; poll skillopt_jobs for the outcome.',
1653
1689
  parameters: {
1654
- project: { type: 'string', description: 'Project directory' },
1655
- skillPath: { type: 'string', description: 'Path to SKILL.md to optimize' },
1656
- candidate: { type: 'string', description: 'Full improved SKILL.md text. Omit to get the diagnosis + rewrite request first; pass it to start the reviewer round.' },
1690
+ type: 'object',
1691
+ properties: {
1692
+ project: { type: 'string', description: 'Project directory' },
1693
+ skillPath: { type: 'string', description: 'Path to SKILL.md to optimize' },
1694
+ candidate: { type: 'string', description: 'Full improved SKILL.md text. Omit to get the diagnosis + rewrite request first; pass it to start the reviewer round.' },
1695
+ },
1657
1696
  },
1658
1697
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
1659
1698
  async execute(args) {
@@ -1723,7 +1762,7 @@ export function apply(ctx, config = {}) {
1723
1762
  const jobsTool = guardedTools.register({
1724
1763
  name: 'skillopt_jobs',
1725
1764
  description: 'List optimize jobs (state, target dimension, verdict) for a project.',
1726
- parameters: { project: { type: 'string', description: 'Project directory' } },
1765
+ parameters: { type: 'object', properties: { project: { type: 'string', description: 'Project directory' } } },
1727
1766
  output: { schema: { type: 'string' }, render: (_args, value) => [{ type: 'text', text: String(value) }] },
1728
1767
  async execute(args) {
1729
1768
  // 主动收割:工具调用即驱动(不依赖 PMO 定时器——实测宿主热重载/
@@ -1976,8 +2015,8 @@ export function apply(ctx, config = {}) {
1976
2015
  // 模型请求(实测 453 blocked / 0 completed)。旧版本把 host 归档用于隐藏会话。
1977
2016
  let hostRepaired = false;
1978
2017
  let hostRepairWarned = false;
1979
- const repairArchivedHosts = async () => {
1980
- if (hostRepaired) return;
2018
+ // 启动 tick、ensureParent、blocked 回合会并发调用:repairOnce 保证同一时刻只跑一次。
2019
+ const repairArchivedHosts = repairOnce(async () => {
1981
2020
  try {
1982
2021
  const registry = serviceOf(ctx, 'workspaceRegistry');
1983
2022
  const repaired = await repairHostSessions({
@@ -2024,7 +2063,7 @@ export function apply(ctx, config = {}) {
2024
2063
  hostRepaired = true;
2025
2064
  diag.append({ ev: 'host.unarchive.sweep.fail', error: error?.message ?? String(error) });
2026
2065
  }
2027
- };
2066
+ }, () => hostRepaired);
2028
2067
  /**
2029
2068
  * 取项目的 PMO 会话(成员的父会话)。核心模型:一个项目一个 PMO,驻留在项目工作区;
2030
2069
  * 成员都是它的子会话,于是全部落在同一工作区。不传项目时取活动项目(skillopt 评审等
@@ -3299,6 +3338,7 @@ export function apply(ctx, config = {}) {
3299
3338
  try { disposeStopGuard(); } catch { /* already disposed */ }
3300
3339
  try { disposeOneShotToolGuard(); } catch { /* already disposed */ }
3301
3340
  try { teamDiscipline.dispose(); } catch { /* already disposed */ }
3341
+ try { staleTreeWakes.dispose(); } catch { /* already disposed */ }
3302
3342
  hostSessionGate.dispose();
3303
3343
  // 在途的 boot 也算本组合的资源:等它落定(落定时见 disposed 会自行关账本),
3304
3344
  // 否则下一组合抢在关锁之前打开同一账本。
package/lib/diaglog.js CHANGED
@@ -35,6 +35,8 @@ export function isErrorEvent(ev) {
35
35
  // 运行时恢复后复用原会话(不新建子智能体)同理:它决定「成员还会不会被唤醒」,
36
36
  // 必须在发布默认级别可见,否则只能看到失败行而不知道有没有救回来。
37
37
  || ev === 'member.session.reused'
38
+ // 热重载后「旧树未散」被暂存的唤醒最终投到了:成员是否真的收到了,只有这行能证明。
39
+ || ev === 'wake.tree-stale.recovered'
38
40
  // Human 停止时中断了哪些成员:决定「停了之后还在跑」是不是插件的锅。
39
41
  || ev === 'team.interrupt'
40
42
  // 停止期间团队会话想唤醒/派生智能体被拦下:停止是否真的停住的直接证据。
@@ -1,73 +1,92 @@
1
- /**
2
- * Repair Team Host sessions archived by earlier revisions.
3
- *
4
- * Members are subagent descendants of the Host Agent, and
5
- * `archived-session-gate` (dsh-api-session-controller) rejects every
6
- * `agent/pre-step` whose Session — or any Session above it in the subagent
7
- * lineage — is archived. The loop then ends the turn as `{kind:'blocked'}`
8
- * **without issuing a model request**, so an archived Host silently disables
9
- * the whole team (measured: 453 blocked turns, 0 completed, no `request/header`).
10
- *
11
- * Earlier revisions archived the Host on purpose to hide it from the session
12
- * list. This sweep lifts that damage by calling `unarchiveSession` for the
13
- * persisted host of each runtime and the `parentSession` of every member session.
14
- *
15
- * Two constraints learned the hard way:
16
- * 1. Use only the **documented** API. `archivedSessionIds` is not part of the
17
- * workspaceRegistry contract; gating on it silently skipped the whole
18
- * repair. `unarchiveSession` on a non-archived id resolves without writing,
19
- * so calling it unconditionally is safe and needs no read-back.
20
- * 2. Diagnostics ending without `.fail` are dropped at the default `errors`
21
- * diag level. Failure rows therefore carry `.fail`; success is proven by
22
- * the durable archive list, not by a log line.
23
- */
24
-
25
- /**
26
- * @param {{
27
- * runtimes: Iterable<any>,
28
- * sessions?: { get?: (id: string) => any },
29
- * workspaceRegistry?: { unarchiveSession?: (id: string) => Promise<void> },
30
- * diag?: { append?: (row: any) => any } | null,
31
- * knownHostSessionIds?: Iterable<string>
32
- * }} options
33
- * @returns {Promise<string[]|null>} session ids the sweep asked to unarchive;
34
- * `null` means the registry was not ready yet and the caller should retry.
35
- */
36
- export async function repairArchivedHosts(options = {}) {
37
- const registry = options.workspaceRegistry;
38
- // `workspaceRegistry` 要等 sessionPersistence 与历史 bootstrap 完成才 active,
39
- // 插件激活瞬间常常还取不到。此时返回 null(而不是空数组)让调用方保持
40
- // 「未修复」状态,等下一个 tick 重试——而不是一次失败就永久放弃。
41
- if (registry === undefined || registry === null || typeof registry.unarchiveSession !== 'function') return null;
42
-
43
- const victims = new Set();
44
- for (const known of options.knownHostSessionIds ?? []) {
45
- if (typeof known === 'string' && known !== '') victims.add(known);
46
- }
47
- for (const runtime of options.runtimes ?? []) {
48
- const hostId = runtime?.service?.state?.hostSessionId;
49
- if (typeof hostId === 'string' && hostId !== '') victims.add(hostId);
50
- for (const member of Object.values(runtime?.service?.state?.members ?? {})) {
51
- const sessionId = member?.sessionId;
52
- if (typeof sessionId !== 'string' || sessionId === '') continue;
53
- // 成员会话自己也可能被归档(例如用户手动归档了那条会话):gate 会直接
54
- // 拒绝它,只有 host 一代的解归档覆盖不到。
55
- victims.add(sessionId);
56
- try {
57
- const header = options.sessions?.get?.(sessionId)?.header;
58
- if (typeof header?.parentSession === 'string') victims.add(header.parentSession);
59
- } catch { /* member session is not live; skip */ }
60
- }
61
- }
62
-
63
- const repaired = [];
64
- for (const sessionId of victims) {
65
- try {
66
- await registry.unarchiveSession(sessionId);
67
- repaired.push(sessionId);
68
- } catch (error) {
69
- options.diag?.append?.({ ev: 'host.unarchive.fail', sessionId, message: error?.message ?? String(error) });
70
- }
71
- }
72
- return repaired;
73
- }
1
+ /**
2
+ * Repair Team Host sessions archived by earlier revisions.
3
+ *
4
+ * Members are subagent descendants of the Host Agent, and
5
+ * `archived-session-gate` (dsh-api-session-controller) rejects every
6
+ * `agent/pre-step` whose Session — or any Session above it in the subagent
7
+ * lineage — is archived. The loop then ends the turn as `{kind:'blocked'}`
8
+ * **without issuing a model request**, so an archived Host silently disables
9
+ * the whole team (measured: 453 blocked turns, 0 completed, no `request/header`).
10
+ *
11
+ * Earlier revisions archived the Host on purpose to hide it from the session
12
+ * list. This sweep lifts that damage by calling `unarchiveSession` for the
13
+ * persisted host of each runtime and the `parentSession` of every member session.
14
+ *
15
+ * Two constraints learned the hard way:
16
+ * 1. Use only the **documented** API. `archivedSessionIds` is not part of the
17
+ * workspaceRegistry contract; gating on it silently skipped the whole
18
+ * repair. `unarchiveSession` on a non-archived id resolves without writing,
19
+ * so calling it unconditionally is safe and needs no read-back.
20
+ * 2. Diagnostics ending without `.fail` are dropped at the default `errors`
21
+ * diag level. Failure rows therefore carry `.fail`; success is proven by
22
+ * the durable archive list, not by a log line.
23
+ */
24
+
25
+ /**
26
+ * @param {{
27
+ * runtimes: Iterable<any>,
28
+ * sessions?: { get?: (id: string) => any },
29
+ * workspaceRegistry?: { unarchiveSession?: (id: string) => Promise<void> },
30
+ * diag?: { append?: (row: any) => any } | null,
31
+ * knownHostSessionIds?: Iterable<string>
32
+ * }} options
33
+ * @returns {Promise<string[]|null>} session ids the sweep asked to unarchive;
34
+ * `null` means the registry was not ready yet and the caller should retry.
35
+ */
36
+ export async function repairArchivedHosts(options = {}) {
37
+ const registry = options.workspaceRegistry;
38
+ // `workspaceRegistry` 要等 sessionPersistence 与历史 bootstrap 完成才 active,
39
+ // 插件激活瞬间常常还取不到。此时返回 null(而不是空数组)让调用方保持
40
+ // 「未修复」状态,等下一个 tick 重试——而不是一次失败就永久放弃。
41
+ if (registry === undefined || registry === null || typeof registry.unarchiveSession !== 'function') return null;
42
+
43
+ const victims = new Set();
44
+ for (const known of options.knownHostSessionIds ?? []) {
45
+ if (typeof known === 'string' && known !== '') victims.add(known);
46
+ }
47
+ for (const runtime of options.runtimes ?? []) {
48
+ const hostId = runtime?.service?.state?.hostSessionId;
49
+ if (typeof hostId === 'string' && hostId !== '') victims.add(hostId);
50
+ for (const member of Object.values(runtime?.service?.state?.members ?? {})) {
51
+ const sessionId = member?.sessionId;
52
+ if (typeof sessionId !== 'string' || sessionId === '') continue;
53
+ // 成员会话自己也可能被归档(例如用户手动归档了那条会话):gate 会直接
54
+ // 拒绝它,只有 host 一代的解归档覆盖不到。
55
+ victims.add(sessionId);
56
+ try {
57
+ const header = options.sessions?.get?.(sessionId)?.header;
58
+ if (typeof header?.parentSession === 'string') victims.add(header.parentSession);
59
+ } catch { /* member session is not live; skip */ }
60
+ }
61
+ }
62
+
63
+ const repaired = [];
64
+ for (const sessionId of victims) {
65
+ try {
66
+ await registry.unarchiveSession(sessionId);
67
+ repaired.push(sessionId);
68
+ } catch (error) {
69
+ options.diag?.append?.({ ev: 'host.unarchive.fail', sessionId, message: error?.message ?? String(error) });
70
+ }
71
+ }
72
+ return repaired;
73
+ }
74
+
75
+ /**
76
+ * 归档修复的调用门:修好之前同一时刻只跑一次,并发调用共享同一个 Promise;修好后直接返回。
77
+ *
78
+ * 启动 tick、ensureParent、blocked 回合会并发调用修复;旧写法在 await 之前只查「修好没」,
79
+ * 几路都通过,同一批会话被解档、PMO 被归入工作区各三遍(il2c 11-19 04:47:11 与 09:17:32
80
+ * 热重载各三行 host.repair.ok,相隔 ≤11ms)。没修好(如 workspaceRegistry 未就绪)时,
81
+ * 下一次调用照常重跑。
82
+ * @param {() => Promise<void>} run 一次修复
83
+ * @param {() => boolean} isDone 是否已修好
84
+ */
85
+ export function repairOnce(run, isDone) {
86
+ let running = null;
87
+ return () => {
88
+ if (isDone()) return Promise.resolve();
89
+ running ??= Promise.resolve().then(run).finally(() => { running = null; });
90
+ return running;
91
+ };
92
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * 热重载后「旧树未散」的唤醒:暂存,等宿主把成员旧回合收掉后再投。
3
+ *
4
+ * 实机(il2c 2026-11-19 04:47):插件在桌面版里关闭再开启后,唤醒玄策连续
5
+ * `UNAUTHORIZED target belongs to another subagent tree`(判定见 wake-failure.js `isStaleTreeError`)。
6
+ * 成员重载前开的回合常驻在旧宿主 Agent 那棵树下,以新根投递一律被拒;官方 `subagents.prompt` 按旧根投递,
7
+ * 旧根已不在线,同样被拒(r43 第二轮)。宿主在成员回合结束、空闲且收件箱为空时把它收掉(dsh-subagent
8
+ * manager.ts `watchLocalSettlement`),之后的投递在新根下冷恢复(il2c:玄策旧回合 05:00:06 结束,
9
+ * 14 秒后开出新回合,此后零失败)。
10
+ *
11
+ * 所以:该成员会话 `turn/end` 后等 settleDelayMs(给宿主收尾)再补投(r43 第三轮:旧回合结束 5 秒后
12
+ * 补投成功,成员回「三号收到」);另有退避定时器兜底(收尾比预期慢,或没观察到 turn/end)。
13
+ * 同一会话只留最新一条计划——唤醒内容在投递时按当时状态生成,旧计划没有额外信息。
14
+ * 旧回合结束后仍被拒、退避用尽才记 `.fail`;其间不往账本记失败;最终投到记
15
+ * `wake.tree-stale.recovered`(errors 级可见)。
16
+ */
17
+
18
+ export const STALE_TREE_BACKOFF_MS = Object.freeze([30_000, 60_000, 120_000, 300_000, 600_000]);
19
+ export const STALE_TREE_SETTLE_MS = 5_000;
20
+
21
+ /**
22
+ * @param {{
23
+ * redeliver: (entry: { sessionId: string, projectId: string, memberId: string, plan: any }) => Promise<unknown>,
24
+ * diag?: { append?: (row: object) => void },
25
+ * backoffMs?: readonly number[],
26
+ * settleDelayMs?: number,
27
+ * setTimer?: (fn: () => void, ms: number) => any,
28
+ * clearTimer?: (handle: any) => void,
29
+ * }} options
30
+ */
31
+ export function createStaleTreeWakes({
32
+ redeliver, diag, backoffMs = STALE_TREE_BACKOFF_MS, settleDelayMs = STALE_TREE_SETTLE_MS,
33
+ setTimer = setTimeout, clearTimer = clearTimeout,
34
+ }) {
35
+ /** sessionId → { sessionId, projectId, memberId, plan, timer } */
36
+ const pending = new Map();
37
+ /**
38
+ * sessionId → { tries, attempts, ended }。会话出现在这里即「曾因旧树被暂存」,投到时据此记 recovered。
39
+ * tries:被拒总次数,只决定下一次间隔(封顶最后一档);attempts:旧回合结束**之后**仍被拒的次数,
40
+ * 用尽才放弃——回合没结束前被拒是预期之中(r43:2 分钟的旧回合里被拒 3 次),不该把长回合的成员耗到放弃。
41
+ */
42
+ const state = new Map();
43
+ let disposed = false;
44
+ const arm = (entry, ms, trigger) => {
45
+ clearTimer(entry.timer);
46
+ entry.timer = setTimer(() => fire(entry.sessionId, trigger), ms);
47
+ entry.timer?.unref?.();
48
+ };
49
+
50
+ const fire = (sessionId, trigger) => {
51
+ const entry = pending.get(sessionId);
52
+ if (entry === undefined || disposed) return;
53
+ pending.delete(sessionId);
54
+ clearTimer(entry.timer);
55
+ diag?.append?.({ ev: 'wake.tree-stale.redeliver', projectId: entry.projectId, memberId: entry.memberId, sessionId, trigger, tries: state.get(sessionId)?.tries ?? 0, reason: entry.plan?.reason ?? null });
56
+ Promise.resolve()
57
+ .then(() => redeliver({ sessionId, projectId: entry.projectId, memberId: entry.memberId, plan: entry.plan }))
58
+ .catch((error) => diag?.append?.({ ev: 'wake.tree-stale.redeliver.fail', projectId: entry.projectId, memberId: entry.memberId, sessionId, message: error?.message ?? String(error) }));
59
+ };
60
+
61
+ return {
62
+ /**
63
+ * 暂存一条被「旧树未散」拒绝的唤醒。retry=true 表示这是补投又被拒,计一次退避。
64
+ * @returns {boolean} false:退避已用尽(或已卸载),调用方按普通失败处理
65
+ */
66
+ defer({ sessionId, projectId, memberId, plan, retry = false }) {
67
+ if (disposed) return false;
68
+ const s = state.get(sessionId) ?? { tries: 0, attempts: 0, ended: false };
69
+ state.set(sessionId, s);
70
+ if (retry) {
71
+ s.tries += 1;
72
+ if (s.ended) s.attempts += 1;
73
+ }
74
+ const previous = pending.get(sessionId);
75
+ if (s.attempts >= backoffMs.length) {
76
+ if (previous !== undefined) clearTimer(previous.timer);
77
+ pending.delete(sessionId);
78
+ state.delete(sessionId);
79
+ diag?.append?.({ ev: 'wake.tree-stale.giveup.fail', projectId, memberId, sessionId, attempts: s.attempts, tries: s.tries, reason: plan?.reason ?? null });
80
+ return false;
81
+ }
82
+ if (previous !== undefined) {
83
+ // 回合未结束时又来新计划:换成最新的,定时器照旧。
84
+ Object.assign(previous, { plan, projectId, memberId });
85
+ return true;
86
+ }
87
+ const delayMs = backoffMs[Math.min(s.tries, backoffMs.length - 1)];
88
+ const entry = { sessionId, projectId, memberId, plan, timer: undefined };
89
+ pending.set(sessionId, entry);
90
+ arm(entry, delayMs, 'timer');
91
+ diag?.append?.({ ev: 'wake.tree-stale', projectId, memberId, sessionId, tries: s.tries, attempts: s.attempts, delayMs, reason: plan?.reason ?? null });
92
+ return true;
93
+ },
94
+ /** 投递成功:曾被暂存过的会话记一行 recovered,并清掉计数。 */
95
+ delivered(sessionId, context = {}) {
96
+ if (typeof sessionId !== 'string' || !state.has(sessionId)) return;
97
+ const s = state.get(sessionId);
98
+ diag?.append?.({ ev: 'wake.tree-stale.recovered', sessionId, tries: s.tries, attempts: s.attempts, ...context });
99
+ state.delete(sessionId);
100
+ },
101
+ /** `session/event` 观察者:暂存会话的回合一结束,等宿主收尾后补投;此后再被拒才计入放弃次数。 */
102
+ observe(session, event) {
103
+ const sessionId = session?.id;
104
+ if (event?.type !== 'turn/end' || typeof sessionId !== 'string') return;
105
+ const s = state.get(sessionId);
106
+ if (s !== undefined) s.ended = true;
107
+ const entry = pending.get(sessionId);
108
+ if (entry !== undefined) arm(entry, settleDelayMs, 'turn-end');
109
+ },
110
+ /** 测试与诊断:当前暂存的会话。 */
111
+ pendingSessions: () => [...pending.keys()],
112
+ dispose() {
113
+ disposed = true;
114
+ for (const entry of pending.values()) clearTimer(entry.timer);
115
+ pending.clear();
116
+ state.clear();
117
+ },
118
+ };
119
+ }
@@ -13,6 +13,23 @@
13
13
 
14
14
  const BUSY_HANDLE = /active write handle/i;
15
15
 
16
+ /**
17
+ * 热重载后「旧树未散」:宿主拒绝以另一棵子智能体树的根投递。
18
+ *
19
+ * 实机(il2c 2026-11-19 04:47):插件在桌面版里关再开后,唤醒玄策连续
20
+ * `UNAUTHORIZED target belongs to another subagent tree`(11-10…11-18 零次,整机重启后零次)。
21
+ * 根因(dsh-subagent manager.ts `deliverToMember`):成员常驻时投递要求 `activation.root === root`;
22
+ * 宿主 Agent 的生命周期挂在创建它的插件作用域上(dsh-agent-loop `initializeAgent` 的 `ownerCtx.effect`),
23
+ * 插件卸载即拆,新实例 resume 出新对象当根,而成员重载前开的回合仍常驻在旧树下。官方 `subagents.prompt`
24
+ * 也救不了:它按旧根投递,旧根已不是在线 Agent(rootOf:exact live caller,r43 第二轮实测)。
25
+ * 回合结束、宿主把它收掉(settlement)之后,下一次投递在新根下冷恢复——见 stale-tree-wakes.js。
26
+ * 同为 UNAUTHORIZED 的「another parent session」是血缘错配,不在此列。
27
+ */
28
+ export function isStaleTreeError(error) {
29
+ return String(error?.code ?? '').toUpperCase() === 'UNAUTHORIZED'
30
+ && /another subagent tree/i.test(String(error?.message ?? ''));
31
+ }
32
+
16
33
  /**
17
34
  * @param {string|null|undefined} causeChain `describeCauseChain()` 的输出
18
35
  * @returns {'wake.session-busy'|'wake.fail'} busy 表示「写租约被占用,必然需要重建」
@@ -374,7 +374,7 @@ export function apply(ctx, config = {}) {
374
374
  defineTool({
375
375
  name: t.name,
376
376
  description: t.description,
377
- parameters: t.parameters,
377
+ parameters: { type: 'object', properties: t.parameters },
378
378
  output: { schema: { type: 'string' }, render: renderOutput },
379
379
  async execute(args, exec) {
380
380
  const a = args || {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@suifei/dsh-ai-team",
3
- "version": "0.4.137",
3
+ "version": "0.4.139",
4
4
  "type": "module",
5
5
  "description": "文渊阁 (Wenyuan Pavilion) — AI Team mode for DeepSeek Harness: concurrent projects, owned tasks, threads, inbox and an append-only team ledger",
6
6
  "license": "MIT",