@cartanova/qgrid-cli 2.20.0 → 2.22.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.
Files changed (81) 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-DjrhMvkM.js → index-CKbDrgCl.js} +17 -17
  51. package/bundle/web-dist/client/assets/{logs-DN5BhglL.js → logs-wd-lZx75.js} +1 -1
  52. package/bundle/web-dist/client/assets/{monit-DZPRb015.js → monit-BjQUu4NS.js} +1 -1
  53. package/bundle/web-dist/client/assets/{routes-DJAp0zIh.js → routes-D-C4eD90.js} +1 -1
  54. package/bundle/web-dist/client/assets/{settings-WY3p1iSx.js → settings-DeJEEmWL.js} +1 -1
  55. package/bundle/web-dist/client/assets/{show-DykCwUpU.js → show-DGcvCaF6.js} +2 -2
  56. package/bundle/web-dist/client/assets/{tokens-DSdQ7R5O.js → tokens-DZCpfLEe.js} +1 -1
  57. package/bundle/web-dist/client/assets/{use-oauth-login-flow-gc2fKVxE.js → use-oauth-login-flow-Rg_ah3e1.js} +1 -1
  58. package/bundle/web-dist/client/assets/{use-update-token-mutation-BGVP43e8.js → use-update-token-mutation-DHVJywXU.js} +1 -1
  59. package/bundle/web-dist/client/assets/{voice-DRzMbzHH.js → voice-CfCzLZf2.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/references/ai-sdk-provider-contract.md +11 -1
  78. package/skills/qgrid/references/decision-rationale.md +6 -0
  79. package/skills/qgrid/references/openai-codex-runtime.md +9 -2
  80. package/skills/qgrid/references/request-log-run-lifecycle.md +3 -1
  81. package/skills/qgrid/references/token-auth-quota-lifecycle.md +4 -2
@@ -29,6 +29,7 @@ import {
29
29
  grokReportedCost,
30
30
  grokSpeechCost,
31
31
  liveCost,
32
+ openaiDecisionCost,
32
33
  openaiSpeechCost,
33
34
  sttCost,
34
35
  type VoiceCost,
@@ -70,11 +71,17 @@ import {
70
71
  GROK_TTS_DEFAULT_LANGUAGE,
71
72
  GROK_TTS_DEFAULT_VOICE,
72
73
  } from "../../utils/providers/grok/grok-voice-client";
74
+ import { OpenAIProtocolError } from "../../utils/providers/openai/openai-backend-protocol";
73
75
  import {
74
76
  OPENAI_CALLBACK_PORTS,
75
77
  openAICallbackRedirectUri,
76
78
  startOpenAICallbackRelay,
77
79
  } from "../../utils/providers/openai/openai-callback-relay";
80
+ import {
81
+ decisionIssues,
82
+ fromOpenAIDecisionResult,
83
+ toOpenAIDecisionRequest,
84
+ } from "../../utils/providers/openai/openai-decisions";
78
85
  import { type OpenAIDispatcher } from "../../utils/providers/openai/openai-dispatcher";
79
86
  import {
80
87
  buildOpenAIAuthUrl,
@@ -130,6 +137,7 @@ import {
130
137
  beforeQuery,
131
138
  finishRunAborted,
132
139
  finishRunWithError,
140
+ maskDataUrls,
133
141
  runProgressRecorder,
134
142
  } from "./qgrid-run-lifecycle";
135
143
  import {
@@ -142,12 +150,15 @@ import {
142
150
  type QueryInput,
143
151
  type AppendStepInput,
144
152
  type CreateRunInput,
153
+ DecideInput,
154
+ type DecideOutput,
145
155
  type FinishRunInput,
146
156
  GenerateImagesInput,
147
157
  type GenerateImagesOutput,
148
158
  LiveCallInput,
149
159
  type LiveCallOutput,
150
160
  type LiveHistoryItem,
161
+ OpenAIDecisionRequest,
151
162
  SpeakInput,
152
163
  type SpeakOutput,
153
164
  TranscribeInput,
@@ -526,7 +537,7 @@ const inflightAnthropicRefresh = new Map<number, Promise<string>>();
526
537
 
527
538
  const mediaLogger = getLogger(["qgrid", "media"]);
528
539
 
529
- type MediaKind = "image" | "video" | "stt" | "tts" | "live";
540
+ type MediaKind = "image" | "video" | "stt" | "tts" | "live" | "decision";
530
541
 
531
542
  const MEDIA_TOOL_NAMES: Record<MediaKind, string> = {
532
543
  image: "image_generation",
@@ -534,6 +545,7 @@ const MEDIA_TOOL_NAMES: Record<MediaKind, string> = {
534
545
  stt: "transcription",
535
546
  tts: "speech",
536
547
  live: "live_session",
548
+ decision: "decision",
537
549
  };
538
550
 
539
551
  function grokNotReady(): Error {
@@ -596,11 +608,8 @@ class TooManyRequestsException extends SoException {
596
608
  }
597
609
  }
598
610
 
599
- /**
600
- * Every Grok token is cooling down. A 429 rather than a 503: the server error handler pins 503's
601
- * Retry-After to its startup interval, while this delay comes from the upstream cooldown.
602
- */
603
- function grokRateLimited(error: GrokRateLimitedError): TooManyRequestsException {
611
+ /** Sets `Retry-After` on the HTTP reply when its headers are still open. */
612
+ function setRetryAfter(retryAfterSec: number): void {
604
613
  let reply: FastifyReply | undefined;
605
614
 
606
615
  try {
@@ -612,11 +621,40 @@ function grokRateLimited(error: GrokRateLimitedError): TooManyRequestsException
612
621
  }
613
622
 
614
623
  // An SSE stream has already sent its headers; the error event then carries the delay alone.
615
- if (reply && !reply.raw.headersSent) reply.header("Retry-After", String(error.retryAfterSec));
624
+ if (reply && !reply.raw.headersSent) reply.header("Retry-After", String(retryAfterSec));
625
+ }
626
+
627
+ /**
628
+ * Every Grok token is cooling down. A 429 rather than a 503: the server error handler pins 503's
629
+ * Retry-After to its startup interval, while this delay comes from the upstream cooldown.
630
+ */
631
+ function grokRateLimited(error: GrokRateLimitedError): TooManyRequestsException {
632
+ setRetryAfter(error.retryAfterSec);
616
633
 
617
634
  return new TooManyRequestsException(SD("qgrid.grokRateLimited")(error.retryAfterSec));
618
635
  }
619
636
 
637
+ const DECISION_CALLER_FAULT_STATUSES = new Set([400, 413, 415, 422]);
638
+
639
+ /**
640
+ * OpenAI's verdict on a Decisions request qgrid could not pre-validate (an unreachable image URL,
641
+ * rejected content) answers 400, and its rate limit 429 with the upstream delay. Credential
642
+ * (401/403) and server failures stay upstream failures.
643
+ */
644
+ function decisionCallerError(cause: Error): Error {
645
+ if (!(cause instanceof OpenAIProtocolError) || cause.status === undefined) return cause;
646
+
647
+ if (cause.status === 429) {
648
+ if (cause.retryAfterMs !== undefined) setRetryAfter(Math.ceil(cause.retryAfterMs / 1000));
649
+
650
+ return new TooManyRequestsException(SD("qgrid.openaiRateLimited")(cause.message));
651
+ }
652
+
653
+ return DECISION_CALLER_FAULT_STATUSES.has(cause.status)
654
+ ? new BadRequestException(SD("qgrid.invalidInput")(cause.message))
655
+ : cause;
656
+ }
657
+
620
658
  /**
621
659
  * Caller-fault Grok errors become 400/429/503 at the chat and media boundaries; upstream and
622
660
  * provider failures propagate unchanged (500 by the server error handler). "No eligible token for
@@ -859,6 +897,13 @@ type MediaLogSuccess = {
859
897
  cost?: GrokMediaCost | VoiceCost;
860
898
  /** Speech only: time to the first audio byte, measured from the same start as `durationMs`. */
861
899
  ttftMs?: number;
900
+ /** Token-billed media (Decisions); other media keep zero token counts. */
901
+ usage?: Pick<
902
+ FinishRunParams,
903
+ "input_tokens" | "output_tokens" | "cache_read_tokens" | "cache_creation_tokens"
904
+ >;
905
+ /** A provider call that returned but failed for the caller (a Decisions refusal). */
906
+ errorMessage?: string;
862
907
  };
863
908
 
864
909
  // Voice rows embed browser-playable audio (TTS output in the response, STT input in the user
@@ -932,9 +977,14 @@ function mediaFinishFields(success: Omit<MediaLogSuccess, "steps">): FinishRunPa
932
977
  output_tokens: 0,
933
978
  cache_read_tokens: 0,
934
979
  cache_creation_tokens: 0,
980
+ ...success.usage,
935
981
  duration_ms: success.durationMs,
936
982
  ...(success.ttftMs !== undefined && { ttft_ms: success.ttftMs }),
937
983
  ...mediaCostFields(success.kind, success.model, success.cost),
984
+ ...(success.errorMessage !== undefined && {
985
+ status: "error",
986
+ error_message: success.errorMessage,
987
+ }),
938
988
  };
939
989
  }
940
990
 
@@ -2608,6 +2658,95 @@ class QgridFrameClass extends BaseFrameClass {
2608
2658
  });
2609
2659
  }
2610
2660
 
2661
+ /**
2662
+ * Decisions in the provider-neutral AI SDK shape; the OpenAI layer converts both ways. A refused
2663
+ * question still returns 200 with a refusal answer, and the run closes as error because AI SDK
2664
+ * fails the whole call.
2665
+ */
2666
+ @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })
2667
+ async decide(params: DecideInput): Promise<DecideOutput> {
2668
+ const input = parseMediaInput(DecideInput, params);
2669
+ // Provider limits (e.g. at least two choices) surface as 400 before any log or token use.
2670
+ const wire = OpenAIDecisionRequest.safeParse(toOpenAIDecisionRequest(input));
2671
+
2672
+ if (!wire.success) {
2673
+ throw new BadRequestException(
2674
+ SD("qgrid.invalidInput")(decisionIssues(wire.error, Object.keys(input.questions))),
2675
+ );
2676
+ }
2677
+
2678
+ const request = wire.data;
2679
+ const dispatcher = openaiVoice();
2680
+ const selection = await resolveMediaTokenSelection("openai", input.tokenName);
2681
+ const [onlyPart] = input.state;
2682
+
2683
+ const start = {
2684
+ kind: "decision",
2685
+ model: input.model,
2686
+ prompt:
2687
+ input.state.length === 1 && onlyPart?.type === "text"
2688
+ ? onlyPart.text
2689
+ : maskDataUrls(JSON.stringify(input.state)),
2690
+ systemPrompt: JSON.stringify(input.questions),
2691
+ projectName: input.projectName,
2692
+ logger: input.logger,
2693
+ } as const;
2694
+
2695
+ return runMediaEndpoint(start, async (signal, requestLogId) => {
2696
+ const dispatched = await dispatcher
2697
+ .decide({ ...request, signal, ...selection })
2698
+ .catch((error: Error) => {
2699
+ throw decisionCallerError(error);
2700
+ });
2701
+
2702
+ const { answers, usage } = fromOpenAIDecisionResult(input.questions, dispatched.result);
2703
+
2704
+ const output: DecideOutput = {
2705
+ model: input.model,
2706
+ answers,
2707
+ usage,
2708
+ tokenName: dispatched.tokenName,
2709
+ };
2710
+
2711
+ if (requestLogId !== undefined) output.requestLogId = requestLogId;
2712
+
2713
+ const answersJson = JSON.stringify(answers);
2714
+
2715
+ const refused = Object.entries(answers).flatMap(([id, answer]) =>
2716
+ answer.type === "refusal" ? [id] : [],
2717
+ );
2718
+
2719
+ const log: MediaRunLog = {
2720
+ tokenName: dispatched.tokenName,
2721
+ response: answersJson,
2722
+ cost: openaiDecisionCost(usage),
2723
+ usage: {
2724
+ input_tokens: usage.inputTokens,
2725
+ output_tokens: usage.outputTokens,
2726
+ cache_read_tokens: usage.cachedInputTokens,
2727
+ cache_creation_tokens: usage.cacheWriteTokens,
2728
+ },
2729
+ steps: [
2730
+ {
2731
+ toolCallId: "decision:0",
2732
+ // The questions exactly as OpenAI received them; the run's system prompt keeps ours.
2733
+ args: {
2734
+ kind: "decision",
2735
+ model: input.model,
2736
+ upstreamQuestions: JSON.stringify(request.questions),
2737
+ promptCacheKey: input.promptCacheKey,
2738
+ },
2739
+ result: answersJson,
2740
+ },
2741
+ ],
2742
+ };
2743
+
2744
+ if (refused.length > 0) log.errorMessage = `Decision refused: ${refused.join(", ")}`;
2745
+
2746
+ return { output, log };
2747
+ });
2748
+ }
2749
+
2611
2750
  // GPT-Live: exchanges the caller's WebRTC offer and returns the answer at once. The run stays
