Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

Hermes Agent support (#288)

Louis595092bbae07
diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstrings
index 187c2cc5..17ebfe25 100644
--- a/NotchBuddy/Resources/Localizable.xcstrings
+++ b/NotchBuddy/Resources/Localizable.xcstrings
@@ -12545,6 +12545,327 @@
}
}
},
+ "plugin.hermes.title": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "ملحق Hermes"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes প্লাগইন"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes Agent"
+ }
+ }
+ }
+ },
+ "plugin.hermes.installed": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ ملحق Hermes مثبَّت في ~/.hermes/plugins/coucou/"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes প্লাগইন ~/.hermes/plugins/coucou/-এ ইনস্টল হয়েছে"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes plugin installed in ~/.hermes/plugins/coucou/"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin de Hermes instalado en ~/.hermes/plugins/coucou/"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin Hermes installé dans ~/.hermes/plugins/coucou/"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes प्लगइन ~/.hermes/plugins/coucou/ में इंस्टॉल हुआ"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin Hermes terpasang di ~/.hermes/plugins/coucou/"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin do Hermes instalado em ~/.hermes/plugins/coucou/"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Плагин Hermes установлен в ~/.hermes/plugins/coucou/"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes 插件已安装至 ~/.hermes/plugins/coucou/"
+ }
+ }
+ }
+ },
+ "plugin.hermes.approvals": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "عرض طلبات الموافقة في الشريط"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "নচে অনুমোদন অনুরোধ দেখান"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Show approval requests in the notch"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mostrar solicitudes de aprobación en el notch"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Afficher les demandes d'approbation dans le notch"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "नॉच में अनुमोदन अनुरोध दिखाएं"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Tampilkan permintaan persetujuan di notch"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Mostrar solicitações de aprovação no notch"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Показывать запросы подтверждения в notch"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "在刘海中显示审批请求"
+ }
+ }
+ }
+ },
+ "plugin.hermes.approvals.enabled": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "تظهر طلبات الموافقة في الشريط. إذا لم تكن Coucou تعمل، يعود Hermes إلى طرفيته الخاصة."
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "নচে অনুমোদন অনুরোধ দেখানো হয়। Coucou না চললে Hermes তার নিজের প্রম্পটে ফলব্যাক করে।"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Approval requests appear in the notch. If Coucou is not running, Hermes falls back to its own prompt."
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Las solicitudes de aprobación aparecen en el notch. Si Coucou no está en ejecución, Hermes usa su propio prompt."
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Les demandes d'approbation s'affichent dans le notch. Si Coucou ne tourne pas, Hermes utilise son propre prompt."
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "नॉच में अनुमोदन अनुरोध दिखाए जाते हैं। यदि Coucou नहीं चल रहा तो Hermes अपने प्रॉम्प्ट पर वापस जाता है।"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Permintaan persetujuan muncul di notch. Jika Coucou tidak berjalan, Hermes menggunakan promptnya sendiri."
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Solicitações de aprovação aparecem no notch. Se Coucou não estiver em execução, Hermes usa seu próprio prompt."
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Запросы подтверждения отображаются в notch. Если Coucou не запущен, Hermes использует собственный prompt."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "审批请求显示在刘海中。若 Coucou 未运行,Hermes 将回退到其自己的提示。"
+ }
+ }
+ }
+ },
+ "plugin.hermes.approvals.disabled": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "تعالج Hermes طلبات الموافقة (الطرفية أو البوابة)."
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes অনুমোদন অনুরোধ পরিচালনা করে (টার্মিনাল বা গেটওয়ে)।"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Approval requests are handled by Hermes (terminal or gateway)."
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Las solicitudes de aprobación las gestiona Hermes (terminal o gateway)."
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Les demandes d'approbation sont gérées par Hermes (terminal ou passerelle)."
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "अनुमोदन अनुरोध Hermes द्वारा संभाले जाते हैं (टर्मिनल या गेटवे)।"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Permintaan persetujuan ditangani oleh Hermes (terminal atau gateway)."
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Solicitações de aprovação tratadas pelo Hermes (terminal ou gateway)."
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Запросы подтверждения обрабатывает Hermes (терминал или шлюз)."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "审批请求由 Hermes 处理(终端或网关)。"
+ }
+ }
+ }
+ },
+
"plugin.install": {
"localizations": {
"ar": {
@@ -16193,6 +16514,135 @@
}
}
},
+ "status.hermes-plugin-installed": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ ملحق Hermes مثبَّت"
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes প্লাগইন ইনস্টল হয়েছে"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes plugin installed"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin de Hermes instalado"
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin Hermes installé"
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes प्लगइन इंस्टॉल हुआ"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin Hermes terpasang"
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin do Hermes instalado"
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Плагин Hermes установлен"
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes 插件已安装"
+ }
+ }
+ }
+ },
+ "status.hermes-plugin-removed": {
+ "localizations": {
+ "ar": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ تمت إزالة ملحق Hermes."
+ }
+ },
+ "bn": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes প্লাগইন সরানো হয়েছে।"
+ }
+ },
+ "en": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Hermes plugin removed"
+ }
+ },
+ "es": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin de Hermes eliminado."
+ }
+ },
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin Hermes supprimé."
+ }
+ },
+ "hi": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes प्लगइन हटा दिया गया।"
+ }
+ },
+ "id": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin Hermes dihapus."
+ }
+ },
+ "pt-BR": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Plugin do Hermes removido."
+ }
+ },
+ "ru": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Плагин Hermes удалён."
+ }
+ },
+ "zh-Hans": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "✓ Hermes 插件已移除。"
+ }
+ }
+ }
+ },
+
"status.codex-hooks-installed": {
"localizations": {
"ar": {
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index 5084320c..241dbd6f 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -414,6 +414,7 @@ final class HookServer: @unchecked Sendable {
case "agent_codex": handledNote = "Handled in Codex."
case "agent_copilot": handledNote = "Handled in Copilot CLI."
case "agent_muse": handledNote = "Handled in Muse Code."
+ case "agent_hermes": handledNote = "Handled in Hermes."
default: handledNote = "Handled in VS Code."
}
var resolved = false
@@ -449,6 +450,11 @@ final class HookServer: @unchecked Sendable {
NotificationCenter.default.post(name: .checkMondayRecap, object: nil)
if state.isPresent { expandIfNeeded(to: .overview) }
SoundEngine.shared.play("work")
+ if agentId == "agent_hermes", let platform = payload["platform"] as? String,
+ !platform.isEmpty, platform != "cli" {
+ let capitalized = platform.prefix(1).uppercased() + platform.dropFirst()
+ appendStep(id: agentId, step: String(capitalized))
+ }
case "UserPromptSubmit":
activeSessionId = sessionId
@@ -590,7 +596,12 @@ final class HookServer: @unchecked Sendable {
private func upsertExternalAgent(id: String, name: String) {
let state = AppState.shared
guard state.tasks.firstIndex(where: { $0.id == id }) == nil else { return }
- let color = IslandConst.colorForProject(name)
+ let color: String
+ if let def = PillCatalog.definition(for: id) {
+ color = def.color
+ } else {
+ color = IslandConst.colorForProject(name)
+ }
let task = AgentTask(id: id, name: name, color: color, state: .idle, steps: [], source: .agent)
if let claudeIdx = state.tasks.firstIndex(where: { $0.id == "integration_claude" }) {
state.tasks.insert(task, at: claudeIdx + 1)
@@ -664,12 +675,19 @@ final class HookServer: @unchecked Sendable {
let isCodexRequest = rawAgent == "codex"
let isCopilotRequest = rawAgent == "copilot"
let isMuseRequest = rawAgent == "muse"
+ // isHermesRequest is true only when the plugin sent coucou_has_transport: true,
+ // meaning register_approval_transport is wired and Hermes will honour our choice.
+ // Without that flag the request falls through to "ask" so Hermes handles it natively.
+ let isHermesRequest = rawAgent == "hermes"
+ && UserDefaults.standard.bool(forKey: "hermesApprovalsEnabled")
+ && (payload["coucou_has_transport"] as? Bool == true)
#else
let isCodexRequest = false
let isCopilotRequest = false
let isMuseRequest = false
+ let isHermesRequest = false
#endif
- if !isCodexRequest && !isCopilotRequest && !isMuseRequest && Self.validateAgent(rawAgent) != nil {
+ if !isCodexRequest && !isCopilotRequest && !isMuseRequest && !isHermesRequest && Self.validateAgent(rawAgent) != nil {
Task.detached { [weak self] in
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
close(fd)
@@ -685,12 +703,14 @@ final class HookServer: @unchecked Sendable {
pillId = "agent_copilot"
} else if isMuseRequest {
pillId = "agent_muse"
+ } else if isHermesRequest {
+ pillId = "agent_hermes"
} else if isCursorEditor {
pillId = "agent_cursor"
} else {
pillId = "integration_claude"
}
- guard isCodexRequest || isCopilotRequest || isMuseRequest || isCursorEditor || isVSCodeEditor else {
+ guard isCodexRequest || isCopilotRequest || isMuseRequest || isHermesRequest || isCursorEditor || isVSCodeEditor else {
Task.detached { [weak self] in
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
close(fd)
@@ -756,6 +776,7 @@ final class HookServer: @unchecked Sendable {
case "agent_codex": note = "Handled in Codex."
case "agent_copilot": note = "Handled in Copilot CLI."
case "agent_muse": note = "Handled in Muse Code."
+ case "agent_hermes": note = "Handled in Hermes."
default: note = "Handled in VS Code."
}
self.dismissApprovalCard(note: note)
@@ -777,6 +798,7 @@ final class HookServer: @unchecked Sendable {
case "agent_codex": note = "Still waiting in Codex."
case "agent_copilot": note = "Still waiting in Copilot CLI."
case "agent_muse": note = "Still waiting in Muse Code."
+ case "agent_hermes": note = "Still waiting in Hermes."
default: note = "Still waiting in VS Code."
}
self.dismissApprovalCard(note: note)
@@ -2403,6 +2425,585 @@ export default function (amp: any): void {
try FileManager.default.removeItem(at: url)
}
+ // MARK: - Hermes plugin installer
+
+ private var _pendingHermesPluginContent: String?
+ private var _pendingHermesPluginFingerprint: String?
+ private var _pendingHermesConfigContent: String?
+ private var _pendingHermesConfigFingerprint: String?
+
+ static var hermesPluginDir: URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".hermes/plugins/coucou")
+ }
+ static var hermesInitPyURL: URL { hermesPluginDir.appendingPathComponent("__init__.py") }
+ static var hermesPluginYamlURL: URL { hermesPluginDir.appendingPathComponent("plugin.yaml") }
+ static var hermesConfigURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".hermes/config.yaml")
+ }
+
+ static func hermesPluginInstalled() -> Bool {
+ guard let content = try? String(contentsOf: hermesInitPyURL, encoding: .utf8) else { return false }
+ return content.contains("nb-hook") && content.contains("hermes")
+ }
+
+ /// Returns true if the installed Hermes version exposes register_approval_transport.
+ /// Runs a quick python3 import check; returns false on any error or if hermes is not installed.
+ /// Finds the `hermes` executable in PATH and common install locations.
+ private static func hermesExecutablePath() -> String? {
+ // Try PATH via `which` first
+ let which = Process()
+ which.executableURL = URL(fileURLWithPath: "/usr/bin/which")
+ which.arguments = ["hermes"]
+ let pipe = Pipe()
+ which.standardOutput = pipe
+ which.standardError = Pipe()
+ if (try? which.run()) != nil {
+ which.waitUntilExit()
+ if which.terminationStatus == 0 {
+ let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ if !out.isEmpty && FileManager.default.isExecutableFile(atPath: out) { return out }
+ }
+ }
+ // Explicit common locations
+ let home = FileManager.default.homeDirectoryForCurrentUser.path
+ for candidate in [
+ "\(home)/.local/bin/hermes",
+ "\(home)/.hermes/bin/hermes",
+ "/usr/local/bin/hermes",
+ "/opt/homebrew/bin/hermes",
+ ] {
+ if FileManager.default.isExecutableFile(atPath: candidate) { return candidate }
+ }
+ return nil
+ }
+
+ /// Reads the shebang of `executablePath` and returns the interpreter path.
+ /// Handles `#!/usr/bin/env python3` by resolving via `which`.
+ private static func interpreterFromShebang(_ executablePath: String) -> String? {
+ guard let fh = FileHandle(forReadingAtPath: executablePath) else { return nil }
+ let data = fh.readData(ofLength: 512)
+ try? fh.close()
+ guard let text = String(data: data, encoding: .utf8),
+ text.hasPrefix("#!") else { return nil }
+ let line = String(text.prefix(while: { $0 != "\n" }).dropFirst(2))
+ .trimmingCharacters(in: .whitespaces)
+ if line.hasPrefix("/usr/bin/env ") {
+ let name = String(line.dropFirst("/usr/bin/env ".count))
+ .trimmingCharacters(in: .whitespaces)
+ let task = Process(); let pipe = Pipe()
+ task.executableURL = URL(fileURLWithPath: "/usr/bin/which")
+ task.arguments = [name]; task.standardOutput = pipe; task.standardError = Pipe()
+ if (try? task.run()) != nil {
+ task.waitUntilExit()
+ let out = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)?
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
+ return out.isEmpty ? nil : out
+ }
+ return nil
+ }
+ return line.isEmpty ? nil : line
+ }
+
+ /// Returns true if the installed Hermes version exposes register_approval_transport.
+ /// Finds the hermes binary, reads its shebang to get the right interpreter (never uses
+ /// system python3), and runs an import check with a 3-second timeout.
+ /// Returns false if hermes/interpreter not found, or import fails.
+ #if !APPSTORE
+ static func hermesSupportsApprovalTransport() -> Bool {
+ guard let hermesPath = hermesExecutablePath(),
+ let pythonPath = interpreterFromShebang(hermesPath),
+ FileManager.default.isExecutableFile(atPath: pythonPath) else { return false }
+ let task = Process()
+ task.executableURL = URL(fileURLWithPath: pythonPath)
+ task.arguments = ["-c", "from hermes_cli.approval_transport import ApprovalRequest"]
+ task.standardOutput = Pipe(); task.standardError = Pipe()
+ do { try task.run() } catch { return false }
+ // Wait up to 3 seconds
+ let group = DispatchGroup(); group.enter()
+ var exited = false
+ DispatchQueue.global(qos: .background).async { task.waitUntilExit(); exited = true; group.leave() }
+ if group.wait(timeout: .now() + 3) == .timedOut { task.terminate(); return false }
+ return task.terminationStatus == 0
+ }
+ #endif
+
+ private func buildHermesInitPy() -> String {
+ let path = Self.hookScriptPath
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "'", with: "\\'")
+ return """
+# Coucou hook plugin for Hermes Agent — generated by Coucou.app
+# Session/tool events → Coucou notch (fire-and-forget, never blocks).
+# Approval transport: uses register_approval_transport when available (future Hermes),
+# falls back to pre_approval_request observer-only hook (hermes 0.15.x).
+import json, subprocess, threading
+from pathlib import Path
+
+HOOK = Path('\(path)')
+_lock = threading.Lock()
+# Maps session_id → metadata dict. Keeps correct session when multiple
+# sessions run concurrently (gateway mode). _current_session_id is kept as
+# a last-seen fallback for hooks that don't supply a session_id.
+_sessions: dict = {}
+_current_session_id = ''
+
+
+def _fire(fields: dict) -> None:
+ \"\"\"Non-blocking: spawn nb-hook and return immediately. Reaps child to avoid zombies.\"\"\"
+ def _run() -> None:
+ try:
+ p = subprocess.Popen(
+ [str(HOOK), '--agent', 'hermes'],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True, # detach from process group
+ )
+ p.stdin.write(json.dumps(fields).encode() + b'\\n')
+ p.stdin.close()
+ p.wait(timeout=5) # reap; 5s >> the 0.3s socket timeout
+ except Exception:
+ pass
+ threading.Thread(target=_run, daemon=True).start()
+
+
+def register(ctx) -> None:
+ def on_session_start(**kwargs) -> None:
+ global _current_session_id
+ sid = kwargs.get('session_id', '')
+ meta = {
+ 'model': kwargs.get('model', ''),
+ 'platform': kwargs.get('platform', 'cli') or 'cli',
+ }
+ with _lock:
+ _sessions[sid] = meta
+ _current_session_id = sid
+ _fire({'hook_event_name': 'SessionStart', 'session_id': sid, 'platform': meta['platform']})
+
+ def on_session_end(**kwargs) -> None:
+ sid = kwargs.get('session_id', '')
+ with _lock:
+ _sessions.pop(sid, None)
+ # Stop is sent by post_llm_call (which has the last assistant message).
+ # Only send StopFailure here when the session was interrupted abnormally.
+ if kwargs.get('interrupted'):
+ _fire({'hook_event_name': 'StopFailure', 'session_id': sid})
+
+ def post_llm_call(**kwargs) -> None:
+ sid = kwargs.get('session_id', '') or _current_session_id
+ response = kwargs.get('assistant_response', '')
+ _fire({
+ 'hook_event_name': 'Stop',
+ 'session_id': sid,
+ 'last_assistant_message': response,
+ })
+
+ def pre_tool_call(**kwargs) -> None:
+ sid = kwargs.get('session_id', '') or _current_session_id
+ _fire({
+ 'hook_event_name': 'PreToolUse',
+ 'session_id': sid,
+ 'tool_name': kwargs.get('tool_name', ''),
+ 'tool_input': kwargs.get('args') or {},
+ })
+
+ def post_tool_call(**kwargs) -> None:
+ sid = kwargs.get('session_id', '') or _current_session_id
+ _fire({
+ 'hook_event_name': 'PostToolUse',
+ 'session_id': sid,
+ 'tool_name': kwargs.get('tool_name', ''),
+ })
+
+ ctx.register_hook('on_session_start', on_session_start)
+ ctx.register_hook('on_session_end', on_session_end)
+ ctx.register_hook('post_llm_call', post_llm_call)
+ ctx.register_hook('pre_tool_call', pre_tool_call)
+ ctx.register_hook('post_tool_call', post_tool_call)
+
+ if hasattr(ctx, 'register_approval_transport'):
+ # Hermes version supports transport API — Coucou shows a real Allow/Deny card
+ # and returns the user's choice to Hermes.
+ def _present(request) -> object:
+ sid = (getattr(request, 'session_id', None)
+ or getattr(request, 'session_key', None)
+ or _current_session_id)
+ cmd = getattr(request, 'command', '')
+ desc = getattr(request, 'description', '')
+ timeout = getattr(request, 'timeout_seconds',
+ getattr(request, 'timeout', 30.0))
+ allowed = list(getattr(request, 'allowed_choices', ('once', 'deny')))
+
+ payload = json.dumps({
+ 'hook_event_name': 'PermissionRequest',
+ 'session_id': sid,
+ 'coucou_agent': 'hermes',
+ 'coucou_has_transport': True,
+ 'tool_name': cmd,
+ 'tool_input': {'command': cmd, 'description': desc},
+ }).encode()
+ try:
+ result = subprocess.run(
+ [str(HOOK), '--agent', 'hermes'],
+ input=payload,
+ capture_output=True,
+ timeout=max(1.0, float(timeout) - 2.0),
+ )
+ data = json.loads(result.stdout)
+ choice = data['choice']
+ if choice not in allowed:
+ raise ValueError(f'invalid choice: {choice!r}')
+ return request.respond(choice)
+ except Exception:
+ # Fall back to Hermes' native prompt on any error.
+ return request.respond('deny')
+
+ ctx.register_approval_transport('coucou', _present)
+ else:
+ # Observer-only hook (hermes 0.15.x): Hermes still controls the decision.
+ # Fire a PreToolUse-style step so the notch shows "⏳ Approval pending in Hermes"
+ # in the step list without displaying a fake Allow/Deny card.
+ def pre_approval_request(**kwargs) -> None:
+ sid = kwargs.get('session_key', '') or _current_session_id
+ _fire({
+ 'hook_event_name': 'PreToolUse',
+ 'session_id': sid,
+ 'tool_name': '⏳ Approval pending in Hermes',
+ 'tool_input': {
+ 'command': kwargs.get('command', ''),
+ 'description': kwargs.get('description', ''),
+ },
+ })
+
+ ctx.register_hook('pre_approval_request', pre_approval_request)
+"""
+ }
+
+ private static let hermesPluginYaml = """
+name: coucou
+version: "1.0"
+description: Coucou notch integration — generated by Coucou.app
+"""
+
+ /// Merges Coucou keys into a Hermes config.yaml string without touching other settings.
+ ///
+ /// Returns the merged YAML string, or nil if the file uses an unsupported structure
+ /// (flow maps `{…}`, YAML anchors `&`, multi-document `---`) that the line-level
+ /// merger cannot safely handle. Callers should surface an error with the lines
+ /// the user needs to add manually.
+ ///
+ /// Plugin enablement (plugins.enabled) is handled by the `hermes plugins enable/disable`
+ /// CLI after the plugin files are written; this function only manages security.approval.
+ static func mergedHermesConfig(_ base: String, enableApprovals: Bool) -> String? {
+ // Reject structures the simple merger cannot handle safely.
+ // Flow maps, anchors, and multi-document markers require a full YAML parser.
+ let unsafePatterns = ["{", " &", "\n---"]
+ for p in unsafePatterns where base.contains(p) {
+ return nil
+ }
+
+ var lines = base.components(separatedBy: "\n")
+
+ // Detect file indentation: look for the first indented line and count spaces.
+ let indent: Int = {
+ for line in lines {
+ let leading = line.prefix(while: { $0 == " " }).count
+ if leading > 0 && leading <= 8 { return leading }
+ }
+ return 2 // default
+ }()
+ let ind = String(repeating: " ", count: indent) // e.g. " " (2) or " " (4)
+ let ind2 = String(repeating: " ", count: indent * 2) // one extra level
+
+ // Returns the index of the first top-level section header line matching `key`.
+ // Top-level = no leading spaces, ends with `:` (optionally with trailing space/comment).
+ func topLevelIndex(key: String) -> Int? {
+ lines.firstIndex { line in
+ let t = line.trimmingCharacters(in: .whitespaces)
+ guard !line.hasPrefix(" ") && !line.hasPrefix("\t") else { return false }
+ return t == "\(key):" || t.hasPrefix("\(key):")
+ }
+ }
+
+ // Returns the range of lines that belong to a top-level section (from its header to
+ // just before the next top-level section, or the end of the array).
+ func sectionRange(from sectionIdx: Int) -> Range<Int> {
+ var end = sectionIdx + 1
+ while end < lines.count {
+ let l = lines[end]
+ // A new top-level key: not blank, not a comment, no leading whitespace
+ if !l.isEmpty && !l.hasPrefix("#") && !l.hasPrefix(" ") && !l.hasPrefix("\t") {
+ break
+ }
+ end += 1
+ }
+ return sectionIdx ..< end
+ }
+
+ // --- security.approval ---
+ let transportLine = "\(ind2)transport: coucou"
+ let fallbackLine = "\(ind2)transport_fallback: builtin"
+
+ func ensureApprovalTransport() {
+ if let secIdx = topLevelIndex(key: "security") {
+ let secRange = sectionRange(from: secIdx)
+ // Look for approval: within the security section (must be indented)
+ if let approvalIdx = (secRange.lowerBound + 1 ..< secRange.upperBound)
+ .first(where: { lines[$0].trimmingCharacters(in: .whitespaces).hasPrefix("approval:") }) {
+ // approval: block exists — update or add transport keys within it
+ let approvalRange = sectionRange(from: approvalIdx)
+ var hasTransport = false
+ var hasFallback = false
+ for i in (approvalRange.lowerBound + 1 ..< approvalRange.upperBound) {
+ let t = lines[i].trimmingCharacters(in: .whitespaces)
+ if t.hasPrefix("transport:") && !t.hasPrefix("transport_fallback") {
+ lines[i] = transportLine; hasTransport = true
+ } else if t.hasPrefix("transport_fallback:") {
+ lines[i] = fallbackLine; hasFallback = true
+ }
+ }
+ let insertAt = approvalRange.lowerBound + 1
+ if !hasFallback { lines.insert(fallbackLine, at: insertAt) }
+ if !hasTransport { lines.insert(transportLine, at: insertAt) }
+ } else {
+ // No approval: key — insert right after security:
+ let insertAt = secIdx + 1
+ lines.insert("\(ind)approval:", at: insertAt)
+ lines.insert(transportLine, at: insertAt + 1)
+ lines.insert(fallbackLine, at: insertAt + 2)
+ }
+ } else {
+ // No security: section — append
+ if lines.last != "" { lines.append("") }
+ lines.append("security:")
+ lines.append("\(ind)approval:")
+ lines.append(transportLine)
+ lines.append(fallbackLine)
+ }
+ }
+
+ func removeApprovalTransport() {
+ // Only remove exact Coucou-written transport keys; don't touch unrelated keys.
+ lines.removeAll { line in
+ let t = line.trimmingCharacters(in: .whitespaces)
+ return t == "transport: coucou" || t == "transport_fallback: builtin"
+ }
+ }
+
+ // --- plugins.enabled ---
+ // Note: actual plugin enable/disable is done via `hermes plugins enable/disable coucou`
+ // CLI after writing/removing the plugin files. This block ensures the preview
+ // shows the complete intended state of config.yaml.
+ func ensureCoucouPlugin() {
+ // "Already present" = coucou in the plugins.enabled list specifically.
+ // Check by finding plugins: section first, then enabled: sub-key within it.
+ if let pluginsIdx = topLevelIndex(key: "plugins") {
+ let pluginsRange = sectionRange(from: pluginsIdx)
+ // Find enabled: within the plugins section
+ if let enabledIdx = (pluginsRange.lowerBound + 1 ..< pluginsRange.upperBound)
+ .first(where: { lines[$0].trimmingCharacters(in: .whitespaces).hasPrefix("enabled:") }) {
+ let enabledLine = lines[enabledIdx]
+ let trimmed = enabledLine.trimmingCharacters(in: .whitespaces)
+ if trimmed.contains("[") && trimmed.contains("]") {
+ // Inline list: enabled: [x, y] or enabled: []
+ if trimmed.contains("coucou") { return } // already present
+ if trimmed == "enabled: []" || trimmed == "enabled:[]" {
+ // Empty inline list → expand to block entry
+ let prefix = enabledLine.prefix(while: { $0 == " " })
+ lines[enabledIdx] = "\(prefix)enabled:"
+ lines.insert("\(prefix)\(ind)- coucou", at: enabledIdx + 1)
+ } else {
+ lines[enabledIdx] = enabledLine.replacingOccurrences(of: "]", with: ", coucou]")
+ }
+ } else {
+ // Block list — check if coucou is already a child of this enabled:
+ let enabledRange = sectionRange(from: enabledIdx)
+ let alreadyPresent = (enabledRange.lowerBound + 1 ..< enabledRange.upperBound)
+ .contains { lines[$0].trimmingCharacters(in: .whitespaces) == "- coucou" }
+ if alreadyPresent { return }
+ // Insert after enabled:
+ let prefix = enabledLine.prefix(while: { $0 == " " })
+ lines.insert("\(prefix)\(ind)- coucou", at: enabledIdx + 1)
+ }
+ } else {
+ // No enabled: key under plugins: — insert after plugins:
+ lines.insert("\(ind)enabled:", at: pluginsIdx + 1)
+ lines.insert("\(ind)\(ind)- coucou", at: pluginsIdx + 2)
+ }
+ } else {
+ // No plugins: section — append
+ if lines.last != "" { lines.append("") }
+ lines.append("plugins:")
+ lines.append("\(ind)enabled:")
+ lines.append("\(ind)\(ind)- coucou")
+ }
+ }
+
+ func removeCoucouPlugin() {
+ // Remove the `- coucou` entry from plugins.enabled only.
+ // If that leaves enabled: with no entries, leave the key in place (don't remove it).
+ guard let pluginsIdx = topLevelIndex(key: "plugins") else { return }
+ let pluginsRange = sectionRange(from: pluginsIdx)
+ guard let enabledIdx = (pluginsRange.lowerBound + 1 ..< pluginsRange.upperBound)
+ .first(where: { lines[$0].trimmingCharacters(in: .whitespaces).hasPrefix("enabled:") })
+ else { return }
+ let enabledLine = lines[enabledIdx]
+ let trimmed = enabledLine.trimmingCharacters(in: .whitespaces)
+ if trimmed.contains("[") && trimmed.contains("]") {
+ // Inline list: remove coucou from it
+ let cleaned = trimmed
+ .replacingOccurrences(of: ", coucou", with: "")
+ .replacingOccurrences(of: "coucou, ", with: "")
+ .replacingOccurrences(of: "coucou", with: "")
+ let prefix = enabledLine.prefix(while: { $0 == " " })
+ lines[enabledIdx] = "\(prefix)\(cleaned)"
+ } else {
+ // Block list: remove the `- coucou` entry
+ let enabledRange = sectionRange(from: enabledIdx)
+ // Collect indices to remove first, then remove in reverse to preserve indices.
+ let toRemove = (enabledRange.lowerBound + 1 ..< enabledRange.upperBound)
+ .filter { lines[$0].trimmingCharacters(in: .whitespaces) == "- coucou" }
+ for i in toRemove.reversed() { lines.remove(at: i) }
+ }
+ }
+
+ ensureCoucouPlugin()
+ if enableApprovals { ensureApprovalTransport() } else { removeApprovalTransport() }
+ return lines.joined(separator: "\n")
+ }
+
+ func previewHermesPlugin(install: Bool) throws -> String {
+ if !install {
+ guard FileManager.default.fileExists(atPath: Self.hermesInitPyURL.path) else {
+ throw NSError(domain: "CoucouNoop", code: 0, userInfo: [
+ NSLocalizedDescriptionKey: "No Hermes plugin to remove."
+ ])
+ }
+ let current = (try? Data(contentsOf: Self.hermesInitPyURL)) ?? Data()
+ _pendingHermesPluginFingerprint = sha256Hex(current)
+ _pendingHermesPluginContent = nil
+ return "(will delete \(Self.hermesInitPyURL.path))"
+ }
+ let current = (try? Data(contentsOf: Self.hermesInitPyURL)) ?? Data()
+ _pendingHermesPluginFingerprint = sha256Hex(current)
+ let content = buildHermesInitPy()
+ _pendingHermesPluginContent = content
+ return content
+ }
+
+ func writeHermesPlugin() throws {
+ guard let fp = _pendingHermesPluginFingerprint else { return }
+ let url = Self.hermesInitPyURL
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ guard sha256Hex(current) == fp else {
+ throw NSError(domain: "Coucou", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "~/.hermes/plugins/coucou/__init__.py changed since preview. Refresh and try again."
+ ])
+ }
+ let fm = FileManager.default
+ if let content = _pendingHermesPluginContent {
+ try fm.createDirectory(at: Self.hermesPluginDir, withIntermediateDirectories: true)
+ if fm.fileExists(atPath: url.path) {
+ let fmt = DateFormatter()
+ fmt.locale = Locale(identifier: "en_US_POSIX")
+ fmt.dateFormat = "yyyyMMdd-HHmmss"
+ let bak = url.deletingLastPathComponent()
+ .appendingPathComponent("__init__.py.bak-\(fmt.string(from: Date()))")
+ try fm.copyItem(at: url, to: bak)
+ }
+ try content.write(to: url, atomically: true, encoding: .utf8)
+ try Self.hermesPluginYaml.write(to: Self.hermesPluginYamlURL, atomically: true, encoding: .utf8)
+ // Register the plugin with the Hermes CLI so it appears in plugins.enabled.
+ // Best-effort — silently ignored if hermes is not on PATH.
+ try? Self.runHermesCLI(["plugins", "enable", "coucou"])
+ }
+ _pendingHermesPluginContent = nil
+ _pendingHermesPluginFingerprint = nil
+ }
+
+ func removeHermesPlugin() throws {
+ let url = Self.hermesInitPyURL
+ guard FileManager.default.fileExists(atPath: url.path) else { return }
+ let content = (try? String(contentsOf: url, encoding: .utf8)) ?? ""
+ guard content.contains("generated by Coucou") else {
+ throw NSError(domain: "Coucou", code: 3, userInfo: [
+ NSLocalizedDescriptionKey: "~/.hermes/plugins/coucou/__init__.py was not generated by Coucou — not deleting it."
+ ])
+ }
+ // Remove from hermes plugins.enabled first, then delete the files.
+ // Best-effort — silently ignored if hermes is not on PATH.
+ try? Self.runHermesCLI(["plugins", "disable", "coucou"])
+ try FileManager.default.removeItem(at: Self.hermesPluginDir)
+ }
+
+ /// Invoke the Hermes CLI with the given arguments.
+ /// Searches standard PATH locations for the `hermes` binary.
+ @discardableResult
+ private static func runHermesCLI(_ args: [String]) throws -> String {
+ let hermesPaths = [
+ "/opt/homebrew/bin/hermes",
+ "/usr/local/bin/hermes",
+ "/usr/bin/hermes",
+ (ProcessInfo.processInfo.environment["HOME"] ?? "") + "/.local/bin/hermes",
+ ]
+ guard let hermesBin = hermesPaths.first(where: { FileManager.default.fileExists(atPath: $0) }) else {
+ throw NSError(domain: "CoucouNoop", code: 0, userInfo: [
+ NSLocalizedDescriptionKey: "hermes CLI not found."
+ ])
+ }
+ let proc = Process()
+ proc.executableURL = URL(fileURLWithPath: hermesBin)
+ proc.arguments = args
+ let out = Pipe()
+ proc.standardOutput = out
+ proc.standardError = Pipe() // discard stderr
+ try proc.run()
+ proc.waitUntilExit()
+ return String(data: out.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
+ }
+
+ func previewHermesConfig(enableApprovals: Bool, supportsTransport: Bool) throws -> String {
+ let base = (try? String(contentsOf: Self.hermesConfigURL, encoding: .utf8)) ?? ""
+ let current = (try? Data(contentsOf: Self.hermesConfigURL)) ?? Data()
+ _pendingHermesConfigFingerprint = sha256Hex(current)
+ let effectiveApprovals = enableApprovals && supportsTransport
+ guard let merged = Self.mergedHermesConfig(base, enableApprovals: effectiveApprovals) else {
+ _pendingHermesConfigContent = nil
+ throw NSError(domain: "Coucou", code: 4, userInfo: [
+ NSLocalizedDescriptionKey: "~/.hermes/config.yaml uses an unsupported structure (flow maps, YAML anchors, or multi-document). Edit it manually and add:\n security:\n approval:\n transport: coucou\n transport_fallback: builtin"
+ ])
+ }
+ _pendingHermesConfigContent = merged
+ return merged
+ }
+
+ func writeHermesConfig() throws {
+ guard let fp = _pendingHermesConfigFingerprint,
+ let content = _pendingHermesConfigContent else { return }
+ let url = Self.hermesConfigURL
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ guard sha256Hex(current) == fp else {
+ throw NSError(domain: "Coucou", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "~/.hermes/config.yaml changed since preview. Refresh and try again."
+ ])
+ }
+ let fm = FileManager.default
+ if fm.fileExists(atPath: url.path) {
+ let fmt = DateFormatter()
+ fmt.locale = Locale(identifier: "en_US_POSIX")
+ fmt.dateFormat = "yyyyMMdd-HHmmss"
+ let bak = url.deletingLastPathComponent()
+ .appendingPathComponent("config.yaml.bak-\(fmt.string(from: Date()))")
+ try fm.copyItem(at: url, to: bak)
+ }
+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try content.write(to: url, atomically: true, encoding: .utf8)
+ _pendingHermesConfigContent = nil
+ _pendingHermesConfigFingerprint = nil
+ }
+
// MARK: SHA-256 fingerprint
private func sha256Hex(_ data: Data) -> String {
@@ -2687,6 +3288,12 @@ def main():
decision = resp_obj.get('permissionDecision', '')
except Exception:
decision = ''
+ if agent == 'hermes':
+ hermes_choice = 'once' if decision == 'allow' else decision
+ if hermes_choice in ('once', 'always', 'deny'):
+ sys.stdout.write(json.dumps({'choice': hermes_choice}) + '\\n')
+ sys.stdout.flush()
+ sys.exit(0)
if decision in ('allow', 'always'):
# Copilot/Muse use {"permissionDecision":"allow"} directly
if agent in ('copilot', 'muse'):
@@ -2722,6 +3329,7 @@ def main():
pass
# App unreachable, timed out, or no explicit decision — print nothing
# Copilot is fail-closed: must always output valid JSON so it re-asks rather than deny
+ # Hermes: no output → json.loads raises in plugin → transport_fallback: builtin activates
if agent == 'copilot':
sys.stdout.write('{"permissionDecision":"ask"}\\n')
sys.stdout.flush()
@@ -2978,6 +3586,12 @@ def main():
decision = resp_obj.get('permissionDecision', '')
except Exception:
decision = ''
+ if agent == 'hermes':
+ hermes_choice = 'once' if decision == 'allow' else decision
+ if hermes_choice in ('once', 'always', 'deny'):
+ sys.stdout.write(json.dumps({'choice': hermes_choice}) + '\\n')
+ sys.stdout.flush()
+ sys.exit(0)
if decision in ('allow', 'always'):
# Copilot/Muse use {"permissionDecision":"allow"} directly
if agent in ('copilot', 'muse'):
@@ -3013,6 +3627,7 @@ def main():
pass
# App unreachable, timed out, or no explicit decision — print nothing
# Copilot is fail-closed: must always output valid JSON so it re-asks rather than deny
+ # Hermes: no output → json.loads raises in plugin → transport_fallback: builtin activates
if agent == 'copilot':
sys.stdout.write('{"permissionDecision":"ask"}\\n')
sys.stdout.flush()
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
index 5fea56ff..403fbaf6 100644
--- a/NotchBuddy/Sources/App/SettingsView.swift
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -73,6 +73,16 @@ struct SettingsView: View {
@State private var showAmpDiff: Bool = false
@State private var pendingAmpContent: String = ""
@State private var ampPendingInstall: Bool = true
+
+ @State private var hermesPluginInstalled: Bool = HookServer.hermesPluginInstalled()
+ @State private var showHermesPluginDiff: Bool = false
+ @State private var pendingHermesPluginContent: String = ""
+ @State private var hermesPluginPendingInstall: Bool = true
+
+ @State private var showHermesConfigDiff: Bool = false
+ @State private var pendingHermesConfigContent: String = ""
+ @AppStorage("hermesApprovalsEnabled") private var hermesApprovalsEnabled: Bool = false
+ @State private var hermesSupportsApprovals: Bool = false
#endif
// Multi-provider chat keys
@@ -758,6 +768,87 @@ struct SettingsView: View {
.padding(6)
}
+ GroupBox(String(localized: "plugin.hermes.title")) {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(hermesPluginInstalled
+ ? String(localized: "plugin.hermes.installed")
+ : "~/.hermes/plugins/coucou/__init__.py")
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundColor(.secondary)
+ HStack(spacing: 10) {
+ if !hermesPluginInstalled {
+ Button(String(localized: "plugin.install")) { triggerHermesPluginPreview(install: true) }
+ .buttonStyle(.borderedProminent)
+ } else {
+ Button(String(localized: "hooks.uninstall")) { triggerHermesPluginPreview(install: false) }
+ .buttonStyle(.bordered)
+ }
+ }
+ if showHermesPluginDiff {
+ ScrollView {
+ Text(pendingHermesPluginContent)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 180)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+ HStack {
+ Button(String(localized: "hooks.confirm-write")) { confirmHermesPluginOp() }
+ .buttonStyle(.borderedProminent)
+ Button(String(localized: "Cancel")) { showHermesPluginDiff = false; pendingHermesPluginContent = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+
+ if hermesPluginInstalled {
+ Divider()
+ Toggle(String(localized: "plugin.hermes.approvals"), isOn: $hermesApprovalsEnabled)
+ .onChange(of: hermesApprovalsEnabled) { _, _ in triggerHermesConfigPreview() }
+ .disabled(!hermesSupportsApprovals)
+ if !hermesSupportsApprovals {
+ Text("Requires a newer version of Hermes — run: hermes update")
+ .font(.caption)
+ .foregroundColor(.orange)
+ .fixedSize(horizontal: false, vertical: true)
+ } else {
+ Text(hermesApprovalsEnabled
+ ? String(localized: "plugin.hermes.approvals.enabled")
+ : String(localized: "plugin.hermes.approvals.disabled"))
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+ if showHermesConfigDiff {
+ ScrollView {
+ Text(pendingHermesConfigContent)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 120)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+ HStack {
+ Button(String(localized: "hooks.confirm-write")) { confirmHermesConfigOp() }
+ .buttonStyle(.borderedProminent)
+ Button(String(localized: "Cancel")) { showHermesConfigDiff = false; pendingHermesConfigContent = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ }
+ .padding(6)
+ }
+ #if !APPSTORE
+ .task(id: hermesPluginInstalled) {
+ guard hermesPluginInstalled else { hermesSupportsApprovals = false; return }
+ let result = await Task.detached(priority: .background) {
+ HookServer.hermesSupportsApprovalTransport()
+ }.value
+ await MainActor.run { hermesSupportsApprovals = result }
+ }
+ #endif
+
GroupBox(String(localized: "plan.title")) {
VStack(alignment: .leading, spacing: 10) {
Text(String(localized: "plan.description"))
@@ -1413,6 +1504,58 @@ struct SettingsView: View {
}
}
+ private func triggerHermesPluginPreview(install: Bool) {
+ do {
+ hermesPluginPendingInstall = install
+ pendingHermesPluginContent = try HookServer.shared.previewHermesPlugin(install: install)
+ showHermesPluginDiff = true
+ statusMessage = String(localized: "plugin.review-content")
+ } catch let e as NSError where e.domain == "CoucouNoop" {
+ statusMessage = e.localizedDescription
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmHermesPluginOp() {
+ do {
+ if hermesPluginPendingInstall {
+ try HookServer.shared.writeHermesPlugin()
+ } else {
+ try HookServer.shared.removeHermesPlugin()
+ }
+ showHermesPluginDiff = false
+ pendingHermesPluginContent = ""
+ hermesPluginInstalled = hermesPluginPendingInstall
+ statusMessage = hermesPluginPendingInstall
+ ? String(localized: "status.hermes-plugin-installed")
+ : String(localized: "status.hermes-plugin-removed")
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func triggerHermesConfigPreview() {
+ do {
+ pendingHermesConfigContent = try HookServer.shared.previewHermesConfig(
+ enableApprovals: hermesApprovalsEnabled,
+ supportsTransport: hermesSupportsApprovals)
+ showHermesConfigDiff = true
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmHermesConfigOp() {
+ do {
+ try HookServer.shared.writeHermesConfig()
+ showHermesConfigDiff = false
+ pendingHermesConfigContent = ""
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
private func installStatusLine() {
do {
pendingStatusLineJSON = try HookServer.shared.previewStatusLine(install: true)
diff --git a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift b/NotchBuddy/Sources/CoucouKit/PillCatalog.swift
index 3f61225c..e7e200de 100644
--- a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift
+++ b/NotchBuddy/Sources/CoucouKit/PillCatalog.swift
@@ -37,6 +37,7 @@ struct PillDefinition {
case "integration_claude": return "Claude Code"
case "agent_cursor": return "Cursor"
case "agent_codex": return "Codex"
+ case "agent_hermes": return "Hermes"
default: return "Agent"
}
}
@@ -67,6 +68,8 @@ enum PillCatalog {
category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
.init(id: "agent_amp", name: "Amp", color: "#F59E0B",
category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
+ .init(id: "agent_hermes", name: "Hermes", color: "#C084FC",
+ category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
// ── AI for the chat ──────────────────────────────────────────────────
.init(id: "ai_anthropic", name: "Anthropic", color: ChatProvider.anthropic.accentHex,
category: .ai, subtitle: "Chat", source: .n8n),
diff --git a/NotchBuddy/Tests/HermesConfigMergerTests.swift b/NotchBuddy/Tests/HermesConfigMergerTests.swift
new file mode 100644
index 00000000..5f2ec575
--- /dev/null
+++ b/NotchBuddy/Tests/HermesConfigMergerTests.swift
@@ -0,0 +1,361 @@
+#!/usr/bin/swift
+// HermesConfigMergerTests.swift — standalone test script for mergedHermesConfig.
+// Run from repo root:
+// swift NotchBuddy/Tests/HermesConfigMergerTests.swift
+//
+// Requires pyyaml: pip3 install pyyaml
+// Each merged output is validated as valid YAML via python3.
+
+import Foundation
+
+// ── Copy of mergedHermesConfig from HookServer.swift ─────────────────────────
+// Keep in sync with HookServer.swift mergedHermesConfig(_:enableApprovals:).
+func mergedHermesConfig(_ base: String, enableApprovals: Bool) -> String? {
+ let unsafePatterns = ["{", " &", "\n---"]
+ for p in unsafePatterns where base.contains(p) {
+ return nil
+ }
+
+ var lines = base.components(separatedBy: "\n")
+
+ let indent: Int = {
+ for line in lines {
+ let leading = line.prefix(while: { $0 == " " }).count
+ if leading > 0 && leading <= 8 { return leading }
+ }
+ return 2
+ }()
+ let ind = String(repeating: " ", count: indent)
+ let ind2 = String(repeating: " ", count: indent * 2)
+
+ func topLevelIndex(key: String) -> Int? {
+ lines.firstIndex { line in
+ let t = line.trimmingCharacters(in: .whitespaces)
+ guard !line.hasPrefix(" ") && !line.hasPrefix("\t") else { return false }
+ return t == "\(key):" || t.hasPrefix("\(key):")
+ }
+ }
+
+ func sectionRange(from sectionIdx: Int) -> Range<Int> {
+ var end = sectionIdx + 1
+ while end < lines.count {
+ let l = lines[end]
+ if !l.isEmpty && !l.hasPrefix("#") && !l.hasPrefix(" ") && !l.hasPrefix("\t") {
+ break
+ }
+ end += 1
+ }
+ return sectionIdx ..< end
+ }
+
+ let transportLine = "\(ind2)transport: coucou"
+ let fallbackLine = "\(ind2)transport_fallback: builtin"
+
+ func ensureApprovalTransport() {
+ if let secIdx = topLevelIndex(key: "security") {
+ let secRange = sectionRange(from: secIdx)
+ if let approvalIdx = (secRange.lowerBound + 1 ..< secRange.upperBound)
+ .first(where: { lines[$0].trimmingCharacters(in: .whitespaces).hasPrefix("approval:") }) {
+ let approvalRange = sectionRange(from: approvalIdx)
+ var hasTransport = false
+ var hasFallback = false
+ for i in (approvalRange.lowerBound + 1 ..< approvalRange.upperBound) {
+ let t = lines[i].trimmingCharacters(in: .whitespaces)
+ if t.hasPrefix("transport:") && !t.hasPrefix("transport_fallback") {
+ lines[i] = transportLine; hasTransport = true
+ } else if t.hasPrefix("transport_fallback:") {
+ lines[i] = fallbackLine; hasFallback = true
+ }
+ }
+ let insertAt = approvalRange.lowerBound + 1
+ if !hasFallback { lines.insert(fallbackLine, at: insertAt) }
+ if !hasTransport { lines.insert(transportLine, at: insertAt) }
+ } else {
+ let insertAt = secIdx + 1
+ lines.insert("\(ind)approval:", at: insertAt)
+ lines.insert(transportLine, at: insertAt + 1)
+ lines.insert(fallbackLine, at: insertAt + 2)
+ }
+ } else {
+ if lines.last != "" { lines.append("") }
+ lines.append("security:")
+ lines.append("\(ind)approval:")
+ lines.append(transportLine)
+ lines.append(fallbackLine)
+ }
+ }
+
+ func removeApprovalTransport() {
+ lines.removeAll { line in
+ let t = line.trimmingCharacters(in: .whitespaces)
+ return t == "transport: coucou" || t == "transport_fallback: builtin"
+ }
+ }
+
+ func ensureCoucouPlugin() {
+ if let pluginsIdx = topLevelIndex(key: "plugins") {
+ let pluginsRange = sectionRange(from: pluginsIdx)
+ if let enabledIdx = (pluginsRange.lowerBound + 1 ..< pluginsRange.upperBound)
+ .first(where: { lines[$0].trimmingCharacters(in: .whitespaces).hasPrefix("enabled:") }) {
+ let enabledLine = lines[enabledIdx]
+ let trimmed = enabledLine.trimmingCharacters(in: .whitespaces)
+ if trimmed.contains("[") && trimmed.contains("]") {
+ if trimmed.contains("coucou") { return }
+ if trimmed == "enabled: []" || trimmed == "enabled:[]" {
+ let prefix = enabledLine.prefix(while: { $0 == " " })
+ lines[enabledIdx] = "\(prefix)enabled:"
+ lines.insert("\(prefix)\(ind)- coucou", at: enabledIdx + 1)
+ } else {
+ lines[enabledIdx] = enabledLine.replacingOccurrences(of: "]", with: ", coucou]")
+ }
+ } else {
+ let enabledRange = sectionRange(from: enabledIdx)
+ let alreadyPresent = (enabledRange.lowerBound + 1 ..< enabledRange.upperBound)
+ .contains { lines[$0].trimmingCharacters(in: .whitespaces) == "- coucou" }
+ if alreadyPresent { return }
+ let prefix = enabledLine.prefix(while: { $0 == " " })
+ lines.insert("\(prefix)\(ind)- coucou", at: enabledIdx + 1)
+ }
+ } else {
+ lines.insert("\(ind)enabled:", at: pluginsIdx + 1)
+ lines.insert("\(ind)\(ind)- coucou", at: pluginsIdx + 2)
+ }
+ } else {
+ if lines.last != "" { lines.append("") }
+ lines.append("plugins:")
+ lines.append("\(ind)enabled:")
+ lines.append("\(ind)\(ind)- coucou")
+ }
+ }
+
+ func removeCoucouPlugin() {
+ guard let pluginsIdx = topLevelIndex(key: "plugins") else { return }
+ let pluginsRange = sectionRange(from: pluginsIdx)
+ guard let enabledIdx = (pluginsRange.lowerBound + 1 ..< pluginsRange.upperBound)
+ .first(where: { lines[$0].trimmingCharacters(in: .whitespaces).hasPrefix("enabled:") })
+ else { return }
+ let enabledLine = lines[enabledIdx]
+ let trimmed = enabledLine.trimmingCharacters(in: .whitespaces)
+ if trimmed.contains("[") && trimmed.contains("]") {
+ let cleaned = trimmed
+ .replacingOccurrences(of: ", coucou", with: "")
+ .replacingOccurrences(of: "coucou, ", with: "")
+ .replacingOccurrences(of: "coucou", with: "")
+ let prefix = enabledLine.prefix(while: { $0 == " " })
+ lines[enabledIdx] = "\(prefix)\(cleaned)"
+ } else {
+ let enabledRange = sectionRange(from: enabledIdx)
+ let toRemove = (enabledRange.lowerBound + 1 ..< enabledRange.upperBound)
+ .filter { lines[$0].trimmingCharacters(in: .whitespaces) == "- coucou" }
+ for i in toRemove.reversed() { lines.remove(at: i) }
+ }
+ }
+
+ ensureCoucouPlugin()
+ if enableApprovals { ensureApprovalTransport() } else { removeApprovalTransport() }
+ return lines.joined(separator: "\n")
+}
+
+// ── Test harness ─────────────────────────────────────────────────────────────
+
+var passed = 0
+var failed = 0
+
+/// Find a Python3 that has pyyaml installed.
+func findPython3() -> String {
+ let candidates = [
+ "/opt/homebrew/bin/python3",
+ "/usr/local/bin/python3",
+ "/usr/bin/python3",
+ ]
+ for p in candidates {
+ let proc = Process()
+ proc.executableURL = URL(fileURLWithPath: p)
+ proc.arguments = ["-c", "import yaml"]
+ proc.standardOutput = Pipe(); proc.standardError = Pipe()
+ if (try? proc.run()) != nil {
+ proc.waitUntilExit()
+ if proc.terminationStatus == 0 { return p }
+ }
+ }
+ return "/usr/bin/python3" // fallback
+}
+
+let pythonBin = findPython3()
+
+func isValidYAML(_ s: String) -> Bool {
+ let proc = Process()
+ proc.executableURL = URL(fileURLWithPath: pythonBin)
+ proc.arguments = ["-c", "import yaml,sys; yaml.safe_load(sys.stdin)"]
+ let inPipe = Pipe(); let errPipe = Pipe()
+ proc.standardInput = inPipe
+ proc.standardError = errPipe
+ proc.standardOutput = Pipe()
+ try? proc.run()
+ inPipe.fileHandleForWriting.write(s.data(using: .utf8)!)
+ inPipe.fileHandleForWriting.closeFile()
+ proc.waitUntilExit()
+ return proc.terminationStatus == 0
+}
+
+func check(_ name: String, _ result: String?, contains: [String] = [], notContains: [String] = [],
+ expectNil: Bool = false) {
+ if expectNil {
+ if result == nil {
+ print(" PASS \(name)")
+ passed += 1
+ } else {
+ print(" FAIL \(name): expected nil but got a string")
+ failed += 1
+ }
+ return
+ }
+ guard let r = result else {
+ print(" FAIL \(name): got nil unexpectedly")
+ failed += 1
+ return
+ }
+ guard isValidYAML(r) else {
+ print(" FAIL \(name): result is not valid YAML\n---\n\(r)\n---")
+ failed += 1
+ return
+ }
+ for c in contains {
+ guard r.contains(c) else {
+ print(" FAIL \(name): missing \(c.debugDescription)\n---\n\(r)\n---")
+ failed += 1
+ return
+ }
+ }
+ for nc in notContains {
+ guard !r.contains(nc) else {
+ print(" FAIL \(name): should not contain \(nc.debugDescription)\n---\n\(r)\n---")
+ failed += 1
+ return
+ }
+ }
+ print(" PASS \(name)")
+ passed += 1
+}
+
+print("HermesConfigMergerTests")
+print("=======================")
+
+// 1. Empty file → adds plugins.enabled.coucou
+check("1. empty file → adds plugins/enabled/coucou",
+ mergedHermesConfig("", enableApprovals: false),
+ contains: ["plugins:", "enabled:", "- coucou"])
+
+// 2. plugins: exists but no enabled: → adds enabled with coucou
+check("2. plugins without enabled → adds enabled/coucou",
+ mergedHermesConfig("plugins:\n disabled: []\n", enableApprovals: false),
+ contains: ["enabled:", "- coucou"])
+
+// 3. plugins.enabled with other item → adds coucou
+check("3. plugins.enabled other items → adds coucou",
+ mergedHermesConfig("plugins:\n enabled:\n - other\n", enableApprovals: false),
+ contains: ["- other", "- coucou"])
+
+// 4. coucou already in plugins.enabled → no duplicate
+let case4 = mergedHermesConfig("plugins:\n enabled:\n - coucou\n", enableApprovals: false)
+check("4. coucou already present → no duplicate",
+ case4,
+ contains: ["- coucou"],
+ notContains: [])
+// Verify only one occurrence of "- coucou"
+if let r4 = case4 {
+ let count = r4.components(separatedBy: "- coucou").count - 1
+ if count == 1 { print(" PASS 4b. no duplicate coucou entry"); passed += 1 }
+ else { print(" FAIL 4b. got \(count) coucou entries"); failed += 1 }
+}
+
+// 5. enabled: [] (empty inline list) → expands to block list with coucou
+check("5. enabled: [] → expands to block with coucou",
+ mergedHermesConfig("plugins:\n enabled: []\n", enableApprovals: false),
+ contains: ["- coucou"],
+ notContains: ["enabled: []"])
+
+// 6. enabled: [other] inline list → adds coucou to inline list
+check("6. enabled: [other] inline → adds coucou",
+ mergedHermesConfig("plugins:\n enabled: [other]\n", enableApprovals: false),
+ contains: ["coucou"])
+
+// 7. Another section with its own enabled: key → only modifies under plugins:
+let case7 = """
+features:
+ enabled: [x]
+plugins:
+ enabled:
+ - existing
+"""
+check("7. another section's enabled: not modified",
+ mergedHermesConfig(case7, enableApprovals: false),
+ contains: ["features:", "enabled: [x]", "- coucou"])
+
+// 8. coucou in disabled: → still adds to enabled:
+check("8. coucou in disabled → also adds to enabled",
+ mergedHermesConfig("plugins:\n disabled:\n - coucou\n enabled:\n - other\n", enableApprovals: false),
+ contains: ["- coucou", "- other"])
+
+// 9. security: without approval: → adds approval with transport keys
+check("9. security without approval → adds transport keys",
+ mergedHermesConfig("security:\n allow_private_urls: false\n", enableApprovals: true),
+ contains: ["approval:", "transport: coucou", "transport_fallback: builtin"])
+
+// 10a. Uninstall: removes - coucou from enabled
+let case10a = """
+plugins:
+ enabled:
+ - coucou
+ - other
+security:
+ approval:
+ transport: coucou
+ transport_fallback: builtin
+"""
+check("10a. uninstall: removes coucou from enabled, transport keys",
+ mergedHermesConfig(case10a, enableApprovals: false),
+ notContains: ["transport: coucou", "transport_fallback: builtin"])
+
+// 10b. After uninstall (disable approvals), transport keys removed
+check("10b. disable approvals: transport keys removed",
+ mergedHermesConfig("security:\n approval:\n transport: coucou\n transport_fallback: builtin\n",
+ enableApprovals: false),
+ notContains: ["transport: coucou", "transport_fallback: builtin"])
+
+// 11. Flow map → returns nil
+check("11. flow map { } → returns nil",
+ mergedHermesConfig("{plugins: {enabled: [coucou]}}", enableApprovals: false),
+ expectNil: true)
+
+// 12. 4-space indentation → uses 4 spaces
+let base12 = """
+model: gpt-4
+plugins:
+ enabled:
+ - other
+"""
+check("12. 4-space indent → uses 4 spaces",
+ mergedHermesConfig(base12, enableApprovals: false),
+ contains: [" - coucou"]) // 8 spaces = 2 levels of 4
+
+// 13. Enable approvals: adds both transport keys
+check("13. enableApprovals=true adds both transport keys",
+ mergedHermesConfig("", enableApprovals: true),
+ contains: ["transport: coucou", "transport_fallback: builtin"])
+
+// 14. security.approval already has transport → update, not duplicate
+let case14 = """
+security:
+ approval:
+ transport: terminal
+ transport_fallback: deny
+"""
+check("14. existing transport → updated, no duplicate",
+ mergedHermesConfig(case14, enableApprovals: true),
+ contains: ["transport: coucou", "transport_fallback: builtin"],
+ notContains: ["transport: terminal", "transport_fallback: deny"])
+
+print("")
+print("Results: \(passed) passed, \(failed) failed")
+exit(failed > 0 ? 1 : 0)