dsh-dock 0.21.2 → 0.23.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.
@@ -113,7 +113,7 @@ async function writeModelConfig(ctx, body) {
113
113
  /** 功能注册表条目:index.js 组装 hostSetups 时使用。 */
114
114
  export const feature = {
115
115
  id: 'modelconfig',
116
- name: '模型设置',
116
+ name: '模型能力',
117
117
  description: '模型目录:编辑各模型的输入模态与思考强度,写回官方配置热生效',
118
118
  defaultEnabled: false,
119
119
  setup(ctx) {
@@ -420,10 +420,10 @@ function ModelsStat() {
420
420
 
421
421
  export const feature = {
422
422
  id: "modelconfig",
423
- name: "模型设置",
423
+ name: "模型能力",
424
424
  order: 100,
425
425
  accent: "#22d3ee",
426
- description: "编辑各 Provider 模型的输入类型与思考强度档位,写回官方配置热生效;Provider 自身的增删改在「模型提供商」里管理",
426
+ description: "编辑各 Provider 模型的输入类型与思考强度档位,写回官方配置热生效;Provider 自身的增删改在「模型管理」里管理",
427
427
  css: [
428
428
  ".dkm-note{color:var(--dsw-alias-label-secondary);font-size:12px;}",
429
429
  ".dkm-warn{color:var(--dk-warn);}",
@@ -122,14 +122,19 @@ const END_REASON_LABELS = {
122
122
 
123
123
  // 钉钉与飞书共用的消息正文(各端再按各自 markdown 方言拼接)
124
124
  // mode: brief = 任务与结果;medium = 加模型/耗时;detailed = 再加回合、Token 与摘要。
125
+ // 子任务结束(主任务可能还在跑):标题/正文标「子任务」,三挡都点名所属主任务——
126
+ // 否则群里看到「任务完成」会误以为整个任务结束了(2026-11-05 用户反馈)。
125
127
  function buildMessageLines(t, mode) {
126
128
  const success = !t.endReason || t.endReason === 'completed'
127
129
  const reasonLabel = END_REASON_LABELS[t.endReason] || '✅ 完成'
128
130
  const models = t.models.length > 0 ? t.models.join(', ') : '未知'
129
131
  const tone = mode === 'brief' || mode === 'medium' ? mode : 'detailed'
132
+ const sub = !!t.isSubtask
133
+ const kind = sub ? '子任务' : '任务'
130
134
  const lines = []
131
- lines.push(`### ${success ? '✅' : '📢'} dsh 任务${success ? '完成' : '结束'}`)
132
- lines.push(`**任务**: ${t.title}`)
135
+ lines.push(`### ${success ? '✅' : '📢'} dsh ${kind}${success ? '完成' : '结束'}`)
136
+ lines.push(`**${kind}**: ${t.title}`)
137
+ if (sub) lines.push(`**主任务**: ${t.parentTitle || '(未知)'}`)
133
138
  if (tone !== 'brief') lines.push(`**模型**: ${models}${t.provider ? `(${t.provider})` : ''}`)
134
139
  lines.push(`**耗时**: ${fmtDurCn(t.duration)}${tone === 'brief' ? '' : `(${fmtClockOf(t.startTime)} → ${fmtClockOf(t.endTime)})`}`)
135
140
  if (tone === 'detailed') {
@@ -143,7 +148,7 @@ function buildMessageLines(t, mode) {
143
148
  lines.push('---')
144
149
  lines.push(`*由 dsh-dock 任务通知发送 · ${fmtDateClockOf(t.endTime)}*`)
145
150
  return {
146
- title: `dsh 任务${success ? '完成' : '结束'}:${truncate(t.title, 40)}`,
151
+ title: `dsh ${kind}${success ? '完成' : '结束'}:${truncate(t.title, 40)}`,
147
152
  success,
148
153
  lines,
149
154
  }
@@ -441,18 +441,27 @@ function endReasonSpeech(reason) {
441
441
  if (reason === "interrupted") return "被打断了";
442
442
  return "完成了";
443
443
  }
444
- /** 结束播报文案(success 由调用方按 isSuccessReason 给)。kind: complete|error */
444
+ /** 结束播报文案(success 由调用方按 isSuccessReason 给)。kind: complete|error
445
+ * 子任务结束(主任务可能还在跑)必须报「子任务」而不是「任务」——否则听着像整个
446
+ * 任务完成了(2026-11-05 用户反馈)。简洁只报「子任务完成/停止了」;适中点名
447
+ * 主任务与子任务;详细再带统计与摘要。归属字段来自完成记录/活跃快照(task-track)。 */
445
448
  export function endBroadcastText(success, record, task, cfg) {
446
449
  const mode = voiceTone(cfg);
447
450
  const reason = (record && record.endReason) || "";
448
451
  const title = (record && record.title) || (task && task.title) || "";
452
+ const sub = !!((record && record.isSubtask) || (task && task.isSubtask));
453
+ const parentTitle = (record && record.parentTitle) || (task && task.parentTitle) || "";
449
454
  if (mode === "brief") {
450
- // 简洁口径不分原因细念:正常完成「任务完成」,其余一律「任务停止了」
455
+ // 简洁口径不分原因细念:正常完成「任务完成」,其余一律「任务停止了」;子任务换主语
456
+ if (sub) return success ? "子任务完成" : "子任务停止了";
451
457
  return success ? "任务完成" : "任务停止了";
452
458
  }
453
459
  if (mode === "medium") {
454
460
  // 适中口径:点名是哪个任务 + 结果 + (停止时)原因 + 耗时;不念回合/Token 统计
455
- const who = title ? "任务「" + truncate(title, 30) + "」" : "任务";
461
+ // 子任务:主任务名截短些(20 字),整句别太长
462
+ const who = sub
463
+ ? (parentTitle ? "主任务「" + truncate(parentTitle, 20) + "」的" : "") + (title ? "子任务「" + truncate(title, 30) + "」" : "子任务")
464
+ : (title ? "任务「" + truncate(title, 30) + "」" : "任务");
456
465
  const parts = [success ? who + "完成了" : who + "停止了"];
457
466
  if (!success) parts.push(",原因:" + endReasonSpeech(reason));
458
467
  const dur = (record && record.duration) || 0;
@@ -461,7 +470,8 @@ export function endBroadcastText(success, record, task, cfg) {
461
470
  return parts.join("");
462
471
  }
463
472
  const parts = [];
464
- if (title) parts.push("任务:" + truncate(title, 30) + "。");
473
+ if (sub && parentTitle) parts.push("主任务:" + truncate(parentTitle, 30) + "。");
474
+ if (title) parts.push((sub ? "子任务:" : "任务:") + truncate(title, 30) + "。");
465
475
  parts.push(success ? "已完成。" : "结束,原因:" + endReasonSpeech(reason) + "。");
466
476
  const dur = (record && record.duration) || 0;
467
477
  if (dur > 0) parts.push("耗时" + fmtDur(dur) + "。");
@@ -1069,12 +1079,22 @@ export function NotifyOverlay(props) {
1069
1079
  const success = isSuccessReason(reason);
1070
1080
  const info = endInfo(reason);
1071
1081
  const event = success ? "complete" : "error";
1082
+ // 主/子归属:完成记录优先(宿主权威),活跃快照兜底(旧宿主记录没带归属时)。
1083
+ // 主任务标题再兜一层:记录/快照都没有就查当前活跃列表(主任务通常还在跑)。
1084
+ const sub = !!((record && record.isSubtask) || task.isSubtask);
1085
+ const parentId = (record && record.parentSessionId) || task.parentSessionId || "";
1086
+ let parentTitle = (record && record.parentTitle) || task.parentTitle || "";
1087
+ if (sub && !parentTitle && parentId) {
1088
+ const p = ((snap.status && snap.status.active) || []).find((x) => x.sessionId === parentId);
1089
+ if (p && p.title) parentTitle = p.title;
1090
+ }
1091
+ const endRecord = Object.assign({}, record || {}, { isSubtask: sub, parentTitle });
1072
1092
  const cardWanted = eventEnabled(cfg, "card", event);
1073
1093
  const soundWanted = cfg.soundNotify !== false && eventEnabled(cfg, "sound", event);
1074
1094
  const systemWanted = !!cfg.systemNotify && eventEnabled(cfg, "system", event);
1075
1095
  // 语音播报与卡片/提示音/系统通知完全正交:各自的事件矩阵与总开关独立判断。
1076
1096
  if (voiceAllowed(cfg) && eventEnabled(cfg, "voice", event)) {
1077
- speakVoice(endBroadcastText(success, record, task, cfg), cfg);
1097
+ speakVoice(endBroadcastText(success, endRecord, task, cfg), cfg);
1078
1098
  }
1079
1099
  const models = record && record.models && record.models.length ? record.models.join(", ")
1080
1100
  : (task.models && task.models.length ? task.models.join(", ") : "未知模型");
@@ -1082,13 +1102,17 @@ export function NotifyOverlay(props) {
1082
1102
  const startTs = (record && record.startTime) || task.startTime;
1083
1103
  const endTs = (record && record.endTime) || Date.now();
1084
1104
  const durText = fmtDur((record && record.duration) || (endTs - startTs));
1085
- const title = success ? "任务完成" : "任务" + info.label;
1105
+ // 子任务结束:标题标「子任务」,三挡正文都点名所属主任务(主任务可能还在跑,
1106
+ // 不点名会被当成整个任务完成了——2026-11-05 用户反馈)
1107
+ const title = success ? (sub ? "子任务完成" : "任务完成") : (sub ? "子任务" : "任务") + info.label;
1086
1108
  const showTitle = (record && record.title) || task.title || "(无标题)";
1087
1109
  if (cardWanted) {
1088
1110
  // 卡片正文按「卡片口径」三挡裁剪(cfg.cardMode,缺省 detailed =历史内容):
1089
1111
  // 简洁=任务+耗时;适中=加模型与起止时间;详细=再加回合/步骤、Token、摘要或错误。
1112
+ // 子任务的主任务归属行不受口径裁剪(三挡都要能定位是哪个主任务)。
1090
1113
  const tone = cardTone(cfg);
1091
- const lines = ["任务:" + showTitle];
1114
+ const lines = [(sub ? "子任务:" : "任务:") + showTitle];
1115
+ if (sub) lines.push("主任务:" + (parentTitle || "(未知)"));
1092
1116
  if (tone !== "brief") lines.push("模型:" + models + (provider ? "(" + provider + ")" : ""));
1093
1117
  lines.push(tone === "brief"
1094
1118
  ? "耗时:" + durText
@@ -1112,6 +1136,8 @@ export function NotifyOverlay(props) {
1112
1136
  // sessionId 是权威标识(跳转/对账都用它),标题只作旧宿主回退。
1113
1137
  sessionId: task.sessionId || "",
1114
1138
  sessionTitle: showTitle,
1139
+ // 子任务会话通常不在侧栏里:跳不到自己时回退到父会话(与卡住卡同款)
1140
+ fallbackSessionId: (sub && parentId) ? parentId : "",
1115
1141
  });
1116
1142
  }
1117
1143
  // 提示音:任务结束时播放(完成/异常配套音);与系统通知独立开关
@@ -1121,7 +1147,9 @@ export function NotifyOverlay(props) {
1121
1147
  && typeof Notification !== "undefined" && Notification.permission === "granted") {
1122
1148
  try {
1123
1149
  new Notification("dsh " + title, {
1124
- body: showTitle + " · " + durText,
1150
+ body: (sub
1151
+ ? (parentTitle ? "主任务「" + truncate(parentTitle, 20) + "」的" : "") + "子任务「" + showTitle + "」"
1152
+ : showTitle) + " · " + durText,
1125
1153
  tag: "dsh-dock-notify-" + task.sessionId,
1126
1154
  });
1127
1155
  } catch { /* 系统通知失败不影响页面内通知 */ }
@@ -1481,7 +1509,7 @@ function NotifyView(props) {
1481
1509
  <div className="dknt-row">
1482
1510
  <span className="dknt-row-label">正文口径</span>
1483
1511
  <ModePicker value={cardTone(cfg)} title="页内卡片正文" onChange={(v) => patch({ cardMode: v })} />
1484
- <span className="dknt-row-sub">简洁=任务与耗时 / 谁卡住;适中=加模型、起止时间、停滞时长;详细=全部(回合步骤、Token、摘要或错误、最后动作)</span>
1512
+ <span className="dknt-row-sub">简洁=任务与耗时 / 谁卡住;适中=加模型、起止时间、停滞时长;详细=全部(回合步骤、Token、摘要或错误、最后动作)。子任务结束标「子任务」并点名主任务(三挡都带归属)</span>
1485
1513
  </div>
1486
1514
  <div className="dknt-row">
1487
1515
  <span className="dknt-row-label">卡片收纳</span>
@@ -1580,7 +1608,7 @@ function NotifyView(props) {
1580
1608
  <div className="dknt-row">
1581
1609
  <span className="dknt-row-label">播报口径</span>
1582
1610
  <ModePicker value={voiceTone(cfg)} title="语音播报" onChange={(v) => patch({ voiceMode: v })} />
1583
- <span className="dknt-row-sub">简洁:一句「任务完成 / 任务停止了 / 任务需要授权 / 主任务(或子任务)·标题 卡住了」;适中:点名任务,结束带原因与耗时、卡住带停滞时长;详细:结束带回合统计与回复摘要,需授权带工具名,卡住带最后动作。</span>
1611
+ <span className="dknt-row-sub">简洁:一句「任务完成 / 子任务完成 / 任务停止了 / 任务需要授权 / 主任务(或子任务)·标题 卡住了」;适中:点名任务(子任务连主任务一起点名),结束带原因与耗时、卡住带停滞时长;详细:结束带回合统计与回复摘要,需授权带工具名,卡住带最后动作。</span>
1584
1612
  </div>
1585
1613
  <div className="dknt-row">
1586
1614
  <span className="dknt-row-label">播报事件</span>
@@ -1689,7 +1717,7 @@ function NotifyView(props) {
1689
1717
  <div className="dknt-row">
1690
1718
  <span className="dknt-row-label">消息口径</span>
1691
1719
  <ModePicker value={cfg.pushMode || "detailed"} title="钉钉消息" onChange={(v) => patch({ pushMode: v })} />
1692
- <span className="dknt-row-sub">简洁=任务与结果;适中=加模型/耗时;详细=再加回合、Token 与摘要。</span>
1720
+ <span className="dknt-row-sub">简洁=任务与结果;适中=加模型/耗时;详细=再加回合、Token 与摘要。子任务结束标「子任务」并点名主任务(三挡都带归属)。</span>
1693
1721
  </div>
1694
1722
  <div className="dknt-row dknt-row-webhook">
1695
1723
  <span className="dknt-row-label">Webhook</span>
@@ -1738,7 +1766,7 @@ function NotifyView(props) {
1738
1766
  <div className="dknt-row">
1739
1767
  <span className="dknt-row-label">消息口径</span>
1740
1768
  <ModePicker value={cfg.pushMode || "detailed"} title="飞书消息" onChange={(v) => patch({ pushMode: v })} />
1741
- <span className="dknt-row-sub">简洁=任务与结果;适中=加模型/耗时;详细=再加回合、Token 与摘要。</span>
1769
+ <span className="dknt-row-sub">简洁=任务与结果;适中=加模型/耗时;详细=再加回合、Token 与摘要。子任务结束标「子任务」并点名主任务(三挡都带归属)。</span>
1742
1770
  </div>
1743
1771
  <div className="dknt-row dknt-row-webhook">
1744
1772
  <span className="dknt-row-label">Webhook</span>
@@ -200,7 +200,7 @@ async function writeProviderConfig(ctx, body) {
200
200
  /** 功能注册表条目:index.js 组装 hostSetups 时使用。 */
201
201
  export const feature = {
202
202
  id: 'providerconfig',
203
- name: '模型提供商',
203
+ name: '模型管理',
204
204
  description: '管理模型 Provider 的端点与 API Key(增删改 + 拉取上游模型列表)',
205
205
  defaultEnabled: false,
206
206
  setup(ctx) {
@@ -430,9 +430,9 @@ function ProvidersView(props) {
430
430
 
431
431
  const piProviders = providers.filter((p) => p.kind === "pi-ai");
432
432
  const body = [
433
- react.createElement("h2", { key: "title", className: "dkp-title" }, "模型提供商"),
433
+ react.createElement("h2", { key: "title", className: "dkp-title" }, "模型管理"),
434
434
  react.createElement("p", { key: "intro", className: "dkp-intro" },
435
- "新增 / 编辑 / 删除自定义模型 Provider(OpenAI 兼容、Anthropic 等),写入官方配置并热生效;API Key 存本机凭据库(文件仅 root 可读)。内置 DeepSeek 官方 Provider 在本页只读,其模型目录在「模型设置」里编辑。本功能可单独停用:停用后这些写配置与出站请求的路由一并关闭。")
435
+ "新增 / 编辑 / 删除自定义模型 Provider(OpenAI 兼容、Anthropic 等),写入官方配置并热生效;API Key 存本机凭据库(文件仅 root 可读)。内置 DeepSeek 官方 Provider 在本页只读,其模型目录在「模型能力」里编辑。本功能可单独停用:停用后这些写配置与出站请求的路由一并关闭。")
436
436
  ];
437
437
  if (snap.error) {
438
438
  body.push(react.createElement("p", { key: "err", className: "dkp-error" }, "模型目录拉取失败:" + snap.error));
@@ -503,8 +503,8 @@ function ProvidersStat() {
503
503
 
504
504
  export const feature = {
505
505
  id: "providerconfig",
506
- name: "模型提供商",
507
- order: 101,
506
+ name: "模型管理",
507
+ order: 99,
508
508
  accent: "#8b5cf6",
509
509
  description: "管理自定义模型 Provider:新增/编辑/删除、拉取上游模型列表、写入 API Key(可单独停用)",
510
510
  css: [
@@ -2,14 +2,15 @@
2
2
  //
3
3
  // 记录 DSH 会话日志中的每次 LLM 调用(assistant/message 的 usage),
4
4
  // 支持历史全量扫描 + 实时 session/event 增量;RPC 经 webServer HTTP 路由
5
- // POST /dsh-dock/tokenlog/query|export|scan|hello|pricing|setpricing
5
+ // POST /dsh-dock/tokenlog/query|export|scan|hello|config|pricing|setpricing
6
6
  // 向浏览器半部提供查询/统计/导出,以及单价的读取与保存。
7
7
  // export 返回结构化明细 { rows, rateUsdCny, count }(不是 CSV 文本):中文表头与取值格式由客户端
8
8
  // 按「调用明细」表统一生成,保证导出与页面显示一致;费用在导出时同样按当前单价重算。
9
9
  //
10
10
  // 数据模型(标量,无 Host 对象引用):
11
11
  // {
12
- // id, time, sessionId, provider, model, apiKey(掩码),
12
+ // id, time, sessionId, parentSessionId, rootSessionId, sessionDepth, isSubtask,
13
+ // provider, model, apiKey(掩码),
13
14
  // inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens,
14
15
  // billedInput, totalTokens, cacheHitPercent, cost, pricingSource, effort, status, llmMs, turn, step
15
16
  // }
@@ -50,12 +51,164 @@ export const feature = {
50
51
  const records = new Map()
51
52
  let scannedSessions = new Set()
52
53
  const headerCache = new Map()
54
+ // 逻辑会话谱系独立于 LLM request/header:来自 SessionHeader.parentSession/origin/delegationDepth。
55
+ // 实时事件先记住头,历史扫描补齐;查询时统一投影到每条调用,旧记录无需重扫即可归属。
56
+ const sessionMeta = new Map()
53
57
  const turnError = new Map()
54
58
  const turnStatus = new Map()
55
59
  const stepStart = new Map()
56
60
 
57
61
  function num(v) { return typeof v === 'number' && Number.isFinite(v) ? v : 0 }
58
62
 
63
+ // ===== 主任务 / 子任务用量归属 =====
64
+ let defaultSessionScope = 'tree'
65
+ function loadSessionScope() {
66
+ try {
67
+ const root = readDockRoot(ctx)
68
+ const value = root && root.tokenlog && root.tokenlog.sessionScope
69
+ defaultSessionScope = value === 'session' ? 'session' : 'tree'
70
+ } catch { defaultSessionScope = 'tree' }
71
+ }
72
+ function rememberSessionHeader(sessionId, raw) {
73
+ if (!sessionId || !raw || typeof raw !== 'object') return
74
+ const prev = sessionMeta.get(sessionId) || {}
75
+ const parentSessionId = typeof raw.parentSession === 'string' && raw.parentSession && raw.parentSession !== sessionId
76
+ ? raw.parentSession : ''
77
+ const depth = Number.isSafeInteger(raw.delegationDepth) && raw.delegationDepth > 0 ? raw.delegationDepth : 0
78
+ // parentSession 也见于普通 fork;只有 origin=subagent / delegationDepth>0 才标成子任务。
79
+ // 仍保留普通 fork 的谱系边,便于追到根;是否“子任务”单独判断。
80
+ sessionMeta.set(sessionId, {
81
+ ...prev, sessionId, parentSessionId,
82
+ isSubtask: raw.origin === 'subagent' || depth > 0,
83
+ delegationDepth: depth,
84
+ })
85
+ }
86
+ function lineageOf(sessionId) {
87
+ const chain = []
88
+ const seen = new Set()
89
+ let cur = sessionId
90
+ let incomplete = false
91
+ while (cur && !seen.has(cur)) {
92
+ seen.add(cur)
93
+ chain.push(cur)
94
+ const meta = sessionMeta.get(cur)
95
+ if (!meta) { incomplete = cur !== sessionId; break }
96
+ cur = meta.parentSessionId || ''
97
+ }
98
+ if (cur && seen.has(cur)) incomplete = true // 损坏谱系成环:止于已知部分,绝不无限递归/重复加总
99
+ const rootSessionId = chain.length ? chain[chain.length - 1] : sessionId
100
+ return { chain, rootSessionId, incomplete }
101
+ }
102
+ function withLineage(record) {
103
+ const meta = sessionMeta.get(record.sessionId) || {}
104
+ const line = lineageOf(record.sessionId)
105
+ return {
106
+ ...record,
107
+ parentSessionId: meta.parentSessionId || '',
108
+ rootSessionId: line.rootSessionId,
109
+ sessionDepth: Math.max(0, line.chain.length - 1),
110
+ isSubtask: !!meta.isSubtask,
111
+ }
112
+ }
113
+ async function resolveSessionScope(args) {
114
+ const q = args || {}
115
+ const sessionId = typeof q.sessionId === 'string' ? q.sessionId.trim() : ''
116
+ const requested = q.sessionScope === 'tree' || q.sessionScope === 'session' ? q.sessionScope : defaultSessionScope
117
+ const scope = sessionId ? requested : 'session'
118
+ const base = {
119
+ sessionId, scope, sessionIds: sessionId ? [sessionId] : [],
120
+ rootSessionId: sessionId, descendantCount: 0, complete: !sessionId, unresolvedParentId: '',
121
+ }
122
+ if (!sessionId || scope !== 'tree') {
123
+ if (sessionId) {
124
+ const line = lineageOf(sessionId)
125
+ base.rootSessionId = line.rootSessionId
126
+ base.complete = !line.incomplete
127
+ }
128
+ return base
129
+ }
130
+ // 首选宿主官方谱系观测:一次 list 取得完整已知祖先/后代,并显式报告缺失父会话。
131
+ if (sessionQuery && typeof sessionQuery.traceSession === 'function') {
132
+ try {
133
+ const trace = await sessionQuery.traceSession(sessionId)
134
+ if (trace && trace.target && trace.target.header) {
135
+ const headers = [trace.target, ...(trace.ancestors || [])]
136
+ const walk = (nodes) => {
137
+ for (const node of nodes || []) {
138
+ if (node && node.session) headers.push(node.session)
139
+ walk(node && node.descendants)
140
+ }
141
+ }
142
+ walk(trace.descendants)
143
+ for (const record of headers) rememberSessionHeader(record.header && record.header.id, record.header)
144
+ const ids = new Set([sessionId])
145
+ const collect = (nodes) => {
146
+ for (const node of nodes || []) {
147
+ const id = node && node.session && node.session.header && node.session.header.id
148
+ if (id) ids.add(id)
149
+ collect(node && node.descendants)
150
+ }
151
+ }
152
+ collect(trace.descendants)
153
+ const rootId = trace.complete && trace.root && trace.root.header ? trace.root.header.id : lineageOf(sessionId).rootSessionId
154
+ return {
155
+ ...base, sessionIds: [...ids], rootSessionId: rootId,
156
+ descendantCount: Math.max(0, ids.size - 1), complete: trace.complete === true,
157
+ unresolvedParentId: trace.complete === false ? String(trace.unresolvedParentId || '') : '',
158
+ }
159
+ }
160
+ } catch { /* 旧宿主/目标未持久化/损坏会话:回退已采集的轻量谱系,不拖垮用量查询 */ }
161
+ }
162
+ // 兼容旧 SessionQuery:先轻量补一次会话头(新子会话可能尚无 LLM 调用,未进实时采集),
163
+ // 再从实时/历史 header 图递归向下;Set 防环与重复计数。list 失败仍用已有内存图。
164
+ if (sessionQuery && typeof sessionQuery.listSessions === 'function') {
165
+ try {
166
+ const sessions = await sessionQuery.listSessions()
167
+ for (const row of sessions || []) {
168
+ const h = row && row.header
169
+ if (h && h.id) rememberSessionHeader(h.id, h)
170
+ }
171
+ } catch { /* 只读列表不可用:保留已采集部分并标 incomplete */ }
172
+ }
173
+ const ids = new Set([sessionId])
174
+ let changed = true
175
+ while (changed) {
176
+ changed = false
177
+ for (const [sid, meta] of sessionMeta) {
178
+ if (meta.parentSessionId && ids.has(meta.parentSessionId) && !ids.has(sid)) {
179
+ ids.add(sid); changed = true
180
+ }
181
+ }
182
+ }
183
+ const line = lineageOf(sessionId)
184
+ return {
185
+ ...base, sessionIds: [...ids], rootSessionId: line.rootSessionId,
186
+ descendantCount: ids.size - 1, complete: !line.incomplete,
187
+ }
188
+ }
189
+ function sessionBreakdown(list, context) {
190
+ if (!context.sessionId) return []
191
+ const selected = new Set(context.sessionIds)
192
+ const map = new Map()
193
+ for (const record of list) {
194
+ if (!selected.has(record.sessionId)) continue
195
+ const row = map.get(record.sessionId) || {
196
+ sessionId: record.sessionId,
197
+ parentSessionId: record.parentSessionId || '',
198
+ rootSessionId: record.rootSessionId || record.sessionId,
199
+ sessionDepth: record.sessionDepth || 0,
200
+ isSubtask: !!record.isSubtask,
201
+ ...totals([record]),
202
+ }
203
+ if (map.has(record.sessionId)) {
204
+ const t = totals([record])
205
+ for (const key of Object.keys(t)) if (typeof t[key] === 'number') row[key] += t[key]
206
+ row.cacheHitPct = row.billedInput > 0 ? Math.round(row.cacheReadTokens / row.billedInput * 100) : 0
207
+ } else map.set(record.sessionId, row)
208
+ }
209
+ return [...map.values()].sort((a, b) => a.sessionDepth - b.sessionDepth || a.sessionId.localeCompare(b.sessionId))
210
+ }
211
+
59
212
  // ===== 定价与金额估算 =====
60
213
  // 定价表以「人民币元 / 百万 tokens」为基准(DeepSeek/智谱官方刊例即人民币), 金额先算 CNY,
61
214
  // 对外记录的 cost 保持 USD,供旧版客户端兼容;当前客户端和 CSV 统一展示人民币。
@@ -670,6 +823,11 @@ export const feature = {
670
823
  id: sessionId + ':' + event.seq,
671
824
  time: event.time,
672
825
  sessionId,
826
+ // 查询时还会用最新 sessionMeta 投影一次;这里保留采集时的标量形状,便于导出/测试。
827
+ parentSessionId: (sessionMeta.get(sessionId) || {}).parentSessionId || '',
828
+ rootSessionId: sessionId,
829
+ sessionDepth: 0,
830
+ isSubtask: !!(sessionMeta.get(sessionId) || {}).isSubtask,
673
831
  provider: head.provider || '',
674
832
  model: head.model || '',
675
833
  apiKey: '',
@@ -716,11 +874,21 @@ export const feature = {
716
874
  let added = 0
717
875
  for (const s of sessions) {
718
876
  const sid = s && s.header ? s.header.id : (s && s.id)
719
- if (!sid || scannedSessions.has(sid)) continue
877
+ if (!sid) continue
878
+ // listSessions 的 header 很轻量:即使该会话日志已扫描过,也刷新谱系(新插件启动时
879
+ // records 为空但 scannedSessions 可能由热重载保留;父子头必须先于归属查询就绪)。
880
+ rememberSessionHeader(sid, s && s.header)
881
+ if (scannedSessions.has(sid)) continue
720
882
  scannedSessions.add(sid)
721
883
  try {
722
884
  const snap = await sessionQuery.readSession(sid)
723
- const events = snap && snap.events ? snap.events : []
885
+ rememberSessionHeader(sid, snap && (snap.session || snap.header))
886
+ const allEvents = snap && snap.events ? snap.events : []
887
+ // 子会话可能带父会话的 seed 前缀;那不是子会话新发生的 LLM 调用。
888
+ // 只采集 inherited cut 之后的自有事件,避免主任务+子任务累计把同一历史再加一次。
889
+ const inherited = Number.isSafeInteger(snap && snap.inheritedEventCount) && snap.inheritedEventCount > 0
890
+ ? snap.inheritedEventCount : 0
891
+ const events = allEvents.filter((e) => Number(e.seq) >= inherited)
724
892
  // 两遍: 先建 turn/end 映射, 再生成记录
725
893
  preScanTurnEnds(sid, events)
726
894
  const recs = ingestEvents(sid, events)
@@ -743,7 +911,7 @@ export const feature = {
743
911
  }
744
912
  }
745
913
 
746
- function buildQuery(args) {
914
+ function buildQuery(args, sessionContext) {
747
915
  const q = args || {}
748
916
  const from = typeof q.from === 'number' ? q.from : 0
749
917
  const to = typeof q.to === 'number' ? q.to : Infinity
@@ -752,13 +920,14 @@ export const feature = {
752
920
  const status = (q.status || '').trim()
753
921
  const effort = (q.effort || '').trim()
754
922
  const sessionId = (q.sessionId || '').trim()
755
- return [...records.values()].filter((r) => {
923
+ const scopeIds = sessionContext && sessionContext.scope === 'tree' ? new Set(sessionContext.sessionIds) : null
924
+ return [...records.values()].map(withLineage).filter((r) => {
756
925
  if (r.time < from || r.time > to) return false
757
926
  if (provider && r.provider !== provider) return false
758
927
  if (model && r.model !== model) return false
759
928
  if (status && r.status !== status) return false
760
929
  if (effort && r.effort !== effort) return false
761
- if (sessionId && r.sessionId !== sessionId) return false
930
+ if (sessionId && (scopeIds ? !scopeIds.has(r.sessionId) : r.sessionId !== sessionId)) return false
762
931
  return true
763
932
  })
764
933
  }
@@ -825,6 +994,7 @@ export const feature = {
825
994
  sessionQuery = sqCtx.sessionQuery
826
995
  // 服务就绪后加载 settings 单价配置(汇率 + 自定义单价 + 抓取开关), 供采集/重扫/导出使用
827
996
  loadPricingConfig()
997
+ loadSessionScope()
828
998
  // 从官网获取最新定价(启动时 + 每 N 小时自动刷新; 面板关闭抓取时不发起请求)
829
999
  if (fetchOfficialEnabled) fetchOfficialPricing()
830
1000
  const fetchTimer = setInterval(() => { if (fetchOfficialEnabled) fetchOfficialPricing() }, getPricingFetchConfig().intervalMs)
@@ -833,6 +1003,7 @@ export const feature = {
833
1003
  disposers.push(sqCtx.on('session/event', (session, event) => {
834
1004
  try {
835
1005
  const sid = typeof session === 'object' && session ? (session.id || '') : String(session || '')
1006
+ if (session && typeof session === 'object') rememberSessionHeader(sid, session.header)
836
1007
  const rec = ingestEvent(sid, event)
837
1008
  if (rec) records.set(rec.id, rec)
838
1009
  // turn/end 到达后回填该 turn 已有记录的状态/错误(实时增量场景)
@@ -873,8 +1044,10 @@ export const feature = {
873
1044
  const payload = await readBody(req)
874
1045
  if (method === 'query') {
875
1046
  loadPricingConfig()
1047
+ loadSessionScope()
1048
+ const sessionContext = await resolveSessionScope(payload || {})
876
1049
  // 费用按当前单价即时重算(withCost): 面板改价后立即反映到统计与明细, 无需重扫历史。
877
- const list = buildQuery(payload || {}).map(withCost)
1050
+ const list = buildQuery(payload || {}, sessionContext).map(withCost)
878
1051
  const rows = [...list].sort((a, b) => b.time - a.time)
879
1052
  const all = [...records.values()]
880
1053
  const cfg = readConfiguredProviders()
@@ -918,10 +1091,32 @@ export const feature = {
918
1091
  sources: [...new Set(list.map((r) => r.pricingSource).filter(Boolean))].map((s) => PRICING_SOURCE_LABELS[s] || s),
919
1092
  },
920
1093
  totals: totals(list),
1094
+ // 选中会话时同时返回“本会话”拆分,客户端不必再做一次查询即可展示 主任务自身 / 子任务 / 累计。
1095
+ // 全局查询不返回拆分,避免把各父任务的累计再次相加造成重复。
1096
+ directTotals: sessionContext.sessionId ? totals(list.filter((r) => r.sessionId === sessionContext.sessionId)) : null,
1097
+ sessionBreakdown: sessionBreakdown(list, sessionContext),
1098
+ sessionScope: sessionContext,
1099
+ defaultSessionScope,
921
1100
  summary: payload && payload.dim ? summarize(list, payload.dim) : [],
922
1101
  }
923
1102
  })
924
1103
  }
1104
+ if (method === 'config') {
1105
+ const input = payload || {}
1106
+ if (input.sessionScope !== undefined && input.sessionScope !== 'tree' && input.sessionScope !== 'session') {
1107
+ const err = new Error('会话用量口径只能是 tree(含子任务)或 session(仅本会话)')
1108
+ err.statusCode = 400
1109
+ throw err
1110
+ }
1111
+ loadSessionScope()
1112
+ if (input.sessionScope !== undefined && input.sessionScope !== defaultSessionScope) {
1113
+ const root = readDockRoot(ctx)
1114
+ const current = root && root.tokenlog && typeof root.tokenlog === 'object' ? root.tokenlog : {}
1115
+ await mutateDockSection(ctx, ['tokenlog'], { ...current, sessionScope: input.sessionScope })
1116
+ loadSessionScope()
1117
+ }
1118
+ return sendJson(res, 200, { ok: true, data: { sessionScope: defaultSessionScope } })
1119
+ }
925
1120
  if (method === 'pricing') {
926
1121
  loadPricingConfig()
927
1122
  return sendJson(res, 200, { ok: true, data: readPricingConfig() })
@@ -933,12 +1128,14 @@ export const feature = {
933
1128
  }
934
1129
  if (method === 'export') {
935
1130
  loadPricingConfig()
936
- const list = buildQuery(payload || {}).map(withCost)
1131
+ loadSessionScope()
1132
+ const sessionContext = await resolveSessionScope(payload || {})
1133
+ const list = buildQuery(payload || {}, sessionContext).map(withCost)
937
1134
  // export 返回结构化明细(不是 CSV 文本):客户端按「明细表列序 + 中文表头」统一
938
1135
  // 格式化成 CSV,取值格式与页面显示一致;rateUsdCny 供客户端把 cost(USD) 折人民币。
939
1136
  return sendJson(res, 200, {
940
1137
  ok: true,
941
- data: { rows: list, rateUsdCny: usdCnyRate, count: list.length },
1138
+ data: { rows: list, rateUsdCny: usdCnyRate, count: list.length, sessionScope: sessionContext },
942
1139
  })
943
1140
  }
944
1141
  if (method === 'scan') {