tuxevil-rotator 3.7.0 → 3.7.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.
@@ -1,13 +1,22 @@
1
1
  // OpenCode Zen request forwarding and SSE stream accumulation.
2
2
 
3
+ import { randomUUID } from "node:crypto";
3
4
  import type { AccountRuntime } from "../../types.js";
4
5
  import type { ForwardedResponse, RequestBody } from "../../proxy.js";
5
6
  import type { StreamAccumulator, TokenUsage } from "../adapter.js";
6
7
  import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
7
8
  import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
8
9
  import { getOpenCodeZenApiKey, OPENCODE_ZEN_PROVIDER_ID } from "./credentials.js";
9
- import { OPENCODE_ZEN_CHAT_URL } from "./catalog.js";
10
+ import {
11
+ isOpenCodeZenResponsesModel,
12
+ OPENCODE_ZEN_CHAT_URL,
13
+ OPENCODE_ZEN_RESPONSES_URL,
14
+ } from "./catalog.js";
10
15
  import { isRecord } from "../../compat/schema-sanitizer.js";
16
+ import type {
17
+ CompatCompletion,
18
+ OpenAIToolCall,
19
+ } from "../google-antigravity/translators.js";
11
20
 
12
21
  const HOP_BY_HOP = new Set([
13
22
  "connection",
@@ -49,16 +58,183 @@ export function buildOpenCodeZenPayload(body: RequestBody): Record<string, unkno
49
58
  };
50
59
  }
51
60
 
