Open History to see the last commit
1import type {
2 MessagePart,
3 ToolApprovalInterrupt,
4 ToolCallPart,
5 ToolResultPart,
6 UIMessage,
7} from '../types'
8import type {
9 ChatUIInterrupt,
10 ChatUIPartKey,
11 ChatUISelectInput,
12 ChatUISelectedMessage,
13 ChatUISelectedPart,
14 ChatUISelection,
15} from './types'
16
17const PART_KEY_BY_TYPE: Record<string, ChatUIPartKey> = {
18 text: 'text',
19 image: 'image',
20 audio: 'audio',
21 video: 'video',
22 document: 'document',
23 thinking: 'thinking',
24 'tool-call': 'toolCall',
25 'tool-result': 'toolResult',
26 'structured-output': 'structuredOutput',
27 'ui-resource': 'uiResource',
28 subagent: 'subagent',
29}
30
31export function partTypeToKey(type: string): ChatUIPartKey | string {
32 const mapped = PART_KEY_BY_TYPE[type]
33 if (mapped) return mapped
34 return type.replace(/-([a-z])/g, (_, letter: string) => letter.toUpperCase())
35}
36
37export function collectInlineToolNames(
38 toolInterrupts?: Record<string, unknown>,
39 mappedToolNames?: ReadonlyArray<string>,
40): Array<string> {
41 const listPlaced = new Set(Object.keys(toolInterrupts ?? {}))
42 return (mappedToolNames ?? []).filter((name) => !listPlaced.has(name))
43}
44
45export function resolveInterruptComponent(
46 interrupt: ChatUIInterrupt,
47 interruptsMap:
48 | {
49 tools?: Record<string, unknown>
50 generic?: Record<string, unknown>
51 }
52 | undefined,
53): unknown {
54 if (!interruptsMap) return undefined
55 if (interrupt.kind === 'tool-approval') {
56 return interruptsMap.tools?.[interrupt.toolName]
57 }
58 const generic = interruptsMap.generic
59 if (!generic) return undefined
60 const definitionId =
61 'definitionId' in interrupt && typeof interrupt.definitionId === 'string'
62 ? interrupt.definitionId
63 : undefined
64 if (definitionId && definitionId !== 'fallback') {
65 const registered = generic[definitionId]
66 if (registered) return registered
67 }
68 return generic.fallback
69}
70
71function isToolCallPart(part: MessagePart): part is ToolCallPart {
72 return part.type === 'tool-call'
73}
74
75function isToolResultPart(part: MessagePart): part is ToolResultPart {
76 return part.type === 'tool-result'
77}
78
79function isToolApproval(
80 interrupt: ChatUIInterrupt,
81): interrupt is ToolApprovalInterrupt {
82 return interrupt.kind === 'tool-approval'
83}
84
85export function selectChatUI(input: ChatUISelectInput): ChatUISelection {
86 const messages = input.messages
87 const interrupts = input.interrupts ?? []
88 const inlineToolNames = new Set(input.inlineToolNames ?? [])
89
90 const resultsByCallId = new Map<string, ToolResultPart>()
91 const callIds = new Set<string>()
92 for (const message of messages) {
93 for (const part of message.parts) {
94 if (isToolCallPart(part)) callIds.add(part.id)
95 if (isToolResultPart(part)) resultsByCallId.set(part.toolCallId, part)
96 }
97 }
98
99 const approvalByCallId = new Map<string, ToolApprovalInterrupt>()
100 for (const interrupt of interrupts) {
101 if (isToolApproval(interrupt)) {
102 approvalByCallId.set(interrupt.toolCallId, interrupt)
103 }
104 }
105
106 const selectedMessages: Array<ChatUISelectedMessage> = messages.map(
107 (message) => ({
108 message,
109 parts: message.parts.map((part) =>
110 toSelectedPart(part, resultsByCallId, approvalByCallId, callIds),
111 ),
112 }),
113 )
114
115 return {
116 messages: selectedMessages,
117 interrupts: interrupts.filter((interrupt) => {
118 if (!isToolApproval(interrupt)) return true
119 if (!inlineToolNames.has(interrupt.toolName)) return true
120 return !callIds.has(interrupt.toolCallId)
121 }),
122 }
123}
124
125function toSelectedPart(
126 part: MessagePart,
127 resultsByCallId: Map<string, ToolResultPart>,
128 approvalByCallId: Map<string, ToolApprovalInterrupt>,
129 callIds: Set<string>,
130): ChatUISelectedPart {
131 if (isToolCallPart(part)) {
132 const result = resultsByCallId.get(part.id)
133 const interrupt = approvalByCallId.get(part.id)
134 return {
135 key: 'toolCall',
136 part,
137 ...(result ? { result } : {}),
138 ...(interrupt ? { interrupt } : {}),
139 input: part.input,
140 output: part.output,
141 }
142 }
143
144 if (isToolResultPart(part)) {
145 return {
146 key: 'toolResult',
147 part,
148 matched: callIds.has(part.toolCallId),
149 }
150 }
151
152 return {
153 key: partTypeToKey(part.type) as Exclude<
154 ChatUIPartKey,
155 'toolCall' | 'toolResult'
156 >,
157 part,
158 }
159}
160
161export function automaticPartsForMessage(
162 selected: ChatUISelectedMessage,
163): Array<ChatUISelectedPart> {
164 return selected.parts.filter(
165 (part) => !(part.key === 'toolResult' && part.matched),
166 )
167}
168
169export function selectMessageUI(
170 message: UIMessage,
171 input: Omit<ChatUISelectInput, 'messages'>,
172): ChatUISelectedMessage {
173 return (
174 selectChatUI({ ...input, messages: [message] }).messages[0] ?? {
175 message,
176 parts: [],
177 }
178 )
179}