@namzu/openai 1.4.0 → 2.0.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 CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - e3da442: Publish a model-owned reasoning-effort default alongside each exact menu and preserve it through retry, idle-timeout, and fallback decorators. Fallback chains expose a default only when every usable member agrees inside the common menu.
8
+
9
+ Add non-wrapping Shift+Up/Shift+Down and Alt+period/Alt+comma effort shortcuts to the interactive composer. An unset selection anchors at the provider-published default; unknown or disagreeing defaults require an explicit `/effort` choice.
10
+
11
+ Correct the subscription transport's model-specific effort contract. Recognized subscription models no longer offer or accept `none`, and only models whose current catalogue includes `ultra` accept it. Consumers that sent `none` to a recognized subscription model must omit effort or select one of the provider's published levels.
12
+
13
+ ## 1.5.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 09141a8: Reuse usable Claude and Codex device sessions before asking for a new credential, add a selectable Namzu-owned login for both subscriptions, and keep API keys optional. Bare `namzu login` no longer starts Claude implicitly; run `namzu login claude` or `namzu login codex`, or choose the provider from the interactive `/login` screen.
18
+
19
+ Add the account-routed `CodexProvider` and `registerCodex()` Responses transport to `@namzu/openai`. Hosts supply a user-authorized access token and ChatGPT account id, and remain responsible for discovery, refresh and persistence.
20
+
3
21
  ## 1.4.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -2,10 +2,10 @@
2
2
  type: Reference
3
3
  title: "@namzu/openai"
4
4
  description: >-
5
- Implements the kernel's `LLMProvider` interface over the official OpenAI
6
- SDK, and over any endpoint that speaks the same wire format.
5
+ Implements the kernel's `LLMProvider` interface for OpenAI API keys and
6
+ account-routed ChatGPT subscription sessions.
7
7
  tags: [readme, package, provider, openai]
8
- timestamp: 2026-08-17T00:00:00Z
8
+ timestamp: 2026-08-22T00:00:00Z
9
9
  status: active
10
10
  diataxis: reference
11
11
  -->
@@ -14,7 +14,7 @@ diataxis: reference
14
14
 
15
15
  <h1>@namzu/openai</h1>
16
16
 
