schema.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. /** Unified JSON-value schema DSL, inference, compilation, and typed tool helper. @module dsh-tools/schema */
  2. import { HarnessError } from '@deepseek-ai/dsh-llm'
  3. import type { JsonValue } from '@deepseek-ai/dsh-session'
  4. import type { ToolDefinition, ToolExecuteReturn, ToolRunContext, ToolResult } from './index.ts'
  5. import { assertSupportedJsonSchema, isPlainJsonRecord, JsonSchemaError, validateJsonSchemaValue } from './json-schema.ts'
  6. import type { JsonSchemaNode, JsonSchemaScalar, ObjectJsonSchema } from './json-schema.ts'
  7. import type { ToolCallView, ToolResultView } from './presentation.ts'
  8. /** Annotation keywords shared by every author-facing schema node. */
  9. export interface ValueSchemaAnnotations {
  10. /** Human-readable description projected into JSON Schema and generated types. */
  11. description?: string
  12. /** Human-readable title projected into JSON Schema. */
  13. title?: string
  14. /** Non-validating default annotation; it must be lossless JSON data. */
  15. default?: JsonValue
  16. /** Non-validating examples annotation; it must be lossless JSON data. */
  17. examples?: JsonValue
  18. }
  19. /** String value schema with type-correct literal constraints. */
  20. export interface StringValueSchemaSpec extends ValueSchemaAnnotations {
  21. type: 'string'
  22. enum?: readonly string[]
  23. const?: string
  24. }
  25. /** Finite JSON-number schema with type-correct literal constraints. */
  26. export interface NumberValueSchemaSpec extends ValueSchemaAnnotations {
  27. type: 'number'
  28. enum?: readonly number[]
  29. const?: number
  30. }
  31. /** Integer schema with type-correct literal constraints. */
  32. export interface IntegerValueSchemaSpec extends ValueSchemaAnnotations {
  33. type: 'integer'
  34. enum?: readonly number[]
  35. const?: number
  36. }
  37. /** Boolean value schema with type-correct literal constraints. */
  38. export interface BooleanValueSchemaSpec extends ValueSchemaAnnotations {
  39. type: 'boolean'
  40. enum?: readonly boolean[]
  41. const?: boolean
  42. }
  43. /** Null value schema with type-correct literal constraints. */
  44. export interface NullValueSchemaSpec extends ValueSchemaAnnotations {
  45. type: 'null'
  46. enum?: readonly null[]
  47. const?: null
  48. }
  49. /** Array value schema; omitted `items` accepts any lossless JSON item. */
  50. export interface ArrayValueSchemaSpec extends ValueSchemaAnnotations {
  51. type: 'array'
  52. items?: ValueSchemaSpec
  53. }
  54. /**
  55. * Explicit object value schema. Openness is mandatory so a nested or output
  56. * object never acquires an accidental JSON Schema default.
  57. */
  58. export interface ObjectValueSchemaSpec extends ValueSchemaAnnotations {
  59. type: 'object'
  60. properties?: ParameterSchemaSpec
  61. additionalProperties: boolean
  62. }
  63. /** Author-only unconstrained lossless JSON node. */
  64. export interface JsonValueSchemaSpec extends ValueSchemaAnnotations {
  65. type: 'json'
  66. }
  67. /** Exact-one union schema; at least two branches are required. */
  68. export interface OneOfValueSchemaSpec extends ValueSchemaAnnotations {
  69. oneOf: readonly [ValueSchemaSpec, ValueSchemaSpec, ...ValueSchemaSpec[]]
  70. }
  71. /** One author-facing schema for any lossless JSON value root. */
  72. export type ValueSchemaSpec =
  73. | StringValueSchemaSpec
  74. | NumberValueSchemaSpec
  75. | IntegerValueSchemaSpec
  76. | BooleanValueSchemaSpec
  77. | NullValueSchemaSpec
  78. | ArrayValueSchemaSpec
  79. | ObjectValueSchemaSpec
  80. | JsonValueSchemaSpec
  81. | OneOfValueSchemaSpec
  82. /** One implicit parameter-root property, optionally required. */
  83. export type ParameterPropertySpec = ValueSchemaSpec & { required?: true }
  84. /**
  85. * Tool parameter schema. The map itself is an implicit open object root;
  86. * requiredness remains a per-property `required: true` annotation.
  87. */
  88. export type ParameterSchemaSpec = Record<string, ParameterPropertySpec>
  89. /** Raw JSON Schema projection of the implicit parameter object. */
  90. export interface ParameterJsonSchema extends ObjectJsonSchema {
  91. properties: Record<string, JsonSchemaNode>
  92. }
  93. /** Flatten an intersection into one object type for readable hovers. */
  94. type Simplify<T> = { [K in keyof T]: T[K] } & {}
  95. /** Keys of a property map marked `required: true`. */
  96. type RequiredKeys<S extends ParameterSchemaSpec> = {
  97. [K in keyof S]: S[K] extends { required: true } ? K : never
  98. }[keyof S]
  99. /** Infer the declared value of one parameter property without key optionality. */
  100. type InferProperty<P extends ParameterPropertySpec> = P extends ValueSchemaSpec ? InferValue<P> : never
  101. /** Infer an implicit property map into required and optional object keys. */
  102. type InferProperties<S extends ParameterSchemaSpec> = Simplify<
  103. & { [K in RequiredKeys<S>]: InferProperty<S[K]> }
  104. & { [K in Exclude<keyof S, RequiredKeys<S>>]?: InferProperty<S[K]> }
  105. >
  106. /** Infer an explicit object node, including its declared openness. */
  107. type InferObject<S extends ObjectValueSchemaSpec> =
  108. S extends { properties: infer P extends ParameterSchemaSpec }
  109. ? S['additionalProperties'] extends true
  110. ? InferProperties<P> & Record<string, JsonValue>
  111. : InferProperties<P>
  112. : S['additionalProperties'] extends true
  113. ? Record<string, JsonValue>
  114. : Record<string, never>
  115. /** Infer a scalar node's literal constraint before its broad primitive type. */
  116. type InferScalar<S, Fallback> =
  117. S extends { const: infer C } ? C :
  118. S extends { enum: readonly (infer E)[] } ? E :
  119. Fallback
  120. /**
  121. * Infer the TypeScript value accepted by an author-facing value schema.
  122. * Output schemas may therefore infer object, array, scalar, or null roots.
  123. */
  124. export type InferValue<S extends ValueSchemaSpec> =
  125. S extends StringValueSchemaSpec ? InferScalar<S, string> :
  126. S extends NumberValueSchemaSpec | IntegerValueSchemaSpec ? InferScalar<S, number> :
  127. S extends BooleanValueSchemaSpec ? InferScalar<S, boolean> :
  128. S extends NullValueSchemaSpec ? null :
  129. S extends ArrayValueSchemaSpec
  130. ? S extends { items: infer I extends ValueSchemaSpec } ? InferValue<I>[] : JsonValue[]
  131. : S extends ObjectValueSchemaSpec ? InferObject<S> :
  132. S extends JsonValueSchemaSpec ? JsonValue :
  133. S extends OneOfValueSchemaSpec ? InferValue<S['oneOf'][number]> :
  134. never
  135. /** Infer the TypeScript argument object for an implicit parameter schema. */
  136. export type InferArgs<S extends ParameterSchemaSpec> = InferProperties<S>
  137. const ANNOTATION_KEYS = ['description', 'title', 'default', 'examples'] as const
  138. /** Throw one author-schema violation through the shared schema error type. */
  139. function authorError(message: string): never {
  140. throw new JsonSchemaError([message])
  141. }
  142. /** Copy own annotation fields for validation by the raw-schema boundary. */
  143. function copyAnnotations(source: Record<string, unknown>, target: JsonSchemaNode): void {
  144. if (Object.hasOwn(source, 'description')) target.description = source.description as string
  145. if (Object.hasOwn(source, 'title')) target.title = source.title as string
  146. if (Object.hasOwn(source, 'default')) target.default = source.default as JsonValue
  147. if (Object.hasOwn(source, 'examples')) target.examples = source.examples as JsonValue
  148. }
  149. /** Reject author-only keys outside one node's declared vocabulary. */
  150. function assertAuthorKeys(source: Record<string, unknown>, path: string, allowed: readonly string[]): void {
  151. for (const key of Object.keys(source)) {
  152. if (!allowed.includes(key)) authorError(`${path}.${key} is not supported by the value schema DSL`)
  153. }
  154. }
  155. /** Compile one implicit property map, collecting per-property requiredness. */
  156. function compilePropertyMap(
  157. input: unknown,
  158. path: string,
  159. seen: Set<object>,
  160. ): { properties: Record<string, JsonSchemaNode>; required?: string[] } {
  161. if (!isPlainJsonRecord(input)) authorError(`${path} must be an object of value schemas`)
  162. if (seen.has(input)) authorError(`${path} is circular`)
  163. seen.add(input)
  164. try {
  165. const properties: Record<string, JsonSchemaNode> = {}
  166. const required: string[] = []
  167. for (const [key, property] of Object.entries(input)) {
  168. if (!isPlainJsonRecord(property)) authorError(`${path}.${key} must be a value schema object`)
  169. if (Object.hasOwn(property, 'required') && property.required !== true) {
  170. authorError(`${path}.${key}.required must be true when present`)
  171. }
  172. Object.defineProperty(properties, key, {
  173. value: compileValueSchema(property, `${path}.${key}`, seen, true),
  174. enumerable: true,
  175. configurable: true,
  176. writable: true,
  177. })
  178. if (property.required === true) required.push(key)
  179. }
  180. return required.length > 0 ? { properties, required } : { properties }
  181. } finally {
  182. seen.delete(input)
  183. }
  184. }
  185. /** Compile one author node without applying any consumer root restriction. */
  186. function compileValueSchema(
  187. input: unknown,
  188. path: string,
  189. seen: Set<object>,
  190. allowRequired = false,
  191. ): JsonSchemaNode {
  192. if (!isPlainJsonRecord(input)) authorError(`${path} must be a value schema object`)
  193. if (seen.has(input)) authorError(`${path} is circular`)
  194. seen.add(input)
  195. try {
  196. const authorKeys = [...ANNOTATION_KEYS, ...(allowRequired ? ['required'] : [])]
  197. const node: JsonSchemaNode = {}
  198. if (Object.hasOwn(input, 'oneOf')) {
  199. assertAuthorKeys(input, path, [...authorKeys, 'oneOf', 'type'])
  200. if (Object.hasOwn(input, 'type')) authorError(`${path} cannot declare both type and oneOf`)
  201. if (!Array.isArray(input.oneOf)) authorError(`${path}.oneOf must be an array of at least two value schemas`)
  202. node.oneOf = input.oneOf.map((branch, index) => compileValueSchema(branch, `${path}.oneOf[${index}]`, seen))
  203. copyAnnotations(input, node)
  204. return node
  205. }
  206. switch (input.type) {
  207. case 'json':
  208. assertAuthorKeys(input, path, [...authorKeys, 'type'])
  209. copyAnnotations(input, node)
  210. return node
  211. case 'object': {
  212. assertAuthorKeys(input, path, [...authorKeys, 'type', 'properties', 'additionalProperties'])
  213. if (!Object.hasOwn(input, 'additionalProperties') || typeof input.additionalProperties !== 'boolean') {
  214. authorError(`${path}.additionalProperties must be explicitly true or false`)
  215. }
  216. node.type = 'object'
  217. copyAnnotations(input, node)
  218. node.additionalProperties = input.additionalProperties
  219. if (Object.hasOwn(input, 'properties')) {
  220. const compiled = compilePropertyMap(input.properties, `${path}.properties`, seen)
  221. node.properties = compiled.properties
  222. if (compiled.required !== undefined) node.required = compiled.required
  223. }
  224. return node
  225. }
  226. case 'array':
  227. assertAuthorKeys(input, path, [...authorKeys, 'type', 'items'])
  228. node.type = 'array'
  229. copyAnnotations(input, node)
  230. if (Object.hasOwn(input, 'items')) node.items = compileValueSchema(input.items, `${path}.items`, seen)
  231. return node
  232. case 'string':
  233. case 'number':
  234. case 'integer':
  235. case 'boolean':
  236. case 'null':
  237. assertAuthorKeys(input, path, [...authorKeys, 'type', 'enum', 'const'])
  238. node.type = input.type
  239. copyAnnotations(input, node)
  240. if (Object.hasOwn(input, 'enum')) {
  241. node.enum = Array.isArray(input.enum)
  242. ? Array.from(input.enum as unknown[], entry => entry as JsonSchemaScalar)
  243. : input.enum as JsonSchemaScalar[]
  244. }
  245. if (Object.hasOwn(input, 'const')) node.const = input.const as JsonSchemaScalar
  246. return node
  247. default:
  248. return authorError(`${path}.type must be string/number/integer/boolean/null/array/object/json, or use oneOf`)
  249. }
  250. } finally {
  251. seen.delete(input)
  252. }
  253. }
  254. /**
  255. * Compile one author-facing value schema to the enforced raw JSON Schema
  256. * subset. The author-only `json` node becomes an annotation-only schema.
  257. * @param spec - schema for any JSON-value root.
  258. * @returns The asserted raw schema projection.
  259. */
  260. export function valueSchemaSpecToJsonSchema(spec: ValueSchemaSpec): JsonSchemaNode {
  261. const schema = compileValueSchema(spec, 'schema', new Set())
  262. assertSupportedJsonSchema(schema)
  263. return schema
  264. }
  265. /**
  266. * Compile the implicit open parameter object into raw JSON Schema.
  267. * @param spec - per-property parameter definitions.
  268. * @returns An object-rooted raw schema with no implicit-root openness override.
  269. */
  270. export function parameterSchemaSpecToJsonSchema(spec: ParameterSchemaSpec): ParameterJsonSchema {
  271. const compiled = compilePropertyMap(spec, 'parameters', new Set())
  272. const schema: ParameterJsonSchema = {
  273. type: 'object',
  274. properties: compiled.properties,
  275. ...(compiled.required === undefined ? {} : { required: compiled.required }),
  276. }
  277. assertSupportedJsonSchema(schema)
  278. return schema
  279. }
  280. /** Invalid model-generated arguments for a typed tool. */
  281. export class ToolArgsError extends HarnessError {
  282. /** Individual violations in schema-walk order. */
  283. readonly violations: string[]
  284. constructor(violations: string[]) {
  285. super(`invalid arguments: ${violations.join('; ')}`, 'INVALID_ARGS')
  286. this.name = 'ToolArgsError'
  287. this.violations = violations
  288. }
  289. }
  290. /**
  291. * Validate model-generated arguments against an implicit parameter schema.
  292. * @param spec - declared parameter schema.
  293. * @param args - candidate arguments, however malformed.
  294. * @returns Path-qualified violations; empty means valid.
  295. */
  296. export function validateArgs(spec: ParameterSchemaSpec, args: unknown): string[] {
  297. return validateJsonSchemaValue(parameterSchemaSpecToJsonSchema(spec), args, '')
  298. }
  299. /** Options for {@link defineTool}. */
  300. export interface DefineToolOptions<S extends ParameterSchemaSpec> {
  301. /** Tool name (must be unique). */
  302. readonly name: string
  303. /** Human-readable description sent to the model. */
  304. readonly description: string
  305. /** Per-property parameter schema compiled to an implicit open object root. */
  306. readonly parameters: S
  307. /** Optional positive cooperative timeout budget in milliseconds. */
  308. readonly timeoutMs?: number
  309. /**
  310. * Pure classifier for sibling overlap.
  311. * @param args - typed validated arguments.
  312. * @returns Whether the call may join a parallel group.
  313. */
  314. isConcurrencySafe?(args: InferArgs<S>): boolean
  315. /**
  316. * Execute the tool after argument validation.
  317. * @param args - typed validated arguments.
  318. * @param exec - execution identity, caller, cancellation, and nesting data.
  319. * @returns Model-facing content and optional presentation metadata.
  320. */
  321. execute(args: InferArgs<S>, exec: ToolRunContext): Promise<ToolExecuteReturn>
  322. /**
  323. * Pure pending-state presenter.
  324. * @param args - typed validated arguments.
  325. * @returns Tool-owned render intent, or `undefined` for the generic card.
  326. */
  327. presentCall?(args: InferArgs<S>): ToolCallView | undefined
  328. /**
  329. * Pure completed-state presenter.
  330. * @param args - typed validated arguments.
  331. * @param result - final model-facing tool result.
  332. * @returns Tool-owned render intent, or `undefined` for the generic card.
  333. */
  334. presentResult?(args: InferArgs<S>, result: ToolResult): ToolResultView | undefined
  335. }
  336. /**
  337. * Define a first-party tool with inferred arguments and strict execution
  338. * validation. Replay-only presenters validate softly and fall back to generic
  339. * rendering for obsolete logged arguments.
  340. * @param options - typed definition and optional presenters.
  341. * @returns A registry-ready definition.
  342. */
  343. export function defineTool<const S extends ParameterSchemaSpec>(options: DefineToolOptions<S>): ToolDefinition {
  344. // Object-literal methods do not use `this`; retaining references is safe.
  345. // eslint-disable-next-line @typescript-eslint/unbound-method
  346. const userExecute = options.execute
  347. // eslint-disable-next-line @typescript-eslint/unbound-method
  348. const userPresentCall = options.presentCall
  349. // eslint-disable-next-line @typescript-eslint/unbound-method
  350. const userPresentResult = options.presentResult
  351. // eslint-disable-next-line @typescript-eslint/unbound-method
  352. const userIsConcurrencySafe = options.isConcurrencySafe
  353. if (options.timeoutMs !== undefined && (!Number.isFinite(options.timeoutMs) || options.timeoutMs <= 0)) {
  354. throw new Error(`defineTool(${options.name}): timeoutMs must be a positive finite number`)
  355. }
  356. const parameters = parameterSchemaSpecToJsonSchema(options.parameters)
  357. const validate = (args: unknown): string[] => validateJsonSchemaValue(parameters, args, '')
  358. const tool: ToolDefinition = {
  359. name: options.name,
  360. description: options.description,
  361. parameters: parameters as unknown as Record<string, unknown>,
  362. ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
  363. async execute(args: unknown, exec: ToolRunContext): Promise<ToolExecuteReturn> {
  364. const violations = validate(args)
  365. if (violations.length > 0) throw new ToolArgsError(violations)
  366. return userExecute(args as InferArgs<S>, exec)
  367. },
  368. }
  369. if (userPresentCall) {
  370. tool.presentCall = (args: unknown): ToolCallView | undefined => {
  371. if (validate(args).length > 0) return undefined
  372. return userPresentCall(args as InferArgs<S>)
  373. }
  374. }
  375. if (userPresentResult) {
  376. tool.presentResult = (args: unknown, result: ToolResult): ToolResultView | undefined => {
  377. if (validate(args).length > 0) return undefined
  378. return userPresentResult(args as InferArgs<S>, result)
  379. }
  380. }
  381. if (userIsConcurrencySafe) {
  382. tool.isConcurrencySafe = (args: unknown): boolean => {
  383. if (validate(args).length > 0) return false
  384. return userIsConcurrencySafe(args as InferArgs<S>)
  385. }
  386. }
  387. return tool
  388. }