agent-procs 0.6.3

Concurrent process runner for AI agents
Documentation
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
use crate::daemon::log_writer::OutputLine;
use crate::daemon::process_manager::ProcessManager;
use crate::protocol::{self, ErrorCode, Response, Stream as ProtoStream};
use std::collections::HashMap;
use tokio::sync::{broadcast, mpsc, oneshot, watch};
use tokio::time::{self, Duration, MissedTickBehavior};

const EXIT_REFRESH_INTERVAL: Duration = Duration::from_millis(200);

/// State published via the watch channel for lock-free proxy reads.
#[derive(Debug, Clone, PartialEq)]
pub struct ProxyState {
    /// Running process name → backend port.
    pub port_map: HashMap<String, u16>,
}

/// Commands sent to the actor via [`PmHandle`].
enum PmCommand {
    Spawn {
        command: String,
        name: Option<String>,
        cwd: Option<String>,
        env: Option<HashMap<String, String>>,
        port: Option<u16>,
        restart: Option<crate::protocol::RestartPolicy>,
        watch: Option<crate::protocol::WatchConfig>,
        reply: oneshot::Sender<Response>,
    },
    Stop {
        target: String,
        reply: oneshot::Sender<Response>,
    },
    StopAll {
        reply: oneshot::Sender<Response>,
    },
    Restart {
        target: String,
        reply: oneshot::Sender<Response>,
    },
    Status {
        reply: oneshot::Sender<Response>,
    },
    StatusSnapshot {
        reply: oneshot::Sender<Response>,
    },
    HasProcess {
        target: String,
        reply: oneshot::Sender<bool>,
    },
    SessionName {
        reply: oneshot::Sender<String>,
    },
    #[allow(clippy::option_option)]
    IsProcessExited {
        target: String,
        reply: oneshot::Sender<Option<Option<i32>>>,
    },
    /// Returns `Some(existing_port)` if proxy is already enabled, `None` if newly enabled.
    EnableProxy {
        proxy_port: u16,
        reply: oneshot::Sender<Option<u16>>,
    },
    Subscribe {
        reply: oneshot::Sender<broadcast::Receiver<OutputLine>>,
    },
    /// Internal: delayed auto-restart for a crashed process.
    AutoRestart {
        name: String,
    },
    /// Internal: file watcher triggered restart.
    WatchRestart {
        name: String,
    },
}

fn actor_error(msg: &str) -> Response {
    Response::Error {
        code: ErrorCode::General,
        message: msg.into(),
    }
}

/// Cloneable handle for sending commands to the [`ProcessManagerActor`].
#[derive(Clone)]
pub struct PmHandle {
    tx: mpsc::Sender<PmCommand>,
}

