@opencode/ai 2.3.0 → 2.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +65 -18
  2. package/dist/cache-policy.js +4 -2
  3. package/dist/effect.d.ts +3 -1
  4. package/dist/generation.d.ts +10 -10
  5. package/dist/generation.js +8 -14
  6. package/dist/image-client.d.ts +56 -59
  7. package/dist/image-client.js +47 -8
  8. package/dist/image.d.ts +36 -95
  9. package/dist/image.js +11 -14
  10. package/dist/index.d.ts +25 -25
  11. package/dist/index.js +29 -22
  12. package/dist/llm.d.ts +4 -1
  13. package/dist/llm.js +10 -1
  14. package/dist/media-client.d.ts +18 -6
  15. package/dist/media-client.js +42 -37
  16. package/dist/media.d.ts +17 -1
  17. package/dist/media.js +28 -7
  18. package/dist/protocols/alibaba-messages.d.ts +24 -2
  19. package/dist/protocols/alibaba-responses.d.ts +26 -0
  20. package/dist/protocols/anthropic-messages.d.ts +70 -6
  21. package/dist/protocols/anthropic-messages.js +74 -9
  22. package/dist/protocols/assemblyai-transcription.js +7 -6
  23. package/dist/protocols/cartesia-speech.d.ts +0 -8
  24. package/dist/protocols/deepgram-speech.d.ts +0 -8
  25. package/dist/protocols/elevenlabs-speech.d.ts +0 -8
  26. package/dist/protocols/google-interactions-video.d.ts +4 -9
  27. package/dist/protocols/google-interactions-video.js +9 -10
  28. package/dist/protocols/google-speech.d.ts +0 -8
  29. package/dist/protocols/google-transcription.d.ts +0 -8
  30. package/dist/protocols/meta-messages.d.ts +24 -2
  31. package/dist/protocols/meta-responses.d.ts +52 -0
  32. package/dist/protocols/minimax-video.d.ts +6 -15
  33. package/dist/protocols/minimax-video.js +25 -27
  34. package/dist/protocols/open-responses.d.ts +250 -24
  35. package/dist/protocols/open-responses.js +40 -24
  36. package/dist/protocols/openai-chat.js +7 -3
  37. package/dist/protocols/openai-compatible-responses.d.ts +26 -0
  38. package/dist/protocols/openai-freeform.d.ts +1 -1
  39. package/dist/protocols/openai-freeform.js +9 -5
  40. package/dist/protocols/openai-images.d.ts +0 -8
  41. package/dist/protocols/openai-responses.d.ts +153 -0
  42. package/dist/protocols/openai-responses.js +68 -7
  43. package/dist/protocols/openai-speech.d.ts +0 -8
  44. package/dist/protocols/openai-transcription.d.ts +0 -8
  45. package/dist/protocols/openrouter-video.d.ts +4 -9
  46. package/dist/protocols/openrouter-video.js +14 -13
  47. package/dist/protocols/seedance-video.d.ts +4 -9
  48. package/dist/protocols/seedance-video.js +13 -12
  49. package/dist/protocols/utils/gateway-protocol.js +1 -0
  50. package/dist/protocols/utils/responses-compaction.js +7 -3
  51. package/dist/protocols/xai-responses.d.ts +26 -0
  52. package/dist/protocols/xai-video.d.ts +4 -9
  53. package/dist/protocols/xai-video.js +13 -9
  54. package/dist/protocols/zai-messages.d.ts +24 -2
  55. package/dist/providers/alibaba.d.ts +50 -2
  56. package/dist/providers/amazon-bedrock-mantle.d.ts +50 -2
  57. package/dist/providers/anthropic-compatible.d.ts +24 -2
  58. package/dist/providers/anthropic.d.ts +24 -2
  59. package/dist/providers/azure.d.ts +76 -2
  60. package/dist/providers/cloudflare-ai-gateway.d.ts +100 -4
  61. package/dist/providers/digitalocean.d.ts +26 -0
  62. package/dist/providers/google-vertex-messages.d.ts +24 -2
  63. package/dist/providers/google-vertex-messages.js +1 -0
  64. package/dist/providers/google-vertex-responses.d.ts +26 -0
  65. package/dist/providers/google.d.ts +3 -3
  66. package/dist/providers/google.js +5 -2
  67. package/dist/providers/meta.d.ts +50 -2
  68. package/dist/providers/minimax.d.ts +50 -2
  69. package/dist/providers/moonshot.d.ts +50 -2
  70. package/dist/providers/openai-compatible-responses.d.ts +26 -0
  71. package/dist/providers/openai.d.ts +26 -0
  72. package/dist/providers/openrouter.d.ts +26 -0
  73. package/dist/providers/venice.d.ts +26 -0
  74. package/dist/providers/xai/videos.d.ts +2 -0
  75. package/dist/providers/xai/videos.js +1 -0
  76. package/dist/providers/xai.d.ts +4 -3
  77. package/dist/providers/xai.js +5 -1
  78. package/dist/providers/zai-coding-plan.d.ts +50 -2
  79. package/dist/public.d.ts +5 -4
  80. package/dist/public.js +1 -1
  81. package/dist/route/client.d.ts +2 -0
  82. package/dist/route/client.js +5 -1
  83. package/dist/route/executor-service.d.ts +14 -1
  84. package/dist/route/executor-service.js +28 -1
  85. package/dist/route/executor.d.ts +5 -2
  86. package/dist/route/executor.js +20 -5
  87. package/dist/route/media-protocol.d.ts +12 -7
  88. package/dist/route/media-protocol.js +11 -4
  89. package/dist/route/media.js +12 -3
  90. package/dist/route/protocol.d.ts +3 -0
  91. package/dist/schema/events.d.ts +5 -0
  92. package/dist/schema/messages.d.ts +24 -1
  93. package/dist/schema/messages.js +26 -2
  94. package/dist/schema/options.d.ts +10 -2
  95. package/dist/speech-client.d.ts +5 -5
  96. package/dist/speech.d.ts +7 -88
  97. package/dist/speech.js +1 -3
  98. package/dist/tool-updates.d.ts +34 -0
  99. package/dist/tool-updates.js +93 -0
  100. package/dist/tool.d.ts +6 -1
  101. package/dist/tool.js +1 -1
  102. package/dist/transcription-client.d.ts +5 -5
  103. package/dist/transcription.d.ts +7 -88
  104. package/dist/transcription.js +1 -3
  105. package/dist/video-client.d.ts +6 -6
  106. package/dist/video-client.js +13 -11
  107. package/dist/video.d.ts +17 -73
  108. package/dist/video.js +9 -8
  109. package/package.json +7 -3
