@cartanova/qgrid-cli 2.21.0 → 2.22.1

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.
Files changed (86) hide show
  1. package/README.ko.md +5 -4
  2. package/README.md +5 -4
  3. package/bundle/dist/application/monit/monit.frame.js +1 -1
  4. package/bundle/dist/application/qgrid/expired-token-reminder.js +1 -1
  5. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +2 -2
  6. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -3
  7. package/bundle/dist/application/qgrid/qgrid.frame.js +130 -24
  8. package/bundle/dist/application/qgrid/qgrid.types.js +205 -2
  9. package/bundle/dist/application/qgrid/token-death.js +1 -1
  10. package/bundle/dist/application/qgrid/token-window-keepalive.js +1 -1
  11. package/bundle/dist/application/request-log/request-log.model.js +2 -2
  12. package/bundle/dist/application/sonamu.generated.js +5 -3
  13. package/bundle/dist/i18n/en.js +2 -1
  14. package/bundle/dist/i18n/ko.js +2 -1
  15. package/bundle/dist/i18n/sd.generated.js +3 -2
  16. package/bundle/dist/sonamu.config.js +2 -2
  17. package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +1 -1
  18. package/bundle/dist/utils/providers/common/model-cost.js +15 -2
  19. package/bundle/dist/utils/providers/grok/grok-dispatcher.js +2 -2
  20. package/bundle/dist/utils/providers/openai/openai-backend-protocol.js +6 -2
  21. package/bundle/dist/utils/providers/openai/openai-decisions.js +178 -0
  22. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +61 -677
  23. package/bundle/dist/utils/providers/openai/openai-image-generation.js +1 -1
  24. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +1 -1
  25. package/bundle/dist/utils/providers/openai/openai-refresh.js +2 -2
  26. package/bundle/dist/utils/providers/openai/openai-responses-runtime.js +430 -0
  27. package/bundle/dist/utils/providers/openai/openai-token-pool.js +291 -0
  28. package/bundle/dist/utils/providers/openai/openai-voice-client.js +2 -6
  29. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +1 -1
  30. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +2 -1
  31. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +2 -4
  32. package/bundle/src/application/qgrid/qgrid.frame.test.ts +100 -1
  33. package/bundle/src/application/qgrid/qgrid.frame.ts +146 -7
  34. package/bundle/src/application/qgrid/qgrid.types.ts +242 -0
  35. package/bundle/src/application/request-log/request-log.entity.json +3 -2
  36. package/bundle/src/application/sonamu.generated.http +31 -0
  37. package/bundle/src/application/sonamu.generated.ts +2 -1
  38. package/bundle/src/i18n/en.ts +1 -0
  39. package/bundle/src/i18n/ko.ts +1 -0
  40. package/bundle/src/i18n/sd.generated.ts +2 -1
  41. package/bundle/src/utils/providers/common/model-cost.ts +20 -0
  42. package/bundle/src/utils/providers/openai/openai-backend-protocol.ts +5 -0
  43. package/bundle/src/utils/providers/openai/openai-decisions.test.ts +240 -0
  44. package/bundle/src/utils/providers/openai/openai-decisions.ts +266 -0
  45. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +133 -7
  46. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +90 -1083
  47. package/bundle/src/utils/providers/openai/openai-responses-runtime.ts +677 -0
  48. package/bundle/src/utils/providers/openai/openai-token-pool.ts +481 -0
  49. package/bundle/src/utils/providers/openai/openai-voice-client.ts +0 -5
  50. package/bundle/web-dist/client/assets/{index-NGqKa5_C.js → index-BSjyOyOc.js} +17 -17
  51. package/bundle/web-dist/client/assets/{logs-BLhlxqoB.js → logs-CFyeyR7u.js} +1 -1
  52. package/bundle/web-dist/client/assets/{monit-C3stGFEK.js → monit-N3gBNCXy.js} +1 -1
  53. package/bundle/web-dist/client/assets/{routes-Dgh-_yS5.js → routes-UbYa5WQL.js} +1 -1
  54. package/bundle/web-dist/client/assets/{settings-DiOZwvRj.js → settings-CTZGAJjl.js} +1 -1
  55. package/bundle/web-dist/client/assets/{show-DucEoTrr.js → show-oNGv2jAJ.js} +2 -2
  56. package/bundle/web-dist/client/assets/{tokens-DvCT1bbk.js → tokens-BrhEjJ3t.js} +1 -1
  57. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DazQfaBL.js → use-oauth-login-flow-Ca1Sn84P.js} +1 -1
  58. package/bundle/web-dist/client/assets/{use-update-token-mutation-CfGbUel6.js → use-update-token-mutation-DMy7Pw8U.js} +1 -1
  59. package/bundle/web-dist/client/assets/{voice-zPre2iO8.js → voice-CVXYbgBN.js} +1 -1
  60. package/bundle/web-dist/client/index.html +1 -1
  61. package/bundle/web-dist/server/assets/{TimedPlayer-CcClBzGi.js → TimedPlayer-mpJpP5tQ.js} +1 -1
  62. package/bundle/web-dist/server/assets/{logs-CxAwuDKc.js → logs-CFa_xamY.js} +6 -3
  63. package/bundle/web-dist/server/assets/{monit-Bl2kSkSF.js → monit-BF6osfj5.js} +2 -2
  64. package/bundle/web-dist/server/assets/{plus-CQ8AHpih.js → plus-DwQFfeid.js} +1 -1
  65. package/bundle/web-dist/server/assets/{refresh-cw-pYSuvt4c.js → refresh-cw-Bj-Jxeb6.js} +1 -1
  66. package/bundle/web-dist/server/assets/{request-model-ZulJMbGm.js → request-model-D_iYrudl.js} +1 -1
  67. package/bundle/web-dist/server/assets/{routes-W-pd1Hps.js → routes-B6be8sJP.js} +3 -3
  68. package/bundle/web-dist/server/assets/{services.generated-C3b31_vt.js → services.generated-D0995hJr.js} +14 -2
  69. package/bundle/web-dist/server/assets/{settings-CFdTg1_f.js → settings-DAle7AgI.js} +3 -3
  70. package/bundle/web-dist/server/assets/{show-DVEIHsXh.js → show-BTSdMDoM.js} +4 -4
  71. package/bundle/web-dist/server/assets/{tokens-BO1hyBuB.js → tokens-Bc9flfLz.js} +4 -4
  72. package/bundle/web-dist/server/assets/{use-oauth-login-flow-CCc8LEmn.js → use-oauth-login-flow-C7c0gCjf.js} +1 -1
  73. package/bundle/web-dist/server/assets/{use-update-token-mutation-Ba-sEhq1.js → use-update-token-mutation-DLJDGdxu.js} +1 -1
  74. package/bundle/web-dist/server/assets/{voice-BCF-Pkzo.js → voice-CEQT57xZ.js} +2 -2
  75. package/bundle/web-dist/server/entry-server.generated.js +214 -10
  76. package/package.json +1 -1
  77. package/skills/qgrid/SKILL.md +2 -2
  78. package/skills/qgrid/references/ai-sdk-provider-contract.md +10 -0
  79. package/skills/qgrid/references/cli-env-and-server-boot.md +2 -3
  80. package/skills/qgrid/references/decision-rationale.md +9 -3
  81. package/skills/qgrid/references/openai-codex-runtime.md +9 -2
  82. package/skills/qgrid/references/provider-runtime-differences.md +2 -2
  83. package/skills/qgrid/references/request-log-run-lifecycle.md +5 -3
  84. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  85. package/skills/qgrid/references/token-auth-quota-lifecycle.md +5 -3
  86. package/skills/qgrid/references/verification-and-debugging.md +3 -3
