1mod follow;
3#[cfg(test)]
4#[path = "tests/lifetime.rs"]
5mod lifetime_tests;
6mod observe;
7mod reference;
8mod result;
9mod watch;
10mod worker;
11pub use crate::store::{RunSummary, RunView};
12use crate::{
13 process,
14 project::{VerifyOptions, selection::Selection},
15 store::{self, Receipts},
16 types::{FailureCode, RequestKey, RunId},
17};
18pub use follow::{Follow, FollowUpdate, RunFinished, reconcile_open, workspaces};
19pub use observe::{
20 Counts, RunObservation, State, reconcile_interrupted, status, view, wait, wait_for_change,
21 wait_observing,
22};
23pub use reference::{Reference, reference};
24pub use result::{
25 Completion, Finding, PAGE_SIZE as RESULT_PAGE_SIZE, ResultCursor, ResultState, RunResultPage,
26 RunVerdict, Signoff, completion, result,
27};
28use serde::{Deserialize, Serialize};
29use std::path::{Path, PathBuf};
30pub use watch::{RunEvent, watch};
31#[doc(hidden)]
32pub use worker::{execute, supervise, supervise_observing_launch};
33
34pub async fn list(
36 state: &Path,
37 repo: Option<&Path>,
38 limit: u32,
39 offset: u32,
40) -> Result<Vec<RunSummary>, String> {
41 store::read_runs(state, repo, limit, offset).await
42}
43
44#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
46#[serde(default)]
47pub struct RunModes {
48 pub speculate: bool,
49}
50impl RunModes {
51 pub(crate) fn is_default(&self) -> bool {
52 self == &Self::default()
53 }
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
57#[serde(rename_all = "snake_case")]
58pub enum Activity {
59 Preparing,
60 Executing,
61 Publishing,
62 Waiting,
63 Cancelling,
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(tag = "state", rename_all = "snake_case")]
68pub enum Worker {
69 Starting {
70 launcher: process::ChildIdentity,
71 },
72 Admitted {
73 owner: process::ChildIdentity,
74 },
75 Legacy,
77}
78#[derive(Debug, Clone, Serialize, Deserialize)]
79#[serde(from = "ControlWire", into = "ControlWire")]
80pub struct Control {
81 pub worker: Worker,
82 pub supervisor: Option<process::ChildIdentity>,
84 pub activity: Activity,
85 pub failure_code: Option<FailureCode>,
86}
87
88#[derive(Serialize, Deserialize)]
89#[serde(rename_all = "camelCase")]
90struct ControlWire {
91 worker: Worker,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
93 supervisor: Option<process::ChildIdentity>,
94 activity: Activity,
95 #[serde(default)]
96 cancellation_requested: bool,
97 #[serde(default, skip_serializing_if = "Option::is_none")]
98 failure_code: Option<FailureCode>,
99}
100
101impl From<ControlWire> for Control {
102 fn from(wire: ControlWire) -> Self {
103 Self {
104 worker: wire.worker,
105 supervisor: wire.supervisor,
106 activity: if wire.cancellation_requested {
107 Activity::Cancelling
108 } else {
109 wire.activity
110 },
111 failure_code: wire.failure_code,
112 }
113 }
114}
115
116impl From<Control> for ControlWire {
117 fn from(control: Control) -> Self {
118 Self {
119 worker: control.worker,
120 supervisor: control.supervisor,
121 activity: control.activity,
122 cancellation_requested: control.is_cancelling(),
123 failure_code: control.failure_code,
124 }
125 }
126}
127
128impl Control {
129 pub fn is_cancelling(&self) -> bool {
130 self.activity == Activity::Cancelling
131 }
132
133 pub(crate) fn starting() -> Result<Self, String> {
134 Ok(Self {
135 worker: Worker::Starting {
136 launcher: process::child_identity(std::process::id()).map_err(|e| e.to_string())?,
137 },
138 supervisor: None,
139 activity: Activity::Preparing,
140 failure_code: None,
141 })
142 }
143 pub(crate) fn legacy() -> Self {
144 Self {
145 worker: Worker::Legacy,
146 supervisor: None,
147 activity: Activity::Executing,
148 failure_code: None,
149 }
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
155#[serde(
156 tag = "kind",
157 rename_all = "camelCase",
158 rename_all_fields = "camelCase"
159)]
160pub enum Origin {
161 Cli,
162 Mcp,
163 #[serde(other)]
164 Unknown,
165}
166
167#[derive(Debug, Clone)]
169pub struct Context {
170 pub(crate) repo: PathBuf,
171 pub(crate) state: PathBuf,
172 executable: PathBuf,
173 origin: Origin,
174}
175impl Context {
176 pub fn repo(&self) -> &Path {
178 &self.repo
179 }
180
181 pub fn state(&self) -> &Path {
183 &self.state
184 }
185
186 pub fn new(repo: &Path, state: Option<&Path>, executable: &Path) -> Result<Self, String> {
187 Ok(Self {
188 repo: crate::workspace::canonical_target(repo).map_err(|e| e.to_string())?,
189 state: crate::workspace::canonical_target(&store::state_dir(state)?)
190 .map_err(|e| e.to_string())?,
191 executable: executable.to_path_buf(),
192 origin: Origin::Cli,
193 })
194 }
195 pub async fn for_run(
197 state: Option<&Path>,
198 id: &RunId,
199 executable: &Path,
200 ) -> Result<Self, String> {
201 let state = crate::store::state_dir(state)?;
202 let repo = crate::store::read_run_repo(&state, id).await?;
203 Self::new(&repo, Some(&state), executable)
204 }
205
206 pub fn worker_diagnostics(&self, id: &RunId) -> String {
208 crate::process::run_worker_diagnostics(&self.state, id)
209 }
210
211 #[must_use]
213 pub fn with_origin(self, origin: Origin) -> Self {
214 Self { origin, ..self }
215 }
216
217 pub fn discover(repo: &Path, state: Option<&Path>) -> Result<Self, String> {
219 let executable = process::artifactize_executable()?;
220 Self::new(repo, state, &executable)
221 }
222}
223
224pub fn check_eval_backend(
228 backend: &crate::config::Backend,
229 state: Option<&Path>,
230 repo: Option<&Path>,
231) -> Result<(), crate::agent::error::Failure> {
232 backend.admit(|name| {
233 let providers = crate::auth::providers::list(state, repo)?;
234 Ok(providers.custom.contains_key(name.as_str()))
235 })
236}
237
238pub async fn start(
239 context: &Context,
240 selection: &Selection,
241 options: &VerifyOptions,
242 request_key: Option<RequestKey>,
243) -> Result<RunObservation, String> {
244 start_with_args_hash(context, selection, options, request_key, None).await
245}
246
247pub(crate) async fn start_with_args_hash(
249 context: &Context,
250 selection: &Selection,
251 options: &VerifyOptions,
252 request_key: Option<RequestKey>,
253 request_args_hash: Option<String>,
254) -> Result<RunObservation, String> {
255 start_observing_launch_with_hash(
256 context,
257 selection,
258 options,
259 request_key,
260 request_args_hash,
261 |_, _| {},
262 )
263 .await
264}
265
266#[doc(hidden)]
268pub async fn start_observing_launch(
269 context: &Context,
270 selection: &Selection,
271 options: &VerifyOptions,
272 request_key: Option<RequestKey>,
273 launched: impl FnOnce(&RunId, process::ChildIdentity),
274) -> Result<RunObservation, String> {
275 start_observing_launch_with_hash(context, selection, options, request_key, None, launched).await
276}
277
278async fn start_observing_launch_with_hash(
279 context: &Context,
280 selection: &Selection,
281 options: &VerifyOptions,
282 request_key: Option<RequestKey>,
283 request_args_hash: Option<String>,
284 launched: impl FnOnce(&RunId, process::ChildIdentity),
285) -> Result<RunObservation, String> {
286 if let Some(key) = &request_key
288 && crate::platform::paths::target_is_file(&context.state.join(store::DATABASE))
289 {
290 let receipts = Receipts::open(&context.state, &context.repo).await?;
291 let result = receipts
292 .keyed_run(&context.repo, key, request_args_hash.as_deref())
293 .await;
294 let closed = receipts.close().await;
295 if let Some(id) = result.and_then(|id| closed.map(|()| id))? {
296 return status(context, &id).await;
297 }
298 }
299 let (id, accepted) = crate::project::verify::reserve(
300 &context.repo,
301 Some(&context.state),
302 selection,
303 options,
304 request_key.as_ref(),
305 request_args_hash.as_deref(),
306 &context.origin,
307 )
308 .await?;
309 if accepted {
310 let receipts = Receipts::open(&context.state, &context.repo).await?;
311 let result = async {
312 let launch =
313 process::launch_run(&context.executable, &id, &context.repo, &context.state);
314 let admitted = match launch {
315 Ok(identity) => {
316 launched(&id, identity);
317 receipts.admit(&id, identity).await
318 }
319 Err(error) => Err(error.to_string()),
320 };
321 if let Err(error) = admitted {
322 worker::fail(&receipts, &id, FailureCode::SpawnFailed, error.clone()).await?;
323 return Err(format!("Run {id} handoff failed: {error}"));
324 }
325 Ok(())
326 }
327 .await;
328 let closed = receipts.close().await;
329 result.and(closed)?;
330 }
331 crate::platform::release_free_memory();
334 status(context, &id).await
335}
336
337#[derive(Debug, Clone, Serialize)]
338pub struct CancelAcknowledgement {
339 pub run: RunId,
340 pub state: State,
341 pub cancellation_requested: bool,
342}
343pub async fn cancel(context: &Context, id: &RunId) -> Result<CancelAcknowledgement, String> {
344 let current = status(context, id).await?;
346 let receipts = Receipts::open(&context.state, &context.repo).await?;
347 let result = receipts.request_cancel(id).await;
348 let closed = receipts.close().await;
349 let (saved, control) = result.and_then(|saved| closed.map(|()| saved))?;
350 Ok(CancelAcknowledgement {
351 run: id.clone(),
352 state: observe::state_for(saved, control.as_ref(), ¤t.counts),
353 cancellation_requested: control.as_ref().is_some_and(Control::is_cancelling),
354 })
355}
356
357fn owner_died(status: crate::types::RunStatus, control: Option<&Control>) -> Result<bool, String> {
358 if !status.is_open() {
359 return Ok(false);
360 }
361 let owner = control.and_then(|control| match control.worker {
362 Worker::Starting { launcher } => Some(launcher),
363 Worker::Admitted { owner } => Some(owner),
364 Worker::Legacy => None,
365 });
366 Ok(owner.is_some() && !process::is_alive(owner).map_err(|error| error.to_string())?)
367}
368
369pub(crate) async fn reconcile(
370 state: &Path,
371 view: store::RunView,
372) -> Result<store::RunView, String> {
373 if owner_died(view.run.status(), view.run.control.as_ref())? {
374 worker::recover(state, &view).await?;
375 return store::read_run(state, &view.run.id).await;
376 }
377 Ok(view)
378}