@opencode/ai 2.3.0 → 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 (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 +250 -24
  35. package/dist/protocols/open-responses.js +40 -24
  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 +7 -3
  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
@@ -1,4 +1,4 @@
1
- import { Context, type Effect } from "effect";
1
+ import { Context, Effect, Stream } from "effect";
2
2
  import type { Headers, HttpClientRequest, HttpClientResponse } from "effect/http";
3
3
  import { HttpContext, type AIError } from "../schema/errors.js";
4
4
  import type { ClientTls } from "../schema/options.js";
@@ -17,6 +17,19 @@ export declare const Service: typeof RequestExecutorService;
17
17
  */
18
18
  export declare const CurrentTls: Context.Reference<ClientTls | undefined>;
19
19
  export type Service = RequestExecutorService;
20
+ /**
21
+ * Middleware for every provider request made while it is set: model calls, media submits, polls, results and cancels,
22
+ * whatever the modality. Set it with {@link withMiddleware}. Downloads of a `url` asset don't use it; they use the
23
+ * asset's own `middleware`, which a route sets only for URLs on the provider's origin.
24
+ */
25
+ export declare const CurrentMiddleware: Context.Reference<HttpMiddleware | undefined>;
26
+ /** `outer` wraps `inner`: it sees the request first and the response last. */
27
+ export declare const composeMiddleware: (outer: HttpMiddleware | undefined, inner: HttpMiddleware | undefined) => HttpMiddleware | undefined;
28
+ /**
29
+ * Runs `fn` on every provider request `self` makes, an Effect or a Stream. Inside an outer `withMiddleware`, the outer
30
+ * one wraps this one. Executor-wide middleware (`RequestExecutor.middleware`) wraps both.
31
+ */
32
+ export declare const withMiddleware: (fn: HttpMiddleware) => <Self extends Effect.Effect<unknown, unknown, unknown> | Stream.Stream<unknown, unknown, unknown>>(self: Self) => Self;
20
33
  export declare const headerDetails: (headers: Headers.Headers) => {
21
34
  [k: string]: string;
22
35
  };
@@ -1,4 +1,4 @@
1
- import { Context } from "effect";
1
+ import { Context, Effect, Stream } from "effect";
2
2
  import { HttpContext } from "../schema/errors.js";
3
3
  export class RequestExecutorService extends Context.Service()("@opencode/AI/RequestExecutor") {
4
4
  }
@@ -10,6 +10,33 @@ export const Service = RequestExecutorService;
10
10
  export const CurrentTls = Context.Reference("@opencode/AI/RequestExecutor/CurrentTls", {
11
11
  defaultValue: () => undefined,
12
12
  });
13
+ /**
14
+ * Middleware for every provider request made while it is set: model calls, media submits, polls, results and cancels,
15
+ * whatever the modality. Set it with {@link withMiddleware}. Downloads of a `url` asset don't use it; they use the
16
+ * asset's own `middleware`, which a route sets only for URLs on the provider's origin.
17
+ */
18
+ export const CurrentMiddleware = Context.Reference("@opencode/AI/RequestExecutor/CurrentMiddleware", { defaultValue: () => undefined });
19
+ /** `outer` wraps `inner`: it sees the request first and the response last. */
20
+ export const composeMiddleware = (outer, inner) => {
21
+ if (outer === undefined)
22
+ return inner;
23
+ if (inner === undefined)
24
+ return outer;
25
+ return (request, handler) => outer(request, (forwarded) => inner(forwarded, handler));
26
+ };
27
+ /**
28
+ * Runs `fn` on every provider request `self` makes, an Effect or a Stream. Inside an outer `withMiddleware`, the outer
29
+ * one wraps this one. Executor-wide middleware (`RequestExecutor.middleware`) wraps both.
30
+ */
31
+ export const withMiddleware = (fn) => (self) => {
32
+ const merged = Effect.gen(function* () {
33
+ return composeMiddleware(yield* CurrentMiddleware, fn);
34
+ });
35
+ // One signature for both, so it infers inside `pipe`; each branch returns the same kind it was given.
36
+ return (Stream.isStream(self)
37
+ ? Stream.provideServiceEffect(self, CurrentMiddleware, merged)
38
+ : Effect.provideServiceEffect(self, CurrentMiddleware, merged));
39
+ };
13
40
  export const headerDetails = (headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, value]));
