@cartanova/qgrid-cli 2.11.1 → 2.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bundle/dist/application/qgrid/qgrid-response-format.js +9 -1
- package/bundle/dist/application/qgrid/qgrid-run-lifecycle.js +28 -4
- package/bundle/dist/application/qgrid/qgrid.dispatcher.js +7 -4
- package/bundle/dist/application/qgrid/qgrid.frame.js +25 -4
- package/bundle/dist/application/request-log/request-log.model.js +5 -1
- package/bundle/dist/utils/providers/anthropic/anthropic-dispatcher.js +7 -2
- package/bundle/dist/utils/providers/anthropic/claude-session.js +10 -2
- package/bundle/dist/utils/providers/grok/grok-backend-protocol.js +1 -1
- package/bundle/dist/utils/providers/grok/grok-dispatcher.js +43 -12
- package/bundle/dist/utils/providers/grok/grok-types.js +2 -2
- package/bundle/dist/utils/providers/openai/openai-dispatcher.js +9 -3
- package/bundle/src/application/qgrid/qgrid-response-format.ts +9 -0
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.test.ts +63 -0
- package/bundle/src/application/qgrid/qgrid-run-lifecycle.ts +49 -7
- package/bundle/src/application/qgrid/qgrid.dispatcher.ts +6 -0
- package/bundle/src/application/qgrid/qgrid.frame.test.ts +9 -2
- package/bundle/src/application/qgrid/qgrid.frame.ts +39 -3
- package/bundle/src/application/request-log/request-log.model.ts +11 -0
- package/bundle/src/utils/providers/anthropic/anthropic-dispatcher.ts +2 -0
- package/bundle/src/utils/providers/anthropic/claude-session.ts +15 -1
- package/bundle/src/utils/providers/common/provider-dispatcher.ts +10 -0
- package/bundle/src/utils/providers/grok/grok-backend-protocol.ts +6 -1
- package/bundle/src/utils/providers/grok/grok-dispatcher.test.ts +74 -3
- package/bundle/src/utils/providers/grok/grok-dispatcher.ts +66 -18
- package/bundle/src/utils/providers/grok/grok-quota.test.ts +18 -0
- package/bundle/src/utils/providers/grok/grok-types.ts +2 -1
- package/bundle/src/utils/providers/openai/openai-dispatcher.test.ts +18 -0
- package/bundle/src/utils/providers/openai/openai-dispatcher.ts +10 -2
- package/bundle/web-dist/client/assets/{index-C96h3feE.js → index-CK9LwGNV.js} +3 -3
- package/bundle/web-dist/client/assets/logs-DjQcEivP.js +1 -0
- package/bundle/web-dist/client/assets/{monit-BBjXa7vB.js → monit-RTxpU7oZ.js} +1 -1
- package/bundle/web-dist/client/assets/{request-model-Bpp_rkK8.js → request-model-DliRuPcw.js} +1 -1
- package/bundle/web-dist/client/assets/routes-DVHoo-YF.js +5 -0
- package/bundle/web-dist/client/assets/{settings-Cdwm3OBB.js → settings-BQUz6UFr.js} +1 -1
- package/bundle/web-dist/client/assets/{show-DBUhALT1.js → show-CalQG1Ew.js} +2 -2
- package/bundle/web-dist/client/assets/{tokens-CVQAVJTo.js → tokens-DU4fWXI9.js} +1 -1
- package/bundle/web-dist/client/index.html +1 -1
- package/bundle/web-dist/server/assets/{logs-B7QmGJq3.js → logs-B5M5B7pN.js} +32 -14
- package/bundle/web-dist/server/assets/{monit-DFt7x3bh.js → monit-p6JM8MMl.js} +1 -1
- package/bundle/web-dist/server/assets/{request-model-eHE6YbaF.js → request-model-Cp6h5EuP.js} +1 -1
- package/bundle/web-dist/server/assets/{routes-_Y-PJfgO.js → routes-rIXpkI-t.js} +4 -19
- package/bundle/web-dist/server/assets/{settings-JwJKxn2e.js → settings-_MoaFGxj.js} +1 -1
- package/bundle/web-dist/server/assets/{show-BEv6z1v_.js → show-Cfm9UeDr.js} +9 -3
- package/bundle/web-dist/server/assets/{tokens-CNT4mI-f.js → tokens-DMSHDg9D.js} +1 -1
- package/bundle/web-dist/server/entry-server.generated.js +54 -38
- package/package.json +1 -1
- package/skills/qgrid/references/ai-sdk-provider-contract.md +1 -1
- package/skills/qgrid/references/cli-env-and-server-boot.md +4 -3
- package/skills/qgrid/references/decision-rationale.md +2 -1
- package/skills/qgrid/references/grok-runtime.md +7 -1
- package/skills/qgrid/references/repo-map.md +2 -0
- package/skills/qgrid/references/request-log-run-lifecycle.md +5 -0
- package/skills/qgrid/references/verification-and-debugging.md +24 -5
- package/bundle/web-dist/client/assets/logs-DBM6U0QD.js +0 -1
- package/bundle/web-dist/client/assets/routes-Crz_PQzi.js +0 -5
- package/bundle/web-dist/client/assets/total-cost-MnfKU8IN.js +0 -1
- package/bundle/web-dist/server/assets/total-cost-fTE9Xy82.js +0 -18
- /package/bundle/web-dist/client/assets/{plus-BsQdY7PS.js → plus-DDvVTvQP.js} +0 -0
- /package/bundle/web-dist/client/assets/{refresh-cw-D9IUmT23.js → refresh-cw-CTQsNddA.js} +0 -0
- /package/bundle/web-dist/server/assets/{plus-DaYQRpBt.js → plus-I0FfLVgU.js} +0 -0
- /package/bundle/web-dist/server/assets/{refresh-cw-BpXNsAy-.js → refresh-cw-DYsnffRC.js} +0 -0
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { getLogger } from "@logtape/logtape";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { type GenerateProgress } from "../../utils/providers/common/provider-dispatcher";
|
|
5
|
+
import { RequestLogModel, type RunProgressUpdate } from "../request-log/request-log.model";
|
|
5
6
|
import {
|
|
6
7
|
estimateImageGenerationCostMicroUsd,
|
|
7
8
|
imageGenerationCostMethod,
|
|
@@ -125,6 +126,44 @@ export async function beforeQuery(args: QueryInput): Promise<{
|
|
|
125
126
|
return { requestLogId, stepIndex };
|
|
126
127
|
}
|
|
127
128
|
|
|
129
|
+
/**
|
|
130
|
+
* Returns a dispatcher progress callback that writes the token, serving model, and TTFT onto the
|
|
131
|
+
* running parent row as they become known. Writes run in order, and a failure only logs: progress
|
|
132
|
+
* must never fail the request. afterQuery's final values replace these.
|
|
133
|
+
*/
|
|
134
|
+
export function runProgressRecorder(
|
|
135
|
+
requestLogId: number,
|
|
136
|
+
stepIndex: number,
|
|
137
|
+
args: QueryInput,
|
|
138
|
+
): (progress: GenerateProgress) => void {
|
|
139
|
+
let pending = Promise.resolve();
|
|
140
|
+
|
|
141
|
+
return (progress) => {
|
|
142
|
+
const update: RunProgressUpdate = {};
|
|
143
|
+
|
|
144
|
+
if (progress.tokenName) update.token_name = progress.tokenName;
|
|
145
|
+
|
|
146
|
+
const modelName = withProviderPrefix(args.model, progress.model);
|
|
147
|
+
|
|
148
|
+
if (modelName) update.model_name = modelName;
|
|
149
|
+
|
|
150
|
+
// The run's TTFT is its first generate step's; a continued tool run keeps the stored value.
|
|
151
|
+
if (progress.ttftMs !== undefined && stepIndex === 0) update.ttft_ms = progress.ttftMs;
|
|
152
|
+
|
|
153
|
+
if (Object.keys(update).length === 0) return;
|
|
154
|
+
|
|
155
|
+
pending = pending.then(async () => {
|
|
156
|
+
try {
|
|
157
|
+
await RequestLogModel.recordRunProgress(requestLogId, update);
|
|
158
|
+
} catch (e) {
|
|
159
|
+
logger.warn(
|
|
160
|
+
`run progress update failed for ${requestLogId}: ${e instanceof Error ? e.message : String(e)}`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
128
167
|
async function appendGenerateStep(
|
|
129
168
|
requestLogId: number,
|
|
130
169
|
stepIndex: number,
|
|
@@ -177,10 +216,12 @@ export async function afterQuery(
|
|
|
177
216
|
|
|
178
217
|
const imageParts = getImageParts(result);
|
|
179
218
|
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
219
|
+
// Grok reports one provider cost for the turn that already includes its image tool calls.
|
|
220
|
+
const imageCostIncluded = args.model?.startsWith("grok/") === true && imageParts.length > 0;
|
|
221
|
+
|
|
222
|
+
const imageCostMicroUsd = imageCostIncluded
|
|
223
|
+
? 0
|
|
224
|
+
: estimateImageGenerationCostMicroUsd(result, args.imageGenerationOptions);
|
|
184
225
|
|
|
185
226
|
for (const step of buildImageGenerationToolSteps(args, imageParts, stepIndex)) {
|
|
186
227
|
await RequestLogModel.appendStep(requestLogId, step);
|
|
@@ -233,8 +274,9 @@ export async function afterQuery(
|
|
|
233
274
|
cost_usd: agg.cost_usd,
|
|
234
275
|
cost_source: agg.cost_source,
|
|
235
276
|
image_cost_usd: imageCostMicroUsd,
|
|
236
|
-
image_cost_method:
|
|
237
|
-
|
|
277
|
+
image_cost_method: imageCostIncluded
|
|
278
|
+
? "included:grok-provider-cost"
|
|
279
|
+
: imageCostMicroUsd !== null
|
|
238
280
|
? imageGenerationCostMethod(args.imageGenerationOptions, result)
|
|
239
281
|
: null,
|
|
240
282
|
history: filterHistoryForStorage(args.history),
|
|
@@ -51,6 +51,7 @@ import { buildToolCallSchema } from "./tool-emulation-schema";
|
|
|
51
51
|
export type InternalQueryInput = QueryInput & {
|
|
52
52
|
preferredTokenId?: number;
|
|
53
53
|
requirePreferredToken?: boolean;
|
|
54
|
+
onProgress?: GenerateRequest["onProgress"];
|
|
54
55
|
};
|
|
55
56
|
|
|
56
57
|
// qgrid 상위가 provider 에 요구하는 실행 계약. 스트리밍은 공통 ProviderDispatcher 에 아직 없어서
|
|
@@ -91,6 +92,8 @@ export interface GrokTokenSink {
|
|
|
91
92
|
/** Observability the concrete Grok dispatcher exposes beyond routing. */
|
|
92
93
|
export interface GrokTokenStateSource {
|
|
93
94
|
tokenStates(): GrokTokenStateSnapshot[];
|
|
95
|
+
/** Refreshes stale settings, subscription, and billing lookups for the usage view. */
|
|
96
|
+
refreshUsage(tokenId: number): Promise<void>;
|
|
94
97
|
}
|
|
95
98
|
|
|
96
99
|
/** Media, voice, and token-state reporting are optional capabilities of a Grok dispatcher. */
|
|
@@ -225,6 +228,7 @@ export class QgridDispatcherClass {
|
|
|
225
228
|
preferredTokenId: input.preferredTokenId,
|
|
226
229
|
imageGeneration: input.imageGeneration,
|
|
227
230
|
imageGenerationOptions: input.imageGenerationOptions,
|
|
231
|
+
onProgress: input.onProgress,
|
|
228
232
|
});
|
|
229
233
|
|
|
230
234
|
this.recordCompleted(provider, result.tokenName);
|
|
@@ -301,6 +305,7 @@ export class QgridDispatcherClass {
|
|
|
301
305
|
abortSignal,
|
|
302
306
|
imageGeneration: input.imageGeneration,
|
|
303
307
|
imageGenerationOptions: input.imageGenerationOptions,
|
|
308
|
+
onProgress: input.onProgress,
|
|
304
309
|
},
|
|
305
310
|
{
|
|
306
311
|
onDelta: emitDelta,
|
|
@@ -391,6 +396,7 @@ function buildDirectRequest(
|
|
|
391
396
|
abortSignal,
|
|
392
397
|
imageGeneration: input.imageGeneration,
|
|
393
398
|
imageGenerationOptions: input.imageGenerationOptions,
|
|
399
|
+
onProgress: input.onProgress,
|
|
394
400
|
};
|
|
395
401
|
|
|
396
402
|
// Opaque namespaces; the Grok dispatcher reads `xai`, OpenAI ignores it.
|
|
@@ -166,6 +166,7 @@ vi.mock("./qgrid-run-lifecycle", () => ({
|
|
|
166
166
|
afterQuery: afterQueryMock,
|
|
167
167
|
finishRunWithError: finishRunWithErrorMock,
|
|
168
168
|
finishRunAborted: finishRunAbortedMock,
|
|
169
|
+
runProgressRecorder: () => () => {},
|
|
169
170
|
}));
|
|
170
171
|
|
|
171
172
|
const tokenEntry = {
|
|
@@ -1724,18 +1725,23 @@ describe("QgridFrame Grok registration and routing", () => {
|
|
|
1724
1725
|
expect(result.text).toBe("grok says hi");
|
|
1725
1726
|
});
|
|
1726
1727
|
|
|
1727
|
-
it("usage
|
|
1728
|
+
it("usage refreshes Grok lookups first and reports billing without keepalive", async () => {
|
|
1728
1729
|
const credentials = grokCredentials();
|
|
1729
1730
|
findManyMock.mockResolvedValueOnce({
|
|
1730
1731
|
rows: [{ ...tokenEntry, id: 9, provider: "grok", name: "grok-a", credentials }],
|
|
1731
1732
|
});
|
|
1733
|
+
let refreshed = false;
|
|
1734
|
+
const refreshUsage = vi.fn(async () => {
|
|
1735
|
+
refreshed = true;
|
|
1736
|
+
});
|
|
1732
1737
|
Object.assign(QgridDispatcher, {
|
|
1733
1738
|
grokDispatcher: {
|
|
1739
|
+
refreshUsage,
|
|
1734
1740
|
tokenStates: () => [
|
|
1735
1741
|
{
|
|
1736
1742
|
id: 9,
|
|
1737
1743
|
name: "grok-a",
|
|
1738
|
-
lastBilling: {
|
|
1744
|
+
lastBilling: refreshed && {
|
|
1739
1745
|
utilizationPct: 42,
|
|
1740
1746
|
periodType: "USAGE_PERIOD_TYPE_WEEKLY",
|
|
1741
1747
|
periodEnd: "2030-01-08T00:00:00Z",
|
|
@@ -1759,6 +1765,7 @@ describe("QgridFrame Grok registration and routing", () => {
|
|
|
1759
1765
|
zdrVideoExcluded: true,
|
|
1760
1766
|
keepaliveApplicable: false,
|
|
1761
1767
|
});
|
|
1768
|
+
expect(refreshUsage).toHaveBeenCalledWith(9);
|
|
1762
1769
|
});
|
|
1763
1770
|
|
|
1764
1771
|
it("usage falls back to the stored tier before the first billing fetch", async () => {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
3
|
|
|
3
4
|
import { getLogger } from "@logtape/logtape";
|
|
4
5
|
import { type FastifyReply, type FastifyRequest } from "fastify";
|
|
@@ -104,6 +105,7 @@ import {
|
|
|
104
105
|
beforeQuery,
|
|
105
106
|
finishRunAborted,
|
|
106
107
|
finishRunWithError,
|
|
108
|
+
runProgressRecorder,
|
|
107
109
|
} from "./qgrid-run-lifecycle";
|
|
108
110
|
import {
|
|
109
111
|
buildAndValidateStrictOutputSchema,
|
|
@@ -255,6 +257,27 @@ function grokOAuthBadRequest(cause: unknown): never {
|
|
|
255
257
|
throw cause;
|
|
256
258
|
}
|
|
257
259
|
|
|
260
|
+
// The usage view waits this long for a lookup refresh; a slower one still fills the cache.
|
|
261
|
+
const GROK_USAGE_REFRESH_WAIT_MS = 3_000;
|
|
262
|
+
|
|
263
|
+
async function refreshGrokUsage(tokenId: number): Promise<void> {
|
|
264
|
+
const refresh = QgridDispatcher.grokDispatcher?.refreshUsage?.(tokenId);
|
|
265
|
+
|
|
266
|
+
if (!refresh) return;
|
|
267
|
+
|
|
268
|
+
const settled = (async () => {
|
|
269
|
+
try {
|
|
270
|
+
await refresh;
|
|
271
|
+
} catch (e) {
|
|
272
|
+
logger.warn(
|
|
273
|
+
`grok usage refresh failed for token ${tokenId}: ${e instanceof Error ? e.message : String(e)}`,
|
|
274
|
+
);
|
|
275
|
+
}
|
|
276
|
+
})();
|
|
277
|
+
|
|
278
|
+
await Promise.race([settled, sleep(GROK_USAGE_REFRESH_WAIT_MS)]);
|
|
279
|
+
}
|
|
280
|
+
|
|
258
281
|
function grokTokenSnapshot(tokenId: number): GrokTokenStateSnapshot | undefined {
|
|
259
282
|
// Token-state reporting is optional on the routing port; the concrete GrokDispatcher has it.
|
|
260
283
|
return QgridDispatcher.grokDispatcher?.tokenStates?.().find((state) => state.id === tokenId);
|
|
@@ -1014,7 +1037,13 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
1014
1037
|
let result: QueryOutput;
|
|
1015
1038
|
|
|
1016
1039
|
try {
|
|
1017
|
-
result = await QgridDispatcher.query(
|
|
1040
|
+
result = await QgridDispatcher.query(
|
|
1041
|
+
{
|
|
1042
|
+
...resolvedArgs,
|
|
1043
|
+
onProgress: runProgressRecorder(requestLogId, stepIndex, resolvedArgs),
|
|
1044
|
+
},
|
|
1045
|
+
disconnect.signal,
|
|
1046
|
+
);
|
|
1018
1047
|
} catch (e) {
|
|
1019
1048
|
const completedDriver = completedDriverFromImageFailure(e, resolvedArgs.serviceTier);
|
|
1020
1049
|
|
|
@@ -1120,7 +1149,12 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
1120
1149
|
|
|
1121
1150
|
try {
|
|
1122
1151
|
await QgridDispatcher.queryStream(
|
|
1123
|
-
|
|
1152
|
+
runInfo
|
|
1153
|
+
? {
|
|
1154
|
+
...args,
|
|
1155
|
+
onProgress: runProgressRecorder(runInfo.requestLogId, runInfo.stepIndex, args),
|
|
1156
|
+
}
|
|
1157
|
+
: args,
|
|
1124
1158
|
{
|
|
1125
1159
|
onDelta: (text) => {
|
|
1126
1160
|
if (!clientClosed && !sse.closed) sse.publish("delta", { text });
|
|
@@ -2085,7 +2119,9 @@ class QgridFrameClass extends BaseFrameClass {
|
|
|
2085
2119
|
}
|
|
2086
2120
|
|
|
2087
2121
|
if (entry.provider === "grok") {
|
|
2088
|
-
//
|
|
2122
|
+
// Refresh stale lookups (60 s cache) so a token without traffic still reports usage.
|
|
2123
|
+
if (entry.active) await refreshGrokUsage(entry.id);
|
|
2124
|
+
|
|
2089
2125
|
const snapshot = entry.active ? grokTokenSnapshot(entry.id) : undefined;
|
|
2090
2126
|
const billing = snapshot?.lastBilling;
|
|
2091
2127
|
const storedTier = StoredGrokCredentials.safeParse(entry.credentials).data?.subscriptionTier;
|
|
@@ -109,6 +109,8 @@ export interface FinishRunParams {
|
|
|
109
109
|
|
|
110
110
|
type FinishRunUpdate = Partial<FinishRunParams> & { id: number; ttft_ms?: number };
|
|
111
111
|
|
|
112
|
+
export type RunProgressUpdate = { token_name?: string; model_name?: string; ttft_ms?: number };
|
|
113
|
+
|
|
112
114
|
/** Copies `key` only when the caller supplied it, so omitted columns stay untouched. */
|
|
113
115
|
function copyDefined<T, K extends keyof T>(target: Partial<T>, source: T, key: K): void {
|
|
114
116
|
if (source[key] !== undefined) target[key] = source[key];
|
|
@@ -654,6 +656,15 @@ class RequestLogModelClass extends BaseModelClass<
|
|
|
654
656
|
});
|
|
655
657
|
}
|
|
656
658
|
|
|
659
|
+
/** Writes facts known mid-run onto a parent that is still running; finished runs stay as is. */
|
|
660
|
+
async recordRunProgress(requestLogId: number, progress: RunProgressUpdate): Promise<void> {
|
|
661
|
+
await this.getPuri("w")
|
|
662
|
+
.from("request_logs")
|
|
663
|
+
.where("id", requestLogId)
|
|
664
|
+
.where("status", "running")
|
|
665
|
+
.update(progress);
|
|
666
|
+
}
|
|
667
|
+
|
|
657
668
|
async finishRun(requestLogId: number, params: FinishRunParams): Promise<void> {
|
|
658
669
|
if (params.status === "succeeded" && !params.token_name) {
|
|
659
670
|
throw new Error("tokenName is required for succeeded runs");
|
|
@@ -276,6 +276,7 @@ export class AnthropicDispatcher implements ProviderDispatcher {
|
|
|
276
276
|
const token = await this.selectToken(model, req.preferredTokenId);
|
|
277
277
|
|
|
278
278
|
if (!token) throw new Error("No anthropic tokens available");
|
|
279
|
+
req.onProgress?.({ tokenName: token.name, model });
|
|
279
280
|
|
|
280
281
|
// 만료 직전에 갱신하되 실패하면 기존 토큰으로 진행한다.
|
|
281
282
|
let accessToken = token.credentials.accessToken;
|
|
@@ -318,6 +319,7 @@ export class AnthropicDispatcher implements ProviderDispatcher {
|
|
|
318
319
|
input: req.coldInput,
|
|
319
320
|
abortSignal: req.abortSignal,
|
|
320
321
|
includePartialMessages: opts?.includePartialMessages,
|
|
322
|
+
onTtft: req.onProgress ? (ttftMs) => req.onProgress?.({ ttftMs }) : undefined,
|
|
321
323
|
},
|
|
322
324
|
onDelta,
|
|
323
325
|
);
|
|
@@ -113,6 +113,8 @@ export interface ClaudeSessionRequest {
|
|
|
113
113
|
input: Array<UserInput>;
|
|
114
114
|
abortSignal?: AbortSignal;
|
|
115
115
|
includePartialMessages?: boolean;
|
|
116
|
+
/** Called once with the measured TTFT when the first delta arrives. */
|
|
117
|
+
onTtft?: (ttftMs: number) => void;
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
export interface ClaudeSessionResult extends ClaudeStreamResult {
|
|
@@ -364,7 +366,19 @@ export function runClaudeSession(
|
|
|
364
366
|
let buffer = "";
|
|
365
367
|
const streamState: ClaudeStreamJsonState = {};
|
|
366
368
|
const ttftTracker = createTtftTracker();
|
|
367
|
-
|
|
369
|
+
let ttftReported = false;
|
|
370
|
+
|
|
371
|
+
const onTrackedDelta = ttftTracker.wrapDelta((text) => {
|
|
372
|
+
const ttftMs = ttftTracker.value();
|
|
373
|
+
|
|
374
|
+
if (!ttftReported && ttftMs !== null) {
|
|
375
|
+
ttftReported = true;
|
|
376
|
+
req.onTtft?.(ttftMs);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
onDelta(text);
|
|
380
|
+
});
|
|
381
|
+
|
|
368
382
|
// bounded stderr 버퍼(최근 ~4KB만 유지 — 무한 누적 방지).
|
|
369
383
|
let stderrBuf = "";
|
|
370
384
|
const STDERR_CAP = 4096;
|
|
@@ -127,6 +127,16 @@ export interface GenerateRequest {
|
|
|
127
127
|
providerOptions?: { [key: string]: JsonValue | undefined };
|
|
128
128
|
// Native tools for providers that accept them on the wire (Grok).
|
|
129
129
|
tools?: ToolDefinition[];
|
|
130
|
+
// Reports run facts as soon as they are known, before the turn completes. Each call carries only
|
|
131
|
+
// the fields that just became known; a failover reports the next token again.
|
|
132
|
+
onProgress?: (progress: GenerateProgress) => void;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export interface GenerateProgress {
|
|
136
|
+
tokenName?: string;
|
|
137
|
+
/** Serving model without the provider prefix. */
|
|
138
|
+
model?: string;
|
|
139
|
+
ttftMs?: number;
|
|
130
140
|
}
|
|
131
141
|
|
|
132
142
|
export interface GenerateResult {
|
|
@@ -39,7 +39,12 @@ export type GrokFunctionTool = {
|
|
|
39
39
|
strict: boolean;
|
|
40
40
|
};
|
|
41
41
|
|
|
42
|
-
export type GrokTool =
|
|
42
|
+
export type GrokTool =
|
|
43
|
+
| GrokFunctionTool
|
|
44
|
+
| { type: "web_search" }
|
|
45
|
+
| { type: "x_search" }
|
|
46
|
+
// Server-side Grok Imagine tool; results arrive as `image_generation_call` output items.
|
|
47
|
+
| { type: "image_generation" };
|
|
43
48
|
|
|
44
49
|
export type GrokToolChoice = "auto" | "none" | "required" | { type: "function"; name: string };
|
|
45
50
|
|
|
@@ -449,6 +449,17 @@ describe("GrokDispatcher selection", () => {
|
|
|
449
449
|
expect(h.events).toEqual([]);
|
|
450
450
|
});
|
|
451
451
|
|
|
452
|
+
it("refreshUsage reads billing for a token without a quota threshold", async () => {
|
|
453
|
+
const h = createHarness();
|
|
454
|
+
h.add(1);
|
|
455
|
+
h.billing.set(1, billingAt(12));
|
|
456
|
+
|
|
457
|
+
await h.dispatcher.refreshUsage(1);
|
|
458
|
+
|
|
459
|
+
expect(h.dispatcher.tokenStates()[0]?.lastBilling).toMatchObject({ utilizationPct: 12 });
|
|
460
|
+
expect(h.events.some((event) => event.startsWith("/billing"))).toBe(true);
|
|
461
|
+
});
|
|
462
|
+
|
|
452
463
|
it("blocks over-threshold tokens and reports QuotaThresholdExceededError", async () => {
|
|
453
464
|
const h = createHarness();
|
|
454
465
|
h.add(1, 1, 50);
|
|
@@ -529,9 +540,9 @@ describe("GrokDispatcher chat", () => {
|
|
|
529
540
|
it("rejects fields Grok does not support", async () => {
|
|
530
541
|
const h = createHarness();
|
|
531
542
|
h.add(1);
|
|
532
|
-
await expect(
|
|
533
|
-
|
|
534
|
-
);
|
|
543
|
+
await expect(
|
|
544
|
+
h.dispatcher.generate(request({ imageGenerationOptions: { quality: "high" } })),
|
|
545
|
+
).rejects.toBeInstanceOf(GrokInvalidRequestError);
|
|
535
546
|
await expect(h.dispatcher.generate(request({ serviceTier: "fast" }))).rejects.toBeInstanceOf(
|
|
536
547
|
GrokInvalidRequestError,
|
|
537
548
|
);
|
|
@@ -829,6 +840,66 @@ describe("GrokDispatcher chat", () => {
|
|
|
829
840
|
// Media routing
|
|
830
841
|
// ---------------------------------------------------------------------------
|
|
831
842
|
|
|
843
|
+
describe("GrokDispatcher image generation tool", () => {
|
|
844
|
+
it("adds the server-side image tool and returns completed images", async () => {
|
|
845
|
+
const h = createHarness();
|
|
846
|
+
h.add(1);
|
|
847
|
+
const imageItem = {
|
|
848
|
+
type: "image_generation_call",
|
|
849
|
+
id: "ig_1",
|
|
850
|
+
status: "completed",
|
|
851
|
+
result: "/9j/4AAQSkZJRg",
|
|
852
|
+
prompt: "a small red apple",
|
|
853
|
+
};
|
|
854
|
+
h.chat.set(1, [
|
|
855
|
+
{
|
|
856
|
+
kind: "ok",
|
|
857
|
+
body: [
|
|
858
|
+
sseEvent({ type: "response.created", response: { id: "resp_1", model: "grok-4.7" } }),
|
|
859
|
+
sseEvent({ type: "response.output_item.done", item: imageItem }),
|
|
860
|
+
sseEvent({ type: "response.output_text.delta", item_id: "msg_1", delta: "Here it is." }),
|
|
861
|
+
sseEvent({
|
|
862
|
+
type: "response.completed",
|
|
863
|
+
response: { id: "resp_1", model: "grok-4.7", usage: golden.response.terminalUsage },
|
|
864
|
+
}),
|
|
865
|
+
].join(""),
|
|
866
|
+
},
|
|
867
|
+
]);
|
|
868
|
+
|
|
869
|
+
const result = await h.dispatcher.generate(request({ imageGeneration: "auto" }));
|
|
870
|
+
|
|
871
|
+
expect(h.requests[0]?.body).toMatchObject({ tools: [{ type: "image_generation" }] });
|
|
872
|
+
expect(result.text).toBe("Here it is.");
|
|
873
|
+
expect(result.images).toEqual([
|
|
874
|
+
{ data: "/9j/4AAQSkZJRg", mediaType: "image/jpeg", revisedPrompt: "a small red apple" },
|
|
875
|
+
]);
|
|
876
|
+
});
|
|
877
|
+
|
|
878
|
+
it("reports the token, serving model, and TTFT as progress", async () => {
|
|
879
|
+
const h = createHarness();
|
|
880
|
+
h.add(1);
|
|
881
|
+
const progress = vi.fn();
|
|
882
|
+
|
|
883
|
+
await h.dispatcher.generate(request({ onProgress: progress }));
|
|
884
|
+
|
|
885
|
+
expect(progress.mock.calls.map(([update]) => update)).toEqual([
|
|
886
|
+
{ tokenName: "t1" },
|
|
887
|
+
{ model: "grok-4.7" },
|
|
888
|
+
{ ttftMs: expect.any(Number) },
|
|
889
|
+
]);
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
it("sends no image tool without imageGeneration", async () => {
|
|
893
|
+
const h = createHarness();
|
|
894
|
+
h.add(1);
|
|
895
|
+
|
|
896
|
+
const result = await h.dispatcher.generate(request());
|
|
897
|
+
|
|
898
|
+
expect(h.requests[0]?.body).not.toHaveProperty("tools");
|
|
899
|
+
expect(result.images).toBeUndefined();
|
|
900
|
+
});
|
|
901
|
+
});
|
|
902
|
+
|
|
832
903
|
describe("GrokDispatcher media", () => {
|
|
833
904
|
it("blocks the request class on media 403 and fails over once", async () => {
|
|
834
905
|
const seen: string[] = [];
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
type GenerateRequest,
|
|
13
13
|
type GenerateResult,
|
|
14
14
|
type GenerateStreamCallbacks,
|
|
15
|
+
type GeneratedImage,
|
|
15
16
|
type MediaDispatcher,
|
|
16
17
|
type MediaDispatchResult,
|
|
17
18
|
type MediaTokenSelection,
|
|
@@ -379,6 +380,23 @@ function historyItems(history: readonly JsonValue[] | undefined): GrokInputItem[
|
|
|
379
380
|
});
|
|
380
381
|
}
|
|
381
382
|
|
|
383
|
+
/** A completed `image_generation_call` item's base64 result; the proxy returns JPEG. */
|
|
384
|
+
function grokGeneratedImage(
|
|
385
|
+
result: JsonValue | undefined,
|
|
386
|
+
prompt: JsonValue | undefined,
|
|
387
|
+
): GeneratedImage | undefined {
|
|
388
|
+
const data = jsonString(result);
|
|
389
|
+
|
|
390
|
+
if (!data) return undefined;
|
|
391
|
+
|
|
392
|
+
let mediaType: GeneratedImage["mediaType"] = "image/jpeg";
|
|
393
|
+
|
|
394
|
+
if (data.startsWith("iVBORw0KGgo")) mediaType = "image/png";
|
|
395
|
+
else if (data.startsWith("UklGR")) mediaType = "image/webp";
|
|
396
|
+
|
|
397
|
+
return { data, mediaType, revisedPrompt: jsonString(prompt) ?? null };
|
|
398
|
+
}
|
|
399
|
+
|
|
382
400
|
function userMessage(req: GenerateRequest): GrokInputItem {
|
|
383
401
|
const content: GrokInputContentPart[] = req.coldInput.map((input) => {
|
|
384
402
|
if (input.type === "text") return { type: "input_text", text: input.text };
|
|
@@ -820,21 +838,29 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
820
838
|
* Refreshes the 60 s settings/subscription/billing caches. Lookup failures fail open, so an
|
|
821
839
|
* expired bearer is refreshed first: a lookup with it would fail and open every gate. A failed
|
|
822
840
|
* refresh therefore takes the token out of selection (`refresh_failed`) instead of failing open.
|
|
841
|
+
* Billing is read only when a threshold or quota block gates the token, unless `includeBilling`.
|
|
823
842
|
*/
|
|
824
|
-
async prefetch(
|
|
843
|
+
async prefetch(
|
|
844
|
+
token: GrokTokenState,
|
|
845
|
+
signal?: AbortSignal,
|
|
846
|
+
includeBilling = false,
|
|
847
|
+
): Promise<void> {
|
|
825
848
|
if (!token.credentials || token.invalidReason || token.reauthRequired) return;
|
|
826
849
|
let now = this.now();
|
|
827
850
|
const tasks: Promise<void>[] = [];
|
|
828
851
|
|
|
852
|
+
const wantsBilling = () =>
|
|
853
|
+
includeBilling ||
|
|
854
|
+
token.quotaThreshold !== null ||
|
|
855
|
+
[...token.quotaBlocks.values()].some((until) => until > now);
|
|
856
|
+
|
|
829
857
|
const stale = (entry: Cached<unknown> | undefined) =>
|
|
830
858
|
!entry ||
|
|
831
859
|
entry.generation !== token.generation ||
|
|
832
860
|
now - entry.fetchedAt >= GROK_LOOKUP_CACHE_TTL_MS;
|
|
833
861
|
|
|
834
862
|
const billingDue = () =>
|
|
835
|
-
(
|
|
836
|
-
stale(token.billing) &&
|
|
837
|
-
now >= token.billingNotBefore;
|
|
863
|
+
wantsBilling() && stale(token.billing) && now >= token.billingNotBefore;
|
|
838
864
|
|
|
839
865
|
if (!stale(token.settings) && !stale(token.subscription) && !billingDue()) return;
|
|
840
866
|
|
|
@@ -864,15 +890,22 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
864
890
|
if (stale(token.settings)) tasks.push(this.loadSettings(token));
|
|
865
891
|
|
|
866
892
|
if (stale(token.subscription)) tasks.push(this.loadSubscription(token));
|
|
867
|
-
const blocked = [...token.quotaBlocks.values()].some((until) => until > now);
|
|
868
893
|
|
|
869
|
-
if ((
|
|
870
|
-
if (now >= token.billingNotBefore) tasks.push(this.loadBilling(token));
|
|
871
|
-
}
|
|
894
|
+
if (billingDue()) tasks.push(this.loadBilling(token));
|
|
872
895
|
|
|
873
896
|
await Promise.all(tasks);
|
|
874
897
|
}
|
|
875
898
|
|
|
899
|
+
/**
|
|
900
|
+
* Usage view: refreshes a token's stale lookups, billing included, so the dashboard shows usage
|
|
901
|
+
* before any request has routed through the token. The 60 s cache bounds the xAI calls.
|
|
902
|
+
*/
|
|
903
|
+
async refreshUsage(tokenId: number): Promise<void> {
|
|
904
|
+
const token = this.tokens.get(tokenId);
|
|
905
|
+
|
|
906
|
+
if (token) await this.prefetch(token, undefined, true);
|
|
907
|
+
}
|
|
908
|
+
|
|
876
909
|
/** Transient refresh failure for `presented`; ignored when the token already holds newer ones. */
|
|
877
910
|
markRefreshFailed(token: GrokTokenState, presented: GrokCredentials, cause: unknown): void {
|
|
878
911
|
if (this.tokens.get(token.id) !== token || !sameCredentials(token.credentials, presented))
|
|
@@ -1621,12 +1654,8 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
1621
1654
|
}
|
|
1622
1655
|
|
|
1623
1656
|
buildChatBody(req: GenerateRequest): GrokChatBody {
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
"imageGeneration is not supported on grok chat models; use the Grok image endpoint",
|
|
1627
|
-
);
|
|
1628
|
-
}
|
|
1629
|
-
|
|
1657
|
+
// imageGeneration enables the server-side image tool below; OpenAI's quality/size/background
|
|
1658
|
+
// options have no Grok equivalent.
|
|
1630
1659
|
if (req.imageGenerationOptions !== undefined) {
|
|
1631
1660
|
throw new GrokInvalidRequestError(
|
|
1632
1661
|
"imageGenerationOptions is not supported on grok chat models",
|
|
@@ -1679,7 +1708,10 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
1679
1708
|
const turnIdx =
|
|
1680
1709
|
history.filter((item) => item.type === "message" && item.role === "user").length + 1;
|
|
1681
1710
|
|
|
1682
|
-
|
|
1711
|
+
// imageGeneration lets the model call the proxy's server-side image tool during the turn.
|
|
1712
|
+
const tools = req.imageGeneration
|
|
1713
|
+
? [...(grokTools(req.tools) ?? []), { type: "image_generation" as const }]
|
|
1714
|
+
: grokTools(req.tools);
|
|
1683
1715
|
|
|
1684
1716
|
const body = buildGrokResponsesRequest({
|
|
1685
1717
|
model: model.id,
|
|
@@ -1741,6 +1773,7 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
1741
1773
|
): Promise<GenerateResult> {
|
|
1742
1774
|
const { req, model } = context;
|
|
1743
1775
|
const startedAt = this.now();
|
|
1776
|
+
req.onProgress?.({ tokenName: token.name });
|
|
1744
1777
|
|
|
1745
1778
|
const headers = buildGrokChatHeaders({
|
|
1746
1779
|
bearer: credentials.accessToken,
|
|
@@ -1787,16 +1820,25 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
1787
1820
|
let servingModel = model.id;
|
|
1788
1821
|
let outputMessageAccepted = false;
|
|
1789
1822
|
const toolCalls: ProviderToolCall[] = [];
|
|
1823
|
+
const images: GeneratedImage[] = [];
|
|
1790
1824
|
let completed = false;
|
|
1791
1825
|
|
|
1792
1826
|
for await (const event of stream.events) {
|
|
1793
1827
|
state.upstreamStarted = true;
|
|
1794
1828
|
|
|
1795
1829
|
if (event.type === "created") {
|
|
1796
|
-
if (event.model)
|
|
1830
|
+
if (event.model) {
|
|
1831
|
+
servingModel = event.model;
|
|
1832
|
+
req.onProgress?.({ model: event.model });
|
|
1833
|
+
}
|
|
1797
1834
|
} else if (event.type === "text-delta") {
|
|
1798
1835
|
if (outputMessageAccepted) continue;
|
|
1799
|
-
|
|
1836
|
+
|
|
1837
|
+
if (firstDeltaAt === undefined) {
|
|
1838
|
+
firstDeltaAt = this.now();
|
|
1839
|
+
req.onProgress?.({ ttftMs: firstDeltaAt - startedAt });
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1800
1842
|
text += event.text;
|
|
1801
1843
|
|
|
1802
1844
|
if (context.onDelta) {
|
|
@@ -1806,7 +1848,11 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
1806
1848
|
} else if (event.type === "output-item" && event.completed) {
|
|
1807
1849
|
const item = event.item;
|
|
1808
1850
|
|
|
1809
|
-
if (item.type === "
|
|
1851
|
+
if (item.type === "image_generation_call") {
|
|
1852
|
+
const image = grokGeneratedImage(item.result, item.prompt);
|
|
1853
|
+
|
|
1854
|
+
if (image) images.push(image);
|
|
1855
|
+
} else if (item.type === "function_call") {
|
|
1810
1856
|
const callId = jsonString(item.call_id);
|
|
1811
1857
|
const name = jsonString(item.name);
|
|
1812
1858
|
const args = jsonString(item.arguments);
|
|
@@ -1890,6 +1936,8 @@ export class GrokDispatcher implements GrokProviderDispatcher, MediaDispatcher,
|
|
|
1890
1936
|
|
|
1891
1937
|
if (toolCalls.length) result.toolCalls = toolCalls;
|
|
1892
1938
|
|
|
1939
|
+
if (images.length) result.images = images;
|
|
1940
|
+
|
|
1893
1941
|
return result;
|
|
1894
1942
|
}
|
|
1895
1943
|
|
|
@@ -56,6 +56,24 @@ describe("readGrokBilling", () => {
|
|
|
56
56
|
});
|
|
57
57
|
});
|
|
58
58
|
|
|
59
|
+
it("reads an omitted creditUsagePercent as 0% for a period without usage", async () => {
|
|
60
|
+
const result = await readGrokBilling(credentials, {
|
|
61
|
+
fetch: fetchReturning({
|
|
62
|
+
config: {
|
|
63
|
+
currentPeriod: {
|
|
64
|
+
type: "USAGE_PERIOD_TYPE_WEEKLY",
|
|
65
|
+
start: "2026-10-15T00:00:00+00:00",
|
|
66
|
+
end: "2026-10-22T00:00:00+00:00",
|
|
67
|
+
},
|
|
68
|
+
onDemandCap: { val: 0 },
|
|
69
|
+
isUnifiedBillingUser: true,
|
|
70
|
+
prepaidBalance: { val: 0 },
|
|
71
|
+
},
|
|
72
|
+
}),
|
|
73
|
+
});
|
|
74
|
+
expect(result).toMatchObject({ kind: "ok", utilizationPct: 0, periodType: "USAGE_PERIOD_TYPE_WEEKLY" });
|
|
75
|
+
});
|
|
76
|
+
|
|
59
77
|
it("returns lookup_failed on HTTP errors and unexpected shapes", async () => {
|
|
60
78
|
expect(await readGrokBilling(credentials, { fetch: fetchReturning("nope", 500) })).toMatchObject({
|
|
61
79
|
kind: "lookup_failed",
|
|
@@ -93,7 +93,8 @@ export type GrokCredentials = z.infer<typeof GrokCredentials>;
|
|
|
93
93
|
/** `GET /billing?format=credits` (camelCase, no on-demand field; U0 item 3). */
|
|
94
94
|
export const GrokBillingConfig = z.looseObject({
|
|
95
95
|
config: z.looseObject({
|
|
96
|
-
|
|
96
|
+
// Protobuf JSON omits zero-valued scalars: a period with no usage arrives without this field.
|
|
97
|
+
creditUsagePercent: z.number().default(0),
|
|
97
98
|
currentPeriod: z.looseObject({
|
|
98
99
|
type: z.string(),
|
|
99
100
|
start: z.string(),
|