shotluma/scripts/opencode-proxy.ts
Enderson Vizcaino 952cd42c0b
fix(ai): send x-opencode-session on every OpenCode request (#23)
* fix(ai): send x-opencode-session on every OpenCode request

OpenCode Go and Zen require a stable per-conversation session id in the
x-opencode-session header so the gateway can route traffic and reuse prompt
caches (https://opencode.ai/docs/go/#where-can-i-use-it). Without it the
gateway answers "Request is missing x-opencode-session and cannot be routed
efficiently" and the run fails.

- build one module-scope session id per browser session and pass it through
  headers to all four OpenCode dialects (responses, chat, messages, google),
  which also covers the vision describer
- forward the header through the hosted Cloudflare Worker proxy, whose
  allowlist previously stripped it; the Vite dev proxy already forwarded it

* fix(ai): keep the OpenCode session id stable across reloads

The module-scope session id was regenerated on every full page load, so
reloads dropped the stable identity the OpenCode gateway needs for routing
and prompt caching.

Read the id from sessionStorage, generate one when none is stored, and
persist it; a fresh tab still gets its own id, which keeps sharding traffic
across clients. Storage that is unavailable or throws falls back to a
per-page-load id instead of failing the request.
2026-10-19 23:16:55 +02:00

92 lines
3.1 KiB
TypeScript

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.
*/
export const OPENCODE_FORWARDED_HEADERS = [
'authorization',
'content-type',
'accept',
'x-opencode-session',
'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)
}