14
41
  export const responseHttp = (response) => new HttpContext({
15
42
  url: response.request.url,
@@ -3,7 +3,7 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
3
3
  import { AIError } from "../schema/index.js";
4
4
  import { Service, type HttpMiddleware, type Interface } from "./executor-service.js";
5
5
  import type { ClientTls } from "../schema/options.js";
6
- export { CurrentTls, responseHttp, Service } from "./executor-service.js";
6
+ export { composeMiddleware, CurrentMiddleware, CurrentTls, responseHttp, Service, withMiddleware, } from "./executor-service.js";
7
7
  export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js";
8
8
  /** Preserve HTTP diagnostics for executor and externally captured failures alike. */
9
9
  export declare const httpFailure: (input: {
@@ -29,6 +29,9 @@ export declare const withTls: (execute: Interface["execute"], tls: ClientTls | u
29
29
  * `middleware` still wrap the call, and status classification still applies.
30
30
  */
31
31
  export declare const withFetch: (fetch: typeof globalThis.fetch | undefined, middleware?: HttpMiddleware) => HttpMiddleware | undefined;
32
- /** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */
32
+ /**
33
+ * Run `fn` on every request: it sees the raw response before status classification, inside middleware already on
34
+ * `executor`, and outside per-call and scoped ({@link withMiddleware}) middleware.
35
+ */
33
36
  export declare const middleware: (fn: HttpMiddleware, executor?: Layer.Layer<Service>) => Layer.Layer<Service>;
34
37
  export * as RequestExecutor from "./executor.js";
@@ -2,8 +2,8 @@ import { Cause, Effect, Layer, Option, Schema, Stream } from "effect";
2
2
  import { FetchHttpClient, Headers, HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse, } from "effect/http";
3
3
  import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../schema/index.js";
4
4
  import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js";
5
- import { CurrentTls, headerDetails, responseHttp, Service, } from "./executor-service.js";
6
- export { CurrentTls, responseHttp, Service } from "./executor-service.js";
5
+ import { composeMiddleware, CurrentMiddleware, CurrentTls, headerDetails, responseHttp, Service, } from "./executor-service.js";
6
+ export { composeMiddleware, CurrentMiddleware, CurrentTls, responseHttp, Service, withMiddleware, } from "./executor-service.js";
7
7
  const normalizedHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
8
8
  const clampRetryAfterMs = (millis) => Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.ceil(millis)));
9
9
  const retryAfterMs = (headers) => {
@@ -182,7 +182,12 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
182
182
  return yield* statusError(response);
183
183
  });
184
184
  return Service.of({
185
- execute: executeOnce,
185
+ // Scoped middleware runs outside per-call middleware. It is cleared while the request runs, so a request a
186
+ // middleware makes itself isn't wrapped again.
187
+ execute: (request, next) => Effect.gen(function* () {
188
+ const middleware = composeMiddleware(yield* CurrentMiddleware, next);
189
+ return yield* executeOnce(request, middleware).pipe(Effect.provideService(CurrentMiddleware, undefined));
190
+ }),
186
191
  });
187
192
  }));
188
193
  export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
@@ -201,11 +206,21 @@ export const withFetch = (fetch, middleware) => {
201
206
  const send = (request) => HttpClient.execute(request).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch));
202
207
  return middleware === undefined ? send : (request) => middleware(request, send);
203
208
  };
204
- /** Run `fn` on every request: it sees the raw response before status classification, inside middleware already on `executor`, and outside per-call middleware. */
209
+ /**
210
+ * Run `fn` on every request: it sees the raw response before status classification, inside middleware already on
211
+ * `executor`, and outside per-call and scoped ({@link withMiddleware}) middleware.
212
+ */
205
213
  export const middleware = (fn, executor = fetchLayer) => Layer.effect(Service, Effect.gen(function* () {
206
214
  const inner = yield* Service;
207
215
  return Service.of({
208
- execute: (request, next) => inner.execute(request, next === undefined ? fn : (input, handler) => fn(input, (forwarded) => next(forwarded, handler))),
216
+ // Scoped middleware sits where per-call middleware does, inside `fn`; it is read here and cleared so the
217
+ // executors below don't apply it again.
218
+ execute: (request, next) => Effect.gen(function* () {
219
+ const scoped = composeMiddleware(yield* CurrentMiddleware, next);
220
+ return yield* inner
221
+ .execute(request, composeMiddleware(fn, scoped))
222
+ .pipe(Effect.provideService(CurrentMiddleware, undefined));
223
+ }),
209
224
  });
210
225
  })).pipe(Layer.provide(executor));
