/ utils / contentArray.ts
contentArray.ts
 1  /**
 2   * Utility for inserting a block into a content array relative to tool_result
 3   * blocks. Used by the API layer to position supplementary content (e.g.,
 4   * cache editing directives) correctly within user messages.
 5   *
 6   * Placement rules:
 7   * - If tool_result blocks exist: insert after the last one
 8   * - Otherwise: insert before the last block
 9   * - If the inserted block would be the final element, a text continuation
10   *   block is appended (some APIs require the prompt not to end with
11   *   non-text content)
12   */
13  
14  /**
15   * Inserts a block into the content array after the last tool_result block.
16   * Mutates the array in place.
17   *
18   * @param content - The content array to modify
19   * @param block - The block to insert
20   */
21  export function insertBlockAfterToolResults(
22    content: unknown[],
23    block: unknown,
24  ): void {
25    // Find position after the last tool_result block
26    let lastToolResultIndex = -1
27    for (let i = 0; i < content.length; i++) {
28      const item = content[i]
29      if (
30        item &&
31        typeof item === 'object' &&
32        'type' in item &&
33        (item as { type: string }).type === 'tool_result'
34      ) {
35        lastToolResultIndex = i
36      }
37    }
38  
39    if (lastToolResultIndex >= 0) {
40      const insertPos = lastToolResultIndex + 1
41      content.splice(insertPos, 0, block)
42      // Append a text continuation if the inserted block is now last
43      if (insertPos === content.length - 1) {
44        content.push({ type: 'text', text: '.' })
45      }
46    } else {
47      // No tool_result blocks — insert before the last block
48      const insertIndex = Math.max(0, content.length - 1)
49      content.splice(insertIndex, 0, block)
50    }
51  }