impl PmHandle {
    pub async fn spawn_process(
        &self,
        command: String,
        name: Option<String>,
        cwd: Option<String>,
        env: Option<HashMap<String, String>>,
        port: Option<u16>,
    ) -> Response {
        self.spawn_process_supervised(command, name, cwd, env, port, None, None)
            .await
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn spawn_process_supervised(
        &self,
        command: String,
        name: Option<String>,
        cwd: Option<String>,
        env: Option<HashMap<String, String>>,
        port: Option<u16>,
        restart: Option<crate::protocol::RestartPolicy>,
        watch: Option<crate::protocol::WatchConfig>,
    ) -> Response {
        let (reply, rx) = oneshot::channel();
        let _ = self
            .tx
            .send(PmCommand::Spawn {
                command,
                name,
                cwd,
                env,
                port,
                restart,
                watch,
                reply,
            })
            .await;
        rx.await.unwrap_or_else(|_| actor_error("actor stopped"))
    }

    pub async fn stop_process(&self, target: &str) -> Response {
        let (reply, rx) = oneshot::channel();
        let _ = self
            .tx
            .send(PmCommand::Stop {
                target: target.to_string(),
                reply,
            })
            .await;
        rx.await.unwrap_or_else(|_| actor_error("actor stopped"))
    }

    pub async fn stop_all(&self) -> Response {
        let (reply, rx) = oneshot::channel();
        let _ = self.tx.send(PmCommand::StopAll { reply }).await;
        rx.await.unwrap_or_else(|_| actor_error("actor stopped"))
    }

    pub async fn restart_process(&self, target: &str) -> Response {
        let (reply, rx) = oneshot::channel();
        let _ = self
            .tx
            .send(PmCommand::Restart {
                target: target.to_string(),
                reply,
            })
            .await;
        rx.await.unwrap_or_else(|_| actor_error("actor stopped"))
    }

    pub async fn status(&self) -> Response {
        let (reply, rx) = oneshot::channel();
        let _ = self.tx.send(PmCommand::Status { reply }).await;
        rx.await.unwrap_or_else(|_| actor_error("actor stopped"))
    }

    pub async fn status_snapshot(&self) -> Response {
        let (reply, rx) = oneshot::channel();
        let _ = self.tx.send(PmCommand::StatusSnapshot { reply }).await;
        rx.await.unwrap_or_else(|_| actor_error("actor stopped"))
    }

    pub async fn has_process(&self, target: &str) -> bool {
        let (reply, rx) = oneshot::channel();
        let _ = self
            .tx
            .send(PmCommand::HasProcess {
                target: target.to_string(),
                reply,
            })
            .await;
        rx.await.unwrap_or(false)
    }

    pub async fn session_name(&self) -> String {
        let (reply, rx) = oneshot::channel();
        let _ = self.tx.send(PmCommand::SessionName { reply }).await;
        rx.await.unwrap_or_default()
    }

    pub async fn is_process_exited(&self, target: &str) -> Option<Option<i32>> {
        let (reply, rx) = oneshot::channel();
        let _ = self
            .tx
            .send(PmCommand::IsProcessExited {
                target: target.to_string(),
                reply,
            })
            .await;
        rx.await.unwrap_or(None)
    }

    /// Enable proxy with the given port. Returns `Some(existing_port)` if already enabled.
    pub async fn enable_proxy(&self, proxy_port: u16) -> Option<u16> {
        let (reply, rx) = oneshot::channel();
        let _ = self
            .tx
            .send(PmCommand::EnableProxy { proxy_port, reply })
            .await;
        rx.await.unwrap_or(None)
    }

    pub async fn subscribe(&self) -> broadcast::Receiver<OutputLine> {
        let (reply, rx) = oneshot::channel();
        let _ = self.tx.send(PmCommand::Subscribe { reply }).await;
        rx.await.expect("actor should be alive for subscribe")
    }
}

/// Actor that owns the [`ProcessManager`] and processes commands sequentially.
pub struct ProcessManagerActor {
    pm: ProcessManager,
    rx: mpsc::Receiver<PmCommand>,
    /// Clone of the sender for scheduling internal commands (e.g. delayed restart).
    self_tx: mpsc::Sender<PmCommand>,
    proxy_state_tx: watch::Sender<ProxyState>,
    proxy_port: Option<u16>,
}

impl ProcessManagerActor {
    /// Create the actor, its handle, and the proxy state watch channel.
    pub fn new(session: &str) -> (PmHandle, watch::Receiver<ProxyState>, Self) {
        let (tx, rx) = mpsc::channel(256);
        let pm = ProcessManager::new(session);

        let initial_state = ProxyState {
            port_map: HashMap::new(),
        };
        let (proxy_state_tx, proxy_state_rx) = watch::channel(initial_state);

        let handle = PmHandle { tx: tx.clone() };
        let actor = Self {
            pm,
            rx,
            self_tx: tx,
            proxy_state_tx,
            proxy_port: None,
        };

        (handle, proxy_state_rx, actor)
    }

