Branchwell

Bucksley / app · bucksley.ai / Sources / BucksleyKit / AskBucksley.swift

1import Foundation
2#if canImport(FoundationModels)
3import FoundationModels
4#endif
5
6/// Ask Bucksley: questions about your money, answered from your own numbers. By default Apple's
7/// on-device model answers, so nothing leaves the device. With the user's own Claude or OpenAI key
8/// (in the Keychain) the question and a compact summary go straight to that provider.
9public struct AskBucksley: Sendable {
10 public struct Answer: Sendable, Hashable {
11 public let text: String
12 public let provider: String
13 /// Transactions the answer looked up, to show under it as links.
14 public var transactionIDs: [String] = []
15 /// The answer covered budgets, so the app offers the smart budget walkthrough.
16 public var offersBudgetPlan = false
17 }
18
19 let http: HTTPClient
20 public init(http: HTTPClient = URLSessionHTTP()) { self.http = http }
21
22 /// Set by the Mac app: runs the person's own agent (Claude Code or Codex) with Bucksley's read-only
23 /// MCP tools and returns its answer.
24 nonisolated(unsafe) public static var agentRunner: (@Sendable (_ prompt: String, _ agent: AskProvider, _ model: String?) async throws -> String)?
25 /// Set by the Mac app: the agents installed on this Mac, best first.
26 nonisolated(unsafe) public static var installedAgents: @Sendable () -> [AskProvider] = { [] }
27
28 /// Who answers: Apple Intelligence unless the person chose another source in Settings and agreed to
29 /// send their numbers to it. An installed agent is never used on its own.
30 public static func provider(for settings: Settings) -> AskProvider {
31 if settings.askProvider.isAgent, !installedAgents().contains(settings.askProvider) { return .apple }
32 return settings.askProvider
33 }
34
35 public static var appleModelAvailable: Bool {
36 #if canImport(FoundationModels)
37 if #available(macOS 26, iOS 26, *) { return SystemLanguageModel.default.availability == .available }
38 #endif
39 return false
40 }
41
42 public static var appleModelStatus: String {
43 #if canImport(FoundationModels)
44 if #available(macOS 26, iOS 26, *) {
45 switch SystemLanguageModel.default.availability {
46 case .available: return "Ready on this device"
47 case .unavailable(.appleIntelligenceNotEnabled): return "Turn on Apple Intelligence in System Settings"
48 case .unavailable(.modelNotReady): return "Apple Intelligence is still downloading"
49 case .unavailable(.deviceNotEligible): return "This device can't run Apple Intelligence"
50 case .unavailable: return "Apple Intelligence isn't available"
51 }
52 }
53 #endif
54 return "Needs macOS 26 or iOS 26"
55 }
56
57 static let instructions = """
58 You are Bucksley, a calm, plain-spoken personal finance assistant inside a read-only money app. \
59 Answer only from the user's data below. Be specific with dollar amounts and dates, keep it to a few \
60 short sentences or a short list, and say when the data doesn't cover the question. You can't move \
61 money or change anything. Never give investment, tax or legal advice beyond describing the numbers. \
62 Never add up or calculate amounts yourself: quote the totals given below or returned by a tool exactly. \
63 Account balances are not transactions or charges: a card's balance is what's owed, never a single purchase. \
64 Transfers between the user's own accounts, such as card payments, are not spending or income. \
65 Use the tools to look up the transactions behind a question. The app lists the transactions you looked up \
66 under your answer as links, so name the important ones and say what stands out instead of repeating every line. \
67 For budgets, saving more or cutting back, act as a coach: use the smart budget plan tool, explain which \
68 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 \
69 how close the plan gets to the savings goal. The app shows a button that sets the plan up in one step. \
70 End with one useful next step when there is one, such as a budget to set or a charge to check.
71 """
72
73 /// Extra direction for an agent, which reaches the numbers through Bucksley's MCP tools.
74 static let agentNote = """
75 You have Bucksley's read-only MCP tools (list_transactions, get_spending, list_budgets, get_smart_budget_plan, \
76 get_cash_flow, list_recurring, get_insights and more). Use them for anything the summary below doesn't settle. \
77 You can't change anything from here. Reply in plain text for a chat bubble: a few short sentences or a short list.
78 """
79
80 /// Direction for an agent that has no tools and answers from the summary alone.
81 static let summaryNote = """
82 You have no tools here. Answer from the summary below, and say when it doesn't cover the question. \
83 Reply in plain text for a chat bubble: a few short sentences or a short list.
84 """
85
86 public func ask(_ question: String, ledger: Ledger, provider: AskProvider, model: String? = nil) async throws -> Answer {
87 let context = Self.context(ledger)
88 let tools = AskTools(ledger: ledger)
89 switch provider {
90 case .claudeCode, .codex, .gemini:
91 guard let run = Self.agentRunner else { throw BucksleyError.missing("\(provider.title) runs only on the Mac.") }
92 let prompt = Self.instructions + "\n\n" + (provider.usesTools ? Self.agentNote : Self.summaryNote) + "\n\n" + context + "\n\nQuestion: " + question
93 let text = try await run(prompt, provider, model).trimmingCharacters(in: .whitespacesAndNewlines)
94 return Answer(text: text, provider: provider.title, transactionIDs: Self.linked(text, found: [], ledger: ledger),
95 offersBudgetPlan: Self.isAboutBudgets(question) || text.lowercased().contains("budget"))
96 case .apple:
97 #if canImport(FoundationModels)
98 if #available(macOS 26, iOS 26, *), Self.appleModelAvailable {
99 let session = LanguageModelSession(tools: tools.appleTools, instructions: Self.instructions + "\n\n" + context)
100 let response = try await session.respond(to: question)
101 let text = response.content.trimmingCharacters(in: .whitespacesAndNewlines)
102 return Answer(text: text, provider: "Apple Intelligence", transactionIDs: Self.linked(text, found: tools.transactionIDs, ledger: ledger), offersBudgetPlan: tools.madeBudgetPlan || Self.isAboutBudgets(question))
103 }
104 #endif
105 return Answer(text: Self.offlineAnswer(question, ledger: ledger), provider: "Bucksley (offline)",
106 transactionIDs: Self.offlineTransactions(question, ledger: ledger), offersBudgetPlan: Self.isAboutBudgets(question))
107 case .claude:
108 guard let key = Keychain.get(.claudeKey) else { throw BucksleyError.missing("Add your Claude API key in Settings → Ask Bucksley.") }
109 var request = URLRequest(url: URL(string: "https://api.anthropic.com/v1/messages")!)
110 request.httpMethod = "POST"
111 request.setValue(key, forHTTPHeaderField: "x-api-key")
112 request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
113 request.setValue("application/json", forHTTPHeaderField: "content-type")
114 let toolDefs = AskTools.definitions.map { ["name": $0.name, "description": $0.description,
115 "input_schema": ["type": "object", "properties": $0.properties]] as [String: Any] }
116 var messages: [[String: Any]] = [["role": "user", "content": question]]
117 for _ in 0..<6 {
118 request.httpBody = try JSONSerialization.data(withJSONObject: [
119 "model": model ?? "claude-opus-5-5", "max_tokens": 1200,
120 "system": Self.instructions + "\n\n" + context, "tools": toolDefs, "messages": messages
121 ] as [String: Any])
122 let (data, response) = try await http.send(request)
123 let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
124 guard response.statusCode == 200 else { throw BucksleyError.network("Claude: " + (((json["error"] as? [String: Any])?["message"] as? String) ?? "HTTP \(response.statusCode)")) }
125 let content = json["content"] as? [[String: Any]] ?? []
126 let uses = content.filter { $0["type"] as? String == "tool_use" }
127 if uses.isEmpty || json["stop_reason"] as? String != "tool_use" {
128 let text = content.compactMap { $0["text"] as? String }.joined()
129 return Answer(text: text, provider: "Claude", transactionIDs: Self.linked(text, found: tools.transactionIDs, ledger: ledger), offersBudgetPlan: tools.madeBudgetPlan || Self.isAboutBudgets(question))
130 }
131 messages.append(["role": "assistant", "content": content])
132 messages.append(["role": "user", "content": uses.map { use in
133 ["type": "tool_result", "tool_use_id": use["id"] as? String ?? "",
134 "content": tools.run(use["name"] as? String ?? "", use["input"] as? [String: Any] ?? [:])] as [String: Any]
135 }])
136 }
137 throw BucksleyError.network("Claude kept looking things up without answering. Try a narrower question.")
138 case .openai:
139 guard let key = Keychain.get(.openAIKey) else { throw BucksleyError.missing("Add your OpenAI API key in Settings → Ask Bucksley.") }
140 var request = URLRequest(url: URL(string: "https://api.openai.com/v1/chat/completions")!)
141 request.httpMethod = "POST"
142 request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
143 request.setValue("application/json", forHTTPHeaderField: "content-type")
144 let toolDefs = AskTools.definitions.map { ["type": "function", "function": ["name": $0.name, "description": $0.description,
145 "parameters": ["type": "object", "properties": $0.properties]]] as [String: Any] }
146 var messages: [[String: Any]] = [["role": "system", "content": Self.instructions + "\n\n" + context], ["role": "user", "content": question]]
147 for _ in 0..<6 {
148 request.httpBody = try JSONSerialization.data(withJSONObject: ["model": model ?? "gpt-6.1-sol", "messages": messages, "tools": toolDefs] as [String: Any])
149 let (data, response) = try await http.send(request)
150 let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
151 guard response.statusCode == 200 else { throw BucksleyError.network("OpenAI: " + (((json["error"] as? [String: Any])?["message"] as? String) ?? "HTTP \(response.statusCode)")) }
152 let message = ((json["choices"] as? [[String: Any]])?.first?["message"] as? [String: Any]) ?? [:]
153 let calls = message["tool_calls"] as? [[String: Any]] ?? []
154 if calls.isEmpty {
155 let text = message["content"] as? String ?? ""
156 return Answer(text: text, provider: "OpenAI", transactionIDs: Self.linked(text, found: tools.transactionIDs, ledger: ledger), offersBudgetPlan: tools.madeBudgetPlan || Self.isAboutBudgets(question))
157 }
158 messages.append(message)
159 for call in calls {
160 let function = call["function"] as? [String: Any] ?? [:]
161 let arguments = (function["arguments"] as? String).flatMap { $0.data(using: .utf8) }
162 .flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } ?? [:]
163 messages.append(["role": "tool", "tool_call_id": call["id"] as? String ?? "",
164 "content": tools.run(function["name"] as? String ?? "", arguments)])
165 }
166 }
167 throw BucksleyError.network("OpenAI kept looking things up without answering. Try a narrower question.")
168 }
169 }
170
171 /// The user's numbers in a few hundred words: accounts, this month and last by category, budgets,
172 /// recurring charges and the latest transactions.
173 public static func context(_ ledger: Ledger, today: String = DayKey.today) -> String {
174 let ws = ledger.workspace
175 func name(_ id: String) -> String { ws.category(id)?.name ?? id }
176 var lines: [String] = ["Today is \(today)."]
177 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))).")
178 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: "; "))
179 let month = MonthKey.of(today), last = MonthKey.adding(-1, to: month)
180 for m in [month, last] {
181 let spend = ledger.spending(month: m)
182 lines.append("Spending in \(MonthKey.title(m)): total \(Money.format(spend.reduce(0) { $0 + $1.amount })); " +
183 spend.prefix(12).map { "\(name($0.categoryID)) \(Money.format($0.amount))" }.joined(separator: ", ") +
184 ". Income \(Money.format(ledger.income(month: m))).")
185 }
186 let largest = ledger.entries(in: month).filter { $0.amount < 0 && ledger.kind($0.categoryID) == .expense }.sorted { $0.amount < $1.amount }.prefix(5)
187 if !largest.isEmpty { lines.append("Largest charges in \(MonthKey.title(month)): " + largest.map { "\($0.day) \($0.name) \(Money.format($0.amount))" }.joined(separator: "; ")) }
188 let budgets = ledger.budgetStatus(month: month, today: today)
189 if !budgets.isEmpty {
190 lines.append("Budgets this month: " + budgets.map { "\(ledger.budgetName($0.id)) spent \(Money.format($0.spent)) of \(Money.format($0.available))" }.joined(separator: "; "))
191 }
192 let recurring = ledger.recurring(today: today).filter { $0.status != .dismissed }
193 if !recurring.isEmpty {
194 let monthly = recurring.reduce(Decimal(0)) { $0 + $1.amount * 30 / Decimal($1.cadence.days) }.rounded(2)
195 lines.append("Recurring total: \(Money.format(monthly)) a month across \(recurring.count) recurring charges.")
196 lines.append("Recurring: " + recurring.prefix(15).map { "\($0.name) \(Money.format($0.amount)) \($0.cadence.rawValue), next \($0.nextDay)" }.joined(separator: "; "))
197 }
198 let flow = ledger.cashFlow(months: 12, through: month)
199 let avg = ledger.cashFlowAverages(flow)
200 lines.append("Cash flow by month (income / spend / net): " + flow.filter { $0.income != 0 || $0.spend != 0 }
201 .map { "\(MonthKey.title($0.month)) \(Money.format($0.income, cents: false)) / \(Money.format($0.spend, cents: false)) / \(Money.format($0.net, cents: false))" }
202 .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)).")
203 let flags = ledger.flags(today: today)
204 if !flags.isEmpty { lines.append("Charges worth a look: " + flags.prefix(8).map(\.reason).joined(separator: " ")) }
205 lines.append("Recent transactions: " + ledger.entries.prefix(40).map { "\($0.day) \($0.name) \(Money.format($0.amount)) [\(name($0.categoryID))]" }.joined(separator: "; "))
206 return lines.joined(separator: "\n")
207 }
208
209 /// Without a model, Bucksley still answers the common questions from the numbers.
210 public static func offlineAnswer(_ question: String, ledger: Ledger, today: String = DayKey.today) -> String {
211 let q = question.lowercased()
212 let ws = ledger.workspace
213 let month = MonthKey.of(today)
214 if let category = ws.categories.first(where: { q.contains($0.name.lowercased()) }) {
215 let now = ledger.spent(category.id, month: month), before = ledger.spent(category.id, month: MonthKey.adding(-1, to: month))
216 var text = "You've spent \(Money.format(now)) on \(category.name) so far in \(MonthKey.title(month)), compared with \(Money.format(before)) last month."
217 if let budget = ledger.budgetStatus(month: month, today: today).first(where: { $0.id == category.id }) {
218 text += " That's \(Int((budget.progress * 100).rounded()))% of your \(Money.format(budget.available)) budget."
219 }
220 return text
221 }
222 if q.contains("net worth") || q.contains("worth") {
223 return "Your net worth is \(Money.format(ledger.netWorth)), \(Money.format(ledger.change(days: 30), signed: true)) over the last 30 days."
224 }
225 if q.contains("subscription") || q.contains("recurring") || q.contains("bill") {
226 let items = ledger.recurring(today: today).filter { $0.status != .dismissed }
227 guard !items.isEmpty else { return "I haven't found any recurring charges yet. They show up after three on a steady schedule." }
228 let monthly = items.reduce(Decimal(0)) { $0 + $1.amount * Decimal(30) / Decimal($1.cadence.days) }
229 return "You have \(items.count) recurring charges, about \(Money.format(monthly.rounded(0), cents: false)) a month. Next up: " +
230 items.prefix(3).map { "\($0.name) \(Money.format($0.amount)) on \($0.nextDay)" }.joined(separator: ", ") + "."
231 }
232 let spend = ledger.spending(month: month)
233 let total = spend.reduce(Decimal(0)) { $0 + $1.amount }
234 let top = spend.prefix(3).map { "\(ws.category($0.categoryID)?.name ?? $0.categoryID) \(Money.format($0.amount, cents: false))" }.joined(separator: ", ")
235 return "So far in \(MonthKey.title(month)) you've spent \(Money.format(total)) and earned \(Money.format(ledger.income(month: month)))." +
236 (top.isEmpty ? "" : " The biggest categories are \(top).") +
237 " Turn on Apple Intelligence or add a Claude or OpenAI key in Settings for fuller answers."
238 }
239
240 /// "Ask My Agent" when Claude or OpenAI is chosen and its key is saved, otherwise "Ask Bucksley"
241 /// (Apple Intelligence on this device).
242 /// Named for who answers: Ask Apple Intelligence, Ask Claude, Ask Codex, Ask Gemini or Ask OpenAI.
243 public static func title(for provider: AskProvider) -> String {
244 switch answerer(provider) {
245 case .apple: "Ask Apple Intelligence"
246 case .claude, .claudeCode: "Ask Claude"
247 case .codex: "Ask Codex"
248 case .openai: "Ask OpenAI"
249 case .gemini: "Ask Gemini"
250 }
251 }
252
253 /// Who actually answers: the chosen source when it's ready, else Apple Intelligence.
254 public static func answerer(_ provider: AskProvider) -> AskProvider {
255 usesAgent(provider) ? provider : .apple
256 }
257
258 public static func usesAgent(_ provider: AskProvider) -> Bool {
259 switch provider {
260 case .apple: false
261 case .claudeCode, .codex, .gemini: installedAgents().contains(provider)
262 case .claude: Keychain.get(.claudeKey)?.isEmpty == false
263 case .openai: Keychain.get(.openAIKey)?.isEmpty == false
264 }
265 }
266
267 /// Answers often use **bold** and lists; show the emphasis instead of the asterisks.
268 public static func formatted(_ text: String) -> AttributedString {
269 (try? AttributedString(markdown: text, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace))) ?? AttributedString(text)
270 }
271
272 static func isAboutBudgets(_ question: String) -> Bool {
273 let q = question.lowercased()
274 return ["budget", "save more", "saving", "cut back", "spend less", "overspend"].contains { q.contains($0) }
275 }
276
277 /// The transactions to link under an answer. Ones the answer names (merchant and amount) come
278 /// first, even when the model answered from the summary without a lookup, then the rest it looked up.
279 static func linked(_ text: String, found: [String], ledger: Ledger, today: String = DayKey.today) -> [String] {
280 let lower = text.lowercased()
281 let recent = DayKey.adding(-120, to: today)
282 let candidates = ledger.entries.filter { e in
283 guard e.day >= recent else { return false }
284 let amount = Money.format(abs(e.amount)).lowercased()
285 guard lower.contains(amount) || lower.contains(amount.replacingOccurrences(of: ".00", with: "")) else { return false }
286 let word = e.name.lowercased().split(separator: " ").map(String.init).first { $0 != "the" } ?? ""
287 return word.count >= 3 && lower.contains(word)
288 }
289 // A repeating charge (rent every month) matches many times: keep the one whose date the answer
290 // gives, otherwise the newest.
291 let picked = Dictionary(grouping: candidates) { "\($0.name.lowercased())|\($0.amount)" }.values.compactMap { group in
292 group.first { lower.contains($0.day) } ?? group.max { $0.day < $1.day }
293 }
294 func position(_ e: LedgerEntry) -> String.Index { lower.range(of: Money.format(abs(e.amount)).lowercased())?.lowerBound ?? lower.endIndex }
295 let named = picked.sorted { position($0) < position($1) }.map(\.id)
296 var seen = Set<String>()
297 return Array((named + (named.isEmpty ? found : [])).filter { seen.insert($0).inserted }.prefix(12))
298 }
299
300 /// The transactions an offline answer is about: a category's this month, or this month's largest charges.
301 static func offlineTransactions(_ question: String, ledger: Ledger, today: String = DayKey.today) -> [String] {
302 let q = question.lowercased(), month = MonthKey.of(today)
303 let entries = ledger.entries(in: month)
304 if let category = ledger.workspace.categories.first(where: { q.contains($0.name.lowercased()) }) {
305 return entries.filter { $0.categoryID == category.id }.prefix(12).map(\.id)
306 }
307 guard !(q.contains("worth") || q.contains("subscription") || q.contains("recurring") || q.contains("bill")) else { return [] }
308 return entries.filter { $0.amount < 0 && ledger.kind($0.categoryID) == .expense }.sorted { $0.amount < $1.amount }.prefix(8).map(\.id)
309 }
310
311 /// One friendly sentence for the Overview card.
312 public static func suggestion(_ ledger: Ledger, today: String = DayKey.today) -> String? {
313 let ws = ledger.workspace
314 if let hot = ledger.budgetStatus(month: MonthKey.of(today), today: today).first(where: { $0.aheadOfPace && $0.pace < 1 }) {
315 let name = ledger.budgetName(hot.id)
316 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.")"
317 }
318 if let s = ledger.budgetSuggestions(today: today).first(where: { s in !ws.budgets.contains { $0.categoryID == s.categoryID } }) {
319 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."
320 }
321 let review = ledger.reviewQueue.count
322 if review > 0 { return "\(review) transaction\(review == 1 ? "" : "s") waiting for review. Swipe through them on your iPhone." }
323 return nil
324 }
325}