@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
@@ -1,4 +1,4 @@
1
- import { $ as __exportAll, A as unknown, B as hashKey, C as looseObject, D as string$2, E as object, F as onlineManager, G as partialMatchKey, H as matchMutation, I as notifyManager, J as QueryClientProvider, K as resolveQueryValue, L as focusManager, N as Mutation, O as tuple, P as Query, Q as __commonJSMin, R as Subscribable, S as literal, T as number$1, U as matchQuery, V as hashQueryKeyByOptions, W as noop, X as require_jsx_runtime, Z as require_react, _ as custom, b as int, c as fetch$1, d as SD, et as __require, f as SUPPORTED_LOCALES, g as boolean$1, h as array, k as union, m as _enum, n as QgridService, o as TokenService, p as setLocale, q as skipToken, s as SonamuQueryMode, tt as __toESM, u as zArrayable, v as date, w as never, x as json, y as discriminatedUnion, z as functionalUpdate$1 } from "./assets/services.generated-C3b31_vt.js";
1
+ import { $ as __commonJSMin, A as union, B as functionalUpdate$1, C as looseObject, D as record, E as object, F as Query, G as noop, H as hashQueryKeyByOptions, I as onlineManager, J as skipToken, K as partialMatchKey, L as notifyManager, O as string$2, P as Mutation, Q as require_react, R as focusManager, S as literal, T as number$1, U as matchMutation, V as hashKey, W as matchQuery, Y as QueryClientProvider, Z as require_jsx_runtime, _ as custom, b as int, c as fetch$1, d as SD, et as __exportAll, f as SUPPORTED_LOCALES, g as boolean$1, h as array, j as unknown, k as tuple, m as _enum, n as QgridService, nt as __toESM, o as TokenService, p as setLocale, q as resolveQueryValue, s as SonamuQueryMode, tt as __require, u as zArrayable, v as date, w as never, x as json, y as discriminatedUnion, z as Subscribable } from "./assets/services.generated-D0995hJr.js";
2
2
  import minpath from "node:path";
3
3
  import minproc from "node:process";
4
4
  import { fileURLToPath as urlToPath } from "node:url";
@@ -52986,6 +52986,209 @@ object({
52986
52986
  grok: ProviderStartupState.optional()
52987
52987
  })
52988
52988
  });