@@ -1,38 +1,23 @@
1
- import { getLogger } from "@logtape/logtape";
2
- import { z } from "zod";
3
-
4
- import { QuotaThresholdExceededError } from "../../../application/qgrid/qgrid.types";
5
- import { TokenModel } from "../../../application/token/token.model";
1
+ import {
2
+ type OpenAIDecisionRequest,
3
+ type OpenAIDecisionResult,
4
+ } from "../../../application/qgrid/qgrid.types";
6
5
  import { type OpenAICredentials } from "../../../application/token/token.types";
7
- import { isOpenAICredentials } from "../common/credentials";
8
- import { resolveOpenAIEffort } from "../common/effort";
9
6
  import {
10
7
  type GenerateRequest,
11
8
  type GenerateResult,
12
9
  type GenerateStreamCallbacks,
13
- type GeneratedImage,
10
+ type MediaDispatchResult,
11
+ type MediaTokenSelection,
14
12
  type ProviderDispatcher,
15
13
  } from "../common/provider-dispatcher";
16
- import { isJsonObject, jsonString } from "../common/provider-types";
17
- import { SmoothWeightedRoundRobin } from "../common/smooth-weighted-round-robin";
18
- import { ThinkingValidationError } from "../common/thinking";
19
- import {
20
- imageMimeType,
21
- type JsonValue,
22
- type OpenAINormalizedEvent,
23
- type OpenAIResponseItem,
24
- type OpenAIResponsesOptions,
25
- } from "./openai-backend-protocol";
26
- import {
27
- OpenAIDirectClient,
28
- type OpenAIDirectClientOptions,
29
- type OpenAIDirectCredentials,
30
- } from "./openai-direct-client";
31
- import { readOpenAIQuotaUsage, type OpenAIRateLimitsWithMeta } from "./openai-quota";
32
- import { handleChatgptAuthTokensRefresh } from "./openai-refresh";
14
+ import { createOpenAIDecision } from "./openai-decisions";
15
+ import { OpenAIDirectClient } from "./openai-direct-client";
16
+ import { type OpenAIRateLimitsWithMeta } from "./openai-quota";
17
+ import { type OpenAIDirectClientFactory, OpenAIResponsesRuntime } from "./openai-responses-runtime";
18
+ import { OpenAITokenPool } from "./openai-token-pool";
33
19
  import { type OpenAITransportKind, resolveOpenAITransportKind } from "./openai-transport-config";