    /// Run the actor loop until all senders are dropped.
    pub async fn run(mut self) {
        let mut exit_refresh = time::interval(EXIT_REFRESH_INTERVAL);
        exit_refresh.set_missed_tick_behavior(MissedTickBehavior::Delay);

        loop {
            tokio::select! {
                cmd = self.rx.recv() => match cmd {
                    Some(cmd) => self.handle_command(cmd).await,
                    None => break,
                },
                _ = exit_refresh.tick() => {
                    if self.pm.refresh_exit_states() {
                        self.publish_proxy_state();
                    }
                    // Check for processes needing restart
                    self.schedule_restarts();
                }
            }
        }
    }

    /// Check for exited processes eligible for auto-restart, schedule delayed restarts.
    /// Also detects processes that have exhausted their `max_restarts` and marks them failed.
    fn schedule_restarts(&mut self) {
        let (restartable, exhausted) = self.pm.classify_restart_candidates();

        // Mark exhausted processes as failed
        for name in &exhausted {
            if let Some(p) = self.pm.find(name)
                && let Some(ref policy) = p.restart_policy
                && let Some(max) = policy.max_restarts
                && let Some(ref tx) = p.supervisor_tx
            {
                let msg = format!("[agent-procs] Max restarts ({}) exhausted", max);
                let _ = tx.try_send(msg);
            }
            self.pm.mark_failed(name);
        }
        if !exhausted.is_empty() {
            self.publish_proxy_state();
        }

        // Schedule delayed restarts for eligible processes
        for name in restartable {
            if let Some(p) = self.pm.find_mut(&name) {
                p.restart_pending = true;
                let delay_ms = p
                    .restart_policy
                    .as_ref()
                    .map_or(1000, |rp| rp.restart_delay_ms);
                let tx = self.self_tx.clone();
                let name_clone = name.clone();
                tokio::spawn(async move {
                    tokio::time::sleep(Duration::from_millis(delay_ms)).await;
                    let _ = tx.send(PmCommand::AutoRestart { name: name_clone }).await;
                });
            }
        }
    }

    async fn handle_command(&mut self, cmd: PmCommand) {
        match cmd {
            PmCommand::Spawn {
                command,
                name,
                cwd,
                env,
                port,
                restart,
                watch,
                reply,
            } => {
                let mut resp = self
                    .pm
                    .spawn_process(&command, name, cwd.as_deref(), env.as_ref(), port)
                    .await;
                // Attach restart/watch config if spawn succeeded
                let has_watch = watch.is_some();
                if let Response::RunOk { ref name, .. } = resp
                    && let Some(p) = self.pm.find_mut(name)
                {
                    p.restart_policy = restart;
                    p.watch_config = watch;
                }
                // Set up file watcher if watch config present
                if has_watch
                    && let Response::RunOk { ref name, .. } = resp
                    && let Err(e) = self.setup_watcher(name)
                {
                    // Process started but watcher failed — annotate the log.
                    // setup_watcher already cleared watch_config so status won't
                    // falsely report the process as watched.
                    let msg = format!("[agent-procs] Watch setup failed: {}", e);
                    if let Some(p) = self.pm.find(name)
                        && let Some(tx) = &p.supervisor_tx
                    {
                        let _ = tx.try_send(msg);
                    }
                }
                if let Response::RunOk {
                    ref name,
                    ref mut url,
                    port: Some(p),
                    ..
                } = resp
                    && let Some(pp) = self.proxy_port
                {
                    *url = Some(protocol::process_url(name, p, Some(pp)));
                }
                self.publish_proxy_state();
                let _ = reply.send(resp);
            }
            PmCommand::Stop { target, reply } => {
                // Tear down watcher on stop
                if let Some(p) = self.pm.find_mut(&target) {
                    p.watch_handle = None;
                }
                let resp = self.pm.stop_process(&target).await;
                self.publish_proxy_state();
                let _ = reply.send(resp);
            }
            PmCommand::StopAll { reply } => {
                let resp = self.pm.stop_all().await;
                self.publish_proxy_state();
                let _ = reply.send(resp);
            }
            PmCommand::Restart { target, reply } => {
                let resp = self.pm.restart_process(&target).await;
                // Recreate file watcher if watch config was preserved
                if let Response::RunOk { ref name, .. } = resp {
                    let _ = self.setup_watcher(name);
                }
                self.publish_proxy_state();
                let _ = reply.send(resp);
            }
            PmCommand::Status { reply } | PmCommand::StatusSnapshot { reply } => {
                let _ = reply.send(self.build_status());
            }
            PmCommand::HasProcess { target, reply } => {
                let _ = reply.send(self.pm.has_process(&target));
            }
            PmCommand::SessionName { reply } => {
                let _ = reply.send(self.pm.session_name().to_string());
            }
            PmCommand::IsProcessExited { target, reply } => {
                let _ = reply.send(self.pm.is_process_exited(&target));
            }
            PmCommand::EnableProxy { proxy_port, reply } => {
                if let Some(existing) = self.proxy_port {
                    let _ = reply.send(Some(existing));
                } else {
                    self.proxy_port = Some(proxy_port);
                    self.pm.enable_proxy();
                    self.publish_proxy_state();
                    let _ = reply.send(None);
                }
            }
            PmCommand::Subscribe { reply } => {
                let _ = reply.send(self.pm.output_tx.subscribe());
            }
            PmCommand::AutoRestart { name } => {
                self.handle_auto_restart(&name).await;
            }
            PmCommand::WatchRestart { name } => {
                self.handle_watch_restart(&name).await;
            }
        }
    }

