dsh-workplan 2.3.0 → 2.3.9

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/lib/runtime.js CHANGED
@@ -19,6 +19,11 @@ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, appendUserMess
19
19
  // [2.2.0][T4/O-3b] O-3b 消费接线:缺省协商上限由预估派生(plan.ts 纯函数,T3 已定稿)。
20
20
  deriveSubtaskTimeoutMs, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, REASONING_EFFORTS, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, mergeHandoffEntriesByUpdatedAt, needEntryText, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, } from './plan.js';
21
21
  import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js';
22
+ // [2.3.9][T3] LLM 家族检测 + 推理等级静态约束(用户强制要求 1/2;详见 llm-rules.ts 头注释)。
23
+ // [2.3.9][T4b] 追加第三层派发纯逻辑核:buildLlmRulesBrief(要求 1/2 全文告知注入,
24
+ // 部门层与专家/组员层共用同一事实源)、planDelegations(负责人「先全面梳理再分配」
25
+ // 硬门禁 + 分工表校验 + 等级钳制)、buildDelegateePrompt(第三层任务书)。
26
+ import { allowedEffortsForModel, buildDelegateePrompt, buildLlmRulesBrief, classifyModelFamily, correctEffortForModel, highestEffortOf, planDelegations, } from './llm-rules.js';
22
27
  import { phaseGateFromErrors, phaseSummaryLine, validatePhaseEvidence } from './three-phase.js';
23
28
  import { lessonStats, rankLessons, readLessons, recordLesson, renderLessonsBrief, resolveLessonsFile, } from './lessons.js';
