@qjp88995/agent-chat-web 0.1.0 → 0.3.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.
Files changed (86) hide show
  1. package/dist/display/block-layout.d.ts +90 -0
  2. package/dist/display/block-layout.d.ts.map +1 -0
  3. package/dist/display/block-layout.js +133 -0
  4. package/dist/display/block-layout.js.map +1 -0
  5. package/dist/display/config.d.ts +52 -0
  6. package/dist/display/config.d.ts.map +1 -0
  7. package/dist/display/config.js +16 -0
  8. package/dist/display/config.js.map +1 -0
  9. package/dist/display/display-names.d.ts +27 -0
  10. package/dist/display/display-names.d.ts.map +1 -0
  11. package/dist/display/display-names.js +34 -0
  12. package/dist/display/display-names.js.map +1 -0
  13. package/dist/display/index.d.ts +20 -0
  14. package/dist/display/index.d.ts.map +1 -0
  15. package/dist/display/index.js +14 -0
  16. package/dist/display/index.js.map +1 -0
  17. package/dist/display/process-line.d.ts +102 -0
  18. package/dist/display/process-line.d.ts.map +1 -0
  19. package/dist/display/process-line.js +216 -0
  20. package/dist/display/process-line.js.map +1 -0
  21. package/dist/display/reasoning-status.d.ts +28 -0
  22. package/dist/display/reasoning-status.d.ts.map +1 -0
  23. package/dist/display/reasoning-status.js +53 -0
  24. package/dist/display/reasoning-status.js.map +1 -0
  25. package/dist/display/spawn-display.d.ts +32 -0
  26. package/dist/display/spawn-display.d.ts.map +1 -0
  27. package/dist/display/spawn-display.js +39 -0
  28. package/dist/display/spawn-display.js.map +1 -0
  29. package/dist/display/tool-display.d.ts +36 -0
  30. package/dist/display/tool-display.d.ts.map +1 -0
  31. package/dist/display/tool-display.js +61 -0
  32. package/dist/display/tool-display.js.map +1 -0
  33. package/dist/stream/delta-coalescer.d.ts +57 -0
  34. package/dist/stream/delta-coalescer.d.ts.map +1 -0
  35. package/dist/stream/delta-coalescer.js +134 -0
  36. package/dist/stream/delta-coalescer.js.map +1 -0
  37. package/dist/stream/index.d.ts +7 -0
  38. package/dist/stream/index.d.ts.map +1 -0
  39. package/dist/stream/index.js +6 -0
  40. package/dist/stream/index.js.map +1 -0
  41. package/dist/stream/session-events.d.ts +50 -0
  42. package/dist/stream/session-events.d.ts.map +1 -0
  43. package/dist/stream/session-events.js +68 -0
  44. package/dist/stream/session-events.js.map +1 -0
  45. package/dist/stream/wire.d.ts +147 -0
  46. package/dist/stream/wire.d.ts.map +1 -0
  47. package/dist/stream/wire.js +2 -0
  48. package/dist/stream/wire.js.map +1 -0
  49. package/dist/subagent/index.d.ts +5 -0
  50. package/dist/subagent/index.d.ts.map +1 -0
  51. package/dist/subagent/index.js +5 -0
  52. package/dist/subagent/index.js.map +1 -0
  53. package/dist/subagent/subagent-handle.d.ts +30 -0
  54. package/dist/subagent/subagent-handle.d.ts.map +1 -0
  55. package/dist/subagent/subagent-handle.js +38 -0
  56. package/dist/subagent/subagent-handle.js.map +1 -0
  57. package/dist/trace/index.d.ts +7 -0
  58. package/dist/trace/index.d.ts.map +1 -0
  59. package/dist/trace/index.js +7 -0
  60. package/dist/trace/index.js.map +1 -0
  61. package/dist/trace/message-blocks.d.ts +83 -0
  62. package/dist/trace/message-blocks.d.ts.map +1 -0
  63. package/dist/trace/message-blocks.js +148 -0
  64. package/dist/trace/message-blocks.js.map +1 -0
  65. package/dist/trace/trace-tree.d.ts +65 -0
  66. package/dist/trace/trace-tree.d.ts.map +1 -0
  67. package/dist/trace/trace-tree.js +259 -0
  68. package/dist/trace/trace-tree.js.map +1 -0
  69. package/package.json +23 -4
  70. package/src/display/block-layout.ts +195 -0
  71. package/src/display/config.ts +72 -0
  72. package/src/display/display-names.ts +46 -0
  73. package/src/display/index.ts +67 -0
  74. package/src/display/process-line.ts +313 -0
  75. package/src/display/reasoning-status.ts +51 -0
  76. package/src/display/spawn-display.ts +72 -0
  77. package/src/display/tool-display.ts +68 -0
  78. package/src/stream/delta-coalescer.ts +210 -0
  79. package/src/stream/index.ts +17 -0
  80. package/src/stream/session-events.ts +97 -0
  81. package/src/stream/wire.ts +144 -0
  82. package/src/subagent/index.ts +4 -0
  83. package/src/subagent/subagent-handle.ts +42 -0
  84. package/src/trace/index.ts +13 -0
  85. package/src/trace/message-blocks.ts +194 -0
  86. package/src/trace/trace-tree.ts +322 -0
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 从 `Delegate` 这次调用的结构化引用里取子会话 id(handle)。
3
+ *
4
+ * **只读 `ref`。** 工具的 `output` 现在恒为渲染文本(SSE、落库、模型三处同源),
5
+ * 从文案里正则抠 id 会随文案静默失效——`persistRef()` 存在就是为了这件事。
6
+ *
7
+ * 真正的拒绝(未定义 / 配额满 / 深度触顶)是 `{kind:'error'}`,`persistRef` 对
8
+ * 它返回 undefined,于是这里给出 null,正确地落进「失败」。而**同步模式等待期
9
+ * 间也没有 handle**(那几十秒里 `tool-result` 事件压根还没发),那不是失败——
10
+ * 判据见 `subagentCardStatus`。
11
+ */
12
+ /**
13
+ * 子 Agent 卡片显示什么状态。
14
+ *
15
+ * **没有 handle ≠ 失败**,这是踩过两次的地方。同步模式(`run_in_background`
16
+ * 缺省)下 `Delegate` 要等子跑完才返回,在那几十秒到几分钟里 `tool-result`
17
+ * 事件根本还没发出 —— 卡片既没有 `output` 也没有 `ref`。异步模式因为工具瞬间
18
+ * 就返回 handle,从来没暴露过这条路径。
19
+ *
20
+ * 判据是**工具调用本身还在不在跑**:还在跑就是「进行中」,跑完了却仍然没有
21
+ * handle 才是真的没派生出去(子 Agent 未定义 / 配额满 / 深度触顶)。
22
+ *
23
+ * 等待期间拿不到 handle 是固有的:子 run 的 `parentRunId` 指向**父 run**,同一
24
+ * 轮里多次 spawn 会共用它,没法一对一认回具体那次工具调用。要在等待期间也能
25
+ * 下钻,得让工具在 spawn 成功的当下就把 handle 报出来(现在没有这条通道);
26
+ * 在那之前,右栏的子会话树仍然照常能看到它、点得进去。
27
+ */
28
+ export function subagentCardStatus(
29
+ handle: string | null,
30
+ toolNodeStatus: 'running' | 'done' | 'failed',
31
+ statusOf: (handle: string) => string
32
+ ): string {
33
+ if (handle) return statusOf(handle);
34
+ return toolNodeStatus === 'running' ? 'running' : 'failed';
35
+ }
36
+
37
+ export function extractHandle(
38
+ ref: Record<string, unknown> | null | undefined
39
+ ): string | null {
40
+ if (ref && typeof ref.handle === 'string' && ref.handle) return ref.handle;
41
+ return null;
42
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * 轨迹:把 `data-agent-trace` 事件(或落库 parts)建成工具/子 run 树,再和正文、
3
+ * 推理拼成一条消息的块序列。
4
+ */
5
+ export {
6
+ appendReasoningBlock,
7
+ appendTextBlock,
8
+ blocksFromParts,
9
+ hiddenRunKeys,
10
+ mergeTraceBlocks,
11
+ type MessageBlock,
12
+ } from './message-blocks.js';
13
+ export { buildTraceTree, type TraceNode, tracesFromParts } from './trace-tree.js';
@@ -0,0 +1,194 @@
1
+ import type { MessagePart } from '@qjp88995/agent-runtime/schema';
2
+
3
+ import type { AgentTraceData } from '../stream/wire.js';
4
+ import { buildTraceTree, type TraceNode } from './trace-tree.js';
5
+
6
+ /**
7
+ * 一条助手消息的**有序内容块**——修复「工具调用永远显示在文本下面」。
8
+ *
9
+ * 旧模型把 `text`(拼接成一整串)与 `traces`(数组)拆成两个独立字段,渲染
10
+ * 时恒「先文本、后工具」,真实时间顺序(文字→工具→文字→工具)在数据层就丢
11
+ * 了。改成一个按到达/落库顺序排列的块序列:`text` 块承载连续文字,`trace`
12
+ * 块只存**顶层** trace 节点的 key(`tool:…`/`run:…`/`err:…`),渲染时再用
13
+ * `buildTraceTree(traces)` 的结果查回完整节点(含子步骤递归)。
14
+ *
15
+ * `reasoning` 块同样进块序列、按位置交错——修「思考→调用工具→再思考」时后一段
16
+ * 思考被并进前一段的问题(后端落库 parts 本就按时间序保留 reasoning/text/
17
+ * tool-call,见 steps-to-parts.ts#contentToParts;旧前端把 reasoning 拍平成一个
18
+ * 顶部字符串、丢了位置)。`LiveMessage.reasoning` 仍保留一份拍平副本(与 `text`
19
+ * 同款,供长度判断/兼容既有断言),但**渲染以块序列为权威**。
20
+ */
21
+ export type MessageBlock =
22
+ | { type: 'text'; text: string }
23
+ | { type: 'trace'; key: string }
24
+ | {
25
+ type: 'reasoning';
26
+ text: string;
27
+ /**
28
+ * 这段思考产出了多久(毫秒)。两条路径给出的是**同一个量**——从第一个
29
+ * delta 到最后一个:流式路径由 `appendReasoningBlock` 边收边数,历史
30
+ * 路径直接取落库 part 的 `durationMs`(runtime 按事件时刻测,见
31
+ * `MessagePartSchema`)。同源是这里的要点:刷新页面后卡片上的数字不该
32
+ * 变,否则用户会以为自己记错了。
33
+ *
34
+ * 可空 = 不知道(该字段之前落的历史消息、abort 兜底路径)。渲染时不
35
+ * 显示时长,而不是显示 0。
36
+ */
37
+ durationMs?: number;
38
+ /** 流式专用:本块第一个 delta 的到达时刻,用来现算 durationMs。 */
39
+ startedAt?: number;
40
+ };
41
+
42
+ /**
43
+ * 追加一段文字增量:并入末尾的 text 块,否则起一个新 text 块。空增量不产生
44
+ * 块(避免流式首帧空 delta 制造空块)。
45
+ */
46
+ export function appendTextBlock(
47
+ blocks: MessageBlock[],
48
+ delta: string
49
+ ): MessageBlock[] {
50
+ if (delta === '') return blocks;
51
+ const last = blocks[blocks.length - 1];
52
+ if (last && last.type === 'text') {
53
+ return [...blocks.slice(0, -1), { type: 'text', text: last.text + delta }];
54
+ }
55
+ return [...blocks, { type: 'text', text: delta }];
56
+ }
57
+
58
+ /**
59
+ * 追加一段思考增量:并入末尾的 reasoning 块,否则起一个**新** reasoning 块。
60
+ * 「起新块」正是修复的关键——一旦中间夹了 text/工具块,后续思考不会再并回前
61
+ * 一段(末尾块类型已变),而是新起一段,保住「思考→工具→再思考」的时间顺序。
62
+ */
63
+ export function appendReasoningBlock(
64
+ blocks: MessageBlock[],
65
+ delta: string,
66
+ now: number = Date.now(),
67
+ /**
68
+ * 这段增量的**起点**。合并帧(刷新后整段重放压成一条)的起点与终点不是同一
69
+ * 时刻,新建块时用它做 `startedAt`——否则秒数从「现在」起、刷新后从 0 开始。
70
+ * 单条帧起点即终点,缺省等于 `now`。
71
+ */
72
+ startedAt: number = now
73
+ ): MessageBlock[] {
74
+ if (delta === '') return blocks;
75
+ const last = blocks[blocks.length - 1];
76
+ if (last && last.type === 'reasoning') {
77
+ return [
78
+ ...blocks.slice(0, -1),
79
+ {
80
+ ...last,
81
+ text: last.text + delta,
82
+ // 每个 delta 都把时长推到「此刻」,于是它在思考期间自然跳动、思考一停
83
+ // 就定格在最后一个 delta 上——不需要额外的定时器,也不会在等工具返回
84
+ // 时继续空转。
85
+ durationMs:
86
+ last.startedAt != null ? now - last.startedAt : last.durationMs,
87
+ },
88
+ ];
89
+ }
90
+ return [
91
+ ...blocks,
92
+ {
93
+ type: 'reasoning',
94
+ text: delta,
95
+ startedAt,
96
+ // 合并帧新建块时起点与终点已经拉开,时长当场就有;单条帧两者相等 → 0,
97
+ // 与旧行为一致(下一条增量再推进)。
98
+ ...(now > startedAt ? { durationMs: now - startedAt } : {}),
99
+ },
100
+ ];
101
+ }
102
+
103
+ /**
104
+ * 根据最新的完整 traces 数组,把**尚未出现在块序列里的顶层 trace 节点**按序
105
+ * 追加到末尾。新顶层节点必然晚于当前所有 text(它此刻才到达),追加到末尾即
106
+ * 正确交错。已存在的 key 不重复插入(tool-result 更新的是同一个 `tool:` 节点,
107
+ * 不产生新块)。
108
+ */
109
+ export function mergeTraceBlocks(
110
+ blocks: MessageBlock[],
111
+ traces: AgentTraceData[]
112
+ ): MessageBlock[] {
113
+ const roots = buildTraceTree(traces);
114
+ const known = new Set(blocks.filter(b => b.type === 'trace').map(b => b.key));
115
+ const out = [...blocks];
116
+ for (const n of roots) {
117
+ if (!known.has(n.key)) out.push({ type: 'trace', key: n.key });
118
+ }
119
+ return out;
120
+ }
121
+
122
+ /**
123
+ * 从已落库消息的 parts 顺序重建块序列——parts 本身就是有序的
124
+ * (reasoning / text / tool-call / tool-result 交错,见
125
+ * steps-to-parts.ts#contentToParts),故刷新页面/切回旧会话也能看到正确的
126
+ * 思考↔文字↔工具时间顺序。tool-result 不产生新块(由对应 tool-call 块承载);
127
+ * reasoning part 按位置产出 reasoning 块(连续的合并成一段)。
128
+ */
129
+ /** 两段思考并成一张卡时的时长合并:都不知道 → 仍然不知道,否则相加。 */
130
+ function sumDuration(
131
+ a: number | undefined,
132
+ b: number | undefined
133
+ ): { durationMs?: number } {
134
+ if (a == null && b == null) return {};
135
+ return { durationMs: (a ?? 0) + (b ?? 0) };
136
+ }
137
+
138
+ export function blocksFromParts(parts: readonly MessagePart[]): MessageBlock[] {
139
+ const out: MessageBlock[] = [];
140
+ for (const p of parts) {
141
+ if (p.type === 'text') {
142
+ if (p.text === '') continue;
143
+ const last = out[out.length - 1];
144
+ if (last && last.type === 'text') {
145
+ out[out.length - 1] = { type: 'text', text: last.text + p.text };
146
+ } else {
147
+ out.push({ type: 'text', text: p.text });
148
+ }
149
+ } else if (p.type === 'reasoning') {
150
+ if (p.text === '') continue;
151
+ const last = out[out.length - 1];
152
+ if (last && last.type === 'reasoning') {
153
+ out[out.length - 1] = {
154
+ type: 'reasoning',
155
+ text: last.text + p.text,
156
+ // 合并成一张卡 → 时长相加。后端只把时间窗挂在每个 step 的第一个
157
+ // reasoning part 上(见 turn-run.ts),故这里相加不会
158
+ // 重复计数;两个都没有时保持 undefined(= 不知道,别显示成 0)。
159
+ ...sumDuration(last.durationMs, p.durationMs),
160
+ };
161
+ } else {
162
+ out.push({
163
+ type: 'reasoning',
164
+ text: p.text,
165
+ ...(p.durationMs != null ? { durationMs: p.durationMs } : {}),
166
+ });
167
+ }
168
+ } else if (p.type === 'tool-call') {
169
+ out.push({ type: 'trace', key: `tool:${p.toolCallId}` });
170
+ }
171
+ }
172
+ return out;
173
+ }
174
+
175
+ /**
176
+ * 主 agent 视图里要**隐藏**的顶层子 run 节点 key 集合。
177
+ *
178
+ * subagent 在主视图由它对应的 `Delegate` **工具节点**代表(渲染成子 Agent
179
+ * 卡,读工具调用的 input/output,见 trace-panel.tsx#SubagentCard)。选工具节点
180
+ * 而非子 run 节点作锚的关键:**Delegate 工具调用在实时 SSE 与历史落库里都
181
+ * 存在**(历史 parts 保留主 agent 自己的工具调用),而**子 run 节点只有实时
182
+ * SSE 才有**——子 agent 边界在持久化时丢失(见 trace-tree.ts#tracesFromParts:
183
+ * 落库 parts 恒 depth 0、无 run-start/run-finish)。以工具节点为锚,实时与历史
184
+ * 表示一致(修「历史丢 title」)。
185
+ *
186
+ * 子 run 节点还携带子会话**内部步骤**(children)——那些属于子会话、下钻查看,
187
+ * 不该平铺在主时间线(修「主 agent 显示 subagent 内部调用」)。故一律隐藏顶层
188
+ * run 节点。
189
+ */
190
+ export function hiddenRunKeys(roots: TraceNode[]): Set<string> {
191
+ const hidden = new Set<string>();
192
+ for (const n of roots) if (n.kind === 'run') hidden.add(n.key);
193
+ return hidden;
194
+ }
@@ -0,0 +1,322 @@
1
+ import type { MessagePart, ToolResultImage } from '@qjp88995/agent-runtime/schema';
2
+
3
+ import type { AgentTraceData } from '../stream/wire.js';
4
+
5
+ export interface TraceNode {
6
+ key: string;
7
+ kind: 'tool' | 'run' | 'error';
8
+ runId: string;
9
+ /**
10
+ * 父 run 的 id(run-start 的 `parentRunId`)。顶层渲染据此把「Delegate
11
+ * 工具节点」与它派生出来的「子 run 节点」认成同一件事的两面——子 run 的
12
+ * `parentRunId` 恒等于发起它的 spawn 工具节点的 `runId`(见
13
+ * message-blocks.ts#hiddenSpawnToolKeys)。多数节点为 null。
14
+ */
15
+ parentRunId: string | null;
16
+ /** 产生该节点的会话 id。run 型节点用它定位子会话(停止/打开)。 */
17
+ sessionId: string;
18
+ depth: number;
19
+ toolName: string | null;
20
+ agentName: string | null;
21
+ prompt: string | null;
22
+ /** 子 run 的一句话任务标题(run 型节点用;其余为 null)。 */
23
+ title: string | null;
24
+ status: 'running' | 'done' | 'failed';
25
+ input: unknown;
26
+ output: unknown;
27
+ /**
28
+ * 工具落库时附的结构化引用(`MessagePart.ref`)。`output` 是给人看的文本,
29
+ * 程序判据一律读这里 —— 从渲染文案里抠 id 会随文案静默失效。
30
+ */
31
+ ref: Record<string, unknown> | null;
32
+ /**
33
+ * 平台针对这次调用追加给模型的提示(`MessagePart.systemNote`,当前唯一来源:
34
+ * 重复调用提醒)。**不是工具输出的一部分**,也不表示失败——单独渲染。
35
+ */
36
+ systemNote: string | null;
37
+ /** 这次调用交给模型看的图(`MessagePart.images`),按 `src` 渲染缩略图。 */
38
+ images: ToolResultImage[] | null;
39
+ message: string | null;
40
+ /**
41
+ * 模型至此吐了多少字符的**入参**(`tool-input-progress`)。
42
+ *
43
+ * 只在「参数还在生成」这一段有意义——`input` 一旦到齐(`tool-call`)它就
44
+ * 不再更新,界面也该改去显示真正的入参。null = 没收到过进度(历史重放、
45
+ * 旧后端、或参数短到一条进度都没触发)。
46
+ */
47
+ inputChars: number | null;
48
+ children: TraceNode[];
49
+ }
50
+
51
+ /**
52
+ * 把扁平事件流重建成可折叠的轨迹树。
53
+ * 子 agent 按 parentRunId 归到父的 run 节点下,前端据此缩进渲染。
54
+ */
55
+ export function buildTraceTree(events: AgentTraceData[]): TraceNode[] {
56
+ const sorted = [...events].sort((a, b) => a.seq - b.seq);
57
+
58
+ const runNodes = new Map<string, TraceNode>();
59
+ const toolNodes = new Map<string, TraceNode>();
60
+ const rootOrder: TraceNode[] = [];
61
+
62
+ const attach = (node: TraceNode, parentRunId: string | null) => {
63
+ if (parentRunId && runNodes.has(parentRunId)) {
64
+ runNodes.get(parentRunId)!.children.push(node);
65
+ } else {
66
+ rootOrder.push(node);
67
+ }
68
+ };
69
+
70
+ for (const e of sorted) {
71
+ if (e.kind === 'run-start' && e.parentRunId) {
72
+ // agentName/prompt 是 AgentTraceData 上的显式字段(projection 直接透传),
73
+ // 不从 input 读——input 语义是「工具入参」,别混用。
74
+ const node: TraceNode = {
75
+ key: `run:${e.runId}`,
76
+ kind: 'run',
77
+ runId: e.runId,
78
+ parentRunId: e.parentRunId,
79
+ sessionId: e.sessionId,
80
+ depth: e.depth,
81
+ toolName: null,
82
+ agentName: e.agentName ?? null,
83
+ prompt: e.prompt ?? null,
84
+ title: e.title ?? null,
85
+ status: 'running',
86
+ input: null,
87
+ output: null,
88
+ ref: null,
89
+ systemNote: null,
90
+ images: null,
91
+ message: null,
92
+ inputChars: null,
93
+ children: [],
94
+ };
95
+ runNodes.set(e.runId, node);
96
+ attach(node, e.parentRunId);
97
+ continue;
98
+ }
99
+
100
+ if (e.kind === 'run-finish') {
101
+ const node = runNodes.get(e.runId);
102
+ if (node) {
103
+ const s = e.status;
104
+ node.status = s === 'completed' || s == null ? 'done' : 'failed';
105
+ }
106
+ continue;
107
+ }
108
+
109
+ // 模型开始吐这次调用的参数了。**先把卡片建出来**——`tool-call` 要等整个
110
+ // step 的流消费完才发,写一篇长文时中间是几十秒空白,界面上什么都没有,
111
+ // 用户只能当它卡了。此时还没有 `input`(正在生成中)。
112
+ if (e.kind === 'tool-input-start' && e.toolCallId) {
113
+ const node: TraceNode = {
114
+ key: `tool:${e.toolCallId}`,
115
+ kind: 'tool',
116
+ runId: e.runId,
117
+ parentRunId: e.parentRunId,
118
+ sessionId: e.sessionId,
119
+ depth: e.depth,
120
+ toolName: e.toolName,
121
+ agentName: null,
122
+ prompt: null,
123
+ title: null,
124
+ status: 'running',
125
+ input: null,
126
+ output: null,
127
+ ref: null,
128
+ systemNote: null,
129
+ images: null,
130
+ message: null,
131
+ inputChars: null,
132
+ children: [],
133
+ };
134
+ toolNodes.set(e.toolCallId, node);
135
+ attach(node, e.depth > 0 ? e.runId : null);
136
+ continue;
137
+ }
138
+
139
+ // 参数还在生成——只更新那个数字,让卡片动起来。
140
+ if (e.kind === 'tool-input-progress' && e.toolCallId) {
141
+ const node = toolNodes.get(e.toolCallId);
142
+ if (node) node.inputChars = e.inputChars;
143
+ continue;
144
+ }
145
+
146
+ /**
147
+ * 内容预览**不动这张卡上的任何东西**(正文是稿栏的事,见
148
+ * `doc-stage.ts`)——尤其不能碰 `inputChars`:progress 数的是**入参原始
149
+ * JSON** 的码点数,preview 的 `chars` 数的是**解码后正文**的码点数,后者
150
+ * 恒小于前者。两个量纲写进同一格,卡片上那个「已生成 N 字」就会在两条
151
+ * 事件交替到达时来回跳。
152
+ */
153
+ if (e.kind === 'tool-input-preview') continue;
154
+
155
+ if (e.kind === 'tool-call' && e.toolCallId) {
156
+ // **已经有节点就地更新,不要再 attach 一个**:`tool-input-start` 多数
157
+ // 情况下已经把它建出来并挂进树了,这里再建一个会让同一次调用在界面上
158
+ // 出现两张卡片。历史重放(`tracesFromParts`)只产 tool-call/tool-result,
159
+ // 走的仍是下面的新建分支。
160
+ const existing = toolNodes.get(e.toolCallId);
161
+ if (existing) {
162
+ existing.input = e.input;
163
+ continue;
164
+ }
165
+ const node: TraceNode = {
166
+ key: `tool:${e.toolCallId}`,
167
+ kind: 'tool',
168
+ runId: e.runId,
169
+ parentRunId: e.parentRunId,
170
+ sessionId: e.sessionId,
171
+ depth: e.depth,
172
+ toolName: e.toolName,
173
+ agentName: null,
174
+ prompt: null,
175
+ title: null,
176
+ status: 'running',
177
+ input: e.input,
178
+ output: null,
179
+ ref: null,
180
+ systemNote: null,
181
+ images: null,
182
+ message: null,
183
+ inputChars: null,
184
+ children: [],
185
+ };
186
+ toolNodes.set(e.toolCallId, node);
187
+ // 深度 > 0 的工具挂到自己所属的子 run 下。
188
+ attach(node, e.depth > 0 ? e.runId : null);
189
+ continue;
190
+ }
191
+
192
+ if (e.kind === 'tool-result' && e.toolCallId) {
193
+ const node = toolNodes.get(e.toolCallId);
194
+ if (node) {
195
+ node.output = e.output;
196
+ // **`ref` 只可能出现在 tool-result 上**——tool-call 那一刻工具还没跑,
197
+ // 自然没有结果可引用,故上面建节点时它恒为 null。漏掉这一行的后果不是
198
+ // 「少个字段」而是一个响亮的错误结论:`extractHandle(node.ref)` 恒返回
199
+ // null,子 Agent 卡片的 `subagentCardStatus` 就走进「跑完了却没派生出
200
+ // 去」那一支,把**每一个成功完成的子 Agent 都渲染成「✗ 失败」**,连
201
+ // 「⤢ 打开」「⏹ 停止」两个按钮也一起消失(它们以 handle 为渲染条件)。
202
+ // 实时与历史两条路都经过本函数,所以刷新页面也不会好;而右栏与回执气泡
203
+ // 各有各的状态来源,同屏显示「完成」——这正是它当初的暴露方式。
204
+ node.ref = e.ref ?? null;
205
+ node.systemNote = e.systemNote ?? null;
206
+ node.images = e.images ?? null;
207
+ // **读后端算好的 `isError`,不从 `output` 反推。** 这里曾经写的是
208
+ // `output.ok === false`,而 `output` 从来就没有过 `ok` 字段(实时那份
209
+ // 是 `ToolOut`,判别键叫 `kind`;落库那份是纯文本)——判据恒为假,
210
+ // 每一次失败的工具调用都渲染成绿色的「完成」。
211
+ node.status = e.isError === true ? 'failed' : 'done';
212
+ }
213
+ continue;
214
+ }
215
+
216
+ if (e.kind === 'error') {
217
+ attach(
218
+ {
219
+ key: `err:${e.seq}`,
220
+ kind: 'error',
221
+ runId: e.runId,
222
+ parentRunId: e.parentRunId,
223
+ sessionId: e.sessionId,
224
+ depth: e.depth,
225
+ toolName: null,
226
+ agentName: null,
227
+ prompt: null,
228
+ title: null,
229
+ status: 'failed',
230
+ input: null,
231
+ output: null,
232
+ ref: null,
233
+ systemNote: null,
234
+ images: null,
235
+ message: e.message,
236
+ inputChars: null,
237
+ children: [],
238
+ },
239
+ e.depth > 0 ? e.runId : null
240
+ );
241
+ }
242
+ }
243
+
244
+ return rootOrder;
245
+ }
246
+
247
+ /**
248
+ * 把已落库消息的 tool-call/tool-result parts 还原成扁平的 AgentTraceData,
249
+ * 供 buildTraceTree 复用同一套折叠渲染——不然刷新页面/切回旧会话就再也看不到
250
+ * 历史消息调用过的工具,只有"本次会话内正在流式产生"的消息才有轨迹,这与本
251
+ * 任务的验收标准("能看到它调了哪些工具")不符。
252
+ *
253
+ * 落库 parts 是摊平的(子 agent 边界在持久化时已丢失,见
254
+ * apps/api/.../steps-to-parts.ts 的注释——`content` 判别联合没有 runId/depth
255
+ * 字段),故这里恒定 `runId:'persisted'`/`depth:0`;子 agent 嵌套只对本次会话
256
+ * 内的实时 SSE 数据有效(Plan 3 范围,本函数不处理)。
257
+ */
258
+ export function tracesFromParts(
259
+ parts: readonly MessagePart[],
260
+ sessionId: string
261
+ ): AgentTraceData[] {
262
+ const out: AgentTraceData[] = [];
263
+ let seq = 0;
264
+ for (const p of parts) {
265
+ if (p.type === 'tool-call') {
266
+ seq += 1;
267
+ out.push({
268
+ seq,
269
+ sessionId,
270
+ runId: 'persisted',
271
+ messageId: 'persisted',
272
+ parentRunId: null,
273
+ depth: 0,
274
+ kind: 'tool-call',
275
+ toolCallId: p.toolCallId,
276
+ toolName: p.toolName,
277
+ input: p.input,
278
+ output: null,
279
+ isError: null,
280
+ inputChars: null,
281
+ ref: null,
282
+ systemNote: null,
283
+ images: null,
284
+ messages: null,
285
+ text: null,
286
+ message: null,
287
+ agentName: null,
288
+ prompt: null,
289
+ title: null,
290
+ status: null,
291
+ });
292
+ } else if (p.type === 'tool-result') {
293
+ seq += 1;
294
+ out.push({
295
+ seq,
296
+ sessionId,
297
+ runId: 'persisted',
298
+ messageId: 'persisted',
299
+ parentRunId: null,
300
+ depth: 0,
301
+ kind: 'tool-result',
302
+ toolCallId: p.toolCallId,
303
+ toolName: p.toolName,
304
+ input: null,
305
+ output: p.output,
306
+ isError: p.isError ?? null,
307
+ inputChars: null,
308
+ ref: p.ref ?? null,
309
+ systemNote: p.systemNote ?? null,
310
+ images: p.images ?? null,
311
+ messages: null,
312
+ text: null,
313
+ message: null,
314
+ agentName: null,
315
+ prompt: null,
316
+ title: null,
317
+ status: null,
318
+ });
319
+ }
320
+ }
321
+ return out;
322
+ }