@ai-sdk/anthropic 4.0.97 → 4.0.99

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,12 +1,16 @@
1
1
  import { APICallError, InvalidArgumentError, InvalidResponseDataError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
2
- import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertBase64ToUint8Array, convertInlineFileDataToUint8Array, convertToBase64, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderExecutedToolFactory, createProviderStreamError, createToolNameMapping, deleteFromApi, encodePathSegment, experimental_toolCaller, generateId, getFromApi, getTopLevelMediaType, isCustomReasoning, isNonNullable, isProviderStreamError, isRecord, lazySchema, mapReasoningToProviderBudget, mapReasoningToProviderEffort, parseProviderOptions, postFormDataToApi, postJsonToApi, resolve, resolveFullMediaType, resolveProviderReference, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, validateTypes, zodSchema } from "@ai-sdk/provider-utils";
2
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertBase64ToUint8Array, convertInlineFileDataToUint8Array, convertToBase64, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderExecutedToolFactory, createProviderStreamError, createToolNameMapping, deleteFromApi, encodePathSegment, experimental_toolCaller, generateId, getFromApi, getTopLevelMediaType, isCustomReasoning, isNonNullable, isProviderStreamError, isRecord, lazySchema, mapReasoningToProviderBudget, mapReasoningToProviderEffort, parseProviderOptions, postFormDataToApi, postJsonToApi, resolve, resolveFullMediaType, resolveProviderOptions, resolveProviderReference, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, validateTypes, zodSchema } from "@ai-sdk/provider-utils";
3
3
  import { z } from "zod/v4";
4
4
  //#region src/anthropic-error.ts
5
5
  const anthropicErrorDataSchema = lazySchema(() => zodSchema(z.object({
6
6
  type: z.literal("error"),
7
7
  error: z.object({
8
8
  type: z.string(),
9
- message: z.string()
9
+ message: z.string(),
10
+ details: z.object({
11
+ error_code: z.string().nullish().catch(void 0),
12
+ unsupported: z.array(z.string()).nullish().catch(void 0)
13
+ }).nullish().catch(void 0)
10
14
  })
11
15
  })));
