@opencode/ai 2.3.0 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +65 -18
  2. package/dist/cache-policy.js +4 -2
  3. package/dist/effect.d.ts +3 -1
  4. package/dist/generation.d.ts +10 -10
  5. package/dist/generation.js +8 -14
  6. package/dist/image-client.d.ts +56 -59
  7. package/dist/image-client.js +47 -8
  8. package/dist/image.d.ts +36 -95
  9. package/dist/image.js +11 -14
  10. package/dist/index.d.ts +25 -25
  11. package/dist/index.js +29 -22
  12. package/dist/llm.d.ts +4 -1
  13. package/dist/llm.js +10 -1
  14. package/dist/media-client.d.ts +18 -6
  15. package/dist/media-client.js +42 -37
  16. package/dist/media.d.ts +17 -1
  17. package/dist/media.js +28 -7
  18. package/dist/protocols/alibaba-messages.d.ts +24 -2
  19. package/dist/protocols/alibaba-responses.d.ts +26 -0
  20. package/dist/protocols/anthropic-messages.d.ts +70 -6
  21. package/dist/protocols/anthropic-messages.js +74 -9
  22. package/dist/protocols/assemblyai-transcription.js +7 -6
  23. package/dist/protocols/cartesia-speech.d.ts +0 -8
  24. package/dist/protocols/deepgram-speech.d.ts +0 -8
  25. package/dist/protocols/elevenlabs-speech.d.ts +0 -8
  26. package/dist/protocols/google-interactions-video.d.ts +4 -9
  27. package/dist/protocols/google-interactions-video.js +9 -10
  28. package/dist/protocols/google-speech.d.ts +0 -8
  29. package/dist/protocols/google-transcription.d.ts +0 -8
  30. package/dist/protocols/meta-messages.d.ts +24 -2
  31. package/dist/protocols/meta-responses.d.ts +52 -0
  32. package/dist/protocols/minimax-video.d.ts +6 -15
  33. package/dist/protocols/minimax-video.js +25 -27
  34. package/dist/protocols/open-responses.d.ts +410 -138
  35. package/dist/protocols/open-responses.js +47 -28
  36. package/dist/protocols/openai-chat.js +7 -3
  37. package/dist/protocols/openai-compatible-responses.d.ts +26 -0
  38. package/dist/protocols/openai-freeform.d.ts +1 -1
  39. package/dist/protocols/openai-freeform.js +9 -5
  40. package/dist/protocols/openai-images.d.ts +0 -8
  41. package/dist/protocols/openai-responses.d.ts +153 -0
  42. package/dist/protocols/openai-responses.js +68 -7
  43. package/dist/protocols/openai-speech.d.ts +0 -8
  44. package/dist/protocols/openai-transcription.d.ts +0 -8
  45. package/dist/protocols/openrouter-video.d.ts +4 -9
  46. package/dist/protocols/openrouter-video.js +14 -13
  47. package/dist/protocols/seedance-video.d.ts +4 -9
  48. package/dist/protocols/seedance-video.js +13 -12
  49. package/dist/protocols/utils/gateway-protocol.js +1 -0
  50. package/dist/protocols/utils/responses-compaction.js +14 -4
  51. package/dist/protocols/xai-responses.d.ts +26 -0
  52. package/dist/protocols/xai-video.d.ts +4 -9
  53. package/dist/protocols/xai-video.js +13 -9
  54. package/dist/protocols/zai-messages.d.ts +24 -2
  55. package/dist/providers/alibaba.d.ts +50 -2
  56. package/dist/providers/amazon-bedrock-mantle.d.ts +50 -2
  57. package/dist/providers/anthropic-compatible.d.ts +24 -2
  58. package/dist/providers/anthropic.d.ts +24 -2
  59. package/dist/providers/azure.d.ts +76 -2
  60. package/dist/providers/cloudflare-ai-gateway.d.ts +100 -4
  61. package/dist/providers/digitalocean.d.ts +26 -0
  62. package/dist/providers/google-vertex-messages.d.ts +24 -2
  63. package/dist/providers/google-vertex-messages.js +1 -0
  64. package/dist/providers/google-vertex-responses.d.ts +26 -0
  65. package/dist/providers/google.d.ts +3 -3
  66. package/dist/providers/google.js +5 -2
  67. package/dist/providers/meta.d.ts +50 -2
  68. package/dist/providers/minimax.d.ts +50 -2
  69. package/dist/providers/moonshot.d.ts +50 -2
  70. package/dist/providers/openai-compatible-responses.d.ts +26 -0
  71. package/dist/providers/openai.d.ts +26 -0
  72. package/dist/providers/openrouter.d.ts +26 -0
  73. package/dist/providers/venice.d.ts +26 -0
  74. package/dist/providers/xai/videos.d.ts +2 -0
  75. package/dist/providers/xai/videos.js +1 -0
  76. package/dist/providers/xai.d.ts +4 -3
  77. package/dist/providers/xai.js +5 -1
  78. package/dist/providers/zai-coding-plan.d.ts +50 -2
  79. package/dist/public.d.ts +5 -4
  80. package/dist/public.js +1 -1
  81. package/dist/route/client.d.ts +2 -0
  82. package/dist/route/client.js +5 -1
  83. package/dist/route/executor-service.d.ts +14 -1
  84. package/dist/route/executor-service.js +28 -1
  85. package/dist/route/executor.d.ts +5 -2
  86. package/dist/route/executor.js +20 -5
  87. package/dist/route/media-protocol.d.ts +12 -7
  88. package/dist/route/media-protocol.js +11 -4
  89. package/dist/route/media.js +12 -3
  90. package/dist/route/protocol.d.ts +3 -0
  91. package/dist/schema/events.d.ts +5 -0
  92. package/dist/schema/messages.d.ts +24 -1
  93. package/dist/schema/messages.js +26 -2
  94. package/dist/schema/options.d.ts +10 -2
  95. package/dist/speech-client.d.ts +5 -5
  96. package/dist/speech.d.ts +7 -88
  97. package/dist/speech.js +1 -3
  98. package/dist/tool-updates.d.ts +34 -0
  99. package/dist/tool-updates.js +93 -0
  100. package/dist/tool.d.ts +6 -1
  101. package/dist/tool.js +1 -1
  102. package/dist/transcription-client.d.ts +5 -5
  103. package/dist/transcription.d.ts +7 -88
  104. package/dist/transcription.js +1 -3
  105. package/dist/video-client.d.ts +6 -6
  106. package/dist/video-client.js +13 -11
  107. package/dist/video.d.ts +17 -73
  108. package/dist/video.js +9 -8
  109. package/package.json +7 -3