52989
+ var OPENAI_DECISION_MODEL = "gpt-6-luna";
52990
+ var DECISION_IMAGE_DATA_URL = /^data:image\/(?:png|jpeg|webp|gif);base64,([A-Za-z0-9+/]*={0,2})$/;
52991
+ function decisionInlineImageBytes(url) {
52992
+ const base64 = DECISION_IMAGE_DATA_URL.exec(url)?.[1];
52993
+ return base64 === void 0 ? 0 : base64DecodedBytes(base64);
52994
+ }
52995
+ var DecisionImageRef = string$2().superRefine((value, ctx) => {
52996
+ if (/^https?:\/\//.test(value)) return;
52997
+ const base64 = DECISION_IMAGE_DATA_URL.exec(value)?.[1];
52998
+ if (base64 === void 0 || base64.length === 0 || base64.length % 4 !== 0) ctx.addIssue({
52999
+ code: "custom",
53000
+ message: "Expected an HTTP(S) image URL or a base64 PNG/JPEG/WebP/GIF data URL"
53001
+ });
53002
+ else if (base64DecodedBytes(base64) > 19922944) ctx.addIssue({
53003
+ code: "custom",
53004
+ message: `image data URL exceeds ${MEDIA_MAX_INLINE_LABEL}`
53005
+ });
53006
+ });
53007
+ var decisionInputPart = discriminatedUnion("type", [
53008
+ object({
53009
+ type: literal("input_text"),
53010
+ text: string$2()
53011
+ }),
53012
+ object({
53013
+ type: literal("input_json"),
53014
+ data: union([record(string$2(), json()), array(record(string$2(), json())).min(1)])
53015
+ }),
53016
+ object({
53017
+ type: literal("input_image"),
53018
+ image_url: DecisionImageRef,
53019
+ detail: _enum([
53020
+ "low",
53021
+ "high",
53022
+ "auto",
53023
+ "original"
53024
+ ]).optional()
53025
+ })
53026
+ ]);
53027
+ var decisionQuestionBase = {
53028
+ name: string$2().min(1),
53029
+ instructions: string$2().min(1, "OpenAI Decisions requires instructions for this question")
53030
+ };
53031
+ var OpenAIDecisionQuestion = discriminatedUnion("type", [
53032
+ object({
53033
+ type: literal("predicate"),
53034
+ ...decisionQuestionBase
53035
+ }),
53036
+ object({
53037
+ type: literal("choice"),
53038
+ ...decisionQuestionBase,
53039
+ choices: array(object({
53040
+ value: string$2(),
53041
+ description: string$2().optional()
53042
+ })).min(2).max(255)
53043
+ }),
53044
+ object({
53045
+ type: literal("score"),
53046
+ ...decisionQuestionBase,
53047
+ levels: array(object({
53048
+ label: string$2(),
53049
+ description: string$2().optional()
53050
+ })).min(2).max(10)
53051
+ })
53052
+ ]);
53053
+ object({
53054
+ model: literal(OPENAI_DECISION_MODEL),
53055
+ input: union([string$2().min(1), array(object({
53056
+ role: literal("user"),
53057
+ content: array(decisionInputPart).min(1)
53058
+ })).min(1)]),
53059
+ questions: array(OpenAIDecisionQuestion).min(1).max(400).refine((questions) => new Set(questions.map((q) => q.name)).size === questions.length, "Decision question names must be unique"),
53060
+ prompt_cache_key: string$2().max(64).optional(),
53061
+ safety_identifier: string$2().max(128).optional()
53062
+ });
53063
+ var probability = number$1().min(0).max(1);
53064
+ var OpenAIDecisionAnswer = discriminatedUnion("type", [
53065
+ object({
53066
+ type: literal("refusal"),
53067
+ name: string$2()
53068
+ }),
53069
+ object({
53070
+ type: literal("predicate"),
53071
+ name: string$2(),
53072
+ probability
53073
+ }),
53074
+ object({
53075
+ type: literal("choice"),
53076
+ name: string$2(),
53077
+ choice: string$2(),
53078
+ probabilities: array(object({
53079
+ value: string$2(),
53080
+ probability
53081
+ })),
53082
+ confidence: probability.nullish()
53083
+ }),
53084
+ object({
53085
+ type: literal("score"),
53086
+ name: string$2(),
53087
+ score: number$1(),
53088
+ probabilities: array(object({
53089
+ value: number$1().int().nonnegative(),
53090
+ probability
53091
+ })),
53092
+ confidence: probability.nullish()
53093
+ })
53094
+ ]);
53095
+ var tokenCount = number$1().int().nonnegative();
53096
+ /** `cached_tokens` and `cache_write_tokens` are already included in `input_tokens`. */
53097
+ var OpenAIDecisionUsage = object({
53098
+ input_tokens: tokenCount,
53099
+ input_tokens_details: object({
53100
+ cached_tokens: tokenCount.optional(),
53101
+ cache_write_tokens: tokenCount.optional()
53102
+ }).nullish(),
53103
+ output_tokens: tokenCount,
53104
+ total_tokens: tokenCount.optional()
53105
+ });
53106
+ object({
53107
+ model: string$2(),
53108
+ answers: array(OpenAIDecisionAnswer),
53109
+ usage: OpenAIDecisionUsage.nullish()
53110
+ });
53111
+ var DecisionModelId = _enum([`openai/${OPENAI_DECISION_MODEL}`]);
53112
+ /** Instructions and criteria descriptions: text, or JSON the provider serializes. */
53113
+ var DecisionContent = json();
53114
+ var DecisionStatePart = discriminatedUnion("type", [
53115
+ object({
53116
+ type: literal("text"),
53117
+ text: string$2()
53118
+ }),
53119
+ object({
53120
+ type: literal("json"),
53121
+ value: json()
53122
+ }),
53123
+ object({
53124
+ type: literal("image"),
53125
+ url: DecisionImageRef
53126
+ })
53127
+ ]);
53128
+ var DecisionQuestion = discriminatedUnion("type", [
53129
+ object({
53130
+ type: literal("choice"),
53131
+ instructions: DecisionContent.nullish(),
53132
+ criteria: record(string$2(), DecisionContent.nullable())
53133
+ }),
53134
+ object({
53135
+ type: literal("score"),
53136
+ instructions: DecisionContent.nullish(),
53137
+ criteria: array(DecisionContent.nullable()).min(1)
53138
+ }),
53139
+ object({
53140
+ type: literal("boolean"),
53141
+ instructions: DecisionContent.nullish(),
53142
+ criteria: object({
53143
+ true: DecisionContent.nullish(),
53144
+ false: DecisionContent.nullish()
53145
+ }).nullish()
53146
+ })
53147
+ ]);
53148
+ object({
53149
+ model: DecisionModelId,
53150
+ state: array(DecisionStatePart).min(1).refine((parts) => parts.reduce((total, part) => total + (part.type === "image" ? decisionInlineImageBytes(part.url) : 0), 0) <= MEDIA_MAX_INLINE_BYTES, INLINE_IMAGES_TOTAL_MESSAGE),
53151
+ /** Keyed by question ID; answers come back under the same IDs. */
53152
+ questions: record(string$2().min(1), DecisionQuestion).refine((questions) => Object.keys(questions).length > 0, "questions must not be empty"),
53153
+ promptCacheKey: string$2().max(64).optional(),
53154
+ safetyIdentifier: string$2().max(128).optional(),
53155
+ ...MediaCallOptions
53156
+ });
53157
+ var decisionProbabilities = record(string$2(), probability);
53158
+ var DecisionAnswer = discriminatedUnion("type", [
53159
+ object({
53160
+ type: literal("choice"),
53161
+ choice: string$2(),
53162
+ probabilities: decisionProbabilities.optional(),
53163
+ confidence: probability.optional()
53164
+ }),
53165
+ object({
53166
+ type: literal("score"),
53167
+ score: number$1(),
53168
+ /** Keyed by zero-based level index as a string. */
53169
+ probabilities: decisionProbabilities.optional(),
53170
+ confidence: probability.optional()
53171
+ }),
53172
+ object({
53173
+ type: literal("boolean"),
53174
+ probability
53175
+ }),
53176
+ object({ type: literal("refusal") })
53177
+ ]);
53178
+ object({
53179
+ model: DecisionModelId,
53180
+ answers: record(string$2(), DecisionAnswer),
53181
+ usage: object({
53182
+ inputTokens: tokenCount,
53183
+ outputTokens: tokenCount,
53184
+ /** Included in inputTokens. */
53185
+ cachedInputTokens: tokenCount,
53186
+ /** Included in inputTokens. */
53187
+ cacheWriteTokens: tokenCount
53188
+ }),
53189
+ tokenName: string$2(),
53190
+ requestLogId: number$1().optional()
53191
+ });
52989
53192
  //#endregion
52990
53193
  //#region src/components/qgrid/chat-image-generation.ts
52991
53194
  function buildChatHistory(messages, includeImages) {
@@ -53770,7 +53973,7 @@ function ChatWidget() {
53770
53973
  }
53771
53974
  //#endregion
53772
53975
  //#region src/components/Sidebar.tsx
53773
- var qgridVersion = "2.20.0";
53976
+ var qgridVersion = "2.22.0";
53774
53977
  function Sidebar({ className }) {
53775
53978
  const pathname = useRouterState({ select: (s) => s.location.pathname });
53776
53979
  const { tab: currentTab = "tts" } = useSearch({ strict: false });
@@ -55986,7 +56189,7 @@ function RootComponent() {
55986
56189
  }
55987
56190
  //#endregion
55988
56191
  //#region src/routes/index.tsx
55989
- var $$splitComponentImporter$6 = () => import("./assets/routes-W-pd1Hps.js");
56192
+ var $$splitComponentImporter$6 = () => import("./assets/routes-B6be8sJP.js");
55990
56193
  var Route$6 = createFileRoute("/")({ component: lazyRouteComponent($$splitComponentImporter$6, "component") });
55991
56194
  //#endregion
55992
56195
  //#region src/services/sonamu.generated.ts
@@ -56080,7 +56283,8 @@ var RequestLogMediaKind = _enum([
56080
56283
  "video",
56081
56284
  "stt",
56082
56285
  "tts",
56083
- "live"
56286
+ "live",
56287
+ "decision"
56084
56288
  ]).describe("RequestLogMediaKind");
56085
56289
  var RequestLogStepType = _enum(["generate", "tool_call"]).describe("RequestLogStepType");
56086
56290
  var RequestLogStepOrderBy = _enum(["id-asc"]).describe("RequestLogStepOrderBy");
@@ -56392,7 +56596,7 @@ object({
56392
56596
  _enum(["A"]);
56393
56597
  //#endregion
56394
56598
  //#region src/routes/logs.tsx
56395
- var $$splitComponentImporter$5 = () => import("./assets/logs-CxAwuDKc.js");
56599
+ var $$splitComponentImporter$5 = () => import("./assets/logs-CFa_xamY.js");
56396
56600
  var logsSearchSchema = object({
56397
56601
  token: string$2().optional(),
56398
56602
  project: string$2().optional(),
@@ -56408,7 +56612,7 @@ var Route$5 = createFileRoute("/logs")({
56408
56612
  });
56409
56613
  //#endregion
56410
56614
  //#region src/routes/monit.tsx
56411
- var $$splitComponentImporter$4 = () => import("./assets/monit-Bl2kSkSF.js");
56615
+ var $$splitComponentImporter$4 = () => import("./assets/monit-BF6osfj5.js");
56412
56616
  var monitSearchSchema = object({ level: _enum([
56413
56617
  "all",
56414
56618
  "warn",
@@ -56420,15 +56624,15 @@ var Route$4 = createFileRoute("/monit")({
56420
56624
  });
56421
56625
  //#endregion
56422
56626
  //#region src/routes/settings.tsx
56423
- var $$splitComponentImporter$3 = () => import("./assets/settings-CFdTg1_f.js");
56627
+ var $$splitComponentImporter$3 = () => import("./assets/settings-DAle7AgI.js");
56424
56628
  var Route$3 = createFileRoute("/settings")({ component: lazyRouteComponent($$splitComponentImporter$3, "component") });
56425
56629
  //#endregion
56426
56630
  //#region src/routes/tokens.tsx
56427
- var $$splitComponentImporter$2 = () => import("./assets/tokens-BO1hyBuB.js");
56631
+ var $$splitComponentImporter$2 = () => import("./assets/tokens-Bc9flfLz.js");
56428
56632
  var Route$2 = createFileRoute("/tokens")({ component: lazyRouteComponent($$splitComponentImporter$2, "component") });
56429
56633
  //#endregion
56430
56634
  //#region src/routes/voice.tsx
56431
- var $$splitComponentImporter$1 = () => import("./assets/voice-BCF-Pkzo.js");
56635
+ var $$splitComponentImporter$1 = () => import("./assets/voice-CEQT57xZ.js");
56432
56636
  var voiceSearchSchema = object({ tab: _enum(VOICE_TAB_IDS).optional() });
56433
56637
  var Route$1 = createFileRoute("/voice")({
56434
56638
  validateSearch: voiceSearchSchema,
@@ -56436,7 +56640,7 @@ var Route$1 = createFileRoute("/voice")({
56436
56640
  });
56437
56641
  //#endregion
56438
56642
  //#region src/routes/requests/show.tsx
56439
- var $$splitComponentImporter = () => import("./assets/show-DVEIHsXh.js");
56643
+ var $$splitComponentImporter = () => import("./assets/show-BTSdMDoM.js");
56440
56644
  var showSearchSchema = object({ id: number$1() });
56441
56645
  var Route = createFileRoute("/requests/show")({
56442
56646
  validateSearch: showSearchSchema,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cartanova/qgrid-cli",
3
- "version": "2.20.0",
3
+ "version": "2.22.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/cartanova-ai/qgrid"
@@ -265,6 +265,16 @@ For external providers, the logger reads AI SDK's provider-neutral `onStart.outp
265
265
 
266
266
  Grok speech passes the standard `speed` through as `@ai-sdk/xai` does (2.18.0+; the server enforces 0.7-1.5). Speech timing: `qgrid.speech("grok/...")` honors one `providerOptions.xai` key, `withTimestamps` (2.16.0+); `providerOptions.qgrid.withTimestamps` (2.17.0+) works for both `grok/` and `openai/` speech and is read straight from the namespace because the qgrid option parsers drop unknown keys. Every other `xai` key still warns. Timing comes back in `providerMetadata.qgrid.audioTimestamps` (`graphChars`, `graphTimes` `[start, end]` seconds, index-aligned) plus `duration` and `timestampsSource` (`provider` for Grok, `aligned` for OpenAI); the field names match `@ai-sdk/xai`'s `providerMetadata.xai`. A failed timing step returns the audio with `timestampsError` and an `other` warning. Grok transcription maps the server's `words` to AI SDK `segments` (`startSecond`/`endSecond`, 2.17.0+); OpenAI transcription segments stay empty.
267
267
 
268
- Voice ids (2.20.0+): `src/voices.ts` (no imports, exported from the main and `/realtime` entries) holds `QGRID_GROK_VOICES` (`{ female, male }`), `QGRID_OPENAI_SPEECH_VOICES` and `QGRID_LIVE_VOICES` with types `QgridGrokVoice`, `QgridOpenAISpeechVoice`, `QgridLiveVoice`, default first. AI SDK types `voice` as `string`, so these are for pickers and `satisfies` checks. The server's lists in `qgrid.types.ts` (`GROK_TTS_VOICES`, `OPENAI_SPEECH_VOICES`, `OPENAI_LIVE_VOICES`, synced to the dashboard, which reads them instead of keeping its own) are the source; `voices.test.ts` fails when the SDK copy drifts.
268
+ Voice ids (2.20.0+): `src/voices.ts` (no imports, exported from the main and `/realtime` entries, and since 2.21.0 its own `@cartanova/qgrid-ai-sdk/voices` entry for browser and React Native code that must not load the SDK's Node-only code or peers; `voices.test.ts` keeps it import-free) holds `QGRID_GROK_VOICES` (`{ female, male }`), `QGRID_OPENAI_SPEECH_VOICES` and `QGRID_LIVE_VOICES` with types `QgridGrokVoice`, `QgridOpenAISpeechVoice`, `QgridLiveVoice`, default first. AI SDK types `voice` as `string`, so these are for pickers and `satisfies` checks. The server's lists in `qgrid.types.ts` (`GROK_TTS_VOICES`, `OPENAI_SPEECH_VOICES`, `OPENAI_LIVE_VOICES`, synced to the dashboard, which reads them instead of keeping its own) are the source; `voices.test.ts` fails when the SDK copy drifts.
269
269
 
270
270
  Realtime (2.20.0+, SON-595): `qgrid.realtime("openai/gpt-live-1")` (and `createQgridRealtime` from the browser-safe `@cartanova/qgrid-ai-sdk/realtime` entry, `src/realtime.ts`, a second tsdown entry that must never import `http-transport.ts`/`image-model.ts` because they pull in undici) implements AI SDK `Experimental_RealtimeModelV4` for GPT-Live over WebRTC only (`capabilities`: continuous, `transports`/`connections` `webrtc`, `startup: "session-start"`, `finalization: "session-close"`; peer minimums `ai` 7.0.102 and `@ai-sdk/provider` 4.0.15, where WebRTC landed). The browser runtime (`experimental_useRealtime` / `Experimental_AbstractRealtimeSession`) posts `{ sdp, sessionConfig }` to the app's `api.session` route; the route calls `doCreateWebRTCSession`, which POSTs `liveCall` with plain `fetch` (`voice`/`instructions` from `sessionConfig`, `delegation`/`history`/`tokenName`/`logger` from `sessionConfig.providerOptions.qgrid`, which the route must build server-side) and returns `{ sessionId: callId, sdp, requestLogId }`. The data channel speaks the Codex frameless protocol, not the public API's `session.*` names that `@ai-sdk/openai`'s `OpenAIRealtimeModelLive` maps: a per-connection parser (it keeps only the last usage) maps `session.started` → `session-started` without `delegationMode` (the ai 7.0.148 runtime throws on `"provider"`, and `"client"` would tell the app to answer delegations qgrid already answers), `input_transcript.added`/`output_transcript.added` → `transcript-fragment` (speaker from the event type, `item.text`, top-level `start_ms`/`end_ms`; `turn.delta` is not used because each turn's first word appears only in `turn.created`, seen live 2026-11-10), `delegation.created` → `delegation-created` (`target: "provider"`, `offsetMs` from `offset_ms`), `session.usage.updated`/`session.closed` → seconds from `usage.audio_duration_ms` (close falls back to the last usage), `error` → `error`, everything else → `custom`. Client events: `session-close` → `session.close`; `context-append` → `session.context.append` or `delegation.context.append` with `content: [{ type: "input_text", text }]`; the rest throw `UnsupportedFunctionalityError`. Codex lists `input_audio.pause`/`input_audio.resume` (mute) but their acknowledgement events are unknown, and the runtime flips `isInputMuted` only on an acknowledgement, so mute is out of v1. Verified 2026-11-10 with `Experimental_AbstractRealtimeSession` in a browser (harness: the SON-595 issue): the data channel carries `session.started`, `turn.*`, `*_transcript.added`, `delegation.created`, `session.usage.updated` and, about 0.6 s after `session.close`, `session.closed` with usage, so `close()` ends `disconnected` with finalization `confirmed`. In the first two delegated sessions `session.close` was not honored (no `session.closed` on the data channel or the sideband; the data channel errored about 3 s later and the session ended by peer teardown within about 5 s, so the client saw `error`); it did not recur in seven later runs (direct and through qgrid, with, without and during a pending delegation). If it returns, compare against a direct `/calls` session before changing the SDK.
271
+
272
+ ## Decisions (2.22.0+)
273
+
274
+ `qgrid.decision("openai/gpt-6-luna")` (`src/decision-model.ts`) implements AI SDK `Experimental_DecisionModelV4` for `experimental_decide`, with `supportedQuestionTypes` `choice`, `score`, `boolean` (no `box`). Peer minimums are `ai` 7.0.148 and `@ai-sdk/provider` 4.0.31, where the current spec landed (ordered state parts, refusal answers, `maxOutputTokens`/`reasoning` call options). AI SDK marks the spec experimental and changed it in patch releases (4.0.22 renamed evaluate to decide, 4.0.25 changed state), so recheck `doDecide` types when raising the peer range.
275
+
276
+ - Request: `doDecide` posts the provider-neutral `DecideInput` to `/api/qgrid/decide`: AI SDK state parts (`text`, `json`; file parts become `{ type: "image", url }`, bytes as a data URL for PNG/JPEG/WebP/GIF or an http(s) URL; other files throw `UnsupportedFunctionalityError` before any request) and the questions keyed by ID as JSON. The server converts to OpenAI's wire format (below), so the SDK does not know OpenAI's shape.
277
+ - Options: `providerOptions.openai` honors `promptCacheKey` and `safetyIdentifier` (the `@ai-sdk/openai` decision options); other keys, `maxOutputTokens`, and `reasoning` warn. `providerOptions.qgrid` takes `tokenName` (`openai/` prefix) and `logger`.
278
+ - Result: answers keyed by question ID; `confidence` moves from each choice/score answer to `providerMetadata.qgrid.confidence`, next to `tokenName`, `requestLogId`, `cachedInputTokens`, `cacheWriteTokens`. `rounding: { probabilityDecimals: 2, scoreDecimals: 2 }` as `@ai-sdk/openai` declares, because OpenAI rounds and AI SDK otherwise rejects a distribution summing to 0.99. A refusal answer is passed through; AI SDK core throws `Experimental_DecisionRefusalError`.
279
+ - Server conversion (`openai-decisions.ts` `toOpenAIDecisionRequest`/`fromOpenAIDecisionResult`) follows `@ai-sdk/openai` 4.0.116's native decision model: question ID → `name`, `boolean` → `predicate` with `Criteria for true:` / `Criteria for false:` paragraphs after the instructions, choice criteria → `choices`, score criteria → `levels` labeled by index, JSON objects (or arrays of objects) → `input_json`, other JSON → text. One deliberate difference: OpenAI rejects a question without instructions (`Missing required parameter: 'questions[0].instructions'`, live 2026-11-13) although `@ai-sdk/openai` sends it omitted, so qgrid answers 400 before the upstream call, naming the question ID (`decisionIssues`).
280
+
@@ -150,6 +150,12 @@ Sources: `docs/plans/2026-10-17-openai-realtime-audio-plan.md`, `docs/diagnosis/
150
150
  - qgrid answers GPT-Live delegations itself (user decision 2026-11-10): unanswered, the voice only stalls, OpenAI-run `responses` delegation fails on subscription, and Codex does the same with its own agent. The model, effort and web search are per-session choices because some conversations need tools and some do not; the default `openai/gpt-6-luna` at low effort (user's pick) keeps the spoken wait short. Any qgrid model works because the request goes through the ordinary query routing. Caller-defined tools were left out: the caller's only live channel is its peer to OpenAI.
151
151
  - The live session ends from the caller's data channel (`session.close`), not a qgrid close endpoint: it reaches OpenAI in under a second and covers external apps too. A dropped peer is left to OpenAI, which ends the session about 30 s later.
152
152
 
153
+ ## OpenAI Decisions
154
+
155
+ - Decisions is OpenAI-only (2026-11-13). Anthropic and xAI document no decision endpoint, and neither exposes token logprobs on current models (xAI ignores them on `grok-4.20`+). AI SDK emulates Anthropic with prompted estimates and no distributions; qgrid does not add that emulation, so a qgrid probability is always a native one.
156
+ - The qgrid `/decide` API is provider-neutral (the AI SDK decision call in JSON), and the OpenAI provider layer converts both ways (user decision 2026-11-13). An OpenAI-shaped API was rejected because it would expose one provider's wire format at the API boundary and break deployed SDKs when a second provider (Google, Perplexity) arrives; this matches `transcribe`, which routes `openai/` and `grok/` by model prefix.
157
+ - Missing instructions are a 400, not a synthesized default sentence: a default would change the judgment silently, and OpenAI itself rejects the omission.
158
+
153
159
  ## Grok (xAI Subscription) Runtime
154
160
 
155
161
  Sources:
@@ -4,7 +4,10 @@ Use this reference before changing OpenAI transport, concurrency, routing, promp
4
4
 
5
5
  ## Source files
6
6
 
7
- - Dispatcher and token routing: `packages/api/src/utils/providers/openai/openai-dispatcher.ts`.
7
+ - Provider surface (thin): `packages/api/src/utils/providers/openai/openai-dispatcher.ts`. `OpenAIDispatcher` builds the token pool, the Responses runtime, and the voice client (`openai-voice-client.ts`), keeps the first two private, and delegates its public methods to them. Decisions is a stateless function it runs through the pool.
8
+ - Token pool shared by every OpenAI API: `openai-token-pool.ts` (`OpenAITokenPool`: weighted selection behind the quota gate, rate-limit cache, OAuth refresh, token add/update/remove, and `runWithToken` for non-Responses calls). Listeners registered with `onTokenInvalidated` run on refresh and removal; the Responses runtime registers its `retireClient` in its constructor. The pool owns the injected `fetch`, and the 401 check is `isOpenAIUnauthorizedError` in `openai-backend-protocol.ts`. Token selection and results use the common `MediaTokenSelection` / `MediaDispatchResult` types.
9
+ - Responses runtime: `openai-responses-runtime.ts` (`OpenAIResponsesRuntime`: `run`/`runDirect`, request options, the per-token direct-client cache, `inFlight`, `ImageGenerationError`).
10
+ - Native Decisions: `openai-decisions.ts`.
8
11
  - Direct client and transport interface: `openai-direct-client.ts`.
9
12
  - Request, identity headers, and normalized events: `openai-backend-protocol.ts`.
10
13
  - SSE decoding: `openai-sse.ts`.
@@ -238,10 +241,14 @@ Sources: `openai-realtime-protocol.ts` (wire constants, session builders, PCM he
238
241
  - TTS is the one deviation from Codex. The `/calls` sideband never carries `response.output_audio.delta` (media stays on RTP, verified twice), and qgrid has no RTP stack, so speech uses the direct `wss://api.openai.com/v1/realtime?model=<id>` socket, which Codex itself treats as API-key-only (`realtime_conversation.rs:1931-1955`) but which accepts the ChatGPT bearer today. The session is Codex's V2 conversational payload minus `tools`, with a verbatim-reading system prompt (labeled `# Role & Objective` / `# Rules` / `# Examples` sections with capitalized never-answer rules; the caller's `instructions` follow as `# Style`), the text wrapped in `<script>…</script>` as the one `conversation.item.create` user item, and `response.create`; the output is concatenated PCM16 24 kHz returned as WAV (default) or raw PCM. OpenAI realtime has 10 preset voices, matching the Codex v2 list (`alloy ash ballad coral echo sage shimmer verse marin cedar`, default `marin`); others fail with 400. The model's own `response.output_audio_transcript.done` and `response.done.usage` audio/text tokens are logged with the request for fidelity checks. Treat a 401/403 on this socket as the path being gated: fail with the upstream error, do not fall back.
239
242
  - TTS timing (2.19.0+): realtime speech carries no timing, so `speak` with `withTimestamps` force-aligns the text to the generated PCM in process (`utils/speech-aligner.ts`; 2.17.x transcribed the audio with Grok STT instead, removed by user decision 2026-11-09). The model is MMS-FA (Meta's CTC forced aligner, 1,130 languages, CC BY-NC 4.0, adopted with that license risk accepted) converted to int8 ONNX by us (355 MB, about 640 MB resident, about 0.17 s per 6 s clip on Apple Silicon). It scores 20 ms frames of 16 kHz audio against 28 letters; a Viterbi pass walks the script's letters in order. The script is romanized (Hangul per syllable, Latin accents stripped); digits, symbols, and other scripts become a star token (log-probability 0, matches any sound), and a star also wraps the script so a spoken preamble is absorbed. Audio over 30 s is scored in 30 s windows with 2 s context. The session loads on first use and unloads after 10 idle minutes. Output keeps `timestampsSource: "aligned"`; the step log records `alignMs`. The model path is `QGRID_ALIGNER_MODEL`, else `~/.cache/qgrid/models/mms-300m-fa-int8.onnx` (where `qgrid --install-aligner` downloads it), and `onnxruntime-node` is an api devDependency kept external in the build (`tsdown.config.ts` `neverBundle`; a bundled import resolves to a missing pnpm path): the Docker image installs both in layers before Claude Code and qgrid (model from the `aligner-model-v1` GitHub release, pinned by checksum, attribution in `/opt/qgrid/models/NOTICE.md`), and the image smoke test runs one alignment. An npm or pnpm install lacks both until `qgrid --install-aligner`, which fetches the model and the pinned `onnxruntime-node`/`onnxruntime-common` tarballs straight from their URLs (SRI hashes checked), unpacks the runtime with `tar` into `~/.cache/qgrid/runtime/node_modules` keeping only this platform's binary, and never calls npm or pnpm: a pnpm v11 global install isolates each global package, so a globally installed `onnxruntime-node` was invisible to qgrid (verified 2026-11-09). The server imports `onnxruntime-node` normally and falls back to that folder through `createRequire`. The Viterbi back-pointer table is frames x (2 x tokens + 1) bytes, capped at 100 MB: both grow with the audio, so about 4 minutes of dense English (251 s at 16.7 chars/s) is the most it can time; `alignSpeech` rejects longer input before running the model. Bench (SON-589): against Grok TTS character timing, word-boundary error median 4 ms / p90 20 ms / p99 25 ms on 523 words (the STT pass: 5 / 24 / 165 ms, failing on dropped fillers like "Hmm" and code-switched lines), digit words median 9 ms / p90 63 ms; on 126 OpenAI clips it agreed with the STT pass within one frame for 96% of words.
240
243
  - STT words (2.19.0+): `transcribe` aligns the OpenAI transcript to the input audio with the same aligner (`prepareRealtimeInput` PCM at 24 kHz) and returns `TranscribeOutput.words`, the shape Grok STT returns; the step log records `alignMs`, or `wordsError` when alignment fails and the transcript returns without words. Measured 2026-11-09 on Apple Silicon: 2.9 s for a 54 s clip (cold load included), 9.9 s for 3.6 min; a 4.9 min clip exceeded the table cap.
241
- - Dispatcher: `OpenAIDispatcher.runVoice` selects a token with the same quota gate as Responses, refreshes once on a 401 and retries once, and invalidates the rate-limit cache afterwards. `OpenAIVoiceInputError` (unsupported audio, bad voice, empty text) becomes HTTP 400 `qgrid.openaiVoiceInvalidRequest`; everything else propagates as an upstream failure.
244
+ - Dispatcher: `OpenAITokenPool.runWithToken` (`OpenAIDispatcher.runVoice` before 2.22.0; Decisions shares it) selects a token with the same quota gate as Responses, refreshes once on a 401 and retries once, and invalidates the rate-limit cache afterwards. `OpenAIVoiceInputError` (unsupported audio, bad voice, empty text) becomes HTTP 400 `qgrid.openaiVoiceInvalidRequest`; everything else propagates as an upstream failure.
242
245
  - Recommended OpenAI STT (2.20.0+, SON-593): `gpt-transcribe`. OpenAI shuts down `gpt-4o-mini-transcribe`, `gpt-4o-transcribe` and `whisper-1` on 2027-02-26. A transcribe request without `model` goes to Grok (`voiceProvider`), so `OPENAI_REALTIME_DEFAULT_TRANSCRIPTION_MODEL` (now `gpt-transcribe`, was Codex's `gpt-4o-mini-transcribe`) is only the OpenAI client's fallback id and the speech session's input transcription model (TTS accepted `gpt-transcribe` there, or no transcription field, on 2026-11-10). Bench 2026-11-10 through the local server (synthetic speech): `gpt-transcribe` WER 2.3% on 108 English clips and CER 4.4% on 18 Korean/English clips, full transcripts of 60 s and 229 s podcast cuts, empty text for 5 s of silence and of noise, median 4.4 s per clip; `gpt-live-transcribe` 2.8% / 5.9%, stopped at 51 of 126 words (60 s) and 73 of 491 (229 s), median 5.8 s; `gpt-4o-transcribe` 1.4% / 14.5%, failed the 229 s clip, and returned Vietnamese/Japanese phrases for silence/noise. Both successors sometimes corrected learner grammar ("we eat" → "we ate"; run to run it varies). `buildTranscriptionSession` sends qgrid's `language` to `gpt-transcribe` as `languages: [language]` (sending both is an upstream `invalid_value`; the gpt-4o family rejects `languages`; singular `language` was still honored by `gpt-transcribe` on 2026-11-10). `gpt-transcribe` also accepts `keywords`, which qgrid does not expose. The English WER gap to `gpt-4o-transcribe` is number formatting (12 of its 46 edits were "21st" → "twenty-first"). `gpt-live-transcribe` is left as is (user decision 2026-11-10: out of scope); it transcribes only about the first 30 s of one committed buffer (60 s clip: 57 words on one commit, all 129 with a commit every 10 s) and rejects server VAD ("Turn detection is not supported for this transcription model").
243
246
  - Exposed ids (user decision 2026-10-17: keep every reachable id, document limits): STT `gpt-4o-mini-transcribe`, `gpt-4o-transcribe`, `gpt-transcribe` (4/4 on the matrix), `gpt-live-transcribe` and `gpt-realtime-whisper` (return about half of a 60 s clip; whisper also mangles Korean), `whisper-1` (ignores `prompt`). `gpt-realtime-whisper` rejects `prompt` upstream, so `OPENAI_TRANSCRIPTION_MODELS_WITHOUT_PROMPT` makes the client fail with a 400 before the realtime call. TTS `gpt-realtime-2.1-mini` (13/13 verbatim, default), `gpt-realtime-2.1` (12/13) on the 2026-10-17 statement texts; `gpt-realtime-1.5` (6/13, often answers instead of repeating) was removed from the server list, SDK union and READMEs on 2026-11-09 (user decision, 2.18.0). Realtime models are conversational and answer text addressed to the listener: on question-form character lines the original one-sentence prompt let `gpt-realtime-2.1` answer 7 of 12, while the current sectioned prompt with `<script>` delimiters read 12/12 on both 2.1 and 2.1-mini (`docs/diagnosis/2026-11-06-openai-realtime-tts-prompt.md`). That 12/12 was judged by the model's own transcript, which can omit a spoken preamble; on 2026-11-09 two independent STT models (gpt-4o-transcribe, Grok) judged 108 English clips (6 lines x `marin` `cedar` `ballad` x 3): 2.1 54/54, 2.1-mini 53/54 (one take opened with "Sure, let me read that out loud for you exactly as written."), and both read all 9 Korean/English mixed takes in full. gpt-4o-transcribe itself dropped the English part of 3 of 18 mixed clips that Grok STT heard in full. Keep every instruction in the system prompt: an instruction placed in the user item was read aloud. Model behavior is tracked by the live matrix (`OPENAI_LIVE=1 pnpm tsx scripts/live-openai-voice-matrix.ts`, results in `docs/diagnosis/2026-10-17-openai-realtime-audio-probe.md`). Remove an id from `OPENAI_TRANSCRIPTION_MODELS`/`OPENAI_SPEECH_MODELS`, the SDK unions, and the READMEs together when it stops passing. Unavailable on subscription (verified 2026-10-17): `/backend-api/codex/audio/transcriptions`, `/audio/speech`, `gpt-4o-mini-tts`, `tts-1*`, `gpt-transcribe` via `/codex/responses`, Responses `input_audio`. The ChatGPT-web `POST /backend-api/transcribe` works but is not used (removed from Codex in PR #16114, ignores model/language, retains uploads 30 days).
244
247
 
248
+ ## Native Decisions (2.22.0+)
249
+
250
+ Sources: `openai-decisions.ts`, `OpenAIDispatcher.decide`, `qgrid.frame.ts` `decide`. `POST https://api.openai.com/v1/decisions` (the public API, not the Codex backend) accepts the ChatGPT OAuth access token as a plain `Authorization: Bearer`, with no `ChatGPT-Account-ID` needed (live probe 2026-11-13, Pro plan); `chatgpt.com/backend-api/codex/decisions` is 404. The only model is `gpt-6-luna`. `createOpenAIDecision` validates the wire request against OpenAI's limits (1-400 uniquely named questions, 2-255 choices, 2-10 levels, instructions required), posts with a 60 s timeout, maps HTTP errors to `OpenAIProtocolError` with `status` so `runWithToken` refreshes once on 401, and checks one answer per question. A refused question is a 200 with `{ type: "refusal", name }` (qgrid names every question, so a refusal without a name is treated as an invalid response). A timeout or cancel while reading the body surfaces as that abort, not as a malformed response. `runWithToken` runs Decisions with `refreshQuota: false`: voice re-reads quota after every call, but Decisions is high-frequency and keeps the 60 s cached lookup like Responses. At the `/decide` boundary (`decisionCallerError` in `qgrid.frame.ts`), upstream 400/413/415/422 become HTTP 400 with OpenAI's message and 429 becomes HTTP 429 with the upstream `Retry-After`; 401/403 and 5xx stay upstream failures (500). Images are validated before any call (`DecisionImageRef`): http(s) URL, or strict base64 PNG/JPEG/WebP/GIF within 19 MiB each and in total. Usage reports `cached_tokens` and `cache_write_tokens` inside `input_tokens` and `output_tokens: 0`; output is not charged. Whether calls count against the subscription quota is not measured. Not used: conversation-history items, per-question images, boolean choice values, explicit cache breakpoints, `prompt_cache_options`; the AI SDK decision call cannot express them.
251
+
245
252
  ## GPT-Live conversation (SON-592, 2.19.2+)
246
253
 
247
254
  Sources: `openai-realtime-protocol.ts` (GPT-Live section), `OpenAIVoiceClient.createLiveCall`/`watchLiveSession`, `OpenAIDispatcher.startLive`, `qgrid.frame.ts` `liveCall`/`finishLiveRun`, dashboard `VoicePlayground.tsx` `LivePanel`. Probes: SON-591 (access) and SON-592 (spike), 2026-11-10, against `openai/codex` main e0370f0b06.
@@ -104,12 +104,14 @@ Input images are not stored in `request_logs.user_prompt`; that field remains th
104
104
 
105
105
  ## Media fields
106
106
 
107
- - `media_kind`: nullable enum (`image`, `video`, `stt`, `tts`, `live`) written at `createRun` by `startMediaRun` from the media endpoint's kind; text and chat runs keep NULL (chat-generated images are marked only by `is_image_generation`). The list `Fmt` column reads it, so any new media endpoint must open its run through `startMediaRun` or set it explicitly.
107
+ - `media_kind`: nullable enum (`image`, `video`, `stt`, `tts`, `live`, `decision`) written at `createRun` by `startMediaRun` from the media endpoint's kind; text and chat runs keep NULL (chat-generated images are marked only by `is_image_generation`). The list `Fmt` column reads it, so any new media endpoint must open its run through `startMediaRun` or set it explicitly.
108
108
  - Live runs (`live`, 2.19.2+): one row per GPT-Live session, `running` for the whole session (up to two hours). The `live_session` tool step is written with a `{"status":"live"}` result rather than pending, because the 30-minute tool-wait cleanup matches pending tool steps; `recordRunProgress` (which writes only to running rows) rewrites `response` with the conversation after every turn, and the session's end replaces the step result with the summary (turns, kept events, usage, end reason) and finishes the run. Each answered delegation is appended as its own `delegation` tool step (`tool_call_index` 1, 2, ...; args: request, model, effort, webSearch; result: answer, serving model, token, usage, cost; or `error`), written as it completes, and the run's `cost_usd` is the session audio estimate plus every delegation's query cost. A session started from `history` stores it in the run's `history` column as `{type: "message", role, content}` items, which the detail page's History section shows. `expireStaleLiveRuns` closes live runs still running 2 h 15 min after creation (their server stopped mid-session) in the same stale cleanup pass. No audio is stored.
109
109
  - Speech `response`: browser-playable audio is embedded as an `<audio>` data URL (see `sonamu-api-web-flow.md`); speech `ttft_ms` is the first audio byte, passed explicitly to `finishRun` because media runs have no generate step to derive it from.
110
110
 
111
111
  - Voice cost (2.17.1+): subscription voice calls have no per-call bill, so `cost_usd` records the public API list-price estimate with `cost_source: "pricing_table"` (`model-cost.ts`, prices checked 2026-11-09): OpenAI realtime speech from its response usage per token type (cached input is not split out, so all input is charged as uncached text; the in-process timing alignment costs nothing, 2.19.0+); transcription per minute of audio (OpenAI's published per-minute estimates, Grok $0.10/hour); Grok TTS $15 per 1M input characters. Unknown model ids stay unpriced (NULL). The detail page labels the figure "Voice" instead of "Driver". OpenAI speech rows store the caller's style `instructions`, and OpenAI transcription rows the STT `prompt`, as `system_prompt` (2.17.1+); the detail page titles that panel "Style instructions" or "Prompt".
112
112
 
113
+ - Decision runs (`decision`, 2.22.0+): `user_prompt` is the state (a single text part as plain text, otherwise JSON with data URLs masked), `system_prompt` the neutral questions JSON (the detail page titles it "Questions"), `response` the neutral answers JSON. One `decision` tool step records the questions exactly as OpenAI received them (`upstreamQuestions`). Unlike other media rows, the run stores token usage (`input_tokens`, `cache_read_tokens` from `cached_tokens`, `cache_creation_tokens` from `cache_write_tokens`; both already included in `input_tokens`) through `MediaLogSuccess.usage`. `cost_usd` uses `gpt-6-luna` input and cached-input rates with output free (`openaiDecisionCost`); the cache-write rate is Luna's table rate, not confirmed for Decisions. A response containing a refusal is returned to the caller as 200 but closes the run as `error` with `Decision refused: <ids>` (`MediaLogSuccess.errorMessage`), because AI SDK fails the whole call. Known gap: when the upstream call succeeds but its answers fail conversion (an answer type that does not match the question), the run closes as `error` without token usage or cost, because the media failure path records only the message.
114
+
113
115
  ## Structured output fields
114
116
 
115
117
  Structured output requests (those carrying a `jsonSchema`) persist three related fields:
@@ -26,7 +26,7 @@ Use this reference before changing token storage, OAuth flows, token activation,
26
26
  - OpenAI direct OAuth/refresh/quota: `packages/api/src/utils/providers/openai/openai-oauth.ts`, `openai-refresh.ts`, `openai-quota.ts`.
27
27
  - Anthropic quota: `packages/api/src/utils/providers/anthropic/anthropic-quota.ts`.
28
28
  - Grok OAuth/refresh/quota: `packages/api/src/utils/providers/grok/grok-oauth.ts`, `grok-refresh.ts`, `grok-quota.ts`.
29
- - Provider token event handlers: `openai-dispatcher.ts`, `anthropic-dispatcher.ts`, `grok-dispatcher.ts`.
29
+ - Provider token event handlers: `openai-token-pool.ts` (behind `openai-dispatcher.ts`), `anthropic-dispatcher.ts`, `grok-dispatcher.ts`.
30
30
 
31
31
  ## Token Table Contract
32
32
 
@@ -226,7 +226,9 @@ OpenAI row changes:
226
226
  - active INSERT: `onTokenAdded` spawns workers.
227
227
  - active UPDATE: `onTokenUpdated`, then `onTokenActivated`.
228
228
  - inactive row: `onTokenDeactivated`.
229
- - reconcile uses `replaceTokens`, which removes absent tokens, updates existing tokens, adds new tokens, and activates rows present in active DB set.
229
+ - reconcile uses `replaceTokens`, which removes absent tokens, updates existing tokens, adds new tokens, and activates rows present in active DB set (it sets `active: true` itself; before 2.22.0 it went through `onTokenUpdated`, which keeps the pool's previous `active`, so a missed re-activation NOTIFY left the token out until restart).
230
+ - `setToken` returns early when name, credentials, threshold, weight, and active are all unchanged. Before 2.22.0 every reconcile bumped every token's generation, which closed and rebuilt each Responses client (and its WebSocket) and cleared the quota cache and over-threshold state every 10 minutes.
231
+ - startup loads through `TokenModel.findActiveByProvider("A", "openai")`. Before 2.22.0 it used `findMany("A")`, whose default page is 24 rows across every provider, so later OpenAI tokens were missing until the first reconcile.
230
232
 
231
233
  Anthropic row changes:
232
234