Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraAgents/Sources/DateTimeTool.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/// Date arithmetic on the Gregorian calendar in explicit IANA time zones. Pure functions; the current time is always passed in.92public enum DateTimeEngine {93 public static func timeZone(_ identifier: String) throws -> TimeZone {94 let id = identifier.trimmingCharacters(in: .whitespaces)95 if id.uppercased() == "Z" || id.uppercased() == "UTC" { return TimeZone(identifier: "UTC")! }96 guard id.count <= 64, let zone = TimeZone(identifier: id) else {97 throw ToolError("Unknown time zone “\(String(id.prefix(64)))”. Use an IANA identifier such as America/Toronto, Europe/Paris or UTC.")98 }99 return zone100 }101102 public static func calendar(_ zone: TimeZone) -> Calendar {103 var c = Calendar(identifier: .gregorian)104 c.timeZone = zone105 c.locale = Locale(identifier: "en_US_POSIX")106 return c107 }108109 /// Parses `YYYY-MM-DD`, `YYYY-MM-DDTHH:MM[:SS[.fff]]` with an optional `Z` or `±HH:MM` offset.110 /// A value without an offset is a wall-clock time in `zone`.111 public static func parse(_ text: String, zone: TimeZone) throws -> Date {112 let t = text.trimmingCharacters(in: .whitespaces)113 let pattern = #"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?)?\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?$"#114 let bad = ToolError("“\(String(t.prefix(40)))” is not a date this tool reads. Use ISO 8601, for example 2026-03-08, 2026-03-08T14:30:00 or 2026-03-08T14:30:00-04:00.")115 guard t.count <= 40, let regex = try? NSRegularExpression(pattern: pattern),116 let m = regex.firstMatch(in: t, range: NSRange(t.startIndex..., in: t)) else { throw bad }117 func group(_ n: Int) -> String? { Range(m.range(at: n), in: t).map { String(t[$0]) } }118 func int(_ n: Int) -> Int { group(n).flatMap { Int($0) } ?? 0 }119 let year = int(1), month = int(2), day = int(3), hour = int(4), minute = int(5), second = int(6)120 guard (1...9999).contains(year), (1...12).contains(month), (1...31).contains(day), (0...23).contains(hour), (0...59).contains(minute),121 (0...59).contains(second) else { throw bad }122 var effective = zone123 if let offset = group(8) {124 if offset.uppercased() == "Z" { effective = TimeZone(identifier: "UTC")! }125 else {126 let digits = offset.dropFirst().replacingOccurrences(of: ":", with: "")127 let hours = Int(digits.prefix(2)) ?? 0, minutes = digits.count >= 4 ? Int(digits.suffix(2)) ?? 0 : 0128 guard hours <= 14, minutes <= 59, let fixed = TimeZone(secondsFromGMT: (offset.hasPrefix("-") ? -1 : 1) * (hours * 3600 + minutes * 60)) else { throw bad }129 effective = fixed130 }131 }132 let cal = calendar(effective)133 var parts = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute, second: second)134 if let fraction = group(7), let value = Double("0." + fraction) { parts.nanosecond = Int(value * 1_000_000_000) }135 guard let date = cal.date(from: parts) else { throw bad }136 // 2026-02-30 would silently roll over to March: refuse it instead.137 guard let midday = cal.date(from: DateComponents(year: year, month: month, day: day, hour: 12)),138 cal.component(.month, from: midday) == month, cal.component(.day, from: midday) == day else {139 throw ToolError("\(String(t.prefix(10))) is not a real calendar date.")140 }141 return date142 }143144 public static func iso(_ date: Date, zone: TimeZone) -> String {145 let f = ISO8601DateFormatter()146 f.timeZone = zone147 f.formatOptions = [.withInternetDateTime]148 return f.string(from: date)149 }150151 public static func weekday(_ date: Date, zone: TimeZone) -> String {152 calendar(zone).weekdaySymbols[calendar(zone).component(.weekday, from: date) - 1]153 }154155 public static func offsetLabel(_ date: Date, zone: TimeZone) -> String {156 let seconds = zone.secondsFromGMT(for: date)157 let absolute = abs(seconds)158 return String(format: "UTC%@%02d:%02d", seconds < 0 ? "-" : "+", absolute / 3600, (absolute % 3600) / 60)159 }160161 /// The same instant described for a reader: ISO form with offset, UTC form, wall-clock text, zone and weekday.162 public static func describe(_ date: Date, zone: TimeZone) -> String {163 let human = DateFormatter()164 human.calendar = calendar(zone); human.locale = Locale(identifier: "en_US_POSIX"); human.timeZone = zone165 human.dateFormat = "EEEE, d MMMM yyyy, HH:mm:ss"166 let cal = calendar(zone)167 let week = cal.component(.weekOfYear, from: date), dayOfYear = cal.ordinality(of: .day, in: .year, for: date) ?? 0168 return [169 "iso: \(iso(date, zone: zone))",170 "utc: \(iso(date, zone: TimeZone(identifier: "UTC")!))",171 "local: \(human.string(from: date))",172 "timezone: \(zone.identifier) (\(offsetLabel(date, zone: zone)), \(zone.isDaylightSavingTime(for: date) ? "daylight saving time" : "standard time"))",173 "weekday: \(weekday(date, zone: zone))",174 "day_of_year: \(dayOfYear)",175 "week_of_year: \(week)",176 "unix: \(Int(date.timeIntervalSince1970.rounded(.down)))",177 ].joined(separator: "\n")178 }179180 public struct Offset: Sendable, Hashable {181 public var years = 0, months = 0, weeks = 0, days = 0, hours = 0, minutes = 0, seconds = 0182 public init(years: Int = 0, months: Int = 0, weeks: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) {183 self.years = years; self.months = months; self.weeks = weeks; self.days = days184 self.hours = hours; self.minutes = minutes; self.seconds = seconds185 }186 public var isZero: Bool { self == Offset() }187 }188189 /// Calendar units (years, months, weeks, days) keep the wall-clock time across a daylight-saving change;190 /// hours, minutes and seconds are exact elapsed time. Calendar units are applied first.191 public static func add(_ offset: Offset, to date: Date, zone: TimeZone) throws -> Date {192 let cal = calendar(zone)193 let calendarPart = DateComponents(year: offset.years, month: offset.months, day: offset.days + offset.weeks * 7)194 guard let shifted = cal.date(byAdding: calendarPart, to: date) else { throw ToolError("That date is out of range.") }195 let elapsed = Double(offset.hours) * 3600 + Double(offset.minutes) * 60 + Double(offset.seconds)196 let result = shifted.addingTimeInterval(elapsed)197 guard (1...9999).contains(cal.component(.year, from: result)) else { throw ToolError("That date is out of range.") }198 return result199 }200201 public struct Difference: Sendable, Hashable {202 public var seconds: Int203 public var years: Int, months: Int, days: Int, hours: Int, minutes: Int, remainingSeconds: Int204 /// Calendar days between the two local dates, ignoring the time of day.205 public var calendarDays: Int206 }207208 public static func difference(from: Date, to: Date, zone: TimeZone) -> Difference {209 let cal = calendar(zone)210 let parts = cal.dateComponents([.year, .month, .day, .hour, .minute, .second], from: from, to: to)211 let days = cal.dateComponents([.day], from: cal.startOfDay(for: from), to: cal.startOfDay(for: to)).day ?? 0212 return Difference(seconds: Int(to.timeIntervalSince(from).rounded()), years: parts.year ?? 0, months: parts.month ?? 0, days: parts.day ?? 0,213 hours: parts.hour ?? 0, minutes: parts.minute ?? 0, remainingSeconds: parts.second ?? 0, calendarDays: days)214 }215}216217public struct DateTimeTool: AgentTool {218 public let risk: ToolRisk = .safe219 let now: @Sendable () -> Date220 let defaultTimeZone: TimeZone221222 /// `now` is injected so tests (and previews) run against a fixed clock.223 public init(now: @escaping @Sendable () -> Date = { Date() }, defaultTimeZone: TimeZone = .current) {224 self.now = now; self.defaultTimeZone = defaultTimeZone225 }226227 public var definition: ToolDefinition {228 let amount: JSONValue = ["type": "integer", "minimum": .number(-1_000_000), "maximum": 1_000_000]229 return ToolDefinition(230 name: "datetime",231 summary: "Dates and times, computed rather than guessed. Operations: now (current time), add (add or subtract years, months, weeks, days, "232 + "hours, minutes, seconds), difference (between date and other_date), weekday, format (describe a date in a zone), convert (same instant "233 + "in to_timezone). Dates are ISO 8601; a date without an offset is local time in “timezone”.",234 parameters: [235 "type": "object",236 "properties": [237 "operation": ["type": "string", "enum": ["now", "add", "difference", "weekday", "format", "convert"]],238 "timezone": ["type": "string", "maxLength": 64, "description": "IANA time zone such as America/Toronto. Default: the device time zone."],239 "to_timezone": ["type": "string", "maxLength": 64, "description": "Target zone for convert."],240 "date": ["type": "string", "maxLength": 40, "description": "ISO 8601 date or date-time. Default: now."],241 "other_date": ["type": "string", "maxLength": 40, "description": "Second date for difference."],242 "years": amount, "months": amount, "weeks": amount, "days": amount, "hours": amount, "minutes": amount, "seconds": amount,243 ],244 "required": ["operation"],245 "additionalProperties": false,246 ])247 }248249 public func run(_ arguments: JSONValue, context: ToolContext) async throws -> ToolOutput {250 let zone = try arguments["timezone"]?.stringValue.map(DateTimeEngine.timeZone) ?? defaultTimeZone251 let current = now()252 func date(_ key: String) throws -> Date? { try arguments[key]?.stringValue.map { try DateTimeEngine.parse($0, zone: zone) } }253 let base = try date("date") ?? current254255 switch arguments["operation"]?.stringValue ?? "" {256 case "now":257 return ToolOutput(DateTimeEngine.describe(current, zone: zone))258 case "weekday":259 return ToolOutput("weekday: \(DateTimeEngine.weekday(base, zone: zone))\n" + DateTimeEngine.describe(base, zone: zone))260 case "format":261 return ToolOutput(DateTimeEngine.describe(base, zone: zone))262 case "convert":263 guard let target = arguments["to_timezone"]?.stringValue else { throw ToolError("convert needs “to_timezone”.") }264 let targetZone = try DateTimeEngine.timeZone(target)265 return ToolOutput("from:\n" + indent(DateTimeEngine.describe(base, zone: zone)) + "\nto:\n" + indent(DateTimeEngine.describe(base, zone: targetZone)))266 case "add":267 func n(_ key: String) -> Int { arguments[key]?.exactInt ?? 0 }268 let offset = DateTimeEngine.Offset(years: n("years"), months: n("months"), weeks: n("weeks"), days: n("days"), hours: n("hours"),269 minutes: n("minutes"), seconds: n("seconds"))270 guard !offset.isZero else { throw ToolError("add needs at least one of years, months, weeks, days, hours, minutes, seconds.") }271 let result = try DateTimeEngine.add(offset, to: base, zone: zone)272 return ToolOutput("start: \(DateTimeEngine.iso(base, zone: zone))\n" + DateTimeEngine.describe(result, zone: zone))273 case "difference":274 guard let other = try date("other_date") else { throw ToolError("difference needs “other_date” (and “date”, which defaults to now).") }275 let d = DateTimeEngine.difference(from: base, to: other, zone: zone)276 let sign = d.seconds < 0 ? "other_date is earlier than date" : d.seconds == 0 ? "the two instants are equal" : "other_date is later than date"277 return ToolOutput([278 "from: \(DateTimeEngine.iso(base, zone: zone))",279 "to: \(DateTimeEngine.iso(other, zone: zone))",280 "direction: \(sign)",281 "elapsed_seconds: \(d.seconds)",282 "elapsed_hours: \(Calculator.format(.real(Double(d.seconds) / 3600)))",283 "elapsed_days: \(Calculator.format(.real(Double(d.seconds) / 86_400)))",284 "calendar_days: \(d.calendarDays)",285 "breakdown: \(d.years) years, \(d.months) months, \(d.days) days, \(d.hours) hours, \(d.minutes) minutes, \(d.remainingSeconds) seconds",286 ].joined(separator: "\n"))287 default:288 throw ToolError("Unknown operation.")289 }290 }291292 private func indent(_ text: String) -> String { text.split(separator: "\n").map { " " + $0 }.joined(separator: "\n") }293}294