@@ -2,7 +2,7 @@ import { type Context, Effect, Layer, Stream } from "effect";
2
2
  import { type AwaitOptions, type Generation, type Observation } from "./generation.js";
3
3
  import { RequestExecutor } from "./route/executor.js";
4
4
  import type { MediaRoute } from "./route/media.js";
5
- import { AIError } from "./schema/index.js";
5
+ import { AIError, type ProviderID } from "./schema/index.js";
6
6
  /** A media request whose model carries the route that executes it. */
7
7
  export interface RoutedRequest<Self extends MediaRoute.MediaRequest, Event, Response> extends MediaRoute.MediaRequest {
8
8
  readonly model: MediaRoute.MediaRequest["model"] & {
@@ -16,16 +16,28 @@ export interface Interface<Req extends RoutedRequest<Req, Event, Response>, Even
16
16
  readonly start: (request: Req) => Effect.Effect<Generation<Response>, AIError>;
17
17
  readonly resume: (model: Req["model"], token: unknown) => Effect.Effect<Generation<Response>, AIError>;
18
18
  }
19
- /** One modality's layer and service accessors, dispatching each request on its route's `kind`. */
20
- export declare const make: <Self, Req extends RoutedRequest<Req, Event, Response>, Event, Response>(service: Context.Service<Self, Interface<Req, Event, Response>>, input: {
19
+ export interface Input<Event, Response> {
21
20
  readonly modality: string;
22
21
  /** A completed response expanded into the streaming event shape. */
23
22
  readonly responseEvents: (response: Response) => ReadonlyArray<Event>;
24
- }) => {
25
- responseEvents: (response: Response) => ReadonlyArray<Event>;
23
+ }
24
+ /** `${modality}.${operation}` on a route that is not queued. */
25
+ export declare const notQueued: (modality: string, route: {
26
+ readonly provider: ProviderID;
27
+ readonly id: string;
28
+ }, operation: string) => AIError;
29
+ /** One modality's operations over an executor, dispatching each request on its route's `kind`. */
30
+ export declare const operations: <Req extends RoutedRequest<Req, Event, Response>, Event, Response>(execute: MediaRoute.Execute, input: Input<Event, Response>) => Interface<Req, Event, Response>;
31
+ /** One modality's layer and service accessors over `operations`. */
32
+ export declare const make: <Self, Req extends RoutedRequest<Req, Event, Response>, Event, Response>(service: Context.Service<Self, Interface<Req, Event, Response>>, input: Input<Event, Response>) => {
33
+ responseEvents: (response: Response) => readonly Event[];
26
34
  layer: Layer.Layer<Self, never, RequestExecutor.RequestExecutorService>;
27
35
  generate: (request: Req, options?: AwaitOptions) => Effect.Effect<Response, AIError, Self>;
28
- stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | Observation, AIError, Exclude<Self, import("effect/Scope").Scope>>;
36
+ stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | {
37
+ readonly type: "generation-progress";
38
+ readonly id: string;
39
+ readonly progress?: number | undefined;
40
+ }, AIError, Exclude<Self, import("effect/Scope").Scope>>;
29
41
  start: (request: Req) => Effect.Effect<Generation<Response>, AIError, Self>;
30
42
  resume: (model: Req["model"], token: unknown) => Effect.Effect<Generation<Response>, AIError, Self>;
31
43
  };
@@ -2,47 +2,52 @@ import { Effect, Layer, Stream } from "effect";
2
2
  import { resultEvents } from "./generation.js";
3
3
  import { RequestExecutor } from "./route/executor.js";
4
4
  import { AIError, UnsupportedOperationError } from "./schema/index.js";
5
- /** One modality's layer and service accessors, dispatching each request on its route's `kind`. */
5
+ /** `${modality}.${operation}` on a route that is not queued. */
6
+ export const notQueued = (modality, route, operation) => new AIError({
7
+ reason: new UnsupportedOperationError({
8
+ operation: `${modality}.${operation}`,
9
+ provider: route.provider,
10
+ route: route.id,
11
+ message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
12
+ }),
13
+ });
14
+ /** One modality's operations over an executor, dispatching each request on its route's `kind`. */
15
+ export const operations = (execute, input) => {
16
+ const start = (request) => {
17
+ const route = request.model.route;
18
+ if (route.kind !== "queued")
19
+ return Effect.fail(notQueued(input.modality, route, "start"));
20
+ return route.start(request, execute);
21
+ };
22
+ return {
23
+ start,
24
+ resume: (model, token) => {
25
+ if (model.route.kind !== "queued")
26
+ return Effect.fail(notQueued(input.modality, model.route, "resume"));
27
+ return model.route.resume(model, token, execute);
28
+ },
29
+ generate: (request, options) => {
30
+ const route = request.model.route;
31
+ if (route.kind !== "queued")
32
+ return route.generate(request, execute);
33
+ return start(request).pipe(Effect.flatMap((generation) => generation.await(options)));
34
+ },
35
+ stream: (request, options) => {
36
+ const route = request.model.route;
37
+ if (route.kind === "stream")
38
+ return route.stream(request, execute);
39
+ if (route.kind === "queued")
40
+ return Stream.unwrap(start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))));
41
+ return Stream.fromIterableEffect(Effect.map(route.generate(request, execute), input.responseEvents));
42
+ },
43
+ };
44
+ };
45
+ /** One modality's layer and service accessors over `operations`. */
6
46
  export const make = (service, input) => ({
7
47
  responseEvents: input.responseEvents,
8
48
  layer: Layer.effect(service, Effect.gen(function* () {
9
49
  const executor = yield* RequestExecutor.Service;
10
- const notQueued = (route, operation) => new AIError({
11
- reason: new UnsupportedOperationError({
12
- operation: `${input.modality}.${operation}`,
13
- provider: route.provider,
14
- route: route.id,
15
- message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
16
- }),
17
- });
18
- const start = (request) => {
19
- const route = request.model.route;
20
- if (route.kind !== "queued")
21
- return Effect.fail(notQueued(route, "start"));
22
- return route.start(request, executor.execute);
23
- };
24
- return service.of({
25
- start,
26
- resume: (model, token) => {
27
- if (model.route.kind !== "queued")
28
- return Effect.fail(notQueued(model.route, "resume"));
29
- return model.route.resume(model, token, executor.execute);
30
- },
31
- generate: (request, options) => {
32
- const route = request.model.route;
33
- if (route.kind !== "queued")
34
- return route.generate(request, executor.execute);
35
- return start(request).pipe(Effect.flatMap((generation) => generation.await(options)));
36
- },
37
- stream: (request, options) => {
38
- const route = request.model.route;
39
- if (route.kind === "stream")
40
- return route.stream(request, executor.execute);
41
- if (route.kind === "queued")
42
- return Stream.unwrap(start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))));
43
- return Stream.fromIterableEffect(Effect.map(route.generate(request, executor.execute), input.responseEvents));
44
- },
45
- });
50
+ return service.of(operations(executor.execute, input));
46
51
  })),
