@opencode/ai 0.0.0-dev-21713 → 0.0.0-dev-21717

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.
package/README.md CHANGED
@@ -198,6 +198,15 @@ OpenAI reads `OPENAI_API_KEY` and calls `/v1/decisions`.
198
198
  The common API uses `boolean`; System One routes lower it to native `noul`, and OpenAI lowers it to
199
199
  `predicate`. OpenAI predicates take no criteria, so boolean criteria fail before the request, and a
200
200
  refused question fails the call with a `ContentPolicy` error.
201
+ Cloudflare serves its Clef models through Workers AI and TypeSafe Jev through AI Gateway, both on `/ai/run`:
202
+
203
+ ```ts
204
+ import { CloudflareAIGateway, CloudflareWorkersAI } from "@opencode/ai/providers"
205
+
206
+ CloudflareWorkersAI.configure({ accountId }).experimental.evaluation("@cf/cloudflare/clef")
207
+ CloudflareAIGateway.configure({ accountId }).experimental.evaluation("typesafe/jev")
208
+ ```
209
+
201
210
  Choice and score answers include `confidence` when the provider returns it, such as
202
211
  `response.answers.department.confidence`. Score legends remain available in provider metadata, and
203
212
  the provider's rounded probabilities are returned unchanged.
@@ -274,6 +283,14 @@ Package entrypoints are `@opencode/ai/providers/alibaba`, `alibaba/chat`, `aliba
274
283
  and `alibaba/responses`. Live recordings cover all three APIs in Singapore; regional URL construction
275
284
  is unit-tested for all six regions.
276
285
 
286
+ ### Images
287
+
288
+ `alibaba.image(...)` uses the native multimodal generation API (`/api/v1/services/aigc/multimodal-generation/generation`)
289
+ for Qwen-Image (`qwen-image-2.0`, `qwen-image-2.0-pro`) and Wan (`wan2.7-image`, `wan2.7-image-pro`). `size` lowers to
290
+ `W*H`, and `images` are sent as URLs or data URLs for editing. Native `parameters` include `negativePrompt`,
291
+ `promptExtend`, `watermark`, `thinkingMode`, and `enableSequential`; raw keys such as `bbox_list` or `size: "2K"`
292
+ pass through. Results are URLs that Model Studio keeps for 24 hours. A complete `baseURL` for images includes `/api/v1`.
293
+
277
294
  ## Z.AI
278
295
 
279
296
  `ZAI` uses the standard API. Chat Completions is the default language-model API;
@@ -551,6 +568,7 @@ call rather than being dropped, so check this table before swapping only the `mo
551
568
  | Google (Gemini) | 1 | ✗ | ✓ | ✓ | ✗ | ✓ (no public URLs) | ✗ |
552
569
  | xAI | ✓ | ✗ | ✓ | ✗ | ✗ | ✓ | ✗ |
553
570
  | Z.ai | ✗ | ✓ | ✗ | ✗ | ✗ | ✗ | ✗ |
571
+ | Alibaba | ✓ | ✓ | ✗ | ✓ | ✗ | ✓ | ✗ |
554
572
  | Meta | ✓ | ✓ (hint) | ✗ | ✗ | ✓ | ✓ | ✗ |
555
573
  | Black Forest Labs | 1 | per model | per model | ✓ | ✓ | per model (1–8) | `flux-pro-1.0-fill` |
556
574
  | fal | ✓ | per model | per model | ✓ | ✓ | 1 (several on `/edit`, `/multi`) | ✓ |
@@ -0,0 +1,14 @@
1
+ import { EvaluationModel } from "./evaluation.js";
2
+ import { MediaRoute } from "../route/media.js";
3
+ import type { ProviderID } from "../schema/index.js";
4
+ export interface ModelInput extends MediaRoute.ModelInput {
5
+ /** Also the provider metadata key. */
6
+ readonly provider: ProviderID;
7
+ /** The Run API base, `.../client/v4/accounts/{account}/ai/run`. */
8
+ readonly baseURL: string;
9
+ }
10
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One request body as `input`. */
11
+ export declare const model: (input: ModelInput) => EvaluationModel<import("./evaluation.js").EvaluationOptions>;
12
+ export declare const CloudflareRunEvaluation: {
13
+ readonly model: typeof model;
14
+ };
@@ -0,0 +1,43 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { EvaluationModel } from "./evaluation.js";
3
+ import { SystemOne } from "./system-one.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { MediaProtocol } from "../route/media-protocol.js";
6
+ import { MediaRoute } from "../route/media.js";
7
+ // Workers AI models answer with the System One response; third-party models such as TypeSafe Jev wrap it in a
8
+ // completed run record.
9
+ const Envelope = Schema.Struct({
10
+ result: Schema.Union([
11
+ SystemOne.Response,
12
+ Schema.Struct({ state: Schema.Literal("Completed"), result: SystemOne.Response }),
13
+ ]),
14
+ });
15
+ /** Posts `{ model, input }` to Cloudflare's `/ai/run` with the System One request body as `input`. */
16
+ export const model = (input) => {
17
+ const route = MediaProtocol.identity({
18
+ id: "cloudflare-run-evaluation",
19
+ name: "Cloudflare Run",
20
+ provider: input.provider,
21
+ });
22
+ const decodeEnvelope = route.decodeJson(Envelope);
23
+ const composed = MediaRoute.inline({
24
+ protocol: MediaProtocol.inline(route, {
25
+ body: {
26
+ from: (request) => SystemOne.encodeInput(request).pipe(Effect.map((body) => MediaProtocol.json({ model: request.model.id, input: body }))),
27
+ },
28
+ response: {
29
+ decode: (response) => decodeEnvelope(response).pipe(Effect.map((output) => SystemOne.toResponse("answers" in output.value.result ? output.value.result : output.value.result.result, input.provider))),
30
+ },
31
+ }),
32
+ endpoint: Endpoint.path("", { baseURL: input.baseURL }),
33
+ auth: input.auth,
34
+ headers: input.headers,
35
+ });
36
+ return EvaluationModel.make({
37
+ id: input.id,
38
+ provider: input.provider,
39
+ http: input.http,
40
+ route: { id: composed.id, evaluate: composed.generate },
41
+ });
42
+ };
43
+ export const CloudflareRunEvaluation = { model };
@@ -1,6 +1,32 @@
1
- import { EvaluationModel, type EvaluationOptions } from "./evaluation.js";
1
+ import { Effect, Schema } from "effect";
2
+ import { EvaluationModel, EvaluationResponse, type EvaluationOptions, type EvaluationRequestFor } from "./evaluation.js";
2
3
  import { type Definition as AuthDefinition } from "../route/auth.js";
