rpc.schema.ts 5.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /**
  2. * Message-layer zod schemas for API Proxy unary calls and Host pushes. The
  3. * payload slot is unknown in the full-form schemas — business payloads get a
  4. * second parse dispatched by method (two-level parse discipline). Brand cast
  5. * point: rpcIdSchema, and only there.
  6. */
  7. import { z } from 'zod'
  8. import type { z as zCore } from 'zod'
  9. type ZodIssue = zCore.core.$ZodIssue
  10. import type { ClientRequest, RpcError, RpcId, ServerResponse } from './rpc.ts'
  11. /**
  12. * Wire widening of a contract type: widens every property (deeply) to `original | undefined`.
  13. * The repo enables exactOptionalPropertyTypes while zod `.optional()` outputs `T | undefined`,
  14. * so `satisfies z.ZodType<ContractType>` is unusable across the board; anchoring is always
  15. * written `satisfies z.ZodType<Wire<ContractType>>` — the widening only adds undefined, so
  16. * missing fields / wrong types still fail to compile. On the JSON wire, "absent" and
  17. * "value undefined" serialize identically, so the widening loses no validation semantics.
  18. */
  19. export type Wire<T> = T extends readonly (infer E)[] ? Wire<E>[]
  20. : T extends object ? { [K in keyof T]: Wire<T[K]> | undefined }
  21. : T
  22. /**
  23. * RpcId: one brand cast after schema validation (the only cast point in this
  24. * file). No min-length: the id is an opaque echo token, and rejecting values
  25. * here would only turn a correlatable error report into a client-side parse
  26. * failure (the handler substitutes a sentinel when a request's id is unreadable).
  27. */
  28. export const rpcIdSchema = z.string() as unknown as z.ZodType<RpcId>
  29. /** Error body: discriminated by code, per-branch details aligned to RpcErrorDetailsMap; details is required. */
  30. export const rpcErrorSchema: z.ZodType<RpcError> = z.discriminatedUnion('code', [
  31. z.object({ code: z.literal('bad-request'), message: z.string(), details: z.object({ issues: z.array(z.custom<ZodIssue>()) }) }),
  32. z.object({ code: z.literal('cancelled'), message: z.string(), details: z.object({}) }),
  33. z.object({ code: z.literal('session-not-found'), message: z.string(), details: z.object({ sessionId: z.string() }) }),
  34. z.object({ code: z.literal('invalid-time-zone'), message: z.string(), details: z.object({ value: z.string() }) }),
  35. z.object({ code: z.literal('directory-unreadable'), message: z.string(), details: z.object({ path: z.string() }) }),
  36. z.object({ code: z.literal('directory-exists'), message: z.string(), details: z.object({ path: z.string() }) }),
  37. z.object({ code: z.literal('directory-create-failed'), message: z.string(), details: z.object({ path: z.string() }) }),
  38. z.object({ code: z.literal('directory-picker-unavailable'), message: z.string(), details: z.object({ capability: z.string() }) }),
  39. z.object({ code: z.literal('agent-preset-read-only'), message: z.string(), details: z.object({ agentPreset: z.string(), reason: z.string() }) }),
  40. z.object({ code: z.literal('agent-preset-locked'), message: z.string(), details: z.object({ sessionId: z.string(), agentPreset: z.string() }) }),
  41. z.object({ code: z.literal('agent-preset-not-found'), message: z.string(), details: z.object({ agentPreset: z.string(), available: z.array(z.string()) }) }),
  42. z.object({ code: z.literal('agent-preset-invalid'), message: z.string(), details: z.object({ agentPreset: z.string(), reason: z.string() }) }),
  43. z.object({ code: z.literal('agent-busy'), message: z.string(), details: z.object({ reason: z.string() }) }),
  44. z.object({ code: z.literal('settings-rejected'), message: z.string(), details: z.object({ ns: z.string() }) }),
  45. z.object({ code: z.literal('settings-conflict'), message: z.string(), details: z.object({ ns: z.string(), expected: z.number(), actual: z.number() }) }),
  46. z.object({ code: z.literal('credential-rejected'), message: z.string(), details: z.object({ ref: z.string() }) }),
  47. z.object({ code: z.literal('model-discovery-failed'), message: z.string(), details: z.object({ settingsNs: z.string(), baseURL: z.string().optional() }) }),
  48. z.object({ code: z.literal('internal'), message: z.string(), details: z.object({}) }),
  49. ]) as unknown as z.ZodType<RpcError>
  50. /**
  51. * Business success/failure result schema (generic, reusable).
  52. * @param value - Schema for the business value.
  53. * @returns Schema for RpcResult<T>.
  54. */
  55. export function rpcResultSchema<T>(value: z.ZodType<T>): z.ZodUnion<readonly [z.ZodType, z.ZodType]> {
  56. return z.union([
  57. z.object({ ok: z.literal(true), value }),
  58. z.object({ ok: z.literal(false), error: rpcErrorSchema }),
  59. ])
  60. }
  61. // ---- Wire envelope schemas (payload/result.value stay wide for the second business parse) ----
  62. // The wide value slot is optional: a void business result serializes with no
  63. // `value` field at all. Each endpoint's own second parse still requires its
  64. // declared value, so absence never passes for a method that returns data.
  65. /** ClientRequest full form (payload stays wide — the business layer runs the second parse). */
  66. export const clientRequestSchema = z.object({
  67. type: z.literal('client-request'),
  68. rpcId: rpcIdSchema,
  69. method: z.string(),
  70. payload: z.unknown(),
  71. }) as unknown as z.ZodType<ClientRequest>
  72. /** ServerResponse full form (result.value stays wide). */
  73. export const serverResponseSchema = z.object({
  74. type: z.literal('server-response'),
  75. rpcId: rpcIdSchema,
  76. result: rpcResultSchema(z.unknown().optional()),
  77. }) as unknown as z.ZodType<ServerResponse>
  78. /** Wire full-form union (discriminated by type). */
  79. export const rpcMessageSchema = z.discriminatedUnion('type', [
  80. clientRequestSchema as unknown as z.ZodObject<z.ZodRawShape>,
  81. serverResponseSchema as unknown as z.ZodObject<z.ZodRawShape>,
  82. ])