2612
2751
  // running for the whole session (up to two hours), its conversation rewritten after each turn;
2613
2752
  // a run left behind by a server restart is closed by the live stale sweep.
@@ -960,6 +960,248 @@ export const HealthResponse = z.object({
960
960
 
961
961
  export type HealthResponse = z.infer<typeof HealthResponse>;
962
962
 
963
+ // ─── Decisions (OpenAI native /v1/decisions wire format) ───
964
+ // Limits follow https://developers.openai.com/api/reference/resources/decisions/methods/create (2026-11-13).
965
+
966
+ export const OPENAI_DECISION_MODEL = "gpt-6-luna" as const;
967
+
968
+ const DECISION_IMAGE_DATA_URL = /^data:image\/(?:png|jpeg|webp|gif);base64,([A-Za-z0-9+/]*={0,2})$/;
969
+
970
+ function decisionInlineImageBytes(url: string): number {
971
+ const base64 = DECISION_IMAGE_DATA_URL.exec(url)?.[1];
972
+
973
+ return base64 === undefined ? 0 : base64DecodedBytes(base64);
974
+ }
975
+
976
+ // An http(s) URL (fetched by OpenAI, never by qgrid) or a well-formed base64 PNG/JPEG/WebP/GIF data
977
+ // URL within MEDIA_MAX_INLINE_BYTES. Strict base64 also keeps `maskDataUrls` matching it in logs.
978
+ const DecisionImageRef = z.string().superRefine((value, ctx) => {
979
+ if (/^https?:\/\//.test(value)) return;
980
+
981
+ const base64 = DECISION_IMAGE_DATA_URL.exec(value)?.[1];
982
+
983
+ if (base64 === undefined || base64.length === 0 || base64.length % 4 !== 0) {
984
+ ctx.addIssue({
985
+ code: "custom",
986
+ message: "Expected an HTTP(S) image URL or a base64 PNG/JPEG/WebP/GIF data URL",
987
+ });
988
+ } else if (base64DecodedBytes(base64) > MEDIA_MAX_INLINE_BYTES) {
989
+ ctx.addIssue({ code: "custom", message: `image data URL exceeds ${MEDIA_MAX_INLINE_LABEL}` });
990
+ }
991
+ });
992
+
993
+ const decisionInputPart = z.discriminatedUnion("type", [
994
+ z.object({ type: z.literal("input_text"), text: z.string() }),
995
+ z.object({
996
+ type: z.literal("input_json"),
997
+ data: z.union([z.record(z.string(), z.json()), z.array(z.record(z.string(), z.json())).min(1)]),
998
+ }),
999
+ z.object({
1000
+ type: z.literal("input_image"),
1001
+ image_url: DecisionImageRef,
1002
+ detail: z.enum(["low", "high", "auto", "original"]).optional(),
1003
+ }),
1004
+ ]);
1005
+
1006
+ // OpenAI rejects a question without instructions (live 2026-11-13: "Missing required parameter:
1007
+ // 'questions[0].instructions'"), even though @ai-sdk/openai sends it omitted. Boolean criteria
1008
+ // alone still work because they become the instructions.
1009
+ const decisionQuestionBase = {
1010
+ name: z.string().min(1),
1011
+ instructions: z.string().min(1, "OpenAI Decisions requires instructions for this question"),
1012
+ };
1013
+
1014
+ export const OpenAIDecisionQuestion = z.discriminatedUnion("type", [
1015
+ z.object({ type: z.literal("predicate"), ...decisionQuestionBase }),
1016
+ z.object({
1017
+ type: z.literal("choice"),
1018
+ ...decisionQuestionBase,
1019
+ choices: z
1020
+ .array(z.object({ value: z.string(), description: z.string().optional() }))
1021
+ .min(2)
1022
+ .max(255),
1023
+ }),
1024
+ z.object({
1025
+ type: z.literal("score"),
1026
+ ...decisionQuestionBase,
1027
+ levels: z
1028
+ .array(z.object({ label: z.string(), description: z.string().optional() }))
1029
+ .min(2)
1030
+ .max(10),
1031
+ }),
1032
+ ]);
1033
+
1034
+ export type OpenAIDecisionQuestion = z.infer<typeof OpenAIDecisionQuestion>;
1035
+
1036
+ export const OpenAIDecisionRequest = z.object({
1037
+ model: z.literal(OPENAI_DECISION_MODEL),
1038
+ input: z.union([
1039
+ z.string().min(1),
1040
+ z
1041
+ .array(z.object({ role: z.literal("user"), content: z.array(decisionInputPart).min(1) }))
1042
+ .min(1),
1043
+ ]),
1044
+ questions: z
1045
+ .array(OpenAIDecisionQuestion)
1046
+ .min(1)
1047
+ .max(400)
1048
+ .refine(
1049
+ (questions) => new Set(questions.map((q) => q.name)).size === questions.length,
1050
+ "Decision question names must be unique",
1051
+ ),
1052
+ prompt_cache_key: z.string().max(64).optional(),
1053
+ safety_identifier: z.string().max(128).optional(),
1054
+ });
1055
+
1056
+ export type OpenAIDecisionRequest = z.infer<typeof OpenAIDecisionRequest>;
1057
+
1058
+ const probability = z.number().min(0).max(1);
1059
+
1060
+ export const OpenAIDecisionAnswer = z.discriminatedUnion("type", [
1061
+ // qgrid names every question, so a refusal always names the question it declines.
1062
+ z.object({ type: z.literal("refusal"), name: z.string() }),
1063
+ z.object({ type: z.literal("predicate"), name: z.string(), probability }),
1064
+ z.object({
1065
+ type: z.literal("choice"),
1066
+ name: z.string(),
1067
+ choice: z.string(),
1068
+ probabilities: z.array(z.object({ value: z.string(), probability })),
1069
+ confidence: probability.nullish(),
1070
+ }),
1071
+ z.object({
1072
+ type: z.literal("score"),
1073
+ name: z.string(),
1074
+ score: z.number(),
1075
+ probabilities: z.array(z.object({ value: z.number().int().nonnegative(), probability })),
1076
+ confidence: probability.nullish(),
1077
+ }),
1078
+ ]);
1079
+
1080
+ export type OpenAIDecisionAnswer = z.infer<typeof OpenAIDecisionAnswer>;
1081
+
1082
+ const tokenCount = z.number().int().nonnegative();
1083
+
1084
+ /** `cached_tokens` and `cache_write_tokens` are already included in `input_tokens`. */
1085
+ export const OpenAIDecisionUsage = z.object({
1086
+ input_tokens: tokenCount,
1087
+ input_tokens_details: z
1088
+ .object({ cached_tokens: tokenCount.optional(), cache_write_tokens: tokenCount.optional() })
1089
+ .nullish(),
1090
+ output_tokens: tokenCount,
1091
+ total_tokens: tokenCount.optional(),
1092
+ });
1093
+
1094
+ export const OpenAIDecisionResult = z.object({
1095
+ model: z.string(),
1096
+ answers: z.array(OpenAIDecisionAnswer),
1097
+ // A missing or null usage must not fail a call that was already served.
1098
+ usage: OpenAIDecisionUsage.nullish(),
1099
+ });
1100
+
1101
+ export type OpenAIDecisionResult = z.infer<typeof OpenAIDecisionResult>;
1102
+
1103
+ // ─── Decisions (qgrid /decide, provider-neutral) ───
1104
+ // The AI SDK DecisionModelV4 call and result in JSON form. Provider layers convert to and from
1105
+ // their wire format (OpenAI: openai-decisions.ts).
1106
+
1107
+ export const DecisionModelId = z.enum([`openai/${OPENAI_DECISION_MODEL}`]);
1108
+
1109
+ /** Instructions and criteria descriptions: text, or JSON the provider serializes. */
1110
+ const DecisionContent = z.json();
1111
+
1112
+ export const DecisionStatePart = z.discriminatedUnion("type", [
1113
+ z.object({ type: z.literal("text"), text: z.string() }),
1114
+ z.object({ type: z.literal("json"), value: z.json() }),
1115
+ // HTTP(S) URL or base64 data URL; the SDK converts AI SDK file parts to this.
1116
+ z.object({ type: z.literal("image"), url: DecisionImageRef }),
1117
+ ]);
1118
+
1119
+ export const DecisionQuestion = z.discriminatedUnion("type", [
1120
+ z.object({
1121
+ type: z.literal("choice"),
1122
+ instructions: DecisionContent.nullish(),
1123
+ criteria: z.record(z.string(), DecisionContent.nullable()),
1124
+ }),
1125
+ z.object({
1126
+ type: z.literal("score"),
1127
+ instructions: DecisionContent.nullish(),
1128
+ criteria: z.array(DecisionContent.nullable()).min(1),
1129
+ }),
1130
+ z.object({
1131
+ type: z.literal("boolean"),
1132
+ instructions: DecisionContent.nullish(),
1133
+ criteria: z
1134
+ .object({ true: DecisionContent.nullish(), false: DecisionContent.nullish() })
1135
+ .nullish(),
1136
+ }),
1137
+ ]);
1138
+
1139
+ export type DecisionQuestion = z.infer<typeof DecisionQuestion>;
1140
+
1141
+ export const DecideInput = z.object({
1142
+ model: DecisionModelId,
1143
+ state: z
1144
+ .array(DecisionStatePart)
1145
+ .min(1)
1146
+ .refine(
1147
+ (parts) =>
1148
+ parts.reduce(
1149
+ (total, part) => total + (part.type === "image" ? decisionInlineImageBytes(part.url) : 0),
1150
+ 0,
1151
+ ) <= MEDIA_MAX_INLINE_BYTES,
1152
+ INLINE_IMAGES_TOTAL_MESSAGE,
1153
+ ),
1154
+ /** Keyed by question ID; answers come back under the same IDs. */
1155
+ questions: z
1156
+ .record(z.string().min(1), DecisionQuestion)
1157
+ .refine((questions) => Object.keys(questions).length > 0, "questions must not be empty"),
1158
+ // OpenAI only: prompt cache routing key and end-user identifier.
1159
+ promptCacheKey: z.string().max(64).optional(),
1160
+ safetyIdentifier: z.string().max(128).optional(),
1161
+ ...MediaCallOptions,
1162
+ });
1163
+
1164
+ export type DecideInput = z.infer<typeof DecideInput>;
1165
+
1166
+ const decisionProbabilities = z.record(z.string(), probability);
1167
+
1168
+ export const DecisionAnswer = z.discriminatedUnion("type", [
1169
+ z.object({
1170
+ type: z.literal("choice"),
1171
+ choice: z.string(),
1172
+ probabilities: decisionProbabilities.optional(),
1173
+ confidence: probability.optional(),
1174
+ }),
1175
+ z.object({
1176
+ type: z.literal("score"),
1177
+ score: z.number(),
1178
+ /** Keyed by zero-based level index as a string. */
1179
+ probabilities: decisionProbabilities.optional(),
1180
+ confidence: probability.optional(),
1181
+ }),
1182
+ z.object({ type: z.literal("boolean"), probability }),
1183
+ z.object({ type: z.literal("refusal") }),
1184
+ ]);
1185
+
1186
+ export type DecisionAnswer = z.infer<typeof DecisionAnswer>;
1187
+
1188
+ export const DecideOutput = z.object({
1189
+ model: DecisionModelId,
1190
+ answers: z.record(z.string(), DecisionAnswer),
1191
+ usage: z.object({
1192
+ inputTokens: tokenCount,
1193
+ outputTokens: tokenCount,
1194
+ /** Included in inputTokens. */
1195
+ cachedInputTokens: tokenCount,
1196
+ /** Included in inputTokens. */
1197
+ cacheWriteTokens: tokenCount,
1198
+ }),
1199
+ tokenName: z.string(),
1200
+ requestLogId: z.number().optional(),
1201
+ });
1202
+
1203
+ export type DecideOutput = z.infer<typeof DecideOutput>;
1204
+
963
1205
  // ─── Errors ───
964
1206
 
965
1207
  export class QuotaError extends Error {
@@ -226,7 +226,7 @@
226
226
  "type": "enum",
227
227
  "id": "RequestLogMediaKind",
228
228
  "nullable": true,
229
- "desc": "미디어 엔드포인트 종류(image/video/stt/tts/live). 텍스트 요청은 null (목록 Fmt 표시용)"
229
+ "desc": "미디어 엔드포인트 종류(image/video/stt/tts/live/decision). 텍스트 요청은 null (목록 Fmt 표시용)"
230
230
  }
231
231
  ],
232
232
  "indexes": [
@@ -401,7 +401,8 @@
401
401
  "video": "비디오",
402
402
  "stt": "음성 인식",
403
403
  "tts": "음성 합성",
404
- "live": "실시간 대화"
404
+ "live": "실시간 대화",
405
+ "decision": "판정"
405
406
  }
406
407
  }
407
408
  }
