@opencode/ai 0.0.0-dev-1286 → 0.0.0-dev-1288

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 (52) hide show
  1. package/README.md +52 -10
  2. package/dist/effect.d.ts +3 -1
  3. package/dist/image-client.d.ts +52 -59
  4. package/dist/image-client.js +47 -8
  5. package/dist/image.d.ts +27 -7
  6. package/dist/image.js +10 -6
  7. package/dist/index.d.ts +12 -7
  8. package/dist/index.js +12 -7
  9. package/dist/media-client.d.ts +13 -5
  10. package/dist/media-client.js +42 -37
  11. package/dist/media.d.ts +8 -0
  12. package/dist/media.js +14 -0
  13. package/dist/protocols/google-interactions-video.d.ts +38 -0
  14. package/dist/protocols/google-interactions-video.js +187 -0
  15. package/dist/protocols/google-interactions.d.ts +14 -1
  16. package/dist/protocols/google-interactions.js +1 -1
  17. package/dist/protocols/minimax-video.d.ts +45 -0
  18. package/dist/protocols/minimax-video.js +293 -0
  19. package/dist/protocols/openrouter-video.d.ts +4 -9
  20. package/dist/protocols/openrouter-video.js +8 -7
  21. package/dist/protocols/seedance-video.d.ts +4 -9
  22. package/dist/protocols/seedance-video.js +9 -8
  23. package/dist/protocols/utils/responses-compaction.js +1 -1
  24. package/dist/protocols/xai-video.d.ts +4 -9
  25. package/dist/protocols/xai-video.js +8 -7
  26. package/dist/providers/google/videos.d.ts +2 -0
  27. package/dist/providers/google/videos.js +1 -0
  28. package/dist/providers/google.d.ts +5 -0
  29. package/dist/providers/google.js +7 -0
  30. package/dist/providers/minimax/videos.d.ts +3 -0
  31. package/dist/providers/minimax/videos.js +1 -0
  32. package/dist/providers/minimax.d.ts +6 -1
  33. package/dist/providers/minimax.js +10 -1
  34. package/dist/providers/xai/videos.d.ts +2 -0
  35. package/dist/providers/xai/videos.js +1 -0
  36. package/dist/providers/xai.d.ts +4 -3
  37. package/dist/providers/xai.js +5 -1
  38. package/dist/public.d.ts +1 -1
  39. package/dist/route/executor-service.d.ts +6 -0
  40. package/dist/route/executor-service.js +7 -0
  41. package/dist/route/executor.d.ts +7 -1
  42. package/dist/route/executor.js +7 -2
  43. package/dist/route/media-protocol.d.ts +5 -0
  44. package/dist/route/media.js +4 -3
  45. package/dist/route/transport/http.js +1 -1
  46. package/dist/schema/options.d.ts +8 -0
  47. package/dist/schema/options.js +1 -0
  48. package/dist/video-client.d.ts +6 -6
  49. package/dist/video-client.js +13 -11
  50. package/dist/video.d.ts +14 -72
  51. package/dist/video.js +9 -8
  52. package/package.json +19 -3
