@opencode/ai 2.2.7 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.md +164 -99
  2. package/dist/cache-policy.js +4 -2
  3. package/dist/effect.d.ts +11 -8
  4. package/dist/effect.js +2 -1
  5. package/dist/experimental.d.ts +0 -4
  6. package/dist/experimental.js +0 -3
  7. package/dist/generation.d.ts +10 -10
  8. package/dist/generation.js +8 -14
  9. package/dist/image-client.d.ts +56 -59
  10. package/dist/image-client.js +47 -12
  11. package/dist/image.d.ts +36 -95
  12. package/dist/image.js +11 -14
  13. package/dist/index.d.ts +31 -68
  14. package/dist/index.js +54 -30
  15. package/dist/llm.d.ts +4 -1
  16. package/dist/llm.js +10 -1
  17. package/dist/media-client.d.ts +18 -6
  18. package/dist/media-client.js +42 -37
  19. package/dist/media-model.d.ts +2 -0
  20. package/dist/media-model.js +3 -1
  21. package/dist/media.d.ts +26 -4
  22. package/dist/media.js +52 -11
  23. package/dist/protocols/alibaba-messages.d.ts +24 -2
  24. package/dist/protocols/alibaba-responses.d.ts +26 -0
  25. package/dist/protocols/anthropic-messages.d.ts +70 -6
  26. package/dist/protocols/anthropic-messages.js +74 -9
  27. package/dist/protocols/assemblyai-transcription.js +7 -6
  28. package/dist/protocols/cartesia-speech.d.ts +0 -8
  29. package/dist/protocols/deepgram-speech.d.ts +0 -8
  30. package/dist/protocols/elevenlabs-speech.d.ts +0 -8
  31. package/dist/protocols/google-decisions.d.ts +13 -0
  32. package/dist/protocols/google-decisions.js +133 -0
  33. package/dist/protocols/google-interactions-video.d.ts +38 -0
  34. package/dist/protocols/google-interactions-video.js +185 -0
  35. package/dist/protocols/google-interactions.d.ts +14 -1
  36. package/dist/protocols/google-interactions.js +1 -1
  37. package/dist/protocols/google-speech.d.ts +0 -8
  38. package/dist/protocols/google-transcription.d.ts +0 -8
  39. package/dist/protocols/index.d.ts +1 -0
  40. package/dist/protocols/index.js +1 -0
  41. package/dist/protocols/meta-messages.d.ts +24 -2
  42. package/dist/protocols/meta-responses.d.ts +52 -0
  43. package/dist/protocols/minimax-video.d.ts +45 -0
  44. package/dist/protocols/minimax-video.js +290 -0
  45. package/dist/protocols/open-responses.d.ts +250 -24
  46. package/dist/protocols/open-responses.js +40 -24
  47. package/dist/protocols/openai-chat.js +7 -3
  48. package/dist/protocols/openai-compatible-responses.d.ts +26 -0
  49. package/dist/protocols/openai-freeform.d.ts +1 -1
  50. package/dist/protocols/openai-freeform.js +9 -5
  51. package/dist/protocols/openai-images.d.ts +0 -8
  52. package/dist/protocols/openai-responses.d.ts +153 -0
  53. package/dist/protocols/openai-responses.js +68 -7
  54. package/dist/protocols/openai-speech.d.ts +0 -8
  55. package/dist/protocols/openai-transcription.d.ts +0 -8
  56. package/dist/protocols/openrouter-video.d.ts +36 -0
  57. package/dist/protocols/openrouter-video.js +139 -0
  58. package/dist/protocols/seedance-video.d.ts +45 -0
  59. package/dist/protocols/seedance-video.js +217 -0
  60. package/dist/protocols/system-one.d.ts +45 -1
  61. package/dist/protocols/system-one.js +42 -7
  62. package/dist/protocols/utils/gateway-protocol.js +1 -0
  63. package/dist/protocols/utils/responses-compaction.js +8 -4
  64. package/dist/protocols/xai-responses.d.ts +26 -0
  65. package/dist/protocols/xai-video.d.ts +12 -11
  66. package/dist/protocols/xai-video.js +33 -24
  67. package/dist/protocols/zai-messages.d.ts +24 -2
  68. package/dist/provider-error.js +7 -1
  69. package/dist/providers/alibaba.d.ts +50 -2
  70. package/dist/providers/amazon-bedrock-mantle.d.ts +50 -2
  71. package/dist/providers/anthropic-compatible.d.ts +24 -2
  72. package/dist/providers/anthropic.d.ts +24 -2
  73. package/dist/providers/azure.d.ts +76 -2
  74. package/dist/providers/byteplus/videos.d.ts +2 -0
  75. package/dist/providers/byteplus/videos.js +1 -0
  76. package/dist/providers/byteplus.d.ts +26 -0
  77. package/dist/providers/byteplus.js +21 -0
  78. package/dist/providers/cloudflare-ai-gateway.d.ts +100 -4
  79. package/dist/providers/digitalocean.d.ts +26 -0
  80. package/dist/providers/google/decisions.d.ts +2 -0
  81. package/dist/providers/google/decisions.js +1 -0
  82. package/dist/providers/google/videos.d.ts +2 -0
  83. package/dist/providers/google/videos.js +1 -0
  84. package/dist/providers/google-vertex-messages.d.ts +24 -2
  85. package/dist/providers/google-vertex-messages.js +1 -0
  86. package/dist/providers/google-vertex-responses.d.ts +26 -0
  87. package/dist/providers/google.d.ts +11 -4
  88. package/dist/providers/google.js +16 -3
  89. package/dist/providers/index.d.ts +2 -1
  90. package/dist/providers/index.js +2 -1
  91. package/dist/providers/meta.d.ts +50 -2
  92. package/dist/providers/minimax/videos.d.ts +3 -0
  93. package/dist/providers/minimax/videos.js +1 -0
  94. package/dist/providers/minimax.d.ts +56 -3
  95. package/dist/providers/minimax.js +10 -1
  96. package/dist/providers/moonshot.d.ts +50 -2
  97. package/dist/providers/openai-compatible/decisions.d.ts +2 -0
  98. package/dist/providers/openai-compatible/decisions.js +1 -0
  99. package/dist/providers/openai-compatible-responses.d.ts +26 -0
  100. package/dist/providers/openai-compatible.d.ts +2 -0
  101. package/dist/providers/openai-compatible.js +14 -0
  102. package/dist/providers/openai.d.ts +26 -0
  103. package/dist/providers/openrouter/videos.d.ts +2 -0
  104. package/dist/providers/openrouter/videos.js +1 -0
  105. package/dist/providers/openrouter.d.ts +31 -0
  106. package/dist/providers/openrouter.js +8 -0
  107. package/dist/providers/venice.d.ts +26 -0
  108. package/dist/providers/volcengine/videos.d.ts +2 -0
  109. package/dist/providers/volcengine/videos.js +1 -0
  110. package/dist/providers/volcengine.d.ts +26 -0
  111. package/dist/providers/volcengine.js +21 -0
  112. package/dist/providers/xai/videos.d.ts +2 -0
  113. package/dist/providers/xai/videos.js +1 -0
  114. package/dist/providers/xai.d.ts +4 -3
  115. package/dist/providers/xai.js +5 -1
  116. package/dist/providers/zai-coding-plan.d.ts +50 -2
  117. package/dist/public.d.ts +7 -4
  118. package/dist/public.js +2 -1
  119. package/dist/route/client.d.ts +2 -0
  120. package/dist/route/client.js +5 -1
  121. package/dist/route/executor-service.d.ts +20 -1
  122. package/dist/route/executor-service.js +35 -1
  123. package/dist/route/executor.d.ts +11 -2
  124. package/dist/route/executor.js +25 -5
  125. package/dist/route/media-protocol.d.ts +21 -15
  126. package/dist/route/media-protocol.js +11 -4
  127. package/dist/route/media.d.ts +2 -0
  128. package/dist/route/media.js +40 -22
  129. package/dist/route/protocol.d.ts +3 -0
  130. package/dist/route/transport/http.js +1 -1
  131. package/dist/schema/events.d.ts +5 -0
  132. package/dist/schema/messages.d.ts +25 -2
  133. package/dist/schema/messages.js +27 -7
  134. package/dist/schema/options.d.ts +18 -2
  135. package/dist/schema/options.js +1 -0
  136. package/dist/speech-client.d.ts +6 -6
  137. package/dist/speech-client.js +4 -4
  138. package/dist/speech.d.ts +7 -88
  139. package/dist/speech.js +1 -3
  140. package/dist/tool-updates.d.ts +34 -0
  141. package/dist/tool-updates.js +93 -0
  142. package/dist/tool.d.ts +6 -1
  143. package/dist/tool.js +1 -1
  144. package/dist/transcription-client.d.ts +6 -6
  145. package/dist/transcription-client.js +1 -2
  146. package/dist/transcription.d.ts +7 -88
  147. package/dist/transcription.js +1 -3
  148. package/dist/video-client.d.ts +16 -84
  149. package/dist/video-client.js +30 -13
  150. package/dist/video.d.ts +54 -1126
  151. package/dist/video.js +29 -65
  152. package/package.json +59 -7
  153. package/dist/protocols/google-video.d.ts +0 -26
  154. package/dist/protocols/google-video.js +0 -146
  155. package/dist/protocols/runway-video.d.ts +0 -38
  156. package/dist/protocols/runway-video.js +0 -141
  157. package/dist/providers/runway.d.ts +0 -20
  158. package/dist/providers/runway.js +0 -17
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ import { type ImageModel, type ImageRequest, type ImageRequestInput } from "./im
7
7
  import { LLM } from "./llm.js";
