@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,172 @@
1
+ import { ProviderRequestError } from '@namzu/sdk';
2
+ /**
3
+ * Models that take Fast on the API, with the vendor's multiple of every rate.
4
+ * Source: the Fast table of the API pricing page, checked 2026-11-22. The
5
+ * multiple is per model: gpt-5.5 is billed at 2.5 times, the others at 2.
6
+ */
7
+ export const OPENAI_FAST_TABLE = {
8
+ 'gpt-5.4': 2,
9
+ 'gpt-5.4-mini': 2,
10
+ 'gpt-5.5': 2.5,
11
+ 'gpt-5.6-sol': 2,
12
+ 'gpt-5.6-terra': 2,
13
+ 'gpt-5.6-luna': 2,
14
+ 'gpt-6-sol': 2,
15
+ 'gpt-6-luna': 2,
16
+ 'gpt-6-astra': 2,
17
+ 'gpt-6.1-sol': 2,
18
+ 'gpt-6.1-terra': 2,
19
+ 'gpt-6.2-sol': 2,
20
+ 'gpt-6.2-astra': 2,
21
+ };
22
+ /**
23
+ * How much faster the Codex plan allowance drains on a tier, where a source
24
+ * states it for the model. List-price figures: Ultrafast carries a promotion
25
+ * until 2027-02-28 and these are the figures after it, so a message never
26
+ * understates. Source: the vendor's Codex pricing page, checked 2026-11-22.
27
+ * A model absent here has no stated figure, and the message gives none.
28
+ */
29
+ export const PLAN_MULTIPLIER = {
30
+ fast: {
31
+ 'gpt-6.2-sol': 2,
32
+ 'gpt-6.2-astra': 2,
33
+ 'gpt-6.1-sol': 2.5,
34
+ 'gpt-6.1-terra': 2.5,
35
+ 'gpt-6-astra': 2.5,
36
+ 'gpt-6-sol': 2.5,
37
+ 'gpt-6-luna': 2.5,
38
+ },
39
+ ultrafast: {
40
+ 'gpt-6.2-sol': 6,
41
+ 'gpt-6.2-astra': 6,
42
+ 'gpt-6-astra': 8,
43
+ 'gpt-6.1-sol': 8,
44
+ },
45
+ };
46
+ const SNAPSHOT_SUFFIX = /-\d{4}-\d{2}-\d{2}$/;
47
+ function normalise(model) {
48
+ return model.toLowerCase().replace(SNAPSHOT_SUFFIX, '');
49
+ }
50
+ /** The model list a refusal names, generated from the table so it is never typed twice. */
51
+ function offeredModelsText() {
52
+ const ids = Object.keys(OPENAI_FAST_TABLE);
53
+ const named = ids.filter((id) => !id.startsWith('gpt-6'));
54
+ const families = [
55
+ ...new Set(ids.filter((id) => id.startsWith('gpt-6')).map((id) => id.replace(/-[a-z]+$/, ''))),
56
+ ];
57
+ const familyText = families.length > 1
58
+ ? `${families.slice(0, -1).join(', ')} and ${families[families.length - 1]}`
59
+ : (families[0] ?? '');
60
+ return `${named.join(', ')}, and the ${familyText} models (sol, terra, luna and astra where they exist)`;
61
+ }
62
+ const refuse = (reason) => ({ ok: false, reason });
63
+ /**
64
+ * Whether `tier` may be sent to `model` on `route`, and what it costs. Pure:
65
+ * the request path and a caller deciding whether to offer the mode use this
66
+ * one function, so they cannot disagree.
67
+ */
68
+ export function resolveFastMode(input) {
69
+ const { route, model, tier } = input;
70
+ const id = normalise(model);
71
+ if (route === 'api') {
72
+ if (tier === 'ultrafast') {
73
+ return refuse('Ultrafast is offered through the OpenAI (Codex subscription) sign-in only. /fast turns on fast mode here.');
74
+ }
75
+ if (!input.firstPartyEndpoint) {
76
+ return refuse(`Fast mode is offered on OpenAI's own endpoint only, and requests here go to ${input.host ?? 'another host'}.`);
77
+ }
78
+ const multiplier = OPENAI_FAST_TABLE[id];
79
+ if (multiplier === undefined) {
80
+ return refuse(`Model "${model}" has no fast mode. It is offered on ${offeredModelsText()}; choose one of those with /model.`);
81
+ }
82
+ return {
83
+ ok: true,
84
+ tier: 'fast',
85
+ wire: 'priority',
86
+ rate: { kind: 'billing', multiplier },
87
+ };
88
+ }
89
+ if (input.advertised === undefined) {
90
+ return refuse('Fast mode needs your Codex model list, which has not loaded yet. Try /fast again in a moment.');
91
+ }
92
+ if (!input.advertised.includes(tier)) {
93
+ return refuse(tier === 'ultrafast'
94
+ ? `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.`
95
+ : `Your Codex subscription does not list fast mode for model "${model}". Pick another model with /model.`);
96
+ }
97
+ const multiplier = PLAN_MULTIPLIER[tier][id];
98
+ return {
99
+ ok: true,
100
+ tier,
101
+ wire: tier === 'fast' ? 'priority' : 'ultrafast',
102
+ rate: { kind: 'plan', ...(multiplier !== undefined ? { multiplier } : {}) },
103
+ };
104
+ }
105
+ /** Whether this model takes `tier` on this route right now. */
106
+ export function supportsFastMode(input) {
107
+ return resolveFastMode(input).ok;
108
+ }
109
+ /**
110
+ * Refuse, before transport, a tier the route would drop or answer with an
111
+ * error. Returns the wire value to send and, on the subscription route, the
112
+ * routing header that goes with it. The error is the `bad_request` the
113
+ * vendor's 400 would have become, with its own code.
114
+ */
115
+ export function assertFastModeAccepted(input) {
116
+ const verdict = resolveFastMode(input);
117
+ if (!verdict.ok) {
118
+ throw new ProviderRequestError({
119
+ kind: 'bad_request',
120
+ providerId: input.route === 'api' ? 'openai' : 'codex',
121
+ providerCode: 'fast_mode_unsupported',
122
+ detail: verdict.reason,
123
+ });
124
+ }
125
+ return {
126
+ wire: verdict.wire,
127
+ ...(input.route === 'subscription'
128
+ ? {
129
+ header: {
130
+ 'x-codex-routing-hint': `model=${input.model};tier=${verdict.wire}`,
131
+ },
132
+ }
133
+ : {}),
134
+ };
135
+ }
136
+ /** Whether a base URL is OpenAI's own API host (no URL at all means the default, which is). */
137
+ export function isFirstPartyOpenAIEndpoint(baseURL) {
138
+ if (!baseURL)
139
+ return true;
140
+ try {
141
+ return new URL(baseURL).hostname === 'api.openai.com';
142
+ }
143
+ catch {
144
+ return true;
145
+ }
146
+ }
147
+ /**
148
+ * What a response's `service_tier` says about the call, as the fields
149
+ * `TokenUsage` carries. `priority` and `fast` are Fast and are reported
150
+ * through `speed`, never through `serviceTier` (which the cost rule reads as
151
+ * "unpriced" for `priority`). `default` and `auto` are standard: a request
152
+ * downgraded under load bills at the standard rate. No echo means the tier
153
+ * asked for, so an unreported speed is never priced below what was requested.
154
+ */
155
+ export function servedSpeed(served, requested) {
156
+ if (typeof served === 'string' && served.length > 0) {
157
+ switch (served) {
158
+ case 'priority':
159
+ case 'fast':
160
+ return { speed: 'fast' };
161
+ case 'ultrafast':
162
+ return { speed: 'ultrafast' };
163
+ case 'default':
164
+ case 'auto':
165
+ return {};
166
+ default:
167
+ return { serviceTier: served };
168
+ }
169
+ }
170
+ return requested === 'fast' || requested === 'ultrafast' ? { speed: requested } : {};
171
+ }
172
+ //# sourceMappingURL=fast-mode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fast-mode.js","sourceRoot":"","sources":["../src/fast-mode.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAA;AAuDjD;;;;GAIG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAqC;IAClE,SAAS,EAAE,CAAC;IACZ,cAAc,EAAE,CAAC;IACjB,SAAS,EAAE,GAAG;IACd,aAAa,EAAE,CAAC;IAChB,eAAe,EAAE,CAAC;IAClB,cAAc,EAAE,CAAC;IACjB,WAAW,EAAE,CAAC;IACd,YAAY,EAAE,CAAC;IACf,aAAa,EAAE,CAAC;IAChB,aAAa,EAAE,CAAC;IAChB,eAAe,EAAE,CAAC;IAClB,aAAa,EAAE,CAAC;IAChB,eAAe,EAAE,CAAC;CAClB,CAAA;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAiE;IAC5F,IAAI,EAAE;QACL,aAAa,EAAE,CAAC;QAChB,eAAe,EAAE,CAAC;QAClB,aAAa,EAAE,GAAG;QAClB,eAAe,EAAE,GAAG;QACpB,aAAa,EAAE,GAAG;QAClB,WAAW,EAAE,GAAG;QAChB,YAAY,EAAE,GAAG;KACjB;IACD,SAAS,EAAE;QACV,aAAa,EAAE,CAAC;QAChB,eAAe,EAAE,CAAC;QAClB,aAAa,EAAE,CAAC;QAChB,aAAa,EAAE,CAAC;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AQ,KAAK,gBAAgB,CAAA;IACtD,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,IAAI,CAAA;IACZ,CAAC;AACF,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,WAAW,CAC1B,MAAe,EACf,SAAqC;IAErC,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrD,QAAQ,MAAM,EAAE,CAAC;YAChB,KAAK,UAAU,CAAC;YAChB,KAAK,MAAM;gBACV,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAA;YACzB,KAAK,WAAW;gBACf,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,CAAA;YAC9B,KAAK,SAAS,CAAC;YACf,KAAK,MAAM;gBACV,OAAO,EAAE,CAAA;YACV;gBACC,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,CAAA;QAChC,CAAC;IACF,CAAC;IACD,OAAO,SAAS,KAAK,MAAM,IAAI,SAAS,KAAK,WAAW,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAAA;AACrF,CAAC"}
package/dist/index.d.ts CHANGED
@@ -20,5 +20,7 @@ export declare function registerCodex(options?: RegisterOptions): void;
20
20
  export declare function registerOpenAI(options?: RegisterOptions): void;