211
226
  export * as RequestExecutor from "./executor.js";
@@ -1,6 +1,6 @@
1
1
  import { Duration, Effect, Schema, type Stream } from "effect";
2
2
  import { HttpClientResponse } from "effect/http";
3
- import type { Snapshot, Status } from "../generation.js";
3
+ import type { Reason, Snapshot } from "../generation.js";
4
4
  import { Media } from "../media.js";
5
5
  import type { AuthInput } from "./auth.js";
6
6
  import { AIError, AuthenticationError, type HttpContext, InvalidRequestError, ProviderID, ProviderInternalError, RateLimitError } from "../schema/index.js";
@@ -54,10 +54,11 @@ export interface Started<Token> {
54
54
  export interface PollContext<Token> {
55
55
  readonly token: Token;
56
56
  /**
57
- * The headers an authenticated GET of `url` would send (deployment headers plus auth), for result URLs that need
58
- * the API key to download. URLs on another origin than the route's base URL get no headers.
57
+ * What an authenticated download of `url` needs, for result URLs that only download with the API key: the headers a
58
+ * GET would send (deployment headers plus auth) and the caller's scoped middleware. Spread it into `Media.url`. URLs
59
+ * on another origin than the route's base URL get neither, so credentials and hooks never leave the provider's host.
59
60
  */
60
- readonly headers: (url: string) => Effect.Effect<Record<string, string>, AIError>;
61
+ readonly credentials: (url: string) => Effect.Effect<Pick<Media.AssetOptions, "headers" | "middleware">, AIError>;
61
62
  /**
62
63
  * A further GET with the same auth and headers, retried like the poll itself, for providers whose result needs a
63
64
  * second lookup (MiniMax v1 answers with a file id that resolves to a download URL).
@@ -148,7 +149,7 @@ export declare const identity: (input: {
148
149
  body: string;
149
150
  http: HttpContext;
150
151
  invalid: (message: string, cause?: unknown) => AIError;
151
- ended: (status: Exclude<Status, "queued" | "running" | "completed">, message: string, failure?: Failure) => AIError;
152
+ ended: (reason: Reason, message: string, failure?: Failure) => AIError;
152
153
  pending: (id: string) => AIError;
153
154
  contentPolicy: (message: string) => AIError;
154
155
  }, AIError, never>;
@@ -157,7 +158,7 @@ export declare const identity: (input: {
157
158
  body: string;
158
159
  http: HttpContext;
159
160
  invalid: (message: string, cause?: unknown) => AIError;
160
- ended: (status: Exclude<Status, "queued" | "running" | "completed">, message: string, failure?: Failure) => AIError;
161
+ ended: (reason: Reason, message: string, failure?: Failure) => AIError;
161
162
  pending: (id: string) => AIError;
162
163
  contentPolicy: (message: string) => AIError;
163
164
  value: A;
@@ -172,8 +173,12 @@ export declare const identity: (input: {
172
173
  unsupported: (operation: string, message: string) => AIError;
173
174
  };
174
175
  export type Identity = ReturnType<typeof identity>;
176
+ /** A provider status in package terms: still running, completed, or the reason it ended in `error`. */
177
+ export type State = "running" | "completed" | Reason;
175
178
  /** Map a provider status string through the protocol's table; unknown values keep the generation running. */
176
- export declare const status: (table: Readonly<Record<string, Status>>, raw: string) => Status;
179
+ export declare const state: (table: Readonly<Record<string, State>>, raw: string) => State;
180
+ /** The snapshot `status` and `reason` for a provider status string. */
181
+ export declare const status: (table: Readonly<Record<string, State>>, raw: string) => Pick<Snapshot, "status" | "reason">;
177
182
  /** Map a provider error code through the protocol's table; missing or unmapped codes are `ProviderInternal`. */
178
183
  export declare const failure: (table: Readonly<Record<string, Failure>>, code: string | number | undefined) => Failure;
179
184
  /** A `url` asset whose provider-declared retention window starts now. */
@@ -42,7 +42,7 @@ export const identity = (input) => {
42
42
  });
43
43
  /**
44
44
  * Read a text body while retaining the original payload and HTTP context on every downstream error. `invalid` is a
45
- * malformed provider document; `ended` is a generation that reached a terminal status without output (`failed`
45
+ * malformed provider document; `ended` is a generation that ended in `error` without output (reason `failed`
46
46
  * carries the provider's classification, defaulting to `ProviderInternal`; `cancelled`/`expired` mean the result
47
47
  * will never exist); `pending` is a `result()` read before the generation finished, which is caller misuse;
48
48
  * `contentPolicy` is a moderated result.
@@ -54,8 +54,8 @@ export const identity = (input) => {
54
54
  body,
55
55
  http,
56
56
  invalid: (message, cause) => new AIError({ reason: new InvalidProviderOutputError({ route: input.id, message, body, http, cause }) }),
57
- ended: (status, message, failure = "ProviderInternal") => new AIError({
58
- reason: status === "failed"
57
+ ended: (reason, message, failure = "ProviderInternal") => new AIError({
58
+ reason: reason === "failed"
59
59
  ? new FAILURES[failure]({ message, body, http })
60
60
  : new InvalidRequestError({ message, body, http }),
61
61
  }),
@@ -110,7 +110,14 @@ export const identity = (input) => {
110
110
  };
111
111
  };
112
112
  /** Map a provider status string through the protocol's table; unknown values keep the generation running. */
113
- export const status = (table, raw) => Object.hasOwn(table, raw) ? table[raw] : "running";
113
+ export const state = (table, raw) => Object.hasOwn(table, raw) ? table[raw] : "running";
114
+ /** The snapshot `status` and `reason` for a provider status string. */
115
+ export const status = (table, raw) => {
116
+ const mapped = state(table, raw);
117
+ if (mapped === "running" || mapped === "completed")
118
+ return { status: mapped };
119
+ return { status: "error", reason: mapped };
120
+ };
114
121
  /** Map a provider error code through the protocol's table; missing or unmapped codes are `ProviderInternal`. */
115
122
  export const failure = (table, code) => code !== undefined && Object.hasOwn(table, code) ? table[code] : "ProviderInternal";
116
123
  /** A `url` asset whose provider-declared retention window starts now. */
@@ -58,7 +58,16 @@ export const queued = (input) => {
58
58
  // Only the GET exchange retries: a decoded terminal failure (`output.ended`) can be a `ProviderInternal` too, and
59
59
  // re-reading it would spin until the caller's deadline.
60
60
  const get = (path) => transport.call("GET", path, exchange, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.map((sent) => sent.response));
61
- const poll = (operation) => get(operation.path(token)).pipe(Effect.flatMap((response) => operation.decode(response, { token, get, headers: (url) => transport.headers(url, exchange) })));
61
+ const poll = (operation) => get(operation.path(token)).pipe(Effect.flatMap((response) => operation.decode(response, {
62
+ token,
63
+ get,
64
+ credentials: (url) => Effect.gen(function* () {
65
+ const headers = yield* transport.headers(url, exchange);
66
+ if (headers === undefined)
67
+ return {};
68
+ return { headers, middleware: yield* RequestExecutor.CurrentMiddleware };
69
+ }),
70
+ })));
62
71
  const status = poll(protocol.status);
63
72
  const cancel = protocol.cancel;
64
73
  return {
@@ -167,7 +176,7 @@ const makeTransport = (input) => {
167
176
  }),
168
177
  /**
169
178
  * The headers a follow-up GET of `url` sends, for result URLs that only download with the same credentials. A URL
170
- * on another origin than the route's base URL gets none, so credentials never leave the provider's host.
179
+ * on another origin than the route's base URL gets undefined, so credentials never leave the provider's host.
171
180
  */
172
181
  headers: (url, exchange) => URL.canParse(url) && new URL(url).origin === baseURL("").origin
173
182
  ? authorize({
@@ -177,7 +186,7 @@ const makeTransport = (input) => {
177
186
  body: "",
178
187
  headers: Headers.fromInput(exchange.headers),
179
188
  }).pipe(Effect.map((headers) => ({ ...headers })))
180
- : Effect.succeed({}),
189
+ : Effect.succeed(undefined),
181
190
  /** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */
182
191
  call: (method, path, exchange, execute) => {
183
192
  // Provider-issued absolute URLs are used as-is; everything else resolves against the base.
@@ -1,5 +1,6 @@
1
1
  import { Schema, type Effect } from "effect";
2
2
  import type { AIError, LanguageModelSanitizerCompatibility, LLMEvent, LLMRequest, ProtocolID } from "../schema/index.js";
3
+ import type { ToolUpdateEncoding } from "../tool-updates.js";
3
4
  /**
4
5
  * The semantic API contract of one model server family.
5
6
  *
@@ -42,6 +43,8 @@ export interface Protocol<Body, Frame, Event, State> {
42
43
  readonly stream: ProtocolStream<Frame, Event, State>;
43
44
  /** Whether `body.from` lowers `Message.effort(...)` markers; wrappers around another `body.from` must forward it. */
44
45
  readonly supportsEffortUpdates?: (request: LLMRequest) => boolean;
46
+ /** Tool changes `body.from` can send in place of `Message.tools(...)` markers; wrappers around another `body.from` must forward it. */
47
+ readonly toolUpdates?: ToolUpdateEncoding;
45
48
  /** Tool schema sanitizer for every model on this protocol unless the model's compatibility sets one; wrappers around another `body.from` must forward it. */
46
49
  readonly sanitizer?: LanguageModelSanitizerCompatibility;
47
50
  }
@@ -133,6 +133,11 @@ declare const CompactionResponse_base: Schema.Class<CompactionResponse, Schema.S
133
133
  readonly effort?: import("./options.js").ReasoningEffort;
134
134
  readonly previous?: import("./options.js").ReasoningEffort;
135
135
  }) => import("./messages.js").SystemMessage;
136
+ tools: (input: import("../tool.js").ToolChangesInput) => {
137
+ role: "system";
138
+ content: never[];
139
+ tools: import("../tool.js").ToolChangesInput;
140
+ };
136
141
  tool: (result: ToolResultPart | Parameters<typeof ToolResultPart.make>[0]) => import("./messages.js").ToolMessage;
137
142
  }>;