47
52
  generate: (request, options) => service.use((client) => client.generate(request, options)),
48
53
  stream: (request, options) => Stream.unwrap(service.useSync((client) => client.stream(request, options))),
package/dist/media.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Effect, FileSystem, Schema, Stream } from "effect";
3
3
  import { ProviderID } from "./schema/ids.js";
4
4
  import { AIError } from "./schema/errors.js";
5
5
  import { ProviderMetadata } from "./schema/options.js";
6
- import { Service } from "./route/executor-service.js";
6
+ import { type HttpMiddleware, Service } from "./route/executor-service.js";
7
7
  export { detectMediaType } from "./utils/media-type.js";
8
8
  export declare const Source: Schema.Union<readonly [Schema.Struct<{
9
9
  readonly type: Schema.Literal<"bytes">;
@@ -60,6 +60,8 @@ export declare class Asset {
60
60
  readonly providerMetadata?: ProviderMetadata;
61
61
  /** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
62
62
  readonly headers?: Record<string, string>;
63
+ /** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */
64
+ readonly middleware?: HttpMiddleware;
63
65
  constructor(input: Asset.Input);
64
66
  /** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
65
67
  inline(): Inline | undefined;
@@ -122,6 +124,12 @@ export declare namespace Asset {
122
124
  * credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting.
123
125
  */
124
126
  readonly headers?: Record<string, string>;
127
+ /**
128
+ * Middleware for downloading a `url` source, runtime-only like `headers`. A download never uses the caller's
129
+ * scoped middleware (`RequestExecutor.withMiddleware`), so hooks that add provider credentials can't reach another
130
+ * host. Routes set this to that middleware only for result URLs on the provider's origin.
131
+ */
132
+ readonly middleware?: HttpMiddleware;
125
133
  }
126
134
  }
127
135
  /** JSON form of an asset: the serializable `Source` plus caller-supplied metadata. `bytes` sources encode as base64. */
@@ -190,6 +198,12 @@ export declare const AssetSchema: Schema.decodeTo<Schema.declare<Asset, Asset>,
190
198
  }>>;
