@cartanova/qgrid-cli 2.21.0 → 2.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.ko.md +5 -4
  2. package/README.md +5 -4
  3. package/bundle/dist/application/monit/monit.frame.js +1 -1
  4. package/bundle/dist/application/qgrid/expired-token-reminder.js +1 -1
  5. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +2 -2
  6. package/bundle/dist/application/qgrid/qgrid.dispatcher.js +3 -3
  7. package/bundle/dist/application/qgrid/qgrid.frame.js +130 -24
  8. package/bundle/dist/application/qgrid/qgrid.types.js +205 -2
  9. package/bundle/dist/application/qgrid/token-death.js +1 -1
  10. package/bundle/dist/application/qgrid/token-window-keepalive.js +1 -1
  11. package/bundle/dist/application/request-log/request-log.model.js +2 -2
  12. package/bundle/dist/application/sonamu.generated.js +5 -3
  13. package/bundle/dist/i18n/en.js +2 -1
  14. package/bundle/dist/i18n/ko.js +2 -1
  15. package/bundle/dist/i18n/sd.generated.js +3 -2
  16. package/bundle/dist/sonamu.config.js +2 -2
  17. package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +1 -1
  18. package/bundle/dist/utils/providers/common/model-cost.js +15 -2
  19. package/bundle/dist/utils/providers/grok/grok-dispatcher.js +2 -2
  20. package/bundle/dist/utils/providers/openai/openai-backend-protocol.js +6 -2
  21. package/bundle/dist/utils/providers/openai/openai-decisions.js +178 -0
  22. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +61 -677
  23. package/bundle/dist/utils/providers/openai/openai-image-generation.js +1 -1
  24. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +1 -1
  25. package/bundle/dist/utils/providers/openai/openai-refresh.js +2 -2
  26. package/bundle/dist/utils/providers/openai/openai-responses-runtime.js +430 -0
  27. package/bundle/dist/utils/providers/openai/openai-token-pool.js +291 -0
  28. package/bundle/dist/utils/providers/openai/openai-voice-client.js +2 -6
  29. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +1 -1
  30. package/bundle/src/application/qgrid/qgrid.dispatcher.test.ts +2 -1
  31. package/bundle/src/application/qgrid/qgrid.dispatcher.ts +2 -4
  32. package/bundle/src/application/qgrid/qgrid.frame.test.ts +100 -1
  33. package/bundle/src/application/qgrid/qgrid.frame.ts +146 -7
  34. package/bundle/src/application/qgrid/qgrid.types.ts +242 -0
  35. package/bundle/src/application/request-log/request-log.entity.json +3 -2
  36. package/bundle/src/application/sonamu.generated.http +31 -0
  37. package/bundle/src/application/sonamu.generated.ts +2 -1
  38. package/bundle/src/i18n/en.ts +1 -0
  39. package/bundle/src/i18n/ko.ts +1 -0
  40. package/bundle/src/i18n/sd.generated.ts +2 -1
  41. package/bundle/src/utils/providers/common/model-cost.ts +20 -0
  42. package/bundle/src/utils/providers/openai/openai-backend-protocol.ts +5 -0
  43. package/bundle/src/utils/providers/openai/openai-decisions.test.ts +240 -0
  44. package/bundle/src/utils/providers/openai/openai-decisions.ts +266 -0
  45. package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +133 -7
  46. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +90 -1083
  47. package/bundle/src/utils/providers/openai/openai-responses-runtime.ts +677 -0
  48. package/bundle/src/utils/providers/openai/openai-token-pool.ts +481 -0
  49. package/bundle/src/utils/providers/openai/openai-voice-client.ts +0 -5
  50. package/bundle/web-dist/client/assets/{index-NGqKa5_C.js → index-BSjyOyOc.js} +17 -17
  51. package/bundle/web-dist/client/assets/{logs-BLhlxqoB.js → logs-CFyeyR7u.js} +1 -1
  52. package/bundle/web-dist/client/assets/{monit-C3stGFEK.js → monit-N3gBNCXy.js} +1 -1
  53. package/bundle/web-dist/client/assets/{routes-Dgh-_yS5.js → routes-UbYa5WQL.js} +1 -1
  54. package/bundle/web-dist/client/assets/{settings-DiOZwvRj.js → settings-CTZGAJjl.js} +1 -1
  55. package/bundle/web-dist/client/assets/{show-DucEoTrr.js → show-oNGv2jAJ.js} +2 -2
  56. package/bundle/web-dist/client/assets/{tokens-DvCT1bbk.js → tokens-BrhEjJ3t.js} +1 -1
  57. package/bundle/web-dist/client/assets/{use-oauth-login-flow-DazQfaBL.js → use-oauth-login-flow-Ca1Sn84P.js} +1 -1
  58. package/bundle/web-dist/client/assets/{use-update-token-mutation-CfGbUel6.js → use-update-token-mutation-DMy7Pw8U.js} +1 -1
  59. package/bundle/web-dist/client/assets/{voice-zPre2iO8.js → voice-CVXYbgBN.js} +1 -1
  60. package/bundle/web-dist/client/index.html +1 -1
  61. package/bundle/web-dist/server/assets/{TimedPlayer-CcClBzGi.js → TimedPlayer-mpJpP5tQ.js} +1 -1
  62. package/bundle/web-dist/server/assets/{logs-CxAwuDKc.js → logs-CFa_xamY.js} +6 -3
  63. package/bundle/web-dist/server/assets/{monit-Bl2kSkSF.js → monit-BF6osfj5.js} +2 -2
  64. package/bundle/web-dist/server/assets/{plus-CQ8AHpih.js → plus-DwQFfeid.js} +1 -1
  65. package/bundle/web-dist/server/assets/{refresh-cw-pYSuvt4c.js → refresh-cw-Bj-Jxeb6.js} +1 -1
  66. package/bundle/web-dist/server/assets/{request-model-ZulJMbGm.js → request-model-D_iYrudl.js} +1 -1
  67. package/bundle/web-dist/server/assets/{routes-W-pd1Hps.js → routes-B6be8sJP.js} +3 -3
  68. package/bundle/web-dist/server/assets/{services.generated-C3b31_vt.js → services.generated-D0995hJr.js} +14 -2
  69. package/bundle/web-dist/server/assets/{settings-CFdTg1_f.js → settings-DAle7AgI.js} +3 -3
  70. package/bundle/web-dist/server/assets/{show-DVEIHsXh.js → show-BTSdMDoM.js} +4 -4
  71. package/bundle/web-dist/server/assets/{tokens-BO1hyBuB.js → tokens-Bc9flfLz.js} +4 -4
  72. package/bundle/web-dist/server/assets/{use-oauth-login-flow-CCc8LEmn.js → use-oauth-login-flow-C7c0gCjf.js} +1 -1
  73. package/bundle/web-dist/server/assets/{use-update-token-mutation-Ba-sEhq1.js → use-update-token-mutation-DLJDGdxu.js} +1 -1
  74. package/bundle/web-dist/server/assets/{voice-BCF-Pkzo.js → voice-CEQT57xZ.js} +2 -2
  75. package/bundle/web-dist/server/entry-server.generated.js +214 -10
  76. package/package.json +1 -1
  77. package/skills/qgrid/SKILL.md +2 -2
  78. package/skills/qgrid/references/ai-sdk-provider-contract.md +10 -0
  79. package/skills/qgrid/references/cli-env-and-server-boot.md +2 -3
  80. package/skills/qgrid/references/decision-rationale.md +9 -3
  81. package/skills/qgrid/references/openai-codex-runtime.md +9 -2
  82. package/skills/qgrid/references/provider-runtime-differences.md +2 -2
  83. package/skills/qgrid/references/request-log-run-lifecycle.md +5 -3
  84. package/skills/qgrid/references/sonamu-api-web-flow.md +2 -2
  85. package/skills/qgrid/references/token-auth-quota-lifecycle.md +5 -3
  86. package/skills/qgrid/references/verification-and-debugging.md +3 -3