138
143
  readonly usage: Schema.optional<typeof Usage>;
@@ -2,6 +2,7 @@ import { Schema } from "effect";
2
2
  import { Tool } from "@opencode/schema/tool";
3
3
  import { type BaseRequest, CacheHint, type CachePolicy, JsonSchema, type LanguageModel, type LanguageModelProviderOptions, ReasoningEffort, type GenerationOptionsFields } from "./options.js";
4
4
  import { Media } from "../media.js";
5
+ import type { ToolChangesInput } from "../tool.js";
5
6
  export declare const MessageRole: Schema.Literals<readonly ["system", "user", "assistant", "tool"]>;
6
7
  export type MessageRole = Schema.Schema.Type<typeof MessageRole>;
7
8
  declare const systemPartSchema: Schema.Struct<{
@@ -419,6 +420,12 @@ export declare const ContentPart: Schema.toTaggedUnion<"type", readonly [Schema.
419
420
  readonly previous: Schema.optional<Schema.declare<ReasoningEffort, ReasoningEffort>>;
420
421
  }>]>;
421
422
  export type ContentPart = Schema.Schema.Type<typeof ContentPart>;
423
+ /** Tools changed here: `add` appends or redefines tools by name, `remove` drops them by name. */
424
+ export declare const ToolChanges: Schema.Struct<{
425
+ readonly add: Schema.$Array<Schema.suspend<Schema.Codec<ToolEntry, ToolEntry, never, never>>>;
426
+ readonly remove: Schema.$Array<Schema.String>;
427
+ }>;
428
+ export type ToolChanges = Schema.Schema.Type<typeof ToolChanges>;
422
429
  declare const SystemMessage_base: Schema.Class<SystemMessage, Schema.Struct<{
423
430
  readonly id: Schema.optional<Schema.String>;
424
431
  readonly role: Schema.Literal<"system">;
@@ -432,6 +439,10 @@ declare const SystemMessage_base: Schema.Class<SystemMessage, Schema.Struct<{
432
439
  readonly effort: Schema.optional<Schema.declare<ReasoningEffort, ReasoningEffort>>;
433
440
  readonly previous: Schema.optional<Schema.declare<ReasoningEffort, ReasoningEffort>>;
434
441
  }>]>>;
