dsh-cohub 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +1 -1
  2. package/lib/index.js +224 -55
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # dsh-cohub
2
2
 
3
- > 本文对应 **v0.10.2**;完整变更历史见 [CHANGELOG.md](./CHANGELOG.md)。
3
+ > 本文对应 **v0.10.4**;完整变更历史见 [CHANGELOG.md](./CHANGELOG.md)。
4
4
 
5
5
  DeepSeek Harness 版(对照 [OpenCode 版](../oh-my-opencode-cohub/)):中文智能体编排插件。
6
6
  把「纯调度模式 + 13 个技能(12 个代理编排体系 + co-cordis 组合创作)+ 多模型共识 + 运行期调度韧性」移植到 DSH 原生能力之上。
package/lib/index.js CHANGED
@@ -3133,7 +3133,7 @@ function resolveSkillAgentPreset(skillName, enabled = true) {
3133
3133
  return SUBAGENT_READONLY_PRESET;
3134
3134
  if (WRITE_SKILLS.has(key))
3135
3135
  return SUBAGENT_WRITE_PRESET;
3136
- return;
3136
+ return SUBAGENT_WRITE_PRESET;
3137
3137
  }
3138
3138
  function intersectWithRestrictable(filter, restrictableNames) {
3139
3139
  if (!filter || !restrictableNames)
@@ -3146,25 +3146,36 @@ function intersectWithRestrictable(filter, restrictableNames) {
3146
3146
  };
3147
3147
  return next.allow !== undefined || next.deny !== undefined ? next : undefined;
3148
3148
  }
3149
+ var SKILL_NAME_ECHO_MAX = 80;
3150
+ function flattenToOneLine(text) {
3151
+ return text.replace(/\s+/g, " ").trim();
3152
+ }
3153
+ function firstLineClamped(raw, maxChars) {
3154
+ const firstLine = flattenToOneLine(raw.split(/[\r\n]/, 1)[0] ?? "").replace(/\[/g, "[").replace(/\]/g, "]");
3155
+ return firstLine.length > maxChars ? firstLine.slice(0, maxChars) + "…" : firstLine;
3156
+ }
3149
3157
  function describeDegradeReason(error) {
3150
3158
  const message = error?.message;
3151
3159
  const raw = typeof message === "string" && message.length > 0 ? message : String(error);
3152
- const firstLine = (raw.split(/\r?\n/)[0] ?? "").replace(/\s+/g, " ").trim();
3153
- const text = firstLine.length > 0 ? firstLine : "unknown";
3154
- return text.length > 200 ? text.slice(0, 200) : text;
3160
+ const text = firstLineClamped(raw, 200);
3161
+ return text.length > 0 ? text : "unknown";
3155
3162
  }
