@opencode/ai 0.0.0-dev-1311 → 0.0.0-dev-1312

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 (58) hide show
  1. package/dist/decision.d.ts +4 -3
  2. package/dist/decision.js +3 -2
  3. package/dist/embedding.d.ts +4 -3
  4. package/dist/embedding.js +3 -2
  5. package/dist/experimental/cloudflare-run-extraction.js +1 -2
  6. package/dist/experimental/realtime.d.ts +2 -1
  7. package/dist/experimental/realtime.js +8 -8
  8. package/dist/image.js +1 -1
  9. package/dist/media-model.d.ts +5 -4
  10. package/dist/media-model.js +5 -4
  11. package/dist/media.js +4 -17
  12. package/dist/protocols/open-responses-continuation.js +2 -0
  13. package/dist/protocols/utils/responses-compaction.js +3 -3
  14. package/dist/providers/alibaba.js +2 -3
  15. package/dist/providers/assemblyai.d.ts +2 -4
  16. package/dist/providers/azure.js +5 -11
  17. package/dist/providers/baseten.js +2 -3
  18. package/dist/providers/byteplus.d.ts +2 -4
  19. package/dist/providers/cartesia.d.ts +2 -4
  20. package/dist/providers/cloudflare-ai-gateway.js +3 -3
  21. package/dist/providers/cloudflare-workers-ai.js +2 -3
  22. package/dist/providers/cohere.js +2 -3
  23. package/dist/providers/deepgram.d.ts +2 -4
  24. package/dist/providers/deepinfra.js +2 -3
  25. package/dist/providers/digitalocean.js +3 -5
  26. package/dist/providers/elevenlabs.d.ts +2 -4
  27. package/dist/providers/fireworks.js +2 -3
  28. package/dist/providers/google-vertex.js +6 -2
  29. package/dist/providers/google.js +7 -4
  30. package/dist/providers/openai-compatible.js +3 -5
  31. package/dist/providers/openai.js +4 -10
  32. package/dist/providers/opencode.d.ts +2 -4
  33. package/dist/providers/opencode.js +2 -3
  34. package/dist/providers/openrouter.js +3 -5
  35. package/dist/providers/typesafe-ai.d.ts +2 -4
  36. package/dist/providers/typesafe-ai.js +2 -3
  37. package/dist/providers/vercel-ai-gateway.js +3 -5
  38. package/dist/providers/volcengine.d.ts +2 -4
  39. package/dist/route/decision.d.ts +4 -7
  40. package/dist/route/decision.js +8 -10
  41. package/dist/route/embedding.d.ts +4 -7
  42. package/dist/route/embedding.js +4 -7
  43. package/dist/route/executor-service.d.ts +20 -3
  44. package/dist/route/executor-service.js +72 -2
  45. package/dist/route/executor.d.ts +5 -5
  46. package/dist/route/executor.js +68 -73
  47. package/dist/route/media-protocol.d.ts +2 -1
  48. package/dist/route/media-protocol.js +2 -10
  49. package/dist/route/media.d.ts +6 -8
  50. package/dist/route/media.js +8 -8
  51. package/dist/route/transport/http.d.ts +1 -2
  52. package/dist/route/transport/http.js +5 -28
  53. package/dist/schema/errors.js +2 -1
  54. package/dist/schema/options.d.ts +1 -1
  55. package/dist/speech.js +1 -1
  56. package/dist/transcription.js +1 -1
  57. package/dist/video.js +1 -1
  58. package/package.json +3 -3
@@ -1,9 +1,9 @@
1
- import { Cause, Effect, Layer, Option, Schema, Stream } from "effect";
1
+ import { Cause, Clock, Duration, Effect, Layer, Stream } from "effect";
2
2
  import { FetchHttpClient, Headers, HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse, } from "effect/http";
3
- import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../schema/index.js";
3
+ import { AIError, DEFAULT_CHUNK_TIMEOUT_MS, DEFAULT_HTTP_TIMEOUT_MS, HttpContext, HttpRateLimitDetails, timeoutConfig, TransportError, } from "../schema/index.js";
4
4
  import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js";
