handler.ts 13 KB

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