3156
3163
  function formatDegradeNotes(notes) {
3157
3164
  if (notes === undefined || notes.length === 0)
3158
3165
  return "";
3166
+ const reasonOf = (note) => {
3167
+ const flat = firstLineClamped(String(note.reason ?? ""), 200);
3168
+ return flat.length > 0 ? flat : "unknown";
3169
+ };
3159
3170
  if (notes.length === 1) {
3160
3171
  const only = notes[0];
3161
3172
  return `
3162
3173
 
3163
- [` + only.what + "," + only.effect + ":" + only.reason + "]";
3174
+ [` + only.what + "," + only.effect + ":" + reasonOf(only) + "]";
3164
3175
  }
3165
3176
  return `
3166
3177
 
3167
- [降级提示:` + notes.map((n) => n.what + "," + n.effect + "(" + n.reason + ")").join(";") + "]";
3178
+ [降级提示:` + notes.map((n) => n.what + "," + n.effect + "(" + reasonOf(n) + ")").join(";") + "]";
3168
3179
  }
3169
3180
  function upsertDegradeNote(notes, note) {
3170
3181
  if (notes === undefined)
@@ -3570,15 +3581,19 @@ function resolveSkillAndRoute(requestedSkill, getRoutes, ctx, logger) {
3570
3581
  const requested = (typeof requestedSkill === "string" ? requestedSkill : "").trim();
3571
3582
  const skillName = requested || DEFAULT_FALLBACK_SKILL;
3572
3583
  const fallback = requested.length === 0;
3584
+ const echoName = firstLineClamped(skillName, SKILL_NAME_ECHO_MAX) || "unknown";
3573
3585
  let skill = COHUB_SKILLS.find((s) => s.name === skillName);
3586
+ let note;
3574
3587
  if (!skill) {
3575
3588
  (logger ?? ctx.logger)?.warn?.('delegate: unknown skill "' + skillName + '", falling back to co-fixer');
3576
3589
  skill = COHUB_SKILLS.find((s) => s.name === DEFAULT_FALLBACK_SKILL);
3590
+ note = '传入的 skill 名 "' + echoName + '" 未匹配任何 co-* 代理,已兜底为 ' + DEFAULT_FALLBACK_SKILL + ",子代理 preset 同步回退为实施类 " + SUBAGENT_WRITE_PRESET;
3577
3591
  } else if (fallback) {
3578
3592
  (logger ?? ctx.logger)?.warn?.("delegate: skill 未提供(缺字段/空串/纯空白),已兜底为 " + DEFAULT_FALLBACK_SKILL + ";schema 已要求必填,出现本告警说明调用绕过了参数校验");
3593
+ note = "skill 未提供(缺字段/空串/纯空白),已兜底为 " + DEFAULT_FALLBACK_SKILL + ",子代理 preset 回退为实施类 " + SUBAGENT_WRITE_PRESET;
3579
3594
  }
3580
3595
  const route = (getRoutes() ?? []).find((s) => s.name === requested);
3581
- return { skill, route, fallback };
3596
+ return { skill, route, fallback, ...note === undefined ? {} : { note } };
3582
3597
  }
3583
3598
  function formatSkillLabel(skill, fallback) {
3584
3599
  return fallback ? skill.name + " (default:" + DEFAULT_FALLBACK_SKILL + ")" : skill.name;
@@ -3674,10 +3689,17 @@ function resolveDelegationDepth(agent) {
3674
3689
  return MAX_DELEGATION_DEPTH;
3675
3690
  return depth;
3676
3691
  }
3692
+ function describeDepthCandidate(value) {
3693
+ const kind = value === null ? "null" : typeof value;
3694
+ const shown = typeof value === "string" ? JSON.stringify(value) : String(value);
3695
+ return shown + "(" + kind + ")";
3696
+ }
3677
3697
  function guardDelegationDepth(agent, logger) {
3678
3698
  const depth = resolveDelegationDepth(agent);
3679
3699
  if (depth === undefined) {
3680
- logger?.warn?.("[cohub depth-guard] 无法读取当前 agent 的嵌套委派深度" + "(session.header.delegationDepth 缺失),本次放行、不做硬拦截");
3700
+ const header = agent?.session?.header;
3701
+ logger?.warn?.("[cohub depth-guard] 深度候选原始值:" + "header.delegationDepth=" + describeDepthCandidate(header?.delegationDepth) + " / options.subagentDepth=" + describeDepthCandidate(agent?.options?.subagentDepth) + " / session.delegationDepth=" + describeDepthCandidate(agent?.session?.delegationDepth) + " / header.origin=" + describeDepthCandidate(header?.origin));
3702
+ logger?.warn?.("[cohub depth-guard] 无法判定委派深度,按兼容策略放行(fail-open)" + ":session.header.delegationDepth / options.subagentDepth / session.delegationDepth 均缺失或非法," + '且 header.origin 不是 "subagent";本次委派继续执行,嵌套上限不再生效。' + '若上面某候选是字符串 "0" 之类的类型错误,请修宿主(合法值为 number 且为安全整数)');
3681
3703
  return;
3682
3704
  }
3683
3705
  if (depth < MAX_DELEGATION_DEPTH)
@@ -3896,7 +3918,7 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
3896
3918
  const { retry, stall, schedule, budget, background, subagentPresetEnabled } = resolveRuntimeConfig();
3897
3919
  const RETRYABLE = new Set(retry.retryableReasons);
3898
3920
  ctx.logger?.info?.("[cohub schedule] 生效调度参数:batch=" + (schedule?.maxParallelBatch ?? 3) + " wallMs=" + (schedule?.wallClockBudgetMs ?? WALL_CLOCK_BUDGET_MS));
3899
- const { skill, route, fallback: skillFallback } = resolveSkillAndRoute(args.skill, getRoutes, ctx);
3921
+ const { skill, route, fallback: skillFallback, note: skillNote } = resolveSkillAndRoute(args.skill, getRoutes, ctx);
3900
3922
  const skillTag = formatSkillLabel(skill, skillFallback);
3901
3923
  const brief = skill.brief?.trim();
3902
3924
  if (!brief) {
@@ -3905,6 +3927,14 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
3905
3927
  const agentOptions = await buildAgentOptions(route, ctx, skill.name);
3906
3928
  const toolFilter = resolveSkillToolFilter(skill.name, config.toolFilter?.enabled ?? true, ctx.logger);
3907
3929
  const degradeNotes = [];
3930
+ if (skillNote !== undefined) {
3931
+ upsertDegradeNote(degradeNotes, {
3932
+ id: "skill",
3933
+ what: "skill 名未命中",
3934
+ effect: "子代理已按兜底角色 " + skill.name + " 执行",
3935
+ reason: skillNote
3936
+ });
3937
+ }
3908
3938
  const agentPreset = resolveSkillAgentPreset(skill.name, subagentPresetEnabled);
3909
3939
  const fp = envFingerprint();
3910
3940
  const contractResult = resolveContractText({ enabled: envContract.enabled, text: envContract.text }, envSig, ctx, fp);
@@ -4080,7 +4110,8 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
4080
4110
  retries++;
4081
4111
  await new Promise((r) => setTimeout(r, retry.retryDelayMs));
4082
4112
  }
4083
- const err = new Error('delegate: subagent stopped with reason "' + lastReason + '" after ' + retries + " retry(ies)" + (lastDiagnostic === undefined ? "" : "; diagnostic: " + lastDiagnostic) + (stallState.last ? "; stalled: " + stallState.last.diagnostics : "") + "; partial: " + lastPartial);
4113
+ const degradeText = formatDegradeNotes(degradeNotes).replace(/\s+/g, " ");
4114
+ const err = new Error('delegate: subagent stopped with reason "' + lastReason + '" after ' + retries + " retry(ies)" + (lastDiagnostic === undefined ? "" : "; diagnostic: " + lastDiagnostic) + (stallState.last ? "; stalled: " + stallState.last.diagnostics : "") + "; partial: " + lastPartial + degradeText);
4084
4115
  err.cause = {
4085
4116
  stopReason: lastReason,
4086
4117
  ...lastDiagnostic === undefined ? {} : { diagnostic: lastDiagnostic },
@@ -4088,7 +4119,8 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
4088
4119
  ...lastPartialBudget === lastPartial ? {} : { partialBudget: lastPartialBudget },
4089
4120
  skill: skill.name,
4090
4121
  retries,
4091
- ...stallState.last ? { stall: stallState.last } : {}
4122
+ ...stallState.last ? { stall: stallState.last } : {},
4123
+ ...degradeText.length > 0 ? { degrade: degradeText } : {}
4092
4124
  };
4093
4125
  throw err;
4094
4126
  };
@@ -4406,6 +4438,7 @@ function createCouncilTool(config, ctx) {
4406
4438
 
4407
4439
  // src/delegate_batch.ts
4408
4440
  import { defineTool as defineTool3 } from "@deepseek-ai/dsh-tools";
4441
+ var BATCH_TASK_ID_ECHO_MAX = 40;
4409
4442
  var MAX_BATCH_SIZE = 20;
4410
4443
  function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4411
4444
  const envContract = createEnvContract(config);
@@ -4480,7 +4513,16 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4480
4513
  });
4481
4514
  const starts = await Promise.allSettled(normalized.map(async ({ task, taskId, requestedSkill, skillFallback }) => {
4482
4515
  const startedAt = Date.now();
4483
- const { skill, route } = resolveSkillAndRoute(requestedSkill, getRoutes, ctx, ctx.logger);
4516
+ const { skill, route, note: skillNote } = resolveSkillAndRoute(requestedSkill, getRoutes, ctx, ctx.logger);
4517
+ const taskNotes = [];
4518
+ if (skillNote !== undefined) {
4519
+ taskNotes.push({
4520
+ id: "skill",
4521
+ what: "skill 名未命中",
4522
+ effect: "子代理已按兜底角色 " + skill.name + " 执行",
4523
+ reason: skillNote
4524
+ });
4525
+ }
4484
4526
  const skillTag = formatSkillLabel(skill, skillFallback);
4485
4527
  const promptText = buildDelegatePrompt({
4486
4528
  skill,
@@ -4512,20 +4554,26 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4512
4554
  ...toolFilter !== undefined ? { toolFilter } : {},
4513
4555
  ...agentPreset !== undefined ? { agentPreset } : {},
4514
4556
  ...agentOptions ? { agentOptions } : {},
4515
- signal: ac.signal
4557
+ signal: ac.signal,
4558
+ degradeNotes: taskNotes
4516
4559
  });
4517
- return { taskId, skillName: skill.name, skillTag, task, run, ac, onExecAbort, startedAt, startError: undefined };
4560
+ return { taskId, skillName: skill.name, skillTag, task, taskNotes, run, ac, onExecAbort, startedAt, startError: undefined };
4518
4561
  } catch (startError) {
4519
4562
  if (onExecAbort && exec.signal) {
4520
4563
  try {
4521
4564
  exec.signal.removeEventListener("abort", onExecAbort);
4522
4565
  } catch {}
4523
4566
  }
4524
- return { taskId, skillName: skill.name, skillTag, task, run: undefined, ac, onExecAbort: null, startedAt, startError };
4567
+ return { taskId, skillName: skill.name, skillTag, task, taskNotes, run: undefined, ac, onExecAbort: null, startedAt, startError };
4525
4568
  }
4526
4569
  }));
4527
4570
  const results = [];
4528
4571
  const runs = [];
4572
+ const perTaskNotes = [];
4573
+ const degradeField = (notes) => {
4574
+ const text = formatDegradeNotes(notes).trim();
4575
+ return text.length > 0 ? { degrade: text } : {};
4576
+ };
4529
4577
  try {
4530
4578
  for (const s of starts) {
4531
4579
  if (s.status === "rejected") {
@@ -4533,19 +4581,22 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4533
4581
  }
4534
4582
  const val = s.value;
4535
4583
  if (val.startError) {
4584
+ perTaskNotes.push({ taskId: val.taskId, notes: val.taskNotes ?? [] });
4536
4585
  results.push({
4537
4586
  id: val.taskId,
4538
4587
  skill: val.skillTag,
4539
4588
  status: "error",
4540
- error: val.startError instanceof Error ? val.startError.message : String(val.startError)
4589
+ error: val.startError instanceof Error ? val.startError.message : String(val.startError),
4590
+ ...degradeField(val.taskNotes ?? [])
4541
4591
  });
4542
4592
  continue;
4543
4593
  }
4544
- const { run, taskId, skillName, skillTag, ac, onExecAbort, startedAt } = val;
4545
- runs.push({ run, taskId, skillName, skillTag, ac, onExecAbort, startedAt });
4594
+ const { run, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt } = val;
4595
+ runs.push({ run, taskId, skillName, skillTag, taskNotes, ac, onExecAbort, startedAt });
4596
+ perTaskNotes.push({ taskId, notes: taskNotes });
4546
4597
  run.result.catch(() => {});
4547
4598
  }
4548
- for (const { run, taskId, skillName, skillTag, ac, startedAt } of runs) {
4599
+ for (const { run, taskId, skillName, skillTag, taskNotes, ac, startedAt } of runs) {
4549
4600
  let outcome;
4550
4601
  let timer = null;
4551
4602
  const remainingMs = Math.max(0, wallClockBudgetMs - (Date.now() - startedAt));
@@ -4578,7 +4629,8 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4578
4629
  id: taskId,
4579
4630
  skill: skillTag,
4580
4631
  status: "completed",
4581
- result: resultText
4632
+ result: resultText,
4633
+ ...degradeField(taskNotes)
4582
4634
  });
4583
4635
  } else {
4584
4636
  const diag = typeof outcome?.diagnostic === "string" ? outcome.diagnostic : undefined;
@@ -4588,7 +4640,8 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4588
4640
  status: "failed",
4589
4641
  error: `stopReason: ${outcome?.stopReason ?? "unknown"}` + (diag === undefined ? "" : `; diagnostic: ${diag}`),
4590
4642
  stopReason: outcome?.stopReason,
4591
- ...diag === undefined ? {} : { diagnostic: diag }
4643
+ ...diag === undefined ? {} : { diagnostic: diag },
4644
+ ...degradeField(taskNotes)
4592
4645
  });
4593
4646
  }
4594
4647
  } catch (e) {
@@ -4596,7 +4649,8 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
4596
4649
  id: taskId,
4597
4650
  skill: skillTag,
4598
4651
  status: "error",
4599
- error: e instanceof Error ? e.message : String(e)
4652
+ error: e instanceof Error ? e.message : String(e),
4653
+ ...degradeField(taskNotes)
4600
4654
  });
