Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion packages/ai/src/protocols/utils/responses-compaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export const make = (
auth: route.auth,
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
})
const response = yield* executor.execute(
const response = yield* RequestExecutor.withTls(executor.execute, request.http?.tls)(
ProviderShared.jsonPost({
url: parts.url,
body: parts.bodyText,
Expand Down
9 changes: 9 additions & 0 deletions packages/ai/src/route/executor-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Context, type Effect } from "effect"
import type { Headers, HttpClientRequest, HttpClientResponse } from "effect/http"
import { HttpContext, type AIError } from "../schema/errors.js"
import type { ClientTls } from "../schema/options.js"

// The service tag lives in its own leaf module so `Media.Asset` (imported by the schema layer) can require the
// executor without pulling the full executor implementation, and therefore the schema barrel, into a cycle.
Expand All @@ -23,6 +24,14 @@ export class RequestExecutorService extends Context.Service<RequestExecutorServi
"@opencode/AI/RequestExecutor",
) {}
export const Service = RequestExecutorService

/**
* The client certificate for the HTTP request being executed. Transports set it from `http.tls`; the executor's HTTP
* client presents it, since only the runtime's fetch can.
*/
export const CurrentTls = Context.Reference<ClientTls | undefined>("@opencode/AI/RequestExecutor/CurrentTls", {
defaultValue: () => undefined,
})
export type Service = RequestExecutorService

export const headerDetails = (headers: Headers.Headers) =>
Expand Down
19 changes: 17 additions & 2 deletions packages/ai/src/route/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,17 @@ import {
} from "effect/http"
import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../schema/index.js"
import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js"
import { headerDetails, responseHttp, Service, type HttpMiddleware, type Interface } from "./executor-service.js"
import {
CurrentTls,
headerDetails,
responseHttp,
Service,
type HttpMiddleware,
type Interface,
} from "./executor-service.js"
import type { ClientTls } from "../schema/options.js"

export { responseHttp, Service } from "./executor-service.js"
export { CurrentTls, responseHttp, Service } from "./executor-service.js"
export type { HttpHandler, HttpMiddleware, Interface, RequestExecutorService } from "./executor-service.js"

const normalizedHeaders = (headers: Headers.Headers) =>
Expand Down Expand Up @@ -253,6 +261,13 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient> = Layer.e

export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer))

/**
* Sends through `execute`, presenting `tls` on each request. Apply it only where a provider request is sent, so
* downloads made through the plain executor never carry the certificate. The executor's HTTP client reads `CurrentTls`.
*/
export const withTls = (execute: Interface["execute"], tls: ClientTls | undefined): Interface["execute"] =>
tls ? (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTls, tls)) : execute

/**
* Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
* `middleware` still wrap the call, and status classification still applies.
Expand Down
10 changes: 6 additions & 4 deletions packages/ai/src/route/media.ts
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ const makeTransport = <Request extends MediaRequest>(
body: encoded.text,
headers: encoded.headers,
})
const response = yield* execute(
const response = yield* RequestExecutor.withTls(execute, call.request.http?.tls)(
encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))),
RequestExecutor.withFetch(fetch),
)
Expand Down Expand Up @@ -371,9 +371,11 @@ const makeTransport = <Request extends MediaRequest>(
protocol.prepare === undefined
? request
: yield* protocol.prepare(request, (path, body) =>
send({ method: "POST", url: baseURL(path), headers, request, body }, request.fetch, execute).pipe(
Effect.map((sent) => sent.response),
),
send(
{ method: "POST", url: baseURL(path), headers, request: { ...request, http }, body },
request.fetch,
execute,
).pipe(Effect.map((sent) => sent.response)),
)
// Sanitize after merging so model-level overlays are covered; the model value is restored, not sanitized.
const resolved: Request = {
Expand Down
5 changes: 4 additions & 1 deletion packages/ai/src/route/transport/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,10 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
const limits = timeoutConfig(request.timeout)
// Unlike the header and chunk limits, the whole-request budget has no default.
const total = limits.total ? Duration.millis(limits.total) : Duration.infinity
const response = yield* runtime.http.execute(prepared.request, prepared.middleware).pipe(
const response = yield* RequestExecutor.withTls(runtime.http.execute, request.http?.tls)(
prepared.request,
prepared.middleware,
).pipe(
Effect.timeoutOrElse({
duration: Duration.min(timeoutDuration(limits.headers), total),
orElse: () => timeout("request", "Timed out waiting for response headers"),
Expand Down
10 changes: 10 additions & 0 deletions packages/ai/src/schema/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ export interface HttpOptions {
readonly body?: Record<string, unknown>
/** Compression for JSON request bodies. Only set it for endpoints known to decode it. */
readonly encoding?: RequestEncoding
/** Client certificate presented to HTTPS endpoints that request one (mutual TLS). */
readonly tls?: ClientTls
}

