@namzu/openai 4.6.0 → 4.8.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/src/codex.ts CHANGED
@@ -12,7 +12,6 @@ import type {
12
12
  } from '@namzu/sdk'
13
13
  import {
14
14
  ProviderRequestError,
15
- attributionHeaders,
16
15
  isCallerAbortError,
17
16
  isProviderRequestError,
18
17
  providerVendorError,
@@ -33,6 +32,8 @@ import type {
33
32
  } from 'openai/resources/responses/responses'
34
33
 
35
34
  import { type FastTier, assertFastModeAccepted, servedSpeed } from './fast-mode.js'
35
+ import { CODEX_DEFAULT_BASE_URL, codexRequestHeaders } from './images.js'
36
+ import { subscriptionLimits } from './model-limits.js'
36
37
  import type { CodexConfig } from './types.js'
37
38
 
38
39
  export const CODEX_CAPABILITIES: ProviderCapabilities = {
@@ -47,7 +48,7 @@ export const CODEX_CAPABILITIES: ProviderCapabilities = {
47
48
  supportsToolResultDocuments: false,
48
49
  }
49
50
 
50
- const DEFAULT_CODEX_BASE_URL = 'https://chatgpt.com/backend-api/codex'
51
+ const DEFAULT_CODEX_BASE_URL = CODEX_DEFAULT_BASE_URL
51
52
 
52
53
  interface SubscriptionReasoningProfile {
53
54
  readonly default?: ReasoningEffort
@@ -262,10 +263,18 @@ function codexToolOutput(
262
263
  export function toCodexInput(
263
264
  messages: ChatCompletionParams['messages'],
264
265
  targetRoute: ProviderRoute,
266
+ openingSystemRun = messages.findIndex((message) => message.role !== 'system'),
265
267
  ): ResponseInputItem[] {
266
268
  const input: ResponseInputItem[] = []
267
- for (const message of messages) {
268
- if (message.role === 'system') continue
269
+ const opening = openingSystemRun < 0 ? messages.length : openingSystemRun
270
+ for (const [at, message] of messages.entries()) {
271
+ if (message.role === 'system') {
272
+ // The opening run is `instructions`; a later one keeps its place.
273
+ if (at >= opening && message.content) {
274
+ input.push({ type: 'message', role: 'developer', content: message.content })
275
+ }
276
+ continue
277
+ }
269
278
  if (message.role === 'user') {
270
279
  input.push({
271
280
  type: 'message',
@@ -387,6 +396,7 @@ function buildRequest(
387
396
  model: string,
388
397
  targetRoute: ProviderRoute,
389
398
  supportedEffort: readonly ReasoningEffort[] | undefined,
399
+ downgrade: SubscriptionDowngrade = NO_DOWNGRADE,
390
400
  ): ResponseCreateParamsStreaming {
391
401
  if (
392
402
  params.effort !== undefined &&
@@ -407,8 +417,22 @@ function buildRequest(
407
417
  'CodexProvider: disabling reasoning requires `effort: "none"`; omitting that level would not prove reasoning was disabled.',
408
418
  )
409
419
  }
410
- const instructions = params.messages
411
- .filter((message) => message.role === 'system')
420
+ // Only the system messages that open the conversation are the standing
421
+ // instructions. The runtime places a step's preamble (changing guidance,
422
+ // skills, turn notes) later in the list; hoisting it into `instructions`
423
+ // put changing text at the very front of every request, so no request
424
+ // shared a cache prefix with the one before it. Later system messages stay
425
+ // where they were, as developer messages in the input.
426
+ let openingRun = 0
427
+ while (params.messages[openingRun]?.role === 'system') openingRun++
428
+ // After the backend refused the new shape, every system message goes back
429
+ // into `instructions` and none is sent as a developer item.
430
+ if (downgrade.legacyShape) openingRun = params.messages.length
431
+ const instructions = (
432
+ downgrade.legacyShape
433
+ ? params.messages.filter((message) => message.role === 'system')
434
+ : params.messages.slice(0, openingRun)
435
+ )
412
436
  .map((message) => message.content)
413
437
  .join('\n\n')
414
438
  const request = {
@@ -416,7 +440,10 @@ function buildRequest(
416
440
  stream: true,
417
441
  store: false,
418
442
  instructions: instructions || undefined,
419
- input: toCodexInput(params.messages, targetRoute),
443
+ input: toCodexInput(params.messages, targetRoute, openingRun),
444
+ // One key for the whole conversation routes every request to the same
445
+ // cache; without it the backend keys on the request alone.
446
+ ...(params.cacheKey && !downgrade.noCacheKey ? { prompt_cache_key: params.cacheKey } : {}),
420
447
  // The Codex subscription request schema deliberately has no
421
448
  // `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
422
449
  // API control, but projecting it onto this route makes the whole request
@@ -451,6 +478,43 @@ function buildRequest(
451
478
  return request as ResponseCreateParamsStreaming
452
479
  }
453
480
 
481
+ /**
482
+ * What the subscription backend has refused of the newer request shape: the
483
+ * `developer` input item, the `session_id` header, the `prompt_cache_key` body
484
+ * field. Set once for the life of the process, by the one resend that the
485
+ * refusal triggers; later requests go straight to the older shape.
486
+ */
487
+ interface SubscriptionDowngrade {
488
+ /** All system text joined into `instructions`, no developer items, no `session_id` header. */
489
+ legacyShape: boolean
490
+ /** The refusal named `prompt_cache_key`, so it is left off too. */
491
+ noCacheKey: boolean
492
+ }
493
+
494
+ const NO_DOWNGRADE: SubscriptionDowngrade = { legacyShape: false, noCacheKey: false }
495
+ const subscriptionDowngrade: SubscriptionDowngrade = { legacyShape: false, noCacheKey: false }
496
+
497
+ /** Test seam: forget a downgrade recorded earlier in this process. */
498
+ export function resetSubscriptionDowngrade(): void {
499
+ subscriptionDowngrade.legacyShape = false
500
+ subscriptionDowngrade.noCacheKey = false
501
+ }
502
+
503
+ const REFUSED_SHAPE = /\bdeveloper\b|\brole\b|\binput\[\d*\]|session_id|prompt_cache_key/i
504
+
505
+ /**
506
+ * A bad-request answer that names what the newer shape added. Anything else
507
+ * (a different 400, any other status, a network failure) is not one.
508
+ */
509
+ function refusedNewShape(error: unknown): { cacheKey: boolean } | undefined {
510
+ if (typeof error !== 'object' || error === null) return undefined
511
+ const status = (error as { status?: unknown }).status
512
+ if (!(error instanceof OpenAI.BadRequestError) && status !== 400) return undefined
513
+ const message = (error as { message?: unknown }).message
514
+ if (typeof message !== 'string' || !REFUSED_SHAPE.test(message)) return undefined
515
+ return { cacheKey: /prompt_cache_key/i.test(message) }
516
+ }
517
+
454
518
  /**
455
519
  * What an account's model listing said, kept for the life of the process so a
456
520
  * provider rebuilt around a refreshed token still honours an advertised tier.
@@ -461,9 +525,23 @@ const listingByAccount = new Map<
461
525
  {
462
526
  speedTiers: Map<string, readonly FastTier[]>
463
527
  reasoningProfiles: Map<string, SubscriptionReasoningProfile>
528
+ windows: Map<string, number>
529
+ compactLimits: Map<string, number>
464
530
  }
465
531
  >()
466
532
 
533
+ /**
534
+ * The `client_version` the model list is asked with. The backend's own client sends the plain
535
+ * `major.minor.patch` of its release (its newest published release is 0.171); a version above
536
+ * every release reads as the newest client, so no model or field is held back for being too new.
537
+ */
538
+ const MODELS_CLIENT_VERSION = '1.0.0'
539
+
540
+ /** The most a subscription listing may take before the window is left to the SDK's table. */
541
+ const WINDOW_LISTING_TIMEOUT_MS = 3_000
542
+ /** How long a failed listing is remembered, so a turn does not ask again every time. */
543
+ const WINDOW_LISTING_RETRY_MS = 5 * 60_000
544
+
467
545
  export class CodexProvider implements LLMProvider {
468
546
  readonly id = 'codex'
469
547
  readonly name = 'OpenAI Codex'
@@ -474,6 +552,13 @@ export class CodexProvider implements LLMProvider {
474
552
  private reasoningProfiles = new Map<string, SubscriptionReasoningProfile>()
475
553
  /** Per model, the speed tiers the account's listing offers. Absent until a listing has answered. */
476
554
  private speedTiers?: Map<string, readonly FastTier[]>
555
+ /** Per model, the window the account's listing states. Absent until a listing has answered. */
556
+ private windows?: Map<string, number>
557
+ /** Per model, the compaction threshold the account's listing states or implies. */
558
+ private compactLimits?: Map<string, number>
559
+ private windowListingRetryAt = 0
560
+ /** The listing in flight, shared by callers that arrive while it runs. */
561
+ private windowListing?: Promise<boolean>
477
562
  private readonly listingKey: string
478
563
 
479
564
  constructor(config: CodexConfig) {
@@ -485,10 +570,7 @@ export class CodexProvider implements LLMProvider {
485
570
  timeout: config.timeout,
486
571
  ...(config.maxRetries !== undefined ? { maxRetries: config.maxRetries } : {}),
487
572
  defaultHeaders: {
488
- ...attributionHeaders(),
489
- 'ChatGPT-Account-Id': config.accountId,
490
- originator: 'Codex Namzu',
491
- 'User-Agent': 'Codex Namzu/1.0',
573
+ ...codexRequestHeaders(config.accountId),
492
574
  ...(config.defaultHeaders ?? {}),
493
575
  },
494
576
  })
@@ -498,6 +580,8 @@ export class CodexProvider implements LLMProvider {
498
580
  if (known) {
499
581
  this.speedTiers = known.speedTiers
500
582
  this.reasoningProfiles = known.reasoningProfiles
583
+ this.windows = known.windows
584
+ this.compactLimits = known.compactLimits
501
585
  }
502
586
  }
503
587
 
@@ -525,6 +609,57 @@ export class CodexProvider implements LLMProvider {
525
609
  return this.speedTiers.get(model.toLowerCase()) ?? []
526
610
  }
527
611
 
612
+ /**
613
+ * The window the runtime measures compaction against, as the account's model listing states
614
+ * it (scaled by the effective-percent the listing sends, when it sends one), or `undefined`
615
+ * when the listing states none, which leaves the SDK's table to answer.
616
+ *
617
+ * The listing is asked once per account and kept. A failure is remembered for a few minutes
618
+ * and a listing that hangs is cut short. Neither ever fails a turn; only the caller's own
619
+ * abort propagates.
620
+ */
621
+ async resolveContextWindow(model: string, signal?: AbortSignal): Promise<number | undefined> {
622
+ signal?.throwIfAborted()
623
+ if (!this.windows) {
624
+ if (Date.now() < this.windowListingRetryAt) return undefined
625
+ this.windowListing ??= this.listForWindow().finally(() => {
626
+ this.windowListing = undefined
627
+ })
628
+ const abandoned = new Promise<never>((_, reject) => {
629
+ if (signal?.aborted) reject(signal.reason)
630
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true })
631
+ })
632
+ await Promise.race([this.windowListing, abandoned])
633
+ signal?.throwIfAborted()
634
+ }
635
+ return this.windows?.get(model.toLowerCase())
636
+ }
637
+
638
+ /**
639
+ * The token count the account's listing says compaction starts at for `model`: its
640
+ * `auto_compact_token_limit` held to 90% of the window, or 90% of the window when it sends
641
+ * none. Shares the one listing `resolveContextWindow` asks for, with the same bounds.
642
+ */
643
+ async resolveAutoCompactLimit(model: string, signal?: AbortSignal): Promise<number | undefined> {
644
+ await this.resolveContextWindow(model, signal)
645
+ return this.compactLimits?.get(model.toLowerCase())
646
+ }
647
+
648
+ /** One bounded listing for every caller waiting on it; a failure is remembered, never thrown. */
649
+ private async listForWindow(): Promise<boolean> {
650
+ const controller = new AbortController()
651
+ const timer = setTimeout(() => controller.abort(), WINDOW_LISTING_TIMEOUT_MS)
652
+ try {
653
+ await this.listModels(controller.signal)
654
+ return true
655
+ } catch {
656
+ this.windowListingRetryAt = Date.now() + WINDOW_LISTING_RETRY_MS
657
+ return false
658
+ } finally {
659
+ clearTimeout(timer)
660
+ }
661
+ }
662
+
528
663
  async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
529
664
  const model = this.resolveModel(params)
530
665
  const targetRoute = params.providerRoute ?? {
@@ -532,7 +667,8 @@ export class CodexProvider implements LLMProvider {
532
667
  model,
533
668
  chainIndex: 0,
534
669
  }
535
- const built = buildRequest(params, model, targetRoute, this.reasoningEffortLevelsFor(model))
670
+ const effortLevels = this.reasoningEffortLevelsFor(model)
671
+ const built = buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade)
536
672
  // A tier the account's listing does not offer is refused here, before
537
673
  // transport: the backend would drop it and serve standard speed while
538
674
  // the caller believes the request was honoured.
@@ -546,17 +682,45 @@ export class CodexProvider implements LLMProvider {
546
682
  firstPartyEndpoint: true,
547
683
  })
548
684
  : undefined
549
- const request = (
550
- fast ? { ...built, service_tier: fast.wire } : built
551
- ) as ResponseCreateParamsStreaming
685
+ const withTier = (body: ResponseCreateParamsStreaming) =>
686
+ (fast ? { ...body, service_tier: fast.wire } : body) as ResponseCreateParamsStreaming
552
687
  const requestedSpeed =
553
688
  params.speed === 'fast' || params.speed === 'ultrafast' ? params.speed : undefined
689
+ const send = (body: ResponseCreateParamsStreaming, sessionHeader: boolean) =>
690
+ this.client.responses.create(withTier(body), {
691
+ signal: params.signal,
692
+ ...(fast?.header || (sessionHeader && params.cacheKey)
693
+ ? {
694
+ headers: {
695
+ ...(fast?.header ?? {}),
696
+ ...(sessionHeader && params.cacheKey ? { session_id: params.cacheKey } : {}),
697
+ },
698
+ }
699
+ : {}),
700
+ }) as Promise<AsyncIterable<ResponseStreamEvent>>
554
701
  let stream: AsyncIterable<ResponseStreamEvent>
555
702
  try {
556
- stream = (await this.client.responses.create(request, {
557
- signal: params.signal,
558
- ...(fast?.header ? { headers: fast.header } : {}),
559
- })) as AsyncIterable<ResponseStreamEvent>
703
+ try {
704
+ stream = await send(built, !subscriptionDowngrade.legacyShape)
705
+ } catch (error) {
706
+ // The backend refusing the newer shape is answered before any
707
+ // output exists, so one resend in the older shape is safe. It is
708
+ // remembered, so no later request sends the newer shape and nothing
709
+ // is resent twice.
710
+ const refused = subscriptionDowngrade.legacyShape ? undefined : refusedNewShape(error)
711
+ const newShapeSent =
712
+ built.input !== undefined &&
713
+ (Boolean(params.cacheKey) ||
714
+ (Array.isArray(built.input) &&
715
+ built.input.some((item) => 'role' in item && item.role === 'developer')))
716
+ if (!refused || !newShapeSent || params.signal?.aborted) throw error
717
+ subscriptionDowngrade.legacyShape = true
718
+ if (refused.cacheKey) subscriptionDowngrade.noCacheKey = true
719
+ stream = await send(
720
+ buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade),
721
+ false,
722
+ )
723
+ }
560
724
  } catch (error) {
561
725
  if (isCallerAbortError(error, params.signal)) throw params.signal?.reason ?? error
562
726
  if (isProviderRequestError(error)) throw error
@@ -838,12 +1002,14 @@ export class CodexProvider implements LLMProvider {
838
1002
 
839
1003
  async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
840
1004
  signal?.throwIfAborted()
841
- const response = (await this.client.get('/models?client_version=1.0.0', {
1005
+ const response = (await this.client.get(`/models?client_version=${MODELS_CLIENT_VERSION}`, {
842
1006
  signal,
843
1007
  })) as { models?: unknown }
844
1008
  signal?.throwIfAborted()
845
1009
  const profiles = new Map<string, SubscriptionReasoningProfile>()
846
1010
  const tiersBySlug = new Map<string, readonly FastTier[]>()
1011
+ const windows = new Map<string, number>()
1012
+ const compactLimits = new Map<string, number>()
847
1013
  const models = (Array.isArray(response.models) ? response.models : []).flatMap(
848
1014
  (value): ModelInfo[] => {
849
1015
  const item = record(value)
@@ -853,6 +1019,10 @@ export class CodexProvider implements LLMProvider {
853
1019
  if (profile) profiles.set(item.slug.toLowerCase(), profile)
854
1020
  const speedTiers = subscriptionSpeedTiers(item)
855
1021
  tiersBySlug.set(item.slug.toLowerCase(), speedTiers)
1022
+ const { contextWindow, autoCompactTokenLimit } = subscriptionLimits(item)
1023
+ if (contextWindow !== undefined) windows.set(item.slug.toLowerCase(), contextWindow)
1024
+ if (autoCompactTokenLimit !== undefined)
1025
+ compactLimits.set(item.slug.toLowerCase(), autoCompactTokenLimit)
856
1026
  return [
857
1027
  {
858
1028
  id: item.slug,
@@ -862,15 +1032,21 @@ export class CodexProvider implements LLMProvider {
862
1032
  ...(profile ? { reasoningEffortLevels: profile.levels } : {}),
863
1033
  ...(profile?.default !== undefined ? { reasoningEffortDefault: profile.default } : {}),
864
1034
  speedTiers,
1035
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
1036
+ ...(autoCompactTokenLimit !== undefined ? { autoCompactTokenLimit } : {}),
865
1037
  },
866
1038
  ]
867
1039
  },
868
1040
  )
869
1041
  this.reasoningProfiles = profiles
870
1042
  this.speedTiers = tiersBySlug
1043
+ this.windows = windows
1044
+ this.compactLimits = compactLimits
871
1045
  listingByAccount.set(this.listingKey, {
872
1046
  speedTiers: tiersBySlug,
873
1047
  reasoningProfiles: profiles,
1048
+ windows,
1049
+ compactLimits,
874
1050
  })
875
1051
  return models
876
1052
  }
@@ -897,7 +1073,7 @@ export class CodexProvider implements LLMProvider {
897
1073
  */
898
1074
  export function webSearchDetail(item: {
899
1075
  readonly action?: unknown
900
- }): { query?: string; url?: string; results?: number } {
1076
+ }): { query?: string; url?: string; results?: number; searches?: number } {
901
1077
  const action = item.action as
902
1078
  | {
903
1079
  readonly type?: unknown
@@ -921,5 +1097,7 @@ export function webSearchDetail(item: {
921
1097
  ...(query ? { query } : {}),
922
1098
  ...(url && !query ? { url } : {}),
923
1099
  ...(Array.isArray(action.sources) ? { results: action.sources.length } : {}),
1100
+ // One hosted item may run several queries; the count says so, the label names the first.
1101
+ ...(queries.length > 1 ? { searches: queries.length } : {}),
924
1102
  }
925
1103
  }
package/src/images.ts ADDED
@@ -0,0 +1,190 @@
1
+ import { attributionHeaders } from '@namzu/sdk'
2
+
3
+ /** The image model the ChatGPT plan route serves; not selectable by the caller. */
4
+ export const CODEX_IMAGE_MODEL = 'gpt-image-2'
5
+
6
+ /** Where the ChatGPT plan route lives; the image paths hang off the same base as the Responses calls. */
7
+ export const CODEX_DEFAULT_BASE_URL = 'https://chatgpt.com/backend-api/codex'
8
+
9
+ const IMAGE_TURN_HEADER = 'x-codex-image-turn-id'
10
+ const ACTIVE_LIMIT_HEADER = 'x-codex-active-limit'
11
+ /** Generation takes minutes; this bounds one request, the caller's signal bounds it sooner. */
12
+ export const CODEX_IMAGE_TIMEOUT_MS = 10 * 60 * 1000
13
+ /** Largest decoded image the client accepts. */
14
+ export const CODEX_IMAGE_MAX_BYTES = 32 * 1024 * 1024
15
+ /** Limit ids the backend uses for the image quota. */
16
+ export const CODEX_IMAGE_LIMIT_IDS: readonly string[] = ['image_gen', 'imagegen_premium']
17
+
18
+ export interface CodexImagesConfig {
19
+ readonly accessToken: string
20
+ readonly accountId: string
21
+ /** Defaults to the ChatGPT Codex backend. */
22
+ readonly baseURL?: string
23
+ /** Headers added after the standard ones, such as a host's own originator. */
24
+ readonly headers?: Readonly<Record<string, string>>
25
+ readonly fetch?: typeof fetch
26
+ /** Per-request ceiling in milliseconds. */
27
+ readonly timeoutMs?: number
28
+ }
29
+
30
+ export interface CodexImageRequest {
31
+ readonly prompt: string
32
+ readonly transparentBackground?: boolean
33
+ /** `data:` URLs of the images to edit. Present means an edit, absent a new image. */
34
+ readonly images?: readonly string[]
35
+ /** The conversation turn the request belongs to, sent as the per-turn image header. */
36
+ readonly turnId?: string
37
+ readonly signal?: AbortSignal
38
+ }
39
+
40
+ export interface CodexImageResult {
41
+ readonly bytes: Buffer
42
+ readonly mediaType: 'image/png' | 'image/gif'
43
+ readonly requestId?: string
44
+ }
45
+
46
+ export interface CodexImageUsageLimit {
47
+ readonly limitId?: string
48
+ /** Epoch milliseconds when the quota comes back, when the backend said. */
49
+ readonly resetsAt?: number
50
+ }
51
+
52
+ /** A failed image request. `usageLimit` is set when the plan's image quota is spent. */
53
+ export class CodexImagesError extends Error {
54
+ readonly status?: number
55
+ readonly usageLimit?: CodexImageUsageLimit
56
+ readonly requestId?: string
57
+ constructor(
58
+ message: string,
59
+ details: { status?: number; usageLimit?: CodexImageUsageLimit; requestId?: string } = {},
60
+ ) {
61
+ super(message)
62
+ this.name = 'CodexImagesError'
63
+ if (details.status !== undefined) this.status = details.status
64
+ if (details.usageLimit !== undefined) this.usageLimit = details.usageLimit
65
+ if (details.requestId !== undefined) this.requestId = details.requestId
66
+ }
67
+ }
68
+
69
+ function asRecord(value: unknown): Record<string, unknown> | null {
70
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
71
+ ? (value as Record<string, unknown>)
72
+ : null
73
+ }
74
+
75
+ /** The headers every ChatGPT-plan request carries, shared with the Responses client. */
76
+ export function codexRequestHeaders(accountId: string): Record<string, string> {
77
+ return {
78
+ ...attributionHeaders(),
79
+ 'ChatGPT-Account-Id': accountId,
80
+ originator: 'Codex Namzu',
81
+ 'User-Agent': 'Codex Namzu/1.0',
82
+ }
83
+ }
84
+
85
+ /** GIF bytes start `GIF87a` or `GIF89a`; everything else the backend sends is a PNG. */
86
+ export function sniffImageType(bytes: Buffer): 'image/png' | 'image/gif' {
87
+ const head = bytes.subarray(0, 6).toString('latin1')
88
+ return head === 'GIF87a' || head === 'GIF89a' ? 'image/gif' : 'image/png'
89
+ }
90
+
91
+ function failureFrom(status: number, text: string, headers: Headers): CodexImagesError {
92
+ const requestId = headers.get('x-codex-imagegen-request-id') ?? undefined
93
+ let body: Record<string, unknown> | null = null
94
+ try {
95
+ body = asRecord(JSON.parse(text))
96
+ } catch {
97
+ body = null
98
+ }
99
+ const error = asRecord(body?.error)
100
+ const type = typeof error?.type === 'string' ? error.type : undefined
101
+ const message =
102
+ (typeof error?.message === 'string' && error.message) || text.trim().slice(0, 300) || ''
103
+ if (status === 429 && type === 'usage_limit_reached') {
104
+ const limitId = headers.get(ACTIVE_LIMIT_HEADER) ?? undefined
105
+ const seconds = typeof error?.resets_at === 'number' ? error.resets_at : undefined
106
+ return new CodexImagesError('The image quota of this plan is used up.', {
107
+ status,
108
+ usageLimit: {
109
+ ...(limitId ? { limitId } : {}),
110
+ ...(seconds !== undefined ? { resetsAt: seconds * 1000 } : {}),
111
+ },
112
+ ...(requestId ? { requestId } : {}),
113
+ })
114
+ }
115
+ return new CodexImagesError(`HTTP ${status}${message ? `: ${message}` : ''}`, {
116
+ status,
117
+ ...(requestId ? { requestId } : {}),
118
+ })
119
+ }
120
+
121
+ /**
122
+ * Generate or edit one image on the ChatGPT plan route. A request with `images`
123
+ * goes to `images/edits`, one without to `images/generations`; both send the
124
+ * same JSON body and read `data[0].b64_json`.
125
+ */
126
+ export async function requestCodexImage(
127
+ config: CodexImagesConfig,
128
+ request: CodexImageRequest,
129
+ ): Promise<CodexImageResult> {
130
+ const base = (config.baseURL ?? CODEX_DEFAULT_BASE_URL).replace(/\/+$/, '')
131
+ const editing = request.images !== undefined && request.images.length > 0
132
+ const url = `${base}/images/${editing ? 'edits' : 'generations'}`
133
+ const body = {
134
+ prompt: request.prompt,
135
+ model: CODEX_IMAGE_MODEL,
136
+ quality: 'auto',
137
+ size: 'auto',
138
+ background: request.transparentBackground === true ? 'transparent' : 'opaque',
139
+ ...(editing ? { images: request.images?.map((image_url) => ({ image_url })) } : {}),
140
+ }
141
+ const timeout = AbortSignal.timeout(config.timeoutMs ?? CODEX_IMAGE_TIMEOUT_MS)
142
+ const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout
143
+ const doFetch = config.fetch ?? fetch
144
+ let response: Response
145
+ try {
146
+ response = await doFetch(url, {
147
+ method: 'POST',
148
+ signal,
149
+ headers: {
150
+ ...codexRequestHeaders(config.accountId),
151
+ ...(config.headers ?? {}),
152
+ Authorization: `Bearer ${config.accessToken}`,
153
+ 'Content-Type': 'application/json',
154
+ Accept: 'application/json',
155
+ ...(request.turnId ? { [IMAGE_TURN_HEADER]: request.turnId } : {}),
156
+ },
157
+ body: JSON.stringify(body),
158
+ })
159
+ } catch (error) {
160
+ if (request.signal?.aborted) throw request.signal.reason ?? error
161
+ if (timeout.aborted) throw new CodexImagesError('The image request timed out.')
162
+ throw new CodexImagesError(
163
+ `The image request could not be sent: ${error instanceof Error ? error.message : String(error)}`,
164
+ )
165
+ }
166
+ const text = await response.text()
167
+ if (!response.ok) throw failureFrom(response.status, text, response.headers)
168
+ const requestId = response.headers.get('x-codex-imagegen-request-id') ?? undefined
169
+ let parsed: Record<string, unknown> | null = null
170
+ try {
171
+ parsed = asRecord(JSON.parse(text))
172
+ } catch {
173
+ throw new CodexImagesError('The image response could not be read.', { requestId })
174
+ }
175
+ const first = Array.isArray(parsed?.data) ? asRecord(parsed.data[0]) : null
176
+ const encoded = typeof first?.b64_json === 'string' ? first.b64_json : ''
177
+ if (encoded === '') throw new CodexImagesError('The image service returned no image data.')
178
+ // Base64 inflates by 4/3; refuse before decoding what could not fit.
179
+ if (Math.ceil(encoded.length * 0.75) > CODEX_IMAGE_MAX_BYTES + 3)
180
+ throw new CodexImagesError('The generated image is larger than 32 MiB and was not kept.')
181
+ const bytes = Buffer.from(encoded, 'base64')
182
+ if (bytes.length === 0) throw new CodexImagesError('The image service returned no image data.')
183
+ if (bytes.length > CODEX_IMAGE_MAX_BYTES)
184
+ throw new CodexImagesError('The generated image is larger than 32 MiB and was not kept.')
185
+ return {
186
+ bytes,
187
+ mediaType: sniffImageType(bytes),
188
+ ...(requestId ? { requestId } : {}),
189
+ }
190
+ }
package/src/index.ts CHANGED
@@ -47,6 +47,22 @@ export {
47
47
  servedSpeed,
48
48
  supportsFastMode,
49
49
  } from './fast-mode.js'
50
+ export {
51
+ CODEX_DEFAULT_BASE_URL,
52
+ CODEX_IMAGE_LIMIT_IDS,
53
+ CODEX_IMAGE_MAX_BYTES,
54
+ CODEX_IMAGE_MODEL,
55
+ CODEX_IMAGE_TIMEOUT_MS,
56
+ CodexImagesError,
57
+ requestCodexImage,
58
+ sniffImageType,
59
+ } from './images.js'
60
+ export type {
61
+ CodexImageRequest,
62
+ CodexImageResult,
63
+ CodexImageUsageLimit,
64
+ CodexImagesConfig,
65
+ } from './images.js'
50
66
  export type {
51
67
  FastTier,
52
68
  OpenAIFastInput,
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Reading limits out of a model catalogue row, shared by the API-key client and the subscription
3
+ * route so the two spell the same fields the same way.
4
+ */
5
+
6
+ /** A number, or a string that holds one (some backends send counts as strings). */
7
+ function asNumber(value: unknown): number | undefined {
8
+ if (typeof value === 'number') return value
9
+ if (typeof value === 'string' && value.trim() !== '') return Number(value)
10
+ return undefined
11
+ }
12
+
13
+ /** The first of these fields of `row` that holds a positive safe integer. */
14
+ export function firstCount(
15
+ row: Record<string, unknown> | undefined,
16
+ wires: readonly string[],
17
+ ): number | undefined {
18
+ for (const wire of wires) {
19
+ const value = asNumber(row?.[wire])
20
+ if (value !== undefined && Number.isSafeInteger(value) && value > 0) return value
21
+ }
22
+ return undefined
23
+ }
24
+
25
+ /** The spellings catalogues use for the context window, in the order they are tried. */
26
+ export const CONTEXT_WINDOW_WIRES: readonly string[] = [
27
+ 'context_window_tokens',
28
+ 'context_window',
29
+ 'context_length',
30
+ 'max_model_len',
31
+ 'max_context_window',
32
+ ]
33
+
34
+ /** The window a catalogue row states, or `undefined` when it states none. */
35
+ export function declaredContextWindow(row: Record<string, unknown> | undefined) {
36
+ return firstCount(row, CONTEXT_WINDOW_WIRES)
37
+ }
38
+
39
+ /** The share of a window the subscription backend counts as usable when its row states none. */
40
+ export const SUBSCRIPTION_DEFAULT_USABLE_PERCENT = 95
41
+
42
+ /** The share of the resolved window the backend caps its auto-compact limit at. */
43
+ const SUBSCRIPTION_COMPACT_CAP_PERCENT = 90
44
+
45
+ /** What the subscription backend's model row says about the window and compaction. */
46
+ export interface SubscriptionLimits {
47
+ /** `context_window`, else `max_context_window`, scaled by the usable percent. */
48
+ readonly contextWindow?: number
49
+ /** The backend's compaction threshold: its limit held to 90% of the window, or 90% alone. */
50
+ readonly autoCompactTokenLimit?: number
51
+ }
52
+
53
+ /**
54
+ * Read one row of the subscription backend's `/models` answer the way the backend defines it:
55
+ *
56
+ * - resolved window = `context_window`, else `max_context_window`
57
+ * - usable window = resolved x `effective_context_window_percent` / 100, the percent being 95
58
+ * when the row omits it
59
+ * - auto-compact limit = `auto_compact_token_limit` held to 90% of the resolved window, or 90%
60
+ * of it alone when the row sends none, or the row's limit alone when there is no window
61
+ *
62
+ * Counts may arrive as numbers or numeric strings. Only this route applies the percent; the
63
+ * other compatible hosts go through `declaredContextWindow`.
64
+ */
65
+ export function subscriptionLimits(row: Record<string, unknown> | undefined): SubscriptionLimits {
66
+ const resolved = firstCount(row, ['context_window', 'max_context_window'])
67
+ const statedLimit = firstCount(row, ['auto_compact_token_limit'])
68
+ const percentValue = asNumber(row?.effective_context_window_percent)
69
+ const percent =
70
+ percentValue !== undefined && Number.isFinite(percentValue) && percentValue > 0
71
+ ? Math.min(percentValue, 100)
72
+ : SUBSCRIPTION_DEFAULT_USABLE_PERCENT
73
+ const contextWindow =
74
+ resolved === undefined ? undefined : Math.max(1, Math.floor((resolved * percent) / 100))
75
+ let autoCompactTokenLimit: number | undefined
76
+ if (resolved !== undefined) {
77
+ const cap = Math.max(1, Math.floor((resolved * SUBSCRIPTION_COMPACT_CAP_PERCENT) / 100))
78
+ autoCompactTokenLimit = statedLimit === undefined ? cap : Math.min(statedLimit, cap)
79
+ } else {
80
+ autoCompactTokenLimit = statedLimit
81
+ }
82
+ return {
83
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
84
+ ...(autoCompactTokenLimit !== undefined ? { autoCompactTokenLimit } : {}),
85
+ }
86
+ }