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.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Relay Claude Code hooks over a Unix socket on Linux
Salomão Davy5cdcade0e993
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex 4648fe32..98e9044a 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -629,6 +629,7 @@ dependencies = [name = "coucou-hook"version = "0.1.1"dependencies = [+ "libc","serde_json","windows 0.61.3",]diff --git a/windows/hook/Cargo.toml b/windows/hook/Cargo.tomlindex 18a01545..975ffc7c 100644--- a/windows/hook/Cargo.toml+++ b/windows/hook/Cargo.toml@@ -1,6 +1,6 @@[package]name = "coucou-hook"-description = "Relays Claude Code hook events to Coucou over a named pipe"+description = "Relays Claude Code hook events to Coucou over a named pipe (Windows) or a Unix socket (Linux)"version.workspace = trueedition.workspace = truelicense.workspace = true@@ -21,3 +21,7 @@ windows = { version = "0.61", features = ["Win32_System_Pipes","Win32_System_Threading",] }++# The socket syscalls and peer credentials the Linux transport needs.+[target.'cfg(target_os = "linux")'.dependencies]+libc = "0.2"diff --git a/windows/hook/src/main.rs b/windows/hook/src/main.rsindex 70ab3a3e..5bb36378 100644--- a/windows/hook/src/main.rs+++ b/windows/hook/src/main.rs@@ -1,7 +1,8 @@//! coucou-hook — the relay Claude Code runs on every hook event.//!//! Reads the hook JSON on stdin, adds a little terminal context, and hands it to-//! Coucou over the named pipe `\\.\pipe\coucou-<sid>`.+//! Coucou over the named pipe `\\.\pipe\coucou-<sid>` (Windows) or the Unix+//! socket `$XDG_RUNTIME_DIR/coucou.sock` (Linux).//!//! Hard rule (docs/CLAUDE.md): **never block Claude Code.**//! * If the pipe does not exist — Coucou is closed — we exit 0 immediately with@@ -17,7 +18,7 @@use std::io::{Read, Write};use std::sync::mpsc;-use std::time::{Duration, Instant};+use std::time::Duration;/// Budget for getting a pipe connection. Beyond this Claude Code wins, always.const CONNECT_TIMEOUT: Duration = Duration::from_millis(300);@@ -26,10 +27,6 @@ const FIRE_AND_FORGET_BUDGET: Duration = Duration::from_secs(2);/// How long a permission prompt may stay on screen before the terminal takes over.const DECISION_BUDGET: Duration = Duration::from_secs(110);-/// `ERROR_PIPE_BUSY` — every instance is serving someone else right now. This is-/// the one error worth retrying: the server exists and a slot will free up.-const ERROR_PIPE_BUSY: i32 = 231;-/// Fields that are pointless to forward and can be enormous (a whole file read,/// a full command output). The island never shows them.const DROPPED_FIELDS: &[&str] = &["tool_response", "transcript_path"];@@ -37,39 +34,15 @@ const DROPPED_FIELDS: &[&str] = &["tool_response", "transcript_path"];/// less than this anyway.const MAX_FIELD_LEN: usize = 2_000;+#[cfg(windows)]mod win;+#[cfg(windows)]+use win::connect;-/// `\\.\pipe\coucou-<sid>`. The SID keeps two accounts on the same machine from-/// ever meeting on the same pipe; the name falls back to the user name only if-/// the SID cannot be read at all, which should not happen.-fn pipe_path() -> String {- let key = win::current_user_sid()- .unwrap_or_else(|| std::env::var("USERNAME").unwrap_or_else(|_| "user".into()));- format!(r"\\.\pipe\coucou-{key}")-}--/// Opens the pipe. Retries only while the server is busy: any other error means-/// there is nothing to talk to, and waiting would only delay Claude Code.-fn connect() -> Option<std::fs::File> {- use std::os::windows::io::AsRawHandle;- let path = pipe_path();- let deadline = Instant::now() + CONNECT_TIMEOUT;- loop {- match std::fs::OpenOptions::new().read(true).write(true).open(&path) {- Ok(file) => {- let handle = windows::Win32::Foundation::HANDLE(file.as_raw_handle());- // Somebody else's server on our pipe name gets nothing from us.- return win::pipe_server_is_same_user(handle).then_some(file);- }- Err(err) => {- if err.raw_os_error() != Some(ERROR_PIPE_BUSY) || Instant::now() >= deadline {- return None;- }- std::thread::sleep(Duration::from_millis(15));- }- }- }-}+#[cfg(target_os = "linux")]+mod unix;+#[cfg(target_os = "linux")]+use unix::connect;fn main() {let Some((payload, event)) = read_event() else { std::process::exit(0) };@@ -173,7 +146,7 @@ fn read_event() -> Option<(String, String)> {}}- // Which terminal the session runs in. Unlike macOS, Coucou on Windows accepts+ // Which terminal the session runs in. Unlike macOS, Coucou here accepts// events from every terminal, so this is context only — never a filter.for (key, var) in [("term_program", "TERM_PROGRAM"),diff --git a/windows/hook/src/unix.rs b/windows/hook/src/unix.rsnew file mode 100644index 00000000..332e1faa--- /dev/null+++ b/windows/hook/src/unix.rs@@ -0,0 +1,104 @@+//! The Linux transport: a Unix socket in the user's runtime directory.+//!+//! `$XDG_RUNTIME_DIR` is private to the user (mode 0700), so nobody else can+//! even reach the socket. We still check, once connected, that the process on+//! the other end runs as us — the same promise the Windows relay makes with the+//! pipe server's SID, for the same price.++use std::io;+use std::os::unix::ffi::OsStrExt;+use std::os::unix::io::{AsRawFd, FromRawFd};+use std::os::unix::net::UnixStream;+use std::path::{Path, PathBuf};+use std::time::{Duration, Instant};++use crate::CONNECT_TIMEOUT;++/// `$XDG_RUNTIME_DIR/coucou.sock`, or `/run/user/<uid>/coucou.sock` when the+/// variable is missing (a hook started from a stripped-down environment).+/// Must match `platform::relay_socket_path()` in the app exactly.+fn socket_path() -> Option<PathBuf> {+ let dir = std::env::var_os("XDG_RUNTIME_DIR")+ .map(PathBuf::from)+ .filter(|p| p.is_absolute())+ .or_else(|| {+ let p = PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() }));+ p.is_dir().then_some(p)+ })?;+ Some(dir.join("coucou.sock"))+}++/// Opens the socket. Retries only while the app's backlog is full: any other+/// error — no socket, nobody listening — means there is nothing to talk to, and+/// waiting would only delay Claude Code.+pub fn connect() -> Option<UnixStream> {+ let path = socket_path()?;+ let deadline = Instant::now() + CONNECT_TIMEOUT;+ loop {+ match try_connect(&path) {+ // Somebody else's server on our socket gets nothing from us.+ Ok(stream) => return server_is_same_user(&stream).then_some(stream),+ Err(err) => {+ if err.raw_os_error() != Some(libc::EAGAIN) || Instant::now() >= deadline {+ return None;+ }+ std::thread::sleep(Duration::from_millis(15));+ }+ }+ }+}++/// A non-blocking connect, so a full backlog answers EAGAIN at once instead of+/// parking us until the app gets round to accepting. Blocking again afterwards:+/// the main thread's budget bounds every read and write.+fn try_connect(path: &Path) -> io::Result<UnixStream> {+ let fd = unsafe {+ libc::socket(libc::AF_UNIX, libc::SOCK_STREAM | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK, 0)+ };+ if fd < 0 {+ return Err(io::Error::last_os_error());+ }+ // Owns the descriptor from here on, so every early return closes it.+ let stream = unsafe { UnixStream::from_raw_fd(fd) };++ let mut addr: libc::sockaddr_un = unsafe { std::mem::zeroed() };+ addr.sun_family = libc::AF_UNIX as libc::sa_family_t;+ let bytes = path.as_os_str().as_bytes();+ // Room for the terminating NUL, which zeroed() already put there.+ if bytes.len() >= addr.sun_path.len() {+ return Err(io::Error::from(io::ErrorKind::InvalidInput));+ }+ for (dst, src) in addr.sun_path.iter_mut().zip(bytes) {+ *dst = *src as libc::c_char;+ }++ let rc = unsafe {+ libc::connect(+ fd,+ &addr as *const libc::sockaddr_un as *const libc::sockaddr,+ std::mem::size_of::<libc::sockaddr_un>() as libc::socklen_t,+ )+ };+ if rc != 0 {+ return Err(io::Error::last_os_error());+ }+ stream.set_nonblocking(false)?;+ Ok(stream)+}++/// True when the process serving the socket runs as the same user we do.+/// A failure to answer is treated as "not ours", as on Windows.+fn server_is_same_user(stream: &UnixStream) -> bool {+ let mut cred: libc::ucred = unsafe { std::mem::zeroed() };+ let mut len = std::mem::size_of::<libc::ucred>() as libc::socklen_t;+ let rc = unsafe {+ libc::getsockopt(+ stream.as_raw_fd(),+ libc::SOL_SOCKET,+ libc::SO_PEERCRED,+ &mut cred as *mut libc::ucred as *mut libc::c_void,+ &mut len,+ )+ };+ rc == 0 && cred.uid == unsafe { libc::getuid() }+}diff --git a/windows/hook/src/win.rs b/windows/hook/src/win.rsindex 75f1aa2e..edf514a5 100644--- a/windows/hook/src/win.rs+++ b/windows/hook/src/win.rs@@ -6,6 +6,8 @@//! the pipe name carries our SID, and once connected we check the server process//! really belongs to us before sending anything.+use std::time::{Duration, Instant};+use windows::core::PWSTR;use windows::Win32::Foundation::{CloseHandle, HANDLE, LocalFree, HLOCAL};use windows::Win32::Security::Authorization::ConvertSidToStringSidW;@@ -15,6 +17,44 @@ use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION,};+use crate::CONNECT_TIMEOUT;++/// `ERROR_PIPE_BUSY` — every instance is serving someone else right now. This is+/// the one error worth retrying: the server exists and a slot will free up.+const ERROR_PIPE_BUSY: i32 = 231;++/// `\\.\pipe\coucou-<sid>`. The SID keeps two accounts on the same machine from+/// ever meeting on the same pipe; the name falls back to the user name only if+/// the SID cannot be read at all, which should not happen.+fn pipe_path() -> String {+ let key = current_user_sid()+ .unwrap_or_else(|| std::env::var("USERNAME").unwrap_or_else(|_| "user".into()));+ format!(r"\\.\pipe\coucou-{key}")+}++/// Opens the pipe. Retries only while the server is busy: any other error means+/// there is nothing to talk to, and waiting would only delay Claude Code.+pub fn connect() -> Option<std::fs::File> {+ use std::os::windows::io::AsRawHandle;+ let path = pipe_path();+ let deadline = Instant::now() + CONNECT_TIMEOUT;+ loop {+ match std::fs::OpenOptions::new().read(true).write(true).open(&path) {+ Ok(file) => {+ let handle = HANDLE(file.as_raw_handle());+ // Somebody else's server on our pipe name gets nothing from us.+ return pipe_server_is_same_user(handle).then_some(file);+ }+ Err(err) => {+ if err.raw_os_error() != Some(ERROR_PIPE_BUSY) || Instant::now() >= deadline {+ return None;+ }+ std::thread::sleep(Duration::from_millis(15));+ }+ }+ }+}+/// The SID of the account this process runs as, as `S-1-5-21-…`.pub fn current_user_sid() -> Option<String> {unsafe { token_sid(GetCurrentProcess()) }diff --git a/windows/src-tauri/src/pipe.rs b/windows/src-tauri/src/pipe.rsindex 5554dc75..ab8480b0 100644--- a/windows/src-tauri/src/pipe.rs+++ b/windows/src-tauri/src/pipe.rs@@ -1,9 +1,10 @@-// Named-pipe server for coucou-hook.+// Relay server for coucou-hook.//-// `\\.\pipe\coucou-<sid>` — one instance per connection. Every hook event is+// Windows: the named pipe `\\.\pipe\coucou-<sid>`, one instance per connection.+// Linux: the Unix socket `$XDG_RUNTIME_DIR/coucou.sock`. Every hook event is// forwarded to the island as a `hook` event. `PermissionRequest` is the only one// that keeps its connection open: it waits for the island's decision and writes-// it back on the same pipe, which is how approving from the island works.+// it back on the same connection, which is how approving from the island works.//// Claude Code is never blocked by us. Three things guarantee it:// * coucou-hook gives the connection 300 ms and exits cleanly if we are closed;@@ -17,10 +18,6 @@// documented hookSpecificOutput JSON is coucou-hook's job, so the wire format// Claude Code expects lives in exactly one place.-// Until the Linux transport lands, the shared request/decision half of this-// file has no caller there.-#![cfg_attr(not(windows), allow(dead_code, unused_imports))]-use std::collections::HashMap;use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Mutex;@@ -28,8 +25,7 @@ use std::time::Duration;use serde_json::{json, Value};use tauri::{AppHandle, Emitter, Manager};-#[cfg(windows)]-use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};#[cfg(windows)]use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};use tokio::sync::mpsc;@@ -103,15 +99,73 @@ pub fn start(app: AppHandle) {});}-/// The relay transport on Linux is not written yet; until it is, hook events-/// never reach the island and Claude Code carries on as if Coucou were closed.#[cfg(target_os = "linux")]-pub fn start(_app: AppHandle) {- log::line("relay transport not available on this platform yet — hooks are inactive");+pub fn start(app: AppHandle) {+ use std::os::unix::fs::PermissionsExt;+ use tokio::net::UnixListener;++ tauri::async_runtime::spawn(async move {+ let Some(path) = crate::platform::relay_socket_path() else {+ log::line("no runtime directory — Claude Code hooks are inactive");+ return;+ };+ // A socket file left behind by a crash answers nothing and can go. One+ // that answers belongs to a Coucou that is still running: like+ // first_pipe_instance on Windows, we refuse to serve on top of it.+ if path.exists() {+ if std::os::unix::net::UnixStream::connect(&path).is_ok() {+ log::line("another Coucou already serves the relay socket");+ return;+ }+ let _ = std::fs::remove_file(&path);+ }+ let listener = match UnixListener::bind(&path) {+ Ok(l) => l,+ Err(err) => {+ log::line(format!("cannot open the relay socket: {err}"));+ return;+ }+ };+ // The runtime directory is already 0700; this is belt and braces.+ let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));+ let uid = unsafe { libc::getuid() };+ loop {+ let stream = match listener.accept().await {+ Ok((stream, _)) => stream,+ Err(_) => {+ tokio::time::sleep(Duration::from_millis(200)).await;+ continue;+ }+ };+ // Only the relay run by our own user may drive the island.+ if !matches!(stream.peer_cred(), Ok(c) if c.uid() == uid) {+ log::line("refused a relay connection from another user");+ continue;+ }+ let app = app.clone();+ tauri::async_runtime::spawn(async move { handle(app, stream).await });+ }+ });+}++/// One accepted relay connection, whatever carries it.+trait Relay: AsyncRead + AsyncWrite + Unpin {+ /// Ends the conversation once everything has been written.+ fn finish(&mut self) {}}#[cfg(windows)]-async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {+impl Relay for NamedPipeServer {+ fn finish(&mut self) {+ let _ = self.disconnect();+ }+}++/// Dropping the stream closes it; the relay reads up to our newline first.+#[cfg(target_os = "linux")]+impl Relay for tokio::net::UnixStream {}++async fn handle(app: AppHandle, mut pipe: impl Relay) {let mut buf = Vec::new();let mut chunk = [0u8; 4096];loop {@@ -144,7 +198,7 @@ async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {if event != "PermissionRequest" {log::line(format!("hook {event}"));let _ = app.emit_to(WINDOW_LABEL, "hook", payload);- let _ = pipe.disconnect();+ pipe.finish();return;}@@ -167,7 +221,7 @@ async fn handle(app: AppHandle, mut pipe: NamedPipeServer) {let _ = pipe.write_all(format!("{d}\n").as_bytes()).await;let _ = pipe.flush().await;}- let _ = pipe.disconnect();+ pipe.finish();}/// Two waits: a short one for "the card is up", then the long one for a human.diff --git a/windows/src-tauri/src/platform/linux.rs b/windows/src-tauri/src/platform/linux.rsindex d0a296f8..ec9b03f0 100644--- a/windows/src-tauri/src/platform/linux.rs+++ b/windows/src-tauri/src/platform/linux.rs@@ -56,6 +56,20 @@ pub fn local_time() -> LocalTime {}}+/// Where coucou-hook finds us: `$XDG_RUNTIME_DIR/coucou.sock`, or+/// `/run/user/<uid>/coucou.sock` when the variable is missing. Must match+/// `socket_path()` in hook/src/unix.rs exactly.+pub fn relay_socket_path() -> Option<PathBuf> {+ let dir = std::env::var_os("XDG_RUNTIME_DIR")+ .map(PathBuf::from)+ .filter(|p| p.is_absolute())+ .or_else(|| {+ let p = PathBuf::from(format!("/run/user/{}", unsafe { libc::getuid() }));+ p.is_dir().then_some(p)+ })?;+ Some(dir.join("coucou.sock"))+}+// ── Processes ─────────────────────────────────────────────────────────────────/// Nothing to hide: a spawned process only gets a terminal if it asks for one.diff --git a/windows/src-tauri/tauri.linux.conf.json b/windows/src-tauri/tauri.linux.conf.jsonindex 9d3dada0..6b802601 100644--- a/windows/src-tauri/tauri.linux.conf.json+++ b/windows/src-tauri/tauri.linux.conf.json@@ -1,6 +1,9 @@{"$schema": "https://schema.tauri.app/config/2","bundle": {- "resources": []+ "resources": {+ "../target/release/coucou-hook.exe": null,+ "../target/release/coucou-hook": "coucou-hook"+ }}}