/** PEM client certificate and private key, with the passphrase of an encrypted key. */
export interface ClientTls {
readonly cert: string
readonly key: string
readonly passphrase?: string
}

/** Per-phase time limits in milliseconds. */
Expand Down Expand Up @@ -127,6 +136,7 @@ export const mergeTransport = (...items: ReadonlyArray<TransportOptions | undefi
query: mergeStringRecords(...http.map((item) => item?.query)),
body: mergeJsonRecords(...http.map((item) => item?.body)),
encoding: last(http.map((item) => item?.encoding)),
tls: last(http.map((item) => item?.tls)),
}),
}
}
Expand Down
4 changes: 4 additions & 0 deletions packages/client/src/promise/generated/types.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,12 @@
"node": "./src/image/photon-wasm.node.ts",
"default": "./src/image/photon-wasm.bun.ts"
},
"#client-tls": {
"workerd": "./src/effect/client-tls/client-tls.workerd.ts",
"bun": "./src/effect/client-tls/client-tls.bun.ts",
"node": "./src/effect/client-tls/client-tls.node.ts",
"default": "./src/effect/client-tls/client-tls.bun.ts"
},
"#v1-migration": {
"types": "./src/database/v1-migration.bun.ts",
"bun": "./src/database/v1-migration.bun.ts",
Expand Down Expand Up @@ -128,6 +134,7 @@
"jose": "6.0.11",
"jsonc-parser": "3.3.1",
"mime-types": "3.0.2",
"undici": "8.12.3",
"which": "6.0.1",
"zod": "catalog:"
},
Expand Down
9 changes: 8 additions & 1 deletion packages/core/src/aisdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ export * as AISDK from "./aisdk.js"
import { makeLocationNode } from "@opencode/util/effect/app-node"
import { httpFetch } from "@opencode/util/effect/app-node-platform"
import { APICallError } from "@ai-sdk/provider"
import { ClientTls } from "#client-tls"
import type {
JSONSchema7,
JSONValue,
Expand Down Expand Up @@ -134,6 +135,7 @@ function prepareOptions(model: RuntimeInfo, pkg: string, outbound: Fetch) {

const customFetch = settings.fetch
const timeouts = Provider.timeouts(settings)
const tls = Provider.tls(settings)
options.fetch = async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
const opts = { ...(init ?? {}) }
// A plain AbortSignal.timeout would keep running into the body stream, so the header limit uses
Expand All @@ -160,7 +162,12 @@ function prepareOptions(model: RuntimeInfo, pkg: string, outbound: Fetch) {
}
}

const send: Fetch = isFetch(customFetch) ? customFetch : outbound
const https = String(input instanceof Request ? input.url : input).startsWith("https:")
const certified = tls && https ? ClientTls.sender(tls) : undefined
if (tls && https && !certified) throw new Error("Client certificates aren't supported on this runtime")
// A followed redirect keeps the TLS options, so it would present the client certificate to another host.
if (certified) Object.assign(opts, certified.init, { redirect: "error" })
const send: Fetch = certified ? certified.fetch : isFetch(customFetch) ? customFetch : outbound
const middleware = httpMiddleware.getStore()
const res = await (
middleware
Expand Down
42 changes: 39 additions & 3 deletions packages/core/src/effect/app-node-platform.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { LLMClient, RequestExecutor } from "@opencode/ai/route"
import { Effect, Layer } from "effect"
import { FetchHttpClient, HttpClient } from "effect/http"
import { Effect, Layer, Option } from "effect"
import { FetchHttpClient, HttpClient, HttpClientError } from "effect/http"
import { Socket } from "effect/socket"
import { makeGlobalNode } from "@opencode/util/effect/app-node"
import { httpClient } from "@opencode/util/effect/app-node-platform"
import { ClientTls } from "#client-tls"
import { WebSocketConstructor } from "./websocket-constructor.js"

// Bun's fetch ends a request after five quiet minutes, before provider routes' own header and chunk timeouts.
Expand All @@ -18,9 +19,44 @@ const withoutBunTimeout = Layer.effect(
}),
)