21
21
  export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels, } from './client.js';
22
22
  export { CODEX_CAPABILITIES, CodexProvider, } from './codex.js';
23
+ export { OPENAI_FAST_TABLE, PLAN_MULTIPLIER, isFirstPartyOpenAIEndpoint, resolveFastMode as resolveFastModeVerdict, servedSpeed, supportsFastMode, } from './fast-mode.js';
24
+ export type { FastTier, OpenAIFastInput, OpenAIFastRate, OpenAIFastRoute, OpenAIFastVerdict, } from './fast-mode.js';
23
25
  export type { CodexConfig, CodexProviderConfig, OpenAIConfig, OpenAIProviderConfig, } from './types.js';
24
26
  //# 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;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"}
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,OAAO,EACN,iBAAiB,EACjB,eAAe,EACf,0BAA0B,EAC1B,eAAe,IAAI,sBAAsB,EACzC,WAAW,EACX,gBAAgB,GAChB,MAAM,gBAAgB,CAAA;AACvB,YAAY,EACX,QAAQ,EACR,eAAe,EACf,cAAc,EACd,eAAe,EACf,iBAAiB,GACjB,MAAM,gBAAgB,CAAA;AACvB,YAAY,EACX,WAAW,EACX,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,GACpB,MAAM,YAAY,CAAA"}
package/dist/index.js CHANGED
@@ -18,4 +18,5 @@ export function registerOpenAI(options) {
18
18
  }
