@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
@@ -0,0 +1,677 @@
1
+ import { z } from "zod";
2
+
3
+ import { resolveOpenAIEffort } from "../common/effort";
4
+ import {
5
+ type GenerateRequest,
6
+ type GenerateResult,
7
+ type GenerateStreamCallbacks,
8
+ type GeneratedImage,
9
+ } from "../common/provider-dispatcher";
10
+ import { isJsonObject, jsonString } from "../common/provider-types";
11
+ import { ThinkingValidationError } from "../common/thinking";
12
+ import {
13
+ imageMimeType,
14
+ type JsonValue,
15
+ type OpenAINormalizedEvent,
16
+ type OpenAIResponseItem,
17
+ type OpenAIResponsesOptions,
18
+ } from "./openai-backend-protocol";
19
+ import { type OpenAIDirectClient, type OpenAIDirectClientOptions } from "./openai-direct-client";
20
+ import { type OpenAITokenPool, type TokenSelection } from "./openai-token-pool";
21
+ import { type OpenAITransportKind } from "./openai-transport-config";
22
+
23
+ // Verified with the subscription Responses backend; public API support is not sufficient.
24
+ const THINKING_OFF_MODELS = new Set([
25
+ "gpt-6.1-terra",
26
+ "gpt-6-sol",
27
+ "gpt-6-luna",
28
+ "gpt-5.6-sol",
29
+ "gpt-5.6-terra",
30
+ "gpt-5.6-luna",
31
+ "gpt-5.5",
32
+ ]);
33
+
34
+ const DEFAULT_REQUEST_TIMEOUT_MS = 600_000;
35
+ const IMAGE_TOOL = "generate_image";
36
+
37
+ type ImageToolArguments = {
38
+ prompt: string;
39
+ transparent_background: boolean;
40
+ num_last_images_to_include: number;
41
+ };
42
+
43
+ // Exactly these three keys; the backend rejects strict tools, so arguments are validated here.
44
+ const ImageToolArgumentsSchema = z.strictObject({
45
+ prompt: z.string().refine((prompt) => prompt.trim().length > 0),
46
+ transparent_background: z.boolean(),
47
+ num_last_images_to_include: z.number().int().min(0).max(5),
48
+ });
49
+
50
+ function generatedImageFrom(
51
+ event: Extract<OpenAINormalizedEvent, { type: "image" }>,
52
+ ): GeneratedImage {
53
+ const image: GeneratedImage = {
54
+ data: event.base64,
55
+ mediaType: event.mimeType,
56
+ revisedPrompt: event.revisedPrompt ?? null,
57
+ };
58
+
59
+ if (event.generation) image.generation = event.generation;
60
+
61
+ return image;
62
+ }
63
+
64
+ export type ImageFailureKind = "gate" | "not_called" | "incomplete";
65
+
66
+ export class ImageGenerationError extends Error {
67
+ completedDriver?: GenerateResult;
68
+
69
+ constructor(
70
+ readonly kind: ImageFailureKind,
71
+ message: string,
72
+ options?: ErrorOptions,
73
+ ) {
74
+ super(message, options);
75
+ this.name = "ImageGenerationError";
76
+ }
77
+ }
78
+
79
+ export type OpenAIDirectClientFactory = (
80
+ options: OpenAIDirectClientOptions,
81
+ tokenId: number,
82
+ ) => Pick<OpenAIDirectClient, "responses"> & { close?: () => void };
83
+
84
+ type ClientEntry = {
85
+ generation: number;
86
+ client: Pick<OpenAIDirectClient, "responses"> & { close?: () => void };
87
+ inFlight: number;
88
+ retired: boolean;
89
+ };
90
+
91
+ function abortError(signal: AbortSignal): Error {
92
+ const reason = signal.reason;
93
+
94
+ return reason instanceof Error ? reason : new DOMException("Aborted", "AbortError");
95
+ }
96
+
97
+ function activeSignal(signal?: AbortSignal, timeoutMs?: number): AbortSignal {
98
+ const timeout = AbortSignal.timeout(timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);
99
+
100
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
101
+ }
102
+
103
+ function inputItems(req: GenerateRequest): JsonValue[] {
104
+ const history = req.coldHistory ?? [];
105
+
106
+ const content: OpenAIResponseItem[] = req.coldInput.map((input) => {
107
+ if (input.type === "text") return { type: "input_text", text: input.text };
108
+
109
+ if (input.type === "image") return { type: "input_image", image_url: input.url };
110
+
111
+ if (input.type === "localImage") return { type: "input_image", image_url: input.path };
112
+
113
+ return { type: "input_text", text: `${input.name}: ${input.path}` };
114
+ });
115
+
116
+ return [...history, { type: "message", role: "user", content }];
117
+ }
118
+
119
+ function imageReferences(req: GenerateRequest): OpenAIResponseItem[] {
120
+ return inputItems(req).flatMap((item) => {
121
+ if (!isJsonObject(item)) return [];
122
+ const result = jsonString(item.result);
123
+
124
+ if (item.type === "image_generation_call" && result !== undefined) {
125
+ return [
126
+ {
127
+ type: "input_image",
128
+ image_url: `data:${imageMimeType(result, item.output_format)};base64,${result}`,
129
+ },
130
+ ];
131
+ }
132
+
133
+ if (!Array.isArray(item.content)) return [];
134
+
135
+ return item.content
136
+ .filter(isJsonObject)
137
+ .filter((part) => part.type === "input_image" || part.type === "image_url");
138
+ });
139
+ }
140
+
141
+ type OpenAIReasoning = NonNullable<OpenAIResponsesOptions["reasoning"]>;
142
+
143
+ function asReasoning(req: GenerateRequest): OpenAIReasoning | undefined {
144
+ if (req.thinking === false) return { effort: "none" };
145
+
146
+ const summary =
147
+ req.reasoningSummary && req.reasoningSummary !== "none" ? req.reasoningSummary : undefined;
148
+
149
+ const effort =
150
+ resolveOpenAIEffort(req.model ?? "", req.effort) ?? (req.thinking === true ? "low" : undefined);
151
+
152
+ if (!effort && !summary) return undefined;
153
+
154
+ const reasoning: OpenAIReasoning = {};
155
+
156
+ // ultra is a Codex client mode (sub-agent delegation), not a wire value; the backend accepts up to max.
157
+ if (effort) reasoning.effort = effort === "ultra" ? "max" : effort;
158
+
159
+ if (summary) reasoning.summary = summary;
160
+
161
+ return reasoning;
162
+ }
163
+
164
+ const AUTO_IMAGE_INSTRUCTIONS =
165
+ "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.";
166
+
167
+ const AUTO_IMAGE_TOOL: OpenAIResponseItem = {
168
+ type: "function",
169
+ name: IMAGE_TOOL,
170
+ description:
171
+ "Generate or edit an image, optionally with a transparent background or recent conversation images as references.",
172
+ // Astra's subscription backend rejects strict tools; validate arguments locally.
173
+ strict: false,
174
+ parameters: {
175
+ type: "object",
176
+ properties: {
177
+ prompt: {
178
+ type: "string",
179
+ minLength: 1,
180
+ description: "Complete, self-contained instructions for the image generation or edit.",
181
+ },
182
+ transparent_background: { type: "boolean" },
183
+ num_last_images_to_include: { type: "integer", minimum: 0, maximum: 5 },
184
+ },
185
+ required: ["prompt", "transparent_background", "num_last_images_to_include"],
186
+ additionalProperties: false,
187
+ },
188
+ };
189
+
190
+ /**
191
+ * Hosted web search as Codex sends it (tools/src/tool_spec.rs); `external_web_access` asks for
192
+ * live search rather than the cached index. Answered on the subscription route (2026-11-10).
193
+ */
194
+ const WEB_SEARCH_TOOL: OpenAIResponseItem = { type: "web_search", external_web_access: true };
195
+
196
+ function requestOptions(req: GenerateRequest): OpenAIResponsesOptions {
197
+ const { outputFormat, ...imageControls } = req.imageGenerationOptions ?? {};
198
+ const auto = req.imageGeneration === "auto";
199
+
200
+ if (auto && req.outputSchema) {
201
+ throw new ImageGenerationError(
202
+ "gate",
203
+ "Automatic image generation does not support structured output or external tools",
204
+ );
205
+ }
206
+
207
+ if (auto && outputFormat && outputFormat !== "png") {
208
+ throw new ImageGenerationError("gate", "Automatic image generation only supports PNG output");
209
+ }
210
+
211
+ const options: OpenAIResponsesOptions = { model: req.model ?? "", history: inputItems(req) };
212
+
213
+ if (req.systemPrompt) options.instructions = req.systemPrompt;
214
+
215
+ if (auto) {
216
+ options.instructions = [req.systemPrompt, AUTO_IMAGE_INSTRUCTIONS].filter(Boolean).join("\n\n");
217
+ options.parallelToolCalls = false;
218
+ options.tools = [AUTO_IMAGE_TOOL];
219
+ }
220
+
221
+ // Function tools reach OpenAI through qgrid's tool emulation; only hosted search goes native.
222
+ if (req.tools?.some((tool) => tool.type === "web_search")) {
223
+ options.tools = [...(options.tools ?? []), WEB_SEARCH_TOOL];
224
+ }
225
+
226
+ const reasoning = asReasoning(req);
227
+
228
+ if (reasoning) options.reasoning = reasoning;
229
+
230
+ if (req.verbosity) options.verbosity = req.verbosity;
231
+
232
+ if (req.serviceTier) {
233
+ options.serviceTier = req.serviceTier === "fast" ? "priority" : req.serviceTier;
234
+ }
235
+
236
+ if (req.promptCacheKey) options.promptCacheKey = req.promptCacheKey;
237
+
238
+ if (req.outputSchema) options.outputSchema = { schema: req.outputSchema };
239
+
240
+ if (req.imageGeneration && !auto) {
241
+ if (req.imageGenerationOptions) {
242
+ const controls: OpenAIResponseItem = { ...imageControls };
243
+
244
+ if (outputFormat) controls.output_format = outputFormat;
245
+ options.imageGeneration = controls;
246
+ } else {
247
+ options.imageGeneration = true;
248
+ }
249
+ }
250
+
251
+ return options;
252
+ }
253
+
254
+ /**
255
+ * Codex Responses on the shared token pool: text, tool emulation, and chat-driven images. Keeps
256
+ * one direct client per token and retires it when the pool invalidates that token.
257
+ */
258
+ export class OpenAIResponsesRuntime {
259
+ readonly clients = new Map<number, ClientEntry>();
260
+ readonly retiredClients = new Set<ClientEntry>();
261
+ inFlight = 0;
262
+
263
+ constructor(
264
+ readonly pool: OpenAITokenPool,
265
+ readonly transportKind: OpenAITransportKind,
266
+ readonly clientFactory: OpenAIDirectClientFactory,
267
+ ) {
268
+ // A token whose credentials were refreshed or removed must not keep its client.
269
+ pool.onTokenInvalidated((tokenId) => this.retireClient(tokenId));
270
+ }
271
+
272
+ async generateStream(req: GenerateRequest, cb: GenerateStreamCallbacks): Promise<void> {
273
+ if (req.imageGeneration)
274
+ throw new ImageGenerationError(
275
+ "gate",
276
+ "image generation is not supported on the streaming path",
277
+ );
278
+
279
+ try {
280
+ cb.onComplete(await this.run(req, cb.onDelta));
281
+ } catch (error) {
282
+ cb.onError(error instanceof Error ? error : new Error(String(error)));
283
+ throw error;
284
+ }
285
+ }
286
+
287
+ async run(req: GenerateRequest, onDelta?: (text: string) => void): Promise<GenerateResult> {
288
+ if (req.thinking === false) {
289
+ const model = req.model ?? "";
290
+
291
+ if (!THINKING_OFF_MODELS.has(model)) {
292
+ const reason =
293
+ model === "gpt-6-astra" || model === "gpt-6.1-sol"
294
+ ? "the subscription backend requires thinking"
295
+ : "thinking-off support has not been verified on the subscription backend";
296
+
297
+ throw new ThinkingValidationError(
298
+ `thinking:false is unavailable for OpenAI model ${model || "<default>"}: ${reason}`,
299
+ );
300
+ }
301
+ }
302
+
303
+ const signal = activeSignal(req.abortSignal, req.timeoutMs);
304
+
305
+ if (signal.aborted) throw abortError(signal);
306
+
307
+ const selection = await this.pool.selectToken(
308
+ req.preferredTokenId,
309
+ req.requirePreferredToken ?? false,
310
+ signal,
311
+ );
312
+
313
+ this.inFlight++;
314
+
315
+ try {
316
+ if (signal.aborted) throw abortError(signal);
317
+
318
+ return await this.runDirect(selection, { ...req, abortSignal: signal }, onDelta);
319
+ } finally {
320
+ this.inFlight--;
321
+ }
322
+ }
323
+
324
+ async runDirect(
325
+ selection: TokenSelection,
326
+ req: GenerateRequest,
327
+ onDelta?: (text: string) => void,
328
+ ): Promise<GenerateResult> {
329
+ const startedAt = Date.now();
330
+ let firstDeltaAt: number | undefined;
331
+ let text = "";
332
+ req.onProgress?.({ tokenName: selection.metadata.name });
333
+
334
+ const markFirstDelta = () => {
335
+ if (firstDeltaAt !== undefined) return;
336
+ firstDeltaAt = Date.now();
337
+ req.onProgress?.({ ttftMs: firstDeltaAt - startedAt });
338
+ };
339
+
340
+ let outputMessageAccepted = false;
341
+ const messagePhases = new Map<string, string>();
342
+ const streamedMessageIds = new Set<string>();
343
+
344
+ let usage = {
345
+ totalTokens: 0,
346
+ inputTokens: 0,
347
+ outputTokens: 0,
348
+ cachedInputTokens: 0,
349
+ reasoningOutputTokens: 0,
350
+ };
351
+
352
+ const images: GeneratedImage[] = [];
353
+ let imageAttempted = false;
354
+ const auto = req.imageGeneration === "auto";
355
+ const imageCalls = new Map<string, ImageToolArguments>();
356
+ const imageCallIds = new Set<JsonValue | undefined>();
357
+ let imageToolAttempted = false;
358
+ let driverCompleted = false;
359
+ let servingModel = req.model ?? "";
360
+ const metadata = selection.metadata;
361
+
362
+ const driverResult = (): GenerateResult => {
363
+ const result: GenerateResult = {
364
+ text,
365
+ tokenName: metadata.name,
366
+ usage,
367
+ durationMs: Date.now() - startedAt,
368
+ ttftMs: firstDeltaAt === undefined ? null : firstDeltaAt - startedAt,
369
+ model: servingModel,
370
+ threadCoord: {
371
+ workerId: selection.tokenId,
372
+ threadId: req.promptCacheKey ?? "",
373
+ epoch: -1,
374
+ },
375
+ };
376
+
377
+ if (servingModel !== req.model) result.requestedModel = req.model;
378
+
379
+ return result;
380
+ };
381
+
382
+ const clientEntry = this.acquireClient(selection);
383
+
384
+ try {
385
+ for await (const event of clientEntry.client.responses(
386
+ requestOptions(req),
387
+ req.abortSignal,
388
+ )) {
389
+ const itemId = event.type === "output-item" ? jsonString(event.item.id) : undefined;
390
+ const itemPhase = event.type === "output-item" ? jsonString(event.item.phase) : undefined;
391
+
392
+ if (
393
+ req.stopAfterOutputMessage &&
394
+ event.type === "output-item" &&
395
+ event.item.type === "message" &&
396
+ itemId !== undefined &&
397
+ itemPhase !== undefined
398
+ ) {
399
+ messagePhases.set(itemId, itemPhase);
400
+ }
401
+
402
+ if (event.type === "text-delta") {
403
+ if (outputMessageAccepted) continue;
404
+
405
+ if (req.stopAfterOutputMessage && event.itemId) {
406
+ // Buffer commentary/unclassified messages until their completed item.
407
+ // Known final answers retain incremental streaming.
408
+ if (messagePhases.get(event.itemId) !== "final_answer") continue;
409
+ streamedMessageIds.add(event.itemId);
410
+ }
411
+
412
+ markFirstDelta();
413
+ text += event.text;
414
+ onDelta?.(event.text);
415
+ } else if (
416
+ event.type === "output-item" &&
417
+ event.completed &&
418
+ event.item.type === "message" &&
419
+ !outputMessageAccepted &&
420
+ req.stopAfterOutputMessage &&
421
+ Array.isArray(event.item.content)
422
+ ) {
423
+ const messageText = event.item.content
424
+ .flatMap((part) => {
425
+ const partText =
426
+ isJsonObject(part) && part.type === "output_text"
427
+ ? jsonString(part.text)
428
+ : undefined;
429
+
430
+ return partText === undefined ? [] : [partText];
431
+ })
432
+ .join("");
433
+
434
+ // A valid client tool request ends this application turn. Later answers cannot
435
+ // know its result yet. Never split/repair malformed JSON within a message.
436
+ const phase = itemPhase;
437
+
438
+ if (messageText) outputMessageAccepted = req.stopAfterOutputMessage(messageText, phase);
439
+
440
+ if (
441
+ itemId !== undefined &&
442
+ !streamedMessageIds.has(itemId) &&
443
+ (phase !== "commentary" || outputMessageAccepted) &&
444
+ messageText
445
+ ) {
446
+ markFirstDelta();
447
+ text += messageText;
448
+ onDelta?.(messageText);
449
+ streamedMessageIds.add(itemId);
450
+ }
451
+ } else if (event.type === "image") {
452
+ if (auto) throw new ImageGenerationError("incomplete", "Unexpected image output");
453
+ imageAttempted = true;
454
+ images.push(generatedImageFrom(event));
455
+ } else if (auto && event.type === "output-item" && event.item.type === "function_call") {
456
+ if (event.item.name !== IMAGE_TOOL) {
457
+ throw new ImageGenerationError("incomplete", "Unexpected automatic image tool call");
458
+ }
459
+
460
+ imageToolAttempted = true;
461
+ imageCallIds.add(event.item.call_id);
462
+
463
+ if (!event.completed) continue;
464
+ const id = jsonString(event.item.call_id);
465
+ const rawArguments = jsonString(event.item.arguments);
466
+ let decoded: JsonValue;
467
+
468
+ try {
469
+ if (rawArguments === undefined) throw new Error("missing arguments");
470
+ // JSON.parse without a reviver yields only JSON values.
471
+ decoded = JSON.parse(rawArguments);
472
+ } catch {
473
+ throw new ImageGenerationError("incomplete", "Invalid image tool arguments");
474
+ }
475
+
476
+ const parsedArgs = ImageToolArgumentsSchema.safeParse(decoded);
477
+
478
+ if (!id || !parsedArgs.success) {
479
+ throw new ImageGenerationError("incomplete", "Invalid image tool arguments");
480
+ }
481
+
482
+ const args = parsedArgs.data;
483
+
484
+ const previous = imageCalls.get(id);
485
+
486
+ if (
487
+ previous &&
488
+ (previous.prompt !== args.prompt ||
489
+ previous.transparent_background !== args.transparent_background ||
490
+ previous.num_last_images_to_include !== args.num_last_images_to_include)
491
+ ) {
492
+ throw new ImageGenerationError("incomplete", "Conflicting image tool calls");
493
+ }
494
+
495
+ imageCalls.set(id, {
496
+ prompt: args.prompt,
497
+ transparent_background: args.transparent_background,
498
+ num_last_images_to_include: args.num_last_images_to_include,
499
+ });
500
+ } else if (event.type === "completed") {
501
+ driverCompleted = true;
502
+ servingModel = event.model ?? servingModel;
503
+
504
+ if (event.usage) {
505
+ usage = {
506
+ totalTokens: event.usage.totalTokens,
507
+ inputTokens: event.usage.inputTokens,
508
+ outputTokens: event.usage.outputTokens,
509
+ cachedInputTokens: event.usage.cachedInputTokens,
510
+ reasoningOutputTokens: event.usage.reasoningTokens,
511
+ };
512
+ }
513
+ } else if (event.type === "error") {
514
+ if (req.imageGeneration)
515
+ throw new ImageGenerationError("incomplete", event.error.message);
516
+ throw event.error;
517
+ }
518
+ }
519
+
520
+ if (auto && imageToolAttempted) {
521
+ if (!driverCompleted || imageCalls.size !== 1 || imageCallIds.size !== 1) {
522
+ throw new ImageGenerationError("incomplete", "Expected one completed image tool call");
523
+ }
524
+
525
+ if (req.abortSignal?.aborted) throw abortError(req.abortSignal);
526
+ const args = [...imageCalls.values()][0]!;
527
+ const referenceCount = args.num_last_images_to_include;
528
+ const references = referenceCount ? imageReferences(req) : [];
529
+
530
+ if (referenceCount > references.length) {
531
+ throw new ImageGenerationError(
532
+ "incomplete",
533
+ "Requested image references are unavailable",
534
+ );
535
+ }
536
+
537
+ let imageCompleted = false;
538
+
539
+ for await (const event of clientEntry.client.responses(
540
+ {
541
+ model: "gpt-image-2",
542
+ history: [
543
+ {
544
+ type: "message",
545
+ role: "user",
546
+ content: [
547
+ { type: "input_text", text: args.prompt },
548
+ ...(referenceCount ? references.slice(-referenceCount) : []),
549
+ ],
550
+ },
551
+ ],
552
+ imageGeneration: {
553
+ quality: req.imageGenerationOptions?.quality,
554
+ size: req.imageGenerationOptions?.size,
555
+ output_format: "png",
556
+ background: args.transparent_background ? "transparent" : "opaque",
557
+ },
558
+ },
559
+ req.abortSignal,
560
+ )) {
561
+ if (event.type === "image") images.push(generatedImageFrom(event));
562
+ else if (event.type === "completed") imageCompleted = true;
563
+ else if (event.type === "error")
564
+ throw new ImageGenerationError("incomplete", event.error.message, {
565
+ cause: event.error,
566
+ });
567
+ }
568
+
569
+ imageAttempted = true;
570
+
571
+ if (!imageCompleted)
572
+ throw new ImageGenerationError("incomplete", "Image generation did not complete");
573
+ }
574
+
575
+ if (auto && imageAttempted && !driverCompleted)
576
+ throw new ImageGenerationError("incomplete", "Image generation response did not complete");
577
+
578
+ if (req.abortSignal?.aborted) throw abortError(req.abortSignal);
579
+
580
+ if ((req.imageGeneration === true || (auto && imageAttempted)) && images.length === 0) {
581
+ throw new ImageGenerationError(
582
+ imageAttempted ? "incomplete" : "not_called",
583
+ imageAttempted
584
+ ? "image generation did not complete"
585
+ : "model did not call image generation",
586
+ );
587
+ }
588
+ } catch (error) {
589
+ if (auto && driverCompleted && imageToolAttempted) {
590
+ const failure =
591
+ error instanceof ImageGenerationError
592
+ ? error
593
+ : new ImageGenerationError(
594
+ "incomplete",
595
+ error instanceof Error ? error.message : String(error),
596
+ { cause: error },
597
+ );
598
+
599
+ if (error instanceof Error) failure.name = error.name;
600
+ // Only the completed chat stage is chargeable here; discard partial image output.
601
+ failure.completedDriver = driverResult();
602
+ throw failure;
603
+ }
604
+
605
+ throw error;
606
+ } finally {
607
+ this.releaseClient(clientEntry);
608
+ }
609
+
610
+ const result = driverResult();
611
+
612
+ if (images.length) result.images = images;
613
+
614
+ return result;
615
+ }
616
+
617
+ /** 세대가 바뀐 client 는 사용 중인 요청이 끝난 뒤에 닫는다. */
618
+ acquireClient(selection: TokenSelection): ClientEntry {
619
+ const metadata = selection.metadata;
620
+ let entry = this.clients.get(selection.tokenId);
621
+
622
+ if (entry && entry.generation !== metadata.generation) {
623
+ this.retireClient(selection.tokenId);
624
+ entry = undefined;
625
+ }
626
+
627
+ if (!entry) {
628
+ const client = this.clientFactory(
629
+ {
630
+ credentials: {
631
+ accessToken: metadata.credentials.accessToken,
632
+ accountId: metadata.credentials.accountId,
633
+ },
634
+ transportKind: this.transportKind,
635
+ fetch: this.pool.fetchImpl,
636
+ refreshCredentials: () => this.pool.refreshCredentials(selection.tokenId),
637
+ },
638
+ selection.tokenId,
639
+ );
640
+
641
+ entry = { generation: metadata.generation, client, inFlight: 0, retired: false };
642
+ this.clients.set(selection.tokenId, entry);
643
+ }
644
+
645
+ entry.inFlight++;
646
+
647
+ return entry;
648
+ }
649
+
650
+ releaseClient(entry: ClientEntry): void {
651
+ entry.inFlight = Math.max(0, entry.inFlight - 1);
652
+
653
+ if (entry.retired && entry.inFlight === 0) {
654
+ this.retiredClients.delete(entry);
655
+ entry.client.close?.();
656
+ }
657
+ }
658
+
659
+ retireClient(tokenId: number): void {
660
+ const entry = this.clients.get(tokenId);
661
+
662
+ if (!entry) return;
663
+ this.clients.delete(tokenId);
664
+ entry.retired = true;
665
+
666
+ if (entry.inFlight === 0) entry.client.close?.();
667
+ else this.retiredClients.add(entry);
668
+ }
669
+
670
+ /** Closes every client, including retired ones still serving a request. */
671
+ close(): void {
672
+ this.clients.forEach(({ client }) => client.close?.());
673
+ this.clients.clear();
674
+ this.retiredClients.forEach((entry) => entry.client.close?.());
675
+ this.retiredClients.clear();
676
+ }
677
+ }