// Presents the model's client certificate (provider `settings.tls`) on its HTTPS requests, through this runtime's
// certificate-capable fetch. The TLS handshake only sends it to servers that request one.
const withClientCertificate = Layer.effect(
HttpClient.HttpClient,
Effect.gen(function* () {
const client = yield* HttpClient.HttpClient
return HttpClient.transform(client, (effect, request) =>
Effect.gen(function* () {
const tls = yield* RequestExecutor.CurrentTls
if (!tls || !request.url.startsWith("https:")) return yield* effect
const sender = ClientTls.sender(tls)
if (!sender)
return yield* new HttpClientError.HttpClientError({
reason: new HttpClientError.TransportError({
request,
description: "Client certificates aren't supported on this runtime",
}),
})
const init: RequestInit = Option.getOrElse(yield* Effect.serviceOption(FetchHttpClient.RequestInit), () => ({}))
return yield* HttpClient.execute(request).pipe(
Effect.provide(FetchHttpClient.layer),
Effect.provideService(FetchHttpClient.Fetch, sender.fetch),
Effect.provideService(FetchHttpClient.RequestInit, {
...init,
...sender.init,
// A followed redirect keeps the TLS options, so it would present the certificate to whatever host the
// server names.
redirect: init.redirect === "manual" ? "manual" : "error",
}),
)
}),
)
}),
)

export const requestExecutor = makeGlobalNode({
service: RequestExecutor.Service,
layer: RequestExecutor.layer.pipe(Layer.provide(withoutBunTimeout)),
layer: RequestExecutor.layer.pipe(Layer.provide(withoutBunTimeout), Layer.provide(withClientCertificate)),
deps: [httpClient],
})

Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/effect/client-tls/client-tls.bun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { Sender, Tls } from "./client-tls.js"

// Bun's fetch takes the client certificate per request.
export function sender(tls: Tls): Sender | undefined {
return { fetch: globalThis.fetch, init: { tls } }
}

export * as ClientTls from "./client-tls.bun.js"
17 changes: 17 additions & 0 deletions packages/core/src/effect/client-tls/client-tls.node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// The deep path keeps Vite, which runs under Bun where "undici" is a built-in, from leaving the import external.
import { Agent, fetch } from "undici/index.js"
import type { Sender, Tls } from "./client-tls.js"

// Node's fetch only takes a client certificate through an undici dispatcher, and a dispatcher from the npm package
// only works with that package's own fetch, not Node's bundled one. One agent per certificate keeps its connections.
const agents = new Map<string, Agent>()

export function sender(tls: Tls): Sender | undefined {
const id = JSON.stringify([tls.cert, tls.key, tls.passphrase])
const agent = agents.get(id) ?? new Agent({ connect: { cert: tls.cert, key: tls.key, passphrase: tls.passphrase } })
agents.set(id, agent)
// SAFETY: undici's fetch implements the WHATWG fetch contract that FetchHttpClient and the AI SDK call.
return { fetch: fetch as unknown as typeof globalThis.fetch, init: { dispatcher: agent } }
}

export * as ClientTls from "./client-tls.node.js"
12 changes: 12 additions & 0 deletions packages/core/src/effect/client-tls/client-tls.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/** PEM client certificate and private key, with the passphrase of an encrypted key. */
export interface Tls {
readonly cert: string
readonly key: string
readonly passphrase?: string
}

