@opencode/ai 0.0.0-dev-172 → 0.0.0-dev-177

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 (67) hide show
  1. package/README.md +48 -3
  2. package/dist/effect.d.ts +1 -1
  3. package/dist/effect.js +1 -1
  4. package/dist/index.d.ts +2 -1
  5. package/dist/index.js +1 -0
  6. package/dist/protocols/alibaba-chat.d.ts +39 -4
  7. package/dist/protocols/alibaba-responses.d.ts +20 -3
  8. package/dist/protocols/fal-images.d.ts +2 -0
  9. package/dist/protocols/fal-images.js +1 -0
  10. package/dist/protocols/meta-responses.d.ts +40 -6
  11. package/dist/protocols/meta-responses.js +1 -1
  12. package/dist/protocols/minimax-images.d.ts +25 -0
  13. package/dist/protocols/minimax-images.js +150 -0
  14. package/dist/protocols/open-responses.d.ts +182 -27
  15. package/dist/protocols/open-responses.js +108 -36
  16. package/dist/protocols/openai-chat.d.ts +438 -46
  17. package/dist/protocols/openai-chat.js +121 -39
  18. package/dist/protocols/openai-compatible-chat.d.ts +35 -4
  19. package/dist/protocols/openai-compatible-responses.d.ts +20 -3
  20. package/dist/protocols/openai-freeform.d.ts +47 -0
  21. package/dist/protocols/openai-freeform.js +54 -0
  22. package/dist/protocols/openai-images.js +8 -2
  23. package/dist/protocols/openai-responses.d.ts +120 -18
  24. package/dist/protocols/openai-responses.js +17 -8
  25. package/dist/protocols/venice-chat.d.ts +39 -4
  26. package/dist/protocols/venice-chat.js +1 -1
  27. package/dist/protocols/xai-images.d.ts +1 -0
  28. package/dist/protocols/xai-images.js +2 -4
  29. package/dist/protocols/xai-responses.d.ts +20 -3
  30. package/dist/protocols/xai-responses.js +2 -1
  31. package/dist/protocols/zai-chat.d.ts +39 -4
  32. package/dist/providers/alibaba.d.ts +55 -7
  33. package/dist/providers/amazon-bedrock-mantle.d.ts +55 -7
  34. package/dist/providers/azure.d.ts +75 -10
  35. package/dist/providers/baseten.d.ts +70 -8
  36. package/dist/providers/cerebras.d.ts +70 -8
  37. package/dist/providers/cloudflare-ai-gateway.d.ts +110 -14
  38. package/dist/providers/cloudflare-workers-ai.d.ts +70 -8
  39. package/dist/providers/cohere.d.ts +70 -8
  40. package/dist/providers/deepinfra.d.ts +70 -8
  41. package/dist/providers/deepseek.d.ts +70 -8
  42. package/dist/providers/digitalocean.d.ts +109 -12
  43. package/dist/providers/fireworks.d.ts +70 -8
  44. package/dist/providers/google-vertex-chat.d.ts +35 -4
  45. package/dist/providers/google-vertex-responses.d.ts +20 -3
  46. package/dist/providers/groq.d.ts +74 -8
  47. package/dist/providers/meta.d.ts +55 -7
  48. package/dist/providers/minimax/images.d.ts +3 -0
  49. package/dist/providers/minimax/images.js +1 -0
  50. package/dist/providers/minimax.d.ts +62 -8
  51. package/dist/providers/minimax.js +22 -9
  52. package/dist/providers/moonshot.d.ts +55 -7
  53. package/dist/providers/openai-compatible-responses.d.ts +20 -3
  54. package/dist/providers/openai-compatible.d.ts +35 -4
  55. package/dist/providers/openai-compatible.js +9 -2
  56. package/dist/providers/openai.d.ts +55 -7
  57. package/dist/providers/openrouter.d.ts +144 -16
  58. package/dist/providers/togetherai.d.ts +70 -8
  59. package/dist/providers/venice.d.ts +35 -4
  60. package/dist/providers/xai.d.ts +35 -4
  61. package/dist/providers/zai-coding-plan.d.ts +55 -7
  62. package/dist/providers/zai.d.ts +35 -4
  63. package/dist/schema/messages.d.ts +35 -1
  64. package/dist/schema/messages.js +20 -0
  65. package/dist/tool.d.ts +12 -1
  66. package/dist/tool.js +10 -2
  67. package/package.json +7 -3
package/README.md CHANGED
@@ -81,6 +81,27 @@ for await (const event of events) {
81
81
  }
