@namzu/openai 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +176 -0
- package/README.md +36 -7
- package/dist/client.d.ts +13 -3
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +100 -8
- package/dist/client.js.map +1 -1
- package/dist/codex.d.ts +21 -0
- package/dist/codex.d.ts.map +1 -0
- package/dist/codex.js +414 -0
- package/dist/codex.js.map +1 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7 -1
- package/dist/index.js.map +1 -1
- package/dist/types.d.ts +15 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/client.ts +126 -23
- package/src/codex.ts +490 -0
- package/src/index.ts +23 -2
- package/src/types.ts +17 -0
package/src/client.ts
CHANGED
|
@@ -4,12 +4,12 @@ import type {
|
|
|
4
4
|
LLMProvider,
|
|
5
5
|
ModelInfo,
|
|
6
6
|
ProviderCapabilities,
|
|
7
|
+
ReasoningEffort,
|
|
7
8
|
StreamChunk,
|
|
8
9
|
TokenUsage,
|
|
9
10
|
ToolChoice,
|
|
10
11
|
} from '@namzu/sdk'
|
|
11
12
|
import { assertThinkingUnsupported } from '@namzu/sdk'
|
|
12
|
-
import type { ThinkingConfig } from '@namzu/sdk'
|
|
13
13
|
import { toolResultToText } from '@namzu/sdk'
|
|
14
14
|
import {
|
|
15
15
|
ProviderRequestError,
|
|
@@ -21,6 +21,7 @@ import { attributionHeaders } from '@namzu/sdk'
|
|
|
21
21
|
import OpenAI from 'openai'
|
|
22
22
|
import type {
|
|
23
23
|
ChatCompletionContentPart,
|
|
24
|
+
ChatCompletionCreateParamsStreaming,
|
|
24
25
|
ChatCompletionMessageParam,
|
|
25
26
|
ChatCompletionTool,
|
|
26
27
|
ChatCompletionToolChoiceOption,
|
|
@@ -40,6 +41,93 @@ export const OPENAI_CAPABILITIES: ProviderCapabilities = {
|
|
|
40
41
|
supportsDocuments: true,
|
|
41
42
|
}
|
|
42
43
|
|
|
44
|
+
const GPT_5_EFFORT = [
|
|
45
|
+
'minimal',
|
|
46
|
+
'low',
|
|
47
|
+
'medium',
|
|
48
|
+
'high',
|
|
49
|
+
] as const satisfies readonly ReasoningEffort[]
|
|
50
|
+
const GPT_5_1_EFFORT = [
|
|
51
|
+
'none',
|
|
52
|
+
'low',
|
|
53
|
+
'medium',
|
|
54
|
+
'high',
|
|
55
|
+
] as const satisfies readonly ReasoningEffort[]
|
|
56
|
+
const GPT_5_2_TO_5_5_EFFORT = [
|
|
57
|
+
'none',
|
|
58
|
+
'low',
|
|
59
|
+
'medium',
|
|
60
|
+
'high',
|
|
61
|
+
'xhigh',
|
|
62
|
+
] as const satisfies readonly ReasoningEffort[]
|
|
63
|
+
const GPT_5_6_EFFORT = [
|
|
64
|
+
'none',
|
|
65
|
+
'low',
|
|
66
|
+
'medium',
|
|
67
|
+
'high',
|
|
68
|
+
'xhigh',
|
|
69
|
+
'max',
|
|
70
|
+
] as const satisfies readonly ReasoningEffort[]
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Exact reasoning-effort levels published for a recognized OpenAI model id.
|
|
74
|
+
*
|
|
75
|
+
* `undefined` is deliberately different from an empty array. This driver also
|
|
76
|
+
* serves compatible endpoints with model identifiers OpenAI does not publish;
|
|
77
|
+
* claiming that such a model has no effort levels would be as false as claiming
|
|
78
|
+
* that it accepts every level in the SDK vocabulary.
|
|
79
|
+
*/
|
|
80
|
+
export function openAIReasoningEffortLevels(model: string): readonly ReasoningEffort[] | undefined {
|
|
81
|
+
const normalized = model.toLowerCase()
|
|
82
|
+
if (/^gpt-5\.6(?:-(?:sol|terra|luna))?(?:-\d{4}-\d{2}-\d{2})?$/.test(normalized)) {
|
|
83
|
+
return GPT_5_6_EFFORT
|
|
84
|
+
}
|
|
85
|
+
if (/^gpt-5\.5(?:-\d{4}-\d{2}-\d{2})?$/.test(normalized)) {
|
|
86
|
+
return GPT_5_2_TO_5_5_EFFORT
|
|
87
|
+
}
|
|
88
|
+
if (/^gpt-5\.4(?:-(?:mini|nano))?(?:-\d{4}-\d{2}-\d{2})?$/.test(normalized)) {
|
|
89
|
+
return GPT_5_2_TO_5_5_EFFORT
|
|
90
|
+
}
|
|
91
|
+
if (/^gpt-5\.2(?:-\d{4}-\d{2}-\d{2})?$/.test(normalized)) {
|
|
92
|
+
return GPT_5_2_TO_5_5_EFFORT
|
|
93
|
+
}
|
|
94
|
+
if (/^gpt-5\.1(?:-\d{4}-\d{2}-\d{2})?$/.test(normalized)) {
|
|
95
|
+
return GPT_5_1_EFFORT
|
|
96
|
+
}
|
|
97
|
+
if (/^gpt-5(?:-(?:mini|nano))?(?:-\d{4}-\d{2}-\d{2})?$/.test(normalized)) {
|
|
98
|
+
return GPT_5_EFFORT
|
|
99
|
+
}
|
|
100
|
+
return undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function assertOpenAIReasoningEffort(model: string, effort: ReasoningEffort | undefined): void {
|
|
104
|
+
if (effort === undefined) return
|
|
105
|
+
const supported = openAIReasoningEffortLevels(model)
|
|
106
|
+
if (supported === undefined || supported.includes(effort)) return
|
|
107
|
+
throw new Error(
|
|
108
|
+
`OpenAIProvider: effort "${effort}" is not supported by model "${model}". Supported levels: ${supported.join(', ')}. Choose one of those levels or omit \`effort\`.`,
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Add the current effort vocabulary without widening any other vendor field.
|
|
114
|
+
*
|
|
115
|
+
* The installed vendor client declaration predates `max`, while the current
|
|
116
|
+
* API model catalogue already publishes it for GPT-5.6. `ultra` remains valid
|
|
117
|
+
* only for an unknown compatible endpoint here: every recognized official
|
|
118
|
+
* model rejects it above before this bounded cast is reached.
|
|
119
|
+
*/
|
|
120
|
+
function withReasoningEffort(
|
|
121
|
+
request: Omit<ChatCompletionCreateParamsStreaming, 'reasoning_effort'>,
|
|
122
|
+
effort: ReasoningEffort | undefined,
|
|
123
|
+
): ChatCompletionCreateParamsStreaming {
|
|
124
|
+
if (effort === undefined) return request
|
|
125
|
+
return {
|
|
126
|
+
...request,
|
|
127
|
+
reasoning_effort: effort,
|
|
128
|
+
} as ChatCompletionCreateParamsStreaming
|
|
129
|
+
}
|
|
130
|
+
|
|
43
131
|
type OpenAIFinishReason = 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'function_call'
|
|
44
132
|
|
|
45
133
|
type NamzuFinishReason = ChatCompletionResponse['finishReason']
|
|
@@ -112,7 +200,7 @@ export function assertThinkingSupported(params: {
|
|
|
112
200
|
// moved to the SDK where a new driver inherits it instead of re-deciding
|
|
113
201
|
// it. Kept as a named export because it is one, and removing it would
|
|
114
202
|
// break a caller for no gain.
|
|
115
|
-
assertThinkingUnsupported('OpenAIProvider',
|
|
203
|
+
assertThinkingUnsupported('OpenAIProvider', { thinking: params.thinking })
|
|
116
204
|
}
|
|
117
205
|
|
|
118
206
|
/**
|
|
@@ -267,7 +355,10 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
267
355
|
// Merged rather than replaced. Assigning `config.defaultHeaders`
|
|
268
356
|
// straight over would drop attribution for exactly the hosts that
|
|
269
357
|
// customise their transport.
|
|
270
|
-
clientOptions.defaultHeaders = {
|
|
358
|
+
clientOptions.defaultHeaders = {
|
|
359
|
+
...attributionHeaders(),
|
|
360
|
+
...(config.defaultHeaders ?? {}),
|
|
361
|
+
}
|
|
271
362
|
|
|
272
363
|
this.client = new OpenAI(clientOptions)
|
|
273
364
|
this.defaultModel = config.model
|
|
@@ -283,29 +374,37 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
283
374
|
return model
|
|
284
375
|
}
|
|
285
376
|
|
|
377
|
+
reasoningEffortLevelsFor(model: string): readonly ReasoningEffort[] | undefined {
|
|
378
|
+
return openAIReasoningEffortLevels(model)
|
|
379
|
+
}
|
|
380
|
+
|
|
286
381
|
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
287
382
|
const model = this.resolveModel(params)
|
|
288
383
|
assertThinkingSupported(params)
|
|
384
|
+
assertOpenAIReasoningEffort(model, params.effort)
|
|
289
385
|
|
|
290
386
|
let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>
|
|
291
387
|
try {
|
|
292
388
|
stream = await this.client.chat.completions.create(
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
389
|
+
withReasoningEffort(
|
|
390
|
+
{
|
|
391
|
+
model,
|
|
392
|
+
messages: toOpenAIMessages(params.messages),
|
|
393
|
+
stream: true,
|
|
394
|
+
stream_options: { include_usage: true },
|
|
395
|
+
tools: toOpenAITools(params),
|
|
396
|
+
tool_choice: formatToolChoice(params.toolChoice),
|
|
397
|
+
parallel_tool_calls: params.parallelToolCalls,
|
|
398
|
+
temperature: params.temperature,
|
|
399
|
+
max_tokens: params.maxTokens,
|
|
400
|
+
top_p: params.topP,
|
|
401
|
+
frequency_penalty: params.frequencyPenalty,
|
|
402
|
+
presence_penalty: params.presencePenalty,
|
|
403
|
+
stop: params.stop,
|
|
404
|
+
response_format: params.responseFormat,
|
|
405
|
+
},
|
|
406
|
+
params.effort,
|
|
407
|
+
),
|
|
309
408
|
// Per-request abort: a Stop tears the in-flight SSE request down.
|
|
310
409
|
{ signal: params.signal },
|
|
311
410
|
)
|
|
@@ -383,12 +482,16 @@ export class OpenAIProvider implements LLMProvider {
|
|
|
383
482
|
* question has to say so — otherwise it is reported unverifiable, which is
|
|
384
483
|
* the honest default and would be a regression here.
|
|
385
484
|
*/
|
|
386
|
-
async probeCredential(): Promise<void> {
|
|
387
|
-
|
|
485
|
+
async probeCredential(signal?: AbortSignal): Promise<void> {
|
|
486
|
+
signal?.throwIfAborted()
|
|
487
|
+
await this.client.models.list(signal ? { signal } : undefined)
|
|
488
|
+
signal?.throwIfAborted()
|
|
388
489
|
}
|
|
389
490
|
|
|
390
|
-
async listModels(): Promise<ModelInfo[]> {
|
|
391
|
-
|
|
491
|
+
async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
|
|
492
|
+
signal?.throwIfAborted()
|
|
493
|
+
const page = await this.client.models.list(signal ? { signal } : undefined)
|
|
494
|
+
signal?.throwIfAborted()
|
|
392
495
|
return page.data.map((m) => ({
|
|
393
496
|
id: m.id,
|
|
394
497
|
name: m.id,
|
package/src/codex.ts
ADDED
|
@@ -0,0 +1,490 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ChatCompletionParams,
|
|
3
|
+
LLMProvider,
|
|
4
|
+
ModelInfo,
|
|
5
|
+
ProviderCapabilities,
|
|
6
|
+
ProviderRoute,
|
|
7
|
+
ReasoningEffort,
|
|
8
|
+
StreamChunk,
|
|
9
|
+
TokenUsage,
|
|
10
|
+
} from '@namzu/sdk'
|
|
11
|
+
import {
|
|
12
|
+
ProviderRequestError,
|
|
13
|
+
attributionHeaders,
|
|
14
|
+
isCallerAbortError,
|
|
15
|
+
isProviderRequestError,
|
|
16
|
+
providerVendorError,
|
|
17
|
+
toolResultToText,
|
|
18
|
+
} from '@namzu/sdk'
|
|
19
|
+
import OpenAI from 'openai'
|
|
20
|
+
import type {
|
|
21
|
+
ResponseCreateParamsStreaming,
|
|
22
|
+
ResponseInputItem,
|
|
23
|
+
ResponseOutputItem,
|
|
24
|
+
ResponseStreamEvent,
|
|
25
|
+
Tool,
|
|
26
|
+
} from 'openai/resources/responses/responses'
|
|
27
|
+
|
|
28
|
+
import { openAIReasoningEffortLevels } from './client.js'
|
|
29
|
+
import type { CodexConfig } from './types.js'
|
|
30
|
+
|
|
31
|
+
export const CODEX_CAPABILITIES: ProviderCapabilities = {
|
|
32
|
+
supportsTools: true,
|
|
33
|
+
supportsStreaming: true,
|
|
34
|
+
supportsFunctionCalling: true,
|
|
35
|
+
supportsVision: false,
|
|
36
|
+
supportsDocuments: false,
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const DEFAULT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex'
|
|
40
|
+
|
|
41
|
+
interface CodexReplayState {
|
|
42
|
+
readonly kind: 'namzu.codex.responses'
|
|
43
|
+
readonly version: 1
|
|
44
|
+
readonly route: ProviderRoute
|
|
45
|
+
readonly content: string | null
|
|
46
|
+
readonly toolCalls: readonly {
|
|
47
|
+
readonly id: string
|
|
48
|
+
readonly name: string
|
|
49
|
+
readonly arguments: string
|
|
50
|
+
}[]
|
|
51
|
+
readonly items: readonly ResponseOutputItem[]
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function sameRoute(left: ProviderRoute, right: ProviderRoute): boolean {
|
|
55
|
+
return (
|
|
56
|
+
left.providerId === right.providerId &&
|
|
57
|
+
left.model === right.model &&
|
|
58
|
+
left.chainIndex === right.chainIndex
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function record(value: unknown): Record<string, unknown> | null {
|
|
63
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
64
|
+
? (value as Record<string, unknown>)
|
|
65
|
+
: null
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function isRoute(value: unknown): value is ProviderRoute {
|
|
69
|
+
const route = record(value)
|
|
70
|
+
return (
|
|
71
|
+
typeof route?.providerId === 'string' &&
|
|
72
|
+
typeof route.model === 'string' &&
|
|
73
|
+
Number.isInteger(route.chainIndex) &&
|
|
74
|
+
(route.chainIndex as number) >= 0
|
|
75
|
+
)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function durableToolCalls(
|
|
79
|
+
message: Extract<ChatCompletionParams['messages'][number], { role: 'assistant' }>,
|
|
80
|
+
): CodexReplayState['toolCalls'] {
|
|
81
|
+
return (message.toolCalls ?? []).map((call) => ({
|
|
82
|
+
id: call.id,
|
|
83
|
+
name: call.function.name,
|
|
84
|
+
arguments: call.function.arguments,
|
|
85
|
+
}))
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function isCodexReplayState(value: unknown): value is CodexReplayState {
|
|
89
|
+
const state = record(value)
|
|
90
|
+
if (
|
|
91
|
+
state?.kind !== 'namzu.codex.responses' ||
|
|
92
|
+
state.version !== 1 ||
|
|
93
|
+
!isRoute(state.route) ||
|
|
94
|
+
(state.content !== null && typeof state.content !== 'string') ||
|
|
95
|
+
!Array.isArray(state.toolCalls) ||
|
|
96
|
+
!Array.isArray(state.items)
|
|
97
|
+
) {
|
|
98
|
+
return false
|
|
99
|
+
}
|
|
100
|
+
return state.toolCalls.every((item) => {
|
|
101
|
+
const call = record(item)
|
|
102
|
+
return (
|
|
103
|
+
typeof call?.id === 'string' &&
|
|
104
|
+
typeof call.name === 'string' &&
|
|
105
|
+
typeof call.arguments === 'string'
|
|
106
|
+
)
|
|
107
|
+
})
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function replayItems(
|
|
111
|
+
message: Extract<ChatCompletionParams['messages'][number], { role: 'assistant' }>,
|
|
112
|
+
targetRoute: ProviderRoute,
|
|
113
|
+
): readonly ResponseOutputItem[] | null {
|
|
114
|
+
const source = message.source
|
|
115
|
+
if (!source || source.type !== 'model' || !sameRoute(source, targetRoute)) return null
|
|
116
|
+
const state = source.replayState
|
|
117
|
+
if (!isCodexReplayState(state) || !sameRoute(state.route, source)) return null
|
|
118
|
+
if (state.content !== message.content) return null
|
|
119
|
+
if (JSON.stringify(state.toolCalls) !== JSON.stringify(durableToolCalls(message))) return null
|
|
120
|
+
return state.items
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function toCodexInput(
|
|
124
|
+
messages: ChatCompletionParams['messages'],
|
|
125
|
+
targetRoute: ProviderRoute,
|
|
126
|
+
): ResponseInputItem[] {
|
|
127
|
+
const input: ResponseInputItem[] = []
|
|
128
|
+
for (const message of messages) {
|
|
129
|
+
if (message.role === 'system') continue
|
|
130
|
+
if (message.role === 'user') {
|
|
131
|
+
if (message.attachments && message.attachments.length > 0) {
|
|
132
|
+
throw new Error(
|
|
133
|
+
'CodexProvider: this transport does not yet admit image or document attachments. Remove the attachment or select a provider whose declared capabilities include it.',
|
|
134
|
+
)
|
|
135
|
+
}
|
|
136
|
+
input.push({ type: 'message', role: 'user', content: message.content })
|
|
137
|
+
continue
|
|
138
|
+
}
|
|
139
|
+
if (message.role === 'tool') {
|
|
140
|
+
input.push({
|
|
141
|
+
type: 'function_call_output',
|
|
142
|
+
call_id: message.toolCallId,
|
|
143
|
+
output: toolResultToText(message.content),
|
|
144
|
+
})
|
|
145
|
+
continue
|
|
146
|
+
}
|
|
147
|
+
const replayed = replayItems(message, targetRoute)
|
|
148
|
+
if (replayed) {
|
|
149
|
+
input.push(...(replayed as ResponseInputItem[]))
|
|
150
|
+
continue
|
|
151
|
+
}
|
|
152
|
+
if (message.content) {
|
|
153
|
+
input.push({
|
|
154
|
+
type: 'message',
|
|
155
|
+
role: 'assistant',
|
|
156
|
+
content: message.content,
|
|
157
|
+
})
|
|
158
|
+
}
|
|
159
|
+
for (const call of message.toolCalls ?? []) {
|
|
160
|
+
input.push({
|
|
161
|
+
type: 'function_call',
|
|
162
|
+
call_id: call.id,
|
|
163
|
+
name: call.function.name,
|
|
164
|
+
arguments: call.function.arguments,
|
|
165
|
+
})
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return input
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function toCodexTools(params: ChatCompletionParams): Tool[] | undefined {
|
|
172
|
+
if (!params.tools || params.tools.length === 0) return undefined
|
|
173
|
+
return params.tools.map((tool) => ({
|
|
174
|
+
type: 'function',
|
|
175
|
+
name: tool.function.name,
|
|
176
|
+
description: tool.function.description ?? '',
|
|
177
|
+
parameters: tool.function.parameters ?? {},
|
|
178
|
+
// The ChatGPT Codex backend validates `strict: true` against a narrower
|
|
179
|
+
// Responses schema than the Chat Completions endpoint. In particular,
|
|
180
|
+
// every composition branch needs an explicit type and every object
|
|
181
|
+
// property must also be required. Namzu model schemas deliberately keep
|
|
182
|
+
// conditional edit shapes optional and validate the selected shape at
|
|
183
|
+
// execution, so claiming strictness rejects the whole request before the
|
|
184
|
+
// model can answer. The Codex client uses the same boundary for its own
|
|
185
|
+
// tools: Responses function tools are sent with `strict: false` and tool
|
|
186
|
+
// inputs are validated by the runtime. `enforceToolInputSchema` remains a
|
|
187
|
+
// provider hint; this transport cannot truthfully consume it for Namzu's
|
|
188
|
+
// general tool-schema contract.
|
|
189
|
+
strict: false,
|
|
190
|
+
}))
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function responseUsage(usage: {
|
|
194
|
+
input_tokens?: number
|
|
195
|
+
output_tokens?: number
|
|
196
|
+
total_tokens?: number
|
|
197
|
+
input_tokens_details?: { cached_tokens?: number }
|
|
198
|
+
}): TokenUsage {
|
|
199
|
+
const promptTokens = usage.input_tokens ?? 0
|
|
200
|
+
const completionTokens = usage.output_tokens ?? 0
|
|
201
|
+
return {
|
|
202
|
+
promptTokens,
|
|
203
|
+
completionTokens,
|
|
204
|
+
totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
|
|
205
|
+
cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
|
|
206
|
+
cacheWriteTokens: 0,
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function buildRequest(
|
|
211
|
+
params: ChatCompletionParams,
|
|
212
|
+
model: string,
|
|
213
|
+
targetRoute: ProviderRoute,
|
|
214
|
+
): ResponseCreateParamsStreaming {
|
|
215
|
+
const supportedEffort = openAIReasoningEffortLevels(model)
|
|
216
|
+
if (
|
|
217
|
+
params.effort !== undefined &&
|
|
218
|
+
supportedEffort !== undefined &&
|
|
219
|
+
!supportedEffort.includes(params.effort)
|
|
220
|
+
) {
|
|
221
|
+
throw new Error(
|
|
222
|
+
`CodexProvider: effort "${params.effort}" is not supported by model "${model}". Supported levels: ${supportedEffort.join(', ')}. Choose one of those levels or omit \`effort\`.`,
|
|
223
|
+
)
|
|
224
|
+
}
|
|
225
|
+
if (params.thinking?.type === 'enabled') {
|
|
226
|
+
throw new Error(
|
|
227
|
+
'CodexProvider: manual thinking budgets are not a Responses API capability. Use adaptive thinking or omit `thinking`.',
|
|
228
|
+
)
|
|
229
|
+
}
|
|
230
|
+
if (params.thinking?.type === 'disabled' && params.effort !== 'none') {
|
|
231
|
+
throw new Error(
|
|
232
|
+
'CodexProvider: disabling reasoning requires `effort: "none"`; omitting that level would not prove reasoning was disabled.',
|
|
233
|
+
)
|
|
234
|
+
}
|
|
235
|
+
const instructions = params.messages
|
|
236
|
+
.filter((message) => message.role === 'system')
|
|
237
|
+
.map((message) => message.content)
|
|
238
|
+
.join('\n\n')
|
|
239
|
+
const request = {
|
|
240
|
+
model,
|
|
241
|
+
stream: true,
|
|
242
|
+
store: false,
|
|
243
|
+
instructions: instructions || undefined,
|
|
244
|
+
input: toCodexInput(params.messages, targetRoute),
|
|
245
|
+
// The Codex subscription request schema deliberately has no
|
|
246
|
+
// `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
|
|
247
|
+
// API control, but projecting it onto this route makes the whole request
|
|
248
|
+
// invalid; the backend owns the output budget here.
|
|
249
|
+
// The subscription Responses backend expects these three fields even for a
|
|
250
|
+
// turn that exposes no tools. The ordinary public Responses endpoint admits
|
|
251
|
+
// their omission, which is why the generated client types all make them
|
|
252
|
+
// optional; the Codex wire does not have the same defaulting contract.
|
|
253
|
+
tools: toCodexTools(params) ?? [],
|
|
254
|
+
tool_choice: (params.toolChoice ?? 'auto') as ResponseCreateParamsStreaming['tool_choice'],
|
|
255
|
+
parallel_tool_calls: params.parallelToolCalls ?? true,
|
|
256
|
+
include: ['reasoning.encrypted_content'],
|
|
257
|
+
...(params.effort !== undefined
|
|
258
|
+
? { reasoning: { effort: params.effort, summary: 'auto' } }
|
|
259
|
+
: params.thinking?.type === 'adaptive'
|
|
260
|
+
? { reasoning: { summary: 'auto' } }
|
|
261
|
+
: {}),
|
|
262
|
+
}
|
|
263
|
+
// The installed client declaration predates the current GPT-5.6 `max`
|
|
264
|
+
// vocabulary. The model-specific admission check above is the runtime
|
|
265
|
+
// boundary; this cast only bridges that vendor declaration lag.
|
|
266
|
+
return request as ResponseCreateParamsStreaming
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export class CodexProvider implements LLMProvider {
|
|
270
|
+
readonly id = 'codex'
|
|
271
|
+
readonly name = 'OpenAI Codex'
|
|
272
|
+
readonly capabilities = CODEX_CAPABILITIES
|
|
273
|
+
|
|
274
|
+
private client: OpenAI
|
|
275
|
+
private defaultModel?: string
|
|
276
|
+
|
|
277
|
+
constructor(config: CodexConfig) {
|
|
278
|
+
if (!config.accessToken) throw new Error('Codex access token is required.')
|
|
279
|
+
if (!config.accountId) throw new Error('Codex ChatGPT account id is required.')
|
|
280
|
+
this.client = new OpenAI({
|
|
281
|
+
apiKey: config.accessToken,
|
|
282
|
+
baseURL: config.baseURL ?? DEFAULT_CODEX_BASE_URL,
|
|
283
|
+
timeout: config.timeout,
|
|
284
|
+
defaultHeaders: {
|
|
285
|
+
...attributionHeaders(),
|
|
286
|
+
'ChatGPT-Account-Id': config.accountId,
|
|
287
|
+
originator: 'Codex Namzu',
|
|
288
|
+
'User-Agent': 'Codex Namzu/1.0',
|
|
289
|
+
...(config.defaultHeaders ?? {}),
|
|
290
|
+
},
|
|
291
|
+
})
|
|
292
|
+
this.defaultModel = config.model
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
private resolveModel(params: ChatCompletionParams): string {
|
|
296
|
+
const model = params.model || this.defaultModel
|
|
297
|
+
if (!model) throw new Error('CodexProvider: model is required.')
|
|
298
|
+
return model
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
reasoningEffortLevelsFor(model: string): readonly ReasoningEffort[] | undefined {
|
|
302
|
+
return openAIReasoningEffortLevels(model)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
|
|
306
|
+
const model = this.resolveModel(params)
|
|
307
|
+
const targetRoute = params.providerRoute ?? {
|
|
308
|
+
providerId: this.id,
|
|
309
|
+
model,
|
|
310
|
+
chainIndex: 0,
|
|
311
|
+
}
|
|
312
|
+
const request = buildRequest(params, model, targetRoute)
|
|
313
|
+
let stream: AsyncIterable<ResponseStreamEvent>
|
|
314
|
+
try {
|
|
315
|
+
stream = (await this.client.responses.create(request, {
|
|
316
|
+
signal: params.signal,
|
|
317
|
+
})) as AsyncIterable<ResponseStreamEvent>
|
|
318
|
+
} catch (error) {
|
|
319
|
+
if (isCallerAbortError(error, params.signal)) throw params.signal?.reason ?? error
|
|
320
|
+
if (isProviderRequestError(error)) throw error
|
|
321
|
+
throw providerVendorError({ providerId: this.id, error })
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const callIndex = new Map<string, number>()
|
|
325
|
+
let nextCallIndex = 0
|
|
326
|
+
let responseId = 'codex-response'
|
|
327
|
+
try {
|
|
328
|
+
for await (const event of stream) {
|
|
329
|
+
params.signal?.throwIfAborted()
|
|
330
|
+
switch (event.type) {
|
|
331
|
+
case 'response.created':
|
|
332
|
+
responseId = event.response.id
|
|
333
|
+
break
|
|
334
|
+
case 'response.output_text.delta':
|
|
335
|
+
yield { id: responseId, delta: { content: event.delta } }
|
|
336
|
+
break
|
|
337
|
+
case 'response.reasoning_summary_text.delta':
|
|
338
|
+
yield {
|
|
339
|
+
id: responseId,
|
|
340
|
+
delta: {
|
|
341
|
+
reasoning: {
|
|
342
|
+
index: event.output_index,
|
|
343
|
+
type: 'thinking',
|
|
344
|
+
text: event.delta,
|
|
345
|
+
},
|
|
346
|
+
},
|
|
347
|
+
}
|
|
348
|
+
break
|
|
349
|
+
case 'response.reasoning_summary_text.done':
|
|
350
|
+
yield {
|
|
351
|
+
id: responseId,
|
|
352
|
+
delta: {
|
|
353
|
+
reasoning: {
|
|
354
|
+
index: event.output_index,
|
|
355
|
+
type: 'thinking',
|
|
356
|
+
done: true,
|
|
357
|
+
},
|
|
358
|
+
},
|
|
359
|
+
}
|
|
360
|
+
break
|
|
361
|
+
case 'response.output_item.added':
|
|
362
|
+
if (event.item.type === 'function_call') {
|
|
363
|
+
const index = nextCallIndex++
|
|
364
|
+
callIndex.set(event.item.id ?? event.item.call_id, index)
|
|
365
|
+
callIndex.set(event.item.call_id, index)
|
|
366
|
+
yield {
|
|
367
|
+
id: responseId,
|
|
368
|
+
delta: {
|
|
369
|
+
toolCalls: [
|
|
370
|
+
{
|
|
371
|
+
index,
|
|
372
|
+
id: event.item.call_id,
|
|
373
|
+
type: 'function',
|
|
374
|
+
function: {
|
|
375
|
+
name: event.item.name,
|
|
376
|
+
arguments: event.item.arguments,
|
|
377
|
+
},
|
|
378
|
+
},
|
|
379
|
+
],
|
|
380
|
+
},
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
break
|
|
384
|
+
case 'response.function_call_arguments.delta': {
|
|
385
|
+
const index = callIndex.get(event.item_id) ?? event.output_index
|
|
386
|
+
yield {
|
|
387
|
+
id: responseId,
|
|
388
|
+
delta: {
|
|
389
|
+
toolCalls: [{ index, function: { arguments: event.delta } }],
|
|
390
|
+
},
|
|
391
|
+
}
|
|
392
|
+
break
|
|
393
|
+
}
|
|
394
|
+
case 'response.output_item.done':
|
|
395
|
+
if (event.item.type === 'function_call') {
|
|
396
|
+
yield {
|
|
397
|
+
id: responseId,
|
|
398
|
+
delta: {
|
|
399
|
+
toolCallEnd: {
|
|
400
|
+
index: callIndex.get(event.item.id ?? event.item.call_id) ?? event.output_index,
|
|
401
|
+
id: event.item.call_id,
|
|
402
|
+
},
|
|
403
|
+
},
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
break
|
|
407
|
+
case 'response.completed': {
|
|
408
|
+
const calls = event.response.output
|
|
409
|
+
.filter((item) => item.type === 'function_call')
|
|
410
|
+
.map((item) => ({
|
|
411
|
+
id: item.call_id,
|
|
412
|
+
name: item.name,
|
|
413
|
+
arguments: item.arguments,
|
|
414
|
+
}))
|
|
415
|
+
const content = event.response.output
|
|
416
|
+
.filter((item) => item.type === 'message')
|
|
417
|
+
.flatMap((item) => item.content)
|
|
418
|
+
.filter((item) => item.type === 'output_text')
|
|
419
|
+
.map((item) => item.text)
|
|
420
|
+
.join('')
|
|
421
|
+
const replayState: CodexReplayState = {
|
|
422
|
+
kind: 'namzu.codex.responses',
|
|
423
|
+
version: 1,
|
|
424
|
+
route: targetRoute,
|
|
425
|
+
content: content || null,
|
|
426
|
+
toolCalls: calls,
|
|
427
|
+
items: event.response.output,
|
|
428
|
+
}
|
|
429
|
+
yield {
|
|
430
|
+
id: event.response.id,
|
|
431
|
+
delta: {},
|
|
432
|
+
finishReason: calls.length > 0 ? 'tool_calls' : 'stop',
|
|
433
|
+
usage: responseUsage(event.response.usage ?? {}),
|
|
434
|
+
replayState,
|
|
435
|
+
}
|
|
436
|
+
break
|
|
437
|
+
}
|
|
438
|
+
case 'error':
|
|
439
|
+
case 'response.failed':
|
|
440
|
+
throw new ProviderRequestError({
|
|
441
|
+
kind: 'server',
|
|
442
|
+
providerId: this.id,
|
|
443
|
+
detail: 'the Codex Responses stream failed',
|
|
444
|
+
})
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
} catch (error) {
|
|
448
|
+
if (isCallerAbortError(error, params.signal)) throw params.signal?.reason ?? error
|
|
449
|
+
if (isProviderRequestError(error)) throw error
|
|
450
|
+
throw providerVendorError({ providerId: this.id, error })
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
|
|
455
|
+
signal?.throwIfAborted()
|
|
456
|
+
const response = (await this.client.get('/models?client_version=1.0.0', {
|
|
457
|
+
signal,
|
|
458
|
+
})) as { models?: unknown }
|
|
459
|
+
signal?.throwIfAborted()
|
|
460
|
+
if (!Array.isArray(response.models)) return []
|
|
461
|
+
return response.models.flatMap((value): ModelInfo[] => {
|
|
462
|
+
const item = record(value)
|
|
463
|
+
if (typeof item?.slug !== 'string' || item.slug.length === 0) return []
|
|
464
|
+
if (item.visibility === 'hide' || item.visibility === 'hidden') return []
|
|
465
|
+
return [
|
|
466
|
+
{
|
|
467
|
+
id: item.slug,
|
|
468
|
+
name: typeof item.display_name === 'string' ? item.display_name : item.slug,
|
|
469
|
+
inputPrice: 0,
|
|
470
|
+
outputPrice: 0,
|
|
471
|
+
supportsToolUse: true,
|
|
472
|
+
supportsStreaming: true,
|
|
473
|
+
},
|
|
474
|
+
]
|
|
475
|
+
})
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
async probeCredential(signal?: AbortSignal): Promise<void> {
|
|
479
|
+
await this.listModels(signal)
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async healthCheck(): Promise<boolean> {
|
|
483
|
+
try {
|
|
484
|
+
await this.probeCredential()
|
|
485
|
+
return true
|
|
486
|
+
} catch {
|
|
487
|
+
return false
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
}
|