-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathcohere.ts
More file actions
1616 lines (1499 loc) · 45.2 KB
/
Copy pathcohere.ts
File metadata and controls
1616 lines (1499 loc) · 45.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Cohere v2 Chat API endpoint support.
*
* Translates incoming /v2/chat requests into the ChatCompletionRequest
* format used by the fixture router, and converts fixture responses back into
* Cohere's typed SSE streaming (or non-streaming) format.
*
* Cohere uses typed SSE events (event: + data: lines), similar to the
* Claude Messages handler in messages.ts.
*/
import type * as http from "node:http";
import type {
ChatCompletionRequest,
ChatMessage,
Fixture,
FixtureBlock,
HandlerDefaults,
RecordedTimings,
ResponseOverrides,
StreamingProfile,
ToolCall,
ToolDefinition,
} from "./types.js";
import {
generateMessageId,
generateToolCallId,
generateDeterministicEmbedding,
extractOverrides,
isTextResponse,
isToolCallResponse,
isContentWithToolCallsResponse,
isEmbeddingResponse,
isErrorResponse,
serializeErrorResponse,
flattenHeaders,
getTestId,
resolveFixtureBlocks,
resolveResponse,
resolveStrictMode,
resolveReasoningForModel,
strictOverrideField,
getContext,
strictNoMatchMessage,
strictNoMatchLogLine,
} from "./helpers.js";
import { matchFixtureDiagnostic, recordMatchOptions } from "./router.js";
import { writeErrorResponse, delay, calculateDelay } from "./sse-writer.js";
import { createInterruptionSignal } from "./interruption.js";
import type { Journal } from "./journal.js";
import type { Logger } from "./logger.js";
import { applyChaos } from "./chaos.js";
import { proxyAndRecord } from "./recorder.js";
// ─── Cohere v2 Chat request types ───────────────────────────────────────────
interface CohereToolCallDef {
id?: string;
type: string;
function: {
name: string;
arguments: string;
};
}
interface CohereContentPart {
type: string;
text?: string;
}
interface CohereMessage {
role: "user" | "assistant" | "system" | "tool";
content: string | CohereContentPart[];
tool_call_id?: string;
tool_calls?: CohereToolCallDef[];
}
// OpenAI-style tool definition (wrapped in { type: "function", function: { ... } })
interface CohereToolDefOpenAI {
type: string;
function: {
name: string;
description?: string;
parameters?: object;
};
}
// Cohere v2 native tool definition (flat: { name, description, parameter_definitions })
interface CohereToolDefNative {
name: string;
description?: string;
parameter_definitions?: object;
}
type CohereToolDef = CohereToolDefOpenAI | CohereToolDefNative;
interface CohereRequest {
model: string;
messages: CohereMessage[];
stream?: boolean;
tools?: CohereToolDef[];
response_format?: { type: string; json_schema?: object };
temperature?: number;
max_tokens?: number;
}
// ─── Cohere SSE event types ─────────────────────────────────────────────────
interface CohereSSEEvent {
type: string;
[key: string]: unknown;
}
// ─── Zero-value usage block ─────────────────────────────────────────────────
const ZERO_USAGE = {
billed_units: { input_tokens: 0, output_tokens: 0, search_units: 0, classifications: 0 },
tokens: { input_tokens: 0, output_tokens: 0 },
};
// ─── Cohere finish reason / usage mapping ──────────────────────────────────
function cohereFinishReason(
overrideFinishReason: string | undefined,
defaultReason: string,
): string {
if (!overrideFinishReason) return defaultReason;
if (overrideFinishReason === "stop") return "COMPLETE";
if (overrideFinishReason === "tool_calls") return "TOOL_CALL";
if (overrideFinishReason === "length") return "MAX_TOKENS";
return overrideFinishReason;
}
function cohereUsage(overrides?: ResponseOverrides): typeof ZERO_USAGE {
if (!overrides?.usage) return ZERO_USAGE;
const inputTokens = overrides.usage.input_tokens ?? overrides.usage.prompt_tokens ?? 0;
const outputTokens = overrides.usage.output_tokens ?? overrides.usage.completion_tokens ?? 0;
return {
billed_units: {
input_tokens: inputTokens,
output_tokens: outputTokens,
search_units: 0,
classifications: 0,
},
tokens: { input_tokens: inputTokens, output_tokens: outputTokens },
};
}
// ─── Input conversion: Cohere → ChatCompletionRequest ───────────────────────
/** Extract plain text from structured content (array of { type, text } parts) or passthrough string. */
function extractTextContent(content: string | CohereContentPart[]): string {
if (typeof content === "string") return content;
return content
.filter((part) => part.type === "text" && part.text !== undefined)
.map((part) => part.text!)
.join("");
}
/** Type guard: is this an OpenAI-style tool definition (has `function` key)? */
function isOpenAIToolDef(t: CohereToolDef): t is CohereToolDefOpenAI {
return "function" in t && typeof (t as CohereToolDefOpenAI).function === "object";
}
export function cohereToCompletionRequest(req: CohereRequest): ChatCompletionRequest {
const messages: ChatMessage[] = [];
for (const msg of req.messages) {
const textContent = extractTextContent(msg.content);
if (msg.role === "system") {
messages.push({ role: "system", content: textContent });
} else if (msg.role === "user") {
messages.push({ role: "user", content: textContent });
} else if (msg.role === "assistant") {
if (msg.tool_calls && msg.tool_calls.length > 0) {
messages.push({
role: "assistant",
content: textContent || null,
tool_calls: msg.tool_calls.map((tc) => ({
id: tc.id ?? generateToolCallId(),
type: "function" as const,
function: {
name: tc.function.name,
arguments: tc.function.arguments,
},
})),
});
} else {
messages.push({ role: "assistant", content: textContent });
}
} else if (msg.role === "tool") {
messages.push({
role: "tool",
content: textContent,
tool_call_id: msg.tool_call_id,
});
}
}
// Convert tools — accept both OpenAI format and Cohere v2 native format
let tools: ToolDefinition[] | undefined;
if (req.tools && req.tools.length > 0) {
tools = req.tools.map((t) => {
if (isOpenAIToolDef(t)) {
return {
type: "function" as const,
function: {
name: t.function.name,
description: t.function.description,
parameters: t.function.parameters,
},
};
}
// Cohere v2 native format: { name, description, parameter_definitions }
return {
type: "function" as const,
function: {
name: t.name,
description: t.description,
parameters: t.parameter_definitions,
},
};
});
}
return {
model: req.model,
messages,
stream: req.stream,
tools,
...(req.response_format && { response_format: req.response_format }),
...(req.temperature !== undefined && { temperature: req.temperature }),
...(req.max_tokens !== undefined && { max_tokens: req.max_tokens }),
};
}
// ─── Response building: fixture → Cohere v2 Chat format ─────────────────────
// Non-streaming text response
function buildCohereTextResponse(
content: string,
reasoning?: string,
overrides?: ResponseOverrides,
): object {
const contentBlocks: { type: string; text: string }[] = [];
if (reasoning) {
contentBlocks.push({ type: "text", text: reasoning });
}
contentBlocks.push({ type: "text", text: content });
return {
id: overrides?.id ?? generateMessageId(),
finish_reason: cohereFinishReason(overrides?.finishReason, "COMPLETE"),
message: {
role: "assistant",
content: contentBlocks,
tool_calls: [],
tool_plan: "",
citations: [],
},
usage: cohereUsage(overrides),
};
}
// Non-streaming tool call response
function buildCohereToolCallResponse(
toolCalls: ToolCall[],
logger: Logger,
reasoning?: string,
overrides?: ResponseOverrides,
): object {
const cohereCalls = toolCalls.map((tc) => {
// Validate arguments JSON
let argsJson: string;
try {
JSON.parse(tc.arguments || "{}");
argsJson = tc.arguments || "{}";
} catch {
logger.warn(
`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`,
);
argsJson = "{}";
}
return {
id: tc.id || generateToolCallId(),
type: "function",
function: {
name: tc.name,
arguments: argsJson,
},
};
});
// Reasoning as a leading text block (Cohere has no native reasoning type)
const contentBlocks: { type: string; text: string }[] = [];
if (reasoning) {
contentBlocks.push({ type: "text", text: reasoning });
}
return {
id: overrides?.id ?? generateMessageId(),
finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
message: {
role: "assistant",
content: contentBlocks,
tool_calls: cohereCalls,
tool_plan: "",
citations: [],
},
usage: cohereUsage(overrides),
};
}
// Non-streaming content + tool calls response
function buildCohereContentWithToolCallsResponse(
content: string,
toolCalls: ToolCall[],
logger: Logger,
reasoning?: string,
overrides?: ResponseOverrides,
blocks?: FixtureBlock[],
): object {
// Cohere's non-streaming response keeps text in `message.content[]` and tool
// calls in the SEPARATE `message.tool_calls[]` field, so the relative ORDER
// of a text vs. toolCall block is NOT observable on the wire (unlike the
// ordered streaming events, or Anthropic/Gemini's single ordered array).
// When `blocks` is present we therefore derive both fields FROM the blocks
// (so a blocks-only fixture still produces correct output) but make no
// ordering guarantee between the two fields. Legacy fixtures use the
// `content` + `toolCalls` inputs unchanged.
// Resolve the blocks exactly once (pure: validate + copy, no id-gen) and
// reuse the single result for BOTH the tool-call and text derivation below.
const resolvedBlocks = blocks && blocks.length > 0 ? resolveFixtureBlocks(blocks) : undefined;
const effectiveToolCalls: ToolCall[] = resolvedBlocks
? resolvedBlocks
.filter((b): b is Extract<FixtureBlock, { type: "toolCall" }> => b.type === "toolCall")
.map((b) => ({ name: b.name, arguments: b.arguments, id: b.id }))
: toolCalls;
const cohereCalls = effectiveToolCalls.map((tc) => {
let argsJson: string;
try {
JSON.parse(tc.arguments || "{}");
argsJson = tc.arguments || "{}";
} catch {
logger.warn(
`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`,
);
argsJson = "{}";
}
return {
id: tc.id || generateToolCallId(),
type: "function",
function: {
name: tc.name,
arguments: argsJson,
},
};
});
// For the blocks path, derive text only from actual text blocks. A tool-only
// blocks fixture has no text block, so it must NOT emit a spurious empty
// `{ type: "text", text: "" }` entry (real Cohere wouldn't). The legacy
// (no-blocks) path is unchanged: it always emits the `content` text entry.
const textBlocks = resolvedBlocks?.filter(
(b): b is Extract<FixtureBlock, { type: "text" }> => b.type === "text",
);
const hasTextEntry = resolvedBlocks ? (textBlocks?.length ?? 0) > 0 : true;
const effectiveContent: string = resolvedBlocks
? (textBlocks ?? []).map((b) => b.text).join("")
: content;
const contentBlocks: { type: string; text: string }[] = [];
if (reasoning) {
contentBlocks.push({ type: "text", text: reasoning });
}
if (hasTextEntry) {
contentBlocks.push({ type: "text", text: effectiveContent });
}
return {
id: overrides?.id ?? generateMessageId(),
finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
message: {
role: "assistant",
content: contentBlocks,
tool_calls: cohereCalls,
tool_plan: "",
citations: [],
},
usage: cohereUsage(overrides),
};
}
// ─── Streaming event builders ───────────────────────────────────────────────
function buildCohereTextStreamEvents(
content: string,
chunkSize: number,
reasoning?: string,
overrides?: ResponseOverrides,
): CohereSSEEvent[] {
const msgId = overrides?.id ?? generateMessageId();
const events: CohereSSEEvent[] = [];
// message-start
events.push({
id: msgId,
type: "message-start",
delta: {
message: {
role: "assistant",
content: [],
tool_plan: "",
tool_calls: [],
citations: [],
},
},
});
let contentIndex = 0;
// Reasoning as a text block before main content (Cohere has no native reasoning type)
if (reasoning) {
events.push({
type: "content-start",
index: contentIndex,
delta: { message: { content: { type: "text" } } },
});
for (let i = 0; i < reasoning.length; i += chunkSize) {
const slice = reasoning.slice(i, i + chunkSize);
events.push({
type: "content-delta",
index: contentIndex,
delta: { message: { content: { type: "text", text: slice } } },
});
}
events.push({ type: "content-end", index: contentIndex });
contentIndex++;
}
// content-start (type: "text" only, no text field)
events.push({
type: "content-start",
index: contentIndex,
delta: {
message: {
content: { type: "text" },
},
},
});
// content-delta — text chunks
for (let i = 0; i < content.length; i += chunkSize) {
const slice = content.slice(i, i + chunkSize);
events.push({
type: "content-delta",
index: contentIndex,
delta: {
message: {
content: { type: "text", text: slice },
},
},
});
}
// content-end
events.push({
type: "content-end",
index: contentIndex,
});
// message-end
events.push({
type: "message-end",
delta: {
finish_reason: cohereFinishReason(overrides?.finishReason, "COMPLETE"),
usage: cohereUsage(overrides),
},
});
return events;
}
function buildCohereToolCallStreamEvents(
toolCalls: ToolCall[],
chunkSize: number,
logger: Logger,
reasoning?: string,
overrides?: ResponseOverrides,
): CohereSSEEvent[] {
const msgId = overrides?.id ?? generateMessageId();
const events: CohereSSEEvent[] = [];
// message-start
events.push({
id: msgId,
type: "message-start",
delta: {
message: {
role: "assistant",
content: [],
tool_plan: "",
tool_calls: [],
citations: [],
},
},
});
// Reasoning as a text block before the tool plan (Cohere has no native reasoning type)
if (reasoning) {
events.push({
type: "content-start",
index: 0,
delta: { message: { content: { type: "text" } } },
});
for (let i = 0; i < reasoning.length; i += chunkSize) {
const slice = reasoning.slice(i, i + chunkSize);
events.push({
type: "content-delta",
index: 0,
delta: { message: { content: { type: "text", text: slice } } },
});
}
events.push({ type: "content-end", index: 0 });
}
// tool-plan-delta
events.push({
type: "tool-plan-delta",
delta: {
message: {
tool_plan: "I will use the requested tool.",
},
},
});
for (let idx = 0; idx < toolCalls.length; idx++) {
const tc = toolCalls[idx];
const callId = tc.id || generateToolCallId();
// Validate arguments JSON
let argsJson: string;
try {
JSON.parse(tc.arguments || "{}");
argsJson = tc.arguments || "{}";
} catch {
logger.warn(
`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`,
);
argsJson = "{}";
}
// tool-call-start
events.push({
type: "tool-call-start",
index: idx,
delta: {
message: {
tool_calls: {
id: callId,
type: "function",
function: {
name: tc.name,
arguments: "",
},
},
},
},
});
// tool-call-delta — chunked arguments
for (let i = 0; i < argsJson.length; i += chunkSize) {
const slice = argsJson.slice(i, i + chunkSize);
events.push({
type: "tool-call-delta",
index: idx,
delta: {
message: {
tool_calls: {
function: {
arguments: slice,
},
},
},
},
});
}
// tool-call-end
events.push({
type: "tool-call-end",
index: idx,
});
}
// message-end
events.push({
type: "message-end",
delta: {
finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
usage: cohereUsage(overrides),
},
});
return events;
}
function buildCohereContentWithToolCallsStreamEvents(
content: string,
toolCalls: ToolCall[],
chunkSize: number,
logger: Logger,
reasoning?: string,
overrides?: ResponseOverrides,
blocks?: FixtureBlock[],
): CohereSSEEvent[] {
const msgId = overrides?.id ?? generateMessageId();
const events: CohereSSEEvent[] = [];
// message-start
events.push({
id: msgId,
type: "message-start",
delta: {
message: {
role: "assistant",
content: [],
tool_plan: "",
tool_calls: [],
citations: [],
},
},
});
let contentIndex = 0;
// Reasoning as a text block before main content
if (reasoning) {
events.push({
type: "content-start",
index: contentIndex,
delta: { message: { content: { type: "text" } } },
});
for (let i = 0; i < reasoning.length; i += chunkSize) {
const slice = reasoning.slice(i, i + chunkSize);
events.push({
type: "content-delta",
index: contentIndex,
delta: { message: { content: { type: "text", text: slice } } },
});
}
events.push({ type: "content-end", index: contentIndex });
contentIndex++;
}
if (blocks && blocks.length > 0) {
// NEW path (#274): emit Cohere SSE events in the blocks' ARRAY ORDER so a
// tool-first / interleaved fixture streams its tool call before its text.
// Cohere v2 events are ordered, so tool-first is wire-expressible. The
// tool-plan-delta is emitted once before the first toolCall block (Cohere
// requires it preceding tool calls). Legacy fixtures (no blocks) skip this.
const resolved = resolveFixtureBlocks(blocks);
let toolPlanEmitted = false;
let toolIdx = 0;
resolved.forEach((block) => {
if (block.type === "toolCall") {
if (!toolPlanEmitted) {
events.push({
type: "tool-plan-delta",
delta: { message: { tool_plan: "I will use the requested tool." } },
});
toolPlanEmitted = true;
}
const callId = block.id || generateToolCallId();
let argsJson: string;
try {
JSON.parse(block.arguments || "{}");
argsJson = block.arguments || "{}";
} catch {
logger.warn(
`Malformed JSON in fixture tool call arguments for "${block.name}": ${block.arguments}`,
);
argsJson = "{}";
}
events.push({
type: "tool-call-start",
index: toolIdx,
delta: {
message: {
tool_calls: {
id: callId,
type: "function",
function: { name: block.name, arguments: "" },
},
},
},
});
for (let i = 0; i < argsJson.length; i += chunkSize) {
events.push({
type: "tool-call-delta",
index: toolIdx,
delta: {
message: {
tool_calls: { function: { arguments: argsJson.slice(i, i + chunkSize) } },
},
},
});
}
events.push({ type: "tool-call-end", index: toolIdx });
toolIdx++;
} else {
events.push({
type: "content-start",
index: contentIndex,
delta: { message: { content: { type: "text" } } },
});
for (let i = 0; i < block.text.length; i += chunkSize) {
events.push({
type: "content-delta",
index: contentIndex,
delta: {
message: { content: { type: "text", text: block.text.slice(i, i + chunkSize) } },
},
});
}
events.push({ type: "content-end", index: contentIndex });
contentIndex++;
}
});
events.push({
type: "message-end",
delta: {
finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
usage: cohereUsage(overrides),
},
});
return events;
}
// content-start (type: "text" only, no text field)
events.push({
type: "content-start",
index: contentIndex,
delta: {
message: {
content: { type: "text" },
},
},
});
// content-delta — text chunks
for (let i = 0; i < content.length; i += chunkSize) {
const slice = content.slice(i, i + chunkSize);
events.push({
type: "content-delta",
index: contentIndex,
delta: {
message: {
content: { type: "text", text: slice },
},
},
});
}
// content-end
events.push({
type: "content-end",
index: contentIndex,
});
// tool-plan-delta
events.push({
type: "tool-plan-delta",
delta: {
message: {
tool_plan: "I will use the requested tool.",
},
},
});
// Tool call events
for (let idx = 0; idx < toolCalls.length; idx++) {
const tc = toolCalls[idx];
const callId = tc.id || generateToolCallId();
let argsJson: string;
try {
JSON.parse(tc.arguments || "{}");
argsJson = tc.arguments || "{}";
} catch {
logger.warn(
`Malformed JSON in fixture tool call arguments for "${tc.name}": ${tc.arguments}`,
);
argsJson = "{}";
}
// tool-call-start
events.push({
type: "tool-call-start",
index: idx,
delta: {
message: {
tool_calls: {
id: callId,
type: "function",
function: {
name: tc.name,
arguments: "",
},
},
},
},
});
// tool-call-delta — chunked arguments
for (let i = 0; i < argsJson.length; i += chunkSize) {
const slice = argsJson.slice(i, i + chunkSize);
events.push({
type: "tool-call-delta",
index: idx,
delta: {
message: {
tool_calls: {
function: {
arguments: slice,
},
},
},
},
});
}
// tool-call-end
events.push({
type: "tool-call-end",
index: idx,
});
}
// message-end
events.push({
type: "message-end",
delta: {
finish_reason: cohereFinishReason(overrides?.finishReason, "TOOL_CALL"),
usage: cohereUsage(overrides),
},
});
return events;
}
// ─── SSE writer for Cohere typed events ─────────────────────────────────────
interface CohereStreamOptions {
latency?: number;
streamingProfile?: StreamingProfile;
recordedTimings?: RecordedTimings;
replaySpeed?: number;
signal?: AbortSignal;
onChunkSent?: () => void;
}
async function writeCohereSSEStream(
res: http.ServerResponse,
events: CohereSSEEvent[],
optionsOrLatency?: number | CohereStreamOptions,
): Promise<boolean> {
const opts: CohereStreamOptions =
typeof optionsOrLatency === "number" ? { latency: optionsOrLatency } : (optionsOrLatency ?? {});
const latency = opts.latency ?? 0;
const profile = opts.streamingProfile;
const { recordedTimings, replaySpeed } = opts;
const signal = opts.signal;
const onChunkSent = opts.onChunkSent;
if (res.writableEnded) return true;
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
let chunkIndex = 0;
for (const event of events) {
const chunkDelay = calculateDelay(chunkIndex, profile, latency, recordedTimings, replaySpeed);
if (chunkDelay > 0) await delay(chunkDelay, signal);
if (signal?.aborted) return false;
if (res.writableEnded) return true;
res.write(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`);
onChunkSent?.();
if (signal?.aborted) return false;
chunkIndex++;
}
if (!res.writableEnded) {
res.end();
}
return true;
}
// ─── Request handler ────────────────────────────────────────────────────────
export async function handleCohere(
req: http.IncomingMessage,
res: http.ServerResponse,
raw: string,
fixtures: Fixture[],
journal: Journal,
defaults: HandlerDefaults,
setCorsHeaders: (res: http.ServerResponse) => void,
): Promise<void> {
const { logger } = defaults;
setCorsHeaders(res);
let cohereReq: CohereRequest;
try {
cohereReq = JSON.parse(raw) as CohereRequest;
} catch (parseErr) {
const detail = parseErr instanceof Error ? parseErr.message : "unknown";
journal.add({
method: req.method ?? "POST",
path: req.url ?? "/v2/chat",
headers: flattenHeaders(req.headers),
body: null,
response: { status: 400, fixture: null },
});
writeErrorResponse(
res,
400,
JSON.stringify({
error: {
message: `Malformed JSON body: ${detail}`,
type: "invalid_request_error",
},
}),
);
return;
}
// Validate required model field
if (!cohereReq.model) {
journal.add({
method: req.method ?? "POST",
path: req.url ?? "/v2/chat",
headers: flattenHeaders(req.headers),
body: null,
response: { status: 400, fixture: null },
});
writeErrorResponse(
res,
400,
JSON.stringify({
error: {
message: "model is required",
type: "invalid_request_error",
},
}),
);
return;
}
if (!cohereReq.messages || !Array.isArray(cohereReq.messages)) {
journal.add({
method: req.method ?? "POST",
path: req.url ?? "/v2/chat",
headers: flattenHeaders(req.headers),
body: null,
response: { status: 400, fixture: null },
});
writeErrorResponse(
res,
400,
JSON.stringify({
error: {
message: "Invalid request: messages array is required",
type: "invalid_request_error",
},
}),
);
return;
}
// Convert to ChatCompletionRequest for fixture matching
const completionReq = cohereToCompletionRequest(cohereReq);
completionReq._endpointType = "chat";
completionReq._context = getContext(req);
const testId = getTestId(req);
const { fixture, skippedBySequenceOrTurn } = matchFixtureDiagnostic(
fixtures,
completionReq,
journal.getFixtureMatchCountsForTest(testId),
defaults.requestTransform,
// Record mode proxies on a miss to capture a fresh turn (see record gate
// below), so keep turnIndex strict to prevent an earlier-turn fixture from
// shadowing a longer request and skipping the new turn's recording.
recordMatchOptions(!!defaults.record, defaults.logger),
);
if (fixture) {