3.7 实现工具参数的 schema

在 2.4,我们只写了两行代码就声明好了库存工具的参数:

export const StockArgs = obj({ sku: str() });
export type StockArgs = Static<typeof StockArgs>;

这短短两行同时完成了三件事:

  1. 生成标准 JSON Schema:StockArgs 本身就是一个普通 JSON 对象,可以直接序列化发给大模型,告诉模型工具需要哪些参数;
  2. 推导 TypeScript 静态类型:Static<typeof StockArgs> 自动推导出 { sku: string },执行工具的代码直接享有类型检查,不用把字段再手抄一遍;
  3. 运行时校验模型输出:模型返回的工具参数属于不可信外部输入,调用工具前必须用同一个 StockArgs 做运行时校验,把缺字段、类型错或多余字段挡在外面。

这一课我们在独立的 workspace 子包 packages/nano-pi-schema/ 里从零实现这套“一份 schema 三用”的核心机制,为下一课(3.8 跑通工具调用)和后续 Agent 复用。

幽灵类型标签:Schema<T> 与 Static<S>

为什么 str() 返回的只是一个 { type: "string" } 普通对象,Static<typeof s> 却能知道它对应 string?秘诀在于 TypeScript 的幽灵类型标签(type-level brand):

declare const STATIC: unique symbol;

export type Schema<T = unknown> = JsonSchema & {
	readonly [STATIC]?: T;
};

export type Static<S> = S extends { readonly [STATIC]?: infer T }
	? unknown extends T
		? unknown
		: T
	: unknown;

同理,opt(schema) 需要同时服务于编译期和运行期:

obj() 与递归校验器 compile()

packages/nano-pi-schema/src/builders.ts 已经提供好 str、num、int、bool、lit、arr 和 opt。你需要补全 obj(properties, options):

packages/nano-pi-schema/src/validator.ts 的 compile(schema) 返回 { parse(value): ParseResult<Static<S>> }。校验函数按 JSON Schema 字段递归检查未知值 value,并用 JSON Pointer 拼接错误路径(根为 "",进入属性 sku 变为 "/sku",进入数组第 2 项变为 "/items/1"):

解答 展开 收起
GitHub 代码对比

obj() 用 isOptionalSchema() 过滤出所有未经过 opt() 标记的键名组成 required 数组,并默认把 additionalProperties 设为 false。由于 opt() 使用的是 Symbol 键,JSON.stringify() 序列化出来的依然是纯净的标准 JSON Schema。

import type { JsonSchema } from "./types.ts";

/**
 * 仅在编译期存在的“幽灵类型标签”(unique symbol),运行时不会向对象写入任何属性。
 * 作用:让普通 JSON Schema 对象额外记住“通过它校验后的 TypeScript 类型是什么”。
 */
declare const STATIC: unique symbol;

/** 仅在编译期存在的标记,用来区分 `obj()` 中哪些属性经过了 `opt()` 包装。 */
declare const OPTIONAL_TYPE: unique symbol;

/**
 * 运行时用的 Symbol 标记,用来在 `obj()` 构造 `required` 数组时识别 `opt()` 字段。
 * 为什么用 Symbol 而不是普通字符串属性:JSON.stringify() 会自动忽略 Symbol 键,
 * 这样序列化发给大模型的 JSON Schema 里不会多出任何非标准字段。
 */
export const OPTIONAL_MARK = Symbol("nano-pi-schema.optional");

/**
 * 带静态类型标签的 JSON Schema。
 * 交叉类型 `JsonSchema & { readonly [STATIC]?: T }` 表示:运行时它是普通 `JsonSchema`,
 * 编译期额外携带 `T` 供 `Static<S>` 提取。
 */
export type Schema<T = unknown> = JsonSchema & {
	readonly [STATIC]?: T;
};

/** 经过 `opt()` 包装的可选属性 Schema,同时在编译期打上 `OPTIONAL_TYPE` 标签。 */
export type OptionalSchema<T> = Schema<T> & {
	readonly [OPTIONAL_TYPE]: true;
};