24
29
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
@@ -721,22 +726,51 @@ export async function runPlanner(ctx, options) {
721
726
  // 用户的成本预期,所以先归一化再进白名单。
722
727
  const plannerEffortRaw = String(process.env.DSH_WORKPLAN_PLANNER_REASONING_EFFORT ?? '').trim().toLowerCase();
723
728
  const plannerEffort = REASONING_EFFORTS.includes(plannerEffortRaw) ? plannerEffortRaw : '';
724
- const requestedPlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT;
729
+ /*
730
+ * [2.3.9][T3/llm-rules] 用户强制要求 1/2(分配前先检测模型家族):qwen 开头
731
+ * 模型只允许 low / medium / xhigh,其余模型只允许 low / high / max。
732
+ * 默认档随家族取「合法集内最高档」(qwen⇒xhigh、非 qwen⇒max);env 显式
733
+ * 覆盖仍优先,覆盖值同样过静态收窄。静态约束先于宿主能力钳制执行(两道闸:
734
+ * 静态表权威,能力面在其上继续交集钳制,均留痕,与 U7 裁决一致)。模型名
735
+ * 缺失⇒不施加静态约束并用原默认档,保持 [2.2.7]「无从判定⇒不阻断」旧行为。
736
+ */
737
+ const plannerStaticAllowed = allowedEffortsForModel(modelSelection?.model);
738
+ const plannerFamilyDefault = highestEffortOf(plannerStaticAllowed) ?? DEFAULT_PLANNER_REASONING_EFFORT;
739
+ const requestedPlannerEffort = plannerEffort || plannerFamilyDefault;
740
+ const plannerEffortOriginLabel = plannerEffort ? 'env' : `default-${plannerFamilyDefault}`;
741
+ const plannerStaticCorrection = plannerStaticAllowed && !plannerStaticAllowed.includes(requestedPlannerEffort)
742
+ ? correctEffortForModel(requestedPlannerEffort, modelSelection?.model)
743
+ : null;
744
+ const staticRulePlannerEffort = plannerStaticCorrection ? plannerStaticCorrection.effort : requestedPlannerEffort;
745
+ const plannerStaticTrace = plannerStaticCorrection
746
+ ? `→${classifyModelFamily(modelSelection?.model) === 'qwen' ? 'qwen-rule' : 'non-qwen-rule'}:${plannerStaticCorrection.requested}→${plannerStaticCorrection.effort}`
747
+ : '';
748
+ if (plannerStaticCorrection) {
749
+ console.warn('[dsh-workplan] planner reasoning effort corrected by LLM family rules:', JSON.stringify({
750
+ provider: modelSelection?.provider,
751
+ model: modelSelection?.model,
752
+ family: classifyModelFamily(modelSelection?.model),
753
+ requested: requestedPlannerEffort,
754
+ corrected: plannerStaticCorrection.effort,
755
+ allowed: plannerStaticAllowed,
756
+ reason: plannerStaticCorrection.reason,
757
+ }));
758
+ }
725
759
  /*
726
760
  * [2.2.7] 发送前按模型能力钳制档位:宿主对不支持的档位会在网络调用前直接
727
761
  * 抛 UNSUPPORTED_REASONING_EFFORT,重试不自愈(终态),整次规划因此降级。
728
- * 查询不可用时保持旧行为;查询到清单后请求档钳制到清单内等效档,空清单
762
+ * 查询不可用时保持旧行为;查询成功后请求档钳制到清单内等效档,空清单
729
763
  * (模型无 reasoning 元数据)则不发送档位字段。'' 在这里表示「不发送」。
730
764
  */
731
765
  const plannerEffortSupport = await resolveSupportedEfforts(ctx.llm, modelSelection?.provider, modelSelection?.model, signal);
732
766
  const effectivePlannerEffort = plannerEffortSupport === null
733
- ? requestedPlannerEffort
734
- : (clampEffortToSupported(requestedPlannerEffort, plannerEffortSupport) ?? '');
735
- if (plannerEffortSupport !== null && effectivePlannerEffort !== requestedPlannerEffort) {
767
+ ? staticRulePlannerEffort
768
+ : (clampEffortToSupported(staticRulePlannerEffort, plannerEffortSupport) ?? '');
769
+ if (plannerEffortSupport !== null && effectivePlannerEffort !== staticRulePlannerEffort) {
736
770
  console.warn('[dsh-workplan] planner reasoning effort clamped for model compatibility:', JSON.stringify({
737
771
  provider: modelSelection?.provider,
738
772
  model: modelSelection?.model,
739
- requested: requestedPlannerEffort,
773
+ requested: staticRulePlannerEffort,
740
774
  effective: effectivePlannerEffort || '(omitted)',
741
775
  supported: plannerEffortSupport,
742
776
  }));
@@ -846,7 +880,9 @@ export async function runPlanner(ctx, options) {
846
880
  const text = await collectStream(stream, onChunk, sink);
847
881
  lastText = text;
848
882
  const raw = extractJson(text);
849
- const validated = validatePlan(raw);
883
+ // [2.3.9][T3] 事前约束:规划器显式写出集合外档位 → validatePlan 拒绝并点名,
884
+ // 经重试回路回喂自纠(用户要求 1/2;模型名缺失⇒null⇒不施加)。
885
+ const validated = validatePlan(raw, { allowedEfforts: allowedEffortsForModel(modelSelection.model) });
850
886
  if (validated.ok) {
851
887
  /*
852
888
  * [1.12.0] Structure alone is not understanding. Run the three-stage
@@ -948,7 +984,9 @@ export async function runPlanner(ctx, options) {
948
984
  message,
949
985
  `输出共 ${lastText.length} 字符,末尾原文:${JSON.stringify(tail)}`,
950
986
  closed
951
- ? '末尾已闭合 → 断点在正文中间,属语法写错(漏逗号/括号不匹配)'
987
+ // [2.3.2][D2-P1] 定向修复指令:message 已含「错误位置 + 断点附近原文」(extractJson
988
+ // 的 parseFailureHint),这里明确要求只修语法、不动内容,替代旧「整段重掷」。
989
+ ? '末尾已闭合 → 断点在正文中间,属语法写错(漏逗号/括号不匹配):请按上文「错误位置/断点附近原文」只修复该处语法,禁止改动字段值与整体结构'
952
990
  : '末尾未闭合(没有结尾 })→ 疑似输出被截断,请给出更紧凑的完整 JSON',
953
991
  ];
954
992
  }
@@ -1011,9 +1049,10 @@ export async function runPlanner(ctx, options) {
1011
1049
  // 复盘把「主 Agent=high」误读成「规划器=high」。
1012
1050
  // [2.2.7] 钳制发生时同样记录实际发出值('' = 未发送)。
1013
1051
  reasoningEffort: effectivePlannerEffort,
1014
- reasoningEffortSource: (plannerEffort ? 'env' : 'default-max')
1015
- + (plannerEffortSupport !== null && effectivePlannerEffort !== requestedPlannerEffort
1016
- ? `→clamped(${requestedPlannerEffort})` : ''),
1052
+ reasoningEffortSource: plannerEffortOriginLabel
1053
+ + plannerStaticTrace
1054
+ + (plannerEffortSupport !== null && effectivePlannerEffort !== staticRulePlannerEffort
1055
+ ? `→clamped(${staticRulePlannerEffort})` : ''),
1017
1056
  attempt,
1018
1057
  taskChars: typeof taskText === 'string' ? taskText.length : 0,
1019
1058
  promptChars,
@@ -1917,6 +1956,30 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1917
1956
  && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1918
1957
  ? subtask.reasoningEffort
1919
1958
  : DEFAULT_REASONING_EFFORT;
1959
+ /*
1960
+ * [2.3.9][T3/llm-rules] 用户强制要求 1/2 的执行点:派发前对每个子任务的
1961
+ * reasoningEffort 做模型家族等级集合校验。越界档不中断派发(A3 修正轨),
1962
+ * 按强度序自动降级并 console.warn 留痕;随后 [2.2.7] 宿主能力钳制作为
1963
+ * 第二道闸继续生效(静态表权威 + 能力面交集)。模型名缺失⇒不施加静态
1964
+ * 约束,保持旧行为。
1965
+ */
1966
+ const childStaticAllowed = allowedEffortsForModel(modelSelection?.model);
1967
+ const childStaticCorrection = childStaticAllowed && !childStaticAllowed.includes(requestedChildEffort)
1968
+ ? correctEffortForModel(requestedChildEffort, modelSelection?.model)
1969
+ : null;
1970
+ const staticRuleChildEffort = childStaticCorrection ? childStaticCorrection.effort : requestedChildEffort;
1971
+ if (childStaticCorrection) {
1972
+ console.warn('[dsh-workplan] child reasoning effort corrected by LLM family rules:', JSON.stringify({
1973
+ subtaskId: subtask.id,
1974
+ provider: modelSelection?.provider,
1975
+ model: modelSelection?.model,
1976
+ family: classifyModelFamily(modelSelection?.model),
1977
+ requested: requestedChildEffort,
1978
+ corrected: childStaticCorrection.effort,
1979
+ allowed: childStaticAllowed,
1980
+ reason: childStaticCorrection.reason,
1981
+ }));
1982
+ }
1920
1983
  /*
1921
1984
  * [2.2.7] 能力不可查询时保持同步路径:派发链上任何多余的 await 微任务都会
1922
1985
  * 把 awaiting 通道写入推晚一个 tick(notice-channel 运行时集成用例即因此
@@ -1928,8 +1991,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1928
1991
  ? await resolveSupportedEfforts(ctx.llm, modelSelection.provider, modelSelection.model, parentSignal)
1929
1992
  : null;
1930
1993
  const childEffort = childEffortSupport === null
1931
- ? requestedChildEffort
1932
- : (clampEffortToSupported(requestedChildEffort, childEffortSupport) ?? '');
1994
+ ? staticRuleChildEffort
1995
+ : (clampEffortToSupported(staticRuleChildEffort, childEffortSupport) ?? '');
1933
1996
  activation = await ctx.subagents.startActivation({
1934
1997
  provider: 'spawn',
1935
1998
  label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
@@ -1975,6 +2038,21 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1975
2038
  */
1976
2039
  previousFailure: lastFailure ?? null,
1977
2040
  lessonsBrief,
2041
+ /*
2042
+ * [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 的
2043
+ * **全部内容**告知相关部门。注入文本由 llm-rules.ts 的
2044
+ * buildLlmRulesBrief 单一事实源生成(tier='department'):
2045
+ * 要求 1/2 原文 + 本会话模型与家族判定 + 本子任务已配置/钳制后
2046
+ * 的推理等级 + 部门负责人「先全面梳理、再用 dsh_workplan_delegate
2047
+ * 分配给顶尖专家与组员」的强制流程告知。
2048
+ */
2049
+ llmRulesBrief: buildLlmRulesBrief({
2050
+ model: modelSelection?.model ?? null,
2051
+ effort: staticRuleChildEffort || null,
2052
+ requested: childStaticCorrection ? requestedChildEffort : null,
2053
+ correctionReason: childStaticCorrection?.reason ?? null,
2054
+ tier: 'department',
2055
+ }),
1978
2056
  }),
1979
2057
  }],
1980
2058
  parent: options.agent,
@@ -1998,7 +2076,16 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1998
2076
  // [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
1999
2077
  ...(childEffort ? { reasoningEffort: childEffort } : {}),
2000
2078
  },
