* Final pass: smoosh any ` `-prefixed text siblings into the * last tool_result of the same user message. Catches siblings from: * - PreToolUse hook additionalContext (Gap F: attachment between assistant and * tool_result → standalone push → mergeUserMessages → hoist → sibling)
( messages: (UserMessage | AssistantMessage)[], )
| 1833 | * Idempotent. Pure function of shape. |
| 1834 | */ |
| 1835 | function smooshSystemReminderSiblings( |
| 1836 | messages: (UserMessage | AssistantMessage)[], |
| 1837 | ): (UserMessage | AssistantMessage)[] { |
| 1838 | return messages.map(msg => { |
| 1839 | if (msg.type !== 'user') return msg |
| 1840 | const content = msg.message.content |
| 1841 | if (!Array.isArray(content)) return msg |
| 1842 | |
| 1843 | const hasToolResult = content.some(b => b.type === 'tool_result') |
| 1844 | if (!hasToolResult) return msg |
| 1845 | |
| 1846 | const srText: TextBlockParam[] = [] |
| 1847 | const kept: ContentBlockParam[] = [] |
| 1848 | for (const b of content) { |
| 1849 | if (b.type === 'text' && b.text.startsWith('<system-reminder>')) { |
| 1850 | srText.push(b) |
| 1851 | } else { |
| 1852 | kept.push(b) |
| 1853 | } |
| 1854 | } |
| 1855 | if (srText.length === 0) return msg |
| 1856 | |
| 1857 | // Smoosh into the LAST tool_result (positionally adjacent in rendered prompt) |
| 1858 | const lastTrIdx = kept.findLastIndex(b => b.type === 'tool_result') |
| 1859 | const lastTr = kept[lastTrIdx] as ToolResultBlockParam |
| 1860 | const smooshed = smooshIntoToolResult(lastTr, srText) |
| 1861 | if (smooshed === null) return msg // tool_ref constraint — leave alone |
| 1862 | |
| 1863 | const newContent = [ |
| 1864 | ...kept.slice(0, lastTrIdx), |
| 1865 | smooshed, |
| 1866 | ...kept.slice(lastTrIdx + 1), |
| 1867 | ] |
| 1868 | return { |
| 1869 | ...msg, |
| 1870 | message: { ...msg.message, content: newContent }, |
| 1871 | } |
| 1872 | }) |
| 1873 | } |
| 1874 | |
| 1875 | /** |
| 1876 | * Strip non-text blocks from is_error tool_results — the API rejects the |
no test coverage detected