/**
 * 条件类型:从任意构建器返回的 Schema 中提取它对应的 TypeScript 类型。
 * 原理拆解:`S extends { readonly [STATIC]?: infer T }` 匹配幽灵标签并把 `T` 抽出来;
 * 如果传入的只是普通无标签对象,则退回 `unknown`。
 * 展开示例:`Static<ReturnType<typeof str>>` → `string`;
 * `Static<typeof StockArgs>`(其中 `StockArgs = obj({ sku: str() })`)→ `{ sku: string }`。
 * 与官方 pi-schema 的差异:官方的 `Static<S>` 还兼容第三方 TypeBox schema,这里只处理本包构建器。
 */
export type Static<S> = S extends { readonly [STATIC]?: infer T }
	? unknown extends T
		? unknown
		: T
	: unknown;

/** `obj()` 的属性字典约束:每个键对应一个 Schema。 */
export type Properties = Readonly<Record<string, Schema>>;

/**
 * 从对象属性字典中筛选出“经过 `opt()` 包装的键名”联合类型。
 * 原理拆解:映射类型遍历 `P` 的每个键 `K`,若 `P[K]` 带有 `OPTIONAL_TYPE` 则保留键名 `K`,否则为 `never`;
 * 最后用 `[keyof P]` 取值合并成联合。
 */
type OptionalKeys<P extends Properties> = {
	[K in keyof P]: P[K] extends { readonly [OPTIONAL_TYPE]: true } ? K : never;
}[keyof P];

/** 从对象属性字典中排除可选键,剩下的就是必填键名联合。 */
type RequiredKeys<P extends Properties> = Exclude<keyof P, OptionalKeys<P>>;

/** 辅助展开类型:把交叉类型 `{ a: string } & { b?: number }` 拍平为更易读的 `{ a: string; b?: number }`。 */
type Simplify<T> = { [K in keyof T]: T[K] } & {};

/**
 * 把 `obj(properties)` 的属性字典推导出对应的 TypeScript 对象类型:
 * 必填键生成普通属性 `K: Static<P[K]>`,可选键生成带 `?` 的属性 `K?: Static<P[K]>`。
 */
export type StaticObject<P extends Properties> = Simplify<
	{ [K in RequiredKeys<P>]: Static<P[K]> } & {
		[K in OptionalKeys<P>]?: Static<P[K]>;
	}
>;

/** 构建器通用的文档注释选项。 */
export type Annotations = {
	readonly description?: string;
};

/** 字符串构建器选项:支持描述和最小/最大长度限制。 */
export type StringOptions = Annotations & {
	readonly minLength?: number;
	readonly maxLength?: number;
};

/** 数值构建器选项:支持描述和最小/最大值限制。 */
export type NumberOptions = Annotations & {
	readonly minimum?: number;
	readonly maximum?: number;
};

/** 对象构建器选项:默认 `additionalProperties` 为 `false`,拒绝模型臆造的多余字段。 */
export type ObjectOptions = Annotations & {
	readonly additionalProperties?: boolean;
};

/** 生成字符串 JSON Schema,静态类型为 `string`。 */
export function str(options: StringOptions = {}): Schema<string> {
	return { type: "string", ...options };
}

/** 生成数字 JSON Schema,静态类型为 `number`。 */
export function num(options: NumberOptions = {}): Schema<number> {
	return { type: "number", ...options };
}

/** 生成整数 JSON Schema,静态类型为 `number`。 */
export function int(options: NumberOptions = {}): Schema<number> {
	return { type: "integer", ...options };
}

/** 生成布尔值 JSON Schema,静态类型为 `boolean`。 */
export function bool(options: Annotations = {}): Schema<boolean> {
	return { type: "boolean", ...options };
}

