@opencode/ai 2.2.6 → 2.3.0

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 (177) hide show
  1. package/README.md +208 -98
  2. package/dist/ai-client.d.ts +2 -2
  3. package/dist/ai-client.js +2 -1
  4. package/dist/decision.d.ts +10 -0
  5. package/dist/decision.js +2 -0
  6. package/dist/effect.d.ts +14 -7
  7. package/dist/effect.js +6 -1
  8. package/dist/embedding-client.d.ts +21 -0
  9. package/dist/embedding-client.js +30 -0
  10. package/dist/embedding.d.ts +111 -0
  11. package/dist/embedding.js +75 -0
  12. package/dist/experimental.d.ts +0 -4
  13. package/dist/experimental.js +0 -3
  14. package/dist/image-client.d.ts +1 -1
  15. package/dist/image-client.js +2 -6
  16. package/dist/image.d.ts +0 -1
  17. package/dist/image.js +0 -3
  18. package/dist/index.d.ts +18 -50
  19. package/dist/index.js +35 -13
  20. package/dist/media-model.d.ts +2 -0
  21. package/dist/media-model.js +3 -1
  22. package/dist/media.d.ts +9 -3
  23. package/dist/media.js +27 -7
  24. package/dist/protocols/alibaba-chat.d.ts +4 -0
  25. package/dist/protocols/anthropic-messages.js +3 -3
  26. package/dist/protocols/google-decisions.d.ts +13 -0
  27. package/dist/protocols/google-decisions.js +133 -0
  28. package/dist/protocols/google-embed-content.d.ts +34 -0
  29. package/dist/protocols/google-embed-content.js +110 -0
  30. package/dist/protocols/google-interactions-video.d.ts +43 -0
  31. package/dist/protocols/google-interactions-video.js +186 -0
  32. package/dist/protocols/google-interactions.d.ts +14 -1
  33. package/dist/protocols/google-interactions.js +1 -1
  34. package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
  35. package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
  36. package/dist/protocols/index.d.ts +4 -0
  37. package/dist/protocols/index.js +4 -0
  38. package/dist/protocols/minimax-video.d.ts +54 -0
  39. package/dist/protocols/minimax-video.js +292 -0
  40. package/dist/protocols/open-responses.d.ts +1 -1
  41. package/dist/protocols/open-responses.js +31 -8
  42. package/dist/protocols/openai-chat.d.ts +24 -0
  43. package/dist/protocols/openai-chat.js +37 -11
  44. package/dist/protocols/openai-compatible-chat.d.ts +1 -0
  45. package/dist/protocols/openai-decisions.js +14 -1
  46. package/dist/protocols/openai-embeddings.d.ts +16 -0
  47. package/dist/protocols/openai-embeddings.js +76 -0
  48. package/dist/protocols/openrouter-video.d.ts +41 -0
  49. package/dist/protocols/openrouter-video.js +138 -0
  50. package/dist/protocols/seedance-video.d.ts +50 -0
  51. package/dist/protocols/seedance-video.js +216 -0
  52. package/dist/protocols/shared.d.ts +13 -3
  53. package/dist/protocols/shared.js +27 -4
  54. package/dist/protocols/system-one.d.ts +45 -1
  55. package/dist/protocols/system-one.js +50 -8
  56. package/dist/protocols/utils/responses-compaction.js +1 -1
  57. package/dist/protocols/venice-chat.d.ts +4 -0
  58. package/dist/protocols/xai-video.d.ts +8 -2
  59. package/dist/protocols/xai-video.js +20 -15
  60. package/dist/protocols/zai-chat.d.ts +4 -0
  61. package/dist/provider-error.js +7 -1
  62. package/dist/providers/alibaba/embeddings.d.ts +2 -0
  63. package/dist/providers/alibaba/embeddings.js +1 -0
  64. package/dist/providers/alibaba.d.ts +3 -0
  65. package/dist/providers/alibaba.js +14 -1
  66. package/dist/providers/amazon-bedrock-mantle.d.ts +1 -0
  67. package/dist/providers/azure/embeddings.d.ts +2 -0
  68. package/dist/providers/azure/embeddings.js +1 -0
  69. package/dist/providers/azure.d.ts +3 -0
  70. package/dist/providers/azure.js +15 -0
  71. package/dist/providers/baseten.d.ts +2 -0
  72. package/dist/providers/byteplus/videos.d.ts +2 -0
  73. package/dist/providers/byteplus/videos.js +1 -0
  74. package/dist/providers/byteplus.d.ts +26 -0
  75. package/dist/providers/byteplus.js +21 -0
  76. package/dist/providers/cerebras.d.ts +2 -0
  77. package/dist/providers/cloudflare-ai-gateway.d.ts +2 -0
  78. package/dist/providers/cloudflare-workers-ai.d.ts +2 -0
  79. package/dist/providers/cohere/embeddings.d.ts +2 -0
  80. package/dist/providers/cohere/embeddings.js +1 -0
  81. package/dist/providers/cohere.d.ts +8 -0
  82. package/dist/providers/cohere.js +17 -1
  83. package/dist/providers/deepinfra/embeddings.d.ts +2 -0
  84. package/dist/providers/deepinfra/embeddings.js +1 -0
  85. package/dist/providers/deepinfra.d.ts +6 -1
  86. package/dist/providers/deepinfra.js +15 -1
  87. package/dist/providers/deepseek.d.ts +2 -0
  88. package/dist/providers/digitalocean/embeddings.d.ts +2 -0
  89. package/dist/providers/digitalocean/embeddings.js +1 -0
  90. package/dist/providers/digitalocean.d.ts +10 -0
  91. package/dist/providers/digitalocean.js +15 -0
  92. package/dist/providers/fireworks/embeddings.d.ts +2 -0
  93. package/dist/providers/fireworks/embeddings.js +1 -0
  94. package/dist/providers/fireworks.d.ts +6 -1
  95. package/dist/providers/fireworks.js +15 -1
  96. package/dist/providers/google/decisions.d.ts +2 -0
  97. package/dist/providers/google/decisions.js +1 -0
  98. package/dist/providers/google/embeddings.d.ts +2 -0
  99. package/dist/providers/google/embeddings.js +1 -0
  100. package/dist/providers/google/videos.d.ts +2 -0
  101. package/dist/providers/google/videos.js +1 -0
  102. package/dist/providers/google-vertex/embeddings.d.ts +2 -0
  103. package/dist/providers/google-vertex/embeddings.js +1 -0
  104. package/dist/providers/google-vertex-chat.d.ts +1 -0
  105. package/dist/providers/google-vertex.d.ts +7 -0
  106. package/dist/providers/google-vertex.js +52 -0
  107. package/dist/providers/google.d.ts +17 -4
  108. package/dist/providers/google.js +27 -3
  109. package/dist/providers/groq.d.ts +5 -0
  110. package/dist/providers/index.d.ts +2 -1
  111. package/dist/providers/index.js +2 -1
  112. package/dist/providers/meta.d.ts +1 -0
  113. package/dist/providers/minimax/videos.d.ts +3 -0
  114. package/dist/providers/minimax/videos.js +1 -0
  115. package/dist/providers/minimax.d.ts +7 -1
  116. package/dist/providers/minimax.js +10 -1
  117. package/dist/providers/moonshot.d.ts +1 -0
  118. package/dist/providers/openai/embeddings.d.ts +2 -0
  119. package/dist/providers/openai/embeddings.js +1 -0
  120. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  121. package/dist/providers/openai-compatible/decisions.js +1 -0
  122. package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
  123. package/dist/providers/openai-compatible/embeddings.js +1 -0
  124. package/dist/providers/openai-compatible.d.ts +6 -0
  125. package/dist/providers/openai-compatible.js +27 -0
  126. package/dist/providers/openai.d.ts +7 -0
  127. package/dist/providers/openai.js +14 -0
  128. package/dist/providers/openrouter/embeddings.d.ts +2 -0
  129. package/dist/providers/openrouter/embeddings.js +1 -0
  130. package/dist/providers/openrouter/videos.d.ts +2 -0
  131. package/dist/providers/openrouter/videos.js +1 -0
  132. package/dist/providers/openrouter.d.ts +21 -0
  133. package/dist/providers/openrouter.js +23 -0
  134. package/dist/providers/togetherai.d.ts +2 -0
  135. package/dist/providers/venice.d.ts +1 -0
  136. package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
  137. package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
  138. package/dist/providers/vercel-ai-gateway.d.ts +4 -0
  139. package/dist/providers/vercel-ai-gateway.js +15 -1
  140. package/dist/providers/volcengine/videos.d.ts +2 -0
  141. package/dist/providers/volcengine/videos.js +1 -0
  142. package/dist/providers/volcengine.d.ts +26 -0
  143. package/dist/providers/volcengine.js +21 -0
  144. package/dist/providers/xai.d.ts +1 -0
  145. package/dist/providers/zai-coding-plan.d.ts +1 -0
  146. package/dist/providers/zai.d.ts +1 -0
  147. package/dist/public.d.ts +4 -0
  148. package/dist/public.js +2 -0
  149. package/dist/route/embedding.d.ts +61 -0
  150. package/dist/route/embedding.js +88 -0
  151. package/dist/route/executor-service.d.ts +6 -0
  152. package/dist/route/executor-service.js +7 -0
  153. package/dist/route/executor.d.ts +7 -1
  154. package/dist/route/executor.js +7 -2
  155. package/dist/route/media-protocol.d.ts +12 -11
  156. package/dist/route/media.d.ts +2 -0
  157. package/dist/route/media.js +31 -22
  158. package/dist/route/transport/http.js +1 -1
  159. package/dist/schema/messages.d.ts +1 -1
  160. package/dist/schema/messages.js +1 -5
  161. package/dist/schema/options.d.ts +8 -0
  162. package/dist/schema/options.js +1 -0
  163. package/dist/speech-client.d.ts +1 -1
  164. package/dist/speech-client.js +4 -4
  165. package/dist/transcription-client.d.ts +1 -1
  166. package/dist/transcription-client.js +1 -2
  167. package/dist/video-client.d.ts +16 -84
  168. package/dist/video-client.js +28 -13
  169. package/dist/video.d.ts +56 -1072
  170. package/dist/video.js +28 -65
  171. package/package.json +355 -255
  172. package/dist/protocols/google-video.d.ts +0 -26
  173. package/dist/protocols/google-video.js +0 -146
  174. package/dist/protocols/runway-video.d.ts +0 -38
  175. package/dist/protocols/runway-video.js +0 -141
  176. package/dist/providers/runway.d.ts +0 -20
  177. package/dist/providers/runway.js +0 -17
