@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.
package/src/codex.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type {
2
2
  AssistantTextPart,
3
3
  ChatCompletionParams,
4
+ InferenceSpeed,
4
5
  LLMProvider,
5
6
  ModelInfo,
6
7
  ProviderCapabilities,
@@ -31,6 +32,8 @@ import type {
31
32
  Tool,
32
33
  } from 'openai/resources/responses/responses'
33
34
 
35
+ import { type FastTier, assertFastModeAccepted, servedSpeed } from './fast-mode.js'
36
+ import { subscriptionLimits } from './model-limits.js'
34
37
  import type { CodexConfig } from './types.js'
35
38
 
36
39
  export const CODEX_CAPABILITIES: ProviderCapabilities = {
@@ -260,10 +263,18 @@ function codexToolOutput(
260
263
  export function toCodexInput(
261
264
  messages: ChatCompletionParams['messages'],
262
265
  targetRoute: ProviderRoute,
266
+ openingSystemRun = messages.findIndex((message) => message.role !== 'system'),
263
267
  ): ResponseInputItem[] {
264
268
  const input: ResponseInputItem[] = []
265
- for (const message of messages) {
266
- 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
+ }
267
278
  if (message.role === 'user') {
268
279
  input.push({
269
280
  type: 'message',
@@ -336,12 +347,16 @@ export function toCodexTools(params: ChatCompletionParams): Tool[] | undefined {
336
347
  return tools.length ? tools : undefined
337
348
  }
338
349
 
339
- function responseUsage(usage: {
340
- input_tokens?: number
341
- output_tokens?: number
342
- total_tokens?: number
343
- input_tokens_details?: { cached_tokens?: number }
344
- }): TokenUsage {
350
+ function responseUsage(
351
+ usage: {
352
+ input_tokens?: number
353
+ output_tokens?: number
354
+ total_tokens?: number
355
+ input_tokens_details?: { cached_tokens?: number }
356
+ },
357
+ servedTier?: unknown,
358
+ requestedSpeed?: InferenceSpeed,
359
+ ): TokenUsage {
345
360
  const promptTokens = usage.input_tokens ?? 0
346
361
  const completionTokens = usage.output_tokens ?? 0
347
362
  return {
@@ -350,14 +365,38 @@ function responseUsage(usage: {
350
365
  totalTokens: usage.total_tokens ?? promptTokens + completionTokens,
351
366
  cachedTokens: usage.input_tokens_details?.cached_tokens ?? 0,
352
367
  cacheWriteTokens: 0,
368
+ ...servedSpeed(servedTier, requestedSpeed),
353
369
  }
354
370
  }
355
371
 
372
+ /**
373
+ * The speed tiers a model listing entry offers, from the current
374
+ * `service_tiers` objects and the older `additional_speed_tiers` strings.
375
+ * Only the two tiers this driver can request are kept: `priority` (or `fast`)
376
+ * is fast, `ultrafast` is ultrafast; anything else, flex included, is not a
377
+ * speed tier here.
378
+ */
379
+ function subscriptionSpeedTiers(item: Record<string, unknown>): readonly FastTier[] {
380
+ const tiers = new Set<FastTier>()
381
+ const note = (id: unknown) => {
382
+ if (id === 'priority' || id === 'fast') tiers.add('fast')
383
+ else if (id === 'ultrafast') tiers.add('ultrafast')
384
+ }
385
+ if (Array.isArray(item.service_tiers)) {
386
+ for (const entry of item.service_tiers) note(record(entry)?.id)
387
+ }
388
+ if (Array.isArray(item.additional_speed_tiers)) {
389
+ for (const entry of item.additional_speed_tiers) note(entry)
390
+ }
391
+ return (['fast', 'ultrafast'] as const).filter((tier) => tiers.has(tier))
392
+ }
393
+
356
394
  function buildRequest(
357
395
  params: ChatCompletionParams,
358
396
  model: string,
359
397
  targetRoute: ProviderRoute,
360
398
  supportedEffort: readonly ReasoningEffort[] | undefined,
399
+ downgrade: SubscriptionDowngrade = NO_DOWNGRADE,
361
400
  ): ResponseCreateParamsStreaming {
362
401
  if (
363
402
  params.effort !== undefined &&
@@ -378,8 +417,22 @@ function buildRequest(
378
417
  'CodexProvider: disabling reasoning requires `effort: "none"`; omitting that level would not prove reasoning was disabled.',
379
418
  )
380
419
  }
381
- const instructions = params.messages
382
- .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
+ )
383
436
  .map((message) => message.content)
384
437
  .join('\n\n')
385
438
  const request = {
@@ -387,7 +440,10 @@ function buildRequest(
387
440
  stream: true,
388
441
  store: false,
389
442
  instructions: instructions || undefined,
390
- 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 } : {}),
391
447
  // The Codex subscription request schema deliberately has no
392
448
  // `max_output_tokens` member. `ChatCompletionParams.maxTokens` is a public
393
449
  // API control, but projecting it onto this route makes the whole request
@@ -422,6 +478,70 @@ function buildRequest(
422
478
  return request as ResponseCreateParamsStreaming
423
479
  }
424
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
+
518
+ /**
519
+ * What an account's model listing said, kept for the life of the process so a
520
+ * provider rebuilt around a refreshed token still honours an advertised tier.
521
+ * Keyed by account and endpoint, never by token.
522
+ */
523
+ const listingByAccount = new Map<
524
+ string,
525
+ {
526
+ speedTiers: Map<string, readonly FastTier[]>
527
+ reasoningProfiles: Map<string, SubscriptionReasoningProfile>
528
+ windows: Map<string, number>
529
+ compactLimits: Map<string, number>
530
+ }
531
+ >()
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
+
425
545
  export class CodexProvider implements LLMProvider {
426
546
  readonly id = 'codex'
427
547
  readonly name = 'OpenAI Codex'
@@ -430,6 +550,16 @@ export class CodexProvider implements LLMProvider {
430
550
  private client: OpenAI
431
551
  private defaultModel?: string
432
552
  private reasoningProfiles = new Map<string, SubscriptionReasoningProfile>()
553
+ /** Per model, the speed tiers the account's listing offers. Absent until a listing has answered. */
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>
562
+ private readonly listingKey: string
433
563
 
434
564
  constructor(config: CodexConfig) {
435
565
  if (!config.accessToken) throw new Error('Codex access token is required.')
@@ -448,6 +578,14 @@ export class CodexProvider implements LLMProvider {
448
578
  },
449
579
  })
450
580
  this.defaultModel = config.model
581
+ this.listingKey = `${config.accountId}\u0000${config.baseURL ?? DEFAULT_CODEX_BASE_URL}`
582
+ const known = listingByAccount.get(this.listingKey)
583
+ if (known) {
584
+ this.speedTiers = known.speedTiers
585
+ this.reasoningProfiles = known.reasoningProfiles
586
+ this.windows = known.windows
587
+ this.compactLimits = known.compactLimits
588
+ }
451
589
  }
452
590
 
453
591
  private resolveModel(params: ChatCompletionParams): string {
@@ -464,6 +602,67 @@ export class CodexProvider implements LLMProvider {
464
602
  return this.reasoningProfiles.get(model.toLowerCase())?.default
465
603
  }
466
604
 
605
+ /**
606
+ * The speed tiers the account's listing offers for `model`. `undefined`
607
+ * until a listing has answered; once one has, a model it does not carry
608
+ * offers none.
609
+ */
610
+ speedTiersFor(model: string): readonly FastTier[] | undefined {
611
+ if (this.speedTiers === undefined) return undefined
612
+ return this.speedTiers.get(model.toLowerCase()) ?? []
613
+ }
614
+
615
+ /**
616
+ * The window the runtime measures compaction against, as the account's model listing states
617
+ * it (scaled by the effective-percent the listing sends, when it sends one), or `undefined`
618
+ * when the listing states none, which leaves the SDK's table to answer.
619
+ *
620
+ * The listing is asked once per account and kept. A failure is remembered for a few minutes
621
+ * and a listing that hangs is cut short. Neither ever fails a turn; only the caller's own
622
+ * abort propagates.
623
+ */
624
+ async resolveContextWindow(model: string, signal?: AbortSignal): Promise<number | undefined> {
625
+ signal?.throwIfAborted()
626
+ if (!this.windows) {
627
+ if (Date.now() < this.windowListingRetryAt) return undefined
628
+ this.windowListing ??= this.listForWindow().finally(() => {
629
+ this.windowListing = undefined
630
+ })
631
+ const abandoned = new Promise<never>((_, reject) => {
632
+ if (signal?.aborted) reject(signal.reason)
633
+ signal?.addEventListener('abort', () => reject(signal.reason), { once: true })
634
+ })
635
+ await Promise.race([this.windowListing, abandoned])
636
+ signal?.throwIfAborted()
637
+ }
638
+ return this.windows?.get(model.toLowerCase())
639
+ }
640
+
641
+ /**
642
+ * The token count the account's listing says compaction starts at for `model`: its
643
+ * `auto_compact_token_limit` held to 90% of the window, or 90% of the window when it sends
644
+ * none. Shares the one listing `resolveContextWindow` asks for, with the same bounds.
645
+ */
646
+ async resolveAutoCompactLimit(model: string, signal?: AbortSignal): Promise<number | undefined> {
647
+ await this.resolveContextWindow(model, signal)
648
+ return this.compactLimits?.get(model.toLowerCase())
649
+ }
650
+
651
+ /** One bounded listing for every caller waiting on it; a failure is remembered, never thrown. */
652
+ private async listForWindow(): Promise<boolean> {
653
+ const controller = new AbortController()
654
+ const timer = setTimeout(() => controller.abort(), WINDOW_LISTING_TIMEOUT_MS)
655
+ try {
656
+ await this.listModels(controller.signal)
657
+ return true
658
+ } catch {
659
+ this.windowListingRetryAt = Date.now() + WINDOW_LISTING_RETRY_MS
660
+ return false
661
+ } finally {
662
+ clearTimeout(timer)
663
+ }
664
+ }
665
+
467
666
  async *chatStream(params: ChatCompletionParams): AsyncIterable<StreamChunk> {
468
667
  const model = this.resolveModel(params)
469
668
  const targetRoute = params.providerRoute ?? {
@@ -471,12 +670,60 @@ export class CodexProvider implements LLMProvider {
471
670
  model,
472
671
  chainIndex: 0,
473
672
  }
474
- const request = buildRequest(params, model, targetRoute, this.reasoningEffortLevelsFor(model))
673
+ const effortLevels = this.reasoningEffortLevelsFor(model)
674
+ const built = buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade)
675
+ // A tier the account's listing does not offer is refused here, before
676
+ // transport: the backend would drop it and serve standard speed while
677
+ // the caller believes the request was honoured.
678
+ const fast =
679
+ params.speed === 'fast' || params.speed === 'ultrafast'
680
+ ? assertFastModeAccepted({
681
+ route: 'subscription',
682
+ model,
683
+ tier: params.speed,
684
+ advertised: this.speedTiersFor(model),
685
+ firstPartyEndpoint: true,
686
+ })
687
+ : undefined
688
+ const withTier = (body: ResponseCreateParamsStreaming) =>
689
+ (fast ? { ...body, service_tier: fast.wire } : body) as ResponseCreateParamsStreaming
690
+ const requestedSpeed =
691
+ params.speed === 'fast' || params.speed === 'ultrafast' ? params.speed : undefined
692
+ const send = (body: ResponseCreateParamsStreaming, sessionHeader: boolean) =>
693
+ this.client.responses.create(withTier(body), {
694
+ signal: params.signal,
695
+ ...(fast?.header || (sessionHeader && params.cacheKey)
696
+ ? {
697
+ headers: {
698
+ ...(fast?.header ?? {}),
699
+ ...(sessionHeader && params.cacheKey ? { session_id: params.cacheKey } : {}),
700
+ },
701
+ }
702
+ : {}),
703
+ }) as Promise<AsyncIterable<ResponseStreamEvent>>
475
704
  let stream: AsyncIterable<ResponseStreamEvent>
476
705
  try {
477
- stream = (await this.client.responses.create(request, {
478
- signal: params.signal,
479
- })) as AsyncIterable<ResponseStreamEvent>
706
+ try {
707
+ stream = await send(built, !subscriptionDowngrade.legacyShape)
708
+ } catch (error) {
709
+ // The backend refusing the newer shape is answered before any
710
+ // output exists, so one resend in the older shape is safe. It is
711
+ // remembered, so no later request sends the newer shape and nothing
712
+ // is resent twice.
713
+ const refused = subscriptionDowngrade.legacyShape ? undefined : refusedNewShape(error)
714
+ const newShapeSent =
715
+ built.input !== undefined &&
716
+ (Boolean(params.cacheKey) ||
717
+ (Array.isArray(built.input) &&
718
+ built.input.some((item) => 'role' in item && item.role === 'developer')))
719
+ if (!refused || !newShapeSent || params.signal?.aborted) throw error
720
+ subscriptionDowngrade.legacyShape = true
721
+ if (refused.cacheKey) subscriptionDowngrade.noCacheKey = true
722
+ stream = await send(
723
+ buildRequest(params, model, targetRoute, effortLevels, subscriptionDowngrade),
724
+ false,
725
+ )
726
+ }
480
727
  } catch (error) {
481
728
  if (isCallerAbortError(error, params.signal)) throw params.signal?.reason ?? error
482
729
  if (isProviderRequestError(error)) throw error
@@ -541,7 +788,10 @@ export class CodexProvider implements LLMProvider {
541
788
  event.item.type === 'message' &&
542
789
  (event.item.phase === 'commentary' || event.item.phase === 'final_answer')
543
790
  )
544
- textItems.set(event.item.id, { id: event.item.id, phase: event.item.phase })
791
+ textItems.set(event.item.id, {
792
+ id: event.item.id,
793
+ phase: event.item.phase,
794
+ })
545
795
  if (event.item.type === 'web_search_call') {
546
796
  yield {
547
797
  id: responseId,
@@ -678,7 +928,10 @@ export class CodexProvider implements LLMProvider {
678
928
  const part = textParts[partIndex]
679
929
  if (part) textParts[partIndex] = { ...part, text: part.text + suffix }
680
930
  // The driver's text, not the model's.
681
- yield { id: responseId, delta: { content: suffix, contentOrigin: 'driver' } }
931
+ yield {
932
+ id: responseId,
933
+ delta: { content: suffix, contentOrigin: 'driver' },
934
+ }
682
935
  }
683
936
  const replayState: CodexReplayState = {
684
937
  kind: 'namzu.codex.responses',
@@ -695,7 +948,11 @@ export class CodexProvider implements LLMProvider {
695
948
  delta: {},
696
949
  ...(phased ? { textParts } : {}),
697
950
  finishReason: calls.length > 0 ? 'tool_calls' : 'stop',
698
- usage: responseUsage(event.response.usage ?? {}),
951
+ usage: responseUsage(
952
+ event.response.usage ?? {},
953
+ (event.response as { service_tier?: unknown }).service_tier,
954
+ requestedSpeed,
955
+ ),
699
956
  replayState,
700
957
  }
701
958
  break
@@ -715,7 +972,11 @@ export class CodexProvider implements LLMProvider {
715
972
  delta: {},
716
973
  finishReason: reason === 'content_filter' ? 'content_filter' : 'length',
717
974
  ...(reason === 'content_filter' ? { refusal: {} } : {}),
718
- usage: responseUsage(event.response.usage ?? {}),
975
+ usage: responseUsage(
976
+ event.response.usage ?? {},
977
+ (event.response as { service_tier?: unknown }).service_tier,
978
+ requestedSpeed,
979
+ ),
719
980
  }
720
981
  break
721
982
  }
@@ -744,11 +1005,14 @@ export class CodexProvider implements LLMProvider {
744
1005
 
745
1006
  async listModels(signal?: AbortSignal): Promise<ModelInfo[]> {
746
1007
  signal?.throwIfAborted()
747
- const response = (await this.client.get('/models?client_version=1.0.0', {
1008
+ const response = (await this.client.get(`/models?client_version=${MODELS_CLIENT_VERSION}`, {
748
1009
  signal,
749
1010
  })) as { models?: unknown }
750
1011
  signal?.throwIfAborted()
751
1012
  const profiles = new Map<string, SubscriptionReasoningProfile>()
1013
+ const tiersBySlug = new Map<string, readonly FastTier[]>()
1014
+ const windows = new Map<string, number>()
1015
+ const compactLimits = new Map<string, number>()
752
1016
  const models = (Array.isArray(response.models) ? response.models : []).flatMap(
753
1017
  (value): ModelInfo[] => {
754
1018
  const item = record(value)
@@ -756,6 +1020,12 @@ export class CodexProvider implements LLMProvider {
756
1020
  if (item.visibility === 'hide' || item.visibility === 'hidden') return []
757
1021
  const profile = subscriptionReasoningProfile(item)
758
1022
  if (profile) profiles.set(item.slug.toLowerCase(), profile)
1023
+ const speedTiers = subscriptionSpeedTiers(item)
1024
+ tiersBySlug.set(item.slug.toLowerCase(), speedTiers)
1025
+ const { contextWindow, autoCompactTokenLimit } = subscriptionLimits(item)
1026
+ if (contextWindow !== undefined) windows.set(item.slug.toLowerCase(), contextWindow)
1027
+ if (autoCompactTokenLimit !== undefined)
1028
+ compactLimits.set(item.slug.toLowerCase(), autoCompactTokenLimit)
759
1029
  return [
760
1030
  {
761
1031
  id: item.slug,
@@ -764,11 +1034,23 @@ export class CodexProvider implements LLMProvider {
764
1034
  supportsStreaming: true,
765
1035
  ...(profile ? { reasoningEffortLevels: profile.levels } : {}),
766
1036
  ...(profile?.default !== undefined ? { reasoningEffortDefault: profile.default } : {}),
1037
+ speedTiers,
1038
+ ...(contextWindow !== undefined ? { contextWindow } : {}),
1039
+ ...(autoCompactTokenLimit !== undefined ? { autoCompactTokenLimit } : {}),
767
1040
  },
768
1041
  ]
769
1042
  },
770
1043
  )
771
1044
  this.reasoningProfiles = profiles
1045
+ this.speedTiers = tiersBySlug
1046
+ this.windows = windows
1047
+ this.compactLimits = compactLimits
1048
+ listingByAccount.set(this.listingKey, {
1049
+ speedTiers: tiersBySlug,
1050
+ reasoningProfiles: profiles,
1051
+ windows,
1052
+ compactLimits,
1053
+ })
772
1054
  return models
773
1055
  }
774
1056
 
@@ -794,7 +1076,7 @@ export class CodexProvider implements LLMProvider {
794
1076
  */
795
1077
  export function webSearchDetail(item: {
796
1078
  readonly action?: unknown
797
- }): { query?: string; url?: string; results?: number } {
1079
+ }): { query?: string; url?: string; results?: number; searches?: number } {
798
1080
  const action = item.action as
799
1081
  | {
800
1082
  readonly type?: unknown
@@ -818,5 +1100,7 @@ export function webSearchDetail(item: {
818
1100
  ...(query ? { query } : {}),
819
1101
  ...(url && !query ? { url } : {}),
820
1102
  ...(Array.isArray(action.sources) ? { results: action.sources.length } : {}),
1103
+ // One hosted item may run several queries; the count says so, the label names the first.
1104
+ ...(queries.length > 1 ? { searches: queries.length } : {}),
821
1105
  }
822
1106
  }