4601
4655
  } finally {
4602
4656
  if (timer)
@@ -4672,7 +4726,14 @@ ${r.result}
4672
4726
  ctx?.logger?.warn?.("[cohub budget] batch:total:拼装结果 " + fullChars + " 字符 ≈ " + approxTokens(fullChars) + " tokens 超过总预算 " + budget.batchTotalMaxChars + " 字符,已裁剪;各任务全文见各自的 locator。仅告警,不阻断。");
4673
4727
  }
4674
4728
  maybeDeferTodoNudge(exec);
4675
- return statsLine + output;
4729
+ const allNotes = [];
4730
+ for (const { taskId, notes } of perTaskNotes) {
4731
+ const echoTaskId = firstLineClamped(taskId, BATCH_TASK_ID_ECHO_MAX);
4732
+ for (const note of notes) {
4733
+ allNotes.push({ id: note.id, what: echoTaskId + " " + note.what, effect: note.effect, reason: note.reason });
4734
+ }
4735
+ }
4736
+ return statsLine + output + formatDegradeNotes(allNotes);
4676
4737
  }
4677
4738
  });
4678
4739
  }
@@ -5950,6 +6011,12 @@ function applyDiscoveryCoverage(coverage, discovery, childReadFailed = 0) {
5950
6011
  coverage.samplingNote = undefined;
5951
6012
  }
