@copilotkit/aimock 1.46.0 → 1.47.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.
Files changed (183) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHANGELOG.md +12 -1
  4. package/README.md +4 -1
  5. package/dist/aws-event-stream.cjs +20 -23
  6. package/dist/aws-event-stream.cjs.map +1 -1
  7. package/dist/aws-event-stream.d.cts +0 -1
  8. package/dist/aws-event-stream.d.ts +0 -1
  9. package/dist/aws-event-stream.js +20 -24
  10. package/dist/aws-event-stream.js.map +1 -1
  11. package/dist/bedrock-converse.cjs +79 -82
  12. package/dist/bedrock-converse.cjs.map +1 -1
  13. package/dist/bedrock-converse.d.cts.map +1 -1
  14. package/dist/bedrock-converse.d.ts.map +1 -1
  15. package/dist/bedrock-converse.js +80 -83
  16. package/dist/bedrock-converse.js.map +1 -1
  17. package/dist/bedrock.cjs +112 -121
  18. package/dist/bedrock.cjs.map +1 -1
  19. package/dist/bedrock.d.cts.map +1 -1
  20. package/dist/bedrock.d.ts.map +1 -1
  21. package/dist/bedrock.js +113 -122
  22. package/dist/bedrock.js.map +1 -1
  23. package/dist/cohere.cjs +58 -106
  24. package/dist/cohere.cjs.map +1 -1
  25. package/dist/cohere.d.cts.map +1 -1
  26. package/dist/cohere.d.ts.map +1 -1
  27. package/dist/cohere.js +60 -108
  28. package/dist/cohere.js.map +1 -1
  29. package/dist/config-loader.d.cts.map +1 -1
  30. package/dist/config-loader.d.ts.map +1 -1
  31. package/dist/fixture-loader.cjs +103 -2
  32. package/dist/fixture-loader.cjs.map +1 -1
  33. package/dist/fixture-loader.d.cts.map +1 -1
  34. package/dist/fixture-loader.d.ts.map +1 -1
  35. package/dist/fixture-loader.js +104 -4
  36. package/dist/fixture-loader.js.map +1 -1
  37. package/dist/gemini-interactions.cjs +63 -121
  38. package/dist/gemini-interactions.cjs.map +1 -1
  39. package/dist/gemini-interactions.d.cts.map +1 -1
  40. package/dist/gemini-interactions.d.ts.map +1 -1
  41. package/dist/gemini-interactions.js +65 -123
  42. package/dist/gemini-interactions.js.map +1 -1
  43. package/dist/gemini.cjs +242 -155
  44. package/dist/gemini.cjs.map +1 -1
  45. package/dist/gemini.d.cts.map +1 -1
  46. package/dist/gemini.d.ts.map +1 -1
  47. package/dist/gemini.js +244 -157
  48. package/dist/gemini.js.map +1 -1
  49. package/dist/helpers.cjs +400 -7
  50. package/dist/helpers.cjs.map +1 -1
  51. package/dist/helpers.d.cts +51 -1
  52. package/dist/helpers.d.cts.map +1 -1
  53. package/dist/helpers.d.ts +51 -1
  54. package/dist/helpers.d.ts.map +1 -1
  55. package/dist/helpers.js +391 -8
  56. package/dist/helpers.js.map +1 -1
  57. package/dist/index.cjs +4 -2
  58. package/dist/index.d.cts +4 -4
  59. package/dist/index.d.ts +4 -4
  60. package/dist/index.js +4 -4
  61. package/dist/mcp-fakes.d.cts.map +1 -1
  62. package/dist/messages.cjs +159 -141
  63. package/dist/messages.cjs.map +1 -1
  64. package/dist/messages.d.cts.map +1 -1
  65. package/dist/messages.d.ts.map +1 -1
  66. package/dist/messages.js +161 -143
  67. package/dist/messages.js.map +1 -1
  68. package/dist/misbehavior.cjs +62 -3
  69. package/dist/misbehavior.cjs.map +1 -1
  70. package/dist/misbehavior.d.cts.map +1 -1
  71. package/dist/misbehavior.d.ts.map +1 -1
  72. package/dist/misbehavior.js +63 -4
  73. package/dist/misbehavior.js.map +1 -1
  74. package/dist/ndjson-writer.cjs +21 -23
  75. package/dist/ndjson-writer.cjs.map +1 -1
  76. package/dist/ndjson-writer.d.cts +0 -1
  77. package/dist/ndjson-writer.d.cts.map +1 -1
  78. package/dist/ndjson-writer.d.ts +0 -1
  79. package/dist/ndjson-writer.d.ts.map +1 -1
  80. package/dist/ndjson-writer.js +21 -24
  81. package/dist/ndjson-writer.js.map +1 -1
  82. package/dist/ollama.cjs +153 -147
  83. package/dist/ollama.cjs.map +1 -1
  84. package/dist/ollama.d.cts.map +1 -1
  85. package/dist/ollama.d.ts.map +1 -1
  86. package/dist/ollama.js +155 -149
  87. package/dist/ollama.js.map +1 -1
  88. package/dist/openrouter-chat.cjs +1 -1
  89. package/dist/openrouter-chat.js +1 -1
  90. package/dist/raw-validation.cjs +177 -0
  91. package/dist/raw-validation.cjs.map +1 -0
  92. package/dist/raw-validation.js +176 -0
  93. package/dist/raw-validation.js.map +1 -0
  94. package/dist/response/deliver.cjs +144 -0
  95. package/dist/response/deliver.cjs.map +1 -0
  96. package/dist/response/deliver.js +143 -0
  97. package/dist/response/deliver.js.map +1 -0
  98. package/dist/response/frame-loop.cjs +102 -0
  99. package/dist/response/frame-loop.cjs.map +1 -0
  100. package/dist/response/frame-loop.js +100 -0
  101. package/dist/response/frame-loop.js.map +1 -0
  102. package/dist/response/lifecycle.cjs +223 -0
  103. package/dist/response/lifecycle.cjs.map +1 -0
  104. package/dist/response/lifecycle.js +211 -0
  105. package/dist/response/lifecycle.js.map +1 -0
  106. package/dist/response/proxy.cjs +71 -0
  107. package/dist/response/proxy.cjs.map +1 -0
  108. package/dist/response/proxy.js +70 -0
  109. package/dist/response/proxy.js.map +1 -0
  110. package/dist/response/raw.cjs +228 -0
  111. package/dist/response/raw.cjs.map +1 -0
  112. package/dist/response/raw.js +227 -0
  113. package/dist/response/raw.js.map +1 -0
  114. package/dist/response/timing.cjs +157 -0
  115. package/dist/response/timing.cjs.map +1 -0
  116. package/dist/response/timing.js +150 -0
  117. package/dist/response/timing.js.map +1 -0
  118. package/dist/responses.cjs +269 -148
  119. package/dist/responses.cjs.map +1 -1
  120. package/dist/responses.d.cts.map +1 -1
  121. package/dist/responses.d.ts.map +1 -1
  122. package/dist/responses.js +270 -149
  123. package/dist/responses.js.map +1 -1
  124. package/dist/router.cjs +20 -4
  125. package/dist/router.cjs.map +1 -1
  126. package/dist/router.d.cts +7 -1
  127. package/dist/router.d.cts.map +1 -1
  128. package/dist/router.d.ts +7 -1
  129. package/dist/router.d.ts.map +1 -1
  130. package/dist/router.js +21 -5
  131. package/dist/router.js.map +1 -1
  132. package/dist/server.cjs +89 -120
  133. package/dist/server.cjs.map +1 -1
  134. package/dist/server.d.cts.map +1 -1
  135. package/dist/server.d.ts.map +1 -1
  136. package/dist/server.js +91 -122
  137. package/dist/server.js.map +1 -1
  138. package/dist/sse-writer.cjs +49 -30
  139. package/dist/sse-writer.cjs.map +1 -1
  140. package/dist/sse-writer.d.cts +0 -1
  141. package/dist/sse-writer.d.cts.map +1 -1
  142. package/dist/sse-writer.d.ts +0 -1
  143. package/dist/sse-writer.d.ts.map +1 -1
  144. package/dist/sse-writer.js +49 -31
  145. package/dist/sse-writer.js.map +1 -1
  146. package/dist/transcription.cjs +19 -33
  147. package/dist/transcription.cjs.map +1 -1
  148. package/dist/transcription.d.cts.map +1 -1
  149. package/dist/transcription.d.ts.map +1 -1
  150. package/dist/transcription.js +20 -34
  151. package/dist/transcription.js.map +1 -1
  152. package/dist/types.cjs.map +1 -1
  153. package/dist/types.d.cts +173 -10
  154. package/dist/types.d.cts.map +1 -1
  155. package/dist/types.d.ts +173 -10
  156. package/dist/types.d.ts.map +1 -1
  157. package/dist/types.js.map +1 -1
  158. package/dist/ws-framing.cjs +12 -6
  159. package/dist/ws-framing.cjs.map +1 -1
  160. package/dist/ws-framing.d.cts +2 -0
  161. package/dist/ws-framing.d.cts.map +1 -1
  162. package/dist/ws-framing.d.ts +2 -0
  163. package/dist/ws-framing.d.ts.map +1 -1
  164. package/dist/ws-framing.js +12 -6
  165. package/dist/ws-framing.js.map +1 -1
  166. package/dist/ws-gemini-live.cjs +120 -93
  167. package/dist/ws-gemini-live.cjs.map +1 -1
  168. package/dist/ws-gemini-live.js +120 -93
  169. package/dist/ws-gemini-live.js.map +1 -1
  170. package/dist/ws-realtime.cjs +80 -70
  171. package/dist/ws-realtime.cjs.map +1 -1
  172. package/dist/ws-realtime.d.cts.map +1 -1
  173. package/dist/ws-realtime.d.ts.map +1 -1
  174. package/dist/ws-realtime.js +80 -70
  175. package/dist/ws-realtime.js.map +1 -1
  176. package/dist/ws-responses.cjs +72 -53
  177. package/dist/ws-responses.cjs.map +1 -1
  178. package/dist/ws-responses.d.cts.map +1 -1
  179. package/dist/ws-responses.d.ts.map +1 -1
  180. package/dist/ws-responses.js +73 -54
  181. package/dist/ws-responses.js.map +1 -1
  182. package/package.json +1 -1
  183. package/skills/write-fixtures/SKILL.md +34 -2
