Branchwell

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

1import Foundation
2
3/// Where Coach and the Toolkit get their replies. The local agents mirror Inkspring's writing agent and
4/// OpenTalon's task agent: Glimmer runs the agent's own command line tool with its signed-in session.
5enum CoachAgent: String, CaseIterable, Identifiable {
6 case device, claude, codex, gemini, server
7 var id: Self { self }
8
9 static let preference = "coach.agent"
10 static let localAgents: [CoachAgent] = [.claude, .codex, .gemini]
11
12 var title: String {
13 switch self {
14 case .device: "On this device"
15 case .claude: "Claude Code"
16 case .codex: "Codex"
17 case .gemini: "Gemini CLI"
18 case .server: "Local MCP server"
19 }
20 }
21
22 var symbol: String {
23 switch self {
24 case .device: "lock.fill"
25 case .claude: "sparkle"
26 case .codex: "chevron.left.forwardslash.chevron.right"
27 case .gemini: "diamond.fill"
28 case .server: "server.rack"
29 }
30 }
31
32 var isLocalAgent: Bool { Self.localAgents.contains(self) }
33
34 var guide: URL? {
35 switch self {
36 case .claude: URL(string: "https://code.claude.com/docs/en/quickstart")
37 case .codex: URL(string: "https://learn.chatgpt.com/docs/codex/cli")
38 // Gemini runs through Google's Antigravity CLI (agy), as in Inkspring and OpenTalon.
39 case .gemini: URL(string: "https://antigravity.google/docs/getting-started?tab=cli")
40 default: nil
41 }
42 }
43
44 /// The same model lists Inkspring offers for its writing agent. The first entry is the top model.
45 var models: [CoachModel] {
46 switch self {
47 case .claude: [.init(id: "claude-fable-5-2", name: "Fable 5.2"), .init(id: "claude-fable-5", name: "Fable 5"),
48 .init(id: "claude-opus-5-5", name: "Opus 5.5"), .init(id: "claude-sonnet-5-5", name: "Sonnet 5.5"),
49 .init(id: "claude-haiku-5-5", name: "Haiku 5.5")]
50 case .codex: [.init(id: "gpt-6.2-astra", name: "GPT-6.2 Astra"), .init(id: "gpt-6.2-sol", name: "GPT-6.2 Sol"),
51 .init(id: "gpt-6.1-terra", name: "GPT-6.1 Terra"), .init(id: "gpt-6-luna", name: "GPT-6 Luna")]
52 case .gemini: [.init(id: "gemini-4-carbon", name: "Gemini 4 Carbon"), .init(id: "gemini-4-neon", name: "Gemini 4 Neon"),
53 .init(id: "gemini-4-argon", name: "Gemini 4 Argon"), .init(id: "gemini-4-hydrogen", name: "Gemini 4 Hydrogen")]
54 default: []
55 }
56 }
57
58 /// Gemini always needs a model, so its default is the first listed one.
59 var defaultModel: String? { self == .gemini ? models.first?.id : nil }
60
61 func efforts(model: String?) -> [String] {
62 switch self {
63 case .claude: ["low", "medium", "high", "xhigh", "max"]
64 case .codex: ["low", "medium", "high", "xhigh"]
65 // Antigravity encodes effort in the model ID. Neon and Hydrogen also offer extra high.
66 case .gemini: ["gemini-4-neon", "gemini-4-hydrogen"].contains(model ?? defaultModel ?? "")
67 ? ["low", "medium", "high", "xhigh"] : ["low", "medium", "high"]
68 default: []
69 }
70 }
71
72 static func effortName(_ effort: String) -> String {
73 switch effort {
74 case "": "Default"
75 case "xhigh": "Extra high"
76 default: effort.prefix(1).uppercased() + effort.dropFirst()
77 }
78 }
79
80 func modelName(_ id: String?) -> String {
81 guard let id, !id.isEmpty else { return "Agent default" }
82 return models.first { $0.id == id }?.name ?? id
83 }
84
85 #if os(macOS)
86 /// Where each tool installs, in the order Inkspring and OpenTalon look.
87 var candidatePaths: [String] {
88 let home = CoachAgentRunner.userHome
89 return switch self {
90 case .claude: [home + "/.local/bin/claude", "/opt/homebrew/bin/claude", "/usr/local/bin/claude", home + "/.npm-global/bin/claude"]
91 case .codex: ["/Applications/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex",
92 "/Applications/Codex.app/Contents/Resources/codex",
93 home + "/.npm-global/bin/codex", "/opt/homebrew/bin/codex", "/usr/local/bin/codex"]
94 case .gemini: [home + "/.local/bin/agy", home + "/.antigravity/bin/agy", "/opt/homebrew/bin/agy", "/usr/local/bin/agy"]
95 default: []
96 }
97 }
98
99 var executable: URL? {
100 candidatePaths.first(where: FileManager.default.isExecutableFile(atPath:)).map { URL(fileURLWithPath: $0) }
101 }
102 #endif
103}
104
105struct CoachModel: Identifiable, Hashable {
106 let id: String
107 let name: String
108}
109
110/// The person's Coach choices, saved per agent like Inkspring's writing model preferences.
111struct CoachAgentChoice: Equatable {
112 var agent: CoachAgent
113 var model: String
114 var effort: String
115 var timeout: Int
116
117 static let timeouts = [30, 60, 90, 120]
118 static func modelKey(_ agent: CoachAgent) -> String { "coach.model.\(agent.rawValue)" }
119 static func effortKey(_ agent: CoachAgent) -> String { "coach.effort.\(agent.rawValue)" }
120 static let timeoutKey = "coach.timeout"
121
122 static var current: CoachAgentChoice {
123 let defaults = UserDefaults.standard
124 let agent = defaults.string(forKey: CoachAgent.preference).flatMap(CoachAgent.init(rawValue:)) ?? legacyAgent
125 let timeout = defaults.integer(forKey: timeoutKey)
126 return .init(agent: agent, model: defaults.string(forKey: modelKey(agent)) ?? "",
127 effort: defaults.string(forKey: effortKey(agent)) ?? "",
128 timeout: timeouts.contains(timeout) ? timeout : 90)
129 }
130
131 /// Before the agent picker, a saved MCP address meant Coach used that server.
132 private static var legacyAgent: CoachAgent {
133 #if os(macOS)
134 let endpoint = UserDefaults.standard.string(forKey: CoachMCP.preference) ?? ""
135 return CoachMCP.url(endpoint) == nil ? .device : .server
136 #else
137 .device
138 #endif
139 }
140
141 /// The model actually sent, or nil for the agent's own default.
142 var resolvedModel: String? {
143 if agent == .gemini {
144 let family = model.isEmpty ? agent.defaultModel ?? "" : model
145 let effort = agent.efforts(model: family).contains(effort) ? effort : "high"
146 return family + "-" + effort
147 }
148 return model.isEmpty ? nil : model
149 }
150
151 var resolvedEffort: String? {
152 agent != .gemini && agent.efforts(model: model).contains(effort) ? effort : nil
153 }
154
155 /// A short name for the composer, such as "Claude Code · Opus 5.5".
156 var title: String {
157 agent.isLocalAgent ? "\(agent.title) · \(agent.modelName(model.isEmpty ? agent.defaultModel : model))" : agent.title
158 }
159
160 /// Identifies the conversation partner, so earlier turns from another agent aren't replayed to this one.
161 var key: String { "\(agent.rawValue):\(model):\(effort)" }
162
163 /// Coach can use this choice right now on this Mac.
164 var isReady: Bool {
165 #if os(macOS)
166 switch agent {
167 case .device: false
168 case .server: CoachMCP.url(UserDefaults.standard.string(forKey: CoachMCP.preference) ?? "") != nil
169 default: agent.executable != nil
170 }
171 #else
172 false
173 #endif
174 }
175}
176
177/// What Settings shows about recent agent replies. Holds timing and error text only, never questions or replies.
178enum CoachAgentLog {
179 private static let successKey = "coach.lastSuccess"
180 private static let successDetailKey = "coach.lastSuccessDetail"
181 private static let failureKey = "coach.lastFailure"
182 private static let failureDetailKey = "coach.lastFailureDetail"
183
184 static var lastSuccess: Date? { UserDefaults.standard.object(forKey: successKey) as? Date }
185 static var lastSuccessDetail: String? { UserDefaults.standard.string(forKey: successDetailKey) }
186 static var lastFailure: Date? { UserDefaults.standard.object(forKey: failureKey) as? Date }
187 static var lastFailureDetail: String? { UserDefaults.standard.string(forKey: failureDetailKey) }
188
189 static func success(_ choice: CoachAgentChoice, seconds: Double) {
190 UserDefaults.standard.set(Date(), forKey: successKey)
191 UserDefaults.standard.set("\(choice.title) answered in \(seconds.formatted(.number.precision(.fractionLength(1)))) s", forKey: successDetailKey)
192 }
193
194 static func failure(_ choice: CoachAgentChoice, _ error: Error) {
195 UserDefaults.standard.set(Date(), forKey: failureKey)
196 UserDefaults.standard.set("\(choice.title): \(error.localizedDescription)", forKey: failureDetailKey)
197 }
198}
199
200struct CoachAgentFailure: LocalizedError {
201 let message: String
202 var errorDescription: String? { message }
203}
204
205#if os(macOS)
206/// Runs a local agent's command line tool for one reply, with no tools, skills or MCP servers.
207enum CoachAgentRunner {
208 /// The person's real home folder. Inside the App Sandbox, NSHomeDirectory() is Glimmer's container.
209 static var userHome: String {
210 if let entry = getpwuid(getuid()), let directory = entry.pointee.pw_dir { return String(cString: directory) }
211 return NSHomeDirectory()
212 }
213
214 /// Sends one prompt and returns the agent's text. Only what's in `instructions` and `prompt` is shared.
215 static func run(_ choice: CoachAgentChoice, instructions: String, prompt: String) async throws -> String {
216 let agent = choice.agent
217 guard agent.isLocalAgent else { throw CoachAgentFailure(message: "Choose Claude Code, Codex or Gemini CLI.") }
218 guard let executable = agent.executable else {
219 throw CoachAgentFailure(message: "\(agent.title) isn’t installed on this Mac. Install it and sign in, then try again.")
220 }
221 let root = FileManager.default.temporaryDirectory.appending(path: "GlimmerCoach-\(UUID().uuidString)", directoryHint: .isDirectory)
222 try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
223 defer { try? FileManager.default.removeItem(at: root) }
224 let input = root.appending(path: "prompt")
225 let stdout = root.appending(path: "stdout")
226 let stderr = root.appending(path: "stderr")
227 let answer = root.appending(path: "answer")
228
229 let arguments: [String]
230 switch agent {
231 case .claude:
232 try Data(prompt.utf8).write(to: input)
233 arguments = (choice.resolvedModel.map { ["--model", $0] } ?? []) + (choice.resolvedEffort.map { ["--effort", $0] } ?? [])
234 + ["--print", "--restricted", "--output-format", "json", "--tools", "", "--setting-sources", "",
235 "--strict-mcp-config", "--mcp-config", #"{"mcpServers":{}}"#, "--disable-slash-commands",
236 "--no-session-persistence", "--system-prompt", instructions + "\n" + isolation]
237 case .codex:
238 try Data(prompt.utf8).write(to: input)
239 arguments = ["-a", "never", "exec"] + (choice.resolvedModel.map { ["--model", $0] } ?? [])
240 + ["-c", "developer_instructions=" + tomlString(instructions + "\n" + isolation)]
241 + (choice.resolvedEffort.map { ["-c", "model_reasoning_effort=\"\($0)\""] } ?? [])
242 + ["--ignore-user-config", "--ignore-rules", "--ephemeral", "--sandbox", "read-only", "--skip-git-repo-check",
243 "-c", "web_search=\"disabled\"", "--disable", "shell_tool", "--disable", "apps", "--disable", "plugins",
244 "--disable", "hooks", "--disable", "multi_agent", "--output-last-message", answer.path, "-"]
245 default:
246 try geminiProfile(instructions, in: root)
247 let message: [String: Any] = ["event": "user", "message": ["content": prompt]]
248 try (JSONSerialization.data(withJSONObject: message) + Data([0x0A])).write(to: input)
249 arguments = ["--agent", "glimmer-coach", "--model", choice.resolvedModel ?? "", "--sandbox",
250 "--disable-slash-commands", "--print-timeout", "\(max(choice.timeout - 5, 25))s",
251 "--input-format", "stream-json", "--output-format", "stream-json"]
252 }
253 try Data().write(to: stdout)
254 try Data().write(to: stderr)
255 let inputHandle = try FileHandle(forReadingFrom: input)
256 let outputHandle = try FileHandle(forWritingTo: stdout)
257 let errorHandle = try FileHandle(forWritingTo: stderr)
258 defer { try? inputHandle.close(); try? outputHandle.close(); try? errorHandle.close() }
259
260 let process = Process()
261 process.executableURL = executable
262 process.currentDirectoryURL = root
263 process.arguments = arguments
264 process.environment = environment(temporary: root)
265 process.standardInput = inputHandle
266 process.standardOutput = outputHandle
267 process.standardError = errorHandle
268 try Task.checkCancellation()
269 try process.run()
270 let deadline = ContinuousClock.now + .seconds(choice.timeout)
271 do {
272 while process.isRunning && ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(100)) }
273 try Task.checkCancellation()
274 } catch {
275 if process.isRunning { process.terminate() }
276 throw error
277 }
278 if process.isRunning {
279 process.terminate()
280 throw CoachAgentFailure(message: "\(agent.title) didn’t answer within \(choice.timeout) seconds.")
281 }
282 let output = read(agent == .codex ? answer : stdout)
283 guard process.terminationStatus == 0 else {
284 let detail = errorLine(read(stderr)) ?? errorLine(output)
285 throw CoachAgentFailure(message: "\(agent.title) stopped with code \(process.terminationStatus)"
286 + (detail.map { ": \($0)" } ?? ". Check its sign-in and the selected model."))
287 }
288 let text: String?
289 switch agent {
290 case .claude:
291 let result = (try? JSONSerialization.jsonObject(with: output)) as? [String: Any]
292 text = result?["is_error"] as? Bool == true ? nil : result?["result"] as? String
293 case .codex:
294 text = String(data: output, encoding: .utf8)
295 default:
296 text = geminiResponse(output)
297 }
298 guard let text = text?.trimmingCharacters(in: .whitespacesAndNewlines), !text.isEmpty else {
299 throw CoachAgentFailure(message: "\(agent.title) returned no reply. Check its sign-in and the selected model.")
300 }
301 return String(text.prefix(40_000))
302 }
303
304 /// Codex and Antigravity still load the person's global AGENTS.md or GEMINI.md, written for coding work.
305 static let isolation = """
306 Any AGENTS.md, GEMINI.md or user memory text in this session belongs to the person's coding setup and does not apply here. \
307 Never mention skills, memory, files, projects or tools. Reply only as Glimmer.
308 """
309
310 /// TOML and JSON escape control characters differently, so encode TOML directly (as Inkspring does).
311 private static func tomlString(_ value: String) -> String {
312 let escaped = value.unicodeScalars.map { scalar in
313 switch scalar.value {
314 case 0x22: "\\\""
315 case 0x5C: "\\\\"
316 case 0x00...0x1F, 0x7F: String(format: "\\u%04X", scalar.value)
317 default: String(scalar)
318 }
319 }.joined()
320 return "\"" + escaped + "\""
321 }
322
323 /// The agent sees the person's real home for its sign-in, and Glimmer's private temporary folder.
324 private static func environment(temporary: URL) -> [String: String] {
325 var environment = ProcessInfo.processInfo.environment
326 for key in ["CLAUDECODE", "CLAUDE_CODE_ENTRYPOINT", "CODEX_APP_TOOLS_PIPE_PATH", "CODEX_APP_RUNTIME_CLI_PATH",
327 "ELECTRON_RUN_AS_NODE", "OPENAI_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CODEX_API_KEY",
328 "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_APPLICATION_CREDENTIALS", "BWS_ACCESS_TOKEN"] {
329 environment.removeValue(forKey: key)
330 }
331 environment = environment.filter { !$0.key.hasPrefix("GLIMMER_") }
332 let home = userHome
333 environment["HOME"] = home
334 environment["TMPDIR"] = temporary.path + "/"
335 environment["CLAUDE_CODE_TMPDIR"] = temporary.path
336 environment["PATH"] = [home + "/.local/bin", home + "/.npm-global/bin", "/opt/homebrew/bin", "/usr/local/bin",
337 "/usr/bin", "/bin"].joined(separator: ":")
338 return environment
339 }
340
341 private static func geminiProfile(_ instructions: String, in root: URL) throws {
342 let folder = root.appending(path: ".agents/agents", directoryHint: .isDirectory)
343 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
344 let profile = """
345 ---
346 name: glimmer-coach
347 description: Reply as Glimmer's coach.
348 mainAgent: true
349 subagent: false
350 tools: []
351 mcpServers: []
352 plugins: []
353 skills: []
354 commandExecutionPolicy: "off"
355 ---
356 \(instructions)
357 \(isolation)
358 """
359 try profile.write(to: folder.appending(path: "glimmer-coach.md"), atomically: true, encoding: .utf8)
360 }
361
362 private static func geminiResponse(_ stream: Data) -> String? {
363 guard let last = stream.split(separator: 0x0A).last,
364 let event = try? JSONSerialization.jsonObject(with: Data(last)) as? [String: Any],
365 event["event"] as? String == "result", let result = event["result"] as? [String: Any],
366 result["status"] as? String == "SUCCESS" else { return nil }
367 return result["response"] as? String
368 }
369
370 private static func read(_ url: URL) -> Data {
371 guard let handle = try? FileHandle(forReadingFrom: url) else { return Data() }
372 defer { try? handle.close() }
373 return (try? handle.read(upToCount: 2_000_000)) ?? Data()
374 }
375
376 /// The last line that reports an error. Agents echo the prompt to standard error, so other lines stay out.
377 private static func errorLine(_ data: Data) -> String? {
378 let lines = String(decoding: data, as: UTF8.self).split(whereSeparator: \.isNewline).map(String.init)
379 return lines.last { $0.localizedCaseInsensitiveContains("error") || $0.contains("not permitted") || $0.contains("401") }
380 .map { String($0.trimmingCharacters(in: .whitespaces).prefix(240)) }
381 }
382
383 /// Pulls the JSON object out of a reply that may be wrapped in a code fence or a sentence.
384 static func jsonObject(_ text: String) -> [String: Any]? {
385 guard let start = text.firstIndex(of: "{"), let end = text.lastIndex(of: "}"), start < end else { return nil }
386 return try? JSONSerialization.jsonObject(with: Data(text[start...end].utf8)) as? [String: Any]
387 }
388}
389#endif
390
391#if os(macOS)
392/// Sends a Coach or Toolkit request to the chosen agent and records how it went for Settings.
393enum CoachAgentRoute {
394 static let replyFormat = """
395 Reply with only a JSON object: {"answer": "your reply, about 80 words or fewer", "recommendation": "one exact recommendation key from the context, or none"}.
396 """
397
398 static func reply(_ choice: CoachAgentChoice, prompt: String) async throws -> CoachReply {
399 try await logged(choice) {
400 if choice.agent == .server {
401 return try await CoachMCP.reply(endpoint: UserDefaults.standard.string(forKey: CoachMCP.preference) ?? "", prompt: prompt)
402 }
403 let text = try await CoachAgentRunner.run(choice, instructions: CoachGuidanceInstructions.text + "\n" + replyFormat, prompt: prompt)
404 if let object = CoachAgentRunner.jsonObject(text), let answer = object["answer"] as? String,
405 !answer.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
406 let key = object["recommendation"] as? String
407 return CoachReply(answer: answer, recommendation: key == "none" ? nil : key)
408 }
409 return CoachReply(answer: text, recommendation: nil)
410 }
411 }
412
413 static func toolkit(_ choice: CoachAgentChoice, tool: ToolkitTool, input: [String: Any], prompt: String) async throws -> [String: Any] {
414 try await logged(choice) {
415 if choice.agent == .server {
416 return try await CoachMCP.toolkit(endpoint: UserDefaults.standard.string(forKey: CoachMCP.preference) ?? "",
417 tool: tool, input: input, prompt: prompt)
418 }
419 let context = String(decoding: (try? JSONSerialization.data(withJSONObject: input)) ?? Data(), as: UTF8.self)
420 let text = try await CoachAgentRunner.run(choice, instructions: tool.instructions + "\nReply with only a JSON object shaped like " + tool.replyShape,
421 prompt: prompt + "\nInput: " + context)
422 guard let object = CoachAgentRunner.jsonObject(text) else {
423 throw CoachAgentFailure(message: "\(choice.agent.title) didn’t return a readable result.")
424 }
425 return object
426 }
427 }
428
429 /// A short round trip for Settings → Coach → Test Coach.
430 static func test(_ choice: CoachAgentChoice) async throws -> String {
431 let reply = try await reply(choice, prompt: "This is a connection check. Set answer to \"Ready\" and recommendation to \"none\".")
432 return (CoachAgentLog.lastSuccessDetail ?? choice.title) + ": “\(reply.answer.prefix(60))”"
433 }
434
435 /// Runs one Test Coach round trip and exits with its result, so support can check an agent headlessly.
436 static func runTestCommand(_ arguments: [String]) {
437 guard let agent = arguments.first.flatMap(CoachAgent.init(rawValue:)), agent.isLocalAgent else {
438 print("Usage: Glimmer --test-coach claude|codex|gemini [model] [effort]")
439 exit(2)
440 }
441 let choice = CoachAgentChoice(agent: agent, model: arguments.count > 1 ? arguments[1] : "",
442 effort: arguments.count > 2 ? arguments[2] : "", timeout: 120)
443 Task {
444 do {
445 print(try await test(choice))
446 exit(0)
447 } catch {
448 print("Failed: \(error.localizedDescription)")
449 exit(1)
450 }
451 }
452 dispatchMain()
453 }
454
455 private static func logged<T>(_ choice: CoachAgentChoice, _ operation: () async throws -> T) async throws -> T {
456 let start = ContinuousClock.now
457 do {
458 let value = try await operation()
459 let elapsed = (ContinuousClock.now - start).components
460 CoachAgentLog.success(choice, seconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18)
461 return value
462 } catch {
463 if !(error is CancellationError) { CoachAgentLog.failure(choice, error) }
464 throw error
465 }
466 }
467}
468#endif