@ai-sdk/anthropic 4.0.96 → 4.0.98

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.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { APICallError, InvalidArgumentError, InvalidResponseDataError, NoSuchModelError, UnsupportedFunctionalityError } from "@ai-sdk/provider";
2
- import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertInlineFileDataToUint8Array, convertToBase64, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderExecutedToolFactory, createProviderStreamError, createToolNameMapping, encodePathSegment, experimental_toolCaller, generateId, getFromApi, getTopLevelMediaType, isCustomReasoning, isNonNullable, isProviderStreamError, isRecord, lazySchema, loadApiKey, loadOptionalSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, normalizeBatchRequestCounts, normalizeHeaders, parseProviderOptions, postFormDataToApi, postJsonToApi, resolve, resolveFullMediaType, resolveProviderReference, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, validateBaseURL, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
2
+ import { WORKFLOW_DESERIALIZE, WORKFLOW_SERIALIZE, combineHeaders, convertAsyncIteratorToReadableStream, convertBase64ToUint8Array, convertInlineFileDataToUint8Array, convertToBase64, createBinaryStreamResponseHandler, createEventSourceResponseHandler, createJsonErrorResponseHandler, createJsonLinesResponseHandler, createJsonResponseHandler, createProviderDefinedToolFactory, createProviderExecutedToolFactory, createProviderStreamError, createToolNameMapping, deleteFromApi, encodePathSegment, experimental_toolCaller, generateId, getFromApi, getTopLevelMediaType, isCustomReasoning, isNonNullable, isProviderStreamError, isRecord, lazySchema, loadApiKey, loadOptionalSetting, mapReasoningToProviderBudget, mapReasoningToProviderEffort, normalizeBatchRequestCounts, normalizeHeaders, parseProviderOptions, postFormDataToApi, postJsonToApi, resolve, resolveFullMediaType, resolveProviderReference, safeValidateTypes, secureJsonParse, serializeModelOptions, stringifyWithBigIntAndCycles, validateBaseURL, validateTypes, withUserAgentSuffix, withoutTrailingSlash, zodSchema } from "@ai-sdk/provider-utils";
3
3
  import { Experimental_DecisionLanguageModel } from "@ai-sdk/provider-utils/experimental-decision";
4
4
  import { z } from "zod/v4";
5
5
  //#region src/anthropic-error.ts
@@ -7,7 +7,11 @@ const anthropicErrorDataSchema = lazySchema(() => zodSchema(z.object({
7
7
  type: z.literal("error"),
8
8
  error: z.object({
9
9
  type: z.string(),
10
- message: z.string()
10
+ message: z.string(),
11
+ details: z.object({
12
+ error_code: z.string().nullish().catch(void 0),
13
+ unsupported: z.array(z.string()).nullish().catch(void 0)
14
+ }).nullish().catch(void 0)
11
15
  })
12
16
  })));