34
20
  import {
35
- isUnauthorizedRealtimeError,
36
21
  type OpenAILiveCall,
37
22
  type OpenAILiveCallRequest,
38
23
  type OpenAISpeakRequest,
@@ -42,414 +27,47 @@ import {
42
27
  OpenAIVoiceClient,
43
28
  } from "./openai-voice-client";
44
29
 
45
- const logger = getLogger(["qgrid", "openai-dispatcher"]);
46
-
47
- // Verified with the subscription Responses backend; public API support is not sufficient.
48
- const THINKING_OFF_MODELS = new Set([
49
- "gpt-6.1-terra",
50
- "gpt-6-sol",
51
- "gpt-6-luna",
52
- "gpt-5.6-sol",
53
- "gpt-5.6-terra",
54
- "gpt-5.6-luna",
55
- "gpt-5.5",
56
- ]);
57
-
58
- const DEFAULT_REQUEST_TIMEOUT_MS = 600_000;
59
- const IMAGE_TOOL = "generate_image";
60
-
61
- type ImageToolArguments = {
62
- prompt: string;
63
- transparent_background: boolean;
64
- num_last_images_to_include: number;
65
- };
66
-
67
- // Exactly these three keys; the backend rejects strict tools, so arguments are validated here.
68
- const ImageToolArgumentsSchema = z.strictObject({
69
- prompt: z.string().refine((prompt) => prompt.trim().length > 0),
70
- transparent_background: z.boolean(),
71
- num_last_images_to_include: z.number().int().min(0).max(5),
72
- });
73
-
74
- function generatedImageFrom(
75
- event: Extract<OpenAINormalizedEvent, { type: "image" }>,
76
- ): GeneratedImage {
77
- const image: GeneratedImage = {
78
- data: event.base64,
79
- mediaType: event.mimeType,
80
- revisedPrompt: event.revisedPrompt ?? null,
81
- };
82
-
83
- if (event.generation) image.generation = event.generation;
84
-
85
- return image;
86
- }
87
-
88
- export type ImageFailureKind = "gate" | "not_called" | "incomplete";
89
-
90
- export class ImageGenerationError extends Error {
91
- completedDriver?: GenerateResult;
92
-
93
- constructor(
94
- readonly kind: ImageFailureKind,
95
- message: string,
96
- options?: ErrorOptions,
97
- ) {
98
- super(message, options);
99
- this.name = "ImageGenerationError";
100
- }
101
- }
102
-
103
- type TokenMetadata = {
104
- name: string;
105
- credentials: OpenAICredentials;
106
- quotaThreshold?: number | null;
107
- weight: number;
108
- active: boolean;
109
- generation: number;
110
- };
111
-
112
- type TokenSelection = { tokenId: number; metadata: TokenMetadata };
113
-
114
- export type OpenAIDirectClientFactory = (
115
- options: OpenAIDirectClientOptions,
116
- tokenId: number,
117
- ) => Pick<OpenAIDirectClient, "responses"> & { close?: () => void };
118
-
119
- type ClientEntry = {
120
- generation: number;
121
- client: Pick<OpenAIDirectClient, "responses"> & { close?: () => void };
122
- inFlight: number;
123
- retired: boolean;
124
- };
125
-
126
30
  export interface OpenAIDispatcherDependencies {
127
31
  clientFactory?: OpenAIDirectClientFactory;
128
32
  fetch?: typeof fetch;
129
33
  voiceClient?: OpenAIVoiceClient;
130
34
  }
131
35
 
132
- /** Realtime voice call with the media-endpoint token selection contract. */
133
- export type OpenAIVoiceSelection = {
134
- preferredTokenId?: number;
135
- requirePreferredToken?: boolean;
136
- };
137
-
138
- export interface OpenAIVoiceDispatchResult<T> {
139
- result: T;
140
- tokenId: number;
141
- tokenName: string;
142
- }
143
-
144
- function abortError(signal: AbortSignal): Error {
145
- const reason = signal.reason;
146
-
147
- return reason instanceof Error ? reason : new DOMException("Aborted", "AbortError");
148
- }
149
-
150
- function activeSignal(signal?: AbortSignal, timeoutMs?: number): AbortSignal {
151
- const timeout = AbortSignal.timeout(timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
152
-
153
- return signal ? AbortSignal.any([signal, timeout]) : timeout;
154
- }
155
-
156
- function quotaMessage(entries: Array<{ name: string; threshold: number }>): string {
157
- const detail = entries.map((e) => `${e.name} (threshold ${e.threshold}%)`).join(", ");
158
-
159
- return detail
160
- ? `All openai tokens exceeded quota threshold: ${detail}`
161
- : "All openai tokens exceeded quota threshold";
162
- }
163
-
164
- function inputItems(req: GenerateRequest): JsonValue[] {
165
- const history = req.coldHistory ?? [];
166
-
167
- const content: OpenAIResponseItem[] = req.coldInput.map((input) => {
168
- if (input.type === "text") return { type: "input_text", text: input.text };
169
-
170
- if (input.type === "image") return { type: "input_image", image_url: input.url };
171
-
172
- if (input.type === "localImage") return { type: "input_image", image_url: input.path };
173
-
174
- return { type: "input_text", text: `${input.name}: ${input.path}` };
175
- });
176
-
177
- return [...history, { type: "message", role: "user", content }];
178
- }
179
-
180
- function imageReferences(req: GenerateRequest): OpenAIResponseItem[] {
181
- return inputItems(req).flatMap((item) => {
182
- if (!isJsonObject(item)) return [];
183
- const result = jsonString(item.result);
184
-
185
- if (item.type === "image_generation_call" && result !== undefined) {
186
- return [
187
- {
188
- type: "input_image",
189
- image_url: `data:${imageMimeType(result, item.output_format)};base64,${result}`,
190
- },
191
- ];
192
- }
193
-
194
- if (!Array.isArray(item.content)) return [];
195
-
196
- return item.content
197
- .filter(isJsonObject)
198
- .filter((part) => part.type === "input_image" || part.type === "image_url");
199
- });
200
- }
201
-
202
- type OpenAIReasoning = NonNullable<OpenAIResponsesOptions["reasoning"]>;
203
-
204
- function asReasoning(req: GenerateRequest): OpenAIReasoning | undefined {
205
- if (req.thinking === false) return { effort: "none" };
206
-
207
- const summary =
208
- req.reasoningSummary && req.reasoningSummary !== "none" ? req.reasoningSummary : undefined;
209
-
210
- const effort =
211
- resolveOpenAIEffort(req.model ?? "", req.effort) ?? (req.thinking === true ? "low" : undefined);
212
-
213
- if (!effort && !summary) return undefined;
214
-
215
- const reasoning: OpenAIReasoning = {};
216
-
217
- // ultra is a Codex client mode (sub-agent delegation), not a wire value; the backend accepts up to max.
218
- if (effort) reasoning.effort = effort === "ultra" ? "max" : effort;
219
-
220
- if (summary) reasoning.summary = summary;
221
-
222
- return reasoning;
223
- }
224
-
225
- const AUTO_IMAGE_INSTRUCTIONS =
226
- "Use generate_image when image generation or editing is needed; otherwise reply with text. Call it at most once per response. Supply a complete, self-contained prompt with all relevant conversation instructions. Set transparent_background to true only when a transparent background is requested. Set num_last_images_to_include to 0 for a new image without references. For editing or reference-based generation, choose the smallest number of recent conversation images that includes all needed references, at most 5. References retain their chronological order. Do not select images for an unrelated new request.";
227
-
228
- const AUTO_IMAGE_TOOL: OpenAIResponseItem = {
229
- type: "function",
230
- name: IMAGE_TOOL,
231
- description:
232
- "Generate or edit an image, optionally with a transparent background or recent conversation images as references.",
233
- // Astra's subscription backend rejects strict tools; validate arguments locally.
234
- strict: false,
235
- parameters: {
236
- type: "object",
237
- properties: {
238
- prompt: {
239
- type: "string",
240
- minLength: 1,
241
- description: "Complete, self-contained instructions for the image generation or edit.",
242
- },
243
- transparent_background: { type: "boolean" },
244
- num_last_images_to_include: { type: "integer", minimum: 0, maximum: 5 },
245
- },
246
- required: ["prompt", "transparent_background", "num_last_images_to_include"],
247
- additionalProperties: false,
248
- },
249
- };
250
-
251
36
  /**
252
- * Hosted web search as Codex sends it (tools/src/tool_spec.rs); `external_web_access` asks for
253
- * live search rather than the cached index. Answered on the subscription route (2026-11-10).
37
+ * The OpenAI provider surface: one token pool shared by Responses (`openai-responses-runtime.ts`),
38
+ * realtime voice (`openai-voice-client.ts`), and Decisions (`openai-decisions.ts`).
254
39
  */
255
- const WEB_SEARCH_TOOL: OpenAIResponseItem = { type: "web_search", external_web_access: true };
256
-
257
- function requestOptions(req: GenerateRequest): OpenAIResponsesOptions {
258
- const { outputFormat, ...imageControls } = req.imageGenerationOptions ?? {};
259
- const auto = req.imageGeneration === "auto";
260
-
261
- if (auto && req.outputSchema) {
262
- throw new ImageGenerationError(
263
- "gate",
264
- "Automatic image generation does not support structured output or external tools",
265
- );
266
- }
267
-
268
- if (auto && outputFormat && outputFormat !== "png") {
269
- throw new ImageGenerationError("gate", "Automatic image generation only supports PNG output");
270
- }
271
-
272
- const options: OpenAIResponsesOptions = { model: req.model ?? "", history: inputItems(req) };
273
-
274
- if (req.systemPrompt) options.instructions = req.systemPrompt;
275
-
276
- if (auto) {
277
- options.instructions = [req.systemPrompt, AUTO_IMAGE_INSTRUCTIONS].filter(Boolean).join("\n\n");
278
- options.parallelToolCalls = false;
279
- options.tools = [AUTO_IMAGE_TOOL];
280
- }
281
-
282
- // Function tools reach OpenAI through qgrid's tool emulation; only hosted search goes native.
283
- if (req.tools?.some((tool) => tool.type === "web_search")) {
284
- options.tools = [...(options.tools ?? []), WEB_SEARCH_TOOL];
285
- }
286
-
287
- const reasoning = asReasoning(req);
288
-
289
- if (reasoning) options.reasoning = reasoning;
290
-
291
- if (req.verbosity) options.verbosity = req.verbosity;
292
-
293
- if (req.serviceTier) {
294
- options.serviceTier = req.serviceTier === "fast" ? "priority" : req.serviceTier;
295
- }
296
-
297
- if (req.promptCacheKey) options.promptCacheKey = req.promptCacheKey;
298
-
299
- if (req.outputSchema) options.outputSchema = { schema: req.outputSchema };
300
-
301
- if (req.imageGeneration && !auto) {
302
- if (req.imageGenerationOptions) {
303
- const controls: OpenAIResponseItem = { ...imageControls };
304
-
305
- if (outputFormat) controls.output_format = outputFormat;
306
- options.imageGeneration = controls;
307
- } else {
308
- options.imageGeneration = true;
309
- }
310
- }
311
-
312
- return options;
313
- }
314
-
315
- // quota와 cache affinity로 토큰을 선택해 HTTPS/WS로 전송한다. 로컬 동시성 제한은 없다.
316
40
  export class OpenAIDispatcher implements ProviderDispatcher {
317
- readonly tokenMetadata = new Map<number, TokenMetadata>();
318
- readonly transportKind: OpenAITransportKind;
319
- readonly rateLimitsCache = new Map<number, OpenAIRateLimitsWithMeta & { generation: number }>();
320
- readonly pendingRateLimits = new Map<
321
- number,
322
- { token: TokenMetadata; generation: number; promise: Promise<OpenAIRateLimitsWithMeta> }
323
- >();
324
- readonly clients = new Map<number, ClientEntry>();
325
- readonly retiredClients = new Set<ClientEntry>();
326
- static readonly RATE_LIMITS_CACHE_TTL = 60_000;
327
-
328
- readonly selector = new SmoothWeightedRoundRobin();
329
- readonly clientFactory: OpenAIDirectClientFactory;
330
- readonly fetchImpl: typeof fetch;
41
+ // Callers go through the methods below; the parts are not a second way in.
42
+ private readonly pool: OpenAITokenPool;
43
+ private readonly responses: OpenAIResponsesRuntime;
331
44
  readonly voiceClient: OpenAIVoiceClient;
332
- readonly quotaBlocked = new Set<number>();
333
- inFlight = 0;
334
45
 
335
46
  constructor(
336
47
  transportKind: OpenAITransportKind = resolveOpenAITransportKind(),
337
48
  dependencies: OpenAIDispatcherDependencies = {},
338
49
  ) {
339
- this.transportKind = transportKind;
340
- this.clientFactory =
341
- dependencies.clientFactory ?? ((options) => new OpenAIDirectClient(options));
342
- this.fetchImpl = dependencies.fetch ?? fetch;
343
- this.voiceClient = dependencies.voiceClient ?? new OpenAIVoiceClient({ fetch: this.fetchImpl });
344
- }
345
-
346
- // ---- Realtime voice (speech-to-text, text-to-speech) ----------------------
347
-
348
- async transcribe(
349
- request: OpenAITranscribeRequest & OpenAIVoiceSelection,
350
- ): Promise<OpenAIVoiceDispatchResult<OpenAITranscription>> {
351
- const { preferredTokenId, requirePreferredToken, ...voiceRequest } = request;
352
-
353
- return this.runVoice(
354
- { preferredTokenId, requirePreferredToken },
355
- request.signal,
356
- (credentials) => this.voiceClient.transcribe(credentials, voiceRequest),
50
+ const fetchImpl = dependencies.fetch ?? fetch;
51
+ this.voiceClient = dependencies.voiceClient ?? new OpenAIVoiceClient({ fetch: fetchImpl });
52
+ this.pool = new OpenAITokenPool(fetchImpl);
53
+
54
+ this.responses = new OpenAIResponsesRuntime(
55
+ this.pool,
56
+ transportKind,
57
+ dependencies.clientFactory ?? ((options) => new OpenAIDirectClient(options)),
357
58
  );
358
59
  }
359
60
 
360
- async speak(
361
- request: OpenAISpeakRequest & OpenAIVoiceSelection,
362
- ): Promise<OpenAIVoiceDispatchResult<OpenAISpeechResult>> {
363
- const { preferredTokenId, requirePreferredToken, ...voiceRequest } = request;
364
-
365
- return this.runVoice(
366
- { preferredTokenId, requirePreferredToken },
367
- request.signal,
368
- (credentials) => this.voiceClient.speak(credentials, voiceRequest),
369
- );
370
- }
371
-
372
- async startLive(
373
- request: OpenAILiveCallRequest & OpenAIVoiceSelection,
374
- ): Promise<OpenAIVoiceDispatchResult<OpenAILiveCall>> {
375
- const { preferredTokenId, requirePreferredToken, ...liveRequest } = request;
376
-
377
- return this.runVoice(
378
- { preferredTokenId, requirePreferredToken },
379
- request.signal,
380
- (credentials) => this.voiceClient.createLiveCall(credentials, liveRequest),
381
- );
382
- }
383
-
384
- /**
385
- * Selects a token, runs the realtime call, and on one 401 refreshes that token's credentials and
386
- * retries once (as the Responses transports do). Any other failure propagates: a realtime
387
- * session that failed may already have consumed audio tokens.
388
- */
389
- async runVoice<T>(
390
- selection: OpenAIVoiceSelection,
391
- signal: AbortSignal | undefined,
392
- call: (credentials: OpenAIDirectCredentials) => Promise<T>,
393
- ): Promise<OpenAIVoiceDispatchResult<T>> {
394
- const active = signal ?? new AbortController().signal;
395
-
396
- const selected = await this.selectToken(
397
- selection.preferredTokenId,
398
- selection.requirePreferredToken ?? false,
399
- active,
400
- );
401
-
402
- const { tokenId, metadata } = selected;
403
-
404
- let credentials: OpenAIDirectCredentials = {
405
- accessToken: metadata.credentials.accessToken,
406
- accountId: metadata.credentials.accountId,
407
- };
408
-
409
- for (let attempt = 0; ; attempt++) {
410
- try {
411
- const result = await call(credentials);
412
- this.invalidateRateLimitsCache(tokenId);
413
-
414
- return { result, tokenId, tokenName: metadata.name };
415
- } catch (error) {
416
- if (attempt === 0 && error instanceof Error && isUnauthorizedRealtimeError(error)) {
417
- credentials = await this.refreshCredentials(tokenId);
418
- continue;
419
- }
420
-
421
- throw error;
422
- }
423
- }
424
- }
61
+ // ---- Lifecycle and token pool ---------------------------------------------
425
62
 
426
63
  async start(): Promise<void> {
427
- const { rows } = await TokenModel.findMany("A");
428
-
429
- for (const row of rows) {
430
- if (row.provider !== "openai") continue;
431
-
432
- if (!isOpenAICredentials(row.credentials)) {
433
- logger.warn(`skipping token ${row.name}: credentials are not OpenAI OAuth credentials`);
434
- continue;
435
- }
436
-
437
- this.setToken(row.id, row.name, row.credentials, row.quota_threshold, row.weight, row.active);
438
- }
439
-
440
- logger.info(`started direct OpenAI runtime with ${this.tokenMetadata.size} tokens`);
64
+ await this.pool.load();
441
65
  }
442
66
 
443
67
  async stop(): Promise<void> {
444
68
  this.voiceClient.closeLiveSessions();
445
- this.clients.forEach(({ client }) => client.close?.());
446
- this.clients.clear();
447
- this.retiredClients.forEach((entry) => entry.client.close?.());
448
- this.retiredClients.clear();
449
- this.tokenMetadata.clear();
450
- this.rateLimitsCache.clear();
451
- this.quotaBlocked.clear();
452
- this.selector.resetScores();
69
+ this.responses.close();
70
+ this.pool.clear();
453
71
  }
454
72
 
455
73
  async onTokenAdded(
@@ -459,7 +77,7 @@ export class OpenAIDispatcher implements ProviderDispatcher {
459
77
  quotaThreshold?: number | null,
460
78
  weight = 1,
461
79
  ): Promise<void> {
462
- this.setToken(id, name, credentials, quotaThreshold, weight, true);
80
+ return this.pool.onTokenAdded(id, name, credentials, quotaThreshold, weight);
463
81
  }
464
82
 
465
83
  async onTokenUpdated(
@@ -469,716 +87,105 @@ export class OpenAIDispatcher implements ProviderDispatcher {
469
87
  quotaThreshold?: number | null,
470
88
  weight = 1,
471
89
  ): Promise<void> {
472
- const old = this.tokenMetadata.get(id);
473
- this.setToken(id, name, credentials, quotaThreshold, weight, old?.active ?? true);
90
+ return this.pool.onTokenUpdated(id, name, credentials, quotaThreshold, weight);
474
91
  }
475
92
 
476
93
  async onTokenRemoved(id: number): Promise<void> {
477
- this.retireClient(id);
478
- this.tokenMetadata.delete(id);
479
- this.selector.removeToken(id);
480
- this.invalidateRateLimitsCache(id);
481
- this.quotaBlocked.delete(id);
94
+ return this.pool.onTokenRemoved(id);
482
95
  }
483
96
 
484
97
  onTokenDeactivated(id: number): void {
485
- const token = this.tokenMetadata.get(id);
486
-
487
- if (token) token.active = false;
488
- this.selector.resetScores();
98
+ this.pool.onTokenDeactivated(id);
489
99
  }
490
100
 
491
101
  onTokenActivated(id: number): void {
492
- const token = this.tokenMetadata.get(id);
493
-
494
- if (token) token.active = true;
495
- this.selector.resetScores();
102
+ this.pool.onTokenActivated(id);
496
103
  }
497
104
 
498
- async replaceTokens(
499
- rows: Array<{
500
- id: number;
501
- name: string;
502
- credentials: OpenAICredentials;
503
- quotaThreshold?: number | null;
504
- weight: number;
505
- }>,
506
- ): Promise<void> {
507
- const ids = new Set(rows.map((r) => r.id));
508
-
509
- for (const id of this.tokenMetadata.keys()) if (!ids.has(id)) await this.onTokenRemoved(id);
510
-
511
- for (const row of rows)
512
- await this.onTokenUpdated(row.id, row.name, row.credentials, row.quotaThreshold, row.weight);
513
- }
514
-
515
- async generate(req: GenerateRequest): Promise<GenerateResult> {
516
- return this.run(req);
105
+ async replaceTokens(rows: Parameters<OpenAITokenPool["replaceTokens"]>[0]): Promise<void> {
106
+ return this.pool.replaceTokens(rows);
517
107
  }
518
108
 
519
- async generateStream(req: GenerateRequest, cb: GenerateStreamCallbacks): Promise<void> {
520
- if (req.imageGeneration)
521
- throw new ImageGenerationError(
522
- "gate",
523
- "image generation is not supported on the streaming path",
524
- );
525
-
526
- try {
527
- cb.onComplete(await this.run(req, cb.onDelta));
528
- } catch (error) {
529
- cb.onError(error instanceof Error ? error : new Error(String(error)));
530
- throw error;
531
- }
109
+ async getRateLimitsByTokenId(
110
+ tokenId: number,
111
+ signal?: AbortSignal,
112
+ ): Promise<OpenAIRateLimitsWithMeta> {
113
+ return this.pool.getRateLimitsByTokenId(tokenId, signal);
532
114
  }
533
115
 
534
- async run(req: GenerateRequest, onDelta?: (text: string) => void): Promise<GenerateResult> {
535
- if (req.thinking === false) {
536
- const model = req.model ?? "";
537
-
538
- if (!THINKING_OFF_MODELS.has(model)) {
539
- const reason =
540
- model === "gpt-6-astra" || model === "gpt-6.1-sol"
541
- ? "the subscription backend requires thinking"
542
- : "thinking-off support has not been verified on the subscription backend";
543
-
544
- throw new ThinkingValidationError(
545
- `thinking:false is unavailable for OpenAI model ${model || "<default>"}: ${reason}`,
546
- );
547
- }
548
- }
549
-
550
- const signal = activeSignal(req.abortSignal, req.timeoutMs);
551
-
552
- if (signal.aborted) throw abortError(signal);
553
-
554
- const selection = await this.selectToken(
555
- req.preferredTokenId,
556
- req.requirePreferredToken ?? false,
557
- signal,
558
- );
559
-
560
- this.inFlight++;
561
-
562
- try {
563
- if (signal.aborted) throw abortError(signal);
564
-
565
- return await this.runDirect(selection, { ...req, abortSignal: signal }, onDelta);
566
- } finally {
567
- this.inFlight--;
568
- }
116
+ countActiveTokens(): number {
117
+ return this.pool.countActiveTokens();
569
118
  }
570
119
 
571
- async runDirect(
572
- selection: TokenSelection,
573
- req: GenerateRequest,
574
- onDelta?: (text: string) => void,
575
- ): Promise<GenerateResult> {
576
- const startedAt = Date.now();
577
- let firstDeltaAt: number | undefined;
578
- let text = "";
579
- req.onProgress?.({ tokenName: selection.metadata.name });
580
-
581
- const markFirstDelta = () => {
582
- if (firstDeltaAt !== undefined) return;
583
- firstDeltaAt = Date.now();
584
- req.onProgress?.({ ttftMs: firstDeltaAt - startedAt });
585
- };
586
-
587
- let outputMessageAccepted = false;
588
- const messagePhases = new Map<string, string>();
589
- const streamedMessageIds = new Set<string>();
590
-
591
- let usage = {
592
- totalTokens: 0,
593
- inputTokens: 0,
594
- outputTokens: 0,
595
- cachedInputTokens: 0,
596
- reasoningOutputTokens: 0,
597
- };
598
-
599
- const images: GeneratedImage[] = [];
600
- let imageAttempted = false;
601
- const auto = req.imageGeneration === "auto";
602
- const imageCalls = new Map<string, ImageToolArguments>();
603
- const imageCallIds = new Set<JsonValue | undefined>();
604
- let imageToolAttempted = false;
605
- let driverCompleted = false;
606
- let servingModel = req.model ?? "";
607
- const metadata = selection.metadata;
608
-
609
- const driverResult = (): GenerateResult => {
610
- const result: GenerateResult = {
611
- text,
612
- tokenName: metadata.name,
613
- usage,
614
- durationMs: Date.now() - startedAt,
615
- ttftMs: firstDeltaAt === undefined ? null : firstDeltaAt - startedAt,
616
- model: servingModel,
617
- threadCoord: {
618
- workerId: selection.tokenId,
619
- threadId: req.promptCacheKey ?? "",
620
- epoch: -1,
621
- },
622
- };
623
-
624
- if (servingModel !== req.model) result.requestedModel = req.model;
625
-
626
- return result;
627
- };
628
-
629
- const clientEntry = this.acquireClient(selection);
630
-
631
- try {
632
- for await (const event of clientEntry.client.responses(
633
- requestOptions(req),
634
- req.abortSignal,
635
- )) {
636
- const itemId = event.type === "output-item" ? jsonString(event.item.id) : undefined;
637
- const itemPhase = event.type === "output-item" ? jsonString(event.item.phase) : undefined;
638
-
639
- if (
640
- req.stopAfterOutputMessage &&
641
- event.type === "output-item" &&
642
- event.item.type === "message" &&
643
- itemId !== undefined &&
644
- itemPhase !== undefined
645
- ) {
646
- messagePhases.set(itemId, itemPhase);
647
- }
648
-
649
- if (event.type === "text-delta") {
650
- if (outputMessageAccepted) continue;
651
-
652
- if (req.stopAfterOutputMessage && event.itemId) {
653
- // Buffer commentary/unclassified messages until their completed item.
654
- // Known final answers retain incremental streaming.
655
- if (messagePhases.get(event.itemId) !== "final_answer") continue;
656
- streamedMessageIds.add(event.itemId);
657
- }
658
-
659
- markFirstDelta();
660
- text += event.text;
661
- onDelta?.(event.text);
662
- } else if (
663
- event.type === "output-item" &&
664
- event.completed &&
665
- event.item.type === "message" &&
666
- !outputMessageAccepted &&
667
- req.stopAfterOutputMessage &&
668
- Array.isArray(event.item.content)
669
- ) {
670
- const messageText = event.item.content
671
- .flatMap((part) => {
672
- const partText =
673
- isJsonObject(part) && part.type === "output_text"
674
- ? jsonString(part.text)
675
- : undefined;
676
-
677
- return partText === undefined ? [] : [partText];
678
- })
679
- .join("");
680
-
681
- // A valid client tool request ends this application turn. Later answers cannot
682
- // know its result yet. Never split/repair malformed JSON within a message.
683
- const phase = itemPhase;
684
-
685
- if (messageText) outputMessageAccepted = req.stopAfterOutputMessage(messageText, phase);
686
-
687
- if (
688
- itemId !== undefined &&
689
- !streamedMessageIds.has(itemId) &&
690
- (phase !== "commentary" || outputMessageAccepted) &&
691
- messageText
692
- ) {
693
- markFirstDelta();
694
- text += messageText;
695
- onDelta?.(messageText);
696
- streamedMessageIds.add(itemId);
697
- }
698
- } else if (event.type === "image") {
699
- if (auto) throw new ImageGenerationError("incomplete", "Unexpected image output");
700
- imageAttempted = true;
701
- images.push(generatedImageFrom(event));
702
- } else if (auto && event.type === "output-item" && event.item.type === "function_call") {
703
- if (event.item.name !== IMAGE_TOOL) {
704
- throw new ImageGenerationError("incomplete", "Unexpected automatic image tool call");
705
- }
706
-
707
- imageToolAttempted = true;
708
- imageCallIds.add(event.item.call_id);
709
-
710
- if (!event.completed) continue;
711
- const id = jsonString(event.item.call_id);
712
- const rawArguments = jsonString(event.item.arguments);
713
- let decoded: JsonValue;
714
-
715
- try {
716
- if (rawArguments === undefined) throw new Error("missing arguments");
717
- // JSON.parse without a reviver yields only JSON values.
718
- decoded = JSON.parse(rawArguments);
719
- } catch {
720
- throw new ImageGenerationError("incomplete", "Invalid image tool arguments");
721
- }
722
-
723
- const parsedArgs = ImageToolArgumentsSchema.safeParse(decoded);
724
-
725
- if (!id || !parsedArgs.success) {
726
- throw new ImageGenerationError("incomplete", "Invalid image tool arguments");
727
- }
728
-
729
- const args = parsedArgs.data;
730
-
731
- const previous = imageCalls.get(id);
732
-
733
- if (
734
- previous &&
735
- (previous.prompt !== args.prompt ||
736
- previous.transparent_background !== args.transparent_background ||
737
- previous.num_last_images_to_include !== args.num_last_images_to_include)
738
- ) {
739
- throw new ImageGenerationError("incomplete", "Conflicting image tool calls");
740
- }
741
-
742
- imageCalls.set(id, {
743
- prompt: args.prompt,
744
- transparent_background: args.transparent_background,
745
- num_last_images_to_include: args.num_last_images_to_include,
746
- });
747
- } else if (event.type === "completed") {
748
- driverCompleted = true;
749
- servingModel = event.model ?? servingModel;
750
-
751
- if (event.usage) {
752
- usage = {
753
- totalTokens: event.usage.totalTokens,
754
- inputTokens: event.usage.inputTokens,
755
- outputTokens: event.usage.outputTokens,
756
- cachedInputTokens: event.usage.cachedInputTokens,
757
- reasoningOutputTokens: event.usage.reasoningTokens,
758
- };
759
- }
760
- } else if (event.type === "error") {
761
- if (req.imageGeneration)
762
- throw new ImageGenerationError("incomplete", event.error.message);
763
- throw event.error;
764
- }
765
- }
766
-
767
- if (auto && imageToolAttempted) {
768
- if (!driverCompleted || imageCalls.size !== 1 || imageCallIds.size !== 1) {
769
- throw new ImageGenerationError("incomplete", "Expected one completed image tool call");
770
- }
771
-
772
- if (req.abortSignal?.aborted) throw abortError(req.abortSignal);
773
- const args = [...imageCalls.values()][0]!;
774
- const referenceCount = args.num_last_images_to_include;
775
- const references = referenceCount ? imageReferences(req) : [];
776
-
777
- if (referenceCount > references.length) {
778
- throw new ImageGenerationError(
779
- "incomplete",
780
- "Requested image references are unavailable",
781
- );
782
- }
783
-
784
- let imageCompleted = false;
785
-
786
- for await (const event of clientEntry.client.responses(
787
- {
788
- model: "gpt-image-2",
789
- history: [
790
- {
791
- type: "message",
792
- role: "user",
793
- content: [
794
- { type: "input_text", text: args.prompt },
795
- ...(referenceCount ? references.slice(-referenceCount) : []),
796
- ],
797
- },
798
- ],
799
- imageGeneration: {
800
- quality: req.imageGenerationOptions?.quality,
801
- size: req.imageGenerationOptions?.size,
802
- output_format: "png",
803
- background: args.transparent_background ? "transparent" : "opaque",
804
- },
805
- },
806
- req.abortSignal,
807
- )) {
808
- if (event.type === "image") images.push(generatedImageFrom(event));
809
- else if (event.type === "completed") imageCompleted = true;
810
- else if (event.type === "error")
811
- throw new ImageGenerationError("incomplete", event.error.message, {
812
- cause: event.error,
813
- });
814
- }
815
-
816
- imageAttempted = true;
817
-
818
- if (!imageCompleted)
819
- throw new ImageGenerationError("incomplete", "Image generation did not complete");
820
- }
821
-
822
- if (auto && imageAttempted && !driverCompleted)
823
- throw new ImageGenerationError("incomplete", "Image generation response did not complete");
824
-
825
- if (req.abortSignal?.aborted) throw abortError(req.abortSignal);
826
-
827
- if ((req.imageGeneration === true || (auto && imageAttempted)) && images.length === 0) {
828
- throw new ImageGenerationError(
829
- imageAttempted ? "incomplete" : "not_called",
830
- imageAttempted
831
- ? "image generation did not complete"
832
- : "model did not call image generation",
833
- );
834
- }
835
- } catch (error) {
836
- if (auto && driverCompleted && imageToolAttempted) {
837
- const failure =
838
- error instanceof ImageGenerationError
839
- ? error
840
- : new ImageGenerationError(
841
- "incomplete",
842
- error instanceof Error ? error.message : String(error),
843
- { cause: error },
844
- );
845
-
846
- if (error instanceof Error) failure.name = error.name;
847
- // Only the completed chat stage is chargeable here; discard partial image output.
848
- failure.completedDriver = driverResult();
849
- throw failure;
850
- }
851
-
852
- throw error;
853
- } finally {
854
- this.releaseClient(clientEntry);
855
- }
856
-
857
- const result = driverResult();
858
-
859
- if (images.length) result.images = images;
860
-
861
- return result;
120
+ getQuotaSnapshot(): ReturnType<OpenAITokenPool["getQuotaSnapshot"]> {
121
+ return this.pool.getQuotaSnapshot();
862
122
  }
863
123
 
864
- /** 세대가 바뀐 client 는 사용 중인 요청이 끝난 뒤에 닫는다. */
865
- acquireClient(selection: TokenSelection): ClientEntry {
866
- const metadata = selection.metadata;
867
- let entry = this.clients.get(selection.tokenId);
868
-
869
- if (entry && entry.generation !== metadata.generation) {
870
- this.retireClient(selection.tokenId);
871
- entry = undefined;
872
- }
873
-
874
- if (!entry) {
875
- const client = this.clientFactory(
876
- {
877
- credentials: {
878
- accessToken: metadata.credentials.accessToken,
879
- accountId: metadata.credentials.accountId,
880
- },
881
- transportKind: this.transportKind,
882
- fetch: this.fetchImpl,
883
- refreshCredentials: () => this.refreshCredentials(selection.tokenId),
884
- },
885
- selection.tokenId,
886
- );
124
+ // ---- Responses (text, tools, chat images) -----------------------------------
887
125
 
888
- entry = { generation: metadata.generation, client, inFlight: 0, retired: false };
889
- this.clients.set(selection.tokenId, entry);
890
- }
891
-
892
- entry.inFlight++;
893
-
894
- return entry;
126
+ /** Responses requests in flight; monitoring reads it. */
127
+ get inFlight(): number {
128
+ return this.responses.inFlight;
895
129
  }
896
130
 
897
- releaseClient(entry: ClientEntry): void {
898
- entry.inFlight = Math.max(0, entry.inFlight - 1);
899
-
900
- if (entry.retired && entry.inFlight === 0) {
901
- this.retiredClients.delete(entry);
902
- entry.client.close?.();
903
- }
131
+ async generate(req: GenerateRequest): Promise<GenerateResult> {
132
+ return this.responses.run(req);
904
133
  }
905
134
 
906
- retireClient(tokenId: number): void {
907
- const entry = this.clients.get(tokenId);
908
-
909
- if (!entry) return;
910
- this.clients.delete(tokenId);
911
- entry.retired = true;
912
-
913
- if (entry.inFlight === 0) entry.client.close?.();
914
- else this.retiredClients.add(entry);
135
+ async generateStream(req: GenerateRequest, cb: GenerateStreamCallbacks): Promise<void> {
136
+ return this.responses.generateStream(req, cb);
915
137
  }
916
138
 
917
- // 선호 토큰이 quota를 통과하면 다른 토큰 조회와 weighted 상태 변경을 생략한다.
918
- async selectToken(
919
- preferredTokenId: number | undefined,
920
- requirePreferredToken: boolean,
921
- signal: AbortSignal,
922
- ): Promise<TokenSelection> {
923
- if (preferredTokenId !== undefined) {
924
- const preferred = this.tokenMetadata.get(preferredTokenId);
925
-
926
- if (preferred?.active && (await this.isQuotaEligible(preferredTokenId, preferred, signal))) {
927
- return { tokenId: preferredTokenId, metadata: preferred };
928
- }
929
-
930
- if (requirePreferredToken) {
931
- if (!preferred?.active) {
932
- throw new Error(`Preferred openai token ${preferredTokenId} is not available`);
933
- }
934
-
935
- const threshold = preferred.quotaThreshold;
936
-
937
- if (threshold !== null && threshold !== undefined) {
938
- throw new QuotaThresholdExceededError(
939
- quotaMessage([{ name: preferred.name, threshold }]),
940
- );
941
- }
942
- }
943
- }
139
+ // ---- Realtime voice (speech-to-text, text-to-speech) ----------------------
944
140
 
945
- // 콜드 캐시에서 토큰 수만큼 조회 지연이 쌓이지 않도록 병렬 판정한다.
946
- const activeTokens = [...this.tokenMetadata.entries()].filter(([, token]) => token.active);
141
+ async transcribe(
142
+ request: OpenAITranscribeRequest & MediaTokenSelection,
143
+ ): Promise<MediaDispatchResult<OpenAITranscription>> {
144
+ const { preferredTokenId, requirePreferredToken, ...voiceRequest } = request;
947
145
 
948
- const checks = await Promise.all(
949
- activeTokens.map(async ([id, token]) => ({
950
- id,
951
- token,
952
- eligible: await this.isQuotaEligible(id, token, signal),
953
- })),
146
+ return this.pool.runWithToken(
147
+ { preferredTokenId, requirePreferredToken },
148
+ request.signal,
149
+ (credentials) => this.voiceClient.transcribe(credentials, voiceRequest),
954
150
  );
955
-
956
- const eligible = new Set(checks.filter((c) => c.eligible).map((c) => c.id));
957
-
958
- if (eligible.size === 0) {
959
- const over = checks.flatMap((c) => {
960
- const threshold = c.token.quotaThreshold;
961
-
962
- return c.eligible || threshold === null || threshold === undefined
963
- ? []
964
- : [{ name: c.token.name, threshold }];
965
- });
966
-
967
- if (over.length) {
968
- logger.warn("quota_threshold gate: all_exceeded", {
969
- provider: "openai",
970
- overThresholdTokens: over,
971
- });
972
- throw new QuotaThresholdExceededError(quotaMessage(over));
973
- }
974
-
975
- throw new Error("NO_OPENAI_WORKERS");
976
- }
977
-
978
- const selected = this.selector.select(eligible);
979
- const metadata = selected !== null ? this.tokenMetadata.get(selected) : undefined;
980
-
981
- if (selected === null || !metadata) throw new Error("NO_OPENAI_WORKERS");
982
-
983
- return { tokenId: selected, metadata };
984
151
  }
985
152
 
986
- setToken(
987
- id: number,
988
- name: string,
989
- credentials: OpenAICredentials,
990
- quotaThreshold: number | null | undefined,
991
- weight: number,
992
- active: boolean,
993
- ): void {
994
- const old = this.tokenMetadata.get(id);
995
-
996
- if (old) {
997
- Object.assign(old, {
998
- name,
999
- credentials,
1000
- quotaThreshold,
1001
- weight,
1002
- active,
1003
- generation: old.generation + 1,
1004
- });
1005
- } else {
1006
- this.tokenMetadata.set(id, {
1007
- name,
1008
- credentials,
1009
- quotaThreshold,
1010
- weight,
1011
- active,
1012
- generation: 1,
1013
- });
1014
- }
1015
-
1016
- this.selector.setToken(id, weight);
1017
- this.invalidateRateLimitsCache(id);
1018
- this.quotaBlocked.delete(id);
1019
- }
1020
-
1021
- async getRateLimitsByTokenId(
1022
- tokenId: number,
1023
- signal?: AbortSignal,
1024
- ): Promise<OpenAIRateLimitsWithMeta> {
1025
- const token = this.tokenMetadata.get(tokenId);
1026
-
1027
- if (!token) throw new Error(`openai token ${tokenId} not found`);
1028
- const generation = token.generation;
1029
- const cached = this.rateLimitsCache.get(tokenId);
1030
-
1031
- if (
1032
- cached &&
1033
- cached.generation === token.generation &&
1034
- Date.now() - cached.cachedAt < OpenAIDispatcher.RATE_LIMITS_CACHE_TTL
1035
- )
1036
- return cached;
1037
-
1038
- // TTL 만료 시 조회를 공유한다. 최초 호출자의 abort로 실패해도 isQuotaEligible은 fail-open한다.
1039
- const pending = this.pendingRateLimits.get(tokenId);
1040
-
1041
- if (pending?.token === token && pending.generation === generation) return pending.promise;
1042
-
1043
- const fetchPromise = (async () => {
1044
- const result = await readOpenAIQuotaUsage({
1045
- credentials: token.credentials,
1046
- refreshCredentials: () => this.refreshCredentials(tokenId),
1047
- fetch: this.fetchImpl,
1048
- signal,
1049
- });
1050
-
1051
- if (result.kind === "lookup_failed") throw new Error(result.reason);
1052
-
1053
- if (!result.raw) throw new Error("OpenAI quota response missing raw rate limits");
1054
- const entry = { data: result.raw, cachedAt: Date.now(), generation };
1055
-
1056
- if (this.tokenMetadata.get(tokenId) === token && token.generation === generation) {
1057
- this.rateLimitsCache.set(tokenId, entry);
1058
- }
1059
-
1060
- return entry;
1061
- })().finally(() => {
1062
- if (this.pendingRateLimits.get(tokenId)?.promise === fetchPromise) {
1063
- this.pendingRateLimits.delete(tokenId);
1064
- }
1065
- });
1066
-
1067
- this.pendingRateLimits.set(tokenId, { token, generation, promise: fetchPromise });
1068
-
1069
- return fetchPromise;
1070
- }
1071
-
1072
- async refreshCredentials(tokenId: number) {
1073
- const previous = this.tokenMetadata.get(tokenId);
1074
- const generation = previous?.generation;
1075
- const refreshed = await handleChatgptAuthTokensRefresh(tokenId);
1076
-
1077
- const credentials = {
1078
- accessToken: refreshed.accessToken,
1079
- accountId: refreshed.chatgptAccountId,
1080
- };
1081
-
1082
- const current = this.tokenMetadata.get(tokenId);
1083
-
1084
- if (!current?.active) throw new Error(`openai token ${tokenId} is no longer active`);
1085
-
1086
- // A subscriber update may already contain newer credentials. Never overwrite it
1087
- // with the result of a refresh that started against an older generation.
1088
- if (current === previous && current.generation === generation) {
1089
- current.credentials = { ...current.credentials, ...credentials };
1090
- this.retireClient(tokenId);
1091
- this.invalidateRateLimitsCache(tokenId);
1092
- }
1093
-
1094
- return {
1095
- accessToken: current.credentials.accessToken,
1096
- accountId: current.credentials.accountId,
1097
- };
1098
- }
1099
-
1100
- async isQuotaEligible(id: number, token: TokenMetadata, signal?: AbortSignal): Promise<boolean> {
1101
- if (token.quotaThreshold === null || token.quotaThreshold === undefined) return true;
1102
- const generation = token.generation;
1103
- const result = await readOpenAIQuotaUsage(async () => this.getRateLimitsByTokenId(id, signal));
1104
- const current = this.tokenMetadata.get(id);
1105
-
1106
- // A token update (credential refresh, sync) landed mid-lookup: judge the updated token
1107
- // instead of reporting it over quota.
1108
- if (current !== token || token.generation !== generation) {
1109
- return current?.active ? this.isQuotaEligible(id, current, signal) : false;
1110
- }
1111
-
1112
- if (result.kind === "lookup_failed") {
1113
- this.quotaBlocked.delete(id);
1114
- logger.warn("quota_threshold gate: lookup_fail_open", {
1115
- tokenId: id,
1116
- tokenName: token.name,
1117
- lookupReason: result.reason,
1118
- });
1119
-
1120
- return true;
1121
- }
1122
-
1123
- if (result.utilizationPct >= token.quotaThreshold) {
1124
- if (!this.quotaBlocked.has(id))
1125
- logger.info(
1126
- `quota_threshold gate: over_threshold ${token.name}[${id}] (${result.utilizationPct}% >= ${token.quotaThreshold}%)`,
1127
- );
1128
- this.quotaBlocked.add(id);
1129
-
1130
- return false;
1131
- }
1132
-
1133
- if (this.quotaBlocked.delete(id))
1134
- logger.info(
1135
- `quota_threshold gate: recovered ${token.name}[${id}] (${result.utilizationPct}% < ${token.quotaThreshold}%)`,
1136
- );
153
+ async speak(
154
+ request: OpenAISpeakRequest & MediaTokenSelection,
155
+ ): Promise<MediaDispatchResult<OpenAISpeechResult>> {
156
+ const { preferredTokenId, requirePreferredToken, ...voiceRequest } = request;
1137
157
 
1138
- return true;
158
+ return this.pool.runWithToken(
159
+ { preferredTokenId, requirePreferredToken },
160
+ request.signal,
161
+ (credentials) => this.voiceClient.speak(credentials, voiceRequest),
162
+ );
1139
163
  }
1140
164
 
1141
- invalidateRateLimitsCache(id: number): void {
1142
- this.rateLimitsCache.delete(id);
1143
- }
165
+ async startLive(
166
+ request: OpenAILiveCallRequest & MediaTokenSelection,
167
+ ): Promise<MediaDispatchResult<OpenAILiveCall>> {
168
+ const { preferredTokenId, requirePreferredToken, ...liveRequest } = request;
1144
169
 
1145
- countActiveTokens(): number {
1146
- return [...this.tokenMetadata.values()].filter((t) => t.active).length;
170
+ return this.pool.runWithToken(
171
+ { preferredTokenId, requirePreferredToken },
172
+ request.signal,
173
+ (credentials) => this.voiceClient.createLiveCall(credentials, liveRequest),
174
+ );
1147
175
  }
1148
176
 
1149
- // 모니터링 폴링은 TTL 내 캐시만 읽고 fetch하지 않는다. 미조회 토큰은 usedPercent가 null이다.
1150
- getQuotaSnapshot(): Array<{
1151
- name: string;
1152
- usedPercent: number | null;
1153
- threshold: number | null;
1154
- blocked: boolean;
1155
- resetsAt: number | null;
1156
- }> {
1157
- const now = Date.now();
1158
-
1159
- return [...this.tokenMetadata.entries()]
1160
- .map(([id, t]) => {
1161
- const cached = this.rateLimitsCache.get(id);
177
+ // ---- Native Decisions ----------------------------------------------------
1162
178
 
1163
- const fresh =
1164
- cached !== undefined &&
1165
- cached.generation === t.generation &&
1166
- now - cached.cachedAt < OpenAIDispatcher.RATE_LIMITS_CACHE_TTL;
179
+ async decide(
180
+ request: OpenAIDecisionRequest & MediaTokenSelection & { signal?: AbortSignal },
181
+ ): Promise<MediaDispatchResult<OpenAIDecisionResult>> {
182
+ const { preferredTokenId, requirePreferredToken, signal, ...decision } = request;
1167
183
 
1168
- const primary = fresh ? cached.data.rateLimits?.primary : undefined;
1169
-
1170
- return {
1171
- name: t.name,
1172
- usedPercent: primary?.usedPercent ?? null,
1173
- threshold: t.quotaThreshold ?? null,
1174
- blocked: this.quotaBlocked.has(id),
1175
- // wham의 Unix 초를 epoch ms로 변환한다.
1176
- resetsAt:
1177
- primary?.resetsAt !== null && primary?.resetsAt !== undefined
1178
- ? primary.resetsAt * 1000
1179
- : null,
1180
- };
1181
- })
1182
- .toSorted((a, b) => a.name.localeCompare(b.name));
184
+ return this.pool.runWithToken(
185
+ { preferredTokenId, requirePreferredToken },
186
+ signal,
187
+ (credentials) => createOpenAIDecision(credentials, decision, signal, this.pool.fetchImpl),
188
+ { refreshQuota: false },
189
+ );
1183
190
  }
1184
191
  }