package/README.md CHANGED
@@ -249,6 +249,29 @@ const logged = RequestExecutor.middleware((request, next) =>
249
249
  const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged })
250
250
  ```
251
251
 
252
+ To hook only some calls, such as adding a per-user header, scope middleware to them. It runs on every provider request
253
+ they make, whatever the modality: submits, polls, results and cancels. Executor-wide middleware wraps it.
254
+
255
+ ```ts
256
+ const signed: HttpMiddleware = (request, next) => next(HttpClientRequest.setHeader(request, "x-user", "user-1"))
257
+
258
+ // Effect: an Effect or a Stream
259
+ const video =
260
+ yield *
261
+ Effect.gen(function* () {
262
+ const job = yield* ai.video.start({ model, prompt: "A red balloon floats up" })
263
+ return yield* ai.video.result(model, job.id)
264
+ }).pipe(RequestExecutor.withMiddleware(signed))
265
+
266
+ // Promise: `http` on any call's options; a handle it returns keeps it
267
+ await AI.ai.video.start({ model, prompt: "A red balloon floats up" }, { http: signed })
268
+ ```
269
+
270
+ Downloading a `url` asset never uses the caller's scoped middleware, so hooks that add credentials can't reach another
271
+ host such as a CDN or a presigned storage URL. A result URL on the provider's own origin carries the middleware of the
272
+ call that returned it (`asset.middleware`), so it downloads the same way later. Set `middleware` yourself with
273
+ `Media.url(url, { middleware })`.
274
+
252
275
  ## Venice AI
253
276
 
254
277
  `Venice` provides native Chat Completions with streaming tools and reasoning. `model` and `chat`
@@ -1031,12 +1054,29 @@ const program = Effect.gen(function* () {
1031
1054
 
1032
1055
  The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes.
1033
1056
 
1057
+ ### Image jobs
1058
+
1059
+ `ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same
1060
+ calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and
1061
+ read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read;
1062
+ `result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an
1063
+ `UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on
1064
+ every image model today all four fail with an `UnsupportedOperation` reason before sending anything.
1065
+
1066
+ ```ts
1067
+ const program = Effect.gen(function* () {
1068
+ const job = yield* ai.image.start({ model, prompt: "A lighthouse" })
1069
+ const status = yield* ai.image.status(model, job.id) // { status, progress? }
1070
+ if (status.status === "completed") return yield* ai.image.result(model, job.id)
1071
+ })
1072
+ ```
1073
+
1034
1074
  ## Video generation