@@ -733,6 +733,37 @@ Content-Type: application/json
733
733
 
734
734
  ###
735
735
 
736
+ POST {{baseUrl}}/api/qgrid/decide
737
+ Content-Type: application/json
738
+
739
+ {
740
+ "params": {
741
+ "model": "openai/gpt-6-luna",
742
+ "state": [
743
+ {
744
+ "type": "text",
745
+ "text": "TEXT"
746
+ }
747
+ ],
748
+ "questions": {
749
+ "QUESTIONS": {
750
+ "type": "choice",
751
+ "instructions": null,
752
+ "criteria": {
753
+ "CRITERIA": null
754
+ }
755
+ }
756
+ },
757
+ "promptCacheKey": "PROMPTCACHEKEY",
758
+ "safetyIdentifier": "SAFETYIDENTIFIER",
759
+ "tokenName": "TOKENNAME",
760
+ "projectName": "PROJECTNAME",
761
+ "logger": false
762
+ }
763
+ }
764
+
765
+ ###
766
+
736
767
  POST {{baseUrl}}/api/qgrid/liveCall
737
768
  Content-Type: application/json
738
769
 
@@ -140,7 +140,7 @@ export const RequestLogStatusLabel = {
140
140
  aborted: "중단",
141
141
  };
142
142
  export const RequestLogMediaKind = z