@@ -0,0 +1,88 @@
1
+ import { Effect } from "effect";
2
+ import { EmbeddingModel, EmbeddingResponse, EmbeddingUsage, } from "../embedding.js";
3
+ import { ProviderID } from "../schema/index.js";
4
+ import { Auth } from "./auth.js";
5
+ import { Endpoint } from "./endpoint.js";
6
+ import { MediaProtocol } from "./media-protocol.js";
7
+ import { MediaRoute } from "./media.js";
8
+ export const protocol = (input) => input;
9
+ export const make = (input) => {
10
+ const provider = ProviderID.make(input.provider);
11
+ const route = {
12
+ id: input.id,
13
+ provider,
14
+ providerMetadataKey: input.providerMetadataKey ?? provider,
15
+ protocol: input.protocol,
16
+ endpoint: input.endpoint,
17
+ auth: input.auth ?? Auth.none,
18
+ headers: input.headers,
19
+ http: input.http,
20
+ maxValues: input.maxValues,
21
+ };
22
+ return {
23
+ ...route,
24
+ with: (patch) => make({
25
+ ...route,
26
+ ...patch,
27
+ // A new provider gets its own metadata key unless the patch names one.
28
+ providerMetadataKey: patch.providerMetadataKey ?? (patch.provider === undefined ? route.providerMetadataKey : undefined),
29
+ endpoint: patch.endpoint === undefined ? route.endpoint : Endpoint.merge(route.endpoint, patch.endpoint),
30
+ headers: patch.headers === undefined ? route.headers : { ...route.headers, ...patch.headers },
31
+ http: patch.http ?? route.http,
32
+ maxValues: patch.maxValues ?? route.maxValues,
33
+ }),
34
+ model: (model) => EmbeddingModel.make({
35
+ id: model.id,
36
+ provider,
37
+ http: route.http,
38
+ providerOptions: model.providerOptions,
39
+ route: { id: route.id, generate: split(route.maxValues, transport(route).generate) },
40
+ }),
41
+ };
42
+ };
43
+ const CONCURRENCY = 4;
44
+ /**
45
+ * Splits a request whose values exceed `maxValues` and joins the parts: vectors in value order, `inputTokens` summed
46
+ * when every part reports it, and each part's metadata in order under `providerMetadata[key].responses`.
47
+ */
48
+ const split = (maxValues, generate) => (request, execute) => {
49
+ if (maxValues === undefined || request.values.length <= maxValues)
50
+ return generate(request, execute);
51
+ const chunks = Array.from({ length: Math.ceil(request.values.length / maxValues) }, (_, index) => request.values.slice(index * maxValues, (index + 1) * maxValues));
52
+ return Effect.forEach(chunks, (values) => generate({ ...request, values }, execute), {
53
+ concurrency: CONCURRENCY,
54
+ }).pipe(Effect.map((responses) => {
55
+ const tokens = responses.map((response) => response.usage?.inputTokens);
56
+ const keys = [...new Set(responses.flatMap((response) => Object.keys(response.providerMetadata ?? {})))];
57
+ return new EmbeddingResponse({
58
+ embeddings: responses.flatMap((response) => response.embeddings),
59
+ usage: tokens.every((count) => count !== undefined)
60
+ ? new EmbeddingUsage({ inputTokens: tokens.reduce((sum, count) => sum + count, 0) })
61
+ : undefined,
62
+ providerMetadata: keys.length === 0
63
+ ? undefined
64
+ : Object.fromEntries(keys.map((key) => [
65
+ key,
66
+ { responses: responses.map((response) => response.providerMetadata?.[key] ?? {}) },
67
+ ])),
68
+ });
69
+ }));
70
+ };
71
+ // The HTTP plumbing (URL, query, auth, headers, `http` overlays, surrogate sanitizing) is the one media routes use.
72
+ const transport = (route) => MediaRoute.inline({
73
+ protocol: MediaProtocol.inline(MediaProtocol.identity({ id: route.id, name: route.protocol.name, provider: route.provider }), {
74
+ body: {
75
+ from: (request) => route.protocol.body.from(request).pipe(Effect.map((body) => MediaProtocol.json(body))),
76
+ },
77
+ response: {
78
+ decode: (response, context) => route.protocol.response.decode(response, {
79
+ request: context.request,
80
+ providerMetadataKey: route.providerMetadataKey,
81
+ }),
82
+ },
83
+ }),
84
+ endpoint: route.endpoint,
85
+ auth: route.auth,
86
+ headers: route.headers,
87
+ });
88
+ export * as EmbeddingRoute from "./embedding.js";
@@ -1,6 +1,7 @@
1
1
  import { Context, type Effect } 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,6 +11,11 @@ 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;
