@opencode/ai 0.0.0-dev-20215 → 0.0.0-dev-20217

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
@@ -752,7 +752,10 @@ const events = Video.stream({ model: Runway.configure({ apiKey }).video("gen4.5"
752
752
 
753
753
  Status polls, result fetches, cancels, and asset downloads all run through the same request executor with the route's
754
754
  auth. `Generation.await` and `Generation.events` fail with a
755
- `Timeout` reason when `poll.timeout` (default 10 minutes) elapses. Failed,
755
+ `Timeout` reason when `poll.timeout` (default 10 minutes) elapses. Status polls and result fetches retry transient
756
+ failures (rate limits, provider 5xx, network errors) with backoff that honors `retry-after`, always within
757
+ `poll.timeout`; submits and cancels never retry. Interrupting a wait (or aborting its `signal`) does not cancel the
758
+ provider job, which keeps running and billing: call `cancel()` to stop it. Failed,
756
759
  cancelled, and expired generations fail typed with the provider's terminal document on `reason.body`; moderation
757
760
  outcomes (Veo `raiMediaFilteredReasons`, xAI `respect_moderation`, Runway `SAFETY.*` codes) surface as `notices` when
758
761
  a video is still returned and as a `ContentPolicy` reason when nothing is.
@@ -873,11 +876,12 @@ for await (const event of ai.speech.stream({ model, text: "Hello from OpenCode."
873
876
  ## Transcription
874
877
 
875
878
  Transcription (speech-to-text) is the one modality whose providers use every route kind: OpenAI and Gemini stream,
876
- Deepgram answers inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream` work on all of
877
- them; `Transcription.start` / `resume` return a `Generation` on queued routes and fail with `UnsupportedOperation`
878
- elsewhere. Models come from `.transcription(...)` selectors on the `OpenAI`, `Google`, `Deepgram`, and `AssemblyAI`
879
- facades. Common fields (`language`, `prompt`, `timestamps: "none" | "segment" | "word"`, `diarize`, `speakers`) lower
880
- natively or fail with a typed `AIError` before any network call; a route may return more than asked.
879
+ Deepgram and ElevenLabs answer inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream`
880
+ work on all of them; `Transcription.start` / `resume` return a `Generation` on queued routes and fail with
881
+ `UnsupportedOperation` elsewhere. Models come from `.transcription(...)` selectors on the `OpenAI`, `Google`,
882
+ `Deepgram`, `ElevenLabs`, and `AssemblyAI` facades. Common fields (`language`, `prompt`,
883
+ `timestamps: "none" | "segment" | "word"`, `diarize`, `speakers`) lower natively or fail with a typed `AIError` before
884
+ any network call; a route may return more than asked.
881
885
 
882
886
  ```ts
883
887
  import { Console, Effect, Stream } from "effect"
@@ -889,7 +893,7 @@ const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
889
893
  const program = Effect.gen(function* () {
890
894
  const audio = yield* Media.file("./call.mp3")
891
895
 
892
- // Speaker-labelled segments; labels are provider-native strings ("A", "0", "spk:0").
896
+ // Speaker-labelled segments; labels are provider-native strings ("A", "0", "spk:0", "speaker_0").
893
897
  const response = yield* Transcription.generate({
894
898
  model: Deepgram.configure({ apiKey }).transcription("nova-3"),
895
899
  audio,
@@ -899,7 +903,7 @@ const program = Effect.gen(function* () {
899
903
  response.text // "Hello from OpenCode."
900
904
  response.segments // [{ text, startSeconds, endSeconds, speaker: "0" }]
901
905
  response.words // [{ text, startSeconds, endSeconds, speaker, confidence }]
902
- response.language // the provider's own value, lowercased ("en", "english", "en_us")
906
+ response.language // the provider's own value, lowercased ("en", "eng", "english", "en_us")
903
907
 
904
908
  // Text deltas as the model transcribes, then one finish carrying the whole transcript.
905
909
  yield* Transcription.stream({ model: openai.transcription("gpt-4o-mini-transcribe"), audio }).pipe(
@@ -923,7 +927,12 @@ Provider notes:
923
927
  - **OpenAI** takes inline audio only; `diarize` needs `gpt-4o-transcribe-diarize`, timestamps need `whisper-1`, and `whisper-1` does not stream.
924
928
  - **Gemini** needs a transcribe model (`gemini-3.5-transcribe`); `prompt` and `speakers` fail typed.
925
929
  - **Deepgram** detects the language unless `language` is set; vocabulary goes in `providerOptions.keyterm`.
926
- - **AssemblyAI** uploads inline audio before submitting and is the only route that accepts `speakers`.
930
+ - **ElevenLabs** (`scribe_v2`) uploads inline audio as the multipart `file` and sends a URL as `source_url`. Words
931
+ always carry timestamps, and segments are speaker turns, so `diarize`, `timestamps: "segment"`, or `speakers` turns
932
+ on diarization. `speakers` is an upper bound (`num_speakers`); `prompt` fails typed (vocabulary goes in
933
+ `providerOptions.keyterms`), as do webhook delivery and per-channel output (`use_multi_channel` without
934
+ `multichannel_output_style: "combined"`).
935
+ - **AssemblyAI** uploads inline audio before submitting and treats `speakers` as the exact speaker count.
927
936
 
928
937
  The promise client mirrors the Effect API:
929
938
 
@@ -72,8 +72,8 @@ export declare class Generation<Response> {
72
72
  */
73
73
  events(options?: AwaitOptions): Stream.Stream<Event, AIError>;
74
74
  private event;
75
- private timeoutError;
76
75
  private poll;
77
76
  private schedule;
78
77
  }
78
+ /** `events` followed by the expanded result, with the result fetch bounded by the same `poll.timeout` deadline. */
79
79
  export declare const resultEvents: <Response, A>(generation: Generation<Response>, expand: (response: Response) => ReadonlyArray<A>, options?: AwaitOptions) => Stream.Stream<Observation | A, AIError>;
@@ -56,7 +56,7 @@ export class Generation {
56
56
  const settled = this.terminal ? Effect.succeed(this) : this.poll(options?.poll);
57
57
  return settled.pipe(
58
58
  // Non-completed terminal states also go through `result` so the route can surface its provider failure body.
59
- Effect.flatMap((generation) => generation.result()), Effect.timeoutOrElse({ duration: timeout, orElse: () => this.timeoutError(timeout) }));
59
+ Effect.flatMap((generation) => generation.result()), Effect.timeoutOrElse({ duration: timeout, orElse: () => timeoutError(this.id, timeout) }));
60
60
  }
61
61
  cancel() {
62
62
  return this.route.cancel ?? Effect.void;
@@ -73,14 +73,7 @@ export class Generation {
73
73
  const timeout = Duration.fromInputUnsafe(options?.poll?.timeout ?? DEFAULT_POLL_TIMEOUT);
74
74
  return Stream.unwrap(Clock.currentTimeMillis.pipe(Effect.map((start) => {
75
75
  const deadline = start + Duration.toMillis(timeout);
76
- // Fail before polling once the deadline has passed: a fast status request could otherwise win the zero-budget
77
- // race and schedule another zero-delay poll.
78
- const refresh = Clock.currentTimeMillis.pipe(Effect.flatMap((now) => now >= deadline
79
- ? this.timeoutError(timeout)
80
- : this.refresh().pipe(Effect.timeoutOrElse({
81
- duration: Duration.millis(deadline - now),
82
- orElse: () => this.timeoutError(timeout),
83
- }))));
76
+ const refresh = within(this.refresh(), this.id, timeout, deadline);
84
77
  const schedule = this.schedule(options?.poll).pipe(Schedule.modifyDelay((meta) => Effect.succeed(Duration.min(meta.duration, Duration.millis(Math.max(0, deadline - meta.now))))));
85
78
  return Stream.fromEffectSchedule(refresh, schedule).pipe(Stream.takeUntil((generation) => generation.terminal), Stream.map((generation) => generation.event()));
86
79
  })));
@@ -92,14 +85,6 @@ export class Generation {
92
85
  return { type: "generation-queued", id: this.id, position: this.position };
93
86
  return { type: "generation-progress", id: this.id, progress: this.progress };
94
87
  }
95
- timeoutError(timeout) {
96
- return new AIError({
97
- reason: new TimeoutError({
98
- message: `Generation ${this.id} did not finish within ${Duration.format(timeout)}`,
99
- timeoutMs: Duration.toMillis(timeout),
100
- }),
101
- });
102
- }
103
88
  poll(poll) {
104
89
  return this.refresh().pipe(Effect.repeat({ schedule: this.schedule(poll), until: (generation) => generation.terminal }));
105
90
  }
@@ -107,4 +92,24 @@ export class Generation {
107
92
  return Schedule.spaced(poll?.interval ?? DEFAULT_POLL_INTERVAL);
108
93
  }
109
94
  }
110
- export const resultEvents = (generation, expand, options) => generation.events(options).pipe(Stream.filter((event) => event.type !== "generation-finished"), Stream.concat(Stream.fromIterableEffect(Effect.map(generation.result(), expand))));
95
+ /** `events` followed by the expanded result, with the result fetch bounded by the same `poll.timeout` deadline. */
96
+ export const resultEvents = (generation, expand, options) => {
97
+ const timeout = Duration.fromInputUnsafe(options?.poll?.timeout ?? DEFAULT_POLL_TIMEOUT);
98
+ return Stream.unwrap(Clock.currentTimeMillis.pipe(Effect.map((start) => generation.events(options).pipe(Stream.filter((event) => event.type !== "generation-finished"), Stream.concat(Stream.fromIterableEffect(within(generation.result(), generation.id, timeout, start + Duration.toMillis(timeout)).pipe(Effect.map(expand))))))));
99
+ };
100
+ /**
101
+ * Run `effect` within the time left until `deadline`. Fails before starting once the deadline has passed: a fast
102
+ * request could otherwise win the zero-budget race and schedule another zero-delay poll.
103
+ */
104
+ const within = (effect, id, timeout, deadline) => Clock.currentTimeMillis.pipe(Effect.flatMap((now) => now >= deadline
105
+ ? Effect.fail(timeoutError(id, timeout))
106
+ : effect.pipe(Effect.timeoutOrElse({
107
+ duration: Duration.millis(deadline - now),
108
+ orElse: () => Effect.fail(timeoutError(id, timeout)),
109
+ }))));
110
+ const timeoutError = (id, timeout) => new AIError({
111
+ reason: new TimeoutError({
112
+ message: `Generation ${id} did not finish within ${Duration.format(timeout)}`,
113
+ timeoutMs: Duration.toMillis(timeout),
114
+ }),
115
+ });
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ export { ImageClient } from "./image-client.js";
4
4
  export { Auth } from "./route/auth.js";
5
5
  export { Provider } from "./provider.js";
6
6
  export { ProviderPackage } from "./provider-package.js";
7
- export { isContextOverflow, isContextOverflowFailure } from "./provider-error.js";
7
+ export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
8
8
  export type { RouteLanguageModelInput, RouteRoutedLanguageModelInput, Interface as LLMClientShape, LLMClientService, } from "./route/client.js";
9
9
  export * from "./schema/index.js";
10
10
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse, ImageSize, } from "./image.js";
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ export { ImageClient } from "./image-client.js";
4
4
  export { Auth } from "./route/auth.js";
5
5
  export { Provider } from "./provider.js";
6
6
  export { ProviderPackage } from "./provider-package.js";
7
- export { isContextOverflow, isContextOverflowFailure } from "./provider-error.js";
7
+ export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./provider-error.js";
8
8
  export * from "./schema/index.js";
9
9
  export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageRequest, ImageResponse, ImageSize, } from "./image.js";
10
10
  export { Image } from "./image.js";
@@ -5,6 +5,7 @@ import { mergeJsonRecords } from "../schema/index.js";
5
5
  import { TranscriptionModel, TranscriptionResponse } from "../transcription.js";
6
6
  import { ProviderShared } from "./shared.js";
7
7
  import { MediaInput } from "./utils/media-input.js";
8
+ import { SpeakerTurns } from "./utils/speaker-turns.js";
8
9
  const route = MediaProtocol.identity({ id: "deepgram-transcription", name: "Deepgram", provider: "deepgram" });
9
10
  export const DEFAULT_BASE_URL = "https://api.deepgram.com";
10
11
  export const PATH = "/v1/listen";
@@ -63,15 +64,6 @@ const fromRequest = Effect.fn("DeepgramTranscription.fromRequest")(function* (re
63
64
  const decodeListen = route.decodeJson(ListenResponse);
64
65
  const speaker = (value) => (value === undefined ? undefined : String(value));
65
66
  const wordText = (word) => word.punctuated_word ?? word.word;
66
- // Utterances split on pauses, not speakers: the v2 diarizer labels a whole utterance with one speaker even when its
67
- // words change speaker, so segments split each utterance at speaker changes.
68
- const speakerTurns = (words) => words.reduce((turns, word) => {
69
- const last = turns.at(-1);
70
- if (last === undefined || last[0].speaker !== word.speaker)
71
- return [...turns, [word]];
72
- last.push(word);
73
- return turns;
74
- }, []);
75
67
  const decodeResponse = Effect.fn("DeepgramTranscription.decodeResponse")(function* (response) {
76
68
  const output = yield* decodeListen(response);
77
69
  const channel = output.value.results.channels[0];
@@ -82,6 +74,8 @@ const decodeResponse = Effect.fn("DeepgramTranscription.decodeResponse")(functio
82
74
  const requestID = output.value.metadata?.request_id;
83
75
  return new TranscriptionResponse({
84
76
  text: alternative.transcript,
77
+ // Utterances split on pauses, not speakers: the v2 diarizer labels a whole utterance with one speaker even when
78
+ // its words change speaker, so segments split each utterance at speaker changes.
85
79
  segments: output.value.results.utterances?.flatMap((utterance) => utterance.words === undefined || utterance.words.length === 0
86
80
  ? [
87
81
  {
@@ -91,7 +85,7 @@ const decodeResponse = Effect.fn("DeepgramTranscription.decodeResponse")(functio
91
85
  speaker: speaker(utterance.speaker),
92
86
  },
93
87
  ]
94
- : speakerTurns(utterance.words).map((turn) => ({
88
+ : SpeakerTurns.group(utterance.words, (word) => word.speaker).map((turn) => ({
95
89
  text: turn.map(wordText).join(" "),
96
90
  startSeconds: turn[0].start,
97
91
  endSeconds: turn[turn.length - 1].end,
@@ -0,0 +1,28 @@
1
+ import { MediaProtocol } from "../route/media-protocol.js";
2
+ import { MediaRoute } from "../route/media.js";
3
+ import { type OpenString } from "../schema/index.js";
4
+ import { TranscriptionModel, TranscriptionResponse, type TranscriptionRequestFor } from "../transcription.js";
5
+ export declare const DEFAULT_BASE_URL = "https://api.elevenlabs.io";
6
+ export declare const PATH = "/v1/speech-to-text";
7
+ export type ElevenLabsTranscriptionOptions = {
8
+ readonly tag_audio_events?: boolean;
9
+ readonly timestamps_granularity?: OpenString<"none" | "word" | "character">;
10
+ readonly diarization_threshold?: number;
11
+ readonly file_format?: OpenString<"pcm_s16le_16" | "other">;
12
+ readonly temperature?: number;
13
+ readonly seed?: number;
14
+ readonly keyterms?: ReadonlyArray<string>;
15
+ readonly no_verbatim?: boolean;
16
+ readonly detect_speaker_roles?: boolean;
17
+ readonly use_speaker_library?: boolean;
18
+ readonly entity_detection?: string | ReadonlyArray<string>;
19
+ readonly entity_redaction?: string | ReadonlyArray<string>;
20
+ readonly entity_redaction_mode?: OpenString<"redacted" | "entity_type" | "enumerated_entity_type">;
21
+ } & Record<string, unknown>;
22
+ export type Request = TranscriptionRequestFor<ElevenLabsTranscriptionOptions>;
23
+ export declare const protocol: MediaProtocol.Inline<Request, TranscriptionResponse>;
24
+ export declare const model: (input: MediaRoute.ModelInput) => TranscriptionModel<ElevenLabsTranscriptionOptions>;
25
+ export declare const ElevenLabsTranscription: {
26
+ readonly protocol: MediaProtocol.Inline<Request, TranscriptionResponse>;
27
+ readonly model: (input: MediaRoute.ModelInput) => TranscriptionModel<ElevenLabsTranscriptionOptions>;
28
+ };
@@ -0,0 +1,137 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { MediaProtocol } from "../route/media-protocol.js";
3
+ import { MediaRoute } from "../route/media.js";
4
+ import { mergeJsonRecords } from "../schema/index.js";
5
+ import { TranscriptionModel, TranscriptionResponse } from "../transcription.js";
6
+ import { mediaTypeExtension } from "../utils/media-type.js";
7
+ import { ProviderShared, optionalNull } from "./shared.js";
8
+ import { MediaInput } from "./utils/media-input.js";
9
+ import { SpeakerTurns } from "./utils/speaker-turns.js";
10
+ const route = MediaProtocol.identity({
11
+ id: "elevenlabs-transcription",
12
+ name: "ElevenLabs Transcription",
13
+ provider: "elevenlabs",
14
+ });
15
+ export const DEFAULT_BASE_URL = "https://api.elevenlabs.io";
16
+ export const PATH = "/v1/speech-to-text";
17
+ // ---------------------------------------------------------------------------
18
+ // 2. Response schema
19
+ // ---------------------------------------------------------------------------
20
+ /** `type` is `word`, `spacing` (the whitespace between words), or `audio_event` (`(laughter)`). */
21
+ const Token = Schema.Struct({
22
+ text: Schema.String,
23
+ type: Schema.String,
24
+ start: optionalNull(Schema.Number),
25
+ end: optionalNull(Schema.Number),
26
+ speaker_id: optionalNull(Schema.String),
27
+ logprob: optionalNull(Schema.Number),
28
+ });
29
+ const Transcript = Schema.Struct({
30
+ language_code: optionalNull(Schema.String),
31
+ text: Schema.String,
32
+ words: optionalNull(Schema.Array(Token)),
33
+ transcription_id: optionalNull(Schema.String),
34
+ audio_duration_secs: optionalNull(Schema.Number),
35
+ });
36
+ // ---------------------------------------------------------------------------
37
+ // 5. Request body construction
38
+ // ---------------------------------------------------------------------------
39
+ /** Speaker turns are the only segments ElevenLabs can produce, and `num_speakers` only applies to diarization. */
40
+ const diarizes = (request) => request.diarize === true || request.timestamps === "segment" || request.speakers !== undefined;
41
+ const RESERVED_FORM_FIELDS = new Set([
42
+ "file",
43
+ "cloud_storage_url",
44
+ "source_url",
45
+ "model_id",
46
+ "language_code",
47
+ "diarize",
48
+ "num_speakers",
49
+ ]);
50
+ const validate = (request, overlay) => {
51
+ // Webhook requests return 202 with no transcript; the result arrives at a configured webhook instead.
52
+ if (overlay.webhook === true)
53
+ return Effect.fail(route.unsupported("transcription.webhook", `${route.name} does not deliver to webhooks`));
54
+ // Separate multichannel output replaces the transcript with one transcript per channel.
55
+ if (overlay.use_multi_channel === true && overlay.multichannel_output_style !== "combined")
56
+ return Effect.fail(route.unsupported("transcription.multichannel", `${route.name} returns a single transcript; set multichannel_output_style: "combined" to merge channels`));
57
+ if (overlay.timestamps_granularity === "none" && (request.timestamps === "word" || diarizes(request)))
58
+ return Effect.fail(route.unsupported("media.timestamps", `${route.name} cannot return word timestamps or speaker turns with timestamps_granularity: "none"`));
59
+ return Effect.void;
60
+ };
61
+ const fromRequest = Effect.fn("ElevenLabsTranscription.fromRequest")(function* (request) {
62
+ const overlay = mergeJsonRecords(request.providerOptions, request.http?.body) ?? {};
63
+ yield* validate(request, overlay);
64
+ const form = new FormData();
65
+ const url = ProviderShared.mediaUrl(request.audio);
66
+ if (url === undefined) {
67
+ const extension = mediaTypeExtension(request.audio.mediaType);
68
+ const audio = yield* MediaInput.inlineBytes(route.id, request.audio);
69
+ form.append("file", MediaInput.blob(audio, request.audio.mediaType), extension === undefined ? "audio" : `audio.${extension}`);
70
+ }
71
+ MediaInput.appendFields(form, {
72
+ model_id: request.model.id,
73
+ // `cloud_storage_url` is deprecated in favor of `source_url`, which accepts any hosted audio or video URL.
74
+ source_url: url,
75
+ language_code: request.language,
76
+ diarize: diarizes(request) ? true : undefined,
77
+ num_speakers: request.speakers,
78
+ }, { overlay, reserved: RESERVED_FORM_FIELDS, repeatArrays: "key" });
79
+ return MediaProtocol.multipart(form);
80
+ });
81
+ // ---------------------------------------------------------------------------
82
+ // 6. Response decoding
83
+ // ---------------------------------------------------------------------------
84
+ const decodeTranscript = route.decodeJson(Transcript);
85
+ const isTimedWord = (token) => token.type === "word" && typeof token.start === "number" && typeof token.end === "number";
86
+ /** Turn text keeps the provider's own spacing tokens, so languages written without spaces are not re-spaced. */
87
+ const speakerTurns = (tokens) => SpeakerTurns.group(tokens.filter((token) => token.type === "word" || token.type === "spacing"), (token) => token.speaker_id).flatMap((turn) => {
88
+ const words = turn.filter(isTimedWord);
89
+ if (words.length === 0)
90
+ return [];
91
+ return [
92
+ {
93
+ text: turn
94
+ .map((token) => token.text)
95
+ .join("")
96
+ .trim(),
97
+ startSeconds: words[0].start,
98
+ endSeconds: words[words.length - 1].end,
99
+ speaker: turn[0].speaker_id ?? undefined,
100
+ },
101
+ ];
102
+ });
103
+ const decodeResponse = Effect.fn("ElevenLabsTranscription.decodeResponse")(function* (response, context) {
104
+ const output = yield* decodeTranscript(response);
105
+ const transcript = output.value;
106
+ const tokens = transcript.words ?? [];
107
+ const duration = transcript.audio_duration_secs ?? undefined;
108
+ const transcriptionID = transcript.transcription_id ?? undefined;
109
+ return new TranscriptionResponse({
110
+ text: transcript.text,
111
+ segments: diarizes(context.request) ? speakerTurns(tokens) : undefined,
112
+ words: tokens.filter(isTimedWord).map((word) => ({
113
+ text: word.text,
114
+ startSeconds: word.start,
115
+ endSeconds: word.end,
116
+ speaker: word.speaker_id ?? undefined,
117
+ confidence: typeof word.logprob === "number" ? Math.exp(word.logprob) : undefined,
118
+ })),
119
+ language: transcript.language_code?.toLowerCase(),
120
+ durationSeconds: duration,
121
+ usage: duration === undefined ? undefined : { type: "seconds", seconds: duration },
122
+ providerMetadata: transcriptionID === undefined ? undefined : { elevenlabs: { transcriptionId: transcriptionID } },
123
+ });
124
+ });
125
+ // ---------------------------------------------------------------------------
126
+ // 7. Protocol and route
127
+ // ---------------------------------------------------------------------------
128
+ export const protocol = MediaProtocol.inline(route, {
129
+ unsupported: ["prompt"],
130
+ body: { from: fromRequest },
131
+ response: { decode: decodeResponse },
132
+ });
133
+ export const model = (input) => TranscriptionModel.fromRoute({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input);
134
+ export const ElevenLabsTranscription = {
135
+ protocol,
136
+ model,
137
+ };
@@ -118,7 +118,7 @@ const fromRequest = Effect.fn("OpenAITranscription.fromRequest")(function* (requ
118
118
  }, {
119
119
  overlay: mergeJsonRecords(request.providerOptions, request.http?.body),
120
120
  reserved: RESERVED_FORM_FIELDS,
121
- repeatArrays: true,
121
+ repeatArrays: "key[]",
122
122
  });
123
123
  return MediaProtocol.multipart(form);
124
124
  });
@@ -21,12 +21,13 @@ export declare const imageOutput: (invalid: (message: string, cause?: unknown) =
21
21
  readonly url?: string | null;
22
22
  }, mediaType: string | undefined, options?: Media.AssetOptions) => Effect.Effect<Media.Asset, AIError, never>;
23
23
  /**
24
- * Append multipart text fields: strings as-is, other values as JSON, or arrays as repeated `key[]` parts with
25
- * `repeatArrays`. `overlay` keys in `reserved` are dropped so `http.body` cannot replace route-owned fields.
24
+ * Append multipart text fields: strings as-is, other values as JSON, or scalar arrays as one part per item with
25
+ * `repeatArrays`, named `key[]` or `key`. `overlay` keys in `reserved` are dropped so `http.body` cannot replace
26
+ * route-owned fields.
26
27
  */
27
28
  export declare const appendFields: (form: FormData, fields: Record<string, unknown>, options: {
28
29
  readonly overlay?: Record<string, unknown>;
29
30
  readonly reserved: ReadonlySet<string>;
30
- readonly repeatArrays?: true;
31
+ readonly repeatArrays?: "key[]" | "key";
31
32
  }) => void;
32
33
  export * as MediaInput from "./media-input.js";
@@ -43,14 +43,15 @@ export const imageOutput = (invalid, label, item, mediaType, options) => {
43
43
  return Effect.fail(invalid(`${label} has neither image data nor a URL`));
44
44
  };
45
45
  /**
46
- * Append multipart text fields: strings as-is, other values as JSON, or arrays as repeated `key[]` parts with
47
- * `repeatArrays`. `overlay` keys in `reserved` are dropped so `http.body` cannot replace route-owned fields.
46
+ * Append multipart text fields: strings as-is, other values as JSON, or scalar arrays as one part per item with
47
+ * `repeatArrays`, named `key[]` or `key`. `overlay` keys in `reserved` are dropped so `http.body` cannot replace
48
+ * route-owned fields.
48
49
  */
49
50
  export const appendFields = (form, fields, options) => {
50
51
  const overlay = Object.entries(options.overlay ?? {}).filter(([key]) => !options.reserved.has(key));
51
52
  Object.entries(mergeJsonRecords(fields, Object.fromEntries(overlay)) ?? {}).forEach(([key, value]) => {
52
- if (Array.isArray(value) && options.repeatArrays)
53
- return value.forEach((item) => form.append(`${key}[]`, String(item)));
53
+ if (Array.isArray(value) && value.every(isScalar) && options.repeatArrays !== undefined)
54
+ return value.forEach((item) => form.append(options.repeatArrays === "key[]" ? `${key}[]` : key, String(item)));
54
55
  form.append(key, typeof value === "string" ? value : encodeJson(value));
55
56
  });
56
57
  };
@@ -0,0 +1,3 @@
1
+ /** Split an ordered token list into runs of consecutive tokens with the same speaker. */
2
+ export declare const group: <Item>(items: ReadonlyArray<Item>, speaker: (item: Item) => unknown) => Item[][];
3
+ export * as SpeakerTurns from "./speaker-turns.js";
@@ -0,0 +1,9 @@
1
+ /** Split an ordered token list into runs of consecutive tokens with the same speaker. */
2
+ export const group = (items, speaker) => items.reduce((turns, item) => {
3
+ const last = turns.at(-1);
4
+ if (last === undefined || speaker(last[0]) !== speaker(item))
5
+ return [...turns, [item]];
6
+ last.push(item);
7
+ return turns;
8
+ }, []);
9
+ export * as SpeakerTurns from "./speaker-turns.js";
@@ -2,6 +2,11 @@ import { AIError, type HttpContext, type HttpRateLimitDetails } from "./schema/i
2
2
  export declare const isContextOverflow: (message: string) => boolean;
3
3
  export declare const isPayloadTooLarge: (message: string) => boolean;
4
4
  export declare const isContextOverflowFailure: (failure: unknown) => boolean;
5
+ /**
6
+ * Whether a failed call may succeed when sent again: rate limits, provider-side failures, transport failures that did
7
+ * not deliver an accepted write, and unrecognized failures. Callers decide which calls are safe to repeat.
8
+ */
9
+ export declare const isRetryable: (error: AIError) => boolean;
5
10
  export interface ProviderFailure {
6
11
  readonly message: string;
7
12
  readonly status?: number | undefined;
@@ -37,6 +37,46 @@ export const isPayloadTooLarge = (message) => payloadPatterns.some((pattern) =>
37
37
  export const isContextOverflowFailure = (failure) => failure instanceof AIError
38
38
  ? failure.reason._tag === "InvalidRequest" && failure.reason.classification === "context-overflow"
39
39
  : Schema.is(ProviderErrorEvent)(failure) && failure.classification === "context-overflow";
40
+ /**
41
+ * Whether a failed call may succeed when sent again: rate limits, provider-side failures, transport failures that did
42
+ * not deliver an accepted write, and unrecognized failures. Callers decide which calls are safe to repeat.
43
+ */
44
+ export const isRetryable = (error) => {
45
+ const override = error.reason.http?.headers["x-should-retry"];
46
+ if (override === "true")
47
+ return true;
48
+ if (override === "false")
49
+ return false;
50
+ switch (error.reason._tag) {
51
+ case "RateLimit":
52
+ case "ProviderInternal":
53
+ return true;
54
+ // A WebSocket acknowledgment marks delivery accepted before model output may exist.
55
+ // Read failures can still recover; the caller chooses retry versus continuation from durable output.
56
+ case "Transport":
57
+ return (error.reason.delivery !== "rejected" &&
58
+ (error.reason.delivery !== "accepted" || error.reason.operation === "read"));
59
+ case "InvalidProviderOutput":
60
+ return error.reason.classification === "incomplete-stream";
61
+ // Unrecognized failures retry: classification records affirmative
62
+ // deterministic evidence, and transient failures are exactly the ones
63
+ // that arrive in shapes no classifier anticipates.
64
+ case "UnknownProvider":
65
+ return true;
66
+ case "Authentication":
67
+ case "QuotaExceeded":
68
+ case "ContentPolicy":
69
+ case "InvalidRequest":
70
+ case "UnsupportedOperation":
71
+ case "NoRoute":
72
+ case "Timeout":
73
+ return false;
74
+ default: {
75
+ const exhaustive = error.reason;
76
+ return exhaustive;
77
+ }
78
+ }
79
+ };
40
80
  const decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
41
81
  // OpenCode Zen reports account caps as typed 429/402 errors that are not throttles.
42
82
  const QUOTA_CODES = new Set([
@@ -1,6 +1,7 @@
1
1
  import type { ProviderAuthOption } from "../route/auth-options.js";
2
2
  import { type HttpOptions, type ModelID } from "../schema/index.js";
3
3
  export type { ElevenLabsOutputFormat, ElevenLabsSpeechOptions } from "../protocols/elevenlabs-speech.js";
4
+ export type { ElevenLabsTranscriptionOptions } from "../protocols/elevenlabs-transcription.js";
4
5
  export declare const id: string & import("effect/Brand").Brand<"AI.ProviderID">;
5
6
  export type Config = ProviderAuthOption<"optional"> & {
6
7
  readonly baseURL?: string;
@@ -10,15 +11,19 @@ export type Config = ProviderAuthOption<"optional"> & {
10
11
  export declare const configure: (input?: Config) => {
11
12
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
12
13
  speech: (modelID: string | ModelID) => import("../speech.js").SpeechModel<import("../protocols/elevenlabs-speech.js").ElevenLabsSpeechOptions>;
14
+ transcription: (modelID: string | ModelID) => import("../transcription.js").TranscriptionModel<import("../protocols/elevenlabs-transcription.js").ElevenLabsTranscriptionOptions>;
13
15
  configure: (input?: Config) => /*elided*/ any;
14
16
  };
15
17
  export declare const provider: {
16
18
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
17
19
  speech: (modelID: string | ModelID) => import("../speech.js").SpeechModel<import("../protocols/elevenlabs-speech.js").ElevenLabsSpeechOptions>;
20
+ transcription: (modelID: string | ModelID) => import("../transcription.js").TranscriptionModel<import("../protocols/elevenlabs-transcription.js").ElevenLabsTranscriptionOptions>;
18
21
  configure: (input?: Config) => {
19
22
  id: string & import("effect/Brand").Brand<"AI.ProviderID">;
20
23
  speech: (modelID: string | ModelID) => import("../speech.js").SpeechModel<import("../protocols/elevenlabs-speech.js").ElevenLabsSpeechOptions>;
24
+ transcription: (modelID: string | ModelID) => import("../transcription.js").TranscriptionModel<import("../protocols/elevenlabs-transcription.js").ElevenLabsTranscriptionOptions>;
21
25
  configure: /*elided*/ any;
22
26
  };
23
27
  };
24
28
  export declare const speech: (modelID: string | ModelID) => import("../speech.js").SpeechModel<import("../protocols/elevenlabs-speech.js").ElevenLabsSpeechOptions>;
29
+ export declare const transcription: (modelID: string | ModelID) => import("../transcription.js").TranscriptionModel<import("../protocols/elevenlabs-transcription.js").ElevenLabsTranscriptionOptions>;
@@ -2,6 +2,7 @@ import { Auth } from "../route/auth.js";
2
2
  import { MediaRoute } from "../route/media.js";
3
3
  import { ProviderID } from "../schema/index.js";
4
4
  import { ElevenLabsSpeech } from "../protocols/elevenlabs-speech.js";
5
+ import { ElevenLabsTranscription } from "../protocols/elevenlabs-transcription.js";
5
6
  export const id = ProviderID.make("elevenlabs");
6
7
  const auth = (options) => {
7
8
  if ("auth" in options && options.auth)
@@ -13,11 +14,14 @@ const auth = (options) => {
13
14
  export const configure = (input = {}) => {
14
15
  const media = MediaRoute.deployment(input, auth(input));
15
16
  const speech = (modelID) => ElevenLabsSpeech.model({ ...media, id: modelID });
17
+ const transcription = (modelID) => ElevenLabsTranscription.model({ ...media, id: modelID });
16
18
  return {
17
19
  id,
18
20
  speech,
21
+ transcription,
19
22
  configure,
20
23
  };
21
24
  };
22
25
  export const provider = configure();
23
26
  export const speech = provider.speech;
27
+ export const transcription = provider.transcription;
@@ -1,4 +1,4 @@
1
- import { Effect, Schema, Stream } from "effect";
1
+ import { Duration, Effect, Schedule, Schema, Stream } from "effect";
2
2
  import { Headers, HttpClientRequest } from "effect/unstable/http";
3
3
  import { Auth } from "./auth.js";
4
4
  import { Endpoint } from "./endpoint.js";
@@ -6,6 +6,7 @@ import { RequestExecutorService } from "./executor-service.js";
6
6
  import { RequestExecutor } from "./executor.js";
7
7
  import { MediaProtocol } from "./media-protocol.js";
8
8
  import { Generation, isTerminal } from "../generation.js";
9
+ import { isRetryable } from "../provider-error.js";
9
10
  import { AIError, AIErrorReason, HttpOptions, InvalidRequestError, ProviderID, UnsupportedOperationError, mergeHttpOptions, } from "../schema/index.js";
10
11
  import { encodeJson } from "../utils/json.js";
11
12
  import { sanitizeSurrogates } from "../utils/sanitize.js";
@@ -35,6 +36,19 @@ export const inline = (input) => {
35
36
  }),
36
37
  };
37
38
  };
39
+ const READ_RETRY_MAX_DELAY = Duration.seconds(30);
40
+ /**
41
+ * Status and result reads retry transient failures; `start` and `cancel` never do. Gaps grow exponentially from 1s,
42
+ * jittered, up to 30s each, for at most 8 retries (about two minutes when every attempt fails), so a direct
43
+ * `Generation.result()` stays bounded; `await` and `events` also cut retries off at `poll.timeout`. A provider
44
+ * `retryAfterMs` raises the gap, still capped at 30s.
45
+ */
46
+ const READ_RETRY = Schedule.max([
47
+ Schedule.min([Schedule.exponential("1 second"), Schedule.spaced(READ_RETRY_MAX_DELAY)]),
48
+ Schedule.recurs(8),
49
+ ]).pipe(Schedule.jittered, Schedule.setInputType(), Schedule.modifyDelay(({ input, duration }) => Effect.succeed(Duration.min(input.reason._tag === "RateLimit" || input.reason._tag === "ProviderInternal"
50
+ ? Duration.max(duration, Duration.millis(input.reason.retryAfterMs ?? 0))
51
+ : duration, READ_RETRY_MAX_DELAY))));
38
52
  /**
39
53
  * Compose a queued media protocol the same way, adding `start`/`resume` handles whose polls reuse the route's auth,
40
54
  * deployment headers, and (for `start`) the request's `http` overlay. The token is decoded once at the boundary and
@@ -48,9 +62,9 @@ export const queued = (input) => {
48
62
  const encodeToken = Schema.encodeSync(protocol.token);
49
63
  const generationRoute = (token, http, execute) => {
50
64
  const materialize = (asset) => asset.materialize().pipe(Effect.provideService(RequestExecutorService, { execute }));
51
- const poll = (operation) => transport
52
- .call("GET", operation.path(token), http, execute)
53
- .pipe(Effect.flatMap((sent) => operation.decode(sent.response, { token, auth: sent.auth, materialize })));
65
+ // Only the GET exchange retries: a decoded terminal failure (`output.ended`) can be a `ProviderInternal` too, and
66
+ // re-reading it would spin until the caller's deadline.
67
+ const poll = (operation) => transport.call("GET", operation.path(token), http, execute).pipe(Effect.retry({ schedule: READ_RETRY, while: isRetryable }), Effect.flatMap((sent) => operation.decode(sent.response, { token, auth: sent.auth, materialize })));
54
68
  const status = poll(protocol.status);
55
69
  const cancel = protocol.cancel;
56
70
  const send = cancel === undefined
@@ -72,7 +72,7 @@ export type TranscriptionRequestInput<Model extends TranscriptionModel = Transcr
72
72
  readonly providerOptions?: NoInfer<TranscriptionModelOptions<Model>>;
73
73
  readonly http?: HttpOptions.Input;
74
74
  };
75
- /** Speaker labels are provider-native (`A`, `0`, `spk:0`, or a known speaker name). */
75
+ /** Speaker labels are provider-native (`A`, `0`, `spk:0`, `speaker_0`, or a known speaker name). */
76
76
  export declare const TranscriptionSegment: Schema.Struct<{
77
77
  readonly text: Schema.String;
78
78
  readonly startSeconds: Schema.Number;
@@ -36,7 +36,7 @@ export class TranscriptionRequest extends Schema.Class("Transcription.Request")(
36
36
  // ---------------------------------------------------------------------------
37
37
  // Response and events
38
38
  // ---------------------------------------------------------------------------
39
- /** Speaker labels are provider-native (`A`, `0`, `spk:0`, or a known speaker name). */
39
+ /** Speaker labels are provider-native (`A`, `0`, `spk:0`, `speaker_0`, or a known speaker name). */
40
40
  export const TranscriptionSegment = Schema.Struct({
41
41
  text: Schema.String,
42
42
  startSeconds: Schema.Number,
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-20215",
3
+ "version": "0.0.0-dev-20217",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -34,7 +34,7 @@
34
34
  "devDependencies": {
35
35
  "@clack/prompts": "1.0.0-alpha.1",
36
36
  "@effect/platform-node": "4.0.0-rc.112",
37
- "@opencode/http-recorder": "0.0.0-dev-20215",
37
+ "@opencode/http-recorder": "0.0.0-dev-20217",
38
38
  "@tsconfig/bun": "1.0.9",
39
39
  "@types/bun": "1.4.0",
40
40
  "@typescript/native-preview": "7.0.0-dev.20251207.1",
@@ -44,7 +44,7 @@
44
44
  "@aws-sdk/credential-providers": "3.1057.0",
45
45
  "@smithy/eventstream-codec": "4.2.14",
46
46
  "@smithy/util-utf8": "4.2.2",
47
- "@opencode/schema": "0.0.0-dev-20215",
47
+ "@opencode/schema": "0.0.0-dev-20217",
48
48
  "aws4fetch": "1.0.20",
49
49
  "effect": "4.0.0-rc.112",
50
50
  "google-auth-library": "10.5.0"