import Foundation #if canImport(FoundationModels) import FoundationModels #endif /// Ask Bucksley: questions about your money, answered from your own numbers. By default Apple's /// on-device model answers, so nothing leaves the device. With the user's own Claude or OpenAI key /// (in the Keychain) the question and a compact summary go straight to that provider. public struct AskBucksley: Sendable { public struct Answer: Sendable, Hashable { public let text: String public let provider: String /// Transactions the answer looked up, to show under it as links. public var transactionIDs: [String] = [] /// The answer covered budgets, so the app offers the smart budget walkthrough. public var offersBudgetPlan = false } let http: HTTPClient public init(http: HTTPClient = URLSessionHTTP()) { self.http = http } /// Set by the Mac app: runs the person's own agent (Claude Code or Codex) with Bucksley's read-only /// MCP tools and returns its answer. nonisolated(unsafe) public static var agentRunner: (@Sendable (_ prompt: String, _ agent: AskProvider, _ model: String?) async throws -> String)? /// Set by the Mac app: the agents installed on this Mac, best first. nonisolated(unsafe) public static var installedAgents: @Sendable () -> [AskProvider] = { [] } /// Who answers: Apple Intelligence unless the person chose another source in Settings and agreed to /// send their numbers to it. An installed agent is never used on its own. public static func provider(for settings: Settings) -> AskProvider { if settings.askProvider.isAgent, !installedAgents().contains(settings.askProvider) { return .apple } return settings.askProvider } public static var appleModelAvailable: Bool { #if canImport(FoundationModels) if #available(macOS 26, iOS 26, *) { return SystemLanguageModel.default.availability == .available } #endif return false } public static var appleModelStatus: String { #if canImport(FoundationModels) if #available(macOS 26, iOS 26, *) { switch SystemLanguageModel.default.availability { case .available: return "Ready on this device" case .unavailable(.appleIntelligenceNotEnabled): return "Turn on Apple Intelligence in System Settings" case .unavailable(.modelNotReady): return "Apple Intelligence is still downloading" case .unavailable(.deviceNotEligible): return "This device can't run Apple Intelligence" case .unavailable: return "Apple Intelligence isn't available" } } #endif return "Needs macOS 26 or iOS 26" } static let instructions = """ You are Bucksley, a calm, plain-spoken personal finance assistant inside a read-only money app. \ Answer only from the user's data below. Be specific with dollar amounts and dates, keep it to a few \ short sentences or a short list, and say when the data doesn't cover the question. You can't move \ money or change anything. Never give investment, tax or legal advice beyond describing the numbers. \ Never add up or calculate amounts yourself: quote the totals given below or returned by a tool exactly. \ Account balances are not transactions or charges: a card's balance is what's owed, never a single purchase. \ Transfers between the user's own accounts, such as card payments, are not spending or income. \ Use the tools to look up the transactions behind a question. The app lists the transactions you looked up \ under your answer as links, so name the important ones and say what stands out instead of repeating every line. \ For budgets, saving more or cutting back, act as a coach: use the smart budget plan tool, explain which \ categories are fixed bills (budgeted at what's spent, never cut) and which are flexible (set a little under recent spending), name the one or two categories with the most room, and say \ how close the plan gets to the savings goal. The app shows a button that sets the plan up in one step. \ End with one useful next step when there is one, such as a budget to set or a charge to check. """ /// Extra direction for an agent, which reaches the numbers through Bucksley's MCP tools. static let agentNote = """ You have Bucksley's read-only MCP tools (list_transactions, get_spending, list_budgets, get_smart_budget_plan, \ get_cash_flow, list_recurring, get_insights and more). Use them for anything the summary below doesn't settle. \ You can't change anything from here. Reply in plain text for a chat bubble: a few short sentences or a short list. """ /// Direction for an agent that has no tools and answers from the summary alone. static let summaryNote = """ You have no tools here. Answer from the summary below, and say when it doesn't cover the question. \ Reply in plain text for a chat bubble: a few short sentences or a short list. """ public func ask(_ question: String, ledger: Ledger, provider: AskProvider, model: String? = nil) async throws -> Answer { let context = Self.context(ledger) let tools = AskTools(ledger: ledger) switch provider { case .claudeCode, .codex, .gemini: guard let run = Self.agentRunner else { throw BucksleyError.missing("\(provider.title) runs only on the Mac.") } let prompt = Self.instructions + "\n\n" + (provider.usesTools ? Self.agentNote : Self.summaryNote) + "\n\n" + context + "\n\nQuestion: " + question let text = try await run(prompt, provider, model).trimmingCharacters(in: .whitespacesAndNewlines) return Answer(text: text, provider: provider.title, transactionIDs: Self.linked(text, found: [], ledger: ledger), offersBudgetPlan: Self.isAboutBudgets(question) || text.lowercased().contains("budget")) case .apple: #if canImport(FoundationModels) if #available(macOS 26, iOS 26, *), Self.appleModelAvailable { let session = LanguageModelSession(tools: tools.appleTools, instructions: Self.instructions + "\n\n" + context) let response = try await session.respond(to: question) let text = response.content.trimmingCharacters(in: .whitespacesAndNewlines) return Answer(text: text, provider: "Apple Intelligence", transactionIDs: Self.linked(text, found: tools.transactionIDs, ledger: ledger), offersBudgetPlan: tools.madeBudgetPlan || Self.isAboutBudgets(question)) } #endif return Answer(text: Self.offlineAnswer(question, ledger: ledger), provider: "Bucksley (offline)", transactionIDs: Self.offlineTransactions(question, ledger: ledger), offersBudgetPlan: Self.isAboutBudgets(question)) case .claude: guard let key = Keychain.get(.claudeKey) else { throw BucksleyError.missing("Add your Claude API key in Settings → Ask Bucksley.") } var request = URLRequest(url: URL(string: "https://api.anthropic.com/v1/messages")!) request.httpMethod = "POST" request.setValue(key, forHTTPHeaderField: "x-api-key") request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version") request.setValue("application/json", forHTTPHeaderField: "content-type") let toolDefs = AskTools.definitions.map { ["name": $0.name, "description": $0.description, "input_schema": ["type": "object", "properties": $0.properties]] as [String: Any] } var messages: [[String: Any]] = [["role": "user", "content": question]] for _ in 0..<6 { request.httpBody = try JSONSerialization.data(withJSONObject: [ "model": model ?? "claude-opus-5-5", "max_tokens": 1200, "system": Self.instructions + "\n\n" + context, "tools": toolDefs, "messages": messages ] as [String: Any]) let (data, response) = try await http.send(request) let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] guard response.statusCode == 200 else { throw BucksleyError.network("Claude: " + (((json["error"] as? [String: Any])?["message"] as? String) ?? "HTTP \(response.statusCode)")) } let content = json["content"] as? [[String: Any]] ?? [] let uses = content.filter { $0["type"] as? String == "tool_use" } if uses.isEmpty || json["stop_reason"] as? String != "tool_use" { let text = content.compactMap { $0["text"] as? String }.joined() return Answer(text: text, provider: "Claude", transactionIDs: Self.linked(text, found: tools.transactionIDs, ledger: ledger), offersBudgetPlan: tools.madeBudgetPlan || Self.isAboutBudgets(question)) } messages.append(["role": "assistant", "content": content]) messages.append(["role": "user", "content": uses.map { use in ["type": "tool_result", "tool_use_id": use["id"] as? String ?? "", "content": tools.run(use["name"] as? String ?? "", use["input"] as? [String: Any] ?? [:])] as [String: Any] }]) } throw BucksleyError.network("Claude kept looking things up without answering. Try a narrower question.") case .openai: guard let key = Keychain.get(.openAIKey) else { throw BucksleyError.missing("Add your OpenAI API key in Settings → Ask Bucksley.") } var request = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!) request.httpMethod = "POST" request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization") request.setValue("application/json", forHTTPHeaderField: "content-type") let toolDefs = AskTools.definitions.map { ["type": "function", "function": ["name": $0.name, "description": $0.description, "parameters": ["type": "object", "properties": $0.properties]]] as [String: Any] } var messages: [[String: Any]] = [["role": "system", "content": Self.instructions + "\n\n" + context], ["role": "user", "content": question]] for _ in 0..<6 { request.httpBody = try JSONSerialization.data(withJSONObject: ["model": model ?? "gpt-6.1-sol", "messages": messages, "tools": toolDefs] as [String: Any]) let (data, response) = try await http.send(request) let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] guard response.statusCode == 200 else { throw BucksleyError.network("OpenAI: " + (((json["error"] as? [String: Any])?["message"] as? String) ?? "HTTP \(response.statusCode)")) } let message = ((json["choices"] as? [[String: Any]])?.first?["message"] as? [String: Any]) ?? [:] let calls = message["tool_calls"] as? [[String: Any]] ?? [] if calls.isEmpty { let text = message["content"] as? String ?? "" return Answer(text: text, provider: "OpenAI", transactionIDs: Self.linked(text, found: tools.transactionIDs, ledger: ledger), offersBudgetPlan: tools.madeBudgetPlan || Self.isAboutBudgets(question)) } messages.append(message) for call in calls { let function = call["function"] as? [String: Any] ?? [:] let arguments = (function["arguments"] as? String).flatMap { $0.data(using: .utf8) } .flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } ?? [:] messages.append(["role": "tool", "tool_call_id": call["id"] as? String ?? "", "content": tools.run(function["name"] as? String ?? "", arguments)]) } } throw BucksleyError.network("OpenAI kept looking things up without answering. Try a narrower question.") } } /// The user's numbers in a few hundred words: accounts, this month and last by category, budgets, /// recurring charges and the latest transactions. public static func context(_ ledger: Ledger, today: String = DayKey.today) -> String { let ws = ledger.workspace func name(_ id: String) -> String { ws.category(id)?.name ?? id } var lines: [String] = ["Today is \(today)."] lines.append("Net worth \(Money.format(ledger.netWorth)) (change over 30 days \(Money.format(ledger.change(days: 30), signed: true)), over a year \(Money.format(ledger.change(days: 365), signed: true))).") lines.append("Account balances (not transactions; negative means owed): " + ledger.visibleAccounts.map { "\($0.displayName) (\($0.institution), \($0.kind.title)) balance \(Money.format($0.balance))" }.joined(separator: "; ")) let month = MonthKey.of(today), last = MonthKey.adding(-1, to: month) for m in [month, last] { let spend = ledger.spending(month: m) lines.append("Spending in \(MonthKey.title(m)): total \(Money.format(spend.reduce(0) { $0 + $1.amount })); " + spend.prefix(12).map { "\(name($0.categoryID)) \(Money.format($0.amount))" }.joined(separator: ", ") + ". Income \(Money.format(ledger.income(month: m))).") } let largest = ledger.entries(in: month).filter { $0.amount < 0 && ledger.kind($0.categoryID) == .expense }.sorted { $0.amount < $1.amount }.prefix(5) if !largest.isEmpty { lines.append("Largest charges in \(MonthKey.title(month)): " + largest.map { "\($0.day) \($0.name) \(Money.format($0.amount))" }.joined(separator: "; ")) } let budgets = ledger.budgetStatus(month: month, today: today) if !budgets.isEmpty { lines.append("Budgets this month: " + budgets.map { "\(ledger.budgetName($0.id)) spent \(Money.format($0.spent)) of \(Money.format($0.available))" }.joined(separator: "; ")) } let recurring = ledger.recurring(today: today).filter { $0.status != .dismissed } if !recurring.isEmpty { let monthly = recurring.reduce(Decimal(0)) { $0 + $1.amount * 30 / Decimal($1.cadence.days) }.rounded(2) lines.append("Recurring total: \(Money.format(monthly)) a month across \(recurring.count) recurring charges.") lines.append("Recurring: " + recurring.prefix(15).map { "\($0.name) \(Money.format($0.amount)) \($0.cadence.rawValue), next \($0.nextDay)" }.joined(separator: "; ")) } let flow = ledger.cashFlow(months: 12, through: month) let avg = ledger.cashFlowAverages(flow) lines.append("Cash flow by month (income / spend / net): " + flow.filter { $0.income != 0 || $0.spend != 0 } .map { "\(MonthKey.title($0.month)) \(Money.format($0.income, cents: false)) / \(Money.format($0.spend, cents: false)) / \(Money.format($0.net, cents: false))" } .joined(separator: "; ") + ". Monthly averages: income \(Money.format(avg.income, cents: false)), spend \(Money.format(avg.spend, cents: false)), net \(Money.format(avg.net, cents: false)).") let flags = ledger.flags(today: today) if !flags.isEmpty { lines.append("Charges worth a look: " + flags.prefix(8).map(\.reason).joined(separator: " ")) } lines.append("Recent transactions: " + ledger.entries.prefix(40).map { "\($0.day) \($0.name) \(Money.format($0.amount)) [\(name($0.categoryID))]" }.joined(separator: "; ")) return lines.joined(separator: "\n") } /// Without a model, Bucksley still answers the common questions from the numbers. public static func offlineAnswer(_ question: String, ledger: Ledger, today: String = DayKey.today) -> String { let q = question.lowercased() let ws = ledger.workspace let month = MonthKey.of(today) if let category = ws.categories.first(where: { q.contains($0.name.lowercased()) }) { let now = ledger.spent(category.id, month: month), before = ledger.spent(category.id, month: MonthKey.adding(-1, to: month)) var text = "You've spent \(Money.format(now)) on \(category.name) so far in \(MonthKey.title(month)), compared with \(Money.format(before)) last month." if let budget = ledger.budgetStatus(month: month, today: today).first(where: { $0.id == category.id }) { text += " That's \(Int((budget.progress * 100).rounded()))% of your \(Money.format(budget.available)) budget." } return text } if q.contains("net worth") || q.contains("worth") { return "Your net worth is \(Money.format(ledger.netWorth)), \(Money.format(ledger.change(days: 30), signed: true)) over the last 30 days." } if q.contains("subscription") || q.contains("recurring") || q.contains("bill") { let items = ledger.recurring(today: today).filter { $0.status != .dismissed } guard !items.isEmpty else { return "I haven't found any recurring charges yet. They show up after three on a steady schedule." } let monthly = items.reduce(Decimal(0)) { $0 + $1.amount * Decimal(30) / Decimal($1.cadence.days) } return "You have \(items.count) recurring charges, about \(Money.format(monthly.rounded(0), cents: false)) a month. Next up: " + items.prefix(3).map { "\($0.name) \(Money.format($0.amount)) on \($0.nextDay)" }.joined(separator: ", ") + "." } let spend = ledger.spending(month: month) let total = spend.reduce(Decimal(0)) { $0 + $1.amount } let top = spend.prefix(3).map { "\(ws.category($0.categoryID)?.name ?? $0.categoryID) \(Money.format($0.amount, cents: false))" }.joined(separator: ", ") return "So far in \(MonthKey.title(month)) you've spent \(Money.format(total)) and earned \(Money.format(ledger.income(month: month)))." + (top.isEmpty ? "" : " The biggest categories are \(top).") + " Turn on Apple Intelligence or add a Claude or OpenAI key in Settings for fuller answers." } /// "Ask My Agent" when Claude or OpenAI is chosen and its key is saved, otherwise "Ask Bucksley" /// (Apple Intelligence on this device). /// Named for who answers: Ask Apple Intelligence, Ask Claude, Ask Codex, Ask Gemini or Ask OpenAI. public static func title(for provider: AskProvider) -> String { switch answerer(provider) { case .apple: "Ask Apple Intelligence" case .claude, .claudeCode: "Ask Claude" case .codex: "Ask Codex" case .openai: "Ask OpenAI" case .gemini: "Ask Gemini" } } /// Who actually answers: the chosen source when it's ready, else Apple Intelligence. public static func answerer(_ provider: AskProvider) -> AskProvider { usesAgent(provider) ? provider : .apple } public static func usesAgent(_ provider: AskProvider) -> Bool { switch provider { case .apple: false case .claudeCode, .codex, .gemini: installedAgents().contains(provider) case .claude: Keychain.get(.claudeKey)?.isEmpty == false case .openai: Keychain.get(.openAIKey)?.isEmpty == false } } /// Answers often use **bold** and lists; show the emphasis instead of the asterisks. public static func formatted(_ text: String) -> AttributedString { (try? AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(text) } static func isAboutBudgets(_ question: String) -> Bool { let q = question.lowercased() return ["budget", "save more", "saving", "cut back", "spend less", "overspend"].contains { q.contains($0) } } /// The transactions to link under an answer. Ones the answer names (merchant and amount) come /// first, even when the model answered from the summary without a lookup, then the rest it looked up. static func linked(_ text: String, found: [String], ledger: Ledger, today: String = DayKey.today) -> [String] { let lower = text.lowercased() let recent = DayKey.adding(-120, to: today) let candidates = ledger.entries.filter { e in guard e.day >= recent else { return false } let amount = Money.format(abs(e.amount)).lowercased() guard lower.contains(amount) || lower.contains(amount.replacingOccurrences(of: ".00", with: "")) else { return false } let word = e.name.lowercased().split(separator: " ").map(String.init).first { $0 != "the" } ?? "" return word.count >= 3 && lower.contains(word) } // A repeating charge (rent every month) matches many times: keep the one whose date the answer // gives, otherwise the newest. let picked = Dictionary(grouping: candidates) { "\($0.name.lowercased())|\($0.amount)" }.values.compactMap { group in group.first { lower.contains($0.day) } ?? group.max { $0.day < $1.day } } func position(_ e: LedgerEntry) -> String.Index { lower.range(of: Money.format(abs(e.amount)).lowercased())?.lowerBound ?? lower.endIndex } let named = picked.sorted { position($0) < position($1) }.map(\.id) var seen = Set() return Array((named + (named.isEmpty ? found : [])).filter { seen.insert($0).inserted }.prefix(12)) } /// The transactions an offline answer is about: a category's this month, or this month's largest charges. static func offlineTransactions(_ question: String, ledger: Ledger, today: String = DayKey.today) -> [String] { let q = question.lowercased(), month = MonthKey.of(today) let entries = ledger.entries(in: month) if let category = ledger.workspace.categories.first(where: { q.contains($0.name.lowercased()) }) { return entries.filter { $0.categoryID == category.id }.prefix(12).map(\.id) } guard !(q.contains("worth") || q.contains("subscription") || q.contains("recurring") || q.contains("bill")) else { return [] } return entries.filter { $0.amount < 0 && ledger.kind($0.categoryID) == .expense }.sorted { $0.amount < $1.amount }.prefix(8).map(\.id) } /// One friendly sentence for the Overview card. public static func suggestion(_ ledger: Ledger, today: String = DayKey.today) -> String? { let ws = ledger.workspace if let hot = ledger.budgetStatus(month: MonthKey.of(today), today: today).first(where: { $0.aheadOfPace && $0.pace < 1 }) { let name = ledger.budgetName(hot.id) return "\(name) is at \(Int((hot.progress * 100).rounded()))% of its budget with \(Int(((1 - hot.pace) * 100).rounded()))% of the month left. \(hot.remaining >= 0 ? Money.format(hot.remaining, cents: false) + " to go." : Money.format(-hot.remaining, cents: false) + " over already.")" } if let s = ledger.budgetSuggestions(today: today).first(where: { s in !ws.budgets.contains { $0.categoryID == s.categoryID } }) { return "You don't have a budget for \(ws.category(s.categoryID)?.name ?? s.categoryID) yet. Based on your last \(s.months) months, \(Money.format(s.amount, cents: false)) a month would fit." } let review = ledger.reviewQueue.count if review > 0 { return "\(review) transaction\(review == 1 ? "" : "s") waiting for review. Swipe through them on your iPhone." } return nil } }