5952
6013
  }
6014
+ function throwIfAborted(signal) {
6015
+ if (signal?.aborted) {
6016
+ const reason = signal.reason;
6017
+ throw reason instanceof Error ? reason : new Error("分析已取消(" + String(reason ?? "aborted") + ")");
6018
+ }
6019
+ }
5953
6020
  async function findChildIds(ctx, rootId, signal) {
5954
6021
  try {
5955
6022
  const trace = ctx?.sessionQuery?.traceSession;
@@ -5967,6 +6034,7 @@ async function findChildIds(ctx, rootId, signal) {
5967
6034
  }
5968
6035
  }
5969
6036
  } catch (error) {
6037
+ throwIfAborted(signal);
5970
6038
  ctx.logger?.warn?.("[cohub review] traceSession 失败:" + String(error?.message ?? error));
5971
6039
  }
5972
6040
  try {
@@ -6004,6 +6072,7 @@ async function findChildIds(ctx, rootId, signal) {
6004
6072
  }
6005
6073
  return toDiscovery(found, "list");
6006
6074
  } catch (error) {
6075
+ throwIfAborted(signal);
6007
6076
  ctx.logger?.warn?.("[cohub review] listSessions 失败:" + String(error?.message ?? error));
6008
6077
  }
6009
6078
  return { ids: [], total: 0, truncated: false, source: "list" };
