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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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
import { getGlobalConfig, saveGlobalConfig, type ConnectedProviderInfo } from '../../utils/config.js'

const COPILOT_API_BASE = 'https://api.githubcopilot.com'
const MODELS_DEV_URL = 'https://models.dev/api.json'

export type CopilotModelInfo = {
  id: string
  label: string
  description: string
  supportedEndpoints?: string[]
}

type CopilotOutputTokenParam = 'max_tokens' | 'max_completion_tokens'
type CopilotCompatibilityInfo = {
  outputTokenParam?: CopilotOutputTokenParam
  modelSupported?: boolean
  chatCompletionsSupported?: boolean
  updatedAt: number
}

const COPILOT_COMPATIBILITY_CACHE_TTL_MS = 24 * 60 * 60 * 1000
const COPILOT_CHAT_COMPLETIONS_ENDPOINT = '/chat/completions'

export function isCopilotModel(model: string): boolean {
  return model.startsWith('copilot:')
}

export function getCopilotModelId(model: string): string {
  return model.replace(/^copilot:/, '')
}

export function getCopilotProvider(): ConnectedProviderInfo | undefined {
  const config = getGlobalConfig()
  return config.connectedProviders?.['github-copilot']
}

export function isCopilotConnected(): boolean {
  return !!getCopilotProvider()?.oauthToken
}

const FALLBACK_COPILOT_MODELS: CopilotModelInfo[] = [
  { id: 'copilot:claude-sonnet-4.6', label: 'Claude Sonnet 4.6', description: 'Claude Sonnet 4.6 via Copilot' },
  { id: 'copilot:claude-sonnet-4.5', label: 'Claude Sonnet 4.5', description: 'Claude Sonnet 4.5 via Copilot' },
  { id: 'copilot:claude-sonnet-4', label: 'Claude Sonnet 4', description: 'Claude Sonnet 4 via Copilot' },
  { id: 'copilot:claude-opus-4.6', label: 'Claude Opus 4.6', description: 'Claude Opus 4.6 via Copilot' },
  { id: 'copilot:claude-opus-4.5', label: 'Claude Opus 4.5', description: 'Claude Opus 4.5 via Copilot' },
  { id: 'copilot:claude-opus-41', label: 'Claude Opus 4.1', description: 'Claude Opus 4.1 via Copilot' },
  { id: 'copilot:claude-haiku-4.5', label: 'Claude Haiku 4.5', description: 'Claude Haiku 4.5 via Copilot' },
  { id: 'copilot:gpt-5.4', label: 'GPT-5.4', description: 'OpenAI GPT-5.4 via Copilot' },
  { id: 'copilot:gpt-5.4-mini', label: 'GPT-5.4 mini', description: 'OpenAI GPT-5.4 mini via Copilot' },
  { id: 'copilot:gpt-5.3-codex', label: 'GPT-5.3-Codex', description: 'OpenAI GPT-5.3-Codex via Copilot' },
  { id: 'copilot:gpt-5.2-codex', label: 'GPT-5.2-Codex', description: 'OpenAI GPT-5.2-Codex via Copilot' },
  { id: 'copilot:gpt-5.2', label: 'GPT-5.2', description: 'OpenAI GPT-5.2 via Copilot' },
  { id: 'copilot:gpt-5.1', label: 'GPT-5.1', description: 'OpenAI GPT-5.1 via Copilot' },
  { id: 'copilot:gpt-5.1-codex', label: 'GPT-5.1-Codex', description: 'OpenAI GPT-5.1-Codex via Copilot' },
  { id: 'copilot:gpt-5.1-codex-mini', label: 'GPT-5.1-Codex-mini', description: 'OpenAI GPT-5.1-Codex-mini via Copilot' },
  { id: 'copilot:gpt-5.1-codex-max', label: 'GPT-5.1-Codex-max', description: 'OpenAI GPT-5.1-Codex-max via Copilot' },
  { id: 'copilot:gpt-5', label: 'GPT-5', description: 'OpenAI GPT-5 via Copilot' },
  { id: 'copilot:gpt-5-mini', label: 'GPT-5-mini', description: 'OpenAI GPT-5-mini via Copilot' },
  { id: 'copilot:gpt-4.1', label: 'GPT-4.1', description: 'OpenAI GPT-4.1 via Copilot' },
  { id: 'copilot:gpt-4o', label: 'GPT-4o', description: 'OpenAI GPT-4o via Copilot' },
  { id: 'copilot:gemini-3.1-pro-preview', label: 'Gemini 3.1 Pro Preview', description: 'Google Gemini 3.1 Pro via Copilot' },
  { id: 'copilot:gemini-3-pro-preview', label: 'Gemini 3 Pro Preview', description: 'Google Gemini 3 Pro via Copilot' },
  { id: 'copilot:gemini-3-flash-preview', label: 'Gemini 3 Flash', description: 'Google Gemini 3 Flash via Copilot' },
  { id: 'copilot:gemini-2.5-pro', label: 'Gemini 2.5 Pro', description: 'Google Gemini 2.5 Pro via Copilot' },
  { id: 'copilot:grok-code-fast-1', label: 'Grok Code Fast 1', description: 'xAI Grok Code Fast 1 via Copilot' },
]

