@cartanova/qgrid-cli 2.22.2 → 2.23.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 (77) hide show
  1. package/bundle/dist/application/qgrid/model-catalog.js +62 -0
  2. package/bundle/dist/application/qgrid/openai-compat.js +127 -0
  3. package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +2 -2
  4. package/bundle/dist/application/qgrid/qgrid.frame.js +204 -8
  5. package/bundle/dist/application/qgrid/qgrid.types.js +82 -2
  6. package/bundle/dist/application/qgrid/transcribe-stream.js +282 -0
  7. package/bundle/dist/application/queries.generated.js +2 -1
  8. package/bundle/dist/application/request-log/request-log.model.js +5 -4
  9. package/bundle/dist/server-error-handler.js +6 -3
  10. package/bundle/dist/sonamu.config.js +5 -2
  11. package/bundle/dist/utils/providers/anthropic/anthropic-constants.js +8 -2
  12. package/bundle/dist/utils/providers/anthropic/anthropic-quota.js +1 -1
  13. package/bundle/dist/utils/providers/common/model-cost.js +29 -2
  14. package/bundle/dist/utils/providers/openai/openai-dispatcher.js +9 -1
  15. package/bundle/dist/utils/providers/openai/openai-realtime-protocol.js +38 -6
  16. package/bundle/dist/utils/providers/openai/openai-voice-client.js +131 -3
  17. package/bundle/src/application/qgrid/model-catalog.test.ts +37 -0
  18. package/bundle/src/application/qgrid/model-catalog.ts +85 -0
  19. package/bundle/src/application/qgrid/openai-compat.test.ts +99 -0
  20. package/bundle/src/application/qgrid/openai-compat.ts +157 -0
  21. package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +1 -1
  22. package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +1 -1
  23. package/bundle/src/application/qgrid/qgrid.frame.test.ts +5 -0
  24. package/bundle/src/application/qgrid/qgrid.frame.ts +294 -0
  25. package/bundle/src/application/qgrid/qgrid.types.ts +134 -0
  26. package/bundle/src/application/qgrid/transcribe-stream.test.ts +165 -0
  27. package/bundle/src/application/qgrid/transcribe-stream.ts +381 -0
  28. package/bundle/src/application/queries.generated.ts +3 -0
  29. package/bundle/src/application/request-log/request-log.model.test.ts +4 -3
  30. package/bundle/src/application/request-log/request-log.model.ts +4 -3
  31. package/bundle/src/application/sonamu.generated.http +12 -0
  32. package/bundle/src/server-error-handler.ts +10 -7
  33. package/bundle/src/sonamu.config.ts +4 -0
  34. package/bundle/src/utils/providers/anthropic/anthropic-constants.test.ts +3 -0
  35. package/bundle/src/utils/providers/anthropic/anthropic-constants.ts +3 -1
  36. package/bundle/src/utils/providers/anthropic/anthropic-quota.ts +1 -1
  37. package/bundle/src/utils/providers/common/effort.test.ts +2 -0
  38. package/bundle/src/utils/providers/common/model-cost.test.ts +11 -0
  39. package/bundle/src/utils/providers/common/model-cost.ts +43 -5
  40. package/bundle/src/utils/providers/openai/openai-dispatcher.ts +15 -0
  41. package/bundle/src/utils/providers/openai/openai-realtime-protocol.ts +46 -5
  42. package/bundle/src/utils/providers/openai/openai-voice-client.test.ts +89 -2
  43. package/bundle/src/utils/providers/openai/openai-voice-client.ts +188 -0
  44. package/bundle/web-dist/client/assets/index-CtkfXtee.js +104 -0
  45. package/bundle/web-dist/client/assets/logs-C_U9lGtE.js +1 -0
  46. package/bundle/web-dist/client/assets/{monit-0qjGcPcD.js → monit-CNQyE4bk.js} +1 -1
  47. package/bundle/web-dist/client/assets/{routes-D53FyOOp.js → routes-72N6ogd2.js} +2 -2
  48. package/bundle/web-dist/client/assets/{settings-Cbz57odO.js → settings-DbwnDBrc.js} +1 -1
  49. package/bundle/web-dist/client/assets/{show-Boi25Rbi.js → show-BPkKGDnC.js} +2 -2
  50. package/bundle/web-dist/client/assets/tokens-2ig4rFfF.js +1 -0
  51. package/bundle/web-dist/client/assets/{use-oauth-login-flow-CjFv4NI0.js → use-oauth-login-flow-CvjEVH_T.js} +1 -1
  52. package/bundle/web-dist/client/assets/use-update-token-mutation-C8viUPmK.js +1 -0
  53. package/bundle/web-dist/client/assets/{voice-BDO8X2H0.js → voice-D2RSPjn9.js} +2 -2
  54. package/bundle/web-dist/client/index.html +1 -1
  55. package/bundle/web-dist/server/assets/{TimedPlayer-mpJpP5tQ.js → TimedPlayer-B9ds1sqM.js} +1 -1
  56. package/bundle/web-dist/server/assets/{logs-CFa_xamY.js → logs-JziKvWBp.js} +3 -3
  57. package/bundle/web-dist/server/assets/{monit-BF6osfj5.js → monit-CzjNOowb.js} +2 -2
  58. package/bundle/web-dist/server/assets/{plus-DwQFfeid.js → plus-BrRDgdaN.js} +1 -1
  59. package/bundle/web-dist/server/assets/{refresh-cw-Bj-Jxeb6.js → refresh-cw-wU5-wVTi.js} +1 -1
  60. package/bundle/web-dist/server/assets/{request-model-D_iYrudl.js → request-model-D07WSRKx.js} +1 -1
  61. package/bundle/web-dist/server/assets/{routes-B6be8sJP.js → routes-C1tDj0QN.js} +3 -3
  62. package/bundle/web-dist/server/assets/{services.generated-D0995hJr.js → services.generated-rlOX8J2n.js} +201 -0
  63. package/bundle/web-dist/server/assets/{settings-DAle7AgI.js → settings-DJQUI8bU.js} +3 -3
  64. package/bundle/web-dist/server/assets/{show-BTSdMDoM.js → show-BElTj6MG.js} +3 -3
  65. package/bundle/web-dist/server/assets/{tokens-Bc9flfLz.js → tokens-CRpUPv-5.js} +4 -4
  66. package/bundle/web-dist/server/assets/{use-oauth-login-flow-C7c0gCjf.js → use-oauth-login-flow-DLRPNhNE.js} +1 -1
  67. package/bundle/web-dist/server/assets/{use-update-token-mutation-DLJDGdxu.js → use-update-token-mutation-DJkct-j8.js} +1 -1
  68. package/bundle/web-dist/server/assets/{voice-CEQT57xZ.js → voice-BZBlBBpn.js} +4 -10
  69. package/bundle/web-dist/server/entry-server.generated.js +118 -26
  70. package/package.json +1 -1
  71. package/skills/qgrid/references/anthropic-claude-code-runtime.md +4 -3
  72. package/skills/qgrid/references/openai-codex-runtime.md +29 -10
  73. package/skills/qgrid/references/sonamu-api-web-flow.md +1 -1
  74. package/bundle/web-dist/client/assets/index-CiSsWsVT.js +0 -104
  75. package/bundle/web-dist/client/assets/logs-Bir9gDzp.js +0 -1
  76. package/bundle/web-dist/client/assets/tokens-BuK8BpAd.js +0 -1
  77. package/bundle/web-dist/client/assets/use-update-token-mutation-BKufO9oe.js +0 -1