8
8
  import { Media } from "./media.js";
9
9
  import { type CheckpointRequest, type CompactionRequest, type EndpointCompactOptions, type StreamOptions, type TriggerCompactOptions } from "./route/client.js";
10
- import { RequestExecutor } from "./route/executor.js";
10
+ import { RequestExecutor, type HttpMiddleware } from "./route/executor.js";
11
11
  import { LanguageModel, type CompactionCheckpointResponse, type CompactionResponse, type LLMEvent, type LLMResponse } from "./schema/index.js";
12
12
  import type { LoopObjectEvent, ObjectEvent, ObjectResponse, OutputSchema, OutputType, LLMLoopInput, LLMRequestInput } from "./llm.js";
13
13
  import { type SpeechModel, type SpeechRequest, type SpeechRequestInput } from "./speech.js";
@@ -25,7 +25,14 @@ export interface Options {
25
25
  }
26
26
  export interface RunOptions {
27
27
  readonly signal?: AbortSignal;
28
+ /**
29
+ * Runs on every provider request the call makes, like `RequestExecutor.withMiddleware`: submits, polls, results and
30
+ * cancels included. A handle the call returns keeps it for its own calls.
31
+ */
32
+ readonly http?: HttpMiddleware;
28
33
  }
34
+ /** Options for reading or writing an asset. Downloads use the asset's own `middleware`, never a caller's `http`. */
35
+ export type AssetRunOptions = Omit<RunOptions, "http">;
29
36
  export type Services = AIClient.Services;