82
82
  ```
83
83
 
84
+ ### Freeform tools
85
+
86
+ A tool with exactly one required string parameter can set `freeform`, so the model writes that parameter as raw text
87
+ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `lark` grammar.
88
+
89
+ ```ts
90
+ const run_code = AI.tool({
91
+ description: "Run JavaScript",
92
+ parameters: Schema.Struct({ code: Schema.String }),
93
+ freeform: { type: "lark", grammar: JS_GRAMMAR },
94
+ execute: ({ code }) => runCode(code),
95
+ })
96
+ ```
97
+
98
+ OpenAI Responses and Chat Completions, and every provider that reuses them, send it as a
99
+ [custom tool](https://platform.openai.com/docs/guides/function-calling#custom-tools). Other protocols send the normal
100
+ JSON tool. Only set `freeform` for models that accept custom tools in that format; nothing checks this or falls back
101
+ to JSON, so an unsupported model returns the provider's error. Calls, tool input events, results and history always
102
+ use the `{ code }` object, and past calls replay the way the tool is declared in the current request, so the same
103
+ history works with or without `freeform`.
104
+
84
105
  ### Structured output
85
106
 
86
107
  `generateObject` forces a tool call and decodes its input against `schema`; pass `jsonSchema` instead for an
@@ -565,7 +586,9 @@ M2.x models always think, even when a disabling option is supplied. For tool con
565
586
  `response.message` in history before adding `Message.tool(...)` results; this preserves reasoning and any signatures.
566
587
 
567
588
  The default API bases are `https://api.minimax.io/anthropic/v1` for Messages and `https://api.minimax.io/v1` for
