shotluma/scripts/opencode-proxy.ts

92 lines
3.1 KiB
TypeScript
Raw Permalink Normal View History

feat(ai): add OpenCode Zen and Go providers (#18) * feat(ai): add OpenCode Zen and Go providers Add OpenCode as a key-based provider with shared Zen/Go credentials, a same-origin CORS proxy, runtime model catalogs, and a vision-model fallback that describes screenshots for text-only coding models. * fix(ai): keep OpenCode Zen/Go path prefixes when proxying Absolute /v1/... suffixes were resolved against the OpenCode origin and dropped /zen and /zen/go. Join relative to those prefixes in the worker and Vite rewrites. * chore(deps): bump nanoid override to 3.3.18 Clear GHSA-2v37-7h3g-55p8 so bun audit can pass. The previous 3.3.17 pin is now reported as vulnerable. * fix(ai): surface run status events and cache image descriptions across steps OpenCode text-only models describe screenshots with a vision model before generating. The modal dropped 'status' run events, so the band showed 'Starting up …' for the whole describe phase, and each tool-loop step re-described every image from scratch because the description cache lived only one prepare call. * refactor(ai): enhance OpenCode model handling and proxy functionality * fix: allow images to be used in devices * fix(ai): defer vision fallback, harden image cache keys, and remount model browser per provider Address CodeRabbit review on #18: - resolve the OpenCode vision describer only once a prepared step contains an image, so text-only models run image-free requests without a fallback - relay tool preview images whenever the vision fallback is active, not only for chat-dialect models - hash full binary payloads for image description cache keys so distinct same-length images are described separately - build the unavailable-transport error from the selected provider - remount AiCatalogModelBrowser per provider so catalogs never leak between OpenRouter and OpenCode gateways - bound the OpenCode catalog fetch with a 10s timeout and guard the catalog-revision state update after unmount - correct the worker key-handling doc and the vision-default comment
2026-08-20 01:10:05 +02:00
export const OPENCODE_ZEN_UPSTREAM = 'https://opencode.ai/zen'
export const OPENCODE_GO_UPSTREAM = 'https://opencode.ai/zen/go'
const GO_PREFIX = '/api/opencode/go'
const ZEN_PREFIX = '/api/opencode/zen'
/**
* OpenCode serves each model on one of four dialects, so the proxy has to carry
* the auth and versioning headers of all of them: `authorization` for the
* OpenAI Responses and Chat Completions endpoints, `x-api-key` plus the
* `anthropic-*` headers for `/v1/messages`, and `x-goog-api-key` for the Gemini
* endpoint. `x-opencode-session` carries the client session id OpenCode uses
* for routing and prompt caching. Anything outside this list (cookies, origin,
* client hints) is dropped so the proxy stays a pure credential passthrough.
feat(ai): add OpenCode Zen and Go providers (#18) * feat(ai): add OpenCode Zen and Go providers Add OpenCode as a key-based provider with shared Zen/Go credentials, a same-origin CORS proxy, runtime model catalogs, and a vision-model fallback that describes screenshots for text-only coding models. * fix(ai): keep OpenCode Zen/Go path prefixes when proxying Absolute /v1/... suffixes were resolved against the OpenCode origin and dropped /zen and /zen/go. Join relative to those prefixes in the worker and Vite rewrites. * chore(deps): bump nanoid override to 3.3.18 Clear GHSA-2v37-7h3g-55p8 so bun audit can pass. The previous 3.3.17 pin is now reported as vulnerable. * fix(ai): surface run status events and cache image descriptions across steps OpenCode text-only models describe screenshots with a vision model before generating. The modal dropped 'status' run events, so the band showed 'Starting up …' for the whole describe phase, and each tool-loop step re-described every image from scratch because the description cache lived only one prepare call. * refactor(ai): enhance OpenCode model handling and proxy functionality * fix: allow images to be used in devices * fix(ai): defer vision fallback, harden image cache keys, and remount model browser per provider Address CodeRabbit review on #18: - resolve the OpenCode vision describer only once a prepared step contains an image, so text-only models run image-free requests without a fallback - relay tool preview images whenever the vision fallback is active, not only for chat-dialect models - hash full binary payloads for image description cache keys so distinct same-length images are described separately - build the unavailable-transport error from the selected provider - remount AiCatalogModelBrowser per provider so catalogs never leak between OpenRouter and OpenCode gateways - bound the OpenCode catalog fetch with a 10s timeout and guard the catalog-revision state update after unmount - correct the worker key-handling doc and the vision-default comment
2026-08-20 01:10:05 +02:00
*/
export const OPENCODE_FORWARDED_HEADERS = [
'authorization',
'content-type',
'accept',
'x-opencode-session',
feat(ai): add OpenCode Zen and Go providers (#18) * feat(ai): add OpenCode Zen and Go providers Add OpenCode as a key-based provider with shared Zen/Go credentials, a same-origin CORS proxy, runtime model catalogs, and a vision-model fallback that describes screenshots for text-only coding models. * fix(ai): keep OpenCode Zen/Go path prefixes when proxying Absolute /v1/... suffixes were resolved against the OpenCode origin and dropped /zen and /zen/go. Join relative to those prefixes in the worker and Vite rewrites. * chore(deps): bump nanoid override to 3.3.18 Clear GHSA-2v37-7h3g-55p8 so bun audit can pass. The previous 3.3.17 pin is now reported as vulnerable. * fix(ai): surface run status events and cache image descriptions across steps OpenCode text-only models describe screenshots with a vision model before generating. The modal dropped 'status' run events, so the band showed 'Starting up …' for the whole describe phase, and each tool-loop step re-described every image from scratch because the description cache lived only one prepare call. * refactor(ai): enhance OpenCode model handling and proxy functionality * fix: allow images to be used in devices * fix(ai): defer vision fallback, harden image cache keys, and remount model browser per provider Address CodeRabbit review on #18: - resolve the OpenCode vision describer only once a prepared step contains an image, so text-only models run image-free requests without a fallback - relay tool preview images whenever the vision fallback is active, not only for chat-dialect models - hash full binary payloads for image description cache keys so distinct same-length images are described separately - build the unavailable-transport error from the selected provider - remount AiCatalogModelBrowser per provider so catalogs never leak between OpenRouter and OpenCode gateways - bound the OpenCode catalog fetch with a 10s timeout and guard the catalog-revision state update after unmount - correct the worker key-handling doc and the vision-default comment
2026-08-20 01:10:05 +02:00
'x-api-key',
'anthropic-version',
'anthropic-beta',
'x-goog-api-key',
] as const
const joinUpstream = (origin: string, suffix: string): URL => {
const base = `${origin.replace(/\/$/u, '')}/`
const relative = suffix.replace(/^\//u, '')
return new URL(relative, base)
}
/**
* Map a same-origin OpenCode CORS-proxy path onto the Zen or Go upstream.
* `/api/opencode/go` is matched before `/api/opencode/zen` so the prefixes
* cannot overlap.
*/
export const rewriteOpencodeProxyUrl = (requestUrl: URL): URL | null => {
const path = requestUrl.pathname
const search = requestUrl.search
if (path === GO_PREFIX || path.startsWith(`${GO_PREFIX}/`)) {
const upstream = joinUpstream(OPENCODE_GO_UPSTREAM, path.slice(GO_PREFIX.length))
upstream.search = search
return upstream
}
if (path === ZEN_PREFIX || path.startsWith(`${ZEN_PREFIX}/`)) {
const upstream = joinUpstream(OPENCODE_ZEN_UPSTREAM, path.slice(ZEN_PREFIX.length))
upstream.search = search
return upstream
}
return null
}
export const copyOpencodeProxyHeaders = (source: Headers): Headers => {
const headers = new Headers()
for (const name of OPENCODE_FORWARDED_HEADERS) {
const value = source.get(name)
if (value) headers.set(name, value)
}
return headers
}
export const isOpencodeProxyMethod = (method: string): boolean => {
const normalized = method.toUpperCase()
return normalized === 'GET' || normalized === 'POST' || normalized === 'OPTIONS'
}
export const proxyOpencodeRequest = async (request: Request): Promise<Response> => {
if (request.method.toUpperCase() === 'OPTIONS') {
return new Response(null, { status: 204 })
}
if (!isOpencodeProxyMethod(request.method)) {
return new Response('Method not allowed', { status: 405 })
}
const upstream = rewriteOpencodeProxyUrl(new URL(request.url))
if (!upstream) {
return new Response('Not found', { status: 404 })
}
const method = request.method.toUpperCase()
// Node's fetch types require `duplex` when forwarding a stream body.
const init: RequestInit & { duplex?: 'half' } = {
method,
headers: copyOpencodeProxyHeaders(request.headers),
redirect: 'manual',
}
if (method !== 'GET' && method !== 'HEAD') {
init.body = request.body
init.duplex = 'half'
}
return fetch(upstream, init)
}