Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

byok.ts

136 lines3.6 KB

1import { defineByok, defaultByokStorage } from '@tanstack/ai-client/byok'
2import { byteplusByok } from '@tanstack/ai-byteplus/byok'
3import { falByok } from '@tanstack/ai-fal/byok'
4import { geminiByok } from '@tanstack/ai-gemini/byok'
5import { grokByok } from '@tanstack/ai-grok/byok'
6import { openrouterByok } from '@tanstack/ai-openrouter/byok'
7import { reactorByok } from '@tanstack/ai-reactor/byok'
8import { worldlabsByok } from '@tanstack/ai-worldlabs/byok'
9import { createServerFn } from '@tanstack/react-start'
10import {
11 ByokBlockedError,
12 ByokMissingError,
13 isByokMissingBody,
14} from '@tanstack/ai/byok'
15import type { ProviderId } from '@tanstack/ai/byok'
16​
17export {
18 byteplusByok,
19 falByok,
20 geminiByok,
21 grokByok,
22 openrouterByok,
23 reactorByok,
24 worldlabsByok,
26​
27export const KEYED_PROVIDERS = [
28 falByok,
29 geminiByok,
30 grokByok,
31 openrouterByok,
32 byteplusByok,
33 reactorByok,
34 worldlabsByok,
35] as const
36​
37export const byok = defineByok({
38 storage: defaultByokStorage(),
39 providers: KEYED_PROVIDERS,
40})
41​
42// Let the relay decide when a key is missing. The server prefers the
43// `x-byok-*` header, then env.
44byok.setServerCoverage(true)
45​
46export function toByokProvider(
47 provider:
48 | 'fal'
49 | 'gemini'
50 | 'xai'
51 | 'byteplus'
52 | 'openrouter'
53 | 'reactor'
54 | 'worldlabs',
55): ProviderId {
56 if (provider === 'xai') return grokByok.id
57 return provider
59​
60function byokMissingFromUnknown(value: unknown): ByokMissingError | null {
61 if (value instanceof ByokMissingError) return value
62 if (isByokMissingBody(value)) {
63 return new ByokMissingError(value.error.provider)
64 }
65 if (!(value instanceof Error)) return null
66 try {
67 const parsed: unknown = JSON.parse(value.message)
68 if (isByokMissingBody(parsed)) {
69 return new ByokMissingError(parsed.error.provider)
70 }
71 } catch {
72 // The message is not a byok_missing JSON body.
73 }
74 return null
76​
77/**
78 * Start serializes a thrown `byokMissing()` Response as a 401 whose body
79 * is the JSON string. Rehydrate that (or a raw Response) into
80 * `ByokMissingError` so generation hooks and Live/World can `byok.request`.
81 */
82async function throwIfFailedResponse(response: Response): Promise<never> {
83 const text = await response.clone().text()
84 let parsed: unknown
85 try {
86 parsed = JSON.parse(text)
87 } catch {
88 parsed = null
89 }
90 const missing = byokMissingFromUnknown(parsed)
91 if (missing) throw missing
92 throw new Error(
93 `Request failed (${response.status})${text ? `: ${text}` : ''}`,
94 )
96​
97export async function callWithByok<T>(task: Promise<T>): Promise<T> {
98 try {
99 const result = await task
100 if (result instanceof Response) {
101 await throwIfFailedResponse(result)
102 }
103 return result
104 } catch (error) {
105 if (error instanceof Response) {
106 await throwIfFailedResponse(error)
107 }
108 const missing = byokMissingFromUnknown(error)
109 if (missing) throw missing
110 throw error
111 }
113​
114/** Open the key dialog for a missing or locked key. */
115export function requestByokFromError(error: unknown): void {
116 if (error instanceof ByokMissingError) {
117 byok.request(error.provider, 'missing')
118 return
119 }
120 if (error instanceof ByokBlockedError) {
121 byok.request(error.provider, error.reason)
122 }
124​
125/** Booleans only — which keyed providers have an env key on the relay. */
126export const getEnvKeyStatus = createServerFn({ method: 'GET' }).handler(
127 (): Record<string, boolean> => {
128 const status: Record<string, boolean> = {}
129 for (const provider of KEYED_PROVIDERS) {
130 status[provider.id] = (provider.env ?? []).some((name) =>
131 Boolean(process.env[name]),
132 )
133 }
134 return status
135 },