@@ -1,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.21.0";
53976
+ var qgridVersion = "2.22.1";
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.21.0",
3
+ "version": "2.22.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/cartanova-ai/qgrid"
@@ -45,7 +45,7 @@ Request logging is enabled by default. Use `providerOptions.qgrid.logger: false`
45
45
 
46
46
  ## Non-Negotiable Boundaries
47
47
 
48
- - Use `packages/ai-sdk` as the active public SDK surface. `qgrid()` implements `LanguageModelV3` for text, tools, and structured output; it has no public image-generation options and does not support general vision. `qgrid.image("openai/gpt-image-2")` implements `ImageModelV3` for standard AI SDK `generateImage`, directly calling subscription Images for generation or reference editing without a chat driver. Dashboard chat registers its image tool internally; do not add a public SDK tool factory. See `references/ai-sdk-provider-contract.md` for image options, usage, and metadata.
48
+ - Use `packages/ai-sdk` as the active public SDK surface. `qgrid()` implements `LanguageModelV3` for text, tools, and structured output; it has no public image-generation options. User-message image parts are sent as image input on `openai/` and `grok/` models and dropped on `anthropic/` models. `qgrid.image("openai/gpt-image-2")` implements `ImageModelV3` for standard AI SDK `generateImage`, directly calling subscription Images for generation or reference editing without a chat driver. Dashboard chat registers its image tool internally; do not add a public SDK tool factory. See `references/ai-sdk-provider-contract.md` for image options, usage, and metadata.
49
49
  - Expose thinking only as `providerOptions.qgrid.thinking?: boolean`: omission preserves the model policy, false overrides effort, and unsupported/unverified off requests fail explicitly. See the SDK and provider runtime references for the dated support snapshot. Keep Anthropic thinking controls separate from mandatory configuration and memory isolation. Haiku/Sonnet 5.5 off uses a computed thinking-only native body override with Claude Code >=2.1.295; never inherit or expose arbitrary extra body.
