Skip to main content

artifactize_core/tools/
sessions.rs

1//! Review-owned tool sessions. A detached supervisor holds each process group and
2//! runs stop even when its review future is dropped or its token is cancelled.
3
4use std::{collections::BTreeMap, ffi::OsString, io, path::Path, time::Duration};
5
6use tokio::{
7    io::AsyncReadExt,
8    sync::{Mutex, oneshot},
9    task::JoinHandle,
10    time::Instant,
11};
12use tokio_util::sync::{CancellationToken, DropGuard};
13
14mod journal;
15pub(super) mod ownership;
16use journal::{Record, allocate};
17pub(crate) use ownership::executor;
18use ownership::{Cleanup, Ownership};
19
20use super::{Invocation, Registry};
21use crate::{
22    config::{AgentTool, ArtifactName, ToolFqn},
23    platform, process, runtime, workspace,
24};
25
26/// Spawning a session's start and running its stop each get thirty seconds, so a
27/// broken harness cannot delay cleanup indefinitely. Readiness has no fixed bound:
28/// preparing a harness may take as long as it needs while its start lives, and the
29/// review's cancellation or the start's exit ends the wait.
30const LIFECYCLE_TIMEOUT: Duration = Duration::from_secs(30);
31/// Drain without retaining untrusted harness output or allocating for a whole line.
32const DRAIN_BYTES: usize = 8192;
33
34#[derive(Default)]
35pub struct Sessions(BTreeMap<(ArtifactName, ToolFqn), Mutex<Session>>);
36
37enum Session {
38    Pending(Box<Start>),
39    Starting {
40        running: Running,
41        ready: oneshot::Receiver<Result<BTreeMap<OsString, OsString>, String>>,
42    },
43    Ready {
44        running: Running,
45        environment: BTreeMap<OsString, OsString>,
46    },
47    Failed {
48        running: Option<Running>,
49        error: String,
50    },
51}
52
53struct Start {
54    commands: Result<(Invocation, Invocation), String>,
55    workspace: std::path::PathBuf,
56    state: std::path::PathBuf,
57    cancellation: CancellationToken,
58    remove_directory: fn(&Path) -> io::Result<()>,
59}
60
61struct Running {
62    owner: std::sync::Arc<Ownership>,
63    stop: DropGuard,
64    finished: JoinHandle<Result<(), String>>,
65}
66
67impl Start {
68    async fn spawn(self) -> Result<Session, String> {
69        let (start, stop) = self.commands?;
70        let root = workspace::prepare_directory(&self.state.join("tool-sessions"), &self.workspace)
71            .map_err(|error| error.to_string())?;
72        let (directory, lease) =
73            crate::task::joined(tokio::task::spawn_blocking(move || allocate(&root)).await)
74                .map_err(|error| error.to_string())?
75                .map_err(|error| error.to_string())?;
76        let stop_token = CancellationToken::new();
77        let guard = stop_token.clone().drop_guard();
78        let owner = Ownership::new(directory.path(), lease);
79        let (send, ready) = oneshot::channel();
80        let finished = executor()
81            .map_err(|error| error.to_string())?
82            .spawn(supervise(
83                start,
84                stop,
85                self.workspace,
86                directory,
87                self.cancellation,
88                stop_token,
89                owner.clone(),
90                send,
91                self.remove_directory,
92            ));
93        Ok(Session::Starting {
94            running: Running {
95                owner,
96                stop: guard,
97                finished,
98            },
99            ready,
100        })
101    }
102}
103
104impl Session {
105    fn failed(error: String) -> Self {
106        Self::Failed {
107            running: None,
108            error,
109        }
110    }
111
112    fn running(self) -> Option<Running> {
113        match self {
114            Self::Pending(_) => None,
115            Self::Starting { running, .. } | Self::Ready { running, .. } => Some(running),
116            Self::Failed { running, .. } => running,
117        }
118    }
119}
120
121impl Sessions {
122    pub(crate) async fn call(
123        &self,
124        name: &(ArtifactName, ToolFqn),
125    ) -> Result<ownership::Call, String> {
126        let ended = || format!("The tool session `{}` ended.", name.1);
127        let session = self.0.get(name).ok_or_else(ended)?;
128        // Keep startup and readiness serialized, including if tools later allow parallel calls.
129        let mut session = session.lock().await;
130        if matches!(*session, Session::Pending(_)) {
131            let Session::Pending(start) =
132                std::mem::replace(&mut *session, Session::failed("start was dropped".into()))
133            else {
134                unreachable!()
135            };
136            *session = start.spawn().await.unwrap_or_else(Session::failed);
137        }
138        if let Session::Starting { ready, .. } = &mut *session {
139            // Store the supervisor before waiting: a dropped call still leaves close
140            // owning its stop guard and join handle, even before readiness.
141            let ready = ready.await.unwrap_or_else(|error| Err(error.to_string()));
142            let running =
143                std::mem::replace(&mut *session, Session::failed("start was dropped".into()))
144                    .running()
145                    .expect("starting session owns its supervisor");
146            *session = match ready {
147                Ok(environment) => Session::Ready {
148                    running,
149                    environment,
150                },
151                Err(error) => Session::Failed {
152                    running: Some(running),
153                    error,
154                },
155            };
156        }
157        match &*session {
158            Session::Ready {
159                running,
160                environment,
161            } => running.owner.call(environment).ok_or_else(ended),
162            Session::Failed { error, .. } => Err(format!("Tool session {}: {error}", name.1)),
163            _ => unreachable!("session startup resolved"),
164        }
165    }
166
167    pub async fn close(self) -> Result<(), String> {
168        let finished: Vec<_> = self
169            .0
170            .into_values()
171            .filter_map(|session| session.into_inner().running())
172            .map(|running| {
173                drop(running.stop);
174                running.finished
175            })
176            .collect();
177        let mut result = Ok(());
178        for task in finished {
179            let cleaned = crate::task::joined(task.await)
180                .map_err(|error| error.to_string())
181                .and_then(|result| result);
182            if result.is_ok() {
183                result = cleaned;
184            }
185        }
186        result
187    }
188}
189
190impl Registry<'_> {
191    /// Register lazy sessions for admitted tools, or the selected diagnostic tool.
192    /// No process or session directory is created until a bound call.
193    pub fn sessions(
194        &self,
195        state: &Path,
196        selected: Option<&str>,
197        cancellation: CancellationToken,
198    ) -> Sessions {
199        self.sessions_with_removal(state, selected, cancellation, platform::remove_tree)
200    }
201
202    pub(crate) fn sessions_with_removal(
203        &self,
204        state: &Path,
205        selected: Option<&str>,
206        cancellation: CancellationToken,
207        remove_directory: fn(&Path) -> io::Result<()>,
208    ) -> Sessions {
209        let mut sessions = Sessions::default();
210        for (tool_name, tool) in &self.tools {
211            if selected.is_some_and(|selected| tool_name != selected) {
212                continue;
213            }
214            let AgentTool::Command(tool_declaration) = tool.declaration else {
215                continue;
216            };
217            let Some(name) = &tool_declaration.session else {
218                continue;
219            };
220            let owner = &tool.definition.artifact_id;
221            let key = session_key(name, owner);
222            sessions.0.entry(key).or_insert_with(|| {
223                let declaration = &self.scope.artifacts[owner].views.agent_sessions[name];
224                let commands = self
225                    .prepare_session(owner, &declaration.start)
226                    .and_then(|start| {
227                        self.prepare_session(owner, &declaration.stop)
228                            .map(|stop| (start, stop))
229                    });
230                Mutex::new(Session::Pending(Box::new(Start {
231                    commands,
232                    workspace: self.config.root.clone(),
233                    state: state.to_owned(),
234                    cancellation: cancellation.clone(),
235                    remove_directory,
236                })))
237            });
238        }
239        sessions
240    }
241}
242
243pub(super) fn session_key(
244    name: &crate::config::ToolFqn,
245    owner: &crate::config::ArtifactName,
246) -> (ArtifactName, ToolFqn) {
247    (owner.clone(), name.clone())
248}
249
250#[expect(
251    clippy::too_many_arguments,
252    reason = "a supervisor owns its two commands, directory, independent stop and readiness channels"
253)]
254async fn supervise(
255    start: Invocation,
256    stop: Invocation,
257    workspace: std::path::PathBuf,
258    directory: platform::PrivateTempDir,
259    cancellation: CancellationToken,
260    stop_token: CancellationToken,
261    owner: std::sync::Arc<Ownership>,
262    send: oneshot::Sender<Result<BTreeMap<OsString, OsString>, String>>,
263    remove_directory: fn(&Path) -> io::Result<()>,
264) -> Result<(), String> {
265    // Once a supervisor may admit a process, only confirmed cleanup may delete
266    // its journal. Panic or an unexpected return must not invoke TempDir::drop.
267    let path = directory.keep().map_err(|error| error.to_string())?;
268    let mut cleanup = supervise_inner(
269        start,
270        stop,
271        &workspace,
272        &path,
273        cancellation,
274        stop_token,
275        owner,
276        send,
277    )
278    .await;
279    if cleanup.confirmed() {
280        let removed =
281            crate::task::joined(tokio::task::spawn_blocking(move || remove_directory(&path)).await)
282                .map_err(io::Error::other)
283                .and_then(std::convert::identity);
284        if let Err(error) = removed
285            && error.kind() != io::ErrorKind::NotFound
286        {
287            cleanup.merge(Cleanup::error(error));
288        }
289    }
290    cleanup.result()
291}
292
293#[expect(
294    clippy::too_many_arguments,
295    reason = "the supervisor's command, lifecycle and readiness state"
296)]
297async fn supervise_inner(
298    start: Invocation,
299    stop: Invocation,
300    workspace: &Path,
301    directory: &Path,
302    cancellation: CancellationToken,
303    stop_token: CancellationToken,
304    owner: std::sync::Arc<Ownership>,
305    send: oneshot::Sender<Result<BTreeMap<OsString, OsString>, String>>,
306) -> Cleanup {
307    let prepared = prepare(start, workspace, directory, None);
308    let (command, input) = match prepared {
309        Ok(prepared) => prepared,
310        Err(error) => {
311            let _ = send.send(Err(error));
312            return Cleanup::default();
313        }
314    };
315    let environment = command.env.clone();
316    let record = Record::start(directory);
317    let admitted = record.clone();
318    let deadline = Instant::now() + LIFECYCLE_TIMEOUT;
319    let child = process::spawn_owned(
320        &command,
321        true,
322        cancellation.clone(),
323        deadline,
324        Some(move |leader| async move { admitted.register(leader).await }),
325    )
326    .await;
327    let mut child = match child {
328        Ok(child) => child,
329        Err(error) => {
330            let _ = send.send(Err(error.to_string()));
331            record.after_run::<()>(&Err(error));
332            return record.finish();
333        }
334    };
335    let mut stdout = child.stdout().take().expect("stdout is piped");
336    let mut stderr = child.stderr().take().expect("stderr is piped");
337    let mut stdin = child.stdin().take().expect("stdin is piped");
338    let (ready_send, ready_receive) = oneshot::channel();
339    let drain_stdout = tokio::spawn(async move {
340        let ready = async {
341            let mut buffer = [0; DRAIN_BYTES];
342            loop {
343                let count = stdout.read(&mut buffer).await?;
344                if count == 0 {
345                    return Err(io::Error::other("exited before readiness"));
346                }
347                if buffer[..count].contains(&b'\n') {
348                    return Ok(());
349                }
350            }
351        }
352        .await;
353        let _ = ready_send.send(ready);
354        let _ = tokio::io::copy(&mut stdout, &mut tokio::io::sink()).await;
355    });
356    let drain_stderr = tokio::spawn(async move {
357        let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await;
358    });
359    let feed = tokio::spawn(async move {
360        let result = tokio::io::AsyncWriteExt::write_all(&mut stdin, &input).await;
361        drop(stdin);
362        result
363    });
364    let ready = tokio::select! {
365        biased;
366        _ = cancellation.cancelled() => Err("start was cancelled".to_owned()),
367        _ = stop_token.cancelled() => Err("start was dropped".to_owned()),
368        status = child.wait_leader() => Err(match status {
369            Ok(status) => format!("exited before readiness: {status}"),
370            Err(error) => format!("could not wait for the start command: {error}"),
371        }),
372        result = ready_receive => match result {
373            Ok(Ok(())) => match child.try_wait_leader() {
374                Ok(None) => Ok(()),
375                _ => Err("exited before readiness".into()),
376            },
377            Ok(Err(error)) => Err(error.to_string()),
378            Err(error) => Err(error.to_string()),
379        }
380    };
381    let mut child = Some(child);
382    let mut cleanup = Cleanup::default();
383    let started = ready.is_ok();
384    let _ = send.send(ready.map(|()| environment.clone()));
385    if started {
386        tokio::select! {
387            biased;
388            status = child.as_mut().expect("owned start").wait_leader() => {
389                owner.ended.cancel();
390                match child.as_mut().expect("owned start").cleanup().await {
391                    Ok(_) => {
392                        record.confirm();
393                        drop(child.take());
394                        cleanup.merge(record.finish());
395                    },
396                    Err(error) => cleanup.merge(Cleanup::error(error)),
397                }
398                let _ = status;
399                stop_token.cancelled().await;
400            },
401            _ = stop_token.cancelled() => {},
402        }
403    }
404    cleanup.merge(owner.finish_calls().await);
405    // Stop ignores the review's cancelled token. Its own one-shot supervisor bounds
406    // the command, then the session group is killed regardless of its outcome.
407    if let Ok((command, input)) = prepare(stop, workspace, directory, Some(&environment)) {
408        let stopped = Record::new(directory);
409        let admitted = stopped.clone();
410        let result = process::run_with_input_limit(
411            command,
412            Some(input),
413            0,
414            CancellationToken::new(),
415            move |child| async move { admitted.register(child).await },
416        )
417        .await;
418        stopped.after_run(&result);
419        cleanup.merge(stopped.finish());
420    }
421    if let Some(mut child) = child {
422        match child.cleanup().await {
423            Ok(_) => record.confirm(),
424            Err(error) => cleanup.merge(Cleanup::error(error)),
425        }
426    }
427    // A failed signal/wait leaves Record owned; finish marks cleanup incomplete
428    // and keeps every journal even after this supervisor/lease is released.
429    cleanup.merge(record.finish());
430    feed.abort();
431    drain_stdout.abort();
432    drain_stderr.abort();
433    // Aborted tasks end cancelled, which is expected; a panic in one continues here.
434    let _ = crate::task::joined(feed.await);
435    let _ = crate::task::joined(drain_stdout.await);
436    let _ = crate::task::joined(drain_stderr.await);
437    cleanup
438}
439
440fn prepare(
441    mut invocation: Invocation,
442    workspace: &Path,
443    directory: &Path,
444    environment: Option<&BTreeMap<OsString, OsString>>,
445) -> Result<(process::Command, Vec<u8>), String> {
446    let mut command = runtime::Command::prepare(
447        invocation.program,
448        invocation.argv,
449        workspace,
450        directory,
451        Some(LIFECYCLE_TIMEOUT),
452    )
453    .map_err(|error| error.to_string())?;
454    command.cwd = invocation.cwd;
455    command.session_environment(directory);
456    if let Some(environment) = environment {
457        command.inherit_session(environment);
458    }
459    invocation.context.output_dir = Some(command.directory().join("output"));
460    invocation.context.tmp_dir = Some(command.directory().join("tmp"));
461    let input = serde_json::json!({"version": super::JSON_TOOL_INPUT_VERSION, "context": invocation.context, "args": {}}).to_string().into_bytes();
462    Ok((command.into_process(), input))
463}
464
465/// Recover abandoned session journals through their existing identity-checked allocation sweep.
466pub(crate) fn recover(state: &Path) -> io::Result<()> {
467    let root = state.join("tool-sessions");
468    if root.is_dir() {
469        let _ = allocate(&root)?;
470    }
471    Ok(())
472}