@zenmux/rosetta-ai 1.0.1 → 1.0.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.
@@ -20,6 +20,8 @@ export declare class ResponsesToMessagesConverter {
20
20
  private convertReasoning;
21
21
  private stopReasonToStatus;
22
22
  private generateId;
23
+ private extractWebSearchQuery;
24
+ private citationToAnnotation;
23
25
  private createStreamState;
24
26
  private makeSkeletonResponse;
25
27
  }
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ResponsesToMessagesConverter = void 0;
4
+ const sdk_1 = require("@anthropic-ai/sdk");
4
5
  const DEFAULT_MAX_TOKENS = 4096;
5
6
  class ResponsesToMessagesConverter {
6
7
  streamState;
@@ -47,6 +48,15 @@ class ResponsesToMessagesConverter {
47
48
  },
48
49
  };
49
50
  }
51
+ else if (params.text?.format?.type === "json_object") {
52
+ // Anthropic has no bare "json_object" mode; approximate with a permissive object schema.
53
+ result.output_config = {
54
+ format: {
55
+ type: "json_schema",
56
+ schema: { type: "object" },
57
+ },
58
+ };
59
+ }
50
60
  if (params.metadata) {
51
61
  const userId = typeof params.metadata === "object"
52
62
  ? params.metadata.user_id
@@ -69,6 +79,13 @@ class ResponsesToMessagesConverter {
69
79
  // --- Response conversion (Messages → Responses, backward) ---
70
80
  convertResponse(message) {
71
81
  const output = [];
82
+ const textParts = [];
83
+ const annotations = [];
84
+ let messageItem = null;
85
+ // Offset of the current text block within the merged text; citations are per-block.
86
+ let textOffset = 0;
87
+ // Single pass preserving Anthropic's generation order, which matches OpenAI's
88
+ // typical ordering (reasoning → web_search_call → message → function_call).
72
89
  for (const block of message.content) {
73
90
  if (block.type === "thinking") {
74
91
  output.push({
@@ -77,9 +94,17 @@ class ResponsesToMessagesConverter {
77
94
  summary: [{ type: "summary_text", text: block.thinking }],
78
95
  });
79
96
  }
80
- }
81
- for (const block of message.content) {
82
- if (block.type === "tool_use" || block.type === "server_tool_use") {
97
+ else if (block.type === "server_tool_use" && block.name === "web_search") {
98
+ const input = block.input;
99
+ const query = typeof input === "object" && input !== null ? String(input.query ?? "") : "";
100
+ output.push({
101
+ type: "web_search_call",
102
+ id: `ws_${this.generateId()}`,
103
+ status: "completed",
104
+ action: { type: "search", query },
105
+ });
106
+ }
107
+ else if (block.type === "tool_use" || block.type === "server_tool_use") {
83
108
  output.push({
84
109
  type: "function_call",
85
110
  id: `fc_${this.generateId()}`,
@@ -89,28 +114,40 @@ class ResponsesToMessagesConverter {
89
114
  status: "completed",
90
115
  });
91
116
  }
92
- }
93
- const textParts = [];
94
- for (const block of message.content) {
95
- if (block.type === "text") {
117
+ else if (block.type === "text") {
96
118
  textParts.push(block.text);
119
+ const citations = block.citations;
120
+ if (citations) {
121
+ for (const c of citations) {
122
+ annotations.push(this.citationToAnnotation(c, textOffset));
123
+ }
124
+ }
125
+ // Multiple text blocks merge into one message item at the first text block's position.
126
+ if (!messageItem) {
127
+ messageItem = {
128
+ type: "message",
129
+ id: `msg_${this.generateId()}`,
130
+ role: "assistant",
131
+ status: "completed",
132
+ content: [
133
+ {
134
+ type: "output_text",
135
+ text: "",
136
+ annotations: [],
137
+ logprobs: null,
138
+ },
139
+ ],
140
+ };
141
+ output.push(messageItem);
142
+ }
143
+ textOffset += block.text.length;
97
144
  }
145
+ // web_search_tool_result and other result blocks: skipped; the corresponding
146
+ // server_tool_use block already produced the web_search_call item.
98
147
  }
99
- if (textParts.length > 0) {
100
- output.push({
101
- type: "message",
102
- id: `msg_${this.generateId()}`,
103
- role: "assistant",
104
- status: "completed",
105
- content: [
106
- {
107
- type: "output_text",
108
- text: textParts.join(""),
109
- annotations: [],
110
- logprobs: null,
111
- },
112
- ],
113
- });
148
+ if (messageItem) {
149
+ messageItem.content[0].text = textParts.join("");
150
+ messageItem.content[0].annotations = annotations;
114
151
  }
115
152
  if (output.length === 0) {
116
153
  output.push({
@@ -130,6 +167,10 @@ class ResponsesToMessagesConverter {
130
167
  }
131
168
  const status = this.stopReasonToStatus(message.stop_reason, message.content);
132
169
  const usage = message.usage;
170
+ // Responses input_tokens is inclusive of cached tokens (cached ⊆ input), but Anthropic's
171
+ // input_tokens counts only uncached tokens, with cache read/creation as separate buckets.
172
+ const cacheRead = usage.cache_read_input_tokens ?? 0;
173
+ const totalInputTokens = usage.input_tokens + cacheRead + (usage.cache_creation_input_tokens ?? 0);
133
174
  return {
134
175
  id: message.id,
135
176
  object: "response",
@@ -137,7 +178,10 @@ class ResponsesToMessagesConverter {
137
178
  model: message.model,
138
179
  output,
139
180
  status,
140
- error: null,
181
+ // refusal → status "failed"; surface an error so clients don't read it as a normal completion.
182
+ error: status === "failed"
183
+ ? { code: "content_filter", message: "Content refused by the model." }
184
+ : null,
141
185
  incomplete_details: status === "incomplete" ? { reason: "max_output_tokens" } : null,
142
186
  instructions: null,
143
187
  metadata: {},
@@ -153,11 +197,11 @@ class ResponsesToMessagesConverter {
153
197
  truncation: null,
154
198
  user: undefined,
155
199
  usage: {
156
- input_tokens: usage.input_tokens,
200
+ input_tokens: totalInputTokens,
157
201
  output_tokens: usage.output_tokens,
158
- total_tokens: usage.input_tokens + usage.output_tokens,
202
+ total_tokens: totalInputTokens + usage.output_tokens,
159
203
  input_tokens_details: {
160
- cached_tokens: usage.cache_read_input_tokens ?? 0,
204
+ cached_tokens: cacheRead,
161
205
  },
162
206
  output_tokens_details: {
163
207
  reasoning_tokens: 0,
@@ -167,12 +211,38 @@ class ResponsesToMessagesConverter {
167
211
  }
168
212
  // --- Stream conversion (Messages → Responses, backward) ---
169
213
  async *convertStream(stream) {
170
- for await (const event of stream) {
171
- const events = this.convertStreamEvent(event);
172
- for (const e of events) {
173
- yield e;
214
+ try {
215
+ for await (const event of stream) {
216
+ const events = this.convertStreamEvent(event);
217
+ for (const e of events) {
218
+ yield e;
219
+ }
174
220
  }
175
221
  }
222
+ catch (err) {
223
+ // Only Anthropic API errors are converted to OpenAI-style failure events;
224
+ // unexpected errors (programming bugs, network layer, etc.) propagate.
225
+ if (!(err instanceof sdk_1.APIError)) {
226
+ throw err;
227
+ }
228
+ const message = err.message;
229
+ const code = err.status === 429 ? "rate_limit_exceeded" : "server_error";
230
+ const resp = this.makeSkeletonResponse();
231
+ resp.status = "failed";
232
+ resp.error = { code, message };
233
+ yield {
234
+ type: "response.failed",
235
+ response: resp,
236
+ sequence_number: this.streamState.seq++,
237
+ };
238
+ yield {
239
+ type: "error",
240
+ code,
241
+ message,
242
+ param: null,
243
+ sequence_number: this.streamState.seq++,
244
+ };
245
+ }
176
246
  }
177
247
  convertStreamEvent(event) {
178
248
  const state = this.streamState;
@@ -201,37 +271,87 @@ class ResponsesToMessagesConverter {
201
271
  case "content_block_start": {
202
272
  const block = event.content_block;
203
273
  if (block.type === "thinking") {
204
- state.reasoningStarted = true;
274
+ state.currentBlockType = "thinking";
275
+ const reasoningItemId = `rs_${this.generateId()}`;
276
+ state.reasoningItemId = reasoningItemId;
277
+ state.reasoningOutputIndex = state.nextOutputIndex++;
278
+ // Reset per-item so done events don't carry text from prior reasoning items.
279
+ state.reasoningText = "";
205
280
  events.push({
206
281
  type: "response.output_item.added",
207
282
  item: {
208
283
  type: "reasoning",
209
- id: `rs_${this.generateId()}`,
284
+ id: reasoningItemId,
210
285
  summary: [],
211
286
  },
212
- output_index: state.outputIndex,
287
+ output_index: state.reasoningOutputIndex,
213
288
  sequence_number: state.seq++,
214
289
  });
215
290
  events.push({
216
291
  type: "response.reasoning_summary_part.added",
217
- item_id: `rs_${this.generateId()}`,
218
- output_index: state.outputIndex,
292
+ item_id: reasoningItemId,
293
+ output_index: state.reasoningOutputIndex,
219
294
  summary_index: 0,
220
295
  part: { type: "summary_text", text: "" },
221
296
  sequence_number: state.seq++,
222
297
  });
223
298
  }
299
+ else if (block.type === "server_tool_use" && block.name === "web_search") {
300
+ state.webSearchCallCount++;
301
+ const wsOutputIndex = state.nextOutputIndex++;
302
+ const wsItemId = `ws_${this.generateId()}`;
303
+ // web_search_tool_result arrives as a separate later block; key by tool_use_id to pair them.
304
+ state.webSearchByToolUseId.set(block.id, {
305
+ itemId: wsItemId,
306
+ outputIndex: wsOutputIndex,
307
+ query: "",
308
+ done: false,
309
+ });
310
+ state.webSearchToolUseIdByBlockIndex.set(event.index, block.id);
311
+ state.currentBlockType = "server_tool_use_web_search";
312
+ events.push({
313
+ type: "response.output_item.added",
314
+ item: {
315
+ type: "web_search_call",
316
+ id: wsItemId,
317
+ status: "in_progress",
318
+ action: { type: "search", query: "" },
319
+ },
320
+ output_index: wsOutputIndex,
321
+ sequence_number: state.seq++,
322
+ });
323
+ events.push({
324
+ type: "response.web_search_call.in_progress",
325
+ item_id: wsItemId,
326
+ output_index: wsOutputIndex,
327
+ sequence_number: state.seq++,
328
+ });
329
+ // searching fires once when the search begins, not on every query delta.
330
+ events.push({
331
+ type: "response.web_search_call.searching",
332
+ item_id: wsItemId,
333
+ output_index: wsOutputIndex,
334
+ sequence_number: state.seq++,
335
+ });
336
+ }
224
337
  else if (block.type === "tool_use" || block.type === "server_tool_use") {
225
- if (state.toolCallCount === 0 && state.reasoningStarted) {
226
- state.outputIndex++;
227
- }
228
338
  state.toolCallCount++;
229
- const toolOutputIndex = state.outputIndex + state.toolCallCount - 1;
339
+ const toolCallItemId = `fc_${this.generateId()}`;
340
+ const toolOutputIndex = state.nextOutputIndex++;
341
+ state.toolCalls.push({
342
+ id: toolCallItemId,
343
+ call_id: block.id,
344
+ name: block.name,
345
+ arguments: "",
346
+ outputIndex: toolOutputIndex,
347
+ done: false,
348
+ });
349
+ state.currentBlockType = "tool_use";
230
350
  events.push({
231
351
  type: "response.output_item.added",
232
352
  item: {
233
353
  type: "function_call",
234
- id: `fc_${this.generateId()}`,
354
+ id: toolCallItemId,
235
355
  call_id: block.id,
236
356
  name: block.name,
237
357
  arguments: "",
@@ -244,70 +364,192 @@ class ResponsesToMessagesConverter {
244
364
  else if (block.type === "text") {
245
365
  if (!state.textMessageStarted) {
246
366
  state.textMessageStarted = true;
247
- const msgOutputIndex = state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount;
367
+ const textMessageItemId = `msg_${this.generateId()}`;
368
+ state.textMessageItemId = textMessageItemId;
369
+ state.textMessageOutputIndex = state.nextOutputIndex++;
370
+ state.textBlockStartOffset = 0;
248
371
  events.push({
249
372
  type: "response.output_item.added",
250
373
  item: {
251
374
  type: "message",
252
- id: `msg_${this.generateId()}`,
375
+ id: textMessageItemId,
253
376
  role: "assistant",
254
377
  status: "in_progress",
255
378
  content: [],
256
379
  },
257
- output_index: msgOutputIndex,
380
+ output_index: state.textMessageOutputIndex,
258
381
  sequence_number: state.seq++,
259
382
  });
260
383
  events.push({
261
384
  type: "response.content_part.added",
262
- item_id: `msg_${this.generateId()}`,
263
- output_index: msgOutputIndex,
385
+ item_id: textMessageItemId,
386
+ output_index: state.textMessageOutputIndex,
264
387
  content_index: 0,
265
388
  part: { type: "output_text", text: "", annotations: [] },
266
389
  sequence_number: state.seq++,
267
390
  });
268
391
  }
392
+ else {
393
+ // Subsequent text block — its citations are relative to this block's text,
394
+ // so shift by the accumulated length of prior merged blocks.
395
+ state.textBlockStartOffset = state.textMessageText.length;
396
+ }
397
+ state.currentBlockType = "text";
269
398
  }
270
399
  else if (block.type === "web_search_tool_result") {
271
400
  state.webSearchCount++;
401
+ state.currentBlockType = "web_search_tool_result";
402
+ const entry = state.webSearchByToolUseId.get(block.tool_use_id);
403
+ if (entry && !entry.done) {
404
+ entry.done = true;
405
+ const query = this.extractWebSearchQuery(entry.query);
406
+ events.push({
407
+ type: "response.web_search_call.completed",
408
+ item_id: entry.itemId,
409
+ output_index: entry.outputIndex,
410
+ sequence_number: state.seq++,
411
+ });
412
+ const wsItem = {
413
+ type: "web_search_call",
414
+ id: entry.itemId,
415
+ status: "completed",
416
+ action: { type: "search", query },
417
+ };
418
+ events.push({
419
+ type: "response.output_item.done",
420
+ item: wsItem,
421
+ output_index: entry.outputIndex,
422
+ sequence_number: state.seq++,
423
+ });
424
+ state.outputItems.push({ index: entry.outputIndex, item: wsItem });
425
+ }
272
426
  }
273
427
  break;
274
428
  }
275
429
  case "content_block_delta": {
276
430
  const delta = event.delta;
277
431
  if (delta.type === "thinking_delta") {
432
+ state.reasoningText += delta.thinking;
278
433
  events.push({
279
434
  type: "response.reasoning_summary_text.delta",
280
- item_id: `rs_${this.generateId()}`,
281
- output_index: state.outputIndex,
435
+ item_id: state.reasoningItemId,
436
+ output_index: state.reasoningOutputIndex,
282
437
  summary_index: 0,
283
438
  delta: delta.thinking,
284
439
  sequence_number: state.seq++,
285
440
  });
286
441
  }
287
442
  else if (delta.type === "input_json_delta") {
288
- const toolOutputIndex = state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount - 1;
289
- events.push({
290
- type: "response.function_call_arguments.delta",
291
- item_id: `fc_${this.generateId()}`,
292
- output_index: toolOutputIndex,
293
- delta: delta.partial_json,
294
- sequence_number: state.seq++,
295
- });
443
+ // Same delta type carries tool_use args and web_search query; route by current block.
444
+ if (state.currentBlockType === "server_tool_use_web_search") {
445
+ const toolUseId = state.webSearchToolUseIdByBlockIndex.get(event.index);
446
+ const entry = toolUseId ? state.webSearchByToolUseId.get(toolUseId) : undefined;
447
+ if (entry) {
448
+ entry.query += delta.partial_json;
449
+ }
450
+ // searching already emitted at content_block_start; deltas only accumulate query.
451
+ }
452
+ else {
453
+ const lastToolCall = state.toolCalls[state.toolCalls.length - 1];
454
+ if (lastToolCall) {
455
+ lastToolCall.arguments += delta.partial_json;
456
+ events.push({
457
+ type: "response.function_call_arguments.delta",
458
+ item_id: lastToolCall.id,
459
+ output_index: lastToolCall.outputIndex,
460
+ delta: delta.partial_json,
461
+ sequence_number: state.seq++,
462
+ });
463
+ }
464
+ }
296
465
  }
297
466
  else if (delta.type === "text_delta") {
298
- const msgOutputIndex = state.outputIndex + (state.reasoningStarted ? 1 : 0) + state.toolCallCount;
467
+ state.textMessageText += delta.text;
299
468
  events.push({
300
469
  type: "response.output_text.delta",
301
- item_id: `msg_${this.generateId()}`,
302
- output_index: msgOutputIndex,
470
+ item_id: state.textMessageItemId,
471
+ output_index: state.textMessageOutputIndex,
303
472
  content_index: 0,
304
473
  delta: delta.text,
305
474
  sequence_number: state.seq++,
306
475
  });
307
476
  }
477
+ else if (delta.type === "citations_delta") {
478
+ // Anthropic streams citations as deltas; collect and emit on the message's done events.
479
+ const citation = delta.citation;
480
+ if (citation) {
481
+ state.textAnnotations.push(this.citationToAnnotation(citation, state.textBlockStartOffset));
482
+ }
483
+ }
308
484
  break;
309
485
  }
310
486
  case "content_block_stop": {
487
+ const finishedType = state.currentBlockType;
488
+ state.currentBlockType = "";
489
+ if (finishedType === "thinking") {
490
+ events.push({
491
+ type: "response.reasoning_summary_text.done",
492
+ item_id: state.reasoningItemId,
493
+ output_index: state.reasoningOutputIndex,
494
+ summary_index: 0,
495
+ text: state.reasoningText,
496
+ sequence_number: state.seq++,
497
+ });
498
+ events.push({
499
+ type: "response.reasoning_summary_part.done",
500
+ item_id: state.reasoningItemId,
501
+ output_index: state.reasoningOutputIndex,
502
+ summary_index: 0,
503
+ part: { type: "summary_text", text: state.reasoningText },
504
+ sequence_number: state.seq++,
505
+ });
506
+ events.push({
507
+ type: "response.output_item.done",
508
+ item: {
509
+ type: "reasoning",
510
+ id: state.reasoningItemId,
511
+ summary: [{ type: "summary_text", text: state.reasoningText }],
512
+ },
513
+ output_index: state.reasoningOutputIndex,
514
+ sequence_number: state.seq++,
515
+ });
516
+ state.outputItems.push({
517
+ index: state.reasoningOutputIndex,
518
+ item: {
519
+ type: "reasoning",
520
+ id: state.reasoningItemId,
521
+ summary: [{ type: "summary_text", text: state.reasoningText }],
522
+ },
523
+ });
524
+ }
525
+ else if (finishedType === "tool_use") {
526
+ const lastToolCall = state.toolCalls[state.toolCalls.length - 1];
527
+ if (lastToolCall) {
528
+ lastToolCall.done = true;
529
+ events.push({
530
+ type: "response.function_call_arguments.done",
531
+ item_id: lastToolCall.id,
532
+ output_index: lastToolCall.outputIndex,
533
+ arguments: lastToolCall.arguments,
534
+ sequence_number: state.seq++,
535
+ });
536
+ const toolItem = {
537
+ type: "function_call",
538
+ id: lastToolCall.id,
539
+ call_id: lastToolCall.call_id,
540
+ name: lastToolCall.name,
541
+ arguments: lastToolCall.arguments,
542
+ status: "completed",
543
+ };
544
+ events.push({
545
+ type: "response.output_item.done",
546
+ item: toolItem,
547
+ output_index: lastToolCall.outputIndex,
548
+ sequence_number: state.seq++,
549
+ });
550
+ state.outputItems.push({ index: lastToolCall.outputIndex, item: toolItem });
551
+ }
552
+ }
311
553
  break;
312
554
  }
313
555
  case "message_delta": {
@@ -321,13 +563,20 @@ class ResponsesToMessagesConverter {
321
563
  break;
322
564
  }
323
565
  case "message_stop": {
324
- const status = this.stopReasonToStatus(state.stopReason, undefined);
566
+ // Pass a synthetic content array when any tool_call completed its block, so the
567
+ // streaming path matches non-streaming behavior (max_tokens + complete tool_use
568
+ // → "completed", not "incomplete").
569
+ const hasCompleteToolCall = state.toolCalls.some(t => t.done);
570
+ const status = this.stopReasonToStatus(state.stopReason, hasCompleteToolCall ? [{ type: "tool_use" }] : undefined);
325
571
  const resp = this.makeSkeletonResponse();
326
572
  resp.status = status;
573
+ // Responses input_tokens is inclusive of cached tokens (cached ⊆ input), but Anthropic's
574
+ // input_tokens counts only uncached tokens, with cache read/creation as separate buckets.
575
+ const totalInputTokens = state.inputTokens + state.cacheReadTokens + state.cacheCreationTokens;
327
576
  resp.usage = {
328
- input_tokens: state.inputTokens,
577
+ input_tokens: totalInputTokens,
329
578
  output_tokens: state.outputTokens,
330
- total_tokens: state.inputTokens + state.outputTokens,
579
+ total_tokens: totalInputTokens + state.outputTokens,
331
580
  input_tokens_details: {
332
581
  cached_tokens: state.cacheReadTokens,
333
582
  },
@@ -335,6 +584,98 @@ class ResponsesToMessagesConverter {
335
584
  reasoning_tokens: 0,
336
585
  },
337
586
  };
587
+ // Text may span multiple Anthropic blocks; emit the message's done events once at the end.
588
+ if (state.textMessageStarted) {
589
+ events.push({
590
+ type: "response.output_text.done",
591
+ item_id: state.textMessageItemId,
592
+ output_index: state.textMessageOutputIndex,
593
+ content_index: 0,
594
+ text: state.textMessageText,
595
+ sequence_number: state.seq++,
596
+ });
597
+ events.push({
598
+ type: "response.content_part.done",
599
+ item_id: state.textMessageItemId,
600
+ output_index: state.textMessageOutputIndex,
601
+ content_index: 0,
602
+ part: {
603
+ type: "output_text",
604
+ text: state.textMessageText,
605
+ annotations: state.textAnnotations,
606
+ },
607
+ sequence_number: state.seq++,
608
+ });
609
+ const messageItem = {
610
+ type: "message",
611
+ id: state.textMessageItemId,
612
+ role: "assistant",
613
+ status: "completed",
614
+ content: [
615
+ {
616
+ type: "output_text",
617
+ text: state.textMessageText,
618
+ annotations: state.textAnnotations,
619
+ logprobs: null,
620
+ },
621
+ ],
622
+ };
623
+ events.push({
624
+ type: "response.output_item.done",
625
+ item: messageItem,
626
+ output_index: state.textMessageOutputIndex,
627
+ sequence_number: state.seq++,
628
+ });
629
+ state.outputItems.push({ index: state.textMessageOutputIndex, item: messageItem });
630
+ }
631
+ // Truncated tool_calls (no content_block_stop) still belong in output with incomplete status.
632
+ for (const tc of state.toolCalls) {
633
+ if (!tc.done) {
634
+ state.outputItems.push({
635
+ index: tc.outputIndex,
636
+ item: {
637
+ type: "function_call",
638
+ id: tc.id,
639
+ call_id: tc.call_id,
640
+ name: tc.name,
641
+ arguments: tc.arguments,
642
+ status: "incomplete",
643
+ },
644
+ });
645
+ }
646
+ }
647
+ // Truncated web_search_calls (web_search_tool_result never arrived) still need a
648
+ // completed + output_item.done so clients see the item finalize.
649
+ for (const entry of state.webSearchByToolUseId.values()) {
650
+ if (entry.done)
651
+ continue;
652
+ entry.done = true;
653
+ const query = this.extractWebSearchQuery(entry.query);
654
+ const wsStatus = status === "incomplete" ? "incomplete" : "completed";
655
+ events.push({
656
+ type: "response.web_search_call.completed",
657
+ item_id: entry.itemId,
658
+ output_index: entry.outputIndex,
659
+ sequence_number: state.seq++,
660
+ });
661
+ const wsItem = {
662
+ type: "web_search_call",
663
+ id: entry.itemId,
664
+ status: wsStatus,
665
+ action: { type: "search", query },
666
+ };
667
+ events.push({
668
+ type: "response.output_item.done",
669
+ item: wsItem,
670
+ output_index: entry.outputIndex,
671
+ sequence_number: state.seq++,
672
+ });
673
+ state.outputItems.push({ index: entry.outputIndex, item: wsItem });
674
+ }
675
+ // Items accumulate in completion order, not output order (e.g. text finalizes here,
676
+ // after an earlier-emitted tool_use with a higher index). Sort by index to match
677
+ // the output_index sequence clients saw during streaming.
678
+ resp.output = [...state.outputItems].sort((a, b) => a.index - b.index).map(o => o.item);
338
679
  if (status === "incomplete") {
339
680
  events.push({
340
681
  type: "response.incomplete",
@@ -342,6 +683,24 @@ class ResponsesToMessagesConverter {
342
683
  sequence_number: state.seq++,
343
684
  });
344
685
  }
686
+ else if (status === "failed") {
687
+ // refusal → mirror the catch block's failure shape so clients see a terminal
688
+ // response.failed + error instead of a response.completed carrying status "failed".
689
+ const error = { code: "content_filter", message: "Content refused by the model." };
690
+ resp.error = error;
691
+ events.push({
692
+ type: "response.failed",
693
+ response: resp,
694
+ sequence_number: state.seq++,
695
+ });
696
+ events.push({
697
+ type: "error",
698
+ code: error.code,
699
+ message: error.message,
700
+ param: null,
701
+ sequence_number: state.seq++,
702
+ });
703
+ }
345
704
  else {
346
705
  events.push({
347
706
  type: "response.completed",
@@ -363,41 +722,44 @@ class ResponsesToMessagesConverter {
363
722
  });
364
723
  return;
365
724
  }
366
- const pendingToolUses = [];
367
- const flushToolUses = () => {
368
- if (pendingToolUses.length > 0) {
725
+ // Buffer assistant text and tool_use blocks together so a single assistant turn
726
+ // (text + following function_calls) lands in one message, as Anthropic requires.
727
+ const pendingAssistantBlocks = [];
728
+ const flushAssistant = () => {
729
+ if (pendingAssistantBlocks.length > 0) {
369
730
  messages.push({
370
731
  role: "assistant",
371
- content: [...pendingToolUses],
732
+ content: [...pendingAssistantBlocks],
372
733
  });
373
- pendingToolUses.length = 0;
734
+ pendingAssistantBlocks.length = 0;
374
735
  }
375
736
  };
376
737
  for (const item of input) {
377
738
  const typed = item;
378
- if (typed.type === "message") {
379
- flushToolUses();
739
+ if (typed.type === "message" || !typed.type) {
380
740
  if (typed.role === "system" || typed.role === "developer") {
741
+ flushAssistant();
381
742
  const text = this.extractText(typed.content);
382
743
  if (text)
383
744
  systemBlocks.push(text);
384
745
  }
385
746
  else if (typed.role === "user") {
747
+ flushAssistant();
386
748
  const content = this.convertInputContent(typed.content);
387
749
  messages.push({ role: "user", content });
388
750
  }
389
751
  else if (typed.role === "assistant") {
390
- const blocks = [];
391
- if (Array.isArray(typed.content)) {
752
+ // Append to pending; may merge with following function_call tool_use blocks.
753
+ if (typeof typed.content === "string") {
754
+ pendingAssistantBlocks.push({ type: "text", text: typed.content });
755
+ }
756
+ else if (Array.isArray(typed.content)) {
392
757
  for (const part of typed.content) {
393
758
  if (part.type === "output_text") {
394
- blocks.push({ type: "text", text: part.text });
759
+ pendingAssistantBlocks.push({ type: "text", text: part.text });
395
760
  }
396
761
  }
397
762
  }
398
- if (blocks.length > 0) {
399
- messages.push({ role: "assistant", content: blocks });
400
- }
401
763
  }
402
764
  }
403
765
  else if (typed.type === "function_call") {
@@ -408,7 +770,7 @@ class ResponsesToMessagesConverter {
408
770
  catch {
409
771
  parsedInput = {};
410
772
  }
411
- pendingToolUses.push({
773
+ pendingAssistantBlocks.push({
412
774
  type: "tool_use",
413
775
  id: typed.call_id,
414
776
  name: typed.name,
@@ -416,12 +778,19 @@ class ResponsesToMessagesConverter {
416
778
  });
417
779
  }
418
780
  else if (typed.type === "function_call_output") {
419
- flushToolUses();
781
+ flushAssistant();
782
+ const output = typed.output;
783
+ // Array content-part outputs are lossy: serialized as raw JSON rather than
784
+ // unwrapping input_text/image/file parts. Acceptable since Anthropic tool_result
785
+ // text expects a string and array outputs are rare on this path.
786
+ const outputText = typeof output === "string" ? output : output == null ? "" : JSON.stringify(output);
420
787
  const toolResult = {
421
788
  type: "tool_result",
422
789
  tool_use_id: typed.call_id,
423
- content: [{ type: "text", text: typed.output ?? "" }],
790
+ content: [{ type: "text", text: outputText }],
424
791
  };
792
+ // Anthropic requires parallel tool_results grouped in one user message,
793
+ // so append to the prior user message if it already holds tool_results.
425
794
  const last = messages[messages.length - 1];
426
795
  if (last && last.role === "user" && Array.isArray(last.content)) {
427
796
  const lastContent = last.content;
@@ -433,20 +802,21 @@ class ResponsesToMessagesConverter {
433
802
  messages.push({ role: "user", content: [toolResult] });
434
803
  }
435
804
  else if ("role" in typed && "content" in typed && typeof typed.content === "string") {
436
- flushToolUses();
437
805
  const role = typed.role;
438
806
  if (role === "system" || role === "developer") {
807
+ flushAssistant();
439
808
  systemBlocks.push(typed.content);
440
809
  }
441
810
  else if (role === "user") {
811
+ flushAssistant();
442
812
  messages.push({ role: "user", content: [{ type: "text", text: typed.content }] });
443
813
  }
444
814
  else if (role === "assistant") {
445
- messages.push({ role: "assistant", content: [{ type: "text", text: typed.content }] });
815
+ pendingAssistantBlocks.push({ type: "text", text: typed.content });
446
816
  }
447
817
  }
448
818
  }
449
- flushToolUses();
819
+ flushAssistant();
450
820
  }
451
821
  extractText(content) {
452
822
  if (typeof content === "string")
@@ -535,7 +905,7 @@ class ResponsesToMessagesConverter {
535
905
  });
536
906
  }
537
907
  else if (this.isWebSearch(tt)) {
538
- result.push({ type: "web_search_20250305" });
908
+ result.push({ type: "web_search_20250305", name: "web_search" });
539
909
  }
540
910
  }
541
911
  return result;
@@ -556,6 +926,7 @@ class ResponsesToMessagesConverter {
556
926
  ? { type: "auto", disable_parallel_tool_use: true }
557
927
  : { type: "auto" };
558
928
  case "required":
929
+ // Anthropic's name for "required" is "any".
559
930
  return disableParallel
560
931
  ? { type: "any", disable_parallel_tool_use: true }
561
932
  : { type: "any" };
@@ -588,6 +959,7 @@ class ResponsesToMessagesConverter {
588
959
  }
589
960
  // --- Private: response helpers ---
590
961
  stopReasonToStatus(stopReason, content) {
962
+ // Any tool_use in content means the turn ended for tool dispatch, not incompleteness.
591
963
  if (content) {
592
964
  const hasToolCall = content.some(b => b.type === "tool_use" || b.type === "server_tool_use");
593
965
  if (hasToolCall)
@@ -609,16 +981,60 @@ class ResponsesToMessagesConverter {
609
981
  generateId() {
610
982
  return Math.random().toString(36).substring(2, 15);
611
983
  }
984
+ // Parses the query from accumulated web_search input_json_delta. Handles both complete
985
+ // JSON (`{"query":"x"}`) and partial JSON truncated by max_tokens (`{"query":"lat`).
986
+ extractWebSearchQuery(raw) {
987
+ if (!raw)
988
+ return "";
989
+ try {
990
+ const parsed = JSON.parse(raw);
991
+ if (typeof parsed === "object" && parsed !== null && typeof parsed.query === "string") {
992
+ return parsed.query;
993
+ }
994
+ }
995
+ catch {
996
+ // partial JSON; fall through to regex
997
+ }
998
+ const match = raw.match(/"query"\s*:\s*"((?:[^"\\]|\\.)*)/);
999
+ return match ? match[1].replace(/\\"/g, '"').replace(/\\\\/g, "\\") : "";
1000
+ }
1001
+ // Maps an Anthropic citation to an OpenAI output_text annotation. Anthropic's
1002
+ // web_search_result citation maps to OpenAI's url_citation; indices are shifted by
1003
+ // `offset` when merging multiple text blocks into one output_text.
1004
+ citationToAnnotation(citation, offset = 0) {
1005
+ const start = (citation.start_index ?? 0) + offset;
1006
+ const end = (citation.end_index ?? 0) + offset;
1007
+ return {
1008
+ type: "url_citation",
1009
+ start_index: start,
1010
+ end_index: end,
1011
+ url: citation.url ?? "",
1012
+ title: citation.title ?? "",
1013
+ };
1014
+ }
612
1015
  // --- Private: stream helpers ---
613
1016
  createStreamState() {
614
1017
  return {
615
1018
  id: "",
616
1019
  model: "",
617
1020
  seq: 0,
618
- outputIndex: 0,
619
- reasoningStarted: false,
1021
+ nextOutputIndex: 0,
1022
+ reasoningItemId: "",
1023
+ reasoningOutputIndex: 0,
1024
+ reasoningText: "",
620
1025
  toolCallCount: 0,
1026
+ toolCalls: [],
1027
+ webSearchCallCount: 0,
1028
+ webSearchByToolUseId: new Map(),
1029
+ webSearchToolUseIdByBlockIndex: new Map(),
1030
+ currentBlockType: "",
621
1031
  textMessageStarted: false,
1032
+ textMessageItemId: "",
1033
+ textMessageOutputIndex: 0,
1034
+ textMessageText: "",
1035
+ textAnnotations: [],
1036
+ textBlockStartOffset: 0,
1037
+ outputItems: [],
622
1038
  inputTokens: 0,
623
1039
  outputTokens: 0,
624
1040
  cacheReadTokens: 0,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenmux/rosetta-ai",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Universal translator between AI provider protocols",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",