taskmux 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
taskmux/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """
2
+ Taskmux - Modern tmux development environment manager
3
+
4
+ A dynamic tmux session manager with libtmux integration, health monitoring,
5
+ auto-restart capabilities, and WebSocket API for real-time communication.
6
+ """
7
+
8
+ __version__ = "2.0.0"
9
+ __author__ = "Taskmux Contributors"
10
+
11
+ from .config import TaskmuxConfig
12
+ from .tmux_manager import TmuxManager
13
+ from .daemon import TaskmuxDaemon
14
+ from .cli import TaskmuxCLI
15
+
16
+ __all__ = [
17
+ "TaskmuxConfig",
18
+ "TmuxManager",
19
+ "TaskmuxDaemon",
20
+ "TaskmuxCLI",
21
+ ]
taskmux/cli.py ADDED
@@ -0,0 +1,189 @@
1
+ """
2
+ Typer-based CLI interface for Taskmux.
3
+ """
4
+
5
+ import asyncio
6
+
7
+ import typer
8
+ from rich.console import Console
9
+ from rich.table import Table
10
+
11
+ from .config import TaskmuxConfig
12
+ from .daemon import SimpleConfigWatcher, TaskmuxDaemon
13
+ from .tmux_manager import TmuxManager
14
+
15
+ app = typer.Typer(
16
+ name="taskmux",
17
+ help="Modern tmux development environment manager with real-time health monitoring, auto-restart, and WebSocket API",
18
+ epilog="Uses libtmux API with health monitoring and daemon capabilities.",
19
+ rich_markup_mode="rich",
20
+ )
21
+
22
+ console = Console()
23
+
24
+
25
+ class TaskmuxCLI:
26
+ """Main CLI application class."""
27
+
28
+ def __init__(self):
29
+ self.config = TaskmuxConfig()
30
+ self.tmux = TmuxManager(self.config)
31
+
32
+ def handle_config_reload(self):
33
+ """Handle config file reload in daemon mode"""
34
+ # Check for new or changed tasks and restart them
35
+ current_windows = self.tmux.list_windows()
36
+
37
+ for task_name, command in self.config.tasks.items():
38
+ if task_name in current_windows:
39
+ # Task exists, check if command changed (simplified check)
40
+ console.print(f"🔄 Reloading task '{task_name}' due to config change")
41
+ self.tmux.restart_task(task_name)
42
+ else:
43
+ # New task, create window
44
+ if self.tmux.session_exists():
45
+ console.print(f"➕ Adding new task '{task_name}'")
46
+ self.tmux.restart_task(task_name) # This will create if not exists
47
+
48
+
49
+ @app.command()
50
+ def list():
51
+ """List all tasks and their status."""
52
+ cli = TaskmuxCLI()
53
+ cli.tmux.list_tasks()
54
+
55
+
56
+ @app.command()
57
+ def start():
58
+ """Start all tasks."""
59
+ cli = TaskmuxCLI()
60
+ cli.tmux.create_session()
61
+
62
+
63
+ @app.command()
64
+ def restart(
65
+ task: str = typer.Argument(..., help="Task name to restart"),
66
+ ):
67
+ """Restart a specific task."""
68
+ cli = TaskmuxCLI()
69
+ cli.tmux.restart_task(task)
70
+
71
+
72
+ @app.command()
73
+ def kill(
74
+ task: str = typer.Argument(..., help="Task name to kill"),
75
+ ):
76
+ """Kill a specific task."""
77
+ cli = TaskmuxCLI()
78
+ cli.tmux.kill_task(task)
79
+
80
+
81
+ @app.command()
82
+ def logs(
83
+ task: str = typer.Argument(..., help="Task name"),
84
+ follow: bool = typer.Option(False, "-f", "--follow", help="Follow logs"),
85
+ lines: int = typer.Option(100, "-n", "--lines", help="Number of lines"),
86
+ ):
87
+ """Show logs for a task."""
88
+ cli = TaskmuxCLI()
89
+ cli.tmux.show_logs(task, follow, lines)
90
+
91
+
92
+ @app.command()
93
+ def add(
94
+ task: str = typer.Argument(..., help="Task name"),
95
+ command: str = typer.Argument(..., help="Command to run"),
96
+ ):
97
+ """Add a new task."""
98
+ config = TaskmuxConfig()
99
+ config.add_task(task, command)
100
+ console.print(f"✓ Added task '{task}': {command}")
101
+
102
+
103
+ @app.command()
104
+ def remove(
105
+ task: str = typer.Argument(..., help="Task name to remove"),
106
+ ):
107
+ """Remove a task."""
108
+ cli = TaskmuxCLI()
109
+
110
+ # Kill the task if it's running
111
+ if cli.tmux.session_exists():
112
+ cli.tmux.kill_task(task)
113
+
114
+ # Remove from config
115
+ if cli.config.remove_task(task):
116
+ console.print(f"✓ Removed task '{task}'")
117
+ else:
118
+ console.print(f"Task '{task}' not found in config", style="red")
119
+
120
+
121
+ @app.command()
122
+ def status():
123
+ """Show session status."""
124
+ cli = TaskmuxCLI()
125
+ cli.tmux.show_status()
126
+
127
+
128
+ @app.command()
129
+ def health():
130
+ """Check health of all tasks."""
131
+ cli = TaskmuxCLI()
132
+
133
+ if not cli.tmux.session_exists():
134
+ console.print("No session running", style="yellow")
135
+ return
136
+
137
+ table = Table(title="🏥 Health Check Results")
138
+ table.add_column("Status", style="cyan")
139
+ table.add_column("Task", style="magenta")
140
+ table.add_column("Health", style="green")
141
+
142
+ healthy_count = 0
143
+ total_count = len(cli.config.tasks)
144
+
145
+ for task_name in cli.config.tasks:
146
+ is_healthy = cli.tmux.check_task_health(task_name)
147
+ status_icon = "💚" if is_healthy else "🔴"
148
+ status_text = "Healthy" if is_healthy else "Unhealthy"
149
+
150
+ table.add_row(status_icon, task_name, status_text)
151
+
152
+ if is_healthy:
153
+ healthy_count += 1
154
+
155
+ console.print(table)
156
+ console.print(f"Health: {healthy_count}/{total_count} tasks healthy")
157
+
158
+
159
+ @app.command()
160
+ def watch():
161
+ """Watch config file for changes."""
162
+ cli = TaskmuxCLI()
163
+ watcher = SimpleConfigWatcher(cli)
164
+ watcher.watch_config()
165
+
166
+
167
+ @app.command()
168
+ def daemon(
169
+ port: int = typer.Option(8765, "--port", help="WebSocket API port"),
170
+ ):
171
+ """Run in daemon mode with API."""
172
+ daemon = TaskmuxDaemon(api_port=port)
173
+ asyncio.run(daemon.start())
174
+
175
+
176
+ @app.command()
177
+ def stop():
178
+ """Stop the session and all tasks."""
179
+ cli = TaskmuxCLI()
180
+ cli.tmux.stop_session()
181
+
182
+
183
+ def main():
184
+ """Main entry point for the CLI."""
185
+ app()
186
+
187
+
188
+ if __name__ == "__main__":
189
+ main()
taskmux/config.py ADDED
@@ -0,0 +1,57 @@
1
+ """
2
+ Taskmux configuration management.
3
+ """
4
+
5
+ import json
6
+ import sys
7
+ from typing import Dict
8
+
9
+
10
+ class TaskmuxConfig:
11
+ """Manages taskmux.json configuration file loading and validation."""
12
+
13
+ def __init__(self, config_path: str = "taskmux.json"):
14
+ self.config_path = config_path
15
+ self.config = {}
16
+ self.load_config()
17
+
18
+ def load_config(self):
19
+ """Load configuration from JSON file"""
20
+ try:
21
+ with open(self.config_path, "r") as f:
22
+ self.config = json.load(f)
23
+ print(f"✓ Loaded config from {self.config_path}")
24
+ except FileNotFoundError:
25
+ print(f"Error: Config file {self.config_path} not found")
26
+ sys.exit(1)
27
+ except json.JSONDecodeError as e:
28
+ print(f"Error: Invalid JSON in {self.config_path}: {e}")
29
+ sys.exit(1)
30
+
31
+ def save_config(self):
32
+ """Save current configuration to JSON file"""
33
+ with open(self.config_path, "w") as f:
34
+ json.dump(self.config, f, indent=2)
35
+
36
+ @property
37
+ def session_name(self) -> str:
38
+ """Get the tmux session name"""
39
+ return self.config.get("name", "taskmux")
40
+
41
+ @property
42
+ def tasks(self) -> Dict[str, str]:
43
+ """Get the tasks dictionary"""
44
+ return self.config.get("tasks", {})
45
+
46
+ def add_task(self, task_name: str, command: str):
47
+ """Add a new task to the configuration"""
48
+ self.config.setdefault("tasks", {})[task_name] = command
49
+ self.save_config()
50
+
51
+ def remove_task(self, task_name: str) -> bool:
52
+ """Remove a task from the configuration. Returns True if task was found and removed."""
53
+ if task_name not in self.tasks:
54
+ return False
55
+ del self.config["tasks"][task_name]
56
+ self.save_config()
57
+ return True
taskmux/daemon.py ADDED
@@ -0,0 +1,278 @@
1
+ """
2
+ Daemon mode for Taskmux with enhanced monitoring and WebSocket API.
3
+ """
4
+
5
+ import asyncio
6
+ import json
7
+ import logging
8
+ import signal
9
+ import sys
10
+ from datetime import datetime
11
+ from pathlib import Path
12
+ from typing import Set
13
+
14
+ import websockets
15
+ from watchdog.events import FileSystemEventHandler
16
+ from watchdog.observers import Observer
17
+
18
+
19
+ class ConfigWatcher(FileSystemEventHandler):
20
+ """File system event handler for monitoring config file changes."""
21
+
22
+ def __init__(self, taskmux_cli, daemon_mode=False):
23
+ self.taskmux_cli = taskmux_cli
24
+ self.daemon_mode = daemon_mode
25
+
26
+ def on_modified(self, event):
27
+ if event.src_path.endswith("taskmux.json"):
28
+ print("\n🔄 Config file changed, reloading...")
29
+ self.taskmux_cli.config.load_config()
30
+
31
+ # In daemon mode, restart affected tasks
32
+ if self.daemon_mode:
33
+ self.taskmux_cli.handle_config_reload()
34
+
35
+
36
+ class TaskmuxDaemon:
37
+ """Daemon mode for Taskmux with enhanced monitoring and API"""
38
+
39
+ def __init__(self, config_path: str = "taskmux.json", api_port: int = 8765):
40
+ self.config_path = config_path
41
+ self.api_port = api_port
42
+ self.running = False
43
+ self.cli = None
44
+ self.observer = None
45
+ self.health_check_interval = 30 # seconds
46
+ self.health_check_task = None
47
+ self.websocket_clients: Set = set()
48
+ self.logger = self._setup_logging()
49
+
50
+ # Setup signal handlers
51
+ signal.signal(signal.SIGINT, self._signal_handler)
52
+ signal.signal(signal.SIGTERM, self._signal_handler)
53
+
54
+ def _setup_logging(self) -> logging.Logger:
55
+ """Setup logging for daemon mode"""
56
+ logger = logging.getLogger("taskmux-daemon")
57
+ logger.setLevel(logging.INFO)
58
+
59
+ # Console handler
60
+ console_handler = logging.StreamHandler()
61
+ console_handler.setLevel(logging.INFO)
62
+ formatter = logging.Formatter(
63
+ "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
64
+ )
65
+ console_handler.setFormatter(formatter)
66
+ logger.addHandler(console_handler)
67
+
68
+ # File handler
69
+ log_file = Path.home() / ".taskmux" / "daemon.log"
70
+ log_file.parent.mkdir(exist_ok=True)
71
+ file_handler = logging.FileHandler(log_file)
72
+ file_handler.setLevel(logging.DEBUG)
73
+ file_handler.setFormatter(formatter)
74
+ logger.addHandler(file_handler)
75
+
76
+ return logger
77
+
78
+ def _signal_handler(self, signum, frame):
79
+ """Handle shutdown signals"""
80
+ self.logger.info(f"Received signal {signum}, shutting down...")
81
+ self.stop()
82
+ sys.exit(0)
83
+
84
+ async def start(self):
85
+ """Start daemon mode with monitoring and API"""
86
+ self.running = True
87
+
88
+ # Import here to avoid circular import
89
+ from .cli import TaskmuxCLI
90
+
91
+ self.cli = TaskmuxCLI()
92
+
93
+ self.logger.info(f"Starting Taskmux daemon for config: {self.config_path}")
94
+
95
+ # Start file watching
96
+ self.observer = Observer()
97
+ self.observer.schedule(
98
+ ConfigWatcher(self.cli, daemon_mode=True), ".", recursive=False
99
+ )
100
+ self.observer.start()
101
+ self.logger.info("Started config file watcher")
102
+
103
+ # Start health checking
104
+ self.health_check_task = asyncio.create_task(self._health_check_loop())
105
+
106
+ # Start WebSocket API server
107
+ api_task = asyncio.create_task(self._start_api_server())
108
+
109
+ self.logger.info(f"Taskmux daemon started on port {self.api_port}")
110
+ self.logger.info("Use Ctrl+C to stop")
111
+
112
+ try:
113
+ await asyncio.gather(self.health_check_task, api_task)
114
+ except asyncio.CancelledError:
115
+ self.logger.info("Daemon tasks cancelled")
116
+
117
+ def stop(self):
118
+ """Stop daemon mode"""
119
+ self.running = False
120
+
121
+ if self.observer:
122
+ self.observer.stop()
123
+ self.observer.join()
124
+
125
+ if self.health_check_task and not self.health_check_task.done():
126
+ self.health_check_task.cancel()
127
+
128
+ self.logger.info("Taskmux daemon stopped")
129
+
130
+ async def _health_check_loop(self):
131
+ """Continuous health checking loop"""
132
+ while self.running:
133
+ try:
134
+ if self.cli and self.cli.tmux.session_exists():
135
+ self.cli.tmux.auto_restart_unhealthy_tasks()
136
+
137
+ # Broadcast health status to WebSocket clients
138
+ if self.websocket_clients:
139
+ status = await self._get_full_status()
140
+ await self._broadcast_to_clients(
141
+ {"type": "health_check", "data": status}
142
+ )
143
+
144
+ await asyncio.sleep(self.health_check_interval)
145
+ except Exception as e:
146
+ self.logger.error(f"Health check error: {e}")
147
+ await asyncio.sleep(5) # Short sleep on error
148
+
149
+ async def _start_api_server(self):
150
+ """Start WebSocket API server"""
151
+
152
+ async def handle_client(websocket, path):
153
+ self.websocket_clients.add(websocket)
154
+ self.logger.info(
155
+ f"New WebSocket client connected: {websocket.remote_address}"
156
+ )
157
+
158
+ try:
159
+ async for message in websocket:
160
+ try:
161
+ data = json.loads(message)
162
+ response = await self._handle_api_request(data)
163
+ await websocket.send(json.dumps(response))
164
+ except json.JSONDecodeError:
165
+ await websocket.send(json.dumps({"error": "Invalid JSON"}))
166
+ except Exception as e:
167
+ await websocket.send(json.dumps({"error": str(e)}))
168
+ except websockets.exceptions.ConnectionClosed:
169
+ pass
170
+ finally:
171
+ self.websocket_clients.discard(websocket)
172
+ self.logger.info(
173
+ f"WebSocket client disconnected: {websocket.remote_address}"
174
+ )
175
+
176
+ start_server = websockets.serve(handle_client, "localhost", self.api_port)
177
+ await start_server
178
+
179
+ async def _handle_api_request(self, data: dict) -> dict:
180
+ """Handle WebSocket API requests"""
181
+ command = data.get("command")
182
+ params = data.get("params", {})
183
+
184
+ if command == "status":
185
+ return await self._get_full_status()
186
+ elif command == "restart":
187
+ task_name = params.get("task")
188
+ if task_name:
189
+ self.cli.tmux.restart_task(task_name)
190
+ return {"success": True, "message": f"Restarted {task_name}"}
191
+ return {"error": "Task name required"}
192
+ elif command == "kill":
193
+ task_name = params.get("task")
194
+ if task_name:
195
+ self.cli.tmux.kill_task(task_name)
196
+ return {"success": True, "message": f"Killed {task_name}"}
197
+ return {"error": "Task name required"}
198
+ elif command == "logs":
199
+ task_name = params.get("task")
200
+ lines = params.get("lines", 100)
201
+ if task_name and self.cli.tmux.session_exists():
202
+ # Get logs via libtmux
203
+ try:
204
+ window = self.cli.tmux.session.windows.get(window_name=task_name)
205
+ if window:
206
+ pane = window.active_pane
207
+ output = pane.cmd(
208
+ "capture-pane", "-p", "-S", f"-{lines}"
209
+ ).stdout
210
+ return {"success": True, "logs": output}
211
+ except Exception:
212
+ pass
213
+ return {"error": "Could not retrieve logs"}
214
+ else:
215
+ return {"error": f"Unknown command: {command}"}
216
+
217
+ async def _get_full_status(self) -> dict:
218
+ """Get comprehensive status information"""
219
+ if not self.cli:
220
+ return {"error": "CLI not initialized"}
221
+
222
+ session_exists = self.cli.tmux.session_exists()
223
+ tasks_status = {}
224
+
225
+ for task_name in self.cli.config.tasks:
226
+ tasks_status[task_name] = self.cli.tmux.get_task_status(task_name)
227
+
228
+ return {
229
+ "session_name": self.cli.config.session_name,
230
+ "session_exists": session_exists,
231
+ "tasks": tasks_status,
232
+ "api_type": "libtmux",
233
+ "timestamp": datetime.now().isoformat(),
234
+ }
235
+
236
+ async def _broadcast_to_clients(self, message: dict):
237
+ """Broadcast message to all connected WebSocket clients"""
238
+ if not self.websocket_clients:
239
+ return
240
+
241
+ message_str = json.dumps(message)
242
+ disconnected = set()
243
+
244
+ for client in self.websocket_clients:
245
+ try:
246
+ await client.send(message_str)
247
+ except:
248
+ disconnected.add(client)
249
+
250
+ # Remove disconnected clients
251
+ self.websocket_clients -= disconnected
252
+
253
+
254
+ class SimpleConfigWatcher:
255
+ """Simple config file watcher for non-daemon mode."""
256
+
257
+ def __init__(self, taskmux_cli):
258
+ self.taskmux_cli = taskmux_cli
259
+
260
+ def watch_config(self):
261
+ """Watch config file for changes"""
262
+ print(f"👀 Watching {self.taskmux_cli.config.config_path} for changes...")
263
+ print("Press Ctrl+C to stop")
264
+
265
+ observer = Observer()
266
+ observer.schedule(ConfigWatcher(self.taskmux_cli), ".", recursive=False)
267
+ observer.start()
268
+
269
+ try:
270
+ import time
271
+
272
+ while True:
273
+ time.sleep(1)
274
+ except KeyboardInterrupt:
275
+ observer.stop()
276
+ print("\n👋 Stopped watching")
277
+
278
+ observer.join()
taskmux/main.py ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Taskmux - Modern tmux development environment manager
4
+
5
+ Entry point that delegates to the Typer-based CLI.
6
+ """
7
+
8
+ from .cli import main
9
+
10
+ if __name__ == "__main__":
11
+ main()
File without changes
@@ -0,0 +1,259 @@
1
+ """
2
+ Tmux session and task management.
3
+ """
4
+
5
+ import time
6
+ from datetime import datetime
7
+ from typing import Dict, List, Union
8
+
9
+ import libtmux
10
+
11
+ from .config import TaskmuxConfig
12
+
13
+
14
+ class TmuxManager:
15
+ """Manages tmux sessions and tasks using libtmux API."""
16
+
17
+ def __init__(self, config: TaskmuxConfig):
18
+ self.config = config
19
+ self.server = libtmux.Server()
20
+ self.session = None
21
+ self.task_health = {} # Track task health status
22
+ self._refresh_session()
23
+
24
+ def _refresh_session(self):
25
+ """Refresh session object from server"""
26
+ try:
27
+ self.session = self.server.sessions.get(
28
+ session_name=self.config.session_name
29
+ )
30
+ except Exception:
31
+ self.session = None
32
+
33
+ def session_exists(self) -> bool:
34
+ """Check if tmux session exists"""
35
+ self._refresh_session()
36
+ return self.session is not None
37
+
38
+ def list_windows(self) -> List[str]:
39
+ """List all windows in the session"""
40
+ if not self.session_exists():
41
+ return []
42
+
43
+ try:
44
+ return [window.window_name for window in self.session.windows]
45
+ except Exception:
46
+ return []
47
+
48
+ def get_task_status(self, task_name: str) -> Dict[str, Union[str, bool]]:
49
+ """Get detailed status for a task"""
50
+ status = {
51
+ "name": task_name,
52
+ "running": False,
53
+ "healthy": False,
54
+ "command": self.config.tasks.get(task_name, ""),
55
+ "last_check": datetime.now().isoformat(),
56
+ }
57
+
58
+ if not self.session_exists():
59
+ return status
60
+
61
+ windows = self.list_windows()
62
+ status["running"] = task_name in windows
63
+
64
+ if self.session and status["running"]:
65
+ try:
66
+ window = self.session.windows.get(window_name=task_name)
67
+ if window:
68
+ # Check if process is still running
69
+ pane = window.active_pane
70
+ current_command = getattr(pane, "pane_current_command", "")
71
+ status["healthy"] = (
72
+ current_command != "" and current_command != "bash"
73
+ )
74
+ except Exception:
75
+ pass
76
+
77
+ return status
78
+
79
+ def create_session(self):
80
+ """Create new tmux session with all tasks"""
81
+ if self.session_exists():
82
+ print(f"Session '{self.config.session_name}' already exists")
83
+ return
84
+
85
+ tasks = list(self.config.tasks.items())
86
+ if not tasks:
87
+ print("No tasks defined in config")
88
+ return
89
+
90
+ # Create session with libtmux
91
+ self.session = self.server.new_session(
92
+ session_name=self.config.session_name, attach=False
93
+ )
94
+
95
+ # Rename the default window to first task, then create remaining tasks
96
+ first_task, first_command = tasks[0]
97
+ if self.session.windows:
98
+ # Rename default window to first task
99
+ default_window = self.session.windows[0]
100
+ default_window.rename_window(first_task)
101
+ # Send command to the window
102
+ pane = default_window.active_pane
103
+ pane.send_keys(first_command, enter=True)
104
+
105
+ # Create windows for remaining tasks
106
+ for task_name, command in tasks[1:]:
107
+ window = self.session.new_window(
108
+ attach=False, window_name=task_name
109
+ )
110
+ # Send command to the window
111
+ pane = window.active_pane
112
+ pane.send_keys(command, enter=True)
113
+
114
+ print(
115
+ f"✓ Created session '{self.config.session_name}' with {len(tasks)} tasks"
116
+ )
117
+
118
+ def restart_task(self, task_name: str):
119
+ """Restart a specific task"""
120
+ if not self.session_exists():
121
+ print(
122
+ f"Session '{self.config.session_name}' doesn't exist. Run 'taskmux start' first."
123
+ )
124
+ return
125
+
126
+ if task_name not in self.config.tasks:
127
+ print(f"Task '{task_name}' not found in config")
128
+ return
129
+
130
+ command = self.config.tasks[task_name]
131
+
132
+ window = self.session.windows.get(window_name=task_name)
133
+ if window:
134
+ # Kill current process and restart
135
+ pane = window.active_pane
136
+ pane.send_keys("C-c")
137
+ time.sleep(0.5)
138
+ pane.send_keys(command, enter=True)
139
+ else:
140
+ # Create new window
141
+ window = self.session.new_window(
142
+ attach=False, window_name=task_name
143
+ )
144
+ pane = window.active_pane
145
+ pane.send_keys(command, enter=True)
146
+
147
+ print(f"✓ Restarted task '{task_name}'")
148
+
149
+ def kill_task(self, task_name: str):
150
+ """Kill a specific task"""
151
+ if not self.session_exists():
152
+ print(f"Session '{self.config.session_name}' doesn't exist")
153
+ return
154
+
155
+ window = self.session.windows.get(window_name=task_name)
156
+ if window:
157
+ window.kill()
158
+ print(f"✓ Killed task '{task_name}'")
159
+ else:
160
+ print(f"Task '{task_name}' not found")
161
+
162
+ def show_logs(self, task_name: str, follow: bool = False, lines: int = 100):
163
+ """Show logs for a task"""
164
+ if not self.session_exists():
165
+ print(f"Session '{self.config.session_name}' doesn't exist")
166
+ return
167
+
168
+ if task_name not in self.config.tasks:
169
+ print(f"Task '{task_name}' not found in config")
170
+ return
171
+
172
+ window = self.session.windows.get(window_name=task_name)
173
+ if not window:
174
+ print(f"Task '{task_name}' not found")
175
+ return
176
+
177
+ if follow:
178
+ # Attach to the window to follow logs
179
+ window.select_window()
180
+ self.session.attach()
181
+ else:
182
+ # Show recent logs
183
+ pane = window.active_pane
184
+ output = pane.cmd(
185
+ "capture-pane", "-p", "-S", f"-{lines}"
186
+ ).stdout
187
+ for line in output:
188
+ print(line)
189
+
190
+ def list_tasks(self):
191
+ """List all tasks and their status"""
192
+ print(f"Session: {self.config.session_name}")
193
+ print("─" * 70)
194
+
195
+ if not self.config.tasks:
196
+ print("No tasks configured")
197
+ return
198
+
199
+ for task_name, command in self.config.tasks.items():
200
+ status = self.get_task_status(task_name)
201
+ health_icon = (
202
+ "💚" if status["healthy"] else "🔴" if status["running"] else "○"
203
+ )
204
+ status_text = (
205
+ "Healthy"
206
+ if status["healthy"]
207
+ else "Running"
208
+ if status["running"]
209
+ else "Stopped"
210
+ )
211
+ print(f"{health_icon} {status_text:8} {task_name:15} {command}")
212
+
213
+ def show_status(self):
214
+ """Show overall session status"""
215
+ exists = self.session_exists()
216
+ print(
217
+ f"Session '{self.config.session_name}': {'Running' if exists else 'Stopped'} (libtmux)"
218
+ )
219
+
220
+ if exists:
221
+ windows = self.list_windows()
222
+ print(f"Active tasks: {len(windows)}")
223
+ self.list_tasks()
224
+
225
+ def check_task_health(self, task_name: str) -> bool:
226
+ """Check if a task is healthy (process still running)"""
227
+ status = self.get_task_status(task_name)
228
+ is_healthy = status["running"] and status["healthy"]
229
+
230
+ # Update health tracking
231
+ self.task_health[task_name] = {
232
+ "healthy": is_healthy,
233
+ "last_check": datetime.now(),
234
+ "status": status,
235
+ }
236
+
237
+ return is_healthy
238
+
239
+ def auto_restart_unhealthy_tasks(self):
240
+ """Auto-restart tasks that have become unhealthy"""
241
+ if not self.session_exists():
242
+ return
243
+
244
+ for task_name in self.config.tasks:
245
+ if not self.check_task_health(task_name):
246
+ # Check if it was previously healthy (avoid restart loops)
247
+ prev_health = self.task_health.get(task_name, {}).get("healthy", True)
248
+ if prev_health: # Only restart if it was previously healthy
249
+ print(f"🔄 Auto-restarting unhealthy task: {task_name}")
250
+ self.restart_task(task_name)
251
+
252
+ def stop_session(self):
253
+ """Stop the entire tmux session"""
254
+ if not self.session_exists():
255
+ print("No session running")
256
+ return
257
+
258
+ self.session.kill()
259
+ print(f"✓ Stopped session '{self.config.session_name}'")
@@ -0,0 +1,451 @@
1
+ Metadata-Version: 2.4
2
+ Name: taskmux
3
+ Version: 0.1.0
4
+ Summary: Modern tmux development environment manager with real-time health monitoring, auto-restart, and WebSocket API
5
+ Project-URL: Homepage, https://github.com/nc9/taskmux
6
+ Project-URL: Repository, https://github.com/nc9/taskmux
7
+ Project-URL: Issues, https://github.com/nc9/taskmux/issues
8
+ Author-email: Nik Cubrilovic <git@nikcub.me>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: daemon,development,manager,monitoring,session,terminal,tmux
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Software Development :: Build Tools
25
+ Classifier: Topic :: System :: Monitoring
26
+ Classifier: Topic :: Terminals
27
+ Requires-Python: >=3.8
28
+ Requires-Dist: aiofiles>=23.0.0
29
+ Requires-Dist: aiohttp>=3.9.0
30
+ Requires-Dist: libtmux>=0.37.0
31
+ Requires-Dist: rich>=13.0.0
32
+ Requires-Dist: typer>=0.12.0
33
+ Requires-Dist: watchdog>=3.0.0
34
+ Requires-Dist: websockets>=12.0
35
+ Description-Content-Type: text/markdown
36
+
37
+ # Taskmux
38
+
39
+ A modern tmux development environment manager with real-time health monitoring, auto-restart capabilities, and WebSocket API. Built with Python using libtmux for reliable session management.
40
+
41
+ ## Why Taskmux?
42
+
43
+ Instead of manually managing multiple tmux windows or remembering complex command sequences, Taskmux provides:
44
+
45
+ - **Dynamic task management**: Define tasks in JSON, manage via modern CLI
46
+ - **Health monitoring**: Real-time task health checks with visual indicators
47
+ - **Auto-restart**: Automatically restart failed tasks to keep development flowing
48
+ - **WebSocket API**: Real-time status updates and remote task management
49
+ - **Rich CLI**: Beautiful terminal output with Typer and Rich integration
50
+ - **File watching**: Automatically detects config changes and reloads tasks
51
+ - **Zero setup**: Single command installation with uv tool management
52
+
53
+ ## Installation
54
+
55
+ ### Prerequisites
56
+
57
+ - [tmux](https://github.com/tmux/tmux) - Terminal multiplexer
58
+ - [uv](https://docs.astral.sh/uv/) - Modern Python package manager
59
+
60
+ ### Install uv (if you don't have it)
61
+
62
+ **Quick install** (macOS/Linux):
63
+ ```bash
64
+ curl -LsSf https://astral.sh/uv/install.sh | sh
65
+ ```
66
+
67
+ **Windows**:
68
+ ```powershell
69
+ powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
70
+ ```
71
+
72
+ **Alternative methods**:
73
+ ```bash
74
+ # Via Homebrew (macOS)
75
+ brew install uv
76
+
77
+ # Via pipx
78
+ pipx install uv
79
+
80
+ # Via WinGet (Windows)
81
+ winget install --id=astral-sh.uv -e
82
+ ```
83
+
84
+ ### Install Taskmux
85
+
86
+ **Recommended** (installs globally):
87
+ ```bash
88
+ uv tool install taskmux
89
+ ```
90
+
91
+ **From source**:
92
+ ```bash
93
+ git clone https://github.com/your-repo/taskmux
94
+ cd taskmux
95
+ uv tool install .
96
+ ```
97
+
98
+ After installation, `taskmux` command will be available globally.
99
+
100
+ ## Quick Start
101
+
102
+ 1. **Create config file** in your project root:
103
+
104
+ ```json
105
+ {
106
+ "name": "myproject",
107
+ "tasks": {
108
+ "server": "npm run dev",
109
+ "build": "npm run build:watch",
110
+ "test": "npm run test:watch",
111
+ "db": "docker-compose up postgres"
112
+ }
113
+ }
114
+ ```
115
+
116
+ 2. **Start all tasks**:
117
+ ```bash
118
+ taskmux start
119
+ ```
120
+
121
+ 3. **Monitor and manage**:
122
+ ```bash
123
+ taskmux list # See what's running with health status
124
+ taskmux health # Detailed health check table
125
+ taskmux restart server # Restart specific task
126
+ taskmux logs -f test # Follow logs
127
+ ```
128
+
129
+ ## Commands Reference
130
+
131
+ ### Core Commands
132
+
133
+ ```bash
134
+ # Session Management
135
+ taskmux start # Start all tasks in tmux session
136
+ taskmux status # Show session and task status
137
+ taskmux list # List all tasks with health indicators
138
+ taskmux stop # Stop session and all tasks
139
+
140
+ # Task Management
141
+ taskmux restart <task> # Restart specific task
142
+ taskmux kill <task> # Kill specific task
143
+ taskmux add <task> "<command>" # Add new task to config
144
+ taskmux remove <task> # Remove task from config
145
+
146
+ # Monitoring
147
+ taskmux health # Health check with status table
148
+ taskmux logs <task> # Show recent logs
149
+ taskmux logs -f <task> # Follow logs (live)
150
+ taskmux logs -n 100 <task> # Show last N lines
151
+
152
+ # Advanced
153
+ taskmux watch # Watch config for changes
154
+ taskmux daemon --port 8765 # Run with WebSocket API
155
+ ```
156
+
157
+ ### Command Examples
158
+
159
+ ```bash
160
+ # Start development environment
161
+ taskmux start
162
+
163
+ # Check what's running with health status
164
+ taskmux list
165
+ # Output:
166
+ # Session: myproject
167
+ # ──────────────────────────────────────────────────
168
+ # 💚 Healthy server npm run dev
169
+ # 💚 Healthy build npm run build:watch
170
+ # 🔴 Unhealthy test npm run test:watch
171
+ # 💚 Healthy db docker-compose up postgres
172
+
173
+ # Detailed health check
174
+ taskmux health
175
+ # ┏━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━┓
176
+ # ┃ Status ┃ Task ┃ Health ┃
177
+ # ┡━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━┩
178
+ # │ 💚 │ server │ Healthy │
179
+ # │ 💚 │ build │ Healthy │
180
+ # │ 🔴 │ test │ Unhealthy │
181
+ # │ 💚 │ db │ Healthy │
182
+ # └────────┴─────────┴───────────┘
183
+
184
+ # Restart a misbehaving service
185
+ taskmux restart server
186
+
187
+ # Add a new background task
188
+ taskmux add worker "python background_worker.py"
189
+
190
+ # Follow logs for debugging
191
+ taskmux logs -f test
192
+
193
+ # Watch config file for changes
194
+ taskmux watch
195
+ ```
196
+
197
+ ## Configuration
198
+
199
+ ### Config File Format
200
+
201
+ Create `taskmux.json` in your project root:
202
+
203
+ ```json
204
+ {
205
+ "name": "session-name",
206
+ "tasks": {
207
+ "task-name": "command to run",
208
+ "another-task": "another command"
209
+ }
210
+ }
211
+ ```
212
+
213
+ ### Config Examples
214
+
215
+ **Web Development**:
216
+ ```json
217
+ {
218
+ "name": "webapp",
219
+ "tasks": {
220
+ "frontend": "npm run dev",
221
+ "backend": "python manage.py runserver",
222
+ "database": "docker-compose up -d postgres",
223
+ "redis": "redis-server",
224
+ "worker": "celery worker -A myapp",
225
+ "tailwind": "npx tailwindcss -w"
226
+ }
227
+ }
228
+ ```
229
+
230
+ **Data Science**:
231
+ ```json
232
+ {
233
+ "name": "analysis",
234
+ "tasks": {
235
+ "jupyter": "jupyter lab --port=8888",
236
+ "mlflow": "mlflow ui --port=5000",
237
+ "airflow": "airflow webserver",
238
+ "postgres": "docker run -p 5432:5432 postgres:13",
239
+ "tensorboard": "tensorboard --logdir=./logs"
240
+ }
241
+ }
242
+ ```
243
+
244
+ **Microservices**:
245
+ ```json
246
+ {
247
+ "name": "microservices",
248
+ "tasks": {
249
+ "api-gateway": "node gateway/server.js",
250
+ "user-service": "go run services/user/main.go",
251
+ "order-service": "python services/orders/app.py",
252
+ "redis": "redis-server",
253
+ "postgres": "docker-compose up -d db",
254
+ "monitoring": "prometheus --config.file=prometheus.yml"
255
+ }
256
+ }
257
+ ```
258
+
259
+ ## Advanced Features
260
+
261
+ ### Daemon Mode with WebSocket API
262
+
263
+ Run Taskmux as a background daemon with real-time API:
264
+
265
+ ```bash
266
+ # Start daemon on port 8765 (default)
267
+ taskmux daemon
268
+
269
+ # Custom port
270
+ taskmux daemon --port 9000
271
+ ```
272
+
273
+ **WebSocket API Usage**:
274
+ ```javascript
275
+ // Connect to WebSocket API
276
+ const ws = new WebSocket('ws://localhost:8765');
277
+
278
+ // Get status
279
+ ws.send(JSON.stringify({
280
+ command: "status"
281
+ }));
282
+
283
+ // Restart task
284
+ ws.send(JSON.stringify({
285
+ command: "restart",
286
+ params: { task: "server" }
287
+ }));
288
+
289
+ // Get logs
290
+ ws.send(JSON.stringify({
291
+ command: "logs",
292
+ params: { task: "server", lines: 50 }
293
+ }));
294
+ ```
295
+
296
+ ### Health Monitoring & Auto-restart
297
+
298
+ Taskmux continuously monitors task health and can auto-restart failed processes:
299
+
300
+ - **Health indicators**: 💚 Healthy, 🔴 Unhealthy, ○ Stopped
301
+ - **Process monitoring**: Detects when tasks exit or become unresponsive
302
+ - **Auto-restart**: Daemon mode automatically restarts failed tasks
303
+ - **Health checks**: Run `taskmux health` for detailed status
304
+
305
+ ### File Watching
306
+
307
+ Monitor config changes in real-time:
308
+
309
+ ```bash
310
+ # Terminal 1: Start file watcher
311
+ taskmux watch
312
+
313
+ # Terminal 2: Edit config
314
+ echo '{"name": "test", "tasks": {"new": "echo hello"}}' > taskmux.json
315
+ # Watcher automatically reloads config and updates running tasks
316
+
317
+ # New task is immediately available
318
+ taskmux restart new
319
+ ```
320
+
321
+ ## Workflow Integration
322
+
323
+ ### Daily Development
324
+
325
+ ```bash
326
+ # Morning: Start everything
327
+ taskmux start
328
+
329
+ # During development: Monitor health
330
+ taskmux health
331
+
332
+ # Restart services as needed
333
+ taskmux restart api
334
+ taskmux logs -f frontend
335
+
336
+ # Add new services on the fly
337
+ taskmux add monitoring "python monitor.py"
338
+
339
+ # Run with file watching for config changes
340
+ taskmux watch
341
+
342
+ # Evening: Stop everything
343
+ taskmux stop
344
+ ```
345
+
346
+ ### Tmux Integration
347
+
348
+ Taskmux creates standard tmux sessions. You can use all tmux commands:
349
+
350
+ ```bash
351
+ # Attach to session
352
+ tmux attach-session -t myproject
353
+
354
+ # Switch between task windows
355
+ # Ctrl+b 1, Ctrl+b 2, etc.
356
+
357
+ # Create additional windows
358
+ tmux new-window -t myproject -n shell
359
+
360
+ # Detach and reattach later
361
+ # Ctrl+b d
362
+ tmux attach-session -t myproject
363
+ ```
364
+
365
+ ### Multiple Projects
366
+
367
+ Each project gets its own tmux session based on the `name` field:
368
+
369
+ ```bash
370
+ # Project A (session: "webapp")
371
+ cd ~/projects/webapp
372
+ taskmux start
373
+
374
+ # Project B (session: "api")
375
+ cd ~/projects/api
376
+ taskmux start
377
+
378
+ # Both run simultaneously with separate sessions
379
+ tmux list-sessions
380
+ # webapp: 4 windows
381
+ # api: 2 windows
382
+ ```
383
+
384
+ ## Architecture
385
+
386
+ Taskmux is built with modern Python tooling:
387
+
388
+ - **libtmux**: Reliable Python API for tmux session management
389
+ - **Typer**: Modern CLI framework with rich help and validation
390
+ - **Rich**: Beautiful terminal output with tables and progress bars
391
+ - **WebSockets**: Real-time API for remote monitoring and control
392
+ - **asyncio**: Async health monitoring and daemon capabilities
393
+ - **Watchdog**: File system monitoring for config changes
394
+
395
+ ## Troubleshooting
396
+
397
+ ### Common Issues
398
+
399
+ **Config not found**:
400
+ ```bash
401
+ Error: Config file taskmux.json not found
402
+ ```
403
+ - Ensure `taskmux.json` exists in current directory
404
+ - Check JSON syntax with `jq . taskmux.json`
405
+
406
+ **Session already exists**:
407
+ ```bash
408
+ Session 'myproject' already exists
409
+ ```
410
+ - Kill existing session: `taskmux stop`
411
+ - Or attach to it: `tmux attach-session -t myproject`
412
+
413
+ **Task not restarting**:
414
+ - Check if task name exists: `taskmux list`
415
+ - Verify session is running: `taskmux status`
416
+ - Check task health: `taskmux health`
417
+
418
+ **libtmux connection issues**:
419
+ - Ensure tmux is installed and in PATH
420
+ - Try restarting tmux server: `tmux kill-server`
421
+
422
+ ### Debug Mode
423
+
424
+ View detailed tmux session information:
425
+ ```bash
426
+ # Check if session exists
427
+ tmux has-session -t myproject
428
+
429
+ # List windows in session
430
+ tmux list-windows -t myproject
431
+
432
+ # View logs manually
433
+ tmux capture-pane -t myproject:taskname -p
434
+
435
+ # Check daemon logs
436
+ tail -f ~/.taskmux/daemon.log
437
+ ```
438
+
439
+ ## Contributing
440
+
441
+ Taskmux follows modern Python development practices:
442
+
443
+ 1. **Modular architecture**: Separate concerns (CLI, tmux management, daemon, config)
444
+ 2. **Type hints**: Full type annotation for better IDE support
445
+ 3. **Rich CLI**: Beautiful, user-friendly command-line interface
446
+ 4. **Async support**: Background monitoring and WebSocket API
447
+ 5. **Comprehensive testing**: Test across different tmux versions and platforms
448
+
449
+ ## License
450
+
451
+ MIT License - feel free to modify and distribute.
@@ -0,0 +1,12 @@
1
+ taskmux/__init__.py,sha256=W5wMUzcF5IPMuW5rgKAA3tKKd0CO_w9W7vyOvGWLD0g,501
2
+ taskmux/cli.py,sha256=TNeMLcGhoZ7JxDUr90AsWgjbLhUy4Ne-DdYRxP--iDY,4799
3
+ taskmux/config.py,sha256=ZwzCUxZWn-Pwfz1pVs2EUImTQBFepfqf6PaQ7BwPNg0,1803
4
+ taskmux/daemon.py,sha256=WyELHEL8XUCTScJf_-kfDs_j7s__DYFnlx_ZdivZ4zU,9643
5
+ taskmux/main.py,sha256=H2LAzjv5aTTigepneeBxP_0qE-no0g3642O5TF7yW6E,198
6
+ taskmux/tmux_manager.py,sha256=oYlvBOBbF9aAEpC37S4wwtIKsuL8R4j524QhZKgUs5Y,8560
7
+ taskmux/templates/claude.md,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ taskmux-0.1.0.dist-info/METADATA,sha256=_cf4PClz_z5TEGychvrwdlyPU_8sjma2H8iu71ItTTk,11531
9
+ taskmux-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
10
+ taskmux-0.1.0.dist-info/entry_points.txt,sha256=nKwgFRwZPanoeW-GSJ9QdBzg2bMqK-RjNYfg6fWCgwg,46
11
+ taskmux-0.1.0.dist-info/licenses/LICENSE,sha256=gXlGWdKwicnxQy_myUxod66y7btv3y9clpO0_aEk9Ec,1070
12
+ taskmux-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ taskmux = taskmux.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Nik Cubrilovic
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.