5
- import { composeMiddleware, CurrentMiddleware, CurrentTls, headerDetails, responseHttp, Service, } from "./executor-service.js";
6
- export { composeMiddleware, CurrentMiddleware, CurrentTls, responseHttp, Service, withMiddleware, } from "./executor-service.js";
5
+ import { composeMiddleware, CurrentMiddleware, CurrentTimeout, CurrentTls, headerDetails, httpError, responseStream, rootCause, Service, } from "./executor-service.js";
6
+ export { composeMiddleware, CurrentMiddleware, CurrentTimeout, CurrentTls, responseBytes, responseHttp, responseStream, responseText, Service, withMiddleware, } from "./executor-service.js";
7
7
  const normalizedHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
8
8
  const clampRetryAfterMs = (millis) => Math.min(Number.MAX_SAFE_INTEGER, Math.max(0, Math.ceil(millis)));
9
9
  const retryAfterMs = (headers) => {
@@ -83,7 +83,7 @@ const statusError = (response) => Effect.gen(function* () {
83
83
  status: response.status,
84
84
  responseHeaders: headerDetails(response.headers),
85
85
  responseBody: result._tag === "Success" ? result.success : undefined,
86
- cause: result._tag === "Failure" ? (result.failure.cause ?? result.failure) : undefined,
86
+ cause: result._tag === "Failure" ? rootCause(result.failure) : undefined,
87
87
  });
88
88
  });
89
89
  /** Preserve HTTP diagnostics for executor and externally captured failures alike. */
@@ -106,87 +106,78 @@ export const httpFailure = (input) => {
106
106
  }),
107
107
  });
108
108
  };
