refactor(core): move more responsibility to workspace routing (#19455)

This commit is contained in:
James Long
2026-03-27 16:33:56 -04:00
committed by GitHub
parent e5f0e813b6
commit 4b9660b211
5 changed files with 102 additions and 97 deletions

View File

@@ -32,15 +32,7 @@ export const WorktreeAdaptor: Adaptor = {
const config = Config.parse(info)
await Worktree.remove({ directory: config.directory })
},
async fetch(info, input: RequestInfo | URL, init?: RequestInit) {
const { Server } = await import("../../server/server")
const config = Config.parse(info)
const url = input instanceof Request || input instanceof URL ? input : new URL(input, "http://opencode.internal")
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined))
headers.set("x-opencode-directory", config.directory)
const request = new Request(url, { ...init, headers })
return Server.Default().fetch(request)
async fetch(_info, _input: RequestInfo | URL, _init?: RequestInit) {
throw new Error("fetch not implemented")
},
}

View File

@@ -1,64 +0,0 @@
import type { MiddlewareHandler } from "hono"
import { Flag } from "../flag/flag"
import { getAdaptor } from "./adaptors"
import { WorkspaceID } from "./schema"
import { Workspace } from "./workspace"
import { InstanceRoutes } from "../server/instance"
import { lazy } from "../util/lazy"
type Rule = { method?: string; path: string; exact?: boolean; action: "local" | "forward" }
const RULES: Array<Rule> = [
{ path: "/session/status", action: "forward" },
{ method: "GET", path: "/session", action: "local" },
]
function local(method: string, path: string) {
for (const rule of RULES) {
if (rule.method && rule.method !== method) continue
const match = rule.exact ? path === rule.path : path === rule.path || path.startsWith(rule.path + "/")
if (match) return rule.action === "local"
}
return false
}
const routes = lazy(() => InstanceRoutes())
export const WorkspaceRouterMiddleware: MiddlewareHandler = async (c) => {
if (!Flag.OPENCODE_EXPERIMENTAL_WORKSPACES) {
return routes().fetch(c.req.raw, c.env)
}
const url = new URL(c.req.url)
const raw = url.searchParams.get("workspace")
if (!raw) {
return routes().fetch(c.req.raw, c.env)
}
if (local(c.req.method, url.pathname)) {
return routes().fetch(c.req.raw, c.env)
}
const workspaceID = WorkspaceID.make(raw)
const workspace = await Workspace.get(workspaceID)
if (!workspace) {
return new Response(`Workspace not found: ${workspaceID}`, {
status: 500,
headers: {
"content-type": "text/plain; charset=utf-8",
},
})
}
const adaptor = await getAdaptor(workspace.type)
const headers = new Headers(c.req.raw.headers)
headers.delete("x-opencode-workspace")
return adaptor.fetch(workspace, `${url.pathname}${url.search}`, {
method: c.req.method,
body: c.req.method === "GET" || c.req.method === "HEAD" ? undefined : await c.req.raw.arrayBuffer(),
signal: c.req.raw.signal,
headers,
})
}