12
16
  const anthropicFailedResponseHandler = createJsonErrorResponseHandler({
@@ -150,6 +154,7 @@ var AnthropicFiles = class {
150
154
  * keeps this list in sync with the option schema.
151
155
  */
152
156
  const anthropicProviderOptions = { language: {
157
+ thread: { description: "Create or continue a short-lived message thread." },
153
158
  sendReasoning: { description: "Whether to send reasoning to the model." },
154
159
  includePings: { description: "Include transient ping events in streams." },
155
160
  structuredOutputMode: { description: "How structured outputs are generated." },
@@ -1259,20 +1264,55 @@ const anthropicSystemMessageProviderOptions = lazySchema(() => zodSchema(z.objec
1259
1264
  * initial system prompt). A system message carrying tool changes must come
1260
1265
  * right before an assistant message or at the end of the messages.
1261
1266
  *
1262
- * Tools referenced by a `tool_addition` must be declared in the `tools`
1263
- * option (typically with `deferLoading: true` so they are not loaded until
1264
- * the addition surfaces them). The required
1265
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
1267
+ * A `tool_addition` either references a tool by `toolName` or defines it
1268
+ * by value with `tool`:
1269
+ * - By reference: the tool must be declared in the `tools` option
1270
+ * (typically with `deferLoading: true` so it is not loaded until the
1271
+ * addition surfaces it). The required
1272
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
1273
+ * automatically.
1274
+ * - By value: `tool` is a function or provider tool, in the same shape as
1275
+ * an entry of the `tools` option. The tool does not need to be declared
1276
+ * in `tools`, and defining a tool under an existing name replaces it
1277
+ * from that point on. The required `inline-tools-2026-09-15` beta is
1278
+ * added automatically.
1279
+ *
1280
+ * A `tool_removal` always references the tool by `toolName`.
1266
1281
  */
1267
- toolChanges: z.array(z.discriminatedUnion("type", [z.object({
1268
- type: z.literal("tool_addition"),
1269
- toolName: z.string()
1270
- }), z.object({
1271
- type: z.literal("tool_removal"),
1272
- toolName: z.string()
1273
- })])).optional()
1282
+ toolChanges: z.array(z.union([
1283
+ z.object({
1284
+ type: z.literal("tool_addition"),
1285
+ toolName: z.string()
1286
+ }),
1287
+ z.object({
1288
+ type: z.literal("tool_addition"),
1289
+ tool: z.union([z.looseObject({
1290
+ type: z.literal("function"),
1291
+ name: z.string(),
1292
+ inputSchema: z.record(z.string(), z.unknown())
1293
+ }), z.looseObject({
1294
+ type: z.literal("provider"),
1295
+ id: z.string(),
1296
+ name: z.string(),
1297
+ args: z.record(z.string(), z.unknown())
1298
+ })])
1299
+ }),
1300
+ z.object({
1301
+ type: z.literal("tool_removal"),
1302
+ toolName: z.string()
1303
+ })
1304
+ ])).optional()
1274
1305
  })));
1275
1306
  const anthropicLanguageModelOptions = lazySchema(() => zodSchema(z.object({
1307
+ /**
1308
+ * Create or continue a short-lived server-side message thread.
1309
+ * On continuation, messages must contain only new messages. Keep the full
1310
+ * conversation locally so it can be replayed when the thread expires.
1311
+ */
1312
+ thread: z.discriminatedUnion("type", [z.object({ type: z.literal("create") }), z.object({
1313
+ type: z.literal("continue"),
1314
+ previousMessageId: z.string().min(1)
1315
+ })]).optional(),
1276
1316
  /**
1277
1317
  * Whether to send reasoning to the model.
1278
1318
  *
@@ -1564,10 +1604,11 @@ function getCacheControl(providerMetadata, providerOptionsName) {
1564
1604
  return custom?.cacheControl ?? custom?.cache_control ?? anthropic?.cacheControl ?? anthropic?.cache_control;
1565
1605
  }
1566
1606
  var CacheControlValidator = class {
1567
- constructor(providerOptionsName = "anthropic") {
1607
+ constructor(providerOptionsName = "anthropic", initialBreakpointCount = 0) {
1568
1608
  this.providerOptionsName = providerOptionsName;
1569
1609
  this.breakpointCount = 0;
1570
1610
  this.warnings = [];
1611
+ this.breakpointCount = initialBreakpointCount;
1571
1612
  }
1572
1613
  getCacheControl(providerMetadata, context) {
1573
1614
  const cacheControlValue = getCacheControl(providerMetadata, this.providerOptionsName);
@@ -1623,14 +1664,14 @@ const advisor_20260301OutputSchema = lazySchema(() => zodSchema(z.discriminatedU
1623
1664
  })
1624
1665
  ])));
1625
1666
  const advisor_20260301InputSchema = lazySchema(() => zodSchema(z.object({}).strict()));
1626
- const factory$12 = createProviderExecutedToolFactory({
1667
+ const factory$13 = createProviderExecutedToolFactory({
1627
1668
  id: "anthropic.advisor_20260301",
1628
1669
  inputSchema: advisor_20260301InputSchema,
1629
1670
  outputSchema: advisor_20260301OutputSchema,
1630
1671
  supportsDeferredResults: true
1631
1672
  });
1632
1673
  const advisor_20260301 = (args) => {
1633
- return factory$12(args);
1674
+ return factory$13(args);
1634
1675
  };
1635
1676
  //#endregion
1636
1677
  //#region src/tool/computer-toolset_20260801.ts
@@ -1658,8 +1699,8 @@ const computerToolset_20260801Members = [
1658
1699
  "hold_key",
1659
1700
  "wait"
1660
1701
  ];
1661
- const computerToolset_20260801InputSchema = lazySchema(() => zodSchema(z.object({
1662
- action: z.enum(computerToolset_20260801Members),
1702
+ const computerToolset_20260801InputSchema = (configs) => lazySchema(() => zodSchema(z.object({
1703
+ action: z.enum(computerToolset_20260801Members.filter((member) => configs?.[member]?.enabled !== false)),
1663
1704
  coordinate: z.tuple([z.number().int(), z.number().int()]).optional(),
1664
1705
  duration: z.number().optional(),
1665
1706
  region: z.tuple([
@@ -1683,9 +1724,13 @@ const computerToolset_20260801ArgsSchema = lazySchema(() => zodSchema(z.object({
1683
1724
  enabled: z.boolean().optional(),
1684
1725
  deferLoading: z.boolean().optional()
1685
1726
  })).optional() })));
1686
- const computerToolset_20260801 = createProviderDefinedToolFactory({
1727
+ const factory$12 = createProviderDefinedToolFactory({
1687
1728
  id: "anthropic.computer_toolset_20260801",
1688
- inputSchema: computerToolset_20260801InputSchema
1729
+ inputSchema: computerToolset_20260801InputSchema()
1730
+ });
1731
+ const computerToolset_20260801 = (args) => ({
1732
+ ...factory$12(args),
1733
+ inputSchema: computerToolset_20260801InputSchema(args.configs)
1689
1734
  });
1690
1735
  //#endregion
1691
1736
  //#region src/tool/text-editor_20250728.ts
@@ -1924,19 +1969,19 @@ const webFetch_20250910 = (args = {}) => {
1924
1969
  };
1925
1970
  //#endregion
1926
1971
  //#region src/anthropic-prepare-tools.ts
1927
- async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming = false, rejectsForcedToolUse = false }) {
1972
+ async function prepareTools({ tools, toolChoice, hasInlineTools = false, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming = false, rejectsForcedToolUse = false }) {
1928
1973
  tools = tools?.length ? tools : void 0;
1929
1974
  const toolWarnings = [];
1930
1975
  const betas = /* @__PURE__ */ new Set();
1931
1976
  const validator = cacheControlValidator || new CacheControlValidator();
1932
- if (tools == null) return {
1977
+ if (tools == null && !hasInlineTools) return {
1933
1978
  tools: void 0,
1934
1979
  toolChoice: void 0,
1935
1980
  toolWarnings,
1936
1981
  betas
1937
1982
  };
1938
1983
  const anthropicTools = [];
1939
- for (const tool of tools) switch (tool.type) {
1984
+ for (const tool of tools ?? []) switch (tool.type) {
1940
1985
  case "function": {
1941
1986
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
1942
1987
  type: "tool definition",
@@ -2243,8 +2288,9 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2243
2288
  feature: `tool ${tool}`
2244
2289
  });
2245
2290
  }
2291
+ const declaredTools = tools == null ? void 0 : anthropicTools;
2246
2292
  if (toolChoice == null) return {
2247
- tools: anthropicTools,
2293
+ tools: declaredTools,
2248
2294
  toolChoice: disableParallelToolUse ? {
2249
2295
  type: "auto",
2250
2296
  disable_parallel_tool_use: disableParallelToolUse
@@ -2255,7 +2301,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2255
2301
  const type = toolChoice.type;
2256
2302
  switch (type) {
2257
2303
  case "auto": return {
2258
- tools: anthropicTools,
2304
+ tools: declaredTools,
2259
2305
  toolChoice: {
2260
2306
  type: "auto",
2261
2307
  disable_parallel_tool_use: disableParallelToolUse
@@ -2271,7 +2317,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2271
2317
  details: "toolChoice 'required' is not supported with this model or thinking configuration. Using 'auto' instead. Instruct the model to use a tool in the prompt and verify that a tool call was made."
2272
2318
  });
2273
2319
  return {
2274
- tools: anthropicTools,
2320
+ tools: declaredTools,
2275
2321
  toolChoice: {
2276
2322
  type: "auto",
2277
2323
  disable_parallel_tool_use: disableParallelToolUse
@@ -2281,7 +2327,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2281
2327
  };
2282
2328
  }
2283
2329
  return {
2284
- tools: anthropicTools,
2330
+ tools: declaredTools,
2285
2331
  toolChoice: {
2286
2332
  type: "any",
2287
2333
  disable_parallel_tool_use: disableParallelToolUse
@@ -2290,7 +2336,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2290
2336
  betas
2291
2337
  };
2292
2338
  case "none": return {
2293
- tools: anthropicTools,
2339
+ tools: declaredTools,
2294
2340
  toolChoice: { type: "none" },
2295
2341
  toolWarnings,
2296
2342
  betas
@@ -2303,7 +2349,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2303
2349
  details: `toolChoice 'tool' is not supported with this model or thinking configuration. Only the '${toolChoice.toolName}' tool is sent with 'auto' tool choice. Instruct the model to use the tool in the prompt and verify that a tool call was made.`
2304
2350
  });
2305
2351
  return {
2306
- tools: anthropicTools.filter((tool) => "name" in tool && tool.name === toolChoice.toolName),
2352
+ tools: declaredTools?.filter((tool) => "name" in tool && tool.name === toolChoice.toolName),
2307
2353
  toolChoice: {
2308
2354
  type: "auto",
2309
2355
  disable_parallel_tool_use: disableParallelToolUse
@@ -2313,7 +2359,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2313
2359
  };
2314
2360
  }
2315
2361
  return {
2316
- tools: anthropicTools,
2362
+ tools: declaredTools,
2317
2363
  toolChoice: {
2318
2364
  type: "tool",
2319
2365
  name: toolChoice.toolName,
@@ -2691,7 +2737,31 @@ function extractErrorValue(value) {
2691
2737
  }
2692
2738
  return {};
2693
2739
  }
2694
- async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping, toolsetNames = {}, convertMediaPart }) {
2740
+ function isComputerTool(tool) {
2741
+ return tool.type === "provider" && tool.id.startsWith("anthropic.computer_");
2742
+ }
2743
+ /**
2744
+ * Collects the tools that mid-conversation tool changes add by value, so they
2745
+ * can take part in tool name mapping like the tools of the `tools` option.
2746
+ * Tools that cannot be added by value are left out because they are ignored.
2747
+ */
2748
+ async function getInlineToolsFromPrompt(prompt) {
2749
+ const inlineTools = [];
2750
+ for (const message of prompt) {
2751
+ if (message.role !== "system" || message.providerOptions == null) continue;
2752
+ const options = await parseProviderOptions({
2753
+ provider: "anthropic",
2754
+ providerOptions: message.providerOptions,
2755
+ schema: anthropicSystemMessageProviderOptions
2756
+ });
2757
+ for (const toolChange of options?.toolChanges ?? []) if ("tool" in toolChange) {
2758
+ const tool = toolChange.tool;
2759
+ if (!isComputerTool(tool)) inlineTools.push(tool);
2760
+ }
2761
+ }
2762
+ return inlineTools;
2763
+ }
2764
+ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping, toolsetNames = {}, convertMediaPart, convertInlineTool }) {
2695
2765
  const betas = /* @__PURE__ */ new Set();
2696
2766
  const blocks = groupIntoBlocks(prompt);
2697
2767
  const validator = cacheControlValidator || new CacheControlValidator();
@@ -2746,18 +2816,50 @@ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cache
2746
2816
  canCache: true
2747
2817
  })
2748
2818
  });
2749
- for (const toolChange of toolChanges) content.push({
2750
- type: toolChange.type,
2751
- tool: {
2752
- type: "tool_reference",
2753
- name: toolNameMapping.toProviderToolName(toolChange.toolName)
2819
+ let toolChangeCount = 0;
2820
+ let hasInlineToolDefinition = false;
2821
+ for (const toolChange of toolChanges) {
2822
+ if ("tool" in toolChange) {
2823
+ if (convertInlineTool == null) throw new UnsupportedFunctionalityError({ functionality: "tool additions by value in mid-conversation tool changes" });
2824
+ const tool = toolChange.tool;
2825
+ if (isComputerTool(tool)) {
2826
+ warnings.push({
2827
+ type: "other",
2828
+ message: `The tool '${tool.name}' cannot be added by value in a tool change. Declare it in the tools option and add it by reference with toolName. The tool change has been ignored.`
2829
+ });
2830
+ continue;
2831
+ }
2832
+ const { definition, warnings: toolWarnings, betas: toolBetas } = await convertInlineTool(tool);
2833
+ warnings.push(...toolWarnings);
2834
+ for (const beta of toolBetas) betas.add(beta);
2835
+ if (definition == null) continue;
2836
+ content.push({
2837
+ type: "tool_addition",
2838
+ tool: {
2839
+ type: "tool_definition",
2840
+ definition
2841
+ }
2842
+ });
2843
+ toolChangeCount++;
2844
+ hasInlineToolDefinition = true;
2845
+ continue;
2754
2846
  }
2755
- });
2847
+ content.push({
2848
+ type: toolChange.type,
2849
+ tool: {
2850
+ type: "tool_reference",
2851
+ name: toolNameMapping.toProviderToolName(toolChange.toolName)
2852
+ }
2853
+ });
2854
+ toolChangeCount++;
2855
+ }
2856
+ if (content.length === 0 && systemMessageOptions?.clearAt == null && systemMessageOptions?.effort == null) continue;
2756
2857
  convertedMessages.push({
2757
2858
  content,
2758
2859
  clearAt: systemMessageOptions?.clearAt,
2759
2860
  effort: systemMessageOptions?.effort,
2760
- toolChangeCount: toolChanges.length
2861
+ toolChangeCount,
2862
+ hasInlineToolDefinition
2761
2863
  });
2762
2864
  }
2763
2865
  const toolChangeCount = convertedMessages.reduce((count, message) => count + message.toolChangeCount, 0);
@@ -2788,7 +2890,8 @@ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cache
2788
2890
  ...message.clearAt != null && { clear_at: message.clearAt },
2789
2891
  ...message.effort != null && { output_config: { effort: message.effort } }
2790
2892
  });
2791
- if (message.toolChangeCount > 0) betas.add("mid-conversation-tool-changes-2026-07-01");
2893
+ if (message.hasInlineToolDefinition) betas.add("inline-tools-2026-09-15");
2894
+ else if (message.toolChangeCount > 0) betas.add("mid-conversation-tool-changes-2026-07-01");
2792
2895
  if (message.clearAt != null) betas.add("mid-conversation-system-clear-at-2026-08-21");
2793
2896
  if (message.effort != null) betas.add("mid-conversation-output-config-2026-07-01");
2794
2897
  }
@@ -4004,6 +4107,16 @@ function isOpenObject(node) {
4004
4107
  }
4005
4108
  //#endregion
4006
4109
  //#region src/anthropic-language-model.ts
4110
+ function validateToolsetMember({ toolsetName, memberName, tools }) {
4111
+ const toolset = tools?.find((tool) => "type" in tool && tool.type === "computer_toolset_20260801");
4112
+ if (toolsetName !== "computer" || toolset == null || !computerToolset_20260801Members.some((member) => member === memberName) || toolset.configs?.[memberName]?.enabled === false) throw new InvalidResponseDataError({
4113
+ data: {
4114
+ toolsetName,
4115
+ memberName
4116
+ },
4117
+ message: `Received an unavailable toolset member: ${toolsetName}.${memberName}.`
4118
+ });
4119
+ }
4007
4120
  function createAnthropicStreamError(error) {
4008
4121
  const inferredMetadata = getAnthropicStreamErrorMetadata(error.type);
4009
4122
  return createProviderStreamError({
@@ -4112,15 +4225,24 @@ function getAnthropicToolsetNames(tools) {
4112
4225
  * computer tool versions.
4113
4226
  */
4114
4227
  function toToolsetMemberInput({ memberName, input }) {
4228
+ if (typeof input !== "object" || input === null || Array.isArray(input)) throw new InvalidResponseDataError({
4229
+ data: input,
4230
+ message: "Invalid toolset member input: expected an object."
4231
+ });
4115
4232
  return {
4116
- action: memberName,
4117
- ...typeof input === "object" && input !== null && !Array.isArray(input) ? input : {}
4233
+ ...input,
4234
+ action: memberName
4118
4235
  };
4119
4236
  }
4120
4237
  function getProviderOptionsName(provider) {
4121
4238
  const dotIndex = provider.indexOf(".");
4122
4239
  return dotIndex === -1 ? provider : provider.substring(0, dotIndex);
4123
4240
  }
4241
+ /**
4242
+ * Legacy names of custom providerOptions keys, read when the current key is
4243
+ * absent.
4244
+ */
4245
+ const LEGACY_PROVIDER_OPTIONS_NAMES = { googleVertex: ["vertex"] };
4124
4246
  const TEXT_OR_THINKING_BLOCK_TYPES = /* @__PURE__ */ new Set([
4125
4247
  "redacted_thinking",
4126
4248
  "text",
@@ -4212,12 +4334,13 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4212
4334
  providerOptions,
4213
4335
  schema: anthropicLanguageModelOptions
4214
4336
  });
4215
- const customProviderOptions = providerOptionsName !== "anthropic" ? await parseProviderOptions({
4216
- provider: providerOptionsName,
4337
+ const { options: customProviderOptions, namespaces: [customProviderOptionsName] } = await resolveProviderOptions({
4217
4338
  providerOptions,
4339
+ namespaces: providerOptionsName !== "anthropic" ? [providerOptionsName, ...Object.hasOwn(LEGACY_PROVIDER_OPTIONS_NAMES, providerOptionsName) ? LEGACY_PROVIDER_OPTIONS_NAMES[providerOptionsName] : []] : [],
4340
+ resolution: "first",
4218
4341
  schema: anthropicLanguageModelOptions
4219
- }) : null;
4220
- const usedCustomProviderKey = customProviderOptions != null;
4342
+ });
4343
+ const usedCustomProviderKey = customProviderOptionsName === providerOptionsName;
4221
4344
  const anthropicOptions = Object.assign({}, canonicalOptions ?? {}, customProviderOptions ?? {});
4222
4345
  if (anthropicOptions.serviceTier != null) {
4223
4346
  const supportedTiers = providerOptionsName === "anthropic" ? ["auto", "standard_only"] : providerOptionsName === "minimax" ? ["standard", "priority"] : void 0;
@@ -4293,9 +4416,20 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4293
4416
  argument: "providerOptions",
4294
4417
  message: "Anthropic provider options `compaction` and `contextManagement` cannot be used together."
4295
4418
  });
4296
- const cacheControlValidator = new CacheControlValidator(config.cacheControlProviderOptionsName);
4419
+ const thread = anthropicOptions?.thread;
4420
+ if (thread != null && config.supportsMessageThreads !== true) throw new UnsupportedFunctionalityError({
4421
+ functionality: "Anthropic message threads",
4422
+ message: `${config.provider} does not support Anthropic message threads.`
4423
+ });
4424
+ if (thread != null && (compaction != null || contextManagement?.edits.some((edit) => edit.type !== "clear_thinking_20251015" || edit.keep !== "all"))) throw new InvalidArgumentError({
4425
+ argument: "providerOptions.anthropic.thread",
4426
+ message: "Anthropic message threads do not support compaction or context editing, except clear_thinking_20251015 with keep: \"all\"."
4427
+ });
4428
+ const cacheControlValidator = new CacheControlValidator(config.cacheControlProviderOptionsName, thread != null && anthropicOptions?.cacheControl != null ? 1 : 0);
4429
+ const defaultEagerInputStreaming = stream && (anthropicOptions?.toolStreaming ?? true);
4430
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
4297
4431
  const toolNameMapping = createToolNameMapping({
4298
- tools,
4432
+ tools: [...inlineTools, ...tools ?? []],
4299
4433
  providerToolNames: {
4300
4434
  "anthropic.code_execution_20250522": "code_execution",
4301
4435
  "anthropic.code_execution_20250825": "code_execution",
@@ -4323,6 +4457,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4323
4457
  }
4324
4458
  });
4325
4459
  const toolsetNames = getAnthropicToolsetNames(tools);
4460
+ const inlineToolDefinitions = [];
4326
4461
  const { prompt: messagesPrompt, betas } = await convertToAnthropicPrompt({
4327
4462
  prompt,
4328
4463
  sendReasoning: anthropicOptions?.sendReasoning ?? true,
@@ -4330,8 +4465,39 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4330
4465
  cacheControlValidator,
4331
4466
  toolNameMapping,
4332
4467
  toolsetNames,
4333
- convertMediaPart: config.convertMediaPart
4468
+ convertMediaPart: config.convertMediaPart,
4469
+ convertInlineTool: async (tool) => {
4470
+ const { tools: definitions, toolWarnings, betas } = await prepareTools({
4471
+ tools: [tool],
4472
+ toolChoice: void 0,
4473
+ cacheControlValidator,
4474
+ supportsStructuredOutput,
4475
+ supportsStrictTools
4476
+ });
4477
+ if (definitions?.[0] != null) inlineToolDefinitions.push({
4478
+ sdkName: tool.name,
4479
+ definition: definitions[0]
4480
+ });
4481
+ return {
4482
+ definition: definitions?.[0],
4483
+ warnings: toolWarnings,
4484
+ betas
4485
+ };
4486
+ }
4334
4487
  });
4488
+ if (thread != null) {
4489
+ const unpinnedBetas = [...betas].filter((beta) => !userSuppliedBetas.has(beta) && !anthropicOptions?.anthropicBeta?.includes(beta));
4490
+ if (unpinnedBetas.length > 0) warnings.push({
4491
+ type: "compatibility",
4492
+ feature: "providerOptions.anthropic.thread",
4493
+ details: `Message content enabled beta headers: ${unpinnedBetas.join(", ")}. Thread requests require the same beta set on every turn. Pin these values with anthropicBeta on every request, or start a new thread when the set changes.`
4494
+ });
4495
+ if (thread.type === "continue" && (messagesPrompt.system != null || (tools?.length ?? 0) > 0)) warnings.push({
4496
+ type: "compatibility",
4497
+ feature: "providerOptions.anthropic.thread",
4498
+ details: "Continuation uses the system prompt and tool definitions stored by the create request; supplied definitions are omitted from the wire request. Supply identical tools for local tool handling and fixed request settings. To change system instructions or tools, start a new thread."
4499
+ });
4500
+ }
4335
4501
  if (isCustomReasoning(reasoning) && anthropicOptions?.effort == null) {
4336
4502
  const reasoningConfig = resolveAnthropicReasoningConfig({
4337
4503
  reasoning,
@@ -4449,7 +4615,11 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4449
4615
  version: skill.version
4450
4616
  }))
4451
4617
  } : anthropicOptions.container.id },
4452
- system: messagesPrompt.system,
4618
+ system: thread?.type === "continue" ? void 0 : messagesPrompt.system,
4619
+ ...thread != null && { thread: thread.type === "create" ? { type: "create" } : {
4620
+ type: "continue",
4621
+ previous_message_id: thread.previousMessageId
4622
+ } },
4453
4623
  messages: messagesPrompt.messages,
4454
4624
  ...anthropicOptions?.safeguards && anthropicOptions.safeguards.length > 0 && { safeguards: anthropicOptions.safeguards.map((safeguard) => ({
4455
4625
  type: safeguard.type,
@@ -4565,7 +4735,6 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4565
4735
  if (thinkingBlockBinding != null) betas.add("thinking-binding-controls-2026-08-01");
4566
4736
  if (anthropicOptions?.fallbacks === "default") betas.add("server-side-fallback-2026-07-01");
4567
4737
  else if (anthropicOptions?.fallbacks && anthropicOptions.fallbacks.length > 0) betas.add("server-side-fallback-2026-06-01");
4568
- const defaultEagerInputStreaming = stream && (anthropicOptions?.toolStreaming ?? true);
4569
4738
  const { tools: anthropicTools, toolChoice: anthropicToolChoice, toolWarnings, betas: toolsBetas } = await prepareTools(jsonResponseTool != null ? {
4570
4739
  tools: [...(tools ?? []).filter((tool) => toolChoice?.type !== "none" && (toolChoice?.type !== "tool" || tool.name === toolChoice.toolName)), jsonResponseTool],
4571
4740
  toolChoice: { type: "required" },
@@ -4578,6 +4747,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4578
4747
  } : {
4579
4748
  tools: tools ?? [],
4580
4749
  toolChoice,
4750
+ hasInlineTools: inlineTools.length > 0,
4581
4751
  disableParallelToolUse: anthropicOptions?.disableParallelToolUse,
4582
4752
  cacheControlValidator,
4583
4753
  supportsStructuredOutput,
@@ -4585,11 +4755,30 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4585
4755
  defaultEagerInputStreaming,
4586
4756
  rejectsForcedToolUse: rejectsForcedToolUse || thinkingType === "enabled"
4587
4757
  });
4758
+ if (toolChoice?.type === "tool" && (anthropicToolChoice?.type === "auto" || jsonResponseTool != null) || toolChoice?.type === "none" && jsonResponseTool != null) {
4759
+ for (const server of baseArgs.mcp_servers ?? []) server.tool_configuration = {
4760
+ allowed_tools: server.tool_configuration?.allowed_tools,
4761
+ enabled: false
4762
+ };
4763
+ const emittedInlineDefinitions = new Set(messagesPrompt.messages.flatMap((message) => message.role === "system" ? message.content.flatMap((part) => part.type === "tool_addition" && part.tool.type === "tool_definition" ? [part.tool.definition] : []) : []));
4764
+ const selectedSdkName = toolChoice.type === "tool" ? toolChoice.toolName : void 0;
4765
+ const selectedTool = tools?.find((tool) => tool.name === selectedSdkName);
4766
+ const selectedProviderName = jsonResponseTool != null && selectedSdkName != null && selectedTool?.type !== "function" ? toolNameMapping.toProviderToolName(selectedSdkName) : selectedSdkName;
4767
+ const conflictingTool = inlineToolDefinitions.find(({ sdkName, definition }) => emittedInlineDefinitions.has(definition) && (toolChoice.type === "none" || jsonResponseTool != null && sdkName !== selectedSdkName || !("name" in definition) || definition.name !== selectedProviderName));
4768
+ if (conflictingTool != null) {
4769
+ const toolName = "name" in conflictingTool.definition ? conflictingTool.definition.name : conflictingTool.definition.type;
4770
+ const choice = toolChoice.type === "tool" ? `named tool choice '${toolChoice.toolName}'` : `tool choice 'none'`;
4771
+ throw new InvalidArgumentError({
4772
+ argument: "toolChoice",
4773
+ message: `Inline tool '${toolName}' conflicts with ${choice}. Inline definitions must respect the tool choice when forced tool use falls back or the JSON response tool is used.`
4774
+ });
4775
+ }
4776
+ }
4588
4777
  const cacheWarnings = cacheControlValidator.getWarnings();
4589
4778
  return {
4590
4779
  args: {
4591
4780
  ...baseArgs,
4592
- tools: anthropicTools,
4781
+ tools: thread?.type === "continue" ? void 0 : anthropicTools,
4593
4782
  tool_choice: anthropicToolChoice,
4594
4783
  stream: stream === true ? true : void 0
4595
4784
  },
@@ -4599,14 +4788,17 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4599
4788
  ...cacheWarnings
4600
4789
  ],
4601
4790
  betas: /* @__PURE__ */ new Set([
4791
+ ...thread != null ? ["message-threads-2026-08-12"] : [],
4602
4792
  ...betas,
4603
4793
  ...toolsBetas,
4604
4794
  ...userSuppliedBetas,
4605
4795
  ...anthropicOptions?.anthropicBeta ?? []
4606
4796
  ]),
4797
+ markCodeExecutionDynamic: hasDynamicFilteringWebToolWithoutCodeExecution(anthropicTools),
4607
4798
  usesJsonResponseTool: jsonResponseTool != null,
4608
4799
  includePings: stream === true && anthropicOptions?.includePings === true,
4609
4800
  toolNameMapping,
4801
+ preparedTools: anthropicTools,
4610
4802
  providerOptionsName,
4611
4803
  usedCustomProviderKey
4612
4804
  };
@@ -4650,13 +4842,12 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4650
4842
  }
4651
4843
  async doGenerate(options) {
4652
4844
  const configHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
4653
- const { args, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
4845
+ const { args, warnings, betas, usesJsonResponseTool, markCodeExecutionDynamic, toolNameMapping, preparedTools, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
4654
4846
  ...options,
4655
4847
  stream: false,
4656
4848
  userSuppliedBetas: this.getBetasFromHeaders(configHeaders, options.headers)
4657
4849
  });
4658
4850
  const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
4659
- const markCodeExecutionDynamic = hasDynamicFilteringWebToolWithoutCodeExecution(args.tools);
4660
4851
  const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
4661
4852
  url: this.buildRequestUrl(false),
4662
4853
  headers: await this.getHeaders({
@@ -4733,20 +4924,26 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4733
4924
  type: "text",
4734
4925
  text: JSON.stringify(part.input)
4735
4926
  });
4736
- } else if (part.toolset_name != null) content.push({
4737
- type: "tool-call",
4738
- toolCallId: part.id,
4739
- toolName: toolNameMapping.toCustomToolName(part.toolset_name),
4740
- input: JSON.stringify(toToolsetMemberInput({
4741
- memberName: part.name,
4742
- input: part.input
4743
- })),
4744
- providerMetadata: { anthropic: {
4927
+ } else if (part.toolset_name != null) {
4928
+ validateToolsetMember({
4745
4929
  toolsetName: part.toolset_name,
4746
- ...getAnthropicCallerMetadata(part.caller).providerMetadata?.anthropic
4747
- } }
4748
- });
4749
- else content.push({
4930
+ memberName: part.name,
4931
+ tools: preparedTools
4932
+ });
4933
+ content.push({
4934
+ type: "tool-call",
4935
+ toolCallId: part.id,
4936
+ toolName: toolNameMapping.toCustomToolName(part.toolset_name),
4937
+ input: JSON.stringify(toToolsetMemberInput({
4938
+ memberName: part.name,
4939
+ input: part.input
4940
+ })),
4941
+ providerMetadata: { anthropic: {
4942
+ toolsetName: part.toolset_name,
4943
+ ...getAnthropicCallerMetadata(part.caller).providerMetadata?.anthropic
4944
+ } }
4945
+ });
4946
+ } else content.push({
4750
4947
  type: "tool-call",
4751
4948
  toolCallId: part.id,
4752
4949
  toolName: part.name,
@@ -5075,13 +5272,12 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5075
5272
  async doStream(options) {
5076
5273
  "use step";
5077
5274
  const configHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
5078
- const { args: body, warnings, betas, usesJsonResponseTool, includePings, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
5275
+ const { args: body, warnings, betas, usesJsonResponseTool, markCodeExecutionDynamic, includePings, toolNameMapping, preparedTools, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
5079
5276
  ...options,
5080
5277
  stream: true,
5081
5278
  userSuppliedBetas: this.getBetasFromHeaders(configHeaders, options.headers)
5082
5279
  });
5083
5280
  const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
5084
- const markCodeExecutionDynamic = hasDynamicFilteringWebToolWithoutCodeExecution(body.tools);
5085
5281
  const url = this.buildRequestUrl(true);
5086
5282
  const { responseHeaders, value: response } = await postJsonToApi({
5087
5283
  url,
@@ -5246,6 +5442,11 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5246
5442
  id: String(value.index)
5247
5443
  });
5248
5444
  } else if (part.toolset_name != null) {
5445
+ validateToolsetMember({
5446
+ toolsetName: part.toolset_name,
5447
+ memberName: part.name,
5448
+ tools: preparedTools
5449
+ });
5249
5450
  const callerInfo = getAnthropicCallerInfo(part.caller);
5250
5451
  const customToolName = toolNameMapping.toCustomToolName(part.toolset_name);
5251
5452
  const hasNonEmptyInput = part.input && Object.keys(part.input).length > 0;
@@ -5590,9 +5791,12 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5590
5791
  try {
5591
5792
  memberInput = contentBlock.input === "" ? {} : secureJsonParse(contentBlock.input);
5592
5793
  } catch {
5593
- memberInput = void 0;
5794
+ throw new InvalidResponseDataError({
5795
+ data: contentBlock.input,
5796
+ message: "Invalid toolset member input JSON."
5797
+ });
5594
5798
  }
5595
- contentBlock.input = memberInput === void 0 ? contentBlock.input : JSON.stringify(toToolsetMemberInput({
5799
+ contentBlock.input = JSON.stringify(toToolsetMemberInput({
5596
5800
  memberName: contentBlock.toolset.memberName,
5597
5801
  input: memberInput
5598
5802
  }));
@@ -6736,6 +6940,6 @@ var AnthropicSkills = class {
6736
6940
  }
6737
6941
  };
6738
6942
  //#endregion
6739
- export { AnthropicFiles, AnthropicLanguageModel, AnthropicLanguageModel as AnthropicMessagesLanguageModel, AnthropicSkills, anthropicTools, getAnthropicModelCapabilities as getModelCapabilities, prepareTools, sanitizeJsonSchema, supportsNativeStructuredOutputSchema };
6943
+ export { AnthropicFiles, AnthropicLanguageModel, AnthropicLanguageModel as AnthropicMessagesLanguageModel, AnthropicSkills, anthropicModelCatalog, anthropicProviderOptions, anthropicTools, getAnthropicLanguageModelEntry, getAnthropicModelCapabilities as getModelCapabilities, prepareTools, sanitizeJsonSchema, supportsNativeStructuredOutputSchema };
6740
6944
 
6741
6945
  //# sourceMappingURL=index.js.map