Glimmer / app · glimmertoday.ai / native / Glimmer / ToolkitAI.swift
| 1 | import Foundation |
| 2 | import FoundationModels |
| 3 | |
| 4 | /// A Toolkit answer and where it came from. |
| 5 | struct ToolkitResult<Value> { |
| 6 | let value: Value |
| 7 | let source: ToolkitSource |
| 8 | /// Set when a preferred route was unavailable, for example a disconnected writing agent. |
| 9 | var note: String? |
| 10 | } |
| 11 | |
| 12 | /// Routes each Toolkit request: the Mac's connected writing agent first, then Apple Intelligence |
| 13 | /// on this device, then Glimmer's offline guide. Text is only sent to an agent the person connected. |
| 14 | @MainActor |
| 15 | enum ToolkitAI { |
| 16 | static var offlineOnly: Bool { |
| 17 | #if DEBUG |
| 18 | let environment = ProcessInfo.processInfo.environment |
| 19 | // UI tests stay deterministic unless a test asks for the model. |
| 20 | return environment["GLIMMER_TEST_JOURNAL"] != nil && environment["GLIMMER_TEST_TOOLKIT_MODEL"] != "1" |
| 21 | #else |
| 22 | false |
| 23 | #endif |
| 24 | } |
| 25 | |
| 26 | static var hasDeviceModel: Bool { |
| 27 | guard !offlineOnly else { return false } |
| 28 | if #available(iOS 26, macOS 26, *) { return SystemLanguageModel.default.isAvailable } |
| 29 | return false |
| 30 | } |
| 31 | |
| 32 | /// The Coach agent the person chose on this Mac, when it can answer. |
| 33 | static var agentChoice: CoachAgentChoice? { |
| 34 | #if os(macOS) |
| 35 | let choice = CoachAgentChoice.current |
| 36 | guard !offlineOnly, choice.isReady else { return nil } |
| 37 | return choice |
| 38 | #else |
| 39 | nil |
| 40 | #endif |
| 41 | } |
| 42 | |
| 43 | /// One line for the Toolkit page about where suggestions are made. |
| 44 | static var routeSummary: String { |
| 45 | if let agent = agentChoice { |
| 46 | return hasDeviceModel |
| 47 | ? "Suggestions come from \(agent.agent.title), or Apple Intelligence on this Mac when it’s unavailable." |
| 48 | : "Suggestions come from \(agent.agent.title), or Glimmer’s offline guide when it’s unavailable." |
| 49 | } |
| 50 | return hasDeviceModel |
| 51 | ? "Suggestions are made on this device with Apple Intelligence. Your words stay here." |
| 52 | : "Apple Intelligence isn’t available here, so Glimmer’s offline guide makes simpler suggestions. Your words stay here." |
| 53 | } |
| 54 | |
| 55 | static var canReadTone: Bool { agentChoice != nil || hasDeviceModel } |
| 56 | |
| 57 | // MARK: Tools |
| 58 | |
| 59 | static func breakDown(_ title: String, parent: String? = nil, size: StepSize) async -> ToolkitResult<[String]> { |
| 60 | let input: [String: Any] = ["todo": title, "step": parent ?? NSNull(), "step_size": size.rawValue] |
| 61 | var prompt = "To-do: \(title)\n" |
| 62 | if let parent { prompt += "Break down only this one step of it: \(parent)\n" } |
| 63 | prompt += size.guidance |
| 64 | var note: String? |
| 65 | if let payload = await agent(.breakItDown, input: input, prompt: prompt, note: ¬e), |
| 66 | let reply = try? ToolkitReply.decode(ToolkitReply.Steps.self, from: payload) { |
| 67 | let steps = ToolkitClean.lines(reply.steps) |
| 68 | if !steps.isEmpty { return ToolkitResult(value: steps, source: .agent) } |
| 69 | } |
| 70 | if #available(iOS 26, macOS 26, *), hasDeviceModel, |
| 71 | let generated = try? await session(.breakItDown).respond(to: prompt, generating: GeneratedSteps.self).content { |
| 72 | let steps = ToolkitClean.lines(generated.steps) |
| 73 | if !steps.isEmpty { return ToolkitResult(value: steps, source: .device, note: note) } |
| 74 | } |
| 75 | return ToolkitResult(value: OfflineToolkit.breakDown(parent ?? title, size: size, isStep: parent != nil), |
| 76 | source: .guide, note: note) |
| 77 | } |
| 78 | |
| 79 | static func unload(_ text: String, today: Date) async -> ToolkitResult<[UnloadItem]> { |
| 80 | let day = CalendarDay.key(today) |
| 81 | let weekday = today.formatted(.dateTime.weekday(.wide)) |
| 82 | let input: [String: Any] = ["text": text, "today": day] |
| 83 | let prompt = "Today is \(weekday), \(day).\nBrain dump:\n\(text)" |
| 84 | var note: String? |
| 85 | if let payload = await agent(.unload, input: input, prompt: prompt, note: ¬e), |
| 86 | let reply = try? ToolkitReply.decode(ToolkitReply.Items.self, from: payload) { |
| 87 | let items = clean(reply.items) |
| 88 | if !items.isEmpty { return ToolkitResult(value: items, source: .agent) } |
| 89 | } |
| 90 | if #available(iOS 26, macOS 26, *), hasDeviceModel, |
| 91 | let generated = try? await session(.unload).respond(to: prompt, generating: GeneratedUnload.self).content { |
| 92 | // The small model is unreliable with calendar arithmetic, so Glimmer resolves the day words itself. |
| 93 | let offline = OfflineToolkit.unload(text, today: today) |
| 94 | let items = clean(generated.items.map { item in |
| 95 | let named = OfflineToolkit.extractDue(item.when, today: today).1 |
| 96 | let matched = offline.first { |
| 97 | $0.title.localizedCaseInsensitiveContains(item.title) || item.title.localizedCaseInsensitiveContains($0.title) |
| 98 | }?.dueDay |
| 99 | return UnloadItem(title: item.title, dueDay: named ?? matched) |
| 100 | }) |
| 101 | if !items.isEmpty { return ToolkitResult(value: items, source: .device, note: note) } |
| 102 | } |
| 103 | return ToolkitResult(value: OfflineToolkit.unload(text, today: today), source: .guide, note: note) |
| 104 | } |
| 105 | |
| 106 | static func estimate(_ title: String, steps: [String], focus: FocusLevel) async -> ToolkitResult<Int> { |
| 107 | let input: [String: Any] = ["todo": title, "steps": steps, "focus": focus.rawValue.lowercased()] |
| 108 | var prompt = "To-do: \(title)\nFocus today: \(focus.rawValue) (\(focus.detail.lowercased()))." |
| 109 | if !steps.isEmpty { prompt += "\nSteps:\n" + steps.map { "- " + $0 }.joined(separator: "\n") } |
| 110 | var note: String? |
| 111 | if let payload = await agent(.timeCheck, input: input, prompt: prompt, note: ¬e), |
| 112 | let reply = try? ToolkitReply.decode(ToolkitReply.Minutes.self, from: payload), reply.minutes > 0 { |
| 113 | return ToolkitResult(value: ToolkitClean.minutes(reply.minutes), source: .agent) |
| 114 | } |
| 115 | if #available(iOS 26, macOS 26, *), hasDeviceModel, |
| 116 | let generated = try? await session(.timeCheck).respond(to: prompt, generating: GeneratedMinutes.self).content, |
| 117 | generated.minutes > 0 { |
| 118 | return ToolkitResult(value: ToolkitClean.minutes(generated.minutes), source: .device, note: note) |
| 119 | } |
| 120 | return ToolkitResult(value: OfflineToolkit.estimate(title, steps: steps.count, focus: focus), source: .guide, note: note) |
| 121 | } |
| 122 | |
| 123 | /// Falls back to a rough word-pattern read when no model is available. |
| 124 | static func readTheRoom(_ text: String, received: Bool) async -> ToolkitResult<ToneReading>? { |
| 125 | let input: [String: Any] = ["text": text, "direction": received ? "received" : "sending"] |
| 126 | let prompt = (received ? "A message the person received:\n" : "A message the person plans to send:\n") + text |
| 127 | var note: String? |
| 128 | if let payload = await agent(.readTheRoom, input: input, prompt: prompt, note: ¬e), |
| 129 | let reply = try? ToolkitReply.decode(ToneReading.self, from: payload), !reply.tones.isEmpty { |
| 130 | return ToolkitResult(value: clean(reply), source: .agent) |
| 131 | } |
| 132 | if #available(iOS 26, macOS 26, *), hasDeviceModel, |
| 133 | let generated = try? await session(.readTheRoom).respond(to: prompt, generating: GeneratedReading.self).content { |
| 134 | let reading = ToneReading(tones: generated.tones.map { ToneNote(tone: $0.tone, why: $0.why) }, takeaway: generated.takeaway) |
| 135 | if !reading.tones.isEmpty { return ToolkitResult(value: clean(reading), source: .device, note: note) } |
| 136 | } |
| 137 | return OfflineToolkit.readTone(text, received: received).map { ToolkitResult(value: $0, source: .guide, note: note) } |
| 138 | } |
| 139 | |
| 140 | /// Returns nil when the tone needs a model and none is available. |
| 141 | static func reword(_ text: String, tone: RewordTone, size: StepSize) async -> ToolkitResult<String>? { |
| 142 | let input: [String: Any] = ["text": text, "tone": tone.rawValue, "strength": size.rawValue] |
| 143 | let prompt = "Tone: \(tone.rawValue). \(size.rewordStrength)\nMessage:\n\(text)" |
| 144 | var note: String? |
| 145 | if let payload = await agent(.reword, input: input, prompt: prompt, note: ¬e), |
| 146 | let reply = try? ToolkitReply.decode(ToolkitReply.Text.self, from: payload), !reply.text.isEmpty { |
| 147 | return ToolkitResult(value: String(reply.text.prefix(4_000)), source: .agent) |
| 148 | } |
| 149 | if #available(iOS 26, macOS 26, *), hasDeviceModel, |
| 150 | let generated = try? await session(.reword).respond(to: prompt, generating: GeneratedText.self).content, |
| 151 | !generated.text.isEmpty { |
| 152 | return ToolkitResult(value: String(generated.text.prefix(4_000)), source: .device, note: note) |
| 153 | } |
| 154 | return OfflineToolkit.reword(text, tone: tone).map { ToolkitResult(value: $0, source: .guide, note: note) } |
| 155 | } |
| 156 | |
| 157 | /// Returns nil without a model; the view then offers a blank pros and cons form. |
| 158 | static func weigh(_ decision: String) async -> ToolkitResult<Weighing>? { |
| 159 | let input: [String: Any] = ["decision": decision] |
| 160 | let prompt = "Decision: \(decision)" |
| 161 | var note: String? |
| 162 | if let payload = await agent(.weighIt, input: input, prompt: prompt, note: ¬e), |
| 163 | let reply = try? ToolkitReply.decode(Weighing.self, from: payload) { |
| 164 | return ToolkitResult(value: clean(reply), source: .agent) |
| 165 | } |
| 166 | if #available(iOS 26, macOS 26, *), hasDeviceModel, |
| 167 | let generated = try? await session(.weighIt).respond(to: prompt, generating: GeneratedWeighing.self).content { |
| 168 | let weighing = Weighing(pros: generated.pros, cons: generated.cons, unknowns: generated.unknowns, |
| 169 | experiment: generated.experiment) |
| 170 | return ToolkitResult(value: clean(weighing), source: .device, note: note) |
| 171 | } |
| 172 | return nil |
| 173 | } |
| 174 | |
| 175 | // MARK: Routes |
| 176 | |
| 177 | private static func agent(_ tool: ToolkitTool, input: [String: Any], prompt: String, |
| 178 | note: inout String?) async -> [String: Any]? { |
| 179 | #if os(macOS) |
| 180 | guard let choice = agentChoice else { return nil } |
| 181 | do { |
| 182 | return try await CoachAgentRoute.toolkit(choice, tool: tool, input: input, prompt: prompt) |
| 183 | } catch is CancellationError { |
| 184 | return nil |
| 185 | } catch { |
| 186 | note = "\(choice.agent.title) was unavailable." |
| 187 | return nil |
| 188 | } |
| 189 | #else |
| 190 | return nil |
| 191 | #endif |
| 192 | } |
| 193 | |
| 194 | @available(iOS 26, macOS 26, *) |
| 195 | private static func session(_ tool: ToolkitTool) -> LanguageModelSession { |
| 196 | LanguageModelSession(instructions: tool.instructions) |
| 197 | } |
| 198 | |
| 199 | private static func clean(_ items: [UnloadItem]) -> [UnloadItem] { |
| 200 | let titles = ToolkitClean.lines(items.map(\.title), limit: 30, length: PersonalTodo.titleLimit) |
| 201 | return titles.map { line in |
| 202 | let title = line.prefix(1).uppercased() + line.dropFirst() |
| 203 | let due = items.first { $0.title.localizedCaseInsensitiveContains(line) }?.dueDay.flatMap { PracticeDate.parse($0) != nil ? $0 : nil } |
| 204 | return UnloadItem(title: title, dueDay: due) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | private static func clean(_ reading: ToneReading) -> ToneReading { |
| 209 | ToneReading(tones: reading.tones.prefix(4).map { ToneNote(tone: String($0.tone.prefix(40)), why: String($0.why.prefix(300))) }, |
| 210 | takeaway: String(reading.takeaway.prefix(500))) |
| 211 | } |
| 212 | |
| 213 | private static func clean(_ weighing: Weighing) -> Weighing { |
| 214 | Weighing(pros: ToolkitClean.lines(weighing.pros, limit: 6, length: 200), |
| 215 | cons: ToolkitClean.lines(weighing.cons, limit: 6, length: 200), |
| 216 | unknowns: ToolkitClean.lines(weighing.unknowns, limit: 5, length: 200), |
| 217 | experiment: String(weighing.experiment.trimmingCharacters(in: .whitespacesAndNewlines).prefix(300))) |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | // MARK: - Guided generation |
| 222 | |
| 223 | @available(iOS 26, macOS 26, *) |
| 224 | @Generable |
| 225 | private struct GeneratedSteps { |
| 226 | @Guide(description: "Concrete steps in order. Each starts with a verb and is under 12 words.", .maximumCount(12)) |
| 227 | let steps: [String] |
| 228 | } |
| 229 | |
| 230 | @available(iOS 26, macOS 26, *) |
| 231 | @Generable |
| 232 | private struct GeneratedUnloadItem { |
| 233 | @Guide(description: "One actionable to-do that starts with a verb, under 12 words, without the day.") |
| 234 | let title: String |
| 235 | @Guide(description: "The exact day words the text uses for this item, such as tomorrow or by Friday, otherwise an empty string.") |
| 236 | let when: String |
| 237 | } |
| 238 | |
| 239 | @available(iOS 26, macOS 26, *) |
| 240 | @Generable |
| 241 | private struct GeneratedUnload { |
| 242 | @Guide(description: "Every separate action in the brain dump, in the order written.", .maximumCount(30)) |
| 243 | let items: [GeneratedUnloadItem] |
| 244 | } |
| 245 | |
| 246 | @available(iOS 26, macOS 26, *) |
| 247 | @Generable |
| 248 | private struct GeneratedMinutes { |
| 249 | @Guide(description: "Realistic whole minutes for this person today.", .range(1...600)) |
| 250 | let minutes: Int |
| 251 | } |
| 252 | |
| 253 | @available(iOS 26, macOS 26, *) |
| 254 | @Generable |
| 255 | private struct GeneratedTone { |
| 256 | @Guide(description: "One or two words, for example Warm, Rushed or Firm.") |
| 257 | let tone: String |
| 258 | @Guide(description: "A short, plain reason that points to the words causing it.") |
| 259 | let why: String |
| 260 | } |
| 261 | |
| 262 | @available(iOS 26, macOS 26, *) |
| 263 | @Generable |
| 264 | private struct GeneratedReading { |
| 265 | @Guide(description: "Two to four tones the message may carry.", .count(2...4)) |
| 266 | let tones: [GeneratedTone] |
| 267 | @Guide(description: "One or two sentences on what a neutral reader would take away.") |
| 268 | let takeaway: String |
| 269 | } |
| 270 | |
| 271 | @available(iOS 26, macOS 26, *) |
| 272 | @Generable |
| 273 | private struct GeneratedText { |
| 274 | @Guide(description: "The rewritten message only.") |
| 275 | let text: String |
| 276 | } |
| 277 | |
| 278 | @available(iOS 26, macOS 26, *) |
| 279 | @Generable |
| 280 | private struct GeneratedWeighing { |
| 281 | @Guide(description: "Short reasons for it.", .maximumCount(5)) |
| 282 | let pros: [String] |
| 283 | @Guide(description: "Short reasons against it.", .maximumCount(5)) |
| 284 | let cons: [String] |
| 285 | @Guide(description: "What the person doesn't know yet.", .maximumCount(4)) |
| 286 | let unknowns: [String] |
| 287 | @Guide(description: "One small, reversible 7-day experiment, written as an action.") |
| 288 | let experiment: String |
| 289 | } |