14
20
  export declare const headerDetails: (headers: Headers.Headers) => {
15
21
  [k: string]: string;
@@ -3,6 +3,13 @@ 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
+ });
6
13
  export const headerDetails = (headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, value]));
7
14
  export const responseHttp = (response) => new HttpContext({
8
15
  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 { CurrentTls, responseHttp, Service } 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,6 +19,11 @@ 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.
@@ -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 { CurrentTls, headerDetails, responseHttp, Service, } from "./executor-service.js";
6
+ export { CurrentTls, responseHttp, Service } 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) => {
@@ -186,6 +186,11 @@ export const layer = Layer.effect(Service, Effect.gen(function* () {
186
186
  });
187
187
  }));
188
188
  export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
189
+ /**
190
+ * Sends through `execute`, presenting `tls` on each request. Apply it only where a provider request is sent, so
191
+ * downloads made through the plain executor never carry the certificate. The executor's HTTP client reads `CurrentTls`.
192
+ */
193
+ export const withTls = (execute, tls) => tls ? (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTls, tls)) : execute;
189
194
  /**
190
195
  * Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
191
196
  * `middleware` still wrap the call, and status classification still applies.
@@ -50,19 +50,25 @@ 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
+ * 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.
59
+ */
60
+ readonly headers: (url: string) => Effect.Effect<Record<string, string>, AIError>;
61
+ /**
62
+ * A further GET with the same auth and headers, retried like the poll itself, for providers whose result needs a
63
+ * second lookup (MiniMax v1 answers with a file id that resolves to a download URL).
64
+ */
65
+ readonly get: (path: string) => Effect.Effect<HttpClientResponse.HttpClientResponse, AIError>;
60
66
  }