442
+ readonly tools: Schema.optional<Schema.Struct<{
443
+ readonly add: Schema.$Array<Schema.suspend<Schema.Codec<ToolEntry, ToolEntry, never, never>>>;
444
+ readonly remove: Schema.$Array<Schema.String>;
445
+ }>>;
435
446
  }>, {}>;
436
447
  export declare class SystemMessage extends SystemMessage_base {
437
448
  }
@@ -698,7 +709,9 @@ export declare namespace Message {
698
709
  type RoleInput<Props, Content> = Omit<Props, "content"> & {
699
710
  readonly content: Content;
700
711
  };
701
- export type SystemInput = RoleInput<ConstructorParameters<typeof SystemMessage>[0], ContentInput<SystemMessage["content"][number]>>;
712
+ export type SystemInput = RoleInput<Omit<ConstructorParameters<typeof SystemMessage>[0], "tools">, ContentInput<SystemMessage["content"][number]>> & {
713
+ readonly tools?: ToolChangesInput;
714
+ };
702
715
  export type UserInput = RoleInput<ConstructorParameters<typeof UserMessage>[0], UserContentInput>;
703
716
  export type AssistantInput = RoleInput<ConstructorParameters<typeof AssistantMessage>[0], AssistantContentInput>;
704
717
  export type ToolInput = RoleInput<ConstructorParameters<typeof ToolMessage>[0], ToolResultPart | ReadonlyArray<ToolResultPart>>;
@@ -732,6 +745,16 @@ export declare const Message: Schema.Union<readonly [typeof SystemMessage, typeo
732
745
  readonly effort?: ReasoningEffort;
733
746
  readonly previous?: ReasoningEffort;
734
747
  }) => SystemMessage;
