tuxevil-rotator 3.7.0 → 3.7.2

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