@opencode/ai 0.0.0-dev-537 → 0.0.0-dev-544

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 +16 -2
  2. package/dist/cache-policy.js +15 -3
  3. package/dist/decision.d.ts +12 -10
  4. package/dist/decision.js +10 -4
  5. package/dist/experimental/extraction.d.ts +3 -7
  6. package/dist/experimental/extraction.js +2 -3
  7. package/dist/image.d.ts +5 -7
  8. package/dist/image.js +2 -3
  9. package/dist/llm.d.ts +3 -6
  10. package/dist/llm.js +5 -2
  11. package/dist/loop.js +5 -4
  12. package/dist/media-model.d.ts +1 -1
  13. package/dist/media-model.js +1 -1
  14. package/dist/media.d.ts +9 -0
  15. package/dist/media.js +37 -2
  16. package/dist/protocols/anthropic-messages.js +3 -12
  17. package/dist/protocols/bedrock-converse.js +0 -4
  18. package/dist/protocols/gemini.js +0 -4
  19. package/dist/protocols/meta-responses.js +22 -20
  20. package/dist/protocols/mistral-chat.js +0 -3
  21. package/dist/protocols/open-responses.d.ts +1 -1
  22. package/dist/protocols/open-responses.js +4 -6
  23. package/dist/protocols/openai-chat.d.ts +3 -3
  24. package/dist/protocols/openai-chat.js +7 -25
  25. package/dist/protocols/shared.js +11 -9
  26. package/dist/protocols/utils/responses-compaction.js +3 -3
  27. package/dist/protocols/utils/tool-stream.d.ts +2 -2
  28. package/dist/providers/assemblyai.d.ts +1 -1
  29. package/dist/providers/azure.js +2 -2
  30. package/dist/providers/cartesia.d.ts +1 -1
  31. package/dist/providers/deepgram.d.ts +1 -1
  32. package/dist/providers/elevenlabs.d.ts +1 -1
  33. package/dist/providers/openai.js +2 -2
  34. package/dist/providers/opencode.d.ts +2 -2
  35. package/dist/providers/opencode.js +1 -1
  36. package/dist/providers/runway.d.ts +1 -1
  37. package/dist/providers/typesafe-ai.d.ts +2 -2
  38. package/dist/providers/typesafe-ai.js +1 -1
  39. package/dist/public.d.ts +3 -3
  40. package/dist/public.js +1 -1
  41. package/dist/route/client.d.ts +3 -7
  42. package/dist/route/client.js +11 -24
  43. package/dist/route/decision.d.ts +2 -2
  44. package/dist/route/decision.js +3 -3
  45. package/dist/route/executor.d.ts +5 -0
  46. package/dist/route/executor.js +10 -0
  47. package/dist/route/index.d.ts +1 -1
  48. package/dist/route/index.js +1 -1
  49. package/dist/route/media.d.ts +7 -11
  50. package/dist/route/media.js +22 -26
  51. package/dist/route/transport/http.js +6 -5
  52. package/dist/schema/events.d.ts +63 -40
  53. package/dist/schema/events.js +3 -3
  54. package/dist/schema/messages.d.ts +181 -32
  55. package/dist/schema/messages.js +65 -23
  56. package/dist/schema/options.d.ts +42 -30
  57. package/dist/schema/options.js +27 -56
  58. package/dist/speech.d.ts +3 -7
  59. package/dist/speech.js +1 -3
  60. package/dist/testing.d.ts +8 -8
  61. package/dist/tool-history.d.ts +1 -1
  62. package/dist/tool-history.js +3 -9
  63. package/dist/transcription.d.ts +3 -8
  64. package/dist/transcription.js +1 -3
  65. package/dist/video.d.ts +3 -7
  66. package/dist/video.js +1 -3
  67. package/package.json +3 -3
package/README.md CHANGED
@@ -744,6 +744,20 @@ edits endpoint, so input images go to `/images/generations` as `input_references
744
744
  asset into owned bytes before the provider URL expires. Construct assets with `Media.bytes`, `Media.base64`,
745
745
  `Media.url`, `Media.ref(provider, id)`, `Media.fromDataUrl`, or `Media.file(path)`.
746
746
 
747
+ File inputs (message `media` parts, image `images`, decision `media` parts) also take plain data: a `Uint8Array`,
748
+ `ArrayBuffer`, `URL`, or a string holding a data URL, an http(s) URL or base64. Bytes and base64 are sniffed from
749
+ magic bytes; pass `mediaType` when that fails:
750
+
751
+ ```ts
752
+ ai.request({
753
+ model,
754
+ prompt: [
755
+ { type: "text", text: "Summarize this report" },
756
+ { type: "media", media: pdfBase64, mediaType: "application/pdf" },
757
+ ],
758
+ })
759
+ ```
760
+
747
761
  Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
748
762
 
749
763
  ```ts
