ireri-code 2.0.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.
@@ -0,0 +1,542 @@
1
+ """Terminal/command execution tools for ireri."""
2
+
3
+ import asyncio
4
+ import os
5
+ import shlex
6
+ import signal
7
+ import subprocess
8
+ import sys
9
+ import time
10
+ from collections import deque
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any, Dict, List, Optional, Tuple
14
+ from pydantic import BaseModel, Field
15
+
16
+ from . import Tool, ToolArgument, ToolResult, register_tool
17
+ from agent.config import get_config
18
+
19
+ import logging
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ # Dangerous command patterns that require extra approval
25
+ DANGEROUS_PATTERNS = [
26
+ r"rm\s+-rf\s+/",
27
+ r"rm\s+-rf\s+~",
28
+ r"sudo\s+",
29
+ r"chmod\s+777",
30
+ r">\s*/dev/",
31
+ r"curl\s+.*\|\s*sh",
32
+ r"wget\s+.*\|\s*sh",
33
+ r"pip\s+install\s+.*--break-system-packages",
34
+ r"npm\s+install\s+-g",
35
+ r"docker\s+",
36
+ r"kubectl\s+",
37
+ r"systemctl\s+",
38
+ r"service\s+",
39
+ r"mount\s+",
40
+ r"dd\s+if=",
41
+ r"mkfs\s+",
42
+ r"fdisk\s+",
43
+ r":\(\)\{\s*:\|\:&\s*\};:", # fork bomb
44
+ ]
45
+
46
+
47
+ def _is_dangerous(command: str) -> bool:
48
+ """Check if a command matches dangerous patterns."""
49
+ import re
50
+ for pattern in DANGEROUS_PATTERNS:
51
+ if re.search(pattern, command, re.IGNORECASE):
52
+ return True
53
+ return False
54
+
55
+
56
+ def _resolve_workspace_path(path: str) -> Path:
57
+ """Resolve a path relative to workspace root."""
58
+ config = get_config()
59
+ workspace = config.workspace_root
60
+
61
+ # Normalize path: handle Unix-style Windows paths like /c/..., /d/...
62
+ # Also handle special paths like /workspace
63
+ normalized_path = path
64
+ if path == "/workspace" or path == "/workspace/":
65
+ normalized_path = "."
66
+ elif path.startswith('/') and len(path) >= 3 and path[2] == '/':
67
+ # Looks like /c/..., /d/... - Unix-style Windows path
68
+ # Strip the leading /c/ and treat as relative
69
+ normalized_path = path[3:]
70
+
71
+ # If the normalized path equals the workspace root path, use "."
72
+ workspace_str = str(workspace).replace('\\', '/')
73
+ if normalized_path == workspace_str or normalized_path == workspace_str.rstrip('/'):
74
+ normalized_path = "."
75
+
76
+ target = (workspace / normalized_path).resolve()
77
+
78
+ try:
79
+ target.relative_to(workspace)
80
+ except ValueError:
81
+ raise ValueError(f"Path '{path}' attempts to escape workspace")
82
+
83
+ return target
84
+
85
+
86
+ def _kill_process_tree(process: asyncio.subprocess.Process) -> None:
87
+ """Terminate a process and all its children cleanly across Windows and POSIX."""
88
+ if process.returncode is not None:
89
+ return
90
+ try:
91
+ if sys.platform == "win32":
92
+ subprocess.run(
93
+ ["taskkill", "/F", "/T", "/PID", str(process.pid)],
94
+ stdout=subprocess.DEVNULL,
95
+ stderr=subprocess.DEVNULL,
96
+ timeout=5,
97
+ )
98
+ else:
99
+ try:
100
+ os.killpg(os.getpgid(process.pid), signal.SIGKILL)
101
+ except Exception:
102
+ process.kill()
103
+ except Exception:
104
+ try:
105
+ process.kill()
106
+ except Exception:
107
+ pass
108
+
109
+
110
+ class ManagedProcess:
111
+ """Represents a running or recently finished subprocess with live log buffering."""
112
+
113
+ def __init__(
114
+ self,
115
+ process_id: str,
116
+ command: str,
117
+ cwd: str,
118
+ process: asyncio.subprocess.Process,
119
+ background: bool = False,
120
+ ):
121
+ self.process_id = process_id
122
+ self.command = command
123
+ self.cwd = cwd
124
+ self.process = process
125
+ self.background = background
126
+ self.pid = process.pid
127
+ self.started_at = time.monotonic()
128
+ self.started_wall = datetime.now()
129
+ self.ended_at: Optional[float] = None
130
+ self.stdout_lines: deque[str] = deque(maxlen=2000)
131
+ self.stderr_lines: deque[str] = deque(maxlen=2000)
132
+ self.combined_logs: deque[str] = deque(maxlen=4000)
133
+ self._reader_tasks: List[asyncio.Task] = []
134
+ self._done_event = asyncio.Event()
135
+ self._monitor_task: Optional[asyncio.Task] = None
136
+
137
+ @property
138
+ def returncode(self) -> Optional[int]:
139
+ return self.process.returncode
140
+
141
+ @property
142
+ def is_running(self) -> bool:
143
+ return self.process.returncode is None
144
+
145
+ @property
146
+ def uptime_seconds(self) -> float:
147
+ end = self.ended_at if self.ended_at is not None else time.monotonic()
148
+ return max(0.0, end - self.started_at)
149
+
150
+ def start_readers(self) -> None:
151
+ """Start background async stream readers for live stdout/stderr capture."""
152
+ async def _read_stream(stream: Optional[asyncio.StreamReader], target: deque, prefix: str = ""):
153
+ if stream is None:
154
+ return
155
+ try:
156
+ while True:
157
+ line_bytes = await stream.readline()
158
+ if not line_bytes:
159
+ break
160
+ text = line_bytes.decode("utf-8", errors="replace").rstrip("\r\n")
161
+ target.append(text)
162
+ self.combined_logs.append(f"{prefix}{text}")
163
+ except Exception:
164
+ pass
165
+
166
+ async def _monitor():
167
+ try:
168
+ await self.process.wait()
169
+ if self._reader_tasks:
170
+ await asyncio.gather(*self._reader_tasks, return_exceptions=True)
171
+ finally:
172
+ if self.ended_at is None:
173
+ self.ended_at = time.monotonic()
174
+ self._done_event.set()
175
+
176
+ self._reader_tasks = [
177
+ asyncio.create_task(_read_stream(self.process.stdout, self.stdout_lines, "")),
178
+ asyncio.create_task(_read_stream(self.process.stderr, self.stderr_lines, "[stderr] ")),
179
+ ]
180
+ self._monitor_task = asyncio.create_task(_monitor())
181
+
182
+ async def wait_done(self) -> int:
183
+ """Wait for the process and all stream readers to finish."""
184
+ await self._done_event.wait()
185
+ return self.process.returncode if self.process.returncode is not None else -1
186
+
187
+ def get_stdout_text(self) -> str:
188
+ return "\n".join(self.stdout_lines)
189
+
190
+ def get_stderr_text(self) -> str:
191
+ return "\n".join(self.stderr_lines)
192
+
193
+ def get_recent_logs(self, tail: int = 100) -> str:
194
+ """Return the last `tail` combined log lines."""
195
+ if tail <= 0:
196
+ return "\n".join(self.combined_logs)
197
+ lines = list(self.combined_logs)[-tail:]
198
+ return "\n".join(lines)
199
+
200
+
201
+ class ProcessManager:
202
+ """Tracks ongoing and recent commands so they can run in background and stream logs."""
203
+
204
+ def __init__(self):
205
+ self._processes: Dict[str, ManagedProcess] = {}
206
+ self._counter = 0
207
+
208
+ async def start_process(
209
+ self,
210
+ command: str,
211
+ cwd: Path,
212
+ background: bool = False,
213
+ ) -> ManagedProcess:
214
+ """Start a subprocess and begin live log streaming."""
215
+ self._counter += 1
216
+ process_id = f"proc-{self._counter}"
217
+
218
+ kwargs: Dict[str, Any] = {
219
+ "cwd": cwd,
220
+ "stdout": asyncio.subprocess.PIPE,
221
+ "stderr": asyncio.subprocess.PIPE,
222
+ }
223
+ if sys.platform != "win32":
224
+ kwargs["start_new_session"] = True
225
+
226
+ process = await asyncio.create_subprocess_shell(command, **kwargs)
227
+ managed = ManagedProcess(
228
+ process_id=process_id,
229
+ command=command,
230
+ cwd=str(cwd),
231
+ process=process,
232
+ background=background,
233
+ )
234
+ managed.start_readers()
235
+ self._processes[process_id] = managed
236
+ return managed
237
+
238
+ def get_process(self, process_id: Optional[str] = None) -> Optional[ManagedProcess]:
239
+ """Get a process by ID, or the most recent running/available process if omitted."""
240
+ if process_id:
241
+ return self._processes.get(process_id)
242
+ if not self._processes:
243
+ return None
244
+ running = [p for p in self._processes.values() if p.is_running]
245
+ if running:
246
+ return running[-1]
247
+ return list(self._processes.values())[-1]
248
+
249
+ def list_processes(self) -> List[ManagedProcess]:
250
+ """List all tracked processes."""
251
+ return list(self._processes.values())
252
+
253
+ def get_logs(self, process_id: Optional[str] = None, tail: int = 100) -> Tuple[Optional[ManagedProcess], str]:
254
+ """Get recent logs for a process."""
255
+ proc = self.get_process(process_id)
256
+ if not proc:
257
+ return None, ""
258
+ return proc, proc.get_recent_logs(tail=tail)
259
+
260
+ async def stop_process(self, process_id: str) -> Tuple[bool, str]:
261
+ """Stop a running process by ID."""
262
+ proc = self._processes.get(process_id)
263
+ if not proc:
264
+ return False, f"Unknown process ID: {process_id}"
265
+ if not proc.is_running:
266
+ return True, f"Process {process_id} already exited with code {proc.returncode}"
267
+
268
+ _kill_process_tree(proc.process)
269
+ try:
270
+ await asyncio.wait_for(proc.wait_done(), timeout=3.0)
271
+ except asyncio.TimeoutError:
272
+ pass
273
+ return True, f"Stopped process {process_id} (PID {proc.pid})"
274
+
275
+ def stop_all(self) -> int:
276
+ """Synchronously terminate all still-running processes (used on CLI exit)."""
277
+ stopped = 0
278
+ for proc in self._processes.values():
279
+ if proc.is_running:
280
+ _kill_process_tree(proc.process)
281
+ stopped += 1
282
+ return stopped
283
+
284
+
285
+ _process_manager: Optional[ProcessManager] = None
286
+
287
+
288
+ def get_process_manager() -> ProcessManager:
289
+ """Get the global ProcessManager instance."""
290
+ global _process_manager
291
+ if _process_manager is None:
292
+ _process_manager = ProcessManager()
293
+ return _process_manager
294
+
295
+
296
+ class RunCommandArgs(ToolArgument):
297
+ """Arguments for running a command."""
298
+ command: str = Field(description="Command to execute")
299
+ cwd: Optional[str] = Field(default=None, description="Working directory (relative to workspace)")
300
+ timeout: Optional[int] = Field(default=None, description="Timeout in seconds for foreground commands")
301
+ shell: bool = Field(default=True, description="Run through shell")
302
+ background: bool = Field(
303
+ default=False,
304
+ description="Set true for long-running processes (bots, servers, watchers like 'python bot.py'). Returns immediately with process_id and initial logs."
305
+ )
306
+ wait_seconds: float = Field(
307
+ default=2.0,
308
+ description="When background=true, seconds to wait to capture initial startup logs (default 2.0s)"
309
+ )
310
+
311
+
312
+ class RunCommandTool(Tool):
313
+ """Execute a terminal command (foreground or background)."""
314
+
315
+ name = "run_command"
316
+ description = (
317
+ "Execute a shell command in the workspace. For long-running processes like bots, servers, "
318
+ "or watchers (e.g., 'python bot.py', 'npm run dev'), set background=true so it returns "
319
+ "immediately with a process_id instead of blocking."
320
+ )
321
+ args_schema = RunCommandArgs
322
+ requires_approval = True
323
+ dangerous = True
324
+
325
+ async def execute(self, args: RunCommandArgs) -> ToolResult:
326
+ try:
327
+ config = get_config()
328
+
329
+ # Determine working directory
330
+ if args.cwd:
331
+ cwd = _resolve_workspace_path(args.cwd)
332
+ else:
333
+ cwd = config.workspace_root
334
+
335
+ # Check for dangerous commands
336
+ if _is_dangerous(args.command):
337
+ return ToolResult(
338
+ success=False,
339
+ error="Command matches dangerous pattern. Requires explicit approval.",
340
+ metadata={"dangerous": True}
341
+ )
342
+
343
+ timeout = args.timeout or config.command_timeout
344
+ pm = get_process_manager()
345
+
346
+ logger.info(f"Executing command in {cwd} (background={args.background}): {args.command}")
347
+ managed = await pm.start_process(args.command, cwd=cwd, background=args.background)
348
+
349
+ if args.background:
350
+ startup_wait = min(max(args.wait_seconds, 0.2), float(timeout))
351
+ try:
352
+ await asyncio.wait_for(managed.wait_done(), timeout=startup_wait)
353
+ # Process exited during startup window
354
+ stdout_text = managed.get_stdout_text()
355
+ stderr_text = managed.get_stderr_text()
356
+ rc = managed.returncode
357
+ error_msg = None
358
+ if rc != 0:
359
+ error_msg = stderr_text.strip() or stdout_text.strip() or f"Command '{args.command}' exited immediately with code {rc}"
360
+ return ToolResult(
361
+ success=rc == 0,
362
+ output={
363
+ "process_id": managed.process_id,
364
+ "pid": managed.pid,
365
+ "status": "exited",
366
+ "stdout": stdout_text,
367
+ "stderr": stderr_text,
368
+ "returncode": rc,
369
+ "command": args.command,
370
+ },
371
+ error=error_msg,
372
+ metadata={
373
+ "background": True,
374
+ "process_id": managed.process_id,
375
+ "returncode": rc,
376
+ "cwd": str(cwd),
377
+ },
378
+ )
379
+ except asyncio.TimeoutError:
380
+ # Still running in background as expected!
381
+ initial_logs = managed.get_recent_logs(tail=50)
382
+ return ToolResult(
383
+ success=True,
384
+ output={
385
+ "process_id": managed.process_id,
386
+ "pid": managed.pid,
387
+ "status": "running",
388
+ "command": args.command,
389
+ "initial_logs": initial_logs,
390
+ "message": (
391
+ f"Process '{managed.process_id}' (PID {managed.pid}) is running in the background. "
392
+ f"Use get_process_logs(process_id='{managed.process_id}') to inspect logs or stop_process to stop it."
393
+ ),
394
+ },
395
+ metadata={
396
+ "background": True,
397
+ "process_id": managed.process_id,
398
+ "pid": managed.pid,
399
+ "cwd": str(cwd),
400
+ },
401
+ )
402
+
403
+ # Foreground command
404
+ try:
405
+ await asyncio.wait_for(managed.wait_done(), timeout=timeout)
406
+ except asyncio.TimeoutError:
407
+ partial_logs = managed.get_recent_logs(tail=50)
408
+ await pm.stop_process(managed.process_id)
409
+ return ToolResult(
410
+ success=False,
411
+ error=(
412
+ f"Command timed out after {timeout} seconds. "
413
+ f"If '{args.command}' is a long-running bot, server, or watcher, re-run with background=true."
414
+ ),
415
+ output={
416
+ "process_id": managed.process_id,
417
+ "stdout": managed.get_stdout_text(),
418
+ "stderr": managed.get_stderr_text(),
419
+ "partial_logs": partial_logs,
420
+ "command": args.command,
421
+ },
422
+ metadata={"timeout": True, "process_id": managed.process_id}
423
+ )
424
+
425
+ stdout_text = managed.get_stdout_text()
426
+ stderr_text = managed.get_stderr_text()
427
+ rc = managed.returncode
428
+
429
+ error_msg = None
430
+ if rc != 0:
431
+ error_msg = stderr_text.strip() or stdout_text.strip() or f"Command '{args.command}' failed with exit code {rc}"
432
+
433
+ return ToolResult(
434
+ success=rc == 0,
435
+ output={
436
+ "process_id": managed.process_id,
437
+ "stdout": stdout_text,
438
+ "stderr": stderr_text,
439
+ "returncode": rc,
440
+ "command": args.command,
441
+ },
442
+ error=error_msg,
443
+ metadata={
444
+ "process_id": managed.process_id,
445
+ "returncode": rc,
446
+ "cwd": str(cwd),
447
+ }
448
+ )
449
+ except Exception as e:
450
+ logger.error(f"run_command error: {e}")
451
+ return ToolResult(success=False, error=str(e))
452
+
453
+
454
+ class ListProcessesArgs(ToolArgument):
455
+ """Arguments for listing ongoing/recent processes."""
456
+ pass
457
+
458
+
459
+ class ListProcessesTool(Tool):
460
+ """List ongoing and recent commands/processes started by ireri."""
461
+
462
+ name = "list_processes"
463
+ description = "List all ongoing and recent terminal processes with their process_id, PID, status, uptime, and command"
464
+ args_schema = ListProcessesArgs
465
+ requires_approval = False
466
+
467
+ async def execute(self, args: ListProcessesArgs) -> ToolResult:
468
+ pm = get_process_manager()
469
+ items = []
470
+ for proc in pm.list_processes():
471
+ items.append({
472
+ "process_id": proc.process_id,
473
+ "pid": proc.pid,
474
+ "status": "running" if proc.is_running else f"exited ({proc.returncode})",
475
+ "background": proc.background,
476
+ "uptime_seconds": round(proc.uptime_seconds, 1),
477
+ "command": proc.command,
478
+ "cwd": proc.cwd,
479
+ })
480
+ return ToolResult(success=True, output={"processes": items, "count": len(items)})
481
+
482
+
483
+ class GetProcessLogsArgs(ToolArgument):
484
+ """Arguments for retrieving logs from an ongoing or finished process."""
485
+ process_id: Optional[str] = Field(default=None, description="Process ID (e.g. 'proc-1'). Defaults to latest running/recent process.")
486
+ tail: int = Field(default=100, description="Number of recent log lines to return (0 for all buffered lines)")
487
+
488
+
489
+ class GetProcessLogsTool(Tool):
490
+ """Get live stdout/stderr logs of an ongoing or finished process."""
491
+
492
+ name = "get_process_logs"
493
+ description = "Read the latest stdout/stderr logs of an ongoing background process or recent command"
494
+ args_schema = GetProcessLogsArgs
495
+ requires_approval = False
496
+
497
+ async def execute(self, args: GetProcessLogsArgs) -> ToolResult:
498
+ pm = get_process_manager()
499
+ proc, logs = pm.get_logs(process_id=args.process_id, tail=args.tail)
500
+ if not proc:
501
+ return ToolResult(
502
+ success=False,
503
+ error=f"Process not found: {args.process_id or 'no processes started yet'}",
504
+ )
505
+ return ToolResult(
506
+ success=True,
507
+ output={
508
+ "process_id": proc.process_id,
509
+ "pid": proc.pid,
510
+ "status": "running" if proc.is_running else f"exited ({proc.returncode})",
511
+ "uptime_seconds": round(proc.uptime_seconds, 1),
512
+ "command": proc.command,
513
+ "logs": logs,
514
+ "total_buffered_lines": len(proc.combined_logs),
515
+ },
516
+ )
517
+
518
+
519
+ class StopProcessArgs(ToolArgument):
520
+ """Arguments for stopping a running process."""
521
+ process_id: str = Field(description="Process ID to stop (e.g. 'proc-1')")
522
+
523
+
524
+ class StopProcessTool(Tool):
525
+ """Stop an ongoing background process."""
526
+
527
+ name = "stop_process"
528
+ description = "Stop/terminate a running background process by process_id"
529
+ args_schema = StopProcessArgs
530
+ requires_approval = True
531
+
532
+ async def execute(self, args: StopProcessArgs) -> ToolResult:
533
+ pm = get_process_manager()
534
+ ok, msg = await pm.stop_process(args.process_id)
535
+ return ToolResult(success=ok, output={"message": msg} if ok else None, error=None if ok else msg)
536
+
537
+
538
+ # Register terminal tools
539
+ register_tool(RunCommandTool())
540
+ register_tool(ListProcessesTool())
541
+ register_tool(GetProcessLogsTool())
542
+ register_tool(StopProcessTool())