61
67
  /**
62
68
  * Submit, then poll. `start` posts the body to the route endpoint; `status`, `result`, and `cancel` are follow-up
63
69
  * calls addressed by the token. Paths are relative to the route base URL unless the provider hands back absolute
64
70
  * 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
71
+ * return the output inside the status body (xAI) point `result.path` at the status path and decode the
66
72
  * same document, so `Generation.await` and `Video.resume(...).await()` behave identically everywhere.
67
73
  */
68
74
  export interface Queued<Request, Response, Token> {
@@ -91,11 +97,6 @@ export interface Queued<Request, Response, Token> {
91
97
  readonly cancel?: {
92
98
  readonly method: AuthInput["method"];
93
99
  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
100
  };
100
101
  }
101
102
  export declare const queued: <Request, Response, Token>(route: Identity, input: Omit<Queued<Request, Response, Token>, "kind" | "id" | "provider">) => Queued<Request, Response, Token>;
@@ -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,16 @@ 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, { token, get, headers: (url) => transport.headers(url, exchange) })));
61
62
  const status = poll(protocol.status);
62
63
  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
64
  return {
67
65
  status,
68
66
  result: poll(protocol.result),
69
- cancel: send !== undefined && cancel?.activeOnly
70
- ? status.pipe(Effect.flatMap((snapshot) => (isTerminal(snapshot.status) ? Effect.void : send)))
71
- : send,
67
+ cancel: cancel === undefined
68
+ ? undefined
69
+ : transport.call(cancel.method, cancel.path(token), exchange, execute).pipe(Effect.asVoid),
72
70
  };