/**
 * 生成字面量常量 JSON Schema(如 `lit("asc")`),静态类型为精确字面量 `T`。
 * 泛型参数前的 `const` 修饰符避免把 `"asc"` 拓宽成普通 `string`。
 */
export function lit<const T extends string | number | boolean>(
	value: T,
	options: Annotations = {},
): Schema<T> {
	return { const: value, ...options };
}

/** 生成数组 JSON Schema,元素类型由传入的 `item` Schema 自动推导。 */
export function arr<S extends Schema>(item: S, options: Annotations = {}): Schema<Static<S>[]> {
	return { type: "array", items: item, ...options };
}

/**
 * 标记对象中的可选字段。
 * 运行时克隆一份对象并挂上不可被 `JSON.stringify` 序列化的 `OPTIONAL_MARK`,供 `obj()` 生成 `required` 时跳过。
 */
export function opt<S extends Schema>(schema: S): OptionalSchema<Static<S>> {
	return Object.assign({}, schema, {
		[OPTIONAL_MARK]: true,
	}) as unknown as OptionalSchema<Static<S>>;
}

/**
 * 判断某个属性 Schema 是否经过了 `opt()` 标记。
 * 供 `obj()` 实现筛选 `required` 字段时调用。
 */
export function isOptionalSchema(schema: JsonSchema): boolean {
	return Boolean((schema as Record<symbol, unknown>)[OPTIONAL_MARK]);
}

/**
 * 生成对象 JSON Schema,并自动推导必填与可选属性对应的 TypeScript 对象类型。
 * 未经过 `opt()` 标记的键会自动收入 `required` 数组;`additionalProperties` 默认为 `false`。
 * @param properties 属性名到子 Schema 的映射对象。
 * @param options 可选的描述和 `additionalProperties` 开关。
 * @returns 带 `StaticObject<P>` 静态类型的对象 JSON Schema。
 */
export function obj<P extends Properties>(
	properties: P,
	options: ObjectOptions = {},
): Schema<StaticObject<P>> {
	// 1. 筛选出未经过 opt() 标记的属性键作为 JSON Schema 的 required 列表。
	const required: string[] = [];
	for (const [key, propSchema] of Object.entries(properties)) {
		if (!isOptionalSchema(propSchema)) {
			required.push(key);
		}
	}

	// 2. 组装标准对象 JSON Schema;additionalProperties 默认关闭以拦截多余字段。
	const result: Record<string, unknown> = {
		type: "object",
		...(options.description !== undefined ? { description: options.description } : {}),
		properties,
		...(required.length > 0 ? { required } : {}),
		additionalProperties: options.additionalProperties ?? false,
	};

	return result as Schema<StaticObject<P>>;
}

compile() 通过递归函数 validateValue() 依次检查 const、type、长度与数值边界、数组元素、对象必填键和额外字段,并逐层拼接 JSON Pointer 路径,最终以辨别联合 ParseResult<Static<S>> 返回结果。

import type { Static } from "./builders.ts";
import type { JsonSchema, ValidationError, Validator } from "./types.ts";

/** 判断未知值是否为普通对象(排除 null 和数组)。 */
function isPlainObject(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}

