import Foundation import OSLog /// Client for OpenRouter's Decisions API (`/api/alpha/decisions`), which serves "System One" /// decision models such as TypeSafe's Jev and Respan's Span-01. Instead of generating text, /// they answer typed questions about a state with calibrated probabilities. /// /// With `local` set, the same questions are answered on-device by LocalDecisionEngine. /// /// Some models (Span-01) only answer yes/no (`noul`) questions. For those, each choice is /// asked as one yes/no question per option and the most likely option wins. struct DecisionClient: Sendable { let apiKey: String let model: String /// When set, decisions run on-device (d1-2B through llama.cpp) instead of over the network. var local: LocalDecisionEngine? private static let endpoint = URL(string: "https://openrouter.ai/api/alpha/decisions")! struct Choice: Sendable { let instructions: String /// Option key → plain-language description, in display order. let options: [(key: String, description: String)] } struct Noul: Sendable { let instructions: String let yes: String let no: String } struct ChoiceAnswer: Sendable { let choice: String /// Probability of `choice` (for yes/no-only models, the raw "yes" probability). let probability: Double } struct Answers: Sendable { var choices: [String: ChoiceAnswer] = [:] /// Probability of "yes" per question. var nouls: [String: Double] = [:] } /// Respan models reject `choice` questions and structured state. var nounOnly: Bool { model.hasPrefix("respan/") } func decide(state: String, choices: [String: Choice] = [:], nouls: [String: Noul] = [:]) async throws -> Answers { if let local { return try await local.decide(state: state, choices: choices, nouls: nouls) } guard !apiKey.isEmpty else { throw ProviderError.missingAPIKey } var questions: [String: Any] = [:] for (key, q) in nouls { questions[key] = ["type": "noul", "instructions": q.instructions, "criteria": ["true": q.yes, "false": q.no]] } for (key, q) in choices { if nounOnly { for (i, option) in q.options.enumerated() { questions[Self.expandedKey(key, i)] = [ "type": "noul", "instructions": "\(q.instructions) Is the answer: \(option.description)?", "criteria": ["true": "Yes, the answer is: \(option.description)", "false": "No, a different answer"] ] } } else { questions[key] = ["type": "choice", "instructions": q.instructions, "criteria": Dictionary(q.options.map { ($0.key, $0.description) }, uniquingKeysWith: { a, _ in a })] } } var req = URLRequest(url: Self.endpoint) req.httpMethod = "POST" req.timeoutInterval = 30 req.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.httpBody = try JSONSerialization.data(withJSONObject: [ "model": model, "state": state, "questions": questions ]) let started = Date() let (data, response) = try await URLSession.shared.data(for: req) let status = (response as? HTTPURLResponse)?.statusCode ?? 0 guard status == 200 else { let body = String(data: data, encoding: .utf8) ?? "" Logger.api.error("Decisions HTTP \(status, privacy: .public): \(body, privacy: .public)") throw ProviderError.httpError(status, body) } guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any], let raw = json["answers"] as? [String: [String: Any]] else { throw ProviderError.decodingError("Decisions response has no answers") } Logger.api.info("Decisions — model=\(model, privacy: .public) questions=\(questions.count, privacy: .public) in \(Date().timeIntervalSince(started), format: .fixed(precision: 2), privacy: .public)s") var answers = Answers() for key in nouls.keys { answers.nouls[key] = raw[key]?["noul"] as? Double ?? 0 } for (key, q) in choices { if nounOnly { let scored = q.options.indices.map { i in (q.options[i].key, raw[Self.expandedKey(key, i)]?["noul"] as? Double ?? 0) } if let best = scored.max(by: { $0.1 < $1.1 }) { answers.choices[key] = ChoiceAnswer(choice: best.0, probability: best.1) } } else if let answer = raw[key], let choice = answer["choice"] as? String { let probability = (answer["probabilities"] as? [String: Double])?[choice] ?? answer["confidence"] as? Double ?? 0 answers.choices[key] = ChoiceAnswer(choice: choice, probability: probability) } } return answers } private static func expandedKey(_ key: String, _ index: Int) -> String { "\(key)__\(index)" } }