19
19
  export { OPENAI_CAPABILITIES, OpenAIProvider, openAIReasoningEffortLevels, } from './client.js';
20
20
  export { CODEX_CAPABILITIES, CodexProvider, } from './codex.js';
21
+ export { OPENAI_FAST_TABLE, PLAN_MULTIPLIER, isFirstPartyOpenAIEndpoint, resolveFastMode as resolveFastModeVerdict, servedSpeed, supportsFastMode, } from './fast-mode.js';
21
22
  //# 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;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"}
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;AACnB,OAAO,EACN,iBAAiB,EACjB,eAAe,EACf,0BAA0B,EAC1B,eAAe,IAAI,sBAAsB,EACzC,WAAW,EACX,gBAAgB,GAChB,MAAM,gBAAgB,CAAA"}
@@ -0,0 +1,33 @@
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
+ /** The first of these fields of `row` that holds a positive safe integer. */
6
+ export declare function firstCount(row: Record<string, unknown> | undefined, wires: readonly string[]): number | undefined;
7
+ /** The spellings catalogues use for the context window, in the order they are tried. */
8
+ export declare const CONTEXT_WINDOW_WIRES: readonly string[];
9
+ /** The window a catalogue row states, or `undefined` when it states none. */
10
+ export declare function declaredContextWindow(row: Record<string, unknown> | undefined): number | undefined;
11
+ /** The share of a window the subscription backend counts as usable when its row states none. */
12
+ export declare const SUBSCRIPTION_DEFAULT_USABLE_PERCENT = 95;
13
+ /** What the subscription backend's model row says about the window and compaction. */
14
+ export interface SubscriptionLimits {
15
+ /** `context_window`, else `max_context_window`, scaled by the usable percent. */
16
+ readonly contextWindow?: number;
17
+ /** The backend's compaction threshold: its limit held to 90% of the window, or 90% alone. */
18
+ readonly autoCompactTokenLimit?: number;
19
+ }
20
+ /**
21
+ * Read one row of the subscription backend's `/models` answer the way the backend defines it:
22
+ *
23
+ * - resolved window = `context_window`, else `max_context_window`
24
+ * - usable window = resolved x `effective_context_window_percent` / 100, the percent being 95
25
+ * when the row omits it
26
+ * - auto-compact limit = `auto_compact_token_limit` held to 90% of the resolved window, or 90%
27
+ * of it alone when the row sends none, or the row's limit alone when there is no window
28
+ *
29
+ * Counts may arrive as numbers or numeric strings. Only this route applies the percent; the
30
+ * other compatible hosts go through `declaredContextWindow`.
31
+ */
32
+ export declare function subscriptionLimits(row: Record<string, unknown> | undefined): SubscriptionLimits;
33
+ //# sourceMappingURL=model-limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-limits.d.ts","sourceRoot":"","sources":["../src/model-limits.ts"],"names":[],"mappings":"AAAA;;;GAGG;AASH,6EAA6E;AAC7E,wBAAgB,UAAU,CACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACxC,KAAK,EAAE,SAAS,MAAM,EAAE,GACtB,MAAM,GAAG,SAAS,CAMpB;AAED,wFAAwF;AACxF,eAAO,MAAM,oBAAoB,EAAE,SAAS,MAAM,EAMjD,CAAA;AAED,6EAA6E;AAC7E,wBAAgB,qBAAqB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,sBAE7E;AAED,gGAAgG;AAChG,eAAO,MAAM,mCAAmC,KAAK,CAAA;AAKrD,sFAAsF;AACtF,MAAM,WAAW,kBAAkB;IAClC,iFAAiF;IACjF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;IAC/B,6FAA6F;IAC7F,QAAQ,CAAC,qBAAqB,CAAC,EAAE,MAAM,CAAA;CACvC;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,GAAG,kBAAkB,CAqB/F"}
@@ -0,0 +1,71 @@
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
+ /** A number, or a string that holds one (some backends send counts as strings). */
6
+ function asNumber(value) {
7
+ if (typeof value === 'number')
8
+ return value;
9
+ if (typeof value === 'string' && value.trim() !== '')
10
+ return Number(value);
11
+ return undefined;
12
+ }
13
+ /** The first of these fields of `row` that holds a positive safe integer. */
14
+ export function firstCount(row, wires) {
15
+ for (const wire of wires) {
16
+ const value = asNumber(row?.[wire]);
17
+ if (value !== undefined && Number.isSafeInteger(value) && value > 0)
18
+ return value;
19
+ }
20
+ return undefined;
21
+ }
22
+ /** The spellings catalogues use for the context window, in the order they are tried. */
23
+ export const CONTEXT_WINDOW_WIRES = [
24
+ 'context_window_tokens',
25
+ 'context_window',
26
+ 'context_length',
27
+ 'max_model_len',
28
+ 'max_context_window',
29
+ ];
30
+ /** The window a catalogue row states, or `undefined` when it states none. */
31
+ export function declaredContextWindow(row) {
32
+ return firstCount(row, CONTEXT_WINDOW_WIRES);
33
+ }
34
+ /** The share of a window the subscription backend counts as usable when its row states none. */
35
+ export const SUBSCRIPTION_DEFAULT_USABLE_PERCENT = 95;
36
+ /** The share of the resolved window the backend caps its auto-compact limit at. */
37
+ const SUBSCRIPTION_COMPACT_CAP_PERCENT = 90;
38
+ /**
39
+ * Read one row of the subscription backend's `/models` answer the way the backend defines it:
40
+ *
41
+ * - resolved window = `context_window`, else `max_context_window`
42
+ * - usable window = resolved x `effective_context_window_percent` / 100, the percent being 95
43
+ * when the row omits it
44
+ * - auto-compact limit = `auto_compact_token_limit` held to 90% of the resolved window, or 90%
45
+ * of it alone when the row sends none, or the row's limit alone when there is no window
46
+ *
47
+ * Counts may arrive as numbers or numeric strings. Only this route applies the percent; the
48
+ * other compatible hosts go through `declaredContextWindow`.
49
+ */
50
+ export function subscriptionLimits(row) {
51
+ const resolved = firstCount(row, ['context_window', 'max_context_window']);
52
+ const statedLimit = firstCount(row, ['auto_compact_token_limit']);
53
+ const percentValue = asNumber(row?.effective_context_window_percent);
54
+ const percent = percentValue !== undefined && Number.isFinite(percentValue) && percentValue > 0
55
+ ? Math.min(percentValue, 100)
56
+ : SUBSCRIPTION_DEFAULT_USABLE_PERCENT;
57
+ const contextWindow = resolved === undefined ? undefined : Math.max(1, Math.floor((resolved * percent) / 100));
58
+ let autoCompactTokenLimit;
59
+ if (resolved !== undefined) {
60
+ const cap = Math.max(1, Math.floor((resolved * SUBSCRIPTION_COMPACT_CAP_PERCENT) / 100));
61
+ autoCompactTokenLimit = statedLimit === undefined ? cap : Math.min(statedLimit, cap);
62
+ }
63
+ else {
64
+ autoCompactTokenLimit = statedLimit;
65
+ }
66
+ return {
67
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
68
+ ...(autoCompactTokenLimit !== undefined ? { autoCompactTokenLimit } : {}),
69
+ };
70
+ }
71
+ //# sourceMappingURL=model-limits.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model-limits.js","sourceRoot":"","sources":["../src/model-limits.ts"],"names":[],"m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2
  "name": "@namzu/openai",
