handler.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. /**
  2. * Server side of the fetch carrier: maps an ApiProxy onto a pure
  3. * WHATWG Request->Response function. Two-level parse: full form (type/rpcId/method +
  4. * path==method) -> payload dispatched per method. HTTP status expresses only the carrier
  5. * (404 unknown path / 400 non-JSON body / 500 handler crash); business errors are always
  6. * 200 + ServerResponse.
  7. */
  8. import { randomUUID } from 'node:crypto'
  9. import type { z } from 'zod'
  10. import type { ApiProxy, MuxFrame, HostFrame } from '../api/index.ts'
  11. import type { RequestPayload, ResponseValue, RpcMethodMap } from '../api/rpc-map.ts'
  12. import type { ClientRequest, RpcError, RpcRequest, RpcResponse, ServerRequest, ServerResponse } from '../api/rpc.ts'
  13. import { RpcId } from '../api/rpc.ts'
  14. import type { Wire } from '../api/rpc.schema.ts'
  15. import { clientRequestSchema, clientResponseSchema } from '../api/rpc.schema.ts'
  16. import {
  17. sessionCancelRequestSchema,
  18. sessionCreateRequestSchema,
  19. sessionHistoryRequestSchema,
  20. sessionListRequestSchema,
  21. sessionModelsRequestSchema,
  22. sessionPromptRequestSchema,
  23. sessionSelectModelRequestSchema,
  24. } from '../api/sessions.schema.ts'
  25. import { hostDescribeRequestSchema } from '../api/host.schema.ts'
  26. import {
  27. workspaceCreateRequestSchema,
  28. workspaceInsertSessionBeforeRequestSchema,
  29. workspaceListRequestSchema,
  30. workspaceRenameRequestSchema,
  31. } from '../api/workspace.schema.ts'
  32. /**
  33. * Unary dispatch table, keyed by (and compiler-locked to) RpcMethodMap: a map row without a
  34. * route row fails to compile, and each row's schema/invoke pair is checked against that row's
  35. * payload type — a schema pasted onto the wrong row is a type error, not a runtime surprise.
  36. * Schemas anchor to the Wire<> widening (the repo-wide exactOptionalPropertyTypes accommodation
  37. * documented on Wire); the dispatch point carries the one Wire→exact cast.
  38. */
  39. type UnaryRoutes = {
  40. [K in keyof RpcMethodMap]: {
  41. schema: z.ZodType<Wire<RequestPayload<K>>>
  42. invoke(api: ApiProxy, request: RpcRequest<RequestPayload<K>>): Promise<RpcResponse<ResponseValue<K>>>
  43. }
  44. }
  45. const UNARY_ROUTES: UnaryRoutes = {
  46. 'session.list': { schema: sessionListRequestSchema, invoke: (api, r) => api.sessions.list(r) },
  47. 'session.create': { schema: sessionCreateRequestSchema, invoke: (api, r) => api.sessions.create(r) },
  48. 'session.history': { schema: sessionHistoryRequestSchema, invoke: (api, r) => api.sessions.history(r) },
  49. 'session.models': { schema: sessionModelsRequestSchema, invoke: (api, r) => api.sessions.models(r) },
  50. 'session.selectModel': { schema: sessionSelectModelRequestSchema, invoke: (api, r) => api.sessions.selectModel(r) },
  51. 'session.prompt': { schema: sessionPromptRequestSchema, invoke: (api, r) => api.sessions.prompt(r) },
  52. 'session.cancel': { schema: sessionCancelRequestSchema, invoke: (api, r) => api.sessions.cancel(r) },
  53. 'host.describe': { schema: hostDescribeRequestSchema, invoke: (api, r) => api.host.describe(r) },
  54. 'workspace.list': { schema: workspaceListRequestSchema, invoke: (api, r) => api.workspace.list(r) },
  55. 'workspace.create': { schema: workspaceCreateRequestSchema, invoke: (api, r) => api.workspace.create(r) },
  56. 'workspace.rename': { schema: workspaceRenameRequestSchema, invoke: (api, r) => api.workspace.rename(r) },
  57. 'workspace.insertSessionBefore': { schema: workspaceInsertSessionBeforeRequestSchema, invoke: (api, r) => api.workspace.insertSessionBefore(r) },
  58. }
  59. /** Route lookup that narrows an arbitrary path segment to a map key (single cast point for the string→key refinement). */
  60. function methodFor(path: string): keyof RpcMethodMap | undefined {
  61. return Object.hasOwn(UNARY_ROUTES, path) ? path as keyof RpcMethodMap : undefined
  62. }
  63. /**
  64. * Sentinel rpcId for error responses to envelopes whose own rpcId is unreadable: the response
  65. * must still be a valid ServerResponse (a self-violating shape would turn the server's explicit
  66. * bad-request report into a client-side parse failure). Fixed value, documented here as wire contract.
  67. */
  68. const INVALID_REQUEST_RPC_ID = RpcId('invalid-request')
  69. /** Wrap a business error as a ServerResponse full form (rpcId backfilled; an unreadable rpcId uses the invalid-request sentinel). */
  70. function errorResponse(rpcId: RpcId, error: RpcError): Response {
  71. const body: ServerResponse = { type: 'server-response', rpcId, result: { ok: false, error } }
  72. return Response.json(body)
  73. }
  74. /** Complete the impl's narrow form into a ServerResponse full form. */
  75. function fullResponse(narrow: RpcResponse<unknown>): Response {
  76. const body: ServerResponse = { type: 'server-response', rpcId: narrow.rpcId, result: narrow.result }
  77. return Response.json(body)
  78. }
  79. /**
  80. * Parse the payload and invoke one unary route. Generic over the map key so
  81. * the row's schema/invoke pairing typechecks; the only cast collapses the
  82. * Wire<> widening back to the exact payload (undefined-valued properties and
  83. * absent ones are indistinguishable after JSON transport).
  84. */
  85. // K appears once in the signature but ties the UNARY_ROUTES[K] row lookup to its own
  86. // schema/invoke pairing; a union parameter degrades the row to an uninvokable intersection.
  87. // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-parameters
  88. async function handleUnary<K extends keyof RpcMethodMap>(api: ApiProxy, method: K, message: ClientRequest): Promise<Response> {
  89. const route = UNARY_ROUTES[method]
  90. const payload = route.schema.safeParse(message.payload)
  91. if (!payload.success) {
  92. return errorResponse(message.rpcId, { code: 'bad-request', message: `invalid payload for ${method}`, details: { issues: payload.error.issues } })
  93. }
  94. try {
  95. return fullResponse(await route.invoke(api, { rpcId: message.rpcId, payload: payload.data }))
  96. } catch (error: unknown) {
  97. // The impl never throws business errors; reaching here means the implementation itself crashed — 500, carrier layer.
  98. return new Response(`handler failure: ${String(error)}`, { status: 500 })
  99. }
  100. }
  101. /** SSE frame: complete the narrow RpcRequest<frame> into a ServerRequest full form (method = frame type). */
  102. function fullFrame(narrow: RpcRequest<MuxFrame | HostFrame>): ServerRequest {
  103. return { type: 'server-request', rpcId: narrow.rpcId, method: narrow.payload.type, payload: narrow.payload }
  104. }
  105. /**
  106. * Wrap a frame stream as an SSE Response; stops when req.signal aborts. An
  107. * impl throw mid-stream emits one stream/error frame and then closes.
  108. */
  109. function sseResponse(frames: AsyncIterable<RpcRequest<MuxFrame | HostFrame>>): Response {
  110. const encoder = new TextEncoder()
  111. const stream = new ReadableStream<Uint8Array>({
  112. async start(controller) {
  113. try {
  114. // Send an SSE comment line on open so clients/proxies see a live channel (the host
  115. // stream has no baseline frames and would otherwise emit zero bytes while idle;
  116. // a comment line is not a frame, so client frame parsing skips it naturally).
  117. controller.enqueue(encoder.encode(': connected\n\n'))
  118. for await (const narrow of frames) {
  119. controller.enqueue(encoder.encode(`data: ${JSON.stringify(fullFrame(narrow))}\n\n`))
  120. }
  121. } catch (error: unknown) {
  122. // Mid-stream impl failure → one stream/error frame, then close: the client must see
  123. // the failure instead of a silent end (which reads as a normal disconnect). A fresh
  124. // rpcId is minted — this is a server-initiated push like any other frame.
  125. const failure: MuxFrame | HostFrame = { type: 'stream/error', error: { code: 'internal', message: String(error), details: {} } }
  126. try {
  127. controller.enqueue(encoder.encode(`data: ${JSON.stringify(fullFrame({ rpcId: RpcId(randomUUID()), payload: failure }))}\n\n`))
  128. } catch {
  129. // Consumer already cancelled the stream: enqueue-after-cancel is the
  130. // only reachable error, and there is no one left to tell.
  131. }
  132. } finally {
  133. try {
  134. controller.close()
  135. } catch { /* already cancelled by the consumer: a double close is the only reachable error */ }
  136. }
  137. },
  138. })
  139. return new Response(stream, {
  140. headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' },
  141. })
  142. }
  143. /**
  144. * Wraps an ApiProxy into a pure fetch function (isomorphic point: feed the returned fetch straight to InProcessApiClient).
  145. * @param api - the host-side ApiProxy implementation.
  146. * @returns an object holding `fetch(Request)`; paths outside /api/ return 404.
  147. */
  148. export function toFetchHandler(api: ApiProxy): { fetch: typeof fetch } {
  149. return {
  150. // Signature matches global fetch: the isomorphic point hands this function to InProcessApiClient as its transport aspect,
  151. // Clients call in (url, init) form — normalize to Request before handling.
  152. async fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
  153. const req = input instanceof Request ? input : new Request(input, init)
  154. const url = new URL(req.url)
  155. const path = url.pathname
  156. if (path === '/api/events.mux' && req.method === 'GET') {
  157. return sseResponse(api.events.mux({ rpcId: RpcId(randomUUID()), payload: {} }, req.signal))
  158. }
  159. if (path === '/api/events.host' && req.method === 'GET') {
  160. return sseResponse(api.events.host({ rpcId: RpcId(randomUUID()), payload: {} }, req.signal))
  161. }
  162. if (req.method !== 'POST' || !path.startsWith('/api/')) {
  163. return new Response('not found', { status: 404 })
  164. }
  165. let body: unknown
  166. try {
  167. body = await req.json()
  168. } catch {
  169. // 400 = carrier layer (body is not even JSON); valid JSON with a bad shape goes 200 + bad-request.
  170. return new Response('body is not JSON', { status: 400 })
  171. }
  172. if (path === '/api/respond') {
  173. const parsed = clientResponseSchema.safeParse(body)
  174. if (!parsed.success) return Response.json({ accepted: false, reason: 'bad-response' })
  175. return Response.json(await api.respond(parsed.data))
  176. }
  177. const method = methodFor(path.slice('/api/'.length))
  178. if (method === undefined) return new Response('not found', { status: 404 })
  179. const envelope = clientRequestSchema.safeParse(body)
  180. if (!envelope.success) {
  181. // Best effort at correlation: salvage a string rpcId from the raw body;
  182. // otherwise the fixed sentinel keeps the response a valid ServerResponse.
  183. const rawId = (body as { rpcId?: unknown } | null)?.rpcId
  184. const rpcId = typeof rawId === 'string' ? RpcId(rawId) : INVALID_REQUEST_RPC_ID
  185. return errorResponse(rpcId, { code: 'bad-request', message: 'invalid client-request message', details: { issues: envelope.error.issues } })
  186. }
  187. const message: ClientRequest = envelope.data
  188. if (message.method !== method) {
  189. return errorResponse(message.rpcId, { code: 'bad-request', message: `method "${message.method}" does not match path "${method}"`, details: { issues: [] } })
  190. }
  191. return handleUnary(api, method, message)
  192. },
  193. }
  194. }