( a: ContentBlockParam[], b: ContentBlockParam[], )
| 2607 | } |
| 2608 | |
| 2609 | export function mergeUserContentBlocks( |
| 2610 | a: ContentBlockParam[], |
| 2611 | b: ContentBlockParam[], |
| 2612 | ): ContentBlockParam[] { |
| 2613 | // See https://anthropic.slack.com/archives/C06FE2FP0Q2/p1747586370117479 and |
| 2614 | // https://anthropic.slack.com/archives/C0AHK9P0129/p1773159663856279: |
| 2615 | // any sibling after tool_result renders as </function_results>\n\nHuman:<...> |
| 2616 | // on the wire. Repeated mid-conversation, this teaches capy to emit Human: at |
| 2617 | // a bare tail → 3-token empty end_turn. A/B (sai-20260310-161901) validated: |
| 2618 | // smoosh into tool_result.content → 92% → 0%. |
| 2619 | const lastBlock = last(a) |
| 2620 | if (lastBlock?.type !== 'tool_result') { |
| 2621 | return [...a, ...b] |
| 2622 | } |
| 2623 | |
| 2624 | if (!checkStatsigFeatureGate_CACHED_MAY_BE_STALE('ncode_chair_sermon')) { |
| 2625 | // Legacy (ungated) smoosh: only string-content tool_result + all-text |
| 2626 | // siblings → joined string. Matches pre-universal-smoosh behavior on main. |
| 2627 | // The precondition guarantees smooshIntoToolResult hits its string path |
| 2628 | // (no tool_reference bail, string output shape preserved). |
| 2629 | if ( |
| 2630 | typeof lastBlock.content === 'string' && |
| 2631 | b.every(x => x.type === 'text') |
| 2632 | ) { |
| 2633 | const copy = a.slice() |
| 2634 | copy[copy.length - 1] = smooshIntoToolResult(lastBlock, b)! |
| 2635 | return copy |
| 2636 | } |
| 2637 | return [...a, ...b] |
| 2638 | } |
| 2639 | |
| 2640 | // Universal smoosh (gated): fold all non-tool_result block types (text, |
| 2641 | // image, document, search_result) into tool_result.content. tool_result |
| 2642 | // blocks stay as siblings (hoisted later by hoistToolResults). |
| 2643 | const toSmoosh = b.filter(x => x.type !== 'tool_result') |
| 2644 | const toolResults = b.filter(x => x.type === 'tool_result') |
| 2645 | if (toSmoosh.length === 0) { |
| 2646 | return [...a, ...b] |
| 2647 | } |
| 2648 | |
| 2649 | const smooshed = smooshIntoToolResult(lastBlock, toSmoosh) |
| 2650 | if (smooshed === null) { |
| 2651 | // tool_reference constraint — fall back to siblings |
| 2652 | return [...a, ...b] |
| 2653 | } |
| 2654 | |
| 2655 | return [...a.slice(0, -1), smooshed, ...toolResults] |
| 2656 | } |
| 2657 | |
| 2658 | // Sometimes the API returns empty messages (eg. "\n\n"). We need to filter these out, |
| 2659 | // otherwise they will give an API error when we send them to the API next time we call query(). |
no test coverage detected