@namzu/openai 1.4.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 CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.5.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 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.
8
+
9
+ 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.
10
+
3
11
  ## 1.4.0
4
12
 
5
13
  ### 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,21 @@
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
+ chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk>;
17
+ listModels(signal?: AbortSignal): Promise<ModelInfo[]>;
18
+ probeCredential(signal?: AbortSignal): Promise<void>;
19
+ healthCheck(): Promise<boolean>;
20
+ }
21
+ //# 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;AAG7C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE7C,eAAO,MAAM,kBAAkB,EAAE,oBAMhC,CAAA;AAsFD,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;IAIxE,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,414 @@
1
+ import { ProviderRequestError, attributionHeaders, isCallerAbortError, isProviderRequestError, providerVendorError, toolResultToText, } from '@namzu/sdk';
2
+ import OpenAI from 'openai';
3
+ import { openAIReasoningEffortLevels } from './client.js';
4
+ export const CODEX_CAPABILITIES = {
5
+ supportsTools: true,
6
+ supportsStreaming: true,
7
+ supportsFunctionCalling: true,
8
+ supportsVision: false,
9
+ supportsDocuments: false,
10
+ };
11
+ const DEFAULT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex';
12
+ function sameRoute(left, right) {
13
+ return (left.providerId === right.providerId &&
14
+ left.model === right.model &&
15
+ left.chainIndex === right.chainIndex);
16
+ }
17
+ function record(value) {
18
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
19
+ ? value
20
+ : null;
21
+ }
22
+ function isRoute(value) {
23
+ const route = record(value);
24
+ return (typeof route?.providerId === 'string' &&
25
+ typeof route.model === 'string' &&
26
+ Number.isInteger(route.chainIndex) &&
27
+ route.chainIndex >= 0);
28
+ }
29
+ function durableToolCalls(message) {
30
+ return (message.toolCalls ?? []).map((call) => ({
31
+ id: call.id,
32
+ name: call.function.name,
33
+ arguments: call.function.arguments,
34
+ }));
35
+ }
36
+ function isCodexReplayState(value) {
37
+ const state = record(value);
38
+ if (state?.kind !== 'namzu.codex.responses' ||
39
+ state.version !== 1 ||
40
+ !isRoute(state.route) ||
41
+ (state.content !== null && typeof state.content !== 'string') ||
42
+ !Array.isArray(state.toolCalls) ||
43
+ !Array.isArray(state.items)) {
44
+ return false;
45
+ }
46
+ return state.toolCalls.every((item) => {
47
+ const call = record(item);
48
+ return (typeof call?.id === 'string' &&
49
+ typeof call.name === 'string' &&
50
+ typeof call.arguments === 'string');
51
+ });
52
+ }
53
+ function replayItems(message, targetRoute) {
54
+ const source = message.source;
55
+ if (!source || source.type !== 'model' || !sameRoute(source, targetRoute))
56
+ return null;
57
+ const state = source.replayState;
58
+ if (!isCodexReplayState(state) || !sameRoute(state.route, source))
59
+ return null;
60
+ if (state.content !== message.content)
61
+ return null;
62
+ if (JSON.stringify(state.toolCalls) !== JSON.stringify(durableToolCalls(message)))
63
+ return null;
64
+ return state.items;
65
+ }
66
+ export function toCodexInput(messages, targetRoute) {
67
+ const input = [];
68
+ for (const message of messages) {
69
+ if (message.role === 'system')
70
+ continue;
71
+ if (message.role === 'user') {
72
+ if (message.attachments && message.attachments.length > 0) {
73
+ 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.');
74
+ }
75
+ input.push({ type: 'message', role: 'user', content: message.content });
76
+ continue;
77
+ }
78
+ if (message.role === 'tool') {
79
+ input.push({
80
+ type: 'function_call_output',
81
+ call_id: message.toolCallId,
82
+ output: toolResultToText(message.content),
83
+ });
84
+ continue;
85
+ }
86
+ const replayed = replayItems(message, targetRoute);
87
+ if (replayed) {
88
+ input.push(...replayed);
89
+ continue;
90
+ }
91
+ if (message.content) {
92
+ input.push({
93
+ type: 'message',
94
+ role: 'assistant',
95
+ content: message.content,
96
+ });
97
+ }
98
+ for (const call of message.toolCalls ?? []) {
99
+ input.push({
100
+ type: 'function_call',
101
+ call_id: call.id,
102
+ name: call.function.name,
103
+ arguments: call.function.arguments,
104
+ });
105
+ }
106
+ }
107
+ return input;
108
+ }
109
+ export function toCodexTools(params) {
110
+ if (!params.tools || params.tools.length === 0)
111
+ return undefined;
112
+ return params.tools.map((tool) => ({
113
+ type: 'function',
114
+ name: tool.function.name,
115
+ description: tool.function.description ?? '',
116
+ parameters: tool.function.parameters ?? {},
117
+ // The ChatGPT Codex backend validates `strict: true` against a narrower
118
+ // Responses schema than the Chat Completions endpoint. In particular,
119
+ // every composition branch needs an explicit type and every object
120
+ // property must also be required. Namzu model schemas deliberately keep
121
+ // conditional edit shapes optional and validate the selected shape at
122
+ // execution, so claiming strictness rejects the whole request before the
123
+ // model can answer. The Codex client uses the same boundary for its own
124
+ // tools: Responses function tools are sent with `strict: false` and tool
125
+ // inputs are validated by the runtime. `enforceToolInputSchema` remains a
126
+ // provider hint; this transport cannot truthfully consume it for Namzu's
127
+ // general tool-schema contract.
128
+ strict: false,
129
+ }));
130
+ }
131
+ function responseUsage(usage) {
132
+ const promptTokens = usage.input_tokens ?? 0;
133
+ const completionTokens = usage.output_tokens ?? 0;
134
+ return {
135
+ promptTokens,
136
+ completionTokens,
137
+ totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
138
+ cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
139
+ cacheWriteTokens: 0,
140
+ };
141
+ }
142
+ function buildRequest(params, model, targetRoute) {
143
+ const supportedEffort = openAIReasoningEffortLevels(model);
144
+ if (params.effort !== undefined &&
145
+ supportedEffort !== undefined &&
146
+ !supportedEffort.includes(params.effort)) {
147
+ 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\`.`);
148
+ }
149
+ if (params.thinking?.type === 'enabled') {
150
+ throw new Error('CodexProvider: manual thinking budgets are not a Responses API capability. Use adaptive thinking or omit `thinking`.');
151
+ }
152
+ if (params.thinking?.type === 'disabled' && params.effort !== 'none') {
153
+ throw new Error('CodexProvider: disabling reasoning requires `effort: "none"`; omitting that level would not prove reasoning was disabled.');
154
+ }
155
+ const instructions = params.messages
156
+ .filter((message) => message.role === 'system')
157
+ .map((message) => message.content)
158
+ .join('\n\n');
159
+ const request = {
160
+ model,
161
+ stream: true,
162
+ store: false,
163
+ instructions: instructions || undefined,
164
+ input: toCodexInput(params.messages, targetRoute),
165
+ // The Codex subscription request schema deliberately has no
166
+ // `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
167
+ // API control, but projecting it onto this route makes the whole request
168
+ // invalid; the backend owns the output budget here.
169
+ // The subscription Responses backend expects these three fields even for a
170
+ // turn that exposes no tools. The ordinary public Responses endpoint admits
171
+ // their omission, which is why the generated client types all make them
172
+ // optional; the Codex wire does not have the same defaulting contract.
173
+ tools: toCodexTools(params) ?? [],
174
+ tool_choice: (params.toolChoice ?? 'auto'),
175
+ parallel_tool_calls: params.parallelToolCalls ?? true,
176
+ include: ['reasoning.encrypted_content'],
177
+ ...(params.effort !== undefined
178
+ ? { reasoning: { effort: params.effort, summary: 'auto' } }
179
+ : params.thinking?.type === 'adaptive'
180
+ ? { reasoning: { summary: 'auto' } }
181
+ : {}),
182
+ };
183
+ // The installed client declaration predates the current GPT-5.6 `max`
184
+ // vocabulary. The model-specific admission check above is the runtime
185
+ // boundary; this cast only bridges that vendor declaration lag.
186
+ return request;
187
+ }
188
+ export class CodexProvider {
189
+ id = 'codex';
190
+ name = 'OpenAI Codex';
191
+ capabilities = CODEX_CAPABILITIES;
192
+ client;
193
+ defaultModel;
194
+ constructor(config) {
195
+ if (!config.accessToken)
196
+ throw new Error('Codex access token is required.');
197
+ if (!config.accountId)
198
+ throw new Error('Codex ChatGPT account id is required.');
199
+ this.client = new OpenAI({
200
+ apiKey: config.accessToken,
201
+ baseURL: config.baseURL ?? DEFAULT_CODEX_BASE_URL,
202
+ timeout: config.timeout,
203
+ defaultHeaders: {
204
+ ...attributionHeaders(),
205
+ 'ChatGPT-Account-Id': config.accountId,
206
+ originator: 'Codex Namzu',
207
+ 'User-Agent': 'Codex Namzu/1.0',
208
+ ...(config.defaultHeaders ?? {}),
209
+ },
210
+ });
211
+ this.defaultModel = config.model;
212
+ }
213
+ resolveModel(params) {
214
+ const model = params.model || this.defaultModel;
215
+ if (!model)
216
+ throw new Error('CodexProvider: model is required.');
217
+ return model;
218
+ }
219
+ reasoningEffortLevelsFor(model) {
220
+ return openAIReasoningEffortLevels(model);
221
+ }
222
+ async *chatStream(params) {
223
+ const model = this.resolveModel(params);
224
+ const targetRoute = params.providerRoute ?? {
225
+ providerId: this.id,
226
+ model,
227
+ chainIndex: 0,
228
+ };
229
+ const request = buildRequest(params, model, targetRoute);
230
+ let stream;
231
+ try {
232
+ stream = (await this.client.responses.create(request, {
233
+ signal: params.signal,
234
+ }));
235
+ }
236
+ catch (error) {
237
+ if (isCallerAbortError(error, params.signal))
238
+ throw params.signal?.reason ?? error;
239
+ if (isProviderRequestError(error))
240
+ throw error;
241
+ throw providerVendorError({ providerId: this.id, error });
242
+ }
243
+ const callIndex = new Map();
244
+ let nextCallIndex = 0;
245
+ let responseId = 'codex-response';
246
+ try {
247
+ for await (const event of stream) {
248
+ params.signal?.throwIfAborted();
249
+ switch (event.type) {
250
+ case 'response.created':
251
+ responseId = event.response.id;
252
+ break;
253
+ case 'response.output_text.delta':
254
+ yield { id: responseId, delta: { content: event.delta } };
255
+ break;
256
+ case 'response.reasoning_summary_text.delta':
257
+ yield {
258
+ id: responseId,
259
+ delta: {
260
+ reasoning: {
261
+ index: event.output_index,
262
+ type: 'thinking',
263
+ text: event.delta,
264
+ },
265
+ },
266
+ };
267
+ break;
268
+ case 'response.reasoning_summary_text.done':
269
+ yield {
270
+ id: responseId,
271
+ delta: {
272
+ reasoning: {
273
+ index: event.output_index,
274
+ type: 'thinking',
275
+ done: true,
276
+ },
277
+ },
278
+ };
279
+ break;
280
+ case 'response.output_item.added':
281
+ if (event.item.type === 'function_call') {
282
+ const index = nextCallIndex++;
283
+ callIndex.set(event.item.id ?? event.item.call_id, index);
284
+ callIndex.set(event.item.call_id, index);
285
+ yield {
286
+ id: responseId,
287
+ delta: {
288
+ toolCalls: [
289
+ {
290
+ index,
291
+ id: event.item.call_id,
292
+ type: 'function',
293
+ function: {
294
+ name: event.item.name,
295
+ arguments: event.item.arguments,
296
+ },
297
+ },
298
+ ],
299
+ },
300
+ };
301
+ }
302
+ break;
303
+ case 'response.function_call_arguments.delta': {
304
+ const index = callIndex.get(event.item_id) ?? event.output_index;
305
+ yield {
306
+ id: responseId,
307
+ delta: {
308
+ toolCalls: [{ index, function: { arguments: event.delta } }],
309
+ },
310
+ };
311
+ break;
312
+ }
313
+ case 'response.output_item.done':
314
+ if (event.item.type === 'function_call') {
315
+ yield {
316
+ id: responseId,
317
+ delta: {
318
+ toolCallEnd: {
319
+ index: callIndex.get(event.item.id ?? event.item.call_id) ?? event.output_index,
320
+ id: event.item.call_id,
321
+ },
322
+ },
323
+ };
324
+ }
325
+ break;
326
+ case 'response.completed': {
327
+ const calls = event.response.output
328
+ .filter((item) => item.type === 'function_call')
329
+ .map((item) => ({
330
+ id: item.call_id,
331
+ name: item.name,
332
+ arguments: item.arguments,
333
+ }));
334
+ const content = event.response.output
335
+ .filter((item) => item.type === 'message')
336
+ .flatMap((item) => item.content)
337
+ .filter((item) => item.type === 'output_text')
338
+ .map((item) => item.text)
339
+ .join('');
340
+ const replayState = {
341
+ kind: 'namzu.codex.responses',
342
+ version: 1,
343
+ route: targetRoute,
344
+ content: content || null,
345
+ toolCalls: calls,
346
+ items: event.response.output,
347
+ };
348
+ yield {
349
+ id: event.response.id,
350
+ delta: {},
351
+ finishReason: calls.length > 0 ? 'tool_calls' : 'stop',
352
+ usage: responseUsage(event.response.usage ?? {}),
353
+ replayState,
354
+ };
355
+ break;
356
+ }
357
+ case 'error':
358
+ case 'response.failed':
359
+ throw new ProviderRequestError({
360
+ kind: 'server',
361
+ providerId: this.id,
362
+ detail: 'the Codex Responses stream failed',
363
+ });
364
+ }
365
+ }
366
+ }
367
+ catch (error) {
368
+ if (isCallerAbortError(error, params.signal))
369
+ throw params.signal?.reason ?? error;
370
+ if (isProviderRequestError(error))
371
+ throw error;
372
+ throw providerVendorError({ providerId: this.id, error });
373
+ }
374
+ }
375
+ async listModels(signal) {
376
+ signal?.throwIfAborted();
377
+ const response = (await this.client.get('/models?client_version=1.0.0', {
378
+ signal,
379
+ }));
380
+ signal?.throwIfAborted();
381
+ if (!Array.isArray(response.models))
382
+ return [];
383
+ return response.models.flatMap((value) => {
384
+ const item = record(value);
385
+ if (typeof item?.slug !== 'string' || item.slug.length === 0)
386
+ return [];
387
+ if (item.visibility === 'hide' || item.visibility === 'hidden')
388
+ return [];
389
+ return [
390
+ {
391
+ id: item.slug,
392
+ name: typeof item.display_name === 'string' ? item.display_name : item.slug,
393
+ inputPrice: 0,
394
+ outputPrice: 0,
395
+ supportsToolUse: true,
396
+ supportsStreaming: true,
397
+ },
398
+ ];
399
+ });
400
+ }
401
+ async probeCredential(signal) {
402
+ await this.listModels(signal);
403
+ }
404
+ async healthCheck() {
405
+ try {
406
+ await this.probeCredential();
407
+ return true;
408
+ }
409
+ catch {
410
+ return false;
411
+ }
412
+ }
413
+ }
414
+ //# 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,MAAM,QAAQ,CAAA;AAS3B,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAA;AAGzD,MAAM,CAAC,MAAM,kBAAkB,GAAyB;IACvD,aAAa,EAAE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CAAC,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;YAAE,OAAO,EAAE,CAAA;QAC9C,OAAO,QAAQ,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,KAAK,EAAe,EAAE;YACrD,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;YAC1B,IAAI,OAAO,IAAI,EAAE,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,OAAO,EAAE,CAAA;YACvE,IAAI,IAAI,CAAC,UAAU,KAAK,MAAM,IAAI,IAAI,CAAC,UAAU,KAAK,QAAQ;gBAAE,OAAO,EAAE,CAAA;YACzE,OAAO;gBACN;oBACC,EAAE,EAAE,IAAI,CAAC,IAAI;oBACb,IAAI,EAAE,OAAO,IAAI,CAAC,YAAY,KAAK,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI;oBAC3E,UAAU,EAAE,CAAC;oBACb,WAAW,EAAE,CAAC;oBACd,eAAe,EAAE,IAAI;oBACrB,iBAAiB,EAAE,IAAI;iBACvB;aACD,CAAA;QACF,CAAC,CAAC,CAAA;IACH,CAAC;IAED,KAAK,CAAC,eAAe,CAAC,MAAoB;QACzC,MAAM,IAAI,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;IACrB,kBAAkB;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,6BAA6B;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACvC;AAED,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACzD,IAAI,EAAE,QAAQ,CAAA;CACd"}
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;IACrB,kBAAkB;IAClB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,6BAA6B;IAC7B,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACvC;AAED,MAAM,WAAW,oBAAqB,SAAQ,YAAY;IACzD,IAAI,EAAE,QAAQ,CAAA;CACd;AAED,0EAA0E;AAC1E,MAAM,WAAW,WAAW;IAC3B,WAAW,EAAE,MAAM,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;IACjB,iDAAiD;IACjD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,6CAA6C;IAC7C,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,cAAc,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CACvC;AAED,MAAM,WAAW,mBAAoB,SAAQ,WAAW;IACvD,IAAI,EAAE,OAAO,CAAA;CACb"}
package/package.json CHANGED
@@ -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": "1.5.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"
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
+ }
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
+ }