@ai-sdk/anthropic 2.0.111 → 2.0.113

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.
@@ -10,7 +10,8 @@ import {
10
10
  generateId,
11
11
  parseProviderOptions as parseProviderOptions2,
12
12
  postJsonToApi,
13
- resolve
13
+ resolve,
14
+ secureJsonParse as secureJsonParse2
14
15
  } from "@ai-sdk/provider-utils";
15
16
 
16
17
  // src/anthropic-error.ts
@@ -1027,10 +1028,17 @@ var computerToolset_20260801Members = [
1027
1028
  "hold_key",
1028
1029
  "wait"
1029
1030
  ];
1030
- var computerToolset_20260801InputSchema = lazySchema4(
1031
+ var computerToolset_20260801InputSchema = (configs) => lazySchema4(
1031
1032
  () => zodSchema4(
1032
1033
  z4.object({
1033
- action: z4.enum(computerToolset_20260801Members),
1034
+ action: z4.enum(
1035
+ computerToolset_20260801Members.filter(
1036
+ (member) => {
1037
+ var _a;
1038
+ return ((_a = configs == null ? void 0 : configs[member]) == null ? void 0 : _a.enabled) !== false;
1039
+ }
1040
+ )
1041
+ ),
1034
1042
  coordinate: z4.tuple([z4.number().int(), z4.number().int()]).optional(),
1035
1043
  duration: z4.number().optional(),
1036
1044
  region: z4.tuple([
@@ -1060,10 +1068,14 @@ var computerToolset_20260801ArgsSchema = lazySchema4(
1060
1068
  })
1061
1069
  )
1062
1070
  );
1063
- var computerToolset_20260801 = createProviderDefinedToolFactory({
1071
+ var factory = createProviderDefinedToolFactory({
1064
1072
  id: "anthropic.computer_toolset_20260801",
1065
1073
  name: "computer",
1066
- inputSchema: computerToolset_20260801InputSchema
1074
+ inputSchema: computerToolset_20260801InputSchema()
1075
+ });
1076
+ var computerToolset_20260801 = (args) => ({
1077
+ ...factory(args),
1078
+ inputSchema: computerToolset_20260801InputSchema(args.configs)
1067
1079
  });
1068
1080
 
1069
1081
  // src/tool/text-editor_20250728.ts
@@ -1093,13 +1105,13 @@ var textEditor_20250728InputSchema = lazySchema5(
1093
1105
  })
1094
1106
  )
1095
1107
  );
1096
- var factory = createProviderDefinedToolFactory2({
1108
+ var factory2 = createProviderDefinedToolFactory2({
1097
1109
  id: "anthropic.text_editor_20250728",
1098
1110
  name: "str_replace_based_edit_tool",
1099
1111
  inputSchema: textEditor_20250728InputSchema
1100
1112
  });
1101
1113
  var textEditor_20250728 = (args = {}) => {
1102
- return factory(args);
1114
+ return factory2(args);
1103
1115
  };
1104
1116
 
1105
1117
  // src/tool/web-search_20250305.ts
@@ -1145,14 +1157,14 @@ var webSearch_20250305InputSchema = lazySchema6(
1145
1157
  })
1146
1158
  )
1147
1159
  );
1148
- var factory2 = createProviderDefinedToolFactoryWithOutputSchema({
1160
+ var factory3 = createProviderDefinedToolFactoryWithOutputSchema({
1149
1161
  id: "anthropic.web_search_20250305",
1150
1162
  name: "web_search",
1151
1163
  inputSchema: webSearch_20250305InputSchema,
1152
1164
  outputSchema: webSearch_20250305OutputSchema
1153
1165
  });
1154
1166
  var webSearch_20250305 = (args = {}) => {
1155
- return factory2(args);
1167
+ return factory3(args);
1156
1168
  };
1157
1169
 
1158
1170
  // src/tool/web-fetch-20250910.ts
@@ -1206,14 +1218,14 @@ var webFetch_20250910InputSchema = lazySchema7(
1206
1218
  })
1207
1219
  )
1208
1220
  );
1209
- var factory3 = createProviderDefinedToolFactoryWithOutputSchema2({
1221
+ var factory4 = createProviderDefinedToolFactoryWithOutputSchema2({
1210
1222
  id: "anthropic.web_fetch_20250910",
1211
1223
  name: "web_fetch",
1212
1224
  inputSchema: webFetch_20250910InputSchema,
1213
1225
  outputSchema: webFetch_20250910OutputSchema
1214
1226
  });
1215
1227
  var webFetch_20250910 = (args = {}) => {
1216
- return factory3(args);
1228
+ return factory4(args);
1217
1229
  };
1218
1230
 
1219
1231
  // src/anthropic-prepare-tools.ts
@@ -1531,6 +1543,8 @@ import {
1531
1543
  UnsupportedFunctionalityError as UnsupportedFunctionalityError2
1532
1544
  } from "@ai-sdk/provider";
1533
1545
  import {
1546
+ stringifyWithBigIntAndCycles,
1547
+ secureJsonParse,
1534
1548
  convertToBase64,
1535
1549
  parseProviderOptions,
1536
1550
  validateTypes as validateTypes2
@@ -1560,14 +1574,14 @@ var codeExecution_20250522InputSchema = lazySchema8(
1560
1574
  })
1561
1575
  )
1562
1576
  );
1563
- var factory4 = createProviderDefinedToolFactoryWithOutputSchema3({
1577
+ var factory5 = createProviderDefinedToolFactoryWithOutputSchema3({
1564
1578
  id: "anthropic.code_execution_20250522",
1565
1579
  name: "code_execution",
1566
1580
  inputSchema: codeExecution_20250522InputSchema,
1567
1581
  outputSchema: codeExecution_20250522OutputSchema
1568
1582
  });
1569
1583
  var codeExecution_20250522 = (args = {}) => {
1570
- return factory4(args);
1584
+ return factory5(args);
1571
1585
  };
1572
1586
 
1573
1587
  // src/tool/code-execution_20250825.ts
@@ -1653,14 +1667,14 @@ var codeExecution_20250825InputSchema = lazySchema9(
1653
1667
  ])
1654
1668
  )
1655
1669
  );
