-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathopenaiShim.ts
More file actions
2608 lines (2365 loc) · 87.8 KB
/
openaiShim.ts
File metadata and controls
2608 lines (2365 loc) · 87.8 KB
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
/**
* OpenAI-compatible API shim for Claude Code.
*
* Translates Anthropic SDK calls (anthropic.beta.messages.create) into
* OpenAI-compatible chat completion requests and streams back events
* in the Anthropic streaming format so the rest of the codebase is unaware.
*
* Supports: OpenAI, Azure OpenAI, Ollama, LM Studio, OpenRouter,
* Together, Groq, Fireworks, DeepSeek, Mistral, and any OpenAI-compatible API.
*
* Environment variables:
* CLAUDE_CODE_USE_OPENAI=1 — enable this provider
* OPENAI_API_KEY=sk-... — API key (optional for local models)
* OPENAI_AUTH_HEADER=api-key — optional custom auth header name
* OPENAI_AUTH_HEADER_VALUE=... — optional custom auth header value
* OPENAI_AUTH_SCHEME=bearer|raw — auth scheme for Authorization/custom header handling
* OPENAI_API_FORMAT=chat_completions|responses — request format for compatible APIs
* OPENAI_BASE_URL=http://... — base URL (default: https://api.openai.com/v1)
* OPENAI_MODEL=gpt-4o — default model override
* CODEX_API_KEY / ~/.codex/auth.json — Codex auth for codexplan/codexspark
*
* GitHub Copilot API (api.githubcopilot.com), OpenAI-compatible:
* CLAUDE_CODE_USE_GITHUB=1 — enable GitHub inference (no need for USE_OPENAI)
* GITHUB_TOKEN or GH_TOKEN — Copilot API token (mapped to Bearer auth)
* OPENAI_MODEL — optional; use github:copilot or openai/gpt-4.1 style IDs
*/
import { APIError } from '@anthropic-ai/sdk'
import {
readCodexCredentialsAsync,
refreshCodexAccessTokenIfNeeded,
} from '../../utils/codexCredentials.js'
import { logForDebugging } from '../../utils/debug.js'
import { isBareMode, isEnvTruthy } from '../../utils/envUtils.js'
import { resolveGeminiCredential } from '../../utils/geminiAuth.js'
import { hydrateGeminiAccessTokenFromSecureStorage } from '../../utils/geminiCredentials.js'
import { hydrateGithubModelsTokenFromSecureStorage } from '../../utils/githubModelsCredentials.js'
import { resolveOpenAIShimRuntimeContext } from '../../integrations/runtimeMetadata.js'
import { resolveRouteCredentialValue } from '../../integrations/routeMetadata.js'
import {
createThinkTagFilter,
stripThinkTags,
} from './thinkTagSanitizer.js'
import {
codexStreamToAnthropic,
collectCodexCompletedResponse,
convertAnthropicMessagesToResponsesInput,
convertCodexResponseToAnthropicMessage,
convertToolsToResponsesTools,
performCodexRequest,
type AnthropicStreamEvent,
type AnthropicUsage,
type ShimCreateParams,
} from './codexShim.js'
import { buildAnthropicUsageFromRawUsage } from './cacheMetrics.js'
import { compressToolHistory } from './compressToolHistory.js'
import { fetchWithProxyRetry } from './fetchWithProxyRetry.js'
import {
getLocalFastPathConfig,
getLocalProviderRetryBaseUrls,
getGithubEndpointType,
isLocalProviderUrl,
resolveRuntimeCodexCredentials,
resolveProviderRequest,
shouldAttemptLocalToollessRetry,
type LocalFastPathConfig,
} from './providerConfig.js'
import {
buildOpenAICompatibilityErrorMessage,
classifyOpenAIHttpFailure,
classifyOpenAINetworkFailure,
} from './openaiErrorClassification.js'
import { sanitizeSchemaForOpenAICompat } from '../../utils/schemaSanitizer.js'
import { redactSecretValueForDisplay } from '../../utils/providerProfile.js'
import { shouldRedactUrlQueryParam } from '../../utils/urlRedaction.js'
import {
normalizeToolArguments,
hasToolFieldMapping,
} from './toolArgumentNormalization.js'
import { logApiCallStart, logApiCallEnd } from '../../utils/requestLogging.js'
import {
createStreamState,
processStreamChunk,
getStreamStats,
} from '../../utils/streamingOptimizer.js'
import { stableStringifyJson } from '../../utils/stableStringify.js'
type SecretValueSource = Partial<{
OPENAI_API_KEY: string
OPENAI_AUTH_HEADER_VALUE: string
CODEX_API_KEY: string
GEMINI_API_KEY: string
GOOGLE_API_KEY: string
GEMINI_ACCESS_TOKEN: string
MISTRAL_API_KEY: string
}>
const GITHUB_429_MAX_RETRIES = 3
const GITHUB_429_BASE_DELAY_SEC = 1
const GITHUB_429_MAX_DELAY_SEC = 32
const GEMINI_API_HOST = 'generativelanguage.googleapis.com'
const COPILOT_HEADERS: Record<string, string> = {
'User-Agent': 'GitHubCopilotChat/0.26.7',
'Editor-Version': 'vscode/1.99.3',
'Editor-Plugin-Version': 'copilot-chat/0.26.7',
'Copilot-Integration-Id': 'vscode-chat',
}
function isGithubModelsMode(): boolean {
return isEnvTruthy(process.env.CLAUDE_CODE_USE_GITHUB)
}
function filterAnthropicHeaders(
headers: Record<string, string> | undefined,
): Record<string, string> {
if (!headers) return {}
const filtered: Record<string, string> = {}
for (const [key, value] of Object.entries(headers)) {
const lower = key.toLowerCase()
if (
lower.startsWith('x-anthropic') ||
lower.startsWith('anthropic-') ||
lower.startsWith('x-claude') ||
lower === 'x-app' ||
lower === 'x-client-app' ||
lower === 'authorization' ||
lower === 'x-api-key' ||
lower === 'api-key'
) {
continue
}
filtered[key] = value
}
return filtered
}
function hasGeminiApiHost(baseUrl: string | undefined): boolean {
if (!baseUrl) return false
try {
return new URL(baseUrl).hostname.toLowerCase() === GEMINI_API_HOST
} catch {
return false
}
}
function isGeminiModelName(model: string | undefined): boolean {
const normalized = model?.trim().toLowerCase()
return (
normalized?.startsWith('google/gemini-') === true ||
normalized?.startsWith('gemini-') === true
)
}
function shouldPreserveGeminiThoughtSignature(
model: string | undefined,
baseUrl?: string,
): boolean {
return isGeminiMode() || hasGeminiApiHost(baseUrl) || isGeminiModelName(model)
}
function geminiThoughtSignatureFromExtraContent(
extraContent: unknown,
): string | undefined {
if (!extraContent || typeof extraContent !== 'object') return undefined
const google = (extraContent as Record<string, unknown>).google
if (!google || typeof google !== 'object') return undefined
const signature = (google as Record<string, unknown>).thought_signature
return typeof signature === 'string' && signature.length > 0 ? signature : undefined
}
function mergeGeminiThoughtSignature(
extraContent: Record<string, unknown> | undefined,
signature: string | undefined,
): Record<string, unknown> | undefined {
if (!signature) return extraContent
const existingGoogle =
extraContent?.google && typeof extraContent.google === 'object'
? extraContent.google as Record<string, unknown>
: {}
return {
...extraContent,
google: {
...existingGoogle,
thought_signature: signature,
},
}
}
function hasCerebrasApiHost(baseUrl: string | undefined): boolean {
if (!baseUrl) return false
try {
const host = new URL(baseUrl).hostname.toLowerCase()
return host === 'api.cerebras.ai' || host.endsWith('.cerebras.ai')
} catch {
return false
}
}
function normalizeDeepSeekReasoningEffort(
effort: 'low' | 'medium' | 'high' | 'xhigh',
): 'high' | 'max' {
return effort === 'xhigh' ? 'max' : 'high'
}
function formatRetryAfterHint(response: Response): string {
const ra = response.headers.get('retry-after')
return ra ? ` (Retry-After: ${ra})` : ''
}
function redactUrlForDiagnostics(url: string): string {
try {
const parsed = new URL(url)
if (parsed.username) {
parsed.username = 'redacted'
}
if (parsed.password) {
parsed.password = 'redacted'
}
for (const key of parsed.searchParams.keys()) {
if (shouldRedactUrlQueryParam(key)) {
parsed.searchParams.set(key, 'redacted')
}
}
const serialized = parsed.toString()
return redactSecretValueForDisplay(serialized, process.env as SecretValueSource) ?? serialized
} catch {
return redactSecretValueForDisplay(url, process.env as SecretValueSource) ?? url
}
}
function redactUrlsInMessage(message: string): string {
return message.replace(/https?:\/\/\S+/g, match => redactUrlForDiagnostics(match))
}
function sleepMs(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
// ---------------------------------------------------------------------------
// Types — minimal subset of Anthropic SDK types we need to produce
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Message format conversion: Anthropic → OpenAI
// ---------------------------------------------------------------------------
interface 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 }
extra_content?: Record<string, unknown>
}>
tool_call_id?: string
name?: string
/**
* Per-assistant-message chain-of-thought, attached when echoing an
* assistant message back to providers that require it (notably Moonshot:
* "thinking is enabled but reasoning_content is missing in assistant
* tool call message at index N" 400). Derived from the Anthropic thinking
* block captured when the original response was translated.
*/
reasoning_content?: string
}
interface OpenAITool {
type: 'function'
function: {
name: string
description: string
parameters: Record<string, unknown>
strict?: boolean
}
}
function convertSystemPrompt(
system: unknown,
): string {
if (!system) return ''
if (typeof system === 'string') return system
if (Array.isArray(system)) {
return system
.map((block: { type?: string; text?: string }) =>
block.type === 'text' ? block.text ?? '' : '',
)
// Drop the Anthropic billing/attribution block — it's only meaningful to
// Anthropic's `_parse_cc_header` and is dead weight (plus a churning
// per-build fingerprint that busts prefix KV cache) for OpenAI-compat
// providers like local Ollama / llama.cpp / Codex pass-throughs.
.filter(text => !text.startsWith('x-anthropic-billing-header'))
.join('\n\n')
}
return String(system)
}
function convertToolResultContent(
content: unknown,
isError?: boolean,
): string | Array<{ type: string; text?: string; image_url?: { url: string } }> {
if (typeof content === 'string') {
return isError ? `Error: ${content}` : content
}
if (!Array.isArray(content)) {
const text = JSON.stringify(content ?? '')
return isError ? `Error: ${text}` : text
}
const parts: Array<{
type: string
text?: string
image_url?: { url: string }
}> = []
for (const block of content) {
if (block?.type === 'text' && typeof block.text === 'string') {
parts.push({ type: 'text', text: block.text })
continue
}
if (block?.type === 'image') {
const source = block.source
if (source?.type === 'url' && source.url) {
parts.push({ type: 'image_url', image_url: { url: source.url } })
} else if (source?.type === 'base64' && source.media_type && source.data) {
parts.push({
type: 'image_url',
image_url: {
url: `data:${source.media_type};base64,${source.data}`,
},
})
}
continue
}
if (typeof block?.text === 'string') {
parts.push({ type: 'text', text: block.text })
}
}
if (parts.length === 0) return ''
if (parts.length === 1 && parts[0].type === 'text') {
const text = parts[0].text ?? ''
return isError ? `Error: ${text}` : text
}
// Collapse arrays of only text blocks into a single string for DeepSeek
// compatibility (issue #774). DeepSeek rejects arrays in role: "tool" messages.
const allText = parts.every(p => p.type === 'text')
if (allText) {
const text = parts.map(p => p.text ?? '').join('\n\n')
return isError ? `Error: ${text}` : text
}
if (isError && parts[0]?.type === 'text') {
parts[0] = { ...parts[0], text: `Error: ${parts[0].text ?? ''}` }
} else if (isError) {
parts.unshift({ type: 'text', text: 'Error:' })
}
return parts
}
function convertContentBlocks(
content: unknown,
): string | Array<{ type: string; text?: string; image_url?: { url: string } }> {
if (typeof content === 'string') return content
if (!Array.isArray(content)) return String(content ?? '')
const parts: Array<{ type: string; text?: string; image_url?: { url: string } }> = []
for (const block of content) {
switch (block.type) {
case 'text':
parts.push({ type: 'text', text: block.text ?? '' })
break
case 'image': {
const src = block.source
if (src?.type === 'base64') {
parts.push({
type: 'image_url',
image_url: {
url: `data:${src.media_type};base64,${src.data}`,
},
})
} else if (src?.type === 'url') {
parts.push({ type: 'image_url', image_url: { url: src.url } })
}
break
}
case 'tool_use':
// handled separately
break
case 'tool_result':
// handled separately
break
case 'thinking':
case 'redacted_thinking':
// Strip thinking blocks for OpenAI-compatible providers.
// These are Anthropic-specific content types that 3P providers
// don't understand. Serializing them as <thinking> text corrupts
// multi-turn context: the model sees the tags as part of its
// previous reply and may mimic or misattribute them.
break
default:
if (block.text) {
parts.push({ type: 'text', text: block.text })
}
}
}
if (parts.length === 0) return ''
if (parts.length === 1 && parts[0].type === 'text') return parts[0].text ?? ''
// Collapse arrays of only text blocks into a single string for DeepSeek
// compatibility (issue #774).
const allText = parts.every(p => p.type === 'text')
if (allText) {
return parts.map(p => p.text ?? '').join('\n\n')
}
return parts
}
function isGeminiMode(): boolean {
return (
isEnvTruthy(process.env.CLAUDE_CODE_USE_GEMINI) ||
hasGeminiApiHost(process.env.OPENAI_BASE_URL)
)
}
function hydrateOpenAIShimCompatibilityEnv(
processEnv: NodeJS.ProcessEnv = process.env,
): void {
// Provider selection, base URL defaults, and model defaults now flow
// through resolveProviderRequest(). The shim still needs a few legacy
// credential aliases because downstream auth/header paths read OPENAI_*.
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_GEMINI)) {
const geminiApiKey =
processEnv.GEMINI_API_KEY ?? processEnv.GOOGLE_API_KEY
if (geminiApiKey && !processEnv.OPENAI_API_KEY) {
processEnv.OPENAI_API_KEY = geminiApiKey
}
return
}
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_MISTRAL)) {
if (processEnv.MISTRAL_API_KEY && !processEnv.OPENAI_API_KEY) {
processEnv.OPENAI_API_KEY = processEnv.MISTRAL_API_KEY
}
return
}
if (isEnvTruthy(processEnv.CLAUDE_CODE_USE_GITHUB)) {
processEnv.OPENAI_API_KEY ??=
processEnv.GITHUB_TOKEN ?? processEnv.GH_TOKEN ?? ''
return
}
if (processEnv.BANKR_BASE_URL && !processEnv.OPENAI_BASE_URL) {
processEnv.OPENAI_BASE_URL = processEnv.BANKR_BASE_URL
}
if (processEnv.BANKR_MODEL && !processEnv.OPENAI_MODEL) {
processEnv.OPENAI_MODEL = processEnv.BANKR_MODEL
}
const routeCredential = resolveRouteCredentialValue({
processEnv,
baseUrl: processEnv.OPENAI_BASE_URL ?? processEnv.OPENAI_API_BASE,
})
if (routeCredential && !processEnv.OPENAI_API_KEY) {
processEnv.OPENAI_API_KEY = routeCredential
}
}
function convertMessages(
messages: Array<{
role: string
message?: { role?: string; content?: unknown }
content?: unknown
}>,
system: unknown,
options?: {
preserveReasoningContent?: boolean
reasoningContentFallback?: '' | 'omit'
preserveGeminiThoughtSignature?: boolean
},
): OpenAIMessage[] {
const preserveReasoningContent = options?.preserveReasoningContent === true
const reasoningContentFallback = options?.reasoningContentFallback
const preserveGeminiThoughtSignature = options?.preserveGeminiThoughtSignature === true
const result: OpenAIMessage[] = []
const knownToolCallIds = new Set<string>()
// Pre-scan for all tool results in the history to identify valid tool calls
const toolResultIds = new Set<string>()
for (const msg of messages) {
const inner = msg.message ?? msg
const content = (inner as { content?: unknown }).content
if (Array.isArray(content)) {
for (const block of content) {
if (
(block as { type?: string }).type === 'tool_result' &&
(block as { tool_use_id?: string }).tool_use_id
) {
toolResultIds.add((block as { tool_use_id: string }).tool_use_id)
}
}
}
}
// System message first
const sysText = convertSystemPrompt(system)
if (sysText) {
result.push({ role: 'system', content: sysText })
}
for (let i = 0; i < messages.length; i++) {
const msg = messages[i]
const isLastInHistory = i === messages.length - 1
// Claude Code wraps messages in { role, message: { role, content } }
const inner = msg.message ?? msg
const role = (inner as { role?: string }).role ?? msg.role
const content = (inner as { content?: unknown }).content
if (role === 'user') {
// Check for tool_result blocks in user messages
if (Array.isArray(content)) {
const toolResults = content.filter(
(b: { type?: string }) => b.type === 'tool_result',
)
const otherContent = content.filter(
(b: { type?: string }) => b.type !== 'tool_result',
)
// Emit tool results as tool messages, but ONLY if we have a matching tool_use ID.
// Mistral/OpenAI strictly require tool messages to follow an assistant message with tool_calls.
// If the user interrupted (ESC) and a synthetic tool_result was generated without a recorded tool_use,
// emitting it here would cause a "role must alternate" or "unexpected role" error.
for (const tr of toolResults) {
const id = tr.tool_use_id ?? 'unknown'
if (knownToolCallIds.has(id)) {
result.push({
role: 'tool',
tool_call_id: id,
content: convertToolResultContent(tr.content, tr.is_error),
})
} else {
logForDebugging(
`Dropping orphan tool_result for ID: ${id} to prevent API error`,
)
}
}
// Emit remaining user content
if (otherContent.length > 0) {
result.push({
role: 'user',
content: convertContentBlocks(otherContent),
})
}
} else {
result.push({
role: 'user',
content: convertContentBlocks(content),
})
}
} else if (role === 'assistant') {
// Check for tool_use blocks
if (Array.isArray(content)) {
const toolUses = content.filter(
(b: { type?: string }) => b.type === 'tool_use',
)
const thinkingBlock = content.find(
(b: { type?: string }) => b.type === 'thinking',
)
const textContent = content.filter(
(b: { type?: string }) => b.type !== 'tool_use' && b.type !== 'thinking',
)
const assistantMsg: OpenAIMessage = {
role: 'assistant',
content: (() => {
const c = convertContentBlocks(textContent)
return typeof c === 'string'
? c
: Array.isArray(c)
? c.map((p: { text?: string }) => p.text ?? '').join('')
: ''
})(),
}
// Providers that validate reasoning continuity (Moonshot/Kimi Code: "thinking
// is enabled but reasoning_content is missing in assistant tool call
// message at index N" 400) need the original chain-of-thought echoed
// back on each assistant message that carries a tool_call. We kept
// the thinking block on the Anthropic side; re-attach it here as the
// `reasoning_content` field on the outgoing OpenAI-shaped message.
// Gated per-provider because other endpoints either ignore the field
// (harmless) or strict-reject unknown fields (harmful).
if (preserveReasoningContent) {
const thinkingText = (thinkingBlock as { thinking?: string } | undefined)?.thinking
if (typeof thinkingText === 'string' && thinkingText.trim().length > 0) {
assistantMsg.reasoning_content = thinkingText
} else if (
toolUses.length > 0 &&
reasoningContentFallback === ''
) {
assistantMsg.reasoning_content = ''
}
}
if (toolUses.length > 0) {
const mappedToolCalls = toolUses
.map(
(tu: {
id?: string
name?: string
input?: unknown
extra_content?: Record<string, unknown>
signature?: string
}) => {
const id = tu.id ?? `call_${crypto.randomUUID().replace(/-/g, '')}`
// Only keep tool calls that have a corresponding result in the history,
// or if it's the last message (prefill scenario).
// Orphaned tool calls (e.g. from user interruption) cause 400 errors.
if (!toolResultIds.has(id) && !isLastInHistory) {
return null
}
knownToolCallIds.add(id)
const toolCall: NonNullable<
OpenAIMessage['tool_calls']
>[number] = {
id,
type: 'function' as const,
function: {
name: tu.name ?? 'unknown',
arguments:
typeof tu.input === 'string'
? tu.input
: JSON.stringify(tu.input ?? {}),
},
}
// Preserve existing extra_content if present
if (tu.extra_content) {
toolCall.extra_content = { ...tu.extra_content }
}
// Gemini OpenAI-compatible endpoints require Google's
// thought_signature to be replayed with prior function-call
// parts. Preserve only real signatures received from the
// provider; synthetic placeholders are rejected by GMI.
if (preserveGeminiThoughtSignature) {
const signature =
tu.signature ??
geminiThoughtSignatureFromExtraContent(tu.extra_content) ??
(thinkingBlock as { signature?: string } | undefined)?.signature
toolCall.extra_content = mergeGeminiThoughtSignature(
toolCall.extra_content,
signature,
)
}
return toolCall
},
)
.filter((tc): tc is NonNullable<typeof tc> => tc !== null)
if (mappedToolCalls.length > 0) {
assistantMsg.tool_calls = mappedToolCalls
}
}
// Only push assistant message if it has content or tool calls.
// Stripped thinking-only blocks from user interruptions are empty and cause 400s.
if (assistantMsg.content || assistantMsg.tool_calls?.length) {
result.push(assistantMsg)
}
} else {
const assistantMsg: OpenAIMessage = {
role: 'assistant',
content: (() => {
const c = convertContentBlocks(content)
return typeof c === 'string'
? c
: Array.isArray(c)
? c.map((p: { text?: string }) => p.text ?? '').join('')
: ''
})(),
}
if (assistantMsg.content) {
result.push(assistantMsg)
}
}
}
}
// Coalescing pass: merge consecutive messages of the same role.
// OpenAI/vLLM/Ollama require strict user↔assistant alternation.
// Multiple consecutive tool messages are allowed (assistant → tool* → user).
// Consecutive user or assistant messages must be merged to avoid Jinja
// template errors like "roles must alternate" (Devstral, Mistral models).
const coalesced: OpenAIMessage[] = []
for (const msg of result) {
const prev = coalesced[coalesced.length - 1]
// Mistral/Devstral: 'tool' message must be followed by an 'assistant' message.
// If a 'tool' result is followed by a 'user' message, we must inject a semantic
// assistant response to satisfy the strict role sequence:
// ... -> assistant (calls) -> tool (results) -> assistant (semantic) -> user (next)
if (prev && prev.role === 'tool' && msg.role === 'user') {
coalesced.push({
role: 'assistant',
content: '[Tool execution interrupted by user]',
})
}
const lastAfterPossibleInjection = coalesced[coalesced.length - 1]
if (
lastAfterPossibleInjection &&
lastAfterPossibleInjection.role === msg.role &&
msg.role !== 'tool' &&
msg.role !== 'system'
) {
const prevContent = lastAfterPossibleInjection.content
const curContent = msg.content
if (typeof prevContent === 'string' && typeof curContent === 'string') {
lastAfterPossibleInjection.content =
prevContent + (prevContent && curContent ? '\n' : '') + curContent
} else {
const toArray = (
c:
| string
| Array<{ type: string; text?: string; image_url?: { url: string } }>
| undefined,
): Array<{
type: string
text?: string
image_url?: { url: string }
}> => {
if (!c) return []
if (typeof c === 'string') return c ? [{ type: 'text', text: c }] : []
return c
}
lastAfterPossibleInjection.content = [
...toArray(prevContent),
...toArray(curContent),
]
}
if (msg.tool_calls?.length) {
lastAfterPossibleInjection.tool_calls = [
...(lastAfterPossibleInjection.tool_calls ?? []),
...msg.tool_calls,
]
}
} else {
coalesced.push(msg)
}
}
return coalesced
}
/**
* OpenAI requires every key in `properties` to also appear in `required`.
* Anthropic schemas often mark fields as optional (omitted from `required`),
* which causes 400 errors on OpenAI/Codex endpoints. This normalizes the
* schema by ensuring `required` is a superset of `properties` keys.
*/
function normalizeSchemaForOpenAI(
schema: Record<string, unknown>,
strict = true,
): Record<string, unknown> {
const record = sanitizeSchemaForOpenAICompat(schema)
if (record.type === 'object' && record.properties) {
const properties = record.properties as Record<string, Record<string, unknown>>
const existingRequired = Array.isArray(record.required) ? record.required as string[] : []
// Recurse into each property
const normalizedProps: Record<string, unknown> = {}
for (const [key, value] of Object.entries(properties)) {
normalizedProps[key] = normalizeSchemaForOpenAI(
value as Record<string, unknown>,
strict,
)
}
record.properties = normalizedProps
if (strict) {
// Keep only the properties that were originally marked required in the schema.
// Adding every property to required[] (the previous behaviour) caused strict
// OpenAI-compatible providers (Groq, Azure, etc.) to reject tool calls because
// the model correctly omits optional arguments — but the provider treats them
// as missing required fields and returns a 400 / tool_use_failed error.
record.required = existingRequired.filter(k => k in normalizedProps)
// additionalProperties: false is still required by strict-mode providers.
record.additionalProperties = false
} else {
// For Gemini: keep only existing required keys that are present in properties
record.required = existingRequired.filter(k => k in normalizedProps)
}
}
// Recurse into array items
if ('items' in record) {
if (Array.isArray(record.items)) {
record.items = (record.items as unknown[]).map(
item => normalizeSchemaForOpenAI(item as Record<string, unknown>, strict),
)
} else {
record.items = normalizeSchemaForOpenAI(record.items as Record<string, unknown>, strict)
}
}
// Recurse into combinators
for (const key of ['anyOf', 'oneOf', 'allOf'] as const) {
if (key in record && Array.isArray(record[key])) {
record[key] = (record[key] as unknown[]).map(
item => normalizeSchemaForOpenAI(item as Record<string, unknown>, strict),
)
}
}
return record
}
function convertTools(
tools: Array<{ name: string; description?: string; input_schema?: Record<string, unknown> }>,
options: { skipStrict?: boolean } = {},
): OpenAITool[] {
const isGemini = isGeminiMode()
const strict =
!isGemini &&
!isEnvTruthy(process.env.OPENCLAUDE_DISABLE_STRICT_TOOLS) &&
!options.skipStrict
return tools
.filter(t => t.name !== 'ToolSearchTool') // Not relevant for OpenAI
.map(t => {
const schema = { ...(t.input_schema ?? { type: 'object', properties: {} }) } as Record<string, unknown>
// For Codex/OpenAI: promote known Agent sub-fields into required[] only if
// they actually exist in properties (Gemini rejects required keys absent from properties).
if (t.name === 'Agent' && schema.properties) {
const props = schema.properties as Record<string, unknown>
if (!Array.isArray(schema.required)) schema.required = []
const req = schema.required as string[]
for (const key of ['message', 'subagent_type']) {
if (key in props && !req.includes(key)) req.push(key)
}
}
return {
type: 'function' as const,
function: {
name: t.name,
description: t.description ?? '',
parameters: normalizeSchemaForOpenAI(schema, strict),
},
}
})
}
// ---------------------------------------------------------------------------
// Streaming: OpenAI SSE → Anthropic stream events
// ---------------------------------------------------------------------------
interface OpenAIStreamChunk {
id: string
object: string
model: string
choices: Array<{
index: number
delta: {
role?: string
content?: string | null
reasoning_content?: string | null
extra_content?: Record<string, unknown>
tool_calls?: Array<{
index: number
id?: string
type?: string
function?: { name?: string; arguments?: string }
extra_content?: Record<string, unknown>
}>
}
finish_reason: string | null
}>
usage?: {
prompt_tokens?: number
completion_tokens?: number
total_tokens?: number
prompt_tokens_details?: {
cached_tokens?: number
}
}
}
function makeMessageId(): string {
return `msg_${crypto.randomUUID().replace(/-/g, '')}`
}
function convertChunkUsage(
usage: OpenAIStreamChunk['usage'] | undefined,
): Partial<AnthropicUsage> | undefined {
if (!usage) return undefined
// Delegates to the shared helper so this path, codexShim.makeUsage,
// the non-streaming response below, and the integration tests all
// produce byte-identical output for the same raw input.
return buildAnthropicUsageFromRawUsage(
usage as unknown as Record<string, unknown>,
)
}
const JSON_REPAIR_SUFFIXES = [
'}', '"}', ']}', '"]}', '}}', '"}}', ']}}', '"]}}', '"]}]}', '}]}'
]
const RAW_TOOL_CALLS_REQUESTED_PREFIX = 'Tool calls requested:'
type ParsedRawToolCall = {
id: string
name: string
argumentsJson: string
}
function couldBeRawToolCallsRequestedPrefix(text: string): boolean {
const trimmedStart = text.trimStart()
return (
RAW_TOOL_CALLS_REQUESTED_PREFIX.startsWith(trimmedStart) ||
trimmedStart.startsWith(RAW_TOOL_CALLS_REQUESTED_PREFIX)
)
}
function parseRawToolCallsRequestedText(text: string): ParsedRawToolCall[] | null {
const trimmed = text.trim()
if (!trimmed.startsWith(RAW_TOOL_CALLS_REQUESTED_PREFIX)) {
return null
}
const lines = trimmed
.slice(RAW_TOOL_CALLS_REQUESTED_PREFIX.length)
.split(/\r?\n/)
.map(line => line.trim())
.filter(Boolean)
if (lines.length === 0) return null
const toolCalls: ParsedRawToolCall[] = []
for (const line of lines) {
const match = line.match(
/^-\s*([A-Za-z_][A-Za-z0-9_.-]*)\(([\s\S]*)\)\s*\[id:\s*([^\]\s]+)\]\s*$/,
)
if (!match) return null
const [, name, rawArguments, id] = match
if (!name || !id || rawArguments === undefined) return null
const normalizedArguments = normalizeToolArguments(name, rawArguments)
toolCalls.push({
id,
name,
argumentsJson: JSON.stringify(normalizedArguments ?? {}),
})
}
return toolCalls.length > 0 ? toolCalls : null
}
function repairPossiblyTruncatedObjectJson(raw: string): string | null {
try {
const parsed = JSON.parse(raw)
return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? raw
: null
} catch {
for (const combo of JSON_REPAIR_SUFFIXES) {
try {
const repaired = raw + combo
const parsed = JSON.parse(repaired)
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
return repaired
}
} catch {}
}
return null