@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
@@ -6,6 +6,7 @@ import { Framing } from "./framing.js";
6
6
  import { HttpTransport } from "./transport/index.js";
7
7
  import type { HttpMiddleware, Transport, TransportRuntime, WebSocketChannelExecutor } from "./transport/index.js";
8
8
  import type { Protocol } from "./protocol.js";
9
+ import { type ToolUpdateEncoding } from "../tool-updates.js";
9
10
  import type { LanguageModelSanitizerCompatibility, ProtocolID, ProviderOptions } from "../schema/index.js";
10
11
  import type { LLMRequestInput } from "../llm.js";
11
12
  import { AIError, CompactionResponse, CompactionCheckpointResponse, LLMResponse, LanguageModel, LLMEvent, ProviderID, type LLMRequest, type RequestOptions } from "../schema/index.js";
@@ -33,6 +34,7 @@ export interface Route<Body, Prepared = unknown, Compact extends CompactionOpera
33
34
  readonly options?: RequestOptions;
34
35
  readonly body: RouteBody<Body>;
35
36
  readonly supportsEffortUpdates?: (request: LLMRequest) => boolean;
37
+ readonly toolUpdates?: ToolUpdateEncoding;
36
38
  readonly sanitizer?: LanguageModelSanitizerCompatibility;