1035
1075
 
1036
1076
  Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
1037
1077
  fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
1038
- `token`, plain JSON you can store and read back from another process, so recovering after a restart is the same call
1039
- as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
1078
+ `id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart
1079
+ is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
1040
1080
  `BytePlus`, `MiniMax` and `Google` facades.
1041
1081
 
1042
1082
  ```ts
@@ -1057,22 +1097,29 @@ const program = Effect.gen(function* () {
1057
1097
  resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
1058
1098
  sound: false,
1059
1099
  })
1060
- job.token // `{ requestID }` for xAI: store it with the provider and model ID
1100
+ job.id // the provider's job ID: store it with the provider and model ID
1061
1101
 
1062
- const status = yield* ai.video.status(model, job.token)
1063
- status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
1102
+ const status = yield* ai.video.status(model, job.id)
1103
+ status.status // "running" | "completed" | "error"
1104
+ status.reason // "failed" | "cancelled" | "expired", only when status is "error"
1064
1105
  status.progress // 0..1, only when the provider reports it
1065
1106
 
1066
- const response = yield* ai.video.result(model, job.token)
1107
+ const response = yield* ai.video.result(model, job.id)
1067
1108
  yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
1068
1109
  })
1069
1110
  ```
1070
1111
 
1071
1112
  The shared fields are `prompt`, `start`, `end`, `references`, `duration`, `aspect`, `resolution` and `sound`;
1072
1113
  everything else is provider-specific and goes under `providerOptions`, typed from the selected model. A request only
1073
- fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider
1114
+ fails before sending when its protocol has no way to express it, such as a reference video on xAI. `sound` is the
1115
+ exception: on models whose sound can't be switched (MiniMax H3 and Gemini Omni always have it, Hailuo never does) it
1116
+ isn't sent, and the model's own behavior applies. Values the provider
1074
1117
  may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
1075
1118
 
1119
+ `start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with
1120
+ `Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references
1121
+ whose type isn't stated are sent and checked by the provider. `references` take any kind.
1122
+
1076
1123
  `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
1077
1124
  provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
1078
1125
  outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
@@ -1110,11 +1157,11 @@ Provider notes:
1110
1157
  `/v1`, and a bare host (`https://api.minimax.io`) works as is. On H3, `start`, `end` and `references` become `content[]` items with `first_frame`, `last_frame` and `reference_image` /
1111
1158
  `reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
1112
1159
  `ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
1113
- `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound,
1114
- so `sound: false` fails before sending. On Hailuo, `start` and `end` map to `first_frame_image` and
1160
+ `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound
1161
+ and has no field for it, so `sound` isn't sent. On Hailuo, `start` and `end` map to `first_frame_image` and
1115
1162
  `last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
1116
- expires after one hour. Hailuo is silent and has no aspect field, so `sound: true`, an explicit `aspect`, and video
1117
- or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
1163
+ expires after one hour. Hailuo is always silent, so `sound` isn't sent; it has no aspect field, so an explicit
1164
+ `aspect` and video or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
1118
1165
  such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
1119
1166
  - **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
1120
1167
  role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
@@ -1122,7 +1169,7 @@ Provider notes:
1122
1169
  `reference_to_video` for references only; with both, the prompt decides. `duration` becomes
1123
1170
  `response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