109
- const NativeTransportFailure = Schema.Struct({
110
- message: Schema.String,
111
- code: Schema.optionalKey(Schema.String),
112
- cause: Schema.optionalKey(Schema.Unknown),
109
+ const timeoutDuration = (value, fallback = DEFAULT_HTTP_TIMEOUT_MS) => value === false ? Duration.infinity : Duration.millis(value ?? fallback);
110
+ const timeoutError = (url, operation, message, http) => new AIError({
111
+ reason: new TransportError({
112
+ message,
113
+ transport: "http",
114
+ operation,
115
+ code: "Timeout",
116
+ url,
117
+ http,
118
+ }),
113
119
  });
114
- const decodeNativeTransportFailure = Schema.decodeUnknownOption(NativeTransportFailure);
115
- const nativeTransportFailure = (error) => {
116
- const failure = Option.getOrUndefined(decodeNativeTransportFailure(error));
117
- if (!failure)
118
- return undefined;
119
- if (failure.code !== undefined)
120
- return failure;
121
- const cause = Option.getOrUndefined(decodeNativeTransportFailure(failure.cause));
122
- if (cause?.code !== undefined)
123
- return cause;
124
- return failure;
125
- };
126
- // HTTP hooks re-wrap response bodies, so a read failure can arrive as an HttpClientError caused by
127
- // another HttpClientError. The innermost cause carries the native failure.
128
- const rootCause = (error) => HttpClientError.isHttpClientError(error) && "cause" in error.reason && error.reason.cause !== undefined
129
- ? rootCause(error.reason.cause)
130
- : error;
131
- const CONNECTION_LOST = "Connection lost while reading the response";
132
- const httpError = (input) => {
133
- const request = HttpClientError.isHttpClientError(input.error) ? input.error.request : input.request;
134
- const transportError = (failure) => new AIError({
135
- reason: new TransportError({
136
- message: failure.message,
137
- cause: source,
138
- http: input.http,
139
- transport: "http",
140
- operation: input.operation,
141
- code: failure.code,
142
- url: request.url,
143
- }),
144
- });
145
- const source = rootCause(input.error);
146
- const native = nativeTransportFailure(source);
147
- const code = native?.code;
148
- const detail = code && native?.message && !native.message.includes(code) ? `${code}: ${native.message}` : native?.message;
149
- const message = detail ?? (input.error instanceof Error ? input.error.message : undefined);
150
- if (Cause.isTimeoutError(input.error) || Cause.isTimeoutError(source))
151
- return transportError({ message: message ?? "HTTP transport timed out", code: code ?? "Timeout" });
152
- if (!HttpClientError.isHttpClientError(input.error))
153
- return transportError({ message: message ?? "HTTP transport failed", code });
154
- // Effect reports every response body read failure as a DecodeError, but the raw byte stream decodes
155
- // nothing: provider output parsing happens later and fails as InvalidProviderOutput.
156
- if (input.operation === "read" && input.error.reason._tag === "DecodeError")
157
- return transportError({ message: detail ? `${CONNECTION_LOST}: ${detail}` : CONNECTION_LOST, code });
158
- if (input.error.reason._tag === "TransportError") {
159
- return transportError({
160
- message: message ?? input.error.reason.description ?? "HTTP transport failed",
161
- code: code ?? input.error.reason._tag,
162
- });
163
- }
164
- return transportError({
165
- message: message ?? `HTTP transport failed: ${input.error.reason._tag}`,
166
- code: code ?? input.error.reason._tag,
167
- });
120
+ const bodyTimeoutError = (response, message) => new HttpClientError.HttpClientError({
121
+ reason: new HttpClientError.DecodeError({
122
+ request: response.request,
123
+ response,
124
+ cause: new Cause.TimeoutError(message),
125
+ }),
126
+ });
127
+ // A response with one of these statuses has no body to re-wrap.
128
+ const NO_BODY = new Set([101, 204, 205, 304]);
129
+ /**
130
+ * Re-wraps the body behind the chunk and whole-request limits, so every way of reading it (`stream`, `text`, `json`,
131
+ * `formData`, ...) fails cleanly once it stalls.
132
+ */
133
+ const withBodyTimeouts = (raw, limits) => {
134
+ if (NO_BODY.has(raw.status) || (!Duration.isFinite(limits.chunk) && limits.deadline === undefined))
135
+ return Effect.succeed(raw);
136
+ const chunked = raw.stream.pipe(Stream.catchIf((error) => error.reason._tag === "EmptyBodyError", () => Stream.empty), Stream.timeoutOrElse({
137
+ duration: limits.chunk,
138
+ orElse: () => Stream.fail(bodyTimeoutError(raw, "Timed out waiting for response data")),
139
+ }));
140
+ const deadline = limits.deadline;
141
+ const body = deadline === undefined
142
+ ? chunked
143
+ : Stream.unwrap(Effect.map(Clock.currentTimeMillis, (now) => chunked.pipe(Stream.interruptWhen(Effect.sleep(Duration.millis(Math.max(0, deadline - now))).pipe(Effect.andThen(Effect.fail(bodyTimeoutError(raw, "Timed out waiting for the response to complete"))))))));
144
+ return Stream.toReadableStreamEffect(body).pipe(Effect.map((readable) => HttpClientResponse.fromWeb(raw.request, new Response(readable, { status: raw.status, headers: raw.headers }))));
168
145
  };
169
- export const responseStream = (response) => response.stream.pipe(Stream.mapError((error) => httpError({ error, request: response.request, operation: "read", http: responseHttp(response) })));
170
146
  export const stream = (executor, request, middleware) => Stream.unwrap(Effect.gen(function* () {
171
147
  const response = yield* executor.execute(request, middleware);
172
148
  return responseStream(response);
173
149
  }));
174
150
  export const layer = Layer.effect(Service, Effect.gen(function* () {
175
151
  const http = yield* HttpClient.HttpClient;
176
- const executeOnce = (request, middleware) => Effect.gen(function* () {
177
- if (!middleware)
178
- return yield* http.execute(request).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })), Effect.flatMap(statusError));
179
- const response = yield* middleware(request, (input) => http
180
- .execute(input)
181
- .pipe(Effect.mapError((cause) => (cause instanceof Error ? cause : new Error(String(cause)))))).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })));
152
+ const executeOnce = (request, middleware, timeout) => Effect.gen(function* () {
153
+ const started = yield* Clock.currentTimeMillis;
154
+ const limits = timeoutConfig(timeout);
155
+ // Unlike the header and chunk limits, the whole-request budget has no default.
156
+ const total = limits.total ? Duration.millis(limits.total) : Duration.infinity;
157
+ const headersLimit = Duration.min(timeoutDuration(limits.headers), total);
158
+ const send = !middleware
159
+ ? http.execute(request).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })))
160
+ : middleware(request, (input) => http
161
+ .execute(input)
162
+ .pipe(Effect.mapError((cause) => (cause instanceof Error ? cause : new Error(String(cause)))))).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })));
163
+ const raw = yield* send.pipe(Effect.timeoutOrElse({
164
+ duration: headersLimit,
165
+ orElse: () => Effect.fail(timeoutError(request.url, "request", "Timed out waiting for response headers")),
166
+ }));
167
+ const deadline = Duration.isFinite(total) ? started + Duration.toMillis(total) : undefined;
168
+ const response = yield* withBodyTimeouts(raw, {
169
+ chunk: timeoutDuration(limits.chunk, DEFAULT_CHUNK_TIMEOUT_MS),
170
+ deadline,
171
+ });
182
172
  return yield* statusError(response);