@@ -6029,7 +6098,10 @@ function appendErrorLog(cwd, sessionId, message) {
6029
6098
  mkdirSync5(dirname5(logPath), { recursive: true });
6030
6099
  appendFileSync(logPath, new Date().toISOString() + "\t" + sessionId + "\t" + message.replace(/\s+/g, " ").slice(0, 500) + `
6031
6100
  `, "utf8");
6032
- } catch {}
6101
+ return logPath;
6102
+ } catch {
6103
+ return null;
6104
+ }
6033
6105
  }
6034
6106
  function writeErrorRecord(cwd, sessionId, error) {
6035
6107
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
@@ -6364,6 +6436,7 @@ async function readRootSession(ctx, sessionId, signal) {
6364
6436
  try {
6365
6437
  read = await ctx.sessionQuery.readSession(current, signal);
6366
6438
  } catch (error) {
6439
+ throwIfAborted(signal);
6367
6440
  failed = "根会话读取失败(" + String(error?.message ?? error) + ")";
6368
6441
  ctx.logger?.warn?.("[cohub review] " + failed + ",降级为空事件继续出报告");
6369
6442
  read = { session: { id: current }, events: [] };
@@ -6379,6 +6452,7 @@ async function readRootSession(ctx, sessionId, signal) {
6379
6452
  try {
6380
6453
  parentRead = await ctx.sessionQuery.readSession(parent, signal);
6381
6454
  } catch (error) {
6455
+ throwIfAborted(signal);
6382
6456
  ctx.logger?.warn?.("[cohub review] 上溯父会话失败,以 " + current + " 为根:" + String(error?.message ?? error));
6383
6457
  break;
6384
6458
  }
@@ -6388,15 +6462,25 @@ async function readRootSession(ctx, sessionId, signal) {
6388
6462
  }
6389
6463
  return { sessionId: current, read, failed };
6390
6464
  }
6391
- async function runAnalysis(ctx, agent, sessionId, cwdHint, withLlm) {
6465
+ async function runAnalysis(req) {
6466
+ const { ctx, agent, sessionId, cwdHint, withLlm } = req;
6467
+ const external = req.signal;
6392
6468
  const controller = new AbortController;
6393
- const timer = setTimeout(() => controller.abort(), ANALYSIS_TIMEOUT_MS);
6394
- const signal = controller.signal;
6469
+ const onExternalAbort = () => controller.abort(external?.reason);
6470
+ const timer = setTimeout(() => controller.abort(new Error("分析超时(" + Math.round(ANALYSIS_TIMEOUT_MS / 1000) + " 秒)")), ANALYSIS_TIMEOUT_MS);
6471
+ if (external) {
6472
+ if (external.aborted)
6473
+ onExternalAbort();
6474
+ else
6475
+ external.addEventListener("abort", onExternalAbort, { once: true });
6476
+ }
6395
6477
  try {
6396
- await runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal);
6478
+ return { ok: true, ...await runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, controller.signal) };
6397
6479
  } catch (error) {
6480
+ const reason = String(error?.message ?? error);
6398
6481
  const errorPath = writeErrorRecord(cwdHint, sessionId, error);
6399
- ctx.logger?.warn?.("[cohub review] 分析失败(error-*.json " + (errorPath !== null ? "已" : "未") + "落盘):" + String(error?.message ?? error));
6482
+ const logPath = appendErrorLog(cwdHint, sessionId, reason);
6483
+ ctx.logger?.warn?.("[cohub review] 分析失败(error-*.json " + (errorPath !== null ? "已" : "未") + "落盘):" + reason);
6400
6484
  if (errorPath !== null) {
6401
6485
  try {
6402
6486
  updateIndex({
@@ -6408,15 +6492,16 @@ async function runAnalysis(ctx, agent, sessionId, cwdHint, withLlm) {
6408
6492
  jsonPath: errorPath,
6409
6493
  mdPath: null,
6410
6494
  projectCopyPath: null,
6411
- note: "本次复盘整体失败,仅落盘 error 记录:" + String(error?.message ?? error).slice(0, 200),
6495
+ note: "本次复盘整体失败,仅落盘 error 记录:" + reason.slice(0, 200),
6412
6496
  lineageTotal: undefined,
6413
6497
  sessionsTruncated: undefined
6414
6498
  });
6415
6499
  } catch {}
6416
6500
  }
6417
- throw error;
6501
+ return { ok: false, reason, errorPath, logPath };
6418
6502
  } finally {
6419
6503
  clearTimeout(timer);
6504
+ external?.removeEventListener("abort", onExternalAbort);
6420
6505
  }
6421
6506
  }
6422
6507
  async function runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal) {
@@ -6433,6 +6518,7 @@ async function runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal)
6433
6518
  const read = await ctx.sessionQuery.readSession(childId, signal);
6434
6519
  children.push(toSessionEvents(read, childId));
6435
6520
  } catch (error) {
6521
+ throwIfAborted(signal);
6436
6522
  childReadFailed++;
6437
6523
  gaps.push(childId + ": 子会话读取失败(" + String(error?.message ?? error) + ")");
6438
6524
  }
@@ -6485,6 +6571,7 @@ async function runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal)
6485
6571
  analysis.status = "failed";