    async fn handle_auto_restart(&mut self, name: &str) {
        // Re-check guards
        let should_restart = self
            .pm
            .find(name)
            .is_some_and(|p| p.child.is_none() && !p.manually_stopped && p.restart_pending);
        if !should_restart {
            if let Some(p) = self.pm.find_mut(name) {
                p.restart_pending = false;
            }
            return;
        }

        // Capture exit code before respawn (respawn_in_place removes the old record)
        let prev_exit_code = self.pm.find(name).and_then(|p| p.exit_code);

        // Increment count
        if let Some(p) = self.pm.find_mut(name) {
            p.restart_count += 1;
        }

        // Respawn
        match self.pm.respawn_in_place(name).await {
            Ok(()) => {
                // Send success annotation to new capture task
                if let Some(p) = self.pm.find(name) {
                    let count = p.restart_count;
                    let max = p.restart_policy.as_ref().and_then(|rp| rp.max_restarts);
                    let exit = prev_exit_code.map_or("signal".into(), |c: i32| c.to_string());
                    let msg = match max {
                        Some(m) => {
                            format!(
                                "[agent-procs] Restarted (exit {}, attempt {}/{})",
                                exit, count, m
                            )
                        }
                        None => {
                            format!("[agent-procs] Restarted (exit {}, attempt {})", exit, count)
                        }
                    };
                    if let Some(tx) = &p.supervisor_tx {
                        let _ = tx.send(msg).await;
                    }
                }
                // Recreate file watcher for the new process (old one was
                // dropped when respawn_in_place removed the process record)
                let _ = self.setup_watcher(name);
            }
            Err(err) => {
                // Broadcast failure (live only)
                let msg = format!("[agent-procs] Restart failed: {}", err);
                let _ = self.pm.output_tx.send(OutputLine {
                    process: name.to_string(),
                    stream: ProtoStream::Stdout,
                    line: msg,
                });
            }
        }

        // Clear pending
        if let Some(p) = self.pm.find_mut(name) {
            p.restart_pending = false;
        }
        self.publish_proxy_state();
    }

