@copilotkit/aimock 1.12.0 → 1.14.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 +3 -3
- package/.claude-plugin/plugin.json +5 -5
- package/README.md +26 -3
- package/dist/_virtual/_rolldown/runtime.cjs +2 -0
- package/dist/_virtual/_rolldown/runtime.js +29 -0
- package/dist/a2a-types.d.cts.map +1 -1
- package/dist/a2a-types.d.ts.map +1 -1
- package/dist/aimock-cli.cjs +16 -0
- package/dist/aimock-cli.cjs.map +1 -1
- package/dist/aimock-cli.d.cts +2 -0
- package/dist/aimock-cli.d.cts.map +1 -1
- package/dist/aimock-cli.d.ts +2 -0
- package/dist/aimock-cli.d.ts.map +1 -1
- package/dist/aimock-cli.js +16 -0
- package/dist/aimock-cli.js.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1 -1
- package/dist/cli.js.map +1 -1
- package/dist/convert-mockllm.cjs +232 -0
- package/dist/convert-mockllm.cjs.map +1 -0
- package/dist/convert-mockllm.js +230 -0
- package/dist/convert-mockllm.js.map +1 -0
- package/dist/convert-vidaimock.cjs +110 -0
- package/dist/convert-vidaimock.cjs.map +1 -0
- package/dist/convert-vidaimock.js +108 -0
- package/dist/convert-vidaimock.js.map +1 -0
- package/dist/convert.cjs +158 -0
- package/dist/convert.cjs.map +1 -0
- package/dist/convert.d.cts +16 -0
- package/dist/convert.d.cts.map +1 -0
- package/dist/convert.d.ts +16 -0
- package/dist/convert.d.ts.map +1 -0
- package/dist/convert.js +157 -0
- package/dist/convert.js.map +1 -0
- package/dist/fixture-loader.cjs +131 -29
- package/dist/fixture-loader.cjs.map +1 -1
- package/dist/fixture-loader.d.cts +9 -2
- package/dist/fixture-loader.d.cts.map +1 -1
- package/dist/fixture-loader.d.ts +9 -2
- package/dist/fixture-loader.d.ts.map +1 -1
- package/dist/fixture-loader.js +132 -31
- package/dist/fixture-loader.js.map +1 -1
- package/dist/gemini.cjs +76 -55
- package/dist/gemini.cjs.map +1 -1
- package/dist/gemini.d.cts.map +1 -1
- package/dist/gemini.d.ts.map +1 -1
- package/dist/gemini.js +77 -56
- package/dist/gemini.js.map +1 -1
- package/dist/helpers.cjs +142 -76
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.d.cts +14 -4
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.ts +14 -4
- package/dist/helpers.d.ts.map +1 -1
- package/dist/helpers.js +142 -77
- package/dist/helpers.js.map +1 -1
- package/dist/index.cjs +10 -0
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +3 -3
- package/dist/jest.cjs +70 -0
- package/dist/jest.cjs.map +1 -0
- package/dist/jest.d.cts +33 -0
- package/dist/jest.d.cts.map +1 -0
- package/dist/jest.d.ts +33 -0
- package/dist/jest.d.ts.map +1 -0
- package/dist/jest.js +67 -0
- package/dist/jest.js.map +1 -0
- package/dist/llmock.cjs +1 -1
- package/dist/llmock.cjs.map +1 -1
- package/dist/llmock.d.cts +6 -6
- package/dist/llmock.d.cts.map +1 -1
- package/dist/llmock.d.ts +6 -6
- package/dist/llmock.d.ts.map +1 -1
- package/dist/llmock.js +2 -2
- package/dist/llmock.js.map +1 -1
- package/dist/messages.cjs +69 -63
- 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 +70 -64
- package/dist/messages.js.map +1 -1
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.cjs +934 -0
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.js +934 -0
- package/dist/node_modules/.pnpm/@vitest_pretty-format@3.2.4/node_modules/@vitest/pretty-format/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.cjs +1051 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js +1042 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/chunk-hooks.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.cjs +1 -0
- package/dist/node_modules/.pnpm/@vitest_runner@3.2.4/node_modules/@vitest/runner/dist/index.js +3 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.cjs +96 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +93 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.cjs +49 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.js +43 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/helpers.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.cjs +456 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.js +456 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.cjs +170 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.cjs.map +1 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.js +169 -0
- package/dist/node_modules/.pnpm/@vitest_utils@3.2.4/node_modules/@vitest/utils/dist/source-map.js.map +1 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.cjs +388 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js +385 -0
- package/dist/node_modules/.pnpm/js-tokens@9.0.1/node_modules/js-tokens/index.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.cjs +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.js +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/arguments.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.cjs +17 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.js +17 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/array.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.cjs +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.js +12 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/bigint.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.cjs +16 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.js +16 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/class.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.cjs +14 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.js +14 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/date.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.cjs +35 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.js +35 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/error.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.cjs +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.js +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/function.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.cjs +128 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.js +123 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/helpers.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.cjs +41 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.js +40 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/html.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.cjs +100 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.js +100 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/index.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.cjs +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.js +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/map.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.cjs +15 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.js +15 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/number.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.cjs +22 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.js +22 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/object.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.cjs +7 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.js +6 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/promise.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.cjs +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.js +13 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/regexp.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.cjs +19 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.js +19 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/set.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.cjs +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.js +26 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/string.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.cjs +10 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.js +9 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/symbol.js.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.cjs +31 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.cjs.map +1 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.js +31 -0
- package/dist/node_modules/.pnpm/loupe@3.2.1/node_modules/loupe/lib/typedarray.js.map +1 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.cjs +52 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.cjs.map +1 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.js +52 -0
- package/dist/node_modules/.pnpm/strip-literal@3.1.0/node_modules/strip-literal/dist/index.js.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.cjs +83 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.cjs.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.js +82 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/chunk-BVHSVHOK.js.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.cjs +10 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.cjs.map +1 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.js +10 -0
- package/dist/node_modules/.pnpm/tinyrainbow@2.0.0/node_modules/tinyrainbow/dist/node.js.map +1 -0
- package/dist/recorder.cjs +1 -1
- package/dist/recorder.cjs.map +1 -1
- package/dist/recorder.js +1 -1
- package/dist/recorder.js.map +1 -1
- package/dist/responses.cjs +66 -57
- package/dist/responses.cjs.map +1 -1
- package/dist/responses.d.cts +3 -3
- package/dist/responses.d.cts.map +1 -1
- package/dist/responses.d.ts +3 -3
- package/dist/responses.d.ts.map +1 -1
- package/dist/responses.js +67 -58
- package/dist/responses.js.map +1 -1
- package/dist/server.cjs +57 -30
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts.map +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +58 -31
- package/dist/server.js.map +1 -1
- package/dist/stream-collapse.cjs.map +1 -1
- package/dist/stream-collapse.d.cts.map +1 -1
- package/dist/stream-collapse.d.ts.map +1 -1
- package/dist/stream-collapse.js.map +1 -1
- package/dist/types.d.cts +64 -11
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.ts +64 -11
- package/dist/types.d.ts.map +1 -1
- package/dist/vitest.cjs +80 -0
- package/dist/vitest.cjs.map +1 -0
- package/dist/vitest.d.cts +30 -0
- package/dist/vitest.d.cts.map +1 -0
- package/dist/vitest.d.ts +30 -0
- package/dist/vitest.d.ts.map +1 -0
- package/dist/vitest.js +77 -0
- package/dist/vitest.js.map +1 -0
- package/fixtures/example-multi-turn.json +1 -1
- package/fixtures/example-tool-call.json +1 -1
- package/fixtures/examples/a2a/a2a-config.json +42 -0
- package/fixtures/examples/adk/gemini-agent.json +47 -0
- package/fixtures/examples/agui/agui-text-response.json +35 -0
- package/fixtures/examples/chaos/chaos-config.json +10 -0
- package/fixtures/examples/crewai/multi-agent-crew.json +16 -0
- package/fixtures/examples/full-suite.json +116 -0
- package/fixtures/examples/langchain/agent-loop.json +27 -0
- package/fixtures/examples/llamaindex/aimock-config.json +62 -0
- package/fixtures/examples/llamaindex/rag-pipeline.json +34 -0
- package/fixtures/examples/llm/embeddings.json +10 -0
- package/fixtures/examples/llm/error-injection.json +15 -0
- package/fixtures/examples/llm/sequential-responses.json +20 -0
- package/fixtures/examples/llm/streaming-physics.json +15 -0
- package/fixtures/examples/mastra/agent-workflow.json +32 -0
- package/fixtures/examples/mcp/mcp-config.json +26 -0
- package/fixtures/examples/pydanticai/structured-output.json +15 -0
- package/fixtures/examples/record-replay/record-config.json +11 -0
- package/fixtures/examples/vector/vector-config.json +34 -0
- package/package.json +60 -1
- package/skills/write-fixtures/SKILL.md +148 -22
package/dist/recorder.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"recorder.js","names":[],"sources":["../src/recorder.ts"],"sourcesContent":["import * as http from \"node:http\";\nimport * as https from \"node:https\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureResponse,\n RecordConfig,\n RecordProviderKey,\n ToolCall,\n} from \"./types.js\";\nimport { getLastMessageByRole, getTextContent } from \"./router.js\";\nimport type { Logger } from \"./logger.js\";\nimport { collapseStreamingResponse } from \"./stream-collapse.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport { resolveUpstreamUrl } from \"./url.js\";\n\n/** Headers to strip when proxying — hop-by-hop (RFC 2616 §13.5.1) + client-set. */\nconst STRIP_HEADERS = new Set([\n // Hop-by-hop (RFC 2616 §13.5.1)\n \"connection\",\n \"keep-alive\",\n \"transfer-encoding\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"proxy-authorization\",\n \"proxy-authenticate\",\n // Set by HTTP client from the target URL / body\n \"host\",\n \"content-length\",\n // Not relevant for LLM APIs; avoid leaking or mismatched encoding\n \"cookie\",\n \"accept-encoding\",\n]);\n\n/**\n * Proxy an unmatched request to the real upstream provider, record the\n * response as a fixture on disk and in memory, then relay the response\n * back to the original client.\n *\n * Returns `true` if the request was proxied (provider configured),\n * `false` if no upstream URL is configured for the given provider key.\n */\nexport async function proxyAndRecord(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n request: ChatCompletionRequest,\n providerKey: RecordProviderKey,\n pathname: string,\n fixtures: Fixture[],\n defaults: {\n record?: RecordConfig;\n logger: Logger;\n requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest;\n },\n rawBody?: string,\n): Promise<boolean> {\n const record = defaults.record;\n if (!record) return false;\n\n const providers = record.providers;\n const upstreamUrl = providers[providerKey];\n\n if (!upstreamUrl) {\n defaults.logger.warn(`No upstream URL configured for provider \"${providerKey}\" — cannot proxy`);\n return false;\n }\n\n const fixturePath = record.fixturePath ?? \"./fixtures/recorded\";\n let target: URL;\n try {\n target = resolveUpstreamUrl(upstreamUrl, pathname);\n } catch {\n defaults.logger.error(`Invalid upstream URL for provider \"${providerKey}\": ${upstreamUrl}`);\n writeErrorResponse(\n res,\n 502,\n JSON.stringify({\n error: { message: `Invalid upstream URL: ${upstreamUrl}`, type: \"proxy_error\" },\n }),\n );\n return true;\n }\n\n defaults.logger.warn(`NO FIXTURE MATCH — proxying to ${upstreamUrl}${pathname}`);\n\n // Forward all request headers except hop-by-hop and client-set ones.\n const forwardHeaders: Record<string, string> = {};\n for (const [name, val] of Object.entries(req.headers)) {\n if (val !== undefined && !STRIP_HEADERS.has(name)) {\n forwardHeaders[name] = Array.isArray(val) ? val.join(\", \") : val;\n }\n }\n\n const requestBody = rawBody ?? JSON.stringify(request);\n\n // Make upstream request\n let upstreamStatus: number;\n let upstreamHeaders: http.IncomingHttpHeaders;\n let upstreamBody: string;\n let rawBuffer: Buffer;\n\n try {\n const result = await makeUpstreamRequest(target, forwardHeaders, requestBody);\n upstreamStatus = result.status;\n upstreamHeaders = result.headers;\n upstreamBody = result.body;\n rawBuffer = result.rawBuffer;\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Unknown proxy error\";\n defaults.logger.error(`Proxy request failed: ${msg}`);\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Proxy to upstream failed: ${msg}`, type: \"proxy_error\" },\n }),\n );\n return true;\n }\n\n // Detect streaming response and collapse if necessary\n const contentType = upstreamHeaders[\"content-type\"];\n const ctString = Array.isArray(contentType) ? contentType.join(\", \") : (contentType ?? \"\");\n const isBinaryStream = ctString.toLowerCase().includes(\"application/vnd.amazon.eventstream\");\n const collapsed = collapseStreamingResponse(\n ctString,\n providerKey,\n isBinaryStream ? rawBuffer : upstreamBody,\n defaults.logger,\n );\n\n let fixtureResponse: FixtureResponse;\n\n // TTS response — binary audio, not JSON\n const isAudioResponse = ctString.toLowerCase().startsWith(\"audio/\");\n if (isAudioResponse && rawBuffer.length > 0) {\n // Derive format from Content-Type (audio/mpeg→mp3, audio/opus→opus, etc.)\n const audioFormat = ctString\n .toLowerCase()\n .replace(\"audio/\", \"\")\n .replace(\"mpeg\", \"mp3\")\n .split(\";\")[0]\n .trim();\n fixtureResponse = {\n audio: rawBuffer.toString(\"base64\"),\n ...(audioFormat && audioFormat !== \"mp3\" ? { format: audioFormat } : {}),\n };\n } else if (collapsed) {\n // Streaming response — use collapsed result\n defaults.logger.warn(`Streaming response detected (${ctString}) — collapsing to fixture`);\n if (collapsed.truncated) {\n defaults.logger.warn(\"Bedrock EventStream: CRC mismatch — response may be truncated\");\n }\n if (collapsed.droppedChunks && collapsed.droppedChunks > 0) {\n defaults.logger.warn(`${collapsed.droppedChunks} chunk(s) dropped during stream collapse`);\n }\n if (collapsed.content === \"\" && (!collapsed.toolCalls || collapsed.toolCalls.length === 0)) {\n defaults.logger.warn(\"Stream collapse produced empty content — fixture may be incomplete\");\n }\n if (collapsed.toolCalls && collapsed.toolCalls.length > 0) {\n if (collapsed.content) {\n defaults.logger.warn(\n \"Collapsed response has both content and toolCalls — preferring toolCalls\",\n );\n }\n fixtureResponse = { toolCalls: collapsed.toolCalls };\n } else {\n fixtureResponse = { content: collapsed.content ?? \"\" };\n }\n } else {\n // Non-streaming — try to parse as JSON\n let parsedResponse: unknown = null;\n try {\n parsedResponse = JSON.parse(upstreamBody);\n } catch {\n // Not JSON — could be an unknown format\n defaults.logger.warn(\"Upstream response is not valid JSON — saving as error fixture\");\n }\n let encodingFormat: string | undefined;\n try {\n encodingFormat = rawBody ? JSON.parse(rawBody).encoding_format : undefined;\n } catch {\n /* not JSON */\n }\n fixtureResponse = buildFixtureResponse(parsedResponse, upstreamStatus, encodingFormat);\n }\n\n // Build the match criteria from the (optionally transformed) request\n const matchRequest = defaults.requestTransform ? defaults.requestTransform(request) : request;\n const fixtureMatch = buildFixtureMatch(matchRequest);\n\n // Build and save the fixture\n const fixture: Fixture = { match: fixtureMatch, response: fixtureResponse };\n\n // Check if the match is empty (all undefined values) — warn but still save to disk\n const matchValues = Object.values(fixtureMatch);\n const isEmptyMatch = matchValues.length === 0 || matchValues.every((v) => v === undefined);\n if (isEmptyMatch) {\n defaults.logger.warn(\n \"Recorded fixture has empty match criteria — skipping in-memory registration\",\n );\n }\n\n // In proxy-only mode, skip recording to disk and in-memory caching\n if (!defaults.record?.proxyOnly) {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const filename = `${providerKey}-${timestamp}-${crypto.randomUUID().slice(0, 8)}.json`;\n const filepath = path.join(fixturePath, filename);\n\n let writtenToDisk = false;\n try {\n // Ensure fixture directory exists\n fs.mkdirSync(fixturePath, { recursive: true });\n\n // Collect warnings for the fixture file\n const warnings: string[] = [];\n if (isEmptyMatch) {\n warnings.push(\"Empty match criteria — this fixture will not match any request\");\n }\n if (collapsed?.truncated) {\n warnings.push(\"Stream response was truncated — fixture may be incomplete\");\n }\n\n // Auth headers are forwarded to upstream but excluded from saved fixtures for security\n const fileContent: Record<string, unknown> = { fixtures: [fixture] };\n if (warnings.length > 0) {\n fileContent._warning = warnings.join(\"; \");\n }\n fs.writeFileSync(filepath, JSON.stringify(fileContent, null, 2), \"utf-8\");\n writtenToDisk = true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Unknown filesystem error\";\n defaults.logger.error(`Failed to save fixture to disk: ${msg}`);\n res.setHeader(\"X-LLMock-Record-Error\", msg);\n }\n\n if (writtenToDisk) {\n // Register in memory so subsequent identical requests match (skip if empty match)\n if (!isEmptyMatch) {\n fixtures.push(fixture);\n }\n defaults.logger.warn(`Response recorded → ${filepath}`);\n } else {\n defaults.logger.warn(`Response relayed but NOT saved to disk — see error above`);\n }\n } else {\n defaults.logger.info(`Proxied ${providerKey} request (proxy-only mode)`);\n }\n\n // Relay upstream response to client\n const relayHeaders: Record<string, string> = {};\n if (ctString) {\n relayHeaders[\"Content-Type\"] = ctString;\n }\n res.writeHead(upstreamStatus, relayHeaders);\n res.end(isBinaryStream ? rawBuffer : upstreamBody);\n\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction makeUpstreamRequest(\n target: URL,\n headers: Record<string, string>,\n body: string,\n): Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string; rawBuffer: Buffer }> {\n return new Promise((resolve, reject) => {\n const transport = target.protocol === \"https:\" ? https : http;\n const UPSTREAM_TIMEOUT_MS = 30_000;\n const BODY_TIMEOUT_MS = 30_000;\n const req = transport.request(\n target,\n {\n method: \"POST\",\n timeout: UPSTREAM_TIMEOUT_MS,\n headers: {\n ...headers,\n \"Content-Length\": Buffer.byteLength(body).toString(),\n },\n },\n (res) => {\n res.setTimeout(BODY_TIMEOUT_MS, () => {\n req.destroy(new Error(`Upstream response timed out after ${BODY_TIMEOUT_MS / 1000}s`));\n });\n const chunks: Buffer[] = [];\n res.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n res.on(\"error\", reject);\n res.on(\"end\", () => {\n const rawBuffer = Buffer.concat(chunks);\n resolve({\n status: res.statusCode ?? 500,\n headers: res.headers,\n body: rawBuffer.toString(),\n rawBuffer,\n });\n });\n },\n );\n req.on(\"timeout\", () => {\n req.destroy(\n new Error(\n `Upstream request timed out after ${UPSTREAM_TIMEOUT_MS / 1000}s: ${target.href}`,\n ),\n );\n });\n req.on(\"error\", reject);\n req.write(body);\n req.end();\n });\n}\n\n/**\n * Detect the response format from the parsed upstream JSON and convert\n * it into an llmock FixtureResponse.\n */\nfunction buildFixtureResponse(\n parsed: unknown,\n status: number,\n encodingFormat?: string,\n): FixtureResponse {\n if (parsed === null || parsed === undefined) {\n // Raw / unparseable response — save as error\n return {\n error: { message: \"Upstream returned non-JSON response\", type: \"proxy_error\" },\n status,\n };\n }\n\n const obj = parsed as Record<string, unknown>;\n\n // Error response\n if (obj.error) {\n const err = obj.error as Record<string, unknown>;\n return {\n error: {\n message: String(err.message ?? \"Unknown error\"),\n type: String(err.type ?? \"api_error\"),\n code: err.code ? String(err.code) : undefined,\n },\n status,\n };\n }\n\n // OpenAI embeddings: { data: [{ embedding: [...] }] }\n if (Array.isArray(obj.data) && obj.data.length > 0) {\n const first = obj.data[0] as Record<string, unknown>;\n if (Array.isArray(first.embedding)) {\n return { embedding: first.embedding as number[] };\n }\n if (typeof first.embedding === \"string\" && encodingFormat === \"base64\") {\n try {\n const buf = Buffer.from(first.embedding, \"base64\");\n const floats = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);\n return { embedding: Array.from(floats) };\n } catch {\n // Corrupted base64 or non-float32 data — fall through to error\n }\n }\n // OpenAI image generation: { created, data: [{ url, b64_json, revised_prompt }] }\n if (first.url || first.b64_json) {\n const images = (obj.data as Array<Record<string, unknown>>).map((item) => ({\n ...(item.url ? { url: String(item.url) } : {}),\n ...(item.b64_json ? { b64Json: String(item.b64_json) } : {}),\n ...(item.revised_prompt ? { revisedPrompt: String(item.revised_prompt) } : {}),\n }));\n if (images.length === 1) {\n return { image: images[0] };\n }\n return { images };\n }\n }\n\n // Gemini Imagen: { predictions: [...] }\n if (Array.isArray(obj.predictions)) {\n const images = (obj.predictions as Array<Record<string, unknown>>).map((p) => ({\n ...(p.bytesBase64Encoded ? { b64Json: String(p.bytesBase64Encoded) } : {}),\n ...(p.mimeType ? { mimeType: String(p.mimeType) } : {}),\n }));\n if (images.length === 1) {\n return { image: images[0] };\n }\n return { images };\n }\n\n // OpenAI transcription: { text: \"...\", ... }\n if (\n typeof obj.text === \"string\" &&\n (obj.task === \"transcribe\" || obj.language !== undefined || obj.duration !== undefined)\n ) {\n return {\n transcription: {\n text: obj.text as string,\n ...(obj.language ? { language: String(obj.language) } : {}),\n ...(obj.duration !== undefined ? { duration: Number(obj.duration) } : {}),\n ...(Array.isArray(obj.words) ? { words: obj.words } : {}),\n ...(Array.isArray(obj.segments) ? { segments: obj.segments } : {}),\n },\n };\n }\n\n // OpenAI video generation: { id, status, ... }\n if (\n typeof obj.id === \"string\" &&\n typeof obj.status === \"string\" &&\n (obj.status === \"completed\" || obj.status === \"in_progress\" || obj.status === \"failed\")\n ) {\n if (obj.status === \"completed\" && obj.url) {\n return {\n video: {\n id: String(obj.id),\n status: \"completed\" as const,\n url: String(obj.url),\n },\n };\n }\n return {\n video: {\n id: String(obj.id),\n status: obj.status === \"failed\" ? (\"failed\" as const) : (\"processing\" as const),\n },\n };\n }\n\n // Direct embedding: { embedding: [...] }\n if (Array.isArray(obj.embedding)) {\n return { embedding: obj.embedding as number[] };\n }\n\n // OpenAI chat completion: { choices: [{ message: { content, tool_calls } }] }\n if (Array.isArray(obj.choices) && obj.choices.length > 0) {\n const choice = obj.choices[0] as Record<string, unknown>;\n const message = choice.message as Record<string, unknown> | undefined;\n if (message) {\n // Tool calls\n if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {\n const toolCalls: ToolCall[] = (message.tool_calls as Array<Record<string, unknown>>).map(\n (tc) => {\n const fn = tc.function as Record<string, unknown>;\n return {\n name: String(fn.name),\n arguments: String(fn.arguments),\n };\n },\n );\n return { toolCalls };\n }\n // Text content\n if (typeof message.content === \"string\") {\n return { content: message.content };\n }\n }\n }\n\n // Anthropic: { content: [{ type: \"text\", text: \"...\" }] } or tool_use\n if (Array.isArray(obj.content) && obj.content.length > 0) {\n const blocks = obj.content as Array<Record<string, unknown>>;\n // Check for tool_use blocks first\n const toolUseBlocks = blocks.filter((b) => b.type === \"tool_use\");\n if (toolUseBlocks.length > 0) {\n const toolCalls: ToolCall[] = toolUseBlocks.map((b) => ({\n name: String(b.name),\n arguments: typeof b.input === \"string\" ? b.input : JSON.stringify(b.input),\n }));\n return { toolCalls };\n }\n // Text blocks\n const textBlock = blocks.find((b) => b.type === \"text\");\n if (textBlock && typeof textBlock.text === \"string\") {\n return { content: textBlock.text };\n }\n }\n\n // Gemini: { candidates: [{ content: { parts: [{ text: \"...\" }] } }] }\n if (Array.isArray(obj.candidates) && obj.candidates.length > 0) {\n const candidate = obj.candidates[0] as Record<string, unknown>;\n const content = candidate.content as Record<string, unknown> | undefined;\n if (content && Array.isArray(content.parts)) {\n const parts = content.parts as Array<Record<string, unknown>>;\n // Tool calls (functionCall)\n const fnCallParts = parts.filter((p) => p.functionCall);\n if (fnCallParts.length > 0) {\n const toolCalls: ToolCall[] = fnCallParts.map((p) => {\n const fc = p.functionCall as Record<string, unknown>;\n return {\n name: String(fc.name),\n arguments: typeof fc.args === \"string\" ? fc.args : JSON.stringify(fc.args),\n };\n });\n return { toolCalls };\n }\n // Text\n const textPart = parts.find((p) => typeof p.text === \"string\");\n if (textPart && typeof textPart.text === \"string\") {\n return { content: textPart.text };\n }\n }\n }\n\n // Bedrock Converse: { output: { message: { role, content: [{ text }, { toolUse }] } } }\n if (obj.output && typeof obj.output === \"object\") {\n const output = obj.output as Record<string, unknown>;\n const msg = output.message as Record<string, unknown> | undefined;\n if (msg && Array.isArray(msg.content)) {\n const blocks = msg.content as Array<Record<string, unknown>>;\n const toolUseBlocks = blocks.filter((b) => b.toolUse);\n if (toolUseBlocks.length > 0) {\n const toolCalls: ToolCall[] = toolUseBlocks.map((b) => {\n const tu = b.toolUse as Record<string, unknown>;\n return {\n name: String(tu.name ?? \"\"),\n arguments: typeof tu.input === \"string\" ? tu.input : JSON.stringify(tu.input),\n };\n });\n return { toolCalls };\n }\n const textBlock = blocks.find((b) => typeof b.text === \"string\");\n if (textBlock && typeof textBlock.text === \"string\") {\n return { content: textBlock.text };\n }\n }\n }\n\n // Ollama: { message: { content: \"...\", tool_calls: [...] } }\n if (obj.message && typeof obj.message === \"object\") {\n const msg = obj.message as Record<string, unknown>;\n // Tool calls (check before content — Ollama sends content: \"\" alongside tool_calls)\n if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {\n const toolCalls: ToolCall[] = (msg.tool_calls as Array<Record<string, unknown>>)\n .filter((tc) => tc.function != null)\n .map((tc) => {\n const fn = tc.function as Record<string, unknown>;\n return {\n name: String(fn.name ?? \"\"),\n arguments:\n typeof fn.arguments === \"string\" ? fn.arguments : JSON.stringify(fn.arguments),\n };\n });\n return { toolCalls };\n }\n if (typeof msg.content === \"string\" && msg.content.length > 0) {\n return { content: msg.content };\n }\n // Ollama message with content array (like Cohere)\n if (Array.isArray(msg.content) && msg.content.length > 0) {\n const first = msg.content[0] as Record<string, unknown>;\n if (typeof first.text === \"string\") {\n return { content: first.text };\n }\n }\n }\n\n // Fallback: unknown format — save as error\n return {\n error: {\n message: \"Could not detect response format from upstream\",\n type: \"proxy_error\",\n },\n status,\n };\n}\n\n/**\n * Derive fixture match criteria from the original request.\n */\ntype EndpointType = \"chat\" | \"image\" | \"speech\" | \"transcription\" | \"video\" | \"embedding\";\n\nfunction buildFixtureMatch(request: ChatCompletionRequest): {\n userMessage?: string;\n inputText?: string;\n endpoint?: EndpointType;\n} {\n const match: { userMessage?: string; inputText?: string; endpoint?: EndpointType } = {};\n\n // Include endpoint type for multimedia fixtures\n if (request._endpointType && request._endpointType !== \"chat\") {\n match.endpoint = request._endpointType as EndpointType;\n }\n\n // Embedding request\n if (request.embeddingInput) {\n match.inputText = request.embeddingInput;\n return match;\n }\n\n // Chat/multimedia request — match on the last user message\n const lastUser = getLastMessageByRole(request.messages ?? [], \"user\");\n if (lastUser) {\n const text = getTextContent(lastUser.content);\n if (text) {\n match.userMessage = text;\n }\n }\n\n return match;\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM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AO,MAAM,SAAS,SACxB,QAAO,EAAE,SAAS,MAAM,MAAM;;;AAMpC,QAAO;EACL,OAAO;GACL,SAAS;GACT,MAAM;GACP;EACD;EACD;;AAQH,SAAS,kBAAkB,SAIzB;CACA,MAAM,QAA+E,EAAE;AAGvF,KAAI,QAAQ,iBAAiB,QAAQ,kBAAkB,OACrD,OAAM,WAAW,QAAQ;AAI3B,KAAI,QAAQ,gBAAgB;AAC1B,QAAM,YAAY,QAAQ;AAC1B,SAAO;;CAIT,MAAM,WAAW,qBAAqB,QAAQ,YAAY,EAAE,EAAE,OAAO;AACrE,KAAI,UAAU;EACZ,MAAM,OAAO,eAAe,SAAS,QAAQ;AAC7C,MAAI,KACF,OAAM,cAAc;;AAIxB,QAAO"}
|
|
1
|
+
{"version":3,"file":"recorder.js","names":[],"sources":["../src/recorder.ts"],"sourcesContent":["import * as http from \"node:http\";\nimport * as https from \"node:https\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport * as crypto from \"node:crypto\";\nimport type {\n ChatCompletionRequest,\n Fixture,\n FixtureResponse,\n RecordConfig,\n RecordProviderKey,\n ToolCall,\n} from \"./types.js\";\nimport { getLastMessageByRole, getTextContent } from \"./router.js\";\nimport type { Logger } from \"./logger.js\";\nimport { collapseStreamingResponse } from \"./stream-collapse.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport { resolveUpstreamUrl } from \"./url.js\";\n\n/** Headers to strip when proxying — hop-by-hop (RFC 2616 §13.5.1) + client-set. */\nconst STRIP_HEADERS = new Set([\n // Hop-by-hop (RFC 2616 §13.5.1)\n \"connection\",\n \"keep-alive\",\n \"transfer-encoding\",\n \"te\",\n \"trailer\",\n \"upgrade\",\n \"proxy-authorization\",\n \"proxy-authenticate\",\n // Set by HTTP client from the target URL / body\n \"host\",\n \"content-length\",\n // Not relevant for LLM APIs; avoid leaking or mismatched encoding\n \"cookie\",\n \"accept-encoding\",\n]);\n\n/**\n * Proxy an unmatched request to the real upstream provider, record the\n * response as a fixture on disk and in memory, then relay the response\n * back to the original client.\n *\n * Returns `true` if the request was proxied (provider configured),\n * `false` if no upstream URL is configured for the given provider key.\n */\nexport async function proxyAndRecord(\n req: http.IncomingMessage,\n res: http.ServerResponse,\n request: ChatCompletionRequest,\n providerKey: RecordProviderKey,\n pathname: string,\n fixtures: Fixture[],\n defaults: {\n record?: RecordConfig;\n logger: Logger;\n requestTransform?: (req: ChatCompletionRequest) => ChatCompletionRequest;\n },\n rawBody?: string,\n): Promise<boolean> {\n const record = defaults.record;\n if (!record) return false;\n\n const providers = record.providers;\n const upstreamUrl = providers[providerKey];\n\n if (!upstreamUrl) {\n defaults.logger.warn(`No upstream URL configured for provider \"${providerKey}\" — cannot proxy`);\n return false;\n }\n\n const fixturePath = record.fixturePath ?? \"./fixtures/recorded\";\n let target: URL;\n try {\n target = resolveUpstreamUrl(upstreamUrl, pathname);\n } catch {\n defaults.logger.error(`Invalid upstream URL for provider \"${providerKey}\": ${upstreamUrl}`);\n writeErrorResponse(\n res,\n 502,\n JSON.stringify({\n error: { message: `Invalid upstream URL: ${upstreamUrl}`, type: \"proxy_error\" },\n }),\n );\n return true;\n }\n\n defaults.logger.warn(`NO FIXTURE MATCH — proxying to ${upstreamUrl}${pathname}`);\n\n // Forward all request headers except hop-by-hop and client-set ones.\n const forwardHeaders: Record<string, string> = {};\n for (const [name, val] of Object.entries(req.headers)) {\n if (val !== undefined && !STRIP_HEADERS.has(name)) {\n forwardHeaders[name] = Array.isArray(val) ? val.join(\", \") : val;\n }\n }\n\n const requestBody = rawBody ?? JSON.stringify(request);\n\n // Make upstream request\n let upstreamStatus: number;\n let upstreamHeaders: http.IncomingHttpHeaders;\n let upstreamBody: string;\n let rawBuffer: Buffer;\n\n try {\n const result = await makeUpstreamRequest(target, forwardHeaders, requestBody);\n upstreamStatus = result.status;\n upstreamHeaders = result.headers;\n upstreamBody = result.body;\n rawBuffer = result.rawBuffer;\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Unknown proxy error\";\n defaults.logger.error(`Proxy request failed: ${msg}`);\n res.writeHead(502, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: { message: `Proxy to upstream failed: ${msg}`, type: \"proxy_error\" },\n }),\n );\n return true;\n }\n\n // Detect streaming response and collapse if necessary\n const contentType = upstreamHeaders[\"content-type\"];\n const ctString = Array.isArray(contentType) ? contentType.join(\", \") : (contentType ?? \"\");\n const isBinaryStream = ctString.toLowerCase().includes(\"application/vnd.amazon.eventstream\");\n const collapsed = collapseStreamingResponse(\n ctString,\n providerKey,\n isBinaryStream ? rawBuffer : upstreamBody,\n defaults.logger,\n );\n\n let fixtureResponse: FixtureResponse;\n\n // TTS response — binary audio, not JSON\n const isAudioResponse = ctString.toLowerCase().startsWith(\"audio/\");\n if (isAudioResponse && rawBuffer.length > 0) {\n // Derive format from Content-Type (audio/mpeg→mp3, audio/opus→opus, etc.)\n const audioFormat = ctString\n .toLowerCase()\n .replace(\"audio/\", \"\")\n .replace(\"mpeg\", \"mp3\")\n .split(\";\")[0]\n .trim();\n fixtureResponse = {\n audio: rawBuffer.toString(\"base64\"),\n ...(audioFormat && audioFormat !== \"mp3\" ? { format: audioFormat } : {}),\n };\n } else if (collapsed) {\n // Streaming response — use collapsed result\n defaults.logger.warn(`Streaming response detected (${ctString}) — collapsing to fixture`);\n if (collapsed.truncated) {\n defaults.logger.warn(\"Bedrock EventStream: CRC mismatch — response may be truncated\");\n }\n if (collapsed.droppedChunks && collapsed.droppedChunks > 0) {\n defaults.logger.warn(`${collapsed.droppedChunks} chunk(s) dropped during stream collapse`);\n }\n if (collapsed.content === \"\" && (!collapsed.toolCalls || collapsed.toolCalls.length === 0)) {\n defaults.logger.warn(\"Stream collapse produced empty content — fixture may be incomplete\");\n }\n if (collapsed.toolCalls && collapsed.toolCalls.length > 0) {\n if (collapsed.content) {\n defaults.logger.warn(\n \"Collapsed response has both content and toolCalls — preferring toolCalls\",\n );\n }\n fixtureResponse = { toolCalls: collapsed.toolCalls };\n } else {\n fixtureResponse = { content: collapsed.content ?? \"\" };\n }\n } else {\n // Non-streaming — try to parse as JSON\n let parsedResponse: unknown = null;\n try {\n parsedResponse = JSON.parse(upstreamBody);\n } catch {\n // Not JSON — could be an unknown format\n defaults.logger.warn(\"Upstream response is not valid JSON — saving as error fixture\");\n }\n let encodingFormat: string | undefined;\n try {\n encodingFormat = rawBody ? JSON.parse(rawBody).encoding_format : undefined;\n } catch {\n /* not JSON */\n }\n fixtureResponse = buildFixtureResponse(parsedResponse, upstreamStatus, encodingFormat);\n }\n\n // Build the match criteria from the (optionally transformed) request\n const matchRequest = defaults.requestTransform ? defaults.requestTransform(request) : request;\n const fixtureMatch = buildFixtureMatch(matchRequest);\n\n // Build and save the fixture\n const fixture: Fixture = { match: fixtureMatch, response: fixtureResponse };\n\n // Check if the match is empty (all undefined values) — warn but still save to disk\n const matchValues = Object.values(fixtureMatch);\n const isEmptyMatch = matchValues.length === 0 || matchValues.every((v) => v === undefined);\n if (isEmptyMatch) {\n defaults.logger.warn(\n \"Recorded fixture has empty match criteria — skipping in-memory registration\",\n );\n }\n\n // In proxy-only mode, skip recording to disk and in-memory caching\n if (!defaults.record?.proxyOnly) {\n const timestamp = new Date().toISOString().replace(/[:.]/g, \"-\");\n const filename = `${providerKey}-${timestamp}-${crypto.randomUUID().slice(0, 8)}.json`;\n const filepath = path.join(fixturePath, filename);\n\n let writtenToDisk = false;\n try {\n // Ensure fixture directory exists\n fs.mkdirSync(fixturePath, { recursive: true });\n\n // Collect warnings for the fixture file\n const warnings: string[] = [];\n if (isEmptyMatch) {\n warnings.push(\"Empty match criteria — this fixture will not match any request\");\n }\n if (collapsed?.truncated) {\n warnings.push(\"Stream response was truncated — fixture may be incomplete\");\n }\n\n // Auth headers are forwarded to upstream but excluded from saved fixtures for security\n const fileContent: Record<string, unknown> = { fixtures: [fixture] };\n if (warnings.length > 0) {\n fileContent._warning = warnings.join(\"; \");\n }\n fs.writeFileSync(filepath, JSON.stringify(fileContent, null, 2), \"utf-8\");\n writtenToDisk = true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : \"Unknown filesystem error\";\n defaults.logger.error(`Failed to save fixture to disk: ${msg}`);\n res.setHeader(\"X-LLMock-Record-Error\", msg);\n }\n\n if (writtenToDisk) {\n // Register in memory so subsequent identical requests match (skip if empty match)\n if (!isEmptyMatch) {\n fixtures.push(fixture);\n }\n defaults.logger.warn(`Response recorded → ${filepath}`);\n } else {\n defaults.logger.warn(`Response relayed but NOT saved to disk — see error above`);\n }\n } else {\n defaults.logger.info(`Proxied ${providerKey} request (proxy-only mode)`);\n }\n\n // Relay upstream response to client\n const relayHeaders: Record<string, string> = {};\n if (ctString) {\n relayHeaders[\"Content-Type\"] = ctString;\n }\n res.writeHead(upstreamStatus, relayHeaders);\n res.end(isBinaryStream ? rawBuffer : upstreamBody);\n\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nfunction makeUpstreamRequest(\n target: URL,\n headers: Record<string, string>,\n body: string,\n): Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string; rawBuffer: Buffer }> {\n return new Promise((resolve, reject) => {\n const transport = target.protocol === \"https:\" ? https : http;\n const UPSTREAM_TIMEOUT_MS = 30_000;\n const BODY_TIMEOUT_MS = 30_000;\n const req = transport.request(\n target,\n {\n method: \"POST\",\n timeout: UPSTREAM_TIMEOUT_MS,\n headers: {\n ...headers,\n \"Content-Length\": Buffer.byteLength(body).toString(),\n },\n },\n (res) => {\n res.setTimeout(BODY_TIMEOUT_MS, () => {\n req.destroy(new Error(`Upstream response timed out after ${BODY_TIMEOUT_MS / 1000}s`));\n });\n const chunks: Buffer[] = [];\n res.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n res.on(\"error\", reject);\n res.on(\"end\", () => {\n const rawBuffer = Buffer.concat(chunks);\n resolve({\n status: res.statusCode ?? 500,\n headers: res.headers,\n body: rawBuffer.toString(),\n rawBuffer,\n });\n });\n },\n );\n req.on(\"timeout\", () => {\n req.destroy(\n new Error(\n `Upstream request timed out after ${UPSTREAM_TIMEOUT_MS / 1000}s: ${target.href}`,\n ),\n );\n });\n req.on(\"error\", reject);\n req.write(body);\n req.end();\n });\n}\n\n/**\n * Detect the response format from the parsed upstream JSON and convert\n * it into an aimock FixtureResponse.\n */\nfunction buildFixtureResponse(\n parsed: unknown,\n status: number,\n encodingFormat?: string,\n): FixtureResponse {\n if (parsed === null || parsed === undefined) {\n // Raw / unparseable response — save as error\n return {\n error: { message: \"Upstream returned non-JSON response\", type: \"proxy_error\" },\n status,\n };\n }\n\n const obj = parsed as Record<string, unknown>;\n\n // Error response\n if (obj.error) {\n const err = obj.error as Record<string, unknown>;\n return {\n error: {\n message: String(err.message ?? \"Unknown error\"),\n type: String(err.type ?? \"api_error\"),\n code: err.code ? String(err.code) : undefined,\n },\n status,\n };\n }\n\n // OpenAI embeddings: { data: [{ embedding: [...] }] }\n if (Array.isArray(obj.data) && obj.data.length > 0) {\n const first = obj.data[0] as Record<string, unknown>;\n if (Array.isArray(first.embedding)) {\n return { embedding: first.embedding as number[] };\n }\n if (typeof first.embedding === \"string\" && encodingFormat === \"base64\") {\n try {\n const buf = Buffer.from(first.embedding, \"base64\");\n const floats = new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4);\n return { embedding: Array.from(floats) };\n } catch {\n // Corrupted base64 or non-float32 data — fall through to error\n }\n }\n // OpenAI image generation: { created, data: [{ url, b64_json, revised_prompt }] }\n if (first.url || first.b64_json) {\n const images = (obj.data as Array<Record<string, unknown>>).map((item) => ({\n ...(item.url ? { url: String(item.url) } : {}),\n ...(item.b64_json ? { b64Json: String(item.b64_json) } : {}),\n ...(item.revised_prompt ? { revisedPrompt: String(item.revised_prompt) } : {}),\n }));\n if (images.length === 1) {\n return { image: images[0] };\n }\n return { images };\n }\n }\n\n // Gemini Imagen: { predictions: [...] }\n if (Array.isArray(obj.predictions)) {\n const images = (obj.predictions as Array<Record<string, unknown>>).map((p) => ({\n ...(p.bytesBase64Encoded ? { b64Json: String(p.bytesBase64Encoded) } : {}),\n ...(p.mimeType ? { mimeType: String(p.mimeType) } : {}),\n }));\n if (images.length === 1) {\n return { image: images[0] };\n }\n return { images };\n }\n\n // OpenAI transcription: { text: \"...\", ... }\n if (\n typeof obj.text === \"string\" &&\n (obj.task === \"transcribe\" || obj.language !== undefined || obj.duration !== undefined)\n ) {\n return {\n transcription: {\n text: obj.text as string,\n ...(obj.language ? { language: String(obj.language) } : {}),\n ...(obj.duration !== undefined ? { duration: Number(obj.duration) } : {}),\n ...(Array.isArray(obj.words) ? { words: obj.words } : {}),\n ...(Array.isArray(obj.segments) ? { segments: obj.segments } : {}),\n },\n };\n }\n\n // OpenAI video generation: { id, status, ... }\n if (\n typeof obj.id === \"string\" &&\n typeof obj.status === \"string\" &&\n (obj.status === \"completed\" || obj.status === \"in_progress\" || obj.status === \"failed\")\n ) {\n if (obj.status === \"completed\" && obj.url) {\n return {\n video: {\n id: String(obj.id),\n status: \"completed\" as const,\n url: String(obj.url),\n },\n };\n }\n return {\n video: {\n id: String(obj.id),\n status: obj.status === \"failed\" ? (\"failed\" as const) : (\"processing\" as const),\n },\n };\n }\n\n // Direct embedding: { embedding: [...] }\n if (Array.isArray(obj.embedding)) {\n return { embedding: obj.embedding as number[] };\n }\n\n // OpenAI chat completion: { choices: [{ message: { content, tool_calls } }] }\n if (Array.isArray(obj.choices) && obj.choices.length > 0) {\n const choice = obj.choices[0] as Record<string, unknown>;\n const message = choice.message as Record<string, unknown> | undefined;\n if (message) {\n // Tool calls\n if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) {\n const toolCalls: ToolCall[] = (message.tool_calls as Array<Record<string, unknown>>).map(\n (tc) => {\n const fn = tc.function as Record<string, unknown>;\n return {\n name: String(fn.name),\n arguments: String(fn.arguments),\n };\n },\n );\n return { toolCalls };\n }\n // Text content\n if (typeof message.content === \"string\") {\n return { content: message.content };\n }\n }\n }\n\n // Anthropic: { content: [{ type: \"text\", text: \"...\" }] } or tool_use\n if (Array.isArray(obj.content) && obj.content.length > 0) {\n const blocks = obj.content as Array<Record<string, unknown>>;\n // Check for tool_use blocks first\n const toolUseBlocks = blocks.filter((b) => b.type === \"tool_use\");\n if (toolUseBlocks.length > 0) {\n const toolCalls: ToolCall[] = toolUseBlocks.map((b) => ({\n name: String(b.name),\n arguments: typeof b.input === \"string\" ? b.input : JSON.stringify(b.input),\n }));\n return { toolCalls };\n }\n // Text blocks\n const textBlock = blocks.find((b) => b.type === \"text\");\n if (textBlock && typeof textBlock.text === \"string\") {\n return { content: textBlock.text };\n }\n }\n\n // Gemini: { candidates: [{ content: { parts: [{ text: \"...\" }] } }] }\n if (Array.isArray(obj.candidates) && obj.candidates.length > 0) {\n const candidate = obj.candidates[0] as Record<string, unknown>;\n const content = candidate.content as Record<string, unknown> | undefined;\n if (content && Array.isArray(content.parts)) {\n const parts = content.parts as Array<Record<string, unknown>>;\n // Tool calls (functionCall)\n const fnCallParts = parts.filter((p) => p.functionCall);\n if (fnCallParts.length > 0) {\n const toolCalls: ToolCall[] = fnCallParts.map((p) => {\n const fc = p.functionCall as Record<string, unknown>;\n return {\n name: String(fc.name),\n arguments: typeof fc.args === \"string\" ? fc.args : JSON.stringify(fc.args),\n };\n });\n return { toolCalls };\n }\n // Text\n const textPart = parts.find((p) => typeof p.text === \"string\");\n if (textPart && typeof textPart.text === \"string\") {\n return { content: textPart.text };\n }\n }\n }\n\n // Bedrock Converse: { output: { message: { role, content: [{ text }, { toolUse }] } } }\n if (obj.output && typeof obj.output === \"object\") {\n const output = obj.output as Record<string, unknown>;\n const msg = output.message as Record<string, unknown> | undefined;\n if (msg && Array.isArray(msg.content)) {\n const blocks = msg.content as Array<Record<string, unknown>>;\n const toolUseBlocks = blocks.filter((b) => b.toolUse);\n if (toolUseBlocks.length > 0) {\n const toolCalls: ToolCall[] = toolUseBlocks.map((b) => {\n const tu = b.toolUse as Record<string, unknown>;\n return {\n name: String(tu.name ?? \"\"),\n arguments: typeof tu.input === \"string\" ? tu.input : JSON.stringify(tu.input),\n };\n });\n return { toolCalls };\n }\n const textBlock = blocks.find((b) => typeof b.text === \"string\");\n if (textBlock && typeof textBlock.text === \"string\") {\n return { content: textBlock.text };\n }\n }\n }\n\n // Ollama: { message: { content: \"...\", tool_calls: [...] } }\n if (obj.message && typeof obj.message === \"object\") {\n const msg = obj.message as Record<string, unknown>;\n // Tool calls (check before content — Ollama sends content: \"\" alongside tool_calls)\n if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {\n const toolCalls: ToolCall[] = (msg.tool_calls as Array<Record<string, unknown>>)\n .filter((tc) => tc.function != null)\n .map((tc) => {\n const fn = tc.function as Record<string, unknown>;\n return {\n name: String(fn.name ?? \"\"),\n arguments:\n typeof fn.arguments === \"string\" ? fn.arguments : JSON.stringify(fn.arguments),\n };\n });\n return { toolCalls };\n }\n if (typeof msg.content === \"string\" && msg.content.length > 0) {\n return { content: msg.content };\n }\n // Ollama message with content array (like Cohere)\n if (Array.isArray(msg.content) && msg.content.length > 0) {\n const first = msg.content[0] as Record<string, unknown>;\n if (typeof first.text === \"string\") {\n return { content: first.text };\n }\n }\n }\n\n // Fallback: unknown format — save as error\n return {\n error: {\n message: \"Could not detect response format from upstream\",\n type: \"proxy_error\",\n },\n status,\n };\n}\n\n/**\n * Derive fixture match criteria from the original request.\n */\ntype EndpointType = \"chat\" | \"image\" | \"speech\" | \"transcription\" | \"video\" | \"embedding\";\n\nfunction buildFixtureMatch(request: ChatCompletionRequest): {\n userMessage?: string;\n inputText?: string;\n endpoint?: EndpointType;\n} {\n const match: { userMessage?: string; inputText?: string; endpoint?: EndpointType } = {};\n\n // Include endpoint type for multimedia fixtures\n if (request._endpointType && request._endpointType !== \"chat\") {\n match.endpoint = request._endpointType as EndpointType;\n }\n\n // Embedding request\n if (request.embeddingInput) {\n match.inputText = request.embeddingInput;\n return match;\n }\n\n // Chat/multimedia request — match on the last user message\n const lastUser = getLastMessageByRole(request.messages ?? [], \"user\");\n if (lastUser) {\n const text = getTextContent(lastUser.content);\n if (text) {\n match.userMessage = text;\n }\n }\n\n return match;\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,gBAAgB,IAAI,IAAI;CAE5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CAEA;CACA;CACD,CAAC;;;;;;;;;AAUF,eAAsB,eACpB,KACA,KACA,SACA,aACA,UACA,UACA,UAKA,SACkB;CAClB,MAAM,SAAS,SAAS;AACxB,KAAI,CAAC,OAAQ,QAAO;CAGpB,MAAM,cADY,OAAO,UACK;AAE9B,KAAI,CAAC,aAAa;AAChB,WAAS,OAAO,KAAK,4CAA4C,YAAY,kBAAkB;AAC/F,SAAO;;CAGT,MAAM,cAAc,OAAO,eAAe;CAC1C,IAAI;AACJ,KAAI;AACF,WAAS,mBAAmB,aAAa,SAAS;SAC5C;AACN,WAAS,OAAO,MAAM,sCAAsC,YAAY,KAAK,cAAc;AAC3F,qBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;GAAE,SAAS,yBAAyB;GAAe,MAAM;GAAe,EAChF,CAAC,CACH;AACD,SAAO;;AAGT,UAAS,OAAO,KAAK,kCAAkC,cAAc,WAAW;CAGhF,MAAM,iBAAyC,EAAE;AACjD,MAAK,MAAM,CAAC,MAAM,QAAQ,OAAO,QAAQ,IAAI,QAAQ,CACnD,KAAI,QAAQ,UAAa,CAAC,cAAc,IAAI,KAAK,CAC/C,gBAAe,QAAQ,MAAM,QAAQ,IAAI,GAAG,IAAI,KAAK,KAAK,GAAG;CAIjE,MAAM,cAAc,WAAW,KAAK,UAAU,QAAQ;CAGtD,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AAEJ,KAAI;EACF,MAAM,SAAS,MAAM,oBAAoB,QAAQ,gBAAgB,YAAY;AAC7E,mBAAiB,OAAO;AACxB,oBAAkB,OAAO;AACzB,iBAAe,OAAO;AACtB,cAAY,OAAO;UACZ,KAAK;EACZ,MAAM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S;AAGjC,MAAI,MAAM,QAAQ,IAAI,QAAQ,IAAI,IAAI,QAAQ,SAAS,GAAG;GACxD,MAAM,QAAQ,IAAI,QAAQ;AAC1B,OAAI,OAAO,MAAM,SAAS,SACxB,QAAO,EAAE,SAAS,MAAM,MAAM;;;AAMpC,QAAO;EACL,OAAO;GACL,SAAS;GACT,MAAM;GACP;EACD;EACD;;AAQH,SAAS,kBAAkB,SAIzB;CACA,MAAM,QAA+E,EAAE;AAGvF,KAAI,QAAQ,iBAAiB,QAAQ,kBAAkB,OACrD,OAAM,WAAW,QAAQ;AAI3B,KAAI,QAAQ,gBAAgB;AAC1B,QAAM,YAAY,QAAQ;AAC1B,SAAO;;CAIT,MAAM,WAAW,qBAAqB,QAAQ,YAAY,EAAE,EAAE,OAAO;AACrE,KAAI,UAAU;EACZ,MAAM,OAAO,eAAe,SAAS,QAAQ;AAC7C,MAAI,KACF,OAAM,cAAc;;AAIxB,QAAO"}
|
package/dist/responses.cjs
CHANGED
|
@@ -69,14 +69,34 @@ function responsesToCompletionRequest(req) {
|
|
|
69
69
|
tool_choice: req.tool_choice
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
+
function responsesStatus(finishReason, defaultStatus) {
|
|
73
|
+
if (!finishReason) return defaultStatus;
|
|
74
|
+
if (finishReason === "stop") return "completed";
|
|
75
|
+
if (finishReason === "tool_calls") return "completed";
|
|
76
|
+
if (finishReason === "length") return "incomplete";
|
|
77
|
+
if (finishReason === "content_filter") return "failed";
|
|
78
|
+
return finishReason;
|
|
79
|
+
}
|
|
80
|
+
function responsesUsage(overrides) {
|
|
81
|
+
if (!overrides?.usage) return {
|
|
82
|
+
input_tokens: 0,
|
|
83
|
+
output_tokens: 0,
|
|
84
|
+
total_tokens: 0
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
input_tokens: overrides.usage.input_tokens ?? 0,
|
|
88
|
+
output_tokens: overrides.usage.output_tokens ?? 0,
|
|
89
|
+
total_tokens: overrides.usage.total_tokens ?? (overrides.usage.input_tokens ?? 0) + (overrides.usage.output_tokens ?? 0)
|
|
90
|
+
};
|
|
91
|
+
}
|
|
72
92
|
function responseId() {
|
|
73
93
|
return require_helpers.generateId("resp");
|
|
74
94
|
}
|
|
75
95
|
function itemId() {
|
|
76
96
|
return require_helpers.generateId("msg");
|
|
77
97
|
}
|
|
78
|
-
function buildTextStreamEvents(content, model, chunkSize, reasoning, webSearches) {
|
|
79
|
-
const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(model, chunkSize, reasoning, webSearches);
|
|
98
|
+
function buildTextStreamEvents(content, model, chunkSize, reasoning, webSearches, overrides) {
|
|
99
|
+
const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(model, chunkSize, reasoning, webSearches, overrides);
|
|
80
100
|
const { events: msgEvents, msgItem } = buildMessageOutputEvents(content, chunkSize, nextOutputIndex);
|
|
81
101
|
events.push(...msgEvents);
|
|
82
102
|
events.push({
|
|
@@ -85,21 +105,18 @@ function buildTextStreamEvents(content, model, chunkSize, reasoning, webSearches
|
|
|
85
105
|
id: respId,
|
|
86
106
|
object: "response",
|
|
87
107
|
created_at: created,
|
|
88
|
-
model,
|
|
89
|
-
status: "completed",
|
|
108
|
+
model: overrides?.model ?? model,
|
|
109
|
+
status: responsesStatus(overrides?.finishReason, "completed"),
|
|
90
110
|
output: [...prefixOutputItems, msgItem],
|
|
91
|
-
usage:
|
|
92
|
-
input_tokens: 0,
|
|
93
|
-
output_tokens: 0,
|
|
94
|
-
total_tokens: 0
|
|
95
|
-
}
|
|
111
|
+
usage: responsesUsage(overrides)
|
|
96
112
|
}
|
|
97
113
|
});
|
|
98
114
|
return events;
|
|
99
115
|
}
|
|
100
|
-
function buildToolCallStreamEvents(toolCalls, model, chunkSize) {
|
|
101
|
-
const respId = responseId();
|
|
102
|
-
const created = Math.floor(Date.now() / 1e3);
|
|
116
|
+
function buildToolCallStreamEvents(toolCalls, model, chunkSize, overrides) {
|
|
117
|
+
const respId = overrides?.id ?? responseId();
|
|
118
|
+
const created = overrides?.created ?? Math.floor(Date.now() / 1e3);
|
|
119
|
+
const effectiveModel = overrides?.model ?? model;
|
|
103
120
|
const events = [];
|
|
104
121
|
events.push({
|
|
105
122
|
type: "response.created",
|
|
@@ -107,7 +124,7 @@ function buildToolCallStreamEvents(toolCalls, model, chunkSize) {
|
|
|
107
124
|
id: respId,
|
|
108
125
|
object: "response",
|
|
109
126
|
created_at: created,
|
|
110
|
-
model,
|
|
127
|
+
model: effectiveModel,
|
|
111
128
|
status: "in_progress",
|
|
112
129
|
output: []
|
|
113
130
|
}
|
|
@@ -118,7 +135,7 @@ function buildToolCallStreamEvents(toolCalls, model, chunkSize) {
|
|
|
118
135
|
id: respId,
|
|
119
136
|
object: "response",
|
|
120
137
|
created_at: created,
|
|
121
|
-
model,
|
|
138
|
+
model: effectiveModel,
|
|
122
139
|
status: "in_progress",
|
|
123
140
|
output: []
|
|
124
141
|
}
|
|
@@ -176,14 +193,10 @@ function buildToolCallStreamEvents(toolCalls, model, chunkSize) {
|
|
|
176
193
|
id: respId,
|
|
177
194
|
object: "response",
|
|
178
195
|
created_at: created,
|
|
179
|
-
model,
|
|
180
|
-
status: "completed",
|
|
196
|
+
model: effectiveModel,
|
|
197
|
+
status: responsesStatus(overrides?.finishReason, "completed"),
|
|
181
198
|
output: outputItems,
|
|
182
|
-
usage:
|
|
183
|
-
input_tokens: 0,
|
|
184
|
-
output_tokens: 0,
|
|
185
|
-
total_tokens: 0
|
|
186
|
-
}
|
|
199
|
+
usage: responsesUsage(overrides)
|
|
187
200
|
}
|
|
188
201
|
});
|
|
189
202
|
return events;
|
|
@@ -276,9 +289,10 @@ function buildWebSearchStreamEvents(queries, startOutputIndex) {
|
|
|
276
289
|
}
|
|
277
290
|
return events;
|
|
278
291
|
}
|
|
279
|
-
function buildResponsePreamble(model, chunkSize, reasoning, webSearches) {
|
|
280
|
-
const respId = responseId();
|
|
281
|
-
const created = Math.floor(Date.now() / 1e3);
|
|
292
|
+
function buildResponsePreamble(model, chunkSize, reasoning, webSearches, overrides) {
|
|
293
|
+
const respId = overrides?.id ?? responseId();
|
|
294
|
+
const created = overrides?.created ?? Math.floor(Date.now() / 1e3);
|
|
295
|
+
const effectiveModel = overrides?.model ?? model;
|
|
282
296
|
const events = [];
|
|
283
297
|
const prefixOutputItems = [];
|
|
284
298
|
let nextOutputIndex = 0;
|
|
@@ -288,7 +302,7 @@ function buildResponsePreamble(model, chunkSize, reasoning, webSearches) {
|
|
|
288
302
|
id: respId,
|
|
289
303
|
object: "response",
|
|
290
304
|
created_at: created,
|
|
291
|
-
model,
|
|
305
|
+
model: effectiveModel,
|
|
292
306
|
status: "in_progress",
|
|
293
307
|
output: []
|
|
294
308
|
}
|
|
@@ -299,7 +313,7 @@ function buildResponsePreamble(model, chunkSize, reasoning, webSearches) {
|
|
|
299
313
|
id: respId,
|
|
300
314
|
object: "response",
|
|
301
315
|
created_at: created,
|
|
302
|
-
model,
|
|
316
|
+
model: effectiveModel,
|
|
303
317
|
status: "in_progress",
|
|
304
318
|
output: []
|
|
305
319
|
}
|
|
@@ -419,25 +433,21 @@ function buildOutputPrefix(content, reasoning, webSearches) {
|
|
|
419
433
|
});
|
|
420
434
|
return output;
|
|
421
435
|
}
|
|
422
|
-
function buildResponseEnvelope(model, output) {
|
|
436
|
+
function buildResponseEnvelope(model, output, overrides) {
|
|
423
437
|
return {
|
|
424
|
-
id: responseId(),
|
|
438
|
+
id: overrides?.id ?? responseId(),
|
|
425
439
|
object: "response",
|
|
426
|
-
created_at: Math.floor(Date.now() / 1e3),
|
|
427
|
-
model,
|
|
428
|
-
status: "completed",
|
|
440
|
+
created_at: overrides?.created ?? Math.floor(Date.now() / 1e3),
|
|
441
|
+
model: overrides?.model ?? model,
|
|
442
|
+
status: responsesStatus(overrides?.finishReason, "completed"),
|
|
429
443
|
output,
|
|
430
|
-
usage:
|
|
431
|
-
input_tokens: 0,
|
|
432
|
-
output_tokens: 0,
|
|
433
|
-
total_tokens: 0
|
|
434
|
-
}
|
|
444
|
+
usage: responsesUsage(overrides)
|
|
435
445
|
};
|
|
436
446
|
}
|
|
437
|
-
function buildTextResponse(content, model, reasoning, webSearches) {
|
|
438
|
-
return buildResponseEnvelope(model, buildOutputPrefix(content, reasoning, webSearches));
|
|
447
|
+
function buildTextResponse(content, model, reasoning, webSearches, overrides) {
|
|
448
|
+
return buildResponseEnvelope(model, buildOutputPrefix(content, reasoning, webSearches), overrides);
|
|
439
449
|
}
|
|
440
|
-
function buildToolCallResponse(toolCalls, model) {
|
|
450
|
+
function buildToolCallResponse(toolCalls, model, overrides) {
|
|
441
451
|
return buildResponseEnvelope(model, toolCalls.map((tc) => ({
|
|
442
452
|
type: "function_call",
|
|
443
453
|
id: require_helpers.generateId("fc"),
|
|
@@ -445,10 +455,10 @@ function buildToolCallResponse(toolCalls, model) {
|
|
|
445
455
|
name: tc.name,
|
|
446
456
|
arguments: tc.arguments,
|
|
447
457
|
status: "completed"
|
|
448
|
-
})));
|
|
458
|
+
})), overrides);
|
|
449
459
|
}
|
|
450
|
-
function buildContentWithToolCallsStreamEvents(content, toolCalls, model, chunkSize, reasoning, webSearches) {
|
|
451
|
-
const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(model, chunkSize, reasoning, webSearches);
|
|
460
|
+
function buildContentWithToolCallsStreamEvents(content, toolCalls, model, chunkSize, reasoning, webSearches, overrides) {
|
|
461
|
+
const { respId, created, events, prefixOutputItems, nextOutputIndex } = buildResponsePreamble(model, chunkSize, reasoning, webSearches, overrides);
|
|
452
462
|
const { events: msgEvents, msgItem } = buildMessageOutputEvents(content, chunkSize, nextOutputIndex);
|
|
453
463
|
events.push(...msgEvents);
|
|
454
464
|
const fcOutputItems = [];
|
|
@@ -502,23 +512,19 @@ function buildContentWithToolCallsStreamEvents(content, toolCalls, model, chunkS
|
|
|
502
512
|
id: respId,
|
|
503
513
|
object: "response",
|
|
504
514
|
created_at: created,
|
|
505
|
-
model,
|
|
506
|
-
status: "completed",
|
|
515
|
+
model: overrides?.model ?? model,
|
|
516
|
+
status: responsesStatus(overrides?.finishReason, "completed"),
|
|
507
517
|
output: [
|
|
508
518
|
...prefixOutputItems,
|
|
509
519
|
msgItem,
|
|
510
520
|
...fcOutputItems
|
|
511
521
|
],
|
|
512
|
-
usage:
|
|
513
|
-
input_tokens: 0,
|
|
514
|
-
output_tokens: 0,
|
|
515
|
-
total_tokens: 0
|
|
516
|
-
}
|
|
522
|
+
usage: responsesUsage(overrides)
|
|
517
523
|
}
|
|
518
524
|
});
|
|
519
525
|
return events;
|
|
520
526
|
}
|
|
521
|
-
function buildContentWithToolCallsResponse(content, toolCalls, model, reasoning, webSearches) {
|
|
527
|
+
function buildContentWithToolCallsResponse(content, toolCalls, model, reasoning, webSearches, overrides) {
|
|
522
528
|
const output = buildOutputPrefix(content, reasoning, webSearches);
|
|
523
529
|
for (const tc of toolCalls) output.push({
|
|
524
530
|
type: "function_call",
|
|
@@ -528,7 +534,7 @@ function buildContentWithToolCallsResponse(content, toolCalls, model, reasoning,
|
|
|
528
534
|
arguments: tc.arguments,
|
|
529
535
|
status: "completed"
|
|
530
536
|
});
|
|
531
|
-
return buildResponseEnvelope(model, output);
|
|
537
|
+
return buildResponseEnvelope(model, output, overrides);
|
|
532
538
|
}
|
|
533
539
|
async function writeResponsesSSEStream(res, events, optionsOrLatency) {
|
|
534
540
|
const opts = typeof optionsOrLatency === "number" ? { latency: optionsOrLatency } : optionsOrLatency ?? {};
|
|
@@ -643,6 +649,7 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
643
649
|
return;
|
|
644
650
|
}
|
|
645
651
|
if (require_helpers.isContentWithToolCallsResponse(response)) {
|
|
652
|
+
const overrides = require_helpers.extractOverrides(response);
|
|
646
653
|
const journalEntry = journal.add({
|
|
647
654
|
method: req.method ?? "POST",
|
|
648
655
|
path: req.url ?? "/v1/responses",
|
|
@@ -654,11 +661,11 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
654
661
|
}
|
|
655
662
|
});
|
|
656
663
|
if (responsesReq.stream !== true) {
|
|
657
|
-
const body = buildContentWithToolCallsResponse(response.content, response.toolCalls, completionReq.model, response.reasoning, response.webSearches);
|
|
664
|
+
const body = buildContentWithToolCallsResponse(response.content, response.toolCalls, completionReq.model, response.reasoning, response.webSearches, overrides);
|
|
658
665
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
659
666
|
res.end(JSON.stringify(body));
|
|
660
667
|
} else {
|
|
661
|
-
const events = buildContentWithToolCallsStreamEvents(response.content, response.toolCalls, completionReq.model, chunkSize, response.reasoning, response.webSearches);
|
|
668
|
+
const events = buildContentWithToolCallsStreamEvents(response.content, response.toolCalls, completionReq.model, chunkSize, response.reasoning, response.webSearches, overrides);
|
|
662
669
|
const interruption = require_interruption.createInterruptionSignal(fixture);
|
|
663
670
|
if (!await writeResponsesSSEStream(res, events, {
|
|
664
671
|
latency,
|
|
@@ -675,6 +682,7 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
675
682
|
return;
|
|
676
683
|
}
|
|
677
684
|
if (require_helpers.isTextResponse(response)) {
|
|
685
|
+
const overrides = require_helpers.extractOverrides(response);
|
|
678
686
|
const journalEntry = journal.add({
|
|
679
687
|
method: req.method ?? "POST",
|
|
680
688
|
path: req.url ?? "/v1/responses",
|
|
@@ -686,11 +694,11 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
686
694
|
}
|
|
687
695
|
});
|
|
688
696
|
if (responsesReq.stream !== true) {
|
|
689
|
-
const body = buildTextResponse(response.content, completionReq.model, response.reasoning, response.webSearches);
|
|
697
|
+
const body = buildTextResponse(response.content, completionReq.model, response.reasoning, response.webSearches, overrides);
|
|
690
698
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
691
699
|
res.end(JSON.stringify(body));
|
|
692
700
|
} else {
|
|
693
|
-
const events = buildTextStreamEvents(response.content, completionReq.model, chunkSize, response.reasoning, response.webSearches);
|
|
701
|
+
const events = buildTextStreamEvents(response.content, completionReq.model, chunkSize, response.reasoning, response.webSearches, overrides);
|
|
694
702
|
const interruption = require_interruption.createInterruptionSignal(fixture);
|
|
695
703
|
if (!await writeResponsesSSEStream(res, events, {
|
|
696
704
|
latency,
|
|
@@ -707,6 +715,7 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
707
715
|
return;
|
|
708
716
|
}
|
|
709
717
|
if (require_helpers.isToolCallResponse(response)) {
|
|
718
|
+
const overrides = require_helpers.extractOverrides(response);
|
|
710
719
|
const journalEntry = journal.add({
|
|
711
720
|
method: req.method ?? "POST",
|
|
712
721
|
path: req.url ?? "/v1/responses",
|
|
@@ -718,11 +727,11 @@ async function handleResponses(req, res, raw, fixtures, journal, defaults, setCo
|
|
|
718
727
|
}
|
|
719
728
|
});
|
|
720
729
|
if (responsesReq.stream !== true) {
|
|
721
|
-
const body = buildToolCallResponse(response.toolCalls, completionReq.model);
|
|
730
|
+
const body = buildToolCallResponse(response.toolCalls, completionReq.model, overrides);
|
|
722
731
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
723
732
|
res.end(JSON.stringify(body));
|
|
724
733
|
} else {
|
|
725
|
-
const events = buildToolCallStreamEvents(response.toolCalls, completionReq.model, chunkSize);
|
|
734
|
+
const events = buildToolCallStreamEvents(response.toolCalls, completionReq.model, chunkSize, overrides);
|
|
726
735
|
const interruption = require_interruption.createInterruptionSignal(fixture);
|
|
727
736
|
if (!await writeResponsesSSEStream(res, events, {
|
|
728
737
|
latency,
|