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

opencode-routes.ts

155 lines5.2 KB

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