let cachedModels: CopilotModelInfo[] | null = null
let copilotModelsRefreshPromise: Promise<void> | null = null

type CopilotApiModel = {
  id: string
  name?: string
  model_picker_enabled?: boolean
  policy?: { state?: string }
  supported_endpoints?: string[]
}

function supportsCopilotChatCompletions(model: CopilotModelInfo): boolean {
  return (
    !model.supportedEndpoints ||
    model.supportedEndpoints.includes(COPILOT_CHAT_COMPLETIONS_ENDPOINT)
  )
}

export async function fetchCopilotModelsFromApi(): Promise<CopilotModelInfo[] | null> {
  const provider = getCopilotProvider()
  if (!provider?.oauthToken) return null

  const response = await fetch(`${COPILOT_API_BASE}/models`, {
    headers: {
      Authorization: `Bearer ${provider.oauthToken}`,
      'User-Agent': 'claude-code/2.1.88',
      'Openai-Intent': 'conversation-edits',
      'x-initiator': 'user',
    },
    signal: AbortSignal.timeout(10_000),
  })
  if (!response.ok) {
    throw new Error(`Copilot models API failed (${response.status})`)
  }

  const data = await response.json() as {
    data?: CopilotApiModel[]
  }
  if (!Array.isArray(data.data) || data.data.length === 0) {
    return null
  }

  const models = data.data
    .filter(model => model.model_picker_enabled !== false)
    .filter(model => model.policy?.state !== 'disabled')
    .map(
      (model): CopilotModelInfo => ({
        id: `copilot:${model.id}`,
        label: model.name || model.id,
        description: `${model.name || model.id} via Copilot`,
        supportedEndpoints: model.supported_endpoints,
      }),
    )

  return models.length > 0 ? models : null
}

export async function fetchCopilotModelsFromModelsDev(): Promise<CopilotModelInfo[]> {
  try {
    const response = await fetch(MODELS_DEV_URL, {
      signal: AbortSignal.timeout(10_000),
    })
    if (!response.ok) return FALLBACK_COPILOT_MODELS

    const data = await response.json() as Record<string, { models?: Record<string, { name?: string }> }>
    const copilotProvider = data['github-copilot']
    if (!copilotProvider?.models) return FALLBACK_COPILOT_MODELS

    const models: CopilotModelInfo[] = Object.entries(copilotProvider.models).map(
      ([modelId, info]) => ({
        id: `copilot:${modelId}`,
        label: info.name || modelId,
        description: `${info.name || modelId} via Copilot`,
      }),
    )

    return models.length > 0 ? models : FALLBACK_COPILOT_MODELS
  } catch {
    return FALLBACK_COPILOT_MODELS
  }
}

export async function fetchCopilotModels(): Promise<CopilotModelInfo[]> {
  try {
    const apiModels = await fetchCopilotModelsFromApi()
    if (apiModels && apiModels.length > 0) {
      return apiModels
    }
  } catch {}

  return fetchCopilotModelsFromModelsDev()
}

function hasCopilotEndpointMetadata(models: CopilotModelInfo[]): boolean {
  return models.some(model => Array.isArray(model.supportedEndpoints))
}

function shouldUseCachedCopilotModels(cache: {
  models: CopilotModelInfo[]
  fetchedAt: number
} | null | undefined): boolean {
  if (!cache || cache.models.length === 0) return false
  if (!hasCopilotEndpointMetadata(cache.models)) return false
  return Date.now() - cache.fetchedAt < 3600_000
}

function refreshCopilotModelsCacheInBackground(): void {
  if (copilotModelsRefreshPromise || !isCopilotConnected()) {
    return
  }
  copilotModelsRefreshPromise = (async () => {
    const models = await fetchCopilotModels()
    cachedModels = models
    saveGlobalConfig(current => ({
      ...current,
      copilotModelsCache: { models, fetchedAt: Date.now() },
    }))
  })()
    .catch(() => {})
    .finally(() => {
      copilotModelsRefreshPromise = null
    })
}