748
+ /**
749
+ * Change the available tools at this point. A route sends the change in place when the model's `tools.updates`
750
+ * allows it, and otherwise folds it into the top-level `tools`. Returns message input that keeps the tool objects,
751
+ * so `ai.loop` can run an executable tool added here.
752
+ */
753
+ tools: (input: ToolChangesInput) => {
754
+ role: "system";
755
+ content: never[];
756
+ tools: ToolChangesInput;
757
+ };
735
758
  tool: (result: ToolResultPart | Parameters<typeof ToolResultPart.make>[0]) => ToolMessage;
736
759
  };
737
760
  /**
@@ -166,10 +166,16 @@ export const ContentPart = Schema.Union([
166
166
  CompactionPart,
167
167
  EffortPart,
168
168
  ]).pipe(Schema.toTaggedUnion("type"));
169
+ /** Tools changed here: `add` appends or redefines tools by name, `remove` drops them by name. */
170
+ export const ToolChanges = Schema.Struct({
171
+ add: Schema.Array(Schema.suspend(() => ToolEntry)),
172
+ remove: Schema.Array(Schema.String),
173
+ }).annotate({ identifier: "LLM.ToolChanges" });
169
174
  export class SystemMessage extends Schema.Class("LLM.SystemMessage")({
170
175
  id: Schema.optional(Schema.String),
171
176
  role: Schema.Literal("system"),
172
177
  content: Schema.Array(Schema.Union([TextPart, EffortPart]).pipe(Schema.toTaggedUnion("type"))),
178
+ tools: Schema.optional(ToolChanges),
173
179
  }) {
174
180
  }