50
50
  - The old v1 SDK package (`packages/sdk`, `@cartanova/qgrid-sdk`) has been removed from the repository. It survives only as a deprecated npm artifact (1.9.0); do not resurrect it or write new code against it.
51
51
  - Let the server infer single-turn versus tool-run request-log lifecycle. Do not recreate caller-selected logging modes in the SDK or API examples.
@@ -59,7 +59,7 @@ Request logging is enabled by default. Use `providerOptions.qgrid.logger: false`
59
59
 
60
60
  ## Request log IDs (2.10.0+)
61
61
 
62
- - Successful raw query responses and stream `done` events expose optional top-level `requestLogId`. AI SDK text calls expose it as `providerMetadata.qgrid.requestLogId`; await stream metadata after consuming the stream. `generateImage` exposes each call's ID under `providerMetadata.qgrid.images[]` alongside generation metadata.
62
+ - Successful raw query responses and stream `done` events expose optional top-level `requestLogId`. AI SDK text calls expose it as `result.finalStep.providerMetadata.qgrid.requestLogId` (AI SDK 7 keeps top-level `providerMetadata` only as a deprecated alias); for streams, await `finalStep` after consuming the stream. `generateImage` exposes each call's ID under `providerMetadata.qgrid.images[]` alongside generation metadata.
63
63
  - The ID identifies the parent request log and stays the same across tool-run steps. It is omitted with `logger: false`. Keep `runContext.requestLogId` for tool continuation only; do not replay the top-level ID as continuation state.
64
64
  - Update both server and AI SDK to 2.10.0 or later to consume the metadata. Older servers may omit the ID. This contract does not add IDs to delta or error events or change `createQgridLogger` for external providers.
65
65
 