3
- import { HttpOptions, ModelID } from "../schema/index.js";
4
+ import { AIError, HttpOptions, ModelID } from "../schema/index.js";
5
+ export declare const Response: Schema.Struct<{
6
+ readonly model: Schema.String;
7
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
8
+ readonly type: Schema.Literal<"noul">;
9
+ readonly noul: Schema.Number;
10
+ }>, Schema.Struct<{
11
+ readonly type: Schema.Literal<"choice">;
12
+ readonly choice: Schema.String;
13
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
14
+ readonly confidence: Schema.optional<Schema.Number>;
15
+ }>, Schema.Struct<{
16
+ readonly type: Schema.Literal<"score">;
17
+ readonly score: Schema.Number;
18
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
19
+ readonly legend: Schema.optional<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
20
+ readonly confidence: Schema.optional<Schema.Number>;
21
+ }>]>>;
22
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
23
+ readonly input_tokens: Schema.optional<Schema.Number>;
24
+ readonly output_tokens: Schema.optional<Schema.Number>;
25
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
26
+ readonly id: Schema.optional<Schema.String>;
27
+ readonly provider: Schema.optional<Schema.String>;
28
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
29
+ }>;
4
30
  export interface ModelInput {
5
31
  readonly id: string | ModelID;
6
32
  readonly provider: string;
@@ -10,7 +36,76 @@ export interface ModelInput {
10
36
  readonly headers?: Record<string, string>;
11
37
  readonly http?: HttpOptions;
12
38
  }
39
+ /** The System One request body without `model`, with `boolean` questions lowered to native `noul`. */
40
+ export declare const encodeInput: (req: EvaluationRequestFor) => Effect.Effect<{
41
+ readonly [x: string]: unknown;
42
+ readonly state: string | readonly Schema.Json[] | {
43
+ readonly [x: string]: Schema.Json;
44
+ };
45
+ readonly questions: {
46
+ readonly [x: string]: {
47
+ readonly type: "choice";
48
+ readonly instructions: string | readonly Schema.Json[] | {
49
+ readonly [x: string]: Schema.Json;
50
+ };
51
+ readonly criteria: {
52
+ readonly [x: string]: string | readonly Schema.Json[] | {
53
+ readonly [x: string]: Schema.Json;
54
+ } | null;
55
+ };
56
+ } | {
57
+ readonly type: "score";
58
+ readonly instructions: string | readonly Schema.Json[] | {
59
+ readonly [x: string]: Schema.Json;
60
+ };
61
+ readonly criteria: readonly (string | readonly Schema.Json[] | {
62
+ readonly [x: string]: Schema.Json;
63
+ } | null)[];
64
+ } | {
65
+ readonly type: "noul";
66
+ readonly instructions: string | readonly Schema.Json[] | {
67
+ readonly [x: string]: Schema.Json;
68
+ };
69
+ readonly criteria?: {
70
+ readonly true?: string | readonly Schema.Json[] | {
71
+ readonly [x: string]: Schema.Json;
72
+ } | null | undefined;
73
+ readonly false?: string | readonly Schema.Json[] | {
74
+ readonly [x: string]: Schema.Json;
75
+ } | null | undefined;
76
+ } | undefined;
77
+ };
78
+ };
79
+ }, AIError, never>;
80
+ export declare const toResponse: (data: typeof Response.Type, providerMetadataKey: string) => EvaluationResponse;
13
81
  export declare const model: <Options extends EvaluationOptions = EvaluationOptions>(cfg: ModelInput) => EvaluationModel<Options>;
14
82
  export declare const SystemOne: {
83
+ readonly Response: Schema.Struct<{
84
+ readonly model: Schema.String;
85
+ readonly answers: Schema.$Record<Schema.String, Schema.toTaggedUnion<"type", readonly [Schema.Struct<{
86
+ readonly type: Schema.Literal<"noul">;
87
+ readonly noul: Schema.Number;
88
+ }>, Schema.Struct<{
89
+ readonly type: Schema.Literal<"choice">;
90
+ readonly choice: Schema.String;
91
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
92
+ readonly confidence: Schema.optional<Schema.Number>;
93
+ }>, Schema.Struct<{
94
+ readonly type: Schema.Literal<"score">;
95
+ readonly score: Schema.Number;
96
+ readonly probabilities: Schema.$Record<Schema.String, Schema.Number>;
97
+ readonly legend: Schema.optional<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
98
+ readonly confidence: Schema.optional<Schema.Number>;
99
+ }>]>>;
100
+ readonly usage: Schema.optional<Schema.StructWithRest<Schema.Struct<{
101
+ readonly input_tokens: Schema.optional<Schema.Number>;
102
+ readonly output_tokens: Schema.optional<Schema.Number>;
103
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
104
+ readonly id: Schema.optional<Schema.String>;
105
+ readonly provider: Schema.optional<Schema.String>;
106
+ readonly provider_metadata: Schema.optional<Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>>;
107
+ }>;
108
+ readonly encodeInput: typeof encodeInput;
109
+ readonly toResponse: typeof toResponse;
15
110
  readonly model: typeof model;
16
111
  };
@@ -5,6 +5,7 @@ import { Auth } from "../route/auth.js";
5
5
  import { RequestExecutor } from "../route/executor.js";
6
6
  import { JsonObject, ProviderShared } from "../protocols/shared.js";
7
7
  import { AIError, HttpOptions, InvalidProviderOutputError, InvalidRequestError, ModelID, ProviderMetadata, Usage, mergeJsonRecords, } from "../schema/index.js";
8
+ import { encodeJson } from "../utils/json.js";
8
9
  const Noul = Schema.Struct({
9
10
  type: Schema.Literal("noul"),
10
11
  instructions: EvaluationInput,
@@ -22,8 +23,7 @@ const Question = Schema.Union([
22
23
  })),
23
24
  Noul,
24
25
  ]);
25
- const Request = Schema.StructWithRest(Schema.Struct({
26
- model: Schema.String,
26
+ const Input = Schema.StructWithRest(Schema.Struct({
27
27
  state: EvaluationInput,
28
28
  questions: Schema.Record(Schema.String, Question),
29
29
  }), [JsonObject]);
@@ -47,7 +47,7 @@ const NativeUsage = Schema.StructWithRest(Schema.Struct({
47
47
  input_tokens: Schema.optional(Schema.Number),
48
48
  output_tokens: Schema.optional(Schema.Number),
49
49
  }), [JsonObject]);
50
- const Response = Schema.Struct({
50
+ export const Response = Schema.Struct({
51
51
  model: Schema.String,
52
52
  answers: Schema.Record(Schema.String, Answer),
53
53
  usage: Schema.optional(NativeUsage),
@@ -55,6 +55,61 @@ const Response = Schema.Struct({
55
55
  provider: Schema.optional(Schema.String),
56
56
  provider_metadata: Schema.optional(ProviderMetadata),
57
57
  });
58
+ /** The System One request body without `model`, with `boolean` questions lowered to native `noul`. */
59
+ export const encodeInput = (req) => Schema.encodeUnknownEffect(Input)({
60
+ ...mergeJsonRecords(req.options, req.http?.body),
61
+ state: req.state,
62
+ questions: Object.fromEntries(Object.entries(req.questions).map(([id, x]) => [id, x.type === "boolean" ? { ...x, type: "noul" } : x])),
63
+ }).pipe(Effect.mapError((cause) => new AIError({ reason: new InvalidRequestError({ message: cause.message, cause }) })));
64
+ export const toResponse = (data, providerMetadataKey) => {
65
+ const legend = {};
66
+ const answers = Object.fromEntries(Object.entries(data.answers).map(([id, answer]) => {
67
+ if (answer.type === "noul")
68
+ return [id, { type: "boolean", probability: answer.noul }];
69
+ if (answer.type === "choice") {
70
+ return [
71
+ id,
72
+ {
73
+ type: "choice",
74
+ choice: answer.choice,
75
+ probabilities: answer.probabilities,
76
+ ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
77
+ },
78
+ ];
79
+ }
80
+ if (answer.legend !== undefined)
81
+ legend[id] = answer.legend;
82
+ return [
83
+ id,
84
+ {
85
+ type: "score",
86
+ score: answer.score,
87
+ probabilities: answer.probabilities,
88
+ ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
89
+ },
90
+ ];
91
+ }));
92
+ const meta = {
93
+ ...(data.id === undefined ? {} : { responseId: data.id }),
94
+ ...(data.provider === undefined ? {} : { provider: data.provider }),
95
+ ...data.provider_metadata?.[providerMetadataKey],
96
+ ...(Object.keys(legend).length === 0 ? {} : { legend }),
97
+ };
98
+ return new EvaluationResponse({
99
+ model: ModelID.make(data.model),
100
+ answers,
101
+ usage: data.usage
102
+ ? new Usage({
103
+ inputTokens: data.usage.input_tokens,
104
+ outputTokens: data.usage.output_tokens,
105
+ totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
106
+ providerMetadata: { [providerMetadataKey]: data.usage },
107
+ })
108
+ : undefined,
109
+ rounding: new EvaluationRounding({ probabilityDecimals: 2, scoreDecimals: 2 }),
110
+ providerMetadata: Object.keys(meta).length === 0 ? undefined : { [providerMetadataKey]: meta },
111
+ });
112
+ };
58
113
  export const model = (cfg) => EvaluationModel.make({
59
114
  id: cfg.id,
60
115
  provider: cfg.provider,
@@ -64,12 +119,7 @@ export const model = (cfg) => EvaluationModel.make({
64
119
  evaluate: (req, send) => Effect.gen(function* () {
65
120
  const url = new URL(`${cfg.baseURL.replace(/\/$/, "")}/systemone`);
66
121
  Object.entries(req.http?.query ?? {}).forEach(([key, value]) => url.searchParams.set(key, value));
67
- const body = yield* Schema.encodeUnknownEffect(Schema.fromJsonString(Request))({
68
- ...mergeJsonRecords(req.options, req.http?.body),
69
- model: req.model.id,
70
- state: req.state,
71
- questions: Object.fromEntries(Object.entries(req.questions).map(([id, x]) => [id, x.type === "boolean" ? { ...x, type: "noul" } : x])),
72
- }).pipe(Effect.mapError((cause) => new AIError({ reason: new InvalidRequestError({ message: cause.message, cause }) })));
122
+ const body = encodeJson({ ...(yield* encodeInput(req)), model: req.model.id });
73
123
  const headers = yield* Auth.toEffect(cfg.auth)({
74
124
  request: req,
75
125
  method: "POST",
@@ -82,54 +132,8 @@ export const model = (cfg) => EvaluationModel.make({
82
132
  const fail = (message, cause, body) => new AIError({ reason: new InvalidProviderOutputError({ route: "system-one", message, body, http, cause }) });
83
133
  const text = yield* res.text.pipe(Effect.mapError((cause) => fail("Failed to read the System One response", cause)));
84
134
  const data = yield* Schema.decodeUnknownEffect(Schema.fromJsonString(Response))(text).pipe(Effect.mapError((cause) => fail("System One returned an invalid response", cause, text)));
85
- const legend = {};
86
- const answers = Object.fromEntries(Object.entries(data.answers).map(([id, answer]) => {
87
- if (answer.type === "noul")
88
- return [id, { type: "boolean", probability: answer.noul }];
89
- if (answer.type === "choice") {
90
- return [
91
- id,
92
- {
93
- type: "choice",
94
- choice: answer.choice,
95
- probabilities: answer.probabilities,
96
- ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
97
- },
98
- ];
99
- }
100
- if (answer.legend !== undefined)
101
- legend[id] = answer.legend;
102
- return [
103
- id,
104
- {
105
- type: "score",
106
- score: answer.score,
107
- probabilities: answer.probabilities,
108
- ...(answer.confidence === undefined ? {} : { confidence: answer.confidence }),
109
- },
110
- ];
111
- }));
112
- const meta = {
113
- ...(data.id === undefined ? {} : { responseId: data.id }),
114
- ...(data.provider === undefined ? {} : { provider: data.provider }),
115
- ...data.provider_metadata?.[cfg.providerMetadataKey],
116
- ...(Object.keys(legend).length === 0 ? {} : { legend }),
117
- };
118
- return new EvaluationResponse({
119
- model: ModelID.make(data.model),
120
- answers,
121
- usage: data.usage
122
- ? new Usage({
123
- inputTokens: data.usage.input_tokens,
124
- outputTokens: data.usage.output_tokens,
125
- totalTokens: ProviderShared.totalTokens(data.usage.input_tokens, data.usage.output_tokens, undefined),
126
- providerMetadata: { [cfg.providerMetadataKey]: data.usage },
127
- })
128
- : undefined,
129
- rounding: new EvaluationRounding({ probabilityDecimals: 2, scoreDecimals: 2 }),
130
- providerMetadata: Object.keys(meta).length === 0 ? undefined : { [cfg.providerMetadataKey]: meta },
131
- });
135
+ return toResponse(data, cfg.providerMetadataKey);
132
136
  }),
133
137
  },
134
138
  });
135
- export const SystemOne = { model };
139
+ export const SystemOne = { Response, encodeInput, toResponse, model };
@@ -0,0 +1,19 @@
1
+ import { ImageModel, ImageResponse, type ImageRequestFor } from "../image.js";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ export declare const PATH = "/services/aigc/multimodal-generation/generation";
5
+ /** Provider-native `parameters`. Common fields (`n`, `size`, `seed`, `images`) live on the request. */
6
+ export type AlibabaImageOptions = {
7
+ readonly negativePrompt?: string;
8
+ readonly promptExtend?: boolean;
9
+ readonly watermark?: boolean;
10
+ readonly thinkingMode?: boolean;
11
+ readonly enableSequential?: boolean;
12
+ } & Record<string, unknown>;
13
+ export type Request = ImageRequestFor<AlibabaImageOptions>;
14
+ export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
15
+ export declare const model: (input: MediaRoute.ModelInput) => ImageModel<AlibabaImageOptions>;
16
+ export declare const AlibabaImages: {
17
+ readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
18
+ readonly model: typeof model;
19
+ };
@@ -0,0 +1,76 @@
1
+ import { Duration, Effect, Schema } from "effect";
2
+ import { ImageModel, ImageResponse } from "../image.js";
3
+ import { MediaProtocol } from "../route/media-protocol.js";
4
+ import { MediaRoute } from "../route/media.js";
5
+ import { mergeJsonRecords } from "../schema/index.js";
6
+ import { JsonObject, ProviderShared, lenient } from "./shared.js";
7
+ const route = MediaProtocol.identity({ id: "alibaba-images", name: "Alibaba Images", provider: "alibaba" });
8
+ export const PATH = "/services/aigc/multimodal-generation/generation";
9
+ const OUTPUT_RETENTION = Duration.hours(24);
10
+ // ---------------------------------------------------------------------------
11
+ // 2. Response schema
12
+ // ---------------------------------------------------------------------------
13
+ const AlibabaImageResponse = Schema.Struct({
14
+ output: Schema.Struct({
15
+ choices: Schema.Array(Schema.Struct({
16
+ message: Schema.Struct({
17
+ content: Schema.Array(Schema.Struct({ image: Schema.optional(Schema.String) })),
18
+ }),
19
+ })),
20
+ }),
21
+ usage: lenient(JsonObject),
22
+ request_id: Schema.optional(Schema.String),
23
+ });
24
+ // ---------------------------------------------------------------------------
25
+ // 5. Request body construction
26
+ // ---------------------------------------------------------------------------
27
+ const nativeOptions = (options) => {
28
+ if (!options)
29
+ return undefined;
30
+ const { negativePrompt, promptExtend, thinkingMode, enableSequential, ...native } = options;
31
+ return {
32
+ negative_prompt: negativePrompt,
33
+ prompt_extend: promptExtend,
34
+ thinking_mode: thinkingMode,
35
+ enable_sequential: enableSequential,
36
+ ...native,
37
+ };
38
+ };
39
+ const fromRequest = Effect.fn("AlibabaImages.fromRequest")(function* (request) {
40
+ const images = yield* Effect.forEach(request.images ?? [], (image) => ProviderShared.mediaReference(image, undefined, `${route.name} input`).pipe(Effect.map((item) => ({ image: item.value }))));
41
+ return MediaProtocol.json(mergeJsonRecords({
42
+ model: request.model.id,
43
+ input: { messages: [{ role: "user", content: [...images, { text: request.prompt }] }] },
44
+ parameters: mergeJsonRecords({ size: request.size?.replace("x", "*"), n: request.n, seed: request.seed }, nativeOptions(request.providerOptions)),
45
+ }, request.http?.body) ?? {});
46
+ });
47
+ // ---------------------------------------------------------------------------
48
+ // 6. Response decoding
49
+ // ---------------------------------------------------------------------------
50
+ const decodeDocument = route.decodeJson(AlibabaImageResponse);
51
+ const decodeResponse = Effect.fn("AlibabaImages.decodeResponse")(function* (response) {
52
+ const output = yield* decodeDocument(response);
53
+ const decoded = output.value;
54
+ // Qwen-Image returns every image in one choice; Wan returns one choice per image.
55
+ const urls = decoded.output.choices.flatMap((choice) => choice.message.content.flatMap((item) => (item.image === undefined ? [] : [item.image])));
56
+ if (urls.length === 0)
57
+ return yield* output.invalid(`${route.name} returned no images`);
58
+ // Model Studio bills per image; its token counts are informational, so the raw record stays in provider metadata.
59
+ return new ImageResponse({
60
+ images: yield* Effect.forEach(urls, (url) => MediaProtocol.expiringUrl(url, OUTPUT_RETENTION)),
61
+ providerMetadata: { alibaba: { requestID: decoded.request_id, usage: decoded.usage } },
62
+ });
63
+ });
64
+ // ---------------------------------------------------------------------------
65
+ // 7. Protocol and route
66
+ // ---------------------------------------------------------------------------
67
+ export const protocol = MediaProtocol.inline(route, {
68
+ unsupported: ["mask", "aspectRatio", "format"],
69
+ body: { from: fromRequest },
70
+ response: { decode: decodeResponse },
71
+ });
72
+ export const model = (input) => ImageModel.fromRoute({ protocol, path: PATH }, input);
73
+ export const AlibabaImages = {
74
+ protocol,
75
+ model,
76
+ };
@@ -16,10 +16,9 @@ export type OpenAIImageOptions = {
16
16
  readonly partialImages?: number;
17
17
  } & Record<string, unknown>;
18
18
  export type Request = ImageRequestFor<OpenAIImageOptions>;
19
- /** `generate` reads the whole JSON response as one frame, with the requested format for responses that omit it. */
19
+ /** `generate` reads the whole JSON response as one frame. */
20
20
  type Frame = string | {
21
21
  readonly document: string;
22
- readonly requested: string | undefined;
23
22
  };
24
23
  interface State {
25
24
  readonly completed: number;
@@ -103,12 +103,6 @@ const fromRequest = Effect.fn("OpenAIImages.fromRequest")(function* (request) {
103
103
  // ---------------------------------------------------------------------------
104
104
  // 6. Stream parsing
105
105
  // ---------------------------------------------------------------------------
106
- const requestedFormat = (body) => {
107
- if (body.type === "binary")
108
- return undefined;
109
- const value = body.type === "json" ? body.value.output_format : body.value.get("output_format");
110
- return typeof value === "string" ? value : undefined;
111
- };
112
106
  const usage = (value) => value === undefined
113
107
  ? undefined
114
108
  : {
@@ -149,8 +143,10 @@ const onEvent = Effect.fnUntraced(function* (state, frame) {
149
143
  const onDocument = Effect.fnUntraced(function* (frame) {
150
144
  const invalid = (message, cause) => route.frameError(message, frame.document, cause);
151
145
  const decoded = yield* decodeDocument(frame.document).pipe(Effect.mapError((cause) => invalid(`${route.name} returned an invalid response`, cause)));
152
- const format = decoded.output_format ?? frame.requested ?? "png";
153
- const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.decodedAsset(invalid, `${route.name} result ${index}`, item.b64_json, `image/${format}`, {
146
+ // Compatible hosts may omit `output_format` and ignore the requested one, so the bytes decide unreported types.
147
+ const format = decoded.output_format;
148
+ const mediaType = format === undefined ? undefined : `image/${format}`;
149
+ const images = yield* Effect.forEach(decoded.data, (item, index) => MediaInput.decodedAsset(invalid, `${route.name} result ${index}`, item.b64_json, mediaType, {
154
150
  info: info(format, decoded.size),
155
151
  }));
156
152
  if (images.length === 0)
@@ -191,9 +187,7 @@ export const protocol = MediaProtocol.stream(route, {
191
187
  body: { from: fromRequest },
192
188
  frames: (bytes, context) => context.request.mode === "stream"
193
189
  ? Framing.sse.frame(bytes)
194
- : Framing.document
195
- .frame(bytes)
196
- .pipe(Stream.map((document) => ({ document, requested: requestedFormat(context.body) }))),
190
+ : Framing.document.frame(bytes).pipe(Stream.map((document) => ({ document }))),
197
191
  initial: () => ({ completed: 0 }),
198
192
  step,
199
193
  finish,
@@ -131,7 +131,8 @@ const INVALID_REQUEST_CODES = new Set([
131
131
  ]);
132
132
  // Azure OpenAI reports `content_filter` with `innererror.code` ResponsibleAIPolicyViolation.
133
133
  // OpenRouter tags provider failures with a typed `error_type`; its Responses skin also
134
- // emits `image_content_policy_violation` as the native code.
134
+ // emits `image_content_policy_violation` as the native code. Alibaba Model Studio reports
135
+ // moderation rejections as `DataInspectionFailed`.
135
136
  const CONTENT_POLICY_CODES = new Set([
136
137
  "content_filter",
137
138
  "content_moderation",
@@ -139,6 +140,7 @@ const CONTENT_POLICY_CODES = new Set([
139
140
  "content_policy_violation",
140
141
  "image_content_policy_violation",
141
142
  "refusal",
143
+ "datainspectionfailed",
142
144
  ]);
143
145
  // OpenCode Zen replaces upstream codes outside its allow-list but keeps the original
144
146
  // as a `[code]` label at the start of the rewritten message.
@@ -10,6 +10,7 @@ export type Region = "ap-southeast-1" | "cn-beijing" | "cn-hongkong" | "us-east-
10
10
  export type ChatOptionsInput = AlibabaChat.OptionsInput;
11
11
  export type MessagesOptionsInput = AlibabaMessages.OptionsInput;
12
12
  export type ResponsesOptionsInput = AlibabaResponses.OptionsInput;
13
+ export type { AlibabaImageOptions } from "../protocols/alibaba-images.js";
13
14
  type Location = AtLeastOne<{
14
15
  readonly region: Region;
15
16
  /** Overrides the selected API's complete base URL, including its version prefix. */
@@ -667,6 +668,7 @@ export declare const configure: (input: Config) => {
667
668
  readonly previousResponseId?: string | undefined;
668
669
  readonly conversation?: string | undefined;
669
670
  }, import("../route/client.js").CompactionOperations | undefined>;
671
+ image: (id: string | ModelID) => import("../image.js").ImageModel<import("./alibaba.js").AlibabaImageOptions>;
670
672
  configure: typeof configure;
671
673
  };
672
674
  export declare const provider: {
@@ -1,11 +1,13 @@
1
1
  import { Struct } from "effect";
2
2
  import { AlibabaChat } from "../protocols/alibaba-chat.js";
3
+ import { AlibabaImages } from "../protocols/alibaba-images.js";
3
4
  import { AlibabaMessages } from "../protocols/alibaba-messages.js";
4
5
  import { AlibabaResponses } from "../protocols/alibaba-responses.js";
5
6
  import { AuthOptions } from "../route/auth-options.js";
6
7
  import { Route } from "../route/client.js";
7
8
  import { Endpoint } from "../route/endpoint.js";
8
9
  import { Framing } from "../route/framing.js";
10
+ import { MediaRoute } from "../route/media.js";
9
11
  import { ProviderConfigurationError, ProviderID, ToolDefinition } from "../schema/index.js";
10
12
  export const id = ProviderID.make("alibaba");
11
13
  const hosts = new Map([
@@ -66,7 +68,9 @@ export const configure = (input) => {
66
68
  })
67
69
  .model({ id, compatibility: { requireSignature: false } });
68
70
  const responses = (id) => responsesRoute.with(common).model({ id });
69
- return { id, model: chat, chat, messages, responses, configure };
71
+ const media = MediaRoute.deployment({ ...input, baseURL: baseURL ?? `https://${host}/api/v1` }, opts.auth);
72
+ const image = (id) => AlibabaImages.model({ ...media, id });
73
+ return { id, model: chat, chat, messages, responses, image, configure };
70
74
  };
71
75
  export const provider = { id, configure };
72
76
  export const model = (id, input) => fromSettings(input).chat(id);
@@ -27,6 +27,8 @@ export type Settings = ProviderPackage.Settings & OpenAIProviderOptionsInput & G
27
27
  readonly gatewayApiKey?: string;
28
28
  };
29
29
  export declare const baseURL: (input: GatewayURL) => string;
30
+ /** The Run API (`/ai/run`) next to the OpenAI-compatible `/ai/v1` base. */
31
+ export declare const runBaseURL: (input: GatewayURL) => string;
30
32
  export declare const responsesRoute: import("../route/client.js").Route<{
31
33
  readonly model: string;
32
34
  readonly input: readonly ({
@@ -1235,6 +1237,9 @@ export declare const configure: (input: LanguageModelOptions) => {
1235
1237
  endpoint: import("../route/client.js").CompactOperation;
1236
1238
  trigger: import("../route/client.js").TriggerCompactOperation;
1237
1239
  }>;
1240
+ experimental: {
1241
+ evaluation: (value: string | ModelID) => import("../experimental.js").EvaluationModel<import("../experimental.js").EvaluationOptions>;
1242
+ };
1238
1243
  configure: typeof configure;
1239
1244
  };
1240
1245
  export declare const provider: {
@@ -1,6 +1,8 @@
1
+ import { CloudflareRunEvaluation } from "../experimental/cloudflare-run-evaluation.js";
1
2
  import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../protocols/index.js";
2
3
  import { Auth } from "../route/auth.js";
3
- import { ProviderConfigurationError, ProviderID } from "../schema/index.js";
4
+ import { Endpoint } from "../route/endpoint.js";
5
+ import { HttpOptions, ProviderConfigurationError, ProviderID } from "../schema/index.js";
4
6
  import { encodeJson } from "../utils/json.js";
5
7
  export const id = ProviderID.make("cloudflare-ai-gateway");
6
8
  export const authEnvVars = ["CLOUDFLARE_API_TOKEN", "CF_AIG_TOKEN"];
@@ -9,6 +11,16 @@ export const baseURL = (input) => {
9
11
  return input.baseURL;
10
12
  return `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(requireAccountId(input))}/ai/v1`;
11
13
  };
14
+ /** The Run API (`/ai/run`) next to the OpenAI-compatible `/ai/v1` base. */
15
+ export const runBaseURL = (input) => {
16
+ const url = Endpoint.trimBaseUrl(baseURL(input));
17
+ if (!url.endsWith("/ai/v1"))
18
+ throw new ProviderConfigurationError({
19
+ provider: id,
20
+ message: "CloudflareAIGateway needs accountId or a baseURL ending in /ai/v1 to derive the Run API base",
21
+ });
22
+ return `${url.slice(0, -"/v1".length)}/run`;
23
+ };
12
24
  // Cloudflare's REST API rejects parts of the Anthropic Messages and OpenAI Responses request shapes, such as
13
25
  // system prompt blocks and `minimal` reasoning effort, so these models use the provider-native gateway endpoints.
14
26
  const passthroughURL = (input, provider) => `https://gateway.ai.cloudflare.com/v1/${encodeURIComponent(requireAccountId(input))}/${encodeURIComponent(gatewayId(input))}/${provider}`;
@@ -70,6 +82,14 @@ export const configure = (input) => {
70
82
  const responses = responsesRoute.with(passthrough("openai"));
71
83
  const messages = messagesRoute.with(passthrough("anthropic/v1"));
72
84
  const chat = route.with(rest);
85
+ const evaluation = (value) => CloudflareRunEvaluation.model({
86
+ id: value,
87
+ provider: id,
88
+ auth: rest.auth,
89
+ baseURL: runBaseURL(input),
90
+ headers: rest.headers,
91
+ http: HttpOptions.make(input.http),
92
+ });
73
93
  return {
74
94
  id,
75
95
  model: (value) => {
@@ -83,6 +103,7 @@ export const configure = (input) => {
83
103
  return chat.model({ id: value.slice("workers-ai/".length) });
84
104
  return chat.model({ id: value });
85
105
  },
106
+ experimental: { evaluation },
86
107
  configure,
87
108
  };
88
109
  };
@@ -16,6 +16,8 @@ export type Settings = ProviderPackage.Settings & OpenAIProviderOptionsInput & W
16
16
  readonly apiKey?: string;
17
17
  };
18
18
  export declare const baseURL: (input: WorkersAIURL) => string;
19
+ /** The Run API (`/ai/run`) next to the OpenAI-compatible `/ai/v1` base. */
20
+ export declare const runBaseURL: (input: WorkersAIURL) => string;
19
21
  export declare const route: Route<{
20
22
  readonly model: string;
21
23
  readonly messages: readonly ({
@@ -263,6 +265,9 @@ export declare const routes: Route<{
263
265
  export declare const configure: (input: LanguageModelOptions) => {
264
266
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
265
267
  model: (modelID: string | ModelID) => import("../schema/options.js").LanguageModel<import("./openai-options.js").OpenAIOptionsInput, import("../route/client.js").CompactionOperations | undefined>;
268
+ experimental: {
269
+ evaluation: (modelID: string | ModelID) => import("../experimental.js").EvaluationModel<import("../experimental.js").EvaluationOptions>;
270
+ };
266
271
  configure: typeof configure;
267
272
  };
268
273
  export declare const provider: {
@@ -1,8 +1,9 @@
1
+ import { CloudflareRunEvaluation } from "../experimental/cloudflare-run-evaluation.js";
1
2
  import { OpenAIChat } from "../protocols/openai-chat.js";
2
3
  import { AuthOptions } from "../route/auth-options.js";
3
4
  import { Route } from "../route/client.js";
4
5
  import { Endpoint } from "../route/endpoint.js";
5
- import { ProviderConfigurationError, ProviderID } from "../schema/index.js";
6
+ import { HttpOptions, ProviderConfigurationError, ProviderID } from "../schema/index.js";
6
7
  export const id = ProviderID.make("cloudflare-workers-ai");
7
8
  export const authEnvVars = ["CLOUDFLARE_API_KEY", "CLOUDFLARE_WORKERS_AI_TOKEN", "CLOUDFLARE_API_TOKEN"];
8
9
  export const baseURL = (input) => {
@@ -15,6 +16,16 @@ export const baseURL = (input) => {
15
16
  });
16
17
  return `https://api.cloudflare.com/client/v4/accounts/${encodeURIComponent(input.accountId)}/ai/v1`;
17
18
  };
19
+ /** The Run API (`/ai/run`) next to the OpenAI-compatible `/ai/v1` base. */
20
+ export const runBaseURL = (input) => {
21
+ const url = Endpoint.trimBaseUrl(baseURL(input));
22
+ if (!url.endsWith("/ai/v1"))
23
+ throw new ProviderConfigurationError({
24
+ provider: id,
25
+ message: "CloudflareWorkersAI needs accountId or a baseURL ending in /ai/v1 to derive the Run API base",
26
+ });
27
+ return `${url.slice(0, -"/v1".length)}/run`;
28
+ };
18
29
  export const route = Route.make({
19
30
  id: "cloudflare-workers-ai",
20
31
  provider: id,
@@ -26,14 +37,20 @@ export const route = Route.make({
26
37
  export const routes = [route];
27
38
  export const configure = (input) => {
28
39
  const { accountId: _accountId, apiKey: _apiKey, auth: _auth, baseURL: _baseURL, ...defaults } = input;
29
- const configured = route.with({
30
- ...defaults,
31
- endpoint: { baseURL: baseURL(input) },
32
- auth: AuthOptions.bearer(input, authEnvVars),
40
+ const auth = AuthOptions.bearer(input, authEnvVars);
41
+ const configured = route.with({ ...defaults, endpoint: { baseURL: baseURL(input) }, auth });
42
+ const evaluation = (modelID) => CloudflareRunEvaluation.model({
43
+ id: modelID,
44
+ provider: id,
45
+ auth,
46
+ baseURL: runBaseURL(input),
47
+ headers: input.headers,
48
+ http: HttpOptions.make(input.http),
33
49
  });
34
50
  return {
35
51
  id,
36
52
  model: (modelID) => configured.model({ id: modelID }),
53
+ experimental: { evaluation },
37
54
  configure,
38
55
  };
39
56
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
- "version": "0.0.0-dev-21713",
3
+ "version": "0.0.0-dev-21717",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -35,7 +35,7 @@
35
35
  "devDependencies": {
36
36
  "@clack/prompts": "1.0.0-alpha.1",
37
37
  "@effect/platform-node": "4.0.1",
38
- "@opencode/http-recorder": "0.0.0-dev-21713",
38
+ "@opencode/http-recorder": "0.0.0-dev-21717",
39
39
  "@tsconfig/bun": "1.0.9",
40
40
  "@types/bun": "1.4.3",
41
41
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -45,7 +45,7 @@
45
45
  "@aws-sdk/credential-providers": "3.1057.0",
46
46
  "@smithy/eventstream-codec": "4.2.14",
47
47
  "@smithy/util-utf8": "4.2.2",
48
- "@opencode/schema": "0.0.0-dev-21713",
48
+ "@opencode/schema": "0.0.0-dev-21717",
49
49
  "aws4fetch": "1.0.20",
50
50
  "effect": "4.0.1",
51
51
  "google-auth-library": "10.5.0"