@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,381 @@
1
+ import {
2
+ OPENAI_REALTIME_SAMPLE_RATE,
3
+ resampleLinear,
4
+ } from "../../utils/providers/openai/openai-realtime-protocol";
5
+ import {
6
+ type OpenAITranscriptionStream,
7
+ type OpenAITranscriptionStreamEvent,
8
+ } from "../../utils/providers/openai/openai-voice-client";
9
+
10
+ const RATE = OPENAI_REALTIME_SAMPLE_RATE;
11
+ const ms = (samples: number) => (samples / RATE) * 1000;
12
+
13
+ export type CommitPolicyOptions = {
14
+ /** Speech needed in a segment before a pause may end it. */
15
+ minSpeechMs: number;
16
+ /** Quiet that ends a segment once it has enough speech. */
17
+ pauseMs: number;
18
+ /** Quiet that ends a segment with any speech at all, so a short tail does not wait for the cap. */
19
+ longPauseMs: number;
20
+ /** Segment length that forces a commit even mid-speech. gpt-live-transcribe reads only about the
21
+ * first 30 s of one committed buffer. */
22
+ maxMs: number;
23
+ /** Quiet-only audio after which the buffer is cleared instead of committed. */
24
+ idleMs: number;
25
+ /** Frame RMS (0..1) below which a frame counts as quiet. */
26
+ silenceRms: number;
27
+ };
28
+
29
+ export const DEFAULT_COMMIT_POLICY: CommitPolicyOptions = {
30
+ minSpeechMs: 1500,
31
+ pauseMs: 600,
32
+ longPauseMs: 2000,
33
+ maxMs: 20_000,
34
+ // Short, so leading quiet neither eats into maxMs nor shifts the segment start (probe 2026-11-18:
35
+ // a 5 s idle window let 3 s of lead-in push a sentence past the cap).
36
+ idleMs: 1000,
37
+ silenceRms: 0.01,
38
+ };
39
+
40
+ export type CommitDecision = "none" | "commit" | "clear";
41
+
42
+ /**
43
+ * gpt-live-transcribe rejects server VAD, so the server decides where segments end: after a pause
44
+ * that follows enough speech, or at the length cap. A buffer holding only quiet is cleared rather
45
+ * than committed so that it neither costs a transcript nor pushes later speech past the model's
46
+ * first-30-seconds window.
47
+ */
48
+ export class CommitPolicy {
49
+ private segmentSamples = 0;
50
+ private speechSamples = 0;
51
+ private quietRun = 0;
52
+ private readonly options: CommitPolicyOptions;
53
+
54
+ constructor(options: Partial<CommitPolicyOptions> = {}) {
55
+ this.options = { ...DEFAULT_COMMIT_POLICY, ...options };
56
+ }
57
+
58
+ get hasSpeech(): boolean {
59
+ return this.speechSamples > 0;
60
+ }
61
+
62
+ push(samples: Int16Array): CommitDecision {
63
+ let sq = 0;
64
+
65
+ for (const v of samples) sq += (v / 32768) ** 2;
66
+ const quiet = Math.sqrt(sq / Math.max(1, samples.length)) < this.options.silenceRms;
67
+ this.segmentSamples += samples.length;
68
+ this.quietRun = quiet ? this.quietRun + samples.length : 0;
69
+
70
+ if (!quiet) this.speechSamples += samples.length;
71
+
72
+ if (this.speechSamples === 0)
73
+ return ms(this.segmentSamples) >= this.options.idleMs ? "clear" : "none";
74
+
75
+ if (ms(this.segmentSamples) >= this.options.maxMs) return "commit";
76
+
77
+ if (ms(this.quietRun) >= this.options.longPauseMs) return "commit";
78
+
79
+ return ms(this.speechSamples) >= this.options.minSpeechMs &&
80
+ ms(this.quietRun) >= this.options.pauseMs
81
+ ? "commit"
82
+ : "none";
83
+ }
84
+
85
+ reset(): void {
86
+ this.segmentSamples = 0;
87
+ this.speechSamples = 0;
88
+ this.quietRun = 0;
89
+ }
90
+ }
91
+
92
+ export type StreamOutEvent =
93
+ | { event: "delta"; data: { segmentId: string; text: string } }
94
+ | { event: "segment"; data: { segmentId: string; text: string; startMs: number; endMs: number } }
95
+ | { event: "error"; data: { message: string; fatal: boolean } };
96
+
97
+ export type StreamSegment = { segmentId: string; text: string; startMs: number; endMs: number };
98
+
99
+ /** Opens (or reopens) the upstream stream; events must be routed to `onEvent`. */
100
+ export type OpenUpstream = (
101
+ onEvent: (event: OpenAITranscriptionStreamEvent) => void,
102
+ ) => Promise<OpenAITranscriptionStream>;
103
+
104
+ type PendingSegment = {
105
+ index: number;
106
+ startMs: number;
107
+ /** First frame above the silence threshold; reported as the segment start. */
108
+ speechStartMs?: number;
109
+ endMs?: number;
110
+ text?: string;
111
+ };
112
+
113
+ /** Consecutive failed reopen attempts before the session gives up. */
114
+ const MAX_REOPEN_FAILURES = 3;
115
+
116
+ /**
117
+ * One client stream: audio in, segment events out. Times are milliseconds of audio received in
118
+ * this session, so the client can place segments on its own recording clock.
119
+ *
120
+ * Segments bind to upstream items by the item id on input_audio_buffer.committed, which the
121
+ * upstream acknowledges in commit order. Deltas can name an item before its commit (live models
122
+ * stream while audio arrives); those are tentatively the open segment until the ack confirms it.
123
+ */
124
+ export class TranscribeStreamSession {
125
+ private upstream: OpenAITranscriptionStream | undefined;
126
+ private reconnecting = false;
127
+ private readonly policy: CommitPolicy;
128
+ private receivedSamples = 0;
129
+ private nextIndex = 0;
130
+ /** The open (uncommitted) segment, created when its first audio reaches the upstream. */
131
+ private current: PendingSegment | undefined;
132
+ private readonly bySegment = new Map<number, PendingSegment>();
133
+ private readonly itemToSegment = new Map<string, number>();
134
+ /** Segments committed on the current upstream whose commit is not yet acknowledged, in order. */
135
+ private awaitingAck: number[] = [];
136
+ private stopped = false;
137
+ private finished: (() => void) | undefined;
138
+ readonly segments: StreamSegment[] = [];
139
+
140
+ constructor(
141
+ private readonly openUpstream: OpenUpstream,
142
+ private readonly emit: (out: StreamOutEvent) => void,
143
+ policy: Partial<CommitPolicyOptions> = {},
144
+ ) {
145
+ this.policy = new CommitPolicy(policy);
146
+ }
147
+
148
+ get audioMs(): number {
149
+ return ms(this.receivedSamples);
150
+ }
151
+
152
+ async start(): Promise<void> {
153
+ this.upstream = await this.openUpstream((event) => this.onUpstream(event));
154
+ }
155
+
156
+ /** Mono PCM16 at `sampleRate`. Frames that arrive while the upstream reconnects are dropped. */
157
+ async audio(pcm: Int16Array, sampleRate: number): Promise<void> {
158
+ if (this.stopped) return;
159
+ const samples = resampleLinear(pcm, sampleRate, RATE);
160
+
161
+ if (samples.length === 0) return;
162
+ const startSample = this.receivedSamples;
163
+ this.receivedSamples += samples.length;
164
+ const upstream = this.upstream;
165
+
166
+ if (!upstream) return;
167
+
168
+ if (!this.current) {
169
+ this.current = { index: this.nextIndex++, startMs: Math.round(ms(startSample)) };
170
+ this.bySegment.set(this.current.index, this.current);
171
+ }
172
+
173
+ await upstream.append(new Uint8Array(samples.buffer, samples.byteOffset, samples.byteLength));
174
+ const decision = this.policy.push(samples);
175
+
176
+ if (this.current.speechStartMs === undefined && this.policy.hasSpeech)
177
+ this.current.speechStartMs = Math.round(ms(startSample));
178
+
179
+ if (decision === "commit") await this.commit();
180
+ else if (decision === "clear") this.clearIdle();
181
+ }
182
+
183
+ /** Ends the current segment now (client-side boundary, e.g. the speaker changed). */
184
+ async commit(): Promise<void> {
185
+ const segment = this.current;
186
+
187
+ if (!segment || !this.policy.hasSpeech) return;
188
+ segment.endMs = Math.round(ms(this.receivedSamples));
189
+ this.current = undefined;
190
+ this.policy.reset();
191
+ const upstream = this.upstream;
192
+
193
+ if (!upstream) {
194
+ this.bySegment.delete(segment.index);
195
+
196
+ return;
197
+ }
198
+
199
+ this.awaitingAck.push(segment.index);
200
+ await upstream.commit();
201
+ }
202
+
203
+ /**
204
+ * Commits what is left and waits up to `graceMs` for the outstanding transcripts, then closes.
205
+ */
206
+ async stop(graceMs = 10_000): Promise<void> {
207
+ if (this.stopped) return;
208
+ await this.commit().catch(() => undefined);
209
+ this.stopped = true;
210
+
211
+ if (this.upstream && this.outstanding() > 0) {
212
+ await new Promise<void>((resolve) => {
213
+ const timer = setTimeout(resolve, graceMs);
214
+ this.finished = () => {
215
+ clearTimeout(timer);
216
+ resolve();
217
+ };
218
+ });
219
+ }
220
+
221
+ this.upstream?.close();
222
+ this.upstream = undefined;
223
+ }
224
+
225
+ /** The client went away: drop everything without waiting. */
226
+ abort(): void {
227
+ this.stopped = true;
228
+ this.upstream?.close();
229
+ this.upstream = undefined;
230
+ }
231
+
232
+ /** The quiet-only buffer never reaches the model; a new segment starts with the next audio. */
233
+ private clearIdle(): void {
234
+ const idle = this.current;
235
+
236
+ if (idle) {
237
+ this.bySegment.delete(idle.index);
238
+ this.current = undefined;
239
+ }
240
+
241
+ this.policy.reset();
242
+ void this.upstream?.clear().catch(() => undefined);
243
+ }
244
+
245
+ private outstanding(): number {
246
+ let n = 0;
247
+
248
+ for (const s of this.bySegment.values()) if (s.endMs !== undefined && s.text === undefined) n++;
249
+
250
+ return n;
251
+ }
252
+
253
+ private onUpstream(event: OpenAITranscriptionStreamEvent): void {
254
+ switch (event.type) {
255
+ case "delta": {
256
+ let index = this.itemToSegment.get(event.itemId);
257
+
258
+ if (index === undefined && this.current) {
259
+ index = this.current.index;
260
+ this.itemToSegment.set(event.itemId, index);
261
+ }
262
+
263
+ if (index !== undefined && event.text)
264
+ this.emit({ event: "delta", data: { segmentId: `s${index}`, text: event.text } });
265
+
266
+ return;
267
+ }
268
+
269
+ case "committed": {
270
+ const index = this.awaitingAck.shift();
271
+
272
+ if (index !== undefined) this.itemToSegment.set(event.itemId, index);
273
+
274
+ return;
275
+ }
276
+
277
+ case "completed":
278
+ case "failed": {
279
+ const index = this.itemToSegment.get(event.itemId);
280
+ const segment = index === undefined ? undefined : this.bySegment.get(index);
281
+
282
+ if (!segment) return;
283
+ segment.text = event.type === "completed" ? event.text.trim() : "";
284
+
285
+ if (event.type === "failed")
286
+ this.emit({ event: "error", data: { message: event.message, fatal: false } });
287
+
288
+ if (segment.text) {
289
+ const out: StreamSegment = {
290
+ segmentId: `s${segment.index}`,
291
+ text: segment.text,
292
+ startMs: segment.speechStartMs ?? segment.startMs,
293
+ endMs: segment.endMs ?? Math.round(ms(this.receivedSamples)),
294
+ };
295
+
296
+ this.segments.push(out);
297
+ this.emit({ event: "segment", data: out });
298
+ }
299
+
300
+ this.bySegment.delete(segment.index);
301
+
302
+ if (this.stopped && this.outstanding() === 0) this.finished?.();
303
+
304
+ return;
305
+ }
306
+
307
+ case "error":
308
+ // Committing an empty buffer is the one routine error; nothing to tell the client.
309
+ if (event.code !== "input_audio_buffer_commit_empty")
310
+ this.emit({ event: "error", data: { message: event.message, fatal: false } });
311
+
312
+ return;
313
+ case "closed":
314
+ this.upstream = undefined;
315
+
316
+ if (this.stopped) {
317
+ this.finished?.();
318
+
319
+ return;
320
+ }
321
+
322
+ void this.reopenAfterClose(event.error);
323
+ }
324
+ }
325
+
326
+ /**
327
+ * The upstream session ended while the client is still streaming (a session limit or a dropped
328
+ * socket). Audio sent to the old session but not yet transcribed is lost, and frames are dropped
329
+ * until a new session opens. Only this loop opens sessions, with backoff between failures.
330
+ */
331
+ private async reopenAfterClose(error: Error | undefined): Promise<void> {
332
+ if (this.reconnecting) return;
333
+ this.reconnecting = true;
334
+
335
+ for (const s of this.bySegment.values())
336
+ if (s.text === undefined) this.bySegment.delete(s.index);
337
+
338
+ this.awaitingAck = [];
339
+ this.itemToSegment.clear();
340
+ this.current = undefined;
341
+ this.policy.reset();
342
+ this.emit({
343
+ event: "error",
344
+ data: {
345
+ message: `upstream session ended${error ? `: ${error.message}` : ""}; reconnecting`,
346
+ fatal: false,
347
+ },
348
+ });
349
+
350
+ try {
351
+ for (let failures = 0; !this.stopped && !this.upstream;) {
352
+ try {
353
+ const reopened = await this.openUpstream((event) => this.onUpstream(event));
354
+
355
+ // The client stopped while the session was opening.
356
+ if (this.stopped) reopened.close();
357
+ else this.upstream = reopened;
358
+ } catch (e) {
359
+ failures++;
360
+
361
+ if (failures >= MAX_REOPEN_FAILURES) {
362
+ this.stopped = true;
363
+ this.emit({
364
+ event: "error",
365
+ data: {
366
+ message: `could not reconnect: ${e instanceof Error ? e.message : String(e)}`,
367
+ fatal: true,
368
+ },
369
+ });
370
+
371
+ return;
372
+ }
373
+
374
+ await new Promise((r) => setTimeout(r, 1000 * failures));
375
+ }
376
+ }
377
+ } finally {
378
+ this.reconnecting = false;
379
+ }
380
+ }
381
+ }
@@ -120,6 +120,9 @@ export namespace QgridService {
120
120
 
121
121
  export const health = (): SSRQuery =>
122
122
  createSSRQuery("QgridFrame", "health", [], ["Qgrid", "health"]);
123
+
124
+ export const models = (): SSRQuery =>
125
+ createSSRQuery("QgridFrame", "models", [], ["Qgrid", "models"]);
123
126
  }