1124
1171
  lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
1125
- first frame) and `sound: false` (Omni always generates audio). Videos come back as inline bytes. `cancel` posts to
1172
+ first frame). Omni always generates audio and has no field for it, so `sound` isn't sent. Videos come back as inline bytes. `cancel` posts to
1126
1173
  `/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
1127
1174
  to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
1128
1175
 
@@ -1132,8 +1179,8 @@ The promise client has the same calls, each accepting `{ signal }`:
1132
1179
  import { ai } from "@opencode/ai"
1133
1180
 
1134
1181
  const job = await ai.video.start({ model, prompt })
1135
- const status = await ai.video.status(model, job.token)
1136
- if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4")
1182
+ const status = await ai.video.status(model, job.id)
1183
+ if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).video, "./kite.mp4")
1137
1184
  ```
1138
1185
 
1139
1186
  ## Public API
@@ -1147,9 +1194,9 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
1147
1194
  - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
1148
1195
  - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
1149
1196
  - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
1150
- - **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model.
1197
+ - **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs).
1151
1198
  - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
1152
- - **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by a stored token; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer.
1199
+ - **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation). `VideoClient` is its Effect service and layer.
1153
1200
  - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1154
1201
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
1155
1202
  - **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
@@ -1305,8 +1352,8 @@ const program = Effect.gen(function* () {
1305
1352
  })