568
- Chat and Responses. `configure({ baseURL })` replaces the selected API's base, including its version prefix.
589
+ Chat, Responses and Images. `configure({ baseURL })` replaces the selected API's base, including its version prefix;
590
+ use `https://api.minimax.cn/v1` for the mainland China platform. `minimax.image("image-01")` (also
591
+ `@opencode/ai/providers/minimax/images`) generates images; see [MiniMax images](#minimax-images).
569
592
 
570
593
  ## Meta
571
594
 
@@ -683,6 +706,7 @@ table before swapping only the `model`:
683
706
  | Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
684
707
  | Z.ai | ✗ | width × height | width × height | ✗ | `size` |
685
708
  | Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
709
+ | MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
686
710
  | Black Forest Labs | 1 | per model | width × height models | per model (1–8) | `width`, `height`, `seed`, `output_format`, `mask` |
687
711
  | fal | ✓ | per model | per model | 1 (several on `/edit`, `/multi`) | `image_size`, `seed`, `output_format`, `mask` |
688
712
  | Replicate | ✗ | ✗ | ✗ | ✗ (use `providerOptions`) | everything |
@@ -698,7 +722,8 @@ fixed sizes. `providerOptions.size` replaces `aspect` and `resolution`, so setti
698
722
  forwards `outputFormat` but does not apply it, so the returned bytes keep the upstream model's own format. ² Workers AI
699
723
  `@cf/black-forest-labs/flux-1-schnell` takes no size, and the provider rejects it. ³ Non-OpenAI gateway models
700
724
  (`bfl/flux-2-pro`) get a computed width × height, which the gateway passes through; models with a fixed list, such as
701
- Recraft, reject sizes outside it.
725
+ Recraft, reject sizes outside it. ⁴ MiniMax sends its `aspect_ratio` preset for a preset aspect at about `1K` and an
726
+ exact width × height (512–2048 px, steps of 8) otherwise; `image-01-live` takes only the presets, minus `21:9`.
702
727
 
703
728
  `Media.Asset` is the one asset type shared by image requests, image responses, LLM messages, and tool results.
704
729
  `asset.source` is the serializable `Media.Source` (`bytes`, `base64`, `url`, or `ref`); `asset.bytes()`,
@@ -770,7 +795,7 @@ const xai = Image.generate({
770
795
  aspect: "16:9",
771
796
  resolution: "1K",
772
797
  providerOptions: {
773
- responseFormat: "b64_json",
798
+ responseFormat: "url", // defaults to "b64_json" (inline bytes)
774
799
  future_option: true,
775
800
  },
776
801
  http,
@@ -827,6 +852,26 @@ Z.ai does not include trustworthy MIME metadata for output URLs, so generated im
827
852
  `application/octet-stream` until materialized. Output URLs expire after 30 days; call `asset.materialize()` and
828
853
  persist the bytes promptly if they must remain available.
829
854
 
855
+ ### MiniMax images
856
+
857
+ ```ts
858
+ import { MiniMax } from "@opencode/ai/providers"
859
+
860
+ const minimax = Image.generate({
861
+ model: MiniMax.configure({ apiKey }).image("image-01"),
862
+ prompt,
863
+ n: 2,
864
+ aspect: "16:9",
865
+ images: [Media.url("https://example.com/portrait.jpg")], // optional subject reference
866
+ providerOptions: { promptOptimizer: true, seed: 42 },
867
+ })
868
+ ```
869
+
870
+ The reference image is sent as a `character` subject, so it should be a single front-facing portrait. Images come
871
+ back inline (`responseFormat: "base64"` by default); `responseFormat: "url"` returns links that expire after 24 hours
872
+ and carry no MIME type until materialized. MiniMax status codes map to typed errors; code 1026 is a `ContentPolicy`
873
+ error.
874
+
830
875
  ### Partial images
831
876
 
832
877
  OpenAI's GPT image models stream previews. `Image.stream` sends `stream: true` with `partialImages` (0–3, default 2)
package/dist/effect.d.ts CHANGED
@@ -5,7 +5,7 @@ export { Auth } from "./route/auth.js";
5
5
  export { ProviderPackage } from "./provider-package.js";
6
6
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
7
7
  export type { Interface as LLMClientShape, LLMClientService } from "./route/client.js";
8
- export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
8
+ export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, Freeform, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
9
9
  export type { GenerationOptionsFields, GenerationOptionsInput, LanguageModelInput, LanguageModelProviderOptions, ToolDefinitionInput, ToolNamespaceInput, ToolNamespaceEntryInput, ToolEntryInput, UsageInput, } from "./schema/index.js";
10
10
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
11
11
  export type { ImageModelOptions, ImageOptions, ImageRequestFor, ImageRequestInput, ImageResolution, ImageRoute, } from "./image.js";
package/dist/effect.js CHANGED
@@ -4,7 +4,7 @@ export { ImageClient } from "./image-client.js";
4
4
  export { Auth } from "./route/auth.js";
5
5
  export { ProviderPackage } from "./provider-package.js";
6
6
  export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
7
- export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
7
+ export { ProtocolID, RouteID, ModelID, ProviderID, ResponseID, ContentBlockID, ToolCallID, JsonSchema, ProviderOptions, ProviderMetadata, HttpTimeout, RequestEncoding, HttpOptions, GenerationOptions, LanguageModelDefaults, ReasoningEfforts, ReasoningEffort, LanguageModelCompatibility, LanguageModel, LanguageModelSchema, CacheTTL, CacheHint, CachePolicyObject, CachePolicy, MessageRole, SystemPart, TextPart, MediaPart, ToolResultValue, ToolOutput, ToolCallPart, ToolResultPart, ReasoningPart, CompactionPart, EffortPart, ContentPart, Message, Freeform, ToolDefinition, ToolNamespace, ToolEntry, ToolChoice, LLMRequest, FinishReason, Usage, MediaUsage, CompactionResponse, CompactionCheckpointResponse, StepStart, TextStart, TextDelta, TextEnd, ReasoningStart, ReasoningDelta, ReasoningEnd, ToolInputStart, ToolInputDelta, ToolInputEnd, ToolInputError, ToolCall, ToolResult, ToolError, FinishReasonDetails, StepFinish, Finish, MediaEvent, ProviderErrorEvent, LLMEvent, LLMResponse, HttpContext, HttpRateLimitDetails, InvalidRequestError, UnsupportedOperationError, ProviderConfigurationError, NoRouteError, AuthenticationError, RateLimitError, QuotaExceededError, ContentPolicyError, ProviderInternalError, TransportType, TransportOperation, TransportError, InvalidProviderOutputError, UnknownProviderError, TimeoutError, AIErrorReason, AIError, } from "./schema/index.js";
8
8
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse } from "./image.js";
9
9
  export { Image } from "./image.js";
10
10
  export { VideoClient } from "./video-client.js";
package/dist/index.d.ts CHANGED
@@ -10,7 +10,7 @@ import { LanguageModel, type LLMRequest } from "./schema/index.js";
10
10
  import type { GenerateObjectDynamicOptions, GenerateObjectOptions, GenerateObjectResponse, LoopInput, RequestInput } from "./llm.js";
11
11
  import { type SpeechModel, type SpeechRequest, type SpeechRequestInput } from "./speech.js";
12
12
  import { type TranscriptionModel, type TranscriptionRequest, type TranscriptionRequestInput } from "./transcription.js";
13
- import { Tool, type ToolExecuteContext, type ToolSchema } from "./tool.js";
13
+ import { Tool, type FreeformOption, type ToolExecuteContext, type ToolSchema } from "./tool.js";
14
14
  import { type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js";
15
15
  /**
16
16
  * Promise-first entrypoint for scripts and non-Effect callers. One `ManagedRuntime` hosts the LLM, image, video, speech,
@@ -733,6 +733,7 @@ export type Client = ReturnType<typeof make>;
733
733
  export declare const tool: <Parameters extends ToolSchema<any>>(config: {
734
734
  readonly description: string;
735
735
  readonly parameters: Parameters;
736
+ readonly freeform?: FreeformOption<Parameters>;
736
737
  readonly execute: (params: Schema.Schema.Type<Parameters>, context: Partial<ToolExecuteContext> & {
737
738
  readonly signal: AbortSignal;
738
739
  }) => unknown;
package/dist/index.js CHANGED
@@ -117,6 +117,7 @@ export const tool = (config) => Tool.make({
117
117
  description: config.description,
118
118
  parameters: config.parameters,
119
119
  success: Schema.Unknown,
120
+ freeform: config.freeform,
120
121
  execute: (params, context) => Effect.tryPromise({
121
122
  try: async (signal) => (await config.execute(params, { ...context, signal })) ?? null,
122
123
  catch: (error) => new ToolFailure({ message: error instanceof Error ? error.message : String(error), error }),
@@ -109,7 +109,14 @@ export declare const protocol: Protocol<{
109
109
  readonly ttl?: string | undefined;
110
110
  } | undefined;
111
111
  }[] | null;
112
- readonly tool_calls?: readonly {
112
+ readonly tool_calls?: readonly ({
113
+ readonly id: string;
114
+ readonly type: "custom";
115
+ readonly custom: {
116
+ readonly name: string;
117
+ readonly input: string;
118
+ };
119
+ } | {
113
120
  readonly id: string;
114
121
  readonly type: "function";
115
122
  readonly function: {
@@ -121,13 +128,13 @@ export declare const protocol: Protocol<{
121
128
  readonly thought_signature: string;
122
129
  };
123
130
  } | undefined;
124
- }[] | undefined;
131
+ })[] | undefined;
125
132
  readonly reasoning_content?: string | undefined;
126
133
  readonly reasoning?: string | undefined;
127
134
  readonly reasoning_text?: string | undefined;
128
135
  readonly reasoning_details?: unknown;
129
136
  })[];
130
- readonly tools?: readonly {
137
+ readonly tools?: readonly ({
131
138
  readonly type: "function";
132
139
  readonly function: {
133
140
  readonly name: string;
@@ -141,12 +148,36 @@ export declare const protocol: Protocol<{
141
148
  readonly type: "ephemeral";
142
149
  readonly ttl?: string | undefined;
143
150
  } | undefined;
144
- }[] | undefined;
151
+ } | {
152
+ readonly type: "custom";
153
+ readonly custom: {
154
+ readonly name: string;
155
+ readonly description: string;
156
+ readonly format: {
157
+ readonly type: "text";
158
+ } | {
159
+ readonly type: "grammar";
160
+ readonly grammar: {
161
+ readonly syntax: "lark" | "regex";
162
+ readonly definition: string;
163
+ };
164
+ };
165
+ };
166
+ readonly cache_control?: {
167
+ readonly type: "ephemeral";
168
+ readonly ttl?: string | undefined;
169
+ } | undefined;
170
+ })[] | undefined;
145
171
  readonly tool_choice?: "auto" | "none" | "required" | {
146
172
  readonly type: "function";
147
173
  readonly function: {
148
174
  readonly name: string;
149
175
  };
176
+ } | {
177
+ readonly type: "custom";
178
+ readonly custom: {
179
+ readonly name: string;
180
+ };
150
181
  } | undefined;
151
182
  readonly stream: true;
152
183
  readonly stream_options?: {
@@ -215,6 +246,10 @@ export declare const protocol: Protocol<{
215
246
  readonly name?: string | null | undefined;
216
247
  readonly arguments?: string | null | undefined;
217
248
  } | null | undefined;
249
+ readonly custom?: {
250
+ readonly name?: string | null | undefined;
251
+ readonly input?: string | null | undefined;
252
+ } | null | undefined;
218
253
  readonly extra_content?: unknown;
219
254
  }[] | null | undefined;
220
255
  } | null | undefined;
@@ -26,7 +26,7 @@ export declare const protocol: Protocol<{
26
26
  readonly role: "developer";
27
27
  readonly content: string;
28
28
  } | {
29
- readonly type: "function_call_output";
29
+ readonly type: "custom_tool_call_output" | "function_call_output";
30
30
  readonly call_id: string;
31
31
  readonly output: string | readonly ({
32
32
  readonly type: "input_text";
@@ -96,6 +96,12 @@ export declare const protocol: Protocol<{
96
96
  readonly name: string;
97
97
  readonly namespace?: string | undefined;
98
98
  readonly arguments: string;
99
+ } | {
100
+ readonly type: "custom_tool_call";
101
+ readonly id?: string | undefined;
102
+ readonly call_id: string;
103
+ readonly name: string;
104
+ readonly input: string;
99
105
  } | {
100
106
  readonly [x: string]: unknown;
101
107
  readonly type: "web_search_call";
@@ -140,6 +146,17 @@ export declare const protocol: Protocol<{
140
146
  })[];
141
147
  readonly instructions?: string | undefined;
142
148
  readonly tools?: readonly ({
149
+ readonly type: "custom";
150
+ readonly name: string;
151
+ readonly description: string;
152
+ readonly format: {
153
+ readonly type: "text";
154
+ } | {
155
+ readonly type: "grammar";
156
+ readonly syntax: "lark" | "regex";
157
+ readonly definition: string;
158
+ };
159
+ } | {
143
160
  readonly type: "function";
144
161
  readonly name: string;
145
162
  readonly description: string;
@@ -152,13 +169,13 @@ export declare const protocol: Protocol<{
152
169
  readonly type: string;
153
170
  })[] | undefined;
154
171
  readonly tool_choice?: "auto" | "none" | "required" | {
155
- readonly type: "function";
172
+ readonly type: "custom" | "function";
156
173
  readonly name: string;
157
174
  } | {
158
175
  readonly type: "allowed_tools";
159
176
  readonly mode: "auto" | "none" | "required";
160
177
  readonly tools: readonly {
161
- readonly type: "function";
178
+ readonly type: "custom" | "function";
162
179
  readonly name: string;
163
180
  }[];
164
181
  } | undefined;
@@ -14,6 +14,8 @@ export type FalImageOptions = {
14
14
  /** Inpainting mask, sent as `mask_url`. */
15
15
  readonly mask?: Media.Asset;
16
16
  readonly enable_safety_checker?: boolean;
17
+ /** Defaults to `true`, which returns images inline as data URIs; `false` returns hosted URLs. */
18
+ readonly sync_mode?: boolean;
17
19
  } & Record<string, unknown>;
18
20
  export type Request = ImageRequestFor<FalImageOptions>;
19
21
  export declare const protocol: MediaProtocol.Queued<Request, ImageResponse, {
@@ -60,6 +60,7 @@ const fromRequest = Effect.fn("FalImages.fromRequest")(function* (request) {
60
60
  image_urls: list && images.length > 0 ? images : undefined,
61
61
  image_url: list ? undefined : images[0],
62
62
  mask_url: mask === undefined ? undefined : yield* FalQueue.mediaUrl(mask, route.name),
63
+ sync_mode: true,
63
64
  }, native, request.http?.body) ?? {});
64
65
  });