6486
6572
  analysis.error = result.reason;
6487
6573
  ctx.logger?.warn?.("[cohub review] LLM 分析失败:" + result.reason);
6574
+ throwIfAborted(signal);
6488
6575
  }
6489
6576
  } else {
6490
6577
  analysis.status = "completed";
@@ -6527,44 +6614,126 @@ async function runAnalysisInner(ctx, agent, sessionId, cwdHint, withLlm, signal)
6527
6614
  } catch (error) {
6528
6615
  ctx.logger?.warn?.("[cohub review] 复盘索引更新异常:" + String(error?.message ?? error));
6529
6616
  }
6617
+ return {
6618
+ report,
6619
+ jsonPath,
6620
+ mdPath: mdOk ? mdPath : null,
6621
+ projectCopyPath: copy.path,
6622
+ persisted: jsonOk && mdOk
6623
+ };
6530
6624
  }
6531
6625
  function cwdHintOf(inv) {
6532
6626
  const cwd = inv?.agent?.session?.header?.cwd ?? inv?.agent?.session?.meta?.cwd ?? inv?.agent?.options?.cwd ?? null;
6533
6627
  return typeof cwd === "string" && cwd.length > 0 ? cwd : null;
6534
6628
  }
6535
6629
  var inFlight = new Set;