2001
- maxDepth: 1,
2079
+ /*
2080
+ * [2.3.9][T4b] 三层派发深度(用户强制要求 4/5):主 Agent(0) →
2081
+ * 部门负责人子会话(1) → 顶尖专家/组员子会话(2)。maxDepth 是宿主
2082
+ * resolveChildDepth 的**绝对深度上限**(child-agent.d.ts:24-29),
2083
+ * 部门层放行到 2 才能让负责人经 dsh_workplan_delegate 派生第三层;
2084
+ * 第三层成员派生时同样传 2 ⇒ 任何第四层(深度 3)被宿主抛
2085
+ * SubagentDepthError 硬拒,delegateTool 服务端另有一道「只有部门
2086
+ * 负责人行可调用」的校验——提示词说服模型,代码守住边界。
2087
+ */
2088
+ maxDepth: 2,
2002
2089
  },
2003
2090
  signal: child.controller.signal,
2004
2091
  delivery: 'caller',
@@ -4114,6 +4201,23 @@ export function reconstructFromSession(session, targetPlanId) {
4114
4201
  });
4115
4202
  continue;
4116
4203
  }
4204
+ /*
4205
+ * [2.3.0][hotfix] 回放兼容「已回报行 + 旧版 closure:'done' 错误快照」(用户 2026-11-10 截图:
4206
+ * wp-3080d01d T6/T7「非法闭环迁移:reported → done」回放忽略)。
4207
+ *
4208
+ * 2.0.4 之前 live 侧 applyStatus 把 reported 行的 closure 误写回 'done',durable 改判
4209
+ * 消息因此嵌着这个错误快照。2.2.6 D-1 给回放补了 closure 透传,但没有豁免这一组合:
4210
+ * 回放大方把 'done' 当显式闭环意图传给迁移表 → reported → done 被拒 → 整条改判
4211
+ * (含 verification/acceptance 证据)被裸 catch 吞掉,重启后行退回缺证据态。
4212
+ *
4213
+ * 口径与 2.0.4 live 侧镜像:事件 closure='done' 且当前行 closure='reported' 时,这是
4214
+ * 「复核补齐」而非「退回未回报」,丢弃该显式值,让 done 分支按 2.0.4 保留已回报事实。
4215
+ * 其余透传分支(escalated/instructed 等,D-1 语义)零改动。
4216
+ */
4217
+ const preReplayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4218
+ const replayClosure = typeof update.closure === 'string'
4219
+ ? (update.closure === 'done' && preReplayRow?.closure === 'reported' ? undefined : update.closure)
4220
+ : undefined;
4117
4221
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
4118
4222
  /*
4119
4223
  * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
@@ -4132,7 +4236,7 @@ export function reconstructFromSession(session, targetPlanId) {
4132
4236
  * 重启后「待指示」行永久卡死(2026-11-08 wp-3c8c84b2 T2 实证,
4133
4237
  * 见 artifacts/2.2.5-post-restart-regression.md §4 D-1)。
4134
4238
  */
