Repository navigation
Expand file tree
/
Copy pathtranscript.ts
More file actions
85 lines (70 loc) · 2.59 KB
/
Copy pathtranscript.ts
File metadata and controls
85 lines (70 loc) · 2.59 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
import type { AppEvent } from '../events'
const DEFAULT_TRANSCRIPT_CHAR_BUDGET = 35_000
function getEventTimestamp(event: AppEvent): string {
const anyEvent = event as { timestamp?: string }
return anyEvent.timestamp ?? 'unknown-time'
}
function toLine(index: number, event: AppEvent): string | null {
const ts = getEventTimestamp(event)
switch (event.type) {
case 'user_message': {
const contentText = event.text.trim()
if (!contentText) return null
return `[${index}] ${ts} user_message\n${contentText}`
}
case 'turn_outcome':
if (event.outcome._tag !== 'UnexpectedError') return null
return `[${index}] ${ts} turn_outcome.unexpected_error\n${event.outcome.detail.message}`
case 'agent_created':
return `[${index}] ${ts} agent_created role=${event.role} taskId=${event.taskId}`
default:
return null
}
}
function assistantTurnLine(index: number, timestamp: string, text: string): string | null {
if (!text) return null
return `[${index}] ${timestamp} assistant_turn_outcome\n${text}`
}
function truncateTranscript(lines: string[], maxChars: number): string {
if (lines.length === 0) return ''
const sep = '\n\n'
let total = lines.reduce((sum, l) => sum + l.length, 0) + sep.length * (lines.length - 1)
let start = 0
while (start < lines.length && total > maxChars) {
total -= lines[start]!.length + (start < lines.length - 1 ? sep.length : 0)
start++
}
return lines.slice(start).join(sep)
}
export function buildExtractionTranscript(
events: AppEvent[],
opts?: { maxChars?: number }
): string {
const lines: string[] = []
const pendingUserMessages = new Map<string, { startIndex: number; parts: string[] }>()
for (let i = 0; i < events.length; i++) {
const event = events[i]!
if (event.type === 'message_start' && event.destination.kind === 'user') {
pendingUserMessages.set(event.id, { startIndex: i, parts: [] })
continue
}
if (event.type === 'message_chunk') {
const pending = pendingUserMessages.get(event.id)
if (pending) pending.parts.push(event.text)
continue
}
if (event.type === 'message_end') {
const pending = pendingUserMessages.get(event.id)
if (pending) {
pendingUserMessages.delete(event.id)
const text = pending.parts.join('').trim()
const line = assistantTurnLine(i, getEventTimestamp(event), text)
if (line) lines.push(line)
}
continue
}
const line = toLine(i, event)
if (line) lines.push(line)
}
return truncateTranscript(lines, opts?.maxChars ?? DEFAULT_TRANSCRIPT_CHAR_BUDGET)
}