package/dist/cohere.js CHANGED
@@ -1,12 +1,15 @@
1
1
  import { renderError } from "./response/errors.js";
2
2
  import { resolveRequestDecisions, strictOverrideField } from "./response/policy.js";
3
- import { extractOverrides, flattenHeaders, generateDeterministicEmbedding, generateMessageId, generateToolCallId, getContext, getTestId, isCombinedFixtureResponse, isEmbeddingResponse, isErrorResponse, isJsonObject, isTextResponse, isToolCallResponse, prepareOpenAIChatMisbehavior, requireEmittedFunctionToolCalls, resolveFixtureBlockOutcome, resolveOpenAIChatMisbehaviorUsage, resolveReasoningForModel, resolveResponse, servedToolArgs, strictNoMatchLogLine, strictNoMatchMessage, validateChatMessages, validateToolsField } from "./helpers.js";
4
- import { calculateDelay, delay, writeErrorResponse } from "./sse-writer.js";
3
+ import { extractOverrides, flattenHeaders, generateDeterministicEmbedding, generateMessageId, generateToolCallId, getContext, getTestId, isCombinedFixtureResponse, isEmbeddingResponse, isErrorResponse, isJsonObject, isRawResponse, isTextResponse, isToolCallResponse, prepareOpenAIChatMisbehavior, requireEmittedFunctionToolCalls, resolveFixtureBlockOutcome, resolveOpenAIChatMisbehaviorUsage, resolveReasoningForModel, resolveResponse, servedToolArgs, strictNoMatchLogLine, strictNoMatchMessage, validateChatMessages, validateToolsField } from "./helpers.js";
4
+ import { typedSseCodec, writeErrorResponse } from "./sse-writer.js";
5
5
  import { applyChaosAsync } from "./chaos.js";
6
6
  import { normalizeDirectToolSchema, planMisbehavior, recordMisbehaviorOutcome } from "./misbehavior.js";
7
7
  import { matchFixtureDiagnostic, recordMatchOptions } from "./router.js";
8
8
  import { proxyAndRecord } from "./recorder.js";
9
- import { createInterruptionSignal } from "./interruption.js";
9
+ import { servedPayloadLength } from "./response/timing.js";
10
+ import { deliverJson, deliverStream } from "./response/deliver.js";
11
+ import { proxyInterruption, withHangUpDetection } from "./response/proxy.js";
12
+ import { serveRawResponse } from "./response/raw.js";
10
13
  import { mapCohereFinish } from "./response/finish.js";
11
14
  import { render } from "./response/usage/codecs/cohere.js";
12
15
 
@@ -505,34 +508,6 @@ function buildCohereContentWithToolCallsStreamEvents(content, toolCalls, chunkSi
505
508
  });
506
509
  return events;
507
510
  }
508
- async function writeCohereSSEStream(res, events, optionsOrLatency) {
509
- const opts = typeof optionsOrLatency === "number" ? { latency: optionsOrLatency } : optionsOrLatency ?? {};
510
- const latency = opts.latency ?? 0;
511
- const profile = opts.streamingProfile;
512
- const { recordedTimings, replaySpeed } = opts;
513
- const signal = opts.signal;
514
- const onChunkSent = opts.onChunkSent;
515
- if (res.writableEnded) return true;
516
- res.setHeader("Content-Type", "text/event-stream");
517
- res.setHeader("Cache-Control", "no-cache");
518
- res.setHeader("Connection", "keep-alive");
519
- let chunkIndex = 0;
520
- for (const event of events) {
521
- const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);
522
- if (chunkDelay > 0) await delay(chunkDelay, signal);
523
- if (signal?.aborted) return false;
524
- if (res.writableEnded) return true;
525
- res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
526
- onChunkSent?.();
527
- if (signal?.aborted) return false;
528
- chunkIndex++;
529
- }
530
- if (!res.writableEnded) {
531
- if (opts.terminalSentinel && !signal?.aborted) res.write("data: [DONE]\n\n");
532
- res.end();
533
- }
534
- return true;
535
- }
536
511
  async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsHeaders) {
537
512
  const { logger } = defaults;
538
513
  setCorsHeaders(res);
@@ -617,7 +592,10 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
617
592
  completionReq._endpointType = "chat";
618
593
  completionReq._context = getContext(req);
619
594
  const testId = getTestId(req);
620
- const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(fixtures, completionReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform, recordMatchOptions(!!defaults.record, defaults.logger));
595
+ const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(fixtures, completionReq, journal.getFixtureMatchCountsForTest(testId), defaults.requestTransform, {
596
+ ...recordMatchOptions(!!defaults.record, defaults.logger),
597
+ wire: "cohere"
598
+ });
621
599
  if (fixture) {
622
600
  journal.incrementFixtureMatchCount(fixture, fixtures, testId);
623
601
  logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);
@@ -651,7 +629,7 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
651
629
  return;
652
630
  }
653
631
  if (defaults.record) {
654
- const outcome = await proxyAndRecord(req, res, completionReq, "cohere", req.url ?? "/v2/chat", fixtures, defaults, raw);
632
+ const { outcome, clientHungUp } = await withHangUpDetection(req, res, () => proxyAndRecord(req, res, completionReq, "cohere", req.url ?? "/v2/chat", fixtures, defaults, raw));
655
633
  if (outcome === "handled_by_hook") return;
656
634
  if (outcome !== "not_configured") {
657
635
  journal.add({
@@ -662,7 +640,8 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
662
640
  response: {
663
641
  status: res.statusCode ?? 200,
664
642
  fixture: null,
665
- source: "proxy"
643
+ source: "proxy",
644
+ ...proxyInterruption(res, clientHungUp)
666
645
  }
667
646
  });
668
647
  return;
@@ -720,6 +699,23 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
720
699
  }).body);
721
700
  return;
722
701
  }
702
+ if (isRawResponse(resolvedResponse)) {
703
+ await serveRawResponse({
704
+ wire: "cohere",
705
+ stream: cohereReq.stream === true,
706
+ req,
707
+ res,
708
+ fixture,
709
+ response: resolvedResponse,
710
+ body: completionReq,
711
+ journal,
712
+ defaults,
713
+ testId,
714
+ misbehaviorSummary: misbehavior.summary,
715
+ errorWire: "cohere"
716
+ });
717
+ return;
718
+ }
723
719
  const prepared = misbehavior.kind === "applied" ? prepareOpenAIChatMisbehavior(misbehavior) : void 0;
724
720
  const observedK5Stream = cohereReq.stream === true && prepared?.summary.fault === "stop-length-mid-tool";
725
721
  const appliedReasoning = prepared && "reasoning" in prepared.response ? resolveReasoningForModel(prepared.response.reasoning, cohereReq.model, resolveRequestDecisions(defaults.strict, req.headers).reasoningSuppression, logger) : void 0;
@@ -733,6 +729,22 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
733
729
  const empty = prepared?.summary.fault === "empty-response";
734
730
  const latency = fixture.latency ?? defaults.latency;
735
731
  const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);
732
+ const replaySpeed = fixture.replaySpeed ?? defaults.replaySpeed;
733
+ const streamTiming = {
734
+ latency,
735
+ streamingProfile: fixture.streamingProfile,
736
+ recordedTimings: fixture.recordedTimings,
737
+ replaySpeed
738
+ };
739
+ const codec = typedSseCodec({ terminalSentinel: observedK5Stream });
740
+ const jsonOpts = (payloadLength) => ({
741
+ surface: "other",
742
+ payloadLength,
743
+ chunkSize,
744
+ recordedTimings: fixture.recordedTimings,
745
+ duplicateId: !!prepared?.duplicateId,
746
+ replaySpeed
747
+ });
736
748
  if (isErrorResponse(response)) {
737
749
  const status = response.status ?? 500;
738
750
  recordMisbehaviorOutcome({
@@ -775,28 +787,8 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
775
787
  testId
776
788
  });
777
789
  const functionToolCalls = requireEmittedFunctionToolCalls(response, "Cohere");
778
- if (cohereReq.stream !== true) {
779
- const body = buildCohereContentWithToolCallsResponse(response.content ?? "", functionToolCalls, logger, effReasoning, overrides, response.blocks);
780
- res.writeHead(200, { "Content-Type": "application/json" });
781
- res.end(JSON.stringify(body));
782
- } else {
783
- const events = buildCohereContentWithToolCallsStreamEvents(response.content ?? "", functionToolCalls, chunkSize, logger, effReasoning, overrides, response.blocks);
784
- const interruption = createInterruptionSignal(fixture);
785
- if (!await writeCohereSSEStream(res, events, {
786
- terminalSentinel: observedK5Stream,
787
- latency,
788
- streamingProfile: fixture.streamingProfile,
789
- recordedTimings: fixture.recordedTimings,
790
- replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
791
- signal: interruption?.signal,
792
- onChunkSent: interruption?.tick
793
- })) {
794
- if (!res.writableEnded) res.destroy();
795
- journalEntry.response.interrupted = true;
796
- journalEntry.response.interruptReason = interruption?.reason();
797
- }
798
- interruption?.cleanup();
799
- }
790
+ if (cohereReq.stream !== true) await deliverJson(res, journalEntry, fixture, () => buildCohereContentWithToolCallsResponse(response.content ?? "", functionToolCalls, logger, effReasoning, overrides, response.blocks), jsonOpts(servedPayloadLength(response, effReasoning)));
791
+ else await deliverStream(res, journalEntry, fixture, codec, buildCohereContentWithToolCallsStreamEvents(response.content ?? "", functionToolCalls, chunkSize, logger, effReasoning, overrides, response.blocks), streamTiming);
800
792
  return;
801
793
  }
