Branchwell

Jotley / app · jotley.ai / macOS / Utilities / AgentSkillInstaller.swift

Raw 13.0 KB on c22c50f3614b055549c1ecbf54af0165e0bc8df1
1// Shared agent skill installer. Keep this file identical in every one of our Mac apps
2// (Inkspring, Glimmer, Jotley, Textley, OpenTalon); only the bundled SKILL.md differs.
3import Foundation
4
5struct AgentSkillInstaller {
6 enum Agent: String, CaseIterable, Identifiable, Sendable {
7 case claudeCode, codex, gemini
8 var id: Self { self }
9 var title: String {
10 switch self { case .claudeCode: "Claude Code"; case .codex: "Codex"; case .gemini: "Gemini CLI" }
11 }
12 }
13
14 enum State: Equatable, Sendable {
15 case notInstalled
16 case installed
17 case updateAvailable
18 case differentVersion
19 case plugin(String)
20 }
21
22 struct Status: Equatable, Sendable {
23 let agent: Agent
24 let state: State
25 /// The folder that holds the skill, or the folder an install would create.
26 let location: URL
27 /// Codex and Gemini CLI both read ~/.agents/skills, so one copy serves both.
28 let shared: Bool
29 /// False when the agent's own folders are missing from this Mac.
30 let agentFound: Bool
31 }
32
33 let app: String
34 let skillID: String
35 let instructions: Data
36 let license: Data?
37 let home: URL
38
39 init(app: String, skillID: String, instructions: Data, license: Data? = nil,
40 home: URL = AgentSkillInstaller.userHome) {
41 self.app = app
42 self.skillID = skillID
43 self.instructions = instructions
44 self.license = license
45 self.home = home
46 }
47
48 /// The bundled skill's `metadata.version`, the number every copy is compared against.
49 var version: String? { Self.frontMatter(instructions).version }
50
51 /// Loads the bundled skill: AgentSkill.md (the SKILL.md) and AgentSkill-LICENSE.txt in the app's resources.
52 init?(app: String, skillID: String, bundle: Bundle = .main, home: URL = AgentSkillInstaller.userHome) {
53 guard let file = Self.bundledSkill(bundle), let instructions = try? Data(contentsOf: file) else { return nil }
54 let license = bundle.url(forResource: "AgentSkill-LICENSE", withExtension: "txt").flatMap { try? Data(contentsOf: $0) }
55 self.init(app: app, skillID: skillID, instructions: instructions, license: license, home: home)
56 }
57
58 static func bundledSkill(_ bundle: Bundle = .main) -> URL? {
59 bundle.url(forResource: "AgentSkill", withExtension: "md")
60 }
61
62 /// The signed-in user's real home folder, also inside the App Sandbox.
63 static var userHome: URL {
64 if let entry = getpwuid(getuid()), let directory = entry.pointee.pw_dir {
65 return URL(filePath: String(cString: directory), directoryHint: .isDirectory)
66 }
67 return FileManager.default.homeDirectoryForCurrentUser
68 }
69
70 /// Skill folders each agent reads, in the order the agent prefers them.
71 func searchFolders(_ agent: Agent) -> [URL] {
72 switch agent {
73 case .claudeCode: [folder(".claude", "skills")]
74 case .codex: [folder(".agents", "skills"), folder(".codex", "skills")]
75 case .gemini: [folder(".agents", "skills"), folder(".gemini", "skills"), folder(".gemini", "config", "skills")]
76 }
77 }
78
79 /// Where this app installs: Claude Code's folder, or the folder Codex and Gemini CLI share.
80 func installFolder(_ agent: Agent) -> URL {
81 agent == .claudeCode ? folder(".claude", "skills") : folder(".agents", "skills")
82 }
83
84 func status(_ agent: Agent) -> Status {
85 let found = agentFound(agent)
86 for parent in searchFolders(agent) {
87 let candidate = parent.appending(path: skillID, directoryHint: .isDirectory)
88 guard exists(candidate) else { continue }
89 return Status(agent: agent, state: classify(candidate), location: candidate,
90 shared: agent != .claudeCode && parent == folder(".agents", "skills"), agentFound: found)
91 }
92 if agent == .claudeCode, let plugin = claudePlugin() {
93 return Status(agent: agent, state: .plugin(plugin), location: installFolder(agent).appending(path: skillID),
94 shared: false, agentFound: found)
95 }
96 return Status(agent: agent, state: .notInstalled, location: installFolder(agent).appending(path: skillID),
97 shared: agent != .claudeCode, agentFound: found)
98 }
99
100 func statuses() -> [Status] { Agent.allCases.map(status) }
101
102 /// Installs or updates the bundled skill. An older copy of the same skill is replaced; a folder holding
103 /// some other skill is replaced only when `replacing` is true. The old folder (or link) moves to the Trash.
104 @discardableResult
105 func install(_ agent: Agent, replacing: Bool = false) throws -> URL {
106 let parent = installFolder(agent)
107 let target = parent.appending(path: skillID, directoryHint: .isDirectory)
108 let manager = FileManager.default
109 if exists(target) {
110 switch classify(target) {
111 case .installed: return target
112 case .updateAvailable: break
113 default: guard replacing else { throw InstallError.differentVersion(target) }
114 }
115 }
116 try manager.createDirectory(at: parent, withIntermediateDirectories: true)
117 let staging = parent.appending(path: ".\(skillID)-\(UUID().uuidString)", directoryHint: .isDirectory)
118 try manager.createDirectory(at: staging, withIntermediateDirectories: false)
119 do {
120 try instructions.write(to: staging.appending(path: "SKILL.md"))
121 if let license { try license.write(to: staging.appending(path: "LICENSE")) }
122 if exists(target) { try trash(target) }
123 try manager.moveItem(at: staging, to: target)
124 } catch {
125 try? manager.removeItem(at: staging)
126 throw error
127 }
128 return target
129 }
130
131 enum InstallError: LocalizedError {
132 case differentVersion(URL)
133 var errorDescription: String? {
134 switch self {
135 case .differentVersion(let url): "A different skill is already in \(url.path). Choose Replace to use this one."
136 }
137 }
138 }
139
140 // MARK: - App Sandbox access
141
142 /// True in sandboxed apps (Glimmer, Jotley), which can read and write an agent's folder only
143 /// after the person grants it once in an open panel. Unsandboxed apps never ask.
144 static var isSandboxed: Bool { ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] != nil }
145
146 /// The folder a sandboxed app needs for an agent: ~/.claude, or ~/.agents for Codex and Gemini CLI.
147 func accessFolder(_ agent: Agent) -> URL { agent == .claudeCode ? folder(".claude") : folder(".agents") }
148
149 /// Whether a saved grant covers this agent's folder (a grant of the home folder covers both).
150 func hasAccess(_ agent: Agent) -> Bool {
151 !Self.isSandboxed || Self.grants().contains { accessFolder(agent).path.hasPrefix($0.path) }
152 }
153
154 /// Saves a folder the person chose in an open panel. Returns false for a folder that doesn't cover the agent.
155 @discardableResult
156 func rememberGrant(_ chosen: URL, for agent: Agent) -> Bool {
157 let target = accessFolder(agent).standardizedFileURL.path
158 guard target.hasPrefix(chosen.standardizedFileURL.path),
159 let bookmark = try? chosen.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil,
160 relativeTo: nil) else { return false }
161 var saved = UserDefaults.standard.dictionary(forKey: Self.grantsKey) as? [String: Data] ?? [:]
162 saved[chosen.standardizedFileURL.path] = bookmark
163 UserDefaults.standard.set(saved, forKey: Self.grantsKey)
164 return true
165 }
166
167 /// Runs `body` with every saved grant open, so detection and installs can reach the agent folders.
168 func withAccess<T>(_ body: () throws -> T) rethrows -> T {
169 let opened = Self.grants().filter { $0.startAccessingSecurityScopedResource() }
170 defer { opened.forEach { $0.stopAccessingSecurityScopedResource() } }
171 return try body()
172 }
173
174 private static let grantsKey = "agentSkillFolderGrants"
175
176 private static func grants() -> [URL] {
177 guard isSandboxed, let saved = UserDefaults.standard.dictionary(forKey: grantsKey) as? [String: Data] else { return [] }
178 return saved.values.compactMap { data in
179 var stale = false
180 return try? URL(resolvingBookmarkData: data, options: .withSecurityScope, relativeTo: nil, bookmarkDataIsStale: &stale)
181 }
182 }
183
184 // MARK: - Detection
185
186 /// Same bytes, or the same skill at this version or newer: installed. The same skill at an older or
187 /// unknown version, or a copy this app can't read (such as a link the App Sandbox can't follow): update.
188 /// A folder whose SKILL.md names another skill: different.
189 private func classify(_ candidate: URL) -> State {
190 guard let installed = try? Data(contentsOf: candidate.appending(path: "SKILL.md")) else { return .updateAvailable }
191 if installed == instructions { return .installed }
192 let found = Self.frontMatter(installed)
193 guard found.name == skillID else { return .differentVersion }
194 guard let current = version, let other = found.version else { return .updateAvailable }
195 return Self.compare(other, current) == .orderedAscending ? .updateAvailable : .installed
196 }
197
198 /// Reads `name` and `metadata.version` from a SKILL.md front matter block.
199 static func frontMatter(_ data: Data) -> (name: String?, version: String?) {
200 let lines = String(decoding: data, as: UTF8.self).split(separator: "\n", omittingEmptySubsequences: false)
201 guard lines.first?.trimmingCharacters(in: .whitespaces) == "---" else { return (nil, nil) }
202 var name: String?, version: String?, inMetadata = false
203 for line in lines.dropFirst() {
204 if line.trimmingCharacters(in: .whitespaces) == "---" { break }
205 let indented = line.first == " " || line.first == "\t"
206 let parts = line.split(separator: ":", maxSplits: 1)
207 guard parts.count == 2 else { inMetadata = !indented && parts.first == "metadata"; continue }
208 let key = parts[0].trimmingCharacters(in: .whitespaces)
209 let value = parts[1].trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
210 if !indented { inMetadata = key == "metadata" && value.isEmpty }
211 if !indented && key == "name" { name = value }
212 if indented && inMetadata && key == "version" { version = value }
213 }
214 return (name, version)
215 }
216
217 /// Compares dotted version numbers numerically (1.10.0 is newer than 1.9.2).
218 static func compare(_ lhs: String, _ rhs: String) -> ComparisonResult {
219 let left = lhs.split(separator: ".").map { Int($0) ?? 0 }, right = rhs.split(separator: ".").map { Int($0) ?? 0 }
220 for index in 0..<max(left.count, right.count) {
221 let a = index < left.count ? left[index] : 0, b = index < right.count ? right[index] : 0
222 if a != b { return a < b ? .orderedAscending : .orderedDescending }
223 }
224 return .orderedSame
225 }
226
227 /// Claude Code plugins record their install folders; a matching plugin name or skill counts.
228 private func claudePlugin() -> String? {
229 let record = folder(".claude", "plugins").appending(path: "installed_plugins.json")
230 guard let data = try? Data(contentsOf: record),
231 let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
232 let plugins = json["plugins"] as? [String: Any] else { return nil }
233 for (key, installs) in plugins {
234 let name = String(key.split(separator: "@").first ?? Substring(key))
235 if name == skillID || name.hasSuffix("-\(skillID)") { return name }
236 for install in installs as? [[String: Any]] ?? [] {
237 guard let path = install["installPath"] as? String else { continue }
238 if exists(URL(filePath: path).appending(path: "skills/\(skillID)/SKILL.md")) { return name }
239 }
240 }
241 return nil
242 }
243
244 private func agentFound(_ agent: Agent) -> Bool {
245 switch agent {
246 case .claudeCode: exists(folder(".claude"))
247 case .codex: exists(folder(".codex")) || exists(folder(".agents"))
248 case .gemini: exists(folder(".gemini"))
249 }
250 }
251
252 private func folder(_ parts: String...) -> URL {
253 parts.reduce(home) { $0.appending(path: $1, directoryHint: .isDirectory) }
254 }
255
256 private func exists(_ url: URL) -> Bool {
257 (try? url.checkResourceIsReachable()) == true
258 || (try? FileManager.default.destinationOfSymbolicLink(atPath: url.path)) != nil
259 }
260
261 private func trash(_ url: URL) throws {
262 do { try FileManager.default.trashItem(at: url, resultingItemURL: nil) } catch {
263 // Folders outside a Trash-capable volume (or in tests) are moved aside instead of deleted.
264 let aside = url.deletingLastPathComponent().appending(path: ".\(skillID)-replaced-\(UUID().uuidString)")
265 try FileManager.default.moveItem(at: url, to: aside)
266 }
267 }
268}