175
181
  export class UserMessage extends Schema.Class("LLM.UserMessage")({
@@ -201,8 +207,16 @@ function contentWithMedia(input) {
201
207
  }
202
208
  function make(input) {
203
209
  switch (input.role) {
204
- case "system":
205
- return input instanceof SystemMessage ? input : new SystemMessage({ ...input, content: content(input.content) });
210
+ case "system": {
211
+ if (input instanceof SystemMessage)
212
+ return input;
213
+ const { tools, ...rest } = input;
214
+ return new SystemMessage({
215
+ ...rest,
216
+ content: content(input.content),
217
+ ...(tools === undefined ? {} : { tools: toolChanges(tools) }),
218
+ });
219
+ }
206
220
  case "user":
207
221
  return input instanceof UserMessage
208
222
  ? input
@@ -235,8 +249,18 @@ export const Message = withStatics(messageSchema, {
235
249
  */
236
250
  system: (input) => make({ role: "system", content: input }),
237
251
  effort: (input) => make({ role: "system", content: [{ type: "effort", effort: input.effort, previous: input.previous }] }),
252
+ /**
253
+ * Change the available tools at this point. A route sends the change in place when the model's `tools.updates`
254
+ * allows it, and otherwise folds it into the top-level `tools`. Returns message input that keeps the tool objects,
255
+ * so `ai.loop` can run an executable tool added here.
256
+ */
257
+ tools: (input) => ({ role: "system", content: [], tools: input }),
238
258
  tool: (result) => make({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] }),
239
259
  });
260
+ const toolChanges = (input) => ({
261
+ add: (input.add ?? []).map((item) => ("_definition" in item ? item._definition : ToolEntry.make(item))),
262
+ remove: (input.remove ?? []).map((item) => (typeof item === "string" ? item : item.name)),
263
+ });
240
264
  /**
241
265
  * Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format
242
266
  * write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input.
@@ -135,8 +135,16 @@ export interface Capabilities {
135
135
  readonly search?: boolean;
136
136
  /** Input formats accepted by custom (free-form) tools. */
137
137
  readonly freeform?: ReadonlyArray<"text" | "lark" | "regex">;
138
- /** Accepts a changed tool list mid-conversation. */
139
- readonly updates?: boolean;
138
+ /**
139
+ * Tool changes the model takes mid-conversation without changing the leading tool declaration, so the prompt
140
+ * cache holds. `add`: declares a tool not declared before. `remove`: withdraws a declared tool. `replace`:
141
+ * declares a tool under a name declared before (a redefinition, or re-adding a removed tool). Unset or empty:
142
+ * every change folds into the top-level tools. Anthropic Messages sends all three as native blocks. OpenAI
143
+ * Responses needs `add` for any of them: it declares every tool in `additional_tools` items with a short
144
+ * incremental-update hint before each later item, and announces a removal as developer text while the tool
145
+ * stays declared, so list `remove` only for models that follow that announcement.
146
+ */
147
+ readonly updates?: ReadonlyArray<"add" | "remove" | "replace">;
140
148
  };
141
149
  readonly reasoning?: {
142
150
  readonly supported?: boolean;
@@ -18,10 +18,6 @@ export declare const SpeechClient: {
18
18
  readonly startSeconds: number;
19
19
  readonly endSeconds: number;
20
20
  }[];
21
- } | {
22
- readonly type: "generation-queued";
23
- readonly id: string;
24
- readonly position?: number | undefined;
25
21
  } | {
26
22
  readonly type: "generation-progress";
27
23
  readonly id: string;
@@ -68,6 +64,10 @@ export declare const SpeechClient: {
68
64
  readonly startSeconds: number;
69
65
  readonly endSeconds: number;
70
66
  }[];
67
+ } | {
68
+ readonly type: "generation-progress";
69
+ readonly id: string;
70
+ readonly progress?: number | undefined;
71
71
  } | {
72
72
  readonly type: "finish";
73
73
  readonly audio: import("./media.js").Asset;
@@ -97,7 +97,7 @@ export declare const SpeechClient: {
97
97
  readonly [x: string]: unknown;
98
98
  };
99
99
  } | undefined;
100
- } | import("./generation.js").Observation, import("./public.js").AIError, SpeechClientService>;
100
+ }, import("./public.js").AIError, SpeechClientService>;
101
101
  readonly start: (request: SpeechRequest) => import("effect/Effect").Effect<import("./generation.js").Generation<SpeechResponse>, import("./public.js").AIError, SpeechClientService>;
102
102
  readonly resume: (model: import("./speech.js").SpeechModel<{
103
103
  readonly [x: string]: unknown;