30
37
  /**
31
38
  * Promise view of a `Generation`. Its fields are a snapshot taken when the handle was created; `refresh()` resolves to a
@@ -47,14 +54,14 @@ export type GenerationHandle<Response> = Snapshot & {
47
54
  export declare const make: (options?: Options) => {
48
55
  run: <A, E>(effect: Effect.Effect<A, E, Services>, options?: RunOptions) => Promise<A>;
49
56
  /** Decoded asset bytes, downloading `url` sources through the executor. */
50
- bytes: (asset: Media.Asset, options?: RunOptions) => Promise<Uint8Array<ArrayBufferLike>>;
51
- base64: (asset: Media.Asset, options?: RunOptions) => Promise<string>;
57
+ bytes: (asset: Media.Asset, options?: AssetRunOptions) => Promise<Uint8Array<ArrayBufferLike>>;
58
+ base64: (asset: Media.Asset, options?: AssetRunOptions) => Promise<string>;
52
59
  /** Pull a `url` asset into owned bytes before the provider URL expires. */
53
- materialize: (asset: Media.Asset, options?: RunOptions) => Promise<Media.Asset>;
60
+ materialize: (asset: Media.Asset, options?: AssetRunOptions) => Promise<Media.Asset>;
54
61
  /** Read a file into an asset like `Media.file`: sniffed media type, then the extension's. */
55
- file: (path: string, options?: Media.AssetOptions & RunOptions) => Promise<Media.Asset>;
56
- /** Write an asset's bytes like `Media.write`, downloading `url` sources through the executor. */
57
- write: (asset: Media.Asset, path: string, options?: RunOptions) => Promise<void>;
62
+ file: (path: string, options?: Media.AssetOptions & AssetRunOptions) => Promise<Media.Asset>;
63
+ /** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
64
+ write: (asset: Media.Asset, path: string, options?: AssetRunOptions) => Promise<void>;
58
65
  request: typeof LLM.request;
59
66
  generate: {
60
67
  <const Model extends LanguageModel, S extends OutputSchema>(input: LLMRequestInput<Model> & {
@@ -93,10 +100,6 @@ export declare const make: (options?: Options) => {
93
100
  readonly type: "image";
94
101
  readonly index: number;
95
102
  readonly image: Media.Asset;
96
- } | {
97
- readonly type: "generation-queued";
98
- readonly id: string;
99
- readonly position?: number | undefined;
100
103
  } | {
101
104
  readonly type: "generation-progress";
102
105
  readonly id: string;
@@ -130,8 +133,13 @@ export declare const make: (options?: Options) => {
130
133
  };
131
134
  } | undefined;
132
135
  }>;
133
- start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) => Promise<GenerationHandle<import("./image.js").ImageResponse>>;
134
- resume: (model: ImageModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./image.js").ImageResponse>>;
136
+ /** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */
137
+ start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) => Promise<import("./image.js").ImageJob>;
138
+ /** One status read for a job ID. */
139
+ status: (model: ImageModel, id: string, options?: RunOptions) => Promise<import("./image.js").ImageStatus>;
140
+ /** The finished images; fails while the job is still running. */
141
+ result: (model: ImageModel, id: string, options?: RunOptions) => Promise<import("./image.js").ImageResponse>;
142
+ cancel: (model: ImageModel, id: string, options?: RunOptions) => Promise<void>;
135
143
  };
136
144
  decision: {
137
145
  request: typeof import("./decision.js").request;
@@ -141,6 +149,16 @@ export declare const make: (options?: Options) => {
141
149
  request: typeof import("./embedding.js").request;
142
150
  generate: <const Model extends EmbeddingModel>(input: EmbeddingRequestInput<Model>, options?: RunOptions) => Promise<import("./embedding.js").EmbeddingResponse>;
143
151
  };
152
+ video: {
153
+ request: typeof import("./video.js").request;
154
+ /** Submit a generation and return its `{ id }` at once; nothing polls. */
155
+ start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) => Promise<import("./video.js").VideoJob>;
156
+ /** One status read for a job ID. */
157
+ status: (model: VideoModel, id: string, options?: RunOptions) => Promise<import("./video.js").VideoStatus>;
158
+ /** The finished videos; fails while the job is still running. */
159
+ result: (model: VideoModel, id: string, options?: RunOptions) => Promise<import("./video.js").VideoResponse>;
160
+ cancel: (model: VideoModel, id: string, options?: RunOptions) => Promise<void>;
161
+ };
144
162
  /** Experimental: may change without compatibility guarantees. */
