import { z } from "zod"; import { validationError } from "../../../core/errors.js"; import type { SealCapability } from "./index.js"; /** * Checks one invocation's params against the schema its tool declares, then * returns the params unchanged. * * Both dispatch paths — `runCapabilityResult` (every CLI command) and * `executeSealCapability` (`POST /api/tool/:name`, every `/v1/*` route) — used to * hand `params` straight to `handler`, so a required field could be missing, a * limit could be `999999`, or a typo'd HTTP body key could sail through and * surface later as an opaque upstream error or a `Cannot read properties of * undefined`. The schema is now the gate, failing fast with the offending field * path (exit `13` on the CLI, HTTP `400` behind the adapter). * * Two deliberate properties: * * - **Original params are returned, not `result.data`.** Handlers read keys the * schema does not declare — `seal_deploy_hosecloud_configure` accepts the * legacy `appKey`/`appSecurity` aliases alongside `apiKey`/`apiSecret` — and * zod's default strip would silently drop them. Validation must never change * what a working handler receives, only block what would have failed anyway. * - **Undeclared keys never fail.** `z.object` is non-strict, so an extra HTTP * body key is ignored rather than rejected; this is a correctness check, not * an API-compatibility verdict. * * Before rejecting, wire-format values are coerced to the shape the schema * declares (see {@link coerceWireTypes}) because `/v1/*` query strings arrive * entirely as strings while the schema says `z.number()`. */ export function parseCapabilityParams(tool: SealCapability, params: Record): Record { const result = tool.parameters.safeParse(coerceWireTypes(tool.parameters, params)); if (result.success) return params; const detail = result.error.issues .map((issue) => `${issue.path.length ? issue.path.join(".") : "(root)"}: ${issue.message}`) .join("; "); throw validationError(`Invalid parameters for ${tool.name}: ${detail}`); } /** * Rewrites string-shaped query/body values into the type the schema declares * for that key: `"10"` → `10` for `z.number()`, `"true"` → `true` for * `z.boolean()`, `"id,code"` → `["id", "code"]` for `z.array()`. * * Query strings carry no types, so without this every `/v1/*` route that passes * `url.searchParams` through would fail against `z.number().int()` — while a * value that merely looks wrong (`"abc"` for a number) is left alone so zod * reports it instead of hiding it behind a NaN. * * Only top-level keys are touched: nested params arrive as parsed JSON (already * typed), and skipping declared-but-uncoercible leaves errors to zod rather * than guessing. */ function coerceWireTypes(schema: z.ZodType, params: Record): Record { const shape = (schema as z.ZodObject).shape; if (!shape) return params; const coerced = { ...params }; for (const [key, def] of Object.entries(shape)) { const value = coerced[key]; if (typeof value !== "string" || value === "") continue; const target = unwrapType(def); if (target === "number" && /^[+-]?\d+(?:\.\d+)?$/.test(value.trim())) { coerced[key] = Number(value.trim()); } else if (target === "boolean") { if (value === "true") coerced[key] = true; else if (value === "false") coerced[key] = false; } else if (target === "array") { const items = value.split(",").map((item) => item.trim()).filter(Boolean); if (items.length) coerced[key] = items; } } return coerced; } /** * Resolves a field's concrete type name, stepping through `optional` / * `default` / `nullable` wrappers: `"limit: optional"` → `"number"`. * * zod v4 exposes `type` on the schema instance but keeps `innerType` on * `_def`, so both shapes are read — a wrapper reached via `_def.innerType` is * an instance again, and an object reached by other means may be a bare def. */ function unwrapType(schema: unknown): string | undefined { let current = schema as | { type?: string; innerType?: unknown; _def?: { type?: string; innerType?: unknown } } | undefined; // Depth bound: wrappers nest shallowly in practice; anything deeper is a // shape this helper should decline to interpret rather than chase. for (let depth = 0; current && depth < 8; depth++) { const def = current._def ?? current; const type = def.type ?? current.type; if (type === "optional" || type === "default" || type === "nullable") { current = (def.innerType ?? current.innerType) as typeof current; continue; } return type; } return undefined; }