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/DataTransform.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/// RFC 4180 CSV: quoted fields, doubled quotes, delimiters and line breaks inside quotes, CRLF or LF records.92public enum CSV {93 public static func parse(_ text: String, delimiter: Character = ",", maxRows: Int = DataTransform.maxRows) throws -> [[String]] {94 var rows: [[String]] = []95 var row: [String] = []96 var field = ""97 var inQuotes = false, wasQuoted = false, afterQuote = false98 var line = 199 var body = Substring(text)100 if body.first == "\u{FEFF}" { body = body.dropFirst() }101102 func isNewline(_ c: Character) -> Bool { c == "\n" || c == "\r\n" || c == "\r" }103 func endRecord() throws {104 // A completely blank line is not a record.105 if !(row.isEmpty && field.isEmpty && !wasQuoted) {106 row.append(field)107 rows.append(row)108 guard rows.count <= maxRows + 1 else { throw ToolError("The CSV has more than \(maxRows) rows; reduce the input.") }109 }110 row = []; field = ""; wasQuoted = false; afterQuote = false111 }112113 var index = body.startIndex114 while index < body.endIndex {115 let c = body[index]116 let next = body.index(after: index)117 if inQuotes {118 if c == "\"" {119 if next < body.endIndex, body[next] == "\"" { field.append("\""); index = body.index(after: next); continue }120 inQuotes = false; afterQuote = true121 } else {122 if isNewline(c) { line += 1 }123 field.append(c)124 }125 } else if c == delimiter {126 row.append(field); field = ""; wasQuoted = false; afterQuote = false127 } else if isNewline(c) {128 try endRecord(); line += 1129 } else if afterQuote {130 throw ToolError("CSV error on line \(line): unexpected “\(c)” after a closing quote. Quotes inside a quoted field must be doubled.")131 } else if c == "\"", field.isEmpty {132 inQuotes = true; wasQuoted = true133 } else {134 field.append(c)135 }136 index = next137 }138 guard !inQuotes else { throw ToolError("CSV error: a quoted field that starts on or before line \(line) is never closed.") }139 try endRecord()140 return rows141 }142143 public static func escape(_ field: String, delimiter: Character = ",") -> String {144 let needsQuotes = field.contains { $0 == delimiter || $0 == "\"" || $0 == "\n" || $0 == "\r" || $0 == "\r\n" }145 || field.first == " " || field.last == " "146 return needsQuotes ? "\"" + field.replacingOccurrences(of: "\"", with: "\"\"") + "\"" : field147 }148149 public static func write(_ rows: [[String]], delimiter: Character = ",") -> String {150 rows.map { $0.map { escape($0, delimiter: delimiter) }.joined(separator: String(delimiter)) }.joined(separator: "\r\n")151 }152}153154/// A fixed set of table operations over CSV or JSON text. This is a limited evaluator: it has no expressions, no scripting and no I/O.155public enum DataTransform {156 public static let maxInputBytes = 1_000_000157 public static let maxRows = 10_000158 public static let maxColumns = 500159 /// Rows × columns. Short records are padded to the header's width, so a wide header must not multiply a small input.160 public static let maxCells = 400_000161 public static let maxOperations = 16162163 public struct Table: Sendable, Hashable {164 public var columns: [String]165 public var rows: [[String: JSONValue]]166 public init(columns: [String], rows: [[String: JSONValue]]) { self.columns = columns; self.rows = rows }167 }168169 public enum Format: String, Sendable { case csv, json }170171 enum State {172 case table(Table)173 case value(JSONValue)174 }175176 // MARK: Entry point177178 public static func run(input: String, inputFormat: Format?, operations: [JSONValue], outputFormat: Format?, delimiter: Character = ",") throws -> String {179 guard input.utf8.count <= maxInputBytes else {180 throw ToolError("The input is \(input.utf8.count) bytes; the limit is \(maxInputBytes). Reduce it or work on a part of it.")181 }182 guard operations.count <= maxOperations else { throw ToolError("At most \(maxOperations) operations are allowed in one call.") }183 let format = inputFormat ?? detect(input)184 var state: State185 switch format {186 case .csv: state = .table(try tableFromCSV(input, delimiter: delimiter))187 case .json:188 guard let json = JSONValue.parse(input) else { throw ToolError("The input is not valid JSON.") }189 state = lift(json)190 }191 for (i, operation) in operations.enumerated() {192 do { state = try apply(operation, to: state) }193 catch let error as ToolError { throw ToolError("Operation \(i + 1) (\(operation["op"]?.stringValue ?? "?")): \(error.message)") }194 }195 return try render(state, format: outputFormat ?? format, delimiter: delimiter)196 }197198 static func detect(_ input: String) -> Format {199 let first = input.first { !$0.isWhitespace }200 return (first == "[" || first == "{") && JSONValue.parse(input) != nil ? .json : .csv201 }202203 // MARK: Conversion204205 public static func tableFromCSV(_ text: String, delimiter: Character = ",") throws -> Table {206 let records = try CSV.parse(text, delimiter: delimiter, maxRows: maxRows)207 guard let header = records.first else { throw ToolError("The CSV is empty.") }208 guard header.count <= maxColumns else { throw ToolError("The CSV has \(header.count) columns; the limit is \(maxColumns).") }209 guard header.count * (records.count - 1) <= maxCells else {210 throw ToolError("The CSV has \(header.count) columns and \(records.count - 1) rows, more than \(maxCells) cells; reduce the input.")211 }212 var columns: [String] = [], taken = Set<String>()213 for (i, raw) in header.enumerated() {214 var name = raw.trimmingCharacters(in: .whitespaces)215 if name.isEmpty { name = "column_\(i + 1)" }216 var candidate = name, n = 2217 while !taken.insert(candidate).inserted { candidate = "\(name)_\(n)"; n += 1 }218 columns.append(candidate)219 }220 var rows: [[String: JSONValue]] = []221 rows.reserveCapacity(records.count - 1)222 for (i, record) in records.dropFirst().enumerated() {223 guard record.count <= columns.count else {224 throw ToolError("CSV record \(i + 2) has \(record.count) fields but the header has \(columns.count).")225 }226 var row: [String: JSONValue] = [:]227 for (c, name) in columns.enumerated() { row[name] = c < record.count ? typed(record[c]) : .null }228 rows.append(row)229 }230 return Table(columns: columns, rows: rows)231 }232233 /// CSV cells that are plainly numbers become numbers; anything else (including `007`) stays text; an empty cell is null.234 static func typed(_ cell: String) -> JSONValue {235 if cell.isEmpty { return .null }236 if cell.count <= 24, cell.range(of: #"^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$"#, options: .regularExpression) != nil,237 let d = Double(cell), d.isFinite { return .number(d) }238 return .string(cell)239 }240241 /// An array of objects is a table; an array of scalars is a one-column table; anything else stays a plain value.242 static func lift(_ json: JSONValue) -> State {243 guard case .array(let items) = json, !items.isEmpty, items.count <= maxRows else { return .value(json) }244 if items.allSatisfy({ $0.objectValue != nil }) {245 var columns: [String] = [], seen = Set<String>()246 for item in items { for key in (item.objectValue ?? [:]).keys.sorted() where seen.insert(key).inserted { columns.append(key) } }247 guard columns.count <= maxColumns, columns.count * items.count <= maxCells else { return .value(json) }248 return .table(Table(columns: columns, rows: items.map { $0.objectValue ?? [:] }))249 }250 if items.allSatisfy({ $0.objectValue == nil && $0.arrayValue == nil }) {251 return .table(Table(columns: ["value"], rows: items.map { ["value": $0] }))252 }253 return .value(json)254 }255256 static func json(_ table: Table) -> JSONValue {257 // `uniquingKeysWith`, never `uniqueKeysWithValues`: a repeated column name must not be able to stop the process.258 .array(table.rows.map { row in .object(Dictionary(table.columns.map { ($0, row[$0] ?? .null) }, uniquingKeysWith: { first, _ in first })) })259 }260261 static func text(_ value: JSONValue?) -> String {262 switch value {263 case .none, .some(.null): ""264 case .some(.string(let s)): s265 case .some(.number(let n)): Calculator.format(.real(n))266 case .some(.bool(let b)): b ? "true" : "false"267 case .some(let other): other.serialized()268 }269 }270271 static func numeric(_ value: JSONValue?) -> Double? {272 switch value {273 case .some(.number(let n)): n274 case .some(.string(let s)): s.count <= 32 ? Double(s.trimmingCharacters(in: .whitespaces)).flatMap { $0.isFinite ? $0 : nil } : nil275 default: nil276 }277 }278279 static func render(_ state: State, format: Format, delimiter: Character) throws -> String {280 switch (state, format) {281 case (.value(let v), _): return v.serialized(pretty: true)282 case (.table(let table), .json): return json(table).serialized(pretty: table.rows.count <= 50)283 case (.table(let table), .csv):284 return CSV.write([table.columns] + table.rows.map { row in table.columns.map { text(row[$0]) } }, delimiter: delimiter)285 }286 }287288 // MARK: Operations289290 static func apply(_ operation: JSONValue, to state: State) throws -> State {291 let name = operation["op"]?.stringValue ?? ""292 if name == "pointer" {293 guard let path = operation["path"]?.stringValue else { throw ToolError("“path” is required, for example /items/0/name.") }294 let source: JSONValue295 switch state { case .table(let t): source = json(t); case .value(let v): source = v }296 return lift(try pointer(path, in: source))297 }298 guard case .table(var table) = state else {299 throw ToolError("this operation needs rows (an array of objects or a CSV), but the current value is not a table. Use “pointer” to reach the array first.")300 }301 func column(_ key: String = "column") throws -> String {302 guard let c = operation[key]?.stringValue else { throw ToolError("“\(key)” is required.") }303 return try existing(c, in: table)304 }305 func columns(_ key: String, required: Bool = true) throws -> [String] {306 let list = (operation[key]?.arrayValue ?? []).compactMap(\.stringValue)307 if list.isEmpty, required { throw ToolError("“\(key)” must list at least one column.") }308 let resolved = try list.map { try existing($0, in: table) }309 if let repeated = Dictionary(grouping: resolved, by: { $0 }).first(where: { $0.value.count > 1 })?.key {310 throw ToolError("the column “\(repeated)” is listed twice in “\(key)”.")311 }312 return resolved313 }314 func count() throws -> Int {315 guard let n = operation["n"]?.exactInt, n >= 0 else { throw ToolError("“n” must be a whole number, zero or more.") }316 return n317 }318319 switch name {320 case "select":321 table.columns = try columns("columns")322 let keep = Set(table.columns)323 table.rows = table.rows.map { $0.filter { keep.contains($0.key) } }324 case "rename":325 guard let mapping = operation["mapping"]?.objectValue, !mapping.isEmpty else { throw ToolError("“mapping” must be an object such as {\"old\": \"new\"}.") }326 for old in mapping.keys.sorted() {327 _ = try existing(old, in: table)328 guard let new = mapping[old]?.stringValue, !new.isEmpty else { throw ToolError("the new name for “\(old)” must be a non-empty string.") }329 guard new == old || !table.columns.contains(new) else { throw ToolError("a column named “\(new)” already exists.") }330 table.columns = table.columns.map { $0 == old ? new : $0 }331 table.rows = table.rows.map { row in var r = row; r[new] = r.removeValue(forKey: old) ?? .null; return r }332 }333 case "filter":334 let c = try column()335 guard let comparison = operation["operator"]?.stringValue else { throw ToolError("“operator” is required (==, !=, <, <=, >, >=, contains).") }336 guard let value = operation["value"] else { throw ToolError("“value” is required.") }337 table.rows = try table.rows.filter { try matches($0[c], comparison, value) }338 case "sort":339 let keys = try columns("by")340 let descending = operation["descending"]?.boolValue ?? false341 // Decorate-sort-undecorate with the original position as the last key keeps the sort stable.342 table.rows = table.rows.enumerated().sorted { a, b in343 for key in keys {344 let order = compare(a.element[key], b.element[key])345 if order != 0 { return descending ? order > 0 : order < 0 }346 }347 return a.offset < b.offset348 }.map(\.element)349 case "unique":350 let keys = try columns("columns", required: false)351 let by = keys.isEmpty ? table.columns : keys352 var seen = Set<[JSONValue]>()353 table.rows = table.rows.filter { row in seen.insert(by.map { row[$0] ?? .null }).inserted }354 case "head": table.rows = Array(table.rows.prefix(try count()))355 case "tail": table.rows = Array(table.rows.suffix(try count()))356 case "group_by": table = try group(table, by: try columns("by", required: false), aggregates: operation["aggregates"]?.arrayValue ?? [])357 default: throw ToolError("unknown operation. Use select, rename, filter, sort, group_by, unique, head, tail or pointer.")358 }359 return .table(table)360 }361362 static func existing(_ name: String, in table: Table) throws -> String {363 guard table.columns.contains(name) else {364 throw ToolError("there is no column “\(String(name.prefix(60)))”. Columns: \(table.columns.prefix(40).joined(separator: ", ")).")365 }366 return name367 }368369 /// Numbers compare as numbers when both sides are numeric; otherwise text compares as text. Nulls sort last.370 static func compare(_ a: JSONValue?, _ b: JSONValue?) -> Int {371 let aNull = a == nil || a == .null, bNull = b == nil || b == .null372 if aNull || bNull { return aNull && bNull ? 0 : aNull ? 1 : -1 }373 if let x = numeric(a), let y = numeric(b) { return x < y ? -1 : x > y ? 1 : 0 }374 let x = text(a), y = text(b)375 return x < y ? -1 : x > y ? 1 : 0376 }377378 static func matches(_ cell: JSONValue?, _ comparison: String, _ value: JSONValue) throws -> Bool {379 let cellIsNull = cell == nil || cell == .null380 switch comparison {381 case "==", "!=":382 let equal: Bool383 if value == .null || cellIsNull { equal = cellIsNull && value == .null }384 else if let x = numeric(cell), let y = numeric(value) { equal = x == y }385 else { equal = text(cell) == text(value) }386 return comparison == "==" ? equal : !equal387 case "contains":388 return !cellIsNull && text(cell).range(of: text(value), options: [.caseInsensitive, .diacriticInsensitive]) != nil389 case "<", "<=", ">", ">=":390 if cellIsNull || value == .null { return false }391 let order = compare(cell, value)392 switch comparison { case "<": return order < 0; case "<=": return order <= 0; case ">": return order > 0; default: return order >= 0 }393 default:394 throw ToolError("unknown operator “\(String(comparison.prefix(12)))”. Use ==, !=, <, <=, >, >= or contains.")395 }396 }397398 static func group(_ table: Table, by keys: [String], aggregates: [JSONValue]) throws -> Table {399 struct Aggregate { var function: String; var column: String?; var name: String }400 var specs: [Aggregate] = []401 for spec in aggregates {402 guard let function = spec["function"]?.stringValue, ["count", "sum", "mean", "min", "max"].contains(function) else {403 throw ToolError("each aggregate needs “function”: count, sum, mean, min or max.")404 }405 var column: String?406 if let c = spec["column"]?.stringValue { column = try existing(c, in: table) }407 else if function != "count" { throw ToolError("the aggregate “\(function)” needs a “column”.") }408 specs.append(Aggregate(function: function, column: column, name: spec["as"]?.stringValue ?? (column.map { "\(function)_\($0)" } ?? "count")))409 }410 if specs.isEmpty { specs = [Aggregate(function: "count", column: nil, name: "count")] }411 let names = keys + specs.map(\.name)412 guard Set(names).count == names.count else { throw ToolError("two output columns would have the same name; set “as” on the aggregates.") }413414 var order: [[JSONValue]] = []415 var groups: [[JSONValue]: [[String: JSONValue]]] = [:]416 for row in table.rows {417 let key = keys.map { row[$0] ?? .null }418 if groups[key] == nil { order.append(key) }419 groups[key, default: []].append(row)420 }421 var rows: [[String: JSONValue]] = []422 for key in order {423 let members = groups[key] ?? []424 var out = Dictionary(uniqueKeysWithValues: zip(keys, key))425 for spec in specs {426 let cells = spec.column.map { c in members.map { $0[c] ?? .null }.filter { $0 != .null } } ?? []427 let numbers = cells.compactMap { numeric($0) }428 switch spec.function {429 case "count": out[spec.name] = .number(Double(spec.column == nil ? members.count : cells.count))430 case "sum", "mean":431 let sum = numbers.reduce(0, +)432 guard sum.isFinite else { throw ToolError("the \(spec.function) of “\(spec.column ?? "")” is too large to represent.") }433 if spec.function == "sum" { out[spec.name] = .number(sum) }434 else { out[spec.name] = numbers.isEmpty ? .null : .number(sum / Double(numbers.count)) }435 case "min": out[spec.name] = cells.min { compare($0, $1) < 0 } ?? .null436 default: out[spec.name] = cells.max { compare($0, $1) < 0 } ?? .null437 }438 }439 rows.append(out)440 }441 return Table(columns: names, rows: rows)442 }443444 /// RFC 6901 JSON Pointer (`/a/0/b`, with `~1` for `/` and `~0` for `~`).445 public static func pointer(_ path: String, in root: JSONValue) throws -> JSONValue {446 if path.isEmpty || path == "/" && root.objectValue?[""] == nil { return root }447 guard path.hasPrefix("/") else { throw ToolError("a JSON pointer starts with “/”, for example /items/0/name.") }448 var current = root449 var walked = ""450 for raw in path.dropFirst().split(separator: "/", omittingEmptySubsequences: false) {451 let token = raw.replacingOccurrences(of: "~1", with: "/").replacingOccurrences(of: "~0", with: "~")452 walked += "/" + raw453 switch current {454 case .object(let o):455 guard let next = o[token] else {456 throw ToolError("nothing at \(walked): the object has the keys \(o.keys.sorted().prefix(30).joined(separator: ", ")).")457 }458 current = next459 case .array(let a):460 guard let i = Int(token), a.indices.contains(i) else { throw ToolError("nothing at \(walked): the array has \(a.count) item(s), indexed from 0.") }461 current = a[i]462 default:463 throw ToolError("nothing at \(walked): the value before it is not an object or an array.")464 }465 }466 return current467 }468}469470public struct DataTransformTool: AgentTool {471 public let risk: ToolRisk = .safe472 public init() {}473474 public var definition: ToolDefinition {475 let strings: JSONValue = ["type": "array", "items": ["type": "string", "maxLength": 200], "maxItems": 100]476 return ToolDefinition(477 name: "data_transform",478 summary: "Transforms CSV or JSON passed as text with a fixed list of operations applied in order: select {columns}, rename {mapping}, "479 + "filter {column, operator, value}, sort {by, descending}, group_by {by, aggregates:[{function, column, as}]}, unique {columns}, "480 + "head {n}, tail {n}, pointer {path} (JSON Pointer). With no operation it converts between CSV and JSON. No formulas, no code.",481 parameters: [482 "type": "object",483 "properties": [484 "input": ["type": "string", "minLength": 1, "description": "The CSV or JSON text."],485 "input_format": ["type": "string", "enum": ["csv", "json"], "description": "Default: detected."],486 "output_format": ["type": "string", "enum": ["csv", "json"], "description": "Default: same as the input."],487 "delimiter": ["type": "string", "enum": [",", ";", "\t", "|"], "description": "CSV delimiter. Default: comma."],488 "operations": [489 "type": "array", "maxItems": .number(Double(DataTransform.maxOperations)),490 "items": [491 "type": "object",492 "properties": [493 "op": ["type": "string", "enum": ["select", "rename", "filter", "sort", "group_by", "unique", "head", "tail", "pointer"]],494 "columns": strings,495 "mapping": ["type": "object", "additionalProperties": ["type": "string", "minLength": 1, "maxLength": 200]],496 "column": ["type": "string", "maxLength": 200],497 "operator": ["type": "string", "enum": ["==", "!=", "<", "<=", ">", ">=", "contains"]],498 "value": ["type": ["string", "number", "boolean", "null"]],499 "by": strings,500 "descending": ["type": "boolean"],501 "aggregates": [502 "type": "array", "maxItems": 20,503 "items": [504 "type": "object",505 "properties": [506 "function": ["type": "string", "enum": ["count", "sum", "mean", "min", "max"]],507 "column": ["type": "string", "maxLength": 200],508 "as": ["type": "string", "minLength": 1, "maxLength": 200],509 ],510 "required": ["function"],511 "additionalProperties": false,512 ],513 ],514 "n": ["type": "integer", "minimum": 0, "maximum": .number(Double(DataTransform.maxRows))],515 "path": ["type": "string", "maxLength": 500],516 ],517 "required": ["op"],518 "additionalProperties": false,519 ],520 ],521 ],522 "required": ["input"],523 "additionalProperties": false,524 ])525 }526527 public func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {528 let input = arguments["input"]?.stringValue ?? ""529 let delimiter = arguments["delimiter"]?.stringValue?.first ?? ","530 let text = try DataTransform.run(input: input, inputFormat: arguments["input_format"]?.stringValue.flatMap(DataTransform.Format.init(rawValue:)),531 operations: arguments["operations"]?.arrayValue ?? [],532 outputFormat: arguments["output_format"]?.stringValue.flatMap(DataTransform.Format.init(rawValue:)), delimiter: delimiter)533 return ToolOutput(text)534 }535}536