@opencode/ai 2.2.7 → 2.3.1

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.
Files changed (158) hide show
  1. package/README.md +164 -99
  2. package/dist/cache-policy.js +4 -2
  3. package/dist/effect.d.ts +11 -8
  4. package/dist/effect.js +2 -1
  5. package/dist/experimental.d.ts +0 -4
  6. package/dist/experimental.js +0 -3
  7. package/dist/generation.d.ts +10 -10
  8. package/dist/generation.js +8 -14
  9. package/dist/image-client.d.ts +56 -59
  10. package/dist/image-client.js +47 -12
  11. package/dist/image.d.ts +36 -95
  12. package/dist/image.js +11 -14
  13. package/dist/index.d.ts +31 -68
  14. package/dist/index.js +54 -30
  15. package/dist/llm.d.ts +4 -1
  16. package/dist/llm.js +10 -1
  17. package/dist/media-client.d.ts +18 -6
  18. package/dist/media-client.js +42 -37
  19. package/dist/media-model.d.ts +2 -0
  20. package/dist/media-model.js +3 -1
  21. package/dist/media.d.ts +26 -4
  22. package/dist/media.js +52 -11
  23. package/dist/protocols/alibaba-messages.d.ts +24 -2
  24. package/dist/protocols/alibaba-responses.d.ts +26 -0
  25. package/dist/protocols/anthropic-messages.d.ts +70 -6
  26. package/dist/protocols/anthropic-messages.js +74 -9
  27. package/dist/protocols/assemblyai-transcription.js +7 -6
  28. package/dist/protocols/cartesia-speech.d.ts +0 -8
  29. package/dist/protocols/deepgram-speech.d.ts +0 -8
  30. package/dist/protocols/elevenlabs-speech.d.ts +0 -8
  31. package/dist/protocols/google-decisions.d.ts +13 -0
  32. package/dist/protocols/google-decisions.js +133 -0
  33. package/dist/protocols/google-interactions-video.d.ts +38 -0
  34. package/dist/protocols/google-interactions-video.js +185 -0
  35. package/dist/protocols/google-interactions.d.ts +14 -1
  36. package/dist/protocols/google-interactions.js +1 -1
  37. package/dist/protocols/google-speech.d.ts +0 -8
  38. package/dist/protocols/google-transcription.d.ts +0 -8
  39. package/dist/protocols/index.d.ts +1 -0
  40. package/dist/protocols/index.js +1 -0
  41. package/dist/protocols/meta-messages.d.ts +24 -2
  42. package/dist/protocols/meta-responses.d.ts +52 -0
  43. package/dist/protocols/minimax-video.d.ts +45 -0
  44. package/dist/protocols/minimax-video.js +290 -0
  45. package/dist/protocols/open-responses.d.ts +250 -24
  46. package/dist/protocols/open-responses.js +40 -24
  47. package/dist/protocols/openai-chat.js +7 -3
  48. package/dist/protocols/openai-compatible-responses.d.ts +26 -0
  49. package/dist/protocols/openai-freeform.d.ts +1 -1
  50. package/dist/protocols/openai-freeform.js +9 -5
  51. package/dist/protocols/openai-images.d.ts +0 -8
  52. package/dist/protocols/openai-responses.d.ts +153 -0
  53. package/dist/protocols/openai-responses.js +68 -7
  54. package/dist/protocols/openai-speech.d.ts +0 -8
  55. package/dist/protocols/openai-transcription.d.ts +0 -8
  56. package/dist/protocols/openrouter-video.d.ts +36 -0
  57. package/dist/protocols/openrouter-video.js +139 -0
  58. package/dist/protocols/seedance-video.d.ts +45 -0
  59. package/dist/protocols/seedance-video.js +217 -0
  60. package/dist/protocols/system-one.d.ts +45 -1
  61. package/dist/protocols/system-one.js +42 -7
  62. package/dist/protocols/utils/gateway-protocol.js +1 -0
  63. package/dist/protocols/utils/responses-compaction.js +8 -4
  64. package/dist/protocols/xai-responses.d.ts +26 -0
  65. package/dist/protocols/xai-video.d.ts +12 -11
  66. package/dist/protocols/xai-video.js +33 -24
  67. package/dist/protocols/zai-messages.d.ts +24 -2
  68. package/dist/provider-error.js +7 -1
  69. package/dist/providers/alibaba.d.ts +50 -2
  70. package/dist/providers/amazon-bedrock-mantle.d.ts +50 -2
  71. package/dist/providers/anthropic-compatible.d.ts +24 -2
  72. package/dist/providers/anthropic.d.ts +24 -2
  73. package/dist/providers/azure.d.ts +76 -2
  74. package/dist/providers/byteplus/videos.d.ts +2 -0
  75. package/dist/providers/byteplus/videos.js +1 -0
  76. package/dist/providers/byteplus.d.ts +26 -0
  77. package/dist/providers/byteplus.js +21 -0
  78. package/dist/providers/cloudflare-ai-gateway.d.ts +100 -4
  79. package/dist/providers/digitalocean.d.ts +26 -0
  80. package/dist/providers/google/decisions.d.ts +2 -0
  81. package/dist/providers/google/decisions.js +1 -0
  82. package/dist/providers/google/videos.d.ts +2 -0
  83. package/dist/providers/google/videos.js +1 -0
  84. package/dist/providers/google-vertex-messages.d.ts +24 -2
  85. package/dist/providers/google-vertex-messages.js +1 -0
  86. package/dist/providers/google-vertex-responses.d.ts +26 -0
  87. package/dist/providers/google.d.ts +11 -4
  88. package/dist/providers/google.js +16 -3
  89. package/dist/providers/index.d.ts +2 -1
  90. package/dist/providers/index.js +2 -1
  91. package/dist/providers/meta.d.ts +50 -2
  92. package/dist/providers/minimax/videos.d.ts +3 -0
  93. package/dist/providers/minimax/videos.js +1 -0
  94. package/dist/providers/minimax.d.ts +56 -3
  95. package/dist/providers/minimax.js +10 -1
  96. package/dist/providers/moonshot.d.ts +50 -2
  97. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  98. package/dist/providers/openai-compatible/decisions.js +1 -0
  99. package/dist/providers/openai-compatible-responses.d.ts +26 -0
  100. package/dist/providers/openai-compatible.d.ts +2 -0
  101. package/dist/providers/openai-compatible.js +14 -0
  102. package/dist/providers/openai.d.ts +26 -0
  103. package/dist/providers/openrouter/videos.d.ts +2 -0
  104. package/dist/providers/openrouter/videos.js +1 -0
  105. package/dist/providers/openrouter.d.ts +31 -0
  106. package/dist/providers/openrouter.js +8 -0
  107. package/dist/providers/venice.d.ts +26 -0
  108. package/dist/providers/volcengine/videos.d.ts +2 -0
  109. package/dist/providers/volcengine/videos.js +1 -0
  110. package/dist/providers/volcengine.d.ts +26 -0
  111. package/dist/providers/volcengine.js +21 -0
  112. package/dist/providers/xai/videos.d.ts +2 -0
  113. package/dist/providers/xai/videos.js +1 -0
  114. package/dist/providers/xai.d.ts +4 -3
  115. package/dist/providers/xai.js +5 -1
  116. package/dist/providers/zai-coding-plan.d.ts +50 -2
  117. package/dist/public.d.ts +7 -4
  118. package/dist/public.js +2 -1
  119. package/dist/route/client.d.ts +2 -0
  120. package/dist/route/client.js +5 -1
  121. package/dist/route/executor-service.d.ts +20 -1
  122. package/dist/route/executor-service.js +35 -1
  123. package/dist/route/executor.d.ts +11 -2
  124. package/dist/route/executor.js +25 -5
  125. package/dist/route/media-protocol.d.ts +21 -15
  126. package/dist/route/media-protocol.js +11 -4
  127. package/dist/route/media.d.ts +2 -0
  128. package/dist/route/media.js +40 -22
  129. package/dist/route/protocol.d.ts +3 -0
  130. package/dist/route/transport/http.js +1 -1
  131. package/dist/schema/events.d.ts +5 -0
  132. package/dist/schema/messages.d.ts +25 -2
  133. package/dist/schema/messages.js +27 -7
  134. package/dist/schema/options.d.ts +18 -2
  135. package/dist/schema/options.js +1 -0
  136. package/dist/speech-client.d.ts +6 -6
  137. package/dist/speech-client.js +4 -4
  138. package/dist/speech.d.ts +7 -88
  139. package/dist/speech.js +1 -3
  140. package/dist/tool-updates.d.ts +34 -0
  141. package/dist/tool-updates.js +93 -0
  142. package/dist/tool.d.ts +6 -1
  143. package/dist/tool.js +1 -1
  144. package/dist/transcription-client.d.ts +6 -6
  145. package/dist/transcription-client.js +1 -2
  146. package/dist/transcription.d.ts +7 -88
  147. package/dist/transcription.js +1 -3
  148. package/dist/video-client.d.ts +16 -84
  149. package/dist/video-client.js +30 -13
  150. package/dist/video.d.ts +54 -1126
  151. package/dist/video.js +29 -65
  152. package/package.json +59 -7
  153. package/dist/protocols/google-video.d.ts +0 -26
  154. package/dist/protocols/google-video.js +0 -146
  155. package/dist/protocols/runway-video.d.ts +0 -38
  156. package/dist/protocols/runway-video.js +0 -141
  157. package/dist/providers/runway.d.ts +0 -20
  158. package/dist/providers/runway.js +0 -17
