@copilotkit/aimock 1.15.0 → 1.15.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +26 -16
  2. package/dist/bedrock-converse.cjs +133 -25
  3. package/dist/bedrock-converse.cjs.map +1 -1
  4. package/dist/bedrock-converse.d.cts.map +1 -1
  5. package/dist/bedrock-converse.d.ts.map +1 -1
  6. package/dist/bedrock-converse.js +135 -27
  7. package/dist/bedrock-converse.js.map +1 -1
  8. package/dist/bedrock.cjs +262 -48
  9. package/dist/bedrock.cjs.map +1 -1
  10. package/dist/bedrock.d.cts.map +1 -1
  11. package/dist/bedrock.d.ts.map +1 -1
  12. package/dist/bedrock.js +263 -50
  13. package/dist/bedrock.js.map +1 -1
  14. package/dist/chaos.cjs +9 -35
  15. package/dist/chaos.cjs.map +1 -1
  16. package/dist/chaos.d.cts +2 -17
  17. package/dist/chaos.d.cts.map +1 -1
  18. package/dist/chaos.d.ts +2 -17
  19. package/dist/chaos.d.ts.map +1 -1
  20. package/dist/chaos.js +10 -35
  21. package/dist/chaos.js.map +1 -1
  22. package/dist/cohere.cjs +289 -33
  23. package/dist/cohere.cjs.map +1 -1
  24. package/dist/cohere.d.cts +9 -0
  25. package/dist/cohere.d.cts.map +1 -1
  26. package/dist/cohere.d.ts +9 -0
  27. package/dist/cohere.d.ts.map +1 -1
  28. package/dist/cohere.js +290 -34
  29. package/dist/cohere.js.map +1 -1
  30. package/dist/config-loader.d.ts.map +1 -1
  31. package/dist/embeddings.cjs +22 -4
  32. package/dist/embeddings.cjs.map +1 -1
  33. package/dist/embeddings.d.cts +2 -2
  34. package/dist/embeddings.d.cts.map +1 -1
  35. package/dist/embeddings.d.ts +2 -2
  36. package/dist/embeddings.d.ts.map +1 -1
  37. package/dist/embeddings.js +22 -4
  38. package/dist/embeddings.js.map +1 -1
  39. package/dist/gemini.cjs +48 -45
  40. package/dist/gemini.cjs.map +1 -1
  41. package/dist/gemini.d.cts.map +1 -1
  42. package/dist/gemini.d.ts.map +1 -1
  43. package/dist/gemini.js +48 -45
  44. package/dist/gemini.js.map +1 -1
  45. package/dist/helpers.cjs +9 -0
  46. package/dist/helpers.cjs.map +1 -1
  47. package/dist/helpers.d.cts.map +1 -1
  48. package/dist/helpers.d.ts.map +1 -1
  49. package/dist/helpers.js +9 -0
  50. package/dist/helpers.js.map +1 -1
  51. package/dist/images.cjs +21 -3
  52. package/dist/images.cjs.map +1 -1
  53. package/dist/images.js +21 -3
  54. package/dist/images.js.map +1 -1
  55. package/dist/index.cjs +2 -0
  56. package/dist/index.d.cts +2 -2
  57. package/dist/index.d.ts +2 -2
  58. package/dist/index.js +3 -3
  59. package/dist/jest.cjs +10 -3
  60. package/dist/jest.cjs.map +1 -1
  61. package/dist/jest.js +10 -3
  62. package/dist/jest.js.map +1 -1
  63. package/dist/journal.cjs +1 -1
  64. package/dist/journal.cjs.map +1 -1
  65. package/dist/journal.d.cts.map +1 -1
  66. package/dist/journal.d.ts.map +1 -1
  67. package/dist/journal.js +1 -1
  68. package/dist/journal.js.map +1 -1
  69. package/dist/messages.cjs +5 -4
  70. package/dist/messages.cjs.map +1 -1
  71. package/dist/messages.js +5 -4
  72. package/dist/messages.js.map +1 -1
  73. package/dist/ollama.cjs +129 -8
  74. package/dist/ollama.cjs.map +1 -1
  75. package/dist/ollama.d.cts.map +1 -1
  76. package/dist/ollama.d.ts.map +1 -1
  77. package/dist/ollama.js +130 -9
  78. package/dist/ollama.js.map +1 -1
  79. package/dist/recorder.cjs +234 -69
  80. package/dist/recorder.cjs.map +1 -1
  81. package/dist/recorder.d.cts +5 -50
  82. package/dist/recorder.d.cts.map +1 -1
  83. package/dist/recorder.d.ts +5 -50
  84. package/dist/recorder.d.ts.map +1 -1
  85. package/dist/recorder.js +234 -69
  86. package/dist/recorder.js.map +1 -1
  87. package/dist/responses.cjs +12 -3
  88. package/dist/responses.cjs.map +1 -1
  89. package/dist/responses.d.cts +2 -1
  90. package/dist/responses.d.cts.map +1 -1
  91. package/dist/responses.d.ts +2 -1
  92. package/dist/responses.d.ts.map +1 -1
  93. package/dist/responses.js +12 -4
  94. package/dist/responses.js.map +1 -1
  95. package/dist/router.cjs +13 -6
  96. package/dist/router.cjs.map +1 -1
  97. package/dist/router.js +13 -6
  98. package/dist/router.js.map +1 -1
  99. package/dist/server.cjs +150 -94
  100. package/dist/server.cjs.map +1 -1
  101. package/dist/server.d.cts.map +1 -1
  102. package/dist/server.d.ts.map +1 -1
  103. package/dist/server.js +152 -96
  104. package/dist/server.js.map +1 -1
  105. package/dist/speech.cjs +21 -3
  106. package/dist/speech.cjs.map +1 -1
  107. package/dist/speech.js +21 -3
  108. package/dist/speech.js.map +1 -1
  109. package/dist/transcription.cjs +10 -6
  110. package/dist/transcription.cjs.map +1 -1
  111. package/dist/transcription.d.cts.map +1 -1
  112. package/dist/transcription.d.ts.map +1 -1
  113. package/dist/transcription.js +10 -6
  114. package/dist/transcription.js.map +1 -1
  115. package/dist/types.d.cts +1 -16
  116. package/dist/types.d.cts.map +1 -1
  117. package/dist/types.d.ts +1 -16
  118. package/dist/types.d.ts.map +1 -1
  119. package/dist/video.cjs +66 -10
  120. package/dist/video.cjs.map +1 -1
  121. package/dist/video.d.cts +16 -3
  122. package/dist/video.d.cts.map +1 -1
  123. package/dist/video.d.ts +16 -3
  124. package/dist/video.d.ts.map +1 -1
  125. package/dist/video.js +66 -11
  126. package/dist/video.js.map +1 -1
  127. package/dist/vitest.cjs +10 -3
  128. package/dist/vitest.cjs.map +1 -1
  129. package/dist/vitest.js +10 -3
  130. package/dist/vitest.js.map +1 -1
  131. package/package.json +1 -1
