1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334//! Interactive process manager โ persistent process sessions.
//!
//! Allows agents to start long-running processes (REPLs, servers, watchers),
//! write to their stdin, read from stdout/stderr, and kill them.
use dashmap::DashMap;
use std::process::Stdio;
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::Mutex;
use tracing::{debug, warn};
/// Unique process identifier.
pub type ProcessId = String;
/// A managed persistent process.
struct ManagedProcess {
/// stdin writer.
stdin: Option<tokio::process::ChildStdin>,
/// Accumulated stdout output.
stdout_buf: Arc<Mutex<Vec<String>>>,
/// Accumulated stderr output.
stderr_buf: Arc<Mutex<Vec<String>>>,
/// The child process handle.
child: tokio::process::Child,
/// Agent that owns this process.
agent_id: String,
/// Command that was started.
command: String,
/// When the process was started.
started_at: std::time::Instant,
}
/// Process info for listing.
#[derive(Debug, Clone)]
pub struct ProcessInfo {
/// Process ID.
pub id: ProcessId,
/// Agent that owns this process.
pub agent_id: String,
/// Command that was started.
pub command: String,
/// Whether the process is still running.
pub alive: bool,
/// Uptime in seconds.
pub uptime_secs: u64,
}
/// Manager for persistent agent processes.
pub struct ProcessManager {
processes: DashMap<ProcessId, ManagedProcess>,
max_per_agent: usize,
next_id: std::sync::atomic::AtomicU64,
}
impl ProcessManager {
/// Create a new process manager.
pub fn new(max_per_agent: usize) -> Self {
Self {
processes: DashMap::new(),
max_per_agent,
next_id: std::sync::atomic::AtomicU64::new(1),
}
}
/// Start a persistent process. Returns the process ID.
pub async fn start(
&self,
agent_id: &str,
command: &str,
args: &[String],
) -> Result<ProcessId, String> {
// Check per-agent limit
let agent_count = self
.processes
.iter()
.filter(|entry| entry.value().agent_id == agent_id)
.count();
if agent_count >= self.max_per_agent {
return Err(format!(
"Agent '{}' already has {} processes (max: {})",
agent_id, agent_count, self.max_per_agent
));
}
let mut child = tokio::process::Command::new(command)
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("Failed to start process '{}': {}", command, e))?;
let stdin = child.stdin.take();
let stdout = child.stdout.take();
let stderr = child.stderr.take();
let stdout_buf = Arc::new(Mutex::new(Vec::<String>::new()));
let stderr_buf = Arc::new(Mutex::new(Vec::<String>::new()));
// Spawn background readers for stdout/stderr
if let Some(out) = stdout {
let buf = stdout_buf.clone();
tokio::spawn(async move {
let reader = BufReader::new(out);
let mut lines = reader.lines();
while let Ok(Some(line)) = lines.next_line().await {
let mut b = buf.lock().await;
// Cap buffer at 1000 lines
if b.len() >= 1000 {
b.drain(..100); // remove oldest 100
}
b.push(line);
}
});
}
if let Some(err) = stderr {
let buf = stderr_buf.clone();
tokio::spawn(async move {
let reader = BufReader::new(err);
let mut lines = reader.lines();
while let Ok(Some(line)) = lines.next_line().await {
let mut b = buf.lock().await;
if b.len() >= 1000 {
b.drain(..100);
}
b.push(line);
}
});
}
let id = format!(
"proc_{}",
self.next_id
.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
);
let cmd_display = if args.is_empty() {
command.to_string()
} else {
format!("{} {}", command, args.join(" "))
};
debug!(process_id = %id, command = %cmd_display, agent = %agent_id, "Started persistent process");
self.processes.insert(
id.clone(),
ManagedProcess {
stdin,
stdout_buf,
stderr_buf,
child,
agent_id: agent_id.to_string(),
command: cmd_display,
started_at: std::time::Instant::now(),
},
);
Ok(id)
}
/// Write data to a process's stdin.
pub async fn write(&self, process_id: &str, data: &str) -> Result<(), String> {
let mut entry = self
.processes
.get_mut(process_id)
.ok_or_else(|| format!("Process '{}' not found", process_id))?;
let proc = entry.value_mut();
if let Some(stdin) = &mut proc.stdin {
stdin
.write_all(data.as_bytes())
.await
.map_err(|e| format!("Write failed: {}", e))?;
stdin
.flush()
.await
.map_err(|e| format!("Flush failed: {}", e))?;
Ok(())
} else {
Err("Process stdin is closed".to_string())
}
}
/// Read accumulated stdout/stderr (non-blocking drain).
pub async fn read(&self, process_id: &str) -> Result<(Vec<String>, Vec<String>), String> {
let entry = self
.processes
.get(process_id)
.ok_or_else(|| format!("Process '{}' not found", process_id))?;
let mut stdout = entry.stdout_buf.lock().await;
let mut stderr = entry.stderr_buf.lock().await;
let out_lines: Vec<String> = stdout.drain(..).collect();
let err_lines: Vec<String> = stderr.drain(..).collect();
Ok((out_lines, err_lines))
}
/// Kill a process.
pub async fn kill(&self, process_id: &str) -> Result<(), String> {
let (_, mut proc) = self
.processes
.remove(process_id)
.ok_or_else(|| format!("Process '{}' not found", process_id))?;
if let Some(pid) = proc.child.id() {
debug!(process_id, pid, "Killing persistent process");
let _ = crate::subprocess_sandbox::kill_process_tree(pid, 3000).await;
}
let _ = proc.child.kill().await;
Ok(())
}
/// List all processes for an agent.
pub fn list(&self, agent_id: &str) -> Vec<ProcessInfo> {
self.processes
.iter()
.filter(|entry| entry.value().agent_id == agent_id)
.map(|entry| {
let alive = entry.value().child.id().is_some();
ProcessInfo {
id: entry.key().clone(),
agent_id: entry.value().agent_id.clone(),
command: entry.value().command.clone(),
alive,
uptime_secs: entry.value().started_at.elapsed().as_secs(),
}
})
.collect()
}
/// Cleanup: kill processes older than timeout.
pub async fn cleanup(&self, max_age_secs: u64) {
let to_remove: Vec<ProcessId> = self
.processes
.iter()
.filter(|entry| entry.value().started_at.elapsed().as_secs() > max_age_secs)
.map(|entry| entry.key().clone())
.collect();
for id in to_remove {
warn!(process_id = %id, "Cleaning up stale process");
let _ = self.kill(&id).await;
}
}
/// Total process count.
pub fn count(&self) -> usize {
self.processes.len()
}
}
impl Default for ProcessManager {
fn default() -> Self {
Self::new(5)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_start_and_list() {
let pm = ProcessManager::new(5);
let cmd = if cfg!(windows) { "cmd" } else { "cat" };
let args: Vec<String> = if cfg!(windows) {
vec!["/C".to_string(), "echo".to_string(), "hello".to_string()]
} else {
vec![]
};
let id = pm.start("agent1", cmd, &args).await.unwrap();
assert!(id.starts_with("proc_"));
let list = pm.list("agent1");
assert_eq!(list.len(), 1);
assert_eq!(list[0].agent_id, "agent1");
// Cleanup
let _ = pm.kill(&id).await;
}
#[tokio::test]
async fn test_per_agent_limit() {
let pm = ProcessManager::new(1);
let cmd = if cfg!(windows) { "cmd" } else { "cat" };
let args: Vec<String> = if cfg!(windows) {
vec![
"/C".to_string(),
"timeout".to_string(),
"/t".to_string(),
"10".to_string(),
]
} else {
vec![]
};
let id1 = pm.start("agent1", cmd, &args).await.unwrap();
let result = pm.start("agent1", cmd, &args).await;
assert!(result.is_err());
assert!(result.unwrap_err().contains("max: 1"));
let _ = pm.kill(&id1).await;
}
#[tokio::test]
async fn test_kill_nonexistent() {
let pm = ProcessManager::new(5);
let result = pm.kill("nonexistent").await;
assert!(result.is_err());
}
#[tokio::test]
async fn test_read_nonexistent() {
let pm = ProcessManager::new(5);
let result = pm.read("nonexistent").await;
assert!(result.is_err());
}
#[test]
fn test_default_process_manager() {
let pm = ProcessManager::default();
assert_eq!(pm.max_per_agent, 5);
assert_eq!(pm.count(), 0);
}
}