-
-
Notifications
You must be signed in to change notification settings - Fork 285
Expand file tree
/
Copy pathSemanticStepExtractor.ts
More file actions
246 lines (227 loc) · 8.83 KB
/
Copy pathSemanticStepExtractor.ts
File metadata and controls
246 lines (227 loc) · 8.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
/**
* SemanticStepExtractor - Extracts semantic steps from AI chunks.
*
* Semantic steps represent logical units of work within AI responses:
* - thinking: Claude's reasoning process
* - tool_call: Tool invocation
* - tool_result: Tool execution result
* - output: Text output from Claude
* - subagent: Nested agent execution
* - interruption: User interruption
*/
import { countContentTokens } from '@main/utils/tokenizer';
import type { AIChunk, EnhancedAIChunk, SemanticStep } from '@main/types';
/**
* Extract semantic steps from AI chunk responses.
* Semantic steps represent logical units of work within responses.
*
* Note: ALL tool calls are included, including Task tools with subagents.
* Task tools are filtered in the renderer's buildDisplayItems,
* but they are kept here for accurate context token tracking in aggregateToolOutputs.
*/
export function extractSemanticStepsFromAIChunk(chunk: AIChunk | EnhancedAIChunk): SemanticStep[] {
const steps: SemanticStep[] = [];
let stepIdCounter = 0;
// Note: Task tool calls are included in semantic steps for context token tracking.
// The renderer's buildDisplayItems filters Task tools with subagents.
// Process only AI responses (no user message in AIChunk)
for (const msg of chunk.responses) {
if (msg.type === 'assistant') {
// Extract from content blocks
const content = Array.isArray(msg.content) ? msg.content : [];
for (const block of content) {
if (block.type === 'thinking' && block.thinking) {
// Calculate tokens for thinking content (output from Claude)
const thinkingTokens = countContentTokens(block.thinking);
steps.push({
id: `${msg.uuid}-thinking-${stepIdCounter++}`,
type: 'thinking',
startTime: new Date(msg.timestamp),
durationMs: 0, // Estimated from token count
content: {
thinkingText: block.thinking,
tokenCount: thinkingTokens, // Pre-computed token count
},
tokens: {
input: 0,
output: thinkingTokens, // Thinking is output from Claude
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
sourceMessageId: msg.uuid,
});
}
if (block.type === 'tool_use' && block.id && block.name) {
// Include ALL tool calls in semantic steps, including Task tools with processes.
// Task tools with processes are filtered from DISPLAY in the renderer's buildDisplayItems,
// but they should be included here for accurate context token tracking.
// The renderer's aggregateToolOutputs will correctly count Task tool tokens
// as part of the main session's context consumption.
// Calculate tool call tokens directly from name + input
// This reflects what actually enters the context window
const callTokens = countContentTokens(block.name + JSON.stringify(block.input));
steps.push({
id: block.id,
type: 'tool_call',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
toolName: block.name,
toolInput: block.input,
sourceModel: msg.model,
},
tokens: {
input: callTokens,
output: 0,
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
sourceMessageId: msg.uuid,
});
}
if (block.type === 'server_tool_use' && block.name === 'advisor' && block.id) {
// advisor CALL — input is empty so callTokens stay undefined (fallback estimates ~0)
steps.push({
id: block.id,
type: 'tool_call',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
toolName: 'advisor',
toolInput: {},
sourceModel: msg.advisorModel,
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
sourceMessageId: msg.uuid,
});
}
if (block.type === 'advisor_tool_result' && block.tool_use_id) {
// advisor RESULT — advice text is real consumed context, counted like any tool result
const advisorText = block.content?.text ?? '';
steps.push({
id: block.tool_use_id,
type: 'tool_result',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
toolResultContent: advisorText,
isError: false,
tokenCount: advisorText ? countContentTokens(advisorText) : 0,
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
});
}
if (block.type === 'text' && block.text) {
// Calculate tokens for text output (Claude's generated text)
const textTokens = countContentTokens(block.text);
steps.push({
id: `${msg.uuid}-output-${stepIdCounter++}`,
type: 'output',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
outputText: block.text,
tokenCount: textTokens, // Pre-computed token count for consistency
},
tokens: {
input: 0, // Text output is generated by Claude, not input
output: textTokens,
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
sourceMessageId: msg.uuid,
});
}
}
}
// Tool results from internal user messages
// Note: isMeta can be true or null in JSONL, so check for toolResults presence directly
if (msg.type === 'user' && msg.toolResults && msg.toolResults.length > 0) {
for (const result of msg.toolResults) {
steps.push({
id: result.toolUseId,
type: 'tool_result',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
toolResultContent:
typeof result.content === 'string' ? result.content : JSON.stringify(result.content),
isError: result.isError,
toolUseResult: msg.toolUseResult, // Enriched data from message
tokenCount: countContentTokens(result.content), // Pre-computed token count
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
});
}
}
// User interruption messages
// These are user messages with array content containing text like "[Request interrupted by user]"
if (msg.type === 'user' && Array.isArray(msg.content)) {
let foundInterruption = false;
for (const block of msg.content) {
if (block.type === 'text' && block.text) {
const textContent = block.text;
// Check for interruption patterns
if (
textContent.includes('[Request interrupted by user]') ||
textContent.includes('[Request interrupted by user for tool use]')
) {
steps.push({
id: `${msg.uuid}-interruption-${stepIdCounter++}`,
type: 'interruption',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
interruptionText: textContent,
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
});
foundInterruption = true;
}
}
}
// User-rejected tool use (toolUseResult field is "User rejected tool use")
if (!foundInterruption && (msg.toolUseResult as unknown) === 'User rejected tool use') {
steps.push({
id: `${msg.uuid}-interruption-${stepIdCounter++}`,
type: 'interruption',
startTime: new Date(msg.timestamp),
durationMs: 0,
content: {
interruptionText: 'Request interrupted by user',
},
context: msg.agentId ? 'subagent' : 'main',
agentId: msg.agentId,
});
}
}
}
// Link processes as steps
for (const process of chunk.processes) {
steps.push({
id: process.id,
type: 'subagent',
startTime: process.startTime,
endTime: process.endTime,
durationMs: process.durationMs,
content: {
subagentId: process.id,
subagentDescription: process.description,
},
tokens: {
input: process.metrics.inputTokens,
output: process.metrics.outputTokens,
cached: process.metrics.cacheReadTokens,
},
isParallel: process.isParallel,
context: 'subagent',
agentId: process.id,
});
}
// Sort by startTime
return steps.sort((a, b) => a.startTime.getTime() - b.startTime.getTime());
}