124
127
 
125
128
  export namespace MonitService {
@@ -431,10 +431,11 @@ describe("RequestLogModel run lifecycle", () => {
431
431
  expect(candidateChain.where).toHaveBeenCalledWith("request_log_steps.error", null);
432
432
  });
433
433
 
434
- it("closes only live runs still running past the threshold", async () => {
435
- const chain = { from: vi.fn(), where: vi.fn(), update: vi.fn(async () => 2) };
434
+ it("closes only live and stt runs still running past the threshold", async () => {
435
+ const chain = { from: vi.fn(), where: vi.fn(), whereIn: vi.fn(), update: vi.fn(async () => 2) };
436
436
  chain.from.mockReturnValue(chain);
437
437
  chain.where.mockReturnValue(chain);
438
+ chain.whereIn.mockReturnValue(chain);
438
439
  vi.spyOn(
439
440
  RequestLogModel as unknown as { getPuri: () => typeof chain },
440
441
  "getPuri",
@@ -444,7 +445,7 @@ describe("RequestLogModel run lifecycle", () => {
444
445
  await expect(RequestLogModel.expireStaleLiveRuns(threshold, "server stopped")).resolves.toBe(2);
445
446
 
446
447
  expect(chain.from).toHaveBeenCalledWith("request_logs");
447
- expect(chain.where).toHaveBeenCalledWith("media_kind", "live");
448
+ expect(chain.whereIn).toHaveBeenCalledWith("media_kind", ["live", "stt"]);
448
449
  expect(chain.where).toHaveBeenCalledWith("status", "running");
449
450
  expect(chain.where).toHaveBeenCalledWith("created_at", "<", threshold);
450
451
  expect(chain.update).toHaveBeenCalledWith({ status: "error", error_message: "server stopped" });
@@ -624,13 +624,14 @@ class RequestLogModelClass extends BaseModelClass<
624
624
  }
625
625
 
626
626
  /**
627
- * Live voice sessions end within two hours and log themselves at the end; a live run still
628
- * running past `threshold` lost its server mid-session. Returns how many were closed.
627
+ * Live voice sessions and transcription streams end within two hours and log themselves at the
628
+ * end; one-shot stt runs finish within minutes. A live or stt run still running past `threshold`
629
+ * lost its server mid-session. Returns how many were closed.
629
630
  */
630
631
  async expireStaleLiveRuns(threshold: Date, errorMessage: string): Promise<number> {
631
632
  return this.getPuri("w")
632
633
  .from("request_logs")
633
- .where("media_kind", "live")
634
+ .whereIn("media_kind", ["live", "stt"])
634
635
  .where("status", "running")
635
636
  .where("created_at", "<", threshold)
636
637
  .update({ status: "error", error_message: errorMessage });
@@ -792,6 +792,12 @@ Content-Type: application/json
792
792
 
793
793
  ###
794
794
 
795
+ GET {{baseUrl}}/api/qgrid/transcribeStream
796
+ ?
797
+ Content-Type: application/json
798
+
799
+ ###
800
+
795
801
  GET {{baseUrl}}/api/qgrid/usage
796
802
  ?tokenId=0
797
803
  Content-Type: application/json
@@ -804,6 +810,12 @@ Content-Type: application/json
804
810
 
805
811
  ###
806
812
 
813
+ GET {{baseUrl}}/api/qgrid/models
814
+ ?
815
+ Content-Type: application/json
816
+
817
+ ###
818
+
807
819
  GET {{baseUrl}}/api/monit/monitLogs
808
820
  ?cursor=0
809
821
  Content-Type: application/json
@@ -11,16 +11,19 @@ const RETRY_AFTER_SECONDS = "30";
11
11
  //
12
12
  // sonamu 의 isSoException 은 `statusCode !== undefined` 만 보는 duck-typing 이라 바로 그
13
13
  // upstream 예외를 통과시킨다. 여기서는 instanceof 로 실제 계약을 확인한다.
14
- export function handleServerError(error: Error, reply: FastifyReply): void {
15
- getLogger(["qgrid"]).error(`${error}`);
16
-
17
- const statusCode =
18
- error instanceof SoException &&
14
+ export function errorStatusCode(error: Error): number {
15
+ return error instanceof SoException &&
19
16
  Number.isInteger(error.statusCode) &&
20
17
  error.statusCode >= 400 &&
21
18
  error.statusCode <= 599
22
- ? error.statusCode
23
- : 500;
19
+ ? error.statusCode
20
+ : 500;
21
+ }
22
+
23
+ export function handleServerError(error: Error, reply: FastifyReply): void {
24
+ getLogger(["qgrid"]).error(`${error}`);
25
+
26
+ const statusCode = errorStatusCode(error);
24
27
 
25
28
  // 503 은 "지금은 아니지만 곧 된다"는 뜻이라 재시도 시점을 함께 준다. 값이 없으면
26
29
  // 클라이언트는 재시도 간격을 스스로 정해야 하고, 대개 즉시 재시도해 부하만 키운다.
@@ -14,6 +14,7 @@ import {
14
14
  startExpiredTokenReminder,
15
15
  stopExpiredTokenReminder,
16
16
  } from "./application/qgrid/expired-token-reminder";
17
+ import { chatCompletionsHandler } from "./application/qgrid/openai-compat";
17
18
  import { QgridDispatcher } from "./application/qgrid/qgrid.dispatcher";
18
19
  import {
19
20
  mapRequestBodyTooLarge,
@@ -129,6 +130,8 @@ export default defineConfig({
129
130
  formbody: true,
130
131
  qs: true,
131
132
  sse: true,
133
+ // @fastify/websocket for @websocket routes (transcribeStream); without it upgrades hang.
134
+ ws: true,
132
135
  multipart: { limits: { fileSize: 1024 * 1024 * 30 } },
133
136
  static: {
134
137
  root: path.join(import.meta.dirname, "/../", "public"),
@@ -137,6 +140,7 @@ export default defineConfig({
137
140
  custom: (server) => {
138
141
  server.get("/callback", oauthCallback);
139
142
  server.get("/auth/callback", oauthCallback);
143
+ server.post("/v1/chat/completions", chatCompletionsHandler);
140
144
  },
141
145
  },
142
146
  apiConfig: {
@@ -30,6 +30,7 @@ describe("canonicalAnthropicModel", () => {
30
30
 
31
31
  describe("Anthropic 1M context policy", () => {
32
32
  it("지원 모델은 실측 확인된 exact set 만 true", () => {
33
+ expect(supports1MContext("claude-fable-5-2")).toBe(true);
33
34
  expect(supports1MContext("claude-fable-5-1")).toBe(true);
34
35
  expect(supports1MContext("claude-fable-5")).toBe(true);
35
36
  expect(supports1MContext("claude-opus-5")).toBe(true);
@@ -85,6 +86,7 @@ describe("Anthropic 1M context policy", () => {
85
86
 
86
87
  describe("Anthropic thinking policy", () => {
87
88
  it("Fable 5/5.1, Opus 5, Opus 5.5, Sonnet 5.5, Haiku 5.5 는 adaptive thinking 을 보존한다", () => {
89
+ expect(usesAdaptiveThinking("claude-fable-5-2")).toBe(true);
88
90
  expect(usesAdaptiveThinking("claude-fable-5-1")).toBe(true);
89
91
  expect(usesAdaptiveThinking("anthropic/claude-fable-5-1")).toBe(true);
90
92
  expect(usesAdaptiveThinking("claude-fable-5")).toBe(true);
@@ -105,6 +107,7 @@ describe("Anthropic thinking policy", () => {
105
107
 
106
108
  describe("Anthropic Fable family", () => {
107
109
  it("Fable 5/5.1 만 Fable 계열로 판정하고 prefix/[1m] 은 무시한다", () => {
110
+ expect(isFableFamilyModel("claude-fable-5-2")).toBe(true);
108
111
  expect(isFableFamilyModel("claude-fable-5-1")).toBe(true);
109
112
  expect(isFableFamilyModel("claude-fable-5")).toBe(true);
110
113
  expect(isFableFamilyModel("anthropic/claude-fable-5-1[1m]")).toBe(true);
@@ -50,6 +50,7 @@ export function hasOneMillionSuffix(model?: string): boolean {
50
50
  // 1M 지원 여부는 Claude Code 내부의 광범위한 prefix 판정이 아니라 qgrid에서 확인한 exact set 으로
51
51
  // 고정한다. opus-4-7 은 실측 전까지 미포함. 새 모델 추가 시 공식 사양과 실제 CLI 동작을 확인한다.
52
52
  const ONE_MILLION_CONTEXT_MODELS = new Set([
53
+ "claude-fable-5-2",
53
54
  "claude-fable-5-1",
54
55
  "claude-fable-5",
55
56
  "claude-opus-5",
@@ -68,6 +69,7 @@ const CLI_ONE_MILLION_SUFFIX_MODELS = new Set(["claude-sonnet-4-6", "claude-opus
68
69
  // explicit false supports Opus 5, and native extra-body delivery supports Haiku 5.5
69
70
  // (disabled) and Sonnet 5.5 (between_tools). See anthropic-thinking.ts.
70
71
  const ADAPTIVE_THINKING_MODELS = new Set([
72
+ "claude-fable-5-2",
71
73
  "claude-fable-5-1",
72
74
  "claude-fable-5",
73
75
  "claude-opus-5",
@@ -79,7 +81,7 @@ const ADAPTIVE_THINKING_MODELS = new Set([
79
81
  // Fable 계열: 구독 플랜에서 usage credits 가 필요한 최상위 티어. 구독 usage API 의
80
82
  // `seven_day_overage_included` 버킷은 이 계열에만 적용되므로 quota threshold 판정이 참조한다.
81
83
  // Mythos 는 Project Glasswing 조직 전용이라 구독 토큰 경로에서 도달할 수 없어 포함하지 않는다.
82
- const FABLE_FAMILY_MODELS = new Set(["claude-fable-5-1", "claude-fable-5"]);
84
+ const FABLE_FAMILY_MODELS = new Set(["claude-fable-5-2", "claude-fable-5-1", "claude-fable-5"]);
83
85
 
84
86
  // 불변 계약: suffix 가 필요한 모델은 반드시 1M 지원 모델의 부분집합이어야 한다. 역방향 불일치(suffix
85
87
  // 대상인데 지원 집합엔 없음)면 needsCli1mSuffix=true·supports1MContext=false 가 동시에 나서
@@ -28,7 +28,7 @@ export async function readAnthropicQuotaUsage(
28
28
  const utilizationPct = fiveHour !== null && Number.isFinite(fiveHour) ? fiveHour : null;
29
29
  const weeklyUsages = [data.seven_day?.utilization];
30
30
 
31
- // Fable 계열(5, 5.1)은 5시간 창과 별개로 usage credits 기반 7일 버킷도 소진될 수 있다.
31
+ // Fable 계열(5, 5.1, 5.2)은 5시간 창과 별개로 usage credits 기반 7일 버킷도 소진될 수 있다.
32
32
  if (isFableFamilyModel(model)) {
33
33
  weeklyUsages.push(data.seven_day_overage_included?.utilization);
34
34
  }
@@ -23,6 +23,8 @@ describe("resolveOpenAIEffort", () => {
23
23
  expect(resolveOpenAIEffort("gpt-5.6-terra", "max")).toBe("max");
24
24
  expect(resolveOpenAIEffort("gpt-5.6-terra", "ultra")).toBe("ultra");
25
25
  expect(resolveOpenAIEffort("gpt-5.6-luna", "max")).toBe("max");
26
+ expect(resolveOpenAIEffort("gpt-6.2-astra", "ultra")).toBe("ultra");
27
+ expect(resolveOpenAIEffort("gpt-6.2-sol", "ultra")).toBe("ultra");
26
28
  expect(resolveOpenAIEffort("gpt-6.1-sol", "ultra")).toBe("ultra");
27
29
  expect(resolveOpenAIEffort("gpt-6.1-terra", "ultra")).toBe("ultra");
28
30
  expect(resolveOpenAIEffort("gpt-6-sol", "ultra")).toBe("ultra");
@@ -85,6 +85,8 @@ describe("Grok cost", () => {
85
85
 
86
86
  describe("calculateCostUsd", () => {
87
87
  it.each([
88
+ ["gpt-6.2-astra", 2],
89
+ ["gpt-6.2-sol", 0.5],
88
90
  ["gpt-6-astra", 2.6],
89
91
  ["gpt-6.1-sol", 0.5],
90
92
  ["gpt-6.1-terra", 0.25],
@@ -141,6 +143,8 @@ describe("calculateCostUsd", () => {
141
143
  ).toBeCloseTo(0.0875, 10);
142
144
  });
143
145
  it.each([
146
+ ["gpt-6.2-astra", 8, 40, 0.4, 10],
147
+ ["gpt-6.2-sol", 2, 10, 0.1, 2.5],
144
148
  ["gpt-6-astra", 10, 50, 1, 12.5],
145
149
  ["gpt-6.1-sol", 2, 10, 0.1, 2.5],
146
150
  ["gpt-6.1-terra", 1, 5, 0.05, 1.25],
@@ -173,6 +177,7 @@ describe("calculateCostUsd", () => {
173
177
 
174
178
  it.each([
175
179
  // Fable 5.1 은 cache read 만 0.025x 특례($0.25), 나머지 배율은 표준과 같다.
180
+ ["claude-fable-5-2", 8, 40, 0.2, 16],
176
181
  ["claude-fable-5-1", 10, 50, 0.25, 20],
177
182
  ["claude-fable-5", 10, 50, 1, 20],
178
183
  ["claude-haiku-4-5", 1, 5, 0.1, 2],
@@ -229,6 +234,8 @@ describe("calculateCostUsd", () => {
229
234
  });
230
235
 
231
236
  it.each([
237
+ ["gpt-6.2-astra", 8, 40, 0.4, 10, 4.47],
238
+ ["gpt-6.2-sol", 2, 10, 0.1, 2.5, 1.1175],
232
239
  ["gpt-6-astra", 10, 50, 1, 12.5, 5.6125],
233
240
  ["gpt-6.1-sol", 2, 10, 0.1, 2.5, 1.1175],
234
241
  ["gpt-6.1-terra", 1, 5, 0.05, 1.25, 0.55875],
@@ -259,6 +266,8 @@ describe("calculateCostUsd", () => {
259
266
  );
260
267
 
261
268
  it.each([
269
+ ["gpt-6.2-astra", 1.82],
270
+ ["gpt-6.2-sol", 0.455],
262
271
  ["gpt-6-astra", 2.475],
263
272
  ["gpt-6.1-sol", 0.455],
264
273
  ["gpt-6.1-terra", 0.2275],
@@ -278,6 +287,8 @@ describe("calculateCostUsd", () => {
278
287
  });
279
288
 
280
289
  it.each([
290
+ ["gpt-6.2-astra", 2.02],
291
+ ["gpt-6.2-sol", 0.505],
281
292
  ["gpt-6-astra", 2.725],
282
293
  ["gpt-6.1-sol", 0.505],
283
294
  ["gpt-6.1-terra", 0.2525],