802
794
  if (isTextResponse(response)) {
@@ -820,37 +812,17 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
820
812
  defaults,
821
813
  testId
822
814
  });
823
- if (cohereReq.stream !== true) {
824
- const body = empty ? {
825
- ...buildCohereTextResponse("", void 0, overrides),
826
- message: {
827
- role: "assistant",
828
- content: [],
829
- tool_calls: [],
830
- tool_plan: "",
831
- citations: []
832
- }
833
- } : buildCohereTextResponse(response.content, effReasoning, overrides);
834
- res.writeHead(200, { "Content-Type": "application/json" });
835
- res.end(JSON.stringify(body));
836
- } else {
837
- const events = buildCohereTextStreamEvents(response.content, chunkSize, effReasoning, overrides).filter((event) => !empty || event.type === "message-start" || event.type === "message-end");
838
- const interruption = createInterruptionSignal(fixture);
839
- if (!await writeCohereSSEStream(res, events, {
840
- terminalSentinel: observedK5Stream,
841
- latency,
842
- streamingProfile: fixture.streamingProfile,
843
- recordedTimings: fixture.recordedTimings,
844
- replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
845
- signal: interruption?.signal,
846
- onChunkSent: interruption?.tick
847
- })) {
848
- if (!res.writableEnded) res.destroy();
849
- journalEntry.response.interrupted = true;
850
- journalEntry.response.interruptReason = interruption?.reason();
815
+ if (cohereReq.stream !== true) await deliverJson(res, journalEntry, fixture, () => empty ? {
816
+ ...buildCohereTextResponse("", void 0, overrides),
817
+ message: {
818
+ role: "assistant",
819
+ content: [],
820
+ tool_calls: [],
821
+ tool_plan: "",
822
+ citations: []
851
823
  }
852
- interruption?.cleanup();
853
- }
824
+ } : buildCohereTextResponse(response.content, effReasoning, overrides), jsonOpts(servedPayloadLength(response, effReasoning)));
825
+ else await deliverStream(res, journalEntry, fixture, codec, buildCohereTextStreamEvents(response.content, chunkSize, effReasoning, overrides).filter((event) => !empty || event.type === "message-start" || event.type === "message-end"), streamTiming);
854
826
  return;
855
827
  }
856
828
  if (isToolCallResponse(response)) {
@@ -875,28 +847,8 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
875
847
  testId
876
848
  });
877
849
  const functionToolCalls = requireEmittedFunctionToolCalls(response, "Cohere");
878
- if (cohereReq.stream !== true) {
879
- const body = buildCohereToolCallResponse(functionToolCalls, logger, effReasoning, overrides);
880
- res.writeHead(200, { "Content-Type": "application/json" });
881
- res.end(JSON.stringify(body));
882
- } else {
883
- const events = buildCohereToolCallStreamEvents(functionToolCalls, chunkSize, logger, effReasoning, overrides);
884
- const interruption = createInterruptionSignal(fixture);
885
- if (!await writeCohereSSEStream(res, events, {
886
- terminalSentinel: observedK5Stream,
887
- latency,
888
- streamingProfile: fixture.streamingProfile,
889
- recordedTimings: fixture.recordedTimings,
890
- replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,
891
- signal: interruption?.signal,
892
- onChunkSent: interruption?.tick
893
- })) {
894
- if (!res.writableEnded) res.destroy();
895
- journalEntry.response.interrupted = true;
896
- journalEntry.response.interruptReason = interruption?.reason();
897
- }
898
- interruption?.cleanup();
899
- }
850
+ if (cohereReq.stream !== true) await deliverJson(res, journalEntry, fixture, () => buildCohereToolCallResponse(functionToolCalls, logger, effReasoning, overrides), jsonOpts(servedPayloadLength(response, effReasoning)));
851
+ else await deliverStream(res, journalEntry, fixture, codec, buildCohereToolCallStreamEvents(functionToolCalls, chunkSize, logger, effReasoning, overrides), streamTiming);
900
852
  return;
901
853
  }