17
- **The OpenAI model driver for [Namzu](https://github.com/cogitave/namzu).**
17
+ **OpenAI API-key and ChatGPT subscription drivers for [Namzu](https://github.com/cogitave/namzu).**
18
18
 
19
19
  [![npm](https://img.shields.io/npm/v/@namzu/openai.svg)](https://www.npmjs.com/package/@namzu/openai)
20
20
  [![build](https://github.com/cogitave/namzu/actions/workflows/ci.yml/badge.svg)](https://github.com/cogitave/namzu/actions/workflows/ci.yml)
@@ -26,9 +26,11 @@ diataxis: reference
26
26
 
27
27
  ---
28
28
 
29
- Implements the kernel's `LLMProvider` interface over the official OpenAI
30
- SDK, and over any endpoint that speaks the same wire format. Installed only
31
- if you use it — the kernel has no preferred vendor and no driver is a
29
+ Implements the kernel's `LLMProvider` interface over the official OpenAI SDK.
30
+ The package has two explicit transports: `OpenAIProvider` speaks Chat
31
+ Completions with an API key, while `CodexProvider` speaks the account-routed
32
+ Responses backend with a ChatGPT subscription session. Installed only if you
33
+ use either one — the kernel has no preferred vendor and no driver is a
32
34
  dependency of it.
33
35
 
34
36
  ## Install
@@ -41,6 +43,8 @@ pnpm add @namzu/sdk @namzu/openai
41
43
 
42
44
  ## Usage
43
45
 
46
+ ### OpenAI API key
47
+
44
48
  ```ts
45
49
  import { ProviderRegistry } from '@namzu/sdk'
46
50
  import { registerOpenAI } from '@namzu/openai'
@@ -66,6 +70,31 @@ for await (const chunk of provider.chatStream({
66
70
  stream collected. In practice the kernel's run loop calls it and hands you
67
71
  events.
68
72
 
73
+ ### ChatGPT subscription
74
+
75
+ ```ts
76
+ import { ProviderRegistry } from '@namzu/sdk'
77
+ import { registerCodex } from '@namzu/openai'
78
+
79
+ declare const accessToken: string
80
+ declare const accountId: string
81
+
82
+ registerCodex()
83
+
84
+ const { provider } = ProviderRegistry.create({
85
+ type: 'codex',
86
+ accessToken,
87
+ accountId,
88
+ model: 'gpt-5.6-luna',
89
+ })
90
+ ```
91
+
92
+ `accessToken` and `accountId` must come from a user-authorized ChatGPT session.
93
+ The driver does not discover, refresh or persist credentials; that ownership
94
+ belongs to the host. Namzu CLI can reuse a usable device session owned by the
95
+ Codex CLI, without copying it into Namzu's credential store, or create a
96
+ separate Namzu-owned device login when no external session is available.
97
+
69
98
  ## Documentation
70
99
 
71
100
  - [The OpenAI driver — configuration, refusals and compatible endpoints](https://github.com/cogitave/namzu/blob/main/docs/providers/openai.md)
@@ -0,0 +1,22 @@
1
+ import type { ChatCompletionParams, LLMProvider, ModelInfo, ProviderCapabilities, ProviderRoute, ReasoningEffort, StreamChunk } from '@namzu/sdk';
2
+ import type { ResponseInputItem, Tool } from 'openai/resources/responses/responses';
3
+ import type { CodexConfig } from './types.js';
4
+ export declare const CODEX_CAPABILITIES: ProviderCapabilities;
5
+ export declare function toCodexInput(messages: ChatCompletionParams['messages'], targetRoute: ProviderRoute): ResponseInputItem[];
6
+ export declare function toCodexTools(params: ChatCompletionParams): Tool[] | undefined;
7
+ export declare class CodexProvider implements LLMProvider {
8
+ readonly id = "codex";
9
+ readonly name = "OpenAI Codex";
10
+ readonly capabilities: ProviderCapabilities;
11
+ private client;
12
+ private defaultModel?;
13
+ constructor(config: CodexConfig);
14
+ private resolveModel;
15
+ reasoningEffortLevelsFor(model: string): readonly ReasoningEffort[] | undefined;
16
+ reasoningEffortDefaultFor(model: string): ReasoningEffort | undefined;
17
+ chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk>;
18
+ listModels(signal?: AbortSignal): Promise<ModelInfo[]>;
19
+ probeCredential(signal?: AbortSignal): Promise<void>;
20
+ healthCheck(): Promise<boolean>;
21
+ }
22
+ //# sourceMappingURL=codex.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex.d.ts","sourceRoot":"","sources":["../src/codex.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,oBAAoB,EACpB,WAAW,EACX,SAAS,EACT,oBAAoB,EACpB,aAAa,EACb,eAAe,EACf,WAAW,EAEX,MAAM,YAAY,CAAA;AAUnB,OAAO,KAAK,EAEX,iBAAiB,EAGjB,IAAI,EACJ,MAAM,sCAAsC,CAAA;AAE7C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE7C,eAAO,MAAM,kBAAkB,EAAE,oBAMhC,CAAA;AAiHD,wBAAgB,YAAY,CAC3B,QAAQ,EAAE,oBAAoB,CAAC,UAAU,CAAC,EAC1C,WAAW,EAAE,aAAa,GACxB,iBAAiB,EAAE,CA2CrB;AAED,wBAAgB,YAAY,CAAC,MAAM,EAAE,oBAAoB,GAAG,IAAI,EAAE,GAAG,SAAS,CAoB7E;AA8ED,qBAAa,aAAc,YAAW,WAAW;IAChD,QAAQ,CAAC,EAAE,WAAU;IACrB,QAAQ,CAAC,IAAI,kBAAiB;IAC9B,QAAQ,CAAC,YAAY,uBAAqB;IAE1C,OAAO,CAAC,MAAM,CAAQ;IACtB,OAAO,CAAC,YAAY,CAAC,CAAQ;gBAEjB,MAAM,EAAE,WAAW;IAkB/B,OAAO,CAAC,YAAY;IAMpB,wBAAwB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,eAAe,EAAE,GAAG,SAAS;IAI/E,yBAAyB,CAAC,KAAK,EAAE,MAAM,GAAG,eAAe,GAAG,SAAS;IAI9D,UAAU,CAAC,MAAM,EAAE,oBAAoB,GAAG,aAAa,CAAC,WAAW,CAAC;IAqJrE,UAAU,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAwBtD,eAAe,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IAIpD,WAAW,IAAI,OAAO,CAAC,OAAO,CAAC;CAQrC"}
package/dist/codex.js ADDED
@@ -0,0 +1,435 @@
1
+ import { ProviderRequestError, attributionHeaders, isCallerAbortError, isProviderRequestError, providerVendorError, toolResultToText, } from '@namzu/sdk';
2
+ import OpenAI from 'openai';
3
+ export const CODEX_CAPABILITIES = {
4
+ supportsTools: true,
5
+ supportsStreaming: true,
6
+ supportsFunctionCalling: true,
7
+ supportsVision: false,
8
+ supportsDocuments: false,
9
+ };
10
+ const DEFAULT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex';
11
+ const SOL_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
12
+ const TERRA_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'];
13
+ const LUNA_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
14
+ const STANDARD_LEVELS = ['low', 'medium', 'high', 'xhigh'];
15
+ const SUBSCRIPTION_REASONING_PROFILES = new Map([
16
+ ['gpt-5.6-sol', { default: 'low', levels: SOL_LEVELS }],
17
+ ['gpt-5.6-terra', { default: 'medium', levels: TERRA_LEVELS }],
18
+ ['gpt-5.6-luna', { default: 'medium', levels: LUNA_LEVELS }],
19
+ ['gpt-daybreak-blue-latest', { default: 'low', levels: SOL_LEVELS }],
20
+ ['gpt-daybreak-red-latest', { default: 'medium', levels: TERRA_LEVELS }],
21
+ ['gpt-5.5', { default: 'medium', levels: STANDARD_LEVELS }],
22
+ ['gpt-5.4', { default: 'medium', levels: STANDARD_LEVELS }],
23
+ ['gpt-5.4-mini', { default: 'medium', levels: STANDARD_LEVELS }],
24
+ ['gpt-5.2', { default: 'medium', levels: STANDARD_LEVELS }],
25
+ ['codex-auto-review', { default: 'medium', levels: LUNA_LEVELS }],
26
+ ]);
27
+ function subscriptionReasoningProfile(model) {
28
+ return SUBSCRIPTION_REASONING_PROFILES.get(model.toLowerCase());
29
+ }
30
+ function sameRoute(left, right) {
31
+ return (left.providerId === right.providerId &&
32
+ left.model === right.model &&
33
+ left.chainIndex === right.chainIndex);
34
+ }
35
+ function record(value) {
36
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
37
+ ? value
38
+ : null;
39
+ }
40
+ function isRoute(value) {
41
+ const route = record(value);
42
+ return (typeof route?.providerId === 'string' &&
43
+ typeof route.model === 'string' &&
44
+ Number.isInteger(route.chainIndex) &&
45
+ route.chainIndex >= 0);
46
+ }
47
+ function durableToolCalls(message) {
48
+ return (message.toolCalls ?? []).map((call) => ({
49
+ id: call.id,
50
+ name: call.function.name,
51
+ arguments: call.function.arguments,
52
+ }));
53
+ }
54
+ function isCodexReplayState(value) {
55
+ const state = record(value);
56
+ if (state?.kind !== 'namzu.codex.responses' ||
57
+ state.version !== 1 ||
58
+ !isRoute(state.route) ||
59
+ (state.content !== null && typeof state.content !== 'string') ||
60
+ !Array.isArray(state.toolCalls) ||
61
+ !Array.isArray(state.items)) {
62
+ return false;
63
+ }
64
+ return state.toolCalls.every((item) => {
65
+ const call = record(item);
66
+ return (typeof call?.id === 'string' &&
67
+ typeof call.name === 'string' &&
68
+ typeof call.arguments === 'string');
69
+ });
70
+ }
71
+ function replayItems(message, targetRoute) {
72
+ const source = message.source;
73
+ if (!source || source.type !== 'model' || !sameRoute(source, targetRoute))
74
+ return null;
75
+ const state = source.replayState;
76
+ if (!isCodexReplayState(state) || !sameRoute(state.route, source))
77
+ return null;
78
+ if (state.content !== message.content)
79
+ return null;
80
+ if (JSON.stringify(state.toolCalls) !== JSON.stringify(durableToolCalls(message)))
81
+ return null;
82
+ return state.items;
83
+ }
84
+ export function toCodexInput(messages, targetRoute) {
85
+ const input = [];
86
+ for (const message of messages) {
87
+ if (message.role === 'system')
88
+ continue;
89
+ if (message.role === 'user') {
90
+ if (message.attachments && message.attachments.length > 0) {
91
+ throw new Error('CodexProvider: this transport does not yet admit image or document attachments. Remove the attachment or select a provider whose declared capabilities include it.');
92
+ }
93
+ input.push({ type: 'message', role: 'user', content: message.content });
94
+ continue;
95
+ }
96
+ if (message.role === 'tool') {
97
+ input.push({
98
+ type: 'function_call_output',
99
+ call_id: message.toolCallId,
100
+ output: toolResultToText(message.content),
101
+ });
102
+ continue;
103
+ }
104
+ const replayed = replayItems(message, targetRoute);
105
+ if (replayed) {
106
+ input.push(...replayed);
107
+ continue;
108
+ }
109
+ if (message.content) {
110
+ input.push({
111
+ type: 'message',
112
+ role: 'assistant',
113
+ content: message.content,
114
+ });
115
+ }
116
+ for (const call of message.toolCalls ?? []) {
117
+ input.push({
118
+ type: 'function_call',
119
+ call_id: call.id,
120
+ name: call.function.name,
121
+ arguments: call.function.arguments,
122
+ });
123
+ }
124
+ }
125
+ return input;
126
+ }
127
+ export function toCodexTools(params) {
128
+ if (!params.tools || params.tools.length === 0)
129
+ return undefined;
130
+ return params.tools.map((tool) => ({
131
+ type: 'function',
132
+ name: tool.function.name,
133
+ description: tool.function.description ?? '',
134
+ parameters: tool.function.parameters ?? {},
135
+ // The ChatGPT Codex backend validates `strict: true` against a narrower
136
+ // Responses schema than the Chat Completions endpoint. In particular,
137
+ // every composition branch needs an explicit type and every object
138
+ // property must also be required. Namzu model schemas deliberately keep
139
+ // conditional edit shapes optional and validate the selected shape at
140
+ // execution, so claiming strictness rejects the whole request before the
141
+ // model can answer. The Codex client uses the same boundary for its own
142
+ // tools: Responses function tools are sent with `strict: false` and tool
143
+ // inputs are validated by the runtime. `enforceToolInputSchema` remains a
144
+ // provider hint; this transport cannot truthfully consume it for Namzu's
145
+ // general tool-schema contract.
146
+ strict: false,
147
+ }));
148
+ }
149
+ function responseUsage(usage) {
150
+ const promptTokens = usage.input_tokens ?? 0;
151
+ const completionTokens = usage.output_tokens ?? 0;
152
+ return {
153
+ promptTokens,
154
+ completionTokens,
155
+ totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
156
+ cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
157
+ cacheWriteTokens: 0,
158
+ };
159
+ }
160
+ function buildRequest(params, model, targetRoute) {
161
+ const supportedEffort = subscriptionReasoningProfile(model)?.levels;
162
+ if (params.effort !== undefined &&
163
+ supportedEffort !== undefined &&
164
+ !supportedEffort.includes(params.effort)) {
165
+ throw new Error(`CodexProvider: effort "${params.effort}" is not supported by model "${model}". Supported levels: ${supportedEffort.join(', ')}. Choose one of those levels or omit \`effort\`.`);
166
+ }
167
+ if (params.thinking?.type === 'enabled') {
168
+ throw new Error('CodexProvider: manual thinking budgets are not a Responses API capability. Use adaptive thinking or omit `thinking`.');
169
+ }
170
+ if (params.thinking?.type === 'disabled' && params.effort !== 'none') {
171
+ throw new Error('CodexProvider: disabling reasoning requires `effort: "none"`; omitting that level would not prove reasoning was disabled.');
172
+ }
173
+ const instructions = params.messages
174
+ .filter((message) => message.role === 'system')
175
+ .map((message) => message.content)
176
+ .join('\n\n');
177
+ const request = {
178
+ model,
179
+ stream: true,
180
+ store: false,
181
+ instructions: instructions || undefined,
182
+ input: toCodexInput(params.messages, targetRoute),
183
+ // The Codex subscription request schema deliberately has no
184
+ // `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
185
+ // API control, but projecting it onto this route makes the whole request
186
+ // invalid; the backend owns the output budget here.
187
+ // The subscription Responses backend expects these three fields even for a
188
+ // turn that exposes no tools. The ordinary public Responses endpoint admits
189
+ // their omission, which is why the generated client types all make them
190
+ // optional; the Codex wire does not have the same defaulting contract.
191
+ tools: toCodexTools(params) ?? [],
192
+ tool_choice: (params.toolChoice ?? 'auto'),
193
+ parallel_tool_calls: params.parallelToolCalls ?? true,
194
+ include: ['reasoning.encrypted_content'],
195
+ ...(params.effort !== undefined
196
+ ? { reasoning: { effort: params.effort, summary: 'auto' } }
197
+ : params.thinking?.type === 'adaptive'
198
+ ? { reasoning: { summary: 'auto' } }
199
+ : {}),
200
+ };
201
+ // The installed client declaration predates the current advanced effort
202
+ // vocabulary. The model-specific admission check above is the runtime
203
+ // boundary; this cast only bridges that declaration lag.
204
+ return request;
205
+ }
206
+ export class CodexProvider {
207
+ id = 'codex';
208
+ name = 'OpenAI Codex';
209
+ capabilities = CODEX_CAPABILITIES;
210
+ client;
211
+ defaultModel;
212
+ constructor(config) {
213
+ if (!config.accessToken)
214
+ throw new Error('Codex access token is required.');
215
+ if (!config.accountId)
216
+ throw new Error('Codex ChatGPT account id is required.');
217
+ this.client = new OpenAI({
218
+ apiKey: config.accessToken,
219
+ baseURL: config.baseURL ?? DEFAULT_CODEX_BASE_URL,
220
+ timeout: config.timeout,
221
+ defaultHeaders: {
222
+ ...attributionHeaders(),
223
+ 'ChatGPT-Account-Id': config.accountId,
224
+ originator: 'Codex Namzu',
225
+ 'User-Agent': 'Codex Namzu/1.0',
226
+ ...(config.defaultHeaders ?? {}),
227
+ },
228
+ });
229
+ this.defaultModel = config.model;
230
+ }
231
+ resolveModel(params) {
232
+ const model = params.model || this.defaultModel;
233
+ if (!model)
234
+ throw new Error('CodexProvider: model is required.');
235
+ return model;
236
+ }
237
+ reasoningEffortLevelsFor(model) {
238
+ return subscriptionReasoningProfile(model)?.levels;
239
+ }
240
+ reasoningEffortDefaultFor(model) {
241
+ return subscriptionReasoningProfile(model)?.default;
242
+ }
243
+ async *chatStream(params) {
244
+ const model = this.resolveModel(params);
245
+ const targetRoute = params.providerRoute ?? {
246
+ providerId: this.id,
247
+ model,
248
+ chainIndex: 0,
249
+ };
250
+ const request = buildRequest(params, model, targetRoute);
251
+ let stream;
252
+ try {
253
+ stream = (await this.client.responses.create(request, {
254
+ signal: params.signal,
255
+ }));
256
+ }
257
+ catch (error) {
258
+ if (isCallerAbortError(error, params.signal))
259
+ throw params.signal?.reason ?? error;
260
+ if (isProviderRequestError(error))
261
+ throw error;
262
+ throw providerVendorError({ providerId: this.id, error });
263
+ }
264
+ const callIndex = new Map();
265
+ let nextCallIndex = 0;
266
+ let responseId = 'codex-response';
267
+ try {
268
+ for await (const event of stream) {
269
+ params.signal?.throwIfAborted();
270
+ switch (event.type) {
271
+ case 'response.created':
272
+ responseId = event.response.id;
273
+ break;
274
+ case 'response.output_text.delta':
275
+ yield { id: responseId, delta: { content: event.delta } };
276
+ break;
277
+ case 'response.reasoning_summary_text.delta':
278
+ yield {
279
+ id: responseId,
280
+ delta: {
281
+ reasoning: {
282
+ index: event.output_index,
283
+ type: 'thinking',
284
+ text: event.delta,
285
+ },
286
+ },
287
+ };
288
+ break;
289
+ case 'response.reasoning_summary_text.done':
290
+ yield {
291
+ id: responseId,
292
+ delta: {
293
+ reasoning: {
294
+ index: event.output_index,
295
+ type: 'thinking',
296
+ done: true,
297
+ },
298
+ },
299
+ };
300
+ break;
301
+ case 'response.output_item.added':
302
+ if (event.item.type === 'function_call') {
303
+ const index = nextCallIndex++;
304
+ callIndex.set(event.item.id ?? event.item.call_id, index);
305
+ callIndex.set(event.item.call_id, index);
306
+ yield {
307
+ id: responseId,
308
+ delta: {
309
+ toolCalls: [
310
+ {
311
+ index,
312
+ id: event.item.call_id,
313
+ type: 'function',
314
+ function: {
315
+ name: event.item.name,
316
+ arguments: event.item.arguments,
317
+ },
318
+ },
319
+ ],
320
+ },
321
+ };
322
+ }
323
+ break;
324
+ case 'response.function_call_arguments.delta': {
325
+ const index = callIndex.get(event.item_id) ?? event.output_index;
326
+ yield {
327
+ id: responseId,
328
+ delta: {
329
+ toolCalls: [{ index, function: { arguments: event.delta } }],
330
+ },
331
+ };
332
+ break;
333
+ }
334
+ case 'response.output_item.done':
335
+ if (event.item.type === 'function_call') {
336
+ yield {
337
+ id: responseId,
338
+ delta: {
339
+ toolCallEnd: {
340
+ index: callIndex.get(event.item.id ?? event.item.call_id) ?? event.output_index,
341
+ id: event.item.call_id,
342
+ },
343
+ },
344
+ };
345
+ }
346
+ break;
347
+ case 'response.completed': {
348
+ const calls = event.response.output
349
+ .filter((item) => item.type === 'function_call')
350
+ .map((item) => ({
351
+ id: item.call_id,
352
+ name: item.name,
353
+ arguments: item.arguments,
354
+ }));
355
+ const content = event.response.output
356
+ .filter((item) => item.type === 'message')
357
+ .flatMap((item) => item.content)
358
+ .filter((item) => item.type === 'output_text')
359
+ .map((item) => item.text)
360
+ .join('');
361
+ const replayState = {
362
+ kind: 'namzu.codex.responses',
363
+ version: 1,
364
+ route: targetRoute,
365
+ content: content || null,
366
+ toolCalls: calls,
367
+ items: event.response.output,
368
+ };
369
+ yield {
370
+ id: event.response.id,
371
+ delta: {},
372
+ finishReason: calls.length > 0 ? 'tool_calls' : 'stop',
373
+ usage: responseUsage(event.response.usage ?? {}),
374
+ replayState,
375
+ };
376
+ break;
377
+ }
378
+ case 'error':
379
+ case 'response.failed':
380
+ throw new ProviderRequestError({
381
+ kind: 'server',
382
+ providerId: this.id,
383
+ detail: 'the Codex Responses stream failed',
384
+ });
385
+ }
386
+ }
387
+ }
388
+ catch (error) {
389
+ if (isCallerAbortError(error, params.signal))
390
+ throw params.signal?.reason ?? error;
391
+ if (isProviderRequestError(error))
392
+ throw error;
393
+ throw providerVendorError({ providerId: this.id, error });
394
+ }
395
+ }
396
+ async listModels(signal) {
397
+ signal?.throwIfAborted();
398
+ const response = (await this.client.get('/models?client_version=1.0.0', {
399
+ signal,
400
+ }));
401
+ signal?.throwIfAborted();
402
+ if (!Array.isArray(response.models))
403
+ return [];
404
+ return response.models.flatMap((value) => {
405
+ const item = record(value);
406
+ if (typeof item?.slug !== 'string' || item.slug.length === 0)
407
+ return [];
408
+ if (item.visibility === 'hide' || item.visibility === 'hidden')
409
+ return [];
410
+ return [
411
+ {
412
+ id: item.slug,
413
+ name: typeof item.display_name === 'string' ? item.display_name : item.slug,
414
+ inputPrice: 0,
415
+ outputPrice: 0,
416
+ supportsToolUse: true,
417
+ supportsStreaming: true,
418
+ },
419
+ ];
420
+ });
421
+ }
422
+ async probeCredential(signal) {
423
+ await this.listModels(signal);
424
+ }
425
+ async healthCheck() {
426
+ try {
427
+ await this.probeCredential();
428
+ return true;
429
+ }
430
+ catch {
431
+ return false;
432
+ }
433
+ }
434
+ }
435
+ //# sourceMappingURL=codex.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codex.js","sourceRoot":"","sources":["../src/codex.ts"],"names":[],"mappings":"AAUA,OAAO,EACN,oBAAoB,EACpB,kBAAkB,EAClB,kBAAkB,EAClB,sBAAsB,EACtB,mBAAmB,EACnB,gBAAgB,GAChB,MAAM,YAAY,CAAA;AACnB,OAAO,MAAM,MAA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AAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAA;IAC9B,CAAC;IAED,KAAK,CAAC,WAAW;QAChB,IAAI,CAAC;YACJ,MAAM,IAAI,CAAC,eAAe,EAAE,CAAA;YAC5B,OAAO,IAAI,CAAA;QACZ,CAAC;QAAC,MAAM,CAAC;YACR,OAAO,KAAK,CAAA;QACb,CAAC;IACF,CAAC;CACD"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,14 @@
1
1
  import { type RegisterOptions } from '@namzu/sdk';
2
2
  import type { OpenAIProviderConfig } from './types.js';
3
+ import type { CodexProviderConfig } from './types.js';
3
4
  declare module '@namzu/sdk' {
4
5
  interface ProviderConfigRegistry {
5
6
  openai: OpenAIProviderConfig;
7
+ codex: CodexProviderConfig;
6
8
  }
7
9
  }
10
+ /** Register the ChatGPT subscription-backed Codex Responses transport. */
11
+ export declare function registerCodex(options?: RegisterOptions): void;
8
12
  /**
9
13
  * Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
10
14
  * `ProviderRegistry`. Call once at app startup before
@@ -14,6 +18,7 @@ declare module '@namzu/sdk' {
14
18
  * Pass `{ replace: true }` to override.
15
19
  */
16
20
  export declare function registerOpenAI(options?: RegisterOptions): void;
17
- export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels } from './client.js';
18
- export type { OpenAIConfig, OpenAIProviderConfig } from './types.js';
21
+ export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels, } from './client.js';
22
+ export { CODEX_CAPABILITIES, CodexProvider, } from './codex.js';
23
+ export type { CodexConfig, CodexProviderConfig, OpenAIConfig, OpenAIProviderConfig, } from './types.js';
19
24
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAEnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AAItD,OAAO,QAAQ,YAAY,CAAC;IAC3B,UAAU,sBAAsB;QAC/B,MAAM,EAAE,oBAAoB,CAAA;KAC5B;CACD;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAE9D;AAED,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAC9F,YAAY,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,eAAe,EAAE,MAAM,YAAY,CAAA;AAGnE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AACtD,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAA;AAIrD,OAAO,QAAQ,YAAY,CAAC;IAC3B,UAAU,sBAAsB;QAC/B,MAAM,EAAE,oBAAoB,CAAA;QAC5B,KAAK,EAAE,mBAAmB,CAAA;KAC1B;CACD;AAED,0EAA0E;AAC1E,wBAAgB,aAAa,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAE7D;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,OAAO,CAAC,EAAE,eAAe,GAAG,IAAI,CAE9D;AAED,OAAO,EACN,mBAAmB,EACnB,cAAc,EACd,2BAA2B,GAC3B,MAAM,aAAa,CAAA;AACpB,OAAO,EACN,kBAAkB,EAClB,aAAa,GACb,MAAM,YAAY,CAAA;AACnB,YAAY,EACX,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,GACpB,MAAM,YAAY,CAAA"}
package/dist/index.js CHANGED
@@ -1,5 +1,10 @@
1
1
  import { ProviderRegistry } from '@namzu/sdk';
2
2
  import { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js';
3
+ import { CODEX_CAPABILITIES, CodexProvider } from './codex.js';
4
+ /** Register the ChatGPT subscription-backed Codex Responses transport. */
5
+ export function registerCodex(options) {
6
+ ProviderRegistry.register('codex', CodexProvider, CODEX_CAPABILITIES, options);
7
+ }
3
8
  /**
4
9
  * Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
5
10
  * `ProviderRegistry`. Call once at app startup before
@@ -11,5 +16,6 @@ import { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js';
11
16
  export function registerOpenAI(options) {
12
17
  ProviderRegistry.register('openai', OpenAIProvider, OPENAI_CAPABILITIES, options);
13
18
  }
14
- export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels } from './client.js';
19
+ export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels, } from './client.js';
20
+ export { CODEX_CAPABILITIES, CodexProvider, } from './codex.js';
15
21
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AACnE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AAWjE;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,OAAyB;IACvD,gBAAgB,CAAC,QAAQ,CAAC,QAAQ,EAAE,cAAc,EAAE,mBAAmB,EAAE,OAAO,CAAC,CAAA;AAClF,CAAC;AAED,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAwB,MAAM,YAAY,CAAA;AACnE,OAAO,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAA;AACjE,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,MAAM,YAAY,CAAA;AAa9D,0EAA0E;AAC1E,MAAM,UAAU,aAAa,CAAC,OAAyB;IACtD,gBAAgB,CAAC,QAAQ,CAAC,OAAO,EAAE,aAAa,EAAE,kBAAkB,EAAE,OAAO,CAAC,CAAA;AAC/E,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc,CAAC,OAAyB;IACvD,gBAAgB,CAAC,QAAQ,CAAC,QAAQ,EAAE,cAAc,EAAE,mBAAmB,EAAE,OAAO,CAAC,CAAA;AAClF,CAAC;AAED,OAAO,EACN,mBAAmB,EACnB,cAAc,EACd,2BAA2B,GAC3B,MAAM,aAAa,CAAA;AACpB,OAAO,EACN,kBAAkB,EAClB,aAAa,GACb,MAAM,YAAY,CAAA"}
package/dist/types.d.ts CHANGED
@@ -24,4 +24,19 @@ export interface OpenAIConfig {
24
24
  export interface OpenAIProviderConfig extends OpenAIConfig {
25
25
  type: 'openai';
26
26
  }
27
+ /** ChatGPT subscription transport used by the Codex Responses backend. */
28
+ export interface CodexConfig {
29
+ accessToken: string;
30
+ accountId: string;
31
+ /** Default model. Can be overridden per call. */
32
+ model?: string;
33
+ /** Defaults to the ChatGPT Codex backend. */
34
+ baseURL?: string;
35
+ /** Request timeout in milliseconds. */
36
+ timeout?: number;
37
+ defaultHeaders?: Record<string, string>;
38
+ }
39
+ export interface CodexProviderConfig extends CodexConfig {
40
+ type: 'codex';
41
+ }
27
42
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,gFAAgF;IAChF,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,6EAA6E;IAC7E,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,uBAAuB;IACvB,YAAY,CAAC,EAAE,MAAM,CAAA;IAC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 -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@namzu/openai",
3
- "version": "1.4.0",
4
- "description": "OpenAI LLM provider for @namzu/sdk via the official `openai` npm SDK. Chat Completions API with streaming + tool-use.",
3
+ "version": "2.0.0",
4
+ "description": "OpenAI API-key and ChatGPT subscription providers for @namzu/sdk, with streaming and tool use.",
5
5
  "license": "FSL-1.1-MIT",
6
6
  "engines": {
7
7
  "node": ">=20.0.0"
@@ -57,7 +57,7 @@
57
57
  "@types/node": "^22.19.17",
58
58
  "typescript": "^5.5.0",
59
59
  "vitest": "^3.2.6",
60
- "@namzu/sdk": "^31.0.0"
60
+ "@namzu/sdk": "^33.0.0"
61
61
  },
62
62
  "scripts": {
63
63
  "build": "tsc --build",
package/src/codex.ts ADDED
@@ -0,0 +1,520 @@
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 type { CodexConfig } from './types.js'
29
+
30
+ export const CODEX_CAPABILITIES: ProviderCapabilities = {
31
+ supportsTools: true,
32
+ supportsStreaming: true,
33
+ supportsFunctionCalling: true,
34
+ supportsVision: false,
35
+ supportsDocuments: false,
36
+ }
37
+
38
+ const DEFAULT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex'
39
+
40
+ interface SubscriptionReasoningProfile {
41
+ readonly default: ReasoningEffort
42
+ readonly levels: readonly ReasoningEffort[]
43
+ }
44
+
45
+ const SOL_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const
46
+ const TERRA_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max', 'ultra'] as const
47
+ const LUNA_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'] as const
48
+ const STANDARD_LEVELS = ['low', 'medium', 'high', 'xhigh'] as const
49
+
50
+ const SUBSCRIPTION_REASONING_PROFILES = new Map<string, SubscriptionReasoningProfile>([
51
+ ['gpt-5.6-sol', { default: 'low', levels: SOL_LEVELS }],
52
+ ['gpt-5.6-terra', { default: 'medium', levels: TERRA_LEVELS }],
53
+ ['gpt-5.6-luna', { default: 'medium', levels: LUNA_LEVELS }],
54
+ ['gpt-daybreak-blue-latest', { default: 'low', levels: SOL_LEVELS }],
55
+ ['gpt-daybreak-red-latest', { default: 'medium', levels: TERRA_LEVELS }],
56
+ ['gpt-5.5', { default: 'medium', levels: STANDARD_LEVELS }],
57
+ ['gpt-5.4', { default: 'medium', levels: STANDARD_LEVELS }],
58
+ ['gpt-5.4-mini', { default: 'medium', levels: STANDARD_LEVELS }],
59
+ ['gpt-5.2', { default: 'medium', levels: STANDARD_LEVELS }],
60
+ ['codex-auto-review', { default: 'medium', levels: LUNA_LEVELS }],
61
+ ])
62
+
63
+ function subscriptionReasoningProfile(model: string): SubscriptionReasoningProfile | undefined {
64
+ return SUBSCRIPTION_REASONING_PROFILES.get(model.toLowerCase())
65
+ }
66
+
67
+ interface CodexReplayState {
68
+ readonly kind: 'namzu.codex.responses'
69
+ readonly version: 1
70
+ readonly route: ProviderRoute
71
+ readonly content: string | null
72
+ readonly toolCalls: readonly {
73
+ readonly id: string
74
+ readonly name: string
75
+ readonly arguments: string
76
+ }[]
77
+ readonly items: readonly ResponseOutputItem[]
78
+ }
79
+
80
+ function sameRoute(left: ProviderRoute, right: ProviderRoute): boolean {
81
+ return (
82
+ left.providerId === right.providerId &&
83
+ left.model === right.model &&
84
+ left.chainIndex === right.chainIndex
85
+ )
86
+ }
87
+
88
+ function record(value: unknown): Record<string, unknown> | null {
89
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
90
+ ? (value as Record<string, unknown>)
91
+ : null
92
+ }
93
+
94
+ function isRoute(value: unknown): value is ProviderRoute {
95
+ const route = record(value)
96
+ return (
97
+ typeof route?.providerId === 'string' &&
98
+ typeof route.model === 'string' &&
99
+ Number.isInteger(route.chainIndex) &&
100
+ (route.chainIndex as number) >= 0
101
+ )
102
+ }
103
+
104
+ function durableToolCalls(
105
+ message: Extract<ChatCompletionParams['messages'][number], { role: 'assistant' }>,
106
+ ): CodexReplayState['toolCalls'] {
107
+ return (message.toolCalls ?? []).map((call) => ({
108
+ id: call.id,
109
+ name: call.function.name,
110
+ arguments: call.function.arguments,
111
+ }))
112
+ }
113
+
114
+ function isCodexReplayState(value: unknown): value is CodexReplayState {
115
+ const state = record(value)
116
+ if (
117
+ state?.kind !== 'namzu.codex.responses' ||
118
+ state.version !== 1 ||
119
+ !isRoute(state.route) ||
120
+ (state.content !== null && typeof state.content !== 'string') ||
121
+ !Array.isArray(state.toolCalls) ||
122
+ !Array.isArray(state.items)
123
+ ) {
124
+ return false
125
+ }
126
+ return state.toolCalls.every((item) => {
127
+ const call = record(item)
128
+ return (
129
+ typeof call?.id === 'string' &&
130
+ typeof call.name === 'string' &&
131
+ typeof call.arguments === 'string'
132
+ )
133
+ })
134
+ }
135
+
136
+ function replayItems(
137
+ message: Extract<ChatCompletionParams['messages'][number], { role: 'assistant' }>,
138
+ targetRoute: ProviderRoute,
139
+ ): readonly ResponseOutputItem[] | null {
140
+ const source = message.source
141
+ if (!source || source.type !== 'model' || !sameRoute(source, targetRoute)) return null
142
+ const state = source.replayState
143
+ if (!isCodexReplayState(state) || !sameRoute(state.route, source)) return null
144
+ if (state.content !== message.content) return null
145
+ if (JSON.stringify(state.toolCalls) !== JSON.stringify(durableToolCalls(message))) return null
146
+ return state.items
147
+ }
148
+
149
+ export function toCodexInput(
150
+ messages: ChatCompletionParams['messages'],
151
+ targetRoute: ProviderRoute,
152
+ ): ResponseInputItem[] {
153
+ const input: ResponseInputItem[] = []
154
+ for (const message of messages) {
155
+ if (message.role === 'system') continue
156
+ if (message.role === 'user') {
157
+ if (message.attachments && message.attachments.length > 0) {
158
+ throw new Error(
159
+ 'CodexProvider: this transport does not yet admit image or document attachments. Remove the attachment or select a provider whose declared capabilities include it.',
160
+ )
161
+ }
162
+ input.push({ type: 'message', role: 'user', content: message.content })
163
+ continue
164
+ }
165
+ if (message.role === 'tool') {
166
+ input.push({
167
+ type: 'function_call_output',
168
+ call_id: message.toolCallId,
169
+ output: toolResultToText(message.content),
170
+ })
171
+ continue
172
+ }
173
+ const replayed = replayItems(message, targetRoute)
174
+ if (replayed) {
175
+ input.push(...(replayed as ResponseInputItem[]))
176
+ continue
177
+ }
178
+ if (message.content) {
179
+ input.push({
180
+ type: 'message',
181
+ role: 'assistant',
182
+ content: message.content,
183
+ })
184
+ }
185
+ for (const call of message.toolCalls ?? []) {
186
+ input.push({
187
+ type: 'function_call',
188
+ call_id: call.id,
189
+ name: call.function.name,
190
+ arguments: call.function.arguments,
191
+ })
192
+ }
193
+ }
194
+ return input
195
+ }
196
+
197
+ export function toCodexTools(params: ChatCompletionParams): Tool[] | undefined {
198
+ if (!params.tools || params.tools.length === 0) return undefined
199
+ return params.tools.map((tool) => ({
200
+ type: 'function',
201
+ name: tool.function.name,
202
+ description: tool.function.description ?? '',
203
+ parameters: tool.function.parameters ?? {},
204
+ // The ChatGPT Codex backend validates `strict: true` against a narrower
205
+ // Responses schema than the Chat Completions endpoint. In particular,
206
+ // every composition branch needs an explicit type and every object
207
+ // property must also be required. Namzu model schemas deliberately keep
208
+ // conditional edit shapes optional and validate the selected shape at
209
+ // execution, so claiming strictness rejects the whole request before the
210
+ // model can answer. The Codex client uses the same boundary for its own
211
+ // tools: Responses function tools are sent with `strict: false` and tool
212
+ // inputs are validated by the runtime. `enforceToolInputSchema` remains a
213
+ // provider hint; this transport cannot truthfully consume it for Namzu's
214
+ // general tool-schema contract.
215
+ strict: false,
216
+ }))
217
+ }
218
+
219
+ function responseUsage(usage: {
220
+ input_tokens?: number
221
+ output_tokens?: number
222
+ total_tokens?: number
223
+ input_tokens_details?: { cached_tokens?: number }
224
+ }): TokenUsage {
225
+ const promptTokens = usage.input_tokens ?? 0
226
+ const completionTokens = usage.output_tokens ?? 0
227
+ return {
228
+ promptTokens,
229
+ completionTokens,
230
+ totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
231
+ cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
232
+ cacheWriteTokens: 0,
233
+ }
234
+ }
235
+
236
+ function buildRequest(
237
+ params: ChatCompletionParams,
238
+ model: string,
239
+ targetRoute: ProviderRoute,
240
+ ): ResponseCreateParamsStreaming {
241
+ const supportedEffort = subscriptionReasoningProfile(model)?.levels
242
+ if (
243
+ params.effort !== undefined &&
244
+ supportedEffort !== undefined &&
245
+ !supportedEffort.includes(params.effort)
246
+ ) {
247
+ throw new Error(
248
+ `CodexProvider: effort "${params.effort}" is not supported by model "${model}". Supported levels: ${supportedEffort.join(', ')}. Choose one of those levels or omit \`effort\`.`,
249
+ )
250
+ }
251
+ if (params.thinking?.type === 'enabled') {
252
+ throw new Error(
253
+ 'CodexProvider: manual thinking budgets are not a Responses API capability. Use adaptive thinking or omit `thinking`.',
254
+ )
255
+ }
256
+ if (params.thinking?.type === 'disabled' && params.effort !== 'none') {
257
+ throw new Error(
258
+ 'CodexProvider: disabling reasoning requires `effort: "none"`; omitting that level would not prove reasoning was disabled.',
259
+ )
260
+ }
261
+ const instructions = params.messages
262
+ .filter((message) => message.role === 'system')
263
+ .map((message) => message.content)
264
+ .join('\n\n')
265
+ const request = {
266
+ model,
267
+ stream: true,
268
+ store: false,
269
+ instructions: instructions || undefined,
270
+ input: toCodexInput(params.messages, targetRoute),
271
+ // The Codex subscription request schema deliberately has no
272
+ // `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
273
+ // API control, but projecting it onto this route makes the whole request
274
+ // invalid; the backend owns the output budget here.
275
+ // The subscription Responses backend expects these three fields even for a
276
+ // turn that exposes no tools. The ordinary public Responses endpoint admits
277
+ // their omission, which is why the generated client types all make them
278
+ // optional; the Codex wire does not have the same defaulting contract.
279
+ tools: toCodexTools(params) ?? [],
280
+ tool_choice: (params.toolChoice ?? 'auto') as ResponseCreateParamsStreaming['tool_choice'],
281
+ parallel_tool_calls: params.parallelToolCalls ?? true,
282
+ include: ['reasoning.encrypted_content'],
283
+ ...(params.effort !== undefined
284
+ ? { reasoning: { effort: params.effort, summary: 'auto' } }
285
+ : params.thinking?.type === 'adaptive'
286
+ ? { reasoning: { summary: 'auto' } }
287
+ : {}),
288
+ }
289
+ // The installed client declaration predates the current advanced effort
290
+ // vocabulary. The model-specific admission check above is the runtime
291
+ // boundary; this cast only bridges that declaration lag.
292
+ return request as ResponseCreateParamsStreaming
293
+ }
294
+
295
+ export class CodexProvider implements LLMProvider {
296
+ readonly id = 'codex'
297
+ readonly name = 'OpenAI Codex'
298
+ readonly capabilities = CODEX_CAPABILITIES
299
+
300
+ private client: OpenAI
301
+ private defaultModel?: string
302
+
303
+ constructor(config: CodexConfig) {
304
+ if (!config.accessToken) throw new Error('Codex access token is required.')
305
+ if (!config.accountId) throw new Error('Codex ChatGPT account id is required.')
306
+ this.client = new OpenAI({
307
+ apiKey: config.accessToken,
308
+ baseURL: config.baseURL ?? DEFAULT_CODEX_BASE_URL,
309
+ timeout: config.timeout,
310
+ defaultHeaders: {
311
+ ...attributionHeaders(),
312
+ 'ChatGPT-Account-Id': config.accountId,
313
+ originator: 'Codex Namzu',
314
+ 'User-Agent': 'Codex Namzu/1.0',
315
+ ...(config.defaultHeaders ?? {}),
316
+ },
317
+ })
318
+ this.defaultModel = config.model
319
+ }
320
+
321
+ private resolveModel(params: ChatCompletionParams): string {
322
+ const model = params.model || this.defaultModel
323
+ if (!model) throw new Error('CodexProvider: model is required.')
324
+ return model
325
+ }
326
+
327
+ reasoningEffortLevelsFor(model: string): readonly ReasoningEffort[] | undefined {
328
+ return subscriptionReasoningProfile(model)?.levels
329
+ }
330
+
331
+ reasoningEffortDefaultFor(model: string): ReasoningEffort | undefined {
332
+ return subscriptionReasoningProfile(model)?.default
333
+ }
334
+
335
+ async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
336
+ const model = this.resolveModel(params)
337
+ const targetRoute = params.providerRoute ?? {
338
+ providerId: this.id,
339
+ model,
340
+ chainIndex: 0,
341
+ }
342
+ const request = buildRequest(params, model, targetRoute)
343
+ let stream: AsyncIterable<ResponseStreamEvent>
344
+ try {
345
+ stream = (await this.client.responses.create(request, {
346
+ signal: params.signal,
347
+ })) as AsyncIterable<ResponseStreamEvent>
348
+ } catch (error) {
349
+ if (isCallerAbortError(error, params.signal)) throw params.signal?.reason ?? error
350
+ if (isProviderRequestError(error)) throw error
351
+ throw providerVendorError({ providerId: this.id, error })
352
+ }
353
+
354
+ const callIndex = new Map<string, number>()
355
+ let nextCallIndex = 0
356
+ let responseId = 'codex-response'
357
+ try {
358
+ for await (const event of stream) {
359
+ params.signal?.throwIfAborted()
360
+ switch (event.type) {
361
+ case 'response.created':
362
+ responseId = event.response.id
363
+ break
364
+ case 'response.output_text.delta':
365
+ yield { id: responseId, delta: { content: event.delta } }
366
+ break
367
+ case 'response.reasoning_summary_text.delta':
368
+ yield {
369
+ id: responseId,
370
+ delta: {
371
+ reasoning: {
372
+ index: event.output_index,
373
+ type: 'thinking',
374
+ text: event.delta,
375
+ },
376
+ },
377
+ }
378
+ break
379
+ case 'response.reasoning_summary_text.done':
380
+ yield {
381
+ id: responseId,
382
+ delta: {
383
+ reasoning: {
384
+ index: event.output_index,
385
+ type: 'thinking',
386
+ done: true,
387
+ },
388
+ },
389
+ }
390
+ break
391
+ case 'response.output_item.added':
392
+ if (event.item.type === 'function_call') {
393
+ const index = nextCallIndex++
394
+ callIndex.set(event.item.id ?? event.item.call_id, index)
395
+ callIndex.set(event.item.call_id, index)
396
+ yield {
397
+ id: responseId,
398
+ delta: {
399
+ toolCalls: [
400
+ {
401
+ index,
402
+ id: event.item.call_id,
403
+ type: 'function',
404
+ function: {
405
+ name: event.item.name,
406
+ arguments: event.item.arguments,
407
+ },
408
+ },
409
+ ],
410
+ },
411
+ }
412
+ }
413
+ break
414
+ case 'response.function_call_arguments.delta': {
415
+ const index = callIndex.get(event.item_id) ?? event.output_index
416
+ yield {
417
+ id: responseId,
418
+ delta: {
419
+ toolCalls: [{ index, function: { arguments: event.delta } }],
420
+ },
421
+ }
422
+ break
423
+ }
424
+ case 'response.output_item.done':
425
+ if (event.item.type === 'function_call') {
426
+ yield {
427
+ id: responseId,
428
+ delta: {
429
+ toolCallEnd: {
430
+ index: callIndex.get(event.item.id ?? event.item.call_id) ?? event.output_index,
431
+ id: event.item.call_id,
432
+ },
433
+ },
434
+ }
435
+ }
436
+ break
437
+ case 'response.completed': {
438
+ const calls = event.response.output
439
+ .filter((item) => item.type === 'function_call')
440
+ .map((item) => ({
441
+ id: item.call_id,
442
+ name: item.name,
443
+ arguments: item.arguments,
444
+ }))
445
+ const content = event.response.output
446
+ .filter((item) => item.type === 'message')
447
+ .flatMap((item) => item.content)
448
+ .filter((item) => item.type === 'output_text')
449
+ .map((item) => item.text)
450
+ .join('')
451
+ const replayState: CodexReplayState = {
452
+ kind: 'namzu.codex.responses',
453
+ version: 1,
454
+ route: targetRoute,
455
+ content: content || null,
456
+ toolCalls: calls,
457
+ items: event.response.output,
458
+ }
459
+ yield {
460
+ id: event.response.id,
461
+ delta: {},
462
+ finishReason: calls.length > 0 ? 'tool_calls' : 'stop',
463
+ usage: responseUsage(event.response.usage ?? {}),
464
+ replayState,
465
+ }
466
+ break
467
+ }
468
+ case 'error':
469
+ case 'response.failed':
470
+ throw new ProviderRequestError({
471
+ kind: 'server',
472
+ providerId: this.id,
473
+ detail: 'the Codex Responses stream failed',
474
+ })
475
+ }
476
+ }
477
+ } catch (error) {
478
+ if (isCallerAbortError(error, params.signal)) throw params.signal?.reason ?? error
479
+ if (isProviderRequestError(error)) throw error
480
+ throw providerVendorError({ providerId: this.id, error })
481
+ }
482
+ }
483
+
484
+ async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
485
+ signal?.throwIfAborted()
486
+ const response = (await this.client.get('/models?client_version=1.0.0', {
487
+ signal,
488
+ })) as { models?: unknown }
489
+ signal?.throwIfAborted()
490
+ if (!Array.isArray(response.models)) return []
491
+ return response.models.flatMap((value): ModelInfo[] => {
492
+ const item = record(value)
493
+ if (typeof item?.slug !== 'string' || item.slug.length === 0) return []
494
+ if (item.visibility === 'hide' || item.visibility === 'hidden') return []
495
+ return [
496
+ {
497
+ id: item.slug,
498
+ name: typeof item.display_name === 'string' ? item.display_name : item.slug,
499
+ inputPrice: 0,
500
+ outputPrice: 0,
501
+ supportsToolUse: true,
502
+ supportsStreaming: true,
503
+ },
504
+ ]
505
+ })
506
+ }
507
+
508
+ async probeCredential(signal?: AbortSignal): Promise<void> {
509
+ await this.listModels(signal)
510
+ }
511
+
512
+ async healthCheck(): Promise<boolean> {
513
+ try {
514
+ await this.probeCredential()
515
+ return true
516
+ } catch {
517
+ return false
518
+ }
519
+ }
520
+ }
package/src/index.ts CHANGED
@@ -1,15 +1,23 @@
1
1
  import { ProviderRegistry, type RegisterOptions } from '@namzu/sdk'
2
2
  import { OPENAI_CAPABILITIES, OpenAIProvider } from './client.js'
3
+ import { CODEX_CAPABILITIES, CodexProvider } from './codex.js'
3
4
  import type { OpenAIProviderConfig } from './types.js'
5
+ import type { CodexProviderConfig } from './types.js'
4
6
 
5
7
  // Module augmentation: register openai's config type in the sdk's registry interface.
6
8
  // This must live inside index.ts (not a .d.ts) so it executes when index.ts is imported.
7
9
  declare module '@namzu/sdk' {
8
10
  interface ProviderConfigRegistry {
9
11
  openai: OpenAIProviderConfig
12
+ codex: CodexProviderConfig
10
13
  }
11
14
  }
12
15
 
16
+ /** Register the ChatGPT subscription-backed Codex Responses transport. */
17
+ export function registerCodex(options?: RegisterOptions): void {
18
+ ProviderRegistry.register('codex', CodexProvider, CODEX_CAPABILITIES, options)
19
+ }
20
+
13
21
  /**
14
22
  * Register `OpenAIProvider` under the `'openai'` type in `@namzu/sdk`'s
15
23
  * `ProviderRegistry`. Call once at app startup before
@@ -22,5 +30,18 @@ export function registerOpenAI(options?: RegisterOptions): void {
22
30
  ProviderRegistry.register('openai', OpenAIProvider, OPENAI_CAPABILITIES, options)
23
31
  }
24
32
 
25
- export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels } from './client.js'
26
- export type { OpenAIConfig, OpenAIProviderConfig } from './types.js'
33
+ export {
34
+ OPENAI_CAPABILITIES,
35
+ OpenAIProvider,
36
+ openAIReasoningEffortLevels,
37
+ } from './client.js'
38
+ export {
39
+ CODEX_CAPABILITIES,
40
+ CodexProvider,
41
+ } from './codex.js'
42
+ export type {
43
+ CodexConfig,
44
+ CodexProviderConfig,
45
+ OpenAIConfig,
46
+ OpenAIProviderConfig,
47
+ } from './types.js'
package/src/types.ts CHANGED
@@ -26,3 +26,20 @@ export interface OpenAIConfig {
26
26
  export interface OpenAIProviderConfig extends OpenAIConfig {
27
27
  type: 'openai'
28
28
  }
29
+
30
+ /** ChatGPT subscription transport used by the Codex Responses backend. */
31
+ export interface CodexConfig {
32
+ accessToken: string
33
+ accountId: string
34
+ /** Default model. Can be overridden per call. */
35
+ model?: string
36
+ /** Defaults to the ChatGPT Codex backend. */
37
+ baseURL?: string
38
+ /** Request timeout in milliseconds. */
39
+ timeout?: number
40
+ defaultHeaders?: Record<string, string>
41
+ }
42
+
43
+ export interface CodexProviderConfig extends CodexConfig {
44
+ type: 'codex'
45
+ }