183
173
  });
184
174
  return Service.of({
185
- // Scoped middleware runs outside per-call middleware. It is cleared while the request runs, so a request a
186
- // middleware makes itself isn't wrapped again.
175
+ // Scoped middleware and timeouts are cleared while the request runs, so a request a middleware makes itself
176
+ // isn't wrapped again and starts with default timeouts.
187
177
  execute: (request, next) => Effect.gen(function* () {
188
178
  const middleware = composeMiddleware(yield* CurrentMiddleware, next);
189
- return yield* executeOnce(request, middleware).pipe(Effect.provideService(CurrentMiddleware, undefined));
179
+ const timeout = yield* CurrentTimeout;
180
+ return yield* executeOnce(request, middleware, timeout).pipe(Effect.provideService(CurrentMiddleware, undefined), Effect.provideService(CurrentTimeout, undefined));
190
181
  }),
191
182
  });
192
183
  }));
@@ -196,6 +187,10 @@ export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
196
187
  * downloads made through the plain executor never carry the certificate. The executor's HTTP client reads `CurrentTls`.
197
188
  */
198
189
  export const withTls = (execute, tls) => tls ? (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTls, tls)) : execute;
190
+ /** Sends through `execute` with `timeout` applied to the request and its response body. */
191
+ export const withTimeout = (execute, timeout) => timeout === undefined
192
+ ? execute
193
+ : (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTimeout, timeout));
199
194
  /**
200
195
  * Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
201
196
  * `middleware` still wrap the call, and status classification still applies.
@@ -3,6 +3,7 @@ import { HttpClientResponse } from "effect/http";
3
3
  import type { Reason, Snapshot } from "../generation.js";
4
4
  import { Media } from "../media.js";
5
5
  import type { AuthInput } from "./auth.js";
6
+ import { RequestExecutor } from "./executor.js";
6
7
  import { AIError, AuthenticationError, type HttpContext, InvalidRequestError, ProviderID, ProviderInternalError, RateLimitError } from "../schema/index.js";
7
8
  /** Array values become repeated parameters (`keyterm=a&keyterm=b`). */
8
9
  export type Query = Readonly<Record<string, string | ReadonlyArray<string>>>;