/** The `fetch` and request options that present a client certificate on this runtime. */
export interface Sender {
readonly fetch: typeof globalThis.fetch
readonly init: Record<string, unknown>
}
8 changes: 8 additions & 0 deletions packages/core/src/effect/client-tls/client-tls.workerd.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import type { Sender, Tls } from "./client-tls.js"

// Workers' fetch can't present a client certificate. Embedders use an mTLS certificate binding's fetch instead.
export function sender(_tls: Tls): Sender | undefined {
return undefined
}

export * as ClientTls from "./client-tls.workerd.js"
15 changes: 11 additions & 4 deletions packages/core/src/model-resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ const resolveCatalogModel = Effect.fn("ModelResolver.resolveCatalogModel")(funct
...runtime.options,
...mergeTransport(runtime.options, {
timeout: { total: timeouts.timeout, headers: timeouts.headerTimeout, chunk: timeouts.chunkTimeout },
http: { encoding: Provider.encoding(configured) },
http: { encoding: Provider.encoding(configured), tls: Provider.tls(configured) },
}),
},
})
Expand Down Expand Up @@ -315,7 +315,8 @@ const fromCatalogMedia = Effect.fn("ModelResolver.fromCatalogMedia")(function* <
credential?: Credential.Value,
dependencies?: Dependencies,
) {
const { resolved, module, settings } = yield* loadCatalogPackage(model, credential, dependencies)
const { resolved, configured, module, settings } = yield* loadCatalogPackage(model, credential, dependencies)
const tls = Provider.tls(configured)
const runtime: unknown = yield* Effect.try({
try: () => module.model(resolved.modelID ?? resolved.id, settings),
catch: (cause) => constructionError(resolved, cause),
Expand All @@ -330,7 +331,12 @@ const fromCatalogMedia = Effect.fn("ModelResolver.fromCatalogMedia")(function* <
})
: runtime
if (!is(adapted)) return yield* unsupported(resolved)
return adapted
if (!tls || !(adapted instanceof DecisionModel || adapted instanceof ImageModel)) return adapted
// Media and decision models are plain classes with readonly fields, so copy onto the same prototype.
const copy: Runtime = Object.assign(Object.create(Object.getPrototypeOf(adapted)), adapted, {
http: { ...adapted.http, tls },
})
return copy
})

const constructionError = (model: RuntimeInfo, cause: unknown) =>
Expand Down Expand Up @@ -504,7 +510,8 @@ export const layer = Layer.effect(
limit: selected.limit,
compaction: runtimeInfo.settings?.compaction,
cache: runtimeInfo.settings?.cache,
transport: provider?.settings?.transport,
// The WebSocket transport can't present a client certificate, so `tls` keeps the model on HTTP.
transport: Provider.tls(provider?.settings ?? {}) ? "http" : provider?.settings?.transport,
chunkTimeout: Provider.timeout(provider?.settings?.chunkTimeout),
}
})
Expand Down
8 changes: 8 additions & 0 deletions packages/core/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,14 @@ export function encoding(settings: Readonly<Record<string, unknown>>) {
return Option.getOrUndefined(decodeEncoding(settings.encoding))
}

const decodeTls = Schema.decodeUnknownOption(Provider.Tls)

/** Client certificate from provider settings. An empty `cert` or `key`, such as a missing `{file:}`, leaves it unset. */
export function tls(settings: Readonly<Record<string, unknown>>) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropping tls when cert or key is empty (or when the object fails to decode, e.g. no key) turns a config mistake into a confusing network failure. With cert: "{file:./missing.pem}" I got only ECONNRESET: The socket connection was closed unexpectedly…, retried over and over; the real cause is just a warning in the log. Someone who set tls clearly wants a certificate presented. Could an invalid or empty tls fail the model request with a clear, non-retryable error naming settings.tls instead of being silently ignored?

const value = Option.getOrUndefined(decodeTls(settings.tls))
return value?.cert && value.key ? value : undefined
}

export const Request = Provider.Request
export type Request = Provider.Request

Expand Down
Loading
Loading