65
66
  // ---------------------------------------------------------------------------
@@ -40,7 +40,7 @@ export declare const protocol: Protocol<{
40
40
  readonly role: "developer";
41
41
  readonly content: string;
42
42
  } | {
43
- readonly type: "function_call_output";
43
+ readonly type: "custom_tool_call_output" | "function_call_output";
44
44
  readonly call_id: string;
45
45
  readonly output: string | readonly ({
46
46
  readonly type: "input_text";
@@ -110,6 +110,12 @@ export declare const protocol: Protocol<{
110
110
  readonly name: string;
111
111
  readonly namespace?: string | undefined;
112
112
  readonly arguments: string;
113
+ } | {
114
+ readonly type: "custom_tool_call";
115
+ readonly id?: string | undefined;
116
+ readonly call_id: string;
117
+ readonly name: string;
118
+ readonly input: string;
113
119
  } | {
114
120
  readonly [x: string]: unknown;
115
121
  readonly type: "web_search_call";
@@ -154,6 +160,17 @@ export declare const protocol: Protocol<{
154
160
  })[];
155
161
  readonly instructions?: string | undefined;
156
162
  readonly tools?: readonly ({
163
+ readonly type: "custom";
164
+ readonly name: string;
165
+ readonly description: string;
166
+ readonly format: {
167
+ readonly type: "text";
168
+ } | {
169
+ readonly type: "grammar";
170
+ readonly syntax: "lark" | "regex";
171
+ readonly definition: string;
172
+ };
173
+ } | {
157
174
  readonly type: "function";
158
175
  readonly name: string;
159
176
  readonly description: string;
@@ -166,13 +183,13 @@ export declare const protocol: Protocol<{
166
183
  readonly type: string;
167
184
  })[] | undefined;
168
185
  readonly tool_choice?: "auto" | "none" | "required" | {
169
- readonly type: "function";
186
+ readonly type: "custom" | "function";
170
187
  readonly name: string;
171
188
  } | {
172
189
  readonly type: "allowed_tools";
173
190
  readonly mode: "auto" | "none" | "required";
174
191
  readonly tools: readonly {
175
- readonly type: "function";
192
+ readonly type: "custom" | "function";
176
193
  readonly name: string;
177
194
  }[];
178
195
  } | undefined;
@@ -279,7 +296,7 @@ export declare const httpTransport: import("../route/transport/http.js").HttpJso
279
296
  readonly role: "developer";
280
297
  readonly content: string;
281
298
  } | {
282
- readonly type: "function_call_output";
299
+ readonly type: "custom_tool_call_output" | "function_call_output";
283
300
  readonly call_id: string;
284
301
  readonly output: string | readonly ({
285
302
  readonly type: "input_text";
@@ -349,6 +366,12 @@ export declare const httpTransport: import("../route/transport/http.js").HttpJso
349
366
  readonly name: string;
350
367
  readonly namespace?: string | undefined;
351
368
  readonly arguments: string;
369
+ } | {
370
+ readonly type: "custom_tool_call";
371
+ readonly id?: string | undefined;
372
+ readonly call_id: string;
373
+ readonly name: string;
374
+ readonly input: string;
352
375
  } | {
353
376
  readonly [x: string]: unknown;
354
377
  readonly type: "web_search_call";
@@ -393,6 +416,17 @@ export declare const httpTransport: import("../route/transport/http.js").HttpJso
393
416
  })[];
394
417
  readonly instructions?: string | undefined;
395
418
  readonly tools?: readonly ({
419
+ readonly type: "custom";
420
+ readonly name: string;
421
+ readonly description: string;
422
+ readonly format: {
423
+ readonly type: "text";
424
+ } | {
425
+ readonly type: "grammar";
426
+ readonly syntax: "lark" | "regex";
427
+ readonly definition: string;
428
+ };
429
+ } | {
396
430
  readonly type: "function";
397
431
  readonly name: string;
398
432
  readonly description: string;
@@ -405,13 +439,13 @@ export declare const httpTransport: import("../route/transport/http.js").HttpJso
405
439
  readonly type: string;
406
440
  })[] | undefined;
407
441
  readonly tool_choice?: "auto" | "none" | "required" | {
408
- readonly type: "function";
442
+ readonly type: "custom" | "function";
409
443
  readonly name: string;
410
444
  } | {
411
445
  readonly type: "allowed_tools";
412
446
  readonly mode: "auto" | "none" | "required";
413
447
  readonly tools: readonly {
414
- readonly type: "function";
448
+ readonly type: "custom" | "function";
415
449
  readonly name: string;
416
450
  }[];
417
451
  } | undefined;
@@ -97,7 +97,7 @@ const fromRequest = Effect.fn("MetaResponses.fromRequest")(function* (request) {
97
97
  return { ...body, input };
98
98
  });
99
99
  // Hosted replay items have an open `type`, so a plain tag check does not narrow the union.
100
- const isFunctionCallOutput = (item) => item.type === "function_call_output";
100
+ const isFunctionCallOutput = (item) => item.type === "function_call_output" || item.type === "custom_tool_call_output";
101
101
  const HOSTED_TOOLS = {
102
102
  web_search_call: { name: "web_search", input: (item) => item.action ?? {} },
103
103
  image_generation_call: {
@@ -0,0 +1,25 @@
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
+ import { type OpenString } from "../schema/index.js";
5
+ export declare const DEFAULT_BASE_URL = "https://api.minimax.io/v1";
6
+ export declare const PATH = "/image_generation";
7
+ /** Provider-native options. Common `aspect` and `resolution` lower to `aspect_ratio` or `width` and `height`. */
8
+ export type MiniMaxImageOptions = {
9
+ /** Defaults to `base64`, which returns the bytes inline; `url` links expire after 24 hours. */
10
+ readonly responseFormat?: OpenString<"url" | "base64">;
11
+ readonly seed?: number;
12
+ readonly promptOptimizer?: boolean;
13
+ /** Native preset; it replaces `aspect` and `resolution`. */
14
+ readonly aspect_ratio?: string;
15
+ /** Native size, 512 to 2048 in steps of 8 (`image-01` only); it replaces `aspect` and `resolution`. */
16
+ readonly width?: number;
17
+ readonly height?: number;
18
+ } & Record<string, unknown>;
19
+ export type Request = ImageRequestFor<MiniMaxImageOptions>;
20
+ export declare const protocol: MediaProtocol.Inline<Request, ImageResponse>;
21
+ export declare const model: (input: MediaRoute.ModelInput) => ImageModel<MiniMaxImageOptions>;
22
+ export declare const MiniMaxImages: {
23
+ readonly protocol: MediaProtocol.Inline<Request, ImageResponse>;
24
+ readonly model: typeof model;
25
+ };
@@ -0,0 +1,150 @@
1
+ import { Duration, Effect, Schema } from "effect";
2
+ import { ImageModel, ImageResponse } from "../image.js";
3
+ import { Media } from "../media.js";
4
+ import { MediaProtocol } from "../route/media-protocol.js";
5
+ import { MediaRoute } from "../route/media.js";
6
+ import { AIError, QuotaExceededError, mergeJsonRecords } from "../schema/index.js";
7
+ import { ProviderShared, optionalNull } from "./shared.js";
8
+ import { ImageSizing } from "./utils/image-sizing.js";
9
+ import { MediaInput } from "./utils/media-input.js";
10
+ const route = MediaProtocol.identity({ id: "minimax-images", name: "MiniMax Images", provider: "minimax" });
11
+ export const DEFAULT_BASE_URL = "https://api.minimax.io/v1";
12
+ export const PATH = "/image_generation";
13
+ const OUTPUT_RETENTION = Duration.hours(24);
14
+ // ---------------------------------------------------------------------------
15
+ // 2. Response schema
16
+ // ---------------------------------------------------------------------------
17
+ const MiniMaxImageResponse = Schema.Struct({
18
+ id: optionalNull(Schema.String),
19
+ data: optionalNull(Schema.Struct({
20
+ image_urls: optionalNull(Schema.Array(Schema.String)),
21
+ image_base64: optionalNull(Schema.Array(Schema.String)),
22
+ })),
23
+ metadata: optionalNull(Schema.Struct({
24
+ success_count: optionalNull(Schema.Union([Schema.Number, Schema.String])),
25
+ failed_count: optionalNull(Schema.Union([Schema.Number, Schema.String])),
26
+ })),
27
+ base_resp: optionalNull(Schema.Struct({
28
+ status_code: Schema.Number,
29
+ status_msg: optionalNull(Schema.String),
30
+ })),
31
+ });
32
+ const FAILURE = {
33
+ 1002: "RateLimit",
34
+ 1004: "Authentication",
35
+ 2013: "InvalidRequest",
36
+ 2049: "Authentication",
37
+ };
38
+ const INSUFFICIENT_BALANCE = 1008;
39
+ const CONTENT_POLICY = 1026;
40
+ // ---------------------------------------------------------------------------
41
+ // 5. Request body construction
42
+ // ---------------------------------------------------------------------------
43
+ /** MiniMax's `aspect_ratio` presets and the sizes it renders them at. */
44
+ const PRESETS = {
45
+ "1:1": { width: 1024, height: 1024 },
46
+ "16:9": { width: 1280, height: 720 },
47
+ "4:3": { width: 1152, height: 864 },
48
+ "3:2": { width: 1248, height: 832 },
49
+ "2:3": { width: 832, height: 1248 },
50
+ "3:4": { width: 864, height: 1152 },
51
+ "9:16": { width: 720, height: 1280 },
52
+ "21:9": { width: 1344, height: 576 },
53
+ };
54
+ const LIMITS = { multiple: 8, minEdge: 512, maxEdge: 2048 };
55
+ const nativeOptions = (options = {}) => {
56
+ const { responseFormat, promptOptimizer, ...native } = options;
57
+ return { response_format: responseFormat ?? "base64", prompt_optimizer: promptOptimizer, ...native };
58
+ };
59
+ /** `image-01-live` rejects `21:9`. */
60
+ const presets = (model) => model === "image-01" ? PRESETS : Object.fromEntries(Object.entries(PRESETS).filter(([key]) => key !== "21:9"));
61
+ /** Presets render at about 1K, so they serve a preset aspect with no resolution or `1K`. */
62
+ const preset = (request) => {
63
+ const aspect = request.aspect ?? "1:1";
64
+ if (!Object.hasOwn(presets(request.model.id), aspect))
65
+ return undefined;
66
+ if (request.resolution !== undefined && ImageSizing.tier(request.resolution) !== 1)
67
+ return undefined;
68
+ return aspect;
69
+ };
70
+ /** Only `image-01` takes free `width` and `height`; other models render the presets alone. */
71
+ const sizing = (request) => {
72
+ if (!ImageSizing.isRequested(request))
73
+ return Effect.succeed({});
74
+ const aspect = preset(request);
75
+ if (aspect !== undefined)
76
+ return Effect.succeed({ aspect_ratio: aspect });
77
+ if (request.model.id === "image-01")
78
+ return ImageSizing.exact(route, request, LIMITS);
79
+ const available = presets(request.model.id);
80
+ const closest = ImageSizing.nearest(request, Object.values(available));
81
+ const name = Object.keys(available).find((key) => available[key] === closest);
82
+ return Effect.fail(route.unsupported(request.resolution === undefined ? "media.aspect" : "media.resolution", `${request.model.id} can't render ${[request.aspect, request.resolution].filter((value) => value !== undefined).join(" at ")}; the closest size it takes is ${closest.width}x${closest.height} (${name}). Change aspect or resolution, or set aspect_ratio in providerOptions`));
83
+ };
84
+ const isNativeSize = (options) => options?.aspect_ratio !== undefined || options?.width !== undefined || options?.height !== undefined;
85
+ // The API only takes a `character` (portrait) subject, one per request.
86
+ const subject = (asset) => ProviderShared.mediaReference(asset, undefined, `${route.name} input`).pipe(Effect.map((item) => ({ type: "character", image_file: item.value })));
87
+ const fromRequest = Effect.fn("MiniMaxImages.fromRequest")(function* (request) {
88
+ if ((request.images?.length ?? 0) > 1)
89
+ return yield* route.unsupported("media.images", `${route.name} takes one subject reference image`);
90
+ if (isNativeSize(request.providerOptions) && ImageSizing.isRequested(request))
91
+ return yield* ProviderShared.invalidRequest("MiniMax providerOptions aspect_ratio, width and height replace aspect and resolution; set one or the other");
92
+ const references = yield* Effect.forEach(request.images ?? [], subject);
93
+ return MediaProtocol.json(mergeJsonRecords({
94
+ model: request.model.id,
95
+ prompt: request.prompt,
96
+ subject_reference: references.length === 0 ? undefined : references,
97
+ n: request.n,
98
+ ...(yield* sizing(request)),
99
+ }, nativeOptions(request.providerOptions), request.http?.body) ?? {});
100
+ });
101
+ // ---------------------------------------------------------------------------
102
+ // 6. Response decoding
103
+ // ---------------------------------------------------------------------------
104
+ const decodeDocument = route.decodeJson(MiniMaxImageResponse);
105
+ const decodeResponse = Effect.fn("MiniMaxImages.decodeResponse")(function* (response) {
106
+ const output = yield* decodeDocument(response);
107
+ const decoded = output.value;
108
+ // MiniMax answers errors with HTTP 200 and a non-zero `base_resp.status_code`.
109
+ const status = decoded.base_resp;
110
+ if (status && status.status_code !== 0) {
111
+ const message = `${route.name} failed (${status.status_code}): ${status.status_msg ?? "unknown error"}`;
112
+ if (status.status_code === CONTENT_POLICY)
113
+ return yield* output.contentPolicy(message);
114
+ if (status.status_code === INSUFFICIENT_BALANCE)
115
+ return yield* new AIError({ reason: new QuotaExceededError({ message, body: output.body, http: output.http }) });
116
+ return yield* output.ended("failed", message, MediaProtocol.failure(FAILURE, status.status_code));
117
+ }
118
+ const images = [
119
+ ...(yield* Effect.forEach(decoded.data?.image_base64 ?? [], (data, index) => MediaInput.decodedAsset(output.invalid, `${route.name} result ${index}`, data, undefined))),
120
+ // MiniMax returns no content type for URLs; the media type resolves when the asset is materialized.
121
+ ...(yield* Effect.forEach(decoded.data?.image_urls ?? [], (url) => MediaProtocol.expiringUrl(url, OUTPUT_RETENTION))),
122
+ ];
123
+ const failed = Number(decoded.metadata?.failed_count ?? 0);
124
+ if (images.length === 0 && failed > 0)
125
+ return yield* output.contentPolicy(`${route.name} blocked ${failed} image(s) for content safety`);
126
+ if (images.length === 0)
127
+ return yield* output.invalid(`${route.name} returned no images`);
128
+ return new ImageResponse({
129
+ images,
130
+ providerMetadata: {
131
+ minimax: {
132
+ id: decoded.id ?? undefined,
133
+ successCount: decoded.metadata?.success_count ?? undefined,
134
+ failedCount: decoded.metadata?.failed_count ?? undefined,
135
+ },
136
+ },
137
+ });
138
+ });
139
+ // ---------------------------------------------------------------------------
140
+ // 7. Protocol and route
141
+ // ---------------------------------------------------------------------------
142
+ export const protocol = MediaProtocol.inline(route, {
143
+ body: { from: fromRequest },
144
+ response: { decode: decodeResponse },
145
+ });
146
+ export const model = (input) => ImageModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input);
147
+ export const MiniMaxImages = {
148
+ protocol,
149
+ model,
150
+ };