package/README.md CHANGED
@@ -1031,13 +1031,30 @@ const program = Effect.gen(function* () {
1031
1031
 
1032
1032
  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
1033
 
1034
+ ### Image jobs
1035
+
1036
+ `ai.image.generate` and `ai.image.stream` poll a queued image route for you. To manage the job yourself, use the same
1037
+ calls as video: `start` submits it and returns `{ id }` at once, the provider's job ID as a string you can store and
1038
+ read back from another process, and `status`, `result` and `cancel` take the model and that `id`. `status` is one read;
1039
+ `result` fails with an `InvalidRequest` reason while the job is still running; `cancel` fails with an
1040
+ `UnsupportedOperation` reason when the provider has no cancel endpoint. No shipped image route is queued yet, so on
1041
+ every image model today all four fail with an `UnsupportedOperation` reason before sending anything.
1042
+
1043
+ ```ts
1044
+ const program = Effect.gen(function* () {
1045
+ const job = yield* ai.image.start({ model, prompt: "A lighthouse" })
1046
+ const status = yield* ai.image.status(model, job.id) // { status, progress? }
1047
+ if (status.status === "completed") return yield* ai.image.result(model, job.id)
1048
+ })
1049
+ ```
1050
+
1034
1051
  ## Video generation
1035
1052
 
1036
1053
  Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
1037
1054
  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` and
1040
- `BytePlus` facades.
1055
+ `id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart
1056
+ is the same call as a normal status read. Models come from `.video(...)` selectors on the `XAI`, `OpenRouter`, `Volcengine`,
1057
+ `BytePlus`, `MiniMax` and `Google` facades.
1041
1058
 
1042
1059
  ```ts
1043
1060
  import { Effect } from "effect"
@@ -1057,13 +1074,13 @@ const program = Effect.gen(function* () {
1057
1074
  resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
1058
1075
  sound: false,
1059
1076
  })
1060
- job.token // `{ requestID }` for xAI: store it with the provider and model ID
1077
+ job.id // the provider's job ID: store it with the provider and model ID
1061
1078
 
1062
- const status = yield* ai.video.status(model, job.token)
1079
+ const status = yield* ai.video.status(model, job.id)
1063
1080
  status.status // "queued" | "running" | "completed" | "failed" | "cancelled" | "expired"
1064
1081
  status.progress // 0..1, only when the provider reports it
1065
1082
 
1066
- const response = yield* ai.video.result(model, job.token)
1083
+ const response = yield* ai.video.result(model, job.id)
1067
1084
  yield* Media.write(response.video, "./kitten.mp4") // streams the download to disk
1068
1085
  })
1069
1086
  ```
@@ -1073,6 +1090,10 @@ everything else is provider-specific and goes under `providerOptions`, typed fro
1073
1090
  fails before sending when its protocol has no way to express it, such as a reference video on xAI. Values the provider
1074
1091
  may reject, like an unsupported duration or too many references, go to the provider, and its error comes back typed.
1075
1092
 
1093
+ `start` and `end` are images. They take a URL, data URL, base64 string or bytes, or an asset built with
1094
+ `Media.image(...)`, which rejects assets known to be video, audio or documents; URLs and provider file references
1095
+ whose type isn't stated are sent and checked by the provider. `references` take any kind.
1096
+
1076
1097
  `status` is one read; `result` fails with an `InvalidRequest` reason when the job hasn't finished, and with the
1077
1098
  provider's reason (and terminal document on `reason.body`) when it failed, was cancelled or expired. Moderation
1078
1099
  outcomes (xAI `respect_moderation`) fail with a `ContentPolicy` reason when no video comes back. Status and result reads
@@ -1104,6 +1125,27 @@ Provider notes:
1104
1125
  `omni_reference_task_type`, `return_last_frame` and the rest go into the body as-is. `cancel` sends `DELETE`, which
1105
1126
  only cancels a queued task: Ark refuses it for a running one and deletes the record of a finished one. Video URLs
1106
1127
  expire 24 hours after the task finished.
1128
+ - **MiniMax** (`MiniMax.configure(...).video(id)`, or `@opencode/ai/providers/minimax/videos`) serves two APIs and picks
1129
+ one by model family: Hailuo and `*-01` models use v1, everything else (H3) uses v2. Video builds its `/v1` and `/v2`
1130
+ paths on the API host, so a `baseURL` shared with images or chat (`https://api.minimax.cn/v1`) loses its trailing
1131
+ `/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` /
1132
+ `reference_video` / `reference_audio` roles, MiniMax file refs become `mm_file://` URLs, `aspect: "auto"` becomes
1133
+ `ratio: "adaptive"`, and `resolution` is uppercased (`480P`, `2K`). H3 requires `resolution` and `duration`, plus a
1134
+ `ratio` for text-only prompts; nothing is filled in, so MiniMax rejects a request without them. H3 always has sound,
1135
+ so `sound: false` fails before sending. On Hailuo, `start` and `end` map to `first_frame_image` and
1136
+ `last_frame_image`, image references to `subject_reference`, and the result looks up the file's download URL, which
1137
+ expires after one hour. Hailuo is silent and has no aspect field, so `sound: true`, an explicit `aspect`, and video
1138
+ or audio references fail before sending. Cancel works on H3 (only while queued); Hailuo has no cancel. Native fields
1139
+ such as `extra.prompt_expansion_mode` (H3), `prompt_optimizer` (Hailuo) and `callback_url` go under `providerOptions`.
1140
+ - **Google** (`Google.video("gemini-omni-1.2-flash")`) starts a background Gemini Omni interaction. Omni has no
1141
+ role field for media, so `start`, `end` and `references` go into `input` in that order (images, plus video
1142
+ references), and `generation_config.video_config.task` is set to `image_to_video` for frames only or
1143
+ `reference_to_video` for references only; with both, the prompt decides. `duration` becomes
1144
+ `response_format.duration` (`"3s"`), and `aspect` and `resolution` go to `response_format` as is (resolution
1145
+ lowercased); `aspect: "auto"` leaves the ratio out. It rejects `end` without `start` (a lone image reads as the
1146
+ first frame) and `sound: false` (Omni always generates audio). Videos come back as inline bytes. `cancel` posts to
1147
+ `/interactions/{id}/cancel`. `providerOptions` takes native Interactions fields, such as `previous_interaction_id`
1148
+ to edit or extend a generated video, `generation_config.video_config.task`, `service_tier` and `webhook_config`.
1107
1149
 
1108
1150
  The promise client has the same calls, each accepting `{ signal }`:
1109
1151
 
@@ -1111,8 +1153,8 @@ The promise client has the same calls, each accepting `{ signal }`:
1111
1153
  import { ai } from "@opencode/ai"
1112
1154
 
1113
1155
  const job = await ai.video.start({ model, prompt })
1114
- const status = await ai.video.status(model, job.token)
1115
- if (status.status === "completed") await ai.write((await ai.video.result(model, job.token)).video, "./kite.mp4")
1156
+ const status = await ai.video.status(model, job.id)
1157
+ if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).video, "./kite.mp4")
1116
1158
  ```
1117
1159
 
1118
1160
  ## Public API
@@ -1126,9 +1168,9 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
1126
1168
  - **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
1127
1169
  - **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
1128
1170
  - **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
1129
- - **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model.
1171
+ - **`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).
1130
1172
  - **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
