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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
/**
 * Streaming SSE transformation: OpenAI Chat Completions β†’ Anthropic Messages
 *
 * Converts an OpenAI-compatible streaming response into Anthropic Messages
 * streaming format. Follows the patterns established by LiteLLM's
 * AnthropicStreamWrapper for correctness across many providers.
 *
 * Anthropic event order:
 *   message_start
 *     β†’ (content_block_start β†’ content_block_delta* β†’ content_block_stop)*
 *     β†’ message_delta
 *     β†’ message_stop
 *
 * Derived from cc-switch (https://github.com/farion1231/cc-switch)
 * Original work by Jason Young, MIT License
 *
 * Provider-specific reasoning formats handled:
 *   - delta.reasoning_content  (DeepSeek, OpenRouter, XAI, Perplexity, …)
 *   - delta.thinking_blocks    (OpenAI o-series)
 *   - delta.reasoning          (GLM-5, Cerebras, Groq β€” mapped to reasoning_content)
 */

import type { OpenAIChatStreamChunk } from '../transform/types.js'
import { stringifyOpenAIToolArguments } from '../transform/toolArguments.js'

// ─── Types ─────────────────────────────────────────────────

type ContentBlockType = 'text' | 'thinking' | 'tool_use'

type ToolBlockState = {
  id: string
  name: string
  argsBuffer: string
  started: boolean
  anthropicIndex: number
}

type SseEvent = { event: string; data: unknown }

type StreamState = {
  // Event queue β€” guarantees correct multi-event ordering
  queue: SseEvent[]

  // Content block tracking (mirrors LiteLLM's state machine)
  currentBlockType: ContentBlockType
  currentBlockIndex: number
  nextContentIndex: number
  blockStartSent: boolean   // content_block_start emitted for current block?
  blockStopSent: boolean    // content_block_stop emitted for current block?

  // Tool call tracking
  toolBlocks: Map<number, ToolBlockState>

  // Message lifecycle
  model: string
  messageStartSent: boolean
  messageDeltaSent: boolean
  messageStopSent: boolean

  // Holding pattern: hold message_delta until usage arrives
  // (some providers send finish_reason and usage in separate chunks)
  heldMessageDelta: SseEvent | null
}

// ─── Helpers ───────────────────────────────────────────────