4135
- closure: typeof update.closure === 'string' ? update.closure : undefined,
4239
+ closure: replayClosure,
4136
4240
  progress: typeof update.progress === 'number' ? update.progress : undefined,
4137
4241
  summary: typeof update.note === 'string' ? update.note : undefined,
4138
4242
  // [1.8.13] Evidence written through the update tool must survive replay.
@@ -6735,6 +6839,290 @@ export function createWorkplanRuntime(ctx, options = {}) {
6735
6839
  : '已记录处置结果;交付阻塞按最新状态重新计算。',
6736
6840
  };
6737
6841
  }
6842
+ /**
6843
+ * [2.3.9][T4b] 第三层派发(用户强制要求 4/5):部门负责人专用工具。
6844
+ *
6845
+ * 层级模型:主 Agent(根会话, depth 0) → 部门负责人子会话(depth 1) →
6846
+ * 顶尖专家/组员子会话(depth 2, 叶子层)。三道硬边界:
6847
+ * 1. 调用者必须是计划内某行的部门负责人子会话(childId 反查行);
6848
+ * 根会话被拒(用 dsh_workplan_dispatch),第三层成员也被拒——
6849
+ * 其父会话是部门会话、没有计划记录,NO_PLAN/NO_SUBTASK 即叶子层禁令;
6850
+ * 2. 梳理门禁:dispatch 前必须先 review 提交「全面梳理产物 + 分工表」
6851
+ * (planDelegations 唯一判据,durable 回放后依然生效);
6852
+ * 3. 深度:成员 spawn 传 maxDepth:2,第四层(depth 3)由宿主
6853
+ * SubagentDepthError 硬拒(resolveChildDepth 绝对上限)。
6854
+ *
6855
+ * 每位下级的推理等级按其任务复杂度由负责人配置,经 planDelegations 按
6856
+ * 当前模型家族合法集合(qwen→low/medium/xhigh;非qwen→low/high/max)
6857
+ * 钳制并留痕(delegates[].requested/effort 对),随 spawn 的 agentOptions
6858
+ * 下发且全生命周期生效(要求 5)。
6859
+ */
6860
+ async function delegateTool(agent, args, signal) {
6861
+ const childSession = agent?.session;
6862
+ if (!childSession?.id) {
6863
+ return { ok: false, code: 'NO_SESSION', error: '只能在会话内使用第三层派发' };
6864
+ }
6865
+ const parentId = childSession.header?.parentSession;
6866
+ if (!parentId) {
6867
+ return {
6868
+ ok: false,
6869
+ code: 'NOT_LEADER_SESSION',
6870
+ error: '只有「部门负责人子会话」可以使用 dsh_workplan_delegate:根会话请用 dsh_workplan_dispatch 派发主计划;第三层专家/组员是叶子层,不得再派发(用户要求 4:只有一层下级)。',
6871
+ };
6872
+ }
6873
+ let record = state.records.get(parentId);
6874
+ if (!record?.plan) {
6875
+ const parent = ctx.sessions?.get?.(parentId);
6876
+ if (parent) {
6877
+ try {
6878
+ record = reconstructFromSession(parent);
6879
+ }
6880
+ catch (error) {
6881
+ pushRecordError({ errors: [] }, error);
6882
+ }
6883
+ }
6884
+ }
6885
+ if (!record?.plan) {
6886
+ return {
6887
+ ok: false,
6888
+ code: 'NO_PLAN',
6889
+ error: '父会话没有可关联的计划。若你是第三层专家/组员(叶子层):不得再派发,完成自身任务后把结论回报部门负责人即可。',
6890
+ };
6891
+ }
6892
+ const row = (record.statuses ?? []).find((item) => item?.childId === childSession.id);
6893
+ if (!row) {
6894
+ return {
6895
+ ok: false,
6896
+ code: 'NO_SUBTASK',
6897
+ error: '计划里找不到与本子会话关联的子任务行(childId 未登记);第三层派发只能由计划内的部门负责人子会话发起。',
6898
+ };
6899
+ }
6900
+ if (row.status === 'done') {
6901
+ return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已完成,不能再派发第三层。' };
6902
+ }
6903
+ const action = ['review', 'dispatch', 'status'].includes(args?.action) ? String(args.action) : '';
6904
+ if (!action) {
6905
+ return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 review(提交全面梳理产物)/ dispatch(派发给顶尖专家与组员)/ status(查看梳理与下级进度)' };
6906
+ }
6907
+ const subtaskId = String(row.subtaskId);
6908
+ const modelSelection = resolveModelSelection(ctx, { agent });
6909
+ const model = typeof modelSelection?.model === 'string' && modelSelection.model.trim() ? modelSelection.model.trim() : null;
6910
+ const parentSession = ctx.sessions?.get?.(parentId);
6911
+ const persist = (patch) => {
6912
+ const revision = Number(row.revision ?? 0) + 1;
6913
+ record.statuses = applyStatus(record.statuses, subtaskId, { ...patch, revision, updatedBy: 'child' });
6914
+ record.updatedAt = Date.now();
6915
+ try {
6916
+ const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
6917
+ appendUserMessage(parentSession, buildUpdateMessage({
6918
+ planId: record.plan.planId,
6919
+ subtaskId,
6920
+ status: written?.status ?? row.status,
6921
+ ...(patch.consolidation === undefined ? {} : { consolidation: written?.consolidation }),
6922
+ ...(patch.delegates === undefined ? {} : { delegates: written?.delegates }),
6923
+ revision: written?.revision ?? revision,
6924
+ }));
6925
+ }
6926
+ catch (error) {
6927
+ pushRecordError(record, error);
6928
+ }
6929
+ return record.statuses.find((item) => item?.subtaskId === subtaskId);
6930
+ };
6931
+ if (action === 'status') {
6932
+ const delegates = Array.isArray(row.delegates) ? row.delegates : [];
6933
+ return {
6934
+ ok: true,
6935
+ planId: record.plan.planId,
6936
+ subtaskId,
6937
+ action,
6938
+ consolidation: row.consolidation ?? null,
6939
+ delegates,
6940
+ hint: !row.consolidation
6941
+ ? '尚未提交梳理产物:先调用 action="review"(用户要求 4 的硬门禁)。'
6942
+ : delegates.length === 0
6943
+ ? '梳理产物已登记,可调用 action="dispatch" 正式派发给顶尖专家与组员。'
6944
+ : '第三层已派发;各下级结论会送回本会话,收齐后汇总核验,再写最终结果块。',
6945
+ };
6946
+ }
6947
+ if (action === 'review') {
6948
+ const input = isRecord(args?.consolidation) ? args.consolidation : null;
6949
+ if (!input) {
6950
+ return {
6951
+ ok: false,
6952
+ code: 'MISSING_CONSOLIDATION',
6953
+ subtaskId,
6954
+ error: 'review 必须携带 consolidation:{ problemAnalysis[], constraints[]?, unknowns[]?, approach[]?, assignments[{member, role:"expert"|"member", task, reasoningEffort}] }——用户要求 4 的「全面、全盘、深入梳理」产物 + 分工表(至少 1 名顶尖专家 + 1 名组员)。',
6955
+ };
6956
+ }
6957
+ const preview = planDelegations({ consolidation: input, model });
6958
+ if (!preview.ok) {
6959
+ return {
6960
+ ok: false,
6961
+ code: preview.code ?? 'DELEGATE_CONSOLIDATION_INVALID',
6962
+ subtaskId,
6963
+ error: preview.error,
6964
+ hint: '修正梳理产物后重新 action="review";未登记前 action="dispatch" 会持续被硬门禁拒绝。',
6965
+ };
6966
+ }
6967
+ const written = persist({
6968
+ consolidation: {
6969
+ problemAnalysis: input.problemAnalysis,
6970
+ constraints: input.constraints,
6971
+ unknowns: input.unknowns,
6972
+ approach: input.approach,
6973
+ assignments: input.assignments,
6974
+ submittedAt: Date.now(),
6975
+ },
6976
+ });
6977
+ return {
6978
+ ok: true,
6979
+ planId: record.plan.planId,
6980
+ subtaskId,
6981
+ action,
6982
+ consolidation: written?.consolidation ?? null,
6983
+ members: preview.members,
6984
+ clamped: preview.clamped,
6985
+ model: model ?? '(未知,未施加静态等级约束)',
6986
+ hint: '梳理产物已登记(durable,刷新后门禁依然生效)。现在可调用 action="dispatch" 正式派发;每位下级的推理等级已按当前模型家族合法集合钳制(clamped 列出越界修正与原因,留痕可审计)。',
6987
+ };
6988
+ }
6989
+ // action === 'dispatch'
6990
+ const consolidation = isRecord(row.consolidation) ? row.consolidation : null;
6991
+ const delegationPlan = planDelegations({ consolidation, model });
6992
+ if (!delegationPlan.ok) {
6993
+ return {
6994
+ ok: false,
6995
+ code: delegationPlan.code ?? 'DELEGATE_CONSOLIDATION_MISSING',
6996
+ subtaskId,
6997
+ error: delegationPlan.error,
6998
+ };
6999
+ }
7000
+ if (Array.isArray(row.delegates) && row.delegates.some((item) => item?.status === 'running')) {
7001
+ return {
7002
+ ok: false,
7003
+ code: 'DELEGATE_ALREADY_RUNNING',
7004
+ subtaskId,
7005
+ error: '第三层已在派发中(仍有下级 running):不要重复派发。用 action="status" 查看进度;如需补派新成员,先等当前下级结算。',
7006
+ delegates: row.delegates,
7007
+ };
7008
+ }
7009
+ const departmentLabel = DEPARTMENTS[row.department]?.zh ?? String(row.department ?? '部门');
7010
+ // cwd 与 dispatchTool 同源(session.header.cwd,7465 行同款):优先负责人
7011
+ // 子会话自己的工作目录,缺失回退根会话;都没有则交给宿主按 parent 推导。
7012
+ const cwd = typeof childSession.header?.cwd === 'string' && childSession.header.cwd
7013
+ ? childSession.header.cwd
7014
+ : (typeof parentSession?.header?.cwd === 'string' && parentSession.header.cwd
7015
+ ? parentSession.header.cwd
7016
+ : undefined);
7017
+ const delegates = [];
7018
+ for (const assignment of delegationPlan.members) {
7019
+ const rulesBrief = buildLlmRulesBrief({
7020
+ model,
7021
+ effort: assignment.effort,
7022
+ requested: assignment.requested ?? null,
7023
+ correctionReason: assignment.correctionReason ?? null,
7024
+ tier: 'delegate',
7025
+ memberName: assignment.member,
7026
+ memberRole: assignment.role,
7027
+ });
7028
+ const promptText = buildDelegateePrompt({
7029
+ departmentLabel,
7030
+ leaderSubtaskId: subtaskId,
7031
+ leaderSubtaskTitle: String(row.title ?? ''),
7032
+ member: assignment,
7033
+ rulesBrief,
7034
+ cwd: cwd ?? '',
7035
+ leadSessionId: childSession.id,
7036
+ });
7037
+ let childId = null;
7038
+ let memberStatus = 'running';
7039
+ let memberError = null;
7040
+ try {
7041
+ const activation = await ctx.subagents.startActivation({
7042
+ provider: 'spawn',
7043
+ label: `${row.department}:${subtaskId}→${assignment.member}`.slice(0, 120),
7044
+ request: {
7045
+ prompt: [{ type: 'text', text: promptText }],
7046
+ parent: agent,
7047
+ cwd,
7048
+ agentOptions: {
7049
+ ...(modelSelection?.provider && modelSelection?.model
7050
+ ? { provider: modelSelection.provider, model: modelSelection.model }
7051
+ : {}),
7052
+ // 要求 5:等级随任务复杂度配置并全程应用;'' = 模型无 reasoning 元数据 ⇒ 不发送。
7053
+ ...(assignment.effort ? { reasoningEffort: assignment.effort } : {}),
7054
+ },
7055
+ // 成员在 depth 2;任何第四层(depth 3)被宿主绝对深度上限硬拒。
7056
+ maxDepth: 2,
7057
+ },
7058
+ signal,
7059
+ delivery: 'caller',
7060
+ });
7061
+ childId = typeof activation?.childId === 'string' ? activation.childId : null;
7062
+ if (activation && typeof activation.result?.then === 'function') {
7063
+ const settledChildId = childId;
7064
+ activation.result.then((outcome) => {
7065
+ try {
7066
+ const completed = outcome?.stopReason === 'completed';
7067
+ const current = (record.statuses ?? []).find((item) => item?.subtaskId === subtaskId);
7068
+ const list = (Array.isArray(current?.delegates) ? current.delegates : [])
7069
+ .map((item) => (item?.childId === settledChildId
7070
+ ? {
7071
+ ...item,
7072
+ status: completed ? 'done' : 'failed',
7073
+ summary: truncate(resultText(outcome), 300),
7074
+ error: completed ? null : truncate(String(outcome?.diagnostic ?? `子会话结束状态 ${outcome?.stopReason}`), 300),
7075
+ finishedAt: Date.now(),
7076
+ }
7077
+ : item));
7078
+ const revision = Number(current?.revision ?? 0) + 1;
7079
+ record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'child' });
7080
+ record.updatedAt = Date.now();
7081
+ appendUserMessage(parentSession, buildUpdateMessage({
7082
+ planId: record.plan.planId,
7083
+ subtaskId,
7084
+ status: current?.status ?? row.status,
7085
+ delegates: list,
7086
+ revision,
7087
+ }));
7088
+ }
7089
+ catch {
7090
+ // 结算留痕失败不影响主链路:看板下次刷新按内存行渲染。
7091
+ }
7092
+ }).catch(() => { });
7093
+ }
7094
+ }
7095
+ catch (error) {
7096
+ memberStatus = 'rejected';
7097
+ memberError = truncate(String(error?.message ?? error), 300);
7098
+ }
7099
+ delegates.push({
7100
+ member: assignment.member,
7101
+ role: assignment.role,
7102
+ task: assignment.task,
7103
+ effort: assignment.effort,
7104
+ ...(assignment.requested && assignment.requested !== assignment.effort ? { requested: assignment.requested } : {}),
7105
+ childId,
7106
+ status: memberStatus,
7107
+ summary: '',
7108
+ error: memberError,
7109
+ startedAt: Date.now(),
7110
+ finishedAt: null,
7111
+ });
7112
+ }
7113
+ const written = persist({ delegates });
7114
+ const rejected = delegates.filter((item) => item.status === 'rejected');
7115
+ return {
7116
+ ok: rejected.length < delegates.length,
7117
+ planId: record.plan.planId,
7118
+ subtaskId,
7119
+ action,
7120
+ delegates: written?.delegates ?? delegates,
7121
+ clamped: delegationPlan.clamped,
7122
+ ...(rejected.length ? { rejected: rejected.map((item) => ({ member: item.member, error: item.error })) } : {}),
7123
+ hint: '第三层已派发(一层下级、叶子层,第四层会被硬拒)。每位专家/组员的完成结论会送回本会话(delivery=caller);收齐后由你汇总核验,再写最终结果块。用 action="status" 查看进度。',
7124
+ };
7125
+ }
6738
7126
  async function dispatchTool(agent, args, signal) {
6739
7127
  const session = agent?.session;
6740
7128
  if (!session)
@@ -8051,6 +8439,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
8051
8439
  statusTool,
8052
8440
  followupTool,
8053
8441
  escalateTool,
8442
+ // [2.3.9][T4b] 第三层派发(部门负责人专用):review 梳理门禁 → dispatch 专家/组员。
8443
+ delegateTool,
8054
8444
  verifyTool: verifySubtask,
8055
8445
  lessonsTool,
8056
8446
  instructTool,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-workplan",
3
- "version": "2.3.0",
3
+ "version": "2.3.9",
4
4
  "description": "Automatic task decomposition, real department subagents, and a responsive workplan dashboard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/client.ts CHANGED
@@ -95,6 +95,16 @@ window.__ModuleLoader__.load({
95
95
  "closed": "无需动作"
96
96
  },
97
97
  "handoffs": "跨部门需求",
98
+ "delegates": "第三层(专家/组员)",
99
+ "delegateExpert": "专家",
100
+ "delegateMember": "组员",
101
+ "delegateStatus": {
102
+ "running": "执行中",
103
+ "done": "已完成",
104
+ "failed": "失败",
105
+ "timeout": "超时",
106
+ "rejected": "派发被拒"
107
+ },
98
108
  "dept": {
99
109
  "engineering": "工程研发",
100
110
  "research": "研究分析",
@@ -312,6 +322,16 @@ window.__ModuleLoader__.load({
312
322
  "closed": "No action"
313
323
  },
314
324
  "handoffs": "Cross-team needs",
325
+ "delegates": "Third tier (experts/members)",
326
+ "delegateExpert": "expert",
327
+ "delegateMember": "member",
328
+ "delegateStatus": {
329
+ "running": "running",
330
+ "done": "done",
331
+ "failed": "failed",
332
+ "timeout": "timeout",
333
+ "rejected": "rejected"
334
+ },
315
335
  "dept": {
316
336
  "engineering": "Engineering",
317
337
  "research": "Research",
@@ -1737,6 +1757,11 @@ window.__ModuleLoader__.load({
1737
1757
  * [2.2.7][T2/五档] UI Pill 白名单:与 plan.ts 的 REASONING_EFFORTS
1738
1758
  * (low / medium / high / xhigh / max)逐值同步。浏览器包无法 import
1739
1759
  * 宿主常量,此处为唯二事实源之一——漏改会让新档位在任务卡片上静默消失。
1760
+ * [2.3.9][T3] 模型家族收窄口径:qwen 系仅 low/medium/xhigh、其余仅
1761
+ * low/high/max 的**事前约束**发生在规划校验(validatePlan allowedEfforts)
1762
+ * 与派发入口(runtime 静态收窄+qwen-rule 留痕);计划字段本身是存储全集
1763
+ * 五档(旧计划/他模型计划可在本会话回放展示),故 Pill 继续按五档显示、
1764
+ * 不得按家族删档——家族合法性以发送前的收窄/拒绝为准,不靠 UI 过滤兜底。
1740
1765
  */
1741
1766
  const effort = typeof subtask?.reasoningEffort === 'string' && ['low', 'medium', 'high', 'xhigh', 'max'].includes(subtask.reasoningEffort)
1742
1767
  ? subtask.reasoningEffort
@@ -1780,6 +1805,28 @@ window.__ModuleLoader__.load({
1780
1805
  ),
1781
1806
  )
1782
1807
  : null,
1808
+ /*
1809
+ * [2.3.9][T4b] 第三层派发看板(用户要求 4/5):部门负责人分配给
1810
+ * 顶尖专家/组员的每位下级、其推理等级(含越界钳制留痕)与实时状态
1811
+ * 必须对用户与主 Agent 可见,否则「第三层派给了谁、跑没跑完」只存在
1812
+ * 负责人子会话里。数据源 = 状态行 delegates(applyStatus 消毒 +
1813
+ * durable workplan-update 回放,刷新/重启不丢),客户端不推导状态。
1814
+ */
1815
+ Array.isArray(item?.delegates) && item.delegates.length
1816
+ ? h('div', { className: 'dsh-wp-subtask-body' },
1817
+ h('div', null, h('strong', null, `${t('delegates')}:`)),
1818
+ h('ul', { className: 'dsh-wp-muted' },
1819
+ item.delegates.map((member: any, memberIndex: number) => h('li', { key: `${String(member?.childId ?? member?.member ?? '')}-${memberIndex}` },
1820
+ `└ ${String(member?.member ?? '?')}`
1821
+ + `(${member?.role === 'expert' ? t('delegateExpert') : t('delegateMember')})`
1822
+ + `|${t('reasoningEffort')}:${String(member?.effort ?? '?')}`
1823
+ + (member?.requested && member.requested !== member.effort ? `(越界钳制自 ${String(member.requested)})` : '')
1824
+ + `|${t(`delegateStatus.${String(member?.status ?? 'running')}`)}`
1825
+ + (member?.summary ? `:${String(member.summary)}` : ''),
1826
+ )),
1827
+ ),
1828
+ )
1829
+ : null,
1783
1830
  status !== 'blocked' && item?.summary ? h('p', { className: 'dsh-wp-muted' }, `${t('summary')}:${plainError(item.summary)}`) : null,
1784
1831
  /*
1785
1832
  * [1.10.0] R-02:「卡住原因」只属于没做完的行。