1131
- - **`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.
1173
+ - **`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.
1132
1174
  - **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1133
1175
  - **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
1134
1176
  - **`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.
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,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;
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;
49
44
  } | undefined;
50
- readonly providerMetadata?: {
51
- readonly [x: string]: {
52
- readonly [x: string]: unknown;
53
- };
54
- } | 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;
@@ -95,13 +91,10 @@ export declare const ImageClient: {
95
91
  readonly [x: string]: unknown;
96
92
  };
97
93
  } | 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;
94
+ } | import("./generation.js").Observation, AIError, ImageClientService>;
95
+ readonly start: (request: ImageRequest) => Effect.Effect<ImageJob, AIError, ImageClientService>;
96
+ readonly status: (model: ImageModel, id: string) => Effect.Effect<ImageStatus, AIError, ImageClientService>;
97
+ readonly result: (model: ImageModel, id: string) => Effect.Effect<ImageResponse, AIError, ImageClientService>;
98
+ readonly cancel: (model: ImageModel, id: string) => Effect.Effect<void, AIError, ImageClientService>;
106
99
  };
107
100
  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, 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
  };
package/dist/image.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema, Stream } from "effect";
2
- import { Generation, type AwaitOptions } from "./generation.js";
2
+ import { type AwaitOptions, type Status } from "./generation.js";
3
3
  import { Media } from "./media.js";
4
4
  import { MediaModel } from "./media-model.js";
5
5
  import { MediaRoute } from "./route/media.js";
@@ -9,10 +9,13 @@ export type ImageOptions = MediaModel.Options;
9
9
  export type ImageRoute = MediaRoute.AnyRoute<ImageRequest, ImageEvent, ImageResponse>;
10
10
  export declare class ImageModel<Options extends ImageOptions = ImageOptions> extends MediaModel<ImageRoute, Options> {
11
11
  protected readonly _ImageModel: void;
12
- /** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
12
+ /**
13
+ * The number of type arguments selects the kind: `<Options>` for inline or queued, `<Options, Frame, State>` for
14
+ * stream. A queued route's token is the provider's job ID, so `ImageJob.id` is exactly what `status` and `result` take.
15
+ */
13
16
  static fromRoute<Options extends ImageOptions>(route: MediaModel.InlineRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse>, input: MediaRoute.ModelInput): ImageModel<Options>;
14
17
  static fromRoute<Options extends ImageOptions, Frame, State>(route: MediaModel.StreamRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, Frame, State>, input: MediaRoute.ModelInput): ImageModel<Options>;
15
- static fromRoute<Options extends ImageOptions, Token>(route: MediaModel.QueuedRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse, Token>, input: MediaRoute.ModelInput): ImageModel<Options>;
18
+ static fromRoute<Options extends ImageOptions>(route: MediaModel.QueuedRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse, string>, input: MediaRoute.ModelInput): ImageModel<Options>;
16
19
  }
17
20
  export declare const ImageModelSchema: Schema.declare<ImageModel<{
18
21
  readonly [x: string]: unknown;
@@ -39,6 +42,16 @@ export type ImageRequestInput<Model extends ImageModel = ImageModel> = Omit<Imag
39
42
  readonly images?: ReadonlyArray<Media.Input>;
40
43
  readonly providerOptions?: NoInfer<ImageModelOptions<Model>>;
41
44
  };
45
+ /** A submitted generation on a queued route. Store `id` with the model to read the job later, from any process. */
46
+ export interface ImageJob {
47
+ /** The provider's job ID. */
48
+ readonly id: string;
49
+ }
50
+ export interface ImageStatus {
51
+ readonly status: Status;
52
+ /** 0..1, only when the provider reports progress. */
53
+ readonly progress?: number;
54
+ }
42
55
  declare const ImageResponse_base: Schema.Class<ImageResponse, Schema.Struct<{
43
56
  readonly images: Schema.$Array<Schema.decodeTo<Schema.declare<Media.Asset, Media.Asset>, Schema.Struct<{
44
57
  readonly source: Schema.Union<readonly [Schema.Struct<{
@@ -1301,14 +1314,21 @@ export type ImageEvent = Schema.Schema.Type<typeof imageEventTagged>;
1301
1314
  export declare const request: <const Model extends ImageModel>(input: ImageRequestInput<Model>) => ImageRequest<Model>;
1302
1315
  export declare function generate<const Model extends ImageModel>(input: ImageRequestInput<Model>, options?: AwaitOptions): Effect.Effect<ImageResponse, AIError, Service>;
1303
1316
  export declare function stream<const Model extends ImageModel>(input: ImageRequestInput<Model>, options?: AwaitOptions): Stream.Stream<ImageEvent, AIError, Service>;
1304
- /** Inline and streaming routes fail with `UnsupportedOperation`. */
1305
- export declare function start<const Model extends ImageModel>(input: ImageRequestInput<Model>): Effect.Effect<Generation<ImageResponse>, AIError, Service>;
1306
- export declare const resume: (model: ImageModel, token: unknown) => Effect.Effect<Generation<ImageResponse>, AIError, Service>;
1317
+ /** Submit a generation and return at once; nothing polls. Inline and stream routes fail with `UnsupportedOperation`. */
1318
+ export declare function start<const Model extends ImageModel>(input: ImageRequestInput<Model>): Effect.Effect<ImageJob, AIError, Service>;
1319
+ /** One status read for a job ID. */
1320
+ export declare const status: (model: ImageModel, id: string) => Effect.Effect<ImageStatus, AIError, Service>;
1321
+ /** The finished images; fails while the job is still running, or with the provider's reason when it failed. */
1322
+ export declare const result: (model: ImageModel, id: string) => Effect.Effect<ImageResponse, AIError, Service>;
1323
+ /** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */
1324
+ export declare const cancel: (model: ImageModel, id: string) => Effect.Effect<void, AIError, Service>;
1307
1325
  export declare const Image: {
1308
1326
  readonly request: typeof request;
1309
1327
  readonly generate: typeof generate;
1310
1328
  readonly stream: typeof stream;
1311
1329
  readonly start: typeof start;
1312
- readonly resume: typeof resume;
1330
+ readonly status: typeof status;
1331
+ readonly result: typeof result;
1332
+ readonly cancel: typeof cancel;
1313
1333
  };
1314
1334
  export {};
package/dist/image.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema, Stream } from "effect";
2
- import { Generation, ProgressEvent, QueuedEvent } from "./generation.js";
2
+ import { ProgressEvent, QueuedEvent } from "./generation.js";
3
3
  import { Media } from "./media.js";
4
4
  import { MediaModel, composeRoute, tryRequest } from "./media-model.js";
5
5
  import { MediaRoute } from "./route/media.js";
@@ -29,9 +29,6 @@ const ImageRequestSchema = Schema.Struct({
29
29
  resolution: Schema.optional(Schema.String),
30
30
  providerOptions: Schema.optional(ProviderOptions),
31
31
  });
32
- // ---------------------------------------------------------------------------
33
- // Response and events
34
- // ---------------------------------------------------------------------------
35
32
  export class ImageResponse extends Schema.Class("Image.Response")({
36
33
  images: Schema.Array(Media.AssetSchema),
37
34
  usage: Schema.optional(MediaUsage),
@@ -104,11 +101,18 @@ export function stream(input, options) {
104
101
  export function start(input) {
105
102
  return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.start(request)));
106
103
  }
107
- export const resume = (model, token) => ImageClient.resume(model, token);
104
+ /** One status read for a job ID. */
105
+ export const status = (model, id) => ImageClient.status(model, id);
106
+ /** The finished images; fails while the job is still running, or with the provider's reason when it failed. */
107
+ export const result = (model, id) => ImageClient.result(model, id);
108
+ /** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */
109
+ export const cancel = (model, id) => ImageClient.cancel(model, id);
108
110
  export const Image = {
109
111
  request,
110
112
  generate,
111
113
  stream,
112
114
  start,
113
- resume,
115
+ status,
116
+ result,
117
+ cancel,
114
118
  };
package/dist/index.d.ts CHANGED
@@ -130,8 +130,13 @@ export declare const make: (options?: Options) => {
130
130
  };
131
131
  } | undefined;
132
132
  }>;
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>>;
133
+ /** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */
134
+ start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) => Promise<import("./image.js").ImageJob>;
135
+ /** One status read for a job ID. */
136
+ status: (model: ImageModel, id: string, options?: RunOptions) => Promise<import("./image.js").ImageStatus>;
137
+ /** The finished images; fails while the job is still running. */
138
+ result: (model: ImageModel, id: string, options?: RunOptions) => Promise<import("./image.js").ImageResponse>;
139
+ cancel: (model: ImageModel, id: string, options?: RunOptions) => Promise<void>;
135
140
  };
136
141
  decision: {
137
142
  request: typeof import("./decision.js").request;
@@ -143,13 +148,13 @@ export declare const make: (options?: Options) => {
143
148
  };
144
149
  video: {
145
150
  request: typeof import("./video.js").request;
146
- /** Submit a generation and return its `{ id, token }` at once; nothing polls. */
151
+ /** Submit a generation and return its `{ id }` at once; nothing polls. */
147
152
  start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) => Promise<import("./video.js").VideoJob>;
148
- /** One status read for a stored token. */
149
- status: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<import("./video.js").VideoStatus>;
153
+ /** One status read for a job ID. */
154
+ status: (model: VideoModel, id: string, options?: RunOptions) => Promise<import("./video.js").VideoStatus>;
150
155
  /** The finished videos; fails while the job is still running. */
151
- result: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<import("./video.js").VideoResponse>;
152
- cancel: (model: VideoModel, token: unknown, options?: RunOptions) => Promise<void>;
156
+ result: (model: VideoModel, id: string, options?: RunOptions) => Promise<import("./video.js").VideoResponse>;
157
+ cancel: (model: VideoModel, id: string, options?: RunOptions) => Promise<void>;
153
158
  };
154
159
  /** Experimental: may change without compatibility guarantees. */
155
160
  experimental: {
package/dist/index.js CHANGED
@@ -111,8 +111,13 @@ export const make = (options = {}) => {
111
111
  request: Image.request,
112
112
  generate: (input, options) => run(Image.generate(input, options), options),
113
113
  stream: (input, options) => iterate(Image.stream(input, options), options),
114
- start: (input, options) => run(Image.start(input), options).then(handle),
115
- resume: (model, token, options) => run(Image.resume(model, token), options).then(handle),
114
+ /** Submit a generation on a queued route and return its `{ id }` at once; nothing polls. */
115
+ start: (input, options) => run(Image.start(input), options),
116
+ /** One status read for a job ID. */
117
+ status: (model, id, options) => run(Image.status(model, id), options),
118
+ /** The finished images; fails while the job is still running. */
119
+ result: (model, id, options) => run(Image.result(model, id), options),
120
+ cancel: (model, id, options) => run(Image.cancel(model, id), options),
116
121
  },
117
122
  decision: {
118
123
  request: Decision.request,
@@ -124,13 +129,13 @@ export const make = (options = {}) => {
124
129
  },
125
130
  video: {
126
131
  request: Video.request,
127
- /** Submit a generation and return its `{ id, token }` at once; nothing polls. */
132
+ /** Submit a generation and return its `{ id }` at once; nothing polls. */
128
133
  start: (input, options) => run(Video.start(input), options),
129
- /** One status read for a stored token. */
130
- status: (model, token, options) => run(Video.status(model, token), options),
134
+ /** One status read for a job ID. */
135
+ status: (model, id, options) => run(Video.status(model, id), options),
131
136
  /** The finished videos; fails while the job is still running. */
132
- result: (model, token, options) => run(Video.result(model, token), options),
133
- cancel: (model, token, options) => run(Video.cancel(model, token), options),
137
+ result: (model, id, options) => run(Video.result(model, id), options),
138
+ cancel: (model, id, options) => run(Video.cancel(model, id), options),
134
139
  },
135
140
  /** Experimental: may change without compatibility guarantees. */
136
141
  experimental: {
@@ -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,13 +16,21 @@ 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
36
  stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | Observation, AIError, Exclude<Self, import("effect/Scope").Scope>>;
@@ -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))),