6630
+ function formatElapsed(ms) {
6631
+ const safe = Number.isFinite(ms) && ms >= 0 ? ms : 0;
6632
+ return safe < 1000 ? (safe / 1000).toFixed(1) + "s" : Math.round(safe / 1000) + "s";
6633
+ }
6634
+ function kindBreakdown(report) {
6635
+ const order = ["issue", "praise", "observation", "suggestion"];
6636
+ const counts = new Map;
6637
+ for (const f of report.findings ?? []) {
6638
+ const kind = typeof f?.kind === "string" ? f.kind : "observation";
6639
+ counts.set(kind, (counts.get(kind) ?? 0) + 1);
6640
+ }
6641
+ const parts = [];
6642
+ for (const kind of order) {
6643
+ const n = counts.get(kind);
6644
+ if (n !== undefined && n > 0)
6645
+ parts.push(kind + " " + n);
6646
+ }
6647
+ for (const [kind, n] of counts) {
6648
+ if (!order.includes(kind))
6649
+ parts.push(kind + " " + n);
6650
+ }
6651
+ return parts.length > 0 ? "(" + parts.join(" / ") + ")" : "";
6652
+ }
6653
+ function formatSuccessText(art, elapsedMs, withLlm) {
6654
+ const report = art.report;
6655
+ const lines = [];
6656
+ const status = report.analysis?.status ?? "completed";
6657
+ const head = status === "completed" ? "报告已生成" : "报告已生成(分析未完整完成)";
6658
+ lines.push(head + "(用时 " + formatElapsed(elapsedMs) + (withLlm ? "" : ",仅统计,跳过 LLM") + ")");
6659
+ const findings = Array.isArray(report.findings) ? report.findings : [];
6660
+ lines.push("- 结论:" + findings.length + " 条" + kindBreakdown(report));
6661
+ const cov = report.coverage;
6662
+ const analyzed = typeof cov?.sessionsAnalyzed === "number" ? cov.sessionsAnalyzed : undefined;
6663
+ const total = typeof cov?.lineageTotal === "number" ? cov.lineageTotal : undefined;
6664
+ if (analyzed !== undefined && total !== undefined) {
6665
+ const note = cov.samplingNote ? "(" + cov.samplingNote + ")" : "";
6666
+ lines.push("- 覆盖:已分析 " + analyzed + " / 共 " + total + " 个子会话" + note);
6667
+ } else {
6668
+ lines.push("- 覆盖:已读取 " + (Array.isArray(report.sessions) ? report.sessions.length : 0) + " 个会话(子会话总数未知;根会话 + 子会话)");
6669
+ }
6670
+ const reportPath = art.projectCopyPath ?? art.mdPath ?? art.jsonPath;
6671
+ lines.push("- 报告:" + reportPath);
6672
+ if (art.projectCopyPath === null && art.mdPath !== null) {
6673
+ lines.push("- 说明:项目内副本未写入(" + (report.coverage?.gaps?.length ? "见报告缺口" : "cwd 不可用或 .gitignore 冲突") + "),以上为全局目录路径");
6674
+ }
6675
+ if (!art.persisted) {
6676
+ lines.push("- 注意:报告落盘不完整(JSON/MD 至少一个写失败),路径可能不可读");
6677
+ }
6678
+ if (cov?.sessionsTruncated === true) {
6679
+ lines.push("- 提示:**未分析的子会话不在结论内**(结论不得外推到这些子会话)");
6680
+ }
6681
+ if (cov?.inputTruncated === true) {
6682
+ lines.push("- 提示:喂给模型的输入被裁剪过,结论不得外推到未读区间");
6683
+ }
6684
+ if (status !== "completed") {
6685
+ const reason = typeof report.analysis?.error === "string" && report.analysis.error.length > 0 ? report.analysis.error : "原因未记录(详见报告 analysis 段)";
6686
+ lines.push("- 状态:" + status + " —— " + reason);
6687
+ }
6688
+ return lines.join(`
6689
+ `);
6690
+ }
6691
+ function formatErrorText(outcome, elapsedMs) {
6692
+ const lines = ["分析失败:" + outcome.reason + "(用时 " + formatElapsed(elapsedMs) + ")"];
6693
+ if (outcome.errorPath !== null)
6694
+ lines.push("- 错误详情:" + outcome.errorPath);
6695
+ else
6696
+ lines.push("- 错误详情:未落盘(写 error-*.json 失败)");
6697
+ if (outcome.logPath !== null)
6698
+ lines.push("- 错误日志:" + outcome.logPath);
6699
+ else
6700
+ lines.push("- 错误日志:未落盘(写 _errors.log 失败)");
6701
+ return lines.join(`
6702
+ `);
6703
+ }
6536
6704
  function registerReviewCommand(ctx) {
6537
- const handler = (inv) => {
6705
+ const handler = async (inv) => {
6706
+ const startedAt = Date.now();
6707
+ let sessionId = null;
6708
+ let cwdHint = null;
6709
+ let claimed = false;
6538
6710
  try {
6539
- const sessionId = inv?.agent?.session?.id;
6540
- if (typeof sessionId !== "string" || sessionId.length === 0) {
6711
+ const sid = inv?.agent?.session?.id;
6712
+ if (typeof sid !== "string" || sid.length === 0) {
6541
6713
  return { kind: "error", text: "无法确定当前会话 id,已跳过复盘。" };
6542
6714
  }
6543
- if (inFlight.has(sessionId)) {
6544
- return { kind: "error", text: "上一次分析仍在进行中,请稍候(会话 " + sessionId + ")。" };
6715
+ sessionId = sid;
6716
+ if (inFlight.has(sid)) {
6717
+ return { kind: "error", text: "上一次分析仍在进行中,请稍候(会话 " + sid + ")。" };
6545
6718
  }
6546
6719
  const rawInput = typeof inv?.rawInput === "string" ? inv.rawInput : "";
6547
6720
  const withLlm = !/(^|\s)--no-llm(\s|$)/.test(rawInput);
6548
- const cwdHint = cwdHintOf(inv);
6549
- inFlight.add(sessionId);
6550
- (async () => {
6551
- try {
6552
- await runAnalysis(ctx, inv?.agent, sessionId, cwdHint, withLlm);
6553
- } catch (error) {
6554
- const message = String(error?.message ?? error);
6555
- appendErrorLog(cwdHint, sessionId, message);
6556
- ctx.logger?.warn?.("[cohub review] 报告生成失败:" + message);
6557
- } finally {
6558
- inFlight.delete(sessionId);
6559
- }
6560
- })();
6561
- const dir = reviewStorePath(cwdHint, sessionId, "").replace(/[\\/]$/, "");
6562
- return {
6563
- kind: "success",
6564
- text: "正在生成报告…(" + (withLlm ? "含一次 LLM 分析" : "仅统计,跳过 LLM") + ")输出目录:" + dir
6565
- };
6721
+ cwdHint = cwdHintOf(inv);
6722
+ inFlight.add(sid);
6723
+ claimed = true;
6724
+ const outcome = await runAnalysis({ ctx, agent: inv?.agent, sessionId: sid, cwdHint, withLlm, signal: inv?.signal });
6725
+ if (outcome.ok) {
6726
+ return { kind: "success", text: formatSuccessText(outcome, Date.now() - startedAt, withLlm) };
6727
+ }
6728
+ return { kind: "error", text: formatErrorText(outcome, Date.now() - startedAt) };
6566
6729
  } catch (error) {
6567
- return { kind: "error", text: "复盘命令启动失败:" + String(error?.message ?? error) };
6730
+ const message = String(error?.message ?? error);
6731
+ if (sessionId !== null)
6732
+ appendErrorLog(cwdHint, sessionId, message);
6733
+ return { kind: "error", text: "复盘命令执行异常:" + message };
6734
+ } finally {
6735
+ if (claimed && sessionId !== null)
6736
+ inFlight.delete(sessionId);
6568
6737
  }
6569
6738
  };
6570
6739
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cohub",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "description": "DeepSeek Harness 版 CoHub:中文智能体编排——用户可选 2 种工作模式(co-orchestrator 纯调度 / cohub-cordis 创造模式)+ 13 个专职代理技能 + 多模型共识;另由 cohub-subagent-readonly / cohub-subagent-write 两个支撑 preset 实现子代理读写硬隔离(共 4 个 preset)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",