dsh-cohub 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +227 -230
- package/lib/index.js +1502 -37
- package/package.json +2 -2
package/lib/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
|
-
import { readFileSync as
|
|
3
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
4
4
|
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { dshHomePath as
|
|
5
|
+
import { dshHomePath as dshHomePath4 } from "@deepseek-ai/dsh-home-paths";
|
|
6
6
|
|
|
7
7
|
// src/preset-install.ts
|
|
8
8
|
import { createHash } from "node:crypto";
|
|
@@ -271,7 +271,7 @@ var COHUB_SKILLS = [
|
|
|
271
271
|
{
|
|
272
272
|
name: "co-orchestrator",
|
|
273
273
|
description: "纯调度——分析需求→委派→审核(禁止直接文件操作)",
|
|
274
|
-
brief: "你是纯调度者:只用调度工具(delegate/delegate_batch/todo_write/ask_user_question/job_*),禁 read/grep/edit/write/bash
|
|
274
|
+
brief: "你是纯调度者:只用调度工具(delegate/delegate_batch/todo_write/ask_user_question/job_*),禁 read/grep/edit/write/bash。先声明档位再定步数:T0 直接答;T1 只 1 个 co-fixer(自验+提交);T2 ≤1 批探索+planner(8 行内)+1-2 fixer;T3 才走五阶段。UI 类改动才派 co-designer。已核实事实/已批计划直接复用,不重跑探索。并行省墙钟非凑数:无第二个独立任务时单 delegate 即推荐。单批≤maxParallelBatch,单执行≤10 分钟。全中文。",
|
|
275
275
|
source: "dsh-cohub",
|
|
276
276
|
content: `<角色>
|
|
277
277
|
你是纯调度者(Orchestrator)。职责:按任务分档决定流程深度——分析需求并在回复首行声明档位(T0 ~ T3,见「任务分档」)→ 按档委派(T2/T3:信息收集 → co-planner 方案 → 审核 → 执行 → 验证;T1:单委派 co-fixer;T0:不委派)→ 审核并汇总结果。**绝不亲自操作,全部委派(规则2;唯一例外是读取自产 locator,见规则2「locator 读取例外」)**。可用工具仅限调度工具(skill、delegate、delegate_batch、workflow、todo_write、ask_user_question、job_list/job_output、create_goal)。delegate 调用必须同时提供 skill 与 prompt,缺一不可。本会话为 Native 模式(工具由模型直接调用,无 run_code / TypeScript 执行器);单条消息可发出多个 delegate tool_use 块,由 agent loop 并发执行。
|
|
@@ -1084,7 +1084,7 @@ Orchestrator 会在 prompt 中明确指定:
|
|
|
1084
1084
|
{
|
|
1085
1085
|
name: "co-planner",
|
|
1086
1086
|
description: "方案制定——综合需求+信息+规范输出任务分解",
|
|
1087
|
-
brief: "你是方案制定代理(orchestrator 仅在 T2/T3 调用,T1 不参与):综合需求、信息收集与规范分析,输出可直接派发的任务分解。只读不改文件。必须含:子任务清单(≤6 条、每条一行,超出则合并或建议拆多次交付)及依赖、每项委派对象(@explorer/@fixer/@oracle/@designer/@observer 等)、并行化策略(T2/T3
|
|
1087
|
+
brief: "你是方案制定代理(orchestrator 仅在 T2/T3 调用,T1 不参与):综合需求、信息收集与规范分析,输出可直接派发的任务分解。只读不改文件。必须含:子任务清单(≤6 条、每条一行,超出则合并或建议拆多次交付)及依赖、每项委派对象(@explorer/@fixer/@oracle/@designer/@observer 等)、并行化策略(T2/T3 必含:可独立验收且无依赖/写冲突的单元并行同批;同问题多文件/多搜索交单代理内部并行,不按文件数拆;同文件写冲突串行;每批≤3)、验证步骤;具体到文件与操作粒度。不评估、不重述已知事实。中文回复。",
|
|
1088
1088
|
source: "dsh-cohub",
|
|
1089
1089
|
content: `你是方案制定代理——负责任务分解和委派策略。
|
|
1090
1090
|
|
|
@@ -1256,8 +1256,58 @@ var DEFAULT_ENV_CONTRACT = `执行器环境契约(通用原则 + 探测式自
|
|
|
1256
1256
|
2. 以通过验证的写法为准执行后续步骤;
|
|
1257
1257
|
3. 若所有候选写法都失败,立即停止并把探针错误原样回传,不要盲目重试或猜测。`;
|
|
1258
1258
|
|
|
1259
|
+
// src/error-signature.mjs
|
|
1260
|
+
var DEFAULT_OPTS = Object.freeze({ digits: "#", maxLen: 240, prefix: "err:" });
|
|
1261
|
+
function blocksText(output) {
|
|
1262
|
+
if (!Array.isArray(output))
|
|
1263
|
+
return "";
|
|
1264
|
+
const parts = [];
|
|
1265
|
+
for (const b of output) {
|
|
1266
|
+
if (b && typeof b === "object" && b.type === "text" && typeof b.text === "string")
|
|
1267
|
+
parts.push(b.text);
|
|
1268
|
+
}
|
|
1269
|
+
return parts.join(`
|
|
1270
|
+
`);
|
|
1271
|
+
}
|
|
1272
|
+
function normalizeErrorSignature(data, opts) {
|
|
1273
|
+
const digits = opts && opts.digits === "keep" ? "keep" : DEFAULT_OPTS.digits;
|
|
1274
|
+
const maxLen = opts && typeof opts.maxLen === "number" && Number.isFinite(opts.maxLen) ? opts.maxLen : DEFAULT_OPTS.maxLen;
|
|
1275
|
+
const prefix = opts && typeof opts.prefix === "string" ? opts.prefix : DEFAULT_OPTS.prefix;
|
|
1276
|
+
const finish = (text) => {
|
|
1277
|
+
const normalized = digits === "#" ? String(text).replace(/\d+/g, "#") : String(text);
|
|
1278
|
+
const body = normalized.slice(0, maxLen);
|
|
1279
|
+
return prefix + body;
|
|
1280
|
+
};
|
|
1281
|
+
if (typeof data === "string") {
|
|
1282
|
+
const first = data.split(/\r?\n/)[0].trim().replace(/^Error:\s*/, "");
|
|
1283
|
+
if (!first)
|
|
1284
|
+
return null;
|
|
1285
|
+
return finish(first);
|
|
1286
|
+
}
|
|
1287
|
+
if (!data || typeof data !== "object")
|
|
1288
|
+
return null;
|
|
1289
|
+
const err = data.error;
|
|
1290
|
+
let text = "";
|
|
1291
|
+
if (typeof err === "string" && err.trim()) {
|
|
1292
|
+
text = err.trim();
|
|
1293
|
+
} else if (err && typeof err === "object") {
|
|
1294
|
+
const msg = typeof err.message === "string" ? err.message : "";
|
|
1295
|
+
const code = typeof err.code === "string" ? err.code : "";
|
|
1296
|
+
if (msg || code)
|
|
1297
|
+
text = (code ? code + " " : "") + msg;
|
|
1298
|
+
} else {
|
|
1299
|
+
text = blocksText(data.message && data.message.content);
|
|
1300
|
+
}
|
|
1301
|
+
const trimmed = String(text).trim();
|
|
1302
|
+
if (!trimmed) {
|
|
1303
|
+
const isError = data.message && data.message.isError === true || data.isError === true;
|
|
1304
|
+
return isError ? prefix + "unknown" : null;
|
|
1305
|
+
}
|
|
1306
|
+
return finish(trimmed);
|
|
1307
|
+
}
|
|
1308
|
+
|
|
1259
1309
|
// src/env-signatures.ts
|
|
1260
|
-
var CACHE_VERSION =
|
|
1310
|
+
var CACHE_VERSION = 2;
|
|
1261
1311
|
var DEFAULT_TTL_MS = 604800000;
|
|
1262
1312
|
var DEFAULT_ERROR_CATEGORIES = [
|
|
1263
1313
|
"require is not defined",
|
|
@@ -1386,23 +1436,6 @@ function pickEnvContractText(args) {
|
|
|
1386
1436
|
}
|
|
1387
1437
|
return { text: DEFAULT_ENV_CONTRACT, source: "default" };
|
|
1388
1438
|
}
|
|
1389
|
-
function normalizeErrorSignature(data) {
|
|
1390
|
-
if (!data || typeof data !== "object")
|
|
1391
|
-
return null;
|
|
1392
|
-
const err = data.error;
|
|
1393
|
-
if (typeof err === "string" && err.trim())
|
|
1394
|
-
return "err:" + err.trim().slice(0, 120);
|
|
1395
|
-
if (err && typeof err === "object") {
|
|
1396
|
-
const msg = typeof err.message === "string" ? err.message : "";
|
|
1397
|
-
const code = typeof err.code === "string" ? err.code : "";
|
|
1398
|
-
if (msg || code)
|
|
1399
|
-
return "err:" + (code ? code + " " : "") + msg.slice(0, 120);
|
|
1400
|
-
}
|
|
1401
|
-
const text = contentText(data?.message?.content).trim();
|
|
1402
|
-
if (text)
|
|
1403
|
-
return "err:" + text.slice(0, 120);
|
|
1404
|
-
return data?.message?.isError === true ? "err:unknown" : null;
|
|
1405
|
-
}
|
|
1406
1439
|
function classifyEnvContractError(signature, categories) {
|
|
1407
1440
|
const cats = categories && categories.length > 0 ? categories : DEFAULT_ERROR_CATEGORIES;
|
|
1408
1441
|
const lower = signature.toLowerCase();
|
|
@@ -1894,6 +1927,35 @@ function intersectWithRestrictable(filter, restrictableNames) {
|
|
|
1894
1927
|
};
|
|
1895
1928
|
return next.allow !== undefined || next.deny !== undefined ? next : undefined;
|
|
1896
1929
|
}
|
|
1930
|
+
function describeDegradeReason(error) {
|
|
1931
|
+
const message = error?.message;
|
|
1932
|
+
const raw = typeof message === "string" && message.length > 0 ? message : String(error);
|
|
1933
|
+
const firstLine = (raw.split(/\r?\n/)[0] ?? "").replace(/\s+/g, " ").trim();
|
|
1934
|
+
const text = firstLine.length > 0 ? firstLine : "unknown";
|
|
1935
|
+
return text.length > 200 ? text.slice(0, 200) : text;
|
|
1936
|
+
}
|
|
1937
|
+
function formatDegradeNotes(notes) {
|
|
1938
|
+
if (notes === undefined || notes.length === 0)
|
|
1939
|
+
return "";
|
|
1940
|
+
if (notes.length === 1) {
|
|
1941
|
+
const only = notes[0];
|
|
1942
|
+
return `
|
|
1943
|
+
|
|
1944
|
+
[` + only.what + "," + only.effect + ":" + only.reason + "]";
|
|
1945
|
+
}
|
|
1946
|
+
return `
|
|
1947
|
+
|
|
1948
|
+
[降级提示:` + notes.map((n) => n.what + "," + n.effect + "(" + n.reason + ")").join(";") + "]";
|
|
1949
|
+
}
|
|
1950
|
+
function upsertDegradeNote(notes, note) {
|
|
1951
|
+
if (notes === undefined)
|
|
1952
|
+
return;
|
|
1953
|
+
const index = notes.findIndex((n) => n.id === note.id);
|
|
1954
|
+
if (index >= 0)
|
|
1955
|
+
notes[index] = note;
|
|
1956
|
+
else
|
|
1957
|
+
notes.push(note);
|
|
1958
|
+
}
|
|
1897
1959
|
var PRESET_REJECTED = /PRESET_UNAVAILABLE|agent-preset\/(not-found|invalid)|Unknown agent preset|agent preset|preset revision|preset.*unavailable/i;
|
|
1898
1960
|
var TOOL_FILTER_REJECTED = /unknown global tool|toolFilter|tool filter|capabilit/i;
|
|
1899
1961
|
var RESTRICTABLE_NAMES_IN_ERROR = /known global tools:\s*([^\n;]*)/i;
|
|
@@ -1922,6 +1984,13 @@ async function startSubagentRun(ctx, provider, spec) {
|
|
|
1922
1984
|
const aborted = spec.signal?.aborted === true || /abort/i.test(message);
|
|
1923
1985
|
if (aborted || !PRESET_REJECTED.test(message))
|
|
1924
1986
|
throw error;
|
|
1987
|
+
const reason = describeDegradeReason(error);
|
|
1988
|
+
upsertDegradeNote(spec.degradeNotes, {
|
|
1989
|
+
id: "preset",
|
|
1990
|
+
what: "子代理 preset 未生效",
|
|
1991
|
+
effect: "已降级为继承父 preset",
|
|
1992
|
+
reason
|
|
1993
|
+
});
|
|
1925
1994
|
ctx?.logger?.warn?.('[cohub preset] 子代理 preset "' + spec.agentPreset + '" 不可用,已降级为继承父 preset 重试:' + message.slice(0, 300) + "(委派继续,不阻断)");
|
|
1926
1995
|
return spawnWithToolFilterFallout(ctx, provider, { ...spec, agentPreset: undefined });
|
|
1927
1996
|
}
|
|
@@ -1932,7 +2001,16 @@ async function spawnWithToolFilterFallout(ctx, provider, spec) {
|
|
|
1932
2001
|
let lastFilterError;
|
|
1933
2002
|
for (let attempt = 0;attempt < 3; attempt++) {
|
|
1934
2003
|
try {
|
|
1935
|
-
|
|
2004
|
+
const handle = await startSubagentRunOnce(ctx, provider, { ...spec, toolFilter: filter });
|
|
2005
|
+
if (wanted !== undefined && filter === undefined) {
|
|
2006
|
+
upsertDegradeNote(spec.degradeNotes, {
|
|
2007
|
+
id: "toolfilter",
|
|
2008
|
+
what: "工具裁剪未生效",
|
|
2009
|
+
effect: "子代理使用全量工具",
|
|
2010
|
+
reason: lastFilterError === undefined ? "可限制工具清单交集为空,无可裁项" : describeDegradeReason(lastFilterError)
|
|
2011
|
+
});
|
|
2012
|
+
}
|
|
2013
|
+
return handle;
|
|
1936
2014
|
} catch (error) {
|
|
1937
2015
|
const message = error instanceof Error ? error.message : String(error);
|
|
1938
2016
|
const aborted = spec.signal?.aborted === true || /abort/i.test(message);
|
|
@@ -1951,6 +2029,74 @@ async function spawnWithToolFilterFallout(ctx, provider, spec) {
|
|
|
1951
2029
|
}
|
|
1952
2030
|
throw lastFilterError ?? new Error("cohub: subagent spawn failed after toolFilter fallout");
|
|
1953
2031
|
}
|
|
2032
|
+
function resolveAgentsService(ctx) {
|
|
2033
|
+
const pick = (fn) => {
|
|
2034
|
+
try {
|
|
2035
|
+
const value = fn();
|
|
2036
|
+
return value === null ? undefined : value;
|
|
2037
|
+
} catch {
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
};
|
|
2041
|
+
const viaGet = pick(() => typeof ctx?.get === "function" ? ctx.get("agents") : undefined);
|
|
2042
|
+
if (viaGet !== undefined)
|
|
2043
|
+
return viaGet;
|
|
2044
|
+
const viaReflect = pick(() => ctx?.reflect?.get?.("agents", false));
|
|
2045
|
+
if (viaReflect !== undefined)
|
|
2046
|
+
return viaReflect;
|
|
2047
|
+
return pick(() => ctx?.agents);
|
|
2048
|
+
}
|
|
2049
|
+
function applyChildToolFilterDirectly(ctx, childId, filter, degradeNotes) {
|
|
2050
|
+
if (filter === undefined)
|
|
2051
|
+
return;
|
|
2052
|
+
const noteFailure = (reason) => {
|
|
2053
|
+
upsertDegradeNote(degradeNotes, {
|
|
2054
|
+
id: "toolfilter",
|
|
2055
|
+
what: "工具裁剪未生效",
|
|
2056
|
+
effect: "子代理使用全量工具(仍可见 delegate/delegate_batch 等)",
|
|
2057
|
+
reason
|
|
2058
|
+
});
|
|
2059
|
+
};
|
|
2060
|
+
const agents = resolveAgentsService(ctx);
|
|
2061
|
+
if (agents === undefined) {
|
|
2062
|
+
return;
|
|
2063
|
+
}
|
|
2064
|
+
if (childId === undefined)
|
|
2065
|
+
return;
|
|
2066
|
+
let child;
|
|
2067
|
+
let tools;
|
|
2068
|
+
try {
|
|
2069
|
+
child = agents.get(childId);
|
|
2070
|
+
tools = child?.ctx?.tools;
|
|
2071
|
+
} catch {
|
|
2072
|
+
tools = undefined;
|
|
2073
|
+
}
|
|
2074
|
+
if (tools === undefined || typeof tools.restrict !== "function") {
|
|
2075
|
+
noteFailure(child === undefined ? "子代理创建后未在 agents 注册表中存活(无法施加 restrict)" : "子代理 ctx 上取不到 tools 服务(无法施加 restrict)");
|
|
2076
|
+
return;
|
|
2077
|
+
}
|
|
2078
|
+
try {
|
|
2079
|
+
tools.restrict(filter);
|
|
2080
|
+
return;
|
|
2081
|
+
} catch (error) {
|
|
2082
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2083
|
+
const learned = parseRestrictableNames(message);
|
|
2084
|
+
if (learned !== undefined) {
|
|
2085
|
+
learnedRestrictableNames = learned;
|
|
2086
|
+
const next = intersectWithRestrictable(filter, learned);
|
|
2087
|
+
if (next !== undefined) {
|
|
2088
|
+
try {
|
|
2089
|
+
tools.restrict(next);
|
|
2090
|
+
return;
|
|
2091
|
+
} catch (retryError) {
|
|
2092
|
+
noteFailure(describeDegradeReason(retryError));
|
|
2093
|
+
return;
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
noteFailure(describeDegradeReason(error));
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
1954
2100
|
async function startSubagentRunOnce(ctx, provider, spec) {
|
|
1955
2101
|
const subagents = ctx?.subagents;
|
|
1956
2102
|
if (!subagents)
|
|
@@ -1971,6 +2117,7 @@ async function startSubagentRunOnce(ctx, provider, spec) {
|
|
|
1971
2117
|
signal,
|
|
1972
2118
|
delivery: "caller"
|
|
1973
2119
|
});
|
|
2120
|
+
applyChildToolFilterDirectly(ctx, receipt.childId, spec.toolFilter, spec.degradeNotes);
|
|
1974
2121
|
return {
|
|
1975
2122
|
id: receipt.childId,
|
|
1976
2123
|
result: receipt.result,
|
|
@@ -2130,7 +2277,7 @@ class StallWatchdog {
|
|
|
2130
2277
|
this.s.lastToolAt = now;
|
|
2131
2278
|
this.s.lastToolResultAt = now;
|
|
2132
2279
|
if (isError) {
|
|
2133
|
-
const sig = normalizeErrorSignature(d) ?? "err:unknown";
|
|
2280
|
+
const sig = normalizeErrorSignature(d, { digits: "keep" }) ?? "err:unknown";
|
|
2134
2281
|
this.s.consecutiveErrors = sig === this.s.lastErrorSig ? this.s.consecutiveErrors + 1 : 1;
|
|
2135
2282
|
this.s.lastErrorSig = sig;
|
|
2136
2283
|
if (key && key === this.s.lastCallKey)
|
|
@@ -2499,26 +2646,26 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2499
2646
|
const envSig = createEnvSig(config);
|
|
2500
2647
|
return defineTool({
|
|
2501
2648
|
name: "delegate",
|
|
2502
|
-
description: "
|
|
2649
|
+
description: "委派单一子代理:按 skill 路由模型并注入角色指令后运行。" + "background:true=强制后台返 jobId;false=强制前台;缺省=按配置。",
|
|
2503
2650
|
parameters: {
|
|
2504
2651
|
skill: {
|
|
2505
2652
|
type: "string",
|
|
2506
2653
|
required: true,
|
|
2507
|
-
description: "
|
|
2654
|
+
description: "必填,co-* 代理名(如 co-fixer/co-explorer/co-oracle)"
|
|
2508
2655
|
},
|
|
2509
2656
|
prompt: {
|
|
2510
2657
|
type: "string",
|
|
2511
2658
|
required: true,
|
|
2512
|
-
description: "
|
|
2659
|
+
description: "必填,自包含:目标、路径、约束、输出格式"
|
|
2513
2660
|
},
|
|
2514
2661
|
background: {
|
|
2515
2662
|
type: "boolean",
|
|
2516
|
-
description: "true
|
|
2663
|
+
description: "true=强制后台返 jobId;false=强制前台同步;缺省=按配置(enabled && skill 命中 defaultFor)"
|
|
2517
2664
|
}
|
|
2518
2665
|
},
|
|
2519
2666
|
output: DELEGATE_OUTPUT_CONFIG,
|
|
2520
2667
|
isConcurrencySafe: () => true,
|
|
2521
|
-
async execute(args, exec) {
|
|
2668
|
+
async execute(args, exec, observer) {
|
|
2522
2669
|
const parent = exec?.agent;
|
|
2523
2670
|
if (!parent)
|
|
2524
2671
|
throw new Error("delegate requires a calling agent (exec.agent was undefined)");
|
|
@@ -2538,6 +2685,7 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2538
2685
|
}
|
|
2539
2686
|
const agentOptions = await buildAgentOptions(route, ctx, skill.name);
|
|
2540
2687
|
const toolFilter = resolveSkillToolFilter(skill.name, config.toolFilter?.enabled ?? true, ctx.logger);
|
|
2688
|
+
const degradeNotes = [];
|
|
2541
2689
|
const agentPreset = resolveSkillAgentPreset(skill.name, subagentPresetEnabled);
|
|
2542
2690
|
const fp = envFingerprint();
|
|
2543
2691
|
const contractResult = resolveContractText({ enabled: envContract.enabled, text: envContract.text }, envSig, ctx, fp);
|
|
@@ -2550,6 +2698,26 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2550
2698
|
const stallState = { last: null };
|
|
2551
2699
|
let retries = 0;
|
|
2552
2700
|
for (let attempt = 0;attempt <= retry.maxRetries; attempt++) {
|
|
2701
|
+
const attemptStartedAt = Date.now();
|
|
2702
|
+
const attemptNo = attempt + 1;
|
|
2703
|
+
const reportAttempt = (childSessionId, outcome, stopReason) => {
|
|
2704
|
+
const onAttempt = observer?.onAttempt;
|
|
2705
|
+
if (!onAttempt)
|
|
2706
|
+
return;
|
|
2707
|
+
try {
|
|
2708
|
+
onAttempt.call(observer, {
|
|
2709
|
+
skill: skill.name,
|
|
2710
|
+
attempt: attemptNo,
|
|
2711
|
+
childSessionId,
|
|
2712
|
+
startedAt: attemptStartedAt,
|
|
2713
|
+
endedAt: Date.now(),
|
|
2714
|
+
outcome,
|
|
2715
|
+
...stopReason === undefined ? {} : { stopReason }
|
|
2716
|
+
});
|
|
2717
|
+
} catch (error) {
|
|
2718
|
+
ctx.logger?.warn?.("[cohub observer] onAttempt 抛出异常(已忽略):" + String(error?.message ?? error));
|
|
2719
|
+
}
|
|
2720
|
+
};
|
|
2553
2721
|
const stallNote = stallState.last ? ";停滞诊断:" + stallState.last.diagnostics : "";
|
|
2554
2722
|
const retryNote = attempt > 0 ? `
|
|
2555
2723
|
|
|
@@ -2609,7 +2777,8 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2609
2777
|
...toolFilter !== undefined ? { toolFilter } : {},
|
|
2610
2778
|
...agentPreset !== undefined ? { agentPreset } : {},
|
|
2611
2779
|
...agentOptions ? { agentOptions } : {},
|
|
2612
|
-
signal
|
|
2780
|
+
signal,
|
|
2781
|
+
degradeNotes
|
|
2613
2782
|
});
|
|
2614
2783
|
} catch (error) {
|
|
2615
2784
|
if (watchdog)
|
|
@@ -2623,12 +2792,17 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2623
2792
|
lastDiagnostic = undefined;
|
|
2624
2793
|
lastPartial = "";
|
|
2625
2794
|
stallState.last = stallInfo;
|
|
2795
|
+
if (stallInfo)
|
|
2796
|
+
reportAttempt("", "timeout", "aborted");
|
|
2797
|
+
else
|
|
2798
|
+
reportAttempt("", "aborted", "aborted");
|
|
2626
2799
|
if (!RETRYABLE.has(lastReason) || attempt >= retry.maxRetries)
|
|
2627
2800
|
break;
|
|
2628
2801
|
retries++;
|
|
2629
2802
|
await new Promise((r) => setTimeout(r, retry.retryDelayMs));
|
|
2630
2803
|
continue;
|
|
2631
2804
|
}
|
|
2805
|
+
reportAttempt("", "failed", String(error?.message ?? error));
|
|
2632
2806
|
throw error;
|
|
2633
2807
|
}
|
|
2634
2808
|
if (watchdog)
|
|
@@ -2639,6 +2813,9 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2639
2813
|
let outcome;
|
|
2640
2814
|
try {
|
|
2641
2815
|
outcome = await run.result;
|
|
2816
|
+
} catch (error) {
|
|
2817
|
+
reportAttempt(String(run?.id ?? ""), "failed", "error");
|
|
2818
|
+
throw error;
|
|
2642
2819
|
} finally {
|
|
2643
2820
|
if (learner) {
|
|
2644
2821
|
if (learner.flush()) {
|
|
@@ -2655,12 +2832,14 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2655
2832
|
} catch {}
|
|
2656
2833
|
}
|
|
2657
2834
|
if (outcome?.stopReason === "completed") {
|
|
2658
|
-
|
|
2835
|
+
reportAttempt(String(run?.id ?? ""), "completed", "completed");
|
|
2836
|
+
const budgeted = await budgetSubagentResult(ctx, exec, contentText(outcome.output), {
|
|
2659
2837
|
maxChars: resolveSkillResultMaxChars(budget, skill.name),
|
|
2660
2838
|
scope: "delegate",
|
|
2661
2839
|
label: skillTag,
|
|
2662
2840
|
enabled: budget.enabled
|
|
2663
2841
|
});
|
|
2842
|
+
return budgeted + formatDegradeNotes(degradeNotes);
|
|
2664
2843
|
}
|
|
2665
2844
|
lastReason = String(outcome?.stopReason ?? "unknown");
|
|
2666
2845
|
lastDiagnostic = typeof outcome?.diagnostic === "string" ? outcome.diagnostic : undefined;
|
|
@@ -2673,6 +2852,8 @@ function createDelegateTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
2673
2852
|
locatorFallback: "未落盘(失败路径不写盘)"
|
|
2674
2853
|
}).text : partialRaw;
|
|
2675
2854
|
stallState.last = stallInfo;
|
|
2855
|
+
const attemptOutcome = stallInfo ? "timeout" : lastReason === "aborted" ? "aborted" : "failed";
|
|
2856
|
+
reportAttempt(String(run?.id ?? ""), attemptOutcome, lastReason);
|
|
2676
2857
|
if (stallInfo && !stall.recoverable)
|
|
2677
2858
|
break;
|
|
2678
2859
|
if (!RETRYABLE.has(lastReason) || attempt >= retry.maxRetries)
|
|
@@ -3026,12 +3207,12 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
3026
3207
|
}
|
|
3027
3208
|
return defineTool3({
|
|
3028
3209
|
name: "delegate_batch",
|
|
3029
|
-
description: "
|
|
3210
|
+
description: "并发执行多个子代理任务:一次调用并行派发 N 个无依赖任务,返回各自结果。" + "每项 skill/prompt 必填,单批默认 3(上限 20),不重试。",
|
|
3030
3211
|
parameters: {
|
|
3031
3212
|
tasks: {
|
|
3032
3213
|
type: "array",
|
|
3033
3214
|
required: true,
|
|
3034
|
-
description:
|
|
3215
|
+
description: "任务列表,每项 skill/prompt 必填;上限 schedule.maxParallelBatch(默认 3,最大 20)",
|
|
3035
3216
|
items: {
|
|
3036
3217
|
type: "object",
|
|
3037
3218
|
additionalProperties: false,
|
|
@@ -3040,9 +3221,9 @@ function createDelegateBatchTool(ctx, getRoutes, config = {}, getSettings) {
|
|
|
3040
3221
|
skill: {
|
|
3041
3222
|
type: "string",
|
|
3042
3223
|
required: true,
|
|
3043
|
-
description: "
|
|
3224
|
+
description: "必填,co-* 代理名(如 co-fixer/co-explorer/co-oracle)"
|
|
3044
3225
|
},
|
|
3045
|
-
prompt: { type: "string", required: true, description: "
|
|
3226
|
+
prompt: { type: "string", required: true, description: "必填,给该代理的具体任务(自包含)" }
|
|
3046
3227
|
}
|
|
3047
3228
|
}
|
|
3048
3229
|
}
|
|
@@ -3275,6 +3456,1274 @@ ${r.result}
|
|
|
3275
3456
|
});
|
|
3276
3457
|
}
|
|
3277
3458
|
|
|
3459
|
+
// src/review-store.ts
|
|
3460
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
3461
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync3, renameSync, writeFileSync as writeFileSync3 } from "node:fs";
|
|
3462
|
+
import { dirname as dirname3 } from "node:path";
|
|
3463
|
+
import { dshHomePath as dshHomePath2 } from "@deepseek-ai/dsh-home-paths";
|
|
3464
|
+
var REVIEW_STATS_VERSION = 1;
|
|
3465
|
+
function cwdDirName(cwd) {
|
|
3466
|
+
if (typeof cwd !== "string" || cwd.length === 0)
|
|
3467
|
+
return "nocwd";
|
|
3468
|
+
return createHash2("sha256").update(cwd, "utf8").digest("hex").slice(0, 16);
|
|
3469
|
+
}
|
|
3470
|
+
function sessionDirName(sessionId) {
|
|
3471
|
+
return createHash2("sha256").update(String(sessionId), "utf8").digest("hex").slice(0, 32);
|
|
3472
|
+
}
|
|
3473
|
+
function reviewStorePath(cwd, sessionId, fileName = "stats.json") {
|
|
3474
|
+
return dshHomePath2("cohub", "reviews", cwdDirName(cwd), sessionDirName(sessionId), fileName);
|
|
3475
|
+
}
|
|
3476
|
+
function loadStats(cwd, sessionId) {
|
|
3477
|
+
const file = reviewStorePath(cwd, sessionId);
|
|
3478
|
+
try {
|
|
3479
|
+
if (!existsSync3(file))
|
|
3480
|
+
return null;
|
|
3481
|
+
const text = readFileSync3(file, "utf8");
|
|
3482
|
+
const parsed = JSON.parse(text);
|
|
3483
|
+
if (!parsed || typeof parsed !== "object")
|
|
3484
|
+
throw new Error("stats.json 结构不合法");
|
|
3485
|
+
if (parsed.version !== REVIEW_STATS_VERSION)
|
|
3486
|
+
throw new Error("stats.json 版本不符");
|
|
3487
|
+
if (typeof parsed.sessionId !== "string" || parsed.sessionId !== sessionId) {
|
|
3488
|
+
throw new Error("stats.json sessionId 不匹配");
|
|
3489
|
+
}
|
|
3490
|
+
if (!Array.isArray(parsed.turns))
|
|
3491
|
+
throw new Error("stats.json turns 不是数组");
|
|
3492
|
+
return parsed;
|
|
3493
|
+
} catch {
|
|
3494
|
+
isolateCorrupt(file);
|
|
3495
|
+
return null;
|
|
3496
|
+
}
|
|
3497
|
+
}
|
|
3498
|
+
function isolateCorrupt(file) {
|
|
3499
|
+
try {
|
|
3500
|
+
if (!existsSync3(file))
|
|
3501
|
+
return;
|
|
3502
|
+
renameSync(file, file + ".corrupt");
|
|
3503
|
+
} catch {}
|
|
3504
|
+
}
|
|
3505
|
+
async function saveStats(cwd, sessionId, stats) {
|
|
3506
|
+
const file = reviewStorePath(cwd, sessionId);
|
|
3507
|
+
const tmp = file + ".tmp";
|
|
3508
|
+
try {
|
|
3509
|
+
mkdirSync3(dirname3(file), { recursive: true });
|
|
3510
|
+
writeFileSync3(tmp, JSON.stringify(stats, null, 2), "utf8");
|
|
3511
|
+
renameSync(tmp, file);
|
|
3512
|
+
return true;
|
|
3513
|
+
} catch {
|
|
3514
|
+
try {
|
|
3515
|
+
if (existsSync3(tmp))
|
|
3516
|
+
renameSync(tmp, tmp + ".failed");
|
|
3517
|
+
} catch {}
|
|
3518
|
+
return false;
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
|
|
3522
|
+
// src/review-collector.ts
|
|
3523
|
+
function turnKind(reason) {
|
|
3524
|
+
if (typeof reason === "string" && reason)
|
|
3525
|
+
return reason;
|
|
3526
|
+
const kind = reason?.kind;
|
|
3527
|
+
if (typeof kind === "string" && kind)
|
|
3528
|
+
return kind;
|
|
3529
|
+
return "unknown";
|
|
3530
|
+
}
|
|
3531
|
+
function readUsage(raw) {
|
|
3532
|
+
if (!raw || typeof raw !== "object")
|
|
3533
|
+
return null;
|
|
3534
|
+
const u = raw;
|
|
3535
|
+
const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
3536
|
+
const input = num(u.inputTokens);
|
|
3537
|
+
const output = num(u.outputTokens);
|
|
3538
|
+
if (input === null && output === null)
|
|
3539
|
+
return null;
|
|
3540
|
+
return {
|
|
3541
|
+
inputTokens: input,
|
|
3542
|
+
outputTokens: output,
|
|
3543
|
+
totalTokens: num(u.totalTokens),
|
|
3544
|
+
cacheReadTokens: num(u.cacheReadTokens),
|
|
3545
|
+
cacheWriteTokens: num(u.cacheWriteTokens),
|
|
3546
|
+
reasoningTokens: num(u.reasoningTokens)
|
|
3547
|
+
};
|
|
3548
|
+
}
|
|
3549
|
+
function addUsage(acc, add) {
|
|
3550
|
+
if (!acc)
|
|
3551
|
+
return { ...add };
|
|
3552
|
+
const sum = (a, b) => a === null || b === null ? null : a + b;
|
|
3553
|
+
return {
|
|
3554
|
+
inputTokens: sum(acc.inputTokens, add.inputTokens),
|
|
3555
|
+
outputTokens: sum(acc.outputTokens, add.outputTokens),
|
|
3556
|
+
totalTokens: sum(acc.totalTokens, add.totalTokens),
|
|
3557
|
+
cacheReadTokens: sum(acc.cacheReadTokens, add.cacheReadTokens),
|
|
3558
|
+
cacheWriteTokens: sum(acc.cacheWriteTokens, add.cacheWriteTokens),
|
|
3559
|
+
reasoningTokens: sum(acc.reasoningTokens, add.reasoningTokens)
|
|
3560
|
+
};
|
|
3561
|
+
}
|
|
3562
|
+
function readTurn(data, fallback) {
|
|
3563
|
+
const t = data.turn;
|
|
3564
|
+
return typeof t === "number" && Number.isFinite(t) ? t : fallback;
|
|
3565
|
+
}
|
|
3566
|
+
function isToolError(data) {
|
|
3567
|
+
const message = data.message;
|
|
3568
|
+
return message?.isError === true || data.error != null;
|
|
3569
|
+
}
|
|
3570
|
+
function openTurn(state, turn) {
|
|
3571
|
+
let acc = state.turns.get(turn);
|
|
3572
|
+
if (!acc) {
|
|
3573
|
+
acc = { turn, end: null, usage: null, usageEvidenceSeqs: [], tools: new Map };
|
|
3574
|
+
state.turns.set(turn, acc);
|
|
3575
|
+
}
|
|
3576
|
+
return acc;
|
|
3577
|
+
}
|
|
3578
|
+
function toSummary(acc) {
|
|
3579
|
+
if (!acc.end)
|
|
3580
|
+
return null;
|
|
3581
|
+
const tools = [...acc.tools.values()].sort((a, b) => a.callSeq - b.callSeq);
|
|
3582
|
+
return {
|
|
3583
|
+
turn: acc.turn,
|
|
3584
|
+
end: { seq: acc.end.seq, time: acc.end.time, kind: acc.end.kind },
|
|
3585
|
+
usage: acc.usage,
|
|
3586
|
+
usageEvidenceSeqs: [...acc.usageEvidenceSeqs],
|
|
3587
|
+
tools
|
|
3588
|
+
};
|
|
3589
|
+
}
|
|
3590
|
+
function createReviewCollector(ctx, opts = {}) {
|
|
3591
|
+
const enabled = opts.enabled !== false;
|
|
3592
|
+
const debounceMs = Math.max(0, Math.trunc(opts.debounceMs ?? 200));
|
|
3593
|
+
const states = new Map;
|
|
3594
|
+
const queues = new Map;
|
|
3595
|
+
const timers = new Map;
|
|
3596
|
+
let off = null;
|
|
3597
|
+
let disposed = false;
|
|
3598
|
+
const warn = (msg) => {
|
|
3599
|
+
try {
|
|
3600
|
+
ctx?.logger?.warn?.("[cohub review] " + msg);
|
|
3601
|
+
} catch {}
|
|
3602
|
+
};
|
|
3603
|
+
const stateOf = (sessionId, session) => {
|
|
3604
|
+
let st = states.get(sessionId);
|
|
3605
|
+
if (!st) {
|
|
3606
|
+
const header = session?.header;
|
|
3607
|
+
const cwdRaw = header?.cwd;
|
|
3608
|
+
const cwd = typeof cwdRaw === "string" && cwdRaw ? cwdRaw : null;
|
|
3609
|
+
const parentRaw = header?.parentSession;
|
|
3610
|
+
const parentSessionId = typeof parentRaw === "string" && parentRaw ? parentRaw : null;
|
|
3611
|
+
st = {
|
|
3612
|
+
sessionId,
|
|
3613
|
+
cwd,
|
|
3614
|
+
parentSessionId,
|
|
3615
|
+
rootSessionId: parentSessionId ?? sessionId,
|
|
3616
|
+
seenSeqs: new Set,
|
|
3617
|
+
turns: new Map,
|
|
3618
|
+
childSessions: new Set,
|
|
3619
|
+
gaps: new Set
|
|
3620
|
+
};
|
|
3621
|
+
states.set(sessionId, st);
|
|
3622
|
+
}
|
|
3623
|
+
return st;
|
|
3624
|
+
};
|
|
3625
|
+
const enqueue = (sessionId, task) => {
|
|
3626
|
+
const prev = queues.get(sessionId) ?? Promise.resolve();
|
|
3627
|
+
const next = prev.then(task, task).catch(() => {});
|
|
3628
|
+
queues.set(sessionId, next);
|
|
3629
|
+
next.then(() => {
|
|
3630
|
+
if (queues.get(sessionId) === next)
|
|
3631
|
+
queues.delete(sessionId);
|
|
3632
|
+
});
|
|
3633
|
+
return next;
|
|
3634
|
+
};
|
|
3635
|
+
const persist = async (st) => {
|
|
3636
|
+
try {
|
|
3637
|
+
const turns = [...st.turns.values()].map(toSummary).filter((t) => t !== null).sort((a, b) => a.turn - b.turn);
|
|
3638
|
+
if (turns.length === 0)
|
|
3639
|
+
return;
|
|
3640
|
+
const existing = loadStats(st.cwd, st.sessionId);
|
|
3641
|
+
const merged = new Map;
|
|
3642
|
+
for (const t of existing?.turns ?? [])
|
|
3643
|
+
merged.set(t.turn, t);
|
|
3644
|
+
for (const t of turns)
|
|
3645
|
+
merged.set(t.turn, t);
|
|
3646
|
+
const gaps = new Set(existing?.gaps ?? []);
|
|
3647
|
+
for (const g of st.gaps)
|
|
3648
|
+
gaps.add(g);
|
|
3649
|
+
const stats = {
|
|
3650
|
+
version: REVIEW_STATS_VERSION,
|
|
3651
|
+
sessionId: st.sessionId,
|
|
3652
|
+
cwd: st.cwd,
|
|
3653
|
+
rootSessionId: st.rootSessionId,
|
|
3654
|
+
gaps: [...gaps],
|
|
3655
|
+
updatedAt: new Date().toISOString(),
|
|
3656
|
+
turns: [...merged.values()].sort((a, b) => a.turn - b.turn)
|
|
3657
|
+
};
|
|
3658
|
+
const ok = await saveStats(st.cwd, st.sessionId, stats);
|
|
3659
|
+
if (!ok)
|
|
3660
|
+
warn("统计落盘失败(静默降级,不影响主流程):session=" + st.sessionId);
|
|
3661
|
+
} catch (err) {
|
|
3662
|
+
warn("统计落盘异常(已吞掉):session=" + st.sessionId + " " + String(err));
|
|
3663
|
+
}
|
|
3664
|
+
};
|
|
3665
|
+
const schedule = (st) => {
|
|
3666
|
+
if (disposed)
|
|
3667
|
+
return;
|
|
3668
|
+
const sid = st.sessionId;
|
|
3669
|
+
const timer = timers.get(sid);
|
|
3670
|
+
if (timer)
|
|
3671
|
+
clearTimeout(timer);
|
|
3672
|
+
const handle = setTimeout(() => {
|
|
3673
|
+
timers.delete(sid);
|
|
3674
|
+
enqueue(sid, () => persist(st));
|
|
3675
|
+
}, debounceMs);
|
|
3676
|
+
if (typeof handle.unref === "function")
|
|
3677
|
+
handle.unref();
|
|
3678
|
+
timers.set(sid, handle);
|
|
3679
|
+
};
|
|
3680
|
+
const collectChildGaps = (st) => {
|
|
3681
|
+
if (!opts.expectChildSessions)
|
|
3682
|
+
return;
|
|
3683
|
+
let expected = [];
|
|
3684
|
+
try {
|
|
3685
|
+
expected = opts.expectChildSessions(st.rootSessionId) ?? [];
|
|
3686
|
+
} catch (err) {
|
|
3687
|
+
warn("expectChildSessions 抛错(已忽略):" + String(err));
|
|
3688
|
+
return;
|
|
3689
|
+
}
|
|
3690
|
+
for (const childId of expected) {
|
|
3691
|
+
if (typeof childId !== "string" || !childId)
|
|
3692
|
+
continue;
|
|
3693
|
+
if (states.has(childId) || st.childSessions.has(childId))
|
|
3694
|
+
continue;
|
|
3695
|
+
st.gaps.add("subagent events not received for session " + childId);
|
|
3696
|
+
}
|
|
3697
|
+
};
|
|
3698
|
+
const registerChild = (childId, parentId) => {
|
|
3699
|
+
const parent = states.get(parentId);
|
|
3700
|
+
if (parent)
|
|
3701
|
+
parent.childSessions.add(childId);
|
|
3702
|
+
};
|
|
3703
|
+
const consume = (session, event) => {
|
|
3704
|
+
const sessionId = session?.id;
|
|
3705
|
+
if (typeof sessionId !== "string" || !sessionId)
|
|
3706
|
+
return;
|
|
3707
|
+
const type = event?.type;
|
|
3708
|
+
if (typeof type !== "string")
|
|
3709
|
+
return;
|
|
3710
|
+
const seq = event?.seq;
|
|
3711
|
+
const time = event?.time;
|
|
3712
|
+
if (typeof seq !== "number" || !Number.isFinite(seq))
|
|
3713
|
+
return;
|
|
3714
|
+
const st = stateOf(sessionId, session);
|
|
3715
|
+
if (st.seenSeqs.has(seq))
|
|
3716
|
+
return;
|
|
3717
|
+
st.seenSeqs.add(seq);
|
|
3718
|
+
const data = event.data ?? {};
|
|
3719
|
+
const fallbackTurn = st.turns.size > 0 ? Math.max(...st.turns.keys()) : 0;
|
|
3720
|
+
const turn = readTurn(data, fallbackTurn);
|
|
3721
|
+
switch (type) {
|
|
3722
|
+
case "turn/start": {
|
|
3723
|
+
openTurn(st, turn);
|
|
3724
|
+
return;
|
|
3725
|
+
}
|
|
3726
|
+
case "tool/call": {
|
|
3727
|
+
const callId = data.callId;
|
|
3728
|
+
const name = data.name;
|
|
3729
|
+
if (typeof callId !== "string" || !callId)
|
|
3730
|
+
return;
|
|
3731
|
+
const acc = openTurn(st, turn);
|
|
3732
|
+
acc.tools.set(callId, {
|
|
3733
|
+
callId,
|
|
3734
|
+
name: typeof name === "string" ? name : String(name ?? "unknown"),
|
|
3735
|
+
callSeq: seq,
|
|
3736
|
+
resultSeq: null,
|
|
3737
|
+
startedAt: typeof time === "number" && Number.isFinite(time) ? time : 0,
|
|
3738
|
+
endedAt: null,
|
|
3739
|
+
status: "pending"
|
|
3740
|
+
});
|
|
3741
|
+
return;
|
|
3742
|
+
}
|
|
3743
|
+
case "tool/result": {
|
|
3744
|
+
const message = data.message;
|
|
3745
|
+
const callIdRaw = data.callId ?? message?.toolCallId;
|
|
3746
|
+
const callId = typeof callIdRaw === "string" ? callIdRaw : null;
|
|
3747
|
+
if (!callId)
|
|
3748
|
+
return;
|
|
3749
|
+
const acc = openTurn(st, turn);
|
|
3750
|
+
const rec = acc.tools.get(callId);
|
|
3751
|
+
const endedAt = typeof time === "number" && Number.isFinite(time) ? time : 0;
|
|
3752
|
+
if (rec) {
|
|
3753
|
+
rec.resultSeq = seq;
|
|
3754
|
+
rec.endedAt = endedAt;
|
|
3755
|
+
rec.status = isToolError(data) ? "error" : "success";
|
|
3756
|
+
} else {
|
|
3757
|
+
acc.tools.set(callId, {
|
|
3758
|
+
callId,
|
|
3759
|
+
name: "unknown",
|
|
3760
|
+
callSeq: seq,
|
|
3761
|
+
resultSeq: seq,
|
|
3762
|
+
startedAt: endedAt,
|
|
3763
|
+
endedAt,
|
|
3764
|
+
status: isToolError(data) ? "error" : "success"
|
|
3765
|
+
});
|
|
3766
|
+
}
|
|
3767
|
+
return;
|
|
3768
|
+
}
|
|
3769
|
+
case "assistant/message": {
|
|
3770
|
+
const usage = readUsage(data.usage);
|
|
3771
|
+
if (!usage)
|
|
3772
|
+
return;
|
|
3773
|
+
const acc = openTurn(st, turn);
|
|
3774
|
+
acc.usage = addUsage(acc.usage, usage);
|
|
3775
|
+
acc.usageEvidenceSeqs.push(seq);
|
|
3776
|
+
return;
|
|
3777
|
+
}
|
|
3778
|
+
case "turn/end": {
|
|
3779
|
+
const acc = openTurn(st, turn);
|
|
3780
|
+
acc.end = {
|
|
3781
|
+
seq,
|
|
3782
|
+
time: typeof time === "number" && Number.isFinite(time) ? time : 0,
|
|
3783
|
+
kind: turnKind(data.reason)
|
|
3784
|
+
};
|
|
3785
|
+
if (st.parentSessionId === null) {
|
|
3786
|
+
collectChildGaps(st);
|
|
3787
|
+
}
|
|
3788
|
+
schedule(st);
|
|
3789
|
+
return;
|
|
3790
|
+
}
|
|
3791
|
+
default:
|
|
3792
|
+
return;
|
|
3793
|
+
}
|
|
3794
|
+
};
|
|
3795
|
+
if (enabled && typeof ctx?.on === "function") {
|
|
3796
|
+
try {
|
|
3797
|
+
off = ctx.on("session/event", (session, event) => {
|
|
3798
|
+
try {
|
|
3799
|
+
consume(session, event);
|
|
3800
|
+
const sid = session?.id;
|
|
3801
|
+
const parentId = states.get(sid)?.parentSessionId;
|
|
3802
|
+
if (typeof sid === "string" && typeof parentId === "string")
|
|
3803
|
+
registerChild(sid, parentId);
|
|
3804
|
+
} catch (err) {
|
|
3805
|
+
warn("采集异常(已吞掉):" + String(err));
|
|
3806
|
+
}
|
|
3807
|
+
});
|
|
3808
|
+
} catch (err) {
|
|
3809
|
+
warn("挂载 session/event 失败,采集降级为关闭:" + String(err));
|
|
3810
|
+
off = null;
|
|
3811
|
+
}
|
|
3812
|
+
}
|
|
3813
|
+
return {
|
|
3814
|
+
dispose() {
|
|
3815
|
+
disposed = true;
|
|
3816
|
+
for (const [sid, timer] of timers) {
|
|
3817
|
+
clearTimeout(timer);
|
|
3818
|
+
timers.delete(sid);
|
|
3819
|
+
}
|
|
3820
|
+
if (off) {
|
|
3821
|
+
try {
|
|
3822
|
+
off();
|
|
3823
|
+
} catch {}
|
|
3824
|
+
off = null;
|
|
3825
|
+
}
|
|
3826
|
+
for (const st of states.values())
|
|
3827
|
+
enqueue(st.sessionId, () => persist(st));
|
|
3828
|
+
states.clear();
|
|
3829
|
+
},
|
|
3830
|
+
async flush() {
|
|
3831
|
+
for (const [sid, timer] of timers) {
|
|
3832
|
+
clearTimeout(timer);
|
|
3833
|
+
timers.delete(sid);
|
|
3834
|
+
const st = states.get(sid);
|
|
3835
|
+
if (st)
|
|
3836
|
+
enqueue(sid, () => persist(st));
|
|
3837
|
+
}
|
|
3838
|
+
for (let i = 0;i < 3; i++) {
|
|
3839
|
+
const pending = [...queues.values()];
|
|
3840
|
+
if (pending.length === 0)
|
|
3841
|
+
return;
|
|
3842
|
+
await Promise.allSettled(pending);
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3845
|
+
};
|
|
3846
|
+
}
|
|
3847
|
+
|
|
3848
|
+
// src/review-command.ts
|
|
3849
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
3850
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync4, renameSync as renameSync2, writeFileSync as writeFileSync4 } from "node:fs";
|
|
3851
|
+
import { dirname as dirname4 } from "node:path";
|
|
3852
|
+
import { dshHomePath as dshHomePath3 } from "@deepseek-ai/dsh-home-paths";
|
|
3853
|
+
|
|
3854
|
+
// src/review-report.ts
|
|
3855
|
+
import { createHash as createHash3 } from "node:crypto";
|
|
3856
|
+
var USAGE_FIELDS = [
|
|
3857
|
+
"inputTokens",
|
|
3858
|
+
"outputTokens",
|
|
3859
|
+
"totalTokens",
|
|
3860
|
+
"cacheReadTokens",
|
|
3861
|
+
"cacheWriteTokens",
|
|
3862
|
+
"reasoningTokens"
|
|
3863
|
+
];
|
|
3864
|
+
function num(v) {
|
|
3865
|
+
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
3866
|
+
}
|
|
3867
|
+
function pickString(...vals) {
|
|
3868
|
+
for (const v of vals)
|
|
3869
|
+
if (typeof v === "string" && v.length > 0)
|
|
3870
|
+
return v;
|
|
3871
|
+
return null;
|
|
3872
|
+
}
|
|
3873
|
+
function normalizeReason(reason) {
|
|
3874
|
+
if (typeof reason === "string" && reason.length > 0)
|
|
3875
|
+
return reason;
|
|
3876
|
+
if (reason && typeof reason === "object") {
|
|
3877
|
+
const r = reason;
|
|
3878
|
+
for (const key of ["type", "kind", "reason"]) {
|
|
3879
|
+
const v = r[key];
|
|
3880
|
+
if (typeof v === "string" && v.length > 0)
|
|
3881
|
+
return v;
|
|
3882
|
+
}
|
|
3883
|
+
}
|
|
3884
|
+
return "unknown";
|
|
3885
|
+
}
|
|
3886
|
+
function isErrorResult(data) {
|
|
3887
|
+
if (!data || typeof data !== "object")
|
|
3888
|
+
return false;
|
|
3889
|
+
if (data.isError === true)
|
|
3890
|
+
return true;
|
|
3891
|
+
if (data.error !== undefined && data.error !== null)
|
|
3892
|
+
return true;
|
|
3893
|
+
const message = data.message;
|
|
3894
|
+
if (message && typeof message === "object" && message.isError === true)
|
|
3895
|
+
return true;
|
|
3896
|
+
const result = data.result;
|
|
3897
|
+
if (result && typeof result === "object" && result.isError === true)
|
|
3898
|
+
return true;
|
|
3899
|
+
return false;
|
|
3900
|
+
}
|
|
3901
|
+
function nullable(v) {
|
|
3902
|
+
return typeof v === "number" && Number.isFinite(v) ? v : null;
|
|
3903
|
+
}
|
|
3904
|
+
function buildUsage(sum, evidenceSeqs) {
|
|
3905
|
+
if (evidenceSeqs.length === 0)
|
|
3906
|
+
return null;
|
|
3907
|
+
return {
|
|
3908
|
+
inputTokens: nullable(sum.inputTokens),
|
|
3909
|
+
outputTokens: nullable(sum.outputTokens),
|
|
3910
|
+
totalTokens: nullable(sum.totalTokens),
|
|
3911
|
+
cacheReadTokens: nullable(sum.cacheReadTokens),
|
|
3912
|
+
cacheWriteTokens: nullable(sum.cacheWriteTokens),
|
|
3913
|
+
reasoningTokens: nullable(sum.reasoningTokens)
|
|
3914
|
+
};
|
|
3915
|
+
}
|
|
3916
|
+
function replay(session) {
|
|
3917
|
+
const sid = session.sessionId;
|
|
3918
|
+
const gaps = [];
|
|
3919
|
+
const ordered = session.events.map((event, index) => ({ event, index })).sort((a, b) => a.event.seq - b.event.seq || a.index - b.index).map((x) => x.event);
|
|
3920
|
+
const throughSeq = ordered.length > 0 ? ordered[ordered.length - 1].seq : 0;
|
|
3921
|
+
const turns = [];
|
|
3922
|
+
let usageSum = {};
|
|
3923
|
+
let usageSeqs = [];
|
|
3924
|
+
let tools = [];
|
|
3925
|
+
const openCalls = new Map;
|
|
3926
|
+
let pendingToolCount = 0;
|
|
3927
|
+
const resetTurn = () => {
|
|
3928
|
+
usageSum = {};
|
|
3929
|
+
usageSeqs = [];
|
|
3930
|
+
tools = [];
|
|
3931
|
+
openCalls.clear();
|
|
3932
|
+
pendingToolCount = 0;
|
|
3933
|
+
};
|
|
3934
|
+
for (const ev of ordered) {
|
|
3935
|
+
const data = ev.data && typeof ev.data === "object" ? ev.data : {};
|
|
3936
|
+
if (ev.type === "assistant/message") {
|
|
3937
|
+
const usage = data.usage;
|
|
3938
|
+
if (usage && typeof usage === "object") {
|
|
3939
|
+
let counted = 0;
|
|
3940
|
+
for (const field of USAGE_FIELDS) {
|
|
3941
|
+
const v = num(usage[field]);
|
|
3942
|
+
if (v === null)
|
|
3943
|
+
continue;
|
|
3944
|
+
usageSum[field] = (usageSum[field] ?? 0) + v;
|
|
3945
|
+
counted++;
|
|
3946
|
+
}
|
|
3947
|
+
if (counted > 0)
|
|
3948
|
+
usageSeqs.push(ev.seq);
|
|
3949
|
+
}
|
|
3950
|
+
continue;
|
|
3951
|
+
}
|
|
3952
|
+
if (ev.type === "tool/call") {
|
|
3953
|
+
const callId = pickString(data.callId, data.id, data.toolCallId, data.tool_call_id);
|
|
3954
|
+
const name = pickString(data.name, data.toolName, data.tool) ?? "unknown";
|
|
3955
|
+
if (callId === null) {
|
|
3956
|
+
gaps.push(`${sid}: tool/call at seq ${ev.seq} has no callId`);
|
|
3957
|
+
}
|
|
3958
|
+
const key = callId ?? "";
|
|
3959
|
+
const record = {
|
|
3960
|
+
callId: key,
|
|
3961
|
+
name,
|
|
3962
|
+
callSeq: ev.seq,
|
|
3963
|
+
resultSeq: null,
|
|
3964
|
+
startedAt: ev.time,
|
|
3965
|
+
endedAt: null,
|
|
3966
|
+
status: "pending"
|
|
3967
|
+
};
|
|
3968
|
+
tools.push(record);
|
|
3969
|
+
pendingToolCount++;
|
|
3970
|
+
if (!openCalls.has(key))
|
|
3971
|
+
openCalls.set(key, tools.length - 1);
|
|
3972
|
+
continue;
|
|
3973
|
+
}
|
|
3974
|
+
if (ev.type === "tool/result") {
|
|
3975
|
+
const msg = data.message && typeof data.message === "object" ? data.message : undefined;
|
|
3976
|
+
const callId = pickString(msg?.toolCallId, data.toolCallId, data.callId, data.id, data.tool_call_id);
|
|
3977
|
+
const key = callId ?? "";
|
|
3978
|
+
const idx = openCalls.get(key);
|
|
3979
|
+
if (idx === undefined) {
|
|
3980
|
+
gaps.push(`${sid}: tool/result at seq ${ev.seq} has no matching tool/call`);
|
|
3981
|
+
continue;
|
|
3982
|
+
}
|
|
3983
|
+
const record = tools[idx];
|
|
3984
|
+
if (record.status !== "pending") {
|
|
3985
|
+
gaps.push(`${sid}: duplicate tool/result for call ${key} at seq ${ev.seq}`);
|
|
3986
|
+
continue;
|
|
3987
|
+
}
|
|
3988
|
+
record.resultSeq = ev.seq;
|
|
3989
|
+
record.endedAt = ev.time;
|
|
3990
|
+
record.status = isErrorResult(data) ? "error" : "success";
|
|
3991
|
+
openCalls.delete(key);
|
|
3992
|
+
pendingToolCount--;
|
|
3993
|
+
continue;
|
|
3994
|
+
}
|
|
3995
|
+
if (ev.type === "turn/end") {
|
|
3996
|
+
const turnNo = num(data.turn);
|
|
3997
|
+
if (turnNo === null)
|
|
3998
|
+
gaps.push(`${sid}: turn/end at seq ${ev.seq} has no numeric turn`);
|
|
3999
|
+
for (const t of tools) {
|
|
4000
|
+
if (t.status === "pending")
|
|
4001
|
+
gaps.push(`${sid}: tool/call ${t.callId} has no result`);
|
|
4002
|
+
}
|
|
4003
|
+
turns.push({
|
|
4004
|
+
turn: turnNo ?? turns.length + 1,
|
|
4005
|
+
end: { seq: ev.seq, time: ev.time, kind: normalizeReason(data.reason) },
|
|
4006
|
+
usage: buildUsage(usageSum, usageSeqs),
|
|
4007
|
+
usageEvidenceSeqs: usageSeqs.slice(),
|
|
4008
|
+
tools
|
|
4009
|
+
});
|
|
4010
|
+
resetTurn();
|
|
4011
|
+
continue;
|
|
4012
|
+
}
|
|
4013
|
+
}
|
|
4014
|
+
if (turns.length === 0) {
|
|
4015
|
+
gaps.push(`${sid}: no turn/end event; session has no complete turn`);
|
|
4016
|
+
}
|
|
4017
|
+
if (turns.length === 0) {
|
|
4018
|
+
for (const t of tools)
|
|
4019
|
+
gaps.push(`${sid}: tool/call ${t.callId} has no result`);
|
|
4020
|
+
}
|
|
4021
|
+
const noPending = turns.every((t) => t.tools.every((x) => x.status !== "pending")) && pendingToolCount === 0;
|
|
4022
|
+
const complete = turns.length > 0 && noPending;
|
|
4023
|
+
return {
|
|
4024
|
+
summary: { sessionId: sid, parentSessionId: session.parentSessionId, turns },
|
|
4025
|
+
throughSeq,
|
|
4026
|
+
complete,
|
|
4027
|
+
gaps
|
|
4028
|
+
};
|
|
4029
|
+
}
|
|
4030
|
+
function projectKey(cwd) {
|
|
4031
|
+
return createHash3("sha256").update(cwd ?? "", "utf8").digest("hex").slice(0, 16);
|
|
4032
|
+
}
|
|
4033
|
+
function buildReport(input) {
|
|
4034
|
+
const all = [input.root, ...input.children ?? []];
|
|
4035
|
+
const replays = all.map(replay);
|
|
4036
|
+
const throughSeq = {};
|
|
4037
|
+
const gaps = [];
|
|
4038
|
+
let complete = true;
|
|
4039
|
+
for (const r of replays) {
|
|
4040
|
+
throughSeq[r.summary.sessionId] = r.throughSeq;
|
|
4041
|
+
if (!r.complete)
|
|
4042
|
+
complete = false;
|
|
4043
|
+
for (const g of r.gaps)
|
|
4044
|
+
gaps.push(g);
|
|
4045
|
+
}
|
|
4046
|
+
const cwd = typeof input.root.cwd === "string" && input.root.cwd.length > 0 ? input.root.cwd : null;
|
|
4047
|
+
return {
|
|
4048
|
+
schemaVersion: 1,
|
|
4049
|
+
project: { cwd, key: projectKey(cwd) },
|
|
4050
|
+
rootSessionId: input.root.sessionId,
|
|
4051
|
+
coverage: { throughSeq, complete, gaps, inputTruncated: false },
|
|
4052
|
+
sessions: replays.map((r) => r.summary),
|
|
4053
|
+
attempts: [],
|
|
4054
|
+
findings: [],
|
|
4055
|
+
analysis: {
|
|
4056
|
+
requestId: "",
|
|
4057
|
+
inputDigest: "",
|
|
4058
|
+
provider: "",
|
|
4059
|
+
model: "",
|
|
4060
|
+
invocations: 0,
|
|
4061
|
+
status: "completed"
|
|
4062
|
+
}
|
|
4063
|
+
};
|
|
4064
|
+
}
|
|
4065
|
+
|
|
4066
|
+
// src/review-render.ts
|
|
4067
|
+
var DASH = "—";
|
|
4068
|
+
var KIND_ORDER = ["praise", "issue", "suggestion", "observation"];
|
|
4069
|
+
var KIND_TITLE = {
|
|
4070
|
+
praise: "praise(值得肯定)",
|
|
4071
|
+
issue: "issue(问题)",
|
|
4072
|
+
suggestion: "suggestion(建议)",
|
|
4073
|
+
observation: "observation(观察)"
|
|
4074
|
+
};
|
|
4075
|
+
function num2(v) {
|
|
4076
|
+
return typeof v === "number" && Number.isFinite(v) ? String(v) : DASH;
|
|
4077
|
+
}
|
|
4078
|
+
function text(v) {
|
|
4079
|
+
return typeof v === "string" && v.length > 0 ? v : DASH;
|
|
4080
|
+
}
|
|
4081
|
+
function usageCell(usage) {
|
|
4082
|
+
if (!usage)
|
|
4083
|
+
return DASH;
|
|
4084
|
+
const input = num2(usage.inputTokens);
|
|
4085
|
+
const output = num2(usage.outputTokens);
|
|
4086
|
+
if (input === DASH && output === DASH)
|
|
4087
|
+
return DASH;
|
|
4088
|
+
return `${input}/${output}`;
|
|
4089
|
+
}
|
|
4090
|
+
function toolCounts(turn) {
|
|
4091
|
+
const tools = Array.isArray(turn?.tools) ? turn.tools : [];
|
|
4092
|
+
const errors = tools.filter((t) => t?.status === "error").length;
|
|
4093
|
+
return { total: String(tools.length), errors: String(errors) };
|
|
4094
|
+
}
|
|
4095
|
+
function anchorOf(ev) {
|
|
4096
|
+
const base = `[${text(ev?.sessionId)} · turn ${num2(ev?.turn)} · seq ${num2(ev?.seq)}]`;
|
|
4097
|
+
return typeof ev?.callId === "string" && ev.callId.length > 0 ? `${base.slice(0, -1)} · call ${ev.callId}]` : base;
|
|
4098
|
+
}
|
|
4099
|
+
function excerptOf(raw, limit) {
|
|
4100
|
+
const flat = raw.replace(/\s+/g, " ").trim();
|
|
4101
|
+
return flat.length > limit ? `${flat.slice(0, limit)}…` : flat;
|
|
4102
|
+
}
|
|
4103
|
+
function renderFinding(finding, opts, excerptLimit) {
|
|
4104
|
+
const out = [];
|
|
4105
|
+
out.push(`- **${text(finding?.text)}**`);
|
|
4106
|
+
const evidence = Array.isArray(finding?.evidence) ? finding.evidence : [];
|
|
4107
|
+
for (const ev of evidence)
|
|
4108
|
+
out.push(` - 锚点:${anchorOf(ev)}`);
|
|
4109
|
+
if (opts.excerptLookup) {
|
|
4110
|
+
for (const ev of evidence) {
|
|
4111
|
+
let raw = null;
|
|
4112
|
+
try {
|
|
4113
|
+
raw = opts.excerptLookup(String(ev?.sessionId ?? ""), Number(ev?.seq ?? 0));
|
|
4114
|
+
} catch {
|
|
4115
|
+
raw = null;
|
|
4116
|
+
}
|
|
4117
|
+
if (typeof raw === "string" && raw.length > 0) {
|
|
4118
|
+
out.push(` - 摘录:\`${excerptOf(raw, excerptLimit)}\``);
|
|
4119
|
+
break;
|
|
4120
|
+
}
|
|
4121
|
+
}
|
|
4122
|
+
}
|
|
4123
|
+
const limits = Array.isArray(finding?.limitations) ? finding.limitations : [];
|
|
4124
|
+
for (const l of limits)
|
|
4125
|
+
out.push(` - 局限:${text(l)}`);
|
|
4126
|
+
return out;
|
|
4127
|
+
}
|
|
4128
|
+
var STATUS_TITLE = {
|
|
4129
|
+
completed: "completed(分析完成)",
|
|
4130
|
+
interrupted: "interrupted(被取消,结论不完整)",
|
|
4131
|
+
failed: "failed(分析失败,本轮没有模型结论,原因见下方「分析错误说明」)"
|
|
4132
|
+
};
|
|
4133
|
+
function renderMarkdown(report, opts = {}) {
|
|
4134
|
+
const r = report ?? {};
|
|
4135
|
+
const excerptLimit = typeof opts.excerptLimit === "number" && opts.excerptLimit > 0 ? Math.floor(opts.excerptLimit) : 120;
|
|
4136
|
+
const lines = [];
|
|
4137
|
+
const findings = Array.isArray(r.findings) ? r.findings : [];
|
|
4138
|
+
const verified = findings.filter((f) => (Array.isArray(f?.evidence) ? f.evidence.length : 0) > 0);
|
|
4139
|
+
const unverified = findings.filter((f) => !(Array.isArray(f?.evidence) ? f.evidence.length : 0));
|
|
4140
|
+
const coverage = r.coverage ?? { throughSeq: {}, complete: false, gaps: [], inputTruncated: false };
|
|
4141
|
+
const gaps = Array.isArray(coverage.gaps) ? coverage.gaps : [];
|
|
4142
|
+
const complete = coverage.complete === true;
|
|
4143
|
+
lines.push("# 会话复盘报告", "");
|
|
4144
|
+
lines.push(`- 项目 cwd:${text(r.project?.cwd)}`);
|
|
4145
|
+
lines.push(`- 项目键:${text(r.project?.key)}`);
|
|
4146
|
+
lines.push(`- root session id:${text(r.rootSessionId)}`);
|
|
4147
|
+
lines.push(`- 生成时间:${new Date().toISOString()}`);
|
|
4148
|
+
lines.push(`- 采集完整性:${complete ? "complete(所有目标会话已读至末尾)" : "不完整(存在缺口,结论需降级)"}`);
|
|
4149
|
+
lines.push(`- 分析输入是否被裁剪:${coverage.inputTruncated ? "是(结论不得外推到未读区间)" : "否"}`);
|
|
4150
|
+
const analysis = r.analysis ?? {};
|
|
4151
|
+
const statusRaw = typeof analysis.status === "string" && analysis.status.length > 0 ? analysis.status : "";
|
|
4152
|
+
const statusLabel = STATUS_TITLE[statusRaw] ?? text(analysis.status);
|
|
4153
|
+
lines.push(`- 分析状态:${statusLabel}(provider/model:${text(analysis.provider)} / ${text(analysis.model)},调用次数 ${num2(analysis.invocations)})`);
|
|
4154
|
+
if (typeof analysis.error === "string" && analysis.error.length > 0) {
|
|
4155
|
+
lines.push(`- 分析错误说明:${analysis.error}`);
|
|
4156
|
+
}
|
|
4157
|
+
if (statusRaw === "failed") {
|
|
4158
|
+
lines.push("- 本轮**没有产生任何模型结论**:findings 为空是分析失败的结果,不代表本次会话没有值得复盘之处。");
|
|
4159
|
+
}
|
|
4160
|
+
lines.push("");
|
|
4161
|
+
lines.push("## 覆盖范围", "");
|
|
4162
|
+
const throughSeq = coverage.throughSeq ?? {};
|
|
4163
|
+
const throughEntries = Object.entries(throughSeq);
|
|
4164
|
+
if (throughEntries.length === 0) {
|
|
4165
|
+
lines.push(`- 无覆盖记录(throughSeq 为空,${DASH})`);
|
|
4166
|
+
} else {
|
|
4167
|
+
lines.push("| session | throughSeq |", "| --- | --- |");
|
|
4168
|
+
for (const [sid, seq] of throughEntries)
|
|
4169
|
+
lines.push(`| ${sid} | ${num2(seq)} |`);
|
|
4170
|
+
}
|
|
4171
|
+
lines.push("");
|
|
4172
|
+
if (!complete) {
|
|
4173
|
+
lines.push("## ⚠️ 覆盖不完整", "");
|
|
4174
|
+
if (gaps.length === 0) {
|
|
4175
|
+
lines.push("- 采集未完成,但未记录具体缺口(见 coverage.complete)。");
|
|
4176
|
+
} else {
|
|
4177
|
+
for (const g of gaps)
|
|
4178
|
+
lines.push(`- ${text(g)}`);
|
|
4179
|
+
}
|
|
4180
|
+
lines.push("");
|
|
4181
|
+
}
|
|
4182
|
+
lines.push("## 分轮总览", "");
|
|
4183
|
+
const sessions = Array.isArray(r.sessions) ? r.sessions : [];
|
|
4184
|
+
if (sessions.length === 0) {
|
|
4185
|
+
lines.push(`- 无会话摘要(sessions 为空,${DASH})`, "");
|
|
4186
|
+
} else {
|
|
4187
|
+
for (const s of sessions) {
|
|
4188
|
+
lines.push(`### ${text(s?.sessionId)}`, "");
|
|
4189
|
+
lines.push("| turn | 结束原因 | tokens(in/out) | 工具数 | 错误数 |", "| --- | --- | --- | --- | --- |");
|
|
4190
|
+
const turns = Array.isArray(s?.turns) ? s.turns : [];
|
|
4191
|
+
if (turns.length === 0) {
|
|
4192
|
+
lines.push(`| ${DASH} | ${DASH} | ${DASH} | ${DASH} | ${DASH} |`);
|
|
4193
|
+
} else {
|
|
4194
|
+
for (const t of turns) {
|
|
4195
|
+
const counts = toolCounts(t);
|
|
4196
|
+
lines.push(`| ${num2(t?.turn)} | ${text(t?.end?.kind)} | ${usageCell(t?.usage)} | ${counts.total} | ${counts.errors} |`);
|
|
4197
|
+
}
|
|
4198
|
+
}
|
|
4199
|
+
lines.push("");
|
|
4200
|
+
}
|
|
4201
|
+
}
|
|
4202
|
+
const attempts = Array.isArray(r.attempts) ? r.attempts : [];
|
|
4203
|
+
if (attempts.length > 0) {
|
|
4204
|
+
lines.push("## 委派树", "");
|
|
4205
|
+
for (const a of attempts) {
|
|
4206
|
+
const parent = a?.parent;
|
|
4207
|
+
const parentLabel = `${text(parent?.sessionId)} · turn ${num2(parent?.turn)} · seq ${num2(parent?.seq)} · call ${text(parent?.callId)}`;
|
|
4208
|
+
const cost = typeof a?.startedAt === "number" && typeof a?.endedAt === "number" ? `${Math.max(0, Math.round(a.endedAt - a.startedAt))}ms` : DASH;
|
|
4209
|
+
const tag = a?.attempt > 0 || a?.taskIndex > 0 ? `(task ${num2(a?.taskIndex)} / attempt ${num2(a?.attempt)})` : "";
|
|
4210
|
+
lines.push(`- ${parentLabel} → ${text(a?.childSessionId)} (${text(a?.outcome)}, ${cost})${tag}`);
|
|
4211
|
+
}
|
|
4212
|
+
lines.push("");
|
|
4213
|
+
}
|
|
4214
|
+
lines.push("## 发现", "");
|
|
4215
|
+
if (verified.length === 0) {
|
|
4216
|
+
lines.push(`- 本报告没有带证据的结论(findings 为空,${DASH});原因见「分析状态」与「限制说明」。`, "");
|
|
4217
|
+
} else {
|
|
4218
|
+
for (const kind of KIND_ORDER) {
|
|
4219
|
+
const group = verified.filter((f) => f?.kind === kind);
|
|
4220
|
+
if (group.length === 0)
|
|
4221
|
+
continue;
|
|
4222
|
+
lines.push(`### ${KIND_TITLE[kind] ?? kind}`, "");
|
|
4223
|
+
for (const f of group)
|
|
4224
|
+
lines.push(...renderFinding(f, opts, excerptLimit));
|
|
4225
|
+
lines.push("");
|
|
4226
|
+
}
|
|
4227
|
+
const known = new Set(KIND_ORDER);
|
|
4228
|
+
const rest = verified.filter((f) => !known.has(String(f?.kind)));
|
|
4229
|
+
if (rest.length > 0) {
|
|
4230
|
+
lines.push(`### ${DASH}(未知 kind)`, "");
|
|
4231
|
+
for (const f of rest)
|
|
4232
|
+
lines.push(...renderFinding(f, opts, excerptLimit));
|
|
4233
|
+
lines.push("");
|
|
4234
|
+
}
|
|
4235
|
+
}
|
|
4236
|
+
if (unverified.length > 0) {
|
|
4237
|
+
lines.push("## 未验证", "");
|
|
4238
|
+
lines.push("以下条目没有任何证据锚点,不能作为正式结论使用:", "");
|
|
4239
|
+
for (const f of unverified) {
|
|
4240
|
+
lines.push(`- **${text(f?.text)}**(无证据,未验证)`);
|
|
4241
|
+
const limits = Array.isArray(f?.limitations) ? f.limitations : [];
|
|
4242
|
+
for (const l of limits)
|
|
4243
|
+
lines.push(` - 局限:${text(l)}`);
|
|
4244
|
+
lines.push(` - kind:${text(f?.kind)}`);
|
|
4245
|
+
}
|
|
4246
|
+
lines.push("");
|
|
4247
|
+
}
|
|
4248
|
+
lines.push("## 限制说明", "");
|
|
4249
|
+
const noConclusion = verified.length === 0;
|
|
4250
|
+
const analysisError = typeof r.analysis?.error === "string" && r.analysis.error.length > 0 ? String(r.analysis.error) : null;
|
|
4251
|
+
const needsReview = gaps.length > 0 || unverified.length > 0 || !complete;
|
|
4252
|
+
if (needsReview) {
|
|
4253
|
+
lines.push("本报告存在未覆盖部分,结论需人工复核。", "");
|
|
4254
|
+
if (gaps.length > 0)
|
|
4255
|
+
lines.push(`- 采集缺口 ${gaps.length} 处,相关区间的事件未被读到,不应据此下结论。`);
|
|
4256
|
+
if (unverified.length > 0) {
|
|
4257
|
+
lines.push(`- ${unverified.length} 条结论缺少证据,已移入「未验证」节,未计入正式分组。`);
|
|
4258
|
+
}
|
|
4259
|
+
if (noConclusion) {
|
|
4260
|
+
lines.push("- 本次复盘**没有产出任何带锚点的结论**(findings 为空),不存在可复核的结论条目。");
|
|
4261
|
+
}
|
|
4262
|
+
if (!complete)
|
|
4263
|
+
lines.push("- coverage.complete 为 false,统计数字不完整。");
|
|
4264
|
+
if (coverage.inputTruncated)
|
|
4265
|
+
lines.push("- 分析输入被裁剪,结论不得外推到未读区间。");
|
|
4266
|
+
if (analysisError)
|
|
4267
|
+
lines.push(`- 分析失败/降级原因:${analysisError}`);
|
|
4268
|
+
lines.push("");
|
|
4269
|
+
} else if (noConclusion) {
|
|
4270
|
+
lines.push("本报告覆盖范围内无已知缺口,但本次没有产出任何带锚点的结论(findings 为空)。", "");
|
|
4271
|
+
if (analysisError)
|
|
4272
|
+
lines.push(`- 分析说明:${analysisError}`, "");
|
|
4273
|
+
} else {
|
|
4274
|
+
lines.push("本报告覆盖范围内无已知缺口,所有结论均已带锚点。", "");
|
|
4275
|
+
if (analysisError)
|
|
4276
|
+
lines.push(`- 分析说明:${analysisError}`, "");
|
|
4277
|
+
}
|
|
4278
|
+
return lines.join(`
|
|
4279
|
+
`);
|
|
4280
|
+
}
|
|
4281
|
+
|
|
4282
|
+
// src/review-command.ts
|
|
4283
|
+
var DIGEST_LIMIT_CHARS = 12000;
|
|
4284
|
+
var ANALYSIS_MAX_TOKENS = 2000;
|
|
4285
|
+
var MAX_CHILD_SESSIONS = 50;
|
|
4286
|
+
function idOf(rec) {
|
|
4287
|
+
const v = rec?.session?.id ?? rec?.id ?? rec?.sessionId;
|
|
4288
|
+
return typeof v === "string" && v.length > 0 ? v : undefined;
|
|
4289
|
+
}
|
|
4290
|
+
function parentOf(rec) {
|
|
4291
|
+
const v = rec?.session?.parentSession ?? rec?.parentSession ?? rec?.parentSessionId;
|
|
4292
|
+
return typeof v === "string" && v.length > 0 ? v : undefined;
|
|
4293
|
+
}
|
|
4294
|
+
function toSessionEvents(read, fallbackId) {
|
|
4295
|
+
const header = read?.session ?? {};
|
|
4296
|
+
const rawEvents = Array.isArray(read?.events) ? read.events : [];
|
|
4297
|
+
const events = [];
|
|
4298
|
+
for (const ev of rawEvents) {
|
|
4299
|
+
const seq = typeof ev?.seq === "number" ? ev.seq : null;
|
|
4300
|
+
const time = typeof ev?.time === "number" ? ev.time : null;
|
|
4301
|
+
const type = typeof ev?.type === "string" ? ev.type : null;
|
|
4302
|
+
if (seq === null || time === null || type === null)
|
|
4303
|
+
continue;
|
|
4304
|
+
events.push({ seq, time, type, data: ev?.data });
|
|
4305
|
+
}
|
|
4306
|
+
return {
|
|
4307
|
+
sessionId: typeof header.id === "string" ? header.id : fallbackId,
|
|
4308
|
+
parentSessionId: typeof header.parentSession === "string" ? header.parentSession : null,
|
|
4309
|
+
cwd: typeof header.cwd === "string" ? header.cwd : undefined,
|
|
4310
|
+
events
|
|
4311
|
+
};
|
|
4312
|
+
}
|
|
4313
|
+
function collectLineageIds(node, out, depth = 0) {
|
|
4314
|
+
if (node === null || typeof node !== "object" || depth > 8)
|
|
4315
|
+
return;
|
|
4316
|
+
if (Array.isArray(node)) {
|
|
4317
|
+
for (const item of node)
|
|
4318
|
+
collectLineageIds(item, out, depth + 1);
|
|
4319
|
+
return;
|
|
4320
|
+
}
|
|
4321
|
+
const direct = idOf(node);
|
|
4322
|
+
if (direct)
|
|
4323
|
+
out.add(direct);
|
|
4324
|
+
for (const value of Object.values(node)) {
|
|
4325
|
+
if (value !== null && typeof value === "object")
|
|
4326
|
+
collectLineageIds(value, out, depth + 1);
|
|
4327
|
+
}
|
|
4328
|
+
}
|
|
4329
|
+
async function findChildIds(ctx, rootId, signal) {
|
|
4330
|
+
const ids = new Set;
|
|
4331
|
+
try {
|
|
4332
|
+
const trace = ctx?.sessionQuery?.traceSession;
|
|
4333
|
+
if (typeof trace === "function") {
|
|
4334
|
+
const tree = await trace.call(ctx.sessionQuery, rootId, signal);
|
|
4335
|
+
const found = new Set;
|
|
4336
|
+
collectLineageIds(tree?.descendants, found);
|
|
4337
|
+
for (const id of found)
|
|
4338
|
+
if (id !== rootId)
|
|
4339
|
+
ids.add(id);
|
|
4340
|
+
}
|
|
4341
|
+
} catch (error) {
|
|
4342
|
+
ctx.logger?.warn?.("[cohub review] traceSession 失败:" + String(error?.message ?? error));
|
|
4343
|
+
}
|
|
4344
|
+
if (ids.size > 0)
|
|
4345
|
+
return [...ids].slice(0, MAX_CHILD_SESSIONS);
|
|
4346
|
+
try {
|
|
4347
|
+
const list = await ctx.sessionQuery.listSessions(signal);
|
|
4348
|
+
const records = Array.isArray(list) ? list : [];
|
|
4349
|
+
const byParent = new Map;
|
|
4350
|
+
for (const rec of records) {
|
|
4351
|
+
const id = idOf(rec);
|
|
4352
|
+
const parent = parentOf(rec);
|
|
4353
|
+
if (!id || !parent)
|
|
4354
|
+
continue;
|
|
4355
|
+
const bucket = byParent.get(parent) ?? [];
|
|
4356
|
+
bucket.push(id);
|
|
4357
|
+
byParent.set(parent, bucket);
|
|
4358
|
+
}
|
|
4359
|
+
const queue = [rootId];
|
|
4360
|
+
while (queue.length > 0 && ids.size < MAX_CHILD_SESSIONS) {
|
|
4361
|
+
const cur = queue.shift();
|
|
4362
|
+
for (const child of byParent.get(cur) ?? []) {
|
|
4363
|
+
if (child === rootId || ids.has(child))
|
|
4364
|
+
continue;
|
|
4365
|
+
ids.add(child);
|
|
4366
|
+
queue.push(child);
|
|
4367
|
+
}
|
|
4368
|
+
}
|
|
4369
|
+
} catch (error) {
|
|
4370
|
+
ctx.logger?.warn?.("[cohub review] listSessions 失败:" + String(error?.message ?? error));
|
|
4371
|
+
}
|
|
4372
|
+
return [...ids];
|
|
4373
|
+
}
|
|
4374
|
+
function writeTextAtomic(file, text) {
|
|
4375
|
+
const tmp = file + ".tmp";
|
|
4376
|
+
try {
|
|
4377
|
+
mkdirSync4(dirname4(file), { recursive: true });
|
|
4378
|
+
writeFileSync4(tmp, text, "utf8");
|
|
4379
|
+
renameSync2(tmp, file);
|
|
4380
|
+
return true;
|
|
4381
|
+
} catch {
|
|
4382
|
+
try {
|
|
4383
|
+
if (existsSync4(tmp))
|
|
4384
|
+
renameSync2(tmp, tmp + ".failed");
|
|
4385
|
+
} catch {}
|
|
4386
|
+
return false;
|
|
4387
|
+
}
|
|
4388
|
+
}
|
|
4389
|
+
function buildDigest(report) {
|
|
4390
|
+
const lines = [];
|
|
4391
|
+
lines.push("rootSessionId: " + report.rootSessionId);
|
|
4392
|
+
lines.push("projectCwd: " + (report.project.cwd ?? "(null)"));
|
|
4393
|
+
lines.push("coverageComplete: " + String(report.coverage.complete));
|
|
4394
|
+
lines.push("gaps: " + (report.coverage.gaps.length > 0 ? report.coverage.gaps.join(" | ") : "(none)"));
|
|
4395
|
+
lines.push("throughSeq: " + JSON.stringify(report.coverage.throughSeq));
|
|
4396
|
+
for (const s of report.sessions) {
|
|
4397
|
+
lines.push("");
|
|
4398
|
+
lines.push("session " + s.sessionId + " parent=" + (s.parentSessionId ?? "(root)") + " turns=" + s.turns.length);
|
|
4399
|
+
for (const t of s.turns) {
|
|
4400
|
+
const u = t.usage;
|
|
4401
|
+
const tools = t.tools.map((x) => x.name + ":" + x.status + (x.callSeq !== null ? "@seq" + x.callSeq : "")).join(",");
|
|
4402
|
+
lines.push(" turn " + t.turn + " end=" + t.end.kind + "@seq" + t.end.seq + " usage=" + (u ? "in" + (u.inputTokens ?? "?") + "/out" + (u.outputTokens ?? "?") : "(none)") + " tools=[" + tools + "]");
|
|
4403
|
+
}
|
|
4404
|
+
}
|
|
4405
|
+
let text = lines.join(`
|
|
4406
|
+
`);
|
|
4407
|
+
let truncated = false;
|
|
4408
|
+
if (text.length > DIGEST_LIMIT_CHARS) {
|
|
4409
|
+
text = text.slice(0, DIGEST_LIMIT_CHARS);
|
|
4410
|
+
truncated = true;
|
|
4411
|
+
}
|
|
4412
|
+
const digest = createHash4("sha256").update(text, "utf8").digest("hex").slice(0, 16);
|
|
4413
|
+
return { text, digest, truncated };
|
|
4414
|
+
}
|
|
4415
|
+
function extractJsonArray(text) {
|
|
4416
|
+
const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(text);
|
|
4417
|
+
const body = fenced ? fenced[1] : text;
|
|
4418
|
+
const start = body.indexOf("[");
|
|
4419
|
+
const end = body.lastIndexOf("]");
|
|
4420
|
+
if (start < 0 || end <= start)
|
|
4421
|
+
return null;
|
|
4422
|
+
try {
|
|
4423
|
+
const parsed = JSON.parse(body.slice(start, end + 1));
|
|
4424
|
+
return Array.isArray(parsed) ? parsed : null;
|
|
4425
|
+
} catch {
|
|
4426
|
+
return null;
|
|
4427
|
+
}
|
|
4428
|
+
}
|
|
4429
|
+
function callIdOf(type, data) {
|
|
4430
|
+
if (type !== "tool/call" && type !== "tool/result")
|
|
4431
|
+
return null;
|
|
4432
|
+
const message = data?.message && typeof data.message === "object" ? data.message : undefined;
|
|
4433
|
+
const v = data?.callId ?? message?.toolCallId ?? data?.toolCallId ?? data?.tool_call_id ?? data?.id;
|
|
4434
|
+
return typeof v === "string" && v.length > 0 ? v : null;
|
|
4435
|
+
}
|
|
4436
|
+
function buildEvidenceIndex(sessions) {
|
|
4437
|
+
const index = new Map;
|
|
4438
|
+
for (const s of sessions) {
|
|
4439
|
+
const bySeq = new Map;
|
|
4440
|
+
let currentTurn = null;
|
|
4441
|
+
for (const ev of s.events) {
|
|
4442
|
+
const data = ev.data && typeof ev.data === "object" ? ev.data : {};
|
|
4443
|
+
const declared = typeof data.turn === "number" && Number.isFinite(data.turn) ? data.turn : null;
|
|
4444
|
+
if (declared !== null)
|
|
4445
|
+
currentTurn = declared;
|
|
4446
|
+
bySeq.set(ev.seq, { turn: currentTurn, callId: callIdOf(ev.type, data) });
|
|
4447
|
+
}
|
|
4448
|
+
index.set(s.sessionId, bySeq);
|
|
4449
|
+
}
|
|
4450
|
+
return index;
|
|
4451
|
+
}
|
|
4452
|
+
function normalizeFindings(raw, index, defaultSessionId) {
|
|
4453
|
+
const KINDS = new Set(["observation", "praise", "issue", "suggestion"]);
|
|
4454
|
+
const out = [];
|
|
4455
|
+
for (const item of raw) {
|
|
4456
|
+
const rec = item;
|
|
4457
|
+
const text = typeof rec?.text === "string" ? rec.text.trim() : "";
|
|
4458
|
+
if (text.length === 0)
|
|
4459
|
+
continue;
|
|
4460
|
+
const kind = KINDS.has(rec?.kind) ? rec.kind : "observation";
|
|
4461
|
+
const evidence = [];
|
|
4462
|
+
const rawEv = Array.isArray(rec?.evidence) ? rec.evidence : [];
|
|
4463
|
+
for (const e of rawEv) {
|
|
4464
|
+
const sessionId = typeof e?.sessionId === "string" && e.sessionId.length > 0 ? e.sessionId : defaultSessionId;
|
|
4465
|
+
const turn = typeof e?.turn === "number" ? e.turn : null;
|
|
4466
|
+
const seq = typeof e?.seq === "number" ? e.seq : null;
|
|
4467
|
+
if (turn === null || seq === null)
|
|
4468
|
+
continue;
|
|
4469
|
+
const bySeq = index.get(sessionId);
|
|
4470
|
+
if (!bySeq)
|
|
4471
|
+
continue;
|
|
4472
|
+
const anchor = bySeq.get(seq);
|
|
4473
|
+
if (!anchor)
|
|
4474
|
+
continue;
|
|
4475
|
+
if (anchor.turn !== null && anchor.turn !== turn)
|
|
4476
|
+
continue;
|
|
4477
|
+
const callId = typeof e?.callId === "string" && e.callId.length > 0 ? e.callId : null;
|
|
4478
|
+
if (callId !== null && anchor.callId !== callId)
|
|
4479
|
+
continue;
|
|
4480
|
+
evidence.push({ sessionId, turn, seq, callId });
|
|
4481
|
+
}
|
|
4482
|
+
const limitations = Array.isArray(rec?.limitations) ? rec.limitations.filter((x) => typeof x === "string").slice(0, 5) : [];
|
|
4483
|
+
out.push({ id: "f-" + String(out.length + 1).padStart(3, "0"), kind, text, evidence, limitations });
|
|
4484
|
+
if (out.length >= 30)
|
|
4485
|
+
break;
|
|
4486
|
+
}
|
|
4487
|
+
return out;
|
|
4488
|
+
}
|
|
4489
|
+
function nonEmpty(v) {
|
|
4490
|
+
return typeof v === "string" && v.length > 0;
|
|
4491
|
+
}
|
|
4492
|
+
function routeFromAgent(agent, diag) {
|
|
4493
|
+
const options = agent?.options;
|
|
4494
|
+
diag.push("agent.options=" + (options ? "present" : "absent") + (options ? "(provider=" + JSON.stringify(options.provider ?? null) + ",model=" + JSON.stringify(options.model ?? null) + ")" : ""));
|
|
4495
|
+
if (nonEmpty(options?.provider) && nonEmpty(options?.model)) {
|
|
4496
|
+
return { provider: options.provider, model: options.model };
|
|
4497
|
+
}
|
|
4498
|
+
try {
|
|
4499
|
+
const header = typeof agent?.session?.requestHeader === "function" ? agent.session.requestHeader() : null;
|
|
4500
|
+
const config = header?.config;
|
|
4501
|
+
diag.push("session.requestHeader().config=" + (config ? "(provider=" + JSON.stringify(config.provider ?? null) + ",model=" + JSON.stringify(config.model ?? null) + ")" : "absent"));
|
|
4502
|
+
if (nonEmpty(config?.provider) && nonEmpty(config?.model)) {
|
|
4503
|
+
return { provider: config.provider, model: config.model };
|
|
4504
|
+
}
|
|
4505
|
+
} catch (error) {
|
|
4506
|
+
diag.push("session.requestHeader 抛错:" + String(error?.message ?? error));
|
|
4507
|
+
}
|
|
4508
|
+
return null;
|
|
4509
|
+
}
|
|
4510
|
+
function llmOf(ctx, diag, agent) {
|
|
4511
|
+
const direct = ctx?.llm;
|
|
4512
|
+
diag.push("ctx.llm=" + (direct ? "present" : "absent"));
|
|
4513
|
+
if (direct)
|
|
4514
|
+
return direct;
|
|
4515
|
+
const candidates = [
|
|
4516
|
+
["agent.ctx.llm", () => agent?.ctx?.llm],
|
|
4517
|
+
["agent.ctx.get('llm')", () => agent?.ctx?.get?.("llm")],
|
|
4518
|
+
["ctx.get('llm')", () => ctx?.get?.("llm")],
|
|
4519
|
+
["ctx.root.get('llm')", () => ctx?.root?.get?.("llm")],
|
|
4520
|
+
["ctx.parent.get('llm')", () => ctx?.parent?.get?.("llm")]
|
|
4521
|
+
];
|
|
4522
|
+
for (const [label, resolve] of candidates) {
|
|
4523
|
+
try {
|
|
4524
|
+
const svc = resolve();
|
|
4525
|
+
diag.push(label + "=" + (svc ? "present" : "absent"));
|
|
4526
|
+
if (svc)
|
|
4527
|
+
return svc;
|
|
4528
|
+
} catch (error) {
|
|
4529
|
+
diag.push(label + " 抛错:" + String(error?.message ?? error));
|
|
4530
|
+
}
|
|
4531
|
+
}
|
|
4532
|
+
return null;
|
|
4533
|
+
}
|
|
4534
|
+
async function resolveRoute(ctx, agent) {
|
|
4535
|
+
const diag = [];
|
|
4536
|
+
const fromAgent = routeFromAgent(agent, diag);
|
|
4537
|
+
if (fromAgent)
|
|
4538
|
+
return { route: fromAgent, source: "agent" };
|
|
4539
|
+
const llm = llmOf(ctx, diag, agent);
|
|
4540
|
+
if (!llm)
|
|
4541
|
+
return { route: null, reason: "llm 服务不可用(" + diag.join(";") + ")" };
|
|
4542
|
+
try {
|
|
4543
|
+
const providers = await llm.listProviders();
|
|
4544
|
+
diag.push("listProviders=" + (Array.isArray(providers) ? String(providers.length) + " 个" : "非数组"));
|
|
4545
|
+
const provider = Array.isArray(providers) ? providers.find((p) => nonEmpty(p?.id)) : undefined;
|
|
4546
|
+
if (!provider)
|
|
4547
|
+
return { route: null, reason: "agent 无 provider/model,且 listProviders 为空(" + diag.join(";") + ")" };
|
|
4548
|
+
const models = await llm.listModels(provider.id);
|
|
4549
|
+
diag.push("listModels(" + provider.id + ")=" + (Array.isArray(models) ? String(models.length) + " 个" : "非数组"));
|
|
4550
|
+
const model = Array.isArray(models) ? models.find((m) => nonEmpty(m?.id)) : undefined;
|
|
4551
|
+
if (!model)
|
|
4552
|
+
return { route: null, reason: "provider " + provider.id + " 无可用模型(" + diag.join(";") + ")" };
|
|
4553
|
+
return { route: { provider: provider.id, model: model.id }, source: "llm.listProviders" };
|
|
4554
|
+
} catch (error) {
|
|
4555
|
+
return {
|
|
4556
|
+
route: null,
|
|
4557
|
+
reason: "listProviders/listModels 抛错:" + String(error?.message ?? error) + "(" + diag.join(";") + ")"
|
|
4558
|
+
};
|
|
4559
|
+
}
|
|
4560
|
+
}
|
|
4561
|
+
async function callAnalysis(ctx, agent, digest, signal) {
|
|
4562
|
+
const resolved = await resolveRoute(ctx, agent);
|
|
4563
|
+
if (resolved.route === null)
|
|
4564
|
+
return { ok: false, reason: resolved.reason, provider: "", model: "" };
|
|
4565
|
+
const route = resolved.route;
|
|
4566
|
+
const llm = llmOf(ctx, [], agent);
|
|
4567
|
+
if (!llm)
|
|
4568
|
+
return { ok: false, reason: "llm 服务不可用,无法发起分析调用", provider: route.provider, model: route.model };
|
|
4569
|
+
if (typeof llm.prepareCall !== "function") {
|
|
4570
|
+
return { ok: false, reason: "llm 服务缺少 prepareCall 方法,无法发起分析调用", provider: route.provider, model: route.model };
|
|
4571
|
+
}
|
|
4572
|
+
try {
|
|
4573
|
+
const prepared = await llm.prepareCall({ provider: route.provider, model: route.model, maxTokens: ANALYSIS_MAX_TOKENS }, signal);
|
|
4574
|
+
const system = "你是会话复盘分析器。只输出 JSON 数组,不要解释、不要 Markdown 围栏。";
|
|
4575
|
+
const prompt = [
|
|
4576
|
+
"下面是某会话的统计摘要(每行 turn 含 end 事件 seq、usage、工具状态)。",
|
|
4577
|
+
"请输出 JSON 数组,每项形如:",
|
|
4578
|
+
'{"kind":"observation|praise|issue|suggestion","text":"中文结论","evidence":[{"sessionId":"...","turn":1,"seq":42,"callId":null}],"limitations":["..."]}',
|
|
4579
|
+
"硬规则:每条必须带至少 1 条 evidence;evidence 的 sessionId/turn/seq 必须来自下方摘要中真实出现的数据;",
|
|
4580
|
+
"不要编造 seq,不要给无证据的结论(无证据结论将被丢弃)。最多 12 条。",
|
|
4581
|
+
"",
|
|
4582
|
+
"摘要:",
|
|
4583
|
+
digest
|
|
4584
|
+
].join(`
|
|
4585
|
+
`);
|
|
4586
|
+
let raw = "";
|
|
4587
|
+
const preparedConfig = prepared?.config ?? {};
|
|
4588
|
+
for await (const chunk of prepared.stream({
|
|
4589
|
+
...preparedConfig,
|
|
4590
|
+
provider: route.provider,
|
|
4591
|
+
model: route.model,
|
|
4592
|
+
maxTokens: ANALYSIS_MAX_TOKENS,
|
|
4593
|
+
system,
|
|
4594
|
+
messages: [{ role: "user", content: [{ type: "text", text: prompt }] }],
|
|
4595
|
+
signal
|
|
4596
|
+
})) {
|
|
4597
|
+
if (chunk?.type === "text-delta" && typeof chunk.text === "string")
|
|
4598
|
+
raw += chunk.text;
|
|
4599
|
+
}
|
|
4600
|
+
return { ok: true, raw, provider: route.provider, model: route.model, source: resolved.source };
|
|
4601
|
+
} catch (error) {
|
|
4602
|
+
return {
|
|
4603
|
+
ok: false,
|
|
4604
|
+
reason: "LLM 调用失败(" + route.provider + "/" + route.model + "):" + String(error?.message ?? error),
|
|
4605
|
+
provider: route.provider,
|
|
4606
|
+
model: route.model
|
|
4607
|
+
};
|
|
4608
|
+
}
|
|
4609
|
+
}
|
|
4610
|
+
async function runAnalysis(ctx, agent, sessionId, cwdHint, withLlm) {
|
|
4611
|
+
const signal = undefined;
|
|
4612
|
+
const rootRead = await ctx.sessionQuery.readSession(sessionId, signal);
|
|
4613
|
+
const root = toSessionEvents(rootRead, sessionId);
|
|
4614
|
+
const childIds = await findChildIds(ctx, root.sessionId, signal);
|
|
4615
|
+
const children = [];
|
|
4616
|
+
const gaps = [];
|
|
4617
|
+
for (const childId of childIds) {
|
|
4618
|
+
try {
|
|
4619
|
+
const read = await ctx.sessionQuery.readSession(childId, signal);
|
|
4620
|
+
children.push(toSessionEvents(read, childId));
|
|
4621
|
+
} catch (error) {
|
|
4622
|
+
gaps.push(childId + ": 子会话读取失败(" + String(error?.message ?? error) + ")");
|
|
4623
|
+
}
|
|
4624
|
+
}
|
|
4625
|
+
const report = buildReport({ root, children });
|
|
4626
|
+
report.coverage.gaps.push(...gaps);
|
|
4627
|
+
if (gaps.length > 0)
|
|
4628
|
+
report.coverage.complete = false;
|
|
4629
|
+
const cwd = root.cwd ?? cwdHint;
|
|
4630
|
+
const { text: digest, digest: inputDigest, truncated } = buildDigest(report);
|
|
4631
|
+
report.coverage.inputTruncated = truncated;
|
|
4632
|
+
report.analysis.requestId = inputDigest;
|
|
4633
|
+
report.analysis.inputDigest = inputDigest;
|
|
4634
|
+
report.analysis.invocations = 0;
|
|
4635
|
+
report.analysis.status = "failed";
|
|
4636
|
+
const analysis = report.analysis;
|
|
4637
|
+
if (withLlm) {
|
|
4638
|
+
const result = await callAnalysis(ctx, agent, digest, signal);
|
|
4639
|
+
analysis.provider = result.provider;
|
|
4640
|
+
analysis.model = result.model;
|
|
4641
|
+
if (result.ok) {
|
|
4642
|
+
analysis.invocations = 1;
|
|
4643
|
+
const rawItems = extractJsonArray(result.raw);
|
|
4644
|
+
if (rawItems) {
|
|
4645
|
+
const index = buildEvidenceIndex([root, ...children]);
|
|
4646
|
+
report.findings = normalizeFindings(rawItems, index, root.sessionId);
|
|
4647
|
+
analysis.status = "completed";
|
|
4648
|
+
const dropped = rawItems.length - report.findings.length;
|
|
4649
|
+
if (dropped > 0) {
|
|
4650
|
+
analysis.error = "模型返回 " + rawItems.length + " 条结论," + dropped + " 条因证据无法校验被丢弃。";
|
|
4651
|
+
}
|
|
4652
|
+
} else {
|
|
4653
|
+
analysis.error = "模型输出无法解析为 JSON 数组,findings 留空。原始输出前 200 字:" + result.raw.slice(0, 200);
|
|
4654
|
+
ctx.logger?.warn?.("[cohub review] " + analysis.error);
|
|
4655
|
+
}
|
|
4656
|
+
} else {
|
|
4657
|
+
analysis.status = "failed";
|
|
4658
|
+
analysis.error = result.reason;
|
|
4659
|
+
ctx.logger?.warn?.("[cohub review] LLM 分析失败:" + result.reason);
|
|
4660
|
+
}
|
|
4661
|
+
} else {
|
|
4662
|
+
analysis.status = "completed";
|
|
4663
|
+
analysis.provider = "(skipped)";
|
|
4664
|
+
analysis.model = "(skipped)";
|
|
4665
|
+
}
|
|
4666
|
+
const md = renderMarkdown(report, { excerptLimit: 120 });
|
|
4667
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
4668
|
+
const jsonPath = reviewStorePath(cwd, root.sessionId, "report-" + stamp + ".json");
|
|
4669
|
+
const mdPath = reviewStorePath(cwd, root.sessionId, "report-" + stamp + ".md");
|
|
4670
|
+
const jsonOk = writeTextAtomic(jsonPath, JSON.stringify(report, null, 2));
|
|
4671
|
+
const mdOk = writeTextAtomic(mdPath, md);
|
|
4672
|
+
if (!jsonOk || !mdOk) {
|
|
4673
|
+
ctx.logger?.warn?.("[cohub review] 报告落盘失败:json=" + jsonPath + " md=" + mdPath);
|
|
4674
|
+
} else {
|
|
4675
|
+
ctx.logger.info?.("[cohub review] 报告已生成:" + mdPath);
|
|
4676
|
+
}
|
|
4677
|
+
}
|
|
4678
|
+
function cwdHintOf(inv) {
|
|
4679
|
+
const cwd = inv?.agent?.session?.header?.cwd ?? inv?.agent?.session?.meta?.cwd ?? inv?.agent?.options?.cwd ?? null;
|
|
4680
|
+
return typeof cwd === "string" && cwd.length > 0 ? cwd : null;
|
|
4681
|
+
}
|
|
4682
|
+
var inFlight = new Set;
|
|
4683
|
+
function registerReviewCommand(ctx) {
|
|
4684
|
+
const handler = (inv) => {
|
|
4685
|
+
try {
|
|
4686
|
+
const sessionId = inv?.agent?.session?.id;
|
|
4687
|
+
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
|
4688
|
+
return { kind: "error", text: "无法确定当前会话 id,已跳过复盘。" };
|
|
4689
|
+
}
|
|
4690
|
+
if (inFlight.has(sessionId)) {
|
|
4691
|
+
return { kind: "error", text: "上一次分析仍在进行中,请稍候(会话 " + sessionId + ")。" };
|
|
4692
|
+
}
|
|
4693
|
+
const rawInput = typeof inv?.rawInput === "string" ? inv.rawInput : "";
|
|
4694
|
+
const withLlm = !/(^|\s)--no-llm(\s|$)/.test(rawInput);
|
|
4695
|
+
const cwdHint = cwdHintOf(inv);
|
|
4696
|
+
inFlight.add(sessionId);
|
|
4697
|
+
(async () => {
|
|
4698
|
+
try {
|
|
4699
|
+
await runAnalysis(ctx, inv?.agent, sessionId, cwdHint, withLlm);
|
|
4700
|
+
} catch (error) {
|
|
4701
|
+
ctx.logger?.warn?.("[cohub review] 报告生成失败:" + String(error?.message ?? error));
|
|
4702
|
+
} finally {
|
|
4703
|
+
inFlight.delete(sessionId);
|
|
4704
|
+
}
|
|
4705
|
+
})();
|
|
4706
|
+
const dir = reviewStorePath(cwdHint, sessionId, "").replace(/[\\/]$/, "");
|
|
4707
|
+
return {
|
|
4708
|
+
kind: "success",
|
|
4709
|
+
text: "正在生成报告…(" + (withLlm ? "含一次 LLM 分析" : "仅统计,跳过 LLM") + ")输出目录:" + dir
|
|
4710
|
+
};
|
|
4711
|
+
} catch (error) {
|
|
4712
|
+
return { kind: "error", text: "复盘命令启动失败:" + String(error?.message ?? error) };
|
|
4713
|
+
}
|
|
4714
|
+
};
|
|
4715
|
+
try {
|
|
4716
|
+
ctx.commands.register({
|
|
4717
|
+
definitionId: "cohub-review",
|
|
4718
|
+
name: "cohub-review",
|
|
4719
|
+
description: "生成当前会话的可追溯复盘报告",
|
|
4720
|
+
handler
|
|
4721
|
+
});
|
|
4722
|
+
} catch (error) {
|
|
4723
|
+
ctx.logger?.warn?.("[cohub review] 命令注册失败:" + String(error?.message ?? error));
|
|
4724
|
+
}
|
|
4725
|
+
}
|
|
4726
|
+
|
|
3278
4727
|
// src/index.ts
|
|
3279
4728
|
var Councillor = z.object({
|
|
3280
4729
|
name: z.string(),
|
|
@@ -3370,14 +4819,14 @@ var CohubSettingsSchema = z.object({
|
|
|
3370
4819
|
var SHIPPED_PRESETS_DIR = fileURLToPath(new URL("../presets/", import.meta.url));
|
|
3371
4820
|
function readPackageVersion() {
|
|
3372
4821
|
try {
|
|
3373
|
-
const pkg = JSON.parse(
|
|
4822
|
+
const pkg = JSON.parse(readFileSync4(fileURLToPath(new URL("../package.json", import.meta.url)), "utf8"));
|
|
3374
4823
|
return typeof pkg?.version === "string" ? pkg.version : "0.0.0";
|
|
3375
4824
|
} catch {
|
|
3376
4825
|
return "0.0.0";
|
|
3377
4826
|
}
|
|
3378
4827
|
}
|
|
3379
4828
|
function installAgentPresets(logger) {
|
|
3380
|
-
return installShippedPresets(SHIPPED_PRESETS_DIR,
|
|
4829
|
+
return installShippedPresets(SHIPPED_PRESETS_DIR, dshHomePath4(".agent-presets"), readPackageVersion(), logger);
|
|
3381
4830
|
}
|
|
3382
4831
|
function apply(ctx, config) {
|
|
3383
4832
|
ctx.effect(() => ctx.systemPrompt.section({
|
|
@@ -3454,6 +4903,22 @@ function apply(ctx, config) {
|
|
|
3454
4903
|
});
|
|
3455
4904
|
return off;
|
|
3456
4905
|
}, "cohub.tokenMeter()");
|
|
4906
|
+
ctx.effect(() => {
|
|
4907
|
+
const collector = createReviewCollector(ctx, { enabled: true, debounceMs: 200 });
|
|
4908
|
+
return () => collector.dispose();
|
|
4909
|
+
}, "cohub.reviewCollector()");
|
|
4910
|
+
const mountReviewCommand = (child) => {
|
|
4911
|
+
try {
|
|
4912
|
+
registerReviewCommand(child);
|
|
4913
|
+
} catch (error) {
|
|
4914
|
+
ctx.logger?.warn?.("[cohub review] 命令挂载失败(忽略):" + String(error?.message ?? error));
|
|
4915
|
+
}
|
|
4916
|
+
};
|
|
4917
|
+
if (typeof ctx.inject === "function") {
|
|
4918
|
+
ctx.inject(["commands", "sessionQuery"], mountReviewCommand);
|
|
4919
|
+
} else {
|
|
4920
|
+
mountReviewCommand(ctx);
|
|
4921
|
+
}
|
|
3457
4922
|
}
|
|
3458
4923
|
export {
|
|
3459
4924
|
CohubSettingsSchema,
|