3
- "version": "4.5.0",
3
+ "version": "4.7.0",
4
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": {
@@ -57,7 +57,7 @@
57
57
  "@types/node": "^22.19.17",
58
58
  "typescript": "^5.5.0",
59
59
  "vitest": "^4.1.11",
60
- "@namzu/sdk": "^62.0.0"
60
+ "@namzu/sdk": "^69.0.0"
61
61
  },
62
62
  "scripts": {
63
63
  "build": "tsc --build",
package/src/client.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  ChatCompletionParams,
3
3
  ChatCompletionResponse,
4
+ InferenceSpeed,
4
5
  LLMProvider,
5
6
  ModelInfo,
6
7
  ProviderCapabilities,
@@ -26,6 +27,8 @@ import type {
26
27
  ChatCompletionTool,
27
28
  ChatCompletionToolChoiceOption,
28
29
  } from 'openai/resources/chat/completions'
30
+ import { assertFastModeAccepted, isFirstPartyOpenAIEndpoint, servedSpeed } from './fast-mode.js'
31
+ import { declaredContextWindow, firstCount } from './model-limits.js'
29
32
  import type { OpenAIConfig } from './types.js'
30
33
 
31
34
  /**
@@ -109,11 +112,16 @@ export function openAIReasoningEffortLevels(model: string): readonly ReasoningEf
109
112
 
110
113
  /** Whether a base URL names a host other than OpenAI's own API. */
111
114
  function isCompatibleHost(baseURL: string | undefined): boolean {
112
- if (!baseURL) return false
115
+ return !isFirstPartyOpenAIEndpoint(baseURL)
116
+ }
117
+
118
+ /** The host a base URL names, for a refusal that has to say where requests go. */
119
+ function hostOf(baseURL: string | undefined): string | undefined {
120
+ if (!baseURL) return undefined
113
121
  try {
114
- return new URL(baseURL).hostname !== 'api.openai.com'
122
+ return new URL(baseURL).hostname
115
123
  } catch {
116
- return false
124
+ return undefined
117
125
  }
118
126
  }
119
127
 
@@ -141,15 +149,6 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
141
149
  : undefined
142
150
  }
