Open History to see the last commit
1/**
2 * Reactor (reactor.inc) — real-time world/video models.
3 *
4 * There is no `api.reactor.inc/openapi.json`. The runtime compiles each
5 * model's command surface to OpenAPI 3.1 (`POST /events/<name>`, webhooks,
6 * `x-reactor.tracks`). The open-source JS SDK (`@reactor-team/js-sdk`)
7 * fetches that document over the session control channel via
8 * `requestSchema()` once connect() reaches `"ready"` — it is not an HTTP
9 * GET, and it costs a GPU session.
10 *
11 * The same OpenAPI is embedded in the public model API pages
12 * (`https://reactor.inc/models/{slug}/api`, Next.js RSC payload). fetchSpec
13 * pulls those pages, extracts the document, and namespaces paths under the
14 * connect slug so models do not collide. Catalog is public GET /pricing.
15 *
16 * Auth for live sessions is `Reactor-API-Key` (`rk_...`); browser clients
17 * exchange it for a JWT via POST /tokens. Sync/poll stay keyless.
18 */
19import type { Activity } from '#/db/schema.ts'
20import { contentHash } from '#/server/kv.ts'
21import { fetchText, sha256Text } from '../types.ts'
22import { reactorPricingFacts } from '../reactor-pricing.ts'
23import type { ReactorRate } from '../reactor-pricing.ts'
24import type {
25 ListModelsResult,
26 ModelInfo,
27 OpenApiDocument,
28 OpenApiOperation,
29 ProviderConfig,
30 ProviderSecrets,
31 SpecFetchResult,
32 SpecSource,
33} from '../types.ts'
34
35export const REACTOR_DOCS_URL = 'https://docs.reactor.inc'
36export const REACTOR_SITE = 'https://reactor.inc'
37export const REACTOR_API_BASE = 'https://api.reactor.inc'
38export const REACTOR_PRICING_URL = `${REACTOR_API_BASE}/pricing`
39
40type Schema = Record<string, unknown>
41
42interface ReactorModel {
43 /** Pricing catalog `name` and `/models/{slug}/api` page slug. */
44 pricingName: string
45 /** Connect slug (`modelName`). */
46 rawId: string
47 displayName: string
48 /** Override when the marketing page slug differs from pricingName. */
49 pageSlug?: string
50}
51
52/** Billing parent row — not a connect slug. */
53const SKIP_PRICING_NAMES = new Set(['happy-oyster'])
54
55const REACTOR_MODELS: Array<ReactorModel> = [
56 {
57 pricingName: 'fast-h3',
58 rawId: 'reactor/fast-h3',
59 displayName: 'FastH3',
60 },
61 {
62 pricingName: 'helios',
63 rawId: 'reactor/helios',
64 displayName: 'Helios',
65 },
66 {
67 pricingName: 'lingbot',
68 rawId: 'reactor/lingbot',
69 displayName: 'LingBot',
70 },
71 {
72 pricingName: 'lingbot-world-2',
73 rawId: 'reactor/lingbot-world-2',
74 displayName: 'LingBot World 2',
75 },
76 {
77 pricingName: 'longlive-v2',
78 rawId: 'reactor/longlive-v2',
79 displayName: 'LongLive-2.0',
80 },
81 {
82 pricingName: 'ltx2',
83 rawId: 'reactor/ltx2',
84 displayName: 'LTX',
85 pageSlug: 'ltx',
86 },
87 {
88 pricingName: 'sana-streaming',
89 rawId: 'reactor/sana-streaming',
90 displayName: 'SANA-Streaming',
91 },
92 {
93 pricingName: 'visko-orbis-stable',
94 rawId: 'reactor/visko-orbis-stable',
95 displayName: 'Visko Orbis Stable',
96 },
97 {
98 pricingName: 'visko-orbis-dynamic',
99 rawId: 'reactor/visko-orbis-dynamic',
100 displayName: 'Visko Orbis Dynamic',
101 },
102 { pricingName: 'x2', rawId: 'x2', displayName: 'X2' },
103 {
104 pricingName: 'happy-oyster-adventure',
105 rawId: 'reactor/happy-oyster-adventure',
106 displayName: 'HappyOyster Adventure',
107 pageSlug: 'happy-oyster',
108 },
109 {
110 pricingName: 'happy-oyster-director',
111 rawId: 'reactor/happy-oyster-director',
112 displayName: 'HappyOyster Directing',
113 pageSlug: 'happy-oyster',
114 },
115]
116
117const MODEL_BY_PRICING = new Map(
118 REACTOR_MODELS.map((model) => [model.pricingName, model]),
119)
120const MODEL_BY_RAW_ID = new Map(
121 REACTOR_MODELS.map((model) => [model.rawId, model]),
122)
123const RAW_IDS_LONGEST_FIRST = [...MODEL_BY_RAW_ID.keys()].sort(
124 (a, b) => b.length - a.length,
125)
126
127export function modelApiPageUrl(pageSlug: string): string {
128 return `${REACTOR_SITE}/models/${pageSlug}/api`
129}
130
131function pageSlugFor(model: ReactorModel): string {
132 return model.pageSlug ?? model.pricingName
133}
134
135function connectSlugFor(pricingName: string): string {
136 const known = MODEL_BY_PRICING.get(pricingName)
137 if (known) return known.rawId
138 if (pricingName.includes('/')) return pricingName
139 return `reactor/${pricingName}`
140}
141
142function modelForPricingName(pricingName: string): ReactorModel {
143 return (
144 MODEL_BY_PRICING.get(pricingName) ?? {
145 pricingName,
146 rawId: connectSlugFor(pricingName),
147 displayName: pricingName,
148 }
149 )
150}
151
152const JS_STRING_ESCAPES: Record<string, string> = {
153 n: '\n',
154 r: '\r',
155 t: '\t',
156 '"': '"',
157 '\\': '\\',
158 '/': '/',
159 "'": "'",
160}
161
162/**
163 * Read a JS string literal starting at `start` (the first character after
164 * the opening quote). Returns the unescaped value and the index after the
165 * closing quote.
166 */
167export function readJsString(
168 source: string,
169 start: number,
170): { value: string; end: number } | null {
171 let i = start
172 let value = ''
173 while (i < source.length) {
174 const char = source[i]
175 if (char === '\\') {
176 const next = source[i + 1]
177 if (next === undefined) return null
178 if (next === 'u' && i + 5 < source.length) {
179 const hex = source.slice(i + 2, i + 6)
180 if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null
181 value += String.fromCharCode(Number.parseInt(hex, 16))
182 i += 6
183 continue
184 }
185 value += JS_STRING_ESCAPES[next] ?? next
186 i += 2
187 continue
188 }
189 if (char === '"') return { value, end: i + 1 }
190 value += char
191 i += 1
192 }
193 return null
194}
195
196function isRecord(value: unknown): value is Record<string, unknown> {
197 return value !== null && typeof value === 'object' && !Array.isArray(value)
198}
199
200function isOpenApiDocument(value: unknown): value is OpenApiDocument {
201 if (!isRecord(value)) return false
202 if (!isRecord(value.paths)) return false
203 const openapi = value.openapi
204 return typeof openapi === 'string' && openapi.startsWith('3.')
205}
206
207const NEXT_F_STRING_CHUNK = 'self.__next_f.push([1,"'
208
209/**
210 * Pull the model's OpenAPI 3.1 document out of a Next.js RSC payload on
211 * `https://reactor.inc/models/{slug}/api`. The runtime/SDK document is not
212 * published as `openapi.json`; the marketing page embeds it as a string
213 * chunk. Same shape as `Reactor.getSchema()` / `requestSchema()`.
214 */
215export function extractOpenApiFromHtml(html: string): OpenApiDocument | null {
216 let from = 0
217 while (from < html.length) {
218 const start = html.indexOf(NEXT_F_STRING_CHUNK, from)
219 if (start < 0) return null
220 const parsed = readJsString(html, start + NEXT_F_STRING_CHUNK.length)
221 if (parsed === null) return null
222 from = parsed.end
223 if (
224 !parsed.value.includes('"paths"') ||
225 !parsed.value.includes('openapi')
226 ) {
227 continue
228 }
229 try {
230 const doc: unknown = JSON.parse(parsed.value)
231 if (isOpenApiDocument(doc)) return doc
232 } catch {
233 continue
234 }
235 }
236 return null
237}
238
239function commandNameFromPath(path: string): string {
240 const events = /\/events\/([^/]+)$/.exec(path)
241 if (events?.[1]) return events[1]
242 return path.replace(/^\//, '').replaceAll('/', '_')
243}
244
245function requestSchemaFromPost(post: OpenApiOperation): Schema {
246 const body = post.requestBody
247 if (!isRecord(body)) return { type: 'object' }
248 const content = body.content
249 if (!isRecord(content)) return { type: 'object' }
250 const json = content['application/json']
251 if (!isRecord(json)) return { type: 'object' }
252 const schema = json.schema
253 return isRecord(schema) ? schema : { type: 'object' }
254}
255
256function canonicalEnvelope(
257 spec: OpenApiDocument,
258 rawId: string,
259): OpenApiOperation {
260 const oneOf: Array<Schema> = []
261 for (const [path, operations] of Object.entries(spec.paths ?? {})) {
262 const post = operations.post
263 if (!post) continue
264 const name = commandNameFromPath(path)
265 oneOf.push({
266 type: 'object',
267 required: ['command', 'data'],
268 additionalProperties: false,
269 properties: {
270 command: { type: 'string', const: name },
271 data: requestSchemaFromPost(post),
272 },
273 })
274 }
275 return {
276 operationId: `sendCommand_${rawId.replaceAll(/[^a-zA-Z0-9]+/g, '_')}`,
277 summary: `sendCommand envelope for ${rawId}`,
278 description:
279 'WebRTC sendCommand `{ command, data }` after POST /sessions. Individual commands are also listed under /{slug}/events/* (or the model’s own paths). Same OpenAPI the JS SDK loads via requestSchema() on ready.',
280 requestBody: {
281 required: true,
282 content: {
283 'application/json': {
284 schema:
285 oneOf.length > 0
286 ? { oneOf }
287 : { type: 'object', additionalProperties: true },
288 },
289 },
290 },
291 responses: {
292 '200': {
293 description: 'Command reply',
294 content: {
295 'application/json': {
296 schema: {
297 type: 'object',
298 properties: {
299 type: { type: 'string' },
300 data: { type: 'object', additionalProperties: true },
301 },
302 },
303 },
304 },
305 },
306 },
307 }
308}
309
310function namespaceSpec(spec: OpenApiDocument, rawId: string): OpenApiDocument {
311 const clone = structuredClone(spec)
312 const namespaced: NonNullable<OpenApiDocument['paths']> = {}
313 for (const [path, operations] of Object.entries(clone.paths ?? {})) {
314 namespaced[`/${rawId}${path}`] = operations
315 }
316 namespaced[`/${rawId}`] = { post: canonicalEnvelope(spec, rawId) }
317 clone.paths = namespaced
318 clone.info ??= {}
319 clone.info['x-reactor-model'] = rawId
320 clone.servers = [
321 { url: REACTOR_API_BASE, description: 'Reactor Platform API' },
322 ]
323 return clone
324}
325
326function classify(path: string): Activity | null {
327 const bare = (path.split('?')[0] ?? path).replace(/^\//, '')
328 for (const rawId of RAW_IDS_LONGEST_FIRST) {
329 if (bare === rawId || bare.startsWith(`${rawId}/`)) return 'video'
330 }
331 if (bare.includes('/events/')) return 'video'
332 return null
333}
334
335async function fetchPageSpec(
336 pageSlug: string,
337): Promise<
338 { spec: OpenApiDocument; url: string } | { error: string; url: string }
339> {
340 const url = modelApiPageUrl(pageSlug)
341 try {
342 const html = await fetchText(url)
343 const spec = extractOpenApiFromHtml(html)
344 if (!spec) {
345 return { error: `reactor: no OpenAPI in ${url}`, url }
346 }
347 return { spec, url }
348 } catch (error) {
349 const message = error instanceof Error ? error.message : String(error)
350 return { error: `reactor: fetch ${url} failed: ${message}`, url }
351 }
352}
353
354async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
355 const warnings: Array<string> = []
356 const pageCache = new Map<
357 string,
358 { spec: OpenApiDocument; url: string } | { error: string }
359 >()
360 const specs: Array<OpenApiDocument> = []
361 const sources: Array<SpecSource> = []
362
363 for (const model of REACTOR_MODELS) {
364 const slug = pageSlugFor(model)
365 let page = pageCache.get(slug)
366 if (!page) {
367 const fetched = await fetchPageSpec(slug)
368 pageCache.set(slug, fetched)
369 page = fetched
370 }
371 if ('error' in page) {
372 if (!warnings.includes(page.error)) warnings.push(page.error)
373 continue
374 }
375 sources.push({
376 url: `${page.url}#${model.rawId}`,
377 hash: await contentHash(page.spec),
378 })
379 specs.push(namespaceSpec(page.spec, model.rawId))
380 }
381
382 if (specs.length === 0) {
383 warnings.push('reactor: every model OpenAPI page failed to extract')
384 }
385
386 return {
387 specs,
388 sources,
389 outputStrategy: 'post-200',
390 warnings: warnings.length > 0 ? warnings : undefined,
391 }
392}
393
394type PricingRate = ReactorRate
395
396interface RateSource {
397 url: string
398 hash: string
399 extractedAt: string
400}
401
402interface PricingModel {
403 id?: string
404 name?: string
405 rate?: PricingRate
406}
407
408function parsePricing(body: unknown): Array<PricingModel> {
409 if (!isRecord(body)) return []
410 const models = body.models
411 if (!Array.isArray(models)) return []
412 return models.filter((row): row is PricingModel => isRecord(row))
413}
414
415function modelInfo(
416 model: ReactorModel,
417 extras?: {
418 rate?: ReactorRate | null
419 upstreamId?: string
420 source?: RateSource
421 },
422): ModelInfo {
423 const facts =
424 extras?.source && extras.rate
425 ? reactorPricingFacts(extras.rate, extras.source)
426 : {}
427 return {
428 rawId: model.rawId,
429 displayName: model.displayName,
430 activity: 'video',
431 ...facts,
432 providerMetadata: {
433 pricingName: model.pricingName,
434 ...(extras?.upstreamId ? { upstreamId: extras.upstreamId } : {}),
435 },
436 }
437}
438
439function curatedCatalog(): Array<ModelInfo> {
440 return REACTOR_MODELS.map((model) => modelInfo(model))
441}
442
443function catalogFromPricing(
444 rows: Array<PricingModel>,
445 source: RateSource,
446): Array<ModelInfo> {
447 const seen = new Set<string>()
448 const models: Array<ModelInfo> = []
449 for (const row of rows) {
450 const name = row.name
451 if (typeof name !== 'string' || name.length === 0) continue
452 if (SKIP_PRICING_NAMES.has(name)) continue
453 const model = modelForPricingName(name)
454 if (seen.has(model.rawId)) continue
455 seen.add(model.rawId)
456 models.push(
457 modelInfo(model, {
458 rate: row.rate ?? null,
459 source,
460 upstreamId: typeof row.id === 'string' ? row.id : undefined,
461 }),
462 )
463 }
464 for (const model of REACTOR_MODELS) {
465 if (seen.has(model.rawId)) continue
466 seen.add(model.rawId)
467 models.push(modelInfo(model))
468 }
469 return models
470}
471
472async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
473 try {
474 const text = await fetchText(REACTOR_PRICING_URL)
475 const rows = parsePricing(JSON.parse(text) as unknown)
476 if (rows.length === 0) return { models: curatedCatalog() }
477 const source = {
478 url: REACTOR_PRICING_URL,
479 hash: await sha256Text(text),
480 extractedAt: new Date().toISOString(),
481 }
482 return { models: catalogFromPricing(rows, source) }
483 } catch {
484 return { models: curatedCatalog() }
485 }
486}
487
488export const provider: ProviderConfig = {
489 id: 'reactor',
490 displayName: 'Reactor',
491 authEnvVar: 'REACTOR_API_KEY',
492 specSourceUrl: `${REACTOR_SITE}/models`,
493 modelsEndpoint: REACTOR_PRICING_URL,
494 defaultDerivation: 'upstream-spec',
495 specGrain: 'model',
496 connect: {
497 servers: [{ url: REACTOR_API_BASE, description: 'Reactor Platform API' }],
498 securitySchemes: {
499 apiKey: {
500 type: 'apiKey',
501 in: 'header',
502 name: 'Reactor-API-Key',
503 description:
504 'API key starting with `rk_`. Browser clients exchange it for a session-scoped JWT via POST /tokens. The JS SDK then loads each model’s OpenAPI via requestSchema() after connect() reaches ready.',
505 },
506 },
507 security: [{ apiKey: [] }],
508 },
509 fetchSpec,
510 listModels,
511 classify,
512}