13
17
  const anthropicFailedResponseHandler = createJsonErrorResponseHandler({
@@ -15,16 +19,23 @@ const anthropicFailedResponseHandler = createJsonErrorResponseHandler({
15
19
  errorToMessage: (data) => data.error.message
16
20
  });
17
21
  //#endregion
18
- //#region src/anthropic-files.ts
22
+ //#region src/files/anthropic-files-api.ts
19
23
  const anthropicUploadFileResponseSchema = lazySchema(() => zodSchema(z.object({
20
24
  id: z.string(),
21
- type: z.literal("file"),
22
- filename: z.string(),
23
- mime_type: z.string(),
24
- size_bytes: z.number(),
25
- created_at: z.string(),
26
- downloadable: z.boolean().nullish()
25
+ type: z.literal("file").nullish(),
26
+ filename: z.string().nullish(),
27
+ mime_type: z.string().nullish(),
28
+ size_bytes: z.number().nullish(),
29
+ created_at: z.string().nullish(),
30
+ downloadable: z.boolean().nullish(),
31
+ expires_at: z.string().nullish()
32
+ })));
33
+ const anthropicDeleteFileResponseSchema = lazySchema(() => zodSchema(z.object({
34
+ type: z.literal("file_deleted").nullish(),
35
+ id: z.string()
27
36
  })));
37
+ //#endregion
38
+ //#region src/files/anthropic-files.ts
28
39
  var AnthropicFiles = class {
29
40
  get provider() {
30
41
  return this.config.provider;
@@ -33,6 +44,17 @@ var AnthropicFiles = class {
33
44
  this.config = config;
34
45
  this.specificationVersion = "v4";
35
46
  }
47
+ getFileId(file) {
48
+ const fileId = file.anthropic;
49
+ if (fileId == null || fileId.trim() === "") throw new InvalidArgumentError({
50
+ argument: "file",
51
+ message: "file reference is missing an 'anthropic' file id."
52
+ });
53
+ return fileId;
54
+ }
55
+ async getHeaders(headers) {
56
+ return combineHeaders(await resolve(this.config.headers), { "anthropic-beta": "files-api-2025-04-14" }, headers);
57
+ }
36
58
  async uploadFile({ data, mediaType, filename, abortSignal, headers }) {
37
59
  const fileBytes = convertInlineFileDataToUint8Array(data);
38
60
  const blob = new Blob([fileBytes], { type: mediaType });
@@ -41,7 +63,7 @@ var AnthropicFiles = class {
41
63
  else formData.append("file", blob);
42
64
  const { value: response } = await postFormDataToApi({
43
65
  url: `${this.config.baseURL}/files`,
44
- headers: combineHeaders(await resolve(this.config.headers), { "anthropic-beta": "files-api-2025-04-14" }, headers),
66
+ headers: await this.getHeaders(headers),
45
67
  formData,
46
68
  failedResponseHandler: anthropicFailedResponseHandler,
47
69
  successfulResponseHandler: createJsonResponseHandler(anthropicUploadFileResponseSchema),
@@ -53,13 +75,76 @@ var AnthropicFiles = class {
53
75
  providerReference: { anthropic: response.id },
54
76
  mediaType: response.mime_type ?? mediaType,
55
77
  filename: response.filename ?? filename,
56
- providerMetadata: { anthropic: {
57
- filename: response.filename,
58
- mimeType: response.mime_type,
59
- sizeBytes: response.size_bytes,
60
- createdAt: response.created_at,
61
- ...response.downloadable != null ? { downloadable: response.downloadable } : {}
62
- } }
78
+ byteSize: response.size_bytes ?? void 0,
79
+ createdAt: response.created_at != null ? new Date(response.created_at) : void 0,
80
+ expiresAt: response.expires_at != null ? new Date(response.expires_at) : void 0,
81
+ providerMetadata: { anthropic: this.toFileMetadata(response) }
82
+ };
83
+ }
84
+ async deleteFile({ file, abortSignal, headers }) {
85
+ const fileId = this.getFileId(file);
86
+ const { value: response } = await deleteFromApi({
87
+ url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}`,
88
+ headers: await this.getHeaders(headers),
89
+ abortSignal,
90
+ fetch: this.config.fetch,
91
+ failedResponseHandler: anthropicFailedResponseHandler,
92
+ successfulResponseHandler: createJsonResponseHandler(anthropicDeleteFileResponseSchema)
93
+ });
94
+ return {
95
+ warnings: [],
96
+ providerReference: { anthropic: response.id },
97
+ deleted: true
98
+ };
99
+ }
100
+ async getFileMetadata({ file, abortSignal, headers }) {
101
+ const fileId = this.getFileId(file);
102
+ const { value: response } = await getFromApi({
103
+ url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}`,
104
+ headers: await this.getHeaders(headers),
105
+ abortSignal,
106
+ fetch: this.config.fetch,
107
+ failedResponseHandler: anthropicFailedResponseHandler,
108
+ successfulResponseHandler: createJsonResponseHandler(anthropicUploadFileResponseSchema),
109
+ validateUrl: false
110
+ });
111
+ return {
112
+ warnings: [],
113
+ providerReference: { anthropic: response.id },
114
+ filename: response.filename ?? void 0,
115
+ mediaType: response.mime_type ?? void 0,
116
+ byteSize: response.size_bytes ?? void 0,
117
+ createdAt: response.created_at != null ? new Date(response.created_at) : void 0,
118
+ expiresAt: response.expires_at != null ? new Date(response.expires_at) : void 0,
119
+ providerMetadata: { anthropic: this.toFileMetadata(response) }
120
+ };
121
+ }
122
+ toFileMetadata(response) {
123
+ return {
124
+ ...response.filename != null ? { filename: response.filename } : {},
125
+ ...response.mime_type != null ? { mimeType: response.mime_type } : {},
126
+ ...response.size_bytes != null ? { sizeBytes: response.size_bytes } : {},
127
+ ...response.created_at != null ? { createdAt: response.created_at } : {},
128
+ ...response.downloadable != null ? { downloadable: response.downloadable } : {},
129
+ ...response.expires_at != null ? { expiresAt: response.expires_at } : {}
130
+ };
131
+ }
132
+ async downloadFile({ file, abortSignal, headers }) {
133
+ const fileId = this.getFileId(file);
134
+ const { value: content, responseHeaders } = await getFromApi({
135
+ url: `${this.config.baseURL}/files/${encodePathSegment(fileId)}/content`,
136
+ headers: await this.getHeaders(headers),
137
+ abortSignal,
138
+ fetch: this.config.fetch,
139
+ failedResponseHandler: anthropicFailedResponseHandler,
140
+ successfulResponseHandler: createBinaryStreamResponseHandler(),
141
+ validateUrl: false
142
+ });
143
+ const mediaType = responseHeaders?.["content-type"]?.split(";")[0].trim();
144
+ return {
145
+ warnings: [],
146
+ content,
147
+ ...mediaType ? { mediaType } : {}
63
148
  };
64
149
  }
65
150
  };
@@ -70,7 +155,9 @@ var AnthropicFiles = class {
70
155
  * keeps this list in sync with the option schema.
71
156
  */
72
157
  const anthropicProviderOptions = { language: {
158
+ thread: { description: "Create or continue a short-lived message thread." },
73
159
  sendReasoning: { description: "Whether to send reasoning to the model." },
160
+ includePings: { description: "Include transient ping events in streams." },
74
161
  structuredOutputMode: { description: "How structured outputs are generated." },
75
162
  thinking: { description: "Extended thinking configuration." },
76
163
  disableParallelToolUse: { description: "Use at most one tool per response." },
@@ -346,6 +433,7 @@ function createAnthropicLanguageModelEntry(modelId, documented) {
346
433
  compaction: documented?.compaction ?? "unknown"
347
434
  } },
348
435
  providerOptions: { language: declareProviderOptions(anthropicProviderOptions.language, declared ? true : "unknown", {
436
+ includePings: true,
349
437
  thinking: reasoningSupport,
350
438
  effort: documented?.effort ?? "unknown",
351
439
  speed: declared ? modelId === "claude-opus-4-6" : "unknown",
@@ -722,10 +810,12 @@ const anthropicResponseSchema = lazySchema(() => zodSchema(z.object({
722
810
  ])),
723
811
  stop_reason: z.string().nullish(),
724
812
  stop_sequence: z.string().nullish(),
813
+ service_tier: z.string().nullish(),
725
814
  stop_details: anthropicStopDetailsSchema().nullish(),
726
815
  input_transformations: z.array(anthropicInputTransformationSchema()).nullish(),
727
816
  safeguard_results: z.array(anthropicSafeguardResultSchema()).nullish(),
728
817
  usage: z.looseObject({
818
+ service_tier: z.string().nullish(),
729
819
  input_tokens: z.number(),
730
820
  output_tokens: z.number(),
731
821
  output_tokens_details: z.object({ thinking_tokens: z.number().nullish() }).nullish(),
@@ -775,7 +865,9 @@ const anthropicChunkSchema = lazySchema(() => zodSchema(z.discriminatedUnion("ty
775
865
  id: z.string().nullish(),
776
866
  model: z.string().nullish(),
777
867
  role: z.string().nullish(),
868
+ service_tier: z.string().nullish(),
778
869
  usage: z.looseObject({
870
+ service_tier: z.string().nullish(),
779
871
  input_tokens: z.number(),
780
872
  cache_creation_input_tokens: z.number().nullish(),
781
873
  cache_read_input_tokens: z.number().nullish()
@@ -1064,6 +1156,7 @@ const anthropicChunkSchema = lazySchema(() => zodSchema(z.discriminatedUnion("ty
1064
1156
  }).nullish()
1065
1157
  }),
1066
1158
  usage: z.looseObject({
1159
+ service_tier: z.string().nullish(),
1067
1160
  input_tokens: z.number().nullish(),
1068
1161
  output_tokens: z.number(),
1069
1162
  output_tokens_details: z.object({ thinking_tokens: z.number().nullish() }).nullish(),
@@ -1172,20 +1265,55 @@ const anthropicSystemMessageProviderOptions = lazySchema(() => zodSchema(z.objec
1172
1265
  * initial system prompt). A system message carrying tool changes must come
1173
1266
  * right before an assistant message or at the end of the messages.
1174
1267
  *
1175
- * Tools referenced by a `tool_addition` must be declared in the `tools`
1176
- * option (typically with `deferLoading: true` so they are not loaded until
1177
- * the addition surfaces them). The required
1178
- * `mid-conversation-tool-changes-2026-07-01` beta is added automatically.
1268
+ * A `tool_addition` either references a tool by `toolName` or defines it
1269
+ * by value with `tool`:
1270
+ * - By reference: the tool must be declared in the `tools` option
1271
+ * (typically with `deferLoading: true` so it is not loaded until the
1272
+ * addition surfaces it). The required
1273
+ * `mid-conversation-tool-changes-2026-07-01` beta is added
1274
+ * automatically.
1275
+ * - By value: `tool` is a function or provider tool, in the same shape as
1276
+ * an entry of the `tools` option. The tool does not need to be declared
1277
+ * in `tools`, and defining a tool under an existing name replaces it
1278
+ * from that point on. The required `inline-tools-2026-09-15` beta is
1279
+ * added automatically.
1280
+ *
1281
+ * A `tool_removal` always references the tool by `toolName`.
1179
1282
  */
1180
- toolChanges: z.array(z.discriminatedUnion("type", [z.object({
1181
- type: z.literal("tool_addition"),
1182
- toolName: z.string()
1183
- }), z.object({
1184
- type: z.literal("tool_removal"),
1185
- toolName: z.string()
1186
- })])).optional()
1283
+ toolChanges: z.array(z.union([
1284
+ z.object({
1285
+ type: z.literal("tool_addition"),
1286
+ toolName: z.string()
1287
+ }),
1288
+ z.object({
1289
+ type: z.literal("tool_addition"),
1290
+ tool: z.union([z.looseObject({
1291
+ type: z.literal("function"),
1292
+ name: z.string(),
1293
+ inputSchema: z.record(z.string(), z.unknown())
1294
+ }), z.looseObject({
1295
+ type: z.literal("provider"),
1296
+ id: z.string(),
1297
+ name: z.string(),
1298
+ args: z.record(z.string(), z.unknown())
1299
+ })])
1300
+ }),
1301
+ z.object({
1302
+ type: z.literal("tool_removal"),
1303
+ toolName: z.string()
1304
+ })
1305
+ ])).optional()
1187
1306
  })));
1188
1307
  const anthropicLanguageModelOptions = lazySchema(() => zodSchema(z.object({
1308
+ /**
1309
+ * Create or continue a short-lived server-side message thread.
1310
+ * On continuation, messages must contain only new messages. Keep the full
1311
+ * conversation locally so it can be replayed when the thread expires.
1312
+ */
1313
+ thread: z.discriminatedUnion("type", [z.object({ type: z.literal("create") }), z.object({
1314
+ type: z.literal("continue"),
1315
+ previousMessageId: z.string().min(1)
1316
+ })]).optional(),
1189
1317
  /**
1190
1318
  * Whether to send reasoning to the model.
1191
1319
  *
@@ -1204,6 +1332,8 @@ const anthropicLanguageModelOptions = lazySchema(() => zodSchema(z.object({
1204
1332
  "jsonTool",
1205
1333
  "auto"
1206
1334
  ]).optional(),
1335
+ /** Emit typed streaming heartbeat parts. Disabled by default. */
1336
+ includePings: z.boolean().optional(),
1207
1337
  /**
1208
1338
  * Configuration for enabling Claude's extended thinking.
1209
1339
  *
@@ -1353,8 +1483,17 @@ userId: z.string().optional() }).optional(),
1353
1483
  * Only supported with claude-opus-4-6.
1354
1484
  */
1355
1485
  speed: z.enum(["fast", "standard"]).optional(),
1356
- /** Selects Anthropic's service tier for the request. */
1357
- serviceTier: z.enum(["auto", "standard_only"]).optional(),
1486
+ /**
1487
+ * Request admission tier. Anthropic accepts `auto` and `standard_only`;
1488
+ * MiniMax accepts `standard` and `priority`. Values for another known
1489
+ * provider are omitted with an unsupported-setting warning.
1490
+ */
1491
+ serviceTier: z.enum([
1492
+ "auto",
1493
+ "standard_only",
1494
+ "standard",
1495
+ "priority"
1496
+ ]).optional(),
1358
1497
  /**
1359
1498
  * Controls where model inference runs for this request.
1360
1499
  *
@@ -1466,10 +1605,11 @@ function getCacheControl(providerMetadata, providerOptionsName) {
1466
1605
  return custom?.cacheControl ?? custom?.cache_control ?? anthropic?.cacheControl ?? anthropic?.cache_control;
1467
1606
  }
1468
1607
  var CacheControlValidator = class {
1469
- constructor(providerOptionsName = "anthropic") {
1608
+ constructor(providerOptionsName = "anthropic", initialBreakpointCount = 0) {
1470
1609
  this.providerOptionsName = providerOptionsName;
1471
1610
  this.breakpointCount = 0;
1472
1611
  this.warnings = [];
1612
+ this.breakpointCount = initialBreakpointCount;
1473
1613
  }
1474
1614
  getCacheControl(providerMetadata, context) {
1475
1615
  const cacheControlValue = getCacheControl(providerMetadata, this.providerOptionsName);
@@ -1826,19 +1966,19 @@ const webFetch_20250910 = (args = {}) => {
1826
1966
  };
1827
1967
  //#endregion
1828
1968
  //#region src/anthropic-prepare-tools.ts
1829
- async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming = false, rejectsForcedToolUse = false }) {
1969
+ async function prepareTools({ tools, toolChoice, hasInlineTools = false, disableParallelToolUse, cacheControlValidator, supportsStructuredOutput, supportsStrictTools, defaultEagerInputStreaming = false, rejectsForcedToolUse = false }) {
1830
1970
  tools = tools?.length ? tools : void 0;
1831
1971
  const toolWarnings = [];
1832
1972
  const betas = /* @__PURE__ */ new Set();
1833
1973
  const validator = cacheControlValidator || new CacheControlValidator();
1834
- if (tools == null) return {
1974
+ if (tools == null && !hasInlineTools) return {
1835
1975
  tools: void 0,
1836
1976
  toolChoice: void 0,
1837
1977
  toolWarnings,
1838
1978
  betas
1839
1979
  };
1840
1980
  const anthropicTools = [];
1841
- for (const tool of tools) switch (tool.type) {
1981
+ for (const tool of tools ?? []) switch (tool.type) {
1842
1982
  case "function": {
1843
1983
  const cacheControl = validator.getCacheControl(tool.providerOptions, {
1844
1984
  type: "tool definition",
@@ -1864,7 +2004,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
1864
2004
  ...allowedCallers != null ? { allowed_callers: allowedCallers } : {},
1865
2005
  ...tool.inputExamples != null ? { input_examples: tool.inputExamples.map((example) => example.input) } : {}
1866
2006
  });
1867
- if (supportsStructuredOutput === true) betas.add("structured-outputs-2025-11-13");
2007
+ if (supportsStructuredOutput === true && supportsStrictTools === true) betas.add("structured-outputs-2025-11-13");
1868
2008
  if (tool.inputExamples != null || allowedCallers != null) betas.add("advanced-tool-use-2025-11-20");
1869
2009
  break;
1870
2010
  }
@@ -2145,8 +2285,9 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2145
2285
  feature: `tool ${tool}`
2146
2286
  });
2147
2287
  }
2288
+ const declaredTools = tools == null ? void 0 : anthropicTools;
2148
2289
  if (toolChoice == null) return {
2149
- tools: anthropicTools,
2290
+ tools: declaredTools,
2150
2291
  toolChoice: disableParallelToolUse ? {
2151
2292
  type: "auto",
2152
2293
  disable_parallel_tool_use: disableParallelToolUse
@@ -2157,7 +2298,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2157
2298
  const type = toolChoice.type;
2158
2299
  switch (type) {
2159
2300
  case "auto": return {
2160
- tools: anthropicTools,
2301
+ tools: declaredTools,
2161
2302
  toolChoice: {
2162
2303
  type: "auto",
2163
2304
  disable_parallel_tool_use: disableParallelToolUse
@@ -2173,7 +2314,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2173
2314
  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."
2174
2315
  });
2175
2316
  return {
2176
- tools: anthropicTools,
2317
+ tools: declaredTools,
2177
2318
  toolChoice: {
2178
2319
  type: "auto",
2179
2320
  disable_parallel_tool_use: disableParallelToolUse
@@ -2183,7 +2324,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2183
2324
  };
2184
2325
  }
2185
2326
  return {
2186
- tools: anthropicTools,
2327
+ tools: declaredTools,
2187
2328
  toolChoice: {
2188
2329
  type: "any",
2189
2330
  disable_parallel_tool_use: disableParallelToolUse
@@ -2192,7 +2333,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2192
2333
  betas
2193
2334
  };
2194
2335
  case "none": return {
2195
- tools: anthropicTools,
2336
+ tools: declaredTools,
2196
2337
  toolChoice: { type: "none" },
2197
2338
  toolWarnings,
2198
2339
  betas
@@ -2205,7 +2346,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2205
2346
  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.`
2206
2347
  });
2207
2348
  return {
2208
- tools: anthropicTools.filter((tool) => "name" in tool && tool.name === toolChoice.toolName),
2349
+ tools: declaredTools?.filter((tool) => "name" in tool && tool.name === toolChoice.toolName),
2209
2350
  toolChoice: {
2210
2351
  type: "auto",
2211
2352
  disable_parallel_tool_use: disableParallelToolUse
@@ -2215,7 +2356,7 @@ async function prepareTools({ tools, toolChoice, disableParallelToolUse, cacheCo
2215
2356
  };
2216
2357
  }
2217
2358
  return {
2218
- tools: anthropicTools,
2359
+ tools: declaredTools,
2219
2360
  toolChoice: {
2220
2361
  type: "tool",
2221
2362
  name: toolChoice.toolName,
@@ -2593,7 +2734,31 @@ function extractErrorValue(value) {
2593
2734
  }
2594
2735
  return {};
2595
2736
  }
2596
- async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping, toolsetNames = {}, convertMediaPart }) {
2737
+ function isComputerTool(tool) {
2738
+ return tool.type === "provider" && tool.id.startsWith("anthropic.computer_");
2739
+ }
2740
+ /**
2741
+ * Collects the tools that mid-conversation tool changes add by value, so they
2742
+ * can take part in tool name mapping like the tools of the `tools` option.
2743
+ * Tools that cannot be added by value are left out because they are ignored.
2744
+ */
2745
+ async function getInlineToolsFromPrompt(prompt) {
2746
+ const inlineTools = [];
2747
+ for (const message of prompt) {
2748
+ if (message.role !== "system" || message.providerOptions == null) continue;
2749
+ const options = await parseProviderOptions({
2750
+ provider: "anthropic",
2751
+ providerOptions: message.providerOptions,
2752
+ schema: anthropicSystemMessageProviderOptions
2753
+ });
2754
+ for (const toolChange of options?.toolChanges ?? []) if ("tool" in toolChange) {
2755
+ const tool = toolChange.tool;
2756
+ if (!isComputerTool(tool)) inlineTools.push(tool);
2757
+ }
2758
+ }
2759
+ return inlineTools;
2760
+ }
2761
+ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cacheControlValidator, toolNameMapping, toolsetNames = {}, convertMediaPart, convertInlineTool }) {
2597
2762
  const betas = /* @__PURE__ */ new Set();
2598
2763
  const blocks = groupIntoBlocks(prompt);
2599
2764
  const validator = cacheControlValidator || new CacheControlValidator();
@@ -2648,18 +2813,50 @@ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cache
2648
2813
  canCache: true
2649
2814
  })
2650
2815
  });
2651
- for (const toolChange of toolChanges) content.push({
2652
- type: toolChange.type,
2653
- tool: {
2654
- type: "tool_reference",
2655
- name: toolNameMapping.toProviderToolName(toolChange.toolName)
2816
+ let toolChangeCount = 0;
2817
+ let hasInlineToolDefinition = false;
2818
+ for (const toolChange of toolChanges) {
2819
+ if ("tool" in toolChange) {
2820
+ if (convertInlineTool == null) throw new UnsupportedFunctionalityError({ functionality: "tool additions by value in mid-conversation tool changes" });
2821
+ const tool = toolChange.tool;
2822
+ if (isComputerTool(tool)) {
2823
+ warnings.push({
2824
+ type: "other",
2825
+ 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.`
2826
+ });
2827
+ continue;
2828
+ }
2829
+ const { definition, warnings: toolWarnings, betas: toolBetas } = await convertInlineTool(tool);
2830
+ warnings.push(...toolWarnings);
2831
+ for (const beta of toolBetas) betas.add(beta);
2832
+ if (definition == null) continue;
2833
+ content.push({
2834
+ type: "tool_addition",
2835
+ tool: {
2836
+ type: "tool_definition",
2837
+ definition
2838
+ }
2839
+ });
2840
+ toolChangeCount++;
2841
+ hasInlineToolDefinition = true;
2842
+ continue;
2656
2843
  }
2657
- });
2844
+ content.push({
2845
+ type: toolChange.type,
2846
+ tool: {
2847
+ type: "tool_reference",
2848
+ name: toolNameMapping.toProviderToolName(toolChange.toolName)
2849
+ }
2850
+ });
2851
+ toolChangeCount++;
2852
+ }
2853
+ if (content.length === 0 && systemMessageOptions?.clearAt == null && systemMessageOptions?.effort == null) continue;
2658
2854
  convertedMessages.push({
2659
2855
  content,
2660
2856
  clearAt: systemMessageOptions?.clearAt,
2661
2857
  effort: systemMessageOptions?.effort,
2662
- toolChangeCount: toolChanges.length
2858
+ toolChangeCount,
2859
+ hasInlineToolDefinition
2663
2860
  });
2664
2861
  }
2665
2862
  const toolChangeCount = convertedMessages.reduce((count, message) => count + message.toolChangeCount, 0);
@@ -2690,7 +2887,8 @@ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cache
2690
2887
  ...message.clearAt != null && { clear_at: message.clearAt },
2691
2888
  ...message.effort != null && { output_config: { effort: message.effort } }
2692
2889
  });
2693
- if (message.toolChangeCount > 0) betas.add("mid-conversation-tool-changes-2026-07-01");
2890
+ if (message.hasInlineToolDefinition) betas.add("inline-tools-2026-09-15");
2891
+ else if (message.toolChangeCount > 0) betas.add("mid-conversation-tool-changes-2026-07-01");
2694
2892
  if (message.clearAt != null) betas.add("mid-conversation-system-clear-at-2026-08-21");
2695
2893
  if (message.effort != null) betas.add("mid-conversation-output-config-2026-07-01");
2696
2894
  }
@@ -2995,7 +3193,7 @@ async function convertToAnthropicPrompt({ prompt, sendReasoning, warnings, cache
2995
3193
  for (let j = 0; j < block.messages.length; j++) {
2996
3194
  const message = block.messages[j];
2997
3195
  const isLastMessage = j === block.messages.length - 1;
2998
- const { content } = message;
3196
+ const content = message.content.filter((part) => part.type !== "text" || part.text.length > 0);
2999
3197
  for (let k = 0; k < content.length; k++) {
3000
3198
  const part = content[k];
3001
3199
  const isLastContentPart = k === content.length - 1;
@@ -4121,6 +4319,17 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4121
4319
  }) : null;
4122
4320
  const usedCustomProviderKey = customProviderOptions != null;
4123
4321
  const anthropicOptions = Object.assign({}, canonicalOptions ?? {}, customProviderOptions ?? {});
4322
+ if (anthropicOptions.serviceTier != null) {
4323
+ const supportedTiers = providerOptionsName === "anthropic" ? ["auto", "standard_only"] : providerOptionsName === "minimax" ? ["standard", "priority"] : void 0;
4324
+ if (supportedTiers != null && !supportedTiers.includes(anthropicOptions.serviceTier)) {
4325
+ warnings.push({
4326
+ type: "unsupported",
4327
+ feature: "serviceTier",
4328
+ details: `serviceTier "${anthropicOptions.serviceTier}" is not supported by ${providerOptionsName}. Use ${supportedTiers.map((tier) => `"${tier}"`).join(" or ")}.`
4329
+ });
4330
+ anthropicOptions.serviceTier = void 0;
4331
+ }
4332
+ }
4124
4333
  const { maxOutputTokens: maxOutputTokensForModel, supportsStructuredOutput: modelSupportsStructuredOutput, supportsAdaptiveThinking, rejectsSamplingParameters, supportsXhighEffort, rejectsThinkingDisabledAboveHighEffort, rejectsThinkingDisabled, rejectsBudgetThinking, rejectsForcedToolUse, supportsBetweenToolsThinking, isKnownModel } = getAnthropicModelCapabilities(modelId);
4125
4334
  if (!isKnownModel && maxOutputTokens == null) warnings.push({
4126
4335
  type: "compatibility",
@@ -4184,9 +4393,20 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4184
4393
  argument: "providerOptions",
4185
4394
  message: "Anthropic provider options `compaction` and `contextManagement` cannot be used together."
4186
4395
  });
4187
- const cacheControlValidator = new CacheControlValidator(config.cacheControlProviderOptionsName);
4396
+ const thread = anthropicOptions?.thread;
4397
+ if (thread != null && config.supportsMessageThreads !== true) throw new UnsupportedFunctionalityError({
4398
+ functionality: "Anthropic message threads",
4399
+ message: `${config.provider} does not support Anthropic message threads.`
4400
+ });
4401
+ if (thread != null && (compaction != null || contextManagement?.edits.some((edit) => edit.type !== "clear_thinking_20251015" || edit.keep !== "all"))) throw new InvalidArgumentError({
4402
+ argument: "providerOptions.anthropic.thread",
4403
+ message: "Anthropic message threads do not support compaction or context editing, except clear_thinking_20251015 with keep: \"all\"."
4404
+ });
4405
+ const cacheControlValidator = new CacheControlValidator(config.cacheControlProviderOptionsName, thread != null && anthropicOptions?.cacheControl != null ? 1 : 0);
4406
+ const defaultEagerInputStreaming = stream && (anthropicOptions?.toolStreaming ?? true);
4407
+ const inlineTools = await getInlineToolsFromPrompt(prompt);
4188
4408
  const toolNameMapping = createToolNameMapping({
4189
- tools,
4409
+ tools: [...inlineTools, ...tools ?? []],
4190
4410
  providerToolNames: {
4191
4411
  "anthropic.code_execution_20250522": "code_execution",
4192
4412
  "anthropic.code_execution_20250825": "code_execution",
@@ -4221,8 +4441,35 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4221
4441
  cacheControlValidator,
4222
4442
  toolNameMapping,
4223
4443
  toolsetNames,
4224
- convertMediaPart: config.convertMediaPart
4444
+ convertMediaPart: config.convertMediaPart,
4445
+ convertInlineTool: async (tool) => {
4446
+ const { tools: definitions, toolWarnings, betas } = await prepareTools({
4447
+ tools: [tool],
4448
+ toolChoice: void 0,
4449
+ cacheControlValidator,
4450
+ supportsStructuredOutput,
4451
+ supportsStrictTools
4452
+ });
4453
+ return {
4454
+ definition: definitions?.[0],
4455
+ warnings: toolWarnings,
4456
+ betas
4457
+ };
4458
+ }
4225
4459
  });
4460
+ if (thread != null) {
4461
+ const unpinnedBetas = [...betas].filter((beta) => !userSuppliedBetas.has(beta) && !anthropicOptions?.anthropicBeta?.includes(beta));
4462
+ if (unpinnedBetas.length > 0) warnings.push({
4463
+ type: "compatibility",
4464
+ feature: "providerOptions.anthropic.thread",
4465
+ 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.`
4466
+ });
4467
+ if (thread.type === "continue" && (messagesPrompt.system != null || (tools?.length ?? 0) > 0)) warnings.push({
4468
+ type: "compatibility",
4469
+ feature: "providerOptions.anthropic.thread",
4470
+ 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."
4471
+ });
4472
+ }
4226
4473
  if (isCustomReasoning(reasoning) && anthropicOptions?.effort == null) {
4227
4474
  const reasoningConfig = resolveAnthropicReasoningConfig({
4228
4475
  reasoning,
@@ -4340,7 +4587,11 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4340
4587
  version: skill.version
4341
4588
  }))
4342
4589
  } : anthropicOptions.container.id },
4343
- system: messagesPrompt.system,
4590
+ system: thread?.type === "continue" ? void 0 : messagesPrompt.system,
4591
+ ...thread != null && { thread: thread.type === "create" ? { type: "create" } : {
4592
+ type: "continue",
4593
+ previous_message_id: thread.previousMessageId
4594
+ } },
4344
4595
  messages: messagesPrompt.messages,
4345
4596
  ...anthropicOptions?.safeguards && anthropicOptions.safeguards.length > 0 && { safeguards: anthropicOptions.safeguards.map((safeguard) => ({
4346
4597
  type: safeguard.type,
@@ -4456,7 +4707,6 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4456
4707
  if (thinkingBlockBinding != null) betas.add("thinking-binding-controls-2026-08-01");
4457
4708
  if (anthropicOptions?.fallbacks === "default") betas.add("server-side-fallback-2026-07-01");
4458
4709
  else if (anthropicOptions?.fallbacks && anthropicOptions.fallbacks.length > 0) betas.add("server-side-fallback-2026-06-01");
4459
- const defaultEagerInputStreaming = stream && (anthropicOptions?.toolStreaming ?? true);
4460
4710
  const { tools: anthropicTools, toolChoice: anthropicToolChoice, toolWarnings, betas: toolsBetas } = await prepareTools(jsonResponseTool != null ? {
4461
4711
  tools: [...(tools ?? []).filter((tool) => toolChoice?.type !== "none" && (toolChoice?.type !== "tool" || tool.name === toolChoice.toolName)), jsonResponseTool],
4462
4712
  toolChoice: { type: "required" },
@@ -4469,6 +4719,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4469
4719
  } : {
4470
4720
  tools: tools ?? [],
4471
4721
  toolChoice,
4722
+ hasInlineTools: inlineTools.length > 0,
4472
4723
  disableParallelToolUse: anthropicOptions?.disableParallelToolUse,
4473
4724
  cacheControlValidator,
4474
4725
  supportsStructuredOutput,
@@ -4480,7 +4731,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4480
4731
  return {
4481
4732
  args: {
4482
4733
  ...baseArgs,
4483
- tools: anthropicTools,
4734
+ tools: thread?.type === "continue" ? void 0 : anthropicTools,
4484
4735
  tool_choice: anthropicToolChoice,
4485
4736
  stream: stream === true ? true : void 0
4486
4737
  },
@@ -4490,12 +4741,15 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4490
4741
  ...cacheWarnings
4491
4742
  ],
4492
4743
  betas: /* @__PURE__ */ new Set([
4744
+ ...thread != null ? ["message-threads-2026-08-12"] : [],
4493
4745
  ...betas,
4494
4746
  ...toolsBetas,
4495
4747
  ...userSuppliedBetas,
4496
4748
  ...anthropicOptions?.anthropicBeta ?? []
4497
4749
  ]),
4750
+ markCodeExecutionDynamic: hasDynamicFilteringWebToolWithoutCodeExecution(anthropicTools),
4498
4751
  usesJsonResponseTool: jsonResponseTool != null,
4752
+ includePings: stream === true && anthropicOptions?.includePings === true,
4499
4753
  toolNameMapping,
4500
4754
  providerOptionsName,
4501
4755
  usedCustomProviderKey
@@ -4540,13 +4794,12 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4540
4794
  }
4541
4795
  async doGenerate(options) {
4542
4796
  const configHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
4543
- const { args, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
4797
+ const { args, warnings, betas, usesJsonResponseTool, markCodeExecutionDynamic, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
4544
4798
  ...options,
4545
4799
  stream: false,
4546
4800
  userSuppliedBetas: this.getBetasFromHeaders(configHeaders, options.headers)
4547
4801
  });
4548
4802
  const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
4549
- const markCodeExecutionDynamic = hasDynamicFilteringWebToolWithoutCodeExecution(args.tools);
4550
4803
  const { responseHeaders, value: response, rawValue: rawResponse } = await postJsonToApi({
4551
4804
  url: this.buildRequestUrl(false),
4552
4805
  headers: await this.getHeaders({
@@ -4929,9 +5182,11 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4929
5182
  warnings,
4930
5183
  providerMetadata: (() => {
4931
5184
  const stopDetails = mapAnthropicStopDetails$1(response.stop_details);
5185
+ const serviceTier = response.usage.service_tier ?? response.service_tier;
4932
5186
  const anthropicMetadata = {
4933
5187
  usage: response.usage,
4934
5188
  stopSequence: response.stop_sequence ?? null,
5189
+ ...serviceTier != null ? { serviceTier } : {},
4935
5190
  ...stopDetails != null ? { stopDetails } : {},
4936
5191
  ...response.input_transformations != null ? { inputTransformations: response.input_transformations } : {},
4937
5192
  ...response.safeguard_results != null ? { safeguardResults: response.safeguard_results } : {},
@@ -4963,13 +5218,12 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
4963
5218
  async doStream(options) {
4964
5219
  "use step";
4965
5220
  const configHeaders = this.config.headers ? await resolve(this.config.headers) : void 0;
4966
- const { args: body, warnings, betas, usesJsonResponseTool, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
5221
+ const { args: body, warnings, betas, usesJsonResponseTool, markCodeExecutionDynamic, includePings, toolNameMapping, providerOptionsName, usedCustomProviderKey } = await this.getArgs({
4967
5222
  ...options,
4968
5223
  stream: true,
4969
5224
  userSuppliedBetas: this.getBetasFromHeaders(configHeaders, options.headers)
4970
5225
  });
4971
5226
  const citationDocuments = [...this.extractCitationDocuments(options.prompt)];
4972
- const markCodeExecutionDynamic = hasDynamicFilteringWebToolWithoutCodeExecution(body.tools);
4973
5227
  const url = this.buildRequestUrl(true);
4974
5228
  const { responseHeaders, value: response } = await postJsonToApi({
4975
5229
  url,
@@ -5002,6 +5256,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5002
5256
  let contextManagement = null;
5003
5257
  let rawUsage = void 0;
5004
5258
  let stopSequence = null;
5259
+ let serviceTier = null;
5005
5260
  let stopDetails = void 0;
5006
5261
  let inputTransformations;
5007
5262
  let safeguardResults;
@@ -5046,7 +5301,9 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5046
5301
  }
5047
5302
  const value = chunk.value;
5048
5303
  switch (value.type) {
5049
- case "ping": return;
5304
+ case "ping":
5305
+ if (includePings) controller.enqueue({ type: "ping" });
5306
+ return;
5050
5307
  case "content_block_start": {
5051
5308
  const part = value.content_block;
5052
5309
  const contentBlockType = part.type;
@@ -5610,6 +5867,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5610
5867
  });
5611
5868
  return;
5612
5869
  }
5870
+ serviceTier = value.message.usage.service_tier ?? value.message.service_tier ?? null;
5613
5871
  isMessageOpen = true;
5614
5872
  activeMessageId = value.message.id;
5615
5873
  heldBackTextByIndex.clear();
@@ -5701,6 +5959,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5701
5959
  if (value.context_management) contextManagement = mapAnthropicResponseContextManagement$1(value.context_management);
5702
5960
  if (value.input_transformations != null) inputTransformations = value.input_transformations;
5703
5961
  if (value.delta.safeguard_results != null) safeguardResults = value.delta.safeguard_results;
5962
+ serviceTier = value.usage.service_tier ?? serviceTier;
5704
5963
  rawUsage = {
5705
5964
  ...rawUsage,
5706
5965
  ...value.usage
@@ -5712,6 +5971,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5712
5971
  const anthropicMetadata = {
5713
5972
  usage: rawUsage ?? null,
5714
5973
  stopSequence,
5974
+ ...serviceTier != null ? { serviceTier } : {},
5715
5975
  ...stopDetails != null ? { stopDetails } : {},
5716
5976
  ...inputTransformations != null ? { inputTransformations } : {},
5717
5977
  ...safeguardResults != null ? { safeguardResults } : {},
@@ -5821,7 +6081,7 @@ var AnthropicLanguageModel = class AnthropicLanguageModel {
5821
6081
  try {
5822
6082
  await firstChunkReader.read();
5823
6083
  let result = await firstChunkReader.read();
5824
- if (result.value?.type === "raw") result = await firstChunkReader.read();
6084
+ while (result.value?.type === "raw" || result.value?.type === "ping") result = await firstChunkReader.read();
5825
6085
  if (result.value?.type === "error") {
5826
6086
  const error = result.value.error;
5827
6087
  if (!isProviderStreamError(error)) throw new Error("Expected a normalized Anthropic stream error");
@@ -6054,6 +6314,10 @@ var AnthropicBatch = class {
6054
6314
  userSuppliedBetas: new Set(explicitBatchBetas)
6055
6315
  }
6056
6316
  });
6317
+ if (prepared.args.thread != null) throw new UnsupportedFunctionalityError({
6318
+ functionality: "message threads in batches",
6319
+ message: `Anthropic Message Batches do not support message threads (request "${request.id}").`
6320
+ });
6057
6321
  if (prepared.usesJsonResponseTool) throw new UnsupportedFunctionalityError({
6058
6322
  functionality: "batch responseFormat JSON-tool fallback",
6059
6323
  message: `Anthropic Message Batches cannot decode the JSON-tool structured-output fallback (request "${request.id}") because batch results are retrieved independently of the start call. Use a model that supports native output_format structured outputs.`
@@ -6614,9 +6878,11 @@ function anthropicCallerMetadata(caller) {
6614
6878
  }
6615
6879
  function convertAnthropicMessageMetadata(response) {
6616
6880
  const stopDetails = mapAnthropicStopDetails(response.stop_details);
6881
+ const serviceTier = response.usage.service_tier ?? response.service_tier;
6617
6882
  return {
6618
6883
  usage: response.usage,
6619
6884
  stopSequence: response.stop_sequence ?? null,
6885
+ ...serviceTier != null ? { serviceTier } : {},
6620
6886
  ...stopDetails != null ? { stopDetails } : {},
6621
6887
  ...response.input_transformations != null ? { inputTransformations: response.input_transformations } : {},
6622
6888
  ...response.safeguard_results != null ? { safeguardResults: response.safeguard_results } : {},
@@ -7349,7 +7615,7 @@ var AnthropicSkills = class {
7349
7615
  };
7350
7616
  //#endregion
7351
7617
  //#region src/version.ts
7352
- const VERSION = "4.0.96";
7618
+ const VERSION = "4.0.98";
7353
7619
  //#endregion
7354
7620
  //#region src/anthropic-provider.ts
7355
7621
  const ANTHROPIC_API_URL = "https://api.anthropic.com";
@@ -7395,6 +7661,7 @@ function createAnthropic(options = {}) {
7395
7661
  };
7396
7662
  const languageModelConfig = {
7397
7663
  provider: providerName,
7664
+ supportsMessageThreads: true,
7398
7665
  baseURL,
7399
7666
  headers: getHeaders,
7400
7667
  fetch: options.fetch,