Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraAgents/Sources/SchemaValidator.swift10// Module : Packages11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import AstraCore9091/// Validates tool arguments against the JSON Schema subset tool definitions use: type, required, properties,92/// additionalProperties, enum, minimum / maximum (inclusive and exclusive), minLength / maxLength, items, minItems / maxItems.93/// Nothing is coerced: `"5"` is not a number. Messages are written for the model so it can correct the call.94public enum SchemaValidator {95 public static let maxIssues = 89697 /// Issues found, empty when the value conforms.98 public static func issues(_ value: JSONValue, schema: JSONValue) -> [String] {99 var out: [String] = []100 check(value, schema, path: "", depth: 0, into: &out)101 return out102 }103104 /// Throws one model-readable error listing every problem (up to `maxIssues`).105 public static func validate(arguments: JSONValue, for tool: ToolDefinition) throws {106 guard case .object = arguments else {107 throw ToolError("Invalid arguments for \(tool.name): the arguments must be a JSON object, got \(typeName(arguments)).")108 }109 let found = issues(arguments, schema: tool.parameters)110 guard !found.isEmpty else { return }111 var lines = found.prefix(maxIssues).map { "- " + $0 }112 if found.count > maxIssues { lines.append("- … and \(found.count - maxIssues) more") }113 throw ToolError("Invalid arguments for \(tool.name):\n" + lines.joined(separator: "\n") + "\nCorrect the arguments and call the tool again.")114 }115116 static func typeName(_ value: JSONValue) -> String {117 switch value {118 case .null: "null"119 case .bool: "boolean"120 case .number(let n): n.isFinite && n.rounded() == n ? "integer" : "number"121 case .string: "string"122 case .array: "array"123 case .object: "object"124 }125 }126127 private static func matches(_ value: JSONValue, type: String) -> Bool {128 switch (type, value) {129 case ("null", .null), ("boolean", .bool), ("string", .string), ("array", .array), ("object", .object): true130 case ("number", .number(let n)): n.isFinite131 case ("integer", .number(let n)): n.isFinite && n.rounded() == n132 default: false133 }134 }135136 private static func show(_ value: JSONValue) -> String {137 let text = value.serialized()138 return text.count > 60 ? String(text.prefix(60)) + "…" : text139 }140141 private static func number(_ n: Double) -> String { n.rounded() == n && abs(n) < 1e15 ? String(Int64(n)) : String(n) }142143 private static func check(_ value: JSONValue, _ schema: JSONValue, path: String, depth: Int, into out: inout [String]) {144 guard out.count <= maxIssues, case .object(let s) = schema else { return }145 // Fail closed: what cannot be checked is refused, never waved through.146 guard depth < 32 else { out.append("arguments are nested too deeply to validate."); return }147 let at = path.isEmpty ? "arguments" : "“\(path)”"148149 if let type = s["type"] {150 let allowed: [String] = type.stringValue.map { [$0] } ?? (type.arrayValue ?? []).compactMap(\.stringValue)151 if !allowed.isEmpty, !allowed.contains(where: { matches(value, type: $0) }) {152 out.append("\(at) must be of type \(allowed.joined(separator: " or ")), got \(typeName(value)).")153 return154 }155 }156 if let options = s["enum"]?.arrayValue, !options.contains(value) {157 out.append("\(at) must be one of \(options.map { show($0) }.joined(separator: ", ")), got \(show(value)).")158 }159160 switch value {161 case .number(let n):162 if let min = s["minimum"]?.number, n < min { out.append("\(at) must be at least \(number(min)), got \(number(n)).") }163 if let max = s["maximum"]?.number, n > max { out.append("\(at) must be at most \(number(max)), got \(number(n)).") }164 if let min = s["exclusiveMinimum"]?.number, n <= min { out.append("\(at) must be greater than \(number(min)), got \(number(n)).") }165 if let max = s["exclusiveMaximum"]?.number, n >= max { out.append("\(at) must be less than \(number(max)), got \(number(n)).") }166 case .string(let text):167 if let min = s["minLength"]?.exactInt, text.count < min {168 out.append(min == 1 ? "\(at) must not be empty." : "\(at) must have at least \(min) characters, got \(text.count).")169 }170 if let max = s["maxLength"]?.exactInt, text.count > max { out.append("\(at) must have at most \(max) characters, got \(text.count).") }171 case .array(let items):172 if let min = s["minItems"]?.exactInt, items.count < min { out.append("\(at) must have at least \(min) item(s), got \(items.count).") }173 if let max = s["maxItems"]?.exactInt, items.count > max { out.append("\(at) must have at most \(max) item(s), got \(items.count).") }174 if let itemSchema = s["items"], case .object = itemSchema {175 for (i, item) in items.enumerated() where out.count <= maxIssues {176 check(item, itemSchema, path: "\(path)[\(i)]", depth: depth + 1, into: &out)177 }178 }179 case .object(let object):180 let properties = s["properties"]?.objectValue ?? [:]181 for name in (s["required"]?.arrayValue ?? []).compactMap(\.stringValue) where object[name] == nil {182 out.append("\(path.isEmpty ? "" : path + ".")\(name): this required property is missing.")183 }184 for key in object.keys.sorted() {185 let childPath = path.isEmpty ? key : path + "." + key186 if let child = properties[key] {187 check(object[key] ?? .null, child, path: childPath, depth: depth + 1, into: &out)188 } else if let extra = s["additionalProperties"] {189 if extra == .bool(false) {190 let known = properties.keys.sorted().joined(separator: ", ")191 out.append("“\(String(childPath.prefix(80)))” is not a known property\(known.isEmpty ? "." : " (allowed: \(known)).")")192 } else if case .object = extra {193 check(object[key] ?? .null, extra, path: childPath, depth: depth + 1, into: &out)194 }195 }196 }197 default: break198 }199 }200}201