145
163
  experimental: {
146
164
  speech: {
@@ -156,10 +174,6 @@ export declare const make: (options?: Options) => {
156
174
  readonly startSeconds: number;
157
175
  readonly endSeconds: number;
158
176
  }[];
159
- } | {
160
- readonly type: "generation-queued";
161
- readonly id: string;
162
- readonly position?: number | undefined;
163
177
  } | {
164
178
  readonly type: "generation-progress";
165
179
  readonly id: string;
@@ -209,10 +223,6 @@ export declare const make: (options?: Options) => {
209
223
  readonly endSeconds: number;
210
224
  readonly speaker?: string | undefined;
211
225
  };
212
- } | {
213
- readonly type: "generation-queued";
214
- readonly id: string;
215
- readonly position?: number | undefined;
216
226
  } | {
217
227
  readonly type: "generation-progress";
218
228
  readonly id: string;
@@ -265,53 +275,6 @@ export declare const make: (options?: Options) => {
265
275
  start: <const Model extends TranscriptionModel>(input: TranscriptionRequestInput<Model> | TranscriptionRequest, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
266
276
  resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./transcription.js").TranscriptionResponse>>;
267
277
  };
268
- video: {
269
- request: typeof import("./video.js").request;
270
- start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) => Promise<GenerationHandle<import("./video.js").VideoResponse>>;
271
- generate: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: AwaitOptions & RunOptions) => Promise<import("./video.js").VideoResponse>;
272
- resume: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<GenerationHandle<import("./video.js").VideoResponse>>;
273
- stream: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: AwaitOptions & RunOptions) => AsyncIterable<{
274
- readonly type: "video";
275
- readonly index: number;
276
- readonly video: Media.Asset;
277
- } | {
278
- readonly type: "generation-queued";
279
- readonly id: string;
280
- readonly position?: number | undefined;
281
- } | {
282
- readonly type: "generation-progress";
283
- readonly id: string;
284
- readonly progress?: number | undefined;
285
- } | {
286
- readonly type: "finish";
287
- readonly usage?: {
288
- readonly type: "seconds";
289
- readonly seconds: number;
290
- } | {
291
- readonly type: "characters";
292
- readonly characters: number;
293
- } | {
294
- readonly type: "credits";
295
- readonly credits: number;
296
- } | {
297
- readonly type: "compute";
298
- readonly seconds: number;
299
- } | {
300
- readonly type: "tokens";
301
- readonly input?: number | undefined;
302
- readonly output?: number | undefined;
303
- readonly total?: number | undefined;
304
- readonly details?: {
305
- readonly [x: string]: unknown;
306
- } | undefined;
307
- } | undefined;
308
- readonly providerMetadata?: {
309
- readonly [x: string]: {
310
- readonly [x: string]: unknown;
311
- };
312
- } | undefined;
313
- }>;
314
- };
315
278
  };
316
279
  dispose: () => Promise<void>;
317
280
  };
package/dist/index.js CHANGED
@@ -28,35 +28,36 @@ const abortEffect = (signal) => signal === undefined
28
28
  export const make = (options = {}) => {
29
29
  const runtime = ManagedRuntime.make(AIClient.layerWith(options.layer ?? RequestExecutor.fetchLayer));
30
30
  /** Run any package Effect (for example `ai.compact(...)` from `@opencode/ai/effect`) inside this runtime. */
31
- const run = (effect, options) => runtime.runPromise(Effect.raceFirst(effect, abortEffect(options?.signal)));
32
- const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => stream.pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
31
+ const run = (effect, options) => runtime.runPromise(Effect.raceFirst(scoped(effect, options?.http), abortEffect(options?.signal)));
32
+ const iterate = (stream, options) => Stream.toAsyncIterable(Stream.unwrap(runtime.contextEffect.pipe(Effect.map((context) => scoped(stream, options?.http).pipe(Stream.interruptWhen(abortEffect(options?.signal)), Stream.provideContext(context))))));
33
+ // `run` and `iterate` apply `http` around the whole call, so the LLM call gets none of its own.
33
34
  function generate(input, options) {
34
- return run(LLM.generate(input, options), options);
35
+ return run(LLM.generate(input, { ...options, http: undefined }), options);
35
36
  }
36
37
  function stream(input, options) {
37
- return iterate(LLM.stream(input, options), options);
38
+ return iterate(LLM.stream(input, { ...options, http: undefined }), options);
38
39
  }
39
40
  function loop(input, options) {
40
- return iterate(LLM.loop(input, options), options);
41
+ return iterate(LLM.loop(input, { ...options, http: undefined }), options);
41
42
  }
42
43
  /** Read `events` from `stream` or `loop` to the end and fold them into the final result. */
43
44
  const collect = (events, options) => run(LLM.collect(Stream.fromAsyncIterable(events, (error) => error)), options);
44
45
  // The overloads pair each request type with its mechanism; `LLM.compact` checks the route's capability at runtime.
45
46
  function compact(request, options) {
46
47
  return options?.mechanism === "trigger"
47
- ? run(LLM.compact(request, options), options)
48
- : run(LLM.compact(request, options), options);
48
+ ? run(LLM.compact(request, { ...options, http: undefined }), options)
49
+ : run(LLM.compact(request, { ...options, http: undefined }), options);
49
50
  }
50
- const handle = (generation) => ({
51
+ const handle = (http) => (generation) => ({
51
52
  ...generation.snapshot,
52
53
  snapshot: generation.snapshot,
53
54
  terminal: generation.terminal,
54
55
  token: generation.token,
55
- await: (options) => run(generation.await(options), options),
56
- events: (options) => iterate(generation.events(options), options),
57
- result: (options) => run(generation.result(), options),
58
- refresh: (options) => run(generation.refresh(), options).then(handle),
59
- cancel: (options) => run(generation.cancel(), options),
56
+ await: (options) => run(generation.await(options), { http, ...options }),
57
+ events: (options) => iterate(generation.events(options), { http, ...options }),
58
+ result: (options) => run(generation.result(), { http, ...options }),
59
+ refresh: (options) => run(generation.refresh(), { http, ...options }).then(handle(options?.http ?? http)),
60
+ cancel: (options) => run(generation.cancel(), { http, ...options }),
60
61
  });
61
62
  return {
62
63
  run,
@@ -76,13 +77,27 @@ export const make = (options = {}) => {
76
77
  return Media.bytes(data, fileMediaType(data, path), options);
77
78
  })), options);
78
79
  },