export async function getCopilotModels(): Promise<CopilotModelInfo[]> {
  if (cachedModels) return filterUnavailableCopilotModels(cachedModels)

  const config = getGlobalConfig()
  const cached = config.copilotModelsCache
  if (shouldUseCachedCopilotModels(cached)) {
    cachedModels = cached.models
    return filterUnavailableCopilotModels(cachedModels)
  }

  const models = await fetchCopilotModels()
  cachedModels = models

  saveGlobalConfig(current => ({
    ...current,
    copilotModelsCache: { models, fetchedAt: Date.now() },
  }))

  return filterUnavailableCopilotModels(models)
}

export function getCopilotModelsCached(): CopilotModelInfo[] {
  if (cachedModels) {
    if (!hasCopilotEndpointMetadata(cachedModels)) {
      refreshCopilotModelsCacheInBackground()
    }
    return filterUnavailableCopilotModels(cachedModels)
  }

  const config = getGlobalConfig()
  const cached = config.copilotModelsCache
  if (cached && cached.models.length > 0) {
    cachedModels = cached.models
    if (!shouldUseCachedCopilotModels(cached)) {
      refreshCopilotModelsCacheInBackground()
    }
    return filterUnavailableCopilotModels(cachedModels)
  }

  refreshCopilotModelsCacheInBackground()
  return filterUnavailableCopilotModels(FALLBACK_COPILOT_MODELS)
}

export { FALLBACK_COPILOT_MODELS as COPILOT_MODELS }

function getCachedCopilotCompatibility(
  modelId: string,
): CopilotCompatibilityInfo | undefined {
  const compatibility = getGlobalConfig().copilotCompatibilityCache?.[modelId]
  if (!compatibility) return undefined
  if (Date.now() - compatibility.updatedAt > COPILOT_COMPATIBILITY_CACHE_TTL_MS) {
    return undefined
  }
  return compatibility
}

function filterUnavailableCopilotModels(
  models: CopilotModelInfo[],
): CopilotModelInfo[] {
  return models.filter(model => {
    if (!supportsCopilotChatCompletions(model)) {
      return false
    }
    const compatibility = getCachedCopilotCompatibility(
      getCopilotModelId(model.id),
    )
    return (
      compatibility?.modelSupported !== false &&
      compatibility?.chatCompletionsSupported !== false
    )
  })
}

function saveCopilotCompatibility(
  modelId: string,
  updates: Partial<CopilotCompatibilityInfo>,
): void {
  saveGlobalConfig(current => {
    const existing = current.copilotCompatibilityCache?.[modelId]
    const next = {
      ...existing,
      ...updates,
      updatedAt: Date.now(),
    } satisfies CopilotCompatibilityInfo

    if (
      existing?.outputTokenParam === next.outputTokenParam &&
      existing?.modelSupported === next.modelSupported &&
      existing?.chatCompletionsSupported === next.chatCompletionsSupported
    ) {
      return current
    }

    return {
      ...current,
      copilotCompatibilityCache: {
        ...current.copilotCompatibilityCache,
        [modelId]: next,
      },
    }
  })
}

function getPreferredCopilotOutputTokenParam(
  modelId: string,
): CopilotOutputTokenParam {
  return (
    getCachedCopilotCompatibility(modelId)?.outputTokenParam ??
    'max_tokens'
  )
}

function savePreferredCopilotOutputTokenParam(
  modelId: string,
  outputTokenParam: CopilotOutputTokenParam,
): void {
  saveCopilotCompatibility(modelId, { outputTokenParam })
}

function buildCopilotChatRequestBody(params: {
  modelId: string
  messages: OpenAIMessage[]
  isStreaming: boolean
  maxTokens?: number
  tools?: OpenAITool[]
  outputTokenParam: CopilotOutputTokenParam
}): Record<string, unknown> {
  const requestBody: Record<string, unknown> = {
    model: params.modelId,
    messages: params.messages,
    stream: params.isStreaming,
  }

  if (params.maxTokens) {
    requestBody[params.outputTokenParam] = params.maxTokens
  }

  if (params.tools && params.tools.length > 0) {
    requestBody.tools = params.tools
    requestBody.tool_choice = 'auto'
  }

  return requestBody
}

async function createCopilotErrorInfo(response: Response): Promise<{
  message?: string
  code?: string
}> {
  const text = await response
    .clone()
    .text()
    .catch(() => '')
  if (!text) return {}
  try {
    const parsed = JSON.parse(text) as {
      error?: { message?: string; code?: string }
    }
    return {
      message: parsed.error?.message,
      code: parsed.error?.code,
    }
  } catch {
    return {}
  }
}

