Open History to see the last commit
1// Read-only local dry run of the live probes. Spends a key and calls the
2// provider; writes nothing (no file, no D1). Never prints the key.
3//
4// pnpm run probe -- <provider> <rawId> [rawId...] chat probe (#717)
5// pnpm run probe -- opencode-go legacy route records
6//
7// Chat probe: prints what each check would observe, decided or not. The
8// Worker's probe cron is what records observations (probe_observations);
9// nothing here can. Route records: prints whether each still matches.
10import { spawnSync } from 'node:child_process'
11
12import {
13 classifyProbeResponse,
14 probeBody,
15 probeChecks,
16 redactKey,
17 sendProbe,
18} from '../src/server/providers/probes/chat-completions.ts'
19import type { ChatCompletionsProbe } from '../src/server/providers/probes/chat-completions.ts'
20import { observationMatches } from '../src/server/providers/probes/compare.ts'
21import {
22 chatProbeFor,
23 chatProbes,
24 probesFor,
25} from '../src/server/providers/probes/index.ts'
26import type { ProbeRecord } from '../src/server/providers/probes/types.ts'
27
28/** Local cap: a dry run never sends more than this many requests. */
29const MAX_DRY_RUN_REQUESTS = 12
30
31const ROUTE_PROBES: Record<string, { origin: string; keyEnv: string }> = {
32 'opencode-go': {
33 origin: 'https://opencode.ai',
34 keyEnv: 'OPENCODE_GO_API_KEY',
35 },
36}
37
38// pnpm 11 passes the `--` through.
39const args = process.argv.slice(2).filter((arg) => arg !== '--')
40const [providerId, ...modelIds] = args
41const chat = providerId ? chatProbeFor(providerId) : null
42const known = [
43 ...Object.keys(ROUTE_PROBES),
44 ...chatProbes.filter((probe) => !probe.gateway).map((p) => p.provider),
45]
46if (!providerId || !known.includes(providerId)) {
47 console.error(
48 `usage: pnpm run probe -- <provider> [rawId...]\nproviders: ${known.join(', ')}`,
49 )
50 process.exit(1)
51}
52
53if (chat) await dryRunChat(chat, modelIds)
54else await checkRouteRecords()
55
56async function dryRunChat(
57 probe: ChatCompletionsProbe,
58 ids: Array<string>,
59): Promise<void> {
60 const checks = probeChecks(probe)
61 if (ids.length === 0) {
62 console.error('name at least one raw model id to probe')
63 process.exit(1)
64 }
65 if (ids.length * checks.length > MAX_DRY_RUN_REQUESTS) {
66 console.error(
67 `would send ${ids.length * checks.length} requests, over the cap of ${MAX_DRY_RUN_REQUESTS}`,
68 )
69 process.exit(1)
70 }
71 const key = readKey(probe.keyEnv)
72 for (const model of ids) {
73 for (const check of checks) {
74 const { status, text } = await sendProbe(
75 probe.url,
76 probeBody(check, model),
77 key,
78 )
79 const outcome = classifyProbeResponse(
80 check,
81 status,
82 text,
83 probe.mandatoryRule,
84 )
85 const said =
86 'undecided' in outcome
87 ? `undecided (${outcome.undecided})`
88 : `${outcome.fact} = ${String(outcome.value)} (${outcome.message})`
89 console.log(`${model} ${check}: ${redactKey(said, key)}`)
90 }
91 }
92 console.log('dry run: nothing written')
93}
94
95async function checkRouteRecords(): Promise<void> {
96 const config = ROUTE_PROBES[providerId!]!
97 const key = readKey(config.keyEnv)
98 let failed = false
99 for (const record of probesFor(providerId!)) {
100 const mismatch = await runRecord(record, config, key)
101 if (mismatch) failed = true
102 console.log(`${record.id}: ${mismatch ?? 'match'}`)
103 }
104 if (failed) process.exit(1)
105}
106
107function readKey(keyEnv: string): string {
108 const fromEnv = process.env[keyEnv]?.trim()
109 if (fromEnv) return fromEnv
110 const result = spawnSync(
111 'doppler',
112 [
113 'secrets',
114 'get',
115 keyEnv,
116 '--project',
117 'modelschemas',
118 '--config',
119 'dev',
120 '--plain',
121 ],
122 { encoding: 'utf8' },
123 )
124 const value = result.error ? '' : result.stdout.trim()
125 if (result.status !== 0 || value.length === 0) {
126 console.error(
127 `${keyEnv} is missing from the environment and from Doppler dev.`,
128 )
129 process.exit(1)
130 }
131 return value
132}
133
134async function runRecord(
135 record: ProbeRecord,
136 config: { origin: string; keyEnv: string },
137 secret: string,
138): Promise<string | null> {
139 const headers: Record<string, string> = {}
140 for (const [name, value] of Object.entries(record.request.headers)) {
141 headers[name] = value.replaceAll(`$${config.keyEnv}`, secret)
142 }
143 const response = await fetch(`${config.origin}${record.request.path}`, {
144 method: record.request.method,
145 headers,
146 body: JSON.stringify(record.request.body),
147 })
148 const text = await response.text()
149 const payloads = record.expect.sse ? ssePayloads(text) : [parseJson(text)]
150 return observationMatches(record.expect, {
151 status: response.status,
152 payloads: payloads.filter((payload) => payload !== undefined),
153 })
154}
155
156function parseJson(text: string): unknown {
157 try {
158 return JSON.parse(text) as unknown
159 } catch {
160 return undefined
161 }
162}
163
164function ssePayloads(text: string): Array<unknown> {
165 return text
166 .split('\n')
167 .filter((line) => line.startsWith('data:'))
168 .map((line) => parseJson(line.slice('data:'.length).trim()))
169 .filter((payload) => payload !== undefined)
170}