@@ -765,8 +779,8 @@ const composed = Effect.gen(function* () {
765
779
 
766
780
  `Media.ref(provider, id)` represents provider file handles such as OpenAI file IDs or Gemini Files URIs; routes
767
781
  only forward refs that belong to their own provider (OpenAI, xAI, and Gemini images accept them). No shipped route
768
- returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Raw strings are not accepted as
769
- image inputs, avoiding ambiguity between base64, URLs, and provider IDs. Empty or omitted `images` uses text-to-image generation; a
782
+ returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Empty or omitted `images` uses
783
+ text-to-image generation; a
770
784
  non-empty array selects the provider's edit behavior (see the table above for routes that limit the count). OpenAI
771
785
  uses multipart for byte/data-URL edits and its JSON reference body for URL or file-ID edits. Inpainting is a
772
786
  provider option on the routes that support it (OpenAI):
@@ -11,7 +11,7 @@
11
11
  // Manual `cache: CacheHint` placements on individual parts are preserved and
12
12
  // count against the four-breakpoint budget; auto only fills remaining slots.
13
13
  import { CacheHint } from "./schema/options.js";
14
- import { Message, ToolDefinition } from "./schema/messages.js";
14
+ import { AssistantMessage, SystemMessage, ToolDefinition, ToolMessage, UserMessage, } from "./schema/messages.js";
15
15
  import { effortUpdate } from "./effort-updates.js";
16
16
  const AUTO = {
17
17
  tools: true,
@@ -119,8 +119,7 @@ const markMessageAt = (messages, index, hint, budget) => {
119
119
  if (!existing || !isCacheablePart(existing) || existing.cache || budget.remaining === 0)
120
120
  return messages;
121
121
  budget.remaining -= 1;
122
- const nextContent = target.content.map((part, i) => (i === markAt ? { ...existing, cache: hint } : part));
123
- const next = new Message({ ...target, content: nextContent });
122
+ const next = cachePartAt(target, markAt, hint);
124
123
  // Single pass over `messages`, substituting the one updated entry. Long
125
124
  // conversations call this on every request, so avoid `.map()` here — its
126
125
  // closure dispatch and identity copies show up in profiling.
@@ -128,6 +127,19 @@ const markMessageAt = (messages, index, hint, budget) => {
128
127
  result[index] = next;
129
128
  return result;
130
129
  };
130
+ const cachePartAt = (message, index, hint) => {
131
+ switch (message.role) {
132
+ case "system":
133
+ return new SystemMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
134
+ case "user":
135
+ return new UserMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
136
+ case "assistant":
137
+ return new AssistantMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
138
+ case "tool":
139
+ return new ToolMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
140
+ }
141
+ };
142
+ const cacheContentAt = (content, index, hint) => content.map((part, i) => (i === index ? { ...part, cache: hint } : part));
131
143
  const markMessages = (messages, strategy, hint, budget) => {
132
144
  if (messages.length === 0)
133
145
  return messages;
@@ -1,7 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { Service, type Execute } from "./decision-client.js";
3
3
  import { Media } from "./media.js";
4
- import { AIError, HttpOptions, ModelID, ProviderID, ProviderOptions, type OpenString } from "./schema/index.js";
4
+ import { AIError, type BaseRequest, type HttpOptions, ModelID, ProviderID, ProviderOptions, type OpenString } from "./schema/index.js";
5
5
  export declare const DecisionTextPart: Schema.Struct<{
6
6
  readonly type: Schema.Literal<"text">;
7
7
  readonly text: Schema.String;
@@ -87,8 +87,16 @@ export declare const DecisionPart: Schema.toTaggedUnion<"type", readonly [Schema
87
87
  readonly filename: Schema.optional<Schema.String>;
88
88
  }>]>;
89
89
  export type DecisionPart = Schema.Schema.Type<typeof DecisionPart>;
90
+ /** A media part as input: `media` may be plain data, with `mediaType` naming its type when the content can't. */
91
+ export type DecisionMediaPartInput = Omit<typeof DecisionMediaPart.Type, "media"> & {
92
+ readonly media: Media.Input;
93
+ readonly mediaType?: string;
94
+ };
95
+ export type DecisionPartInput = Exclude<DecisionPart, {
96
+ readonly type: "media";
97
+ }> | DecisionMediaPartInput;
90
98
  /** A plain object is one `json` part. */
91
- export type DecisionInput = typeof Schema.JsonObject.Type | ReadonlyArray<DecisionPart>;
99
+ export type DecisionInput = typeof Schema.JsonObject.Type | ReadonlyArray<DecisionPartInput>;
92
100
  /** Choice values are typed: `true` and `"true"` are different values. */
93
101
  export declare const ChoiceValue: Schema.Union<readonly [Schema.String, Schema.Boolean]>;
94
102
  export type ChoiceValue = Schema.Schema.Type<typeof ChoiceValue>;
@@ -291,20 +299,14 @@ export declare namespace DecisionModel {
291
299
  export declare const DecisionModelSchema: Schema.declare<DecisionModel<DecisionOptions>, DecisionModel<DecisionOptions>>;
292
300
  export type DecisionModelOptions<Model> = Model extends DecisionModel<infer Options> ? Options : never;
293
301
  /** A normalized decision request, the plain object `ai.decision.request(...)` returns. */
294
- export interface DecisionRequest<Model extends DecisionModel = DecisionModel, Questions extends DecisionQuestions = DecisionQuestions> {
295
- readonly model: Model;
302
+ export interface DecisionRequest<Model extends DecisionModel = DecisionModel, Questions extends DecisionQuestions = DecisionQuestions> extends BaseRequest<Model, DecisionModelOptions<Model>> {
296
303
  readonly input: ReadonlyArray<DecisionPart>;
297
304
  readonly questions: Questions;
298
- readonly providerOptions?: DecisionModelOptions<Model>;
299
- readonly http?: HttpOptions;
300
305
  }
301
306
  /** Input accepted by `ai.decision.request` and `generate`. A `DecisionRequest` is also a valid input. */
302
- export interface DecisionRequestInput<Model extends DecisionModel = DecisionModel, Questions extends DecisionQuestions = DecisionQuestions> {
303
- readonly model: Model;
307
+ export interface DecisionRequestInput<Model extends DecisionModel = DecisionModel, Questions extends DecisionQuestions = DecisionQuestions> extends BaseRequest<Model, NoInfer<DecisionModelOptions<Model>>> {
304
308
  readonly input: DecisionInput;
305
309
  readonly questions: Questions;
306
- readonly providerOptions?: NoInfer<DecisionModelOptions<Model>>;
307
- readonly http?: HttpOptions.Input;
308
310
  }
309
311
  declare const DecisionUsage_base: Schema.Class<DecisionUsage, Schema.Struct<{
310
312
  readonly inputTokens: Schema.optional<Schema.Number>;
package/dist/decision.js CHANGED
@@ -2,7 +2,7 @@ import { Effect, Schema } from "effect";
2
2
  import { DecisionClient, Service } from "./decision-client.js";
3
3
  import { Media } from "./media.js";
4
4
  import { tryRequest } from "./media-model.js";
5
- import { AIError, HttpOptions, ModelID, ProviderID, ProviderMetadata, ProviderOptions, } from "./schema/index.js";
5
+ import { AIError, ModelID, ProviderID, ProviderMetadata, ProviderOptions, } from "./schema/index.js";
6
6
  // ---------------------------------------------------------------------------
7
7
  // Input
8
8
  // ---------------------------------------------------------------------------
@@ -122,7 +122,6 @@ const DecisionRequestSchema = Schema.Struct({
122
122
  input: Schema.Array(DecisionPart),
123
123
  questions: DecisionQuestionList,
124
124
  providerOptions: Schema.optional(ProviderOptions),
125
- http: Schema.optional(HttpOptions),
126
125
  });
127
126
  /** What decision hosts report; their raw usage stays in the response's `providerMetadata`. */
128
127
  export class DecisionUsage extends Schema.Class("Decision.Usage")({
@@ -145,10 +144,17 @@ export class DecisionResponse extends Schema.Class("Decision.Response")({
145
144
  /** Normalize decision request input into a plain `DecisionRequest`; a plain object `input` becomes one `json` part. */
146
145
  export const request = (input) => ({
147
146
  ...input,
148
- input: Array.isArray(input.input) ? input.input : [{ type: "json", value: input.input }],
149
- http: HttpOptions.make(input.http),
147
+ input: isParts(input.input) ? input.input.map(decisionPart) : [{ type: "json", value: input.input }],
150
148
  });
151
149
  const validate = Schema.decodeUnknownSync(DecisionRequestSchema);
150
+ // `Array.isArray` doesn't narrow a readonly array union, so the object branch would keep the parts type.
151
+ const isParts = (input) => Array.isArray(input);
152
+ const decisionPart = (part) => {
153
+ if (part.type !== "media")
154
+ return part;
155
+ const { mediaType, ...rest } = part;
156
+ return { ...rest, media: Media.make(part.media, mediaType) };
157
+ };
152
158
  export function generate(input) {
153
159
  return tryRequest(() => {
154
160
  const normalized = request(input);
@@ -2,7 +2,7 @@ import { Effect, Schema } from "effect";
2
2
  import { MediaModel } from "../media-model.js";
3
3
  import { RequestExecutor } from "../route/executor.js";
4
4
  import type { MediaRoute } from "../route/media.js";
5
- import { AIError, HttpOptions, Usage, type OpenString } from "../schema/index.js";
5
+ import { AIError, Usage, type BaseRequest, type OpenString } from "../schema/index.js";
6
6
  /**
7
7
  * The answer schema for each field type Clairic documents, decoding its wire keys (`p_null` and friends). Answers to
8
8
  * other field types pass through as sent.
@@ -122,20 +122,16 @@ export declare class ExtractionModel<Options extends ExtractionOptions = Extract
122
122
  }
123
123
  export type ExtractionModelOptions<Model> = Model extends ExtractionModel<infer Options> ? Options : never;
124
124
  /** A normalized extraction request, the plain object `Extraction.request(...)` returns. */
125
- export interface ExtractionRequest<Model extends ExtractionModel = ExtractionModel, Fields extends ExtractionFields = ExtractionFields> {
126
- readonly model: Model;
125
+ export interface ExtractionRequest<Model extends ExtractionModel = ExtractionModel, Fields extends ExtractionFields = ExtractionFields> extends BaseRequest<Model, ExtractionModelOptions<Model>> {
127
126
  /** The text to read; text answers carry spans into it. */
128
127
  readonly input: string;
129
128
  readonly fields: Fields;
130
129
  /** ISO date that anchors dates written without a year. */
131
130
  readonly referenceDate?: string;
132
- readonly providerOptions?: ExtractionModelOptions<Model>;
133
- readonly http?: HttpOptions;
134
131
  }
135
132
  /** Input accepted by `Extraction.request` and `generate`; an `ExtractionRequest` is also a valid input. */
136
- export type ExtractionRequestInput<Model extends ExtractionModel = ExtractionModel, Fields extends ExtractionFields = ExtractionFields> = Omit<ExtractionRequest<Model, Fields>, "providerOptions" | "http"> & {
133
+ export type ExtractionRequestInput<Model extends ExtractionModel = ExtractionModel, Fields extends ExtractionFields = ExtractionFields> = Omit<ExtractionRequest<Model, Fields>, "providerOptions"> & {
137
134
  readonly providerOptions?: NoInfer<ExtractionModelOptions<Model>>;
138
- readonly http?: HttpOptions.Input;
139
135
  };
140
136
  declare const ExtractionResponse_base: Schema.Class<ExtractionResponse, Schema.Struct<{
141
137
  readonly answers: Schema.$Record<Schema.String, Schema.$Record<Schema.String, Schema.Unknown>>;
@@ -1,7 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { MediaModel, tryRequest } from "../media-model.js";
3
3
  import { RequestExecutor } from "../route/executor.js";
4
- import { AIError, HttpOptions, ProviderMetadata, ProviderOptions, Usage } from "../schema/index.js";
4
+ import { AIError, ProviderMetadata, ProviderOptions, Usage, } from "../schema/index.js";
5
5
  // ---------------------------------------------------------------------------
6
6
  // Answers
7
7
  // ---------------------------------------------------------------------------
@@ -73,7 +73,6 @@ const ExtractionRequestSchema = Schema.Struct({
73
73
  fields: Schema.Record(Schema.String, ExtractionFieldSchema).pipe(Schema.refine((x) => Object.keys(x).length > 0, { message: "Extraction fields must not be empty" })),
74
74
  referenceDate: Schema.optional(Schema.String),
75
75
  providerOptions: Schema.optional(ProviderOptions),
76
- http: Schema.optional(HttpOptions),
77
76
  });
78
77
  export class ExtractionResponse extends Schema.Class("Extraction.Response")({
79
78
  answers: Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown)),
@@ -85,7 +84,7 @@ export class ExtractionResponse extends Schema.Class("Extraction.Response")({
85
84
  // Call API
86
85
  // ---------------------------------------------------------------------------
87
86
  /** Normalize extraction request input into a plain `ExtractionRequest`. */
88
- export const request = (input) => ({ ...input, http: HttpOptions.make(input.http) });
87
+ export const request = (input) => ({ ...input });
89
88
  const validate = Schema.decodeUnknownSync(ExtractionRequestSchema);
90
89
  export function generate(input) {
91
90
  return Effect.gen(function* () {
package/dist/image.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Generation, type AwaitOptions } 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";
6
- import { AIError, HttpOptions, type OpenString } from "./schema/index.js";
6
+ import { AIError, type OpenString, type BaseRequest } from "./schema/index.js";
7
7
  import { Service } from "./image-client.js";
8
8
  export type ImageOptions = MediaModel.Options;
9
9
  export type ImageRoute = MediaRoute.AnyRoute<ImageRequest, ImageEvent, ImageResponse>;
@@ -24,22 +24,20 @@ export declare const ImageAspectRatio: Schema.declare<`${number}:${number}`, `${
24
24
  /** Size tier: `1K` is about as many pixels as 1024×1024 at the requested aspect, `2K` as 2048×2048. */
25
25
  export type ImageResolution = OpenString<"1K" | "2K" | "4K">;
26
26
  /** A normalized image request, the plain object `ai.image.request(...)` returns. */
27
- export interface ImageRequest<Model extends ImageModel = ImageModel> {
28
- readonly model: Model;
27
+ export interface ImageRequest<Model extends ImageModel = ImageModel> extends BaseRequest<Model, ImageModelOptions<Model>> {
29
28
  readonly prompt: string;
30
29
  /** Edit sources or style/subject references, in order. */
31
30
  readonly images?: ReadonlyArray<Media.Asset>;
32
31
  readonly n?: number;
33
32
  readonly aspect?: ImageAspectRatio;
34
33
  readonly resolution?: ImageResolution;
35
- readonly providerOptions?: ImageModelOptions<Model>;
36
- readonly http?: HttpOptions;
37
34
  }
38
35
  export type ImageModelOptions<Model> = Model extends ImageModel<infer Options> ? Options : never;
39
36
  /** Input accepted by `ai.image.request`, `generate`, `stream` and `start`. An `ImageRequest` is also a valid input. */
40
- export type ImageRequestInput<Model extends ImageModel = ImageModel> = Omit<ImageRequest<Model>, "providerOptions" | "http"> & {
37
+ export type ImageRequestInput<Model extends ImageModel = ImageModel> = Omit<ImageRequest<Model>, "images" | "providerOptions"> & {
38
+ /** Edit sources or style/subject references, in order: assets or plain data with a detectable type. */
39
+ readonly images?: ReadonlyArray<Media.Input>;
41
40
  readonly providerOptions?: NoInfer<ImageModelOptions<Model>>;
42
- readonly http?: HttpOptions.Input;
43
41
  };
44
42
  declare const ImageResponse_base: Schema.Class<ImageResponse, Schema.Struct<{
45
43
  readonly images: Schema.$Array<Schema.decodeTo<Schema.declare<Media.Asset, Media.Asset>, Schema.Struct<{
package/dist/image.js CHANGED
@@ -3,7 +3,7 @@ import { Generation, 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";
6
- import { AIError, HttpOptions, MediaUsage, ProviderMetadata, ProviderOptions } from "./schema/index.js";
6
+ import { AIError, MediaUsage, ProviderMetadata, ProviderOptions, } from "./schema/index.js";
7
7
  import { ImageClient, Service } from "./image-client.js";
8
8
  export class ImageModel extends MediaModel {
9
9
  static fromRoute(route, input) {
@@ -28,7 +28,6 @@ const ImageRequestSchema = Schema.Struct({
28
28
  aspect: Schema.optional(ImageAspectRatio),
29
29
  resolution: Schema.optional(Schema.String),
30
30
  providerOptions: Schema.optional(ProviderOptions),
31
- http: Schema.optional(HttpOptions),
32
31
  });
33
32
  // ---------------------------------------------------------------------------
34
33
  // Response and events
@@ -91,7 +90,7 @@ const collectResponse = (events) => {
91
90
  /** Normalize image request input into a plain `ImageRequest`. */
92
91
  export const request = (input) => ({
93
92
  ...input,
94
- http: HttpOptions.make(input.http),
93
+ images: input.images?.map((image) => Media.make(image)),
95
94
  });
96
95
  const validate = Schema.decodeUnknownSync(ImageRequestSchema);
97
96
  const requestEffect = (input) => tryRequest(() => {
package/dist/llm.d.ts CHANGED
@@ -1,27 +1,24 @@
1
1
  import { Effect, JsonSchema, Schema, Stream } from "effect";
2
2
  import { Service, canCompact, type CheckpointRequest, type CompactionRequest, type EndpointCompactOptions, type StreamOptions, type TriggerCompactOptions } from "./route/client.js";
3
- import { GenerationOptions, HttpOptions, AIError, LLMEvent, LLMResponse, Message, LanguageModel, SystemPart, type CachePolicy, type CompactionCheckpointResponse, type CompactionResponse, type Finish, ToolChoice, type ContentPart, type LanguageModelProviderOptions, type LLMRequest, type ToolEntryInput } from "./schema/index.js";
3
+ import { GenerationOptions, AIError, LLMEvent, LLMResponse, Message, LanguageModel, SystemPart, type BaseRequest, type CachePolicy, type CompactionCheckpointResponse, type CompactionResponse, type Finish, ToolChoice, type LanguageModelProviderOptions, type LLMRequest, type ToolEntryInput } from "./schema/index.js";
4
4
  import { type ExecutableTool, type Tool, type ToolSchema } from "./tool.js";
5
5
  /** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */
6
6
  export type LLMRequestInput<Model extends LanguageModel = LanguageModel> = TextRequestFields<Model> & PromptOrMessages;
7
7
  /** Exactly one of `prompt`, a single user message, or `messages`, the full conversation. */
8
8
  export type PromptOrMessages = {
9
- readonly prompt: string | ContentPart | ReadonlyArray<ContentPart>;
9
+ readonly prompt: Message.UserContentInput;
10
10
  readonly messages?: never;
11
11
  } | {
12
12
  readonly messages: ReadonlyArray<Message | Message.Input>;
13
13
  readonly prompt?: never;
14
14
  };
15
- interface TextRequestFields<Model extends LanguageModel> {
15
+ interface TextRequestFields<Model extends LanguageModel> extends BaseRequest<Model, NoInfer<LanguageModelProviderOptions<Model>>> {
16
16
  readonly id?: string;
17
- readonly model: Model;
18
17
  readonly system?: string | SystemPart | ReadonlyArray<SystemPart>;
19
18
  /** Sent in array order. Pass `tool(...)` values or wire entries such as hosted provider tools. */
20
19
  readonly tools?: ReadonlyArray<Tool | ToolEntryInput>;
21
20
  readonly toolChoice?: ToolChoice.Input;
22
21
  readonly generation?: GenerationOptions.Input;
23
- readonly providerOptions?: NoInfer<LanguageModelProviderOptions<Model>>;
24
- readonly http?: HttpOptions.Input;
25
22
  readonly cache?: CachePolicy;
26
23
  /** Stable cache affinity for protocols that support provider-managed prompt caching. */
27
24
  readonly promptCacheKey?: string;
package/dist/llm.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Effect, JsonSchema, Schema, Stream } from "effect";
2
2
  import { tryRequest } from "./media-model.js";
3
3
  import { LLMClient, Service, canCompact, compactRequest, } from "./route/client.js";
4
- import { GenerationOptions, HttpOptions, InvalidProviderOutputError, InvalidRequestError, AIError, LLMEvent, LLMResponse, ResponseFold, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, Usage, withPartial, } from "./schema/index.js";
4
+ import { GenerationOptions, InvalidProviderOutputError, InvalidRequestError, AIError, LLMEvent, LLMResponse, ResponseFold, Message, LanguageModel, SystemPart, ToolChoice, ToolEntry, Usage, withPartial, } from "./schema/index.js";
5
5
  import { tool } from "./tool.js";
6
6
  import { runTools } from "./tool-runtime.js";
7
7
  import { addUsage, nextRequest, pendingCalls } from "./loop.js";
@@ -99,7 +99,10 @@ export const request = (input) => {
99
99
  toolChoice: input.toolChoice ? ToolChoice.make(input.toolChoice) : undefined,
100
100
  generation: input.generation === undefined ? undefined : GenerationOptions.make(input.generation),
101
101
  providerOptions: input.providerOptions,
102
- http: HttpOptions.make(input.http),
102
+ headers: input.headers,
103
+ fetch: input.fetch,
104
+ timeout: input.timeout,
105
+ http: input.http,
103
106
  cache: input.cache,
104
107
  promptCacheKey: input.promptCacheKey,
105
108
  includeRaw: input.includeRaw,
package/dist/loop.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Effect, Stream } from "effect";
2
- import { AIError, InvalidProviderOutputError, LLMResponse, ResponseFold, Message, Usage, LLMEvent, ToolCallPart, ToolChoice, } from "./schema/index.js";
2
+ import { AIError, AssistantMessage, InvalidProviderOutputError, LLMResponse, ResponseFold, Message, Usage, LLMEvent, ToolCallPart, ToolChoice, } from "./schema/index.js";
3
3
  /**
4
4
  * Client calls to answer before the next step. A call whose input was not valid JSON carries the error the model
5
5
  * gets back, so it can retry. A step is final when it calls `answerTool`, even alongside other tools, or when it hits
@@ -21,7 +21,7 @@ export const pendingCalls = (response, answerTool) => {
21
21
  /** The call to replay for input that was not valid JSON. Providers require an object input, so it is empty. */
22
22
  const invalidCall = (event) => ToolCallPart.make({ id: event.id, name: event.name, namespace: event.namespace, input: {} });
23
23
  /** Add the replayed calls for invalid input to the assistant message, so each tool result has its call. */
24
- const withInvalidCalls = (message, calls) => calls.length === 0 ? message : new Message({ ...message, content: [...message.content, ...calls] });
24
+ const withInvalidCalls = (message, calls) => calls.length === 0 ? message : new AssistantMessage({ ...message, content: [...message.content, ...calls] });
25
25
  /** The step's assistant message followed by one tool message per call, in call order. */
26
26
  export const stepMessages = (response, calls, results) => [
27
27
  withInvalidCalls(response.message, calls.flatMap((item) => (item.error === undefined ? [] : [item.call]))),
@@ -95,8 +95,9 @@ export function collect(events) {
95
95
  }
96
96
  if (event.type === "tool-result" && betweenSteps) {
97
97
  const call = invalid.find((item) => item.id === event.id);
98
- if (call)
99
- messages[assistant] = withInvalidCalls(messages[assistant], [call]);
98
+ const previous = messages[assistant];
99
+ if (call && previous.role === "assistant")
100
+ messages[assistant] = withInvalidCalls(previous, [call]);
100
101
  messages.push(Message.tool({
101
102
  id: event.id,
102
103
  name: event.name,
@@ -2,7 +2,7 @@ import { Effect } from "effect";
2
2
  import { Endpoint } from "./route/endpoint.js";
3
3
  import { MediaRoute } from "./route/media.js";
4
4
  import type { MediaProtocol } from "./route/media-protocol.js";
5
- import { AIError, HttpOptions, ModelID, ProviderID, type ProviderOptions } from "./schema/index.js";
5
+ import { AIError, ModelID, ProviderID, type HttpOptions, type ProviderOptions } from "./schema/index.js";
6
6
  /**
7
7
  * What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
8
8
  * (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { Endpoint } from "./route/endpoint.js";
3
3
  import { MediaRoute } from "./route/media.js";
4
- import { AIError, HttpOptions, InvalidRequestError, ModelID, ProviderID } from "./schema/index.js";
4
+ import { AIError, InvalidRequestError, ModelID, ProviderID, } from "./schema/index.js";
5
5
  /**
6
6
  * What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
7
7
  * (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
package/dist/media.d.ts CHANGED
@@ -200,6 +200,15 @@ export declare const ref: (provider: string | ProviderID, id: string, mediaType?
200
200
  export declare const parseDataUrl: (value: string, options?: AssetOptions) => Asset | undefined;
201
201
  /** Parse a `data:<mime>;base64,<data>` URL. Malformed input throws a typed `AIError` because constructors are sync. */
202
202
  export declare const fromDataUrl: (dataUrl: string, options?: AssetOptions) => Asset;
203
+ /** Plain file data: bytes, a URL, or a string holding a data URL, an http(s) URL or base64. */
204
+ export type Data = Uint8Array | ArrayBuffer | URL | string;
205
+ /** What file inputs accept: an `Asset` or plain `Data`. */
206
+ export type Input = Asset | Data;
207
+ /**
208
+ * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
209
+ * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
210
+ */
211
+ export declare const make: (input: Input, mediaType?: string) => Asset;
203
212
  /** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
204
213
  export declare const file: (path: string, options?: AssetOptions) => Effect.Effect<Asset, AIError, FileSystem.FileSystem>;
205
214
  /** Materialize an asset and write its bytes through `FileSystem`. */
package/dist/media.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export * as Media from "./media.js";
2
- import { Effect, FileSystem, Schema, SchemaGetter } from "effect";
2
+ import { Effect, FileSystem, Result, Schema, SchemaGetter } from "effect";
3
3
  import { Base64 } from "effect/encoding";
4
4
  import { HttpClientRequest } from "effect/http";
5
5
  import { ProviderID } from "./schema/ids.js";
@@ -191,7 +191,7 @@ export const url = (value, options) => {
191
191
  return from({ type: "url", url: value, mediaType, expiresAt }, rest);
192
192
  };
193
193
  export const ref = (provider, id, mediaType, options) => from({ type: "ref", provider: ProviderID.make(provider), id, mediaType }, options);
194
- const DATA_URL = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/s;
194
+ const DATA_URL = /^data:([^;,]+)(?:;[^,]*)*;base64,(.*)$/is;
195
195
  /** Parse a `data:<mime>;base64,<data>` URL, or `undefined` when the value is not a base64 data URL. */
196
196
  export const parseDataUrl = (value, options) => {
197
197
  const match = DATA_URL.exec(value);
@@ -204,6 +204,41 @@ export const fromDataUrl = (dataUrl, options) => {
204
204
  throw invalid("Media data URLs must contain a MIME type and base64 data");
205
205
  return asset;
206
206
  };
207
+ /**
208
+ * Normalize file input into an `Asset`. Data URLs carry their media type and bytes or base64 are sniffed from magic
209
+ * bytes; `mediaType` is required when sniffing fails. Assets pass through unchanged.
210
+ */
211
+ export const make = (input, mediaType) => {
212
+ if (input instanceof Asset)
213
+ return input;
214
+ if (input instanceof ArrayBuffer)
215
+ return make(new Uint8Array(input), mediaType);
216
+ if (input instanceof Uint8Array)
217
+ return bytes(input, mediaType ?? requireMediaType(detectMediaType(input)));
218
+ const value = input instanceof URL ? input.href : input;
219
+ if (/^data:/i.test(value)) {
220
+ const match = DATA_URL.exec(value);
221
+ if (match === null)
222
+ throw invalid("Media data URLs must contain a MIME type and base64 data");
223
+ return base64(match[2], mediaType ?? match[1]);
224
+ }
225
+ if (input instanceof URL || /^https?:\/\//i.test(value))
226
+ return url(value, { mediaType });
227
+ if (!BASE64.test(value))
228
+ throw invalid("Media strings must be base64, a data URL or an http(s) URL; read files with Media.file");
229
+ return base64(value, mediaType ?? requireMediaType(sniffBase64(value)));
230
+ };
231
+ const BASE64 = /^[A-Za-z0-9+/\-_\s]*={0,2}\s*$/;
232
+ // 64 characters decode to 48 bytes, enough for every signature `detectMediaType` reads.
233
+ const sniffBase64 = (value) => {
234
+ const head = Result.getOrUndefined(Base64.decode(value.slice(0, 64)));
235
+ return head === undefined ? undefined : detectMediaType(head);
236
+ };
237
+ const requireMediaType = (detected) => {
238
+ if (detected === undefined)
239
+ throw invalid("Media data needs a mediaType because its type cannot be detected");
240
+ return detected;
241
+ };
207
242
  /** Read a file through `FileSystem` and sniff its media type from magic bytes, then the extension. */
208
243
  export const file = (path, options) => Effect.gen(function* () {
209
244
  const fs = yield* FileSystem.FileSystem;
@@ -8,7 +8,7 @@ import { Framing } from "../route/framing.js";
8
8
  import { Protocol } from "../route/protocol.js";
9
9
  import { Headers } from "effect/http";
10
10
  import { HttpTransport } from "../route/transport/index.js";
11
- import { AIError, CacheTTL, HttpOptions, LLMEvent, mergeJsonRecords, Usage, } from "../schema/index.js";
11
+ import { AIError, CacheTTL, LLMEvent, mergeJsonRecords, Usage, } from "../schema/index.js";
12
12
  import { JsonObject, knownString, optionalArray, optionalNull, ProviderShared, withUntypedFrames } from "./shared.js";
13
13
  import { classifyProviderFailure } from "../provider-error.js";
14
14
  import { effortUpdate, resolveEffortUpdates } from "../effort-updates.js";
@@ -683,7 +683,6 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
683
683
  content.push(yield* lowerMedia(part, request, breakpoints));
684
684
  continue;
685
685
  }
686
- return yield* ProviderShared.unsupportedContent("Anthropic Messages", "user", ["text", "media"]);
687
686
  }
688
687
  if (content.length > 0)
689
688
  messages.push({ role: "user", content });
@@ -740,8 +739,6 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
740
739
  }
741
740
  const content = [];
742
741
  for (const part of message.content) {
743
- if (!ProviderShared.supportsContent(part, ["tool-result"]))
744
- return yield* ProviderShared.unsupportedContent("Anthropic Messages", "tool", ["tool-result"]);
745
742
  content.push({
746
743
  type: "tool_result",
747
744
  tool_use_id: scrubToolCallID(part.id),
@@ -1309,7 +1306,7 @@ export const transport = () => {
1309
1306
  const requiredBetas = requiredBetaHeaders(input.body);
1310
1307
  if (requiredBetas.length === 0)
1311
1308
  return http.prepare(input);
1312
- const headers = Headers.fromInput(input.request.http?.headers);
1309
+ const headers = Headers.fromInput(input.request.headers);
1313
1310
  const existingBetas = (headers["anthropic-beta"] ?? "")
1314
1311
  .split(",")
1315
1312
  .map((item) => item.trim())
@@ -1317,13 +1314,7 @@ export const transport = () => {
1317
1314
  const betas = new Set([...existingBetas, ...requiredBetas]);
1318
1315
  return http.prepare({
1319
1316
  ...input,
1320
- request: {
1321
- ...input.request,
1322
- http: new HttpOptions({
1323
- ...input.request.http,
1324
- headers: { ...headers, "anthropic-beta": [...betas].join(",") },
1325
- }),
1326
- },
1317
+ request: { ...input.request, headers: { ...headers, "anthropic-beta": [...betas].join(",") } },
1327
1318
  });
1328
1319
  },
1329
1320
  };
@@ -298,8 +298,6 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
298
298
  if (message.role === "user") {
299
299
  const content = [];
300
300
  for (const part of message.content) {
301
- if (!ProviderShared.supportsContent(part, ["text", "media"]))
302
- return yield* ProviderShared.unsupportedContent("Bedrock Converse", "user", ["text", "media"]);
303
301
  if (part.type === "text") {
304
302
  content.push(...textWithCache(breakpoints, part.text, part.cache));
305
303
  continue;
@@ -352,8 +350,6 @@ const lowerMessages = Effect.fnUntraced(function* (request, breakpoints) {
352
350
  }
353
351
  const content = [];
354
352
  for (const part of message.content) {
355
- if (!ProviderShared.supportsContent(part, ["tool-result"]))
356
- return yield* ProviderShared.unsupportedContent("Bedrock Converse", "tool", ["tool-result"]);
357
353
  const result = yield* lowerToolResult(part, documentNames, normalizeID);
358
354
  const images = hoistImages
359
355
  ? result.toolResult.content.filter((item) => "image" in item)
@@ -240,8 +240,6 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
240
240
  if (message.role === "user") {
241
241
  const parts = [];
242
242
  for (const part of message.content) {
243
- if (!ProviderShared.supportsContent(part, ["text", "media"]))
244
- return yield* ProviderShared.unsupportedContent("Gemini", "user", ["text", "media"]);
245
243
  parts.push(yield* lowerContentPart(part));
246
244
  }
247
245
  contents.push({ role: "user", parts });
@@ -294,8 +292,6 @@ const lowerMessages = Effect.fnUntraced(function* (request) {
294
292
  }
295
293
  const parts = [];
296
294
  for (const part of message.content) {
297
- if (!ProviderShared.supportsContent(part, ["tool-result"]))
298
- return yield* ProviderShared.unsupportedContent("Gemini", "tool", ["tool-result"]);
299
295
  if (part.result.type !== "content") {
300
296
  parts.push({
301
297
  functionResponse: {
@@ -1,7 +1,7 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { Base64 } from "effect/encoding";
3
3
  import { Protocol } from "../route/protocol.js";
4
- import { LLMEvent, Message, ToolResultPart } from "../schema/index.js";
4
+ import { AssistantMessage, LLMEvent, ToolResultPart } from "../schema/index.js";
5
5
  import { OpenResponses } from "./open-responses.js";
6
6
  import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js";
7
7
  import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js";
@@ -50,25 +50,27 @@ const fromRequest = Effect.fn("MetaResponses.fromRequest")(function* (request) {
50
50
  const key = request.model.route.providerMetadataKey ?? String(request.model.provider);
51
51
  const body = yield* OpenResponses.fromRequestWithAdapter({
52
52
  ...request,
53
- messages: request.messages.map((message) => Message.make({
54
- ...message,
55
- content: message.content.map((part) => {
56
- if (part.type !== "tool-result" ||
57
- !part.providerExecuted ||
58
- part.name !== "image_generation" ||
59
- part.result.type !== "content" ||
60
- part.providerMetadata?.[key]?.itemId !== part.id)
61
- return part;
62
- // Meta's signed image ID carries edit state; replay the handle, not the image bytes as a user message.
63
- return ToolResultPart.make({
64
- ...part,
65
- result: {
66
- type: "json",
67
- value: { type: "image_generation_call", id: part.id, status: "completed", result: null },
68
- },
69
- });
70
- }),
71
- })),
53
+ messages: request.messages.map((message) => message.role !== "assistant"
54
+ ? message
55
+ : new AssistantMessage({
56
+ ...message,
57
+ content: message.content.map((part) => {
58
+ if (part.type !== "tool-result" ||
59
+ !part.providerExecuted ||
60
+ part.name !== "image_generation" ||
61
+ part.result.type !== "content" ||
62
+ part.providerMetadata?.[key]?.itemId !== part.id)
63
+ return part;
64
+ // Meta's signed image ID carries edit state; replay the handle, not the image bytes as a user message.
65
+ return ToolResultPart.make({
66
+ ...part,
67
+ result: {
68
+ type: "json",
69
+ value: { type: "image_generation_call", id: part.id, status: "completed", result: null },
70
+ },
71
+ });
72
+ }),
73
+ })),
72
74
  }, adapter);
73
75
  // Meta cannot see video nested in tool results; attach it after the complete result batch.
74
76
  const input = [];
@@ -165,7 +165,6 @@ const lowerUser = Effect.fnUntraced(function* (message) {
165
165
  content.push(yield* lowerMedia(part));
166
166
  continue;
167
167
  }
168
- return yield* ProviderShared.unsupportedContent("Mistral Chat", "user", ["text", "media"]);
169
168
  }
170
169
  if (content.every((part) => part.type === "text"))
171
170
  return { role: "user", content: content.map((part) => part.text).join("") };
@@ -210,8 +209,6 @@ const lowerAssistant = Effect.fnUntraced(function* (message, normalizeID) {
210
209
  const lowerToolResults = Effect.fnUntraced(function* (message, normalizeID) {
211
210
  const output = [];
212
211
  for (const part of message.content) {
213
- if (part.type !== "tool-result")
214
- return yield* ProviderShared.unsupportedContent("Mistral Chat", "tool", ["tool-result"]);
215
212
  if (part.result.type !== "content") {
216
213
  output.push({
217
214
  role: "tool",