package/dist/media.js CHANGED
@@ -1,11 +1,11 @@
1
1
  export * as Media from "./media.js";
2
- import { Effect, FileSystem, Result, Schema, SchemaGetter } from "effect";
2
+ import { Effect, FileSystem, Result, Schema, SchemaGetter, Stream } from "effect";
3
3
  import { Base64 } from "effect/encoding";
4
4
  import { HttpClientRequest } from "effect/http";
5
5
  import { ProviderID } from "./schema/ids.js";
6
6
  import { AIError, InvalidProviderOutputError, InvalidRequestError } from "./schema/errors.js";
7
7
  import { ProviderMetadata } from "./schema/options.js";
8
- import { responseHttp, Service } from "./route/executor-service.js";
8
+ import { CurrentMiddleware, responseHttp, Service } from "./route/executor-service.js";
9
9
  import { detectMediaType, fileMediaType } from "./utils/media-type.js";
10
10
  export { detectMediaType } from "./utils/media-type.js";
11
11
  const OCTET_STREAM = "application/octet-stream";
@@ -29,7 +29,7 @@ const UrlSource = Schema.Struct({
29
29
  /** Epoch milliseconds after which the provider no longer serves the URL. */
30
30
  expiresAt: Schema.optional(Schema.Number),
31
31
  });