function createCachedCopilotErrorResponse(
  message: string,
  code: string,
): Response {
  return new Response(JSON.stringify({ error: { message, code } }), {
    status: 400,
    headers: { 'Content-Type': 'application/json' },
  })
}

function getSuggestedCopilotOutputTokenParam(
  currentParam: CopilotOutputTokenParam,
  errorMessage: string | undefined,
): CopilotOutputTokenParam | undefined {
  if (!errorMessage) return undefined
  if (
    currentParam === 'max_tokens' &&
    errorMessage.includes("Use 'max_completion_tokens' instead")
  ) {
    return 'max_completion_tokens'
  }
  if (
    currentParam === 'max_completion_tokens' &&
    errorMessage.includes("Use 'max_tokens' instead")
  ) {
    return 'max_tokens'
  }
  return undefined
}

async function postCopilotChatCompletion(params: {
  oauthToken: string
  requestBody: Record<string, unknown>
  signal?: AbortSignal
}): Promise<Response> {
  return fetch(`${COPILOT_API_BASE}/chat/completions`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${params.oauthToken}`,
      'User-Agent': 'claude-code/2.1.88',
      'Openai-Intent': 'conversation-edits',
      'x-initiator': 'user',
    },
    body: JSON.stringify(params.requestBody),
    signal: params.signal,
  })
}

function saveCopilotCompatibilityFromError(
  modelId: string,
  errorInfo: { code?: string },
): void {
  if (errorInfo.code === 'model_not_supported') {
    saveCopilotCompatibility(modelId, {
      modelSupported: false,
      chatCompletionsSupported: false,
    })
  } else if (errorInfo.code === 'unsupported_api_for_model') {
    saveCopilotCompatibility(modelId, {
      chatCompletionsSupported: false,
    })
  }
}

async function sendCopilotChatCompletion(params: {
  oauthToken: string
  modelId: string
  messages: OpenAIMessage[]
  isStreaming: boolean
  maxTokens?: number
  tools?: OpenAITool[]
  signal?: AbortSignal
}): Promise<Response> {
  const compatibility = getCachedCopilotCompatibility(params.modelId)
  if (compatibility?.modelSupported === false) {
    return createCachedCopilotErrorResponse(
      `Copilot model "${params.modelId}" was previously rejected as unsupported.`,
      'model_not_supported',
    )
  }
  if (compatibility?.chatCompletionsSupported === false) {
    return createCachedCopilotErrorResponse(
      `Copilot model "${params.modelId}" does not support the /chat/completions endpoint.`,
      'unsupported_api_for_model',
    )
  }

  let outputTokenParam = getPreferredCopilotOutputTokenParam(params.modelId)
  let requestBody = buildCopilotChatRequestBody({
    modelId: params.modelId,
    messages: params.messages,
    isStreaming: params.isStreaming,
    maxTokens: params.maxTokens,
    tools: params.tools,
    outputTokenParam,
  })

  let response = await postCopilotChatCompletion({
    oauthToken: params.oauthToken,
    requestBody,
    signal: params.signal,
  })
  if (response.ok) {
    saveCopilotCompatibility(params.modelId, {
      modelSupported: true,
      chatCompletionsSupported: true,
      outputTokenParam,
    })
    return response
  }

  const errorInfo = await createCopilotErrorInfo(response)
  if (!params.maxTokens) {
    saveCopilotCompatibilityFromError(params.modelId, errorInfo)
    return response
  }
  const suggestedParam = getSuggestedCopilotOutputTokenParam(
    outputTokenParam,
    errorInfo.message,
  )
  if (!suggestedParam) {
    saveCopilotCompatibilityFromError(params.modelId, errorInfo)
    return response
  }

  savePreferredCopilotOutputTokenParam(params.modelId, suggestedParam)
  outputTokenParam = suggestedParam
  requestBody = buildCopilotChatRequestBody({
    modelId: params.modelId,
    messages: params.messages,
    isStreaming: params.isStreaming,
    maxTokens: params.maxTokens,
    tools: params.tools,
    outputTokenParam,
  })

  response = await postCopilotChatCompletion({
    oauthToken: params.oauthToken,
    requestBody,
    signal: params.signal,
  })
  if (response.ok) {
    saveCopilotCompatibility(params.modelId, {
      modelSupported: true,
      chatCompletionsSupported: true,
      outputTokenParam,
    })
    return response
  }

  saveCopilotCompatibilityFromError(
    params.modelId,
    await createCopilotErrorInfo(response),
  )
  return response
}

type OpenAIMessage = {
  role: 'system' | 'user' | 'assistant' | 'tool'
  content: string | Array<{ type: string; text?: string; image_url?: { url: string } }>
  tool_calls?: Array<{
    id: string
    type: 'function'
    function: { name: string; arguments: string }
  }>
  tool_call_id?: string
}

type OpenAITool = {
  type: 'function'
  function: {
    name: string
    description: string
    parameters: Record<string, unknown>
  }
}

export type AnthropicContentBlock =
  | { type: 'text'; text: string }
  | { type: 'image'; source: { type: 'base64'; media_type: string; data: string } }
  | { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }
  | { type: 'tool_result'; tool_use_id: string; content: string | Array<{ type: string; text?: string }> }
  | { type: 'thinking'; thinking: string }
  | Record<string, unknown>

export type AnthropicMessage = {
  role: 'user' | 'assistant'
  content: string | AnthropicContentBlock[]
}

export function convertAnthropicMessagesToOpenAI(
  messages: AnthropicMessage[],
  systemPrompt?: string,
): OpenAIMessage[] {
  const result: OpenAIMessage[] = []

  if (systemPrompt) {
    result.push({ role: 'system', content: systemPrompt })
  }

  for (const msg of messages) {
    if (typeof msg.content === 'string') {
      result.push({ role: msg.role, content: msg.content })
      continue
    }

    if (msg.role === 'user') {
      const parts: Array<{ type: string; text?: string; image_url?: { url: string } }> = []
      const toolResults: OpenAIMessage[] = []

      for (const block of msg.content) {
        if (block.type === 'text') {
          parts.push({ type: 'text', text: (block as { type: 'text'; text: string }).text })
        } else if (block.type === 'image') {
          const imgBlock = block as { type: 'image'; source: { type: 'base64'; media_type: string; data: string } }
          parts.push({
            type: 'image_url',
            image_url: { url: `data:${imgBlock.source.media_type};base64,${imgBlock.source.data}` },
          })
        } else if (block.type === 'tool_result') {
          const trBlock = block as { type: 'tool_result'; tool_use_id: string; content: string | Array<{ type: string; text?: string }> }
          let content = ''
          if (typeof trBlock.content === 'string') {
            content = trBlock.content
          } else if (Array.isArray(trBlock.content)) {
            content = trBlock.content
              .filter(c => c.type === 'text')
              .map(c => c.text || '')
              .join('\n')
          }
          toolResults.push({
            role: 'tool',
            content,
            tool_call_id: trBlock.tool_use_id,
          })
        }
      }

      if (toolResults.length > 0) {
        result.push(...toolResults)
        if (parts.length > 0) {
          result.push({ role: 'user', content: parts.length === 1 && parts[0].type === 'text' ? parts[0].text! : parts })
        }
      } else if (parts.length > 0) {
        result.push({ role: 'user', content: parts.length === 1 && parts[0].type === 'text' ? parts[0].text! : parts })
      }
    } else if (msg.role === 'assistant') {
      const textParts: string[] = []
      const toolCalls: Array<{ id: string; type: 'function'; function: { name: string; arguments: string } }> = []

      for (const block of msg.content) {
        if (block.type === 'text') {
          textParts.push((block as { type: 'text'; text: string }).text)
        } else if (block.type === 'tool_use') {
          const tuBlock = block as { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }
          toolCalls.push({
            id: tuBlock.id,
            type: 'function',
            function: {
              name: tuBlock.name,
              arguments: JSON.stringify(tuBlock.input),
            },
          })
        }
      }

      const assistantMsg: OpenAIMessage = {
        role: 'assistant',
        content: textParts.join('\n') || '',
      }
      if (toolCalls.length > 0) {
        assistantMsg.tool_calls = toolCalls
      }
      result.push(assistantMsg)
    }
  }

  return result
}

export function convertAnthropicToolsToOpenAI(
  tools: Array<{ name: string; description?: string; input_schema?: Record<string, unknown> }>,
): OpenAITool[] {
  return tools.map(tool => ({
    type: 'function' as const,
    function: {
      name: tool.name,
      description: tool.description || '',
      parameters: tool.input_schema || { type: 'object', properties: {} },
    },
  }))
}

export type CopilotStreamEvent =
  | { type: 'message_start'; message: { id: string; type: 'message'; role: 'assistant'; model: string; content: []; usage: { input_tokens: number; output_tokens: number } } }
  | { type: 'content_block_start'; index: number; content_block: { type: 'text'; text: string } }
  | { type: 'content_block_delta'; index: number; delta: { type: 'text_delta'; text: string } }
  | { type: 'content_block_stop'; index: number }
  | { type: 'message_delta'; delta: { stop_reason: string }; usage: { output_tokens: number } }
  | { type: 'message_stop' }

export async function* streamCopilotRequest(
  model: string,
  messages: AnthropicMessage[],
  systemPrompt: string | undefined,
  tools: Array<{ name: string; description?: string; input_schema?: Record<string, unknown> }>,
  signal: AbortSignal,
): AsyncGenerator<CopilotStreamEvent> {
  const provider = getCopilotProvider()
  if (!provider?.oauthToken) {
    throw new Error('GitHub Copilot is not connected. Use /connect to authenticate.')
  }

  const copilotModelId = getCopilotModelId(model)
  const openaiMessages = convertAnthropicMessagesToOpenAI(messages, systemPrompt)
  const openaiTools = tools.length > 0 ? convertAnthropicToolsToOpenAI(tools) : undefined
  const response = await sendCopilotChatCompletion({
    oauthToken: provider.oauthToken,
    modelId: copilotModelId,
    messages: openaiMessages,
    isStreaming: true,
    maxTokens: 16384,
    tools: openaiTools,
    signal,
  })

  if (!response.ok) {
    const errorText = await response.text().catch(() => 'unknown error')
    throw new Error(`Copilot API error (${response.status}): ${errorText}`)
  }

  if (!response.body) {
    throw new Error('No response body from Copilot API')
  }

  const messageId = `msg_copilot_${Date.now()}`
  let contentIndex = 0
  let hasStartedContent = false
  let currentToolCallIndex = -1
  const toolCalls: Map<number, { id: string; name: string; arguments: string }> = new Map()
  let totalOutputTokens = 0

  yield {
    type: 'message_start',
    message: {
      id: messageId,
      type: 'message',
      role: 'assistant',
      model: copilotModelId,
      content: [],
      usage: { input_tokens: 0, output_tokens: 0 },
    },
  }

  const reader = response.body.getReader()
  const decoder = new TextDecoder()
  let buffer = ''

  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) {
        if (!line.startsWith('data: ')) continue
        const data = line.slice(6).trim()
        if (data === '[DONE]') {
          if (hasStartedContent) {
            yield { type: 'content_block_stop', index: contentIndex - 1 }
          }
          for (const [idx, tc] of toolCalls) {
            yield {
              type: 'content_block_stop',
              index: contentIndex + idx,
            }
          }
          yield {
            type: 'message_delta',
            delta: { stop_reason: toolCalls.size > 0 ? 'tool_use' : 'end_turn' },
            usage: { output_tokens: totalOutputTokens },
          }
          yield { type: 'message_stop' }
          return
        }

        let chunk: {
          choices?: Array<{
            delta?: {
              content?: string | null
              tool_calls?: Array<{
                index: number
                id?: string
                function?: { name?: string; arguments?: string }
              }>
              role?: string
            }
            finish_reason?: string | null
          }>
          usage?: { completion_tokens?: number; prompt_tokens?: number; total_tokens?: number }
        }

        try {
          chunk = JSON.parse(data)
        } catch {
          continue
        }

        if (chunk.usage?.completion_tokens) {
          totalOutputTokens = chunk.usage.completion_tokens
        }

        const choice = chunk.choices?.[0]
        if (!choice?.delta) continue

        const delta = choice.delta

        if (delta.content != null && delta.content !== '') {
          if (!hasStartedContent) {
            hasStartedContent = true
            yield {
              type: 'content_block_start',
              index: contentIndex,
              content_block: { type: 'text', text: '' },
            }
          }
          yield {
            type: 'content_block_delta',
            index: contentIndex,
            delta: { type: 'text_delta', text: delta.content },
          }
        }

        if (delta.tool_calls) {
          for (const tc of delta.tool_calls) {
            if (tc.id) {
              if (hasStartedContent && currentToolCallIndex === -1) {
                yield { type: 'content_block_stop', index: contentIndex }
                contentIndex++
                hasStartedContent = false
              }
              currentToolCallIndex = tc.index
              toolCalls.set(tc.index, {
                id: tc.id,
                name: tc.function?.name || '',
                arguments: tc.function?.arguments || '',
              })
              const toolBlockIndex = hasStartedContent ? contentIndex + 1 + tc.index : contentIndex + tc.index
              yield {
                type: 'content_block_start' as const,
                index: toolBlockIndex,
                content_block: {
                  type: 'text',
                  text: '',
                } as any,
              }
            } else if (tc.function?.arguments) {
              const existing = toolCalls.get(tc.index)
              if (existing) {
                existing.arguments += tc.function.arguments
              }
            }
          }
        }

        if (choice.finish_reason) {
          if (hasStartedContent) {
            yield { type: 'content_block_stop', index: contentIndex }
          }
          yield {
            type: 'message_delta',
            delta: { stop_reason: choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn' },
            usage: { output_tokens: totalOutputTokens },
          }
          yield { type: 'message_stop' }
          return
        }
      }
    }
  } finally {
    reader.releaseLock()
  }

  yield {
    type: 'message_delta',
    delta: { stop_reason: 'end_turn' },
    usage: { output_tokens: totalOutputTokens },
  }
  yield { type: 'message_stop' }
}

export function createCopilotFetchOverride(
  model: string,
): (input: RequestInfo | URL, init?: RequestInit) => Promise<Response> {
  const provider = getCopilotProvider()
  if (!provider?.oauthToken) {
    throw new Error('GitHub Copilot is not connected')
  }

  const copilotModelId = getCopilotModelId(model)

  return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
    const url = input instanceof URL ? input.href : typeof input === 'string' ? input : input.url

    if (!url.includes('/messages') && !url.includes('/v1/')) {
      return fetch(input, init)
    }

    if (url.includes('/count_tokens') || url.includes('/models')) {
      return new Response(JSON.stringify({ input_tokens: 0 }), {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      })
    }

    let anthropicBody: Record<string, unknown> = {}
    if (init?.body) {
      try {
        anthropicBody = JSON.parse(typeof init.body === 'string' ? init.body : new TextDecoder().decode(init.body as ArrayBuffer))
      } catch {
        return fetch(input, init)
      }
    }

    const systemBlocks = anthropicBody.system as Array<{ type: string; text: string }> | string | undefined
    let systemPrompt = ''
    if (typeof systemBlocks === 'string') {
      systemPrompt = systemBlocks
    } else if (Array.isArray(systemBlocks)) {
      systemPrompt = systemBlocks
        .filter(b => b.type === 'text')
        .map(b => b.text)
        .join('\n\n')
    }

    const anthropicMessages = (anthropicBody.messages || []) as AnthropicMessage[]
    const openaiMessages = convertAnthropicMessagesToOpenAI(anthropicMessages, systemPrompt)

    const anthropicTools = (anthropicBody.tools || []) as Array<{ name: string; description?: string; input_schema?: Record<string, unknown> }>
    const openaiTools = anthropicTools.length > 0 ? convertAnthropicToolsToOpenAI(anthropicTools) : undefined

    const isStreaming = anthropicBody.stream === true
    const maxTokens =
      typeof anthropicBody.max_tokens === 'number'
        ? anthropicBody.max_tokens
        : undefined

    const copilotResponse = await sendCopilotChatCompletion({
      oauthToken: provider.oauthToken,
      modelId: copilotModelId,
      messages: openaiMessages,
      isStreaming,
      maxTokens,
      tools: openaiTools,
      signal: init?.signal,
    })

    if (!copilotResponse.ok) {
      return copilotResponse
    }

    if (!isStreaming) {
      const data = await copilotResponse.json() as {
        id: string
        choices: Array<{
          message: {
            role: string
            content: string | null
            tool_calls?: Array<{
              id: string
              function: { name: string; arguments: string }
            }>
          }
          finish_reason: string
        }>
        usage?: { prompt_tokens: number; completion_tokens: number }
      }

      const choice = data.choices[0]
      const anthropicContent: Array<{
        type: string
        text?: string
        id?: string
        name?: string
        input?: unknown
      }> = []

      if (choice?.message?.content) {
        anthropicContent.push({ type: 'text', text: choice.message.content })
      }

      if (choice?.message?.tool_calls) {
        for (const tc of choice.message.tool_calls) {
          anthropicContent.push({
            type: 'tool_use',
            id: tc.id,
            name: tc.function.name,
            input: JSON.parse(tc.function.arguments || '{}'),
          })
        }
      }

      const anthropicResponse = {
        id: data.id || `msg_copilot_${Date.now()}`,
        type: 'message',
        role: 'assistant',
        content: anthropicContent,
        model: copilotModelId,
        stop_reason: choice?.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn',
        usage: {
          input_tokens: data.usage?.prompt_tokens || 0,
          output_tokens: data.usage?.completion_tokens || 0,
        },
      }

      return new Response(JSON.stringify(anthropicResponse), {
        status: 200,
        headers: { 'Content-Type': 'application/json' },
      })
    }

    const transformStream = convertOpenAIStreamToAnthropic(copilotResponse.body!, copilotModelId)

    return new Response(transformStream, {
      status: 200,
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive',
      },
    })
  }
}

export function convertOpenAIStreamToAnthropic(
  openaiStream: ReadableStream,
  model: string,
): ReadableStream<Uint8Array> {
  const encoder = new TextEncoder()
  const decoder = new TextDecoder()

  let messageId = `msg_${Date.now()}`
  let contentIndex = 0
  let hasStartedContent = false
  let currentToolCallIndex = -1
  const toolCalls: Map<number, { id: string; name: string; arguments: string }> = new Map()
  let totalOutputTokens = 0

  return new ReadableStream({
    async start(controller) {
      const reader = openaiStream.getReader()
      let buffer = ''

      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) {
            if (!line.startsWith('data: ')) continue
            const data = line.slice(6).trim()
            if (data === '[DONE]') {
              if (hasStartedContent) {
                controller.enqueue(encoder.encode(`event: content_block_stop\ndata: {"index":${contentIndex - 1}}\n\n`))
              }
              for (const [idx, tc] of toolCalls) {
                controller.enqueue(
                  encoder.encode(`event: content_block_stop\ndata: {"index":${contentIndex + idx}}\n\n`),
                )
              }
              controller.enqueue(
                encoder.encode(
                  `event: message_delta\ndata: {"delta":{"stop_reason":"${toolCalls.size > 0 ? 'tool_use' : 'end_turn'}"},"usage":{"output_tokens":${totalOutputTokens}}}\n\n`,
                ),
              )
              controller.enqueue(encoder.encode('event: message_stop\ndata: {}\n\n'))
              return
            }

            let chunk: {
              choices?: Array<{
                delta?: {
                  content?: string | null
                  tool_calls?: Array<{
                    index: number
                    id?: string
                    function?: { name?: string; arguments?: string }
                  }>
                  role?: string
                }
                finish_reason?: string | null
              }>
              usage?: { completion_tokens?: number; prompt_tokens?: number; total_tokens?: number }
            }

            try {
              chunk = JSON.parse(data)
            } catch {
              continue
            }

            if (chunk.usage?.completion_tokens) {
              totalOutputTokens = chunk.usage.completion_tokens
            }

            const choice = chunk.choices?.[0]
            if (!choice?.delta) continue

            const delta = choice.delta

            if (delta.content != null && delta.content !== '') {
              if (!hasStartedContent) {
                hasStartedContent = true
                controller.enqueue(
                  encoder.encode(
                    `event: content_block_start\ndata: {"index":${contentIndex},"content_block":{"type":"text","text":""}}\n\n`,
                  ),
                )
              }
              controller.enqueue(
                encoder.encode(
                  `event: content_block_delta\ndata: {"index":${contentIndex},"delta":{"type":"text_delta","text":"${JSON.stringify(delta.content).slice(1, -1)}"}}\n\n`,
                ),
              )
            }

            if (delta.tool_calls) {
              for (const tc of delta.tool_calls) {
                if (tc.id) {
                  if (hasStartedContent && currentToolCallIndex === -1) {
                    controller.enqueue(
                      encoder.encode(`event: content_block_stop\ndata: {"index":${contentIndex}}\n\n`),
                    )
                    contentIndex++
                    hasStartedContent = false
                  }
                  currentToolCallIndex = tc.index
                  toolCalls.set(tc.index, {
                    id: tc.id,
                    name: tc.function?.name || '',
                    arguments: tc.function?.arguments || '',
                  })
                  const toolBlockIndex =
                    hasStartedContent ? contentIndex + 1 + tc.index : contentIndex + tc.index
                  controller.enqueue(
                    encoder.encode(
                      `event: content_block_start\ndata: {"index":${toolBlockIndex},"content_block":{"type":"text","text":""}}\n\n`,
                    ),
                  )
                } else if (tc.function?.arguments) {
                  const existing = toolCalls.get(tc.index)
                  if (existing) {
                    existing.arguments += tc.function.arguments
                  }
                }
              }
            }

            if (choice.finish_reason) {
              if (hasStartedContent) {
                controller.enqueue(
                  encoder.encode(`event: content_block_stop\ndata: {"index":${contentIndex}}\n\n`),
                )
              }
              controller.enqueue(
                encoder.encode(
                  `event: message_delta\ndata: {"delta":{"stop_reason":"${choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn'}"},"usage":{"output_tokens":${totalOutputTokens}}}\n\n`,
                ),
              )
              controller.enqueue(encoder.encode('event: message_stop\ndata: {}\n\n'))
              return
            }
          }
        }
      } finally {
        reader.releaseLock()
        controller.close()
      }
    },
  })
}