@@ -268,3 +268,13 @@ Grok speech passes the standard `speed` through as `@ai-sdk/xai` does (2.18.0+;
268
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
+
@@ -10,10 +10,9 @@ Use this reference for qgrid startup, configuration, and runtime-facing environm
10
10
 
11
11
  When npm reports a newer `@cartanova/qgrid-cli`, including patch releases, the CLI installs that exact resolved version and restarts from the updated binary. Do not use a moving `@latest` install target for this path; exact versions avoid stale pnpm global project ranges. The npm lookup and global install are best-effort: a registry/package-manager outage is logged prominently and boot continues on the current qgrid version. A successful install is still verified against the exact resolved version before restart.
12
12
 
13
- The CLI also ensures runtime CLIs are installed/current enough:
13
+ The CLI checks one runtime CLI at startup and only warns when it is missing (it does not install it):
14
14
 
15
- - `codex` from `@openai/codex`, required for OpenAI tokens.
16
- - `claude` from `@anthropic-ai/claude-code`, required for Anthropic tokens.
15
+ - `claude` (Claude Code), required for Anthropic tokens. OpenAI and Grok tokens need no local CLI: qgrid calls their backends directly.
17
16
 
18
17
  ## CLI database env vars
19
18
 
@@ -94,8 +94,8 @@ Key decisions:
94
94
  - Direct PKCE OAuth, refresh, and `wham/usage` quota lookup replace delegated runtime calls. Generation and quota requests send Codex CLI identity headers.
95
95
  - Requests run uncapped, matching the Anthropic runtime: transport is a single HTTPS/WS request, so no local resource justifies a cap, and upstream limits are the backend's responses. The worker-era permit/queue layer was removed once this became clear.
96
96
  - Every turn sends full Responses-format history. A model-scoped opaque value derived from `sessionKey` is forwarded as `prompt_cache_key`; it is not a provider thread address.
97
- - `AbortSignal` cancellation covers queue wait, retry delay, and active HTTPS transport.
98
- - The transport interface is independent of HTTPS so a future WebSocket implementation can preserve dispatcher behavior.
97
+ - `AbortSignal` cancellation covers token selection (including the quota lookup) and the active transport. There is no queue.
98
+ - The transport interface is independent of HTTPS; the WebSocket transport (`QGRID_OPENAI_TRANSPORT=websocket`, the current default) uses the same dispatcher behavior.
99
99
  - The backend is private and unstable. Mocked protocol tests do not establish live provider compatibility.
100
100
  - OpenAI cached tokens are included in `input_tokens`. Cache-hit denominator is `input_tokens`, not `input + cache_read + cache_creation`.
101
101
 
@@ -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 on `choice` and `score` questions are a 400, not a synthesized default sentence: a default would change the judgment silently, and OpenAI itself rejects the omission. A `boolean` question may rely on its criteria, which become the instructions.
158
+
153
159
  ## Grok (xAI Subscription) Runtime
154
160
 
155
161
  Sources:
@@ -255,7 +261,7 @@ Key decisions:
255
261
  - CLI and SDK were split so AI consumers do not install Sonamu, database, and runtime-server dependencies just to call qgrid.
256
262
  - The CLI is a direct Node/bundle runner, not a Docker wrapper. Docker was removed to keep `npm i -g ...` plus `qgrid start` usable without local Docker setup.
257
263
  - CLI user-facing configuration is intentionally small: database connection, port, public callback URL, server URL, and project name. Bundle bootstrapping details are implementation internals.
258
- - The CLI checks runtime CLIs (`codex`, `claude`) because qgrid delegates provider execution to those local binaries.
264
+ - The CLI checks for `claude` only and warns when it is missing: Anthropic execution is delegated to that local binary, while OpenAI and Grok are called directly.
259
265
  - The dashboard version should follow the CLI package version because the dashboard is shipped by the CLI bundle, not as an independently versioned web product.
260
266
  - qgrid skills ship with the CLI package, not a separate skills package. qgrid cannot be used with the AI SDK alone; a local qgrid CLI server is required, so CLI install is the right moment to sync `.agents/skills/qgrid` and `.claude/skills/qgrid` into the consuming project.
261
267
  - Sonamu 0.11 (2.11.0) keeps qgrid-side workarounds instead of pinning back: the API build sets `NODE_ENV=production` (SON-567), CI creates an empty `packages/api/.env`, and `.oxlintrc.json` disables `no-unnecessary-type-assertion` for Sonamu's lint temp files (SON-564). Remove each workaround once the matching Sonamu issue ships. Peer ranges that upstream packages have not widened yet are allowed per parent in `pnpm-workspace.yaml` `peerDependencyRules.allowedVersions`, with the reason next to each entry.
@@ -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.
@@ -10,7 +10,7 @@ Use this reference when comparing OpenAI, Anthropic, and Grok behavior, debuggin
10
10
  | Epoch | Legacy compatibility value; not a process generation | Always `0` | `-1`; not a process generation |
11
11
  | Request concurrency | Uncapped; stateless request per call | Uncapped; fresh process per request | Uncapped by default; optional `QGRID_GROK_MAX_INFLIGHT_PER_TOKEN` excludes accounts at the cap |
12
12
  | Token selection | Smooth weighted RR over quota-eligible tokens; valid affinity may prefer its token | Smooth weighted RR over quota-eligible tokens per request | Smooth weighted RR after quota, on-demand, cooldown, entitlement, and capacity gates; valid affinity may prefer its token |
13
- | Model routing | `openai/*`; qgrid strips provider prefix before provider call | `anthropic/*`; provider canonicalizes model and strips prefix/`[1m]` | `grok/*`; qgrid strips the provider prefix and validates against the seeded/live catalog |
13
+ | Model routing | `openai/*`; qgrid strips provider prefix before provider call | `anthropic/*`; provider canonicalizes model and strips prefix/`[1m]` | `grok/*`; qgrid strips the provider prefix and looks the id up in the seeded/live catalog; an unlisted id is forwarded as-is and the upstream decides |
14
14
  | Prefix-less models | Fallback not implemented | Fallback not implemented | Fallback not implemented |
15
15
  | Effort vocabulary | Codex catalog levels `low`..`ultra` | Claude Code `--effort` levels `low`..`max` | Catalog levels `low`, `medium`, `high`, `xhigh`; thinking-off is unverified and rejected |
16
16
  | Unsupported effort | Server drops it before the request; backend default applies | Server drops it; qgrid default `low` applies | Server drops it; catalog default applies |
@@ -25,7 +25,7 @@ Use this reference when comparing OpenAI, Anthropic, and Grok behavior, debuggin
25
25
  | Cost source | qgrid model price fallback | Prefer Claude Code `total_cost_usd`, else qgrid fallback | Provider ticks are authoritative; catalog-seeded fallback when ticks are absent |
26
26
  | Settings isolation | Per-token credentials in memory | Shared project cwd plus per-token `CLAUDE_CONFIG_DIR` | Per-token OAuth credentials and stable ids in memory |
27
27
  | Streaming close | `AbortSignal` cancels selection or active transport | Abort kills the fresh child process | `AbortSignal` cancels selection or active SSE; success requires `response.completed` |
28
- | Media/voice | OpenAI image routes only | Explicitly unsupported | Image generation/editing, async video URL jobs, STT, and TTS on `api.x.ai` |
28
+ | Media/voice | Standalone Codex Images, realtime STT/TTS, GPT-Live conversations, and native Decisions | Explicitly unsupported | Image generation/editing, async video URL jobs, STT, and TTS on `api.x.ai` |
29
29
 
30
30
  ## Routing contract
31
31
 
@@ -40,7 +40,7 @@ Candidate discovery is only a hint; each candidate is rechecked and finalized in
40
40
 
41
41
  ## Tool-call loop
42
42
 
43
- Since 2.10.0, the frame returns the parent `requestLogId` at the top level of successful query responses and stream `done` events, including terminal text responses. It retains the allocated ID if logging postprocessing fails after provider success. The field is absent with `logger: false`. Tool-run steps share the ID, while `runContext.requestLogId` remains reserved for continuing pending tool calls. SDK callers read `providerMetadata.qgrid.requestLogId`; streaming metadata becomes available at completion. Delta and error events are unchanged.
43
+ Since 2.10.0, the frame returns the parent `requestLogId` at the top level of successful query responses and stream `done` events, including terminal text responses. It retains the allocated ID if logging postprocessing fails after provider success. The field is absent with `logger: false`. Tool-run steps share the ID, while `runContext.requestLogId` remains reserved for continuing pending tool calls. SDK callers read `result.finalStep.providerMetadata.qgrid.requestLogId` (AI SDK 7 keeps top-level `providerMetadata` only as a deprecated alias); streaming metadata becomes available at completion. Delta and error events are unchanged.
44
44
 
45
45
  The AI SDK provider tracks pending tool-call IDs. When the next AI SDK call contains all required tool results, it sends the existing logging `runContext` when one was returned and sends the tool results. With `logger: false`, it still correlates the pending calls locally and continues the generation without a request-log id.
46
46
 
@@ -59,7 +59,7 @@ New request logs store routed model identity in the existing model fields; they
59
59
  - Public qgrid `QueryOutput.model` and AI SDK response model metadata continue to report the provider runtime model without changing their response contract. Do not copy that prefixless response value directly into server-native storage.
60
60
  - `createQgridLogger` combines the telemetry model provider and model id for the requested value, and qualifies the observed step/final response model with that provider. AI SDK adapter ids such as `openai.responses` and `anthropic.messages` are normalized to their base provider before storage. Avoid duplicating a prefix when the model id already starts with the same provider.
61
61
 
62
- This is a forward-only storage normalization. Do not backfill legacy prefixless rows, and do not invent a new `provider` column. Dashboard and query consumers must tolerate both legacy prefixless values and new prefixed values. Treat `status` as authoritative: a running row has no confirmed serving model, so the dashboard should render an explicit running state rather than a model placeholder or fallback display.
62
+ This is a forward-only storage normalization. Do not backfill legacy prefixless rows, and do not invent a new `provider` column. Dashboard and query consumers must tolerate both legacy prefixless values and new prefixed values. Treat `status` as authoritative: a running row may not have a confirmed serving model yet, so the dashboard shows the requested model (and the serving model once the provider reports it) with a running badge rather than treating the missing model as an error.
63
63
 
64
64
  Provider-qualified ids widen `model_name` and `requested_model_name` from 50 to 255 characters on both request-log entities. Generate and apply the normal Sonamu schema migration before running the new server. Do not hand-edit generated types, hand-author a derivable migration, or rewrite existing model values as part of that width migration.
65
65
 
@@ -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:
@@ -62,9 +62,9 @@ In 2.9.8, list and detail model labels show requested model to image model for g
62
62
 
63
63
  The list header ends its filter row with a reload button (2.10.2+) that calls the generated hooks' `refresh()` for the list and the total-cost query with the current filters; it does not refetch the token/project/model filter options, and TanStack Query's `isRefreshing` disables it while a reload is in flight.
64
64
 
65
- Structured output visibility: the list has an `Fmt` column (`voice/stt`, `voice/tts` or `voice/live` when `media_kind` is `stt`, `tts` or `live`, `video` when it is `video`, otherwise `img` when `is_image_generation` is true, otherwise `json` when `is_structured` is true, otherwise `text`) and a `broken` badge driven by `response_json_ok = false`; there is no broken-JSON list filter. At review time, all 114,647 succeeded structured rows had `response_json_ok = true` and zero false rows existed; the unindexed zero-result lookup scanned 1,286,016 rows and took about 3 seconds. Before reinstating the filter, validate the failure-signal semantics and index the predicate. The detail page shows a dark Response Type panel (zod expression by default, `type` declaration via toggle) rendered server-side from the stored `json_schema`. Plain-text rows render no panel. Rows written by pre-2.7.2 servers show `text`.
65
+ Structured output visibility: the list has an `Fmt` column (`voice/stt`, `voice/tts` or `voice/live` when `media_kind` is `stt`, `tts` or `live`, `video` when it is `video`, `decision` when it is `decision`, otherwise `img` when `is_image_generation` is true, otherwise `json` when `is_structured` is true, otherwise `text`) and a `broken` badge driven by `response_json_ok = false`; there is no broken-JSON list filter. At review time, all 114,647 succeeded structured rows had `response_json_ok = true` and zero false rows existed; the unindexed zero-result lookup scanned 1,286,016 rows and took about 3 seconds. Before reinstating the filter, validate the failure-signal semantics and index the predicate. The detail page shows a dark Response Type panel (zod expression by default, `type` declaration via toggle) rendered server-side from the stored `json_schema`. Plain-text rows render no panel. Rows written by pre-2.7.2 servers show `text`.
66
66
 
67
- Media rows (2.15.5+): `startMediaRun` writes the nullable `media_kind` column (`image`, `video`, `stt`, `tts`) at `createRun`; text runs keep it NULL, and media rows written before the column stay NULL and show their old `Fmt` label (no backfill). Speech rows store browser-playable audio (`audio/wav`, `audio/mpeg`) in `response` as `<audio src="data:...;base64,..."></audio>`, the same inline pattern image rows use, and the detail page renders it as an `<audio controls>` player; OpenAI `pcm` output is wrapped as WAV for the log copy only, while Grok `pcm`/`mulaw`/`alaw` keep the `[audio <mime> <bytes> bytes]` placeholder. The audio is stored once, not repeated in the `speech` step result. Speech `ttft_ms` is time to the first audio byte measured from the same start as `duration_ms`: the first `response.output_audio.delta` for OpenAI realtime, response-header arrival for Grok `/tts` (not streamed, so it is close to the full duration). `finishRun` takes an explicit `ttft_ms` for runs without generate steps and otherwise derives it from the first generate step. STT rows record no TTFT; since 2.16.0 their browser-playable input audio is embedded the same way in `user_prompt` (the detail page renders the USER panel through the same media parser), and other input types keep the placeholder. Inline audio grows the request-log table with every logged voice call; `logger: false` skips it. Voice step results keep word timing (`words`: TTS output words, or the words heard in the STT input; 2.17.0+). The detail page fetches that one step (subset `A`) only for `tts` rows and renders the RESPONSE clip with the shared `TimedPlayer` (highlighted, clickable words); `stt` rows show the input audio as a plain player (2.19.0+, by user decision 2026-11-09: timing on the user prompt read as wrong). `live` rows (2.19.2+) title the system prompt Instructions, hide the empty User panel, and show `response` as the Conversation; the Voice playground (`/voice?tab=tts|stt|live`, listed as TTS, STT and Live Conversation under Voice in the sidebar, with an in-page tab bar only on narrow screens; panels stay mounted so switching keeps state) runs Live Conversation on the browser's own `RTCPeerConnection` with an `oai-events` data channel, calls `QgridService.liveCall` with the offer, sends the chosen delegation model (any model the dashboard chat offers: both read `QGRID_MODEL_GROUPS` and the `Effort` enum from the synced `qgrid.types.ts`; the served list lives on the server, with the reasons retired ids are left out), effort and web search (disabled for `anthropic/`), a Request log toggle (off sends `logger: false`), a Continue button that starts a new session with the earlier history plus the last session's turns as `history` (shown dimmed above the new turns), builds its transcript from the data channel's `turn.*` events, and ends with `session.close` on that channel (see `openai-codex-runtime.md`).
67
+ Media rows (2.15.5+): `startMediaRun` writes the nullable `media_kind` column (`image`, `video`, `stt`, `tts`; `live` since 2.19.2 and `decision` since 2.22.0) at `createRun`; text runs keep it NULL, and media rows written before the column stay NULL and show their old `Fmt` label (no backfill). Speech rows store browser-playable audio (`audio/wav`, `audio/mpeg`) in `response` as `<audio src="data:...;base64,..."></audio>`, the same inline pattern image rows use, and the detail page renders it as an `<audio controls>` player; OpenAI `pcm` output is wrapped as WAV for the log copy only, while Grok `pcm`/`mulaw`/`alaw` keep the `[audio <mime> <bytes> bytes]` placeholder. The audio is stored once, not repeated in the `speech` step result. Speech `ttft_ms` is time to the first audio byte measured from the same start as `duration_ms`: the first `response.output_audio.delta` for OpenAI realtime, response-header arrival for Grok `/tts` (not streamed, so it is close to the full duration). `finishRun` takes an explicit `ttft_ms` for runs without generate steps and otherwise derives it from the first generate step. STT rows record no TTFT; since 2.16.0 their browser-playable input audio is embedded the same way in `user_prompt` (the detail page renders the USER panel through the same media parser), and other input types keep the placeholder. Inline audio grows the request-log table with every logged voice call; `logger: false` skips it. Voice step results keep word timing (`words`: TTS output words, or the words heard in the STT input; 2.17.0+). The detail page fetches that one step (subset `A`) only for `tts` rows and renders the RESPONSE clip with the shared `TimedPlayer` (highlighted, clickable words); `stt` rows show the input audio as a plain player (2.19.0+, by user decision 2026-11-09: timing on the user prompt read as wrong). `live` rows (2.19.2+) title the system prompt Instructions, hide the empty User panel, and show `response` as the Conversation; the Voice playground (`/voice?tab=tts|stt|live`, listed as TTS, STT and Live Conversation under Voice in the sidebar, with an in-page tab bar only on narrow screens; panels stay mounted so switching keeps state) runs Live Conversation on the browser's own `RTCPeerConnection` with an `oai-events` data channel, calls `QgridService.liveCall` with the offer, sends the chosen delegation model (any model the dashboard chat offers: both read `QGRID_MODEL_GROUPS` and the `Effort` enum from the synced `qgrid.types.ts`; the served list lives on the server, with the reasons retired ids are left out), effort and web search (disabled for `anthropic/`), a Request log toggle (off sends `logger: false`), a Continue button that starts a new session with the earlier history plus the last session's turns as `history` (shown dimmed above the new turns), builds its transcript from the data channel's `turn.*` events, and ends with `session.close` on that channel (see `openai-codex-runtime.md`).
68
68
 
69
69
  Voice playground (2.15.5+): the sidebar's Playground section links `/voice`, a dashboard-only test page with Text to speech and Speech to text panels that call the generated `QgridService.useSpeakMutation` / `useTranscribeMutation` with project name `qgrid_voice`; no API was added. Voice lists are web constants: OpenAI's 10 realtime presets and the 28 Grok `/tts` voices (9 female, 19 male) listed for the subscription token on 2026-11-06; the server still validates them. Instructions and the STT prompt are shown only for `openai/` models; in their place Grok TTS shows a Speed slider (0.7-1.5 in 0.05 steps, 2.18.0+), sent as `speed` only when it is not 1, and the history row title carries the speed. STT sends no `language`: a 2026-11-09 run (6 OpenAI STT models × auto/en/ko × 6 synthetic learner clips) found `en` no better than auto and `ko` translating English audio into Korean on gpt-4o-transcribe and whisper-1. The STT model list (2.20.0+, SON-593) is `openai/gpt-transcribe` (replacing `gpt-4o-transcribe`, which shuts down 2027-02-26) and `grok/grok-voice-transcribe-2.0`; the server still accepts the other ids. The page is one card with Text to speech / Speech to text tabs; both panels stay mounted (the inactive one is hidden) so form state and history survive tab switches. Each result is prepended to an in-memory history row (removable, lost on reload) with a request-log link that opens in a new tab so the history is kept. TTS voices are chips (Grok split Female/Male) above the text: a name selects the voice, and ▶ plays a bundled sample from `packages/web/public/voice-samples/{openai,grok}/<voice>.mp3` without a request (and selects it; pressing again stops). Each of the 38 samples introduces itself ("I'm <Voice>. Nice to meet you. How's it going?"), regenerated on 2026-11-09 through qgrid (`grok/grok-tts`, `openai/gpt-realtime-2.1-mini`) and checked with STT; re-encoded to 40 kbps mono MP3 (about 640 KB, shipped in the CLI bundle via `web-dist`). Do not trust the OpenAI speech self-transcript as a verbatim check: one ballad take carried an audible "Okay, let's read that line aloud exactly as written." preamble that two STT models heard while `response.output_audio_transcript.done` showed only the script. A voice added upstream needs a sample file or its ▶ fails to load. STT recordings and uploads are numbered clips so one clip run through several models reads as a comparison. A "Word timing" checkbox (default on, 2.17.0+) sends `withTimestamps`; TTS rows and STT rows with word timing (Grok, or OpenAI through the qgrid aligner, 2.19.0+) then render the clip with its words under the player (`TimedPlayer`), highlight the word being spoken (animation-frame polling with a `timeupdate` fallback when frames are throttled), and show the timing source (Grok TTS, qgrid aligner, or the failure). Clicking a word plays from its start. For OpenAI models, recordings (MediaRecorder webm/opus) and uploads are decoded with `AudioContext` at 24 kHz, mixed to mono, and sent as PCM16 WAV (`voice-audio.ts`), because the OpenAI transcription route accepts only WAV or raw PCM; Grok gets the original file (2.19.0+), which keeps a compressed upload far under the 19 MiB inline limit. Results link to their request log. Each panel (TTS, STT, Live Conversation) shows, beside it from 1280 px (below it when narrower), the `@cartanova/qgrid-ai-sdk` call for its current settings: its imports and the call (`generateSpeech`, `transcribe`, `experimental_useRealtime` plus the server `doCreateWebRTCSession`), in a separate card with a gap like the request log's columns (`voice-sdk-examples.ts`). The card is `CodePanel` (`components/qgrid/CodePanel.tsx`: dark highlighted block and copy button), which the request log's Response Type card (`ResponseTypeSection`) also uses; its highlighter covers server type/zod text and these examples (comments, `import`/`from`/`const`/`await` and `satisfies`, unless used as a property name).
70
70
 
@@ -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
 
@@ -223,10 +223,12 @@ On DELETE or missing row:
223
223
 
224
224
  OpenAI row changes:
225
225
 
226
- - active INSERT: `onTokenAdded` spawns workers.
226
+ - active INSERT: `onTokenAdded` adds the token to the pool (there are no workers to spawn).
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
 
@@ -125,7 +125,7 @@ AI SDK structured output:
125
125
  - `scripts/qgrid-structured-ai-sdk-smoke.ts`
126
126
  - Uses local `packages/ai-sdk/src/index`.
127
127
  - Env: `QGRID_URL`, `SMOKE_MODEL`, `SMOKE_CASES`, `SMOKE_REPEAT`.
128
- - Uses AI SDK 6 `streamText` with `Output.object`; useful for structured-output regressions.
128
+ - Uses AI SDK 7 `streamText` with `Output.object`; useful for structured-output regressions.
129
129
 
130
130
  AI SDK tools plus structured output:
131
131
 
@@ -198,7 +198,7 @@ Dashboard throws `Module "" has been externalized for browser compatibility. Can
198
198
 
199
199
  `Direct LLM API fallback not implemented`:
200
200
 
201
- - Model likely lacks `openai/` or `anthropic/` prefix.
201
+ - Model likely lacks the `openai/`, `anthropic/`, or `grok/` prefix.
202
202
  - Do not silently route prefix-less Claude model names to Anthropic.
203
203
 
204
204
  `No anthropic tokens available`:
@@ -227,7 +227,7 @@ Dashboard throws `Module "" has been externalized for browser compatibility. Can
227
227
 
228
228
  `image generation is not supported on the Anthropic route`:
229
229
 
230
- - Image generation is OpenAI/Codex-only.
230
+ - Image generation runs on OpenAI (`openai/gpt-image-2`) and Grok (`grok/grok-imagine-image*`) image models; the Anthropic route has none.
231
231
 
232
232
  `qgrid.image: expected one image from the direct subscription Images route`:
233
233