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.

More agents: Copilot CLI, Muse Code, OpenCode, Amp (#263)

Louisec1a4f269344
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index 26dde14c..0837f95d 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -387,9 +387,11 @@ final class HookServer: @unchecked Sendable {
if let pending = state.pendingApproval, agentId == pending.pillId {
let handledNote: String
switch pending.pillId {
- case "agent_cursor": handledNote = "Handled in Cursor."
- case "agent_codex": handledNote = "Handled in Codex."
- default: handledNote = "Handled in VS Code."
+ case "agent_cursor": handledNote = "Handled in Cursor."
+ case "agent_codex": handledNote = "Handled in Codex."
+ case "agent_copilot": handledNote = "Handled in Copilot CLI."
+ case "agent_muse": handledNote = "Handled in Muse Code."
+ default: handledNote = "Handled in VS Code."
}
var resolved = false
switch name {
@@ -623,15 +625,19 @@ final class HookServer: @unchecked Sendable {
termProgram.lowercased().contains("vscode") ||
bundleId.lowercased().contains("vscode"))
- // Codex gets the same approval card as Claude Code / Cursor (GitHub build only).
+ // Codex, Copilot CLI and Muse Code get the same approval card as Claude Code / Cursor.
// Other external agents (any other coucou_agent) answer immediately with "ask"
// so the agent re-asks in its own terminal — they do not get a notch card.
#if !APPSTORE
- let isCodexRequest = rawAgent == "codex"
+ let isCodexRequest = rawAgent == "codex"
+ let isCopilotRequest = rawAgent == "copilot"
+ let isMuseRequest = rawAgent == "muse"
#else
- let isCodexRequest = false
+ let isCodexRequest = false
+ let isCopilotRequest = false
+ let isMuseRequest = false
#endif
- if !isCodexRequest && Self.validateAgent(rawAgent) != nil {
+ if !isCodexRequest && !isCopilotRequest && !isMuseRequest && Self.validateAgent(rawAgent) != nil {
Task.detached { [weak self] in
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
close(fd)
@@ -643,12 +649,16 @@ final class HookServer: @unchecked Sendable {
let pillId: String
if isCodexRequest {
pillId = "agent_codex"
+ } else if isCopilotRequest {
+ pillId = "agent_copilot"
+ } else if isMuseRequest {
+ pillId = "agent_muse"
} else if isCursorEditor {
pillId = "agent_cursor"
} else {
pillId = "integration_claude"
}
- guard isCodexRequest || isCursorEditor || isVSCodeEditor else {
+ guard isCodexRequest || isCopilotRequest || isMuseRequest || isCursorEditor || isVSCodeEditor else {
Task.detached { [weak self] in
self?.sendLine(fd: fd, text: #"{"permissionDecision":"ask"}"#)
close(fd)
@@ -710,9 +720,11 @@ final class HookServer: @unchecked Sendable {
guard let self, self.pendingApprovalFD == fd else { return }
let note: String
switch capturedPillId {
- case "agent_cursor": note = "Handled in Cursor."
- case "agent_codex": note = "Handled in Codex."
- default: note = "Handled in VS Code."
+ case "agent_cursor": note = "Handled in Cursor."
+ case "agent_codex": note = "Handled in Codex."
+ case "agent_copilot": note = "Handled in Copilot CLI."
+ case "agent_muse": note = "Handled in Muse Code."
+ default: note = "Handled in VS Code."
}
self.dismissApprovalCard(note: note)
}
@@ -720,16 +732,20 @@ final class HookServer: @unchecked Sendable {
source.resume()
approvalFDSource = source
- // 115s safety timeout — show a note and cancel without sending a decision.
+ // Safety timeout — show a note and cancel without sending a decision.
// nb-hook reads EOF from the cancel handler's close and exits; Claude Code / Codex re-asks.
+ // Copilot/Muse use 110s (their relay waits 118s but their hook timeout is 120s, leaving little margin).
+ let waitTimeout: Double = (isCopilotRequest || isMuseRequest) ? 110 : 115
let captured = fd
- DispatchQueue.main.asyncAfter(deadline: .now() + 115) { [weak self] in
+ DispatchQueue.main.asyncAfter(deadline: .now() + waitTimeout) { [weak self] in
guard let self, self.pendingApprovalFD == captured else { return }
let note: String
switch capturedPillId {
- case "agent_cursor": note = "Still waiting in Cursor."
- case "agent_codex": note = "Still waiting in Codex."
- default: note = "Still waiting in VS Code."
+ case "agent_cursor": note = "Still waiting in Cursor."
+ 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."
+ default: note = "Still waiting in VS Code."
}
self.dismissApprovalCard(note: note)
}
@@ -1852,6 +1868,494 @@ final class HookServer: @unchecked Sendable {
options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
}
+ // MARK: - GitHub Copilot CLI hook installer
+
+ static var copilotHooksURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".copilot/hooks/coucou.json")
+ }
+
+ /// True when ~/.copilot/hooks/coucou.json already routes Copilot events to Coucou's nb-hook.
+ static func copilotHooksInstalled() -> Bool {
+ guard let data = try? Data(contentsOf: copilotHooksURL),
+ let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let hooks = root["hooks"] as? [String: Any] else { return false }
+ for value in hooks.values {
+ guard let entries = value as? [[String: Any]] else { continue }
+ for entry in entries {
+ if let cmd = entry["bash"] as? String,
+ cmd.contains("nb-hook"), cmd.contains("--agent copilot") { return true }
+ }
+ }
+ return false
+ }
+
+ private var _pendingCopilotData: Data?
+ private var _pendingCopilotFingerprint: String?
+
+ func previewCopilotHooks(install: Bool) throws -> String {
+ let url = Self.copilotHooksURL
+ let exists = FileManager.default.fileExists(atPath: url.path)
+ if !install && !exists {
+ throw NSError(domain: "CoucouNoop", code: 0, userInfo: [
+ NSLocalizedDescriptionKey: "No Copilot hooks to remove."
+ ])
+ }
+ let current = exists ? try Data(contentsOf: url) : Data()
+ _pendingCopilotFingerprint = sha256Hex(current)
+ if install {
+ let newData = try buildCopilotHooksData()
+ _pendingCopilotData = newData
+ return String(data: newData, encoding: .utf8) ?? ""
+ } else {
+ _pendingCopilotData = nil // nil = delete signal
+ return "(will delete \(url.path))"
+ }
+ }
+
+ func writeCopilotHooks() throws {
+ guard let fp = _pendingCopilotFingerprint else { return }
+ let url = Self.copilotHooksURL
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ guard sha256Hex(current) == fp else {
+ throw NSError(domain: "Coucou", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "~/.copilot/hooks/coucou.json changed since preview. Refresh and try again."
+ ])
+ }
+ if let data = _pendingCopilotData {
+ try writeJSONFile(data, to: url, suffix: "coucou.json")
+ } else {
+ // Uninstall: delete the file entirely
+ try FileManager.default.removeItem(at: url)
+ }
+ _pendingCopilotData = nil
+ _pendingCopilotFingerprint = nil
+ }
+
+ private func buildCopilotHooksData() throws -> Data {
+ var root = try Self.strictReadJSONObject(at: Self.copilotHooksURL,
+ label: "~/.copilot/hooks/coucou.json")
+ if let raw = root["hooks"], !(raw is [String: Any]) {
+ throw NSError(domain: "Coucou", code: 2, userInfo: [
+ NSLocalizedDescriptionKey: "~/.copilot/hooks/coucou.json: \"hooks\" has an unexpected type — Coucou has not touched it."
+ ])
+ }
+ let base = hookBase()
+ // Copilot CLI uses camelCase event names; each entry uses "bash" + "timeoutSec".
+ // The event name is passed as a positional arg so the relay can fall back to it.
+ // Copilot is fail-closed on permissionRequest — must always output valid JSON.
+ let events: [(String, Int)] = [
+ ("sessionStart", 10),
+ ("userPromptSubmitted", 10),
+ ("preToolUse", 10),
+ ("permissionRequest", 120),
+ ("postToolUse", 10),
+ ("agentStop", 10),
+ ("sessionEnd", 3),
+ ("notification", 10),
+ ]
+ var hooks = root["hooks"] as? [String: Any] ?? [:]
+ for (event, timeout) in events {
+ if let raw = hooks[event], !(raw is [[String: Any]]) {
+ throw NSError(domain: "Coucou", code: 2, userInfo: [
+ NSLocalizedDescriptionKey: "~/.copilot/hooks/coucou.json: \"hooks\"[\"\(event)\"] has an unexpected type — Coucou has not touched it."
+ ])
+ }
+ var entries = hooks[event] as? [[String: Any]] ?? []
+ entries.removeAll { ($0["bash"] as? String)?.contains("nb-hook") == true }
+ entries.append(["type": "command", "bash": "\(base) --agent copilot \(event)", "timeoutSec": timeout])
+ hooks[event] = entries
+ }
+ root["hooks"] = hooks
+ root["version"] = 1
+ return try JSONSerialization.data(withJSONObject: root,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ }
+
+ private func withoutCopilotHooks() throws -> Data {
+ var root = try Self.strictReadJSONObject(at: Self.copilotHooksURL,
+ label: "~/.copilot/hooks/coucou.json")
+ if var hooks = root["hooks"] as? [String: Any] {
+ for key in hooks.keys {
+ if var entries = hooks[key] as? [[String: Any]] {
+ entries.removeAll { ($0["command"] as? String)?.contains("nb-hook") == true }
+ if entries.isEmpty { hooks.removeValue(forKey: key) } else { hooks[key] = entries }
+ }
+ }
+ if hooks.isEmpty { root.removeValue(forKey: "hooks") } else { root["hooks"] = hooks }
+ }
+ return try JSONSerialization.data(withJSONObject: root,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ }
+
+ // MARK: - Muse Code hook installer
+
+ static var museSettingsURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".config/muse/settings.json")
+ }
+
+ /// True when ~/.config/muse/settings.json already routes Muse events to Coucou's nb-hook.
+ static func museHooksInstalled() -> Bool {
+ guard let data = try? Data(contentsOf: museSettingsURL),
+ let settings = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
+ let hooks = settings["hooks"] as? [String: Any] else { return false }
+ for value in hooks.values {
+ guard let groups = value as? [[String: Any]] else { continue }
+ for group in groups {
+ if let innerHooks = group["hooks"] as? [[String: Any]] {
+ for h in innerHooks {
+ if let cmd = h["command"] as? String,
+ cmd.contains("nb-hook"), cmd.contains("--agent muse") { return true }
+ }
+ }
+ if let cmd = group["command"] as? String,
+ cmd.contains("nb-hook"), cmd.contains("--agent muse") { return true }
+ }
+ }
+ return false
+ }
+
+ private var _pendingMuseData: Data?
+ private var _pendingMuseFingerprint: String?
+
+ func previewMuseHooks(install: Bool) throws -> String {
+ let url = Self.museSettingsURL
+ let exists = FileManager.default.fileExists(atPath: url.path)
+ if !install && !exists {
+ throw NSError(domain: "CoucouNoop", code: 0, userInfo: [
+ NSLocalizedDescriptionKey: "No Muse Code hooks to remove."
+ ])
+ }
+ let current = exists ? try Data(contentsOf: url) : Data()
+ _pendingMuseFingerprint = sha256Hex(current)
+ let newData = install ? try buildMuseHooksData() : try withoutMuseHooks()
+ _pendingMuseData = newData
+ return String(data: newData, encoding: .utf8) ?? ""
+ }
+
+ func writeMuseHooks() throws {
+ guard let data = _pendingMuseData, let fp = _pendingMuseFingerprint else { return }
+ let url = Self.museSettingsURL
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ guard sha256Hex(current) == fp else {
+ throw NSError(domain: "Coucou", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "~/.config/muse/settings.json changed since preview. Refresh and try again."
+ ])
+ }
+ try writeJSONFile(data, to: url, suffix: "settings.json")
+ _pendingMuseData = nil
+ _pendingMuseFingerprint = nil
+ }
+
+ private func buildMuseHooksData() throws -> Data {
+ var settings = try Self.strictReadJSONObject(at: Self.museSettingsURL,
+ label: "~/.config/muse/settings.json")
+ if let raw = settings["hooks"], !(raw is [String: Any]) {
+ throw NSError(domain: "Coucou", code: 2, userInfo: [
+ NSLocalizedDescriptionKey: "~/.config/muse/settings.json: \"hooks\" has an unexpected type — Coucou has not touched it."
+ ])
+ }
+ let base = hookBase()
+ // Muse uses PascalCase events. Timeouts in milliseconds (seconds × 1000).
+ let events: [(String, Int)] = [
+ ("SessionStart", 10),
+ ("UserPromptSubmit", 5),
+ ("PreToolUse", 5),
+ ("PermissionRequest", 120),
+ ("PostToolUse", 5),
+ ("Stop", 5),
+ ("SessionEnd", 3),
+ ]
+ let isNew = !FileManager.default.fileExists(atPath: Self.museSettingsURL.path)
+ var hooks = settings["hooks"] as? [String: Any] ?? [:]
+ for (event, timeoutSec) in events {
+ if let raw = hooks[event], !(raw is [[String: Any]]) {
+ throw NSError(domain: "Coucou", code: 2, userInfo: [
+ NSLocalizedDescriptionKey: "~/.config/muse/settings.json: \"hooks\"[\"\(event)\"] has an unexpected type — Coucou has not touched it."
+ ])
+ }
+ var groups = hooks[event] as? [[String: Any]] ?? []
+ groups = removeNbHookEntries(from: groups)
+ let hookEntry: [String: Any] = [
+ "type": "command",
+ "command": "\(base) --agent muse \(event)",
+ "timeout": timeoutSec * 1000,
+ ]
+ groups.append(["matcher": "*", "hooks": [hookEntry]])
+ hooks[event] = groups
+ }
+ settings["hooks"] = hooks
+ if isNew { settings["schema_version"] = 1 }
+ return try JSONSerialization.data(withJSONObject: settings,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ }
+
+ private func withoutMuseHooks() throws -> Data {
+ var settings = try Self.strictReadJSONObject(at: Self.museSettingsURL,
+ label: "~/.config/muse/settings.json")
+ if let raw = settings["hooks"], !(raw is [String: Any]) {
+ throw NSError(domain: "Coucou", code: 2, userInfo: [
+ NSLocalizedDescriptionKey: "~/.config/muse/settings.json: \"hooks\" has an unexpected type — Coucou has not touched it."
+ ])
+ }
+ if var hooks = settings["hooks"] as? [String: Any] {
+ for key in hooks.keys {
+ if let groups = hooks[key] as? [[String: Any]] {
+ let cleaned = removeNbHookEntries(from: groups)
+ if cleaned.isEmpty { hooks.removeValue(forKey: key) } else { hooks[key] = cleaned }
+ }
+ }
+ if hooks.isEmpty { settings.removeValue(forKey: "hooks") } else { settings["hooks"] = hooks }
+ }
+ return try JSONSerialization.data(withJSONObject: settings,
+ options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes])
+ }
+
+ // MARK: - OpenCode plugin installer
+
+ private var _pendingOpenCodeContent: String?
+ private var _pendingOpenCodeFingerprint: String?
+
+ static var openCodePluginURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".config/opencode/plugins/coucou.js")
+ }
+
+ static func openCodePluginInstalled() -> Bool {
+ guard let content = try? String(contentsOf: openCodePluginURL, encoding: .utf8) else { return false }
+ return content.contains("nb-hook") && content.contains("opencode")
+ }
+
+ private func buildOpenCodePluginContent() -> String {
+ let path = Self.hookScriptPath
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "'", with: "\\'")
+ return """
+// Coucou hook plugin for OpenCode — generated by Coucou.app
+// Forwards every event to the Coucou notch (fire-and-forget, never blocks).
+import { spawn } from 'node:child_process';
+
+const HOOK = '\(path)';
+const EVENT_MAP = {
+ 'session.created': 'SessionStart',
+ 'session.idle': 'Stop',
+ 'session.error': 'StopFailure',
+ 'session.deleted': 'SessionEnd',
+ 'permission.asked': 'PermissionRequest',
+};
+
+function forward(hook_event_name, payload) {
+ const p = spawn('/bin/sh', [HOOK, '--agent', 'opencode'],
+ { stdio: ['pipe', 'ignore', 'ignore'], detached: true });
+ p.on('error', () => {});
+ p.stdin.on('error', () => {});
+ p.stdin.write(JSON.stringify({ hook_event_name, ...payload }) + '\\n');
+ p.stdin.end();
+ p.unref();
+}
+
+export const CoucouPlugin = async (_ctx) => ({
+ event: async ({ event }) => {
+ const hook_event_name = EVENT_MAP[event.type];
+ if (!hook_event_name) return;
+ const props = event.properties || {};
+ const payload = {
+ session_id: event.sessionID || event.session_id || props.sessionID || props.session_id || '',
+ cwd: event.cwd || event.directory || props.cwd || props.directory || '',
+ };
+ if (typeof props.tool === 'string') payload.tool_name = props.tool;
+ if (props.input != null) payload.tool_input = props.input;
+ forward(hook_event_name, payload);
+ },
+ 'tool.execute.before': async (input) => {
+ forward('PreToolUse', {
+ session_id: input.sessionID || input.session_id || '',
+ cwd: input.cwd || '',
+ tool_name: typeof input.tool === 'string' ? input.tool : '',
+ tool_input: input.input ?? null,
+ });
+ },
+ 'tool.execute.after': async (input, _output) => {
+ forward('PostToolUse', {
+ session_id: input.sessionID || input.session_id || '',
+ cwd: input.cwd || '',
+ tool_name: typeof input.tool === 'string' ? input.tool : '',
+ });
+ },
+});
+"""
+ }
+
+ func previewOpenCodePlugin(install: Bool) throws -> String {
+ let url = Self.openCodePluginURL
+ let exists = FileManager.default.fileExists(atPath: url.path)
+ if !install {
+ guard exists else {
+ throw NSError(domain: "CoucouNoop", code: 0, userInfo: [
+ NSLocalizedDescriptionKey: "No OpenCode plugin to remove."
+ ])
+ }
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ _pendingOpenCodeFingerprint = sha256Hex(current)
+ _pendingOpenCodeContent = nil
+ return "(will delete \(url.path))"
+ }
+ let current = exists ? (try? Data(contentsOf: url)) ?? Data() : Data()
+ _pendingOpenCodeFingerprint = sha256Hex(current)
+ let content = buildOpenCodePluginContent()
+ _pendingOpenCodeContent = content
+ return content
+ }
+
+ func writeOpenCodePlugin() throws {
+ guard let fp = _pendingOpenCodeFingerprint else { return }
+ let url = Self.openCodePluginURL
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ guard sha256Hex(current) == fp else {
+ throw NSError(domain: "Coucou", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "~/.config/opencode/plugins/coucou.js changed since preview. Refresh and try again."
+ ])
+ }
+ guard let content = _pendingOpenCodeContent else {
+ // Uninstall path: checked by removeOpenCodePlugin
+ return
+ }
+ 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 backupURL = url.deletingLastPathComponent()
+ .appendingPathComponent("coucou.js.bak-\(fmt.string(from: Date()))")
+ try fm.copyItem(at: url, to: backupURL)
+ }
+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try content.write(to: url, atomically: true, encoding: .utf8)
+ _pendingOpenCodeContent = nil
+ _pendingOpenCodeFingerprint = nil
+ }
+
+ func removeOpenCodePlugin() throws {
+ let url = Self.openCodePluginURL
+ 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: "~/.config/opencode/plugins/coucou.js was not generated by Coucou — not deleting it."
+ ])
+ }
+ try FileManager.default.removeItem(at: url)
+ }
+
+ // MARK: - Amp plugin installer
+
+ private var _pendingAmpContent: String?
+ private var _pendingAmpFingerprint: String?
+
+ static var ampPluginURL: URL {
+ FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent(".config/amp/plugins/coucou.ts")
+ }
+
+ static func ampPluginInstalled() -> Bool {
+ guard let content = try? String(contentsOf: ampPluginURL, encoding: .utf8) else { return false }
+ return content.contains("nb-hook") && content.contains("'amp'")
+ }
+
+ private func buildAmpPluginContent() -> String {
+ let path = Self.hookScriptPath
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "'", with: "\\'")
+ return """
+// Coucou hook plugin for Amp — generated by Coucou.app
+// Forwards every event to the Coucou notch (display only, never blocks).
+import { spawn } from 'node:child_process';
+
+const HOOK = '\(path)';
+
+function forward(event_name: string, fields: Record<string, unknown>): void {
+ const payload = JSON.stringify({ hook_event_name: event_name, ...fields });
+ const p = spawn('/bin/sh', [HOOK, '--agent', 'amp'],
+ { stdio: ['pipe', 'ignore', 'ignore'], detached: true });
+ p.on('error', () => {});
+ (p.stdin as import('node:stream').Writable).on('error', () => {});
+ (p.stdin as import('node:stream').Writable).write(payload + '\\n');
+ (p.stdin as import('node:stream').Writable).end();
+ p.unref();
+}
+
+export default function (amp: any): void {
+ amp.on('session.start', (e: any) => { forward('SessionStart', { session_id: e.thread?.id ?? '' }); });
+ amp.on('agent.start', (e: any) => { forward('UserPromptSubmit', { session_id: e.thread?.id ?? '' }); });
+ amp.on('tool.call', (e: any) => { try { forward('PreToolUse', { session_id: e.thread?.id ?? '', tool_name: typeof e.tool === 'string' ? e.tool : '' }); } finally { return { action: 'allow' }; } });
+ amp.on('tool.result', (e: any) => { forward('PostToolUse', { session_id: e.thread?.id ?? '' }); });
+ amp.on('agent.end', (e: any) => { forward('Stop', { session_id: e.thread?.id ?? '' }); });
+}
+"""
+ }
+
+ func previewAmpPlugin(install: Bool) throws -> String {
+ let url = Self.ampPluginURL
+ let exists = FileManager.default.fileExists(atPath: url.path)
+ if !install {
+ guard exists else {
+ throw NSError(domain: "CoucouNoop", code: 0, userInfo: [
+ NSLocalizedDescriptionKey: "No Amp plugin to remove."
+ ])
+ }
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ _pendingAmpFingerprint = sha256Hex(current)
+ _pendingAmpContent = nil
+ return "(will delete \(url.path))"
+ }
+ let current = exists ? (try? Data(contentsOf: url)) ?? Data() : Data()
+ _pendingAmpFingerprint = sha256Hex(current)
+ let content = buildAmpPluginContent()
+ _pendingAmpContent = content
+ return content
+ }
+
+ func writeAmpPlugin() throws {
+ guard let fp = _pendingAmpFingerprint else { return }
+ let url = Self.ampPluginURL
+ let current = (try? Data(contentsOf: url)) ?? Data()
+ guard sha256Hex(current) == fp else {
+ throw NSError(domain: "Coucou", code: 1, userInfo: [
+ NSLocalizedDescriptionKey: "~/.config/amp/plugins/coucou.ts changed since preview. Refresh and try again."
+ ])
+ }
+ guard let content = _pendingAmpContent else {
+ // Uninstall path: checked by removeAmpPlugin
+ return
+ }
+ 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 backupURL = url.deletingLastPathComponent()
+ .appendingPathComponent("coucou.ts.bak-\(fmt.string(from: Date()))")
+ try fm.copyItem(at: url, to: backupURL)
+ }
+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try content.write(to: url, atomically: true, encoding: .utf8)
+ _pendingAmpContent = nil
+ _pendingAmpFingerprint = nil
+ }
+
+ func removeAmpPlugin() throws {
+ let url = Self.ampPluginURL
+ 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: "~/.config/amp/plugins/coucou.ts was not generated by Coucou — not deleting it."
+ ])
+ }
+ try FileManager.default.removeItem(at: url)
+ }
+
// MARK: SHA-256 fingerprint
private func sha256Hex(_ data: Data) -> String {
@@ -1876,11 +2380,31 @@ private let nbHookShellWrapper = """
#!/bin/sh
# Coucou hook relay — always exits 0, never blocks Claude Code
HOOK_DIR="$(dirname "$0")"
+out=""
if xcode-select -p >/dev/null 2>&1; then
out=$(/usr/bin/python3 "$HOOK_DIR/nb-hook.py" "$@" 2>/dev/null)
rc=$?
- if [ "$rc" -eq 0 ] && [ -n "$out" ]; then
- printf '%s\\n' "$out"
+ if [ "$rc" -ne 0 ] || [ -z "$out" ]; then
+ out=""
+ fi
+fi
+if [ -n "$out" ]; then
+ printf '%s\\n' "$out"
+else
+ # Copilot is fail-closed — must always output valid JSON even when python3 is absent or crashes.
+ _cop=0; _perm=0
+ for _a in "$@"; do
+ case "$_a" in
+ copilot) _cop=1 ;;
+ permissionRequest|PermissionRequest) _perm=1 ;;
+ esac
+ done
+ if [ "$_cop" -eq 1 ]; then
+ if [ "$_perm" -eq 1 ]; then
+ printf '{"permissionDecision":"ask"}\\n'
+ else
+ printf '{}\\n'
+ fi
fi
fi
exit 0
@@ -1901,25 +2425,42 @@ def normalize_event(name):
'BeforeAgent': 'UserPromptSubmit', 'AfterAgent': 'Stop',
'startup': 'SessionStart', 'exit': 'SessionEnd',
'PreInvocation': 'UserPromptSubmit', 'PostInvocation': 'PostToolUse',
+ 'pre_tool_use': 'PreToolUse', 'post_tool_use': 'PostToolUse',
+ 'user_prompt_submit': 'UserPromptSubmit', 'session_start': 'SessionStart',
+ 'session_end': 'SessionEnd', 'stop': 'Stop',
+ 'sessionStart': 'SessionStart', 'userPromptSubmitted': 'UserPromptSubmit',
+ 'agentStop': 'Stop', 'notification': 'Notification',
+ 'preToolUse': 'PreToolUse', 'postToolUse': 'PostToolUse',
+ 'permissionRequest': 'PermissionRequest', 'sessionEnd': 'SessionEnd',
}
return mapping.get(name, name)
def normalize_tool_fields(payload):
- if 'tool_name' in payload:
- return
- tool = payload.get('toolCall')
- if not isinstance(tool, dict):
- tool = {}
- name = tool.get('name') or payload.get('tool', '')
- if name:
- payload['tool_name'] = name
- if 'tool_input' not in payload and isinstance(tool.get('args'), dict):
- flat = dict(tool['args'])
- for src, dst in [('CommandLine', 'command'), ('FilePath', 'file_path'),
- ('Path', 'path'), ('Url', 'url'), ('Query', 'query'), ('Pattern', 'pattern')]:
- if src in flat:
- flat[dst] = flat[src]
- payload['tool_input'] = flat
+ if 'tool_name' not in payload:
+ # Copilot sends toolName directly; other agents nest in toolCall
+ if payload.get('toolName'):
+ payload['tool_name'] = payload['toolName']
+ else:
+ tool = payload.get('toolCall')
+ if not isinstance(tool, dict):
+ tool = {}
+ name = tool.get('name') or payload.get('tool', '')
+ if name:
+ payload['tool_name'] = name
+ if 'tool_input' not in payload:
+ # Copilot sends toolArgs directly
+ tool_args = payload.get('toolArgs')
+ if isinstance(tool_args, dict):
+ payload['tool_input'] = tool_args
+ else:
+ tool = payload.get('toolCall') or {}
+ if isinstance(tool.get('args'), dict):
+ flat = dict(tool['args'])
+ for src, dst in [('CommandLine', 'command'), ('FilePath', 'file_path'),
+ ('Path', 'path'), ('Url', 'url'), ('Query', 'query'), ('Pattern', 'pattern')]:
+ if src in flat:
+ flat[dst] = flat[src]
+ payload['tool_input'] = flat
if 'session_id' not in payload:
for k in ['conversationId', 'conversation_id', 'sessionId', 'GEMINI_SESSION_ID']:
if payload.get(k):
@@ -1929,6 +2470,9 @@ def normalize_tool_fields(payload):
sid = os.environ.get('GEMINI_SESSION_ID', '')
if sid:
payload['session_id'] = sid
+ # Copilot sends workdir for the current working directory
+ if not payload.get('cwd') and payload.get('workdir'):
+ payload['cwd'] = payload['workdir']
def main():
raw = b''
@@ -2096,26 +2640,25 @@ def main():
decision = resp_obj.get('permissionDecision', '')
except Exception:
decision = ''
- if decision == 'allow':
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow'}}}
- sys.stdout.write(json.dumps(out) + '\\n')
- sys.stdout.flush()
- sys.exit(0)
- elif decision == 'always' and agent != 'codex':
- # Let Claude Code persist the rule via updatedPermissions
- suggestions = payload.get('permission_suggestions', [])
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow', 'updatedPermissions': suggestions}}}
- sys.stdout.write(json.dumps(out) + '\\n')
- sys.stdout.flush()
- sys.exit(0)
- elif decision == 'always':
- # Codex rejects updatedPermissions — answer a plain allow instead
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow'}}}
+ if decision in ('allow', 'always'):
+ # Copilot/Muse use {"permissionDecision":"allow"} directly
+ if agent in ('copilot', 'muse'):
+ out = {'permissionDecision': 'allow'}
+ elif decision == 'always' and agent != 'codex':
+ # Let Claude Code persist the rule via updatedPermissions
+ suggestions = payload.get('permission_suggestions', [])
+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow', 'updatedPermissions': suggestions}}}
+ else:
+ # Claude Code / Codex plain allow
+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow'}}}
sys.stdout.write(json.dumps(out) + '\\n')
sys.stdout.flush()
sys.exit(0)
elif decision == 'deny':
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'deny', 'message': 'Denied from Coucou'}}}
+ if agent in ('copilot', 'muse'):
+ out = {'permissionDecision': 'deny'}
+ else:
+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'deny', 'message': 'Denied from Coucou'}}}
sys.stdout.write(json.dumps(out) + '\\n')
sys.stdout.flush()
sys.exit(0)
@@ -2131,7 +2674,10 @@ def main():
except Exception:
pass
# App unreachable, timed out, or no explicit decision — print nothing
- # Claude Code / Codex will handle the absence of output (re-ask or default behaviour)
+ # Copilot is fail-closed: must always output valid JSON so it re-asks rather than deny
+ if agent == 'copilot':
+ sys.stdout.write('{"permissionDecision":"ask"}\\n')
+ sys.stdout.flush()
sys.exit(0)
# All other events: fire-and-forget (0.3s timeout, never blocks)
@@ -2144,12 +2690,15 @@ def main():
except Exception:
pass # Always exit cleanly — never block the agent
- # Gemini CLI and Antigravity expect a JSON response on stdout (empty = no decision)
- if agent in ('gemini', 'antigravity'):
+ # Gemini CLI, Antigravity, Muse Code and Copilot CLI expect {} on stdout (empty = no decision)
+ if agent in ('gemini', 'antigravity', 'muse', 'copilot'):
sys.stdout.write('{}\\n')
sys.stdout.flush()
-main()
+try:
+ main()
+except Exception:
+ pass
sys.exit(0)
"""
@@ -2168,25 +2717,42 @@ def normalize_event(name):
'BeforeAgent': 'UserPromptSubmit', 'AfterAgent': 'Stop',
'startup': 'SessionStart', 'exit': 'SessionEnd',
'PreInvocation': 'UserPromptSubmit', 'PostInvocation': 'PostToolUse',
+ 'pre_tool_use': 'PreToolUse', 'post_tool_use': 'PostToolUse',
+ 'user_prompt_submit': 'UserPromptSubmit', 'session_start': 'SessionStart',
+ 'session_end': 'SessionEnd', 'stop': 'Stop',
+ 'sessionStart': 'SessionStart', 'userPromptSubmitted': 'UserPromptSubmit',
+ 'agentStop': 'Stop', 'notification': 'Notification',
+ 'preToolUse': 'PreToolUse', 'postToolUse': 'PostToolUse',
+ 'permissionRequest': 'PermissionRequest', 'sessionEnd': 'SessionEnd',
}
return mapping.get(name, name)
def normalize_tool_fields(payload):
- if 'tool_name' in payload:
- return
- tool = payload.get('toolCall')
- if not isinstance(tool, dict):
- tool = {}
- name = tool.get('name') or payload.get('tool', '')
- if name:
- payload['tool_name'] = name
- if 'tool_input' not in payload and isinstance(tool.get('args'), dict):
- flat = dict(tool['args'])
- for src, dst in [('CommandLine', 'command'), ('FilePath', 'file_path'),
- ('Path', 'path'), ('Url', 'url'), ('Query', 'query'), ('Pattern', 'pattern')]:
- if src in flat:
- flat[dst] = flat[src]
- payload['tool_input'] = flat
+ if 'tool_name' not in payload:
+ # Copilot sends toolName directly; other agents nest in toolCall
+ if payload.get('toolName'):
+ payload['tool_name'] = payload['toolName']
+ else:
+ tool = payload.get('toolCall')
+ if not isinstance(tool, dict):
+ tool = {}
+ name = tool.get('name') or payload.get('tool', '')
+ if name:
+ payload['tool_name'] = name
+ if 'tool_input' not in payload:
+ # Copilot sends toolArgs directly
+ tool_args = payload.get('toolArgs')
+ if isinstance(tool_args, dict):
+ payload['tool_input'] = tool_args
+ else:
+ tool = payload.get('toolCall') or {}
+ if isinstance(tool.get('args'), dict):
+ flat = dict(tool['args'])
+ for src, dst in [('CommandLine', 'command'), ('FilePath', 'file_path'),
+ ('Path', 'path'), ('Url', 'url'), ('Query', 'query'), ('Pattern', 'pattern')]:
+ if src in flat:
+ flat[dst] = flat[src]
+ payload['tool_input'] = flat
if 'session_id' not in payload:
for k in ['conversationId', 'conversation_id', 'sessionId', 'GEMINI_SESSION_ID']:
if payload.get(k):
@@ -2196,6 +2762,9 @@ def normalize_tool_fields(payload):
sid = os.environ.get('GEMINI_SESSION_ID', '')
if sid:
payload['session_id'] = sid
+ # Copilot sends workdir for the current working directory
+ if not payload.get('cwd') and payload.get('workdir'):
+ payload['cwd'] = payload['workdir']
def main():
raw = b''
@@ -2362,26 +2931,25 @@ def main():
decision = resp_obj.get('permissionDecision', '')
except Exception:
decision = ''
- if decision == 'allow':
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow'}}}
- sys.stdout.write(json.dumps(out) + '\\n')
- sys.stdout.flush()
- sys.exit(0)
- elif decision == 'always' and agent != 'codex':
- # Let Claude Code persist the rule via updatedPermissions
- suggestions = payload.get('permission_suggestions', [])
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow', 'updatedPermissions': suggestions}}}
- sys.stdout.write(json.dumps(out) + '\\n')
- sys.stdout.flush()
- sys.exit(0)
- elif decision == 'always':
- # Codex rejects updatedPermissions — answer a plain allow instead
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow'}}}
+ if decision in ('allow', 'always'):
+ # Copilot/Muse use {"permissionDecision":"allow"} directly
+ if agent in ('copilot', 'muse'):
+ out = {'permissionDecision': 'allow'}
+ elif decision == 'always' and agent != 'codex':
+ # Let Claude Code persist the rule via updatedPermissions
+ suggestions = payload.get('permission_suggestions', [])
+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow', 'updatedPermissions': suggestions}}}
+ else:
+ # Claude Code / Codex plain allow
+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'allow'}}}
sys.stdout.write(json.dumps(out) + '\\n')
sys.stdout.flush()
sys.exit(0)
elif decision == 'deny':
- out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'deny', 'message': 'Denied from Coucou'}}}
+ if agent in ('copilot', 'muse'):
+ out = {'permissionDecision': 'deny'}
+ else:
+ out = {'hookSpecificOutput': {'hookEventName': 'PermissionRequest', 'decision': {'behavior': 'deny', 'message': 'Denied from Coucou'}}}
sys.stdout.write(json.dumps(out) + '\\n')
sys.stdout.flush()
sys.exit(0)
@@ -2397,6 +2965,10 @@ def main():
except Exception:
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
+ if agent == 'copilot':
+ sys.stdout.write('{"permissionDecision":"ask"}\\n')
+ sys.stdout.flush()
sys.exit(0)
try:
@@ -2408,11 +2980,14 @@ def main():
except Exception:
pass # Always exit cleanly — never block the agent
- # Gemini CLI and Antigravity expect a JSON response on stdout (empty = no decision)
- if agent in ('gemini', 'antigravity'):
+ # Gemini CLI, Antigravity, Muse Code and Copilot CLI expect {} on stdout (empty = no decision)
+ if agent in ('gemini', 'antigravity', 'muse', 'copilot'):
sys.stdout.write('{}\\n')
sys.stdout.flush()
-main()
+try:
+ main()
+except Exception:
+ pass
sys.exit(0)
"""
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index 3947f0d6..e73907c3 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -217,7 +217,8 @@ struct OverviewView: View {
NSWorkspace.shared.openApplication(at: url, configuration: .init(), completionHandler: nil)
}
#endif
- case "agent_gemini", "agent_antigravity":
+ case "agent_gemini", "agent_antigravity",
+ "agent_copilot", "agent_muse", "agent_opencode", "agent_amp":
#if !APPSTORE
let terminalBundleIds = ["com.apple.Terminal", "com.googlecode.iterm2",
"net.kovidgoyal.kitty", "com.mitchellh.ghostty"]
@@ -309,8 +310,11 @@ struct ApprovalView: View {
PrimaryButton("Allow") {
HookServer.shared.sendApprovalDecision("allow")
}
- // Codex rejects updatedPermissions, so "Always" is not offered
- if approval?.pillId != "agent_codex" {
+ // Codex, Copilot CLI and Muse Code do not support updatedPermissions
+ let hideAlways = approval?.pillId == "agent_codex"
+ || approval?.pillId == "agent_copilot"
+ || approval?.pillId == "agent_muse"
+ if !hideAlways {
SecondaryButton("Always") {
HookServer.shared.sendApprovalDecision("always")
}
@@ -1607,6 +1611,30 @@ struct IntegrationCardView: View {
#else
return false
#endif
+ case "agent_copilot":
+ #if !APPSTORE
+ return HookServer.copilotHooksInstalled()
+ #else
+ return false
+ #endif
+ case "agent_muse":
+ #if !APPSTORE
+ return HookServer.museHooksInstalled()
+ #else
+ return false
+ #endif
+ case "agent_opencode":
+ #if !APPSTORE
+ return HookServer.openCodePluginInstalled()
+ #else
+ return false
+ #endif
+ case "agent_amp":
+ #if !APPSTORE
+ return HookServer.ampPluginInstalled()
+ #else
+ return false
+ #endif
case "agent_cursor", "agent_codex":
return false // coming soon
case "integration_music":
@@ -1735,6 +1763,8 @@ struct IntegrationCardView: View {
: nil
if let err = svcErr { return err }
let isHooks = task.id == "agent_gemini" || task.id == "agent_antigravity"
+ || task.id == "agent_copilot" || task.id == "agent_muse"
+ || task.id == "agent_opencode" || task.id == "agent_amp"
let isAI = ChatProvider(pillID: task.id) != nil
if isConfigured {
if isHooks { return "Hooks installed" }
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
index 9a3d0408..ebc58524 100644
--- a/NotchBuddy/Sources/App/SettingsView.swift
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -52,6 +52,26 @@ struct SettingsView: View {
@State private var showCodexDiff: Bool = false
@State private var pendingCodexJSON: String = ""
@State private var codexPendingInstall: Bool = true
+
+ @State private var copilotHooksInstalled: Bool = HookServer.copilotHooksInstalled()
+ @State private var showCopilotDiff: Bool = false
+ @State private var pendingCopilotJSON: String = ""
+ @State private var copilotPendingInstall: Bool = true
+
+ @State private var museHooksInstalled: Bool = HookServer.museHooksInstalled()
+ @State private var showMuseDiff: Bool = false
+ @State private var pendingMuseJSON: String = ""
+ @State private var musePendingInstall: Bool = true
+
+ @State private var openCodePluginInstalled: Bool = HookServer.openCodePluginInstalled()
+ @State private var showOpenCodeDiff: Bool = false
+ @State private var pendingOpenCodeContent: String = ""
+ @State private var openCodePendingInstall: Bool = true
+
+ @State private var ampPluginInstalled: Bool = HookServer.ampPluginInstalled()
+ @State private var showAmpDiff: Bool = false
+ @State private var pendingAmpContent: String = ""
+ @State private var ampPendingInstall: Bool = true
#endif
// Multi-provider chat keys
@@ -532,6 +552,138 @@ struct SettingsView: View {
.padding(6)
}
+ GroupBox("GitHub Copilot CLI Hooks") {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(copilotHooksInstalled
+ ? "Hooks installed — restart Copilot CLI to activate"
+ : "~/.copilot/hooks/coucou.json")
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundColor(.secondary)
+ HStack(spacing: 10) {
+ Button("Install hooks") { triggerCopilotPreview(install: true) }
+ .buttonStyle(.borderedProminent)
+ Button("Uninstall") { triggerCopilotPreview(install: false) }
+ .buttonStyle(.bordered)
+ }
+ if showCopilotDiff {
+ ScrollView {
+ Text(pendingCopilotJSON)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 140)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+ HStack {
+ Button("Confirm & write") { confirmCopilotOp() }
+ .buttonStyle(.borderedProminent)
+ Button("Cancel") { showCopilotDiff = false; pendingCopilotJSON = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ .padding(6)
+ }
+
+ GroupBox("Muse Code Hooks") {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(museHooksInstalled
+ ? "Hooks installed — restart Muse Code to activate"
+ : "~/.config/muse/settings.json")
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundColor(.secondary)
+ HStack(spacing: 10) {
+ Button("Install hooks") { triggerMusePreview(install: true) }
+ .buttonStyle(.borderedProminent)
+ Button("Uninstall") { triggerMusePreview(install: false) }
+ .buttonStyle(.bordered)
+ }
+ if showMuseDiff {
+ ScrollView {
+ Text(pendingMuseJSON)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 140)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+ HStack {
+ Button("Confirm & write") { confirmMuseOp() }
+ .buttonStyle(.borderedProminent)
+ Button("Cancel") { showMuseDiff = false; pendingMuseJSON = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ .padding(6)
+ }
+
+ GroupBox("OpenCode Plugin") {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(openCodePluginInstalled
+ ? "Plugin installed — restart OpenCode to activate"
+ : "~/.config/opencode/plugins/coucou.js")
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundColor(.secondary)
+ HStack(spacing: 10) {
+ Button("Install plugin") { triggerOpenCodePreview(install: true) }
+ .buttonStyle(.borderedProminent)
+ Button("Uninstall") { triggerOpenCodePreview(install: false) }
+ .buttonStyle(.bordered)
+ }
+ if showOpenCodeDiff {
+ ScrollView {
+ Text(pendingOpenCodeContent)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 140)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+ HStack {
+ Button("Confirm & write") { confirmOpenCodeOp() }
+ .buttonStyle(.borderedProminent)
+ Button("Cancel") { showOpenCodeDiff = false; pendingOpenCodeContent = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ .padding(6)
+ }
+
+ GroupBox("Amp Plugin") {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(ampPluginInstalled
+ ? "Plugin installed — restart Amp to activate"
+ : "~/.config/amp/plugins/coucou.ts")
+ .font(.system(size: 11, design: .monospaced))
+ .foregroundColor(.secondary)
+ HStack(spacing: 10) {
+ Button("Install plugin") { triggerAmpPreview(install: true) }
+ .buttonStyle(.borderedProminent)
+ Button("Uninstall") { triggerAmpPreview(install: false) }
+ .buttonStyle(.bordered)
+ }
+ if showAmpDiff {
+ ScrollView {
+ Text(pendingAmpContent)
+ .font(.system(size: 10, design: .monospaced))
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ .frame(height: 140)
+ .background(Color(NSColor.textBackgroundColor))
+ .cornerRadius(6)
+ HStack {
+ Button("Confirm & write") { confirmAmpOp() }
+ .buttonStyle(.borderedProminent)
+ Button("Cancel") { showAmpDiff = false; pendingAmpContent = "" }
+ .buttonStyle(.bordered)
+ }
+ }
+ }
+ .padding(6)
+ }
+
GroupBox("Plan usage") {
VStack(alignment: .leading, spacing: 10) {
Text("Shows your Claude plan usage (5-hour and weekly limits) in the notch header. Coucou adds a status line relay to ~/.claude/settings.json. If you already have a status line, it keeps working as before. Pro and Max plans only.")
@@ -1071,6 +1223,122 @@ struct SettingsView: View {
}
}
+ private func triggerCopilotPreview(install: Bool) {
+ do {
+ copilotPendingInstall = install
+ pendingCopilotJSON = try HookServer.shared.previewCopilotHooks(install: install)
+ showCopilotDiff = true
+ statusMessage = "Review the JSON below before confirming."
+ } catch let e as NSError where e.domain == "CoucouNoop" {
+ statusMessage = e.localizedDescription
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmCopilotOp() {
+ do {
+ try HookServer.shared.writeCopilotHooks()
+ showCopilotDiff = false
+ pendingCopilotJSON = ""
+ copilotHooksInstalled = copilotPendingInstall
+ statusMessage = copilotPendingInstall
+ ? "✓ Copilot CLI hooks installed in ~/.copilot/hooks/coucou.json"
+ : "✓ Copilot CLI hooks removed."
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func triggerMusePreview(install: Bool) {
+ do {
+ musePendingInstall = install
+ pendingMuseJSON = try HookServer.shared.previewMuseHooks(install: install)
+ showMuseDiff = true
+ statusMessage = "Review the JSON below before confirming."
+ } catch let e as NSError where e.domain == "CoucouNoop" {
+ statusMessage = e.localizedDescription
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmMuseOp() {
+ do {
+ try HookServer.shared.writeMuseHooks()
+ showMuseDiff = false
+ pendingMuseJSON = ""
+ museHooksInstalled = musePendingInstall
+ statusMessage = musePendingInstall
+ ? "✓ Muse Code hooks installed in ~/.config/muse/settings.json"
+ : "✓ Muse Code hooks removed."
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func triggerOpenCodePreview(install: Bool) {
+ do {
+ openCodePendingInstall = install
+ pendingOpenCodeContent = try HookServer.shared.previewOpenCodePlugin(install: install)
+ showOpenCodeDiff = true
+ statusMessage = "Review the content below before confirming."
+ } catch let e as NSError where e.domain == "CoucouNoop" {
+ statusMessage = e.localizedDescription
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmOpenCodeOp() {
+ do {
+ if openCodePendingInstall {
+ try HookServer.shared.writeOpenCodePlugin()
+ } else {
+ try HookServer.shared.removeOpenCodePlugin()
+ }
+ showOpenCodeDiff = false
+ pendingOpenCodeContent = ""
+ openCodePluginInstalled = openCodePendingInstall
+ statusMessage = openCodePendingInstall
+ ? "✓ OpenCode plugin installed in ~/.config/opencode/plugins/coucou.js"
+ : "✓ OpenCode plugin removed."
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func triggerAmpPreview(install: Bool) {
+ do {
+ ampPendingInstall = install
+ pendingAmpContent = try HookServer.shared.previewAmpPlugin(install: install)
+ showAmpDiff = true
+ statusMessage = "Review the content below before confirming."
+ } catch let e as NSError where e.domain == "CoucouNoop" {
+ statusMessage = e.localizedDescription
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
+ private func confirmAmpOp() {
+ do {
+ if ampPendingInstall {
+ try HookServer.shared.writeAmpPlugin()
+ } else {
+ try HookServer.shared.removeAmpPlugin()
+ }
+ showAmpDiff = false
+ pendingAmpContent = ""
+ ampPluginInstalled = ampPendingInstall
+ statusMessage = ampPendingInstall
+ ? "✓ Amp plugin installed in ~/.config/amp/plugins/coucou.ts"
+ : "✓ Amp plugin removed."
+ } catch {
+ statusMessage = "❌ \(error.localizedDescription)"
+ }
+ }
+
private func installStatusLine() {
do {
pendingStatusLineJSON = try HookServer.shared.previewStatusLine(install: true)
@@ -1229,9 +1497,13 @@ struct SettingsView: View {
if isMain { return nil }
if def.comingSoon { return "Coming soon" }
#if !APPSTORE
- if def.id == "agent_gemini" && !HookServer.geminiHooksInstalled() { return "Hooks not installed" }
- if def.id == "agent_antigravity" && !HookServer.agyHooksInstalled() { return "Hooks not installed" }
- if def.id == "agent_codex" && !HookServer.codexHooksInstalled() { return "Hooks not installed" }
+ if def.id == "agent_gemini" && !HookServer.geminiHooksInstalled() { return "Hooks not installed" }
+ if def.id == "agent_antigravity" && !HookServer.agyHooksInstalled() { return "Hooks not installed" }
+ if def.id == "agent_codex" && !HookServer.codexHooksInstalled() { return "Hooks not installed" }
+ if def.id == "agent_copilot" && !HookServer.copilotHooksInstalled() { return "Hooks not installed" }
+ if def.id == "agent_muse" && !HookServer.museHooksInstalled() { return "Hooks not installed" }
+ if def.id == "agent_opencode" && !HookServer.openCodePluginInstalled() { return "Plugin not installed" }
+ if def.id == "agent_amp" && !HookServer.ampPluginInstalled() { return "Plugin not installed" }
#endif
if def.category == .ai {
if let provider = ChatProvider(pillID: def.id), provider.isLocal {
diff --git a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift b/NotchBuddy/Sources/CoucouKit/PillCatalog.swift
index 530b5ecf..3f61225c 100644
--- a/NotchBuddy/Sources/CoucouKit/PillCatalog.swift
+++ b/NotchBuddy/Sources/CoucouKit/PillCatalog.swift
@@ -59,6 +59,14 @@ enum PillCatalog {
// ── Agents ───────────────────────────────────────────────────────────
.init(id: "agent_gemini", name: "Gemini CLI", color: "#8AB4F8",
category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
+ .init(id: "agent_copilot", name: "Copilot CLI", color: "#818CF8",
+ category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
+ .init(id: "agent_muse", name: "Muse Code", color: "#38BDF8",
+ category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
+ .init(id: "agent_opencode", name: "OpenCode", color: "#4ADE80",
+ category: .agent, subtitle: "Agent", source: .agent, githubOnly: true),
+ .init(id: "agent_amp", name: "Amp", color: "#F59E0B",
+ 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/README.md b/README.md
index d02ad1d2..ae0a1b1e 100644
--- a/README.md
+++ b/README.md
@@ -34,7 +34,7 @@ Meet **Mochi**: a soft little squircle with big eyes that pops out of your notch
## Features
-- 🤖 **Claude Code, Cursor, Codex, Gemini CLI, Antigravity and other agents, live** — see every session in your notch: what it reads, edits and runs, step by step. Tag a hook payload with `coucou_agent` to give any agent its own pill (see [`docs/AGENTS.md`](docs/AGENTS.md)). Finished? Mochi does a happy little jump.
+- 🤖 **Claude Code, Cursor, Codex, Gemini CLI, Antigravity, Copilot CLI, Muse Code, OpenCode, Amp and other agents, live** — see every session in your notch: what it reads, edits and runs, step by step. Tag a hook payload with `coucou_agent` to give any agent its own pill (see [`docs/AGENTS.md`](docs/AGENTS.md)). Finished? Mochi does a happy little jump.
- See what Claude is editing, live in the notch: each file modification shows the file name and +N −M counts in the ticker, tap to read the full diff
- ✅ **Approve and answer from the notch** — Claude Code permission requests show up with **Allow / Deny / Always**; `AskUserQuestion` prompts show the choices right in the notch (single or multi-select, up to 4 questions). One click, or "Reply in terminal" to fall back to the CLI. Codex also gets Allow / Deny.
- 🧑‍💻 **Jump to the right terminal** — open the exact terminal window of a session *(macOS)*.
@@ -216,6 +216,23 @@ Click the Coucou icon in the menu bar (macOS) or in the system tray (Windows, Li
If Coucou isn't running, the hook exits immediately: **Claude Code is never blocked.**
+### Supported agents
+
+| Agent | How it connects | Mac-only? |
+|---|---|---|
+| Claude Code | Settings → Claude Code → **Install hooks** | No |
+| Gemini CLI | Settings → Gemini CLI → **Install hooks** | Mac only |
+| Antigravity | Settings → Antigravity → **Install hooks** | Mac only |
+| Cursor | Hooks installed automatically alongside Claude Code | No |
+| Codex | `--agent codex` flag; Settings → Codex → **Install hooks** | No |
+| Copilot CLI | `--agent copilot` flag + camelCase events | No |
+| Muse Code | `--agent muse` flag | No |
+| OpenCode | Plugin — **Settings → OpenCode Plugin → Install** | Mac only |
+| Amp | Plugin — **Settings → Amp Plugin → Install** | Mac only |
+| Any other | `--agent <name>` flag; see [`docs/AGENTS.md`](docs/AGENTS.md) | No |
+
+OpenCode and Amp use a TypeScript/JavaScript plugin model rather than a hook command. Coucou installs the plugin file into `~/.config/opencode/plugins/` and `~/.config/amp/plugins/` respectively — these are macOS paths; the Windows/Linux build does not support them.
+
## Things to try
| Do this | Mochi does that |
diff --git a/docs/AGENTS.md b/docs/AGENTS.md
index 055a9afa..7144d4ea 100644
--- a/docs/AGENTS.md
+++ b/docs/AGENTS.md
@@ -99,7 +99,11 @@ A **declared pill** is a catalog entry (`PillCatalog.swift`) that has been enabl
A catalog pill that is not checked in Settings behaves like any other agent: it gets an automatic pill when a session starts, and that pill is removed when the session ends.
-The GitHub build exposes Gemini CLI (`agent_gemini`) and Antigravity (`agent_antigravity`) in Settings → Active pills. Cursor (`agent_cursor`) and Codex (`agent_codex`, GitHub build only) are there too — their pills can be declared and set as the main pill; session support is coming in a future version.
+The GitHub build exposes Gemini CLI (`agent_gemini`), Antigravity (`agent_antigravity`),
+GitHub Copilot CLI (`agent_copilot`), Muse Code (`agent_muse`), OpenCode (`agent_opencode`)
+and Amp (`agent_amp`) in Settings → Active pills. Cursor (`agent_cursor`) and Codex
+(`agent_codex`, GitHub build only) are there too — their pills can be declared and set as
+the main pill; session support is coming in a future version.
## Real-world examples
@@ -134,6 +138,72 @@ island's `tool_name` / `session_id`.
| `PostInvocation` | `PostToolUse` |
| `Stop` | `Stop` |
+### GitHub Copilot CLI (macOS)
+
+Coucou supports Copilot CLI out of the box via **Settings → GitHub Copilot CLI Hooks → Install hooks**.
+The installer writes to `~/.copilot/hooks/coucou.json` and uses `--agent copilot`.
+Copilot CLI uses camelCase event names and `{"bash":"…","timeoutSec":N}` entries.
+Copilot CLI is fail-closed on `permissionRequest`: the relay always outputs valid JSON
+and returns `{"permissionDecision":"ask"}` on timeout so Copilot re-prompts in the terminal.
+Coucou shows a real Allow / Deny card for Copilot approval requests.
+
+| Copilot CLI event | Canonical event |
+|---|---|
+| `sessionStart` | `SessionStart` |
+| `userPromptSubmitted` | `UserPromptSubmit` |
+| `preToolUse` | `PreToolUse` |
+| `permissionRequest` | `PermissionRequest` |
+| `postToolUse` | `PostToolUse` |
+| `agentStop` | `Stop` |
+| `sessionEnd` | `SessionEnd` |
+| `notification` | `Notification` |
+
+### Muse Code (macOS)
+
+Coucou supports Muse Code out of the box via **Settings → Muse Code Hooks → Install hooks**.
+The installer merges into `~/.config/muse/settings.json` and uses `--agent muse`.
+Muse uses PascalCase event names. Coucou shows a real Allow / Deny card for Muse approval requests.
+
+| Muse Code event | Canonical event |
+|---|---|
+| `SessionStart` | `SessionStart` |
+| `UserPromptSubmit` | `UserPromptSubmit` |
+| `PreToolUse` | `PreToolUse` |
+| `PermissionRequest` | `PermissionRequest` |
+| `PostToolUse` | `PostToolUse` |
+| `Stop` | `Stop` |
+| `SessionEnd` | `SessionEnd` |
+
+### OpenCode (macOS)
+
+Coucou supports OpenCode via **Settings → OpenCode Plugin → Install plugin**.
+The installer writes a JS plugin to `~/.config/opencode/plugins/coucou.js`.
+The plugin maps OpenCode event types to canonical Coucou names and forwards them fire-and-forget; OpenCode is never blocked.
+
+| OpenCode event | Canonical event |
+|---|---|
+| `session.created` | `SessionStart` |
+| `session.idle` | `Stop` |
+| `session.error` | `StopFailure` |
+| `session.deleted` | `SessionEnd` |
+| `tool.execute.before` | `PreToolUse` |
+| `tool.execute.after` | `PostToolUse` |
+| `permission.asked` | `PermissionRequest` |
+
+### Amp (macOS)
+
+Coucou supports Amp via **Settings → Amp Plugin → Install plugin**.
+The installer writes a TypeScript plugin to `~/.config/amp/plugins/coucou.ts`.
+The `tool.call` handler returns `{ action: 'allow' }` so Amp always proceeds; all events are forwarded display-only.
+
+| Amp event | Canonical event |
+|---|---|
+| `session.start` | `SessionStart` |
+| `agent.start` | `UserPromptSubmit` |
+| `tool.call` | `PreToolUse` |
+| `tool.result` | `PostToolUse` |
+| `agent.end` | `Stop` |
+
### Any other tool
Follow the generic pattern: call `nb-hook --agent <your-name> <EventName>` (macOS),
diff --git a/docs/SPEC.md b/docs/SPEC.md
index e2a511a1..7ecc2dca 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -101,11 +101,11 @@ Toutes les pastilles déclarées sont définies dans `PillCatalog.all` (source d
| Catégorie | Titre | Pastilles | Subtitle (repos) | Subtitle (session) |
|---|---|---|---|---|
| `workspace` | Where you code | VS Code, Cursor, Antigravity *(GitHub only)*, Codex *(GitHub only)* | Integration | Claude Code / Cursor / Codex / Agent |
-| `agent` | Agents | Gemini CLI *(GitHub only)* | Agent | Agent |
+| `agent` | Agents | Gemini CLI *(GitHub only)*, Copilot CLI *(GitHub only)*, Muse Code *(GitHub only)*, OpenCode *(GitHub only)*, Amp *(GitHub only)* | Agent | Agent |
| `ai` | AI for the chat | Anthropic, Google AI, OpenAI, Ollama, LM Studio | Chat | — |
| `service` | Services | Resend, n8n, Vercel, GitHub, Notion, Cal.com, Stripe, Apple Music *(GitHub only)* | Integration | — |
-Couleurs : Cursor `#C0C4CC`, Codex `#2DD4BF`, Gemini CLI `#8AB4F8`, Antigravity `#E879F9`, pastilles IA = `ChatProvider.accentHex` (Ollama `#FACC15`, LM Studio `#A3E635`).
+Couleurs : Cursor `#C0C4CC`, Codex `#2DD4BF`, Gemini CLI `#8AB4F8`, Antigravity `#E879F9`, Copilot CLI `#818CF8`, Muse Code `#38BDF8`, OpenCode `#4ADE80`, Amp `#F59E0B`, pastilles IA = `ChatProvider.accentHex` (Ollama `#FACC15`, LM Studio `#A3E635`).
Règles :
- **`mainPillId`** (défaut `integration_claude`) est la pastille workspace toujours chargée. Elle ne compte pas dans les 4 places. Modifiable via le sélecteur Main dans Settings.
@@ -114,7 +114,7 @@ Règles :
- `removeTask` sur `mainPillId` ou une pastille déclarée + active → reset à `.idle` + `pillBadge = nil` + nom du catalogue (pas de suppression). Sinon → suppression normale.
- `sortTasksByCatalog` : pastilles du catalogue dans l'ordre du catalogue ; pastilles hors catalogue juste après `integration_claude`.
- Pastilles `githubOnly` : exclues des builds App Store (`#if APPSTORE`).
-- Hooks (Gemini CLI, Antigravity, Codex) : `isConfigured` = `HookServer.geminiHooksInstalled()` / `agyHooksInstalled()` / `codexHooksInstalled()` sous `#if !APPSTORE`. La section Codex Hooks dans Settings installe les hooks dans `~/.codex/hooks.json` avec le même flux backup + preview que Gemini CLI. Après l'installation, la carte affiche : « run /hooks in Codex or open Hooks in the app's settings to trust them ». Approbations Codex : carte avec Allow et Deny seulement (pas Always) ; updatedPermissions jamais envoyé ; notes « Handled in Codex. » / « Still waiting in Codex. ».
+- Hooks (Gemini CLI, Antigravity, Codex, Copilot CLI, Muse Code) et plugins (OpenCode, Amp) : `isConfigured` = méthodes correspondantes de `HookServer` sous `#if !APPSTORE`. La section Codex Hooks dans Settings installe les hooks dans `~/.codex/hooks.json` avec le même flux backup + preview que Gemini CLI. Après l'installation, la carte affiche : « run /hooks in Codex or open Hooks in the app's settings to trust them ». Approbations Codex, Copilot CLI, Muse Code : carte avec Allow et Deny seulement (pas Always) ; updatedPermissions jamais envoyé pour Codex/Copilot/Muse ; notes « Handled in Codex. » / « Handled in Copilot CLI. » / « Handled in Muse Code. ». OpenCode : plugin JS dans `~/.config/opencode/plugins/coucou.js`, événements mappés via EVENT_MAP, lecture depuis `event.properties`. Amp : plugin TypeScript dans `~/.config/amp/plugins/coucou.ts`, `tool.call` retourne toujours `{ action: 'allow' }`.
- Pastilles IA (cloud) : `isConfigured` = clé API dans le Keychain. Pastilles IA locales (Ollama, LM Studio) : `isConfigured` = URL serveur non vide (définie via le bouton **Connect** dans Réglages → Chat). Bouton « Chat with… » → change le fournisseur et ouvre la vue `.prompt`.
### Carte GitHub (`GitHubPulseCardView`)
diff --git a/windows/README.md b/windows/README.md
index 60374024..c2bf92ab 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -136,6 +136,25 @@ windows/
`%LOCALAPPDATA%\Coucou\coucou.log` — hook events, permission decisions, poller
problems. It stays on your machine.
+## Supported agents
+
+The relay (`coucou-hook.exe`) works with any tool that can run a command on hook events. Pass `--agent <name>` to create a named pill.
+
+| Agent | How to connect | Config file |
+|---|---|---|
+| Claude Code | **Settings → Claude Code → Install hooks** | `%USERPROFILE%\.claude\settings.json` |
+| Gemini CLI | `--agent gemini` positional arg | `%USERPROFILE%\.gemini\settings.json` |
+| Antigravity | `--agent antigravity` positional arg | `%USERPROFILE%\.config\antigravity\hooks.json` |
+| Cursor | hooks installed automatically | `%USERPROFILE%\.claude\settings.json` |
+| Codex | `--agent codex` positional arg | `%USERPROFILE%\.codex\hooks.json` |
+| Copilot CLI | `--agent copilot` positional arg + camelCase events | `%USERPROFILE%\.copilot\hooks\coucou.json` |
+| Muse Code | `--agent muse` positional arg | `%USERPROFILE%\.config\muse\settings.json` |
+| OpenCode | JS plugin (`coucou.js`) | `%USERPROFILE%\.config\opencode\plugins\coucou.js` |
+| Amp | TypeScript plugin (`coucou.ts`) | `%USERPROFILE%\.config\amp\plugins\coucou.ts` |
+| Any other | `--agent <name>` positional arg | your tool's hook config |
+
+OpenCode and Amp use a plugin model. The plugin installer (**Settings → OpenCode Plugin** / **Settings → Amp Plugin**) is Mac-only: it installs a TypeScript/JavaScript file into `~/.config/opencode/plugins/` and `~/.config/amp/plugins/`, which are macOS paths. The Windows/Linux Tauri app does not ship a plugin installer for these two agents. To use them on Windows or Linux, generate the plugin file on a Mac (or write it by hand) and drop it into `%USERPROFILE%\.config\opencode\plugins\coucou.js` or `%USERPROFILE%\.config\amp\plugins\coucou.ts` as shown in the table above.
+
## What's different from the Mac version
- No notch, so the island lives at the top centre of the screen and retracts into