    async fn handle_watch_restart(&mut self, name: &str) {
        let should_restart = self.pm.find(name).is_some_and(|p| !p.manually_stopped);
        if !should_restart {
            return;
        }

        // Stop process (without manually_stopped)
        if self.pm.find(name).is_some_and(|p| p.child.is_some()) {
            let _ = self.pm.stop_process(name).await;
            // Clear manually_stopped (stop_process sets it)
            if let Some(p) = self.pm.find_mut(name) {
                p.manually_stopped = false;
            }
        }

        // Reset restart count (watch restarts are intentional)
        if let Some(p) = self.pm.find_mut(name) {
            p.restart_count = 0;
            p.failed = false;
        }

        // Respawn
        match self.pm.respawn_in_place(name).await {
            Ok(()) => {
                if let Some(p) = self.pm.find(name)
                    && let Some(tx) = &p.supervisor_tx
                {
                    let _ = tx
                        .send("[agent-procs] File changed, restarted".to_string())
                        .await;
                }
                // Recreate watcher for the new process
                let _ = self.setup_watcher(name);
            }
            Err(err) => {
                let _ = self.pm.output_tx.send(OutputLine {
                    process: name.to_string(),
                    stream: ProtoStream::Stdout,
                    line: format!("[agent-procs] Watch restart failed: {}", err),
                });
            }
        }

        self.publish_proxy_state();
    }

    /// Set up a file watcher for a process if it has a `WatchConfig`.
    /// Returns `Err` with an error message if the watcher could not be created.
    /// On failure, clears `watch_config` so status/TUI don't report a phantom watcher.
    fn setup_watcher(&mut self, name: &str) -> Result<(), String> {
        let (paths, ignore, cwd) = {
            let Some(p) = self.pm.find(name) else {
                return Ok(());
            };
            let Some(ref wc) = p.watch_config else {
                return Ok(());
            };
            (
                wc.paths.clone(),
                wc.ignore.clone(),
                p.cwd.clone().unwrap_or_else(|| ".".to_string()),
            )
        };

        let base_dir = std::path::PathBuf::from(&cwd);
        let ignore_refs: Option<Vec<String>> = ignore;
        let ignore_slice = ignore_refs.as_deref();

        let tx = self.self_tx.clone();
        let proc_name = name.to_string();
        let (restart_tx, mut restart_rx) = tokio::sync::mpsc::channel::<String>(16);

        // Forward watch events to PmCommand::WatchRestart
        tokio::spawn(async move {
            while let Some(name) = restart_rx.recv().await {
                let _ = tx.send(PmCommand::WatchRestart { name }).await;
            }
        });

        match crate::daemon::watcher::create_watcher(
            &paths,
            ignore_slice,
            &base_dir,
            proc_name,
            restart_tx,
        ) {
            Ok(handle) => {
                if let Some(p) = self.pm.find_mut(name) {
                    p.watch_handle = Some(handle);
                }
                Ok(())
            }
            Err(e) => {
                tracing::warn!(process = %name, error = %e, "failed to create file watcher");
                // Clear watch_config so status/TUI don't report as watched
                if let Some(p) = self.pm.find_mut(name) {
                    p.watch_config = None;
                }
                Err(e)
            }
        }
    }

    /// Build a status response with proxy URL rewriting applied.
    fn build_status(&mut self) -> Response {
        if self.pm.refresh_exit_states() {
            self.publish_proxy_state();
        }
        let mut resp = self.pm.status_snapshot();
        self.rewrite_urls(&mut resp);
        resp
    }

    /// Rewrite process URLs to proxy form when proxy is enabled.
    fn rewrite_urls(&self, resp: &mut Response) {
        let Some(pp) = self.proxy_port else { return };
        if let Response::Status { ref mut processes } = *resp {
            for p in processes.iter_mut() {
                if let Some(port) = p.port {
                    p.url = Some(protocol::process_url(&p.name, port, Some(pp)));
                }
            }
        }
    }

    /// Publish current port map to the watch channel for lock-free proxy reads.
    /// Skips the update if the port map hasn't changed.
    fn publish_proxy_state(&self) {
        let new_map = self.pm.running_ports();
        let current = self.proxy_state_tx.borrow();
        if current.port_map == new_map {
            return;
        }
        drop(current);
        let _ = self.proxy_state_tx.send(ProxyState { port_map: new_map });
    }
}