1use 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
26const LIFECYCLE_TIMEOUT: Duration = Duration::from_secs(30);
31const 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 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 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 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 let path = directory.keep().map_err(|error| error.to_string())?;
268 let lease = owner.clone();
269 let mut cleanup = supervise_inner(
270 start,
271 stop,
272 &workspace,
273 &path,
274 cancellation,
275 stop_token,
276 owner,
277 send,
278 )
279 .await;
280 if cleanup.confirmed() {
281 let removed =
282 crate::task::joined(tokio::task::spawn_blocking(move || remove_directory(&path)).await)
283 .map_err(io::Error::other)
284 .and_then(std::convert::identity);
285 if let Err(error) = removed
286 && error.kind() != io::ErrorKind::NotFound
287 {
288 cleanup.merge(Cleanup::error(error));
289 }
290 }
291 lease.release();
292 cleanup.result()
293}
294
295#[expect(
296 clippy::too_many_arguments,
297 reason = "the supervisor's command, lifecycle and readiness state"
298)]
299async fn supervise_inner(
300 start: Invocation,
301 stop: Invocation,
302 workspace: &Path,
303 directory: &Path,
304 cancellation: CancellationToken,
305 stop_token: CancellationToken,
306 owner: std::sync::Arc<Ownership>,
307 send: oneshot::Sender<Result<BTreeMap<OsString, OsString>, String>>,
308) -> Cleanup {
309 let prepared = prepare(start, workspace, directory, None);
310 let (command, input) = match prepared {
311 Ok(prepared) => prepared,
312 Err(error) => {
313 let _ = send.send(Err(error));
314 return Cleanup::default();
315 }
316 };
317 let environment = command.env.clone();
318 let record = Record::start(directory);
319 let admitted = record.clone();
320 let deadline = Instant::now() + LIFECYCLE_TIMEOUT;
321 let child = process::spawn_owned(
322 &command,
323 true,
324 cancellation.clone(),
325 deadline,
326 Some(move |leader| async move { admitted.register(leader).await }),
327 )
328 .await;
329 let mut child = match child {
330 Ok(child) => child,
331 Err(error) => {
332 let _ = send.send(Err(error.to_string()));
333 record.after_run::<()>(&Err(error));
334 return record.finish();
335 }
336 };
337 let mut stdout = child.stdout().take().expect("stdout is piped");
338 let mut stderr = child.stderr().take().expect("stderr is piped");
339 let mut stdin = child.stdin().take().expect("stdin is piped");
340 let (ready_send, ready_receive) = oneshot::channel();
341 let drain_stdout = tokio::spawn(async move {
342 let ready = async {
343 let mut buffer = [0; DRAIN_BYTES];
344 loop {
345 let count = stdout.read(&mut buffer).await?;
346 if count == 0 {
347 return Err(io::Error::other("exited before readiness"));
348 }
349 if buffer[..count].contains(&b'\n') {
350 return Ok(());
351 }
352 }
353 }
354 .await;
355 let _ = ready_send.send(ready);
356 let _ = tokio::io::copy(&mut stdout, &mut tokio::io::sink()).await;
357 });
358 let drain_stderr = tokio::spawn(async move {
359 let _ = tokio::io::copy(&mut stderr, &mut tokio::io::sink()).await;
360 });
361 let feed = tokio::spawn(async move {
362 let result = tokio::io::AsyncWriteExt::write_all(&mut stdin, &input).await;
363 drop(stdin);
364 result
365 });
366 let ready = tokio::select! {
367 biased;
368 _ = cancellation.cancelled() => Err("start was cancelled".to_owned()),
369 _ = stop_token.cancelled() => Err("start was dropped".to_owned()),
370 status = child.wait_leader() => Err(match status {
371 Ok(status) => format!("exited before readiness: {status}"),
372 Err(error) => format!("could not wait for the start command: {error}"),
373 }),
374 result = ready_receive => match result {
375 Ok(Ok(())) => match child.try_wait_leader() {
376 Ok(None) => Ok(()),
377 _ => Err("exited before readiness".into()),
378 },
379 Ok(Err(error)) => Err(error.to_string()),
380 Err(error) => Err(error.to_string()),
381 }
382 };
383 let mut child = Some(child);
384 let mut cleanup = Cleanup::default();
385 let started = ready.is_ok();
386 let _ = send.send(ready.map(|()| environment.clone()));
387 if started {
388 tokio::select! {
389 biased;
390 status = child.as_mut().expect("owned start").wait_leader() => {
391 owner.ended.cancel();
392 match child.as_mut().expect("owned start").cleanup().await {
393 Ok(_) => {
394 record.confirm();
395 drop(child.take());
396 cleanup.merge(record.finish());
397 },
398 Err(error) => cleanup.merge(Cleanup::error(error)),
399 }
400 let _ = status;
401 stop_token.cancelled().await;
402 },
403 _ = stop_token.cancelled() => {},
404 }
405 }
406 cleanup.merge(owner.finish_calls().await);
407 if let Ok((command, input)) = prepare(stop, workspace, directory, Some(&environment)) {
410 let stopped = Record::new(directory);
411 let admitted = stopped.clone();
412 let result = process::run_with_input_limit(
413 command,
414 Some(input),
415 0,
416 CancellationToken::new(),
417 move |child| async move { admitted.register(child).await },
418 )
419 .await;
420 stopped.after_run(&result);
421 cleanup.merge(stopped.finish());
422 }
423 if let Some(mut child) = child {
424 match child.cleanup().await {
425 Ok(_) => record.confirm(),
426 Err(error) => cleanup.merge(Cleanup::error(error)),
427 }
428 }
429 cleanup.merge(record.finish());
432 feed.abort();
433 drain_stdout.abort();
434 drain_stderr.abort();
435 let _ = crate::task::joined(feed.await);
437 let _ = crate::task::joined(drain_stdout.await);
438 let _ = crate::task::joined(drain_stderr.await);
439 cleanup
440}
441
442fn prepare(
443 mut invocation: Invocation,
444 workspace: &Path,
445 directory: &Path,
446 environment: Option<&BTreeMap<OsString, OsString>>,
447) -> Result<(process::Command, Vec<u8>), String> {
448 let mut command = runtime::Command::prepare(
449 invocation.program,
450 invocation.argv,
451 workspace,
452 directory,
453 Some(LIFECYCLE_TIMEOUT),
454 )
455 .map_err(|error| error.to_string())?;
456 command.cwd = invocation.cwd;
457 command.session_environment(directory);
458 if let Some(environment) = environment {
459 command.inherit_session(environment);
460 }
461 invocation.context.output_dir = Some(command.directory().join("output"));
462 invocation.context.tmp_dir = Some(command.directory().join("tmp"));
463 let input = serde_json::json!({"version": super::JSON_TOOL_INPUT_VERSION, "context": invocation.context, "args": {}}).to_string().into_bytes();
464 Ok((command.into_process(), input))
465}
466
467pub(crate) fn recover(state: &Path) -> io::Result<()> {
469 let root = state.join("tool-sessions");
470 if root.is_dir() {
471 let _ = allocate(&root)?;
472 }
473 Ok(())
474}