@namzu/openai 4.5.0 → 4.7.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.
@@ -0,0 +1,250 @@
1
+ import { ProviderRequestError } from '@namzu/sdk'
2
+ import type { InferenceSpeed, TokenUsage } from '@namzu/sdk'
3
+
4
+ /**
5
+ * Fast mode on OpenAI models: a premium low-latency tier, asked for with
6
+ * `speed: 'fast'` (or `'ultrafast'` where the route offers it).
7
+ *
8
+ * Two routes, decided differently because the evidence differs:
9
+ *
10
+ * - `api` (an API key, Chat Completions): a table of exact model ids, from the
11
+ * Fast rows of the vendor's API pricing page and its fast-mode guide
12
+ * (checked 2026-11-22). A table and not a floor, because OpenAI ids do not
13
+ * follow one family-and-version grammar. A model absent from the table is
14
+ * refused until a one-line change, which is cheaper than sending a tier a
15
+ * model rejects. `ultrafast` is never sent here: Chat Completions has no such
16
+ * value.
17
+ * - `subscription` (the Codex subscription, Responses): no model list in code.
18
+ * The account's own model listing says which tiers a model offers
19
+ * (`ModelInfo.speedTiers`), and a tier is admitted only when it is listed.
20
+ *
21
+ * Everything else is refused here, before transport, so the rule is one rule:
22
+ * `fast` means fast or an error, never a quiet standard-speed reply.
23
+ */
24
+
25
+ export type OpenAIFastRoute = 'api' | 'subscription'
26
+ export type FastTier = 'fast' | 'ultrafast'
27
+
28
+ export interface OpenAIFastRate {
29
+ /** `billing`: a multiple of the per-token rate. `plan`: the subscription allowance drains faster. */
30
+ readonly kind: 'billing' | 'plan'
31
+ /** Stated by a source for this model; absent when no source states one. Never invented. */
32
+ readonly multiplier?: number
33
+ }
34
+
35
+ export type OpenAIFastVerdict =
36
+ | {
37
+ readonly ok: true
38
+ readonly tier: FastTier
39
+ readonly wire: 'priority' | 'ultrafast'
40
+ readonly rate: OpenAIFastRate
41
+ }
42
+ | { readonly ok: false; readonly reason: string }
43
+
44
+ export interface OpenAIFastInput {
45
+ readonly route: OpenAIFastRoute
46
+ readonly model: string
47
+ readonly tier: FastTier
48
+ /** Subscription only: the tiers the account's model listing established for `model`. Absent: not loaded. */
49
+ readonly advertised?: readonly FastTier[]
50
+ /** Whether requests go to OpenAI's own endpoint. Only the `api` route reads it. */
51
+ readonly firstPartyEndpoint: boolean
52
+ /** The host requests go to, named in the refusal when it is not OpenAI's own. */
53
+ readonly host?: string
54
+ }
55
+
56
+ /**
57
+ * Models that take Fast on the API, with the vendor's multiple of every rate.
58
+ * Source: the Fast table of the API pricing page, checked 2026-11-22. The
59
+ * multiple is per model: gpt-5.5 is billed at 2.5 times, the others at 2.
60
+ */
61
+ export const OPENAI_FAST_TABLE: Readonly<Record<string, number>> = {
62
+ 'gpt-5.4': 2,
63
+ 'gpt-5.4-mini': 2,
64
+ 'gpt-5.5': 2.5,
65
+ 'gpt-5.6-sol': 2,
66
+ 'gpt-5.6-terra': 2,
67
+ 'gpt-5.6-luna': 2,
68
+ 'gpt-6-sol': 2,
69
+ 'gpt-6-luna': 2,
70
+ 'gpt-6-astra': 2,
71
+ 'gpt-6.1-sol': 2,
72
+ 'gpt-6.1-terra': 2,
73
+ 'gpt-6.2-sol': 2,
74
+ 'gpt-6.2-astra': 2,
75
+ }
76
+
77
+ /**
78
+ * How much faster the Codex plan allowance drains on a tier, where a source
79
+ * states it for the model. List-price figures: Ultrafast carries a promotion
80
+ * until 2027-02-28 and these are the figures after it, so a message never
81
+ * understates. Source: the vendor's Codex pricing page, checked 2026-11-22.
82
+ * A model absent here has no stated figure, and the message gives none.
83
+ */
84
+ export const PLAN_MULTIPLIER: Readonly<Record<FastTier, Readonly<Record<string, number>>>> = {
85
+ fast: {
86
+ 'gpt-6.2-sol': 2,
87
+ 'gpt-6.2-astra': 2,
88
+ 'gpt-6.1-sol': 2.5,
89
+ 'gpt-6.1-terra': 2.5,
90
+ 'gpt-6-astra': 2.5,
91
+ 'gpt-6-sol': 2.5,
92
+ 'gpt-6-luna': 2.5,
93
+ },
94
+ ultrafast: {
95
+ 'gpt-6.2-sol': 6,
96
+ 'gpt-6.2-astra': 6,
97
+ 'gpt-6-astra': 8,
98
+ 'gpt-6.1-sol': 8,
99
+ },
100
+ }
101
+
102
+ const SNAPSHOT_SUFFIX = /-\d{4}-\d{2}-\d{2}$/
103
+
104
+ function normalise(model: string): string {
105
+ return model.toLowerCase().replace(SNAPSHOT_SUFFIX, '')
106
+ }
107
+
108
+ /** The model list a refusal names, generated from the table so it is never typed twice. */
109
+ function offeredModelsText(): string {
110
+ const ids = Object.keys(OPENAI_FAST_TABLE)
111
+ const named = ids.filter((id) => !id.startsWith('gpt-6'))
112
+ const families = [
113
+ ...new Set(ids.filter((id) => id.startsWith('gpt-6')).map((id) => id.replace(/-[a-z]+$/, ''))),
114
+ ]
115
+ const familyText =
116
+ families.length > 1
117
+ ? `${families.slice(0, -1).join(', ')} and ${families[families.length - 1]}`
118
+ : (families[0] ?? '')
119
+ return `${named.join(', ')}, and the ${familyText} models (sol, terra, luna and astra where they exist)`
120
+ }
121
+
122
+ const refuse = (reason: string): OpenAIFastVerdict => ({ ok: false, reason })
123
+
124
+ /**
125
+ * Whether `tier` may be sent to `model` on `route`, and what it costs. Pure:
126
+ * the request path and a caller deciding whether to offer the mode use this
127
+ * one function, so they cannot disagree.
128
+ */
129
+ export function resolveFastMode(input: OpenAIFastInput): OpenAIFastVerdict {
130
+ const { route, model, tier } = input
131
+ const id = normalise(model)
132
+ if (route === 'api') {
133
+ if (tier === 'ultrafast') {
134
+ return refuse(
135
+ 'Ultrafast is offered through the OpenAI (Codex subscription) sign-in only. /fast turns on fast mode here.',
136
+ )
137
+ }
138
+ if (!input.firstPartyEndpoint) {
139
+ return refuse(
140
+ `Fast mode is offered on OpenAI's own endpoint only, and requests here go to ${input.host ?? 'another host'}.`,
141
+ )
142
+ }
143
+ const multiplier = OPENAI_FAST_TABLE[id]
144
+ if (multiplier === undefined) {
145
+ return refuse(
146
+ `Model "${model}" has no fast mode. It is offered on ${offeredModelsText()}; choose one of those with /model.`,
147
+ )
148
+ }
149
+ return {
150
+ ok: true,
151
+ tier: 'fast',
152
+ wire: 'priority',
153
+ rate: { kind: 'billing', multiplier },
154
+ }
155
+ }
156
+ if (input.advertised === undefined) {
157
+ return refuse(
158
+ 'Fast mode needs your Codex model list, which has not loaded yet. Try /fast again in a moment.',
159
+ )
160
+ }
161
+ if (!input.advertised.includes(tier)) {
162
+ return refuse(
163
+ tier === 'ultrafast'
164
+ ? `Your Codex subscription does not list Ultrafast for model "${model}". It is offered on some plans and models only; /fast turns on fast mode instead.`
165
+ : `Your Codex subscription does not list fast mode for model "${model}". Pick another model with /model.`,
166
+ )
167
+ }
168
+ const multiplier = PLAN_MULTIPLIER[tier][id]
169
+ return {
170
+ ok: true,
171
+ tier,
172
+ wire: tier === 'fast' ? 'priority' : 'ultrafast',
173
+ rate: { kind: 'plan', ...(multiplier !== undefined ? { multiplier } : {}) },
174
+ }
175
+ }
176
+
177
+ /** Whether this model takes `tier` on this route right now. */
178
+ export function supportsFastMode(input: OpenAIFastInput): boolean {
179
+ return resolveFastMode(input).ok
180
+ }
181
+
182
+ /**
183
+ * Refuse, before transport, a tier the route would drop or answer with an
184
+ * error. Returns the wire value to send and, on the subscription route, the
185
+ * routing header that goes with it. The error is the `bad_request` the
186
+ * vendor's 400 would have become, with its own code.
187
+ */
188
+ export function assertFastModeAccepted(input: OpenAIFastInput): {
189
+ wire: 'priority' | 'ultrafast'
190
+ header?: Record<string, string>
191
+ } {
192
+ const verdict = resolveFastMode(input)
193
+ if (!verdict.ok) {
194
+ throw new ProviderRequestError({
195
+ kind: 'bad_request',
196
+ providerId: input.route === 'api' ? 'openai' : 'codex',
197
+ providerCode: 'fast_mode_unsupported',
198
+ detail: verdict.reason,
199
+ })
200
+ }
201
+ return {
202
+ wire: verdict.wire,
203
+ ...(input.route === 'subscription'
204
+ ? {
205
+ header: {
206
+ 'x-codex-routing-hint': `model=${input.model};tier=${verdict.wire}`,
207
+ },
208
+ }
209
+ : {}),
210
+ }
211
+ }
212
+
213
+ /** Whether a base URL is OpenAI's own API host (no URL at all means the default, which is). */
214
+ export function isFirstPartyOpenAIEndpoint(baseURL: string | undefined): boolean {
215
+ if (!baseURL) return true
216
+ try {
217
+ return new URL(baseURL).hostname === 'api.openai.com'
218
+ } catch {
219
+ return true
220
+ }
221
+ }
222
+
223
+ /**
224
+ * What a response's `service_tier` says about the call, as the fields
225
+ * `TokenUsage` carries. `priority` and `fast` are Fast and are reported
226
+ * through `speed`, never through `serviceTier` (which the cost rule reads as
227
+ * "unpriced" for `priority`). `default` and `auto` are standard: a request
228
+ * downgraded under load bills at the standard rate. No echo means the tier
229
+ * asked for, so an unreported speed is never priced below what was requested.
230
+ */
231
+ export function servedSpeed(
232
+ served: unknown,
233
+ requested: InferenceSpeed | undefined,
234
+ ): Pick<TokenUsage, 'speed' | 'serviceTier'> {
235
+ if (typeof served === 'string' && served.length > 0) {
236
+ switch (served) {
237
+ case 'priority':
238
+ case 'fast':
239
+ return { speed: 'fast' }
240
+ case 'ultrafast':
241
+ return { speed: 'ultrafast' }
242
+ case 'default':
243
+ case 'auto':
244
+ return {}
245
+ default:
246
+ return { serviceTier: served }
247
+ }
248
+ }
249
+ return requested === 'fast' || requested === 'ultrafast' ? { speed: requested } : {}
250
+ }
package/src/index.ts CHANGED
@@ -39,6 +39,21 @@ export {
39
39
  CODEX_CAPABILITIES,
40
40
  CodexProvider,
41
41
  } from './codex.js'
42
+ export {
43
+ OPENAI_FAST_TABLE,
44
+ PLAN_MULTIPLIER,
45
+ isFirstPartyOpenAIEndpoint,
46
+ resolveFastMode as resolveFastModeVerdict,
47
+ servedSpeed,
48
+ supportsFastMode,
49
+ } from './fast-mode.js'
50
+ export type {
51
+ FastTier,
52
+ OpenAIFastInput,
53
+ OpenAIFastRate,
54
+ OpenAIFastRoute,
55
+ OpenAIFastVerdict,
56
+ } from './fast-mode.js'
42
57
  export type {
43
58
  CodexConfig,
44
59
  CodexProviderConfig,
@@ -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
+ }