handler.ts 16 KB

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