JsonSchema
CORE · type · 类型合同
JSON Schema as consumed by the App's validator; Core never interprets its contents.
导入
ts
import type { JsonSchema } from '@jangts/agent-core';js
/** @typedef {import('@jangts/agent-core').JsonSchema} JsonSchema */其他公开入口:@jangts/agent-core、@jangts/agent-core/types、@jangts/agent-core/structs。
定义
ts
type JsonSchema = Readonly<Record<string, unknown>>;索引结构
| 字段 | 类型 | 必需 | 说明 |
|---|---|---|---|
[key: string] | unknown | 必需 | 只读。索引项。 |
使用示例
- Schema:保留 JSON 声明与实际解析的同一合同:Support 生成规范的 SchemaAdapter,Core 只要求 jsonSchema 与同步 parse 合同。
- 从 Tool 与阶段声明生成预览规则:复用实际 Schema 与阶段引用,只为明确允许展示的 Tool 生成规则。
一个有实际校验的字符串对象
入门 · Node.js
ts
import { Support } from '@jangts/agent-core';
const nameSchema = Support.defineSchema({
jsonSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], additionalProperties: false },
parse(value: unknown) {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 1 || !('name' in value) || typeof value.name !== 'string') throw new TypeError('需要 name 字符串');
return { name: value.name };
},
});
console.log(nameSchema.parse({ name: 'Ivan' }));js
import { Support } from '@jangts/agent-core';
const nameSchema = Support.defineSchema({
jsonSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'], additionalProperties: false },
parse(value) {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== 1 || !('name' in value) || typeof value.name !== 'string')
throw new TypeError('需要 name 字符串');
return { name: value.name };
},
});
console.log(nameSchema.parse({ name: 'Ivan' }));复用已经拥有的解析对象
配置 · Node.js
实际接解析库时,toJsonSchema 必须准确表达该 parser;不是库名称决定可信度。
ts
import { Support } from '@jangts/agent-core';
class NameParser {
parse(value: unknown) { if (typeof value !== 'string' || !value.trim()) throw new TypeError('需要非空姓名'); return value.trim(); }
}
const schema = Support.fromParserSchema(new NameParser(), {
toJsonSchema: () => ({ type: 'string', minLength: 1 }),
});
console.log(schema.parse(' Ivan '));js
import { Support } from '@jangts/agent-core';
class NameParser {
parse(value) { if (typeof value !== 'string' || !value.trim())
throw new TypeError('需要非空姓名'); return value.trim(); }
}
const schema = Support.fromParserSchema(new NameParser(), {
toJsonSchema: () => ({ type: 'string', minLength: 1 }),
});
console.log(schema.parse(' Ivan '));