function formatSse(event: string, data: unknown): string {
  return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`
}

function createState(model: string): StreamState {
  return {
    queue: [],
    currentBlockType: 'text',
    currentBlockIndex: -1,
    nextContentIndex: 0,
    blockStartSent: false,
    blockStopSent: false,
    toolBlocks: new Map(),
    model,
    messageStartSent: false,
    messageDeltaSent: false,
    messageStopSent: false,
    heldMessageDelta: null,
  }
}

// ─── Public entry point ────────────────────────────────────

/**
 * Transform an OpenAI Chat Completions SSE stream into an Anthropic Messages SSE stream.
 */
export function openaiChatStreamToAnthropic(
  upstream: ReadableStream<Uint8Array>,
  model: string,
): ReadableStream<Uint8Array> {
  const encoder = new TextEncoder()
  const decoder = new TextDecoder()
  let buffer = ''
  const state = createState(model)

  return new ReadableStream({
    async start(controller) {
      const reader = upstream.getReader()
      let errored = false

      try {
        while (true) {
          const { done, value } = await reader.read()
          if (done) break

          buffer += decoder.decode(value, { stream: true })
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''

          for (const line of lines) {
            const trimmed = line.trim()
            if (!trimmed || trimmed.startsWith(':')) continue

            if (trimmed === 'data: [DONE]') {
              finalizeStream(state)
              flushQueue(state, controller, encoder)
              continue
            }

            if (!trimmed.startsWith('data: ')) continue
            const jsonStr = trimmed.slice(6)

            let chunk: OpenAIChatStreamChunk
            try {
              chunk = JSON.parse(jsonStr)
            } catch {
              continue
            }

            processChunk(chunk, state)
            flushQueue(state, controller, encoder)
          }
        }
      } catch (err) {
        errored = true
        controller.error(err)
      } finally {
        if (!errored) {
          finalizeStream(state)
          flushQueue(state, controller, encoder)
          controller.close()
        }
      }
    },
  })
}

// ─── Queue management ──────────────────────────────────────

function enqueue(state: StreamState, event: string, data: unknown): void {
  state.queue.push({ event, data })
}

function flushQueue(
  state: StreamState,
  controller: ReadableStreamDefaultController,
  encoder: TextEncoder,
): void {
  for (const item of state.queue) {
    controller.enqueue(encoder.encode(formatSse(item.event, item.data)))
  }
  state.queue.length = 0
}

// ─── Message lifecycle events ──────────────────────────────

function ensureMessageStart(state: StreamState, chunkId?: string): void {
  if (state.messageStartSent) return
  state.messageStartSent = true
  enqueue(state, 'message_start', {
    type: 'message_start',
    message: {
      id: chunkId || `msg_${Date.now()}`,
      type: 'message',
      role: 'assistant',
      content: [],
      model: state.model,
      stop_reason: null,
      stop_sequence: null,
      usage: { input_tokens: 0, output_tokens: 0 },
    },
  })
}

// ─── Content block lifecycle ───────────────────────────────

function openBlock(state: StreamState, blockType: ContentBlockType, block: Record<string, unknown>): number {
  const index = state.nextContentIndex++
  state.currentBlockType = blockType
  state.currentBlockIndex = index
  state.blockStartSent = true
  state.blockStopSent = false
  enqueue(state, 'content_block_start', {
    type: 'content_block_start',
    index,
    content_block: block,
  })
  return index
}

function emitDelta(state: StreamState, index: number, delta: Record<string, unknown>): void {
  enqueue(state, 'content_block_delta', {
    type: 'content_block_delta',
    index,
    delta,
  })
}

function closeCurrentBlock(state: StreamState): void {
  if (!state.blockStartSent || state.blockStopSent) return
  state.blockStopSent = true
  enqueue(state, 'content_block_stop', {
    type: 'content_block_stop',
    index: state.currentBlockIndex,
  })
}

function closeAllToolBlocks(state: StreamState): void {
  for (const [, block] of state.toolBlocks) {
    if (block.started) {
      enqueue(state, 'content_block_stop', {
        type: 'content_block_stop',
        index: block.anthropicIndex,
      })
    }
  }
  state.toolBlocks.clear()
  if (state.currentBlockType === 'tool_use') {
    state.blockStopSent = true
  }
}

function closeAllOpenBlocks(state: StreamState): void {
  // Close current text/thinking block. Tool blocks are tracked separately
  // because providers can stream multiple tool calls in parallel.
  if (state.currentBlockType !== 'tool_use') {
    closeCurrentBlock(state)
  }
  closeAllToolBlocks(state)
}

// ─── Block type detection (follows LiteLLM priority) ───────

type DeltaEx = Record<string, unknown> & {
  content?: string | null
  tool_calls?: Array<{
    index: number
    id?: string
    type?: string
    function?: { name?: string; arguments?: string }
  }>
}

/**
 * Extract reasoning/thinking content from delta regardless of provider format.
 *
 * Handles:
 *   delta.reasoning_content  β€” DeepSeek, OpenRouter, XAI, Perplexity
 *   delta.reasoning          β€” GLM-5, Cerebras, Groq
 *   delta.thinking_blocks    β€” OpenAI o-series
 */
function extractReasoning(delta: DeltaEx): { thinking: string; signature: string } | null {
  // Format 1: reasoning_content (most common)
  if (typeof delta.reasoning_content === 'string' && delta.reasoning_content) {
    return { thinking: delta.reasoning_content, signature: '' }
  }

  // Format 2: reasoning (GLM-5, Cerebras, Groq)
  if (typeof delta.reasoning === 'string' && delta.reasoning) {
    return { thinking: delta.reasoning, signature: '' }
  }

  // Format 3: thinking_blocks (OpenAI o-series)
  const thinkingBlocks = delta.thinking_blocks as Array<Record<string, unknown>> | undefined
  if (Array.isArray(thinkingBlocks) && thinkingBlocks.length > 0) {
    const block = thinkingBlocks[0]
    if (block.type === 'thinking') {
      const thinking = (block.thinking as string) || ''
      const signature = (block.signature as string) || ''
      if (thinking || signature) {
        return { thinking, signature }
      }
    }
  }

  return null
}

/**
 * Determine what block type this chunk carries and whether it's a new block.
 * Priority (matches LiteLLM): tool_calls > text > reasoning > ignore
 */
function detectBlockTransition(
  delta: DeltaEx,
  state: StreamState,
): { type: ContentBlockType; isNew: boolean } | null {
  // Priority 1: Tool calls
  if (delta.tool_calls && delta.tool_calls.length > 0) {
    const tc = delta.tool_calls[0]
    // A tool call with function.name signals a NEW tool block
    const isNew = state.currentBlockType !== 'tool_use' || !!(tc.function?.name)
    return { type: 'tool_use', isNew }
  }

  // Priority 2: Text content
  if (delta.content != null && delta.content !== '') {
    const isNew = state.currentBlockType !== 'text' || !state.blockStartSent
    return { type: 'text', isNew }
  }

  // Priority 3: Reasoning/thinking
  const reasoning = extractReasoning(delta)
  if (reasoning) {
    const isNew = state.currentBlockType !== 'thinking' || !state.blockStartSent
    return { type: 'thinking', isNew }
  }

  return null
}

// ─── Main chunk processing ─────────────────────────────────

function processChunk(chunk: OpenAIChatStreamChunk, state: StreamState): void {
  const choice = chunk.choices?.[0]

  // Handle chunks with empty/missing choices (some providers send these)
  if (!choice) {
    // Check if this is a usage-only chunk (no choices but has usage)
    if (chunk.usage && state.heldMessageDelta) {
      mergeUsageIntoHeldDelta(state, chunk.usage)
    }
    return
  }

  // Update model from first chunk
  state.model = chunk.model || state.model
  ensureMessageStart(state, chunk.id)

  const delta = choice.delta as DeltaEx

  // Detect what this chunk carries
  const transition = detectBlockTransition(delta, state)

  if (transition) {
    // Handle block transition: close previous block if type changed
    if (transition.isNew && state.blockStartSent && !state.blockStopSent) {
      if (state.currentBlockType === 'tool_use' && transition.type !== 'tool_use') {
        closeAllToolBlocks(state)
      } else if (state.currentBlockType !== 'tool_use') {
        closeCurrentBlock(state)
      }
    }

    switch (transition.type) {
      case 'thinking':
        handleThinking(delta, state)
        break
      case 'text':
        handleText(delta, state)
        break
      case 'tool_use':
        handleToolCalls(delta, state)
        break
    }
  }

  // Handle finish_reason
  if (choice.finish_reason) {
    handleFinishReason(choice.finish_reason, chunk, state)
  }
}

// ─── Content handlers ──────────────────────────────────────

function handleThinking(delta: DeltaEx, state: StreamState): void {
  const reasoning = extractReasoning(delta)
  if (!reasoning) return

  if (state.currentBlockType !== 'thinking' || !state.blockStartSent) {
    openBlock(state, 'thinking', { type: 'thinking', thinking: '' })
  }

  if (reasoning.thinking) {
    emitDelta(state, state.currentBlockIndex, {
      type: 'thinking_delta', thinking: reasoning.thinking,
    })
  }
  if (reasoning.signature) {
    emitDelta(state, state.currentBlockIndex, {
      type: 'signature_delta', signature: reasoning.signature,
    })
  }
}

function handleText(delta: DeltaEx, state: StreamState): void {
  if (delta.content == null || delta.content === '') return

  if (state.currentBlockType !== 'text' || !state.blockStartSent) {
    openBlock(state, 'text', { type: 'text', text: '' })
  }

  emitDelta(state, state.currentBlockIndex, {
    type: 'text_delta', text: delta.content,
  })
}

function handleToolCalls(delta: DeltaEx, state: StreamState): void {
  if (!delta.tool_calls) return

  for (const tc of delta.tool_calls) {
    const tcIndex = tc.index

    if (!state.toolBlocks.has(tcIndex)) {
      state.toolBlocks.set(tcIndex, {
        id: '', name: '', argsBuffer: '', started: false, anthropicIndex: -1,
      })
    }

    const block = state.toolBlocks.get(tcIndex)!
    if (tc.id) block.id = tc.id
    if (tc.function?.name) block.name += tc.function.name
    const argumentsDelta = stringifyOpenAIToolArguments(tc.function?.arguments)
    if (argumentsDelta) block.argsBuffer += argumentsDelta

    // Start tool block once we have id + name
    if (!block.started && block.id && block.name) {
      block.started = true
      block.anthropicIndex = state.nextContentIndex++
      state.currentBlockType = 'tool_use'
      state.currentBlockIndex = block.anthropicIndex
      state.blockStartSent = true
      state.blockStopSent = false

      enqueue(state, 'content_block_start', {
        type: 'content_block_start',
        index: block.anthropicIndex,
        content_block: { type: 'tool_use', id: block.id, name: block.name, input: {} },
      })

      // Flush buffered arguments
      if (block.argsBuffer) {
        emitDelta(state, block.anthropicIndex, {
          type: 'input_json_delta', partial_json: block.argsBuffer,
        })
      }
    } else if (block.started && argumentsDelta) {
      emitDelta(state, block.anthropicIndex, {
        type: 'input_json_delta', partial_json: argumentsDelta,
      })
    }
  }
}

// ─── Finish & usage handling ───────────────────────────────

function handleFinishReason(
  finishReason: string,
  chunk: OpenAIChatStreamChunk,
  state: StreamState,
): void {
  if (state.messageDeltaSent) return

  // CRITICAL: close ALL content blocks BEFORE message_delta
  closeAllOpenBlocks(state)

  const stopReason = mapFinishReason(finishReason)
  const usage = chunk.usage
    ? { output_tokens: chunk.usage.completion_tokens || 0 }
    : { output_tokens: 0 }

  const messageDelta: SseEvent = {
    event: 'message_delta',
    data: {
      type: 'message_delta',
      delta: { stop_reason: stopReason, stop_sequence: null },
      usage,
    },
  }

  // If usage is available in the same chunk, emit immediately
  if (chunk.usage) {
    state.messageDeltaSent = true
    state.queue.push(messageDelta)
  } else {
    // Hold message_delta, wait for usage chunk
    state.heldMessageDelta = messageDelta
  }
}

function mergeUsageIntoHeldDelta(
  state: StreamState,
  usage: NonNullable<OpenAIChatStreamChunk['usage']>,
): void {
  if (!state.heldMessageDelta) return

  const data = state.heldMessageDelta.data as Record<string, unknown>
  data.usage = { output_tokens: usage.completion_tokens || 0 }
  state.messageDeltaSent = true
  state.queue.push(state.heldMessageDelta)
  state.heldMessageDelta = null
}

function finalizeStream(state: StreamState): void {
  if (state.messageStopSent) return
  state.messageStopSent = true

  ensureMessageStart(state)

  // Close any remaining open blocks
  closeAllOpenBlocks(state)

  // Flush held message_delta if still waiting for usage
  if (state.heldMessageDelta && !state.messageDeltaSent) {
    state.messageDeltaSent = true
    state.queue.push(state.heldMessageDelta)
    state.heldMessageDelta = null
  }

  // Emit message_delta if never sent (e.g., stream ended without finish_reason)
  if (!state.messageDeltaSent) {
    state.messageDeltaSent = true
    enqueue(state, 'message_delta', {
      type: 'message_delta',
      delta: { stop_reason: 'end_turn', stop_sequence: null },
      usage: { output_tokens: 0 },
    })
  }

  enqueue(state, 'message_stop', { type: 'message_stop' })
}

// ─── Utilities ─────────────────────────────────────────────

function mapFinishReason(reason: string): string {
  switch (reason) {
    case 'stop': return 'end_turn'
    case 'tool_calls': return 'tool_use'
    case 'length': return 'max_tokens'
    case 'content_filter': return 'end_turn'
    default: return 'end_turn'
  }
}