37
39
  readonly with: {
38
40
  <Next extends CompactionOperations | undefined>(patch: RoutePatch<Body, Prepared> & {
@@ -6,6 +6,7 @@ import { Framing } from "./framing.js";
6
6
  import { HttpTransport } from "./transport/index.js";
7
7
  import { applyCachePolicy } from "../cache-policy.js";
8
8
  import { applyEffortUpdates } from "../effort-updates.js";
9
+ import { mapToolUpdates, planToolUpdates } from "../tool-updates.js";
9
10
  import { normalizeToolHistory } from "../tool-history.js";
10
11
  import { sanitizeSurrogates } from "../utils/sanitize.js";
11
12
  import * as ProviderShared from "../protocols/shared.js";
@@ -108,6 +109,7 @@ function makeFromTransport(input) {
108
109
  options: routeInput.options,
109
110
  body: protocol.body,
110
111
  supportsEffortUpdates: protocol.supportsEffortUpdates,
112
+ toolUpdates: protocol.toolUpdates,
111
113
  sanitizer: protocol.sanitizer,
112
114
  with: (patch) => {
113
115
  const { compact, id, provider, providerMetadataKey, auth, transport, endpoint, ...options } = patch;
@@ -201,7 +203,9 @@ const prepareRequest = (request) => {
201
203
  const sanitized = restoreClasses({ ...sanitizeSurrogates({ ...original, model: undefined }), model: original.model });
202
204
  // Deduplicate per sibling level; a tool and a namespace may share a name.
203
205
  const dedupe = (tools) => [...new Map(tools.map((tool) => [`${tool.type}:${tool.name}`, tool])).values()].map((tool) => tool.type === "tool" ? tool : { ...tool, tools: dedupe(tool.tools) });
204
- const resolved = applyCachePolicy(applyEffortUpdates({ ...sanitized, tools: ToolSchemaProjection.tools(dedupe(sanitized.tools), sanitized.model) }));
206
+ const project = (tools) => ToolSchemaProjection.tools(dedupe(tools), sanitized.model);
207
+ const updated = planToolUpdates(sanitized);
208
+ const resolved = applyCachePolicy(applyEffortUpdates(mapToolUpdates({ ...updated, tools: project(updated.tools) }, project)));
205
209
  const headers = resolved.model.route.headers?.({ request: resolved });
206
210
  return headers === undefined ? resolved : { ...resolved, headers: { ...headers, ...resolved.headers } };
207
211
  };
@@ -1,6 +1,7 @@
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
+ import type { ClientTls } from "../schema/options.js";
4
5
  export interface Interface {
5
6
  readonly execute: (request: HttpClientRequest.HttpClientRequest, middleware?: HttpMiddleware) => Effect.Effect<HttpClientResponse.HttpClientResponse, AIError>;
6
7
  }
@@ -10,7 +11,25 @@ declare const RequestExecutorService_base: Context.ServiceClass<RequestExecutorS
10
11
  export declare class RequestExecutorService extends RequestExecutorService_base {
11
12
  }
12
13
  export declare const Service: typeof RequestExecutorService;
14
+ /**
15
+ * The client certificate for the HTTP request being executed. Transports set it from `http.tls`; the executor's HTTP
16
+ * client presents it, since only the runtime's fetch can.
17
+ */
18
+ export declare const CurrentTls: Context.Reference<ClientTls | undefined>;
13
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;
14
33
  export declare const headerDetails: (headers: Headers.Headers) => {
15
34
  [k: string]: string;
16
35
  };
@@ -1,8 +1,42 @@
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
  }
5
5
  export const Service = RequestExecutorService;
6
+ /**
7
+ * The client certificate for the HTTP request being executed. Transports set it from `http.tls`; the executor's HTTP
8
+ * client presents it, since only the runtime's fetch can.
9
+ */
10
+ export const CurrentTls = Context.Reference("@opencode/AI/RequestExecutor/CurrentTls", {
11
+ defaultValue: () => undefined,
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
+ };
6
40
  export const headerDetails = (headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, value]));
7
41
  export const responseHttp = (response) => new HttpContext({
8
42
  url: response.request.url,
@@ -2,7 +2,8 @@ import { Layer, Stream } from "effect";
2
2
  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
- export { responseHttp, Service } from "./executor-service.js";
5
+ import type { ClientTls } from "../schema/options.js";
6
+ export { composeMiddleware, CurrentMiddleware, CurrentTls, responseHttp, Service, withMiddleware, } from "./executor-service.js";
6
7
  export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js";
7
8
  /** Preserve HTTP diagnostics for executor and externally captured failures alike. */
8
9
  export declare const httpFailure: (input: {
@@ -18,11 +19,19 @@ export declare const responseStream: (response: HttpClientResponse.HttpClientRes
18
19
  export declare const stream: (executor: Interface, request: HttpClientRequest.HttpClientRequest, middleware?: HttpMiddleware) => Stream.Stream<Uint8Array, AIError>;
19
20
  export declare const layer: Layer.Layer<Service, never, HttpClient.HttpClient>;
20
21
  export declare const fetchLayer: Layer.Layer<import("./executor-service.js").RequestExecutorService, never, never>;
22
+ /**
23
+ * Sends through `execute`, presenting `tls` on each request. Apply it only where a provider request is sent, so
24
+ * downloads made through the plain executor never carry the certificate. The executor's HTTP client reads `CurrentTls`.
25
+ */
26
+ export declare const withTls: (execute: Interface["execute"], tls: ClientTls | undefined) => Interface["execute"];
21
27
  /**
22
28
  * Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
23
29
  * `middleware` still wrap the call, and status classification still applies.
24
30
  */
25
31
  export declare const withFetch: (fetch: typeof globalThis.fetch | undefined, middleware?: HttpMiddleware) => HttpMiddleware | undefined;
26
- /** 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
+ */
27
36
  export declare const middleware: (fn: HttpMiddleware, executor?: Layer.Layer<Service>) => Layer.Layer<Service>;
28
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 { headerDetails, responseHttp, Service } from "./executor-service.js";
6
- export { 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,10 +182,20 @@ 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));
194
+ /**
195
+ * Sends through `execute`, presenting `tls` on each request. Apply it only where a provider request is sent, so
196
+ * downloads made through the plain executor never carry the certificate. The executor's HTTP client reads `CurrentTls`.
197
+ */
198
+ export const withTls = (execute, tls) => tls ? (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTls, tls)) : execute;
189
199
  /**
190
200
  * Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
191
201
  * `middleware` still wrap the call, and status classification still applies.
@@ -196,11 +206,21 @@ export const withFetch = (fetch, middleware) => {
196
206
  const send = (request) => HttpClient.execute(request).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.Fetch, fetch));
197
207
  return middleware === undefined ? send : (request) => middleware(request, send);
198
208
  };
199
- /** 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
+ */
200
213
  export const middleware = (fn, executor = fetchLayer) => Layer.effect(Service, Effect.gen(function* () {
201
214
  const inner = yield* Service;
202
215
  return Service.of({
203
- 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
+ }),
204
224
  });
205
225
  })).pipe(Layer.provide(executor));
206
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";
@@ -50,19 +50,26 @@ export interface Started<Token> {
50
50
  readonly token: Token;
51
51
  readonly snapshot: Snapshot;
52
52
  }
53
- /**
54
- * A follow-up call's inputs: the decoded token and the auth headers the route sent, so a protocol can attach them
55
- * to output URLs that require the same credentials to download (Veo).
56
- */
53
+ /** A follow-up call's inputs: the decoded token. */
57
54
  export interface PollContext<Token> {
58
55
  readonly token: Token;
59
- readonly auth: Record<string, string>;
56
+ /**
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.
60
+ */
61
+ readonly credentials: (url: string) => Effect.Effect<Pick<Media.AssetOptions, "headers" | "middleware">, AIError>;
62
+ /**
63
+ * A further GET with the same auth and headers, retried like the poll itself, for providers whose result needs a
64
+ * second lookup (MiniMax v1 answers with a file id that resolves to a download URL).
65
+ */
66
+ readonly get: (path: string) => Effect.Effect<HttpClientResponse.HttpClientResponse, AIError>;
60
67
  }
61
68
  /**
62
69
  * Submit, then poll. `start` posts the body to the route endpoint; `status`, `result`, and `cancel` are follow-up
63
70
  * calls addressed by the token. Paths are relative to the route base URL unless the provider hands back absolute
64
71
  * URLs, in which case they are used verbatim. `result` is always its own GET: providers that
65
- * return the output inside the status body (Veo, xAI, Runway) point `result.path` at the status path and decode the
72
+ * return the output inside the status body (xAI) point `result.path` at the status path and decode the
66
73
  * same document, so `Generation.await` and `Video.resume(...).await()` behave identically everywhere.
67
74
  */
68
75
  export interface Queued<Request, Response, Token> {
@@ -91,11 +98,6 @@ export interface Queued<Request, Response, Token> {
91
98
  readonly cancel?: {
92
99
  readonly method: AuthInput["method"];
93
100
  readonly path: (token: Token) => string;
94
- /**
95
- * Fetch a fresh status first and skip the call for terminal generations, for providers whose cancel endpoint
96
- * destroys finished work (Runway's `DELETE /v1/tasks/{id}` deletes completed tasks and their outputs).
97
- */
98
- readonly activeOnly?: boolean;
99
101
  };
100
102
  }
101
103
  export declare const queued: <Request, Response, Token>(route: Identity, input: Omit<Queued<Request, Response, Token>, "kind" | "id" | "provider">) => Queued<Request, Response, Token>;
@@ -147,7 +149,7 @@ export declare const identity: (input: {
147
149
  body: string;
148
150
  http: HttpContext;
149
151
  invalid: (message: string, cause?: unknown) => AIError;
150
- ended: (status: Exclude<Status, "queued" | "running" | "completed">, message: string, failure?: Failure) => AIError;
152
+ ended: (reason: Reason, message: string, failure?: Failure) => AIError;
151
153
  pending: (id: string) => AIError;
152
154
  contentPolicy: (message: string) => AIError;
153
155
  }, AIError, never>;
@@ -156,7 +158,7 @@ export declare const identity: (input: {
156
158
  body: string;
157
159
  http: HttpContext;
158
160
  invalid: (message: string, cause?: unknown) => AIError;
159
- ended: (status: Exclude<Status, "queued" | "running" | "completed">, message: string, failure?: Failure) => AIError;
161
+ ended: (reason: Reason, message: string, failure?: Failure) => AIError;
160
162
  pending: (id: string) => AIError;
161
163
  contentPolicy: (message: string) => AIError;
162
164
  value: A;
@@ -171,8 +173,12 @@ export declare const identity: (input: {
171
173
  unsupported: (operation: string, message: string) => AIError;
172
174
  };
173
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;
174
178
  /** Map a provider status string through the protocol's table; unknown values keep the generation running. */
175
- 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">;
176
182
  /** Map a provider error code through the protocol's table; missing or unmapped codes are `ProviderInternal`. */
177
183
  export declare const failure: (table: Readonly<Record<string, Failure>>, code: string | number | undefined) => Failure;
178
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. */
@@ -46,6 +46,8 @@ export interface QueuedRoute<Request extends MediaRequest, Response> {
46
46
  readonly start: (request: Request, execute: Execute) => Effect.Effect<Generation<Response>, AIError>;
47
47
  /** Rebuild a handle from a persisted `Generation.token`; fails typed when the token is not this route's. */
48
48
  readonly resume: (model: MediaRequest["model"], token: unknown, execute: Execute) => Effect.Effect<Generation<Response>, AIError>;
49
+ /** The status, result and cancel operations for a persisted token, without reading its status first. */
50
+ readonly attach: (model: MediaRequest["model"], token: unknown, execute: Execute) => Effect.Effect<Generation<Response>["route"], AIError>;
49
51
  }
50
52
  /** One request whose response parses into events; `generate` runs the same stream and collects it. */
51
53
  export interface StreamRoute<Request extends MediaRequest, Event, Response> {
@@ -4,7 +4,7 @@ import { Auth } from "./auth.js";
4
4
  import { Endpoint } from "./endpoint.js";
5
5
  import { RequestExecutor } from "./executor.js";
6
6
  import { MediaProtocol } from "./media-protocol.js";
7
- import { Generation, isTerminal } from "../generation.js";
7
+ import { Generation } from "../generation.js";
8
8
  import { isRetryable } from "../provider-error.js";
9
9
  import { AIError, AIErrorReason, InvalidRequestError, ProviderID, UnsupportedOperationError, mergeProviderOptions, mergeTransport, } from "../schema/index.js";
10
10
  import { encodeJson } from "../utils/json.js";
@@ -57,18 +57,25 @@ export const queued = (input) => {
57
57
  const generationRoute = (token, exchange, execute) => {
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
- const poll = (operation) => transport.call("GET", operation.path(token), exchange, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.flatMap((sent) => operation.decode(sent.response, { token, auth: sent.auth })));
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, {
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
+ })));
61
71
  const status = poll(protocol.status);
62
72
  const cancel = protocol.cancel;
63
- const send = cancel === undefined
64
- ? undefined
65
- : transport.call(cancel.method, cancel.path(token), exchange, execute).pipe(Effect.asVoid);
66
73
  return {
67
74
  status,
68
75
  result: poll(protocol.result),
69
- cancel: send !== undefined && cancel?.activeOnly
70
- ? status.pipe(Effect.flatMap((snapshot) => (isTerminal(snapshot.status) ? Effect.void : send)))
71
- : send,
76
+ cancel: cancel === undefined
77
+ ? undefined
78
+ : transport.call(cancel.method, cancel.path(token), exchange, execute).pipe(Effect.asVoid),
72
79
  };
73
80
  };
74
81
  const start = Effect.fn("MediaRoute.start")(function* (request, execute) {
@@ -77,17 +84,19 @@ export const queued = (input) => {
77
84
  const route = generationRoute(started.token, submitted.exchange, execute);
78
85
  return new Generation(route, encodeToken(started.token), started.snapshot);
79
86
  });
87
+ const decode = (raw) => decodeToken(raw).pipe(Effect.mapError((cause) => new AIError({
88
+ reason: new InvalidRequestError({
89
+ message: `${protocol.id} cannot resume a generation from this token`,
90
+ cause,
91
+ }),
92
+ })));
93
+ const attach = (model, raw, execute) => decode(raw).pipe(Effect.map((token) => generationRoute(token, transport.exchange(model), execute)));
80
94
  const resume = Effect.fn("MediaRoute.resume")(function* (model, raw, execute) {
81
- const token = yield* decodeToken(raw).pipe(Effect.mapError((cause) => new AIError({
82
- reason: new InvalidRequestError({
83
- message: `${protocol.id} cannot resume a generation from this token`,
84
- cause,
85
- }),
86
- })));
95
+ const token = yield* decode(raw);
87
96
  const route = generationRoute(token, transport.exchange(model), execute);
88
97
  return new Generation(route, encodeToken(token), yield* route.status);
89
98
  });
90
- return { kind: "queued", id: protocol.id, provider: protocol.provider, protocol: protocol.id, start, resume };
99
+ return { kind: "queued", id: protocol.id, provider: protocol.provider, protocol: protocol.id, start, resume, attach };
91
100
  };
92
101
  /** Compose a streaming media protocol; `generate` runs the same stream in `generate` mode and folds it with `collect`. */
93
102
  export const stream = (input) => {
@@ -129,7 +138,6 @@ export const stream = (input) => {
129
138
  const makeTransport = (input) => {
130
139
  const authorize = Auth.toEffect(input.auth);
131
140
  const baseURL = (path) => new URL(`${Endpoint.trimBaseUrl(input.endpoint.baseURL ?? "")}${path}`);
132
- /** `auth` is only what `Auth` added or changed, never untouched deployment headers. */
133
141
  const send = Effect.fn("MediaRoute.send")(function* (call, fetch, execute) {
134
142
  const encoded = encode(call.body, call.headers);
135
143
  const url = call.url.toString();
@@ -140,11 +148,8 @@ const makeTransport = (input) => {
140
148
  body: encoded.text,
141
149
  headers: encoded.headers,
142
150
  });
143
- const response = yield* execute(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
144
- return {
145
- response,
146
- auth: Object.fromEntries(Object.entries(headers).filter(([key, value]) => encoded.headers[key] !== value)),
147
- };
151
+ const response = yield* RequestExecutor.withTls(execute, call.request.http?.tls)(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
152
+ return { response };
148
153
  });
149
154
  return {
150
155
  /** Route and model overlays; `start` additionally merges the request's own. */
@@ -158,7 +163,7 @@ const makeTransport = (input) => {
158
163
  const headers = Headers.fromInput(merged);
159
164
  const prepared = protocol.prepare === undefined
160
165
  ? request
161
- : yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request, body }, request.fetch, execute).pipe(Effect.map((sent) => sent.response)));
166
+ : yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request: { ...request, http }, body }, request.fetch, execute).pipe(Effect.map((sent) => sent.response)));
162
167
  // Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized.
163
168
  const resolved = {
164
169
  ...sanitizeSurrogates({ ...prepared, headers: merged, http, providerOptions }),
@@ -169,6 +174,19 @@ const makeTransport = (input) => {
169
174
  const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, request.fetch, execute);
170
175
  return { response: sent.response, context: { request: resolved, body }, exchange };
171
176
  }),
177
+ /**
178
+ * The headers a follow-up GET of `url` sends, for result URLs that only download with the same credentials. A URL
179
+ * on another origin than the route's base URL gets undefined, so credentials never leave the provider's host.
180
+ */
181
+ headers: (url, exchange) => URL.canParse(url) && new URL(url).origin === baseURL("").origin
182
+ ? authorize({
183
+ request: { http: exchange.http },
184
+ method: "GET",
185
+ url,
186
+ body: "",
187
+ headers: Headers.fromInput(exchange.headers),
188
+ }).pipe(Effect.map((headers) => ({ ...headers })))
189
+ : Effect.succeed(undefined),
172
190
  /** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */
173
191
  call: (method, path, exchange, execute) => {
174
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
  }
@@ -66,7 +66,7 @@ export const httpJson = (input) => ({
66
66
  const limits = timeoutConfig(request.timeout);
67
67
  // Unlike the header and chunk limits, the whole-request budget has no default.
68
68
  const total = limits.total ? Duration.millis(limits.total) : Duration.infinity;
69
- const response = yield* runtime.http.execute(prepared.request, prepared.middleware).pipe(Effect.timeoutOrElse({
69
+ const response = yield* RequestExecutor.withTls(runtime.http.execute, request.http?.tls)(prepared.request, prepared.middleware).pipe(Effect.timeoutOrElse({
70
70
  duration: Duration.min(timeoutDuration(limits.headers), total),
71
71
  orElse: () => timeout("request", "Timed out waiting for response headers"),
72
72
  }));
@@ -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
  /**
@@ -747,7 +770,7 @@ export declare const Freeform: Schema.Union<readonly [Schema.Struct<{
747
770
  readonly type: Schema.Literal<"lark">;
748
771
  readonly grammar: Schema.String;
749
772
  }>]>;
750
- export type Freeform = Schema.Schema.Type<typeof Freeform>;
773
+ export type Freeform = Tool.Freeform;
751
774
  declare const toolDefinitionFields: {
752
775
  name: Schema.String;
753
776
  description: Schema.String;