1306
1353
  ```
1307
1354
 
1308
- Inline routes emit only `finish` from `stream` (no faked deltas); queued routes emit `generation-queued` /
1309
- `generation-progress` before it.
1355
+ Inline routes emit only `finish` from `stream` (no faked deltas); queued routes emit `generation-progress`
1356
+ before it.
1310
1357
 
1311
1358
  Provider notes:
1312
1359
 
@@ -13,6 +13,7 @@
13
13
  import { CacheHint } from "./schema/options.js";
14
14
  import { AssistantMessage, SystemMessage, ToolDefinition, ToolMessage, UserMessage, } from "./schema/messages.js";
15
15
  import { effortUpdate } from "./effort-updates.js";
16
+ import { toolsUpdate } from "./tool-updates.js";
16
17
  const AUTO = {
17
18
  tools: true,
18
19
  system: true,
@@ -151,15 +152,16 @@ const markMessages = (messages, strategy, hint, budget) => {
151
152
  let remaining = strategy.tail;
152
153
  while (remaining > 0 && start > 0) {
153
154
  start -= 1;
154
- if (effortUpdate(messages[start]) === undefined)
155
+ if (!isMarker(messages[start]))
155
156
  remaining -= 1;
156
157
  }
157
158
  let next = messages;
158
159
  for (let i = start; i < messages.length; i++)
159
- if (effortUpdate(messages[i]) === undefined)
160
+ if (!isMarker(messages[i]))
160
161
  next = markMessageAt(next, i, hint, budget);
161
162
  return next;
162
163
  };
164
+ const isMarker = (message) => effortUpdate(message) !== undefined || toolsUpdate(message) !== undefined;
163
165
  const countHints = (request) => countToolHints(request.tools) +
164
166
  request.system.reduce((count, part) => count + (part.cache === undefined ? 0 : 1), 0) +
165
167
  request.messages.reduce((count, message) => count +
package/dist/effect.d.ts CHANGED
@@ -13,7 +13,9 @@ export declare const ai: {
13
13
  readonly generate: typeof import("./image.js").generate;
14
14
  readonly stream: typeof import("./image.js").stream;
15
15
  readonly start: typeof import("./image.js").start;
16
- readonly resume: typeof import("./image.js").resume;
16
+ readonly status: typeof import("./image.js").status;
17
+ readonly result: typeof import("./image.js").result;
18
+ readonly cancel: typeof import("./image.js").cancel;
17
19
  };
18
20
  readonly decision: {
19
21
  readonly request: typeof import("./decision.js").request;
@@ -1,14 +1,18 @@
1
1
  import { Duration, Effect, Schema, Stream } from "effect";
2
2
  import { AIError } from "./schema/errors.js";
3
- export declare const Status: Schema.Literals<readonly ["queued", "running", "completed", "failed", "cancelled", "expired"]>;
3
+ export declare const Status: Schema.Literals<readonly ["running", "completed", "error"]>;
4
4
  export type Status = Schema.Schema.Type<typeof Status>;
5
+ /** Why a generation ended in `error`. */
6
+ export declare const Reason: Schema.Literals<readonly ["failed", "cancelled", "expired"]>;
7
+ export type Reason = Schema.Schema.Type<typeof Reason>;
5
8
  /** Provider-neutral view of one generation observation. */
6
9
  export interface Snapshot {
7
10
  readonly id: string;
8
11
  readonly status: Status;
12
+ /** Set when `status` is `error`. */
13
+ readonly reason?: Reason;
9
14
  /** Normalized 0..1 when the provider reports progress. */
10
15
  readonly progress?: number;
11
- readonly position?: number;
12
16
  }
13
17
  /**
14
18
  * Route-owned generation operations for one generation. The media route decodes its serializable token once (from the
@@ -26,31 +30,27 @@ export interface Poll {
26
30
  export interface AwaitOptions {
27
31
  readonly poll?: Poll;
28
32
  }
29
- export declare const QueuedEvent: Schema.Struct<{
30
- readonly type: Schema.tag<"generation-queued">;
31
- readonly id: Schema.String;
32
- readonly position: Schema.optional<Schema.Number>;
33
- }>;
34
33
  export declare const ProgressEvent: Schema.Struct<{
35
34
  readonly type: Schema.tag<"generation-progress">;
36
35
  readonly id: Schema.String;
37
36
  readonly progress: Schema.optional<Schema.Number>;
38
37
  }>;
39
- export type Observation = Schema.Schema.Type<typeof QueuedEvent> | Schema.Schema.Type<typeof ProgressEvent>;
38
+ export type Observation = Schema.Schema.Type<typeof ProgressEvent>;
40
39
  export type Event = Observation | {
41
40
  readonly type: "generation-finished";
42
41
  readonly id: string;
43
42
  readonly status: Status;
43
+ readonly reason?: Reason;
44
44
  };
45
- export declare const isTerminal: (status: Status) => boolean;
45
+ export declare const isTerminal: (status: Status) => status is "completed" | "error";
46
46
  export declare class Generation<Response> {
47
47
  readonly route: Route<Response>;
48
48
  /** Route-owned serializable JSON; pass it to the modality's `resume` from another process. */
49
49
  readonly token: unknown;
50
50
  readonly id: string;
51
51
  readonly status: Status;
52
+ readonly reason?: Reason;
52
53
  readonly progress?: number;
53
- readonly position?: number;
54
54
  constructor(route: Route<Response>,
55
55
  /** Route-owned serializable JSON; pass it to the modality's `resume` from another process. */
56
56
  token: unknown, snapshot: Snapshot);
@@ -1,27 +1,23 @@
1
1
  import { Clock, Duration, Effect, Schedule, Schema, Stream } from "effect";
2
2
  import { AIError, TimeoutError } from "./schema/errors.js";
3
- export const Status = Schema.Literals(["queued", "running", "completed", "failed", "cancelled", "expired"]);
3
+ export const Status = Schema.Literals(["running", "completed", "error"]);
4
+ /** Why a generation ended in `error`. */
5
+ export const Reason = Schema.Literals(["failed", "cancelled", "expired"]);
4
6
  const DEFAULT_POLL_INTERVAL = Duration.seconds(5);
5
7
  const DEFAULT_POLL_TIMEOUT = Duration.minutes(10);
6
- export const QueuedEvent = Schema.Struct({
7
- type: Schema.tag("generation-queued"),
8
- id: Schema.String,
9
- position: Schema.optional(Schema.Number),
10
- }).annotate({ identifier: "Generation.Event.Queued" });
11
8
  export const ProgressEvent = Schema.Struct({
12
9
  type: Schema.tag("generation-progress"),
13
10
  id: Schema.String,
14
11
  progress: Schema.optional(Schema.Number),
15
12
  }).annotate({ identifier: "Generation.Event.Progress" });
16
- const TERMINAL = new Set(["completed", "failed", "cancelled", "expired"]);
17
- export const isTerminal = (status) => TERMINAL.has(status);
13
+ export const isTerminal = (status) => status !== "running";
18
14
  export class Generation {
19
15
  route;
20
16
  token;
21
17
  id;
22
18
  status;
19
+ reason;
23
20
  progress;
24
- position;
25
21
  constructor(route,
26
22
  /** Route-owned serializable JSON; pass it to the modality's `resume` from another process. */
27
23
  token, snapshot) {
@@ -29,15 +25,15 @@ export class Generation {
29
25
  this.token = token;
30
26
  this.id = snapshot.id;
31
27
  this.status = snapshot.status;
28
+ this.reason = snapshot.reason;
32
29
  this.progress = snapshot.progress;
33
- this.position = snapshot.position;
34
30
  }
35
31
  get snapshot() {
36
32
  return {
37
33
  id: this.id,
38
34
  status: this.status,
35
+ reason: this.reason,
39
36
  progress: this.progress,
40
- position: this.position,
41
37
  };
42
38
  }
43
39
  get terminal() {
@@ -80,9 +76,7 @@ export class Generation {
80
76
  }
81
77
  event() {
82
78
  if (this.terminal)
83
- return { type: "generation-finished", id: this.id, status: this.status };
84
- if (this.status === "queued")
85
- return { type: "generation-queued", id: this.id, position: this.position };
79
+ return { type: "generation-finished", id: this.id, status: this.status, reason: this.reason };
86
80
  return { type: "generation-progress", id: this.id, progress: this.progress };
87
81
  }
88
82
  poll(poll) {
@@ -1,65 +1,61 @@
1
- import { Context } from "effect";
1
+ import { Context, Effect, Layer, Stream } from "effect";
2
+ import type { AwaitOptions } from "./generation.js";
2
3
  import { MediaClient } from "./media-client.js";
3
- import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js";
4
- export type Interface = MediaClient.Interface<ImageRequest, ImageEvent, ImageResponse>;
4
+ import { RequestExecutor } from "./route/executor.js";
5
+ import { AIError } from "./schema/index.js";
6
+ import type { ImageEvent, ImageJob, ImageModel, ImageRequest, ImageResponse, ImageStatus } from "./image.js";
7
+ /** `start`, `status`, `result` and `cancel` fail with `UnsupportedOperation` on inline and stream routes. */
8
+ export interface Interface extends Pick<MediaClient.Interface<ImageRequest, ImageEvent, ImageResponse>, "generate" | "stream"> {
9
+ readonly start: (request: ImageRequest) => Effect.Effect<ImageJob, AIError>;
10
+ readonly status: (model: ImageModel, id: string) => Effect.Effect<ImageStatus, AIError>;
11
+ readonly result: (model: ImageModel, id: string) => Effect.Effect<ImageResponse, AIError>;
12
+ readonly cancel: (model: ImageModel, id: string) => Effect.Effect<void, AIError>;
13
+ }
5
14
  declare const ImageClientService_base: Context.ServiceClass<ImageClientService, "@opencode/ImageClient", Interface>;
6
15
  export declare class ImageClientService extends ImageClientService_base {
7
16
  }
8
17
  export declare const Service: typeof ImageClientService;
9
18
  export type Service = ImageClientService;
10
- export declare const ImageClient: {
11
- readonly responseEvents: (response: ImageResponse) => readonly ({
12
- readonly type: "image-partial";
13
- readonly index: number;
14
- readonly image: import("./media.js").Asset;
19
+ declare const responseEvents: (response: ImageResponse) => ({
20
+ type: "image";
21
+ index: number;
22
+ image: import("./media.js").Asset;
23
+ } | {
24
+ type: "finish";
25
+ usage: {
26
+ readonly type: "seconds";
27
+ readonly seconds: number;
15
28
  } | {
16
- readonly type: "image";
17
- readonly index: number;
18
- readonly image: import("./media.js").Asset;
29
+ readonly type: "characters";
30
+ readonly characters: number;
19
31
  } | {
20
- readonly type: "generation-queued";
21
- readonly id: string;
22
- readonly position?: number | undefined;
32
+ readonly type: "credits";
33
+ readonly credits: number;
23
34
  } | {
24
- readonly type: "generation-progress";
25
- readonly id: string;
26
- readonly progress?: number | undefined;
35
+ readonly type: "compute";
36
+ readonly seconds: number;
27
37
  } | {
28
- readonly type: "finish";
29
- readonly usage?: {
30
- readonly type: "seconds";
31
- readonly seconds: number;
32
- } | {
33
- readonly type: "characters";
34
- readonly characters: number;
35
- } | {
36
- readonly type: "credits";
37
- readonly credits: number;
38
- } | {
39
- readonly type: "compute";
40
- readonly seconds: number;
41
- } | {
42
- readonly type: "tokens";
43
- readonly input?: number | undefined;
44
- readonly output?: number | undefined;
45
- readonly total?: number | undefined;
46
- readonly details?: {
47
- readonly [x: string]: unknown;
48
- } | undefined;
49
- } | undefined;
50
- readonly providerMetadata?: {
51
- readonly [x: string]: {
52
- readonly [x: string]: unknown;
53
- };
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;
54
44
  } | undefined;
55
- })[];
56
- readonly layer: import("effect/Layer").Layer<ImageClientService, never, import("./route.js").RequestExecutorService>;
57
- readonly generate: (request: ImageRequest<import("./image.js").ImageModel<{
58
- readonly [x: string]: unknown;
59
- }>>, options?: import("./generation.js").AwaitOptions) => import("effect/Effect").Effect<ImageResponse, import("./public.js").AIError, ImageClientService>;
60
- readonly stream: (request: ImageRequest<import("./image.js").ImageModel<{
61
- readonly [x: string]: unknown;
62
- }>>, options?: import("./generation.js").AwaitOptions) => import("effect/Stream").Stream<{
45
+ } | undefined;
46
+ providerMetadata: {
47
+ readonly [x: string]: {
48
+ readonly [x: string]: unknown;
49
+ };
50
+ } | undefined;
51
+ })[];
52
+ export declare const layer: Layer.Layer<ImageClientService, never, RequestExecutor.RequestExecutorService>;
53
+ export declare const ImageClient: {
54
+ readonly Service: typeof ImageClientService;
55
+ readonly layer: Layer.Layer<ImageClientService, never, RequestExecutor.RequestExecutorService>;
56
+ readonly responseEvents: typeof responseEvents;
57
+ readonly generate: (request: ImageRequest, options?: AwaitOptions) => Effect.Effect<ImageResponse, AIError, ImageClientService>;
58
+ readonly stream: (request: ImageRequest, options?: AwaitOptions) => Stream.Stream<{
63
59
  readonly type: "image-partial";
64
60
  readonly index: number;
65
61
  readonly image: import("./media.js").Asset;
@@ -67,6 +63,10 @@ export declare const ImageClient: {
67
63
  readonly type: "image";
68
64
  readonly index: number;
69
65
  readonly image: import("./media.js").Asset;
66
+ } | {
67
+ readonly type: "generation-progress";
68
+ readonly id: string;
69
+ readonly progress?: number | undefined;
70
70
  } | {
71
71
  readonly type: "finish";
72
72
  readonly usage?: {
@@ -95,13 +95,10 @@ export declare const ImageClient: {
95
95
  readonly [x: string]: unknown;
96
96
  };
97
97
  } | undefined;
98
- } | import("./generation.js").Observation, import("./public.js").AIError, ImageClientService>;
99
- readonly start: (request: ImageRequest<import("./image.js").ImageModel<{
100
- readonly [x: string]: unknown;
101
- }>>) => import("effect/Effect").Effect<import("./generation.js").Generation<ImageResponse>, import("./public.js").AIError, ImageClientService>;
102
- readonly resume: (model: import("./image.js").ImageModel<{
103
- readonly [x: string]: unknown;
104
- }>, token: unknown) => import("effect/Effect").Effect<import("./generation.js").Generation<ImageResponse>, import("./public.js").AIError, ImageClientService>;
105
- readonly Service: typeof ImageClientService;
98
+ }, AIError, ImageClientService>;
99
+ readonly start: (request: ImageRequest) => Effect.Effect<ImageJob, AIError, ImageClientService>;
100
+ readonly status: (model: ImageModel, id: string) => Effect.Effect<ImageStatus, AIError, ImageClientService>;
101
+ readonly result: (model: ImageModel, id: string) => Effect.Effect<ImageResponse, AIError, ImageClientService>;
102
+ readonly cancel: (model: ImageModel, id: string) => Effect.Effect<void, AIError, ImageClientService>;
106
103
  };
107
104
  export {};
@@ -1,15 +1,54 @@
1
- import { Context } from "effect";
1
+ import { Context, Effect, Layer, Schema, Stream } from "effect";
2
2
  import { MediaClient } from "./media-client.js";
3
+ import { RequestExecutor } from "./route/executor.js";
4
+ import { AIError, UnsupportedOperationError } from "./schema/index.js";
3
5
  export class ImageClientService extends Context.Service()("@opencode/ImageClient") {
4
6
  }
5
7
  export const Service = ImageClientService;
8
+ const responseEvents = (response) => [
9
+ ...response.images.map((image, index) => ({ type: "image", index, image })),
10
+ { type: "finish", usage: response.usage, providerMetadata: response.providerMetadata },
11
+ ];
12
+ // A queued image route whose token isn't a string is a programmer defect, not a provider error.
13
+ const decodeID = (token) => Schema.decodeUnknownEffect(Schema.String)(token).pipe(Effect.orDie);
14
+ export const layer = Layer.effect(Service, Effect.gen(function* () {
15
+ const executor = yield* RequestExecutor.Service;
16
+ const media = MediaClient.operations(executor.execute, {
17
+ modality: "image",
18
+ responseEvents,
19
+ });
20
+ const attach = (model, id, operation) => {
21
+ if (model.route.kind !== "queued")
22
+ return Effect.fail(MediaClient.notQueued("image", model.route, operation));
23
+ return model.route.attach(model, id, executor.execute);
24
+ };
25
+ return Service.of({
26
+ generate: media.generate,
27
+ stream: media.stream,
28
+ start: (request) => media.start(request).pipe(
29
+ // The token, not the snapshot id, is what `status` and `result` decode; `ImageModel.fromRoute` makes it a string.
30
+ Effect.flatMap((generation) => decodeID(generation.token)), Effect.map((id) => ({ id }))),
31
+ status: (model, id) => attach(model, id, "status").pipe(Effect.flatMap((route) => route.status), Effect.map((snapshot) => ({ status: snapshot.status, reason: snapshot.reason, progress: snapshot.progress }))),
32
+ result: (model, id) => attach(model, id, "result").pipe(Effect.flatMap((route) => route.result)),
33
+ cancel: (model, id) => attach(model, id, "cancel").pipe(Effect.flatMap((route) => route.cancel ??
34
+ Effect.fail(new AIError({
35
+ reason: new UnsupportedOperationError({
36
+ operation: "image.cancel",
37
+ provider: model.provider,
38
+ route: model.route.id,
39
+ message: `${model.provider}/${model.route.id} has no way to cancel an image generation`,
40
+ }),
41
+ })))),
42
+ });
43
+ }));
6
44
  export const ImageClient = {
7
45
  Service,
8
- ...MediaClient.make(Service, {
9
- modality: "image",
10
- responseEvents: (response) => [
11
- ...response.images.map((image, index) => ({ type: "image", index, image })),
12
- { type: "finish", usage: response.usage, providerMetadata: response.providerMetadata },
13
- ],
14
- }),
46
+ layer,
47
+ responseEvents,
48
+ generate: (request, options) => Service.use((client) => client.generate(request, options)),
49
+ stream: (request, options) => Stream.unwrap(Service.useSync((client) => client.stream(request, options))),
50
+ start: (request) => Service.use((client) => client.start(request)),
51
+ status: (model, id) => Service.use((client) => client.status(model, id)),
52
+ result: (model, id) => Service.use((client) => client.result(model, id)),
53
+ cancel: (model, id) => Service.use((client) => client.cancel(model, id)),
15
54
  };