32
- /** A provider-side handle: OpenAI `file_id`, Gemini file URI, `gs://`, `runway://`, or a prior generation id. */
32
+ /** A provider-side handle: OpenAI `file_id`, Gemini file URI, `gs://`, or a prior generation id. */
33
33
  const RefSource = Schema.Struct({
34
34
  type: Schema.Literal("ref"),
35
35
  provider: ProviderID,
@@ -78,6 +78,8 @@ export class Asset {
78
78
  providerMetadata;
79
79
  /** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
80
80
  headers;
81
+ /** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */
82
+ middleware;
81
83
  // Derived payload forms are cached on the instance because every protocol lowering re-reads the same payload. The
82
84
  // cache is check-then-set (concurrent first reads of a `url` source may both download) and is never observable
83
85
  // through `source`, so round-tripping through `Media.from(asset.source)` stays lossless.
@@ -94,6 +96,7 @@ export class Asset {
94
96
  this.expiresAt = input.source.type === "url" ? input.source.expiresAt : undefined;
95
97
  this.providerMetadata = input.providerMetadata;
96
98
  this.headers = input.source.type === "url" ? input.headers : undefined;
99
+ this.middleware = input.source.type === "url" ? input.middleware : undefined;
97
100
  }
98
101
  /** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
99
102
  inline() {
@@ -116,10 +119,17 @@ export class Asset {
116
119
  return Effect.fail(invalid(`Cannot materialize provider ref ${source.provider}:${source.id}`));
117
120
  const decoded = source.type === "base64"
118
121
  ? Effect.fromResult(Base64.decode(source.data)).pipe(Effect.mapError((cause) => invalid(`Media asset contains invalid base64 data`, cause)))
119
- : download(source, this.headers);
122
+ : download(source, this.headers, this.middleware);
120
123
  return decoded.pipe(Effect.tap((data) => Effect.sync(() => (this.#bytes = data))));
121
124
  });
122
125
  }
126
+ /** The payload as a byte stream; `url` sources stream from the network without being buffered or cached. */
127
+ stream() {
128
+ const source = this.source;
129
+ if (source.type !== "url" || this.#bytes !== undefined)
130
+ return Stream.fromEffect(this.bytes());
131
+ return Stream.unwrap(downloadStream(source, this.headers, this.middleware));
132
+ }
123
133
  base64() {
124
134
  return Effect.suspend(() => {
125
135
  const source = this.source;
@@ -171,9 +181,18 @@ export const AssetSchema = AssetEncoded.pipe(Schema.decodeTo(AssetInstance, {
171
181
  decode: SchemaGetter.transform((encoded) => new Asset(encoded)),
172
182
  encode: SchemaGetter.transform(encodeAsset),
173
183
  }));
174
- const download = Effect.fn("Media.download")(function* (source, headers) {
184
+ /**
185
+ * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with
186
+ * `Media.image`; an asset known to be a video, audio or document is rejected.
187
+ */
188
+ export const ImageAssetSchema = AssetInstance.check(Schema.makeFilter((asset) => asset.kind === "image" ||
189
+ ((asset.source.type === "url" || asset.source.type === "ref") && asset.source.mediaType === undefined) ||
190
+ `expected an image, got ${asset.mediaType}`)).pipe(Schema.brand("Media.ImageAsset"));
191
+ const download = Effect.fn("Media.download")(function* (source, headers, middleware) {
175
192
  const executor = yield* Service;
176
- const response = yield* executor.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})));
193
+ const response = yield* executor
194
+ .execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
195
+ .pipe(Effect.provideService(CurrentMiddleware, middleware));
177
196
  const buffer = yield* response.arrayBuffer.pipe(Effect.mapError((cause) => new AIError({
178
197
  reason: new InvalidProviderOutputError({
179
198
  message: `Failed to read media from ${source.url}`,
@@ -183,6 +202,19 @@ const download = Effect.fn("Media.download")(function* (source, headers) {
183
202
  })));
184
203
  return new Uint8Array(buffer);
185
204
  });
205
+ const downloadStream = Effect.fn("Media.downloadStream")(function* (source, headers, middleware) {
206
+ const executor = yield* Service;
207
+ const response = yield* executor
208
+ .execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
209
+ .pipe(Effect.provideService(CurrentMiddleware, middleware));
210
+ return response.stream.pipe(Stream.mapError((cause) => new AIError({
211
+ reason: new InvalidProviderOutputError({
212
+ message: `Failed to read media from ${source.url}`,
213
+ http: responseHttp(response),
214
+ cause,
215
+ }),
216
+ })));
217
+ });
186
218
  export const from = (source, options) => new Asset({ ...options, source });
187
219
  export const bytes = (data, mediaType, options) => from({ type: "bytes", data, mediaType: mediaType ?? detectMediaType(data) ?? OCTET_STREAM }, options);
188
220
  export const base64 = (data, mediaType, options) => from({ type: "base64", data, mediaType }, options);
@@ -204,6 +236,13 @@ export const fromDataUrl = (dataUrl, options) => {
204
236
  throw invalid("Media data URLs must contain a MIME type and base64 data");
205
237
  return asset;
206
238
  };
239
+ /** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */
240
+ export const image = (input, mediaType) => {
241
+ const asset = make(input, mediaType);
242
+ if (!Schema.is(ImageAssetSchema)(asset))
243
+ throw invalid(`expected an image, got ${asset.mediaType}`);
244
+ return asset;
245
+ };
207
246
  /**
208
247
  * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
209
248
  * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
@@ -247,11 +286,13 @@ export const file = (path, options) => Effect.gen(function* () {
247
286
  .pipe(Effect.mapError((cause) => invalid(`Failed to read media file ${path}`, cause)));
248
287
  return bytes(data, fileMediaType(data, path), options);
249
288
  });
250
- /** Materialize an asset and write its bytes through `FileSystem`. */
289
+ /**
290
+ * Stream an asset's bytes into a file through `FileSystem` without buffering `url` downloads. The bytes go to a temporary
291
+ * file next to `path` that replaces it only once the download finished, so a failed download leaves an existing file as
292
+ * it was.
293
+ */
251
294
  export const write = (asset, path) => Effect.gen(function* () {
252
295
  const fs = yield* FileSystem.FileSystem;
253
- const data = yield* asset.bytes();
254
- yield* fs
255
- .writeFile(path, data)
256
- .pipe(Effect.mapError((cause) => invalid(`Failed to write media file ${path}`, cause)));
296
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
297
+ yield* asset.stream().pipe(Stream.run(fs.sink(temporary)), Effect.andThen(fs.rename(temporary, path)), Effect.onError(() => fs.remove(temporary).pipe(Effect.ignore)), Effect.mapError((cause) => cause instanceof AIError ? cause : invalid(`Failed to write media file ${path}`, cause)));
257
298
  });
@@ -240,14 +240,36 @@ export declare const protocol: Protocol<{
240
240
  })[];
241
241
  } | {
242
242
  readonly role: "system";
243
- readonly content: readonly {
243
+ readonly content: readonly ({
244
+ readonly type: "tool_addition";
245
+ readonly tool: {
246
+ readonly type: "tool_definition";
247
+ readonly definition: {
248
+ readonly name: string;
249
+ readonly description: string;
250
+ readonly input_schema: {
251
+ readonly [x: string]: unknown;
252
+ };
253
+ readonly cache_control?: {
254
+ readonly type: "ephemeral";
255
+ readonly ttl?: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
256
+ } | undefined;
257
+ };
258
+ };
259
+ } | {
260
+ readonly type: "tool_removal";
261
+ readonly tool: {
262
+ readonly type: "tool_reference";
263
+ readonly name: string;
264
+ };
265
+ } | {
244
266
  readonly type: "text";
245
267
  readonly text: string;
246
268
  readonly cache_control?: {
247
269
  readonly type: "ephemeral";
248
270
  readonly ttl?: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
249
271
  } | undefined;
250
- }[];
272
+ })[];
251
273
  readonly output_config?: {
252
274
  readonly effort: string;
253
275
  } | undefined;
@@ -17,6 +17,32 @@ export declare const protocol: Protocol<{
17
17
  readonly reasoning: {
18
18
  readonly effort: OpenResponsesOptions.ReasoningEffort;
19
19
  };
20
+ } | {
21
+ readonly type: "additional_tools";
22
+ readonly role: "developer";
23
+ readonly tools: readonly ({
24
+ readonly type: "custom";
25
+ readonly name: string;
26
+ readonly description: string;
27
+ readonly format: {
28
+ readonly type: "text";
29
+ } | {
30
+ readonly type: "grammar";
31
+ readonly syntax: "lark" | "regex";
32
+ readonly definition: string;
33
+ };
34
+ } | {
35
+ readonly type: "function";
36
+ readonly name: string;
37
+ readonly description: string;
38
+ readonly parameters: {
39
+ readonly [x: string]: unknown;
40
+ };
41
+ readonly strict?: boolean | undefined;
42
+ } | {
43
+ readonly [x: string]: unknown;
44
+ readonly type: string;
45
+ })[];
20
46
  } | {
21
47
  readonly type: "message";
22
48
  readonly role: "system";
@@ -364,14 +364,34 @@ export declare const AnthropicMessagesBody: Schema.Struct<{
364
364
  }>]>>;
365
365
  }>, Schema.Struct<{
366
366
  readonly role: Schema.Literal<"system">;
367
- readonly content: Schema.$Array<Schema.Struct<{
367
+ readonly content: Schema.$Array<Schema.Union<readonly [Schema.Struct<{
368
368
  readonly type: Schema.tag<"text">;
369
369
  readonly text: Schema.String;
370
370
  readonly cache_control: Schema.optional<Schema.Struct<{
371
371
  readonly type: Schema.tag<"ephemeral">;
372
372
  readonly ttl: Schema.optional<Schema.TemplateLiteral<readonly [Schema.Number, Schema.Literals<readonly ["ms", "s", "m", "h", "d"]>]>>;
373
373
  }>>;
374
- }>>;
374
+ }>, Schema.Struct<{
375
+ readonly type: Schema.tag<"tool_addition">;
376
+ readonly tool: Schema.Struct<{
377
+ readonly type: Schema.tag<"tool_definition">;
378
+ readonly definition: Schema.Struct<{
379
+ readonly name: Schema.String;
380
+ readonly description: Schema.String;
381
+ readonly input_schema: Schema.$Record<Schema.String, Schema.Unknown>;
382
+ readonly cache_control: Schema.optional<Schema.Struct<{
383
+ readonly type: Schema.tag<"ephemeral">;
384
+ readonly ttl: Schema.optional<Schema.TemplateLiteral<readonly [Schema.Number, Schema.Literals<readonly ["ms", "s", "m", "h", "d"]>]>>;
385
+ }>>;
386
+ }>;
387
+ }>;
388
+ }>, Schema.Struct<{
389
+ readonly type: Schema.tag<"tool_removal">;
390
+ readonly tool: Schema.Struct<{
391
+ readonly type: Schema.tag<"tool_reference">;
392
+ readonly name: Schema.String;
393
+ }>;
394
+ }>]>>;
375
395
  readonly output_config: Schema.optional<Schema.Struct<{
376
396
  readonly effort: Schema.String;
377
397
  }>>;
@@ -672,14 +692,36 @@ export declare const protocol: Protocol<{
672
692
  })[];
673
693
  } | {
674
694
  readonly role: "system";
675
- readonly content: readonly {
695
+ readonly content: readonly ({
696
+ readonly type: "tool_addition";
697
+ readonly tool: {
698
+ readonly type: "tool_definition";
699
+ readonly definition: {
700
+ readonly name: string;
701
+ readonly description: string;
702
+ readonly input_schema: {
703
+ readonly [x: string]: unknown;
704
+ };
705
+ readonly cache_control?: {
706
+ readonly type: "ephemeral";
707
+ readonly ttl?: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
708
+ } | undefined;
709
+ };
710
+ };
711
+ } | {
712
+ readonly type: "tool_removal";
713
+ readonly tool: {
714
+ readonly type: "tool_reference";
715
+ readonly name: string;
716
+ };
717
+ } | {
676
718
  readonly type: "text";
677
719
  readonly text: string;
678
720
  readonly cache_control?: {
679
721
  readonly type: "ephemeral";
680
722
  readonly ttl?: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
681
723
  } | undefined;
682
- }[];
724
+ })[];
683
725
  readonly output_config?: {
684
726
  readonly effort: string;
685
727
  } | undefined;
@@ -1067,14 +1109,36 @@ export declare const route: Route<{
1067
1109
  })[];
1068
1110
  } | {
1069
1111
  readonly role: "system";
1070
- readonly content: readonly {
1112
+ readonly content: readonly ({
1113
+ readonly type: "tool_addition";
1114
+ readonly tool: {
1115
+ readonly type: "tool_definition";
1116
+ readonly definition: {
1117
+ readonly name: string;
1118
+ readonly description: string;
1119
+ readonly input_schema: {
1120
+ readonly [x: string]: unknown;
1121
+ };
1122
+ readonly cache_control?: {
1123
+ readonly type: "ephemeral";
1124
+ readonly ttl?: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
1125
+ } | undefined;
1126
+ };
1127
+ };
1128
+ } | {
1129
+ readonly type: "tool_removal";
1130
+ readonly tool: {
1131
+ readonly type: "tool_reference";
1132
+ readonly name: string;
1133
+ };
1134
+ } | {
1071
1135
  readonly type: "text";
1072
1136
  readonly text: string;
1073
1137
  readonly cache_control?: {
1074
1138
  readonly type: "ephemeral";
1075
1139
  readonly ttl?: `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
1076
1140
  } | undefined;
1077
- }[];
1141
+ })[];
1078
1142
  readonly output_config?: {
1079
1143
  readonly effort: string;
1080
1144
  } | undefined;
@@ -12,6 +12,7 @@ import { AIError, CacheTTL, LLMEvent, mergeJsonRecords, Usage, } from "../schema
12
12
  import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js";
13
13
  import { classifyProviderFailure } from "../provider-error.js";
14
14
  import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js";
15
+ import { addsTools, foldTools, toolsUpdate, withdrawnTools } from "../tool-updates.js";
15
16
  import * as Cache from "./utils/cache.js";
16
17
  import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js";
17
18
  import { Lifecycle } from "./utils/lifecycle.js";
@@ -196,21 +197,29 @@ const AnthropicAssistantBlock = Schema.Union([
196
197
  AnthropicServerToolUseBlock,
197
198
  AnthropicServerToolResultBlock,
198
199
  ]);
200
+ const AnthropicTool = Schema.Struct({
201
+ name: Schema.String,
202
+ description: Schema.String,
203
+ input_schema: JsonObject,
204
+ cache_control: Schema.optional(AnthropicCacheControl),
205
+ });
206
+ const AnthropicToolAdditionBlock = Schema.Struct({
207
+ type: Schema.tag("tool_addition"),
208
+ tool: Schema.Struct({ type: Schema.tag("tool_definition"), definition: AnthropicTool }),
209
+ });
210
+ const AnthropicToolRemovalBlock = Schema.Struct({
211
+ type: Schema.tag("tool_removal"),
212
+ tool: Schema.Struct({ type: Schema.tag("tool_reference"), name: Schema.String }),
213
+ });
199
214
  const AnthropicMessage = Schema.Union([
200
215
  Schema.Struct({ role: Schema.Literal("user"), content: Schema.Array(AnthropicUserBlock) }),
201
216
  Schema.Struct({ role: Schema.Literal("assistant"), content: Schema.Array(AnthropicAssistantBlock) }),
202
217
  Schema.Struct({
203
218
  role: Schema.Literal("system"),
204
- content: Schema.Array(AnthropicTextBlock),
219
+ content: Schema.Array(Schema.Union([AnthropicTextBlock, AnthropicToolAdditionBlock, AnthropicToolRemovalBlock])),
205
220
  output_config: Schema.optional(Schema.Struct({ effort: Schema.String })),
206
221
  }),
207
222
  ]).pipe(Schema.toTaggedUnion("role"));
208
- const AnthropicTool = Schema.Struct({
209
- name: Schema.String,
210
- description: Schema.String,
211
- input_schema: JsonObject,
212
- cache_control: Schema.optional(AnthropicCacheControl),
213
- });
214
223
  const AnthropicToolChoice = Schema.Union([
215
224
  Schema.Struct({
216
225
  type: Schema.Literals(["auto", "any", "none"]),
@@ -634,6 +643,23 @@ const lowerWrappedSystemUpdate = Effect.fnUntraced(function* (message, breakpoin
634
643
  const part = yield* ProviderShared.wrappedSystemUpdate("Anthropic Messages", message);
635
644
  return { type: "text", text: part.text, cache_control: cacheControl(breakpoints, part.cache) };
636
645
  });
646
+ const lowerToolsUpdate = Effect.fnUntraced(function* (message, update, withdrawn, breakpoints) {
647
+ const text = message.content.length === 0 ? [] : (yield* lowerNativeSystemUpdate(message, breakpoints)).content;
648
+ return {
649
+ role: "system",
650
+ content: [
651
+ ...ProviderShared.flattenTools(update.add).map((tool) => ({
652
+ type: "tool_addition",
653
+ tool: { type: "tool_definition", definition: lowerTool(breakpoints, tool) },
654
+ })),
655
+ ...withdrawn.map((name) => ({
656
+ type: "tool_removal",
657
+ tool: { type: "tool_reference", name },
658
+ })),
659
+ ...text,
660
+ ],
661
+ };
662
+ });
637
663
  const appendToUserTurn = (messages, block) => {
638
664
  const last = messages.at(-1);
639
665
  if (last?.role === "user")
@@ -648,9 +674,22 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
648
674
  // user turn, the nearest spot where Anthropic accepts a native system message.
649
675
  const holdUpdates = supportsNativeSystemUpdates(request);
650
676
  const held = [];
677
+ // The tools declared so far, so each tool update can name the flattened tools it takes away.
678
+ let declared = request.tools;
651
679
  const releaseHeld = Effect.fnUntraced(function* () {
652
680
  const native = acceptsNativeSystemAfter(messages.findLast((message) => message.role !== "system"));
653
681
  for (const update of held.splice(0)) {
682
+ const tools = toolsUpdate(update);
683
+ if (tools !== undefined) {
684
+ if (!native)
685
+ return yield* invalid("Anthropic Messages tool updates must follow a user message or tool result");
686
+ const next = foldTools(declared, tools.add, tools.remove);
687
+ const lowered = yield* lowerToolsUpdate(update, tools, withdrawnTools(declared, next), breakpoints);
688
+ declared = next;
689
+ if (lowered.content.length > 0)
690
+ messages.push(lowered);
691
+ continue;
692
+ }
654
693
  if (native)
655
694
  messages.push(yield* lowerNativeSystemUpdate(update, breakpoints));
656
695
  else
@@ -665,6 +704,12 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
665
704
  messages.push({ role: "system", content: [], output_config: { effort: update.effort ?? DEFAULT_EFFORT } });
666
705
  continue;
667
706
  }
707
+ // Held like text updates, so one between a tool call and its result lands after the result. Planning keeps a
708
+ // marker in place only on models that take native system messages.
709
+ if (toolsUpdate(message) !== undefined) {
710
+ held.push(message);
711
+ continue;
712
+ }
668
713
  if (splitsLocalToolResults(request.messages, index))
669
714
  return yield* invalid("Anthropic Messages system updates cannot split a local tool call from its tool result");
670
715
  if (holdUpdates)
@@ -776,6 +821,21 @@ const supportsEffortUpdates = (request) => {
776
821
  return true;
777
822
  return version.major > 5 || (version.major === 5 && version.minor >= 1);
778
823
  };
824
+ // `tool_addition` adds a tool, or redefines one with the same name; `tool_removal` removes one. A held marker is
825
+ // released just before the next assistant message, where Anthropic only accepts a native system message after a
826
+ // user message or tool result; a marker that would land elsewhere folds.
827
+ const toolUpdates = {
828
+ kinds: ["add", "remove", "replace"],
829
+ placeable: (request, index) => {
830
+ if (!supportsNativeSystemUpdates(request))
831
+ return false;
832
+ const end = request.messages.findIndex((next, at) => at > index && next.role === "assistant");
833
+ const role = request.messages
834
+ .slice(0, end === -1 ? undefined : end)
835
+ .findLast((next) => next.role !== "system")?.role;
836
+ return role === "user" || role === "tool";
837
+ },
838
+ };
779
839
  const applyThinkingBindingDefault = (model, thinking) => {
780
840
  if (isThinkingOff(thinking))
781
841
  return thinking;
@@ -808,8 +868,9 @@ const fromRequest = Effect.fn("AnthropicMessages.fromRequest")(function* (reques
808
868
  const breakpoints = Cache.newBreakpoints(ANTHROPIC_BREAKPOINT_CAP);
809
869
  const flattened = ProviderShared.flattenToolRequest(updates.request);
810
870
  const tools = flattened.tools.length === 0 ? undefined : flattened.tools.map((tool) => lowerTool(breakpoints, tool));
811
- // Anthropic rejects tool_choice when tools are absent; "none" is only meaningful with tools present.
812
- const toolChoice = tools === undefined || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice);
871
+ // Anthropic rejects tool_choice when no tool is declared; "none" is only meaningful with tools present.
872
+ const declared = tools !== undefined || addsTools(request);
873
+ const toolChoice = !declared || !request.toolChoice ? undefined : yield* lowerToolChoice(request.toolChoice);
813
874
  const systemParts = request.system.filter((part) => part.text.length > 0);
814
875
  const system = systemParts.length === 0
815
876
  ? undefined
@@ -1298,6 +1359,7 @@ export const protocol = Protocol.make({
1298
1359
  step,
1299
1360
  },
1300
1361
  supportsEffortUpdates,
1362
+ toolUpdates,
1301
1363
  });
1302
1364
  export const transport = () => {
1303
1365
  const http = HttpTransport.httpJson({ framing });
@@ -1331,6 +1393,9 @@ function requiredBetaHeaders(body) {
1331
1393
  betas.push("compact-2026-01-12");
1332
1394
  if (body.messages.some((message) => message.role === "system" && message.output_config !== undefined))
1333
1395
  betas.push("mid-conversation-output-config-2026-07-01");
1396
+ if (body.messages.some((message) => message.role === "system" &&
1397
+ message.content.some((block) => block.type === "tool_addition" || block.type === "tool_removal")))
1398
+ betas.push("inline-tools-2026-09-15");
1334
1399
  // Opus 5.5 accepts `speed` without this header; earlier fast-mode models reject `speed` without it.
1335
1400
  if (body.speed !== undefined)
1336
1401
  betas.push("fast-mode-2026-02-01");
@@ -39,7 +39,7 @@ const Transcript = Schema.Struct({
39
39
  error: optionalNull(Schema.String),
40
40
  });
41
41
  const STATUS = {
42
- queued: "queued",
42
+ queued: "running",
43
43
  processing: "running",
44
44
  completed: "completed",
45
45
  error: "failed",
@@ -77,19 +77,20 @@ const fromRequest = Effect.fn("AssemblyAITranscription.fromRequest")(function* (
77
77
  const decodeTranscript = route.decodeJson(Transcript);
78
78
  const decodeStart = Effect.fn("AssemblyAITranscription.decodeStart")(function* (response) {
79
79
  const output = yield* decodeTranscript(response);
80
- const status = MediaProtocol.status(STATUS, output.value.status);
81
- return { token: { transcriptID: output.value.id }, snapshot: { id: output.value.id, status } };
80
+ return {
81
+ token: { transcriptID: output.value.id },
82
+ snapshot: { id: output.value.id, ...MediaProtocol.status(STATUS, output.value.status) },
83
+ };
82
84
  });
83
85
  const decodeStatus = Effect.fn("AssemblyAITranscription.decodeStatus")(function* (response, context) {
84
86
  const output = yield* decodeTranscript(response);
85
- const status = MediaProtocol.status(STATUS, output.value.status);
86
- return { id: context.token.transcriptID, status };
87
+ return { id: context.token.transcriptID, ...MediaProtocol.status(STATUS, output.value.status) };
87
88
  });
88
89
  const seconds = (milliseconds) => milliseconds / 1000;
89
90
  const decodeResult = Effect.fn("AssemblyAITranscription.decodeResult")(function* (response, context) {
90
91
  const output = yield* decodeTranscript(response);
91
92
  const transcript = output.value;
92
- const status = MediaProtocol.status(STATUS, transcript.status);
93
+ const status = MediaProtocol.state(STATUS, transcript.status);
93
94
  const error = transcript.error ?? undefined;
94
95
  if (status === "failed")
95
96
  return yield* output.ended("failed", `${route.name} transcription failed${error === undefined ? "" : `: ${error}`}`);
@@ -32,10 +32,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
32
32
  readonly startSeconds: number;
33
33
  readonly endSeconds: number;
34
34
  }[];
35
- } | {
36
- readonly type: "generation-queued";
37
- readonly id: string;
38
- readonly position?: number | undefined;
39
35
  } | {
40
36
  readonly type: "generation-progress";
41
37
  readonly id: string;
@@ -82,10 +78,6 @@ export declare const CartesiaSpeech: {
82
78
  readonly startSeconds: number;
83
79
  readonly endSeconds: number;
84
80
  }[];
85
- } | {
86
- readonly type: "generation-queued";
87
- readonly id: string;
88
- readonly position?: number | undefined;
89
81
  } | {
90
82
  readonly type: "generation-progress";
91
83
  readonly id: string;
@@ -25,10 +25,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
25
25
  readonly startSeconds: number;
26
26
  readonly endSeconds: number;
27
27
  }[];
28
- } | {
29
- readonly type: "generation-queued";
30
- readonly id: string;
31
- readonly position?: number | undefined;
32
28
  } | {
33
29
  readonly type: "generation-progress";
34
30
  readonly id: string;
@@ -75,10 +71,6 @@ export declare const DeepgramSpeech: {
75
71
  readonly startSeconds: number;
76
72
  readonly endSeconds: number;
77
73
  }[];
78
- } | {
79
- readonly type: "generation-queued";
80
- readonly id: string;
81
- readonly position?: number | undefined;
82
74
  } | {
83
75
  readonly type: "generation-progress";
84
76
  readonly id: string;
@@ -28,10 +28,6 @@ export declare const protocol: MediaProtocol.Streamed<Request, {
28
28
  readonly startSeconds: number;
29
29
  readonly endSeconds: number;
30
30
  }[];
31
- } | {
32
- readonly type: "generation-queued";
33
- readonly id: string;
34
- readonly position?: number | undefined;
35
31
  } | {
36
32
  readonly type: "generation-progress";
37
33
  readonly id: string;
@@ -78,10 +74,6 @@ export declare const ElevenLabsSpeech: {
78
74
  readonly startSeconds: number;
79
75
  readonly endSeconds: number;
80
76
  }[];
81
- } | {
82
- readonly type: "generation-queued";
83
- readonly id: string;
84
- readonly position?: number | undefined;
85
77
  } | {
86
78
  readonly type: "generation-progress";
87
79
  readonly id: string;
@@ -0,0 +1,13 @@
1
+ import { Schema } from "effect";
2
+ import { DecisionRoute } from "../route/decision.js";
3
+ import { type ProviderOptions } from "../schema/index.js";
4
+ export declare const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com/v1beta";
5
+ declare const Options: Schema.Struct<{
6
+ /** Token budget for every image and video input; `ultra_high` applies to images only. */
7
+ readonly mediaResolution: Schema.optional<Schema.declare<import("../schema/options.js").OpenString<"high" | "low" | "medium" | "ultra_high">, import("../schema/options.js").OpenString<"high" | "low" | "medium" | "ultra_high">>>;
8
+ }>;
9
+ /** Known fields map to their wire names; anything else is sent as given. */
10
+ export type OptionsInput = ProviderOptions & typeof Options.Encoded;
11
+ export declare const protocol: DecisionRoute.Protocol;
12
+ export declare const route: DecisionRoute.Route;
13
+ export * as GoogleDecisions from "./google-decisions.js";