52
- export async function forwardRequest(
53
- account: AccountRuntime,
61
+ function textFromContent(value: unknown): string {
62
+ if (typeof value === "string") return value;
63
+ if (!Array.isArray(value)) return "";
64
+ return value
65
+ .map((part) => {
66
+ if (!isRecord(part)) return "";
67
+ return typeof part.text === "string" ? part.text : "";
68
+ })
69
+ .filter(Boolean)
70
+ .join("\n");
71
+ }
72
+
73
+ function responsesContent(value: unknown, role: string): unknown {
74
+ if (typeof value === "string") {
75
+ return [{
76
+ type: role === "assistant" ? "output_text" : "input_text",
77
+ text: value,
78
+ }];
79
+ }
80
+ if (!Array.isArray(value)) return value ?? [];
81
+ return value.map((part) => {
82
+ if (!isRecord(part)) return part;
83
+ if (
84
+ part.type === "text" ||
85
+ part.type === "input_text" ||
86
+ part.type === "output_text"
87
+ ) {
88
+ return {
89
+ type: role === "assistant" ? "output_text" : "input_text",
90
+ text: typeof part.text === "string" ? part.text : "",
91
+ };
92
+ }
93
+ if (part.type === "image_url" && isRecord(part.image_url)) {
94
+ return {
95
+ type: "input_image",
96
+ image_url: part.image_url.url,
97
+ };
98
+ }
99
+ return part;
100
+ });
101
+ }
102
+
103
+ function responsesTool(value: unknown): unknown {
104
+ if (!isRecord(value) || value.type !== "function" || !isRecord(value.function)) {
105
+ return value;
106
+ }
107
+ const fn = value.function;
108
+ const tool: Record<string, unknown> = {
109
+ type: "function",
110
+ name: fn.name,
111
+ };
112
+ for (const field of ["description", "parameters", "strict"]) {
113
+ if (fn[field] !== undefined) tool[field] = fn[field];
114
+ }
115
+ return tool;
116
+ }
117
+
118
+ function responsesToolChoice(value: unknown): unknown {
119
+ if (!isRecord(value) || value.type !== "function" || !isRecord(value.function)) {
120
+ return value;
121
+ }
122
+ return { type: "function", name: value.function.name };
123
+ }
124
+
125
+ /** Convert the common Chat Completions envelope into OpenAI Responses input. */
126
+ export function buildOpenCodeZenResponsesPayload(
54
127
  body: RequestBody,
55
- originalHeaders: Record<string, string>,
56
- signal?: AbortSignal,
57
- ): Promise<ForwardedResponse> {
58
- const payload = buildOpenCodeZenPayload(body);
59
- const apiKey = getOpenCodeZenApiKey(account.config) ?? "";
128
+ ): Record<string, unknown> {
129
+ const request = isRecord(body.request) ? body.request : {};
130
+
131
+ // Keep already-native Responses requests intact. This is useful for callers
132
+ // of /v1/responses and avoids throwing away fields the compatibility layer
133
+ // does not need to interpret.
134
+ if ("input" in request) {
135
+ const payload: Record<string, unknown> = { ...request, model: body.model, store: false };
136
+ if (payload.max_output_tokens === undefined && payload.max_tokens !== undefined) {
137
+ payload.max_output_tokens = payload.max_tokens;
138
+ }
139
+ delete payload.max_tokens;
140
+ return payload;
141
+ }
142
+
143
+ const input: unknown[] = [];
144
+ const instructions: string[] = [];
145
+ const messages = Array.isArray(request.messages) ? request.messages : [];
146
+
147
+ for (const rawMessage of messages) {
148
+ if (!isRecord(rawMessage)) continue;
149
+ const role = typeof rawMessage.role === "string" ? rawMessage.role : "user";
150
+
151
+ if (role === "system" || role === "developer") {
152
+ const text = textFromContent(rawMessage.content);
153
+ if (text) instructions.push(text);
154
+ continue;
155
+ }
156
+
157
+ if (role === "tool") {
158
+ input.push({
159
+ type: "function_call_output",
160
+ call_id: rawMessage.tool_call_id,
161
+ output: typeof rawMessage.content === "string"
162
+ ? rawMessage.content
163
+ : JSON.stringify(rawMessage.content ?? ""),
164
+ });
165
+ continue;
166
+ }
167
+
168
+ if (Array.isArray(rawMessage.tool_calls)) {
169
+ for (const rawCall of rawMessage.tool_calls) {
170
+ if (!isRecord(rawCall) || !isRecord(rawCall.function)) continue;
171
+ input.push({
172
+ type: "function_call",
173
+ call_id: rawCall.id,
174
+ name: rawCall.function.name,
175
+ arguments: typeof rawCall.function.arguments === "string"
176
+ ? rawCall.function.arguments
177
+ : JSON.stringify(rawCall.function.arguments ?? {}),
178
+ });
179
+ }
180
+ }
181
+
182
+ if (rawMessage.content !== undefined && rawMessage.content !== null) {
183
+ input.push({
184
+ role: role === "assistant" ? "assistant" : "user",
185
+ content: responsesContent(rawMessage.content, role),
186
+ });
187
+ }
188
+ }
189
+
190
+ const payload: Record<string, unknown> = {
191
+ model: body.model,
192
+ input,
193
+ stream: request.stream === true,
194
+ store: false,
195
+ };
196
+ if (instructions.length > 0) payload.instructions = instructions.join("\n\n");
197
+ if (typeof request.max_output_tokens === "number") {
198
+ payload.max_output_tokens = request.max_output_tokens;
199
+ } else if (typeof request.max_tokens === "number") {
200
+ payload.max_output_tokens = request.max_tokens;
201
+ }
202
+ for (const field of [
203
+ "temperature",
204
+ "top_p",
205
+ "parallel_tool_calls",
206
+ "reasoning",
207
+ "metadata",
208
+ "stop",
209
+ ]) {
210
+ if (request[field] !== undefined) payload[field] = request[field];
211
+ }
212
+ if (typeof request.reasoning_effort === "string" && payload.reasoning === undefined) {
213
+ payload.reasoning = { effort: request.reasoning_effort };
214
+ }
215
+ if (Array.isArray(request.tools) && request.tools.length > 0) {
216
+ payload.tools = request.tools.map(responsesTool);
217
+ }
218
+ if (request.tool_choice !== undefined) {
219
+ payload.tool_choice = responsesToolChoice(request.tool_choice);
220
+ }
221
+ return payload;
222
+ }
60
223
 
61
- const forwardHeaders: Record<string, string> = {};
224
+ function headerValue(headers: Record<string, string>, name: string): string | undefined {
225
+ const wanted = name.toLowerCase();
226
+ for (const [key, value] of Object.entries(headers)) {
227
+ if (key.toLowerCase() === wanted && value.trim()) return value;
228
+ }
229
+ return undefined;
230
+ }
231
+
232
+ function buildOpenCodeZenHeaders(
233
+ originalHeaders: Record<string, string>,
234
+ body: RequestBody,
235
+ account: AccountRuntime,
236
+ ): Record<string, string> {
237
+ const headers: Record<string, string> = {};
62
238
  for (const [key, value] of Object.entries(originalHeaders)) {
63
239
  const lower = key.toLowerCase();
64
240
  if (
@@ -67,15 +243,45 @@ export async function forwardRequest(
67
243
  lower !== "content-type" &&
68
244
  lower !== "accept"
69
245
  ) {
70
- forwardHeaders[key] = value;
246
+ headers[key] = value;
71
247
  }
72
248
  }
73
249
 
74
- forwardHeaders["Authorization"] = `Bearer ${apiKey}`;
250
+ // OpenCode's free tier requires these context headers. Native OpenCode
251
+ // emits them only for provider IDs beginning with `opencode`; the rotator
252
+ // is commonly configured under a custom provider ID, so fill safe defaults.
253
+ if (!headerValue(headers, "x-opencode-session")) {
254
+ headers["x-opencode-session"] = `zen-session-${body.requestId || randomUUID()}`;
255
+ }
256
+ if (!headerValue(headers, "x-opencode-request")) {
257
+ headers["x-opencode-request"] = `zen-request-${body.requestId || randomUUID()}`;
258
+ }
259
+ if (!headerValue(headers, "x-opencode-client")) {
260
+ headers["x-opencode-client"] = "tuxevil-rotator";
261
+ }
262
+ if (!headerValue(headers, "user-agent")) {
263
+ headers["User-Agent"] = "tuxevil-rotator/opencode-zen";
264
+ }
265
+
266
+ headers.Authorization = `Bearer ${getOpenCodeZenApiKey(account.config) ?? ""}`;
267
+ return headers;
268
+ }
269
+
270
+ export async function forwardRequest(
271
+ account: AccountRuntime,
272
+ body: RequestBody,
273
+ originalHeaders: Record<string, string>,
274
+ signal?: AbortSignal,
275
+ ): Promise<ForwardedResponse> {
276
+ const usesResponses = isOpenCodeZenResponsesModel(body.model);
277
+ const payload = usesResponses
278
+ ? buildOpenCodeZenResponsesPayload(body)
279
+ : buildOpenCodeZenPayload(body);
280
+ const forwardHeaders = buildOpenCodeZenHeaders(originalHeaders, body, account);
75
281
  forwardHeaders["Content-Type"] = "application/json";
76
282
  forwardHeaders["Accept"] = payload.stream === true ? "text/event-stream" : "application/json";
77
283
 
78
- const endpoint = OPENCODE_ZEN_CHAT_URL;
284
+ const endpoint = usesResponses ? OPENCODE_ZEN_RESPONSES_URL : OPENCODE_ZEN_CHAT_URL;
79
285
  const response = await fetch(endpoint, {
80
286
  method: "POST",
81
287
  headers: forwardHeaders,
@@ -84,9 +290,494 @@ export async function forwardRequest(
84
290
  dispatcher: getAccountProxyDispatcher(account, OPENCODE_ZEN_PROVIDER_ID),
85
291
  } as RequestInitWithDispatcher);
86
292
 
293
+ // The compatibility layer normalises all provider responses through the
294
+ // Chat Completions shape before the local endpoint wraps them again. This
295
+ // keeps Chat, Anthropic, and Responses callers on the same parser path.
296
+ if (usesResponses && response.ok) {
297
+ if (payload.stream === true && response.body) {
298
+ const headers = new Headers(response.headers);
299
+ headers.delete("content-length");
300
+ headers.set("content-type", "text/event-stream");
301
+ return {
302
+ response: new Response(
303
+ transformOpenCodeZenResponsesStream(response.body, body.model),
304
+ { status: response.status, statusText: response.statusText, headers },
305
+ ),
306
+ endpoint,
307
+ };
308
+ }
309
+ const raw = await response.text();
310
+ const headers = new Headers(response.headers);
311
+ headers.delete("content-length");
312
+ headers.set("content-type", "application/json");
313
+ return {
314
+ response: new Response(
315
+ JSON.stringify(openCodeZenResponsesToChatJson(raw, body.model)),
316
+ { status: response.status, statusText: response.statusText, headers },
317
+ ),
318
+ endpoint,
319
+ };
320
+ }
321
+
87
322
  return { response, endpoint };
88
323
  }
89
324
 
325
+ export type OpenCodeZenResponsesUpdate =
326
+ | { kind: "text"; delta: string }
327
+ | { kind: "reasoning"; delta: string }
328
+ | { kind: "tool-start"; index: number; id: string; name: string }
329
+ | { kind: "tool-delta"; index: number; delta: string }
330
+ | { kind: "usage"; usage: TokenUsage }
331
+ | { kind: "finish"; reason?: string }
332
+ | { kind: "error"; message: string };
333
+
334
+ function responseErrorMessage(value: unknown): string {
335
+ if (typeof value === "string" && value.trim()) return value.trim();
336
+ if (isRecord(value) && typeof value.message === "string" && value.message.trim()) {
337
+ return value.message.trim();
338
+ }
339
+ return "OpenCode Zen Responses stream failed";
340
+ }
341
+
342
+ function responseFinishReason(value: Record<string, unknown>): string | undefined {
343
+ if (value.status === "incomplete" && isRecord(value.incomplete_details)) {
344
+ return typeof value.incomplete_details.reason === "string"
345
+ ? value.incomplete_details.reason
346
+ : undefined;
347
+ }
348
+ if (value.status === "failed") return "error";
349
+ return undefined;
350
+ }
351
+
352
+ function responseCompletionFromRecord(
353
+ value: Record<string, unknown>,
354
+ rawResponse: unknown = value,
355
+ ): CompatCompletion {
356
+ let text = "";
357
+ let thinkingText = "";
358
+ const toolCalls: OpenAIToolCall[] = [];
359
+ const output = Array.isArray(value.output) ? value.output : [];
360
+
361
+ for (const rawItem of output) {
362
+ if (!isRecord(rawItem)) continue;
363
+ if (rawItem.type === "message" && Array.isArray(rawItem.content)) {
364
+ for (const rawContent of rawItem.content) {
365
+ if (!isRecord(rawContent)) continue;
366
+ if (
367
+ (rawContent.type === "output_text" || rawContent.type === "text") &&
368
+ typeof rawContent.text === "string"
369
+ ) {
370
+ text += rawContent.text;
371
+ } else if (rawContent.type === "refusal" && typeof rawContent.refusal === "string") {
372
+ text += rawContent.refusal;
373
+ }
374
+ }
375
+ }
376
+ if (rawItem.type === "reasoning" && Array.isArray(rawItem.summary)) {
377
+ for (const rawSummary of rawItem.summary) {
378
+ if (isRecord(rawSummary) && typeof rawSummary.text === "string") {
379
+ thinkingText += rawSummary.text;
380
+ }
381
+ }
382
+ }
383
+ if (rawItem.type === "function_call") {
384
+ toolCalls.push({
385
+ id: typeof rawItem.call_id === "string"
386
+ ? rawItem.call_id
387
+ : typeof rawItem.id === "string"
388
+ ? rawItem.id
389
+ : `call_${toolCalls.length}`,
390
+ type: "function",
391
+ function: {
392
+ name: typeof rawItem.name === "string" ? rawItem.name : "unknown",
393
+ arguments: typeof rawItem.arguments === "string"
394
+ ? rawItem.arguments
395
+ : JSON.stringify(rawItem.arguments ?? {}),
396
+ },
397
+ });
398
+ }
399
+ }
400
+
401
+ if (!text && typeof value.output_text === "string") text = value.output_text;
402
+ const usage = extractUsageFromRecord(value);
403
+ const error = isRecord(value.error) ? responseErrorMessage(value.error) : undefined;
404
+ return {
405
+ text,
406
+ thinkingText: thinkingText || undefined,
407
+ inputTokens: usage?.inputTokens ?? 0,
408
+ outputTokens: usage?.outputTokens ?? 0,
409
+ responseId: typeof value.id === "string" ? value.id : undefined,
410
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
411
+ rawResponse,
412
+ streamError: error,
413
+ finishReason: responseFinishReason(value),
414
+ };
415
+ }
416
+
417
+ export function parseOpenCodeZenResponsesJson(raw: string): CompatCompletion {
418
+ try {
419
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
420
+ return responseCompletionFromRecord(parsed, parsed);
421
+ } catch {
422
+ return {
423
+ text: "",
424
+ inputTokens: 0,
425
+ outputTokens: 0,
426
+ rawResponse: raw,
427
+ streamError: "Invalid OpenCode Zen Responses JSON",
428
+ };
429
+ }
430
+ }
431
+
432
+ /** Parse native OpenAI Responses SSE events into provider-neutral updates. */
433
+ export class OpenCodeZenResponsesStreamParser {
434
+ private buffer = "";
435
+ private eventName = "";
436
+ private text = "";
437
+ private thinkingText = "";
438
+ private responseId: string | undefined;
439
+ private usage: TokenUsage | null = null;
440
+ private finishReason: string | undefined;
441
+ private streamError: string | undefined;
442
+ private readonly toolCalls = new Map<number, OpenAIToolCall>();
443
+ private readonly toolItemIndexes = new Map<string, number>();
444
+
445
+ append(chunkText: string): OpenCodeZenResponsesUpdate[] {
446
+ this.buffer += chunkText;
447
+ const updates: OpenCodeZenResponsesUpdate[] = [];
448
+ let newline = this.buffer.indexOf("\n");
449
+ while (newline >= 0) {
450
+ const line = this.buffer.slice(0, newline).replace(/\r$/, "");
451
+ this.buffer = this.buffer.slice(newline + 1);
452
+ if (line.startsWith("event:")) {
453
+ this.eventName = line.slice(6).trim();
454
+ } else if (line.startsWith("data:")) {
455
+ const payload = line.slice(5).trim();
456
+ if (payload && payload !== "[DONE]") {
457
+ updates.push(...this.processPayload(payload));
458
+ }
459
+ } else if (!line.trim()) {
460
+ this.eventName = "";
461
+ }
462
+ newline = this.buffer.indexOf("\n");
463
+ }
464
+ return updates;
465
+ }
466
+
467
+ flush(): OpenCodeZenResponsesUpdate[] {
468
+ if (!this.buffer.trim()) return [];
469
+ return this.append("\n");
470
+ }
471
+
472
+ getText(): string {
473
+ return this.text;
474
+ }
475
+
476
+ getUsage(): TokenUsage | null {
477
+ return this.usage;
478
+ }
479
+
480
+ toCompletion(): CompatCompletion {
481
+ return {
482
+ text: this.text,
483
+ thinkingText: this.thinkingText || undefined,
484
+ inputTokens: this.usage?.inputTokens ?? 0,
485
+ outputTokens: this.usage?.outputTokens ?? 0,
486
+ responseId: this.responseId,
487
+ toolCalls: this.toolCalls.size > 0 ? Array.from(this.toolCalls.values()) : undefined,
488
+ streamError: this.streamError,
489
+ finishReason: this.finishReason,
490
+ rawResponse: {
491
+ id: this.responseId,
492
+ object: "response",
493
+ output_text: this.text,
494
+ usage: this.usage
495
+ ? {
496
+ input_tokens: this.usage.inputTokens,
497
+ output_tokens: this.usage.outputTokens,
498
+ total_tokens: this.usage.inputTokens + this.usage.outputTokens,
499
+ }
500
+ : undefined,
501
+ },
502
+ };
503
+ }
504
+
505
+ private processPayload(payload: string): OpenCodeZenResponsesUpdate[] {
506
+ let parsed: Record<string, unknown>;
507
+ try {
508
+ parsed = JSON.parse(payload) as Record<string, unknown>;
509
+ } catch {
510
+ return [];
511
+ }
512
+ const type = this.eventName || (typeof parsed.type === "string" ? parsed.type : "");
513
+ const response = isRecord(parsed.response) ? parsed.response : null;
514
+ if (response && typeof response.id === "string") this.responseId = response.id;
515
+ if (!this.responseId && typeof parsed.id === "string") this.responseId = parsed.id;
516
+
517
+ if (type === "response.output_text.delta" && typeof parsed.delta === "string") {
518
+ this.text += parsed.delta;
519
+ return [{ kind: "text", delta: parsed.delta }];
520
+ }
521
+ if (
522
+ type === "response.reasoning_summary_text.delta" &&
523
+ typeof parsed.delta === "string"
524
+ ) {
525
+ this.thinkingText += parsed.delta;
526
+ return [{ kind: "reasoning", delta: parsed.delta }];
527
+ }
528
+ if (type === "response.output_item.added" && isRecord(parsed.item)) {
529
+ const item = parsed.item;
530
+ if (item.type !== "function_call") return [];
531
+ const index = typeof parsed.output_index === "number"
532
+ ? parsed.output_index
533
+ : this.toolCalls.size;
534
+ const itemId = typeof item.id === "string" ? item.id : undefined;
535
+ if (itemId) this.toolItemIndexes.set(itemId, index);
536
+ if (this.toolCalls.has(index)) return [];
537
+ const call: OpenAIToolCall = {
538
+ id: typeof item.call_id === "string"
539
+ ? item.call_id
540
+ : itemId || `call_${index}`,
541
+ type: "function",
542
+ function: {
543
+ name: typeof item.name === "string" ? item.name : "unknown",
544
+ arguments: typeof item.arguments === "string" ? item.arguments : "",
545
+ },
546
+ };
547
+ this.toolCalls.set(index, call);
548
+ return [{
549
+ kind: "tool-start",
550
+ index,
551
+ id: call.id,
552
+ name: call.function.name,
553
+ }];
554
+ }
555
+ if (
556
+ type === "response.function_call_arguments.delta" &&
557
+ typeof parsed.delta === "string"
558
+ ) {
559
+ const index = this.toolIndex(parsed);
560
+ const call = this.ensureTool(index);
561
+ call.function.arguments += parsed.delta;
562
+ return [{ kind: "tool-delta", index, delta: parsed.delta }];
563
+ }
564
+ if (type === "response.output_item.done" && isRecord(parsed.item)) {
565
+ const item = parsed.item;
566
+ if (item.type !== "function_call") return [];
567
+ const index = typeof parsed.output_index === "number"
568
+ ? parsed.output_index
569
+ : typeof item.id === "string" && this.toolItemIndexes.has(item.id)
570
+ ? this.toolItemIndexes.get(item.id)!
571
+ : this.toolCalls.size;
572
+ const call = this.ensureTool(index, item);
573
+ if (typeof item.arguments !== "string") return [];
574
+ const current = typeof call.function.arguments === "string"
575
+ ? call.function.arguments
576
+ : "";
577
+ const delta = item.arguments.startsWith(current)
578
+ ? item.arguments.slice(current.length)
579
+ : item.arguments;
580
+ call.function.arguments = item.arguments;
581
+ return delta ? [{ kind: "tool-delta", index, delta }] : [];
582
+ }
583
+ if (
584
+ type === "response.completed" ||
585
+ type === "response.incomplete" ||
586
+ type === "response.failed"
587
+ ) {
588
+ const completed = response ?? parsed;
589
+ const usage = extractUsageFromRecord(completed);
590
+ const updates: OpenCodeZenResponsesUpdate[] = [];
591
+ if (usage) {
592
+ this.usage = usage;
593
+ updates.push({ kind: "usage", usage });
594
+ }
595
+ this.finishReason = responseFinishReason(completed);
596
+ if (type === "response.failed") {
597
+ this.streamError = responseErrorMessage(parsed.error ?? completed.error);
598
+ updates.push({ kind: "error", message: this.streamError });
599
+ } else {
600
+ updates.push({ kind: "finish", reason: this.finishReason });
601
+ }
602
+ return updates;
603
+ }
604
+ if (type === "error" || type === "response.error") {
605
+ this.streamError = responseErrorMessage(parsed.error ?? parsed);
606
+ return [{ kind: "error", message: this.streamError }];
607
+ }
608
+ return [];
609
+ }
610
+
611
+ private toolIndex(parsed: Record<string, unknown>): number {
612
+ if (typeof parsed.output_index === "number") return parsed.output_index;
613
+ if (typeof parsed.item_id === "string" && this.toolItemIndexes.has(parsed.item_id)) {
614
+ return this.toolItemIndexes.get(parsed.item_id)!;
615
+ }
616
+ return Math.max(0, this.toolCalls.size - 1);
617
+ }
618
+
619
+ private ensureTool(index: number, item?: Record<string, unknown>): OpenAIToolCall {
620
+ const existing = this.toolCalls.get(index);
621
+ if (existing) return existing;
622
+ const call: OpenAIToolCall = {
623
+ id: typeof item?.call_id === "string"
624
+ ? item.call_id
625
+ : typeof item?.id === "string"
626
+ ? item.id
627
+ : `call_${index}`,
628
+ type: "function",
629
+ function: {
630
+ name: typeof item?.name === "string" ? item.name : "unknown",
631
+ arguments: "",
632
+ },
633
+ };
634
+ this.toolCalls.set(index, call);
635
+ if (typeof item?.id === "string") this.toolItemIndexes.set(item.id, index);
636
+ return call;
637
+ }
638
+ }
639
+
640
+ function openCodeZenChatChunk(
641
+ id: string,
642
+ model: string,
643
+ delta: Record<string, unknown>,
644
+ usage?: Record<string, number>,
645
+ ): string {
646
+ return `data: ${JSON.stringify({
647
+ id,
648
+ object: "chat.completion.chunk",
649
+ created: Math.floor(Date.now() / 1000),
650
+ model,
651
+ choices: usage ? [] : [{ index: 0, delta, finish_reason: null }],
652
+ ...(usage ? { usage } : {}),
653
+ })}\n\n`;
654
+ }
655
+
656
+ function updateToOpenCodeZenChatSse(
657
+ update: OpenCodeZenResponsesUpdate,
658
+ id: string,
659
+ model: string,
660
+ ): string {
661
+ switch (update.kind) {
662
+ case "text":
663
+ return openCodeZenChatChunk(id, model, { content: update.delta });
664
+ case "reasoning":
665
+ return openCodeZenChatChunk(id, model, { reasoning_content: update.delta });
666
+ case "tool-start":
667
+ return openCodeZenChatChunk(id, model, {
668
+ tool_calls: [{
669
+ index: update.index,
670
+ id: update.id,
671
+ type: "function",
672
+ function: { name: update.name, arguments: "" },
673
+ }],
674
+ });
675
+ case "tool-delta":
676
+ return openCodeZenChatChunk(id, model, {
677
+ tool_calls: [{ index: update.index, function: { arguments: update.delta } }],
678
+ });
679
+ case "usage":
680
+ return openCodeZenChatChunk(id, model, {}, {
681
+ prompt_tokens: update.usage.inputTokens,
682
+ completion_tokens: update.usage.outputTokens,
683
+ total_tokens: update.usage.inputTokens + update.usage.outputTokens,
684
+ });
685
+ case "finish":
686
+ return "";
687
+ case "error":
688
+ throw new Error(update.message);
689
+ }
690
+ }
691
+
692
+ /** Convert native Responses SSE into OpenAI Chat Completions SSE. */
693
+ export function transformOpenCodeZenResponsesStream(
694
+ body: ReadableStream<Uint8Array>,
695
+ model: string,
696
+ ): ReadableStream<Uint8Array> {
697
+ let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;
698
+ const encoder = new TextEncoder();
699
+ const decoder = new TextDecoder();
700
+ const parser = new OpenCodeZenResponsesStreamParser();
701
+ const id = `chatcmpl-${randomUUID()}`;
702
+ return new ReadableStream<Uint8Array>({
703
+ async start(controller) {
704
+ reader = body.getReader();
705
+ try {
706
+ while (true) {
707
+ const next = await reader.read();
708
+ if (next.done) break;
709
+ const updates = parser.append(decoder.decode(next.value, { stream: true }));
710
+ for (const update of updates) {
711
+ const rendered = updateToOpenCodeZenChatSse(update, id, model);
712
+ if (rendered) controller.enqueue(encoder.encode(rendered));
713
+ }
714
+ }
715
+ const tail = decoder.decode();
716
+ for (const update of [...parser.append(tail), ...parser.flush()]) {
717
+ const rendered = updateToOpenCodeZenChatSse(update, id, model);
718
+ if (rendered) controller.enqueue(encoder.encode(rendered));
719
+ }
720
+ controller.close();
721
+ } catch (error) {
722
+ controller.error(error);
723
+ } finally {
724
+ reader = null;
725
+ }
726
+ },
727
+ async cancel(reason) {
728
+ await reader?.cancel(reason);
729
+ },
730
+ });
731
+ }
732
+
733
+ function openCodeZenResponsesToChatJson(
734
+ raw: string,
735
+ model: string,
736
+ ): Record<string, unknown> {
737
+ let parsed: Record<string, unknown>;
738
+ try {
739
+ parsed = JSON.parse(raw) as Record<string, unknown>;
740
+ } catch {
741
+ return {
742
+ error: {
743
+ message: "Invalid OpenCode Zen Responses JSON",
744
+ type: "upstream_error",
745
+ },
746
+ };
747
+ }
748
+ const completion = responseCompletionFromRecord(parsed, parsed);
749
+ const hasToolCalls = Boolean(completion.toolCalls?.length);
750
+ const finishReason = hasToolCalls
751
+ ? "tool_calls"
752
+ : completion.finishReason === "max_output_tokens"
753
+ ? "length"
754
+ : "stop";
755
+ const created = typeof parsed.created_at === "number"
756
+ ? parsed.created_at
757
+ : Math.floor(Date.now() / 1000);
758
+ return {
759
+ id: completion.responseId || `chatcmpl-${randomUUID()}`,
760
+ object: "chat.completion",
761
+ created,
762
+ model,
763
+ choices: [{
764
+ index: 0,
765
+ message: {
766
+ role: "assistant",
767
+ content: hasToolCalls ? null : completion.text,
768
+ ...(hasToolCalls ? { tool_calls: completion.toolCalls } : {}),
769
+ ...(completion.thinkingText ? { reasoning_content: completion.thinkingText } : {}),
770
+ },
771
+ finish_reason: finishReason,
772
+ }],
773
+ usage: {
774
+ prompt_tokens: completion.inputTokens,
775
+ completion_tokens: completion.outputTokens,
776
+ total_tokens: completion.inputTokens + completion.outputTokens,
777
+ },
778
+ };
779
+ }
780
+
90
781
  function extractUsageFromRecord(record: Record<string, unknown>): TokenUsage | null {
91
782
  const usage = isRecord(record.usage) ? record.usage : record;
92
783
  const inputTokens =
@@ -167,7 +858,7 @@ export class OpenCodeZenSseAccumulator implements StreamAccumulator {
167
858
  }
168
859
  }
169
860
 
170
- const BENCHMARK_MODEL = "deepseek-v4-flash-free";
861
+ const BENCHMARK_MODEL = "big-pickle";
171
862
 
172
863
  export function getBenchmarkSpec(): {
173
864
  body: RequestBody;