package/dist/cohere.d.ts CHANGED
@@ -4,10 +4,19 @@ import * as http from "node:http";
4
4
 
5
5
  //#region src/cohere.d.ts
6
6
 
7
+ interface CohereToolCallDef {
8
+ id?: string;
9
+ type: string;
10
+ function: {
11
+ name: string;
12
+ arguments: string;
13
+ };
14
+ }
7
15
  interface CohereMessage {
8
16
  role: "user" | "assistant" | "system" | "tool";
9
17
  content: string;
10
18
  tool_call_id?: string;
19
+ tool_calls?: CohereToolCallDef[];
11
20
  }
12
21
  interface CohereToolDef {
13
22
  type: string;
@@ -1 +1 @@
1
- {"version":3,"file":"cohere.d.ts","names":[],"sources":["../src/cohere.ts"],"sourcesContent":[],"mappings":";;;;;;UAwCU,aAAA,CAuC+B;MAAM,EAAA,MAAA,GAAA,WAAA,GAAA,QAAA,GAAA,MAAA;SAAgB,EAAA,MAAA;EAAqB,YAAA,CAAA,EAAA,MAAA;AAmTpF;UApVU,aAAA,CAoVwB;MAC3B,EAAA,MAAK;UACA,EAAA;IAEA,IAAA,EAAA,MAAA;IACD,WAAA,CAAA,EAAA,MAAA;IACC,UAAA,CAAA,EAAA,MAAA;;;UAjVF,aAAA,CAmVA;;YAjVE;;UAEF;;;;;;iBAoBM,yBAAA,MAA+B,gBAAgB;iBAmTzC,YAAA,MACf,IAAA,CAAK,sBACL,IAAA,CAAK,uCAEA,oBACD,mBACC,uCACY,IAAA,CAAK,0BAC1B"}
1
+ {"version":3,"file":"cohere.d.ts","names":[],"sources":["../src/cohere.ts"],"sourcesContent":[],"mappings":";;;;;;AAwHA,UA7EU,iBAAA,CA6EM;EAAyB,EAAA,CAAA,EAAA,MAAA;MAAM,EAAA,MAAA;UAAgB,EAAA;IAAqB,IAAA,EAAA,MAAA;IA+jB9D,SAAA,EAAY,MAAA;EAAA,CAAA;;UAnoBxB,aAAA,CAqoBE;MAEA,EAAA,MAAA,GAAA,WAAA,GAAA,QAAA,GAAA,MAAA;SACD,EAAA,MAAA;cACC,CAAA,EAAA,MAAA;YACiB,CAAA,EAtoBd,iBAsoBc,EAAA;;UAnoBnB,aAAA,CAooBA;;;;;;;;UA3nBA,aAAA;;YAEE;;UAEF;;;;;;iBAgDM,yBAAA,MAA+B,gBAAgB;iBA+jBzC,YAAA,MACf,IAAA,CAAK,sBACL,IAAA,CAAK,uCAEA,oBACD,mBACC,uCACY,IAAA,CAAK,0BAC1B"}
package/dist/cohere.js CHANGED
@@ -1,4 +1,4 @@
1
- import { flattenHeaders, generateMessageId, generateToolCallId, getTestId, isErrorResponse, isTextResponse, isToolCallResponse } from "./helpers.js";
1
+ import { extractOverrides, flattenHeaders, generateMessageId, generateToolCallId, getTestId, isContentWithToolCallsResponse, isErrorResponse, isTextResponse, isToolCallResponse } from "./helpers.js";
2
2
  import { matchFixture } from "./router.js";
3
3
  import { calculateDelay, delay, writeErrorResponse } from "./sse-writer.js";
4
4
  import { createInterruptionSignal } from "./interruption.js";
@@ -18,6 +18,30 @@ const ZERO_USAGE = {
18
18
  output_tokens: 0
19
19
  }
20
20
  };