73
71
  };
74
72
  const start = Effect.fn("MediaRoute.start")(function* (request, execute) {
@@ -77,17 +75,19 @@ export const queued = (input) => {
77
75
  const route = generationRoute(started.token, submitted.exchange, execute);
78
76
  return new Generation(route, encodeToken(started.token), started.snapshot);
79
77
  });
78
+ const decode = (raw) => decodeToken(raw).pipe(Effect.mapError((cause) => new AIError({
79
+ reason: new InvalidRequestError({
80
+ message: `${protocol.id} cannot resume a generation from this token`,
81
+ cause,
82
+ }),
83
+ })));
84
+ const attach = (model, raw, execute) => decode(raw).pipe(Effect.map((token) => generationRoute(token, transport.exchange(model), execute)));
80
85
  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
- })));
86
+ const token = yield* decode(raw);
87
87
  const route = generationRoute(token, transport.exchange(model), execute);
88
88
  return new Generation(route, encodeToken(token), yield* route.status);
89
89
  });
90
- return { kind: "queued", id: protocol.id, provider: protocol.provider, protocol: protocol.id, start, resume };
90
+ return { kind: "queued", id: protocol.id, provider: protocol.provider, protocol: protocol.id, start, resume, attach };
91
91
  };
92
92
  /** Compose a streaming media protocol; `generate` runs the same stream in `generate` mode and folds it with `collect`. */
93
93
  export const stream = (input) => {
@@ -129,7 +129,6 @@ export const stream = (input) => {
129
129
  const makeTransport = (input) => {
130
130
  const authorize = Auth.toEffect(input.auth);
131
131
  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
132
  const send = Effect.fn("MediaRoute.send")(function* (call, fetch, execute) {
134
133
  const encoded = encode(call.body, call.headers);
135
134
  const url = call.url.toString();
@@ -140,11 +139,8 @@ const makeTransport = (input) => {
140
139
  body: encoded.text,
141
140
  headers: encoded.headers,
142
141
  });
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
- };
142
+ const response = yield* RequestExecutor.withTls(execute, call.request.http?.tls)(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
143
+ return { response };
148
144
  });
149
145
  return {
150
146
  /** Route and model overlays; `start` additionally merges the request's own. */
@@ -158,7 +154,7 @@ const makeTransport = (input) => {
158
154
  const headers = Headers.fromInput(merged);
159
155
  const prepared = protocol.prepare === undefined
160
156
  ? 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)));
157
+ : 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
158
  // Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized.
163
159
  const resolved = {
164
160
  ...sanitizeSurrogates({ ...prepared, headers: merged, http, providerOptions }),
@@ -169,6 +165,19 @@ const makeTransport = (input) => {
169
165
  const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, request.fetch, execute);
170
166
  return { response: sent.response, context: { request: resolved, body }, exchange };
171
167
  }),
168
+ /**
169
+ * 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.
171
+ */
172
+ headers: (url, exchange) => URL.canParse(url) && new URL(url).origin === baseURL("").origin
173
+ ? authorize({
174
+ request: { http: exchange.http },
175
+ method: "GET",
176
+ url,
177
+ body: "",
178
+ headers: Headers.fromInput(exchange.headers),
179
+ }).pipe(Effect.map((headers) => ({ ...headers })))
180
+ : Effect.succeed({}),
172
181
  /** Bodiless follow-up call (status, result, cancel) with the same auth and headers as `submit`. */
173
182
  call: (method, path, exchange, execute) => {
174
183
  // Provider-issued absolute URLs are used as-is; everything else resolves against the base.
@@ -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
  }));
