handler.ts 11 KB

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