79
- /** Write an asset's bytes like `Media.write`, downloading `url` sources through the executor. */
80
+ /** Write an asset's bytes like `Media.write`: streamed through a temporary file that replaces `path` on success. */
80
81
  write: async (asset, path, options) => {
81
- const { writeFile } = await import("node:fs/promises");
82
- return run(asset.bytes().pipe(Effect.flatMap((data) => Effect.tryPromise({
83
- try: (signal) => writeFile(path, data, { signal }),
84
- catch: (cause) => fileError(`Failed to write media file ${path}`, cause),
85
- }))), options);
82
+ const { open, rename, rm } = await import("node:fs/promises");
83
+ const temporary = `${path}.${crypto.randomUUID()}.tmp`;
84
+ try {
85
+ const file = await open(temporary, "w");
86
+ try {
87
+ for await (const chunk of iterate(asset.stream(), options))
88
+ await file.write(chunk);
89
+ }
90
+ finally {
91
+ await file.close();
92
+ }
93
+ await rename(temporary, path);
94
+ }
95
+ catch (cause) {
96
+ await rm(temporary, { force: true });
97
+ if (cause instanceof AIError || cause === options?.signal?.reason)
98
+ throw cause;
99
+ throw fileError(`Failed to write media file ${path}`, cause);
100
+ }
86
101
  },
87
102
  request: LLM.request,
88
103
  generate,
@@ -97,8 +112,13 @@ export const make = (options = {}) => {
97
112
  request: Image.request,
98
113
  generate: (input, options) => run(Image.generate(input, options), options),
99
114
  stream: (input, options) => iterate(Image.stream(input, options), options),
100
- start: (input, options) => run(Image.start(input), options).then(handle),
101
- resume: (model, token, options) => run(Image.resume(model, token), options).then(handle),
115
+ /** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */
116
+ start: (input, options) => run(Image.start(input), options),
117
+ /** One status read for a job ID. */
118
+ status: (model, id, options) => run(Image.status(model, id), options),
119
+ /** The finished images; fails while the job is still running. */
120
+ result: (model, id, options) => run(Image.result(model, id), options),
121
+ cancel: (model, id, options) => run(Image.cancel(model, id), options),
102
122
  },
103
123
  decision: {
104
124
  request: Decision.request,
@@ -108,6 +128,16 @@ export const make = (options = {}) => {
108
128
  request: Embedding.request,
109
129
  generate: (input, options) => run(Embedding.generate(input), options),
110
130
  },
131
+ video: {
132
+ request: Video.request,
133
+ /** Submit a generation and return its `{ id }` at once; nothing polls. */
134
+ start: (input, options) => run(Video.start(input), options),
135
+ /** One status read for a job ID. */
136
+ status: (model, id, options) => run(Video.status(model, id), options),
137
+ /** The finished videos; fails while the job is still running. */
138
+ result: (model, id, options) => run(Video.result(model, id), options),
139
+ cancel: (model, id, options) => run(Video.cancel(model, id), options),
140
+ },
111
141
  /** Experimental: may change without compatibility guarantees. */
112
142
  experimental: {
113
143
  speech: {
@@ -119,20 +149,14 @@ export const make = (options = {}) => {
119
149
  request: Transcription.request,
120
150
  generate: (input, options) => run(Transcription.generate(input, { poll: options?.poll }), options),
121
151
  stream: (input, options) => iterate(Transcription.stream(input, { poll: options?.poll }), options),
122
- start: (input, options) => run(Transcription.start(input), options).then(handle),
123
- resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle),
124
- },
125
- video: {
126
- request: Video.request,
127
- start: (input, options) => run(Video.start(input), options).then(handle),
128
- generate: (input, options) => run(Video.generate(input, { poll: options?.poll }), options),
129
- resume: (model, token, options) => run(Video.resume(model, token), options).then(handle),
130
- stream: (input, options) => iterate(Video.stream(input, { poll: options?.poll }), options),
152
+ start: (input, options) => run(Transcription.start(input), options).then(handle(options?.http)),
153
+ resume: (model, token, options) => run(Transcription.resume(model, token), options).then(handle(options?.http)),
131
154
  },
132
155
  },
133
156
  dispose: () => runtime.dispose(),
134
157
  };
135
158
  };
159
+ const scoped = (self, http) => (http === undefined ? self : RequestExecutor.withMiddleware(http)(self));
136
160
  const fileError = (message, cause) => new AIError({ reason: new InvalidRequestError({ message, cause }) });
137
161
  /** `tool` from `@opencode/ai/effect`, with an `execute` that returns a value or a Promise and throws to fail. */
