zen.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. import type { APIEvent } from "@solidjs/start/server"
  2. import path from "node:path"
  3. import { and, Database, eq, isNull, sql } from "@opencode/cloud-core/drizzle/index.js"
  4. import { KeyTable } from "@opencode/cloud-core/schema/key.sql.js"
  5. import { BillingTable, UsageTable } from "@opencode/cloud-core/schema/billing.sql.js"
  6. import { centsToMicroCents } from "@opencode/cloud-core/util/price.js"
  7. import { Identifier } from "@opencode/cloud-core/identifier.js"
  8. import { Resource } from "@opencode/cloud-resource"
  9. type ModelCost = {
  10. input: number
  11. output: number
  12. cacheRead: number
  13. cacheWrite5m: number
  14. cacheWrite1h: number
  15. }
  16. type Model = {
  17. id: string
  18. auth: boolean
  19. cost: ModelCost | ((usage: any) => ModelCost)
  20. headerMappings: Record<string, string>
  21. providers: Record<
  22. string,
  23. {
  24. api: string
  25. apiKey: string
  26. model: string
  27. weight?: number
  28. }
  29. >
  30. }
  31. export async function handler(
  32. input: APIEvent,
  33. opts: {
  34. modifyBody?: (body: any) => any
  35. setAuthHeader: (headers: Headers, apiKey: string) => void
  36. parseApiKey: (headers: Headers) => string | undefined
  37. onStreamPart: (chunk: string) => void
  38. getStreamUsage: () => any
  39. normalizeUsage: (body: any) => {
  40. inputTokens: number
  41. outputTokens: number
  42. reasoningTokens?: number
  43. cacheReadTokens: number
  44. cacheWrite5mTokens?: number
  45. cacheWrite1hTokens?: number
  46. }
  47. },
  48. ) {
  49. class AuthError extends Error {}
  50. class CreditsError extends Error {}
  51. class ModelError extends Error {}
  52. const MODELS: Record<string, Model> = {
  53. "claude-opus-4-1": {
  54. id: "claude-opus-4-1" as const,
  55. auth: true,
  56. cost: {
  57. input: 0.000015,
  58. output: 0.000075,
  59. cacheRead: 0.0000015,
  60. cacheWrite5m: 0.00001875,
  61. cacheWrite1h: 0.00003,
  62. },
  63. headerMappings: {},
  64. providers: {
  65. anthropic: {
  66. api: "https://api.anthropic.com",
  67. apiKey: Resource.ANTHROPIC_API_KEY.value,
  68. model: "claude-opus-4-1-20250805",
  69. },
  70. },
  71. },
  72. "claude-sonnet-4": {
  73. id: "claude-sonnet-4" as const,
  74. auth: true,
  75. cost: (usage: any) => {
  76. const totalInputTokens =
  77. usage.inputTokens + usage.cacheReadTokens + usage.cacheWrite5mTokens + usage.cacheWrite1hTokens
  78. return totalInputTokens <= 200_000
  79. ? {
  80. input: 0.000003,
  81. output: 0.000015,
  82. cacheRead: 0.0000003,
  83. cacheWrite5m: 0.00000375,
  84. cacheWrite1h: 0.000006,
  85. }
  86. : {
  87. input: 0.000006,
  88. output: 0.0000225,
  89. cacheRead: 0.0000006,
  90. cacheWrite5m: 0.0000075,
  91. cacheWrite1h: 0.000012,
  92. }
  93. },
  94. headerMappings: {},
  95. providers: {
  96. anthropic: {
  97. api: "https://api.anthropic.com",
  98. apiKey: Resource.ANTHROPIC_API_KEY.value,
  99. model: "claude-sonnet-4-20250514",
  100. },
  101. },
  102. },
  103. "claude-3-5-haiku": {
  104. id: "claude-3-5-haiku" as const,
  105. auth: true,
  106. cost: {
  107. input: 0.0000008,
  108. output: 0.000004,
  109. cacheRead: 0.00000008,
  110. cacheWrite5m: 0.000001,
  111. cacheWrite1h: 0.0000016,
  112. },
  113. headerMappings: {},
  114. providers: {
  115. anthropic: {
  116. api: "https://api.anthropic.com",
  117. apiKey: Resource.ANTHROPIC_API_KEY.value,
  118. model: "claude-3-5-haiku-20241022",
  119. },
  120. },
  121. },
  122. "gpt-5": {
  123. id: "gpt-5" as const,
  124. auth: true,
  125. cost: {
  126. input: 0.00000125,
  127. output: 0.00001,
  128. cacheRead: 0.000000125,
  129. cacheWrite5m: 0,
  130. cacheWrite1h: 0,
  131. },
  132. headerMappings: {},
  133. providers: {
  134. openai: {
  135. api: "https://api.openai.com",
  136. apiKey: Resource.OPENAI_API_KEY.value,
  137. model: "gpt-5",
  138. },
  139. },
  140. },
  141. "qwen3-coder": {
  142. id: "qwen3-coder" as const,
  143. auth: true,
  144. cost: {
  145. input: 0.00000045,
  146. output: 0.0000018,
  147. cacheRead: 0,
  148. cacheWrite5m: 0,
  149. cacheWrite1h: 0,
  150. },
  151. headerMappings: {},
  152. providers: {
  153. baseten: {
  154. api: "https://inference.baseten.co",
  155. apiKey: Resource.BASETEN_API_KEY.value,
  156. model: "Qwen/Qwen3-Coder-480B-A35B-Instruct",
  157. weight: 4,
  158. },
  159. fireworks: {
  160. api: "https://api.fireworks.ai/inference",
  161. apiKey: Resource.FIREWORKS_API_KEY.value,
  162. model: "accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",
  163. weight: 1,
  164. },
  165. },
  166. },
  167. "kimi-k2": {
  168. id: "kimi-k2" as const,
  169. auth: true,
  170. cost: {
  171. input: 0.0000006,
  172. output: 0.0000025,
  173. cacheRead: 0,
  174. cacheWrite5m: 0,
  175. cacheWrite1h: 0,
  176. },
  177. headerMappings: {},
  178. providers: {
  179. baseten: {
  180. api: "https://inference.baseten.co",
  181. apiKey: Resource.BASETEN_API_KEY.value,
  182. model: "moonshotai/Kimi-K2-Instruct-0905",
  183. weight: 4,
  184. },
  185. fireworks: {
  186. api: "https://api.fireworks.ai/inference",
  187. apiKey: Resource.FIREWORKS_API_KEY.value,
  188. model: "accounts/fireworks/models/kimi-k2-instruct-0905",
  189. weight: 1,
  190. },
  191. },
  192. },
  193. "grok-code": {
  194. id: "grok-code" as const,
  195. auth: false,
  196. cost: {
  197. input: 0,
  198. output: 0,
  199. cacheRead: 0,
  200. cacheWrite5m: 0,
  201. cacheWrite1h: 0,
  202. },
  203. headerMappings: {
  204. "x-grok-conv-id": "x-opencode-session",
  205. "x-grok-req-id": "x-opencode-request",
  206. },
  207. providers: {
  208. xai: {
  209. api: "https://api.x.ai",
  210. apiKey: Resource.XAI_API_KEY.value,
  211. model: "grok-code",
  212. },
  213. },
  214. },
  215. // deprecated
  216. "qwen/qwen3-coder": {
  217. id: "qwen/qwen3-coder" as const,
  218. auth: true,
  219. cost: {
  220. input: 0.00000038,
  221. output: 0.00000153,
  222. cacheRead: 0,
  223. cacheWrite5m: 0,
  224. cacheWrite1h: 0,
  225. },
  226. headerMappings: {},
  227. providers: {
  228. baseten: {
  229. api: "https://inference.baseten.co",
  230. apiKey: Resource.BASETEN_API_KEY.value,
  231. model: "Qwen/Qwen3-Coder-480B-A35B-Instruct",
  232. weight: 5,
  233. },
  234. fireworks: {
  235. api: "https://api.fireworks.ai/inference",
  236. apiKey: Resource.FIREWORKS_API_KEY.value,
  237. model: "accounts/fireworks/models/qwen3-coder-480b-a35b-instruct",
  238. weight: 1,
  239. },
  240. },
  241. },
  242. }
  243. const FREE_WORKSPACES = [
  244. "wrk_01K46JDFR0E75SG2Q8K172KF3Y", // frank
  245. ]
  246. const logger = {
  247. metric: (values: Record<string, any>) => {
  248. console.log(`_metric:${JSON.stringify(values)}`)
  249. },
  250. log: console.log,
  251. debug: (message: string) => {
  252. if (Resource.App.stage === "production") return
  253. console.debug(message)
  254. },
  255. }
  256. try {
  257. const url = new URL(input.request.url)
  258. const body = await input.request.json()
  259. logger.debug(JSON.stringify(body))
  260. logger.metric({
  261. is_tream: !!body.stream,
  262. session: input.request.headers.get("x-opencode-session"),
  263. request: input.request.headers.get("x-opencode-request"),
  264. })
  265. const MODEL = validateModel()
  266. const apiKey = await authenticate()
  267. const isFree = FREE_WORKSPACES.includes(apiKey?.workspaceID ?? "")
  268. await checkCredits()
  269. const providerName = selectProvider()
  270. const providerData = MODEL.providers[providerName]
  271. logger.metric({ provider: providerName })
  272. // Request to model provider
  273. const startTimestamp = Date.now()
  274. const res = await fetch(path.posix.join(providerData.api, url.pathname.replace(/^\/zen/, "") + url.search), {
  275. method: "POST",
  276. headers: (() => {
  277. const headers = input.request.headers
  278. headers.delete("host")
  279. headers.delete("content-length")
  280. opts.setAuthHeader(headers, providerData.apiKey)
  281. Object.entries(MODEL.headerMappings ?? {}).forEach(([k, v]) => {
  282. headers.set(k, headers.get(v)!)
  283. })
  284. return headers
  285. })(),
  286. body: JSON.stringify({
  287. ...(opts.modifyBody?.(body) ?? body),
  288. model: providerData.model,
  289. }),
  290. })
  291. // Scrub response headers
  292. const resHeaders = new Headers()
  293. const keepHeaders = ["content-type", "cache-control"]
  294. for (const [k, v] of res.headers.entries()) {
  295. if (keepHeaders.includes(k.toLowerCase())) {
  296. resHeaders.set(k, v)
  297. }
  298. }
  299. // Handle non-streaming response
  300. if (!body.stream) {
  301. const json = await res.json()
  302. const body = JSON.stringify(json)
  303. logger.metric({ response_length: body.length })
  304. logger.debug(body)
  305. await trackUsage(json.usage)
  306. return new Response(body, {
  307. status: res.status,
  308. statusText: res.statusText,
  309. headers: resHeaders,
  310. })
  311. }
  312. // Handle streaming response
  313. const stream = new ReadableStream({
  314. start(c) {
  315. const reader = res.body?.getReader()
  316. const decoder = new TextDecoder()
  317. let buffer = ""
  318. let responseLength = 0
  319. function pump(): Promise<void> {
  320. return (
  321. reader?.read().then(async ({ done, value }) => {
  322. if (done) {
  323. logger.metric({ response_length: responseLength })
  324. const usage = opts.getStreamUsage()
  325. if (usage) await trackUsage(usage)
  326. c.close()
  327. return
  328. }
  329. if (responseLength === 0) {
  330. logger.metric({ time_to_first_byte: Date.now() - startTimestamp })
  331. }
  332. responseLength += value.length
  333. buffer += decoder.decode(value, { stream: true })
  334. const parts = buffer.split("\n\n")
  335. buffer = parts.pop() ?? ""
  336. for (const part of parts) {
  337. logger.debug(part)
  338. opts.onStreamPart(part.trim())
  339. }
  340. c.enqueue(value)
  341. return pump()
  342. }) || Promise.resolve()
  343. )
  344. }
  345. return pump()
  346. },
  347. })
  348. return new Response(stream, {
  349. status: res.status,
  350. statusText: res.statusText,
  351. headers: resHeaders,
  352. })
  353. function validateModel() {
  354. if (!(body.model in MODELS)) {
  355. throw new ModelError(`Model ${body.model} not supported`)
  356. }
  357. const model = MODELS[body.model as keyof typeof MODELS]
  358. logger.metric({ model: model.id })
  359. return model
  360. }
  361. async function authenticate() {
  362. try {
  363. const apiKey = opts.parseApiKey(input.request.headers)
  364. if (!apiKey) throw new AuthError("Missing API key.")
  365. const key = await Database.use((tx) =>
  366. tx
  367. .select({
  368. id: KeyTable.id,
  369. workspaceID: KeyTable.workspaceID,
  370. })
  371. .from(KeyTable)
  372. .where(and(eq(KeyTable.key, apiKey), isNull(KeyTable.timeDeleted)))
  373. .then((rows) => rows[0]),
  374. )
  375. if (!key) throw new AuthError("Invalid API key.")
  376. logger.metric({
  377. api_key: key.id,
  378. workspace: key.workspaceID,
  379. })
  380. return key
  381. } catch (e) {
  382. // ignore error if model does not require authentication
  383. if (!MODEL.auth) return
  384. throw e
  385. }
  386. }
  387. async function checkCredits() {
  388. if (!apiKey || !MODEL.auth || isFree) return
  389. const billing = await Database.use((tx) =>
  390. tx
  391. .select({
  392. balance: BillingTable.balance,
  393. })
  394. .from(BillingTable)
  395. .where(eq(BillingTable.workspaceID, apiKey.workspaceID))
  396. .then((rows) => rows[0]),
  397. )
  398. if (billing.balance <= 0) throw new CreditsError("Insufficient balance")
  399. }
  400. function selectProvider() {
  401. const picks = Object.entries(MODEL.providers).flatMap(([name, provider]) =>
  402. Array<string>(provider.weight ?? 1).fill(name),
  403. )
  404. return picks[Math.floor(Math.random() * picks.length)]
  405. }
  406. async function trackUsage(usage: any) {
  407. const { inputTokens, outputTokens, reasoningTokens, cacheReadTokens, cacheWrite5mTokens, cacheWrite1hTokens } =
  408. opts.normalizeUsage(usage)
  409. const modelCost = typeof MODEL.cost === "function" ? MODEL.cost(usage) : MODEL.cost
  410. const inputCost = modelCost.input * inputTokens * 100
  411. const outputCost = modelCost.output * outputTokens * 100
  412. const reasoningCost = reasoningTokens ? modelCost.output * reasoningTokens * 100 : undefined
  413. const cacheReadCost = modelCost.cacheRead * cacheReadTokens * 100
  414. const cacheWrite5mCost = cacheWrite5mTokens ? modelCost.cacheWrite5m * cacheWrite5mTokens * 100 : undefined
  415. const cacheWrite1hCost = cacheWrite1hTokens ? modelCost.cacheWrite1h * cacheWrite1hTokens * 100 : undefined
  416. const totalCostInCent =
  417. inputCost +
  418. outputCost +
  419. (reasoningCost ?? 0) +
  420. cacheReadCost +
  421. (cacheWrite5mCost ?? 0) +
  422. (cacheWrite1hCost ?? 0)
  423. logger.metric({
  424. "tokens.input": inputTokens,
  425. "tokens.output": outputTokens,
  426. "tokens.reasoning": reasoningTokens,
  427. "tokens.cache_read": cacheReadTokens,
  428. "tokens.cache_write_5m": cacheWrite5mTokens,
  429. "tokens.cache_write_1h": cacheWrite1hTokens,
  430. "cost.input": Math.round(inputCost),
  431. "cost.output": Math.round(outputCost),
  432. "cost.reasoning": reasoningCost ? Math.round(reasoningCost) : undefined,
  433. "cost.cache_read": Math.round(cacheReadCost),
  434. "cost.cache_write_5m": cacheWrite5mCost ? Math.round(cacheWrite5mCost) : undefined,
  435. "cost.cache_write_1h": cacheWrite1hCost ? Math.round(cacheWrite1hCost) : undefined,
  436. "cost.total": Math.round(totalCostInCent),
  437. })
  438. if (!apiKey) return
  439. const cost = isFree ? 0 : centsToMicroCents(totalCostInCent)
  440. await Database.transaction(async (tx) => {
  441. await tx.insert(UsageTable).values({
  442. workspaceID: apiKey.workspaceID,
  443. id: Identifier.create("usage"),
  444. model: MODEL.id,
  445. provider: providerName,
  446. inputTokens,
  447. outputTokens,
  448. reasoningTokens,
  449. cacheReadTokens,
  450. cacheWriteTokens: (cacheWrite5mTokens ?? 0) + (cacheWrite1hTokens ?? 0),
  451. cost,
  452. })
  453. await tx
  454. .update(BillingTable)
  455. .set({
  456. balance: sql`${BillingTable.balance} - ${cost}`,
  457. })
  458. .where(eq(BillingTable.workspaceID, apiKey.workspaceID))
  459. })
  460. await Database.use((tx) =>
  461. tx
  462. .update(KeyTable)
  463. .set({ timeUsed: sql`now()` })
  464. .where(eq(KeyTable.id, apiKey.id)),
  465. )
  466. }
  467. } catch (error: any) {
  468. logger.metric({
  469. "error.type": error.constructor.name,
  470. "error.message": error.message,
  471. })
  472. // Note: both top level "type" and "error.type" fields are used by the @ai-sdk/anthropic client to render the error message.
  473. if (error instanceof AuthError || error instanceof CreditsError || error instanceof ModelError)
  474. return new Response(
  475. JSON.stringify({
  476. type: "error",
  477. error: { type: error.constructor.name, message: error.message },
  478. }),
  479. { status: 401 },
  480. )
  481. return new Response(
  482. JSON.stringify({
  483. type: "error",
  484. error: {
  485. type: "error",
  486. message: error.message,
  487. },
  488. }),
  489. { status: 500 },
  490. )
  491. }
  492. }