@@ -0,0 +1,99 @@
1
+ import { describe, expect, it } from "vitest";
2
+
3
+ import {
4
+ ChatCompletionRequest,
5
+ ChatCompletionRequestError,
6
+ toChatCompletion,
7
+ toQueryInput,
8
+ } from "./openai-compat";
9
+ import { type QueryOutput } from "./qgrid.types";
10
+
11
+ const parse = (body: object) => ChatCompletionRequest.parse(body);
12
+
13
+ describe("toQueryInput", () => {
14
+ it("maps system and the last user message, ignoring sampling options", () => {
15
+ const input = toQueryInput(parse({
16
+ model: "openai/gpt-5.4",
17
+ messages: [
18
+ { role: "system", content: "summarize" },
19
+ { role: "user", content: "transcript" },
20
+ ],
21
+ temperature: 0.3,
22
+ max_tokens: 10,
23
+ }));
24
+
25
+ expect(input).toEqual({
26
+ model: "openai/gpt-5.4",
27
+ system: "summarize",
28
+ prompt: "transcript",
29
+ projectName: "openai-compat",
30
+ });
31
+ });
32
+
33
+ it("replays earlier turns as Responses-style history and joins text parts", () => {
34
+ const input = toQueryInput(
35
+ parse({
36
+ model: "openai/m",
37
+ messages: [
38
+ { role: "user", content: "a" },
39
+ { role: "assistant", content: "b" },
40
+ { role: "user", content: [{ type: "text", text: "c" }, { type: "text", text: "d" }] },
41
+ ],
42
+ }),
43
+ "meetily",
44
+ );
45
+
46
+ expect(input.prompt).toBe("cd");
47
+ expect(input.projectName).toBe("meetily");
48
+ expect(JSON.parse(input.history ?? "")).toEqual([
49
+ { type: "message", role: "user", content: [{ type: "input_text", text: "a" }] },
50
+ { type: "message", role: "assistant", content: [{ type: "output_text", text: "b" }] },
51
+ ]);
52
+ });
53
+
54
+ it.each([
55
+ ["stream", { stream: true }],
56
+ ["tools", { tools: [{ type: "function" }] }],
57
+ ["tool messages", { messages: [{ role: "tool", content: "x" }] }],
58
+ ["trailing assistant", { messages: [{ role: "assistant", content: "x" }] }],
59
+ ])("rejects %s", (_name, overrides) => {
60
+ const body = parse({ model: "openai/m", messages: [{ role: "user", content: "hi" }], ...overrides });
61
+
62
+ expect(() => toQueryInput(body)).toThrow(ChatCompletionRequestError);
63
+ });
64
+
65
+ it.each([
66
+ ["image parts", { messages: [{ role: "user", content: [{ type: "image_url" }] }] }],
67
+ ["empty model", { model: "" }],
68
+ ["prefix-less model", { model: "claude-opus-5-5" }],
69
+ ])("schema rejects %s", (_name, overrides) => {
70
+ const body = { model: "openai/m", messages: [{ role: "user", content: "hi" }], ...overrides };
71
+
72
+ expect(ChatCompletionRequest.safeParse(body).success).toBe(false);
73
+ });
74
+ });
75
+
76
+ describe("toChatCompletion", () => {
77
+ it("wraps text and folds cached input into prompt_tokens", () => {
78
+ const result = {
79
+ requestLogId: 42,
80
+ text: "summary",
81
+ model: "openai/gpt-5.4",
82
+ usage: {
83
+ input_tokens: 10,
84
+ output_tokens: 5,
85
+ reasoning_tokens: 0,
86
+ cache_creation_input_tokens: 2,
87
+ cache_read_input_tokens: 3,
88
+ },
89
+ } as QueryOutput;
90
+
91
+ expect(toChatCompletion(result, "requested")).toMatchObject({
92
+ id: "chatcmpl-42",
93
+ object: "chat.completion",
94
+ model: "openai/gpt-5.4",
95
+ choices: [{ message: { role: "assistant", content: "summary" }, finish_reason: "stop" }],
96
+ usage: { prompt_tokens: 15, completion_tokens: 5, total_tokens: 20 },
97
+ });
98
+ });
99
+ });
@@ -0,0 +1,157 @@
1
+ import { getLogger } from "@logtape/logtape";
2
+ import { type FastifyReply, type FastifyRequest } from "fastify";
3
+ import { z } from "zod";
4
+
5
+ import { errorStatusCode } from "../../server-error-handler";
6
+ import { QgridFrame } from "./qgrid.frame";
7
+ import { type QueryInput, type QueryOutput } from "./qgrid.types";
8
+
9
+ // OpenAI Chat Completions compatibility for third-party apps (e.g. Meetily) that only accept an
10
+ // OpenAI-compatible base URL. Scope: non-streaming text. Streaming, tools and images are rejected
11
+ // explicitly so callers do not mistake silent drops for model behavior.
12
+
13
+ const DEFAULT_PROJECT_NAME = "openai-compat";
14
+
15
+ // Only text parts are accepted; image or audio parts fail parsing with a 400.
16
+ const TextPart = z.object({ type: z.literal("text"), text: z.string() });
17
+
18
+ const MessageContent = z
19
+ .union([z.string(), z.array(TextPart).transform((parts) => parts.map((p) => p.text).join(""))])
20
+ .nullish()
21
+ .transform((content) => content ?? "");
22
+
23
+ const ChatMessage = z.looseObject({
24
+ role: z.enum(["system", "developer", "user", "assistant", "tool"]),
25
+ content: MessageContent,
26
+ tool_calls: z.array(z.unknown()).optional(),
27
+ });
28
+
29
+ // Sampling options (temperature, top_p, max_tokens, ...) pass through looseObject and are ignored:
30
+ // qgrid has no matching inputs, and rejecting them would break most clients.
31
+ export const ChatCompletionRequest = z.looseObject({
32
+ // Prefix-less names fall through to the OpenAI runtime and fail upstream with a misleading 500.
33
+ model: z
34
+ .string()
35
+ .regex(/^[a-z]+\/.+/, "use a provider-prefixed qgrid model, e.g. anthropic/claude-opus-5-5"),
36
+ messages: z.array(ChatMessage).min(1),
37
+ stream: z.boolean().optional(),
38
+ tools: z.array(z.unknown()).optional(),
39
+ });
40
+
41
+ export type ChatCompletionRequest = z.infer<typeof ChatCompletionRequest>;
42
+
43
+ const RequestHeaders = z.looseObject({ "x-qgrid-project": z.string().optional() });
44
+
45
+ export class ChatCompletionRequestError extends Error {}
46
+
47
+ export function toQueryInput(req: ChatCompletionRequest, projectName?: string): QueryInput {
48
+ if (req.stream) throw new ChatCompletionRequestError("stream: true is not supported");
49
+
50
+ if (req.tools?.length) throw new ChatCompletionRequestError("tools are not supported");
51
+
52
+ const systemParts: string[] = [];
53
+ const turns: Array<{ role: "user" | "assistant"; text: string }> = [];
54
+
55
+ for (const message of req.messages) {
56
+ if (message.role === "tool" || message.tool_calls?.length) {
57
+ throw new ChatCompletionRequestError("tool messages are not supported");
58
+ }
59
+
60
+ if (message.role === "system" || message.role === "developer") {
61
+ systemParts.push(message.content);
62
+ } else {
63
+ turns.push({ role: message.role, text: message.content });
64
+ }
65
+ }
66
+
67
+ const last = turns.pop();
68
+
69
+ if (last?.role !== "user") {
70
+ throw new ChatCompletionRequestError("the last non-system message must be from the user");
71
+ }
72
+
73
+ // Same Responses-style items the AI SDK provider replays as `history`.
74
+ const history = turns.map((turn) =>
75
+ turn.role === "user"
76
+ ? { type: "message", role: "user", content: [{ type: "input_text", text: turn.text }] }
77
+ : { type: "message", role: "assistant", content: [{ type: "output_text", text: turn.text }] },
78
+ );
79
+
80
+ const input: QueryInput = {
81
+ model: req.model,
82
+ prompt: last.text,
83
+ projectName: projectName || DEFAULT_PROJECT_NAME,
84
+ };
85
+
86
+ if (systemParts.length > 0) input.system = systemParts.join("\n\n");
87
+
88
+ if (history.length > 0) input.history = JSON.stringify(history);
89
+
90
+ return input;
91
+ }
92
+
93
+ export function toChatCompletion(result: QueryOutput, requestedModel: string) {
94
+ const { usage } = result;
95
+
96
+ const promptTokens =
97
+ usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens;
98
+
99
+ return {
100
+ id: `chatcmpl-${result.requestLogId ?? crypto.randomUUID()}`,
101
+ object: "chat.completion",
102
+ created: Math.floor(Date.now() / 1000),
103
+ model: result.model ?? requestedModel,
104
+ choices: [
105
+ {
106
+ index: 0,
107
+ message: { role: "assistant", content: result.text },
108
+ finish_reason: "stop",
109
+ },
110
+ ],
111
+ usage: {
112
+ prompt_tokens: promptTokens,
113
+ completion_tokens: usage.output_tokens,
114
+ total_tokens: promptTokens + usage.output_tokens,
115
+ },
116
+ };
117
+ }
118
+
119
+ function sendError(reply: FastifyReply, status: number, message: string) {
120
+ const type = status < 500 ? "invalid_request_error" : "server_error";
121
+
122
+ return reply.status(status).send({ error: { message, type, code: null } });
123
+ }
124
+
125
+ // ponytail: calls QgridFrame.query outside Sonamu's HTTP context, so a client disconnect does not
126
+ // abort the provider call and 429 Retry-After headers are not set. Fix when adding streaming.
127
+ export async function chatCompletionsHandler(request: FastifyRequest, reply: FastifyReply) {
128
+ const parsed = ChatCompletionRequest.safeParse(request.body);
129
+
130
+ if (!parsed.success) {
131
+ const issue = parsed.error.issues[0];
132
+
133
+ return sendError(reply, 400, `invalid request at ${issue?.path.join(".")}: ${issue?.message}`);
134
+ }
135
+
136
+ const projectName = RequestHeaders.safeParse(request.headers).data?.["x-qgrid-project"];
137
+ let input: QueryInput;
138
+
139
+ try {
140
+ input = toQueryInput(parsed.data, projectName);
141
+ } catch (e) {
142
+ if (e instanceof ChatCompletionRequestError) return sendError(reply, 400, e.message);
143
+
144
+ throw e;
145
+ }
146
+
147
+ try {
148
+ const result = await QgridFrame.query(input);
149
+
150
+ return reply.send(toChatCompletion(result, input.model ?? ""));
151
+ } catch (e) {
152
+ const error = e instanceof Error ? e : new Error(String(e));
153
+ getLogger(["qgrid", "openai-compat"]).error(`${error}`);
154
+
155
+ return sendError(reply, errorStatusCode(error), error.message);
156
+ }
157
+ }
@@ -293,7 +293,7 @@ describe("qgrid run lifecycle start", () => {
293
293
 
294
294
  expect(expireStaleLiveRunsMock).toHaveBeenCalledWith(
295
295
  new Date(lifecycleNow - (2 * 60 + 15) * 60 * 1000),
296
- "live session: the server stopped before the session ended",
296
+ "live session or transcription stream: the server stopped before it ended",
297
297
  );
298
298
  });