1656
- var factory5 = createProviderDefinedToolFactoryWithOutputSchema4({
1670
+ var factory6 = createProviderDefinedToolFactoryWithOutputSchema4({
1657
1671
  id: "anthropic.code_execution_20250825",
1658
1672
  name: "code_execution",
1659
1673
  inputSchema: codeExecution_20250825InputSchema,
1660
1674
  outputSchema: codeExecution_20250825OutputSchema
1661
1675
  });
1662
1676
  var codeExecution_20250825 = (args = {}) => {
1663
- return factory5(args);
1677
+ return factory6(args);
1664
1678
  };
1665
1679
 
1666
1680
  // src/convert-to-anthropic-messages-prompt.ts
@@ -1955,7 +1969,7 @@ async function convertToAnthropicMessagesPrompt({
1955
1969
  case "json":
1956
1970
  case "error-json":
1957
1971
  default:
1958
- contentValue = JSON.stringify(output.value);
1972
+ contentValue = stringifyWithBigIntAndCycles(output.value);
1959
1973
  break;
1960
1974
  }
1961
1975
  const toolsetName = getAnthropicToolsetName({
@@ -2129,7 +2143,7 @@ async function convertToAnthropicMessagesPrompt({
2129
2143
  type: "tool_use",
2130
2144
  id: part.toolCallId,
2131
2145
  name: part.toolName,
2132
- input: part.input,
2146
+ input: parseToolCallInput(part.input),
2133
2147
  cache_control: cacheControl
2134
2148
  });
2135
2149
  break;
@@ -2364,6 +2378,18 @@ function getAnthropicToolsetName({
2364
2378
  const fromMetadata = (_a = providerOptions == null ? void 0 : providerOptions.anthropic) == null ? void 0 : _a.toolsetName;
2365
2379
  return typeof fromMetadata === "string" ? fromMetadata : void 0;
2366
2380
  }
2381
+ function parseToolCallInput(input) {
2382
+ if (typeof input === "string") {
2383
+ try {
2384
+ const parsed = secureJsonParse(input);
2385
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
2386
+ return parsed;
2387
+ }
2388
+ } catch (e) {
2389
+ }
2390
+ }
2391
+ return input;
2392
+ }
2367
2393
 
2368
2394
  // src/map-anthropic-stop-reason.ts
2369
2395
  function mapAnthropicStopReason({
@@ -2534,7 +2560,204 @@ function isPlainObject(value) {
2534
2560
  return typeof value === "object" && value !== null && !Array.isArray(value);
2535
2561
  }
2536
2562
 
2563
+ // src/has-circular-schema-reference.ts
2564
+ var SCHEMA_MAP_KEYWORDS = /* @__PURE__ */ new Set([
2565
+ "dependentSchemas",
2566
+ "patternProperties",
2567
+ "properties"
2568
+ ]);
2569
+ var DATA_KEYWORDS = /* @__PURE__ */ new Set(["const", "default", "enum", "examples"]);
2570
+ function hasCircularSchemaReference(schema) {
2571
+ const visiting = /* @__PURE__ */ new Set();
2572
+ const visited = /* @__PURE__ */ new Set();
2573
+ const visit = (pointer) => {
2574
+ if (visiting.has(pointer)) {
2575
+ return true;
2576
+ }
2577
+ if (visited.has(pointer)) {
2578
+ return false;
2579
+ }
2580
+ const target = resolveSchemaPointer(schema, pointer);
2581
+ if (target === void 0) {
2582
+ return false;
2583
+ }
2584
+ visiting.add(pointer);
2585
+ const isCircular = collectLocalRefs(target).some(visit);
2586
+ visiting.delete(pointer);
2587
+ visited.add(pointer);
2588
+ return isCircular;
2589
+ };
2590
+ return visit("#");
2591
+ }
2592
+ function collectLocalRefs(node, refs = []) {
2593
+ if (Array.isArray(node)) {
2594
+ for (const item of node) {
2595
+ collectLocalRefs(item, refs);
2596
+ }
2597
+ return refs;
2598
+ }
2599
+ if (!isRecord(node)) {
2600
+ return refs;
2601
+ }
2602
+ for (const [key, value] of Object.entries(node)) {
2603
+ if (key === "$ref") {
2604
+ if (typeof value === "string" && value.startsWith("#")) {
2605
+ refs.push(value);
2606
+ }
2607
+ } else if (SCHEMA_MAP_KEYWORDS.has(key) && isRecord(value)) {
2608
+ for (const subschema of Object.values(value)) {
2609
+ collectLocalRefs(subschema, refs);
2610
+ }
2611
+ } else if (
2612
+ // definitions are only reached through a `$ref`:
2613
+ key !== "$defs" && key !== "definitions" && !DATA_KEYWORDS.has(key)
2614
+ ) {
2615
+ collectLocalRefs(value, refs);
2616
+ }
2617
+ }
2618
+ return refs;
2619
+ }
2620
+ function resolveSchemaPointer(schema, pointer) {
2621
+ if (pointer === "#") {
2622
+ return schema;
2623
+ }
2624
+ if (!pointer.startsWith("#/")) {
2625
+ return void 0;
2626
+ }
2627
+ let decodedPointer;
2628
+ try {
2629
+ decodedPointer = decodeURIComponent(pointer.slice(2));
2630
+ } catch (e) {
2631
+ return void 0;
2632
+ }
2633
+ let current = schema;
2634
+ for (const rawSegment of decodedPointer.split("/")) {
2635
+ const segment = rawSegment.replace(/~1/g, "/").replace(/~0/g, "~");
2636
+ if (Array.isArray(current)) {
2637
+ current = current[Number(segment)];
2638
+ } else if (isRecord(current)) {
2639
+ current = current[segment];
2640
+ } else {
2641
+ return void 0;
2642
+ }
2643
+ }
2644
+ return current;
2645
+ }
2646
+ function isRecord(value) {
2647
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2648
+ }
2649
+
2650
+ // src/supports-native-structured-output-schema.ts
2651
+ var MAX_OPTIONAL_PROPERTIES = 10;
2652
+ var SUBSCHEMA_KEYWORDS = [
2653
+ "additionalProperties",
2654
+ "contains",
2655
+ "else",
2656
+ "if",
2657
+ "items",
2658
+ "not",
2659
+ "then"
2660
+ ];
2661
+ var SUBSCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems"];
2662
+ var SUBSCHEMA_MAP_KEYWORDS = [
2663
+ "dependentSchemas",
2664
+ "patternProperties",
2665
+ "properties"
2666
+ ];
2667
+ function supportsNativeStructuredOutputSchema(schema) {
2668
+ if (schema.$ref != null || hasCircularSchemaReference(schema)) {
2669
+ return false;
2670
+ }
2671
+ const { optionalProperties, hasOpenObject } = getSchemaStats(
2672
+ schema,
2673
+ schema,
2674
+ /* @__PURE__ */ new Map()
2675
+ );
2676
+ return !hasOpenObject && optionalProperties <= MAX_OPTIONAL_PROPERTIES;
2677
+ }
2678
+ function getSchemaStats(node, root, refStats) {
2679
+ const stats = { optionalProperties: 0, hasOpenObject: false };
2680
+ if (!isRecord(node)) {
2681
+ return stats;
2682
+ }
2683
+ const add = (child) => {
2684
+ const childStats = getSchemaStats(child, root, refStats);
2685
+ stats.optionalProperties += childStats.optionalProperties;
2686
+ stats.hasOpenObject || (stats.hasOpenObject = childStats.hasOpenObject);
2687
+ };
2688
+ if (typeof node.$ref === "string" && node.$ref.startsWith("#")) {
2689
+ let resolved = refStats.get(node.$ref);
2690
+ if (resolved == null) {
2691
+ resolved = getSchemaStats(
2692
+ resolveSchemaPointer(root, node.$ref),
2693
+ root,
2694
+ refStats
2695
+ );
2696
+ refStats.set(node.$ref, resolved);
2697
+ }
2698
+ stats.optionalProperties += resolved.optionalProperties;
2699
+ stats.hasOpenObject || (stats.hasOpenObject = resolved.hasOpenObject);
2700
+ }
2701
+ if (isOpenObject(node)) {
2702
+ stats.hasOpenObject = true;
2703
+ }
2704
+ if (isRecord(node.properties)) {
2705
+ const required = new Set(Array.isArray(node.required) ? node.required : []);
2706
+ stats.optionalProperties += Object.keys(node.properties).filter(
2707
+ (name) => !required.has(name)
2708
+ ).length;
2709
+ }
2710
+ for (const keyword of SUBSCHEMA_KEYWORDS) {
2711
+ const value = node[keyword];
2712
+ if (Array.isArray(value)) {
2713
+ value.forEach(add);
2714
+ } else {
2715
+ add(value);
2716
+ }
2717
+ }
2718
+ for (const keyword of SUBSCHEMA_LIST_KEYWORDS) {
2719
+ const value = node[keyword];
2720
+ if (Array.isArray(value)) {
2721
+ value.forEach(add);
2722
+ }
2723
+ }
2724
+ for (const keyword of SUBSCHEMA_MAP_KEYWORDS) {
2725
+ const value = node[keyword];
2726
+ if (isRecord(value)) {
2727
+ Object.values(value).forEach(add);
2728
+ }
2729
+ }
2730
+ return stats;
2731
+ }
2732
+ function isOpenObject(node) {
2733
+ const { additionalProperties, patternProperties, properties, type } = node;
2734
+ if (additionalProperties === true || isRecord(additionalProperties)) {
2735
+ return true;
2736
+ }
2737
+ if (isRecord(patternProperties) && Object.keys(patternProperties).length > 0) {
2738
+ return true;
2739
+ }
2740
+ const isObjectType = type === "object" || Array.isArray(type) && type.includes("object");
2741
+ return isObjectType && properties == null && additionalProperties !== false;
2742
+ }
2743
+
2537
2744
  // src/anthropic-messages-language-model.ts
2745
+ function validateToolsetMember({
2746
+ toolsetName,
2747
+ memberName,
2748
+ tools
2749
+ }) {
2750
+ var _a, _b;
2751
+ const toolset = tools == null ? void 0 : tools.find(
2752
+ (tool) => "type" in tool && tool.type === "computer_toolset_20260801"
2753
+ );
2754
+ if (toolsetName !== "computer" || toolset == null || !computerToolset_20260801Members.some((member) => member === memberName) || ((_b = (_a = toolset.configs) == null ? void 0 : _a[memberName]) == null ? void 0 : _b.enabled) === false) {
2755
+ throw new InvalidResponseDataError({
2756
+ data: { toolsetName, memberName },
2757
+ message: `Received an unavailable toolset member: ${toolsetName}.${memberName}.`
2758
+ });
2759
+ }
2760
+ }
2538
2761
  function getAnthropicToolsetNames(tools) {
2539
2762
  const toolsetNames = {};
2540
2763
  for (const tool of tools != null ? tools : []) {
@@ -2549,8 +2772,8 @@ function toToolsetMemberInput({
2549
2772
  input
2550
2773
  }) {
2551
2774
  return {
2552
- action: memberName,
2553
- ...typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}
2775
+ ...typeof input === "object" && input !== null && !Array.isArray(input) ? input : {},
2776
+ action: memberName
2554
2777
  };
2555
2778
  }
2556
2779
  function getJsonResponseToolName(tools) {
@@ -2591,6 +2814,31 @@ function createCitationSource(citation, citationDocuments, generateId2) {
2591
2814
  }
2592
2815
  };
2593
2816
  }
2817
+ var TEXT_OR_THINKING_BLOCK_TYPES = /* @__PURE__ */ new Set([
2818
+ "redacted_thinking",
2819
+ "text",
2820
+ "thinking"
2821
+ ]);
2822
+ function isContinuationStopReason(stopReason) {
2823
+ return stopReason === "pause_turn" || stopReason === "tool_use";
2824
+ }
2825
+ function getJsonResponseToolFallbackText(content, stopReason, jsonResponseToolName) {
2826
+ const text = /* @__PURE__ */ new Set();
2827
+ if (isContinuationStopReason(stopReason)) {
2828
+ return text;
2829
+ }
2830
+ for (const part of content) {
2831
+ if (part.type === "tool_use" && part.name === jsonResponseToolName) {
2832
+ return /* @__PURE__ */ new Set();
2833
+ }
2834
+ if (part.type === "text") {
2835
+ text.add(part);
2836
+ } else if (!TEXT_OR_THINKING_BLOCK_TYPES.has(part.type)) {
2837
+ text.clear();
2838
+ }
2839
+ }
2840
+ return text;
2841
+ }
2594
2842
  var AnthropicMessagesLanguageModel = class {
2595
2843
  constructor(modelId, config) {
2596
2844
  this.specificationVersion = "v2";
@@ -2718,9 +2966,10 @@ var AnthropicMessagesLanguageModel = class {
2718
2966
  }
2719
2967
  }
2720
2968
  const isAnthropicModel = isKnownModel || this.modelId.includes("claude-");
2969
+ const supportsResponseSchema = (responseFormat == null ? void 0 : responseFormat.type) !== "json" || responseFormat.schema == null || supportsNativeStructuredOutputSchema(responseFormat.schema);
2721
2970
  const structureOutputMode = (_a = anthropicOptions == null ? void 0 : anthropicOptions.structuredOutputMode) != null ? _a : this.modelId.includes("claude-fable-5-1") || this.modelId.includes("claude-opus-5-5") || this.modelId.includes("claude-sonnet-5-5") ? "auto" : "jsonTool";
2722
- let useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput;
2723
- if (!useStructuredOutput && rejectsForcedToolUse && supportsStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null) {
2971
+ let useStructuredOutput = structureOutputMode === "outputFormat" || structureOutputMode === "auto" && supportsStructuredOutput && supportsResponseSchema;
2972
+ if (!useStructuredOutput && rejectsForcedToolUse && supportsStructuredOutput && (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && supportsResponseSchema) {
2724
2973
  warnings.push({
2725
2974
  type: "unsupported-setting",
2726
2975
  setting: "providerOptions.anthropic.structuredOutputMode",
@@ -3029,8 +3278,13 @@ var AnthropicMessagesLanguageModel = class {
3029
3278
  betas: toolsBetas
3030
3279
  } = await prepareTools(
3031
3280
  jsonResponseTool != null ? {
3032
- tools: [...tools != null ? tools : [], jsonResponseTool],
3033
- toolChoice: tools != null && tools.length > 0 ? { type: "required" } : { type: "tool", toolName: jsonResponseTool.name },
3281
+ tools: [
3282
+ ...(tools != null ? tools : []).filter(
3283
+ (tool) => (toolChoice == null ? void 0 : toolChoice.type) !== "none" && ((toolChoice == null ? void 0 : toolChoice.type) !== "tool" || tool.name === toolChoice.toolName)
3284
+ ),
3285
+ jsonResponseTool
3286
+ ],
3287
+ toolChoice: rejectsForcedToolUse ? { type: "auto" } : tools != null && tools.length > 0 ? { type: "required" } : { type: "tool", toolName: jsonResponseTool.name },
3034
3288
  disableParallelToolUse: true,
3035
3289
  cacheControlValidator,
3036
3290
  rejectsForcedToolUse
@@ -3136,10 +3390,15 @@ var AnthropicMessagesLanguageModel = class {
3136
3390
  });
3137
3391
  const content = [];
3138
3392
  let isJsonResponseFromTool = false;
3393
+ const jsonResponseToolFallbackText = jsonResponseToolName != null ? getJsonResponseToolFallbackText(
3394
+ response.content,
3395
+ response.stop_reason,
3396
+ jsonResponseToolName
3397
+ ) : void 0;
3139
3398
  for (const part of response.content) {
3140
3399
  switch (part.type) {
3141
3400
  case "text": {
3142
- if (jsonResponseToolName == null) {
3401
+ if (jsonResponseToolFallbackText == null || jsonResponseToolFallbackText.has(part)) {
3143
3402
  const webSearchCitations = (_a = part.citations) == null ? void 0 : _a.filter(
3144
3403
  (citation) => citation.type === "web_search_result_location"
3145
3404
  );
@@ -3214,6 +3473,11 @@ var AnthropicMessagesLanguageModel = class {
3214
3473
  text: JSON.stringify(part.input)
3215
3474
  });
3216
3475
  } else if (part.toolset_name != null) {
3476
+ validateToolsetMember({
3477
+ toolsetName: part.toolset_name,
3478
+ memberName: part.name,
3479
+ tools: args.tools
3480
+ });
3217
3481
  content.push({
3218
3482
  type: "tool-call",
3219
3483
  toolCallId: part.id,
@@ -3518,6 +3782,16 @@ var AnthropicMessagesLanguageModel = class {
3518
3782
  let iterations = null;
3519
3783
  let contextManagement = null;
3520
3784
  let isJsonResponseFromTool = false;
3785
+ let rawStopReason;
3786
+ const heldBackText = [];
3787
+ const heldBackTextByIndex = /* @__PURE__ */ new Map();
3788
+ const createTextEnd = (id, citations) => ({
3789
+ type: "text-end",
3790
+ id,
3791
+ ...citations.length > 0 && {
3792
+ providerMetadata: { anthropic: { citations } }
3793
+ }
3794
+ });
3521
3795
  let isMessageOpen = false;
3522
3796
  let activeMessageId;
3523
3797
  let hasInvalidMessageSequence = false;
@@ -3529,7 +3803,7 @@ var AnthropicMessagesLanguageModel = class {
3529
3803
  controller.enqueue({ type: "stream-start", warnings });
3530
3804
  },
3531
3805
  transform(chunk, controller) {
3532
- var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k;
3806
+ var _a2, _b2, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
3533
3807
  if (hasInvalidMessageSequence) {
3534
3808
  return;
3535
3809
  }
@@ -3551,8 +3825,21 @@ var AnthropicMessagesLanguageModel = class {
3551
3825
  return;
3552
3826
  }
3553
3827
  blockType = contentBlockType;
3828
+ if (!TEXT_OR_THINKING_BLOCK_TYPES.has(contentBlockType)) {
3829
+ heldBackText.length = 0;
3830
+ }
3554
3831
  switch (contentBlockType) {
3555
3832
  case "text": {
3833
+ if (jsonResponseToolName != null) {
3834
+ const entry = {
3835
+ id: String(value.index),
3836
+ text: "",
3837
+ citations: []
3838
+ };
3839
+ heldBackText.push(entry);
3840
+ heldBackTextByIndex.set(value.index, entry);
3841
+ return;
3842
+ }
3556
3843
  contentBlocks[value.index] = {
3557
3844
  type: "text",
3558
3845
  citations: []
@@ -3613,6 +3900,11 @@ var AnthropicMessagesLanguageModel = class {
3613
3900
  id: String(value.index)
3614
3901
  });
3615
3902
  } else if (value.content_block.toolset_name != null) {
3903
+ validateToolsetMember({
3904
+ toolsetName: value.content_block.toolset_name,
3905
+ memberName: value.content_block.name,
3906
+ tools: args.tools
3907
+ });
3616
3908
  contentBlocks[value.index] = {
3617
3909
  type: "tool-call",
3618
3910
  toolCallId: value.content_block.id,
@@ -3842,11 +4134,14 @@ var AnthropicMessagesLanguageModel = class {
3842
4134
  if (contentBlock.toolset != null) {
3843
4135
  let memberInput = {};
3844
4136
  try {
3845
- memberInput = contentBlock.input === "" ? {} : JSON.parse(contentBlock.input);
4137
+ memberInput = contentBlock.input === "" ? {} : secureJsonParse2(contentBlock.input);
3846
4138
  } catch (e) {
3847
- memberInput = void 0;
4139
+ throw new InvalidResponseDataError({
4140
+ data: contentBlock.input,
4141
+ message: "Invalid toolset member input JSON."
4142
+ });
3848
4143
  }
3849
- contentBlock.input = memberInput === void 0 ? contentBlock.input : JSON.stringify(
4144
+ contentBlock.input = JSON.stringify(
3850
4145
  toToolsetMemberInput({
3851
4146
  memberName: contentBlock.toolset.memberName,
3852
4147
  input: memberInput
@@ -3888,6 +4183,8 @@ var AnthropicMessagesLanguageModel = class {
3888
4183
  switch (deltaType) {
3889
4184
  case "text_delta": {
3890
4185
  if (jsonResponseToolName != null) {
4186
+ const entry = heldBackTextByIndex.get(value.index);
4187
+ if (entry != null) entry.text += value.delta.text;
3891
4188
  return;
3892
4189
  }
3893
4190
  controller.enqueue({
@@ -3966,8 +4263,10 @@ var AnthropicMessagesLanguageModel = class {
3966
4263
  case "citations_delta": {
3967
4264
  const citation = value.delta.citation;
3968
4265
  const contentBlock = contentBlocks[value.index];
3969
- if ((contentBlock == null ? void 0 : contentBlock.type) === "text" && citation.type === "web_search_result_location") {
3970
- contentBlock.citations.push(citation);
4266
+ if (citation.type === "web_search_result_location") {
4267
+ if ((contentBlock == null ? void 0 : contentBlock.type) === "text")
4268
+ contentBlock.citations.push(citation);
4269
+ (_b2 = heldBackTextByIndex.get(value.index)) == null ? void 0 : _b2.citations.push(citation);
3971
4270
  }
3972
4271
  const source = createCitationSource(
3973
4272
  citation,
@@ -4004,16 +4303,17 @@ var AnthropicMessagesLanguageModel = class {
4004
4303
  }
4005
4304
  isMessageOpen = true;
4006
4305
  activeMessageId = value.message.id;
4306
+ heldBackTextByIndex.clear();
4007
4307
  usage.inputTokens = value.message.usage.input_tokens;
4008
- usage.cachedInputTokens = (_b2 = value.message.usage.cache_read_input_tokens) != null ? _b2 : void 0;
4308
+ usage.cachedInputTokens = (_c = value.message.usage.cache_read_input_tokens) != null ? _c : void 0;
4009
4309
  rawUsage = {
4010
4310
  ...value.message.usage
4011
4311
  };
4012
- cacheCreationInputTokens = (_c = value.message.usage.cache_creation_input_tokens) != null ? _c : null;
4312
+ cacheCreationInputTokens = (_d = value.message.usage.cache_creation_input_tokens) != null ? _d : null;
4013
4313
  controller.enqueue({
4014
4314
  type: "response-metadata",
4015
- id: (_d = value.message.id) != null ? _d : void 0,
4016
- modelId: (_e = value.message.model) != null ? _e : void 0
4315
+ id: (_e = value.message.id) != null ? _e : void 0,
4316
+ modelId: (_f = value.message.model) != null ? _f : void 0
4017
4317
  });
4018
4318
  return;
4019
4319
  }
@@ -4027,7 +4327,7 @@ var AnthropicMessagesLanguageModel = class {
4027
4327
  if (value.usage.iterations != null) {
4028
4328
  iterations = value.usage.iterations;
4029
4329
  }
4030
- const servedByFallback = (_f = value.usage.iterations) == null ? void 0 : _f.some(
4330
+ const servedByFallback = (_g = value.usage.iterations) == null ? void 0 : _g.some(
4031
4331
  (iter) => iter.type === "fallback_message"
4032
4332
  );
4033
4333
  if (value.usage.iterations && value.usage.iterations.length > 0 && !servedByFallback) {
@@ -4046,21 +4346,22 @@ var AnthropicMessagesLanguageModel = class {
4046
4346
  }
4047
4347
  usage.outputTokens = value.usage.output_tokens;
4048
4348
  }
4049
- usage.totalTokens = ((_g = usage.inputTokens) != null ? _g : 0) + ((_h = usage.outputTokens) != null ? _h : 0);
4349
+ usage.totalTokens = ((_h = usage.inputTokens) != null ? _h : 0) + ((_i = usage.outputTokens) != null ? _i : 0);
4350
+ rawStopReason = value.delta.stop_reason;
4050
4351
  finishReason = mapAnthropicStopReason({
4051
4352
  finishReason: value.delta.stop_reason,
4052
4353
  isJsonResponseFromTool
4053
4354
  });
4054
4355
  stopDetails = mapAnthropicStopDetails(value.delta.stop_details);
4055
- stopSequence = (_i = value.delta.stop_sequence) != null ? _i : null;
4356
+ stopSequence = (_j = value.delta.stop_sequence) != null ? _j : null;
4056
4357
  container = value.delta.container != null ? {
4057
4358
  expiresAt: value.delta.container.expires_at,
4058
4359
  id: value.delta.container.id,
4059
- skills: (_k = (_j = value.delta.container.skills) == null ? void 0 : _j.map((skill) => ({
4360
+ skills: (_l = (_k = value.delta.container.skills) == null ? void 0 : _k.map((skill) => ({
4060
4361
  type: skill.type,
4061
4362
  skillId: skill.skill_id,
4062
4363
  version: skill.version
4063
- }))) != null ? _k : null
4364
+ }))) != null ? _l : null
4064
4365
  } : null;
4065
4366
  if (value.context_management != null) {
4066
4367
  contextManagement = {
@@ -4098,6 +4399,15 @@ var AnthropicMessagesLanguageModel = class {
4098
4399
  case "message_stop": {
4099
4400
  isMessageOpen = false;
4100
4401
  activeMessageId = void 0;
4402
+ if (!isJsonResponseFromTool && !isContinuationStopReason(rawStopReason)) {
4403
+ for (const { id, text, citations } of heldBackText) {
4404
+ if (text.length === 0) continue;
4405
+ controller.enqueue({ type: "text-start", id });
4406
+ controller.enqueue({ type: "text-delta", id, delta: text });
4407
+ controller.enqueue(createTextEnd(id, citations));
4408
+ }
4409
+ }
4410
+ heldBackText.length = 0;
4101
4411
  controller.enqueue({
4102
4412
  type: "finish",
4103
4413
  finishReason,
@@ -4513,14 +4823,14 @@ var codeExecution_20260120InputSchema = lazySchema12(
4513
4823
  ])
4514
4824
  )
4515
4825
  );
4516
- var factory6 = createProviderDefinedToolFactoryWithOutputSchema5({
4826
+ var factory7 = createProviderDefinedToolFactoryWithOutputSchema5({
4517
4827
  id: "anthropic.code_execution_20260120",
4518
4828
  name: "code_execution",
4519
4829
  inputSchema: codeExecution_20260120InputSchema,
4520
4830
  outputSchema: codeExecution_20260120OutputSchema
4521
4831
  });
4522
4832
  var codeExecution_20260120 = (args = {}) => {
4523
- return factory6(args);
4833
+ return factory7(args);
4524
4834
  };
4525
4835
 
4526
4836
  // src/tool/computer_20241022.ts
@@ -4921,6 +5231,7 @@ export {
4921
5231
  anthropicTools,
4922
5232
  getModelCapabilities,
4923
5233
  prepareTools,
4924
- sanitizeJsonSchema
5234
+ sanitizeJsonSchema,
5235
+ supportsNativeStructuredOutputSchema
4925
5236
  };
4926
5237
  //# sourceMappingURL=index.mjs.map