@copilotkit/aimock 1.37.3 → 1.38.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/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +35 -0
- package/README.md +27 -9
- package/dist/agui-recorder.cjs +6 -0
- package/dist/agui-recorder.cjs.map +1 -1
- package/dist/agui-recorder.d.cts.map +1 -1
- package/dist/agui-recorder.d.ts.map +1 -1
- package/dist/agui-recorder.js +6 -0
- package/dist/agui-recorder.js.map +1 -1
- package/dist/agui-types.d.ts.map +1 -1
- package/dist/api-key-auth.cjs +166 -0
- package/dist/api-key-auth.cjs.map +1 -0
- package/dist/api-key-auth.d.cts +17 -0
- package/dist/api-key-auth.d.cts.map +1 -0
- package/dist/api-key-auth.d.ts +17 -0
- package/dist/api-key-auth.d.ts.map +1 -0
- package/dist/api-key-auth.js +158 -0
- package/dist/api-key-auth.js.map +1 -0
- package/dist/cli.cjs +4 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +4 -1
- package/dist/cli.js.map +1 -1
- package/dist/config-loader.cjs +4 -2
- package/dist/config-loader.cjs.map +1 -1
- package/dist/config-loader.d.cts +2 -1
- package/dist/config-loader.d.cts.map +1 -1
- package/dist/config-loader.d.ts +2 -1
- package/dist/config-loader.d.ts.map +1 -1
- package/dist/config-loader.js +5 -3
- package/dist/config-loader.js.map +1 -1
- package/dist/fal-audio.cjs +2 -0
- package/dist/fal-audio.cjs.map +1 -1
- package/dist/fal-audio.d.cts.map +1 -1
- package/dist/fal-audio.d.ts.map +1 -1
- package/dist/fal-audio.js +2 -0
- package/dist/fal-audio.js.map +1 -1
- package/dist/fal.cjs +4 -1
- package/dist/fal.cjs.map +1 -1
- package/dist/fal.d.cts.map +1 -1
- package/dist/fal.d.ts.map +1 -1
- package/dist/fal.js +4 -1
- package/dist/fal.js.map +1 -1
- package/dist/fixture-loader.cjs +0 -0
- package/dist/fixture-loader.cjs.map +1 -1
- package/dist/fixture-loader.d.cts +3 -1
- package/dist/fixture-loader.d.cts.map +1 -1
- package/dist/fixture-loader.d.ts +3 -1
- package/dist/fixture-loader.d.ts.map +1 -1
- package/dist/fixture-loader.js +0 -0
- package/dist/fixture-loader.js.map +1 -1
- package/dist/grok-video.cjs +9 -2
- package/dist/grok-video.cjs.map +1 -1
- package/dist/grok-video.js +10 -3
- package/dist/grok-video.js.map +1 -1
- package/dist/helpers.cjs +16 -22
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +16 -21
- package/dist/helpers.js.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/llmock.cjs +14 -3
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +4 -2
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +4 -2
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +15 -5
- package/dist/llmock.js.map +1 -1
- package/dist/messages.cjs +4 -4
- package/dist/messages.cjs.map +1 -1
- package/dist/messages.d.cts.map +1 -1
- package/dist/messages.d.ts.map +1 -1
- package/dist/messages.js +4 -4
- package/dist/messages.js.map +1 -1
- package/dist/openrouter-chat.cjs +333 -0
- package/dist/openrouter-chat.cjs.map +1 -0
- package/dist/openrouter-chat.js +325 -0
- package/dist/openrouter-chat.js.map +1 -0
- package/dist/openrouter-video.cjs +24 -7
- package/dist/openrouter-video.cjs.map +1 -1
- package/dist/openrouter-video.d.cts.map +1 -1
- package/dist/openrouter-video.d.ts.map +1 -1
- package/dist/openrouter-video.js +25 -8
- package/dist/openrouter-video.js.map +1 -1
- package/dist/provider-auth.cjs +20 -0
- package/dist/provider-auth.cjs.map +1 -1
- package/dist/provider-auth.js +20 -1
- package/dist/provider-auth.js.map +1 -1
- package/dist/recorder.cjs +51 -9
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.d.cts.map +1 -1
- package/dist/recorder.d.ts.map +1 -1
- package/dist/recorder.js +52 -12
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +200 -89
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts +18 -3
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts +18 -3
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +199 -90
- package/dist/responses.js.map +1 -1
- package/dist/router.cjs +41 -6
- package/dist/router.cjs.map +1 -1
- package/dist/router.d.cts.map +1 -1
- package/dist/router.d.ts.map +1 -1
- package/dist/router.js +41 -7
- package/dist/router.js.map +1 -1
- package/dist/server.cjs +156 -66
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +1 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +157 -68
- package/dist/server.js.map +1 -1
- package/dist/sse-writer.cjs +3 -0
- package/dist/sse-writer.cjs.map +1 -1
- package/dist/sse-writer.d.cts +8 -0
- package/dist/sse-writer.d.cts.map +1 -1
- package/dist/sse-writer.d.ts +8 -0
- package/dist/sse-writer.d.ts.map +1 -1
- package/dist/sse-writer.js +3 -0
- package/dist/sse-writer.js.map +1 -1
- package/dist/stream-collapse.cjs +26 -0
- package/dist/stream-collapse.cjs.map +1 -1
- package/dist/stream-collapse.d.cts +7 -0
- package/dist/stream-collapse.d.cts.map +1 -1
- package/dist/stream-collapse.d.ts +7 -0
- package/dist/stream-collapse.d.ts.map +1 -1
- package/dist/stream-collapse.js +26 -0
- package/dist/stream-collapse.js.map +1 -1
- package/dist/transcription.cjs +49 -2
- package/dist/transcription.cjs.map +1 -1
- package/dist/transcription.d.cts.map +1 -1
- package/dist/transcription.d.ts.map +1 -1
- package/dist/transcription.js +50 -3
- package/dist/transcription.js.map +1 -1
- package/dist/types.d.cts +202 -5
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +202 -5
- package/dist/types.d.ts.map +1 -1
- package/dist/vector-types.d.cts.map +1 -1
- package/dist/veo-video.cjs +9 -2
- package/dist/veo-video.cjs.map +1 -1
- package/dist/veo-video.js +10 -3
- package/dist/veo-video.js.map +1 -1
- package/dist/ws-realtime.cjs +306 -57
- package/dist/ws-realtime.cjs.map +1 -1
- package/dist/ws-realtime.d.cts +1 -0
- package/dist/ws-realtime.d.cts.map +1 -1
- package/dist/ws-realtime.d.ts +1 -0
- package/dist/ws-realtime.d.ts.map +1 -1
- package/dist/ws-realtime.js +307 -58
- package/dist/ws-realtime.js.map +1 -1
- package/dist/ws-responses.cjs +11 -6
- package/dist/ws-responses.cjs.map +1 -1
- package/dist/ws-responses.d.cts.map +1 -1
- package/dist/ws-responses.d.ts.map +1 -1
- package/dist/ws-responses.js +12 -7
- package/dist/ws-responses.js.map +1 -1
- package/package.json +1 -1
- package/skills/write-fixtures/SKILL.md +81 -47
package/dist/transcription.cjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_helpers = require('./helpers.cjs');
|
|
2
2
|
const require_router = require('./router.cjs');
|
|
3
3
|
const require_sse_writer = require('./sse-writer.cjs');
|
|
4
|
+
const require_interruption = require('./interruption.cjs');
|
|
4
5
|
const require_chaos = require('./chaos.cjs');
|
|
5
6
|
const require_recorder = require('./recorder.cjs');
|
|
6
7
|
|
|
@@ -46,6 +47,7 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
46
47
|
const boundary = extractBoundary(Array.isArray(req.headers["content-type"]) ? req.headers["content-type"][0] : req.headers["content-type"]);
|
|
47
48
|
const model = extractFormField(raw, "model", boundary) ?? "whisper-1";
|
|
48
49
|
const responseFormat = extractFormField(raw, "response_format", boundary) ?? "json";
|
|
50
|
+
const stream = extractFormField(raw, "stream", boundary) === "true";
|
|
49
51
|
const syntheticReq = {
|
|
50
52
|
model,
|
|
51
53
|
messages: [],
|
|
@@ -155,7 +157,7 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
155
157
|
} }));
|
|
156
158
|
return;
|
|
157
159
|
}
|
|
158
|
-
journal.add({
|
|
160
|
+
const journalEntry = journal.add({
|
|
159
161
|
method,
|
|
160
162
|
path,
|
|
161
163
|
headers: require_helpers.flattenHeaders(req.headers),
|
|
@@ -166,6 +168,47 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
166
168
|
}
|
|
167
169
|
});
|
|
168
170
|
const t = response.transcription;
|
|
171
|
+
if (endpointType === "transcription" && stream && model !== "whisper-1") {
|
|
172
|
+
const done = {
|
|
173
|
+
type: "transcript.text.done",
|
|
174
|
+
text: t.text,
|
|
175
|
+
...t.languages !== void 0 ? { languages: t.languages } : {},
|
|
176
|
+
...t.usage !== void 0 ? { usage: t.usage } : {}
|
|
177
|
+
};
|
|
178
|
+
const latency = fixture.latency ?? defaults.latency;
|
|
179
|
+
const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);
|
|
180
|
+
const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;
|
|
181
|
+
res.writeHead(200, {
|
|
182
|
+
"Content-Type": "text/event-stream",
|
|
183
|
+
"Cache-Control": "no-cache",
|
|
184
|
+
Connection: "keep-alive"
|
|
185
|
+
});
|
|
186
|
+
let chunkIndex = 0;
|
|
187
|
+
const interruption = require_interruption.createInterruptionSignal(fixture);
|
|
188
|
+
for (let index = 0; index < t.text.length; index += chunkSize) {
|
|
189
|
+
const chunkDelay = require_sse_writer.calculateDelay(chunkIndex, fixture.streamingProfile, latency, fixture.recordedTimings, replaySpeed);
|
|
190
|
+
if (chunkDelay > 0) await require_sse_writer.delay(chunkDelay, interruption?.signal);
|
|
191
|
+
if (interruption?.signal.aborted) break;
|
|
192
|
+
res.write(`data: ${JSON.stringify({
|
|
193
|
+
type: "transcript.text.delta",
|
|
194
|
+
delta: t.text.slice(index, index + chunkSize)
|
|
195
|
+
})}\n\n`);
|
|
196
|
+
interruption?.tick();
|
|
197
|
+
chunkIndex++;
|
|
198
|
+
}
|
|
199
|
+
if (interruption?.signal.aborted) {
|
|
200
|
+
journalEntry.response.interrupted = true;
|
|
201
|
+
journalEntry.response.interruptReason = interruption.reason();
|
|
202
|
+
interruption.cleanup();
|
|
203
|
+
res.destroy();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
res.write(`data: ${JSON.stringify(done)}\n\n`);
|
|
207
|
+
res.write("data: [DONE]\n\n");
|
|
208
|
+
res.end();
|
|
209
|
+
interruption?.cleanup();
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
169
212
|
if (responseFormat === "verbose_json" || t.words != null || t.segments != null) {
|
|
170
213
|
const verboseBody = {
|
|
171
214
|
task: endpointType === "translation" ? "translate" : "transcribe",
|
|
@@ -179,7 +222,11 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
179
222
|
res.end(JSON.stringify(verboseBody));
|
|
180
223
|
} else {
|
|
181
224
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
182
|
-
res.end(JSON.stringify({
|
|
225
|
+
res.end(JSON.stringify({
|
|
226
|
+
text: t.text,
|
|
227
|
+
...t.languages !== void 0 ? { languages: t.languages } : {},
|
|
228
|
+
...t.usage !== void 0 ? { usage: t.usage } : {}
|
|
229
|
+
}));
|
|
183
230
|
}
|
|
184
231
|
}
|
|
185
232
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcription.cjs","names":["getContext","getTestId","matchFixtureDiagnostic","applyChaos","flattenHeaders","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","proxyAndRecord","resolveResponse","isErrorResponse","serializeErrorResponse","isTranscriptionResponse"],"sources":["../src/transcription.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport {\n isTranscriptionResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n/**\n * Extract the multipart boundary string from a Content-Type header.\n */\nexport function extractBoundary(contentType: string | undefined): string | undefined {\n if (!contentType) return undefined;\n const match = contentType.match(/boundary=([^\\s;]+)/i);\n return match?.[1];\n}\n\n/**\n * Extract a text field from multipart form data using boundary-based parsing.\n * Splits the body by the multipart boundary so each part is isolated, then\n * checks each part's Content-Disposition header for the target field name.\n * This avoids false matches from binary audio data that might contain\n * header-like byte sequences.\n */\nexport function extractFormField(\n raw: string,\n fieldName: string,\n boundary: string | undefined,\n): string | undefined {\n if (!boundary) {\n // Fallback: no boundary available, use simple regex (best-effort)\n console.warn(\"extractFormField: no multipart boundary found, using best-effort regex fallback\");\n const escaped = fieldName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(\n `Content-Disposition:\\\\s*form-data;[^\\\\r\\\\n]*name=\"${escaped}\"[^\\\\r\\\\n]*\\\\r\\\\n\\\\r\\\\n([^\\\\r\\\\n]*)`,\n \"i\",\n );\n const match = raw.match(pattern);\n return match?.[1];\n }\n\n // Split by boundary delimiter — each chunk is one part\n const delimiter = `--${boundary}`;\n const parts = raw.split(delimiter);\n\n for (const part of parts) {\n // Skip the preamble (before first boundary) and epilogue (after closing boundary)\n if (!part || part.trimStart().startsWith(\"--\")) continue;\n\n // Split part into headers and body at the first blank line (\\r\\n\\r\\n)\n const headerEnd = part.indexOf(\"\\r\\n\\r\\n\");\n if (headerEnd === -1) continue;\n\n const headers = part.slice(0, headerEnd);\n const body = part.slice(headerEnd + 4);\n\n // Check if this part's Content-Disposition names the target field\n const cdMatch = headers.match(/Content-Disposition:\\s*form-data;[^\\r\\n]*name=\"([^\"]+)\"/i);\n if (cdMatch && cdMatch[1] === fieldName) {\n // Return the body value, trimming trailing \\r\\n from the part boundary\n return body.replace(/\\r\\n$/, \"\");\n }\n }\n return undefined;\n}\n\nexport async function handleTranscription(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n endpointType: \"transcription\" | \"translation\" = \"transcription\",\n): Promise<void> {\n setCorsHeaders(res);\n const defaultPath =\n endpointType === \"translation\" ? \"/v1/audio/translations\" : \"/v1/audio/transcriptions\";\n const path = req.url ?? defaultPath;\n const method = req.method ?? \"POST\";\n\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n const boundary = extractBoundary(contentType);\n\n const model = extractFormField(raw, \"model\", boundary) ?? \"whisper-1\";\n const responseFormat = extractFormField(raw, \"response_format\", boundary) ?? \"json\";\n\n const syntheticReq: ChatCompletionRequest = {\n model,\n messages: [],\n _endpointType: endpointType,\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"openai\",\n req.url ?? defaultPath,\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isTranscriptionResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response is not a transcription type\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const t = response.transcription;\n const useVerbose = responseFormat === \"verbose_json\" || t.words != null || t.segments != null;\n\n if (useVerbose) {\n const verboseBody: Record<string, unknown> = {\n task: endpointType === \"translation\" ? \"translate\" : \"transcribe\",\n language: t.language ?? \"english\",\n duration: t.duration ?? 0,\n text: t.text,\n };\n if (t.words && t.words.length > 0) {\n verboseBody.words = t.words;\n }\n if (t.segments && t.segments.length > 0) {\n verboseBody.segments = t.segments;\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(verboseBody));\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ text: t.text }));\n }\n}\n"],"mappings":";;;;;;;;;;AAwBA,SAAgB,gBAAgB,aAAqD;AACnF,KAAI,CAAC,YAAa,QAAO;AAEzB,QADc,YAAY,MAAM,sBAAsB,GACvC;;;;;;;;;AAUjB,SAAgB,iBACd,KACA,WACA,UACoB;AACpB,KAAI,CAAC,UAAU;AAEb,UAAQ,KAAK,kFAAkF;EAC/F,MAAM,UAAU,UAAU,QAAQ,uBAAuB,OAAO;EAChE,MAAM,UAAU,IAAI,OAClB,qDAAqD,QAAQ,sCAC7D,IACD;AAED,SADc,IAAI,MAAM,QAAQ,GACjB;;CAIjB,MAAM,YAAY,KAAK;CACvB,MAAM,QAAQ,IAAI,MAAM,UAAU;AAElC,MAAK,MAAM,QAAQ,OAAO;AAExB,MAAI,CAAC,QAAQ,KAAK,WAAW,CAAC,WAAW,KAAK,CAAE;EAGhD,MAAM,YAAY,KAAK,QAAQ,WAAW;AAC1C,MAAI,cAAc,GAAI;EAEtB,MAAM,UAAU,KAAK,MAAM,GAAG,UAAU;EACxC,MAAM,OAAO,KAAK,MAAM,YAAY,EAAE;EAGtC,MAAM,UAAU,QAAQ,MAAM,2DAA2D;AACzF,MAAI,WAAW,QAAQ,OAAO,UAE5B,QAAO,KAAK,QAAQ,SAAS,GAAG;;;AAMtC,eAAsB,oBACpB,KACA,KACA,K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;AACF,wCACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GACL,SAAS;GACT,MAAM;GACP,EACF,CAAC,CACH;AACD;;AAGF,SAAQ,IAAI;EACV;EACA;EACA,SAASA,+BAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;CAEF,MAAM,IAAI,SAAS;AAGnB,KAFmB,mBAAmB,kBAAkB,EAAE,SAAS,QAAQ,EAAE,YAAY,MAEzE;EACd,MAAM,cAAuC;GAC3C,MAAM,iBAAiB,gBAAgB,cAAc;GACrD,UAAU,EAAE,YAAY;GACxB,UAAU,EAAE,YAAY;GACxB,MAAM,EAAE;GACT;AACD,MAAI,EAAE,SAAS,EAAE,MAAM,SAAS,EAC9B,aAAY,QAAQ,EAAE;AAExB,MAAI,EAAE,YAAY,EAAE,SAAS,SAAS,EACpC,aAAY,WAAW,EAAE;AAE3B,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU,YAAY,CAAC;QAC/B;AACL,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"transcription.cjs","names":["getContext","getTestId","matchFixtureDiagnostic","applyChaos","flattenHeaders","resolveStrictMode","strictNoMatchMessage","strictNoMatchLogLine","strictOverrideField","proxyAndRecord","resolveResponse","isErrorResponse","serializeErrorResponse","isTranscriptionResponse","createInterruptionSignal","calculateDelay","delay"],"sources":["../src/transcription.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport {\n isTranscriptionResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { calculateDelay, delay, writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\n\n/**\n * Extract the multipart boundary string from a Content-Type header.\n */\nexport function extractBoundary(contentType: string | undefined): string | undefined {\n if (!contentType) return undefined;\n const match = contentType.match(/boundary=([^\\s;]+)/i);\n return match?.[1];\n}\n\n/**\n * Extract a text field from multipart form data using boundary-based parsing.\n * Splits the body by the multipart boundary so each part is isolated, then\n * checks each part's Content-Disposition header for the target field name.\n * This avoids false matches from binary audio data that might contain\n * header-like byte sequences.\n */\nexport function extractFormField(\n raw: string,\n fieldName: string,\n boundary: string | undefined,\n): string | undefined {\n if (!boundary) {\n // Fallback: no boundary available, use simple regex (best-effort)\n console.warn(\"extractFormField: no multipart boundary found, using best-effort regex fallback\");\n const escaped = fieldName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(\n `Content-Disposition:\\\\s*form-data;[^\\\\r\\\\n]*name=\"${escaped}\"[^\\\\r\\\\n]*\\\\r\\\\n\\\\r\\\\n([^\\\\r\\\\n]*)`,\n \"i\",\n );\n const match = raw.match(pattern);\n return match?.[1];\n }\n\n // Split by boundary delimiter — each chunk is one part\n const delimiter = `--${boundary}`;\n const parts = raw.split(delimiter);\n\n for (const part of parts) {\n // Skip the preamble (before first boundary) and epilogue (after closing boundary)\n if (!part || part.trimStart().startsWith(\"--\")) continue;\n\n // Split part into headers and body at the first blank line (\\r\\n\\r\\n)\n const headerEnd = part.indexOf(\"\\r\\n\\r\\n\");\n if (headerEnd === -1) continue;\n\n const headers = part.slice(0, headerEnd);\n const body = part.slice(headerEnd + 4);\n\n // Check if this part's Content-Disposition names the target field\n const cdMatch = headers.match(/Content-Disposition:\\s*form-data;[^\\r\\n]*name=\"([^\"]+)\"/i);\n if (cdMatch && cdMatch[1] === fieldName) {\n // Return the body value, trimming trailing \\r\\n from the part boundary\n return body.replace(/\\r\\n$/, \"\");\n }\n }\n return undefined;\n}\n\nexport async function handleTranscription(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n endpointType: \"transcription\" | \"translation\" = \"transcription\",\n): Promise<void> {\n setCorsHeaders(res);\n const defaultPath =\n endpointType === \"translation\" ? \"/v1/audio/translations\" : \"/v1/audio/transcriptions\";\n const path = req.url ?? defaultPath;\n const method = req.method ?? \"POST\";\n\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n const boundary = extractBoundary(contentType);\n\n const model = extractFormField(raw, \"model\", boundary) ?? \"whisper-1\";\n const responseFormat = extractFormField(raw, \"response_format\", boundary) ?? \"json\";\n const stream = extractFormField(raw, \"stream\", boundary) === \"true\";\n\n const syntheticReq: ChatCompletionRequest = {\n model,\n messages: [],\n _endpointType: endpointType,\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"openai\",\n req.url ?? defaultPath,\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isTranscriptionResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response is not a transcription type\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n const journalEntry = journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const t = response.transcription;\n\n // Only the transcription endpoint streams modern models. Whisper-1 ignores\n // `stream=true`, and translations continue to return their JSON response.\n if (endpointType === \"transcription\" && stream && model !== \"whisper-1\") {\n const done = {\n type: \"transcript.text.done\",\n text: t.text,\n ...(t.languages !== undefined ? { languages: t.languages } : {}),\n ...(t.usage !== undefined ? { usage: t.usage } : {}),\n };\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n let chunkIndex = 0;\n const interruption = createInterruptionSignal(fixture);\n for (let index = 0; index < t.text.length; index += chunkSize) {\n const chunkDelay = calculateDelay(\n chunkIndex,\n fixture.streamingProfile,\n latency,\n fixture.recordedTimings,\n replaySpeed,\n );\n if (chunkDelay > 0) await delay(chunkDelay, interruption?.signal);\n if (interruption?.signal.aborted) break;\n res.write(\n `data: ${JSON.stringify({ type: \"transcript.text.delta\", delta: t.text.slice(index, index + chunkSize) })}\\n\\n`,\n );\n interruption?.tick();\n chunkIndex++;\n }\n if (interruption?.signal.aborted) {\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption.reason();\n interruption.cleanup();\n res.destroy();\n return;\n }\n res.write(`data: ${JSON.stringify(done)}\\n\\n`);\n // The live `gpt-transcribe&stream=true` stream ends with the `[DONE]`\n // sentinel after `transcript.text.done`. Omitting it leaves clients that\n // loop until the sentinel waiting on a stream that never terminates.\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n interruption?.cleanup();\n return;\n }\n\n const useVerbose = responseFormat === \"verbose_json\" || t.words != null || t.segments != null;\n\n if (useVerbose) {\n const verboseBody: Record<string, unknown> = {\n task: endpointType === \"translation\" ? \"translate\" : \"transcribe\",\n language: t.language ?? \"english\",\n duration: t.duration ?? 0,\n text: t.text,\n };\n if (t.words && t.words.length > 0) {\n verboseBody.words = t.words;\n }\n if (t.segments && t.segments.length > 0) {\n verboseBody.segments = t.segments;\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(verboseBody));\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n text: t.text,\n ...(t.languages !== undefined ? { languages: t.languages } : {}),\n ...(t.usage !== undefined ? { usage: t.usage } : {}),\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,SAAgB,gBAAgB,aAAqD;AACnF,KAAI,CAAC,YAAa,QAAO;AAEzB,QADc,YAAY,MAAM,sBAAsB,GACvC;;;;;;;;;AAUjB,SAAgB,iBACd,KACA,WACA,UACoB;AACpB,KAAI,CAAC,UAAU;AAEb,UAAQ,KAAK,kFAAkF;EAC/F,MAAM,UAAU,UAAU,QAAQ,uBAAuB,OAAO;EAChE,MAAM,UAAU,IAAI,OAClB,qDAAqD,QAAQ,sCAC7D,IACD;AAED,SADc,IAAI,MAAM,QAAQ,GACjB;;CAIjB,MAAM,YAAY,KAAK;CACvB,MAAM,QAAQ,IAAI,MAAM,UAAU;AAElC,MAAK,MAAM,QAAQ,OAAO;AAExB,MAAI,CAAC,QAAQ,KAAK,WAAW,CAAC,WAAW,KAAK,CAAE;EAGhD,MAAM,YAAY,KAAK,QAAQ,WAAW;AAC1C,MAAI,cAAc,GAAI;EAEtB,MAAM,UAAU,KAAK,MAAM,GAAG,UAAU;EACxC,MAAM,OAAO,KAAK,MAAM,YAAY,EAAE;EAGtC,MAAM,UAAU,QAAQ,MAAM,2DAA2D;AACzF,MAAI,WAAW,QAAQ,OAAO,UAE5B,QAAO,KAAK,QAAQ,SAAS,GAAG;;;AAMtC,eAAsB,oBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACA,eAAgD,iBACjC;AACf,gBAAe,IAAI;CACnB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AAI,SAAS;AACb;;AAEF,MAAI,MAAM,SAAS,KAAK,UAAU,KAAK,CAAC,MAAM;AAI9C,MAAI,MAAM,mBAAmB;AAC7B,MAAI,KAAK;AACT,gBAAc,SAAS;AACvB;;AAKF,KAFmB,mBAAmB,kBAAkB,EAAE,SAAS,QAAQ,EAAE,YAAY,MAEzE;EACd,MAAM,cAAuC;GAC3C,MAAM,iBAAiB,gBAAgB,cAAc;GACrD,UAAU,EAAE,YAAY;GACxB,UAAU,EAAE,YAAY;GACxB,MAAM,EAAE;GACT;AACD,MAAI,EAAE,SAAS,EAAE,MAAM,SAAS,EAC9B,aAAY,QAAQ,EAAE;AAExB,MAAI,EAAE,YAAY,EAAE,SAAS,SAAS,EACpC,aAAY,WAAW,EAAE;AAE3B,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU,YAAY,CAAC;QAC/B;AACL,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IACF,KAAK,UAAU;GACb,MAAM,EAAE;GACR,GAAI,EAAE,cAAc,SAAY,EAAE,WAAW,EAAE,WAAW,GAAG,EAAE;GAC/D,GAAI,EAAE,UAAU,SAAY,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE;GACpD,CAAC,CACH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcription.d.cts","names":[],"sources":["../src/transcription.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"transcription.d.cts","names":[],"sources":["../src/transcription.ts"],"sourcesContent":[],"mappings":";;;;;;iBAgFsB,mBAAA,MACf,MAAA,CAAK,sBACL,MAAA,CAAK,uCAEA,oBACD,mBACC,uCACY,MAAA,CAAK,0EAE1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcription.d.ts","names":[],"sources":["../src/transcription.ts"],"sourcesContent":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"transcription.d.ts","names":[],"sources":["../src/transcription.ts"],"sourcesContent":[],"mappings":";;;;;;iBAgFsB,mBAAA,MACf,MAAA,CAAK,sBACL,MAAA,CAAK,uCAEA,oBACD,mBACC,uCACY,MAAA,CAAK,0EAE1B"}
|
package/dist/transcription.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { flattenHeaders, getContext, getTestId, isErrorResponse, isTranscriptionResponse, resolveResponse, resolveStrictMode, serializeErrorResponse, strictNoMatchLogLine, strictNoMatchMessage, strictOverrideField } from "./helpers.js";
|
|
2
2
|
import { matchFixtureDiagnostic } from "./router.js";
|
|
3
|
-
import { writeErrorResponse } from "./sse-writer.js";
|
|
3
|
+
import { calculateDelay, delay, writeErrorResponse } from "./sse-writer.js";
|
|
4
|
+
import { createInterruptionSignal } from "./interruption.js";
|
|
4
5
|
import { applyChaos } from "./chaos.js";
|
|
5
6
|
import { proxyAndRecord } from "./recorder.js";
|
|
6
7
|
|
|
@@ -46,6 +47,7 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
46
47
|
const boundary = extractBoundary(Array.isArray(req.headers["content-type"]) ? req.headers["content-type"][0] : req.headers["content-type"]);
|
|
47
48
|
const model = extractFormField(raw, "model", boundary) ?? "whisper-1";
|
|
48
49
|
const responseFormat = extractFormField(raw, "response_format", boundary) ?? "json";
|
|
50
|
+
const stream = extractFormField(raw, "stream", boundary) === "true";
|
|
49
51
|
const syntheticReq = {
|
|
50
52
|
model,
|
|
51
53
|
messages: [],
|
|
@@ -155,7 +157,7 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
155
157
|
} }));
|
|
156
158
|
return;
|
|
157
159
|
}
|
|
158
|
-
journal.add({
|
|
160
|
+
const journalEntry = journal.add({
|
|
159
161
|
method,
|
|
160
162
|
path,
|
|
161
163
|
headers: flattenHeaders(req.headers),
|
|
@@ -166,6 +168,47 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
166
168
|
}
|
|
167
169
|
});
|
|
168
170
|
const t = response.transcription;
|
|
171
|
+
if (endpointType === "transcription" && stream && model !== "whisper-1") {
|
|
172
|
+
const done = {
|
|
173
|
+
type: "transcript.text.done",
|
|
174
|
+
text: t.text,
|
|
175
|
+
...t.languages !== void 0 ? { languages: t.languages } : {},
|
|
176
|
+
...t.usage !== void 0 ? { usage: t.usage } : {}
|
|
177
|
+
};
|
|
178
|
+
const latency = fixture.latency ?? defaults.latency;
|
|
179
|
+
const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);
|
|
180
|
+
const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;
|
|
181
|
+
res.writeHead(200, {
|
|
182
|
+
"Content-Type": "text/event-stream",
|
|
183
|
+
"Cache-Control": "no-cache",
|
|
184
|
+
Connection: "keep-alive"
|
|
185
|
+
});
|
|
186
|
+
let chunkIndex = 0;
|
|
187
|
+
const interruption = createInterruptionSignal(fixture);
|
|
188
|
+
for (let index = 0; index < t.text.length; index += chunkSize) {
|
|
189
|
+
const chunkDelay = calculateDelay(chunkIndex, fixture.streamingProfile, latency, fixture.recordedTimings, replaySpeed);
|
|
190
|
+
if (chunkDelay > 0) await delay(chunkDelay, interruption?.signal);
|
|
191
|
+
if (interruption?.signal.aborted) break;
|
|
192
|
+
res.write(`data: ${JSON.stringify({
|
|
193
|
+
type: "transcript.text.delta",
|
|
194
|
+
delta: t.text.slice(index, index + chunkSize)
|
|
195
|
+
})}\n\n`);
|
|
196
|
+
interruption?.tick();
|
|
197
|
+
chunkIndex++;
|
|
198
|
+
}
|
|
199
|
+
if (interruption?.signal.aborted) {
|
|
200
|
+
journalEntry.response.interrupted = true;
|
|
201
|
+
journalEntry.response.interruptReason = interruption.reason();
|
|
202
|
+
interruption.cleanup();
|
|
203
|
+
res.destroy();
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
res.write(`data: ${JSON.stringify(done)}\n\n`);
|
|
207
|
+
res.write("data: [DONE]\n\n");
|
|
208
|
+
res.end();
|
|
209
|
+
interruption?.cleanup();
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
169
212
|
if (responseFormat === "verbose_json" || t.words != null || t.segments != null) {
|
|
170
213
|
const verboseBody = {
|
|
171
214
|
task: endpointType === "translation" ? "translate" : "transcribe",
|
|
@@ -179,7 +222,11 @@ async function handleTranscription(req, res, raw, fixtures, journal, defaults, s
|
|
|
179
222
|
res.end(JSON.stringify(verboseBody));
|
|
180
223
|
} else {
|
|
181
224
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
182
|
-
res.end(JSON.stringify({
|
|
225
|
+
res.end(JSON.stringify({
|
|
226
|
+
text: t.text,
|
|
227
|
+
...t.languages !== void 0 ? { languages: t.languages } : {},
|
|
228
|
+
...t.usage !== void 0 ? { usage: t.usage } : {}
|
|
229
|
+
}));
|
|
183
230
|
}
|
|
184
231
|
}
|
|
185
232
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcription.js","names":[],"sources":["../src/transcription.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport {\n isTranscriptionResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n/**\n * Extract the multipart boundary string from a Content-Type header.\n */\nexport function extractBoundary(contentType: string | undefined): string | undefined {\n if (!contentType) return undefined;\n const match = contentType.match(/boundary=([^\\s;]+)/i);\n return match?.[1];\n}\n\n/**\n * Extract a text field from multipart form data using boundary-based parsing.\n * Splits the body by the multipart boundary so each part is isolated, then\n * checks each part's Content-Disposition header for the target field name.\n * This avoids false matches from binary audio data that might contain\n * header-like byte sequences.\n */\nexport function extractFormField(\n raw: string,\n fieldName: string,\n boundary: string | undefined,\n): string | undefined {\n if (!boundary) {\n // Fallback: no boundary available, use simple regex (best-effort)\n console.warn(\"extractFormField: no multipart boundary found, using best-effort regex fallback\");\n const escaped = fieldName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(\n `Content-Disposition:\\\\s*form-data;[^\\\\r\\\\n]*name=\"${escaped}\"[^\\\\r\\\\n]*\\\\r\\\\n\\\\r\\\\n([^\\\\r\\\\n]*)`,\n \"i\",\n );\n const match = raw.match(pattern);\n return match?.[1];\n }\n\n // Split by boundary delimiter — each chunk is one part\n const delimiter = `--${boundary}`;\n const parts = raw.split(delimiter);\n\n for (const part of parts) {\n // Skip the preamble (before first boundary) and epilogue (after closing boundary)\n if (!part || part.trimStart().startsWith(\"--\")) continue;\n\n // Split part into headers and body at the first blank line (\\r\\n\\r\\n)\n const headerEnd = part.indexOf(\"\\r\\n\\r\\n\");\n if (headerEnd === -1) continue;\n\n const headers = part.slice(0, headerEnd);\n const body = part.slice(headerEnd + 4);\n\n // Check if this part's Content-Disposition names the target field\n const cdMatch = headers.match(/Content-Disposition:\\s*form-data;[^\\r\\n]*name=\"([^\"]+)\"/i);\n if (cdMatch && cdMatch[1] === fieldName) {\n // Return the body value, trimming trailing \\r\\n from the part boundary\n return body.replace(/\\r\\n$/, \"\");\n }\n }\n return undefined;\n}\n\nexport async function handleTranscription(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n endpointType: \"transcription\" | \"translation\" = \"transcription\",\n): Promise<void> {\n setCorsHeaders(res);\n const defaultPath =\n endpointType === \"translation\" ? \"/v1/audio/translations\" : \"/v1/audio/transcriptions\";\n const path = req.url ?? defaultPath;\n const method = req.method ?? \"POST\";\n\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n const boundary = extractBoundary(contentType);\n\n const model = extractFormField(raw, \"model\", boundary) ?? \"whisper-1\";\n const responseFormat = extractFormField(raw, \"response_format\", boundary) ?? \"json\";\n\n const syntheticReq: ChatCompletionRequest = {\n model,\n messages: [],\n _endpointType: endpointType,\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"openai\",\n req.url ?? defaultPath,\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isTranscriptionResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response is not a transcription type\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const t = response.transcription;\n const useVerbose = responseFormat === \"verbose_json\" || t.words != null || t.segments != null;\n\n if (useVerbose) {\n const verboseBody: Record<string, unknown> = {\n task: endpointType === \"translation\" ? \"translate\" : \"transcribe\",\n language: t.language ?? \"english\",\n duration: t.duration ?? 0,\n text: t.text,\n };\n if (t.words && t.words.length > 0) {\n verboseBody.words = t.words;\n }\n if (t.segments && t.segments.length > 0) {\n verboseBody.segments = t.segments;\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(verboseBody));\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({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;AACD,MAAI,EAAE,SAAS,EAAE,MAAM,SAAS,EAC9B,aAAY,QAAQ,EAAE;AAExB,MAAI,EAAE,YAAY,EAAE,SAAS,SAAS,EACpC,aAAY,WAAW,EAAE;AAE3B,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU,YAAY,CAAC;QAC/B;AACL,MAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,MAAI,IAAI,KAAK,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"transcription.js","names":[],"sources":["../src/transcription.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport {\n isTranscriptionResponse,\n isErrorResponse,\n serializeErrorResponse,\n flattenHeaders,\n getTestId,\n resolveResponse,\n resolveStrictMode,\n strictOverrideField,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic } from \"./router.js\";\nimport { calculateDelay, delay, writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\n\n/**\n * Extract the multipart boundary string from a Content-Type header.\n */\nexport function extractBoundary(contentType: string | undefined): string | undefined {\n if (!contentType) return undefined;\n const match = contentType.match(/boundary=([^\\s;]+)/i);\n return match?.[1];\n}\n\n/**\n * Extract a text field from multipart form data using boundary-based parsing.\n * Splits the body by the multipart boundary so each part is isolated, then\n * checks each part's Content-Disposition header for the target field name.\n * This avoids false matches from binary audio data that might contain\n * header-like byte sequences.\n */\nexport function extractFormField(\n raw: string,\n fieldName: string,\n boundary: string | undefined,\n): string | undefined {\n if (!boundary) {\n // Fallback: no boundary available, use simple regex (best-effort)\n console.warn(\"extractFormField: no multipart boundary found, using best-effort regex fallback\");\n const escaped = fieldName.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const pattern = new RegExp(\n `Content-Disposition:\\\\s*form-data;[^\\\\r\\\\n]*name=\"${escaped}\"[^\\\\r\\\\n]*\\\\r\\\\n\\\\r\\\\n([^\\\\r\\\\n]*)`,\n \"i\",\n );\n const match = raw.match(pattern);\n return match?.[1];\n }\n\n // Split by boundary delimiter — each chunk is one part\n const delimiter = `--${boundary}`;\n const parts = raw.split(delimiter);\n\n for (const part of parts) {\n // Skip the preamble (before first boundary) and epilogue (after closing boundary)\n if (!part || part.trimStart().startsWith(\"--\")) continue;\n\n // Split part into headers and body at the first blank line (\\r\\n\\r\\n)\n const headerEnd = part.indexOf(\"\\r\\n\\r\\n\");\n if (headerEnd === -1) continue;\n\n const headers = part.slice(0, headerEnd);\n const body = part.slice(headerEnd + 4);\n\n // Check if this part's Content-Disposition names the target field\n const cdMatch = headers.match(/Content-Disposition:\\s*form-data;[^\\r\\n]*name=\"([^\"]+)\"/i);\n if (cdMatch && cdMatch[1] === fieldName) {\n // Return the body value, trimming trailing \\r\\n from the part boundary\n return body.replace(/\\r\\n$/, \"\");\n }\n }\n return undefined;\n}\n\nexport async function handleTranscription(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n raw: string,\n fixtures: Fixture[],\n journal: Journal,\n defaults: HandlerDefaults,\n setCorsHeaders: (res: http.ServerResponse) => void,\n endpointType: \"transcription\" | \"translation\" = \"transcription\",\n): Promise<void> {\n setCorsHeaders(res);\n const defaultPath =\n endpointType === \"translation\" ? \"/v1/audio/translations\" : \"/v1/audio/transcriptions\";\n const path = req.url ?? defaultPath;\n const method = req.method ?? \"POST\";\n\n const contentType = Array.isArray(req.headers[\"content-type\"])\n ? req.headers[\"content-type\"][0]\n : req.headers[\"content-type\"];\n const boundary = extractBoundary(contentType);\n\n const model = extractFormField(raw, \"model\", boundary) ?? \"whisper-1\";\n const responseFormat = extractFormField(raw, \"response_format\", boundary) ?? \"json\";\n const stream = extractFormField(raw, \"stream\", boundary) === \"true\";\n\n const syntheticReq: ChatCompletionRequest = {\n model,\n messages: [],\n _endpointType: endpointType,\n _context: getContext(req),\n };\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n syntheticReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n defaults.logger.debug(`No fixture matched for request`);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveStrictMode(defaults.strict, req.headers);\n if (effectiveStrict) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n defaults.logger.error(strictNoMatchLogLine(method, path, skippedBySequenceOrTurn));\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 503,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 503,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"openai\",\n req.url ?? defaultPath,\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n JSON.stringify({\n error: {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n code: \"no_fixture_match\",\n },\n }),\n );\n return;\n }\n\n const response = await resolveResponse(fixture, syntheticReq);\n\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, serializeErrorResponse(response), {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n if (!isTranscriptionResponse(response)) {\n journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response is not a transcription type\",\n type: \"server_error\",\n },\n }),\n );\n return;\n }\n\n const journalEntry = journal.add({\n method,\n path,\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n\n const t = response.transcription;\n\n // Only the transcription endpoint streams modern models. Whisper-1 ignores\n // `stream=true`, and translations continue to return their JSON response.\n if (endpointType === \"transcription\" && stream && model !== \"whisper-1\") {\n const done = {\n type: \"transcript.text.done\",\n text: t.text,\n ...(t.languages !== undefined ? { languages: t.languages } : {}),\n ...(t.usage !== undefined ? { usage: t.usage } : {}),\n };\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;\n res.writeHead(200, {\n \"Content-Type\": \"text/event-stream\",\n \"Cache-Control\": \"no-cache\",\n Connection: \"keep-alive\",\n });\n let chunkIndex = 0;\n const interruption = createInterruptionSignal(fixture);\n for (let index = 0; index < t.text.length; index += chunkSize) {\n const chunkDelay = calculateDelay(\n chunkIndex,\n fixture.streamingProfile,\n latency,\n fixture.recordedTimings,\n replaySpeed,\n );\n if (chunkDelay > 0) await delay(chunkDelay, interruption?.signal);\n if (interruption?.signal.aborted) break;\n res.write(\n `data: ${JSON.stringify({ type: \"transcript.text.delta\", delta: t.text.slice(index, index + chunkSize) })}\\n\\n`,\n );\n interruption?.tick();\n chunkIndex++;\n }\n if (interruption?.signal.aborted) {\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption.reason();\n interruption.cleanup();\n res.destroy();\n return;\n }\n res.write(`data: ${JSON.stringify(done)}\\n\\n`);\n // The live `gpt-transcribe&stream=true` stream ends with the `[DONE]`\n // sentinel after `transcript.text.done`. Omitting it leaves clients that\n // loop until the sentinel waiting on a stream that never terminates.\n res.write(\"data: [DONE]\\n\\n\");\n res.end();\n interruption?.cleanup();\n return;\n }\n\n const useVerbose = responseFormat === \"verbose_json\" || t.words != null || t.segments != null;\n\n if (useVerbose) {\n const verboseBody: Record<string, unknown> = {\n task: endpointType === \"translation\" ? \"translate\" : \"transcribe\",\n language: t.language ?? \"english\",\n duration: t.duration ?? 0,\n text: t.text,\n };\n if (t.words && t.words.length > 0) {\n verboseBody.words = t.words;\n }\n if (t.segments && t.segments.length > 0) {\n verboseBody.segments = t.segments;\n }\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(verboseBody));\n } else {\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n text: t.text,\n ...(t.languages !== undefined ? { languages: t.languages } : {}),\n ...(t.usage !== undefined ? { usage: t.usage } : {}),\n }),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;AAyBA,SAAgB,gBAAgB,aAAqD;AACnF,KAAI,CAAC,YAAa,QAAO;AAEzB,QADc,YAAY,MAAM,sBAAsB,GACvC;;;;;;;;;AAUjB,SAAgB,iBACd,KACA,WACA,UACoB;AACpB,KAAI,CAAC,UAAU;AAEb,UAAQ,KAAK,kFAAkF;EAC/F,MAAM,UAAU,UAAU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AAI,IACF,KAAK,UAAU;GACb,MAAM,EAAE;GACR,GAAI,EAAE,cAAc,SAAY,EAAE,WAAW,EAAE,WAAW,GAAG,EAAE;GAC/D,GAAI,EAAE,UAAU,SAAY,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE;GACpD,CAAC,CACH"}
|
package/dist/types.d.cts
CHANGED
|
@@ -40,6 +40,39 @@ interface ChatCompletionRequest {
|
|
|
40
40
|
model: string;
|
|
41
41
|
messages: ChatMessage[];
|
|
42
42
|
stream?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* OpenRouter fallback model list. When present (and the request arrived on
|
|
45
|
+
* the OpenRouter `/api/v1/...` base), the candidate list `[model, ...models]`
|
|
46
|
+
* is attempted in order. A NON-error fixture match wins; an ERROR fixture
|
|
47
|
+
* candidate falls through to the next candidate by default — UNLESS it is
|
|
48
|
+
* terminal, in which case that error is served with no failover. An error is
|
|
49
|
+
* terminal when its fixture sets `fallthrough: false` (per-error-class gate)
|
|
50
|
+
* or when the request sets `provider.allow_fallbacks: false` (request-level
|
|
51
|
+
* gate). A winning (non-error) slug is echoed back as the response `model`;
|
|
52
|
+
* when the chain terminates on an error, the response is the OpenRouter error
|
|
53
|
+
* envelope (`{ error: { code, message, metadata? } }`), which carries no
|
|
54
|
+
* `model` field. Purely additive: a request without `models` behaves as a
|
|
55
|
+
* single-model match. Every other
|
|
56
|
+
* OpenRouter request extension (`route`, `reasoning`, `plugins`,
|
|
57
|
+
* `prediction`, `usage`, and any unknown key) is accepted and journaled via
|
|
58
|
+
* the index signature below — never required, never rejected. aimock does not
|
|
59
|
+
* model those sub-shapes; unknown body keys pass straight through.
|
|
60
|
+
*/
|
|
61
|
+
models?: string[];
|
|
62
|
+
/**
|
|
63
|
+
* OpenRouter provider-routing preferences. Accepted loosely and journaled
|
|
64
|
+
* verbatim; the ONLY sub-field aimock reads behaviorally is
|
|
65
|
+
* `allow_fallbacks`. When `allow_fallbacks === false` on an OpenRouter
|
|
66
|
+
* request, the `models[]` fallback loop is suppressed — only the primary is
|
|
67
|
+
* tried, and a primary error fixture is served as terminal instead of
|
|
68
|
+
* falling through (the fail-CLOSED half of the feature). Absent/`true` keeps
|
|
69
|
+
* the default fall-through behavior. Every other provider-prefs key
|
|
70
|
+
* (`order`, `only`, `ignore`, `sort`, …) passes straight through unread.
|
|
71
|
+
*/
|
|
72
|
+
provider?: {
|
|
73
|
+
allow_fallbacks?: boolean;
|
|
74
|
+
[key: string]: unknown;
|
|
75
|
+
};
|
|
43
76
|
stream_options?: {
|
|
44
77
|
include_usage?: boolean;
|
|
45
78
|
[key: string]: unknown;
|
|
@@ -110,6 +143,14 @@ interface FixtureMatch {
|
|
|
110
143
|
/** Which occurrence of this match to respond to (0-indexed). Undefined means match any. */
|
|
111
144
|
sequenceIndex?: number;
|
|
112
145
|
turnIndex?: number;
|
|
146
|
+
/**
|
|
147
|
+
* Turn-scoped tool-result presence gate: matches on whether the CURRENT turn
|
|
148
|
+
* (the messages after the last `role: "user"` message) contains a `role: "tool"`
|
|
149
|
+
* message. Scoping to the current turn — rather than the whole conversation —
|
|
150
|
+
* lets a leg-1 (`false`) / leg-2 (`true`) fixture pair keep discriminating on
|
|
151
|
+
* later turns whose history still carries earlier turns' tool results. If the
|
|
152
|
+
* request has no user message, it falls back to scanning the whole conversation.
|
|
153
|
+
*/
|
|
113
154
|
hasToolResult?: boolean;
|
|
114
155
|
endpoint?: "chat" | "image" | "speech" | "transcription" | "translation" | "video" | "embedding" | "audio-gen" | "elevenlabs-tts" | "fal-audio" | "fal" | "realtime" | "realtime-transcription" | "realtime-translation";
|
|
115
156
|
context?: string;
|
|
@@ -142,10 +183,63 @@ interface ResponseOverrides {
|
|
|
142
183
|
promptTokenCount?: number;
|
|
143
184
|
candidatesTokenCount?: number;
|
|
144
185
|
totalTokenCount?: number;
|
|
186
|
+
/**
|
|
187
|
+
* OpenRouter per-request cost (USD/credits). Fixture-scriptable — powers
|
|
188
|
+
* budget-guard demos ("assert the guard trips at $5 without spending $5").
|
|
189
|
+
* Emitted on OpenRouter-shaped responses only, and ONLY when supplied —
|
|
190
|
+
* `cost`/`cost_details` are nullable and omitted by default (never 0).
|
|
191
|
+
*/
|
|
192
|
+
cost?: number;
|
|
193
|
+
/**
|
|
194
|
+
* OpenRouter cost breakdown. When the response emits `cost_details` at all
|
|
195
|
+
* it MUST carry all three upstream fields (the canonical `@openrouter/sdk`
|
|
196
|
+
* throws on a partial object); a fixture may supply any subset and the rest
|
|
197
|
+
* default to 0. Only emitted when the fixture supplies a `cost`.
|
|
198
|
+
*/
|
|
199
|
+
cost_details?: {
|
|
200
|
+
upstream_inference_cost?: number;
|
|
201
|
+
upstream_inference_prompt_cost?: number;
|
|
202
|
+
upstream_inference_completions_cost?: number;
|
|
203
|
+
[key: string]: unknown;
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* OpenRouter prompt-token breakdown. Emitted ONLY when overridden — the
|
|
207
|
+
* default response never asserts a fake cache state.
|
|
208
|
+
*/
|
|
209
|
+
prompt_tokens_details?: {
|
|
210
|
+
cached_tokens?: number;
|
|
211
|
+
cache_write_tokens?: number;
|
|
212
|
+
audio_tokens?: number;
|
|
213
|
+
[key: string]: unknown;
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* OpenRouter completion-token breakdown. Emitted ONLY when overridden.
|
|
217
|
+
*/
|
|
218
|
+
completion_tokens_details?: {
|
|
219
|
+
reasoning_tokens?: number;
|
|
220
|
+
[key: string]: unknown;
|
|
221
|
+
};
|
|
222
|
+
/**
|
|
223
|
+
* OpenRouter bring-your-own-key flag on the usage object. Emitted ONLY when
|
|
224
|
+
* overridden (avoids asserting a fake BYOK state by default).
|
|
225
|
+
*/
|
|
226
|
+
is_byok?: boolean;
|
|
145
227
|
};
|
|
146
228
|
systemFingerprint?: string;
|
|
147
229
|
finishReason?: string;
|
|
148
230
|
role?: string;
|
|
231
|
+
/**
|
|
232
|
+
* OpenRouter top-level `provider` override. When omitted, OpenRouter-shaped
|
|
233
|
+
* responses default it to the author segment of the winning model slug
|
|
234
|
+
* (`openai/gpt-4o` → `"openai"`). Ignored for OpenAI (`/v1/...`) responses.
|
|
235
|
+
*/
|
|
236
|
+
provider?: string;
|
|
237
|
+
/**
|
|
238
|
+
* OpenRouter `native_finish_reason` override (the raw upstream finish reason).
|
|
239
|
+
* When omitted, OpenRouter-shaped responses mirror `finish_reason`. Ignored
|
|
240
|
+
* for OpenAI responses.
|
|
241
|
+
*/
|
|
242
|
+
nativeFinishReason?: string;
|
|
149
243
|
}
|
|
150
244
|
interface TextResponse extends ResponseOverrides {
|
|
151
245
|
content: string;
|
|
@@ -240,10 +334,34 @@ interface ErrorResponse {
|
|
|
240
334
|
type?: string;
|
|
241
335
|
param?: string | null;
|
|
242
336
|
code?: string;
|
|
337
|
+
/**
|
|
338
|
+
* OpenRouter error metadata. Emitted verbatim inside the OpenRouter error
|
|
339
|
+
* envelope (`{ error: { code, message, metadata } }`) when the request
|
|
340
|
+
* arrived on the OpenRouter base. Moderation blocks carry
|
|
341
|
+
* `{ reasons, flagged_input, provider_name, model_slug }` on a 403.
|
|
342
|
+
* Ignored for OpenAI-shaped error responses.
|
|
343
|
+
*/
|
|
344
|
+
metadata?: Record<string, unknown>;
|
|
243
345
|
};
|
|
244
346
|
status?: number;
|
|
245
347
|
/** Override the Retry-After header value on 429 responses. Default: 1. */
|
|
246
348
|
retryAfter?: number;
|
|
349
|
+
/**
|
|
350
|
+
* OpenRouter `models[]` failover eligibility for THIS error class. Real
|
|
351
|
+
* OpenRouter fails over INCONSISTENTLY by error class — a `403 budget-exceeded`
|
|
352
|
+
* or a generic "provider returned error" is served as terminal (it does NOT
|
|
353
|
+
* advance to the next `models[]` candidate), while 429/503 usually do fail
|
|
354
|
+
* over (openclaw #60191). This flag lets a fixture reproduce that:
|
|
355
|
+
* - absent / `true` (default) — the error candidate FALLS THROUGH to the next
|
|
356
|
+
* `models[]` candidate (backward-compatible; existing fixtures unchanged).
|
|
357
|
+
* - `false` — the error is TERMINAL: the fallback loop stops and serves this
|
|
358
|
+
* error with no failover, even if a later candidate would match.
|
|
359
|
+
*
|
|
360
|
+
* Composes with the request-level `provider.allow_fallbacks`: fall-through
|
|
361
|
+
* happens only when BOTH allow it (if EITHER says don't, don't). Only
|
|
362
|
+
* consulted for OpenRouter `models[]` fallback; ignored elsewhere.
|
|
363
|
+
*/
|
|
364
|
+
fallthrough?: boolean;
|
|
247
365
|
}
|
|
248
366
|
interface EmbeddingResponse {
|
|
249
367
|
embedding: number[];
|
|
@@ -277,7 +395,11 @@ interface TranscriptionResponse {
|
|
|
277
395
|
transcription: {
|
|
278
396
|
text: string;
|
|
279
397
|
language?: string;
|
|
398
|
+
languages?: Array<{
|
|
399
|
+
code: string;
|
|
400
|
+
}>;
|
|
280
401
|
duration?: number;
|
|
402
|
+
usage?: Record<string, unknown>;
|
|
281
403
|
words?: Array<{
|
|
282
404
|
word: string;
|
|
283
405
|
start: number;
|
|
@@ -368,6 +490,13 @@ interface Fixture {
|
|
|
368
490
|
recordedTimings?: RecordedTimings;
|
|
369
491
|
replaySpeed?: number;
|
|
370
492
|
chaos?: ChaosConfig;
|
|
493
|
+
/**
|
|
494
|
+
* Opt into OpenRouter's `: OPENROUTER PROCESSING` SSE keepalive comment
|
|
495
|
+
* lines on this fixture's streamed OpenRouter responses (default OFF).
|
|
496
|
+
* A faithful client skips `:`-prefixed lines before JSON-parsing; enabling
|
|
497
|
+
* this exercises that path. No effect on non-streaming or OpenAI responses.
|
|
498
|
+
*/
|
|
499
|
+
openRouterProcessing?: boolean;
|
|
371
500
|
metadata?: {
|
|
372
501
|
systemHash?: string;
|
|
373
502
|
toolsHash?: string;
|
|
@@ -476,6 +605,13 @@ interface FixtureFileEntry {
|
|
|
476
605
|
responseFormat?: string;
|
|
477
606
|
sequenceIndex?: number;
|
|
478
607
|
turnIndex?: number;
|
|
608
|
+
/**
|
|
609
|
+
* Turn-scoped tool-result presence gate: matches on whether the CURRENT turn
|
|
610
|
+
* (the messages after the last `role: "user"` message) contains a `role: "tool"`
|
|
611
|
+
* message, not the whole conversation. Falls back to scanning the whole
|
|
612
|
+
* conversation when the request has no user message. Mirrors the runtime
|
|
613
|
+
* `FixtureMatch.hasToolResult`.
|
|
614
|
+
*/
|
|
479
615
|
hasToolResult?: boolean;
|
|
480
616
|
endpoint?: "chat" | "image" | "speech" | "transcription" | "translation" | "video" | "embedding" | "audio-gen" | "elevenlabs-tts" | "fal-audio" | "fal" | "realtime" | "realtime-transcription" | "realtime-translation";
|
|
481
617
|
context?: string;
|
|
@@ -489,6 +625,8 @@ interface FixtureFileEntry {
|
|
|
489
625
|
recordedTimings?: RecordedTimings;
|
|
490
626
|
replaySpeed?: number;
|
|
491
627
|
chaos?: ChaosConfig;
|
|
628
|
+
/** See {@link Fixture.openRouterProcessing}. */
|
|
629
|
+
openRouterProcessing?: boolean;
|
|
492
630
|
metadata?: {
|
|
493
631
|
systemHash?: string;
|
|
494
632
|
toolsHash?: string;
|
|
@@ -525,24 +663,61 @@ interface JournalEntry {
|
|
|
525
663
|
strictOverride?: boolean;
|
|
526
664
|
};
|
|
527
665
|
}
|
|
666
|
+
/**
|
|
667
|
+
* OpenRouter-only additions layered onto a `usage` object when a response is
|
|
668
|
+
* shaped for the OpenRouter `/api/v1/...` base. `cost`/`cost_details` are
|
|
669
|
+
* NULLABLE and emitted only when a fixture supplies a cost (default: omitted).
|
|
670
|
+
* When `cost_details` is emitted it carries all three upstream fields (partial
|
|
671
|
+
* objects break the canonical SDK). The detail breakdowns and `is_byok` appear
|
|
672
|
+
* only when a fixture overrides them; an emitted `prompt_tokens_details` always
|
|
673
|
+
* carries `cached_tokens` and an emitted `completion_tokens_details` always
|
|
674
|
+
* carries `reasoning_tokens` (required-if-present in the AI SDK provider).
|
|
675
|
+
*/
|
|
676
|
+
interface OpenRouterUsageExtras {
|
|
677
|
+
cost?: number;
|
|
678
|
+
cost_details?: {
|
|
679
|
+
upstream_inference_cost: number;
|
|
680
|
+
upstream_inference_prompt_cost: number;
|
|
681
|
+
upstream_inference_completions_cost: number;
|
|
682
|
+
[key: string]: unknown;
|
|
683
|
+
};
|
|
684
|
+
prompt_tokens_details?: {
|
|
685
|
+
cached_tokens: number;
|
|
686
|
+
cache_write_tokens?: number;
|
|
687
|
+
audio_tokens?: number;
|
|
688
|
+
[key: string]: unknown;
|
|
689
|
+
};
|
|
690
|
+
completion_tokens_details?: {
|
|
691
|
+
reasoning_tokens: number;
|
|
692
|
+
[key: string]: unknown;
|
|
693
|
+
};
|
|
694
|
+
is_byok?: boolean;
|
|
695
|
+
}
|
|
528
696
|
interface SSEChunk {
|
|
529
697
|
id: string;
|
|
530
698
|
object: "chat.completion.chunk";
|
|
531
699
|
created: number;
|
|
532
700
|
model: string;
|
|
533
701
|
choices: SSEChoice[];
|
|
534
|
-
|
|
702
|
+
/** Nullable: OpenRouter shaping emits this on every chunk (null when unset). */
|
|
703
|
+
system_fingerprint?: string | null;
|
|
535
704
|
usage?: {
|
|
536
705
|
prompt_tokens: number;
|
|
537
706
|
completion_tokens: number;
|
|
538
707
|
total_tokens: number;
|
|
539
|
-
};
|
|
708
|
+
} & OpenRouterUsageExtras;
|
|
709
|
+
/** OpenRouter top-level provider that served the chunk. OpenRouter shaping only. */
|
|
710
|
+
provider?: string;
|
|
711
|
+
/** OpenRouter emits `service_tier: null` on the final (usage-bearing) chunk. Shaping only. */
|
|
712
|
+
service_tier?: string | null;
|
|
540
713
|
}
|
|
541
714
|
interface SSEChoice {
|
|
542
715
|
index: number;
|
|
543
716
|
delta: SSEDelta;
|
|
544
717
|
logprobs: null;
|
|
545
718
|
finish_reason: string | null;
|
|
719
|
+
/** OpenRouter raw upstream finish reason, alongside the normalized one. */
|
|
720
|
+
native_finish_reason?: string | null;
|
|
546
721
|
}
|
|
547
722
|
interface SSEDelta {
|
|
548
723
|
role?: string;
|
|
@@ -569,20 +744,37 @@ interface ChatCompletion {
|
|
|
569
744
|
prompt_tokens: number;
|
|
570
745
|
completion_tokens: number;
|
|
571
746
|
total_tokens: number;
|
|
572
|
-
};
|
|
573
|
-
|
|
747
|
+
} & OpenRouterUsageExtras;
|
|
748
|
+
/**
|
|
749
|
+
* Nullable: OpenRouter shaping always emits this on the non-streaming
|
|
750
|
+
* response (null when no override) because the canonical `@openrouter/sdk`
|
|
751
|
+
* requires the field. OpenAI responses omit it unless overridden.
|
|
752
|
+
*/
|
|
753
|
+
system_fingerprint?: string | null;
|
|
754
|
+
/** OpenRouter top-level provider that served the request. OpenRouter shaping only. */
|
|
755
|
+
provider?: string;
|
|
756
|
+
/** OpenRouter emits `service_tier: null` on the non-streaming response. Shaping only. */
|
|
757
|
+
service_tier?: string | null;
|
|
574
758
|
}
|
|
575
759
|
interface ChatCompletionChoice {
|
|
576
760
|
index: number;
|
|
577
761
|
message: ChatCompletionMessage;
|
|
578
762
|
logprobs: null;
|
|
579
763
|
finish_reason: string;
|
|
764
|
+
/** OpenRouter raw upstream finish reason, alongside the normalized one. */
|
|
765
|
+
native_finish_reason?: string;
|
|
580
766
|
}
|
|
581
767
|
interface ChatCompletionMessage {
|
|
582
768
|
role: string;
|
|
583
769
|
content: string | null;
|
|
584
770
|
refusal: string | null;
|
|
585
771
|
reasoning_content?: string;
|
|
772
|
+
/**
|
|
773
|
+
* OpenRouter emits `reasoning` (null when absent) on the response message.
|
|
774
|
+
* OpenRouter shaping mirrors `reasoning_content` here (or null). Omitted for
|
|
775
|
+
* OpenAI responses.
|
|
776
|
+
*/
|
|
777
|
+
reasoning?: string | null;
|
|
586
778
|
tool_calls?: ToolCallMessage[];
|
|
587
779
|
}
|
|
588
780
|
type RecordProviderKey = "openai" | "anthropic" | "gemini" | "gemini-interactions" | "vertexai" | "bedrock" | "azure" | "ollama" | "cohere" | "elevenlabs" | "fal" | "openrouter" | "veo" | "grok";
|
|
@@ -699,6 +891,8 @@ interface FalRecordConfig {
|
|
|
699
891
|
timeoutMs?: number;
|
|
700
892
|
}
|
|
701
893
|
interface MockServerOptions {
|
|
894
|
+
/** Optional inbound test-client access keys. Omit to preserve permissive behavior. */
|
|
895
|
+
auth?: ApiKeyAuthConfig;
|
|
702
896
|
port?: number;
|
|
703
897
|
host?: string;
|
|
704
898
|
latency?: number;
|
|
@@ -782,6 +976,9 @@ interface MockServerOptions {
|
|
|
782
976
|
*/
|
|
783
977
|
grokVideo?: FalQueueConfig;
|
|
784
978
|
}
|
|
979
|
+
interface ApiKeyAuthConfig {
|
|
980
|
+
apiKeys: readonly string[];
|
|
981
|
+
}
|
|
785
982
|
/**
|
|
786
983
|
* Poll-progression thresholds, documented below in fal queue terms; when used
|
|
787
984
|
* as `openRouterVideo` the states map to `pending` / `in_progress` /
|
|
@@ -830,5 +1027,5 @@ interface HandlerDefaults {
|
|
|
830
1027
|
}
|
|
831
1028
|
//# sourceMappingURL=types.d.ts.map
|
|
832
1029
|
//#endregion
|
|
833
|
-
export { AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, FalQueueOpts, Fixture, FixtureBlock, FixtureFile, FixtureFileBlock, FixtureFileContentWithToolCallsResponse, FixtureFileEntry, FixtureFileResponse, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, HandlerDefaults, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, RecordedTimings, ResponseFactory, ResponseOverrides, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse };
|
|
1030
|
+
export { ApiKeyAuthConfig, AudioResponse, ChaosAction, ChaosConfig, ChatCompletion, ChatCompletionChoice, ChatCompletionMessage, ChatCompletionRequest, ChatMessage, ContentPart, ContentWithToolCallsResponse, EmbeddingFixtureOpts, EmbeddingResponse, ErrorResponse, FalQueueOpts, Fixture, FixtureBlock, FixtureFile, FixtureFileBlock, FixtureFileContentWithToolCallsResponse, FixtureFileEntry, FixtureFileResponse, FixtureFileTextResponse, FixtureFileToolCall, FixtureFileToolCallResponse, FixtureMatch, FixtureOpts, FixtureResponse, HandlerDefaults, ImageItem, ImageResponse, JournalEntry, MockServerOptions, Mountable, RawJSONResponse, RecordConfig, RecordProviderKey, RecordedTimings, ResponseFactory, ResponseOverrides, SSEChoice, SSEChunk, SSEDelta, SSEToolCallDelta, StreamingProfile, TextResponse, ToolCall, ToolCallMessage, ToolCallResponse, ToolDefinition, TranscriptionResponse, VideoResponse };
|
|
834
1031
|
//# sourceMappingURL=types.d.cts.map
|