299
299
 
@@ -421,7 +421,7 @@ async function performStaleRunCleanup(): Promise<void> {
421
421
 
422
422
  const liveCount = await RequestLogModel.expireStaleLiveRuns(
423
423
  new Date(Date.now() - STALE_LIVE_RUN_THRESHOLD_MS),
424
- "live session: the server stopped before the session ended",
424
+ "live session or transcription stream: the server stopped before it ended",
425
425
  );
426
426
 
427
427
  const cleanedCount = staleIds.length + liveCount;
@@ -2674,6 +2674,11 @@ describe("QgridFrame Grok media and voice (U11)", () => {
2674
2674
  await expect(QgridFrame.liveCall({ sdp: "v=0", history: tooLong })).rejects.toMatchObject({
2675
2675
  statusCode: 400,
2676
2676
  });
2677
+ // The instructions take one initial item, so with them 128 history items are too many.
2678
+ const full = tooLong.slice(1);
2679
+ await expect(
2680
+ QgridFrame.liveCall({ sdp: "v=0", instructions: "Be brief.", history: full }),
2681
+ ).rejects.toMatchObject({ statusCode: 400 });
2677
2682
  });
2678
2683
 
2679
2684
  it("tells the voice when a delegation fails instead of leaving it waiting", async () => {
@@ -13,6 +13,8 @@ import {
13
13
  SoException,
14
14
  Sonamu,
15
15
  stream,
16
+ websocket,
17
+ type WebSocketContext,
16
18
  } from "sonamu";
17
19
  import { getCacheManagerRef } from "sonamu/cache";
18
20
  import { z } from "zod";
@@ -102,6 +104,7 @@ import {
102
104
  type OpenAILiveDelegation,
103
105
  type OpenAILiveSummary,
104
106
  type OpenAILiveTurn,
107
+ OPENAI_STREAM_DEFAULT_TRANSCRIPTION_MODEL,
105
108
  OpenAIVoiceInputError,
106
109
  } from "../../utils/providers/openai/openai-voice-client";
107
110
  import { alignSpeech } from "../../utils/speech-aligner";
@@ -114,6 +117,8 @@ import {
114
117
  } from "../request-log/request-log.model";
115
118
  import { type HistoryItems, type RequestLogListParams } from "../request-log/request-log.types";
116
119
  import { type TokenSubsetA } from "../sonamu.generated";
120
+ import { buildModelCatalog } from "./model-catalog";
121
+ import { type StreamOutEvent, TranscribeStreamSession } from "./transcribe-stream";
117
122
 
118
123
  /** Fields token refresh reads; dispatchers pass their pooled view of a token. */
119
124
  type RefreshableToken = Pick<TokenSubsetA, "id" | "name" | "provider" | "credentials">;
@@ -156,6 +161,9 @@ import {
156
161
  GenerateImagesInput,
157
162
  type GenerateImagesOutput,
158
163
  LiveCallInput,
164
+ TranscribeStreamInEvents,
165
+ TranscribeStreamOutEvents,
166
+ TranscribeStreamStart,
159
167
  type LiveCallOutput,
160
168
  type LiveHistoryItem,
161
169
  OpenAIDecisionRequest,
@@ -170,6 +178,7 @@ import {
170
178
  type GrokDeviceCodeStart,
171
179
  type GrokDevicePollResult,
172
180
  type HealthResponse,
181
+ type ModelCatalog,
173
182
  type OAuthStartResult,
174
183
  type QueryOutput,
175
184
  type QgridRunContext,
@@ -1565,6 +1574,146 @@ async function finishLiveRun(run: LiveRun, summary: OpenAILiveSummary): Promise<
1565
1574
  }
1566
1575
  }
1567
1576
 
1577
+ /** Streams end themselves at two hours, under the live stale sweep threshold for running stt rows. */
1578
+ const TRANSCRIBE_STREAM_MAX_MS = 2 * 60 * 60 * 1000;
1579
+
1580
+ type TranscribeStreamRun = {
1581
+ session: TranscribeStreamSession;
1582
+ route: string;
1583
+ model: string;
1584
+ sampleRate: number;
1585
+ input: TranscribeStreamStart;
1586
+ /** The token of the most recent (re)open. */
1587
+ token: { name: string };
1588
+ requestLogId: number | undefined;
1589
+ startedAt: number;
1590
+ finished: boolean;
1591
+ timer?: NodeJS.Timeout;
1592
+ };
1593
+
1594
+ async function startTranscribeStream(
1595
+ params: TranscribeStreamStart,
1596
+ publish: (out: StreamOutEvent) => void,
1597
+ ): Promise<TranscribeStreamRun> {
1598
+ const input = parseMediaInput(TranscribeStreamStart, params);
1599
+ const dispatcher = openaiVoice();
1600
+ const selection = await resolveMediaTokenSelection("openai", input.tokenName);
1601
+
1602
+ const { id, route } = routeProviderModelId(
1603
+ "openai",
1604
+ input.model,
1605
+ OPENAI_STREAM_DEFAULT_TRANSCRIPTION_MODEL,
1606
+ );
1607
+
1608
+ const requestLogId = await startMediaRun(input.logger, {
1609
+ kind: "stt",
1610
+ model: route,
1611
+ prompt: "",
1612
+ systemPrompt: input.prompt,
1613
+ projectName: input.projectName,
1614
+ });
1615
+
1616
+ const token = { name: "" };
1617
+
1618
+ // Every (re)open picks a token the usual way and refreshes a 401 once.
1619
+ const session = new TranscribeStreamSession(async (onEvent) => {
1620
+ const opened = await dispatcher.startTranscriptionStream({
1621
+ model: id,
1622
+ language: input.language,
1623
+ prompt: input.prompt,
1624
+ onEvent,
1625
+ ...selection,
1626
+ });
1627
+
1628
+ token.name = opened.tokenName;
1629
+
1630
+ return opened.result;
1631
+ }, publish);
1632
+
1633
+ const run: TranscribeStreamRun = {
1634
+ session,
1635
+ route,
1636
+ model: id,
1637
+ sampleRate: input.sampleRate,
1638
+ input,
1639
+ token,
1640
+ requestLogId,
1641
+ startedAt: Date.now(),
1642
+ finished: false,
1643
+ };
1644
+
1645
+ try {
1646
+ await run.session.start();
1647
+ } catch (e) {
1648
+ await failMediaRun(requestLogId, e, false);
1649
+ throw e instanceof OpenAIVoiceInputError
1650
+ ? new BadRequestException(SD("qgrid.invalidInput")(e.message))
1651
+ : e;
1652
+ }
1653
+
1654
+ return run;
1655
+ }
1656
+
1657
+ async function finishTranscribeStream(
1658
+ run: TranscribeStreamRun,
1659
+ publishDone:
1660
+ | ((done: { audioMs: number; segments: number; requestLogId?: number }) => void)
1661
+ | undefined,
1662
+ ): Promise<void> {
1663
+ if (run.finished) return;
1664
+ run.finished = true;
1665
+ clearTimeout(run.timer);
1666
+
1667
+ if (publishDone) await run.session.stop();
1668
+ else run.session.abort();
1669
+
1670
+ const audioMs = Math.round(run.session.audioMs);
1671
+ const segments = run.session.segments;
1672
+ publishDone?.({
1673
+ audioMs,
1674
+ segments: segments.length,
1675
+ ...(run.requestLogId !== undefined && { requestLogId: run.requestLogId }),
1676
+ });
1677
+
1678
+ if (run.requestLogId === undefined) return;
1679
+
1680
+ if (!run.token.name) {
1681
+ await failMediaRun(
1682
+ run.requestLogId,
1683
+ new Error("stream ended before the upstream opened"),
1684
+ true,
1685
+ );
1686
+
1687
+ return;
1688
+ }
1689
+
1690
+ await finishMediaRun(run.requestLogId, {
1691
+ kind: "stt",
1692
+ model: run.route,
1693
+ tokenName: run.token.name,
1694
+ durationMs: Date.now() - run.startedAt,
1695
+ response: segments.map((s) => s.text).join("\n"),
1696
+ cost: sttCost(run.route, audioMs / 1000),
1697
+ steps: [
1698
+ {
1699
+ toolCallId: "transcription:stream",
1700
+ args: {
1701
+ kind: "stt",
1702
+ model: run.route,
1703
+ transport: "realtime-ws-stream",
1704
+ sampleRate: run.sampleRate,
1705
+ language: run.input.language,
1706
+ prompt: run.input.prompt,
1707
+ audioMs,
1708
+ segments: segments.length,
1709
+ endedBy: publishDone ? "stop" : "disconnect",
1710
+ },
1711
+ result: JSON.stringify({ segments }),
1712
+ },
1713
+ ],
1714
+ });
1715
+ }
1716
+
1568
1717
  class QgridFrameClass extends BaseFrameClass {
1569
1718
  constructor() {
1570
1719
  super("Qgrid");
@@ -2761,6 +2910,15 @@ class QgridFrameClass extends BaseFrameClass {
2761
2910
  @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })
2762
2911
  async liveCall(params: LiveCallInput): Promise<LiveCallOutput> {
2763
2912
  const input = parseMediaInput(LiveCallInput, params);
2913
+
2914
+ // The instructions also go out as the first initial item (buildLiveSession), so with them the
2915
+ // caller's history may take one item fewer than OpenAI's 128.
2916
+ if (input.instructions && (input.history?.length ?? 0) > 127) {
2917
+ throw new BadRequestException(
2918
+ SD("qgrid.invalidInput")("history holds at most 127 items when instructions are set"),
2919
+ );
2920
+ }
2921
+
2764
2922
  const dispatcher = openaiVoice();
2765
2923
  const selection = await resolveMediaTokenSelection("openai", input.tokenName);
2766
2924
  const voice = input.voice ?? OPENAI_LIVE_DEFAULT_VOICE;
@@ -2859,6 +3017,128 @@ class QgridFrameClass extends BaseFrameClass {
2859
3017
  return output;
2860
3018
  }
2861
3019
 
3020
+ // Streaming speech-to-text (openai/ only). The client sends start, then ~100 ms PCM frames,
3021
+ // and gets text deltas while a segment is spoken and a segment event when it ends. One request
3022
+ // log row covers the whole stream; it is written when the stream ends.
3023
+ @websocket({
3024
+ outEvents: TranscribeStreamOutEvents,
3025
+ inEvents: TranscribeStreamInEvents,
3026
+ heartbeat: 20_000,
3027
+ description: "Streams microphone audio and returns live transcript deltas and segments.",
3028
+ })
3029
+ async transcribeStream(
3030
+ ctx: WebSocketContext<TranscribeStreamOutEvents, TranscribeStreamInEvents>,
3031
+ ): Promise<void> {
3032
+ const ws = ctx.ws;
3033
+ let run: TranscribeStreamRun | undefined;
3034
+ let startAttempted = false;
3035
+ let closed = false;
3036
+
3037
+ // Events can still arrive from the upstream pump after the client left; never throw there.
3038
+ const publish: typeof ws.publish = (event, data) => {
3039
+ if (closed) return;
3040
+
3041
+ try {
3042
+ ws.publish(event, data);
3043
+ } catch (e) {
3044
+ mediaLogger.warn(
3045
+ `transcribeStream publish failed: ${e instanceof Error ? e.message : String(e)}`,
3046
+ );
3047
+ }
3048
+ };
3049
+
3050
+ const end = async (withDone: boolean) => {
3051
+ if (!run || run.finished) return;
3052
+ await finishTranscribeStream(run, withDone ? (done) => publish("done", done) : undefined);
3053
+
3054
+ if (!closed) ws.close();
3055
+ };
3056
+
3057
+ // Handlers run in arrival order; audio frames must reach the upstream in that order too.
3058
+ let queue: Promise<void> = Promise.resolve();
3059
+
3060
+ const serial = (task: () => Promise<void>) => {
3061
+ queue = queue.then(task).catch((e) => {
3062
+ mediaLogger.error(`transcribeStream: ${e instanceof Error ? e.message : String(e)}`);
3063
+ publish("error", { message: e instanceof Error ? e.message : String(e), fatal: false });
3064
+ });
3065
+ };
3066
+
3067
+ ws.onMessage("start", (input) =>
3068
+ serial(async () => {
3069
+ if (startAttempted) return;
3070
+ startAttempted = true;
3071
+
3072
+ try {
3073
+ run = await startTranscribeStream(input, (out) => {
3074
+ if (out.event === "delta") publish("delta", out.data);
3075
+ else if (out.event === "segment") publish("segment", out.data);
3076
+ else {
3077
+ publish("error", out.data);
3078
+
3079
+ // The session gave up (reconnect failed); finish with what was transcribed.
3080
+ if (out.data.fatal) serial(() => end(true));
3081
+ }
3082
+ });
3083
+ } catch (e) {
3084
+ publish("error", { message: e instanceof Error ? e.message : String(e), fatal: true });
3085
+
3086
+ if (!closed) ws.close();
3087
+
3088
+ return;
3089
+ }
3090
+
3091
+ // The client left while the upstream was opening: close it now rather than at 2 hours.
3092
+ if (closed) {
3093
+ await end(false);
3094
+
3095
+ return;
3096
+ }
3097
+
3098
+ publish("ready", {
3099
+ model: run.route,
3100
+ tokenName: run.token.name,
3101
+ ...(run.requestLogId !== undefined && { requestLogId: run.requestLogId }),
3102
+ });
3103
+ run.timer = setTimeout(() => {
3104
+ publish("error", { message: "stream reached the 2 hour limit", fatal: true });
3105
+ serial(() => end(true));
3106
+ }, TRANSCRIBE_STREAM_MAX_MS);
3107
+ }),
3108
+ );
3109
+
3110
+ ws.onMessage("audio", ({ pcm }) =>
3111
+ serial(async () => {
3112
+ if (!run) throw new Error("send start before audio");
3113
+
3114
+ if (run.finished) return;
3115
+ // Copy into a fresh buffer: Buffer.from(base64) may sit at an odd pool offset, which an
3116
+ // Int16Array view cannot start at.
3117
+ const bytes = Buffer.from(pcm, "base64");
3118
+ const samples = new Int16Array(Math.floor(bytes.byteLength / 2));
3119
+ new Uint8Array(samples.buffer).set(bytes.subarray(0, samples.byteLength));
3120
+ await run.session.audio(samples, run.sampleRate);
3121
+ }),
3122
+ );
3123
+
3124
+ ws.onMessage("commit", () =>
3125
+ serial(async () => {
3126
+ if (run && !run.finished) await run.session.commit();
3127
+ }),
3128
+ );
3129
+
3130
+ ws.onMessage("stop", () => serial(() => end(true)));
3131
+
3132
+ ws.onClose(() => {
3133
+ closed = true;
3134
+
3135
+ // A client that leaves without stop still gets its stream logged with what was transcribed.
3136
+ if (run && !run.finished) void finishTranscribeStream(run, undefined);
3137
+ });
3138
+
3139
+ await ws.waitForClose();
3140
+ }
3141
+
2862
3142
  @api({ httpMethod: "GET", clients: ["axios", "tanstack-query"] })
2863
3143
  async usage(tokenId?: number): Promise<UsageResponse> {
2864
3144
  const { rows: allTokens } = await TokenModel.findMany("A");
@@ -3050,6 +3330,20 @@ class QgridFrameClass extends BaseFrameClass {
3050
3330
  providers,
3051
3331
  };
3052
3332
  }
3333
+
3334
+ // Models by task with prices and capabilities; `available` means the provider has started and
3335
+ // holds an active token, so a request would be routed now.
3336
+ @api({ httpMethod: "GET", clients: ["axios", "tanstack-query"] })
3337
+ async models(): Promise<ModelCatalog> {
3338
+ const withTokens = new Set([...QgridDispatcher.tokens.values()].map((t) => t.provider));
3339
+
3340
+ return buildModelCatalog(
3341
+ (provider) =>
3342
+ isProviderId(provider) &&
3343
+ QgridDispatcher.dispatchers.has(provider) &&
3344
+ withTokens.has(provider),
3345
+ );
3346
+ }
3053
3347
  }
3054
3348
 
3055
3349
  export const QgridFrame = new QgridFrameClass();