138
162
  export const tool = (config) => {
package/dist/llm.d.ts CHANGED
@@ -15,7 +15,10 @@ export type PromptOrMessages = {
15
15
  interface TextRequestFields<Model extends LanguageModel> extends BaseRequest<Model, NoInfer<LanguageModelProviderOptions<Model>>>, GenerationOptionsFields {
16
16
  readonly id?: string;
17
17
  readonly system?: string | SystemPart | ReadonlyArray<SystemPart>;
18
- /** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */
18
+ /**
19
+ * Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. The same as a
20
+ * `Message.tools({ add: tools })` leading the history.
21
+ */
19
22
  readonly tools?: ReadonlyArray<Tool | ToolEntryInput>;
20
23
  readonly toolChoice?: ToolChoice.Input;
21
24
  readonly cache?: CachePolicy;
package/dist/llm.js CHANGED
@@ -5,6 +5,7 @@ import { InvalidProviderOutputError, InvalidRequestError, mergeGeneration, AIErr
5
5
  import { tool } from "./tool.js";
6
6
  import { runTools } from "./tool-runtime.js";
7
7
  import { addUsage, nextRequest, pendingCalls } from "./loop.js";
8
+ import { foldTools } from "./tool-updates.js";
8
9
  export function generate(input, options) {
9
10
  return prepare(input).pipe(Effect.flatMap(({ request, output }) => LLMClient.generate(request, options).pipe(Effect.flatMap((response) => output === undefined
10
11
  ? Effect.succeed(response)
@@ -15,8 +16,16 @@ export function stream(input, options) {
15
16
  }
16
17
  export function loop(input, options) {
17
18
  const { tools, until, ...rest } = input;
18
- return Stream.unwrap(prepare({ ...rest, tools }).pipe(Effect.map(({ request, output }) => driveLoop({ tools, until, output, options }, request, [], undefined))));
19
+ return Stream.unwrap(prepare({ ...rest, tools }).pipe(
20
+ // Untyped callers may omit `tools`.
21
+ Effect.map(({ request, output }) => driveLoop({ tools: runnableTools(tools ?? [], input.messages ?? []), until, output, options }, request, [], undefined))));
19
22
  }
23
+ // Tools that `Message.tools(...)` adds run like top-level ones; a later change with the same name replaces or removes them.
24
+ const runnableTools = (tools, messages) => messages
25
+ .reduce((current, message) => message.role === "system" && message.tools !== undefined
26
+ ? foldTools(current, message.tools.add ?? [], (message.tools.remove ?? []).map((item) => (typeof item === "string" ? item : item.name)))
27
+ : current, tools)
28
+ .filter((item) => "_definition" in item);
20
29
  export { collect } from "./loop.js";
21
30
  /**
22
31
  * Stream one model call. Its `finish` is held back: `after` gets the completed step and streams what follows it.
@@ -2,7 +2,7 @@ import { type Context, Effect, Layer, Stream } from "effect";
2
2
  import { type AwaitOptions, type Generation, type Observation } from "./generation.js";
3
3
  import { RequestExecutor } from "./route/executor.js";
4
4
  import type { MediaRoute } from "./route/media.js";
5
- import { AIError } from "./schema/index.js";
5
+ import { AIError, type ProviderID } from "./schema/index.js";
6
6
  /** A media request whose model carries the route that executes it. */
7
7
  export interface RoutedRequest<Self extends MediaRoute.MediaRequest, Event, Response> extends MediaRoute.MediaRequest {
8
8
  readonly model: MediaRoute.MediaRequest["model"] & {
@@ -16,16 +16,28 @@ export interface Interface<Req extends RoutedRequest<Req, Event, Response>, Even
16
16
  readonly start: (request: Req) => Effect.Effect<Generation<Response>, AIError>;
17
17
  readonly resume: (model: Req["model"], token: unknown) => Effect.Effect<Generation<Response>, AIError>;
18
18
  }
19
- /** One modality's layer and service accessors, dispatching each request on its route's `kind`. */
20
- export declare const make: <Self, Req extends RoutedRequest<Req, Event, Response>, Event, Response>(service: Context.Service<Self, Interface<Req, Event, Response>>, input: {
19
+ export interface Input<Event, Response> {
21
20
  readonly modality: string;
22
21
  /** A completed response expanded into the streaming event shape. */
23
22
  readonly responseEvents: (response: Response) => ReadonlyArray<Event>;
24
- }) => {
25
- responseEvents: (response: Response) => ReadonlyArray<Event>;
23
+ }
24
+ /** `${modality}.${operation}` on a route that is not queued. */
25
+ export declare const notQueued: (modality: string, route: {
26
+ readonly provider: ProviderID;
27
+ readonly id: string;
28
+ }, operation: string) => AIError;
29
+ /** One modality's operations over an executor, dispatching each request on its route's `kind`. */
30
+ export declare const operations: <Req extends RoutedRequest<Req, Event, Response>, Event, Response>(execute: MediaRoute.Execute, input: Input<Event, Response>) => Interface<Req, Event, Response>;
31
+ /** One modality's layer and service accessors over `operations`. */
32
+ export declare const make: <Self, Req extends RoutedRequest<Req, Event, Response>, Event, Response>(service: Context.Service<Self, Interface<Req, Event, Response>>, input: Input<Event, Response>) => {
33
+ responseEvents: (response: Response) => readonly Event[];
26
34
  layer: Layer.Layer<Self, never, RequestExecutor.RequestExecutorService>;
27
35
  generate: (request: Req, options?: AwaitOptions) => Effect.Effect<Response, AIError, Self>;
28
- stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | Observation, AIError, Exclude<Self, import("effect/Scope").Scope>>;
36
+ stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | {
37
+ readonly type: "generation-progress";
38
+ readonly id: string;
39
+ readonly progress?: number | undefined;
40
+ }, AIError, Exclude<Self, import("effect/Scope").Scope>>;
29
41
  start: (request: Req) => Effect.Effect<Generation<Response>, AIError, Self>;
30
42
  resume: (model: Req["model"], token: unknown) => Effect.Effect<Generation<Response>, AIError, Self>;
31
43
  };
@@ -2,47 +2,52 @@ import { Effect, Layer, Stream } from "effect";
2
2
  import { resultEvents } from "./generation.js";
3
3
  import { RequestExecutor } from "./route/executor.js";
4
4
  import { AIError, UnsupportedOperationError } from "./schema/index.js";
5
- /** One modality's layer and service accessors, dispatching each request on its route's `kind`. */
5
+ /** `${modality}.${operation}` on a route that is not queued. */
6
+ export const notQueued = (modality, route, operation) => new AIError({
7
+ reason: new UnsupportedOperationError({
8
+ operation: `${modality}.${operation}`,
9
+ provider: route.provider,
10
+ route: route.id,
11
+ message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
12
+ }),
13
+ });
14
+ /** One modality's operations over an executor, dispatching each request on its route's `kind`. */
15
+ export const operations = (execute, input) => {
16
+ const start = (request) => {
17
+ const route = request.model.route;
18
+ if (route.kind !== "queued")
19
+ return Effect.fail(notQueued(input.modality, route, "start"));
20
+ return route.start(request, execute);
21
+ };
22
+ return {
23
+ start,
24
+ resume: (model, token) => {
25
+ if (model.route.kind !== "queued")
26
+ return Effect.fail(notQueued(input.modality, model.route, "resume"));
27
+ return model.route.resume(model, token, execute);
28
+ },
29
+ generate: (request, options) => {
30
+ const route = request.model.route;
31
+ if (route.kind !== "queued")
32
+ return route.generate(request, execute);
33
+ return start(request).pipe(Effect.flatMap((generation) => generation.await(options)));
34
+ },
35
+ stream: (request, options) => {
36
+ const route = request.model.route;
37
+ if (route.kind === "stream")
38
+ return route.stream(request, execute);
39
+ if (route.kind === "queued")
40
+ return Stream.unwrap(start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))));
41
+ return Stream.fromIterableEffect(Effect.map(route.generate(request, execute), input.responseEvents));
42
+ },
43
+ };
44
+ };
45
+ /** One modality's layer and service accessors over `operations`. */
6
46
  export const make = (service, input) => ({
7
47
  responseEvents: input.responseEvents,
8
48
  layer: Layer.effect(service, Effect.gen(function* () {
9
49
  const executor = yield* RequestExecutor.Service;
10
- const notQueued = (route, operation) => new AIError({
11
- reason: new UnsupportedOperationError({
12
- operation: `${input.modality}.${operation}`,
13
- provider: route.provider,
14
- route: route.id,
15
- message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
16
- }),
17
- });
18
- const start = (request) => {
19
- const route = request.model.route;
20
- if (route.kind !== "queued")
21
- return Effect.fail(notQueued(route, "start"));
22
- return route.start(request, executor.execute);
23
- };
24
- return service.of({
25
- start,
26
- resume: (model, token) => {
27
- if (model.route.kind !== "queued")
28
- return Effect.fail(notQueued(model.route, "resume"));
29
- return model.route.resume(model, token, executor.execute);
30
- },
31
- generate: (request, options) => {
32
- const route = request.model.route;
33
- if (route.kind !== "queued")
34
- return route.generate(request, executor.execute);
35
- return start(request).pipe(Effect.flatMap((generation) => generation.await(options)));
36
- },
37
- stream: (request, options) => {
38
- const route = request.model.route;
39
- if (route.kind === "stream")
40
- return route.stream(request, executor.execute);
41
- if (route.kind === "queued")
42
- return Stream.unwrap(start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))));
43
- return Stream.fromIterableEffect(Effect.map(route.generate(request, executor.execute), input.responseEvents));
44
- },
45
- });
50
+ return service.of(operations(executor.execute, input));
46
51
  })),
47
52
  generate: (request, options) => service.use((client) => client.generate(request, options)),
48
53
  stream: (request, options) => Stream.unwrap(service.useSync((client) => client.stream(request, options))),
@@ -42,5 +42,7 @@ export declare namespace MediaModel {
42
42
  }
43
43
  /** Compose a protocol route input with one deployment through `MediaRoute.inline`, `queued`, or `stream`. */
44
44
  export declare const composeRoute: <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(route: MediaModel.AnyRouteInput<Request, Event, Response, Frame, State, Token>, input: MediaRoute.ModelInput, collect: (events: ReadonlyArray<Event>) => Effect.Effect<Response, AIError>) => MediaRoute.AnyRoute<Request, Event, Response>;
45
+ /** Compose a queued protocol route input with one deployment through `MediaRoute.queued`. */
46
+ export declare const composeQueuedRoute: <Request extends MediaRoute.MediaRequest, Response, Token>(route: MediaModel.QueuedRouteInput<Request, Response, Token>, input: MediaRoute.ModelInput) => MediaRoute.QueuedRoute<Request, Response>;
45
47
  /** Lift a synchronous Schema-class constructor into a typed `InvalidRequest` failure. */
46
48
  export declare const tryRequest: <A>(make: () => A) => Effect.Effect<A, AIError>;
@@ -27,9 +27,11 @@ export const composeRoute = (route, input, collect) => {
27
27
  if (isStreamInput(route))
28
28
  return MediaRoute.stream({ ...composition(route, input), collect });
29
29
  if (isQueuedInput(route))
30
- return MediaRoute.queued(composition(route, input));
30
+ return composeQueuedRoute(route, input);
31
31
  return MediaRoute.inline(composition(route, input));
32
32
  };
33
+ /** Compose a queued protocol route input with one deployment through `MediaRoute.queued`. */
34
+ export const composeQueuedRoute = (route, input) => MediaRoute.queued(composition(route, input));
33
35
  const composition = (route, input) => ({
34
36
  protocol: route.protocol,
35
37
  endpoint: Endpoint.path(route.path, { baseURL: input.baseURL ?? route.baseURL }),
package/dist/media.d.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  export * as Media from "./media.js";
2
- import { Effect, FileSystem, Schema } from "effect";
2
+ import { Effect, FileSystem, Schema, Stream } from "effect";
3
3
  import { ProviderID } from "./schema/ids.js";
4
4
  import { AIError } from "./schema/errors.js";
5
5
  import { ProviderMetadata } from "./schema/options.js";
6
- import { Service } from "./route/executor-service.js";
6
+ import { type HttpMiddleware, Service } from "./route/executor-service.js";
7
7
  export { detectMediaType } from "./utils/media-type.js";
8
8
  export declare const Source: Schema.Union<readonly [Schema.Struct<{
9
9
  readonly type: Schema.Literal<"bytes">;
@@ -60,11 +60,15 @@ export declare class Asset {
60
60
  readonly providerMetadata?: ProviderMetadata;
61
61
  /** Transient download credentials for `url` sources; see `Asset.Input.headers`. */
62
62
  readonly headers?: Record<string, string>;
63
+ /** Middleware for downloading a `url` source; see `Asset.Input.middleware`. */
64
+ readonly middleware?: HttpMiddleware;
63
65
  constructor(input: Asset.Input);
64
66
  /** Inline payload without effects, for protocols that embed base64 or data URLs directly. */
65
67
  inline(): Inline | undefined;
66
68
  /** Decoded payload; downloads `url` sources through the request executor and caches the result. */
67
69
  bytes(): Effect.Effect<Uint8Array, AIError, Service>;
70
+ /** The payload as a byte stream; `url` sources stream from the network without being buffered or cached. */
71
+ stream(): Stream.Stream<Uint8Array, AIError, Service>;
68
72
  base64(): Effect.Effect<string, AIError, Service>;
69
73
  dataUrl(): Effect.Effect<string, AIError, Service>;
70
74
  /**
@@ -115,11 +119,17 @@ export declare namespace Asset {
115
119
  readonly info?: Info;
116
120
  readonly providerMetadata?: ProviderMetadata;
117
121
  /**
118
- * Headers required to download a `url` source, such as the provider API key Veo demands for its file URIs.
122
+ * Headers required to download a `url` source, such as a provider API key.
119
123
  * They are runtime-only: never part of `source`, `toJSON()`, or `AssetSchema`, so a persisted asset cannot leak
120
124
  * credentials and cannot be downloaded again after a round-trip. Call `materialize()` before persisting.
121
125
  */
122
126
  readonly headers?: Record<string, string>;
127
+ /**
128
+ * Middleware for downloading a `url` source, runtime-only like `headers`. A download never uses the caller's
129
+ * scoped middleware (`RequestExecutor.withMiddleware`), so hooks that add provider credentials can't reach another
130
+ * host. Routes set this to that middleware only for result URLs on the provider's origin.
131
+ */
132
+ readonly middleware?: HttpMiddleware;
123
133
  }
124
134
  }
125
135
  /** JSON form of an asset: the serializable `Source` plus caller-supplied metadata. `bytes` sources encode as base64. */
@@ -188,6 +198,12 @@ export declare const AssetSchema: Schema.decodeTo<Schema.declare<Asset, Asset>,
188
198
  }>>;
189
199
  readonly providerMetadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
190
200
  }>, never, never>;
201
+ /**
202
+ * An image, or a URL or provider file reference whose type it doesn't state, which the provider checks itself. Build one with
203
+ * `Media.image`; an asset known to be a video, audio or document is rejected.
204
+ */
205
+ export declare const ImageAssetSchema: Schema.brand<Schema.declare<Asset, Asset>, "Media.ImageAsset">;
206
+ export type ImageAsset = typeof ImageAssetSchema.Type;
191
207
  export type AssetOptions = Omit<Asset.Input, "source">;
192
208
  export declare const from: (source: Source, options?: AssetOptions) => Asset;
193
209
  export declare const bytes: (data: Uint8Array, mediaType?: string, options?: AssetOptions) => Asset;
@@ -204,6 +220,8 @@ export declare const fromDataUrl: (dataUrl: string, options?: AssetOptions) => A
204
220
  export type Data = Uint8Array | ArrayBuffer | URL | string;
205
221
  /** What file inputs accept: an `Asset` or plain `Data`. */
206
222
  export type Input = Asset | Data;
223
+ /** Normalize input into an `ImageAsset`; throws when it's known not to be an image. */
224
+ export declare const image: (input: Input, mediaType?: string) => ImageAsset;
207
225
  /**
208
226
  * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
209
227
  * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
@@ -211,5 +229,9 @@ export type Input = Asset | Data;
211
229
  export declare const make: (input: Input, mediaType?: string) => Asset;
212
230
  /** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
213
231
  export declare const file: (path: string, options?: AssetOptions) => Effect.Effect<Asset, AIError, FileSystem.FileSystem>;
214
- /** Materialize an asset and write its bytes through `FileSystem`. */
232
+ /**
233
+ * Stream an asset's bytes into a file through `FileSystem` without buffering `url` downloads. The bytes go to a temporary
234
+ * file next to `path` that replaces it only once the download finished, so a failed download leaves an existing file as
235
+ * it was.
236
+ */
215
237
  export declare const write: (asset: Asset, path: string) => Effect.Effect<void, AIError, FileSystem.FileSystem | Service>;