21
+ function cohereFinishReason(overrideFinishReason, defaultReason) {
22
+ if (!overrideFinishReason) return defaultReason;
23
+ if (overrideFinishReason === "stop") return "COMPLETE";
24
+ if (overrideFinishReason === "tool_calls") return "TOOL_CALL";
25
+ if (overrideFinishReason === "length") return "MAX_TOKENS";
26
+ return overrideFinishReason;
27
+ }
28
+ function cohereUsage(overrides) {
29
+ if (!overrides?.usage) return ZERO_USAGE;
30
+ const inputTokens = overrides.usage.input_tokens ?? overrides.usage.prompt_tokens ?? 0;
31
+ const outputTokens = overrides.usage.output_tokens ?? overrides.usage.completion_tokens ?? 0;
32
+ return {
33
+ billed_units: {
34
+ input_tokens: inputTokens,
35
+ output_tokens: outputTokens,
36
+ search_units: 0,
37
+ classifications: 0
38
+ },
39
+ tokens: {
40
+ input_tokens: inputTokens,
41
+ output_tokens: outputTokens
42
+ }
43
+ };
44
+ }
21
45
  function cohereToCompletionRequest(req) {
22
46
  const messages = [];
23
47
  for (const msg of req.messages) if (msg.role === "system") messages.push({
@@ -28,7 +52,19 @@ function cohereToCompletionRequest(req) {
28
52
  role: "user",
29
53
  content: msg.content
30
54
  });
31
- else if (msg.role === "assistant") messages.push({
55
+ else if (msg.role === "assistant") if (msg.tool_calls && msg.tool_calls.length > 0) messages.push({
56
+ role: "assistant",
57
+ content: msg.content || null,
58
+ tool_calls: msg.tool_calls.map((tc) => ({
59
+ id: tc.id ?? generateToolCallId(),
60
+ type: "function",
61
+ function: {
62
+ name: tc.function.name,
63
+ arguments: tc.function.arguments
64
+ }
65
+ }))
66
+ });
67
+ else messages.push({
32
68
  role: "assistant",
33
69
  content: msg.content
34
70
  });
@@ -50,45 +86,55 @@ function cohereToCompletionRequest(req) {
50
86
  model: req.model,
51
87
  messages,
52
88
  stream: req.stream,
53
- tools
89
+ tools,
90
+ ...req.response_format && { response_format: req.response_format }
54
91
  };
55
92
  }
56
- function buildCohereTextResponse(content) {
93
+ function buildCohereTextResponse(content, reasoning, overrides) {
94
+ const contentBlocks = [];
95
+ if (reasoning) contentBlocks.push({
96
+ type: "text",
97
+ text: reasoning
98
+ });
99
+ contentBlocks.push({
100
+ type: "text",
101
+ text: content
102
+ });
57
103
  return {
58
- id: generateMessageId(),
59
- finish_reason: "COMPLETE",
104
+ id: overrides?.id ?? generateMessageId(),
105
+ finish_reason: cohereFinishReason(overrides?.finishReason, "COMPLETE"),
60
106
  message: {
61
107
  role: "assistant",
62
- content: [{
63
- type: "text",
64
- text: content
65
- }],
108
+ content: contentBlocks,
66
109
  tool_calls: [],
67
110
  tool_plan: "",
68
111
  citations: []
69
112
  },
70
- usage: ZERO_USAGE
113
+ usage: cohereUsage(overrides)
71
114
  };
72
115
  }
73
- function buildCohereToolCallResponse(toolCalls, logger) {
116
+ function buildCohereToolCallResponse(toolCalls, logger, overrides) {
74
117
  const cohereCalls = toolCalls.map((tc) => {
118
+ let argsJson;
75
119
  try {
76
120
  JSON.parse(tc.arguments || "{}");
121
+ argsJson = tc.arguments || "{}";
77
122
  } catch {
78
123
  logger.warn(`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`);
124
+ argsJson = "{}";
79
125
  }
80
126
  return {
81
127
  id: tc.id || generateToolCallId(),
82
128
  type: "function",
83
129
  function: {
84
130
  name: tc.name,
85
- arguments: tc.arguments || "{}"
131
+ arguments: argsJson
86
132
  }
87
133
  };
88
134
  });
89
135
  return {
90
- id: generateMessageId(),
91
- finish_reason: "TOOL_CALL",
136
+ id: overrides?.id ?? generateMessageId(),
137
+ finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
92
138
  message: {
93
139
  role: "assistant",
94
140
  content: [],
@@ -96,11 +142,52 @@ function buildCohereToolCallResponse(toolCalls, logger) {
96
142
  tool_plan: "",
97
143
  citations: []
98
144
  },
99
- usage: ZERO_USAGE
145
+ usage: cohereUsage(overrides)
100
146
  };
101
147
  }
102
- function buildCohereTextStreamEvents(content, chunkSize) {
103
- const msgId = generateMessageId();
148
+ function buildCohereContentWithToolCallsResponse(content, toolCalls, logger, reasoning, overrides) {
149
+ const cohereCalls = toolCalls.map((tc) => {
150
+ let argsJson;
151
+ try {
152
+ JSON.parse(tc.arguments || "{}");
153
+ argsJson = tc.arguments || "{}";
154
+ } catch {
155
+ logger.warn(`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`);
156
+ argsJson = "{}";
157
+ }
158
+ return {
159
+ id: tc.id || generateToolCallId(),
160
+ type: "function",
161
+ function: {
162
+ name: tc.name,
163
+ arguments: argsJson
164
+ }
165
+ };
166
+ });
167
+ const contentBlocks = [];
168
+ if (reasoning) contentBlocks.push({
169
+ type: "text",
170
+ text: reasoning
171
+ });
172
+ contentBlocks.push({
173
+ type: "text",
174
+ text: content
175
+ });
176
+ return {
177
+ id: overrides?.id ?? generateMessageId(),
178
+ finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
179
+ message: {
180
+ role: "assistant",
181
+ content: contentBlocks,
182
+ tool_calls: cohereCalls,
183
+ tool_plan: "",
184
+ citations: []
185
+ },
186
+ usage: cohereUsage(overrides)
187
+ };
188
+ }
189
+ function buildCohereTextStreamEvents(content, chunkSize, reasoning, overrides) {
190
+ const msgId = overrides?.id ?? generateMessageId();
104
191
  const events = [];
105
192
  events.push({
106
193
  id: msgId,
@@ -113,16 +200,40 @@ function buildCohereTextStreamEvents(content, chunkSize) {
113
200
  citations: []
114
201
  } }
115
202
  });
203
+ let contentIndex = 0;
204
+ if (reasoning) {
205
+ events.push({
206
+ type: "content-start",
207
+ index: contentIndex,
208
+ delta: { message: { content: { type: "text" } } }
209
+ });
210
+ for (let i = 0; i < reasoning.length; i += chunkSize) {
211
+ const slice = reasoning.slice(i, i + chunkSize);
212
+ events.push({
213
+ type: "content-delta",
214
+ index: contentIndex,
215
+ delta: { message: { content: {
216
+ type: "text",
217
+ text: slice
218
+ } } }
219
+ });
220
+ }
221
+ events.push({
222
+ type: "content-end",
223
+ index: contentIndex
224
+ });
225
+ contentIndex++;
226
+ }
116
227
  events.push({
117
228
  type: "content-start",
118
- index: 0,
229
+ index: contentIndex,
119
230
  delta: { message: { content: { type: "text" } } }
120
231
  });
121
232
  for (let i = 0; i < content.length; i += chunkSize) {
122
233
  const slice = content.slice(i, i + chunkSize);
123
234
  events.push({
124
235
  type: "content-delta",
125
- index: 0,
236
+ index: contentIndex,
126
237
  delta: { message: { content: {
127
238
  type: "text",
128
239
  text: slice
@@ -131,19 +242,82 @@ function buildCohereTextStreamEvents(content, chunkSize) {
131
242
  }
132
243
  events.push({
133
244
  type: "content-end",
134
- index: 0
245
+ index: contentIndex
135
246
  });
136
247
  events.push({
137
248
  type: "message-end",
138
249
  delta: {
139
- finish_reason: "COMPLETE",
140
- usage: ZERO_USAGE
250
+ finish_reason: cohereFinishReason(overrides?.finishReason, "COMPLETE"),
251
+ usage: cohereUsage(overrides)
252
+ }
253
+ });
254
+ return events;
255
+ }
256
+ function buildCohereToolCallStreamEvents(toolCalls, chunkSize, logger, overrides) {
257
+ const msgId = overrides?.id ?? generateMessageId();
258
+ const events = [];
259
+ events.push({
260
+ id: msgId,
261
+ type: "message-start",
262
+ delta: { message: {
263
+ role: "assistant",
264
+ content: [],
265
+ tool_plan: "",
266
+ tool_calls: [],
267
+ citations: []
268
+ } }
269
+ });
270
+ events.push({
271
+ type: "tool-plan-delta",
272
+ delta: { message: { tool_plan: "I will use the requested tool." } }
273
+ });
274
+ for (let idx = 0; idx < toolCalls.length; idx++) {
275
+ const tc = toolCalls[idx];
276
+ const callId = tc.id || generateToolCallId();
277
+ let argsJson;
278
+ try {
279
+ JSON.parse(tc.arguments || "{}");
280
+ argsJson = tc.arguments || "{}";
281
+ } catch {
282
+ logger.warn(`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`);
283
+ argsJson = "{}";
284
+ }
285
+ events.push({
286
+ type: "tool-call-start",
287
+ index: idx,
288
+ delta: { message: { tool_calls: {
289
+ id: callId,
290
+ type: "function",
291
+ function: {
292
+ name: tc.name,
293
+ arguments: ""
294
+ }
295
+ } } }
296
+ });
297
+ for (let i = 0; i < argsJson.length; i += chunkSize) {
298
+ const slice = argsJson.slice(i, i + chunkSize);
299
+ events.push({
300
+ type: "tool-call-delta",
301
+ index: idx,
302
+ delta: { message: { tool_calls: { function: { arguments: slice } } } }
303
+ });
304
+ }
305
+ events.push({
306
+ type: "tool-call-end",
307
+ index: idx
308
+ });
309
+ }
310
+ events.push({
311
+ type: "message-end",
312
+ delta: {
313
+ finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
314
+ usage: cohereUsage(overrides)
141
315
  }
142
316
  });
143
317
  return events;
144
318
  }
145
- function buildCohereToolCallStreamEvents(toolCalls, chunkSize, logger) {
146
- const msgId = generateMessageId();
319
+ function buildCohereContentWithToolCallsStreamEvents(content, toolCalls, chunkSize, logger, reasoning, overrides) {
320
+ const msgId = overrides?.id ?? generateMessageId();
147
321
  const events = [];
148
322
  events.push({
149
323
  id: msgId,
@@ -156,6 +330,50 @@ function buildCohereToolCallStreamEvents(toolCalls, chunkSize, logger) {
156
330
  citations: []
157
331
  } }
158
332
  });
333
+ let contentIndex = 0;
334
+ if (reasoning) {
335
+ events.push({
336
+ type: "content-start",
337
+ index: contentIndex,
338
+ delta: { message: { content: { type: "text" } } }
339
+ });
340
+ for (let i = 0; i < reasoning.length; i += chunkSize) {
341
+ const slice = reasoning.slice(i, i + chunkSize);
342
+ events.push({
343
+ type: "content-delta",
344
+ index: contentIndex,
345
+ delta: { message: { content: {
346
+ type: "text",
347
+ text: slice
348
+ } } }
349
+ });
350
+ }
351
+ events.push({
352
+ type: "content-end",
353
+ index: contentIndex
354
+ });
355
+ contentIndex++;
356
+ }
357
+ events.push({
358
+ type: "content-start",
359
+ index: contentIndex,
360
+ delta: { message: { content: { type: "text" } } }
361
+ });
362
+ for (let i = 0; i < content.length; i += chunkSize) {
363
+ const slice = content.slice(i, i + chunkSize);
364
+ events.push({
365
+ type: "content-delta",
366
+ index: contentIndex,
367
+ delta: { message: { content: {
368
+ type: "text",
369
+ text: slice
370
+ } } }
371
+ });
372
+ }
373
+ events.push({
374
+ type: "content-end",
375
+ index: contentIndex
376
+ });
159
377
  events.push({
160
378
  type: "tool-plan-delta",
161
379
  delta: { message: { tool_plan: "I will use the requested tool." } }
@@ -199,8 +417,8 @@ function buildCohereToolCallStreamEvents(toolCalls, chunkSize, logger) {
199
417
  events.push({
200
418
  type: "message-end",
201
419
  delta: {
202
- finish_reason: "TOOL_CALL",
203
- usage: ZERO_USAGE
420
+ finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
421
+ usage: cohereUsage(overrides)
204
422
  }
205
423
  });
206
424
  return events;
@@ -296,10 +514,10 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
296
514
  path: req.url ?? "/v2/chat",
297
515
  headers: flattenHeaders(req.headers),
298
516
  body: completionReq
299
- }, fixture ? "fixture" : "proxy", defaults.registry, defaults.logger)) return;
517
+ }, defaults.registry, defaults.logger)) return;
300
518
  if (!fixture) {
301
519
  if (defaults.record) {
302
- if (await proxyAndRecord(req, res, completionReq, "cohere", req.url ?? "/v2/chat", fixtures, defaults, raw) !== "not_configured") {
520
+ if (await proxyAndRecord(req, res, completionReq, "cohere", req.url ?? "/v2/chat", fixtures, defaults, raw)) {
303
521
  journal.add({
304
522
  method: req.method ?? "POST",
305
523
  path: req.url ?? "/v2/chat",
@@ -307,7 +525,8 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
307
525
  body: completionReq,
308
526
  response: {
309
527
  status: res.statusCode ?? 200,
310
- fixture: null
528
+ fixture: null,
529
+ source: "proxy"
311
530
  }
312
531
  });
313
532
  return;
@@ -350,7 +569,43 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
350
569
  writeErrorResponse(res, status, JSON.stringify(response));
351
570
  return;
352
571
  }
572
+ if (isContentWithToolCallsResponse(response)) {
573
+ if (response.webSearches?.length) logger.warn("webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring");
574
+ const overrides = extractOverrides(response);
575
+ const journalEntry = journal.add({
576
+ method: req.method ?? "POST",
577
+ path: req.url ?? "/v2/chat",
578
+ headers: flattenHeaders(req.headers),
579
+ body: completionReq,
580
+ response: {
581
+ status: 200,
582
+ fixture
583
+ }
584
+ });
585
+ if (cohereReq.stream !== true) {
586
+ const body = buildCohereContentWithToolCallsResponse(response.content, response.toolCalls, logger, response.reasoning, overrides);
587
+ res.writeHead(200, { "Content-Type": "application/json" });
588
+ res.end(JSON.stringify(body));
589
+ } else {
590
+ const events = buildCohereContentWithToolCallsStreamEvents(response.content, response.toolCalls, chunkSize, logger, response.reasoning, overrides);
591
+ const interruption = createInterruptionSignal(fixture);
592
+ if (!await writeCohereSSEStream(res, events, {
593
+ latency,
594
+ streamingProfile: fixture.streamingProfile,
595
+ signal: interruption?.signal,
596
+ onChunkSent: interruption?.tick
597
+ })) {
598
+ if (!res.writableEnded) res.destroy();
599
+ journalEntry.response.interrupted = true;
600
+ journalEntry.response.interruptReason = interruption?.reason();
601
+ }
602
+ interruption?.cleanup();
603
+ }
604
+ return;
605
+ }
353
606
  if (isTextResponse(response)) {
607
+ if (response.webSearches?.length) logger.warn("webSearches in fixture response are not supported for Cohere v2 Chat API — ignoring");
608
+ const overrides = extractOverrides(response);
354
609
  const journalEntry = journal.add({
355
610
  method: req.method ?? "POST",
356
611
  path: req.url ?? "/v2/chat",
@@ -362,11 +617,11 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
362
617
  }
363
618
  });
364
619
  if (cohereReq.stream !== true) {
365
- const body = buildCohereTextResponse(response.content);
620
+ const body = buildCohereTextResponse(response.content, response.reasoning, overrides);
366
621
  res.writeHead(200, { "Content-Type": "application/json" });
367
622
  res.end(JSON.stringify(body));
368
623
  } else {
369
- const events = buildCohereTextStreamEvents(response.content, chunkSize);
624
+ const events = buildCohereTextStreamEvents(response.content, chunkSize, response.reasoning, overrides);
370
625
  const interruption = createInterruptionSignal(fixture);
371
626
  if (!await writeCohereSSEStream(res, events, {
372
627
  latency,
@@ -383,6 +638,7 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
383
638
  return;
384
639
  }
385
640
  if (isToolCallResponse(response)) {
641
+ const overrides = extractOverrides(response);
386
642
  const journalEntry = journal.add({
387
643
  method: req.method ?? "POST",
388
644
  path: req.url ?? "/v2/chat",
@@ -394,11 +650,11 @@ async function handleCohere(req, res, raw, fixtures, journal, defaults, setCorsH
394
650
  }
395
651
  });
396
652
  if (cohereReq.stream !== true) {
397
- const body = buildCohereToolCallResponse(response.toolCalls, logger);
653
+ const body = buildCohereToolCallResponse(response.toolCalls, logger, overrides);
398
654
  res.writeHead(200, { "Content-Type": "application/json" });
399
655
  res.end(JSON.stringify(body));
400
656
  } else {
401
- const events = buildCohereToolCallStreamEvents(response.toolCalls, chunkSize, logger);
657
+ const events = buildCohereToolCallStreamEvents(response.toolCalls, chunkSize, logger, overrides);
402
658
  const interruption = createInterruptionSignal(fixture);
403
659
  if (!await writeCohereSSEStream(res, events, {
404
660
  latency,
@@ -1 +1 @@
1
- {"version":3,"file":"cohere.js","names":[],"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 HandlerDefaults,\n StreamingProfile,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n generateMessageId,\n generateToolCallId,\n isTextResponse,\n isToolCallResponse,\n isErrorResponse,\n flattenHeaders,\n getTestId,\n} from \"./helpers.js\";\nimport { matchFixture } 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 { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n// ─── Cohere v2 Chat request types ───────────────────────────────────────────\n\ninterface CohereMessage {\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\ninterface CohereToolDef {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\ninterface CohereRequest {\n model: string;\n messages: CohereMessage[];\n stream?: boolean;\n tools?: CohereToolDef[];\n response_format?: { type: string; json_schema?: object };\n}\n\n// ─── Cohere SSE event types ─────────────────────────────────────────────────\n\ninterface CohereSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\n// ─── Zero-value usage block ─────────────────────────────────────────────────\n\nconst ZERO_USAGE = {\n billed_units: { input_tokens: 0, output_tokens: 0, search_units: 0, classifications: 0 },\n tokens: { input_tokens: 0, output_tokens: 0 },\n};\n\n// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────\n\nexport function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n if (msg.role === \"system\") {\n messages.push({ role: \"system\", content: msg.content });\n } else if (msg.role === \"user\") {\n messages.push({ role: \"user\", content: msg.content });\n } else if (msg.role === \"assistant\") {\n messages.push({ role: \"assistant\", content: msg.content });\n } else if (msg.role === \"tool\") {\n messages.push({\n role: \"tool\",\n content: msg.content,\n tool_call_id: msg.tool_call_id,\n });\n }\n }\n\n // Convert tools\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => ({\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\n return {\n model: req.model,\n messages,\n stream: req.stream,\n tools,\n };\n}\n\n// ─── Response building: fixture → Cohere v2 Chat format ─────────────────────\n\n// Non-streaming text response\nfunction buildCohereTextResponse(content: string): object {\n return {\n id: generateMessageId(),\n finish_reason: \"COMPLETE\",\n message: {\n role: \"assistant\",\n content: [{ type: \"text\", text: content }],\n tool_calls: [],\n tool_plan: \"\",\n citations: [],\n },\n usage: ZERO_USAGE,\n };\n}\n\n// Non-streaming tool call response\nfunction buildCohereToolCallResponse(toolCalls: ToolCall[], logger: Logger): object {\n const cohereCalls = toolCalls.map((tc) => {\n // Validate arguments JSON\n try {\n JSON.parse(tc.arguments || \"{}\");\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n }\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: tc.arguments || \"{}\",\n },\n };\n });\n\n return {\n id: generateMessageId(),\n finish_reason: \"TOOL_CALL\",\n message: {\n role: \"assistant\",\n content: [],\n tool_calls: cohereCalls,\n tool_plan: \"\",\n citations: [],\n },\n usage: ZERO_USAGE,\n };\n}\n\n// ─── Streaming event builders ───────────────────────────────────────────────\n\nfunction buildCohereTextStreamEvents(content: string, chunkSize: number): CohereSSEEvent[] {\n const msgId = 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 // content-start (type: \"text\" only, no text field)\n events.push({\n type: \"content-start\",\n index: 0,\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: 0,\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: 0,\n });\n\n // message-end\n events.push({\n type: \"message-end\",\n delta: {\n finish_reason: \"COMPLETE\",\n usage: ZERO_USAGE,\n },\n });\n\n return events;\n}\n\nfunction buildCohereToolCallStreamEvents(\n toolCalls: ToolCall[],\n chunkSize: number,\n logger: Logger,\n): CohereSSEEvent[] {\n const msgId = 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 // 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 let argsJson: string;\n try {\n JSON.parse(tc.arguments || \"{}\");\n argsJson = tc.arguments || \"{}\";\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsJson = \"{}\";\n }\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: \"TOOL_CALL\",\n usage: ZERO_USAGE,\n },\n });\n\n return events;\n}\n\n// ─── SSE writer for Cohere typed events ─────────────────────────────────────\n\ninterface CohereStreamOptions {\n latency?: number;\n streamingProfile?: StreamingProfile;\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 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);\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 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 {\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 JSON.stringify({\n error: {\n message: \"Malformed JSON\",\n type: \"invalid_request_error\",\n },\n }),\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 JSON.stringify({\n error: {\n message: \"model is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!cohereReq.messages || !Array.isArray(cohereReq.messages)) {\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 JSON.stringify({\n error: {\n message: \"Invalid request: messages array is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = cohereToCompletionRequest(cohereReq);\n completionReq._endpointType = \"chat\";\n\n const testId = getTestId(req);\n const fixture = matchFixture(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\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 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 !== \"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 },\n });\n return;\n }\n }\n const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n if (defaults.strict) {\n logger.error(\n `STRICT: No fixture matched for ${req.method ?? \"POST\"} ${req.url ?? \"/v2/chat\"}`,\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: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const response = fixture.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 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 writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n // Text response\n if (isTextResponse(response)) {\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 if (cohereReq.stream !== true) {\n const body = buildCohereTextResponse(response.content);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereTextStreamEvents(response.content, chunkSize);\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\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 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 if (cohereReq.stream !== true) {\n const body = buildCohereToolCallResponse(response.toolCalls, logger);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereToolCallStreamEvents(response.toolCalls, chunkSize, logger);\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\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 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 writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n"],"mappings":";;;;;;;;AAwEA,MAAM,aAAa;CACjB,cAAc;EAAE,cAAc;EAAG,eAAe;EAAG,cAAc;EAAG,iBAAiB;EAAG;CACxF,QAAQ;EAAE,cAAc;EAAG,eAAe;EAAG;CAC9C;AAID,SAAgB,0BAA0B,KAA2C;CACnF,MAAM,WAA0B,EAAE;AAElC,MAAK,MAAM,OAAO,IAAI,SACpB,KAAI,IAAI,SAAS,SACf,UAAS,KAAK;EAAE,MAAM;EAAU,SAAS,IAAI;EA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pE,OAAI,UAAU,KAAK,EAAE,gBAAgB,oBAAoB,CAAC;AAC1D,OAAI,IAAI,KAAK,UAAU,KAAK,CAAC;SACxB;GACL,MAAM,SAAS,gCAAgC,SAAS,WAAW,WAAW,OAAO;GACrF,MAAM,eAAe,yBAAyB,QAAQ;AAOtD,OAAI,CANc,MAAM,qBAAqB,KAAK,QAAQ;IACxD;IACA,kBAAkB,QAAQ;IAC1B,QAAQ,cAAc;IACtB,aAAa,cAAc;IAC5B,CAAC,EACc;AACd,QAAI,CAAC,IAAI,cAAe,KAAI,SAAS;AACrC,iBAAa,SAAS,cAAc;AACpC,iBAAa,SAAS,kBAAkB,cAAc,QAAQ;;AAEhE,iBAAc,SAAS;;AAEzB;;AAIF,SAAQ,IAAI;EACV,QAAQ,IAAI,UAAU;EACtB,MAAM,IAAI,OAAO;EACjB,SAAS,eAAe,IAAI,QAAQ;EACpC,MAAM;EACN,UAAU;GAAE,QAAQ;GAAK;GAAS;EACnC,CAAC;AACF,oBACE,KACA,KACA,KAAK,UAAU,EACb,OAAO;EACL,SAAS;EACT,MAAM;EACP,EACF,CAAC,CACH"}
1
+ {"version":3,"file":"cohere.js","names":[],"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 HandlerDefaults,\n ResponseOverrides,\n StreamingProfile,\n ToolCall,\n ToolDefinition,\n} from \"./types.js\";\nimport {\n generateMessageId,\n generateToolCallId,\n extractOverrides,\n isTextResponse,\n isToolCallResponse,\n isContentWithToolCallsResponse,\n isErrorResponse,\n flattenHeaders,\n getTestId,\n} from \"./helpers.js\";\nimport { matchFixture } 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 { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.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 CohereMessage {\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n content: string;\n tool_call_id?: string;\n tool_calls?: CohereToolCallDef[];\n}\n\ninterface CohereToolDef {\n type: string;\n function: {\n name: string;\n description?: string;\n parameters?: object;\n };\n}\n\ninterface CohereRequest {\n model: string;\n messages: CohereMessage[];\n stream?: boolean;\n tools?: CohereToolDef[];\n response_format?: { type: string; json_schema?: object };\n}\n\n// ─── Cohere SSE event types ─────────────────────────────────────────────────\n\ninterface CohereSSEEvent {\n type: string;\n [key: string]: unknown;\n}\n\n// ─── Zero-value usage block ─────────────────────────────────────────────────\n\nconst ZERO_USAGE = {\n billed_units: { input_tokens: 0, output_tokens: 0, search_units: 0, classifications: 0 },\n tokens: { input_tokens: 0, output_tokens: 0 },\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 if (overrideFinishReason === \"stop\") return \"COMPLETE\";\n if (overrideFinishReason === \"tool_calls\") return \"TOOL_CALL\";\n if (overrideFinishReason === \"length\") return \"MAX_TOKENS\";\n return overrideFinishReason;\n}\n\nfunction cohereUsage(overrides?: ResponseOverrides): typeof ZERO_USAGE {\n if (!overrides?.usage) return ZERO_USAGE;\n const inputTokens = overrides.usage.input_tokens ?? overrides.usage.prompt_tokens ?? 0;\n const outputTokens = overrides.usage.output_tokens ?? overrides.usage.completion_tokens ?? 0;\n return {\n billed_units: {\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n search_units: 0,\n classifications: 0,\n },\n tokens: { input_tokens: inputTokens, output_tokens: outputTokens },\n };\n}\n\n// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────\n\nexport function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {\n const messages: ChatMessage[] = [];\n\n for (const msg of req.messages) {\n if (msg.role === \"system\") {\n messages.push({ role: \"system\", content: msg.content });\n } else if (msg.role === \"user\") {\n messages.push({ role: \"user\", content: msg.content });\n } else if (msg.role === \"assistant\") {\n if (msg.tool_calls && msg.tool_calls.length > 0) {\n messages.push({\n role: \"assistant\",\n content: msg.content || 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: msg.content });\n }\n } else if (msg.role === \"tool\") {\n messages.push({\n role: \"tool\",\n content: msg.content,\n tool_call_id: msg.tool_call_id,\n });\n }\n }\n\n // Convert tools\n let tools: ToolDefinition[] | undefined;\n if (req.tools && req.tools.length > 0) {\n tools = req.tools.map((t) => ({\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\n return {\n model: req.model,\n messages,\n stream: req.stream,\n tools,\n ...(req.response_format && { response_format: req.response_format }),\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 overrides?: ResponseOverrides,\n): object {\n const cohereCalls = toolCalls.map((tc) => {\n // Validate arguments JSON\n let argsJson: string;\n try {\n JSON.parse(tc.arguments || \"{}\");\n argsJson = tc.arguments || \"{}\";\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsJson = \"{}\";\n }\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\n return {\n id: overrides?.id ?? generateMessageId(),\n finish_reason: cohereFinishReason(overrides?.finishReason, \"TOOL_CALL\"),\n message: {\n role: \"assistant\",\n content: [],\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): object {\n const cohereCalls = toolCalls.map((tc) => {\n let argsJson: string;\n try {\n JSON.parse(tc.arguments || \"{}\");\n argsJson = tc.arguments || \"{}\";\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsJson = \"{}\";\n }\n return {\n id: tc.id || generateToolCallId(),\n type: \"function\",\n function: {\n name: tc.name,\n arguments: argsJson,\n },\n };\n });\n\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, \"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// ─── 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 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 // 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 let argsJson: string;\n try {\n JSON.parse(tc.arguments || \"{}\");\n argsJson = tc.arguments || \"{}\";\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsJson = \"{}\";\n }\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): 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 // 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 let argsJson: string;\n try {\n JSON.parse(tc.arguments || \"{}\");\n argsJson = tc.arguments || \"{}\";\n } catch {\n logger.warn(\n `Malformed JSON in fixture tool call arguments for \"${tc.name}\": ${tc.arguments}`,\n );\n argsJson = \"{}\";\n }\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 latency?: number;\n streamingProfile?: StreamingProfile;\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 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);\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 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 {\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 JSON.stringify({\n error: {\n message: \"Malformed JSON\",\n type: \"invalid_request_error\",\n },\n }),\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 JSON.stringify({\n error: {\n message: \"model is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n if (!cohereReq.messages || !Array.isArray(cohereReq.messages)) {\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 JSON.stringify({\n error: {\n message: \"Invalid request: messages array is required\",\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n // Convert to ChatCompletionRequest for fixture matching\n const completionReq = cohereToCompletionRequest(cohereReq);\n completionReq._endpointType = \"chat\";\n\n const testId = getTestId(req);\n const fixture = matchFixture(\n fixtures,\n completionReq,\n journal.getFixtureMatchCountsForTest(testId),\n defaults.requestTransform,\n );\n\n if (fixture) {\n journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n }\n\n if (\n applyChaos(\n res,\n fixture,\n defaults.chaos,\n req.headers,\n journal,\n {\n method: req.method ?? \"POST\",\n path: req.url ?? \"/v2/chat\",\n headers: flattenHeaders(req.headers),\n body: completionReq,\n },\n defaults.registry,\n defaults.logger,\n )\n )\n return;\n\n if (!fixture) {\n if (defaults.record) {\n const proxied = await proxyAndRecord(\n req,\n res,\n completionReq,\n \"cohere\",\n req.url ?? \"/v2/chat\",\n fixtures,\n defaults,\n raw,\n );\n if (proxied) {\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 const strictStatus = defaults.strict ? 503 : 404;\n const strictMessage = defaults.strict\n ? \"Strict mode: no fixture matched\"\n : \"No fixture matched\";\n if (defaults.strict) {\n logger.error(\n `STRICT: No fixture matched for ${req.method ?? \"POST\"} ${req.url ?? \"/v2/chat\"}`,\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: { status: strictStatus, fixture: null },\n });\n writeErrorResponse(\n res,\n strictStatus,\n JSON.stringify({\n error: {\n message: strictMessage,\n type: \"invalid_request_error\",\n },\n }),\n );\n return;\n }\n\n const response = fixture.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 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 writeErrorResponse(res, status, JSON.stringify(response));\n return;\n }\n\n // Content + tool calls response (must be checked before text/tool-only branches)\n if (isContentWithToolCallsResponse(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 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 if (cohereReq.stream !== true) {\n const body = buildCohereContentWithToolCallsResponse(\n response.content,\n response.toolCalls,\n logger,\n response.reasoning,\n overrides,\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 response.toolCalls,\n chunkSize,\n logger,\n response.reasoning,\n overrides,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\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 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 if (cohereReq.stream !== true) {\n const body = buildCohereTextResponse(response.content, response.reasoning, 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 response.reasoning,\n overrides,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\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 const overrides = extractOverrides(response);\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 if (cohereReq.stream !== true) {\n const body = buildCohereToolCallResponse(response.toolCalls, logger, overrides);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify(body));\n } else {\n const events = buildCohereToolCallStreamEvents(\n response.toolCalls,\n chunkSize,\n logger,\n overrides,\n );\n const interruption = createInterruptionSignal(fixture);\n const completed = await writeCohereSSEStream(res, events, {\n latency,\n streamingProfile: fixture.streamingProfile,\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 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 writeErrorResponse(\n res,\n 500,\n JSON.stringify({\n error: {\n message: \"Fixture response did not match any known type\",\n type: \"server_error\",\n },\n }),\n );\n}\n"],"mappings":";;;;;;;;AAqFA,MAAM,aAAa;CACjB,cAAc;EAAE,cAAc;EAAG,eAAe;EAAG,cAAc;EAAG,iBAAiB;EAAG;CACxF,QAAQ;EAAE,cAAc;EAAG,eAAe;EAAG;CAC9C;AAID,SAAS,mBACP,sBACA,eACQ;AACR,KAAI,CAAC,qBAAsB,QAAO;AAClC,KAAI,yBAAyB,OAAQ,QAAO;AAC5C,KAAI,yBAAyB,aAAc,QAAO;AAClD,KAAI,yBAAyB,SAAU,QAAO;AAC9C,QAAO;;AAGT,SAAS,YAAY,WAAkD;AACrE,KAAI,CAAC,WAAW,MAAO,QAAO;CAC9B,MAAM,cAAc,UAAU,MAAM,gBAAgB,UAAU,MAAM,iBAAiB;CACrF,MAAM,eAAe,UAAU,MAAM,iBAAiB,UAAU,MAAM,qBAAqB;AAC3F,QAAO;EACL,cAAc;GACZ,cAAc;GACd,eAAe;GACf,cAAc;GACd,iBAAiB;GAClB;EACD,QAAQ;GAAE,cAAc;GAAa,eAAe;GAAc;EACnE;;AAKH,SAAgB,0BAA0B,KAA2C;CACnF,MAAM,WAA0B,E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