191
199
  readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
192
200
  }>, never, never>;
201
+ /**
202
+ * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with
203
+ * `Media.image`; an asset known to be a video, audio or document is rejected.
204
+ */
205
+ export declare const ImageAssetSchema: Schema.brand<Schema.declare<Asset, Asset>, "Media.ImageAsset">;
206
+ export type ImageAsset = typeof ImageAssetSchema.Type;
193
207
  export type AssetOptions = Omit<Asset.Input, "source">;
194
208
  export declare const from: (source: Source, options?: AssetOptions) => Asset;
195
209
  export declare const bytes: (data: Uint8Array, mediaType?: string, options?: AssetOptions) => Asset;
@@ -206,6 +220,8 @@ export declare const fromDataUrl: (dataUrl: string, options?: AssetOptions) => A
206
220
  export type Data = Uint8Array | ArrayBuffer | URL | string;
207
221
  /** What file inputs accept: an `Asset` or plain `Data`. */
208
222
  export type Input = Asset | Data;
223
+ /** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */
224
+ export declare const image: (input: Input, mediaType?: string) => ImageAsset;
209
225
  /**
210
226
  * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
211
227
  * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
package/dist/media.js CHANGED
@@ -5,7 +5,7 @@ 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";
@@ -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,7 +119,7 @@ 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
  }
@@ -125,7 +128,7 @@ export class Asset {
125
128
  const source = this.source;
126
129
  if (source.type !== "url" || this.#bytes !== undefined)
127
130
  return Stream.fromEffect(this.bytes());
128
- return Stream.unwrap(downloadStream(source, this.headers));
131
+ return Stream.unwrap(downloadStream(source, this.headers, this.middleware));
129
132
  }
130
133
  base64() {
131
134
  return Effect.suspend(() => {
@@ -178,9 +181,18 @@ export const AssetSchema = AssetEncoded.pipe(Schema.decodeTo(AssetInstance, {
178
181
  decode: SchemaGetter.transform((encoded) => new Asset(encoded)),
179
182
  encode: SchemaGetter.transform(encodeAsset),
180
183
  }));
181
- 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) {
182
192
  const executor = yield* Service;
183
- 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));
184
196
  const buffer = yield* response.arrayBuffer.pipe(Effect.mapError((cause) => new AIError({
185
197
  reason: new InvalidProviderOutputError({
186
198
  message: `Failed to read media from ${source.url}`,
@@ -190,9 +202,11 @@ const download = Effect.fn("Media.download")(function* (source, headers) {
190
202
  })));
191
203
  return new Uint8Array(buffer);
192
204
  });
193
- const downloadStream = Effect.fn("Media.downloadStream")(function* (source, headers) {
205
+ const downloadStream = Effect.fn("Media.downloadStream")(function* (source, headers, middleware) {
194
206
  const executor = yield* Service;
195
- const response = yield* executor.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})));
207
+ const response = yield* executor
208
+ .execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
209
+ .pipe(Effect.provideService(CurrentMiddleware, middleware));
196
210
  return response.stream.pipe(Stream.mapError((cause) => new AIError({
197
211
  reason: new InvalidProviderOutputError({
198
212
  message: `Failed to read media from ${source.url}`,
@@ -222,6 +236,13 @@ export const fromDataUrl = (dataUrl, options) => {
222
236
  throw invalid("Media data URLs must contain a MIME type and base64 data");
223
237
  return asset;
224
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
+ };
225
246
  /**
226
247
  * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
227
248
  * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
@@ -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}`}`);