902
854
  recordMisbehaviorOutcome({
@@ -1 +1 @@
1
- {"version":3,"file":"cohere.js","names":["renderCohereUsage"],"sources":["../src/cohere.ts"],"sourcesContent":["/**\n * Cohere v2 Chat API endpoint support.\n *\n * Translates incoming /v2/chat requests into the ChatCompletionRequest\n * format used by the fixture router, and converts fixture responses back into\n * Cohere's typed SSE streaming (or non-streaming) format.\n *\n * Cohere uses typed SSE events (event: + data: lines), similar to the\n * Claude Messages handler in messages.ts.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n FixtureBlock,\n HandlerDefaults,\n RecordedTimings,\n ResponseOverrides,\n StreamingProfile,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n prepareOpenAIChatMisbehavior,\n resolveOpenAIChatMisbehaviorUsage,\n generateMessageId,\n generateToolCallId,\n generateDeterministicEmbedding,\n extractOverrides,\n requireEmittedFunctionToolCalls,\n isTextResponse,\n isToolCallResponse,\n isCombinedFixtureResponse,\n isEmbeddingResponse,\n isErrorResponse,\n validateChatMessages,\n validateToolsField,\n flattenHeaders,\n isJsonObject,\n getTestId,\n resolveFixtureBlockOutcome,\n resolveResponse,\n resolveReasoningForModel,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n servedToolArgs,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic, recordMatchOptions } from \"./router.js\";\nimport { writeErrorResponse, delay, calculateDelay } from \"./sse-writer.js\";\nimport { createInterruptionSignal } from \"./interruption.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport {\n normalizeDirectToolSchema,\n planMisbehavior,\n recordMisbehaviorOutcome,\n} from \"./misbehavior.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { mapCohereFinish } from \"./response/finish.js\";\nimport { render as renderCohereUsage } from \"./response/usage/codecs/cohere.js\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport { renderError } from \"./response/errors.js\";\n\n// ─── Cohere v2 Chat request types ───────────────────────────────────────────\n\ninterface CohereToolCallDef {\n id?: string;\n type: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface CohereContentPart {\n type: string;\n text?: string;\n}\n\ninterface CohereMessage {\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string | CohereContentPart[];\n tool_call_id?: string;\n tool_calls?: CohereToolCallDef[];\n}\n\n// OpenAI-style tool definition (wrapped in { type: \"function\", function: { ... } })\ninterface CohereToolDefOpenAI {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\n// Cohere v2 native tool definition (flat: { name, description, parameter_definitions })\ninterface CohereToolDefNative {\n name: string;\n description?: string;\n parameter_definitions?: object;\n}\n\ntype CohereToolDef = CohereToolDefOpenAI | CohereToolDefNative;\n\ninterface CohereRequest {\n model: string;\n messages: CohereMessage[];\n stream?: boolean;\n tools?: CohereToolDef[];\n response_format?: { type: string; json_schema?: object };\n temperature?: number;\n max_tokens?: number;\n}\n\n// ─── Cohere SSE event types ─────────────────────────────────────────────────\n\ninterface CohereSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\n// ─── Cohere finish reason / usage mapping ──────────────────────────────────\n\nfunction cohereFinishReason(\n overrideFinishReason: string | undefined,\n defaultReason: string,\n): string {\n if (!overrideFinishReason) return defaultReason;\n return mapCohereFinish(overrideFinishReason);\n}\n\nfunction cohereUsage(overrides?: ResponseOverrides): ReturnType<typeof renderCohereUsage> {\n return renderCohereUsage(overrides);\n}\n\n// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────\n\n/** Extract plain text from structured content (array of { type, text } parts) or passthrough string. */\nfunction extractTextContent(content: string | CohereContentPart[] | null | undefined): string {\n if (content === null || content === undefined) return \"\";\n if (typeof content === \"string\") return content;\n return content\n .filter(\n (part) =>\n part !== null && part !== undefined && part.type === \"text\" && part.text !== undefined,\n )\n .map((part) => part.text!)\n .join(\"\");\n}\n\n/** Type guard: is this an OpenAI-style tool definition (has `function` key)? */\nfunction isOpenAIToolDef(t: CohereToolDef): t is CohereToolDefOpenAI {\n return \"function\" in t && typeof (t as CohereToolDefOpenAI).function === \"object\";\n}\n\nexport function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n const textContent = extractTextContent(msg.content);\n if (msg.role === \"system\") {\n messages.push({ role: \"system\", content: textContent });\n } else if (msg.role === \"user\") {\n messages.push({ role: \"user\", content: textContent });\n } else if (msg.role === \"assistant\") {\n if (msg.tool_calls && msg.tool_calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: textContent || null,\n tool_calls: msg.tool_calls.map((tc) => ({\n id: tc.id ?? generateToolCallId(),\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n })),\n });\n } else {\n messages.push({ role: \"assistant\", content: textContent });\n }\n } else if (msg.role === \"tool\") {\n messages.push({\n role: \"tool\",\n content: textContent,\n tool_call_id: msg.tool_call_id,\n });\n }\n }\n\n // Convert tools — accept both OpenAI format and Cohere v2 native format\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => {\n if (isOpenAIToolDef(t)) {\n return {\n type: \"function\" as const,\n function: {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n },\n };\n }\n // Preserve the native map identity before adapting to canonical JSON Schema.\n const schema = normalizeDirectToolSchema({ tools: [t] }, t.name);\n // Cohere v2 native format: { name, description, parameter_definitions }\n return {\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: schema\n ? { type: \"object\", properties: schema.properties, required: [...schema.required] }\n : undefined,\n },\n };\n });\n }\n\n return {\n model: req.model,\n messages,\n stream: req.stream,\n tools,\n ...(req.response_format && { response_format: req.response_format }),\n ...(req.temperature !== undefined && { temperature: req.temperature }),\n ...(req.max_tokens !== undefined && { max_tokens: req.max_tokens }),\n };\n}\n\n// ─── Response building: fixture → Cohere v2 Chat format ─────────────────────\n\n// Non-streaming text response\nfunction buildCohereTextResponse(\n content: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n contentBlocks.push({ type: \"text\", text: content });\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming tool call response\nfunction buildCohereToolCallResponse(\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const cohereCalls = toolCalls.map((tc) => {\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // Reasoning as a leading text block (Cohere has no native reasoning type)\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming content + tool calls response\nfunction buildCohereContentWithToolCallsResponse(\n content: string,\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): object {\n // Cohere's non-streaming response keeps text in `message.content[]` and tool\n // calls in the SEPARATE `message.tool_calls[]` field, so the relative ORDER\n // of a text vs. toolCall block is NOT observable on the wire (unlike the\n // ordered streaming events, or Anthropic/Gemini's single ordered array).\n // When `blocks` is present we therefore derive both fields FROM the blocks\n // (so a blocks-only fixture still produces correct output) but make no\n // ordering guarantee between the two fields. Legacy fixtures use the\n // `content` + `toolCalls` inputs unchanged.\n // Resolve the blocks exactly once (pure: validate + copy, no id-gen) and\n // reuse the single result for BOTH the tool-call and text derivation below.\n const outcome = blocks && blocks.length > 0 ? resolveFixtureBlockOutcome(blocks) : undefined;\n const resolvedBlocks = outcome?.ordered;\n\n const effectiveToolCalls: ToolCall[] = resolvedBlocks\n ? resolvedBlocks\n .filter((b): b is Extract<FixtureBlock, { type: \"toolCall\" }> => b.type === \"toolCall\")\n .map((b) => ({ name: b.name, arguments: b.arguments, id: b.id }))\n : toolCalls;\n\n const cohereCalls = effectiveToolCalls.map((tc) => {\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // For the blocks path, derive text only from actual text blocks. A tool-only\n // blocks fixture has no text block, so it must NOT emit a spurious empty\n // `{ type: \"text\", text: \"\" }` entry (real Cohere wouldn't). The legacy\n // (no-blocks) path is unchanged: it always emits the `content` text entry.\n const textBlocks = resolvedBlocks?.filter(\n (b): b is Extract<FixtureBlock, { type: \"text\" }> => b.type === \"text\",\n );\n const hasTextEntry = resolvedBlocks ? (textBlocks?.length ?? 0) > 0 : true;\n const effectiveContent: string = resolvedBlocks\n ? (textBlocks ?? []).map((b) => b.text).join(\"\")\n : content;\n\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n if (hasTextEntry) {\n contentBlocks.push({ type: \"text\", text: effectiveContent });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome && !outcome.hasToolCalls ? \"COMPLETE\" : \"TOOL_CALL\",\n ),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// ─── Streaming event builders ───────────────────────────────────────────────\n\nfunction buildCohereTextStreamEvents(\n content: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereToolCallStreamEvents(\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n // Reasoning as a text block before the tool plan (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: 0,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: 0,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: 0 });\n }\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereContentWithToolCallsStreamEvents(\n content: string,\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n if (blocks && blocks.length > 0) {\n // NEW path (#274): emit Cohere SSE events in the blocks' ARRAY ORDER so a\n // tool-first / interleaved fixture streams its tool call before its text.\n // Cohere v2 events are ordered, so tool-first is wire-expressible. The\n // tool-plan-delta is emitted once before the first toolCall block (Cohere\n // requires it preceding tool calls). Legacy fixtures (no blocks) skip this.\n const outcome = resolveFixtureBlockOutcome(blocks);\n const resolved = outcome.ordered;\n let toolPlanEmitted = false;\n let toolIdx = 0;\n resolved.forEach((block) => {\n if (block.type === \"toolCall\") {\n if (!toolPlanEmitted) {\n events.push({\n type: \"tool-plan-delta\",\n delta: { message: { tool_plan: \"I will use the requested tool.\" } },\n });\n toolPlanEmitted = true;\n }\n const callId = block.id || generateToolCallId();\n const args = servedToolArgs(block, \"string\", logger);\n const argsJson = args.raw;\n events.push({\n type: \"tool-call-start\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: { name: block.name, arguments: \"\" },\n },\n },\n },\n });\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n events.push({\n type: \"tool-call-delta\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: { function: { arguments: argsJson.slice(i, i + chunkSize) } },\n },\n },\n });\n }\n events.push({ type: \"tool-call-end\", index: toolIdx });\n toolIdx++;\n } else {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < block.text.length; i += chunkSize) {\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: { content: { type: \"text\", text: block.text.slice(i, i + chunkSize) } },\n },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n });\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome.hasToolCalls ? \"TOOL_CALL\" : \"COMPLETE\",\n ),\n usage: cohereUsage(overrides),\n },\n });\n return events;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n // Tool call events\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\n// ─── SSE writer for Cohere typed events ─────────────────────────────────────\n\ninterface CohereStreamOptions {\n terminalSentinel?: boolean;\n latency?: number;\n streamingProfile?: StreamingProfile;\n recordedTimings?: RecordedTimings;\n replaySpeed?: number;\n signal?: AbortSignal;\n onChunkSent?: () => void;\n}\n\nasync function writeCohereSSEStream(\n res: http.ServerResponse,\n events: CohereSSEEvent[],\n optionsOrLatency?: number | CohereStreamOptions,\n): Promise<boolean> {\n const opts: CohereStreamOptions =\n typeof optionsOrLatency === \"number\" ? { latency: optionsOrLatency } : (optionsOrLatency ?? {});\n const latency = opts.latency ?? 0;\n const profile = opts.streamingProfile;\n const { recordedTimings, replaySpeed } = opts;\n const signal = opts.signal;\n const onChunkSent = opts.onChunkSent;\n\n if (res.writableEnded) return true;\n res.setHeader(\"Content-Type\", \"text/event-stream\");\n res.setHeader(\"Cache-Control\", \"no-cache\");\n res.setHeader(\"Connection\", \"keep-alive\");\n\n let chunkIndex = 0;\n for (const event of events) {\n const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);\n if (chunkDelay > 0) await delay(chunkDelay, signal);\n if (signal?.aborted) return false;\n if (res.writableEnded) return true;\n res.write(`event: ${event.type}\\ndata: ${JSON.stringify(event)}\\n\\n`);\n onChunkSent?.();\n if (signal?.aborted) return false;\n chunkIndex++;\n }\n\n if (!res.writableEnded) {\n if (opts.terminalSentinel && !signal?.aborted) res.write(\"data: [DONE]\\n\\n\");\n res.end();\n }\n return true;\n}\n\n// ─── Request handler ────────────────────────────────────────────────────────\n\nexport async function handleCohere(\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): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let cohereReq: CohereRequest;\n try {\n cohereReq = JSON.parse(raw) as CohereRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Malformed JSON body: ${detail}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `cohereReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(cohereReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Validate required model field\n if (!cohereReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"model is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject wrong-typed message/tool fields before the converter dereferences\n // them — otherwise the TypeError surfaces as a 500 instead of a 400.\n let shapeError = validateChatMessages(cohereReq.messages) ?? validateToolsField(cohereReq.tools);\n if (!shapeError && Array.isArray(cohereReq.tools)) {\n const nullFunctionIndex = cohereReq.tools.findIndex(\n (tool) => \"function\" in tool && tool.function === null,\n );\n if (nullFunctionIndex !== -1) {\n shapeError = `tools[${nullFunctionIndex}].function must be an object`;\n }\n }\n if (shapeError) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Invalid request: ${shapeError}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = cohereToCompletionRequest(cohereReq);\n completionReq._endpointType = \"chat\";\n completionReq._context = getContext(req);\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss;\n if (effectiveStrict) {\n const strictStatus = 503;\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/chat\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: strictStatus,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n strictStatus,\n renderError(\"cohere\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"cohere\",\n req.url ?? \"/v2/chat\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n });\n return;\n }\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n renderError(\"cohere\", \"fixture-miss\", {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n const resolvedResponse = await resolveResponse(fixture, completionReq);\n const misbehavior = planMisbehavior({\n wire: \"cohere\",\n fixture,\n response: resolvedResponse,\n request: completionReq,\n stream: cohereReq.stream === true,\n emitsToolCallIds: true,\n defaults,\n rawHeaders: req.headers,\n url: req.url,\n });\n if (misbehavior.kind === \"error\") {\n const entry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: misbehavior.status, fixture },\n });\n recordMisbehaviorOutcome({ entry, summary: misbehavior.summary, defaults, testId });\n if (!misbehavior.summary?.evaluations.length) logger.error(misbehavior.message);\n writeErrorResponse(\n res,\n misbehavior.status,\n renderError(\"cohere\", \"misbehavior\", {\n message: misbehavior.message,\n code: misbehavior.code,\n }).body,\n );\n return;\n }\n // Cohere carries the same raw argument strings and call identities as Chat.\n // Reuse the accepted preparation so generated/duplicate IDs match metadata.\n const prepared =\n misbehavior.kind === \"applied\" ? prepareOpenAIChatMisbehavior(misbehavior) : undefined;\n const observedK5Stream =\n cohereReq.stream === true && prepared?.summary.fault === \"stop-length-mid-tool\";\n const appliedReasoning =\n prepared && \"reasoning\" in prepared.response\n ? resolveReasoningForModel(\n prepared.response.reasoning,\n cohereReq.model,\n resolveRequestDecisions(defaults.strict, req.headers).reasoningSuppression,\n logger,\n )\n : undefined;\n const usage = prepared\n ? resolveOpenAIChatMisbehaviorUsage(prepared, completionReq, appliedReasoning !== undefined)\n : undefined;\n const response =\n prepared && usage\n ? {\n ...prepared.response,\n usage,\n ...(prepared.stop\n ? { finishReason: observedK5Stream ? \"tool_calls\" : prepared.stop }\n : {}),\n }\n : resolvedResponse;\n const summary = prepared?.summary ?? misbehavior.summary;\n const empty = prepared?.summary.fault === \"empty-response\";\n const latency = fixture.latency ?? defaults.latency;\n const chunkSize = Math.max(1, fixture.chunkSize ?? defaults.chunkSize);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Content + tool calls response (must be checked before text/tool-only branches)\n if (isCombinedFixtureResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n const body = buildCohereContentWithToolCallsResponse(\n response.content ?? \"\",\n functionToolCalls,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n );\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereContentWithToolCallsStreamEvents(\n response.content ?? \"\",\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n terminalSentinel: observedK5Stream,\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n if (cohereReq.stream !== true) {\n const body = empty\n ? {\n ...buildCohereTextResponse(\"\", undefined, overrides),\n message: {\n role: \"assistant\",\n content: [],\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n }\n : buildCohereTextResponse(response.content, effReasoning, overrides);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereTextStreamEvents(\n response.content,\n chunkSize,\n effReasoning,\n overrides,\n ).filter((event) => !empty || event.type === \"message-start\" || event.type === \"message-end\");\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n terminalSentinel: observedK5Stream,\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n const body = buildCohereToolCallResponse(functionToolCalls, logger, effReasoning, overrides);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereToolCallStreamEvents(\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n terminalSentinel: observedK5Stream,\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed: fixture.replaySpeed ?? defaults.replaySpeed,\n signal: interruption?.signal,\n onChunkSent: interruption?.tick,\n });\n if (!completed) {\n if (!res.writableEnded) res.destroy();\n journalEntry.response.interrupted = true;\n journalEntry.response.interruptReason = interruption?.reason();\n }\n interruption?.cleanup();\n }\n return;\n }\n\n // Unknown response type\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n recordMisbehaviorOutcome({ entry: journalEntry, summary, defaults, testId });\n writeErrorResponse(\n res,\n 500,\n renderError(\"cohere\", \"unknown-response\", {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n }).body,\n );\n}\n\n// ─── Cohere v2 Embed API types ────────────────────────────────────────────\n\ninterface CohereEmbedRequest {\n texts: string[];\n model: string;\n input_type?: string;\n embedding_types?: string[];\n truncate?: string;\n}\n\ninterface CohereEmbedResponse {\n id: string;\n texts: string[];\n embeddings: Record<string, number[][]>;\n meta: { api_version: { version: string } };\n}\n\n// ─── Cohere Embed handler ─────────────────────────────────────────────────\n\nexport async function handleCohereEmbed(\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): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let embedReq: CohereEmbedRequest;\n try {\n embedReq = JSON.parse(raw) as CohereEmbedRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Malformed JSON body: ${detail}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `embedReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(embedReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Validate required fields\n if (!embedReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"model is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n if (!embedReq.texts || !Array.isArray(embedReq.texts)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Invalid request: texts array is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Every text must be a string — a number reaches createHash().update() in\n // the no-fixture fallback and throws a TypeError (500) instead of a 400.\n if (!embedReq.texts.every((text) => typeof text === \"string\")) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Invalid request: texts must be an array of strings\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Concatenate all texts for fixture matching\n const combinedInput = embedReq.texts.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router\n const syntheticReq: ChatCompletionRequest = {\n model: embedReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\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 // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n // Determine requested embedding types (default to float)\n const embeddingTypes =\n embedReq.embedding_types && embedReq.embedding_types.length > 0\n ? embedReq.embedding_types\n : [\"float\"];\n\n function rejectInvalidEmbeddingTypes(): boolean {\n if (embedReq.embedding_types == null) return false;\n const isArray = Array.isArray(embedReq.embedding_types);\n if (isArray && embedReq.embedding_types.every((type) => typeof type === \"string\")) return false;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 400, fixture: fixture ?? null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: isArray\n ? \"Invalid request: embedding_types must be an array of strings\"\n : \"Invalid request: embedding_types must be an array\",\n type: \"invalid_request_error\",\n }).body,\n );\n return true;\n }\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Embedding response — use the fixture's embedding for each input text\n if (isEmbeddingResponse(response)) {\n if (rejectInvalidEmbeddingTypes()) return;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const vectors = embedReq.texts.map(() => [...response.embedding]);\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n renderError(\"cohere\", \"unknown-response\", {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n }).body,\n );\n return;\n }\n\n // No fixture match — check strict mode\n if (resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/embed\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 renderError(\"cohere\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Try record-and-replay proxy\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"cohere\",\n req.url ?? \"/v2/embed\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 if (rejectInvalidEmbeddingTypes()) return;\n\n // No fixture match — generate deterministic embeddings from input texts\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n const dimensions = 1024; // Cohere embed-v4.0 default\n const vectors = embedReq.texts.map((text) => generateDeterministicEmbedding(text, dimensions));\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;;;;;;;AAgIA,SAAS,mBACP,sBACA,eACQ;AACR,KAAI,CAAC,qBAAsB,QAAO;AAClC,QAAO,gBAAgB,qBAAqB;;AAG9C,SAAS,YAAY,WAAqE;AACxF,QAAOA,OAAkB,UAAU;;;AAMrC,SAAS,mBAAmB,SAAkE;AAC5F,KAAI,YAAY,QAAQ,YAAY,OAAW,QAAO;AACtD,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAO,QACJ,QACE,SACC,SAAS,QAAQ,SAAS,UAAa,KAAK,SAAS,UAAU,KAAK,SAAS,OAChF,CACA,KAAK,SAAS,KAAK,KAAM,CACzB,KAAK,GAAG;;;AAIb,SAAS,gBAAgB,GAA4C;AACnE,QAAO,cAAc,KAAK,OAAQ,EAA0B,aAAa;;AAG3E,SAAgB,0BAA0B,KAA2C;CACnF,MAAM,WAA0B,EAAE;AAElC,MAAK,MAAM,OAAO,IAAI,UAAU;EAC9B,MAAM,cAAc,mBAAmB,IAAI,QAAQ;AACnD,MAAI,IAAI,SAAS,SACf,UAAS,KAAK;GAAE,MAAM;GAAU,SAAS;GAAa,CAAC;WAC9C,IAAI,SAAS,OACtB,UAAS,KAAK;GAAE,MAAM;GAAQ,SAAS;GAAa,CAAC;WAC5C,IAAI,SAAS,YACtB,KAAI,IAAI,cAAc,IAAI,WAAW,SAAS,EAC5C,UAAS,KAAK;GACZ,MAAM;GACN,SAAS,eAAe;GACxB,YAAY,IAAI,WAAW,KA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AAS;IACT,GAAG,oBAAoB,SAAS,QAAQ,IAAI,QAAQ;IACrD;GACF,CAAC;AACF,qBACE,KACA,KACA,YAAY,UAAU,eAAe;GACnC,SAAS;GACT,MAAM;GACP,CAAC,CAAC,KACJ;AACD;;AAIF,KAAI,SAAS,QAAQ;EACnB,MAAM,UAAU,MAAM,eACpB,KACA,KACA,cACA,UACA,IAAI,OAAO,aACX,UACA,UACA,IACD;AACD,MAAI,YAAY,kBAAmB;AACnC,MAAI,YAAY,kBAAkB;AAChC,WAAQ,IAAI;IACV,QAAQ,IAAI,UAAU;IACtB,MAAM,IAAI,OAAO;IACjB,SAAS,eAAe,IAAI,QAAQ;IACpC,MAAM;IACN,UAAU;KAAE,QAAQ,IAAI,cAAc;KAAK,SAAS;KAAM,QAAQ;KAAS;IAC5E,CAAC;AACF;;;AAIJ,KAAI,6BAA6B,CAAE;AAGnC,QAAO,KACL,qCAAqC,cAAc,MAAM,GAAG,GAAG,CAAC,sCACjE;CACD,MAAM,aAAa;CACnB,MAAM,UAAU,SAAS,MAAM,KAAK,SAAS,+BAA+B,MAAM,WAAW,CAAC;CAC9F,MAAM,aAAyC,EAAE;AACjD,MAAK,MAAM,KAAK,eACd,YAAW,KAAK;AAGlB,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK,SAAS;GAAM;EACzC,CAAC;CAEF,MAAM,OAA4B;EAChC,IAAI,mBAAmB;EACvB,OAAO,SAAS;EAChB;EACA,MAAM,EAAE,aAAa,EAAE,SAAS,KAAK,EAAE;EACxC;AACD,KAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,KAAI,IAAI,KAAK,UAAU,KAAK,CAAC"}
1
+ {"version":3,"file":"cohere.js","names":["renderCohereUsage"],"sources":["../src/cohere.ts"],"sourcesContent":["/**\n * Cohere v2 Chat API endpoint support.\n *\n * Translates incoming /v2/chat requests into the ChatCompletionRequest\n * format used by the fixture router, and converts fixture responses back into\n * Cohere's typed SSE streaming (or non-streaming) format.\n *\n * Cohere uses typed SSE events (event: + data: lines), similar to the\n * Claude Messages handler in messages.ts.\n */\n\nimport type * as http from \"node:http\";\nimport type {\n ChatCompletionRequest,\n ChatMessage,\n Fixture,\n FixtureBlock,\n HandlerDefaults,\n ResponseOverrides,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n prepareOpenAIChatMisbehavior,\n resolveOpenAIChatMisbehaviorUsage,\n generateMessageId,\n generateToolCallId,\n generateDeterministicEmbedding,\n extractOverrides,\n requireEmittedFunctionToolCalls,\n isTextResponse,\n isToolCallResponse,\n isCombinedFixtureResponse,\n isEmbeddingResponse,\n isErrorResponse,\n isRawResponse,\n validateChatMessages,\n validateToolsField,\n flattenHeaders,\n isJsonObject,\n getTestId,\n resolveFixtureBlockOutcome,\n resolveResponse,\n resolveReasoningForModel,\n getContext,\n strictNoMatchMessage,\n strictNoMatchLogLine,\n servedToolArgs,\n} from \"./helpers.js\";\nimport { matchFixtureDiagnostic, recordMatchOptions } from \"./router.js\";\nimport { writeErrorResponse, typedSseCodec } from \"./sse-writer.js\";\nimport { deliverJson, deliverStream } from \"./response/deliver.js\";\nimport { proxyInterruption, withHangUpDetection } from \"./response/proxy.js\";\nimport { servedPayloadLength } from \"./response/timing.js\";\nimport type { Journal } from \"./journal.js\";\nimport type { Logger } from \"./logger.js\";\nimport { applyChaosAsync } from \"./chaos.js\";\nimport {\n normalizeDirectToolSchema,\n planMisbehavior,\n recordMisbehaviorOutcome,\n} from \"./misbehavior.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\nimport { mapCohereFinish } from \"./response/finish.js\";\nimport { render as renderCohereUsage } from \"./response/usage/codecs/cohere.js\";\nimport { resolveRequestDecisions, strictOverrideField } from \"./response/policy.js\";\nimport { renderError } from \"./response/errors.js\";\nimport { serveRawResponse } from \"./response/raw.js\";\n\n// ─── Cohere v2 Chat request types ───────────────────────────────────────────\n\ninterface CohereToolCallDef {\n id?: string;\n type: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\ninterface CohereContentPart {\n type: string;\n text?: string;\n}\n\ninterface CohereMessage {\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string | CohereContentPart[];\n tool_call_id?: string;\n tool_calls?: CohereToolCallDef[];\n}\n\n// OpenAI-style tool definition (wrapped in { type: \"function\", function: { ... } })\ninterface CohereToolDefOpenAI {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\n// Cohere v2 native tool definition (flat: { name, description, parameter_definitions })\ninterface CohereToolDefNative {\n name: string;\n description?: string;\n parameter_definitions?: object;\n}\n\ntype CohereToolDef = CohereToolDefOpenAI | CohereToolDefNative;\n\ninterface CohereRequest {\n model: string;\n messages: CohereMessage[];\n stream?: boolean;\n tools?: CohereToolDef[];\n response_format?: { type: string; json_schema?: object };\n temperature?: number;\n max_tokens?: number;\n}\n\n// ─── Cohere SSE event types ─────────────────────────────────────────────────\n\ninterface CohereSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\n// ─── Cohere finish reason / usage mapping ──────────────────────────────────\n\nfunction cohereFinishReason(\n overrideFinishReason: string | undefined,\n defaultReason: string,\n): string {\n if (!overrideFinishReason) return defaultReason;\n return mapCohereFinish(overrideFinishReason);\n}\n\nfunction cohereUsage(overrides?: ResponseOverrides): ReturnType<typeof renderCohereUsage> {\n return renderCohereUsage(overrides);\n}\n\n// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────\n\n/** Extract plain text from structured content (array of { type, text } parts) or passthrough string. */\nfunction extractTextContent(content: string | CohereContentPart[] | null | undefined): string {\n if (content === null || content === undefined) return \"\";\n if (typeof content === \"string\") return content;\n return content\n .filter(\n (part) =>\n part !== null && part !== undefined && part.type === \"text\" && part.text !== undefined,\n )\n .map((part) => part.text!)\n .join(\"\");\n}\n\n/** Type guard: is this an OpenAI-style tool definition (has `function` key)? */\nfunction isOpenAIToolDef(t: CohereToolDef): t is CohereToolDefOpenAI {\n return \"function\" in t && typeof (t as CohereToolDefOpenAI).function === \"object\";\n}\n\nexport function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n const textContent = extractTextContent(msg.content);\n if (msg.role === \"system\") {\n messages.push({ role: \"system\", content: textContent });\n } else if (msg.role === \"user\") {\n messages.push({ role: \"user\", content: textContent });\n } else if (msg.role === \"assistant\") {\n if (msg.tool_calls && msg.tool_calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: textContent || null,\n tool_calls: msg.tool_calls.map((tc) => ({\n id: tc.id ?? generateToolCallId(),\n type: \"function\" as const,\n function: {\n name: tc.function.name,\n arguments: tc.function.arguments,\n },\n })),\n });\n } else {\n messages.push({ role: \"assistant\", content: textContent });\n }\n } else if (msg.role === \"tool\") {\n messages.push({\n role: \"tool\",\n content: textContent,\n tool_call_id: msg.tool_call_id,\n });\n }\n }\n\n // Convert tools — accept both OpenAI format and Cohere v2 native format\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => {\n if (isOpenAIToolDef(t)) {\n return {\n type: \"function\" as const,\n function: {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n },\n };\n }\n // Preserve the native map identity before adapting to canonical JSON Schema.\n const schema = normalizeDirectToolSchema({ tools: [t] }, t.name);\n // Cohere v2 native format: { name, description, parameter_definitions }\n return {\n type: \"function\" as const,\n function: {\n name: t.name,\n description: t.description,\n parameters: schema\n ? { type: \"object\", properties: schema.properties, required: [...schema.required] }\n : undefined,\n },\n };\n });\n }\n\n return {\n model: req.model,\n messages,\n stream: req.stream,\n tools,\n ...(req.response_format && { response_format: req.response_format }),\n ...(req.temperature !== undefined && { temperature: req.temperature }),\n ...(req.max_tokens !== undefined && { max_tokens: req.max_tokens }),\n };\n}\n\n// ─── Response building: fixture → Cohere v2 Chat format ─────────────────────\n\n// Non-streaming text response\nfunction buildCohereTextResponse(\n content: string,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n contentBlocks.push({ type: \"text\", text: content });\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming tool call response\nfunction buildCohereToolCallResponse(\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): object {\n const cohereCalls = toolCalls.map((tc) => {\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // Reasoning as a leading text block (Cohere has no native reasoning type)\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// Non-streaming content + tool calls response\nfunction buildCohereContentWithToolCallsResponse(\n content: string,\n toolCalls: ToolCall[],\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): object {\n // Cohere's non-streaming response keeps text in `message.content[]` and tool\n // calls in the SEPARATE `message.tool_calls[]` field, so the relative ORDER\n // of a text vs. toolCall block is NOT observable on the wire (unlike the\n // ordered streaming events, or Anthropic/Gemini's single ordered array).\n // When `blocks` is present we therefore derive both fields FROM the blocks\n // (so a blocks-only fixture still produces correct output) but make no\n // ordering guarantee between the two fields. Legacy fixtures use the\n // `content` + `toolCalls` inputs unchanged.\n // Resolve the blocks exactly once (pure: validate + copy, no id-gen) and\n // reuse the single result for BOTH the tool-call and text derivation below.\n const outcome = blocks && blocks.length > 0 ? resolveFixtureBlockOutcome(blocks) : undefined;\n const resolvedBlocks = outcome?.ordered;\n\n const effectiveToolCalls: ToolCall[] = resolvedBlocks\n ? resolvedBlocks\n .filter((b): b is Extract<FixtureBlock, { type: \"toolCall\" }> => b.type === \"toolCall\")\n .map((b) => ({ name: b.name, arguments: b.arguments, id: b.id }))\n : toolCalls;\n\n const cohereCalls = effectiveToolCalls.map((tc) => {\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n // For the blocks path, derive text only from actual text blocks. A tool-only\n // blocks fixture has no text block, so it must NOT emit a spurious empty\n // `{ type: \"text\", text: \"\" }` entry (real Cohere wouldn't). The legacy\n // (no-blocks) path is unchanged: it always emits the `content` text entry.\n const textBlocks = resolvedBlocks?.filter(\n (b): b is Extract<FixtureBlock, { type: \"text\" }> => b.type === \"text\",\n );\n const hasTextEntry = resolvedBlocks ? (textBlocks?.length ?? 0) > 0 : true;\n const effectiveContent: string = resolvedBlocks\n ? (textBlocks ?? []).map((b) => b.text).join(\"\")\n : content;\n\n const contentBlocks: { type: string; text: string }[] = [];\n if (reasoning) {\n contentBlocks.push({ type: \"text\", text: reasoning });\n }\n if (hasTextEntry) {\n contentBlocks.push({ type: \"text\", text: effectiveContent });\n }\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome && !outcome.hasToolCalls ? \"COMPLETE\" : \"TOOL_CALL\",\n ),\n message: {\n role: \"assistant\",\n content: contentBlocks,\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: cohereUsage(overrides),\n };\n}\n\n// ─── Streaming event builders ───────────────────────────────────────────────\n\nfunction buildCohereTextStreamEvents(\n content: string,\n chunkSize: number,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"COMPLETE\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereToolCallStreamEvents(\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n // Reasoning as a text block before the tool plan (Cohere has no native reasoning type)\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: 0,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: 0,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: 0 });\n }\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n // Validate arguments JSON\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\nfunction buildCohereContentWithToolCallsStreamEvents(\n content: string,\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n reasoning?: string,\n overrides?: ResponseOverrides,\n blocks?: FixtureBlock[],\n): CohereSSEEvent[] {\n const msgId = overrides?.id ?? generateMessageId();\n const events: CohereSSEEvent[] = [];\n\n // message-start\n events.push({\n id: msgId,\n type: \"message-start\",\n delta: {\n message: {\n role: \"assistant\",\n content: [],\n tool_plan: \"\",\n tool_calls: [],\n citations: [],\n },\n },\n });\n\n let contentIndex = 0;\n\n // Reasoning as a text block before main content\n if (reasoning) {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < reasoning.length; i += chunkSize) {\n const slice = reasoning.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\", text: slice } } },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n\n if (blocks && blocks.length > 0) {\n // NEW path (#274): emit Cohere SSE events in the blocks' ARRAY ORDER so a\n // tool-first / interleaved fixture streams its tool call before its text.\n // Cohere v2 events are ordered, so tool-first is wire-expressible. The\n // tool-plan-delta is emitted once before the first toolCall block (Cohere\n // requires it preceding tool calls). Legacy fixtures (no blocks) skip this.\n const outcome = resolveFixtureBlockOutcome(blocks);\n const resolved = outcome.ordered;\n let toolPlanEmitted = false;\n let toolIdx = 0;\n resolved.forEach((block) => {\n if (block.type === \"toolCall\") {\n if (!toolPlanEmitted) {\n events.push({\n type: \"tool-plan-delta\",\n delta: { message: { tool_plan: \"I will use the requested tool.\" } },\n });\n toolPlanEmitted = true;\n }\n const callId = block.id || generateToolCallId();\n const args = servedToolArgs(block, \"string\", logger);\n const argsJson = args.raw;\n events.push({\n type: \"tool-call-start\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: { name: block.name, arguments: \"\" },\n },\n },\n },\n });\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n events.push({\n type: \"tool-call-delta\",\n index: toolIdx,\n delta: {\n message: {\n tool_calls: { function: { arguments: argsJson.slice(i, i + chunkSize) } },\n },\n },\n });\n }\n events.push({ type: \"tool-call-end\", index: toolIdx });\n toolIdx++;\n } else {\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: { message: { content: { type: \"text\" } } },\n });\n for (let i = 0; i < block.text.length; i += chunkSize) {\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: { content: { type: \"text\", text: block.text.slice(i, i + chunkSize) } },\n },\n });\n }\n events.push({ type: \"content-end\", index: contentIndex });\n contentIndex++;\n }\n });\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(\n overrides?.finishReason,\n outcome.hasToolCalls ? \"TOOL_CALL\" : \"COMPLETE\",\n ),\n usage: cohereUsage(overrides),\n },\n });\n return events;\n }\n\n // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\" },\n },\n },\n });\n\n // content-delta — text chunks\n for (let i = 0; i < content.length; i += chunkSize) {\n const slice = content.slice(i, i + chunkSize);\n events.push({\n type: \"content-delta\",\n index: contentIndex,\n delta: {\n message: {\n content: { type: \"text\", text: slice },\n },\n },\n });\n }\n\n // content-end\n events.push({\n type: \"content-end\",\n index: contentIndex,\n });\n\n // tool-plan-delta\n events.push({\n type: \"tool-plan-delta\",\n delta: {\n message: {\n tool_plan: \"I will use the requested tool.\",\n },\n },\n });\n\n // Tool call events\n for (let idx = 0; idx < toolCalls.length; idx++) {\n const tc = toolCalls[idx];\n const callId = tc.id || generateToolCallId();\n\n const args = servedToolArgs(tc, \"string\", logger);\n const argsJson = args.raw;\n\n // tool-call-start\n events.push({\n type: \"tool-call-start\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n id: callId,\n type: \"function\",\n function: {\n name: tc.name,\n arguments: \"\",\n },\n },\n },\n },\n });\n\n // tool-call-delta — chunked arguments\n for (let i = 0; i < argsJson.length; i += chunkSize) {\n const slice = argsJson.slice(i, i + chunkSize);\n events.push({\n type: \"tool-call-delta\",\n index: idx,\n delta: {\n message: {\n tool_calls: {\n function: {\n arguments: slice,\n },\n },\n },\n },\n });\n }\n\n // tool-call-end\n events.push({\n type: \"tool-call-end\",\n index: idx,\n });\n }\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n usage: cohereUsage(overrides),\n },\n });\n\n return events;\n}\n\n// ─── Request handler ────────────────────────────────────────────────────────\n\nexport async function handleCohere(\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): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let cohereReq: CohereRequest;\n try {\n cohereReq = JSON.parse(raw) as CohereRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Malformed JSON body: ${detail}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `cohereReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(cohereReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Validate required model field\n if (!cohereReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"model is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject wrong-typed message/tool fields before the converter dereferences\n // them — otherwise the TypeError surfaces as a 500 instead of a 400.\n let shapeError = validateChatMessages(cohereReq.messages) ?? validateToolsField(cohereReq.tools);\n if (!shapeError && Array.isArray(cohereReq.tools)) {\n const nullFunctionIndex = cohereReq.tools.findIndex(\n (tool) => \"function\" in tool && tool.function === null,\n );\n if (nullFunctionIndex !== -1) {\n shapeError = `tools[${nullFunctionIndex}].function must be an object`;\n }\n }\n if (shapeError) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Invalid request: ${shapeError}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = cohereToCompletionRequest(cohereReq);\n completionReq._endpointType = \"chat\";\n completionReq._context = getContext(req);\n\n const testId = getTestId(req);\n const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n { ...recordMatchOptions(!!defaults.record, defaults.logger), wire: \"cohere\" },\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n const effectiveStrict = resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss;\n if (effectiveStrict) {\n const strictStatus = 503;\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/chat\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: strictStatus,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n strictStatus,\n renderError(\"cohere\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n if (defaults.record) {\n const { outcome, clientHungUp } = await withHangUpDetection(req, res, () =>\n proxyAndRecord(\n req,\n res,\n completionReq,\n \"cohere\",\n req.url ?? \"/v2/chat\",\n fixtures,\n defaults,\n raw,\n ),\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: res.statusCode ?? 200,\n fixture: null,\n source: \"proxy\",\n ...proxyInterruption(res, clientHungUp),\n },\n });\n return;\n }\n }\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: {\n status: 404,\n fixture: null,\n ...strictOverrideField(defaults.strict, req.headers),\n },\n });\n writeErrorResponse(\n res,\n 404,\n renderError(\"cohere\", \"fixture-miss\", {\n message: \"No fixture matched\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n const resolvedResponse = await resolveResponse(fixture, completionReq);\n const misbehavior = planMisbehavior({\n wire: \"cohere\",\n fixture,\n response: resolvedResponse,\n request: completionReq,\n stream: cohereReq.stream === true,\n emitsToolCallIds: true,\n defaults,\n rawHeaders: req.headers,\n url: req.url,\n });\n if (misbehavior.kind === \"error\") {\n const entry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: misbehavior.status, fixture },\n });\n recordMisbehaviorOutcome({ entry, summary: misbehavior.summary, defaults, testId });\n if (!misbehavior.summary?.evaluations.length) logger.error(misbehavior.message);\n writeErrorResponse(\n res,\n misbehavior.status,\n renderError(\"cohere\", \"misbehavior\", {\n message: misbehavior.message,\n code: misbehavior.code,\n }).body,\n );\n return;\n }\n\n // Raw passthrough (#549): the authored events or JSON, framed for this wire.\n if (isRawResponse(resolvedResponse)) {\n await serveRawResponse({\n wire: \"cohere\",\n stream: cohereReq.stream === true,\n req,\n res,\n fixture,\n response: resolvedResponse,\n body: completionReq,\n journal,\n defaults,\n testId,\n misbehaviorSummary: misbehavior.summary,\n errorWire: \"cohere\",\n });\n return;\n }\n\n // Cohere carries the same raw argument strings and call identities as Chat.\n // Reuse the accepted preparation so generated/duplicate IDs match metadata.\n const prepared =\n misbehavior.kind === \"applied\" ? prepareOpenAIChatMisbehavior(misbehavior) : undefined;\n const observedK5Stream =\n cohereReq.stream === true && prepared?.summary.fault === \"stop-length-mid-tool\";\n const appliedReasoning =\n prepared && \"reasoning\" in prepared.response\n ? resolveReasoningForModel(\n prepared.response.reasoning,\n cohereReq.model,\n resolveRequestDecisions(defaults.strict, req.headers).reasoningSuppression,\n logger,\n )\n : undefined;\n const usage = prepared\n ? resolveOpenAIChatMisbehaviorUsage(prepared, completionReq, appliedReasoning !== undefined)\n : undefined;\n const response =\n prepared && usage\n ? {\n ...prepared.response,\n usage,\n ...(prepared.stop\n ? { finishReason: observedK5Stream ? \"tool_calls\" : prepared.stop }\n : {}),\n }\n : resolvedResponse;\n const summary = prepared?.summary ?? misbehavior.summary;\n const empty = prepared?.summary.fault === \"empty-response\";\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 const streamTiming = {\n latency,\n streamingProfile: fixture.streamingProfile,\n recordedTimings: fixture.recordedTimings,\n replaySpeed,\n };\n const codec = typedSseCodec<CohereSSEEvent>({ terminalSentinel: observedK5Stream });\n // Cohere has no separate misbehavior reply: an applied plan is merged into\n // `response` above and served by the branches below, so every non-streaming\n // site sizes its wait from the served payload and carries the K4 flag.\n const jsonOpts = (payloadLength: number) => ({\n surface: \"other\" as const,\n payloadLength,\n chunkSize,\n recordedTimings: fixture.recordedTimings,\n duplicateId: !!prepared?.duplicateId,\n replaySpeed,\n });\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Content + tool calls response (must be checked before text/tool-only branches)\n if (isCombinedFixtureResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n await deliverJson(\n res,\n journalEntry,\n fixture,\n () =>\n buildCohereContentWithToolCallsResponse(\n response.content ?? \"\",\n functionToolCalls,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n ),\n jsonOpts(servedPayloadLength(response, effReasoning)),\n );\n } else {\n const events = buildCohereContentWithToolCallsStreamEvents(\n response.content ?? \"\",\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n response.blocks,\n );\n await deliverStream(res, journalEntry, fixture, codec, events, streamTiming);\n }\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n if (cohereReq.stream !== true) {\n await deliverJson(\n res,\n journalEntry,\n fixture,\n () =>\n empty\n ? {\n ...buildCohereTextResponse(\"\", undefined, overrides),\n message: {\n role: \"assistant\",\n content: [],\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n }\n : buildCohereTextResponse(response.content, effReasoning, overrides),\n jsonOpts(servedPayloadLength(response, effReasoning)),\n );\n } else {\n const events = buildCohereTextStreamEvents(\n response.content,\n chunkSize,\n effReasoning,\n overrides,\n ).filter((event) => !empty || event.type === \"message-start\" || event.type === \"message-end\");\n await deliverStream(res, journalEntry, fixture, codec, events, streamTiming);\n }\n return;\n }\n\n // Tool call response\n if (isToolCallResponse(response)) {\n if (response.webSearches?.length) {\n logger.warn(\n \"webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring\",\n );\n }\n const overrides = extractOverrides(response);\n const effectiveStrict = resolveRequestDecisions(\n defaults.strict,\n req.headers,\n ).reasoningSuppression;\n const effReasoning = prepared\n ? appliedReasoning\n : resolveReasoningForModel(response.reasoning, cohereReq.model, effectiveStrict, logger);\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 200, fixture },\n });\n recordMisbehaviorOutcome({\n entry: journalEntry,\n summary,\n defaults,\n testId,\n });\n const functionToolCalls = requireEmittedFunctionToolCalls(response, \"Cohere\");\n if (cohereReq.stream !== true) {\n await deliverJson(\n res,\n journalEntry,\n fixture,\n () => buildCohereToolCallResponse(functionToolCalls, logger, effReasoning, overrides),\n jsonOpts(servedPayloadLength(response, effReasoning)),\n );\n } else {\n const events = buildCohereToolCallStreamEvents(\n functionToolCalls,\n chunkSize,\n logger,\n effReasoning,\n overrides,\n );\n await deliverStream(res, journalEntry, fixture, codec, events, streamTiming);\n }\n return;\n }\n\n // Unknown response type\n const journalEntry = journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n response: { status: 500, fixture },\n });\n recordMisbehaviorOutcome({ entry: journalEntry, summary, defaults, testId });\n writeErrorResponse(\n res,\n 500,\n renderError(\"cohere\", \"unknown-response\", {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n }).body,\n );\n}\n\n// ─── Cohere v2 Embed API types ────────────────────────────────────────────\n\ninterface CohereEmbedRequest {\n texts: string[];\n model: string;\n input_type?: string;\n embedding_types?: string[];\n truncate?: string;\n}\n\ninterface CohereEmbedResponse {\n id: string;\n texts: string[];\n embeddings: Record<string, number[][]>;\n meta: { api_version: { version: string } };\n}\n\n// ─── Cohere Embed handler ─────────────────────────────────────────────────\n\nexport async function handleCohereEmbed(\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): Promise<void> {\n const { logger } = defaults;\n setCorsHeaders(res);\n\n let embedReq: CohereEmbedRequest;\n try {\n embedReq = JSON.parse(raw) as CohereEmbedRequest;\n } catch (parseErr) {\n const detail = parseErr instanceof Error ? parseErr.message : \"unknown\";\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: `Malformed JSON body: ${detail}`,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Reject non-object bodies (e.g. `null`) before touching fields —\n // otherwise `embedReq.model` throws a TypeError that surfaces as a 500\n // instead of a 400.\n if (!isJsonObject(embedReq)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Request body must be a JSON object\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Validate required fields\n if (!embedReq.model) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"model is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n if (!embedReq.texts || !Array.isArray(embedReq.texts)) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Invalid request: texts array is required\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Every text must be a string — a number reaches createHash().update() in\n // the no-fixture fallback and throws a TypeError (500) instead of a 400.\n if (!embedReq.texts.every((text) => typeof text === \"string\")) {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: null,\n response: { status: 400, fixture: null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: \"Invalid request: texts must be an array of strings\",\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Concatenate all texts for fixture matching\n const combinedInput = embedReq.texts.join(\" \");\n\n // Build a synthetic ChatCompletionRequest for the fixture router\n const syntheticReq: ChatCompletionRequest = {\n model: embedReq.model,\n messages: [],\n embeddingInput: combinedInput,\n _endpointType: \"embedding\",\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 // Record mode proxies on a miss to capture a fresh turn (see record gate\n // below), so keep turnIndex strict to prevent an earlier-turn fixture from\n // shadowing a longer request and skipping the new turn's recording.\n recordMatchOptions(!!defaults.record, defaults.logger),\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n } else {\n logger.debug(`No fixture matched for request`);\n }\n\n if (\n await applyChaosAsync(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n req.url,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n },\n fixture ? \"fixture\" : \"proxy\",\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n // Determine requested embedding types (default to float)\n const embeddingTypes =\n embedReq.embedding_types && embedReq.embedding_types.length > 0\n ? embedReq.embedding_types\n : [\"float\"];\n\n function rejectInvalidEmbeddingTypes(): boolean {\n if (embedReq.embedding_types == null) return false;\n const isArray = Array.isArray(embedReq.embedding_types);\n if (isArray && embedReq.embedding_types.every((type) => typeof type === \"string\")) return false;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 400, fixture: fixture ?? null },\n });\n writeErrorResponse(\n res,\n 400,\n renderError(\"cohere\", \"validation\", {\n message: isArray\n ? \"Invalid request: embedding_types must be an array of strings\"\n : \"Invalid request: embedding_types must be an array\",\n type: \"invalid_request_error\",\n }).body,\n );\n return true;\n }\n\n if (fixture) {\n const response = await resolveResponse(fixture, syntheticReq);\n\n // Error response\n if (isErrorResponse(response)) {\n const status = response.status ?? 500;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status, fixture },\n });\n writeErrorResponse(res, status, renderError(\"openai\", \"fixture\", response.error).body, {\n retryAfter: response.retryAfter,\n });\n return;\n }\n\n // Embedding response — use the fixture's embedding for each input text\n if (isEmbeddingResponse(response)) {\n if (rejectInvalidEmbeddingTypes()) return;\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture },\n });\n const vectors = embedReq.texts.map(() => [...response.embedding]);\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n return;\n }\n\n // Fixture matched but response type is not compatible with embeddings\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 500, fixture },\n });\n writeErrorResponse(\n res,\n 500,\n renderError(\"cohere\", \"unknown-response\", {\n message:\n \"Fixture response did not match any known embedding type (must have embedding or error)\",\n type: \"server_error\",\n }).body,\n );\n return;\n }\n\n // No fixture match — check strict mode\n if (resolveRequestDecisions(defaults.strict, req.headers).fixtureMiss) {\n const strictMessage = strictNoMatchMessage(skippedBySequenceOrTurn);\n logger.error(\n strictNoMatchLogLine(req.method ?? \"POST\", req.url ?? \"/v2/embed\", skippedBySequenceOrTurn),\n );\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 renderError(\"cohere\", \"strict-miss\", {\n message: strictMessage,\n type: \"invalid_request_error\",\n }).body,\n );\n return;\n }\n\n // Try record-and-replay proxy\n if (defaults.record) {\n const outcome = await proxyAndRecord(\n req,\n res,\n syntheticReq,\n \"cohere\",\n req.url ?? \"/v2/embed\",\n fixtures,\n defaults,\n raw,\n );\n if (outcome === \"handled_by_hook\") return;\n if (outcome !== \"not_configured\") {\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\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 if (rejectInvalidEmbeddingTypes()) return;\n\n // No fixture match — generate deterministic embeddings from input texts\n logger.warn(\n `No embedding fixture matched for \"${combinedInput.slice(0, 80)}\" — returning deterministic fallback`,\n );\n const dimensions = 1024; // Cohere embed-v4.0 default\n const vectors = embedReq.texts.map((text) => generateDeterministicEmbedding(text, dimensions));\n const embeddings: Record<string, number[][]> = {};\n for (const t of embeddingTypes) {\n embeddings[t] = vectors;\n }\n\n journal.add({\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/embed\",\n headers: flattenHeaders(req.headers),\n body: syntheticReq,\n response: { status: 200, fixture: null },\n });\n\n const body: CohereEmbedResponse = {\n id: generateMessageId(),\n texts: embedReq.texts,\n embeddings,\n meta: { api_version: { version: \"2\" } },\n };\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkIA,SAAS,mBACP,sBACA,eACQ;AACR,KAAI,CAAC,qBAAsB,QAAO;AAClC,QAAO,gBAAgB,qBAAqB;;AAG9C,SAAS,YAAY,WAAqE;AACxF,QAAOA,OAAkB,UAAU;;;AAMrC,SAAS,mBAAmB,SAAkE;AAC5F,KAAI,YAAY,QAAQ,YAAY,OAAW,QAAO;AACtD,KAAI,OAAO,YAAY,SAAU,QAAO;AACxC,QAAO,QACJ,QACE,SACC,SAAS,QAAQ,SAAS,UAAa,KAAK,SAAS,UAAU,KAAK,SAAS,OAChF,CACA,KAAK,SAAS,KAAK,KAAM,CACzB,KAAK,GAAG;;;AAIb,SAAS,gBAAgB,GAA4C;AACnE,QAAO,cAAc,KAAK,OAAQ,EAA0B,aAAa;;AAG3E,SAAgB,0BAA0B,KAA2C;CACnF,MAAM,WAA0B,EAAE;AAElC,MAAK,MAAM,OAAO,IAAI,UAAU;EAC9B,MAAM,cAAc,mBAAmB,IAAI,QAAQ;AACnD,MAAI,IAAI,SAAS,SACf,UAAS,KAAK;GAAE,MAAM;GAAU,SAAS;GAAa,CAAC;WAC9C,IAAI,SAAS,OACtB,UAAS,KAAK;GAAE,MAAM;GAAQ,SAAS;GAAa,CAAC;WAC5C,IAAI,SAAS,YACtB,KAAI,IAAI,cAAc,IAAI,WAAW,SAAS,EAC5C,UAAS,KAAK;GACZ,MAAM;GACN,SAAS,eAAe;GACxB,YAAY,IAAI,WAAW,KAAK,QAAQ;IACtC,IAAI,GAA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