Open History to see the last commit
1/** Native OpenCode routes, with unpublished request/response schemas absent. */
2import { markdownSection, markdownTableRows } from './model-facts.ts'
3import { fetchText, sha256Text } from './types.ts'
4import type { OpenApiDocument, SpecFetchResult } from './types.ts'
5
6export const ROUTE_ONLY_MARKER = 'x-modelschemas-route-only'
7const ROUTE_ACTIVITY = 'x-modelschemas-opencode-activity'
8const DOCS_ROOT =
9 'https://raw.githubusercontent.com/anomalyco/opencode/dev/services/www/src/docs/content/console/'
10/** Source of https://opencode.ai/v2/docs/console/api/inference/: Zen's Endpoints table. */
11export const OPENCODE_ROUTE_DOCS_URL = `${DOCS_ROOT}api/inference.mdx`
12/** Source of https://opencode.ai/v2/docs/console/go/: Go's per-model Endpoints table. */
13export const OPENCODE_GO_ROUTE_DOCS_URL = `${DOCS_ROOT}go.mdx`
14const ORIGIN = 'https://opencode.ai'
15
16interface RouteRow {
17 schemaEndpointId?: string | null
18 activity?: string | null
19}
20
21/** Paths the page's `## Endpoints` table lists. Throws when it lists none. */
22export function documentedRoutes(text: string, url: string): Array<string> {
23 const routes: Array<string> = []
24 for (const cells of markdownTableRows(markdownSection(text, 'Endpoints'))) {
25 for (const cell of cells) {
26 const code = /^`([^`]+)`$/.exec(cell)?.[1] ?? ''
27 const path = code.startsWith(ORIGIN) ? code.slice(ORIGIN.length) : code
28 if (path.startsWith('/inference/')) routes.push(path)
29 }
30 }
31 if (routes.length === 0)
32 throw new Error(`opencode: ${url} documents no endpoint paths`)
33 return routes
34}
35
36/** A documented path as a matcher for a stored path. A `<placeholder>` matches one path segment. */
37function routePattern(documented: string): RegExp {
38 const escaped = documented.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
39 return new RegExp(`^${escaped.replace(/<[^>]+>/g, '[^/:]+')}$`)
40}
41
42export async function openCodeRouteSpec(
43 rows: Array<RouteRow>,
44 docs: { url: string; text?: string; hash?: string },
45 go: boolean,
46): Promise<SpecFetchResult> {
47 const routes = rows.flatMap((row) =>
48 row.schemaEndpointId && row.activity === 'chat'
49 ? [`/${row.schemaEndpointId.replace(/^\//, '')}`]
50 : [],
51 )
52 if (routes.length === 0)
53 throw new Error('opencode: catalog names no verified chat routes')
54 const url = go ? OPENCODE_GO_ROUTE_DOCS_URL : OPENCODE_ROUTE_DOCS_URL
55 const text = await fetchText(url, { signal: AbortSignal.timeout(30_000) })
56 const documented = documentedRoutes(text, url).map(routePattern)
57 const method = { url, hash: await sha256Text(text) }
58 const paths: NonNullable<OpenApiDocument['paths']> = {}
59 for (const path of routes) {
60 if (!documented.some((pattern) => pattern.test(path)))
61 throw new Error(`opencode: ${url} documents no ${path} route`)
62 paths[path] = {
63 post: {
64 [ROUTE_ONLY_MARKER]: true,
65 [ROUTE_ACTIVITY]: 'chat',
66 'x-modelschemas-method-source': method,
67 responses: {},
68 },
69 }
70 }
71 const hash =
72 docs.hash ?? (docs.text !== undefined ? await sha256Text(docs.text) : null)
73 if (!hash) throw new Error('opencode: route spec has no catalog source')
74 return {
75 specs: [{ openapi: '3.1.0', paths }],
76 sources: [{ url: docs.url, hash }],
77 outputStrategy: 'post-200',
78 }
79}
80
81export function classifyOpenCodeRoute(
82 _path: string,
83 operation: Record<string, unknown>,
84): 'chat' | null {
85 return operation[ROUTE_ONLY_MARKER] === true &&
86 operation[ROUTE_ACTIVITY] === 'chat'
87 ? 'chat'
88 : null
89}