Open History to see the last commit
1/**
2 * Facts OpenCode publishes for every Go request, plus training on request
3 * data. The live models list states it as `go.training` (issue #675). The
4 * same list states each route as `api.<protocol>.base_url` (issue #679).
5 * A probe record still states training for an id the list does not mention.
6 */
7import { requiredHeaderParameters } from './connect.ts'
8import { probesFor } from './probes/index.ts'
9import type { FactSource, ModelFactSources, RequiredHeader } from './types.ts'
10
11/** https://opencode.ai/docs/console/go/ (`/docs/go/` 301s here). */
12export const OPENCODE_GO_DOCS_URL = 'https://opencode.ai/docs/console/go/'
13
14/** Live Go model list. Each row's `api` states that model's route. */
15export const OPENCODE_GO_MODELS_URL =
16 'https://opencode.ai/inference/go/v1/models'
17
18const OPENCODE_ORIGIN = 'https://opencode.ai'
19
20/**
21 * Path under `api.<protocol>.base_url`. `generate-content` is Google's
22 * method: the model id is one path segment, the same shape as
23 * `:generateContent` on the probe records. `interactions` is Google's
24 * Interactions API: `POST {base}/interactions`, and the model id is a
25 * request-body field, not a path segment. OpenCode publishes no request
26 * schema for either route, so both stay route-only (`opencode-routes.ts`).
27 * A key this map does not name is an unknown shape.
28 */
29const GO_PROTOCOL_PATH: Record<string, (id: string) => string> = {
30 'chat-completions': () => 'chat/completions',
31 responses: () => 'responses',
32 messages: () => 'messages',
33 'generate-content': (id) => {
34 if (id.includes('/') || id.includes(':')) {
35 throw new Error(`opencode-go: unreadable model id ${id}`)
36 }
37 return `models/${id}:generateContent`
38 },
39 interactions: () => 'interactions',
40}
41
42export const OPENCODE_GO_REQUIRED_HEADERS: Array<RequiredHeader> = [
43 {
44 name: 'x-opencode-session',
45 description:
46 'A stable session id the client chooses for each conversation.',
47 },
48 {
49 name: 'User-Agent',
50 description:
51 'A client-specific User-Agent, such as my-coding-agent/1.0, not a generic SDK or HTTP-library name.',
52 },
53]
54
55/** OpenAPI header parameters for every Go operation. Values are not constants. */
56export function openCodeGoHeaderParameters(): Array<Record<string, unknown>> {
57 return requiredHeaderParameters(OPENCODE_GO_REQUIRED_HEADERS).map(
58 (parameter) => ({
59 ...parameter,
60 description: `${String(parameter.description)} ${OPENCODE_GO_DOCS_URL}`,
61 }),
62 )
63}
64
65const HEADER_SOURCE: FactSource = {
66 derivation: 'docs-derived',
67 sourceUrl: OPENCODE_GO_DOCS_URL,
68 path: 'Where can I use it?',
69}
70
71function isRecord(value: unknown): value is Record<string, unknown> {
72 return typeof value === 'object' && value !== null && !Array.isArray(value)
73}
74
75/**
76 * `go.training` on each id of `GET /v1/models` for Go. That boolean is what
77 * https://opencode.ai/console/go#privacy shows. `true` trains. `false` is a
78 * stated no. Throws when a listed id has no boolean: a missing field is an
79 * unknown shape, not an unstated fact.
80 */
81export function goTrainsOnRequestData(payload: unknown): Map<string, boolean> {
82 if (!isRecord(payload) || !Array.isArray(payload.data)) {
83 throw new Error('opencode-go: models payload has no data array')
84 }
85 const training = new Map<string, boolean>()
86 for (const row of payload.data) {
87 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
88 continue
89 }
90 const go = row.go
91 if (!isRecord(go) || typeof go.training !== 'boolean') {
92 throw new Error(`opencode-go: ${row.id} has no go.training boolean`)
93 }
94 training.set(row.id, go.training)
95 }
96 if (training.size === 0) {
97 throw new Error('opencode-go: models payload listed no ids')
98 }
99 return training
100}
101
102function goApiPath(id: string, protocol: string, baseUrl: string): string {
103 const url = URL.parse(baseUrl)
104 const path = url?.pathname.replace(/\/$/, '') ?? ''
105 if (
106 url?.origin !== OPENCODE_ORIGIN ||
107 path.length === 0 ||
108 url.search.length > 0 ||
109 url.hash.length > 0
110 ) {
111 throw new Error(
112 `opencode-go: ${id} api.${protocol}.base_url is not an opencode.ai path`,
113 )
114 }
115 const suffix = Object.hasOwn(GO_PROTOCOL_PATH, protocol)
116 ? GO_PROTOCOL_PATH[protocol]
117 : undefined
118 if (!suffix) {
119 throw new Error(`opencode-go: ${id} has unknown api protocol ${protocol}`)
120 }
121 return `${path}/${suffix(id)}`
122}
123
124/**
125 * Routes `GET /v1/models` states for Go: `api.<protocol>.base_url` plus
126 * that protocol's path. Cost, limits, and capabilities on the same row are
127 * unread. Throws when a listed id has no `api` entry or an unknown
128 * protocol key: a missing field is an unknown shape, not an unstated route.
129 */
130export function goListingRoutes(payload: unknown): Array<string> {
131 if (!isRecord(payload) || !Array.isArray(payload.data)) {
132 throw new Error('opencode-go: models payload has no data array')
133 }
134 const routes: Array<string> = []
135 const seen = new Set<string>()
136 for (const row of payload.data) {
137 if (!isRecord(row) || typeof row.id !== 'string' || row.id.length === 0) {
138 continue
139 }
140 const api = row.api
141 if (!isRecord(api) || Object.keys(api).length === 0) {
142 throw new Error(`opencode-go: ${row.id} has no api entry`)
143 }
144 for (const [protocol, entry] of Object.entries(api)) {
145 if (!Object.hasOwn(GO_PROTOCOL_PATH, protocol)) {
146 throw new Error(
147 `opencode-go: ${row.id} has unknown api protocol ${protocol}`,
148 )
149 }
150 if (!isRecord(entry) || typeof entry.base_url !== 'string') {
151 throw new Error(`opencode-go: ${row.id} api.${protocol} is unreadable`)
152 }
153 const route = goApiPath(row.id, protocol, entry.base_url)
154 if (seen.has(route)) continue
155 seen.add(route)
156 routes.push(route)
157 }
158 }
159 if (routes.length === 0) {
160 throw new Error('opencode-go: models payload listed no ids')
161 }
162 routes.sort()
163 return routes
164}
165
166export function openCodeGoFacts(
167 providerId: string,
168 rawId: string,
169): {
170 requiredRequestHeaders: Array<RequiredHeader> | null
171 trainsOnRequestData: boolean | null
172 factSources: Pick<
173 ModelFactSources,
174 'requiredRequestHeaders' | 'trainsOnRequestData'
175 >
176} {
177 if (providerId !== 'opencode-go') {
178 return {
179 requiredRequestHeaders: null,
180 trainsOnRequestData: null,
181 factSources: {},
182 }
183 }
184 const training = probesFor(providerId).find(
185 (record) => record.model === rawId && record.trainsOnRequestData === true,
186 )
187 return {
188 requiredRequestHeaders: OPENCODE_GO_REQUIRED_HEADERS,
189 trainsOnRequestData: training ? true : null,
190 factSources: {
191 requiredRequestHeaders: HEADER_SOURCE,
192 ...(training
193 ? {
194 trainsOnRequestData: {
195 derivation: 'probe-verified' as const,
196 verifiedAt: training.verifiedAt,
197 sourceUrl: `src/server/providers/probes/opencode-go.ts#${training.id}`,
198 },
199 }
200 : {}),
201 },
202 }
203}