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