-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtranscript-to-messages.ts
More file actions
367 lines (326 loc) · 12.1 KB
/
Copy pathtranscript-to-messages.ts
File metadata and controls
367 lines (326 loc) · 12.1 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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
/**
* Parses a Claude Code JSONL transcript into the FullMessage[] format used
* by the indexer.
*
* Transcript format observations:
* - Each line is a JSON object with a `type` field
* - `type: "file-history-snapshot"` — internal snapshot, skip
* - `type: "user"` with `isMeta: true` — local command caveat, skip
* - `type: "user"` with array `content` of `tool_result` — tool output, keep
* - `type: "user"` with string `content` — regular user message, keep
* (but skip /command messages and login stdout noise)
* - `type: "assistant"` — may appear multiple times with the same `message.id`
* (streaming chunks); we keep the LAST entry per message.id
* - `isApiErrorMessage: true` — skip
* - Assistant `content` blocks of type "thinking" — skip (internal reasoning)
* - Assistant `content` blocks of type "tool_use" — keep (tool call)
* - User `content` array with `tool_result` — keep (tool output)
*/
import fs from "fs";
import type { FullMessage, MessagePart } from "./types";
// ---------------------------------------------------------------------------
// IDE context tag stripping
// ---------------------------------------------------------------------------
/** Regex to match and remove IDE-injected XML tags and their content */
const IDE_TAG_RE = /<(ide_opened_file|ide_selection|system-reminder)>[\s\S]*?<\/\1>/g;
/**
* Strips IDE context tags (ide_opened_file, ide_selection, system-reminder)
* from user message text. Returns the cleaned text trimmed.
*/
function stripIdeContextTags(text: string): string {
return text.replace(IDE_TAG_RE, "").trim();
}
// ---------------------------------------------------------------------------
// Raw transcript line shapes
// ---------------------------------------------------------------------------
interface TranscriptUserLine {
type: "user";
uuid: string;
timestamp: string;
sessionId: string;
isMeta?: boolean;
isApiErrorMessage?: boolean;
message: {
role: "user";
content: string | (TranscriptToolResult | TranscriptToolResultContentBlock)[];
};
toolUseResult?: {
stdout?: string;
stderr?: string;
};
sourceToolAssistantUUID?: string;
}
interface TranscriptToolResultContentBlock {
type: "text";
text: string;
}
interface TranscriptToolResult {
type: "tool_result";
tool_use_id: string;
// Claude Code sends either a plain string or an array of content blocks
content: string | TranscriptToolResultContentBlock[];
is_error: boolean;
}
interface TranscriptAssistantLine {
type: "assistant";
uuid: string;
timestamp: string;
sessionId: string;
isApiErrorMessage?: boolean;
message: {
id: string;
role: "assistant";
model?: string;
content: TranscriptContentBlock[];
stop_reason?: string | null;
};
requestId?: string;
}
interface TranscriptContentBlock {
type: "text" | "thinking" | "tool_use";
// text
text?: string;
// thinking
thinking?: string;
signature?: string;
// tool_use
id?: string;
name?: string;
input?: unknown;
}
type TranscriptLine =
| TranscriptUserLine
| TranscriptAssistantLine
| { type: string; [key: string]: unknown };
// ---------------------------------------------------------------------------
// Converters
// ---------------------------------------------------------------------------
function convertUserMessage(line: TranscriptUserLine): FullMessage | null {
const content = line.message.content;
// Skip meta messages (local command caveats, /login stdout, etc.)
if (line.isMeta) return null;
// Skip API error messages
if (line.isApiErrorMessage) return null;
const parts: MessagePart[] = [];
if (typeof content === "string") {
const text = stripIdeContextTags(content);
// Skip empty, slash-commands, and local-command XML noise
if (!text) return null;
if (text.startsWith("<local-command") || text.startsWith("<command-name>")) return null;
parts.push({ type: "text", text });
} else if (Array.isArray(content)) {
// Content array may contain text blocks AND/OR tool_result blocks.
// Claude Code (especially via VS Code extension) sends user messages
// with content as [{type: "text", text: "..."}] instead of a plain string.
for (const block of content) {
if (block.type === "text" && "text" in block) {
const text = stripIdeContextTags(block.text ?? "");
if (text && !text.startsWith("<local-command") && !text.startsWith("<command-name>")) {
parts.push({ type: "text", text });
}
} else if (block.type === "tool_result" && "tool_use_id" in block) {
const trBlock = block as TranscriptToolResult;
// content may be a plain string or an array of { type: "text", text } blocks
let resultText: string;
if (typeof trBlock.content === "string") {
resultText = trBlock.content;
} else if (Array.isArray(trBlock.content)) {
resultText = trBlock.content
.filter((b) => b.type === "text")
.map((b) => b.text)
.join("\n");
} else {
resultText = "";
}
parts.push({
type: "tool-invocation",
toolName: "tool_result",
toolCallId: trBlock.tool_use_id,
state: "result",
result: resultText || (trBlock.is_error ? "(error)" : "(no output)"),
});
}
}
}
if (parts.length === 0) return null;
// Messages that contain only tool_result blocks are labeled as "tool" role
// so the renderer can emit "## Tool Result" instead of "## User".
const isToolResultOnly =
Array.isArray(line.message.content) &&
parts.every((p) => p.type === "tool-invocation" && p.toolName === "tool_result");
return {
info: {
id: line.uuid,
role: isToolResultOnly ? "tool" : "user",
time: { created: new Date(line.timestamp).getTime() },
},
parts,
};
}
function convertAssistantMessage(line: TranscriptAssistantLine): FullMessage | null {
if (line.isApiErrorMessage) return null;
const parts: MessagePart[] = [];
for (const block of line.message.content) {
switch (block.type) {
case "text":
if (block.text?.trim()) {
parts.push({ type: "text", text: block.text.trim() });
}
break;
case "tool_use": {
const result = (block as unknown as Record<string, unknown>)._result as string | undefined;
parts.push({
type: "tool-invocation",
toolName: block.name ?? "unknown",
toolCallId: block.id,
state: result !== undefined ? "result" : "call",
args: block.input,
...(result !== undefined ? { result } : {}),
});
break;
}
case "thinking":
// Skip internal reasoning — not useful to index
break;
}
}
if (parts.length === 0) return null;
return {
info: {
id: line.uuid,
role: "assistant",
modelID: line.message.model,
time: { created: new Date(line.timestamp).getTime() },
},
parts,
};
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Parses a Claude Code JSONL transcript file into FullMessage[].
*
* Deduplicates streaming assistant chunks (same message.id → keep last),
* and pairs tool_use calls with their tool_result responses.
*/
export function parseTranscript(transcriptPath: string): FullMessage[] {
const raw = fs.readFileSync(transcriptPath, "utf8");
const lines = raw.split("\n").filter((l) => l.trim());
// First pass: collect all lines, deduplicate assistant messages by message.id.
// Claude Code emits multiple entries per assistant message (streaming chunks,
// thinking-only vs final). We want:
// - orderedEntries: one slot per logical message (keyed by first-seen uuid
// for users, first-seen message.id for assistants)
// - assistantByMsgId: always updated to the LAST entry (most complete content)
const assistantByMsgId = new Map<string, TranscriptAssistantLine>();
// For assistants, track which message.id has already been slotted in orderedEntries
const seenAssistantMsgIds = new Set<string>();
const orderedEntries: Array<{ uuid: string; line: TranscriptLine }> = [];
const seenUuids = new Set<string>();
for (const raw of lines) {
let line: TranscriptLine;
try {
line = JSON.parse(raw);
} catch {
continue;
}
if (line.type === "file-history-snapshot") continue;
if (line.type === "assistant") {
const al = line as TranscriptAssistantLine;
const msgId = al.message?.id;
if (msgId) {
// Always overwrite — last chunk wins (most complete content)
assistantByMsgId.set(msgId, al);
// Only add ONE slot per message.id (use the first-seen uuid as the
// stable cursor id for incremental indexing)
if (!seenAssistantMsgIds.has(msgId)) {
seenAssistantMsgIds.add(msgId);
seenUuids.add(al.uuid);
orderedEntries.push({ uuid: al.uuid, line });
}
}
continue;
}
if (line.type === "user" || line.type === "system") {
const ul = line as TranscriptUserLine;
if (!seenUuids.has(ul.uuid)) {
seenUuids.add(ul.uuid);
orderedEntries.push({ uuid: ul.uuid, line });
}
}
}
// Second pass: resolve assistant lines to their final (deduplicated) version
// and pair tool_use with tool_result
const messages: FullMessage[] = [];
// Build a map: tool_use_id → tool result text (from user tool_result messages)
const toolResults = new Map<string, string>();
for (const { line } of orderedEntries) {
if (line.type !== "user") continue;
const ul = line as TranscriptUserLine;
if (Array.isArray(ul.message.content)) {
for (const block of ul.message.content) {
if (block.type === "tool_result" && "tool_use_id" in block) {
let text: string;
if (typeof block.content === "string") {
text = block.content ?? "";
} else if (Array.isArray(block.content)) {
text = block.content.filter((b) => b.type === "text").map((b) => b.text).join("\n");
} else {
text = "";
}
toolResults.set(block.tool_use_id, text);
}
}
}
}
for (const { uuid: slotUuid, line } of orderedEntries) {
if (line.type === "assistant") {
const al = line as TranscriptAssistantLine;
const msgId = al.message?.id;
// Use the final (deduplicated) version for content, but preserve the
// first-seen uuid as the stable info.id for incremental indexing cursors.
const finalLine = msgId ? (assistantByMsgId.get(msgId) ?? al) : al;
// Enrich tool_use blocks with their results
const enriched: TranscriptAssistantLine = {
...finalLine,
// Override uuid with the stable slot uuid so info.id stays consistent
uuid: slotUuid,
message: {
...finalLine.message,
content: finalLine.message.content.map((block) => {
if (block.type === "tool_use" && block.id && toolResults.has(block.id)) {
return { ...block, _result: toolResults.get(block.id) };
}
return block;
}),
},
};
const msg = convertAssistantMessage(enriched);
if (msg) messages.push(msg);
} else if (line.type === "user") {
const ul = line as TranscriptUserLine;
const msg = convertUserMessage(ul);
// Skip tool_result-only messages — their content is now merged
// into the preceding assistant message's tool_use blocks
if (msg && msg.info.role !== "tool") messages.push(msg);
}
}
return messages;
}
/**
* Derives a session title from the transcript messages.
* Uses the first meaningful user message text, truncated to 60 chars.
*/
export function deriveSessionTitle(messages: FullMessage[]): string {
for (const msg of messages) {
if (msg.info.role !== "user") continue;
for (const part of msg.parts) {
if (part.type === "text" && part.text) {
const title = part.text.replace(/\s+/g, " ").trim().slice(0, 60);
if (title) return title;
}
}
}
return "Claude Code Session";
}