Branchwell

Glimmer / app · glimmertoday.ai / native / Glimmer / AgentSetup.swift

1#if os(macOS)
2import AppKit
3import Foundation
4import UniformTypeIdentifiers
5
6/// Connection setup for Claude Code, Codex and Claude chat. Every step is an explicit action in
7/// Settings; Glimmer never edits an agent's configuration on its own.
8@MainActor
9enum AgentSetup {
10 static var command: String { Bundle.main.executableURL?.path ?? "/Applications/Glimmer.app/Contents/MacOS/Glimmer" }
11 static let argument = AgentAccess.argument
12
13 enum SetupError: LocalizedError {
14 case invalidConfiguration, unsafeFile, changedFile, exportFailed
15
16 var errorDescription: String? {
17 switch self {
18 case .invalidConfiguration: "The existing configuration isn’t a valid MCP configuration, so Glimmer left it unchanged."
19 case .unsafeFile: "Choose a folder whose configuration is a regular file, not a link or folder."
20 case .changedFile: "The project’s .mcp.json changed while saving. Try again."
21 case .exportFailed: "Glimmer couldn’t save the Claude extension. Choose another location and try again."
22 }
23 }
24 }
25
26 // MARK: Claude Code
27
28 nonisolated static func mergedProjectConfiguration(existing: Data?, command: String) throws -> (data: Data, replaces: Bool) {
29 let entry: [String: Any] = ["type": "stdio", "command": command, "args": [AgentAccess.argument]]
30 var root: [String: Any] = [:]
31 if let existing, !existing.isEmpty {
32 guard let parsed = try? JSONSerialization.jsonObject(with: existing) as? [String: Any] else {
33 throw SetupError.invalidConfiguration
34 }
35 root = parsed
36 }
37 if let servers = root["mcpServers"], !(servers is [String: Any]) { throw SetupError.invalidConfiguration }
38 var servers = root["mcpServers"] as? [String: Any] ?? [:]
39 let replaces = servers["glimmer"].map { !NSDictionary(dictionary: ["entry": $0]).isEqual(to: ["entry": entry]) } ?? false
40 servers["glimmer"] = entry
41 root["mcpServers"] = servers
42 return (try JSONSerialization.data(withJSONObject: root, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]), replaces)
43 }
44
45 static func saveProjectConnection(gemini: Bool = false) throws -> String? {
46 let panel = NSOpenPanel()
47 let client = gemini ? "Gemini CLI" : "Claude Code"
48 let path = gemini ? ".gemini/settings.json" : ".mcp.json"
49 panel.title = "Choose your \(client) project folder"
50 panel.message = "Glimmer adds itself to \(path) in this folder. Other servers in the file stay as they are."
51 panel.prompt = "Save Connection"
52 panel.canChooseFiles = false
53 panel.canChooseDirectories = true
54 panel.canCreateDirectories = true
55 guard panel.runModal() == .OK, let folder = panel.url else { return nil }
56 let scoped = folder.startAccessingSecurityScopedResource()
57 defer { if scoped { folder.stopAccessingSecurityScopedResource() } }
58 if gemini {
59 let directory = folder.appending(path: ".gemini", directoryHint: .isDirectory)
60 if (try? directory.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) == true { throw SetupError.unsafeFile }
61 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
62 }
63 let file = folder.appending(path: path)
64 let existing = try readConfiguration(file)
65 let merged = try mergedProjectConfiguration(existing: existing, command: command)
66 if merged.replaces {
67 let alert = NSAlert()
68 alert.messageText = "Replace this project’s Glimmer connection?"
69 alert.informativeText = "Only the glimmer entry changes, so it points at this copy of Glimmer. Other MCP servers are kept."
70 alert.addButton(withTitle: "Replace")
71 alert.addButton(withTitle: "Cancel")
72 guard alert.runModal() == .alertFirstButtonReturn else { return nil }
73 }
74 guard try readConfiguration(file) == existing else { throw SetupError.changedFile }
75 try merged.data.write(to: file, options: .atomic)
76 return "Saved to \(folder.lastPathComponent)/\(path). Start a new \(client) session in that folder."
77 }
78
79 private static func readConfiguration(_ file: URL) throws -> Data? {
80 // Check the link itself first, including a broken one.
81 if let values = try? file.resourceValues(forKeys: [.isSymbolicLinkKey, .isDirectoryKey]),
82 values.isSymbolicLink == true || values.isDirectory == true { throw SetupError.unsafeFile }
83 guard FileManager.default.fileExists(atPath: file.path) else { return nil }
84 return try Data(contentsOf: file)
85 }
86
87 // MARK: Claude chat
88
89 static func saveClaudeExtension() throws -> String? {
90 let panel = NSSavePanel()
91 panel.title = "Save the Claude extension"
92 panel.nameFieldStringValue = "Glimmer.mcpb"
93 panel.allowedContentTypes = [UTType(filenameExtension: "mcpb") ?? .data]
94 panel.message = "Install this file in the Claude app under Settings → Extensions. It holds no journal data."
95 guard panel.runModal() == .OK, let destination = panel.url else { return nil }
96
97 let staging = FileManager.default.temporaryDirectory.appending(path: "Glimmer-\(UUID().uuidString)", directoryHint: .isDirectory)
98 try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)
99 defer { try? FileManager.default.removeItem(at: staging) }
100 try Data(extensionServer.utf8).write(to: staging.appending(path: "server.js"))
101 try extensionManifest(command: command).write(to: staging.appending(path: "manifest.json"))
102 guard let tiff = NSApplication.shared.applicationIconImage?.tiffRepresentation,
103 let png = NSBitmapImageRep(data: tiff)?.representation(using: .png, properties: [:]) else { throw SetupError.exportFailed }
104 try png.write(to: staging.appending(path: "icon.png"))
105
106 // Coordinated reading "for uploading" hands back a zip of the folder, which is what an .mcpb is.
107 var coordinationError: NSError?
108 var copyError: Error?
109 NSFileCoordinator().coordinate(readingItemAt: staging, options: .forUploading, error: &coordinationError) { zip in
110 do { try Data(contentsOf: zip).write(to: destination, options: .atomic) } catch { copyError = error }
111 }
112 if coordinationError != nil || copyError != nil { throw SetupError.exportFailed }
113 NSWorkspace.shared.activateFileViewerSelecting([destination])
114 return "Glimmer.mcpb saved. In the Claude app, open Settings → Extensions and install it, then start a new chat."
115 }
116
117 nonisolated static func extensionManifest(command: String) throws -> Data {
118 let manifest: [String: Any] = [
119 "manifest_version": "0.3",
120 "name": "glimmer",
121 "display_name": "Glimmer",
122 "version": AgentAccess.version,
123 "description": "Read your Glimmer attention summaries and log moments on your Mac.",
124 "long_description": "Connect Claude chat to the Glimmer journal on this Mac. Glimmer Settings → Agent access controls what Claude can read and change. Claude may send what it reads to Anthropic under Claude's terms.",
125 "author": ["name": "Protomota, LLC", "url": "https://protomota.com"],
126 "homepage": "https://glimmertoday.ai",
127 "support": "https://glimmertoday.ai/mcp",
128 "privacy_policies": ["https://glimmertoday.ai/privacy#mcp"],
129 "icon": "icon.png",
130 "server": [
131 "type": "node",
132 "entry_point": "server.js",
133 "mcp_config": [
134 "command": "node",
135 "args": ["${__dirname}/server.js"],
136 "env": ["GLIMMER_APP_EXECUTABLE": command]
137 ]
138 ],
139 "tools": AgentAccess.tools.map { ["name": $0["name"] ?? "", "description": $0["description"] ?? ""] },
140 "compatibility": ["platforms": ["darwin"], "runtimes": ["node": ">=18.0.0"]]
141 ]
142 return try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
143 }
144
145 /// Claude supplies Node. The script only starts Glimmer's own `--mcp` server and passes messages through.
146 nonisolated static let extensionServer = """
147 'use strict';
148 const { spawn } = require('node:child_process');
149 const fs = require('node:fs');
150
151 const candidates = [process.env.GLIMMER_APP_EXECUTABLE, '/Applications/Glimmer.app/Contents/MacOS/Glimmer']
152 .filter(path => typeof path === 'string' && path.endsWith('/Glimmer.app/Contents/MacOS/Glimmer'));
153 const executable = candidates.find(path => fs.existsSync(path));
154 if (!executable) {
155 process.stderr.write('Install Glimmer for Mac in Applications, then turn on Settings → Agent access.\\n');
156 process.exit(1);
157 }
158
159 const glimmer = spawn(executable, ['--mcp'], { stdio: ['pipe', 'pipe', 'inherit'] });
160 process.stdin.pipe(glimmer.stdin);
161 glimmer.stdout.pipe(process.stdout);
162 process.stdin.on('end', () => glimmer.stdin.end());
163 glimmer.on('exit', code => process.exit(code ?? 0));
164 glimmer.on('error', () => {
165 process.stderr.write('Glimmer could not start. Open Glimmer once, then try again.\\n');
166 process.exit(1);
167 });
168 """
169
170 // MARK: Connection check
171
172 /// Starts this copy of Glimmer the way an agent does and lists its tools.
173 nonisolated static func testConnection(executable: String) async -> Result<Int, Error> {
174 await Task.detached { listTools(executable: executable) }.value
175 }
176
177 private nonisolated static func listTools(executable: String) -> Result<Int, Error> {
178 let process = Process()
179 process.executableURL = URL(fileURLWithPath: executable)
180 process.arguments = [AgentAccess.argument]
181 let input = Pipe(), output = Pipe()
182 process.standardInput = input
183 process.standardOutput = output
184 process.standardError = FileHandle.nullDevice
185 do {
186 try process.run()
187 let requests = [
188 #"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"\#(AgentAccess.checkClient)","version":"1"}}}"#,
189 #"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
190 #"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#
191 ]
192 input.fileHandleForWriting.write(Data((requests.joined(separator: "\n") + "\n").utf8))
193 try input.fileHandleForWriting.close()
194 let deadline = DispatchTime.now() + .seconds(10)
195 let finished = DispatchSemaphore(value: 0)
196 process.terminationHandler = { _ in finished.signal() }
197 if finished.wait(timeout: deadline) == .timedOut { process.terminate() }
198 let data = output.fileHandleForReading.readDataToEndOfFile()
199 for line in data.split(separator: 10) {
200 guard let message = try? JSONSerialization.jsonObject(with: Data(line)) as? [String: Any],
201 message["id"] as? Int == 2,
202 let tools = (message["result"] as? [String: Any])?["tools"] as? [Any] else { continue }
203 return .success(tools.count)
204 }
205 return .failure(SetupError.exportFailed)
206 } catch {
207 return .failure(error)
208 }
209 }
210
211 static func copy(_ value: String) {
212 NSPasteboard.general.clearContents()
213 NSPasteboard.general.setString(value, forType: .string)
214 }
215}
216#endif