Repository navigation
Expand file tree
/
Copy pathanswer.ts
More file actions
50 lines (45 loc) · 1.94 KB
/
Copy pathanswer.ts
File metadata and controls
50 lines (45 loc) · 1.94 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
import type { Message, Part, TextPart } from "@opencode-ai/sdk/v2"
/**
* The text a reader would call the answer: the last assistant message with text,
* and only the text after its last tool call, so "let me check the router" style
* progress lines from earlier steps are not read.
*/
export function finalAnswer(messages: readonly Message[], parts: (messageID: string) => readonly Part[]) {
return messages
.toReversed()
.filter((message) => message.role === "assistant")
.map((message) => ({ messageID: message.id, partIDs: answerParts(parts(message.id)) }))
.find((answer) => answer.partIDs.length > 0)
}
/**
* Whether play should resume the paused reading instead of reading the latest answer.
* A reading of an older message (picked by clicking it) resumes until a newer answer
* arrives; `latest` is the latest answer when the reading was opened.
*/
export function resumes(
reading: { sessionID: string; messageID: string; latest?: string },
answer: { sessionID: string; messageID: string } | undefined,
) {
if (!answer) return true
if (reading.sessionID !== answer.sessionID) return false
return reading.messageID === answer.messageID || reading.latest === answer.messageID
}
/**
* Whether a clicked part belongs to the open reading. V2 part ids are indices within
* their message, so the part id alone matches the same index in other messages.
*/
export function inReading(
segments: readonly { messageID: string; partID: string }[],
spot: { messageID: string; partID: string },
) {
return segments.some((segment) => segment.messageID === spot.messageID && segment.partID === spot.partID)
}
export function answerParts(parts: readonly Part[]) {
return parts
.slice(parts.findLastIndex((part) => part.type === "tool") + 1)
.filter(isAnswerText)
.map((part) => part.id)
}
export function isAnswerText(part: Part): part is TextPart {
return part.type === "text" && !part.synthetic && part.text.trim().length > 0
}