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_...`). The only HTTP
17 * call is POST /tokens, which mints the session JWT. Command paths in the
18 * extracted documents (`POST /events/<name>`) are `sendCommand` messages
19 * on the session channel: fetchSpec still stores their schemas, and the
20 * assembled document publishes them as components tagged
21 * `x-modelschemas-transport: realtime`, not as paths on api.reactor.inc.
22 * Sync/poll stay keyless.
23 */
24import type { Activity } from '#/db/schema.ts'
25import { contentHash } from '#/server/kv.ts'
26import { fetchText, sha256Text } from '../types.ts'
27import { reactorPricingFacts } from '../reactor-pricing.ts'
28import type { ReactorRate } from '../reactor-pricing.ts'
29import type {
30 ListModelsResult,
31 ModelInfo,
32 OpenApiDocument,
33 OpenApiOperation,
34 ProviderConfig,
35 ProviderSecrets,
36 SpecFetchResult,
37 SpecSource,
38} from '../types.ts'
39
40export const REACTOR_DOCS_URL = 'https://docs.reactor.inc'
41export const REACTOR_SITE = 'https://reactor.inc'
42export const REACTOR_API_BASE = 'https://api.reactor.inc'
43export const REACTOR_PRICING_URL = `${REACTOR_API_BASE}/pricing`
44
45type Schema = Record<string, unknown>
46
47interface ReactorModel {
48 /** Pricing catalog `name`. */
49 pricingName: string
50 /** Catalog row id. Usually the connect slug. */
51 rawId: string
52 displayName: string
53 /** Override when the marketing page slug differs from pricingName. */
54 pageSlug?: string
55 /** Session `modelName` passed to `POST /tokens` match. Defaults to rawId. */
56 connectSlug?: string
57}
58
59/** Billing parent row — not a connect slug. */
60const SKIP_PRICING_NAMES = new Set(['happy-oyster'])
61
62const REACTOR_MODELS: Array<ReactorModel> = [
63 {
64 pricingName: 'fast-h3',
65 rawId: 'reactor/fast-h3',
66 displayName: 'FastH3',
67 },
68 {
69 pricingName: 'helios',
70 rawId: 'reactor/helios',
71 displayName: 'Helios',
72 },
73 {
74 pricingName: 'lingbot',
75 rawId: 'reactor/lingbot',
76 displayName: 'LingBot',
77 },
78 {
79 pricingName: 'lingbot-world-2',
80 rawId: 'reactor/lingbot-world-2',
81 displayName: 'LingBot World 2',
82 },
83 {
84 pricingName: 'longlive-v2',
85 rawId: 'reactor/longlive-v2',
86 displayName: 'LongLive-2.0',
87 },
88 {
89 pricingName: 'ltx2',
90 rawId: 'reactor/ltx2',
91 displayName: 'LTX',
92 pageSlug: 'ltx',
93 },
94 {
95 pricingName: 'sana-streaming',
96 rawId: 'reactor/sana-streaming',
97 displayName: 'SANA-Streaming',
98 },
99 {
100 pricingName: 'visko-orbis-stable',
101 rawId: 'reactor/visko-orbis-stable',
102 displayName: 'Visko Orbis Stable',
103 },
104 {
105 pricingName: 'visko-orbis-dynamic',
106 rawId: 'reactor/visko-orbis-dynamic',
107 displayName: 'Visko Orbis Dynamic',
108 },
109 {
110 // Same model as the stored `x2` row. /pricing and the connect slug
111 // renamed to `xmax/x2`; the marketing page stayed `/models/x2`.
112 pricingName: 'xmax/x2',
113 rawId: 'x2',
114 connectSlug: 'xmax/x2',
115 displayName: 'X2',
116 pageSlug: 'x2',
117 },
118 {
119 // XMAX X2.1, a separate editor. Pricing name is the connect slug;
120 // the page and CLI use the short slug.
121 pricingName: 'reactor/xmax-x2-1',
122 rawId: 'reactor/xmax-x2-1',
123 displayName: 'XMAX X2.1',
124 pageSlug: 'xmax-x2-1',
125 },
126 {
127 pricingName: 'happy-oyster-adventure',
128 rawId: 'reactor/happy-oyster-adventure',
129 displayName: 'HappyOyster Adventure',
130 pageSlug: 'happy-oyster',
131 },
132 {
133 pricingName: 'happy-oyster-director',
134 rawId: 'reactor/happy-oyster-director',
135 displayName: 'HappyOyster Directing',
136 pageSlug: 'happy-oyster',
137 },
138]
139
140const MODEL_BY_PRICING = new Map(
141 REACTOR_MODELS.map((model) => [model.pricingName, model]),
142)
143const MODEL_BY_RAW_ID = new Map(
144 REACTOR_MODELS.map((model) => [model.rawId, model]),
145)
146const RAW_IDS_LONGEST_FIRST = [...MODEL_BY_RAW_ID.keys()].sort(
147 (a, b) => b.length - a.length,
148)
149
150export function modelApiPageUrl(pageSlug: string): string {
151 return `${REACTOR_SITE}/models/${pageSlug}/api`
152}
153
154function pageSlugFor(model: ReactorModel): string {
155 return model.pageSlug ?? model.pricingName
156}
157
158function connectSlugFor(pricingName: string): string {
159 const known = MODEL_BY_PRICING.get(pricingName)
160 if (known) return known.rawId
161 if (pricingName.includes('/')) return pricingName
162 return `reactor/${pricingName}`
163}
164
165function modelForPricingName(pricingName: string): ReactorModel {
166 return (
167 MODEL_BY_PRICING.get(pricingName) ?? {
168 pricingName,
169 rawId: connectSlugFor(pricingName),
170 displayName: pricingName,
171 }
172 )
173}
174
175const JS_STRING_ESCAPES: Record<string, string> = {
176 n: '\n',
177 r: '\r',
178 t: '\t',
179 '"': '"',
180 '\\': '\\',
181 '/': '/',
182 "'": "'",
183}
184
185/**
186 * Read a JS string literal starting at `start` (the first character after
187 * the opening quote). Returns the unescaped value and the index after the
188 * closing quote.
189 */
190export function readJsString(
191 source: string,
192 start: number,
193): { value: string; end: number } | null {
194 let i = start
195 let value = ''
196 while (i < source.length) {
197 const char = source[i]
198 if (char === '\\') {
199 const next = source[i + 1]
200 if (next === undefined) return null
201 if (next === 'u' && i + 5 < source.length) {
202 const hex = source.slice(i + 2, i + 6)
203 if (!/^[0-9a-fA-F]{4}$/.test(hex)) return null
204 value += String.fromCharCode(Number.parseInt(hex, 16))
205 i += 6
206 continue
207 }
208 value += JS_STRING_ESCAPES[next] ?? next
209 i += 2
210 continue
211 }
212 if (char === '"') return { value, end: i + 1 }
213 value += char
214 i += 1
215 }
216 return null
217}
218
219function isRecord(value: unknown): value is Record<string, unknown> {
220 return value !== null && typeof value === 'object' && !Array.isArray(value)
221}
222
223function isOpenApiDocument(value: unknown): value is OpenApiDocument {
224 if (!isRecord(value)) return false
225 if (!isRecord(value.paths)) return false
226 const openapi = value.openapi
227 return typeof openapi === 'string' && openapi.startsWith('3.')
228}
229
230const NEXT_F_STRING_CHUNK = 'self.__next_f.push([1,"'
231
232/**
233 * Pull the model's OpenAPI 3.1 document out of a Next.js RSC payload on
234 * `https://reactor.inc/models/{slug}/api`. The runtime/SDK document is not
235 * published as `openapi.json`; the marketing page embeds it as a string
236 * chunk. Same shape as `Reactor.getSchema()` / `requestSchema()`.
237 */
238export function extractOpenApiFromHtml(html: string): OpenApiDocument | null {
239 let from = 0
240 while (from < html.length) {
241 const start = html.indexOf(NEXT_F_STRING_CHUNK, from)
242 if (start < 0) return null
243 const parsed = readJsString(html, start + NEXT_F_STRING_CHUNK.length)
244 if (parsed === null) return null
245 from = parsed.end
246 if (
247 !parsed.value.includes('"paths"') ||
248 !parsed.value.includes('openapi')
249 ) {
250 continue
251 }
252 try {
253 const doc: unknown = JSON.parse(parsed.value)
254 if (isOpenApiDocument(doc)) return doc
255 } catch {
256 continue
257 }
258 }
259 return null
260}
261
262function commandNameFromPath(path: string): string {
263 const events = /\/events\/([^/]+)$/.exec(path)
264 if (events?.[1]) return events[1]
265 return path.replace(/^\//, '').replaceAll('/', '_')
266}
267
268function requestSchemaFromPost(post: OpenApiOperation): Schema {
269 const body = post.requestBody
270 if (!isRecord(body)) return { type: 'object' }
271 const content = body.content
272 if (!isRecord(content)) return { type: 'object' }
273 const json = content['application/json']
274 if (!isRecord(json)) return { type: 'object' }
275 const schema = json.schema
276 return isRecord(schema) ? schema : { type: 'object' }
277}
278
279function canonicalEnvelope(
280 spec: OpenApiDocument,
281 rawId: string,
282): OpenApiOperation {
283 const oneOf: Array<Schema> = []
284 for (const [path, operations] of Object.entries(spec.paths ?? {})) {
285 const post = operations.post
286 if (!post) continue
287 const name = commandNameFromPath(path)
288 oneOf.push({
289 type: 'object',
290 required: ['command', 'data'],
291 additionalProperties: false,
292 properties: {
293 command: { type: 'string', const: name },
294 data: requestSchemaFromPost(post),
295 },
296 })
297 }
298 return {
299 operationId: `sendCommand_${rawId.replaceAll(/[^a-zA-Z0-9]+/g, '_')}`,
300 summary: `sendCommand envelope for ${rawId}`,
301 description:
302 '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.',
303 requestBody: {
304 required: true,
305 content: {
306 'application/json': {
307 schema:
308 oneOf.length > 0
309 ? { oneOf }
310 : { type: 'object', additionalProperties: true },
311 },
312 },
313 },
314 responses: {
315 '200': {
316 description: 'Command reply',
317 content: {
318 'application/json': {
319 schema: {
320 type: 'object',
321 properties: {
322 type: { type: 'string' },
323 data: { type: 'object', additionalProperties: true },
324 },
325 },
326 },
327 },
328 },
329 },
330 }
331}
332
333function namespaceSpec(spec: OpenApiDocument, rawId: string): OpenApiDocument {
334 const clone = structuredClone(spec)
335 const namespaced: NonNullable<OpenApiDocument['paths']> = {}
336 for (const [path, operations] of Object.entries(clone.paths ?? {})) {
337 namespaced[`/${rawId}${path}`] = operations
338 }
339 namespaced[`/${rawId}`] = { post: canonicalEnvelope(spec, rawId) }
340 clone.paths = namespaced
341 clone.info ??= {}
342 clone.info['x-reactor-model'] = rawId
343 clone.servers = [
344 { url: REACTOR_API_BASE, description: 'Reactor Platform API' },
345 ]
346 return clone
347}
348
349function classify(path: string): Activity | null {
350 const bare = (path.split('?')[0] ?? path).replace(/^\//, '')
351 for (const rawId of RAW_IDS_LONGEST_FIRST) {
352 if (bare === rawId || bare.startsWith(`${rawId}/`)) return 'video'
353 }
354 if (bare.includes('/events/')) return 'video'
355 return null
356}
357
358async function fetchPageSpec(
359 pageSlug: string,
360): Promise<
361 { spec: OpenApiDocument; url: string } | { error: string; url: string }
362> {
363 const url = modelApiPageUrl(pageSlug)
364 try {
365 const html = await fetchText(url)
366 const spec = extractOpenApiFromHtml(html)
367 if (!spec) {
368 return { error: `reactor: no OpenAPI in ${url}`, url }
369 }
370 return { spec, url }
371 } catch (error) {
372 const message = error instanceof Error ? error.message : String(error)
373 return { error: `reactor: fetch ${url} failed: ${message}`, url }
374 }
375}
376
377async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
378 const warnings: Array<string> = []
379 const pageCache = new Map<
380 string,
381 { spec: OpenApiDocument; url: string } | { error: string }
382 >()
383 const specs: Array<OpenApiDocument> = []
384 const sources: Array<SpecSource> = []
385
386 for (const model of REACTOR_MODELS) {
387 const slug = pageSlugFor(model)
388 let page = pageCache.get(slug)
389 if (!page) {
390 const fetched = await fetchPageSpec(slug)
391 pageCache.set(slug, fetched)
392 page = fetched
393 }
394 if ('error' in page) {
395 if (!warnings.includes(page.error)) warnings.push(page.error)
396 continue
397 }
398 sources.push({
399 url: `${page.url}#${model.rawId}`,
400 hash: await contentHash(page.spec),
401 })
402 specs.push(namespaceSpec(page.spec, model.rawId))
403 }
404
405 if (specs.length === 0) {
406 warnings.push('reactor: every model OpenAPI page failed to extract')
407 }
408
409 return {
410 specs,
411 sources,
412 outputStrategy: 'post-200',
413 warnings: warnings.length > 0 ? warnings : undefined,
414 }
415}
416
417type PricingRate = ReactorRate
418
419interface RateSource {
420 url: string
421 hash: string
422 extractedAt: string
423}
424
425interface PricingModel {
426 id?: string
427 name?: string
428 rate?: PricingRate
429}
430
431function parsePricing(body: unknown): Array<PricingModel> {
432 if (!isRecord(body)) return []
433 const models = body.models
434 if (!Array.isArray(models)) return []
435 return models.filter((row): row is PricingModel => isRecord(row))
436}
437
438function modelInfo(
439 model: ReactorModel,
440 extras?: {
441 rate?: ReactorRate | null
442 upstreamId?: string
443 source?: RateSource
444 },
445): ModelInfo {
446 const facts =
447 extras?.source && extras.rate
448 ? reactorPricingFacts(extras.rate, extras.source)
449 : {}
450 return {
451 rawId: model.rawId,
452 displayName: model.displayName,
453 activity: 'video',
454 ...facts,
455 providerMetadata: {
456 pricingName: model.pricingName,
457 ...(extras?.upstreamId ? { upstreamId: extras.upstreamId } : {}),
458 },
459 }
460}
461
462function catalogFromPricing(
463 rows: Array<PricingModel>,
464 source: RateSource,
465): Array<ModelInfo> {
466 const seen = new Set<string>()
467 const models: Array<ModelInfo> = []
468 for (const row of rows) {
469 const name = row.name
470 if (typeof name !== 'string' || name.length === 0) continue
471 if (SKIP_PRICING_NAMES.has(name)) continue
472 const model = modelForPricingName(name)
473 if (seen.has(model.rawId)) continue
474 seen.add(model.rawId)
475 models.push(
476 modelInfo(model, {
477 rate: row.rate ?? null,
478 source,
479 upstreamId: typeof row.id === 'string' ? row.id : undefined,
480 }),
481 )
482 }
483 for (const model of REACTOR_MODELS) {
484 if (seen.has(model.rawId)) continue
485 seen.add(model.rawId)
486 models.push(modelInfo(model))
487 }
488 return models
489}
490
491/** Wire model name for a catalog raw id. Unknown ids pass through. */
492function sessionConnectSlug(rawId: string): string {
493 return MODEL_BY_RAW_ID.get(rawId)?.connectSlug ?? rawId
494}
495
496function matchItem(pinnedModel: string | undefined): Schema {
497 return pinnedModel === undefined
498 ? {
499 type: 'string',
500 description:
501 'Connect slug (`reactor/helios`). No wildcard; list every model the token may start.',
502 }
503 : { type: 'string', enum: [sessionConnectSlug(pinnedModel)] }
504}
505
506/** Request body for `POST /tokens`. Optional fields are the documented ones. */
507export function sessionTokenRequestSchema(pinnedModel?: string): Schema {
508 return {
509 type: 'object',
510 additionalProperties: false,
511 required: ['authorization_details'],
512 properties: {
513 expires_after: {
514 type: 'integer',
515 minimum: 1,
516 description:
517 'Token lifetime in seconds. Session-scoped tokens default to 1 hour. Values at or above 21600 (6 hours) are clamped, and the response is still 200, so read expires_at.',
518 },
519 authorization_details: {
520 type: 'array',
521 minItems: 1,
522 description:
523 'Scope the token. Omitting this mints an unscoped token; the assembled operation requires it.',
524 items: {
525 type: 'object',
526 additionalProperties: false,
527 required: ['type', 'resources'],
528 properties: {
529 type: {
530 type: 'string',
531 const: 'session',
532 description:
533 'The token can create sessions and do what those sessions need, and nothing else.',
534 },
535 resources: {
536 type: 'object',
537 additionalProperties: false,
538 required: ['models'],
539 properties: {
540 models: {
541 type: 'object',
542 additionalProperties: false,
543 required: ['match'],
544 properties: {
545 match: {
546 type: 'array',
547 minItems: 1,
548 items: matchItem(pinnedModel),
549 description:
550 'Models the token may start sessions for. Every id must be visible to the API key.',
551 },
552 },
553 },
554 sessions: {
555 type: 'object',
556 additionalProperties: false,
557 required: ['bind'],
558 properties: {
559 bind: {
560 type: 'array',
561 minItems: 1,
562 items: { type: 'string' },
563 description:
564 'Open session ids, owned by this account, that this token did not create and may still act on.',
565 },
566 },
567 },
568 },
569 },
570 constraints: {
571 type: 'object',
572 additionalProperties: false,
573 properties: {
574 max_sessions: {
575 type: 'integer',
576 minimum: 1,
577 maximum: 500,
578 description:
579 'Sessions this token may create in total. Defaults to 5. Closing a session does not restore capacity.',
580 },
581 max_session_duration_seconds: {
582 type: 'integer',
583 minimum: 1,
584 maximum: 86400,
585 description:
586 'Cap every session this token creates, in seconds (24 hours). Omit for no token cap; an account maximum still applies.',
587 },
588 },
589 },
590 },
591 },
592 },
593 },
594 }
595}
596
597function sessionTokenResponseSchema(): Schema {
598 return {
599 type: 'object',
600 required: ['jwt', 'expires_at'],
601 properties: {
602 jwt: {
603 type: 'string',
604 description:
605 'Session JWT. Pass it to the JS SDK. Do not send the API key to the browser.',
606 },
607 expires_at: {
608 type: 'integer',
609 description:
610 'Unix epoch seconds when the JWT expires. The server clamps expires_after, so read this value.',
611 },
612 },
613 }
614}
615
616/**
617 * The one HTTP operation on `api.reactor.inc` that a Reactor integration
618 * calls. Command schemas stay out of `paths` (see `realtimeCommands`).
619 */
620export function reactorPlatformOperations(
621 pinnedModel: string | undefined,
622): Record<string, Record<string, OpenApiOperation>> {
623 return {
624 '/tokens': {
625 post: {
626 operationId: 'createSessionToken',
627 summary: 'Mint a session-scoped JWT',
628 description:
629 'Exchange a Reactor-API-Key for a short-lived session JWT. Send this from the server. Model commands are not HTTP on this host: their schemas are components tagged x-modelschemas-transport: realtime, and the JS SDK sends them on the session channel after connect() is ready. A missing key returns 401.',
630 parameters: [
631 {
632 name: 'Reactor-API-Key',
633 in: 'header',
634 required: true,
635 description: 'API key starting with `rk_`. Server-side only.',
636 schema: { type: 'string' },
637 },
638 ],
639 requestBody: {
640 required: true,
641 content: {
642 'application/json': {
643 schema: sessionTokenRequestSchema(pinnedModel),
644 },
645 },
646 },
647 responses: {
648 '200': {
649 description: 'Session JWT.',
650 content: {
651 'application/json': { schema: sessionTokenResponseSchema() },
652 },
653 },
654 '401': {
655 description: 'Missing or invalid Reactor-API-Key.',
656 content: {
657 'application/json': {
658 schema: {
659 type: 'object',
660 required: ['error'],
661 properties: { error: { type: 'string' } },
662 },
663 },
664 },
665 },
666 },
667 },
668 },
669 }
670}
671
672async function listModels(_env: ProviderSecrets): Promise<ListModelsResult> {
673 const text = await fetchText(REACTOR_PRICING_URL)
674 let body: unknown
675 try {
676 body = JSON.parse(text) as unknown
677 } catch (error) {
678 const message = error instanceof Error ? error.message : String(error)
679 throw new Error(`reactor: /pricing is not JSON (${message})`)
680 }
681 const rows = parsePricing(body)
682 if (rows.length === 0) {
683 throw new Error('reactor: /pricing lists no models')
684 }
685 const source = {
686 url: REACTOR_PRICING_URL,
687 hash: await sha256Text(text),
688 extractedAt: new Date().toISOString(),
689 }
690 return { models: catalogFromPricing(rows, source) }
691}
692
693export const provider: ProviderConfig = {
694 id: 'reactor',
695 displayName: 'Reactor',
696 authEnvVar: 'REACTOR_API_KEY',
697 specSourceUrl: `${REACTOR_SITE}/models`,
698 modelsEndpoint: REACTOR_PRICING_URL,
699 defaultDerivation: 'upstream-spec',
700 specGrain: 'model',
701 connect: {
702 servers: [{ url: REACTOR_API_BASE, description: 'Reactor Platform API' }],
703 securitySchemes: {
704 apiKey: {
705 type: 'apiKey',
706 in: 'header',
707 name: 'Reactor-API-Key',
708 description:
709 '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.',
710 },
711 },
712 security: [{ apiKey: [] }],
713 },
714 realtimeCommands: true,
715 platformOperations: reactorPlatformOperations,
716 fetchSpec,
717 listModels,
718 classify,
719}