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