143
151
 
144
- /** The first of these fields of `row` that holds a positive safe integer. */
145
- function firstCount(row: Record<string, unknown> | undefined, wires: readonly string[]) {
146
- for (const wire of wires) {
147
- const value = row?.[wire]
148
- if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return value
149
- }
150
- return undefined
151
- }
152
-
153
152
  /** A price per token that is a number or a numeric string, as a rate per million tokens. */
154
153
  function ratePerMillion(value: unknown): number | undefined {
155
154
  const perToken = typeof value === 'string' && value.trim() !== '' ? Number(value) : value
@@ -187,12 +186,7 @@ function compatibleModelMetadata(model: unknown): Partial<ModelInfo> {
187
186
 
188
187
  // Catalogues spell the same limits several ways: the first spelling that holds a positive
189
188
  // integer wins.
190
- const contextWindow = firstCount(row, [
191
- 'context_window_tokens',
192
- 'context_window',
193
- 'context_length',
194
- 'max_model_len',
195
- ])
189
+ const contextWindow = declaredContextWindow(row)
196
190
  if (contextWindow !== undefined) result.contextWindow = contextWindow
197
191
  const maxOutputTokens =
198
192
  firstCount(row, ['maximum_output_tokens', 'max_output_tokens', 'max_completion_tokens']) ??
@@ -297,7 +291,11 @@ interface RawOpenAIUsage {
297
291
  prompt_tokens_details?: { cached_tokens?: number }
298
292
  }
299
293
 
300
- function parseUsage(raw?: RawOpenAIUsage | null): TokenUsage {
294
+ function parseUsage(
295
+ raw?: RawOpenAIUsage | null,
296
+ servedTier?: unknown,
297
+ requestedSpeed?: InferenceSpeed,
298
+ ): TokenUsage {
301
299
  if (!raw) {
302
300
  return {
303
301
  promptTokens: 0,
@@ -315,6 +313,7 @@ function parseUsage(raw?: RawOpenAIUsage | null): TokenUsage {
315
313
  totalTokens: raw.total_tokens ?? promptTokens + completionTokens,
316
314
  cachedTokens: raw.prompt_tokens_details?.cached_tokens ?? 0,
317
315
  cacheWriteTokens: 0,
316
+ ...servedSpeed(servedTier, requestedSpeed),
318
317
  }
319
318
  }
320
319
 
@@ -497,6 +496,8 @@ export class OpenAIProvider implements LLMProvider {
497
496
  /** Before this time (ms since the epoch) a failed listing is not asked for again. */
498
497
  private windowListingRetryAt = 0
499
498
  private thinkingOffFields: OpenAIConfig['thinkingOffFields']
499
+ /** The base URL requests go to, kept to name the host when fast mode is refused there. */
500
+ private readonly effectiveBaseURL: string | undefined
500
501
 
501
502
  constructor(config: OpenAIConfig) {
502
503
  if (!config.apiKey) {
@@ -523,7 +524,8 @@ export class OpenAIProvider implements LLMProvider {
523
524
  this.defaultModel = config.model
524
525
  this.thinkingOffFields = config.thinkingOffFields
525
526
  // The client reads the standard base-URL variable when none is given, so that is where requests go.
526
- this.compatibleHost = isCompatibleHost(config.baseURL ?? process.env.OPENAI_BASE_URL)
527
+ this.effectiveBaseURL = config.baseURL ?? process.env.OPENAI_BASE_URL
528
+ this.compatibleHost = isCompatibleHost(this.effectiveBaseURL)
527
529
  }
528
530
 
529
531
  /**
@@ -594,6 +596,23 @@ export class OpenAIProvider implements LLMProvider {
594
596
  : this.thinkingOffFields
595
597
  : undefined
596
598
 
599
+ // Fast mode is admitted or refused here, before transport: a model or an
600
+ // endpoint that does not take the tier would otherwise serve standard
601
+ // speed (or fail) while the caller believes it was honoured. Only the
602
+ // fast tier has a wire value; the verdict refuses `ultrafast` on this route.
603
+ let serviceTier: 'priority' | undefined
604
+ if (params.speed === 'fast' || params.speed === 'ultrafast') {
605
+ const accepted = assertFastModeAccepted({
606
+ route: 'api',
607
+ model,
608
+ tier: params.speed,
609
+ firstPartyEndpoint: !this.compatibleHost,
610
+ host: hostOf(this.effectiveBaseURL),
611
+ })
612
+ serviceTier = accepted.wire === 'priority' ? 'priority' : undefined
613
+ }
614
+ const requestedSpeed = params.speed === 'fast' ? ('fast' as const) : undefined
615
+
597
616
  let stream: Awaited<ReturnType<typeof this.client.chat.completions.create>>
598
617
  try {
599
618
  stream = await this.client.chat.completions.create(
@@ -613,6 +632,7 @@ export class OpenAIProvider implements LLMProvider {
613
632
  presence_penalty: params.presencePenalty,
614
633
  stop: params.stop,
615
634
  response_format: params.responseFormat,
635
+ ...(serviceTier ? { service_tier: serviceTier } : {}),
616
636
  ...(offFields ?? {}),
617
637
  },
618
638
  params.effort,
@@ -634,8 +654,12 @@ export class OpenAIProvider implements LLMProvider {
634
654
  // A choice reported why it stopped. A stream that closes without one was
635
655
  // cut by the connection, and what it carried is not a whole response.
636
656
  let finished = false
657
+ // The tier the service says served the call, from whichever chunk carries it.
658
+ let servedTier: unknown
637
659
  try {
638
660
  for await (const chunk of stream) {
661
+ const echoed = (chunk as { service_tier?: unknown }).service_tier
662
+ if (typeof echoed === 'string' && echoed.length > 0) servedTier = echoed
639
663
  // Stop pulling promptly on abort; `for await` calls the stream's
640
664
  // `.return()` on this throw, releasing the connection.
641
665
  params.signal?.throwIfAborted()
@@ -674,7 +698,9 @@ export class OpenAIProvider implements LLMProvider {
674
698
  const finishReason = choice?.finish_reason
675
699
  ? mapFinishReason(choice.finish_reason)
676
700
  : undefined
677
- const usage = chunk.usage ? parseUsage(chunk.usage) : undefined
701
+ const usage = chunk.usage
702
+ ? parseUsage(chunk.usage, servedTier, requestedSpeed)
703
+ : undefined
678
704
  if (finishReason) finished = true
679
705
 
680
706
  if (!hasDelta && !finishReason && !usage) continue
@@ -684,7 +710,13 @@ export class OpenAIProvider implements LLMProvider {
684
710
  delta: {
685
711
  content: delta?.content ?? undefined,
686
712
  ...(reasoning
687
- ? { reasoning: { index: 0, type: 'thinking' as const, text: reasoning } }
713
+ ? {
714
+ reasoning: {
715
+ index: 0,
716
+ type: 'thinking' as const,
717
+ text: reasoning,
718
+ },
719
+ }
688
720
  : {}),
689
721
  toolCalls,
690
722
  },