* Format user messages for new_context display, separating system reminders. * Only handles user messages (assistant messages are filtered out before this is called).
(messages: UserMessage[])
| 164 | * Only handles user messages (assistant messages are filtered out before this is called). |
| 165 | */ |
| 166 | function formatMessagesForContext(messages: UserMessage[]): FormattedMessages { |
| 167 | const contextParts: string[] = [] |
| 168 | const systemReminders: string[] = [] |
| 169 | |
| 170 | for (const message of messages) { |
| 171 | const content = message.message.content |
| 172 | if (typeof content === 'string') { |
| 173 | const reminderContent = extractSystemReminderContent(content) |
| 174 | if (reminderContent) { |
| 175 | systemReminders.push(reminderContent) |
| 176 | } else { |
| 177 | contextParts.push(`[USER]\n${content}`) |
| 178 | } |
| 179 | } else if (Array.isArray(content)) { |
| 180 | for (const block of content) { |
| 181 | if (block.type === 'text') { |
| 182 | const reminderContent = extractSystemReminderContent(block.text) |
| 183 | if (reminderContent) { |
| 184 | systemReminders.push(reminderContent) |
| 185 | } else { |
| 186 | contextParts.push(`[USER]\n${block.text}`) |
| 187 | } |
| 188 | } else if (block.type === 'tool_result') { |
| 189 | const resultContent = |
| 190 | typeof block.content === 'string' |
| 191 | ? block.content |
| 192 | : jsonStringify(block.content) |
| 193 | // Tool results can also contain system reminders (e.g., malware warning) |
| 194 | const reminderContent = extractSystemReminderContent(resultContent) |
| 195 | if (reminderContent) { |
| 196 | systemReminders.push(reminderContent) |
| 197 | } else { |
| 198 | contextParts.push( |
| 199 | `[TOOL RESULT: ${block.tool_use_id}]\n${resultContent}`, |
| 200 | ) |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | return { contextParts, systemReminders } |
| 208 | } |
| 209 | |
| 210 | export interface LLMRequestNewContext { |
| 211 | /** System prompt (typically only on first request or if changed) */ |
no test coverage detected