/** 拼接下一层 JSON Pointer 路径(按 RFC 6901 转义 "~" 和 "/")。 */
function childPath(basePath: string, segment: string | number): string {
	const escaped = String(segment).replace(/~/g, "~0").replace(/\//g, "~1");
	return `${basePath}/${escaped}`;
}

/** 递归校验单个值并把所有不合规项追加到 `errors` 数组。 */
function validateValue(
	schema: JsonSchema,
	value: unknown,
	path: string,
	errors: ValidationError[],
): void {
	// 1. 字面量常量约束(const):必须与期望值严格全等。
	if (schema.const !== undefined) {
		if (value !== schema.const) {
			errors.push({
				path,
				message: `期望值为 ${JSON.stringify(schema.const)}`,
			});
		}
		return;
	}

	// 2. 按基础类型分派校验逻辑,类型不匹配时直接返回,避免产生连带误报。
	switch (schema.type) {
		case "string": {
			if (typeof value !== "string") {
				errors.push({ path, message: "期望类型为字符串" });
				return;
			}
			if (schema.minLength !== undefined && value.length < schema.minLength) {
				errors.push({
					path,
					message: `字符串长度不能少于 ${schema.minLength}`,
				});
			}
			if (schema.maxLength !== undefined && value.length > schema.maxLength) {
				errors.push({
					path,
					message: `字符串长度不能超过 ${schema.maxLength}`,
				});
			}
			return;
		}

		case "number":
		case "integer": {
			const isValidNumber =
				typeof value === "number" &&
				Number.isFinite(value) &&
				(schema.type === "number" || Number.isInteger(value));
			if (!isValidNumber) {
				errors.push({
					path,
					message: schema.type === "integer" ? "期望类型为整数" : "期望类型为数字",
				});
				return;
			}
			if (schema.minimum !== undefined && value < schema.minimum) {
				errors.push({ path, message: `数值不能小于 ${schema.minimum}` });
			}
			if (schema.maximum !== undefined && value > schema.maximum) {
				errors.push({ path, message: `数值不能大于 ${schema.maximum}` });
			}
			return;
		}

		case "boolean": {
			if (typeof value !== "boolean") {
				errors.push({ path, message: "期望类型为布尔值" });
			}
			return;
		}

		case "array": {
			if (!Array.isArray(value)) {
				errors.push({ path, message: "期望类型为数组" });
				return;
			}
			if (schema.items) {
				for (let index = 0; index < value.length; index++) {
					validateValue(schema.items, value[index], childPath(path, index), errors);
				}
			}
			return;
		}

		case "object": {
			if (!isPlainObject(value)) {
				errors.push({ path, message: "期望类型为对象" });
				return;
			}

			// 3. 检查所有必填属性是否存在且非 undefined。
			for (const requiredKey of schema.required ?? []) {
				if (!Object.hasOwn(value, requiredKey) || value[requiredKey] === undefined) {
					errors.push({
						path: childPath(path, requiredKey),
						message: "缺少必填字段",
					});
				}
			}

			// 4. 逐个校验已声明属性的值;若关闭了 additionalProperties,则拒绝未声明的多余键。
			const properties = schema.properties ?? {};
			for (const [key, propValue] of Object.entries(value)) {
				if (propValue === undefined) continue;
				const propSchema = properties[key];
				if (propSchema) {
					validateValue(propSchema, propValue, childPath(path, key), errors);
				} else if (schema.additionalProperties === false) {
					errors.push({
						path: childPath(path, key),
						message: "不允许出现未声明的额外字段",
					});
				}
			}
			return;
		}

		default:
			return;
	}
}

/**
 * 把一份 JSON Schema 编译成可复用的运行时校验器。
 * 校验通过返回 `{ ok: true, value }`(类型已收窄为 `Static<S>`),
 * 校验失败返回 `{ ok: false, errors }`,每条错误带有 JSON Pointer 路径(如 `"/sku"`、`"/items/1"`)与中文说明。
 * 与官方 pi-schema 的差异:官方在编译阶段把校验规则预编译为闭包树并支持类型强制转换(coerce);
 * 这里按 JSON Schema 字段递归检查,逻辑直观且覆盖工具调用所需的核心约束。
 * @param schema 由构建器生成或手写的 JSON Schema 对象。
 * @returns 带 `parse(value)` 方法的校验器。
 */
export function compile<S extends JsonSchema>(schema: S): Validator<Static<S>> {
	return {
		parse(value: unknown) {
			const errors: ValidationError[] = [];
			validateValue(schema, value, "", errors);
			if (errors.length > 0) {
				return { ok: false, errors };
			}
			return { ok: true, value: value as Static<S> };
		},
	};
}

运行 pnpm check && pnpm test:run 同时验证 Static<typeof schema> 的编译期类型推导与四条运行时校验测试。