@@ -747,7 +747,7 @@ export declare const Freeform: Schema.Union<readonly [Schema.Struct<{
747
747
  readonly type: Schema.Literal<"lark">;
748
748
  readonly grammar: Schema.String;
749
749
  }>]>;
750
- export type Freeform = Schema.Schema.Type<typeof Freeform>;
750
+ export type Freeform = Tool.Freeform;
751
751
  declare const toolDefinitionFields: {
752
752
  name: Schema.String;
753
753
  description: Schema.String;
@@ -241,11 +241,7 @@ export const Message = withStatics(messageSchema, {
241
241
  * Raw-text wire encoding for a tool with exactly one required string parameter. Models that accept the format
242
242
  * write that parameter's value directly instead of JSON arguments; calls still decode to the normal object input.
243
243
  */
244
- export const Freeform = Schema.Union([
245
- Schema.Struct({ type: Schema.Literal("text") }),
246
- Schema.Struct({ type: Schema.Literal("regex"), pattern: Schema.String }),
247
- Schema.Struct({ type: Schema.Literal("lark"), grammar: Schema.String }),
248
- ]).annotate({ identifier: "LLM.Freeform" });
244
+ export const Freeform = Tool.Freeform;
249
245
  const toolDefinitionFields = {
250
246
  name: Schema.String,
251
247
  description: Schema.String,
@@ -29,6 +29,14 @@ export interface HttpOptions {
29
29
  readonly body?: Record<string, unknown>;
30
30
  /** Compression for JSON request bodies. Only set it for endpoints known to decode it. */
31
31
  readonly encoding?: RequestEncoding;
32
+ /** Client certificate presented to HTTPS endpoints that request one (mutual TLS). */
33
+ readonly tls?: ClientTls;
34
+ }
35
+ /** PEM client certificate and private key, with the passphrase of an encrypted key. */
36
+ export interface ClientTls {
37
+ readonly cert: string;
38
+ readonly key: string;
39
+ readonly passphrase?: string;
32
40
  }
33
41
  /** Per-phase time limits in milliseconds. */
34
42
  export interface TimeoutConfig {
@@ -61,6 +61,7 @@ export const mergeTransport = (...items) => {
61
61
  query: mergeStringRecords(...http.map((item) => item?.query)),
62
62
  body: mergeJsonRecords(...http.map((item) => item?.body)),
63
63
  encoding: last(http.map((item) => item?.encoding)),
64
+ tls: last(http.map((item) => item?.tls)),
64
65
  }),
65
66
  };
66
67
  };
@@ -1,6 +1,6 @@
1
1
  import { Context } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
- import { type SpeechEvent, type SpeechRequest, type SpeechResponse } from "./speech.js";
3
+ import type { SpeechEvent, SpeechRequest, SpeechResponse } from "./speech.js";
4
4
  export type Interface = MediaClient.Interface<SpeechRequest, SpeechEvent, SpeechResponse>;
5
5
  declare const SpeechClientService_base: Context.ServiceClass<SpeechClientService, "@opencode/SpeechClient", Interface>;
6
6
  export declare class SpeechClientService extends SpeechClientService_base {
@@ -1,6 +1,5 @@
1
1
  import { Context } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
- import { SpeechTimestampsEvent, SpeechFinishEvent, } from "./speech.js";
4
3
  export class SpeechClientService extends Context.Service()("@opencode/SpeechClient") {
5
4
  }
6
5
  export const Service = SpeechClientService;
@@ -9,12 +8,13 @@ export const SpeechClient = {
9
8
  ...MediaClient.make(Service, {
10
9
  modality: "speech",
11
10
  responseEvents: (response) => [
12
- ...(response.timestamps === undefined ? [] : [SpeechTimestampsEvent.make({ items: response.timestamps })]),
13
- SpeechFinishEvent.make({
11
+ ...(response.timestamps === undefined ? [] : [{ type: "timestamps", items: response.timestamps }]),
12
+ {
13
+ type: "finish",
14
14
  audio: response.audio,
15
15
  usage: response.usage,
16
16
  providerMetadata: response.providerMetadata,
17
- }),
17
+ },
18
18
  ],
19
19
  }),
20
20
  };
@@ -1,6 +1,6 @@
1
1
  import { Context } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
- import { type TranscriptionEvent, type TranscriptionRequest, type TranscriptionResponse } from "./transcription.js";
3
+ import type { TranscriptionEvent, TranscriptionRequest, TranscriptionResponse } from "./transcription.js";
4
4
  export type Interface = MediaClient.Interface<TranscriptionRequest, TranscriptionEvent, TranscriptionResponse>;
5
5
  declare const TranscriptionClientService_base: Context.ServiceClass<TranscriptionClientService, "@opencode/TranscriptionClient", Interface>;
6
6
  export declare class TranscriptionClientService extends TranscriptionClientService_base {
@@ -1,6 +1,5 @@
1
1
  import { Context } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
- import { TranscriptionFinishEvent, } from "./transcription.js";
4
3
  export class TranscriptionClientService extends Context.Service()("@opencode/TranscriptionClient") {
5
4
  }
6
5
  export const Service = TranscriptionClientService;
@@ -8,6 +7,6 @@ export const TranscriptionClient = {
8
7
  Service,
9
8
  ...MediaClient.make(Service, {
10
9
  modality: "transcription",
11
- responseEvents: (response) => [TranscriptionFinishEvent.make({ ...response })],
10
+ responseEvents: (response) => [{ type: "finish", ...response }],
12
11
  }),
13
12
  };
@@ -1,93 +1,25 @@
1
- import { Context } from "effect";
2
- import { MediaClient } from "./media-client.js";
3
- import { type VideoEvent, type VideoRequest, type VideoResponse } from "./video.js";
4
- export type Interface = MediaClient.Interface<VideoRequest, VideoEvent, VideoResponse>;
1
+ import { Context, Effect, Layer } from "effect";
2
+ import { RequestExecutor } from "./route/executor.js";
3
+ import { AIError } from "./schema/index.js";
4
+ import type { VideoJob, VideoModel, VideoRequest, VideoResponse, VideoStatus } from "./video.js";
5
+ export interface Interface {
6
+ readonly start: (request: VideoRequest) => Effect.Effect<VideoJob, AIError>;
7
+ readonly status: (model: VideoModel, token: unknown) => Effect.Effect<VideoStatus, AIError>;
8
+ readonly result: (model: VideoModel, token: unknown) => Effect.Effect<VideoResponse, AIError>;
9
+ readonly cancel: (model: VideoModel, token: unknown) => Effect.Effect<void, AIError>;
10
+ }
5
11
  declare const VideoClientService_base: Context.ServiceClass<VideoClientService, "@opencode/VideoClient", Interface>;
6
12
  export declare class VideoClientService extends VideoClientService_base {
7
13
  }
8
14
  export declare const Service: typeof VideoClientService;
9
15
  export type Service = VideoClientService;
16
+ export declare const layer: Layer.Layer<VideoClientService, never, RequestExecutor.RequestExecutorService>;
10
17
  export declare const VideoClient: {
11
- readonly responseEvents: (response: VideoResponse) => readonly ({
12
- readonly type: "video";
13
- readonly index: number;
14
- readonly video: import("./media.js").Asset;
15
- } | {
16
- readonly type: "generation-queued";
17
- readonly id: string;
18
- readonly position?: number | undefined;
19
- } | {
20
- readonly type: "generation-progress";
21
- readonly id: string;
22
- readonly progress?: number | undefined;
23
- } | {
24
- readonly type: "finish";
25
- readonly usage?: {
26
- readonly type: "seconds";
27
- readonly seconds: number;
28
- } | {
29
- readonly type: "characters";
30
- readonly characters: number;
31
- } | {
32
- readonly type: "credits";
33
- readonly credits: number;
34
- } | {
35
- readonly type: "compute";
36
- readonly seconds: number;
37
- } | {
38
- readonly type: "tokens";
39
- readonly input?: number | undefined;
40
- readonly output?: number | undefined;
41
- readonly total?: number | undefined;
42
- readonly details?: {
43
- readonly [x: string]: unknown;
44
- } | undefined;
45
- } | undefined;
46
- readonly providerMetadata?: {
47
- readonly [x: string]: {
48
- readonly [x: string]: unknown;
49
- };
50
- } | undefined;
51
- })[];
52
- readonly layer: import("effect/Layer").Layer<VideoClientService, never, import("./route.js").RequestExecutorService>;
53
- readonly generate: (request: VideoRequest, options?: import("./generation.js").AwaitOptions) => import("effect/Effect").Effect<VideoResponse, import("./public.js").AIError, VideoClientService>;
54
- readonly stream: (request: VideoRequest, options?: import("./generation.js").AwaitOptions) => import("effect/Stream").Stream<{
55
- readonly type: "video";
56
- readonly index: number;
57
- readonly video: import("./media.js").Asset;
58
- } | {
59
- readonly type: "finish";
60
- readonly usage?: {
61
- readonly type: "seconds";
62
- readonly seconds: number;
63
- } | {
64
- readonly type: "characters";
65
- readonly characters: number;
66
- } | {
67
- readonly type: "credits";
68
- readonly credits: number;
69
- } | {
70
- readonly type: "compute";
71
- readonly seconds: number;
72
- } | {
73
- readonly type: "tokens";
74
- readonly input?: number | undefined;
75
- readonly output?: number | undefined;
76
- readonly total?: number | undefined;
77
- readonly details?: {
78
- readonly [x: string]: unknown;
79
- } | undefined;
80
- } | undefined;
81
- readonly providerMetadata?: {
82
- readonly [x: string]: {
83
- readonly [x: string]: unknown;
84
- };
85
- } | undefined;
86
- } | import("./generation.js").Observation, import("./public.js").AIError, VideoClientService>;
87
- readonly start: (request: VideoRequest) => import("effect/Effect").Effect<import("./generation.js").Generation<VideoResponse>, import("./public.js").AIError, VideoClientService>;
88
- readonly resume: (model: import("./video.js").VideoModel<{
89
- readonly [x: string]: unknown;
90
- }>, token: unknown) => import("effect/Effect").Effect<import("./generation.js").Generation<VideoResponse>, import("./public.js").AIError, VideoClientService>;
91
18
  readonly Service: typeof VideoClientService;
19
+ readonly layer: Layer.Layer<VideoClientService, never, RequestExecutor.RequestExecutorService>;
20
+ readonly start: (request: VideoRequest) => Effect.Effect<VideoJob, AIError, VideoClientService>;
21
+ readonly status: (model: VideoModel, token: unknown) => Effect.Effect<VideoStatus, AIError, VideoClientService>;
22
+ readonly result: (model: VideoModel, token: unknown) => Effect.Effect<VideoResponse, AIError, VideoClientService>;
23
+ readonly cancel: (model: VideoModel, token: unknown) => Effect.Effect<void, AIError, VideoClientService>;
92
24
  };
93
25
  export {};
@@ -1,19 +1,34 @@
1
- import { Context } from "effect";
2
- import { MediaClient } from "./media-client.js";
3
- import { VideoOutputEvent, VideoFinishEvent } from "./video.js";
1
+ import { Context, Effect, Layer } from "effect";
2
+ import { RequestExecutor } from "./route/executor.js";
3
+ import { AIError, UnsupportedOperationError } from "./schema/index.js";
4
4
  export class VideoClientService extends Context.Service()("@opencode/VideoClient") {
5
5
  }
6
6
  export const Service = VideoClientService;
7
+ export const layer = Layer.effect(Service, Effect.gen(function* () {
8
+ const executor = yield* RequestExecutor.Service;
9
+ const attach = (model, token) => model.route.attach(model, token, executor.execute);
10
+ return Service.of({
11
+ start: (request) => request.model.route
12
+ .start(request, executor.execute)
13
+ .pipe(Effect.map((generation) => ({ id: generation.id, token: generation.token }))),
14
+ status: (model, token) => attach(model, token).pipe(Effect.flatMap((route) => route.status), Effect.map((snapshot) => ({ status: snapshot.status, progress: snapshot.progress }))),
15
+ result: (model, token) => attach(model, token).pipe(Effect.flatMap((route) => route.result)),
16
+ cancel: (model, token) => attach(model, token).pipe(Effect.flatMap((route) => route.cancel ??
17
+ Effect.fail(new AIError({
18
+ reason: new UnsupportedOperationError({
19
+ operation: "video.cancel",
20
+ provider: model.provider,
21
+ route: model.route.id,
22
+ message: `${model.provider}/${model.route.id} has no way to cancel a video generation`,
23
+ }),
24
+ })))),
25
+ });
26
+ }));
7
27
  export const VideoClient = {
8
28
  Service,
9
- ...MediaClient.make(Service, {
10
- modality: "video",
11
- responseEvents: (response) => [
12
- ...response.videos.map((video, index) => VideoOutputEvent.make({ index, video })),
13
- VideoFinishEvent.make({
14
- usage: response.usage,
15
- providerMetadata: response.providerMetadata,
16
- }),
17
- ],
18
- }),
29
+ layer,
30
+ start: (request) => Service.use((client) => client.start(request)),
31
+ status: (model, token) => Service.use((client) => client.status(model, token)),
32
+ result: (model, token) => Service.use((client) => client.result(model, token)),
33
+ cancel: (model, token) => Service.use((client) => client.cancel(model, token)),
19
34
  };