@@ -153,7 +154,7 @@ export declare const identity: (input: {
153
154
  pending: (id: string) => AIError;
154
155
  contentPolicy: (message: string) => AIError;
155
156
  }, AIError, never>;
156
- bytes: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<Uint8Array<ArrayBuffer>, AIError, never>;
157
+ bytes: typeof RequestExecutor.responseBytes;
157
158
  decodeJson: <A>(schema: Schema.Codec<A, unknown>) => (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<{
158
159
  body: string;
159
160
  http: HttpContext;
@@ -32,14 +32,6 @@ const FAILURES = {
32
32
  export const identity = (input) => {
33
33
  const provider = ProviderID.make(input.provider);
34
34
  const frameError = (message, body, cause) => new AIError({ reason: new InvalidProviderOutputError({ route: input.id, message, body, cause }) });
35
- const readError = (http) => (cause) => new AIError({
36
- reason: new InvalidProviderOutputError({
37
- route: input.id,
38
- message: `Failed to read the ${input.name} response`,
39
- http,
40
- cause,
41
- }),
42
- });
43
35
  /**
44
36
  * Read a text body while retaining the original payload and HTTP context on every downstream error. `invalid` is a
45
37
  * malformed provider document; `ended` is a generation that ended in `error` without output (reason `failed`
@@ -49,7 +41,7 @@ export const identity = (input) => {
49
41
  */
50
42
  const text = Effect.fn("MediaProtocol.text")(function* (response) {
51
43
  const http = RequestExecutor.responseHttp(response);
52
- const body = yield* response.text.pipe(Effect.mapError(readError(http)));
44
+ const body = yield* RequestExecutor.responseText(response);
53
45
  return {
54
46
  body,
55
47
  http,
@@ -79,7 +71,7 @@ export const identity = (input) => {
79
71
  });
80
72
  };
81
73
  /** Read a raw binary body, for providers that answer with the media bytes themselves. */
82
- const bytes = (response) => response.arrayBuffer.pipe(Effect.map((buffer) => new Uint8Array(buffer)), Effect.mapError(readError(RequestExecutor.responseHttp(response))));
74
+ const bytes = RequestExecutor.responseBytes;
83
75
  return {
84
76
  id: input.id,
85
77
  name: input.name,
@@ -4,13 +4,13 @@ import { Endpoint } from "./endpoint.js";
4
4
  import type { Interface } from "./executor-service.js";
5
5
  import { MediaProtocol } from "./media-protocol.js";
6
6
  import { Generation } from "../generation.js";
7
- import { AIError, ProviderID, type BaseRequest, type HttpOptions, type ProviderOptions } from "../schema/index.js";
7
+ import { AIError, ProviderID, type BaseRequest, type ProviderOptions, type TransportOptions } from "../schema/index.js";
8
8
  export type Execute = Interface["execute"];
9
9
  /** The minimum a media request must carry for the route to build a transport request. */
10
10
  export type MediaRequest = BaseRequest<{
11
11
  readonly id: string;
12
12
  readonly provider: ProviderID;
13
- readonly http?: HttpOptions;
13
+ readonly transport?: TransportOptions;
14
14
  readonly providerOptions?: ProviderOptions;
15
15
  }>;
16
16
  /** Deployment inputs every media model factory accepts; provider facades fill these from `configure(...)`. */
@@ -18,16 +18,14 @@ export interface ModelInput {
18
18
  readonly id: string;
19
19
  readonly auth: Auth.Definition;
20
20
  readonly baseURL?: string;
21
- readonly headers?: Record<string, string>;
22
- readonly http?: HttpOptions;
21
+ /** Deployment headers, timeouts and `http` overlays every request of the model starts from. */
22
+ readonly transport?: TransportOptions;
23
23
  /** Defaults under each request's `providerOptions`. */
24
24
  readonly providerOptions?: ProviderOptions;
25
25
  }
26
26
  /** A provider facade's `configure(...)` input as the `ModelInput` every media selector shares, minus the model id. */
27
- export declare const deployment: (input: {
27
+ export declare const deployment: (input: TransportOptions & {
28
28
  readonly baseURL?: string;
29
- readonly headers?: Record<string, string>;
30
- readonly http?: HttpOptions;
31
29
  }, auth: Auth.Definition) => Omit<ModelInput, "id">;
32
30
  /** One request, one response. */
33
31
  export interface InlineRoute<Request extends MediaRequest, Response> {
@@ -62,7 +60,7 @@ export type AnyRoute<Request extends MediaRequest, Event, Response> = InlineRout
62
60
  export interface Composition<Request extends MediaRequest> {
63
61
  readonly endpoint: Endpoint.Definition<MediaProtocol.Body, Request>;
64
62
  readonly auth: Auth.Definition;
65
- /** Deployment headers applied before transport authentication. */
63
+ /** Headers the protocol requires on every call; the model's transport headers win. */
66
64
  readonly headers?: Record<string, string>;
67
65
  }
68
66
  export interface InlineInput<Request extends MediaRequest, Response> extends Composition<Request> {
@@ -10,7 +10,7 @@ import { AIError, AIErrorReason, InvalidRequestError, ProviderID, UnsupportedOpe
10
10
  import { encodeJson } from "../utils/json.js";
11
11
  import { sanitizeSurrogates } from "../utils/sanitize.js";
12
12
  /** A provider facade's `configure(...)` input as the `ModelInput` every media selector shares, minus the model id. */
13
- export const deployment = (input, auth) => ({ auth, baseURL: input.baseURL, headers: input.headers, http: input.http });
13
+ export const deployment = (input, auth) => ({ auth, baseURL: input.baseURL, transport: mergeTransport(input) });
14
14
  /**
15
15
  * Compose an inline media protocol with an endpoint and auth into a runnable route. The route owns the transport
16
16
  * plumbing every media protocol would otherwise duplicate: option merging, surrogate sanitizing, unsupported-field
@@ -148,22 +148,22 @@ const makeTransport = (input) => {
148
148
  body: encoded.text,
149
149
  headers: encoded.headers,
150
150
  });
151
- const response = yield* RequestExecutor.withTls(execute, call.request.http?.tls)(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
151
+ const response = yield* RequestExecutor.withTimeout(RequestExecutor.withTls(execute, call.request.http?.tls), call.timeout)(encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))), RequestExecutor.withFetch(fetch));
152
152
  return { response };
153
153
  });
154
154
  return {
155
155
  /** Route and model overlays; `start` additionally merges the request's own. */
156
- exchange: (model) => mergeTransport({ headers: input.headers, http: model.http }),
156
+ exchange: (model) => mergeTransport({ headers: input.headers }, model.transport),
157
157
  /** POST the protocol body to the route endpoint. */
158
158
  submit: Effect.fn("MediaRoute.submit")(function* (request, protocol, execute) {
159
159
  yield* rejectUnsupported(input.protocol.id, input.protocol.provider, request, protocol.unsupported);
160
- const { headers: merged, http } = mergeTransport({ headers: input.headers, http: request.model.http }, request);
161
- const exchange = { headers: merged, http, fetch: request.fetch };
160
+ const { headers: merged, timeout, http, } = mergeTransport({ headers: input.headers }, request.model.transport, request);
161
+ const exchange = { headers: merged, timeout, http, fetch: request.fetch };
162
162
  const providerOptions = mergeProviderOptions(request.model.providerOptions, request.providerOptions);
163
163
  const headers = Headers.fromInput(merged);
164
164
  const prepared = protocol.prepare === undefined
165
165
  ? request
166
- : yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request: { ...request, http }, body }, request.fetch, execute).pipe(Effect.map((sent) => sent.response)));
166
+ : yield* protocol.prepare(request, (path, body) => send({ method: "POST", url: baseURL(path), headers, request: { ...request, http }, body, timeout }, request.fetch, execute).pipe(Effect.map((sent) => sent.response)));
167
167
  // Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized.
168
168
  const resolved = {
169
169
  ...sanitizeSurrogates({ ...prepared, headers: merged, http, providerOptions }),
@@ -171,7 +171,7 @@ const makeTransport = (input) => {
171
171
  };
172
172
  const body = yield* protocol.from(resolved);
173
173
  const url = withQuery(withQuery(Endpoint.render(input.endpoint, { request: resolved, body }), body.type === "multipart" ? undefined : body.query), http?.query);
174
- const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, request.fetch, execute);
174
+ const sent = yield* send({ method: "POST", url, headers, request: resolved, body, timeout }, request.fetch, execute);
175
175
  return { response: sent.response, context: { request: resolved, body }, exchange };
176
176
  }),
177
177
  /**
@@ -194,7 +194,7 @@ const makeTransport = (input) => {
194
194
  for (const [key, value] of Object.entries(input.endpoint.query ?? {}))
195
195
  url.searchParams.set(key, value);
196
196
  const headers = Headers.fromInput(exchange.headers);
197
- return send({ method, url, headers, request: { http: exchange.http } }, exchange.fetch, execute);
197
+ return send({ method, url, headers, request: { http: exchange.http }, timeout: exchange.timeout }, exchange.fetch, execute);
198
198
  },
199
199
  };
200
200
  };
@@ -2,7 +2,6 @@ import { Effect } from "effect";
2
2
  import { Headers, HttpClientRequest } from "effect/http";
3
3
  import { Framing } from "../framing.js";
4
4
  import type { HttpMiddleware, Transport, TransportPrepareInput } from "./index.js";
5
- import { AIError } from "../../schema/index.js";
6
5
  export type JsonRequestInput<Body> = TransportPrepareInput<Body>;
7
6
  export interface JsonRequestParts<Body = unknown> {
8
7
  readonly url: string;
@@ -20,7 +19,7 @@ export declare const jsonRequestParts: <Body>(input: JsonRequestInput<Body>) =>
20
19
  jsonBody: Body | Record<string, unknown>;
21
20
  bodyText: string;
22
21
  headers: Headers.Headers;
23
- }, AIError, never>;
22
+ }, import("../../schema/errors.js").AIError, never>;
24
23
  export interface HttpJsonInput<_Body, Frame> {
25
24
  readonly framing: Framing.Definition<Frame>;
26
25
  }
@@ -1,10 +1,10 @@
1
- import { Clock, Duration, Effect, Stream } from "effect";
1
+ import { Effect } from "effect";
2
2
  import { Headers, HttpClientRequest } from "effect/http";
3
3
  import { Auth } from "../auth.js";
4
4
  import { render as renderEndpoint } from "../endpoint.js";
5
5
  import { Framing } from "../framing.js";
6
6
  import * as ProviderShared from "../../protocols/shared.js";
7
- import { AIError, DEFAULT_CHUNK_TIMEOUT_MS, DEFAULT_HTTP_TIMEOUT_MS, mergeJsonRecords, timeoutConfig, TransportError, } from "../../schema/index.js";
7
+ import { mergeJsonRecords } from "../../schema/index.js";
8
8
  import { RequestExecutor } from "../executor.js";
9
9
  const bodyWithOverlay = (body, request, encodeBody) => Effect.gen(function* () {
10
10
  if (request.http?.body === undefined)
@@ -52,38 +52,15 @@ export const httpJson = (input) => ({
52
52
  };
53
53
  }),
54
54
  execute: (prepared, request, runtime) => Effect.gen(function* () {
55
- const timeout = (operation, message, http) => new AIError({
56
- reason: new TransportError({
57
- message,
58
- transport: "http",
59
- operation,
60
- code: "Timeout",
61
- url: prepared.request.url,
62
- http,
63
- }),
64
- });
65
- const started = yield* Clock.currentTimeMillis;
66
- const limits = timeoutConfig(request.timeout);
67
- // Unlike the header and chunk limits, the whole-request budget has no default.
68
- const total = limits.total ? Duration.millis(limits.total) : Duration.infinity;
69
- const response = yield* RequestExecutor.withTls(runtime.http.execute, request.http?.tls)(prepared.request, prepared.middleware).pipe(Effect.timeoutOrElse({
70
- duration: Duration.min(timeoutDuration(limits.headers), total),
71
- orElse: () => timeout("request", "Timed out waiting for response headers"),
72
- }));
73
- const http = RequestExecutor.responseHttp(response);
74
- const remaining = Duration.subtract(total, Duration.millis((yield* Clock.currentTimeMillis) - started));
55
+ const response = yield* RequestExecutor.withTimeout(RequestExecutor.withTls(runtime.http.execute, request.http?.tls), request.timeout)(prepared.request, prepared.middleware);
75
56
  return {
76
- frames: prepared.framing.frame(RequestExecutor.responseStream(response).pipe(Stream.timeoutOrElse({
77
- duration: timeoutDuration(limits.chunk, DEFAULT_CHUNK_TIMEOUT_MS),
78
- orElse: () => Stream.fail(timeout("read", "Timed out waiting for response data", http)),
79
- }), Stream.interruptWhen(Effect.sleep(remaining).pipe(Effect.andThen(Effect.fail(timeout("read", "Timed out waiting for the response to complete", http))))))),
80
- http,
57
+ frames: prepared.framing.frame(RequestExecutor.responseStream(response)),
58
+ http: RequestExecutor.responseHttp(response),
81
59
  body: prepared.framing.body,
82
60
  raw: prepared.framing.raw,
83
61
  };
84
62
  }),
85
63
  });
86
- const timeoutDuration = (value, fallback = DEFAULT_HTTP_TIMEOUT_MS) => value === false ? Duration.infinity : Duration.millis(value ?? fallback);
87
64
  export const sseJson = {
88
65
  id: "http-json/sse",
89
66
  with: () => httpJson({ framing: Framing.sse }),
@@ -165,7 +165,8 @@ export class AIError extends Schema.TaggedError()("AI.Error", {
165
165
  // A WebSocket acknowledgment marks delivery accepted before model output may exist.
166
166
  // Read failures can still recover; the caller chooses retry versus continuation from durable output.
167
167
  case "Transport":
168
- return (this.reason.delivery !== "rejected" && (this.reason.delivery !== "accepted" || this.reason.operation === "read"));
168
+ return (this.reason.delivery !== "rejected" &&
169
+ (this.reason.delivery !== "accepted" || this.reason.operation === "read"));
169
170
  case "InvalidProviderOutput":
170
171
  return this.reason.classification === "incomplete-stream";
171
172
  // Unrecognized failures retry: classification records affirmative
@@ -53,7 +53,7 @@ export type RequestTimeout = HttpTimeout | TimeoutConfig;
53
53
  export interface TransportOptions {
54
54
  /** Merged over the provider's headers; these win. */
55
55
  readonly headers?: Record<string, string>;
56
- /** Applied to text requests; media requests do not apply it yet. */
56
+ /** Applied to every HTTP request. */
57
57
  readonly timeout?: RequestTimeout;
58
58
  readonly http?: HttpOptions;
59
59
  }
package/dist/speech.js CHANGED
@@ -10,7 +10,7 @@ export class SpeechModel extends MediaModel {
10
10
  return new SpeechModel({
11
11
  id: input.id,
12
12
  provider: route.protocol.provider,
13
- http: input.http,
13
+ transport: input.transport,
14
14
  providerOptions: input.providerOptions,
15
15
  route: composeRoute(route, input, collectResponse),
16
16
  });
@@ -10,7 +10,7 @@ export class TranscriptionModel extends MediaModel {
10
10
  return new TranscriptionModel({
11
11
  id: input.id,
12
12
  provider: route.protocol.provider,
13
- http: input.http,
13
+ transport: input.transport,
14
14
  providerOptions: input.providerOptions,
15
15
  route: composeRoute(route, input, collectResponse),
16
16
  });
package/dist/video.js CHANGED
@@ -10,7 +10,7 @@ export class VideoModel extends MediaModel {
10
10
  return new VideoModel({
11
11
  id: input.id,
12
12
  provider: route.protocol.provider,
13
- http: input.http,
13
+ transport: input.transport,
14
14
  providerOptions: input.providerOptions,
15
15
  route: composeQueuedRoute(route, input),
16
16
  });
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-1311",
3
+ "version": "0.0.0-dev-1312",
4
4
  "name": "@opencode/ai",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -624,7 +624,7 @@
624
624
  "devDependencies": {
625
625
  "@clack/prompts": "1.0.0-alpha.1",
626
626
  "@effect/platform-node": "4.1.0",
627
- "@opencode/http-recorder": "0.0.0-dev-1311",
627
+ "@opencode/http-recorder": "0.0.0-dev-1312",
628
628
  "@tsconfig/bun": "1.0.9",
629
629
  "@types/bun": "1.4.3",
630
630
  "@typescript/native": "npm:typescript@7.1.0-beta",
@@ -634,7 +634,7 @@
634
634
  "@aws-sdk/credential-providers": "3.1057.0",
635
635
  "@smithy/eventstream-codec": "4.2.14",
636
636
  "@smithy/util-utf8": "4.2.2",
637
- "@opencode/schema": "0.0.0-dev-1311",
637
+ "@opencode/schema": "0.0.0-dev-1312",
638
638
  "aws4fetch": "1.0.20",
639
639
  "effect": "4.1.0",
640
640
  "google-auth-library": "10.5.0"