Glimmer / app · glimmertoday.ai / native / Glimmer / AgentAccess.swift
| 1 | #if os(macOS) |
| 2 | import CoreFoundation |
| 3 | import Foundation |
| 4 | |
| 5 | /// Glimmer's local MCP server. An agent launches the app executable with `--mcp`, which reads and |
| 6 | /// writes the journal on this Mac and never opens a window. Glimmer's Settings decides what it may do. |
| 7 | enum AgentAccess { |
| 8 | static let argument = "--mcp" |
| 9 | static let marker = "AllowAgentSummaries" |
| 10 | static let changesMarker = "AllowAgentChanges" |
| 11 | static let activityFile = "AgentActivity.json" |
| 12 | static let checkClient = "Glimmer connection check" |
| 13 | static var version: String { Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0" } |
| 14 | |
| 15 | enum Level: Equatable { |
| 16 | case off, summaries, changes |
| 17 | } |
| 18 | |
| 19 | static func level(in directory: URL) -> Level { |
| 20 | let manager = FileManager.default |
| 21 | guard manager.fileExists(atPath: directory.appending(path: marker).path) else { return .off } |
| 22 | return manager.fileExists(atPath: directory.appending(path: changesMarker).path) ? .changes : .summaries |
| 23 | } |
| 24 | |
| 25 | static let instructions = """ |
| 26 | Glimmer is a private, neurodivergent-friendly spiritual life coach for deep thinkers and anyone too busy thinking to stay organized, with daily reflections and a journal on this Mac. People log moments (an app, activity or person) with an aftertaste \ |
| 27 | from -2 (drained) to +2 (nourished), check off a daily plan, record energy and run 7-day experiments. |
| 28 | Glimmer Settings → Agent access controls this server. "Share read-only summaries" allows summaries, get_daily_glimmer and list_practices. \ |
| 29 | "Let agents log and check off" also allows get_today and the tools that change the journal. |
| 30 | For a daily dashboard, call get_daily_glimmer with no arguments on the person's chosen schedule using their Mac time zone. \ |
| 31 | Upsert the dashboard card by day_id and an external practice task by task_id. Use list_practices to choose another exercise. \ |
| 32 | If the person wants it on their plan, call save_practice with the practice_id and day. After the person confirms they did it, \ |
| 33 | call set_task_done with that task_id, the same day, and done=true. A read never marks the task complete. Scheduling belongs to the client. \ |
| 34 | For personal to-dos use list_personal_todos, add_personal_todo and set_personal_todo_done. These are separate from the coaching plan. \ |
| 35 | A to-do can carry small steps (with one level of smaller steps) and a time estimate in minutes. Pass steps and estimate_minutes to add_personal_todo, \ |
| 36 | or replace a to-do's steps later with set_todo_steps. Keep each step short and start it with a verb. \ |
| 37 | Only set a reminder time when requested. Glimmer schedules device-local reminders after it reads the saved task, if notifications are allowed on that device. \ |
| 38 | For other plan tasks call get_today first and use the IDs it returns. Log a moment only when the person \ |
| 39 | describes it or asks you to, using their own rating. Summaries describe self-reported patterns; they are not medical advice. |
| 40 | Setup: Claude Code uses Glimmer's Save Project Connection in Settings → Agent access, Codex uses a STDIO server with the \ |
| 41 | command and argument Glimmer shows, Gemini CLI uses a project .gemini/settings.json, and Claude chat uses the Glimmer.mcpb extension saved from the same place. |
| 42 | """ |
| 43 | |
| 44 | @MainActor |
| 45 | static func run() { |
| 46 | let bundled = AppResources.url("Catalog", extension: "json").flatMap { try? Catalog.load(from: $0) } |
| 47 | let content = bundled.map { EditorialLibrary(bundled: $0) } |
| 48 | let session = Session(journal: JournalStore.storageURL, catalog: content?.edition?.content ?? bundled) |
| 49 | while let line = readLine() { |
| 50 | guard let response = session.handle(line) else { continue } |
| 51 | send(response) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | private static func send(_ response: [String: Any]) { |
| 56 | guard let data = try? JSONSerialization.data(withJSONObject: response) else { return } |
| 57 | FileHandle.standardOutput.write(data + Data([10])) |
| 58 | } |
| 59 | |
| 60 | @MainActor |
| 61 | final class Session { |
| 62 | private let journal: URL |
| 63 | private let catalog: Catalog? |
| 64 | private var initialized = false |
| 65 | private var client = "An agent" |
| 66 | |
| 67 | init(journal: URL, catalog: Catalog? = AppResources.url("Catalog", extension: "json").flatMap { try? Catalog.load(from: $0) }) { |
| 68 | self.journal = journal |
| 69 | self.catalog = catalog |
| 70 | } |
| 71 | |
| 72 | private var directory: URL { journal.deletingLastPathComponent() } |
| 73 | |
| 74 | /// Answers one JSON-RPC line. Notifications get no answer. |
| 75 | func handle(_ line: String) -> [String: Any]? { |
| 76 | guard let data = line.data(using: .utf8), |
| 77 | let request = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { |
| 78 | return error(NSNull(), -32700, "Invalid JSON") |
| 79 | } |
| 80 | guard request["jsonrpc"] as? String == "2.0", let method = request["method"] as? String else { |
| 81 | return error(request["id"] ?? NSNull(), -32600, "Invalid Request") |
| 82 | } |
| 83 | guard let id = request["id"] else { return nil } |
| 84 | let params = request["params"] as? [String: Any] ?? [:] |
| 85 | switch method { |
| 86 | case "initialize": |
| 87 | let supported = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] |
| 88 | let requested = params["protocolVersion"] as? String ?? "" |
| 89 | if let info = params["clientInfo"] as? [String: Any], let name = info["name"] as? String, !name.isEmpty { |
| 90 | client = String(String.UnicodeScalarView(name.unicodeScalars.filter { !CharacterSet.controlCharacters.contains($0) }).prefix(80)) |
| 91 | } |
| 92 | initialized = true |
| 93 | if client != AgentAccess.checkClient { recordActivity(tool: nil) } |
| 94 | return result(id, [ |
| 95 | "protocolVersion": supported.contains(requested) ? requested : supported[0], |
| 96 | "capabilities": ["tools": [:]], |
| 97 | "serverInfo": ["name": "glimmer", "title": "Glimmer", "version": AgentAccess.version], |
| 98 | "instructions": AgentAccess.instructions |
| 99 | ]) |
| 100 | case "ping": |
| 101 | return result(id, [:]) |
| 102 | case "tools/list" where initialized: |
| 103 | return result(id, ["tools": AgentAccess.tools]) |
| 104 | case "tools/call" where initialized: |
| 105 | return result(id, call(params)) |
| 106 | default: |
| 107 | return error(id, -32601, "Method not available") |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | private func call(_ params: [String: Any]) -> [String: Any] { |
| 112 | guard let name = params["name"] as? String, let tool = Tool(rawValue: name) else { |
| 113 | return failure("Unknown Glimmer tool.") |
| 114 | } |
| 115 | guard let arguments = (params["arguments"] ?? [:]) as? [String: Any] else { |
| 116 | return failure("Provide a JSON object for tool arguments.") |
| 117 | } |
| 118 | let level = AgentAccess.level(in: directory) |
| 119 | guard level != .off else { |
| 120 | return failure("Agent access is off. Open Glimmer → Settings → Agent access and turn on Share read-only summaries.") |
| 121 | } |
| 122 | guard !tool.needsChanges || level == .changes else { |
| 123 | return failure("This needs Glimmer → Settings → Agent access → Let agents log and check off. Ask the person to turn it on.") |
| 124 | } |
| 125 | let store = JournalStore(url: journal, catalogURL: nil) |
| 126 | guard store.loadError == nil, store.journal.onboardingComplete else { |
| 127 | return failure("Finish Glimmer setup on this Mac first.") |
| 128 | } |
| 129 | let outcome = run(tool, arguments, store: store) |
| 130 | if outcome["isError"] == nil && client != AgentAccess.checkClient { recordActivity(tool: name) } |
| 131 | return outcome |
| 132 | } |
| 133 | |
| 134 | private func run(_ tool: Tool, _ arguments: [String: Any], store: JournalStore) -> [String: Any] { |
| 135 | let now = Date() |
| 136 | store.day = now |
| 137 | switch tool { |
| 138 | case .attention: |
| 139 | guard Set(arguments.keys).isSubset(of: ["days"]), let days = integer(arguments["days"] ?? 7), (1...30).contains(days) else { |
| 140 | return failure("Provide a whole number of days between 1 and 30.") |
| 141 | } |
| 142 | return AgentAccess.attentionSummary(store.journal, days: days, now: now) |
| 143 | case .plan: |
| 144 | guard arguments.isEmpty else { return failure("This tool does not accept arguments.") } |
| 145 | return AgentAccess.planSummary(store.journal, now: now) |
| 146 | case .daily: |
| 147 | guard arguments.isEmpty else { return failure("This tool does not accept arguments.") } |
| 148 | guard let catalog, let selected = catalog.dailyPractice(on: now, level: store.journal.guidanceLevel(asOf: now)), |
| 149 | let lesson = catalog.dailyLesson(for: store.journal, on: now) else { return failure("The coaching catalog is unavailable.") } |
| 150 | let day = PracticeDate.key(now) |
| 151 | let practice = datedPracticeFields(selected.practice, in: selected.topic, on: now, journal: store.journal) |
| 152 | let takeaway = lesson.pages.first(where: { $0.kind == "takeaway" })?.tryToday ?? lesson.tagline |
| 153 | var result: [String: Any] = ["day": day, "day_id": "glimmer:daily:\(day)", "time_zone": TimeZone.current.identifier, |
| 154 | "source": ["author": CoachingSource.author, "role": CoachingSource.role, "credit": CoachingSource.credit, "note": CoachingSource.note, "url": CoachingSource.sourcesURL.absoluteString], |
| 155 | "lesson": ["lesson_id": lesson.slug, "title": lesson.title, "takeaway": takeaway], "practice": practice] |
| 156 | if let topic = catalog.reflectionTopic, let reflection = catalog.dailyReflection(on: now, level: store.journal.guidanceLevel(asOf: now)) { |
| 157 | result["reflection"] = datedPracticeFields(reflection, in: topic, on: now, journal: store.journal) |
| 158 | } |
| 159 | return AgentAccess.success(result) |
| 160 | case .practices: |
| 161 | guard Set(arguments.keys).isSubset(of: ["topic_id"]), let catalog else { return failure("Provide an optional topic_id.") } |
| 162 | let topics: [PracticeTopic] |
| 163 | if let requested = arguments["topic_id"] { |
| 164 | guard let id = requested as? String, let topic = catalog.practiceTopics.first(where: { $0.id == id }) else { |
| 165 | return failure("Unknown topic_id. Call list_practices without arguments to see available topics.") |
| 166 | } |
| 167 | topics = [topic] |
| 168 | } else { topics = catalog.practiceTopics } |
| 169 | return AgentAccess.success(["practices": topics.flatMap { topic in topic.exercises.map { practiceFields($0, in: topic) } }]) |
| 170 | case .savePractice: |
| 171 | guard Set(arguments.keys) == ["day", "practice_id"], let day = arguments["day"] as? String, |
| 172 | let date = PracticeDate.parse(day), let practiceID = arguments["practice_id"] as? String, |
| 173 | let practice = catalog?.practiceTopics.lazy.flatMap(\.exercises).first(where: { $0.id == practiceID }) else { |
| 174 | return failure("Provide a valid day (YYYY-MM-DD) and a practice_id from get_daily_glimmer or list_practices.") |
| 175 | } |
| 176 | let task = practice.task(on: date) |
| 177 | var added = false |
| 178 | guard store.change({ journal in |
| 179 | guard !journal.tasks.contains(where: { $0.id == task.id }) else { return } |
| 180 | journal.tasks.append(task) |
| 181 | added = true |
| 182 | }) else { return failure("Glimmer couldn’t save the practice.") } |
| 183 | return AgentAccess.success(["practice_id": practice.id, "task_id": task.id, "day": day, "added": added, |
| 184 | "done": store.journal.completions[CalendarDay.key(date)]?.contains(task.id) == true]) |
| 185 | case .today: |
| 186 | guard arguments.isEmpty else { return failure("This tool does not accept arguments.") } |
| 187 | return today(store.journal, now: now) |
| 188 | case .logMoment: |
| 189 | return logMoment(arguments, store: store, now: now) |
| 190 | case .addTask: |
| 191 | return addTask(arguments, store: store, now: now) |
| 192 | case .personalTodos: |
| 193 | let filter = arguments["filter"] as? String ?? "open" |
| 194 | guard Set(arguments.keys).isSubset(of: ["filter"]), |
| 195 | arguments["filter"] == nil || arguments["filter"] is String, |
| 196 | ["open", "due", "completed", "all"].contains(filter) else { |
| 197 | return failure("Use an optional filter of open, due, completed or all.") |
| 198 | } |
| 199 | let day = PracticeDate.key(now) |
| 200 | let todos = PersonalTodo.ordered((store.journal.personalTodos ?? []).filter { task in |
| 201 | filter == "all" || (filter == "open" && !task.completed) || |
| 202 | (filter == "due" && task.isDue(by: day)) || (filter == "completed" && task.completed) |
| 203 | }) |
| 204 | return AgentAccess.success(["day": day, "time_zone": TimeZone.current.identifier, |
| 205 | "todos": todos.map { personalTodoFields($0, journal: store.journal) }]) |
| 206 | case .addPersonalTodo: |
| 207 | return addPersonalTodo(arguments, store: store, now: now) |
| 208 | case .setPersonalTodo: |
| 209 | guard Set(arguments.keys) == ["task_id", "done"], |
| 210 | let id = (arguments["task_id"] as? String).flatMap(UUID.init(uuidString:)), |
| 211 | let done = boolean(arguments["done"]) else { |
| 212 | return failure("Provide task_id and done (true or false).") |
| 213 | } |
| 214 | guard store.setPersonalTodoDone(id, done: done), |
| 215 | let task = store.journal.personalTodos?.first(where: { $0.id == id }) else { |
| 216 | return failure("Glimmer couldn’t update that personal to-do. Verify the ID with list_personal_todos.") |
| 217 | } |
| 218 | return AgentAccess.success(personalTodoFields(task, journal: store.journal)) |
| 219 | case .setTodoSteps: |
| 220 | return setTodoSteps(arguments, store: store) |
| 221 | case .setTask: |
| 222 | guard Set(arguments.keys).isSubset(of: ["task_id", "done", "day"]), let id = arguments["task_id"] as? String, |
| 223 | let done = arguments["done"] == nil ? true : boolean(arguments["done"]) else { |
| 224 | return failure("Provide task_id and optionally done (true or false) and day (YYYY-MM-DD).") |
| 225 | } |
| 226 | let date: Date |
| 227 | if let raw = arguments["day"] { |
| 228 | guard let day = raw as? String, let parsed = PracticeDate.parse(day), day <= PracticeDate.key(now) else { |
| 229 | return failure("Provide today’s date or a past date in YYYY-MM-DD format.") |
| 230 | } |
| 231 | date = parsed |
| 232 | } else { date = now } |
| 233 | let day = CalendarDay.key(date) |
| 234 | var updatedTask: PlanTask? |
| 235 | guard store.change({ journal in |
| 236 | guard let task = journal.tasks.first(where: { $0.id == id && $0.occurs(on: date) }) else { return } |
| 237 | updatedTask = task |
| 238 | if (journal.completions[day]?.contains(id) == true) != done { journal.toggleTask(task, on: date) } |
| 239 | }) else { return failure("Glimmer couldn’t save this change.") } |
| 240 | guard let task = updatedTask else { return failure("No task with that ID is scheduled on the requested day.") } |
| 241 | return AgentAccess.success(["task_id": task.id, "task": task.name, "day": PracticeDate.key(date), "done": done, "coins": store.journal.coins]) |
| 242 | case .energy: |
| 243 | guard Set(arguments.keys) == ["level"], let id = arguments["level"] as? String, |
| 244 | let levels = catalog?.energy, let index = levels.firstIndex(where: { $0.id == id }) else { |
| 245 | return failure("Provide level: one of empty, low, mid, high or full.") |
| 246 | } |
| 247 | let value = Double(index) / Double(max(1, levels.count - 1)) |
| 248 | guard store.change({ $0.recordEnergy(.init(level: id, value: value), on: now) }) else { |
| 249 | return failure("Glimmer couldn't save this change.") |
| 250 | } |
| 251 | return AgentAccess.success(["day": CalendarDay.key(now), "energy": levels[index].label]) |
| 252 | case .checkIn: |
| 253 | guard Set(arguments.keys) == ["outcome"], let raw = arguments["outcome"] as? String, |
| 254 | let outcome = ["held": Experiment.Outcome.held, "slipped": .slip][raw] else { |
| 255 | return failure("Provide outcome: held or slipped.") |
| 256 | } |
| 257 | guard let active = store.journal.experiment else { return failure("There is no experiment running.") } |
| 258 | let day = CalendarDay.key(now) |
| 259 | if let existing = active.checkins[day] { |
| 260 | return failure("Today's check-in is already recorded as \(existing.rawValue.lowercased()).") |
| 261 | } |
| 262 | guard !active.readyToReview else { return failure("This experiment is finished. The person reviews it in Glimmer.") } |
| 263 | guard store.change({ $0.checkIn(outcome, on: now) }), store.journal.experiment?.checkins[day] != nil else { |
| 264 | return failure("Glimmer couldn't record this check-in.") |
| 265 | } |
| 266 | let checkins = store.journal.experiment?.checkins.count ?? 0 |
| 267 | return AgentAccess.success(["experiment": active.suggestion.title, "outcome": outcome.rawValue, |
| 268 | "checkIns": checkins, "readyToReview": checkins >= active.duration]) |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | private func datedPracticeFields(_ practice: Practice, in topic: PracticeTopic, on date: Date, journal: Journal) -> [String: Any] { |
| 273 | let id = practice.taskID(day: PracticeDate.key(date)) |
| 274 | var result = practiceFields(practice, in: topic) |
| 275 | result["task_id"] = id |
| 276 | result["saved"] = journal.tasks.contains { $0.id == id } |
| 277 | result["done"] = journal.completions[CalendarDay.key(date)]?.contains(id) == true |
| 278 | return result |
| 279 | } |
| 280 | |
| 281 | private func practiceFields(_ practice: Practice, in topic: PracticeTopic) -> [String: Any] { |
| 282 | ["practice_id": practice.id, "topic_id": topic.id, "topic": topic.title, "title": practice.title, "instruction": practice.sub, |
| 283 | "stage": practice.stage, "stage_name": JourneyStage.name(practice.stage)] |
| 284 | } |
| 285 | |
| 286 | private func today(_ journal: Journal, now: Date) -> [String: Any] { |
| 287 | let day = CalendarDay.key(now) |
| 288 | let done = journal.completions[day] ?? [] |
| 289 | let tasks: [[String: Any]] = journal.tasks.filter { $0.occurs(on: now) }.map { |
| 290 | ["id": $0.id, "name": $0.name, "icon": $0.icon, "done": done.contains($0.id)] |
| 291 | } |
| 292 | var experiment: Any = NSNull() |
| 293 | if let active = journal.experiment { |
| 294 | experiment = ["title": active.suggestion.title, "detail": active.suggestion.sub, |
| 295 | "checkIns": active.checkins.count, "checkedInToday": active.checkins[day] != nil, |
| 296 | "readyToReview": active.readyToReview] as [String: Any] |
| 297 | } |
| 298 | let energy: Any = journal.energy[day].map { $0.level } ?? NSNull() |
| 299 | return AgentAccess.success([ |
| 300 | "day": day, |
| 301 | "tasks": tasks, |
| 302 | "energy": energy, |
| 303 | "momentsLoggedToday": journal.moments.filter { $0.day == day }.count, |
| 304 | "favoriteSources": journal.favoriteSources ?? [], |
| 305 | "experiment": experiment |
| 306 | ]) |
| 307 | } |
| 308 | |
| 309 | private func logMoment(_ arguments: [String: Any], store: JournalStore, now: Date) -> [String: Any] { |
| 310 | let source = (arguments["source"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) |
| 311 | guard Set(arguments.keys).isSubset(of: ["source", "aftertaste", "decision", "tags", "day"]), |
| 312 | (1...60).contains(source.count), |
| 313 | let aftertaste = integer(arguments["aftertaste"]), (-2...2).contains(aftertaste) else { |
| 314 | return failure("Provide source (what the moment was about) and aftertaste, a whole number from -2 (drained) to 2 (nourished).") |
| 315 | } |
| 316 | let decision = (arguments["decision"] as? String).flatMap(Decision.init(rawValue:)) |
| 317 | guard arguments["decision"] == nil || decision != nil else { return failure("decision must be less, same or more.") } |
| 318 | let tags = arguments["tags"] as? [String] ?? [] |
| 319 | guard arguments["tags"] == nil || (arguments["tags"] is [String] && tags.count <= 5 && tags.allSatisfy { (1...40).contains($0.count) }) else { |
| 320 | return failure("tags must be up to five short words.") |
| 321 | } |
| 322 | let date: Date |
| 323 | if let supplied = arguments["day"] { |
| 324 | guard let day = supplied as? String, let parsed = PracticeDate.parse(day), day <= PracticeDate.key(now) else { |
| 325 | return failure("Use today or a past date in YYYY-MM-DD format.") |
| 326 | } |
| 327 | date = day == PracticeDate.key(now) ? now : parsed |
| 328 | } else { date = now } |
| 329 | let name = matchingSource(source, journal: store.journal) |
| 330 | let kind = catalog.map { Moment.kind(of: name, catalog: $0) } ?? "Feed" |
| 331 | let moment = Moment(source: name, kind: kind, tags: tags, value: Double(aftertaste + 2) / 4, |
| 332 | decision: decision ?? .same, date: date, day: CalendarDay.key(date)) |
| 333 | guard store.change({ $0.record(moment) }) else { return failure("Glimmer couldn't save this moment.") } |
| 334 | return AgentAccess.success(["logged": name, "day": moment.day, "category": kind, "aftertaste": moment.word, |
| 335 | "decision": moment.decision.title, "momentsLoggedToday": store.todayLogs.count]) |
| 336 | } |
| 337 | |
| 338 | /// Adds a one-time task to today's or tomorrow's plan. The same name on the same day is not added twice. |
| 339 | private func addTask(_ arguments: [String: Any], store: JournalStore, now: Date) -> [String: Any] { |
| 340 | let name = (arguments["name"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) |
| 341 | let icon = (arguments["icon"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines) |
| 342 | let dayName = arguments["day"] as? String ?? "today" |
| 343 | guard Set(arguments.keys).isSubset(of: ["name", "day", "icon"]), (1...60).contains(name.count), |
| 344 | arguments["icon"] == nil || (1...60).contains(icon.count) else { |
| 345 | return failure("Provide name (up to 60 characters), optionally day (today or tomorrow) and icon (one emoji).") |
| 346 | } |
| 347 | guard let offset = ["today": 0, "tomorrow": 1][dayName], |
| 348 | let date = Calendar.current.date(byAdding: .day, value: offset, to: Calendar.current.startOfDay(for: now)) else { |
| 349 | return failure("day must be today or tomorrow.") |
| 350 | } |
| 351 | let day = CalendarDay.key(date) |
| 352 | if let existing = store.journal.tasks.first(where: { |
| 353 | $0.occurs(on: date) && $0.name.localizedCaseInsensitiveCompare(name) == .orderedSame |
| 354 | }) { |
| 355 | return AgentAccess.success(["task_id": existing.id, "name": existing.name, "day": day, "added": false]) |
| 356 | } |
| 357 | var task = PlanTask() |
| 358 | task.name = name |
| 359 | if !icon.isEmpty { task.icon = icon } |
| 360 | task.anchor = date |
| 361 | task.repeats = false |
| 362 | guard store.change({ $0.tasks.append(task) }) else { return failure("Glimmer couldn't save this task.") } |
| 363 | return AgentAccess.success(["task_id": task.id, "name": name, "day": day, "added": true]) |
| 364 | } |
| 365 | |
| 366 | private func personalTodoFields(_ task: PersonalTodo, journal: Journal) -> [String: Any] { |
| 367 | var fields: [String: Any] = ["task_id": task.id.uuidString, "title": task.title, "done": task.completed] |
| 368 | fields["due_day"] = task.dueDay |
| 369 | fields["reminder_at"] = task.reminderAt.map { ISO8601DateFormatter().string(from: $0) } |
| 370 | let steps = journal.steps(for: task.id) |
| 371 | if !steps.isEmpty { |
| 372 | fields["steps"] = steps.map { step -> [String: Any] in |
| 373 | var fields = stepFields(step) |
| 374 | let smaller = journal.steps(for: task.id, parent: step.id) |
| 375 | if !smaller.isEmpty { fields["steps"] = smaller.map(stepFields) } |
| 376 | return fields |
| 377 | } |
| 378 | } |
| 379 | if let estimate = journal.estimate(for: task.id) { |
| 380 | fields["estimate_minutes"] = estimate.minutes |
| 381 | fields["estimate_source"] = estimate.source |
| 382 | } |
| 383 | return fields |
| 384 | } |
| 385 | |
| 386 | private func stepFields(_ step: TodoStep) -> [String: Any] { |
| 387 | ["step_id": step.id.uuidString, "title": step.title, "done": step.done] |
| 388 | } |
| 389 | |
| 390 | /// Reads an optional list of step titles. Returns nil when the value is invalid. |
| 391 | private func stepTitles(_ value: Any?) -> [String]?? { |
| 392 | guard let value else { return .some(nil) } |
| 393 | guard let raw = value as? [Any], raw.count <= 12 else { return nil } |
| 394 | let titles = raw.compactMap { ($0 as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) } |
| 395 | guard titles.count == raw.count, titles.allSatisfy({ (1...TodoStep.titleLimit).contains($0.count) }) else { return nil } |
| 396 | return .some(titles) |
| 397 | } |
| 398 | |
| 399 | private func setTodoSteps(_ arguments: [String: Any], store: JournalStore) -> [String: Any] { |
| 400 | guard Set(arguments.keys).isSubset(of: ["task_id", "steps", "parent_step_id"]), |
| 401 | let id = (arguments["task_id"] as? String).flatMap(UUID.init(uuidString:)), |
| 402 | case .some(.some(let titles)) = stepTitles(arguments["steps"]) else { |
| 403 | return failure("Provide task_id and steps (0–12 titles of 1–160 characters), and optionally parent_step_id.") |
| 404 | } |
| 405 | let parent = (arguments["parent_step_id"] as? String).flatMap(UUID.init(uuidString:)) |
| 406 | guard arguments["parent_step_id"] == nil || parent != nil else { return failure("parent_step_id must be a step_id UUID.") } |
| 407 | guard let task = store.journal.personalTodos?.first(where: { $0.id == id }) else { |
| 408 | return failure("No personal to-do has that task_id. Verify it with list_personal_todos.") |
| 409 | } |
| 410 | if let parent { |
| 411 | guard let step = store.journal.todoSteps?.first(where: { $0.id == parent && $0.todoID == id }), step.parentID == nil else { |
| 412 | return failure("parent_step_id must be a top-level step of this to-do. Steps go two levels deep.") |
| 413 | } |
| 414 | } |
| 415 | guard store.change({ $0.replaceSteps(for: id, parent: parent, with: titles) }) else { |
| 416 | return failure("Glimmer couldn’t save these steps.") |
| 417 | } |
| 418 | return AgentAccess.success(personalTodoFields(task, journal: store.journal)) |
| 419 | } |
| 420 | |
| 421 | private func addPersonalTodo(_ arguments: [String: Any], store: JournalStore, now: Date) -> [String: Any] { |
| 422 | guard Set(arguments.keys).isSubset(of: ["title", "due_day", "reminder_at", "request_id", "steps", "estimate_minutes"]), |
| 423 | let title = (arguments["title"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 424 | (1...PersonalTodo.titleLimit).contains(title.count) else { |
| 425 | return failure("Provide a title of 1–160 characters and optional due_day, reminder_at, request_id, steps and estimate_minutes.") |
| 426 | } |
| 427 | guard case .some(let steps) = stepTitles(arguments["steps"]) else { |
| 428 | return failure("steps must be a list of up to 12 short titles, each 1–160 characters.") |
| 429 | } |
| 430 | let minutes = integer(arguments["estimate_minutes"]) |
| 431 | guard arguments["estimate_minutes"] == nil || minutes.map({ (1...1440).contains($0) }) == true else { |
| 432 | return failure("estimate_minutes must be a whole number from 1 to 1440.") |
| 433 | } |
| 434 | let dueDay = arguments["due_day"] as? String |
| 435 | guard arguments["due_day"] == nil || dueDay.flatMap(PracticeDate.parse) != nil else { |
| 436 | return failure("due_day must be a valid local date in YYYY-MM-DD format.") |
| 437 | } |
| 438 | let requestedID = (arguments["request_id"] as? String).flatMap(UUID.init(uuidString:)) |
| 439 | guard arguments["request_id"] == nil || requestedID != nil else { |
| 440 | return failure("request_id must be a UUID. Reuse it for retries.") |
| 441 | } |
| 442 | if let existing = store.journal.personalTodos?.first(where: { $0.id == requestedID }) { |
| 443 | return personalTodoResult(existing, added: false, journal: store.journal) |
| 444 | } |
| 445 | let reminderAt = (arguments["reminder_at"] as? String).flatMap { raw -> Date? in |
| 446 | let formatter = ISO8601DateFormatter() |
| 447 | if let date = formatter.date(from: raw) { return date } |
| 448 | formatter.formatOptions.insert(.withFractionalSeconds) |
| 449 | return formatter.date(from: raw) |
| 450 | } |
| 451 | guard arguments["reminder_at"] == nil || reminderAt.map({ $0 > now }) == true else { |
| 452 | return failure("reminder_at must be a future ISO 8601 timestamp with a UTC offset or Z.") |
| 453 | } |
| 454 | var task = PersonalTodo(id: requestedID ?? UUID(), title: title, dueDay: dueDay, reminderAt: reminderAt) |
| 455 | var added = false |
| 456 | guard store.change({ journal in |
| 457 | // Check again under the write lock for parallel retries from multiple clients. |
| 458 | var todos = journal.personalTodos ?? [] |
| 459 | if let existing = todos.first(where: { $0.id == task.id }) { |
| 460 | task = existing |
| 461 | } else { |
| 462 | todos.append(task) |
| 463 | journal.personalTodos = todos |
| 464 | if let steps { journal.replaceSteps(for: task.id, with: steps) } |
| 465 | if let minutes { journal.setEstimate(minutes, source: ToolkitSource.agent.rawValue, for: task.id) } |
| 466 | added = true |
| 467 | } |
| 468 | }) else { return failure("Glimmer couldn’t save this personal to-do.") } |
| 469 | return personalTodoResult(task, added: added, journal: store.journal) |
| 470 | } |
| 471 | |
| 472 | private func personalTodoResult(_ task: PersonalTodo, added: Bool, journal: Journal) -> [String: Any] { |
| 473 | var fields = personalTodoFields(task, journal: journal) |
| 474 | fields["added"] = added |
| 475 | if task.reminderAt != nil { |
| 476 | fields["reminder_delivery"] = "Glimmer schedules this locally when the app reads the task on a device with notifications enabled." |
| 477 | } |
| 478 | return AgentAccess.success(fields) |
| 479 | } |
| 480 | |
| 481 | /// Uses the journal's own spelling (and emoji) when the name matches a source Glimmer already knows. |
| 482 | private func matchingSource(_ source: String, journal: Journal) -> String { |
| 483 | let known = (journal.favoriteSources ?? []) + journal.customSources + (catalog?.activities ?? []) + (catalog?.people ?? []) |
| 484 | func plain(_ text: String) -> String { |
| 485 | let kept = text.unicodeScalars.drop { !CharacterSet.alphanumerics.contains($0) } |
| 486 | return String(String.UnicodeScalarView(kept)).trimmingCharacters(in: .whitespaces).lowercased() |
| 487 | } |
| 488 | return known.first { plain($0) == plain(source) } ?? source |
| 489 | } |
| 490 | |
| 491 | private func integer(_ value: Any?) -> Int? { |
| 492 | guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), |
| 493 | number.doubleValue.rounded() == number.doubleValue else { return nil } |
| 494 | return number.intValue |
| 495 | } |
| 496 | |
| 497 | private func boolean(_ value: Any?) -> Bool? { |
| 498 | guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { return nil } |
| 499 | return number.boolValue |
| 500 | } |
| 501 | |
| 502 | private func recordActivity(tool: String?) { |
| 503 | var activity = AgentActivity.read(in: directory) ?? AgentActivity() |
| 504 | activity.client = client |
| 505 | activity.clientDate = Date() |
| 506 | if let tool { |
| 507 | activity.tool = tool |
| 508 | activity.toolDate = Date() |
| 509 | } |
| 510 | activity.write(in: directory) |
| 511 | } |
| 512 | |
| 513 | private func result(_ id: Any, _ result: [String: Any]) -> [String: Any] { |
| 514 | ["jsonrpc": "2.0", "id": id, "result": result] |
| 515 | } |
| 516 | |
| 517 | private func error(_ id: Any, _ code: Int, _ message: String) -> [String: Any] { |
| 518 | ["jsonrpc": "2.0", "id": id, "error": ["code": code, "message": message]] |
| 519 | } |
| 520 | |
| 521 | private func failure(_ message: String) -> [String: Any] { AgentAccess.failure(message) } |
| 522 | } |
| 523 | |
| 524 | private enum Tool: String { |
| 525 | case attention = "get_attention_summary", plan = "get_plan_summary", today = "get_today" |
| 526 | case daily = "get_daily_glimmer", practices = "list_practices", savePractice = "save_practice" |
| 527 | case logMoment = "log_moment", addTask = "add_plan_task", setTask = "set_task_done", energy = "record_energy", checkIn = "check_in_experiment" |
| 528 | case personalTodos = "list_personal_todos", addPersonalTodo = "add_personal_todo", setPersonalTodo = "set_personal_todo_done" |
| 529 | case setTodoSteps = "set_todo_steps" |
| 530 | |
| 531 | var needsChanges: Bool { ![.attention, .plan, .daily, .practices].contains(self) } |
| 532 | } |
| 533 | |
| 534 | static var tools: [[String: Any]] { |
| 535 | func tool(_ name: String, _ title: String, _ description: String, _ properties: [String: Any] = [:], |
| 536 | required: [String] = [], readOnly: Bool, idempotent: Bool = true) -> [String: Any] { |
| 537 | var schema: [String: Any] = ["type": "object", "properties": properties, "additionalProperties": false] |
| 538 | if !required.isEmpty { schema["required"] = required } |
| 539 | return ["name": name, "title": title, "description": description, "inputSchema": schema, |
| 540 | "annotations": ["title": title, "readOnlyHint": readOnly, "destructiveHint": false, |
| 541 | "idempotentHint": idempotent, "openWorldHint": false]] |
| 542 | } |
| 543 | let changes = " Requires Let agents log and check off in Glimmer's Agent access settings." |
| 544 | return [ |
| 545 | tool("get_attention_summary", "Attention summary", |
| 546 | "Read an aggregate of self-reported aftertaste from the last 1–30 calendar days, grouped by general activity category. Individual entries, source names and timestamps are excluded. Patterns are descriptive, not medical conclusions.", |
| 547 | ["days": ["type": "integer", "minimum": 1, "maximum": 30, "description": "Days to include, today counting as one. Default 7."]], |
| 548 | readOnly: true), |
| 549 | tool("get_plan_summary", "Plan summary", |
| 550 | "Read counts of scheduled and completed tasks for today, today's energy and progress on the current experiment. Excludes task titles and journal entries.", |
| 551 | readOnly: true), |
| 552 | tool("get_daily_glimmer", "Daily Glimmer", |
| 553 | "Read today’s public coaching lesson, practice and a quiet reflection with stable day_id and task_id, local time zone, and saved/done flags. Excludes private journal text, custom task names and onboarding answers. Upsert by these IDs in your own dashboard.", readOnly: true), |
| 554 | tool("list_practices", "Coaching practices", "Browse the editorial practice catalog. Without topic_id this returns every available topic and practice.", |
| 555 | ["topic_id": ["type": "string"]], readOnly: true), |
| 556 | tool("save_practice", "Save a practice to the plan", "Add a catalog exercise as one dated plan task. Repeating the same day and practice returns the same task_id." + changes, |
| 557 | ["practice_id": ["type": "string"], "day": ["type": "string", "format": "date"]], required: ["practice_id", "day"], readOnly: false), |
| 558 | tool("get_today", "Today in Glimmer", |
| 559 | "Read today's plan with task IDs, names and whether each is done, today's energy, how many moments were logged, favourite sources and the running experiment." + changes, |
| 560 | readOnly: true), |
| 561 | tool("log_moment", "Log a moment", |
| 562 | "Record a moment the person describes: what it was about and how it left them feeling." + changes, |
| 563 | ["source": ["type": "string", "minLength": 1, "maxLength": 60, "description": "The app, activity or person, such as Instagram, Walk or Called a friend."], |
| 564 | "aftertaste": ["type": "integer", "minimum": -2, "maximum": 2, "description": "-2 drained, -1 off, 0 neutral, 1 lighter, 2 nourished."], |
| 565 | "day": ["type": "string", "format": "date", "description": "Optional local date for a past moment. Defaults to today."], |
| 566 | "decision": ["type": "string", "enum": ["less", "same", "more"], "description": "Whether they want less, the same or more of it. Default same."], |
| 567 | "tags": ["type": "array", "items": ["type": "string", "maxLength": 40], "maxItems": 5, "description": "Optional short words, such as Bored or Before bed."]], |
| 568 | required: ["source", "aftertaste"], readOnly: false, idempotent: false), |
| 569 | tool("add_plan_task", "Add a plan task", |
| 570 | "Add a one-time task to today's or tomorrow's plan, such as a goal the person wants to get done. A task with the same name on that day is not added twice." + changes, |
| 571 | ["name": ["type": "string", "minLength": 1, "maxLength": 60, "description": "What to do, in a few words."], |
| 572 | "day": ["type": "string", "enum": ["today", "tomorrow"], "description": "Default today."], |
| 573 | "icon": ["type": "string", "maxLength": 60, "description": "Optional SF Symbol name, such as drop.fill. Glimmer picks one from the name when it is left out."]], |
| 574 | required: ["name"], readOnly: false), |
| 575 | tool("set_task_done", "Check off a task", |
| 576 | "Set a task’s completion explicitly. Omit day for today. Use the original day and task_id when writing back a saved practice, including after midnight." + changes, |
| 577 | ["task_id": ["type": "string"], "day": ["type": "string", "format": "date"], "done": ["type": "boolean", "description": "Default true."]], |
| 578 | required: ["task_id"], readOnly: false), |
| 579 | tool("list_personal_todos", "Personal to-dos", |
| 580 | "Read personal to-dos with stable IDs, due dates, reminder times, steps (with step_id and done) and any estimate_minutes. Due includes today's and overdue unfinished tasks." + changes, |
| 581 | ["filter": ["type": "string", "enum": ["open", "due", "completed", "all"], "default": "open"]], |
| 582 | readOnly: true), |
| 583 | tool("add_personal_todo", "Add a personal to-do", |
| 584 | "Save a personal to-do separate from the coaching plan. Supply the same request_id when retrying. Reminders are scheduled locally after the app reads the task." + changes, |
| 585 | ["title": ["type": "string", "minLength": 1, "maxLength": PersonalTodo.titleLimit], |
| 586 | "due_day": ["type": "string", "format": "date", "description": "Optional local date, YYYY-MM-DD."], |
| 587 | "reminder_at": ["type": "string", "format": "date-time", "description": "Optional requested future time including a UTC offset or Z."], |
| 588 | "request_id": ["type": "string", "format": "uuid", "description": "Client-generated UUID. Reuse on retries."], |
| 589 | "steps": ["type": "array", "maxItems": 12, "description": "Optional small steps, in order. Start each with a verb.", |
| 590 | "items": ["type": "string", "minLength": 1, "maxLength": TodoStep.titleLimit]], |
| 591 | "estimate_minutes": ["type": "integer", "minimum": 1, "maximum": 1440, "description": "Optional time estimate in minutes."]], |
| 592 | required: ["title"], readOnly: false, idempotent: false), |
| 593 | tool("set_todo_steps", "Set to-do steps", |
| 594 | "Replace the steps of a personal to-do, or the smaller steps under one top-level step when parent_step_id is given. Steps whose titles stay the same keep their IDs and done state. Pass an empty list to clear them." + changes, |
| 595 | ["task_id": ["type": "string", "format": "uuid"], |
| 596 | "steps": ["type": "array", "maxItems": 12, "items": ["type": "string", "minLength": 1, "maxLength": TodoStep.titleLimit]], |
| 597 | "parent_step_id": ["type": "string", "format": "uuid", "description": "Optional top-level step_id to break down further."]], |
| 598 | required: ["task_id", "steps"], readOnly: false), |
| 599 | tool("set_personal_todo_done", "Set personal to-do completion", |
| 600 | "Complete or reopen a personal to-do using its task_id." + changes, |
| 601 | ["task_id": ["type": "string", "format": "uuid"], "done": ["type": "boolean"]], |
| 602 | required: ["task_id", "done"], readOnly: false), |
| 603 | tool("record_energy", "Record energy", |
| 604 | "Record today's energy level. A new value replaces today's earlier one." + changes, |
| 605 | ["level": ["type": "string", "enum": ["empty", "low", "mid", "high", "full"]]], |
| 606 | required: ["level"], readOnly: false), |
| 607 | tool("check_in_experiment", "Experiment check-in", |
| 608 | "Record today's check-in for the running 7-day experiment. One check-in per day." + changes, |
| 609 | ["outcome": ["type": "string", "enum": ["held", "slipped"]]], |
| 610 | required: ["outcome"], readOnly: false) |
| 611 | ] |
| 612 | } |
| 613 | |
| 614 | static func attentionSummary(_ journal: Journal, days: Int, now: Date) -> [String: Any] { |
| 615 | let categories = ["Activity", "People", "AI", "Messages", "Work", "Streaming", "News", "Feed"] |
| 616 | let moments = journal.moments.map { original in |
| 617 | var moment = original |
| 618 | if !categories.contains(moment.kind) { moment.kind = "Other" } |
| 619 | return moment |
| 620 | } |
| 621 | let summary = ReflectionSummary(moments, day: now, days: days) |
| 622 | let groups: [[String: Any]] = summary.kinds.map { |
| 623 | ["category": $0.name, "count": $0.count, "averageAftertaste": $0.average] |
| 624 | } |
| 625 | return success([ |
| 626 | "days": days, |
| 627 | "loggedMoments": summary.moments.count, |
| 628 | "neutralOrBetterPercent": summary.alignment.map { $0 as Any } ?? NSNull(), |
| 629 | "aftertasteScale": "−2 (drained) to +2 (nourished)", |
| 630 | "categories": groups |
| 631 | ]) |
| 632 | } |
| 633 | |
| 634 | static func planSummary(_ journal: Journal, now: Date) -> [String: Any] { |
| 635 | let today = CalendarDay.key(now) |
| 636 | let tasks = journal.tasks.filter { $0.occurs(on: now) } |
| 637 | let completed = journal.completions[today] ?? [] |
| 638 | return success([ |
| 639 | "day": today, |
| 640 | "scheduledTasks": tasks.count, |
| 641 | "completedTasks": tasks.filter { completed.contains($0.id) }.count, |
| 642 | "energy": journal.energy[today].map(\.level) |
| 643 | .flatMap { ["empty", "low", "mid", "high", "full"].contains($0) ? $0 as Any : nil } ?? NSNull(), |
| 644 | "experimentCheckIns": journal.experiment.map { $0.checkins.count as Any } ?? NSNull(), |
| 645 | "experimentReviewReady": journal.experiment?.readyToReview ?? false |
| 646 | ]) |
| 647 | } |
| 648 | |
| 649 | static func success(_ data: [String: Any]) -> [String: Any] { |
| 650 | guard let bytes = try? JSONSerialization.data(withJSONObject: data, options: .sortedKeys) else { |
| 651 | return failure("Could not prepare the Glimmer result.") |
| 652 | } |
| 653 | return ["content": [["type": "text", "text": String(decoding: bytes, as: UTF8.self)]]] |
| 654 | } |
| 655 | |
| 656 | static func failure(_ message: String) -> [String: Any] { |
| 657 | ["content": [["type": "text", "text": message]], "isError": true] |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | /// The last agent that connected and the last tool it used, shown in Settings → Agent access. |
| 662 | struct AgentActivity: Codable, Equatable { |
| 663 | var client: String? |
| 664 | var clientDate: Date? |
| 665 | var tool: String? |
| 666 | var toolDate: Date? |
| 667 | |
| 668 | static func read(in directory: URL) -> AgentActivity? { |
| 669 | guard let data = try? Data(contentsOf: directory.appending(path: AgentAccess.activityFile)) else { return nil } |
| 670 | return try? JSONDecoder().decode(AgentActivity.self, from: data) |
| 671 | } |
| 672 | |
| 673 | func write(in directory: URL) { |
| 674 | guard let data = try? JSONEncoder().encode(self) else { return } |
| 675 | try? data.write(to: directory.appending(path: AgentAccess.activityFile), options: .atomic) |
| 676 | } |
| 677 | } |
| 678 | #endif |