Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

opencode-routes.ts

131 lines4.6 KB

1/** Native OpenCode routes, with unpublished request/response schemas absent. */
2import { markdownSection, markdownTableRows } from './model-facts.ts'
3import { openCodeGoHeaderParameters } from './opencode-go-facts.ts'
4import { probesFor } from './probes/index.ts'
5import { fetchText, PROVENANCE_MARKER, sha256Text } from './types.ts'
6import type {
7 OpenApiDocument,
8 OpenApiOperation,
9 SpecFetchResult,
10} from './types.ts'
11​
12export const ROUTE_ONLY_MARKER = 'x-modelschemas-route-only'
13const ROUTE_ACTIVITY = 'x-modelschemas-opencode-activity'
14const DOCS_ROOT =
15 'https://raw.githubusercontent.com/anomalyco/opencode/dev/services/site/src/docs/content/console/'
16/** Source of https://opencode.ai/docs/console/api/inference/: Zen's Endpoints table. */
17export const OPENCODE_ROUTE_DOCS_URL = `${DOCS_ROOT}api/inference.mdx`
18/** Source of https://opencode.ai/docs/console/go/: Go's per-model Endpoints table. */
19export const OPENCODE_GO_ROUTE_DOCS_URL = `${DOCS_ROOT}go.mdx`
20const ORIGIN = 'https://opencode.ai'
21​
22interface RouteRow {
23 schemaEndpointId?: string | null
24 activity?: string | null
26​
27/** Paths the page's `## Endpoints` table lists. Throws when it lists none. */
28export function documentedRoutes(text: string, url: string): Array<string> {
29 const routes: Array<string> = []
30 for (const cells of markdownTableRows(markdownSection(text, 'Endpoints'))) {
31 for (const cell of cells) {
32 const code = /^`([^`]+)`$/.exec(cell)?.[1] ?? ''
33 const path = code.startsWith(ORIGIN) ? code.slice(ORIGIN.length) : code
34 if (path.startsWith('/inference/')) routes.push(path)
35 }
36 }
37 if (routes.length === 0)
38 throw new Error(`opencode: ${url} documents no endpoint paths`)
39 return routes
41​
42/** A documented path as a matcher for a stored path. A `<placeholder>` matches one path segment. */
43function routePattern(documented: string): RegExp {
44 const escaped = documented.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
45 return new RegExp(`^${escaped.replace(/<[^>]+>/g, '[^/:]+')}$`)
47​
48/**
49 * A probed route stays route-only. The live call shows the method and a
50 * response shape; it does not publish the request schema.
51 */
52export function probeOperation(record: {
53 verifiedAt: string
54 route: string
55}): OpenApiOperation {
56 return {
57 [ROUTE_ONLY_MARKER]: true,
58 [ROUTE_ACTIVITY]: 'chat',
59 [PROVENANCE_MARKER]: {
60 derivation: 'probe-verified',
61 verifiedAt: record.verifiedAt,
62 },
63 'x-modelschemas-probe': record.route,
64 responses: {},
65 }
67​
68export async function openCodeRouteSpec(
69 rows: Array<RouteRow>,
70 docs: { url: string; text?: string; hash?: string },
71 go: boolean,
72): Promise<SpecFetchResult> {
73 const routes = rows.flatMap((row) =>
74 row.schemaEndpointId && row.activity === 'chat'
75 ? [`/${row.schemaEndpointId.replace(/^\//, '')}`]
76 : [],
77 )
78 const provider = go ? 'opencode-go' : 'opencode'
79 const probed = new Map(
80 probesFor(provider).map((record) => [`/${record.route}`, record]),
81 )
82 for (const path of probed.keys()) {
83 if (!routes.includes(path)) routes.push(path)
84 }
85 if (routes.length === 0)
86 throw new Error('opencode: catalog names no verified chat routes')
87 const url = go ? OPENCODE_GO_ROUTE_DOCS_URL : OPENCODE_ROUTE_DOCS_URL
88 const text = await fetchText(url, { signal: AbortSignal.timeout(30_000) })
89 const documented = documentedRoutes(text, url).map(routePattern)
90 const method = { url, hash: await sha256Text(text) }
91 const headers = go ? openCodeGoHeaderParameters() : undefined
92 const paths: NonNullable<OpenApiDocument['paths']> = {}
93 for (const path of routes) {
94 const record = probed.get(path)
95 if (record) {
96 paths[path] = {
97 post: { ...probeOperation(record), parameters: headers },
98 }
99 continue
100 }
101 if (!documented.some((pattern) => pattern.test(path)))
102 throw new Error(`opencode: ${url} documents no ${path} route`)
103 paths[path] = {
104 post: {
105 [ROUTE_ONLY_MARKER]: true,
106 [ROUTE_ACTIVITY]: 'chat',
107 'x-modelschemas-method-source': method,
108 ...(headers ? { parameters: headers } : {}),
109 responses: {},
110 },
111 }
112 }
113 const hash =
114 docs.hash ?? (docs.text !== undefined ? await sha256Text(docs.text) : null)
115 if (!hash) throw new Error('opencode: route spec has no catalog source')
116 return {
117 specs: [{ openapi: '3.1.0', paths }],
118 sources: [{ url: docs.url, hash }],
119 outputStrategy: 'post-200',
120 }
122​
123export function classifyOpenCodeRoute(
124 _path: string,
125 operation: Record<string, unknown>,
126): 'chat' | null {
127 return operation[ROUTE_ONLY_MARKER] === true &&
128 operation[ROUTE_ACTIVITY] === 'chat'
129 ? 'chat'
130 : null