143
- .enum(["image", "video", "stt", "tts", "live"])
143
+ .enum(["image", "video", "stt", "tts", "live", "decision"])
144
144
  .describe("RequestLogMediaKind");
145
145
  export type RequestLogMediaKind = z.infer<typeof RequestLogMediaKind>;
146
146
  export const RequestLogMediaKindLabel = {
@@ -149,6 +149,7 @@ export const RequestLogMediaKindLabel = {
149
149
  stt: "음성 인식",
150
150
  tts: "음성 합성",
151
151
  live: "실시간 대화",
152
+ decision: "판정",
152
153
  };
153
154
 
154
155
  // Enums: RequestLogStep
@@ -64,6 +64,7 @@ export default {
64
64
  "qgrid.grokNoWorkers": (detail: string) => `No Grok token is available: ${detail}`,
65
65
  "qgrid.grokRateLimited": (retryAfterSec: number) =>
66
66
  `All Grok tokens are rate limited. Retry after ${retryAfterSec} seconds`,
67
+ "qgrid.openaiRateLimited": (detail: string) => `OpenAI rate limit reached: ${detail}`,
67
68
  "qgrid.grokOnDemandExcluded": (tokens: string) =>
68
69
  `All Grok tokens are excluded because on-demand billing is enabled at xAI: ${tokens}. Turn off on-demand billing, or add another account`,
69
70
  "qgrid.grokZdrVideoUnavailable": (tokens: string) =>
@@ -65,6 +65,7 @@ export default {
65
65
  "qgrid.grokNoWorkers": (detail: string) => `사용 가능한 Grok 토큰이 없습니다: ${detail}`,
66
66
  "qgrid.grokRateLimited": (retryAfterSec: number) =>
67
67
  `모든 Grok 토큰이 요청 한도에 걸렸습니다. ${retryAfterSec}초 후 다시 시도해주세요`,
68
+ "qgrid.openaiRateLimited": (detail: string) => `OpenAI 요청 한도에 걸렸습니다: ${detail}`,
68
69
  "qgrid.grokOnDemandExcluded": (tokens: string) =>
69
70
  `xAI에서 on-demand 과금이 켜져 있어 모든 Grok 토큰이 제외되었습니다: ${tokens}. on-demand 과금을 끄거나 다른 계정을 추가해주세요`,
70
71
  "qgrid.grokZdrVideoUnavailable": (tokens: string) =>
@@ -251,7 +251,7 @@ const entityLabels = {
251
251
  "entity.RequestLog.is_image_generation": "이미지 생성 turn 여부 (quota 귀속용)",
252
252
  "entity.RequestLog.is_structured": "structured output(jsonSchema) 요청 여부 (목록 구분 표시용)",
253
253
  "entity.RequestLog.media_kind":
254
- "미디어 엔드포인트 종류(image/video/stt/tts/live). 텍스트 요청은 null (목록 Fmt 표시용)",
254
+ "미디어 엔드포인트 종류(image/video/stt/tts/live/decision). 텍스트 요청은 null (목록 Fmt 표시용)",
255
255
  "enum.RequestLogOrderBy.id-desc": "ID최신순",
256
256
  "enum.RequestLogOrderBy.id-asc": "ID오래된순",
257
257
  "enum.RequestLogOrderBy.created_at-desc": "등록일시최신순",
@@ -282,6 +282,7 @@ const entityLabels = {
282
282
  "enum.RequestLogMediaKind.stt": "음성 인식",
283
283
  "enum.RequestLogMediaKind.tts": "음성 합성",
284
284
  "enum.RequestLogMediaKind.live": "실시간 대화",
285
+ "enum.RequestLogMediaKind.decision": "판정",
285
286
  "entity.RequestLogStep": "RequestLogStep",
286
287
  "entity.RequestLogStep.id": "ID",
287
288
  "entity.RequestLogStep.created_at": "등록일시",
@@ -501,6 +501,26 @@ export function openaiSpeechCost(
501
501
  );
502
502
  }
503
503
 
504
+ /**
505
+ * Native Decisions on gpt-6-luna: Luna's input and cached-input rates; output is not charged
506
+ * (https://developers.openai.com/api/docs/guides/decisions, 2026-11-13). Cache writes use Luna's
507
+ * table rate, which the Decisions pages do not confirm.
508
+ */
509
+ export function openaiDecisionCost(usage: {
510
+ inputTokens: number;
511
+ cachedInputTokens: number;
512
+ cacheWriteTokens: number;
513
+ }): VoiceCost {
514
+ return priced(
515
+ calculateCostUsd("gpt-6-luna", {
516
+ inputTokens: usage.inputTokens,
517
+ outputTokens: 0,
518
+ cachedInputTokens: usage.cachedInputTokens,
519
+ cacheCreationInputTokens: usage.cacheWriteTokens,
520
+ }),
521
+ );
522
+ }
523
+
504
524
  /** Transcription by audio length; unknown models or a missing duration stay unpriced. */
505
525
  export function sttCost(route: string, durationSec: number | undefined): VoiceCost | undefined {
506
526
  const perMinute = STT_USD_PER_MINUTE.get(route);
@@ -224,6 +224,11 @@ export class OpenAIProtocolError extends Error {
224
224
  }
225
225
  }
226
226
 
227
+ /** A rejected access token: the token pool refreshes the credentials and retries once. */
228
+ export function isOpenAIUnauthorizedError(error: Error): boolean {
229
+ return error instanceof OpenAIProtocolError && error.status === 401;
230
+ }
231
+
227
232
  const tokenCount = z.coerce.number().catch(0);
228
233
 
229
234
  function jsonObjectOrEmpty(value: JsonValue | undefined): JsonObject {