Skip to main content

agent_server/api/
runs.rs

1//! Run submission, inspection, cancellation, and event routes.
2
3use std::collections::{HashMap, HashSet};
4use std::str::FromStr;
5
6use agent_metering::{
7    CostEstimate, CostStatus, ModelPricing, UsageRecord, calculate_cost, summarize_usage,
8};
9
10use super::types::{
11    CancelRunResponse, GetRunResponse, RunEventResponse, SubmitRunRequest, SubmitRunResponse,
12};
13use actix_web::{
14    HttpRequest, HttpResponse, Responder, Scope, get,
15    http::header,
16    post,
17    web::{self, Bytes, Data, Json, Path},
18};
19use agent_runtime::ToolContext;
20use agent_service::Run;
21use agent_service::{
22    CancelRunError, CancelRunOutcome, RunId, RunManager, RunStatus, SubmitRunError,
23};
24use agent_storage::{
25    ConversationId, FileUserIdentityStore, SqliteConversationStore, UserIdentityStore,
26};
27use std::{sync::Arc, time::Duration};
28use tokio::sync::mpsc;
29
30fn owns_run(
31    run: &Run,
32    request: &HttpRequest,
33    auth: Option<&crate::auth::TelegramAuth>,
34    store: Option<&SqliteConversationStore>,
35) -> bool {
36    let Some(auth) = auth else {
37        return true;
38    };
39    let Some(owner) = auth.owner_for_request(request) else {
40        return false;
41    };
42    if let Some(conversation_id) = run.conversation_id {
43        let Ok(id) = ConversationId::from_str(&conversation_id.to_string()) else {
44            return false;
45        };
46        store.is_some_and(|store| {
47            store
48                .get(id)
49                .is_ok_and(|conversation| conversation.owner == owner)
50        })
51    } else {
52        auth.runs_for_owner(&owner).contains(&run.id.to_string())
53    }
54}
55
56fn status_name(status: RunStatus) -> &'static str {
57    match status {
58        RunStatus::Queued => "queued",
59        RunStatus::Running => "running",
60        RunStatus::Completed => "completed",
61        RunStatus::Failed => "failed",
62        RunStatus::Cancelled => "cancelled",
63        RunStatus::TimedOut => "timed_out",
64        RunStatus::MaxIterationsReached => "max_iterations_reached",
65    }
66}
67
68#[get("")]
69async fn list_runs(
70    request: HttpRequest,
71    auth: Option<Data<crate::auth::TelegramAuth>>,
72    manager: Data<RunManager>,
73    store: Option<Data<Arc<SqliteConversationStore>>>,
74) -> impl Responder {
75    let runs = manager
76        .list()
77        .await
78        .into_iter()
79        .filter(|run| match auth.as_ref() {
80            Some(auth) => owns_run(
81                run,
82                &request,
83                Some(auth.get_ref()),
84                store.as_ref().map(|store| store.get_ref().as_ref()),
85            ),
86            None => true,
87        })
88        .collect::<Vec<_>>();
89    let body = runs
90        .into_iter()
91        .map(|run| GetRunResponse {
92            run_id: run.id.to_string(),
93            conversation_id: run.conversation_id.map(|id| id.to_string()),
94            input: run.input,
95            agent: run.agent,
96            status: status_name(run.status),
97            response: run.response,
98            error: run.error,
99        })
100        .collect::<Vec<_>>();
101    HttpResponse::Ok().json(body)
102}
103
104#[get("/usage")]
105async fn get_usage(
106    request: HttpRequest,
107    auth: Option<Data<crate::auth::TelegramAuth>>,
108    store: Option<Data<Arc<SqliteConversationStore>>>,
109    manager: Data<RunManager>,
110) -> impl Responder {
111    let visible_run_ids = manager
112        .list()
113        .await
114        .into_iter()
115        .filter(|run| {
116            owns_run(
117                run,
118                &request,
119                auth.as_deref().map(|value| &**value),
120                store.as_ref().map(|value| value.get_ref().as_ref()),
121            )
122        })
123        .map(|run| run.id.as_uuid())
124        .collect::<HashSet<_>>();
125
126    let records = match manager.usage_records(None).await {
127        Ok(records) => records,
128        Err(error) => {
129            tracing::error!(%error, "failed to load usage records");
130            return HttpResponse::InternalServerError().body("could not load usage records");
131        }
132    };
133
134    let mut pricing_cache: HashMap<(String, String), Vec<ModelPricing>> = HashMap::new();
135    let mut response = Vec::new();
136    for record in records
137        .into_iter()
138        .filter(|record| visible_run_ids.contains(&record.run_id))
139    {
140        let cost = if let Some(reported) = &record.reported_cost {
141            Some(CostEstimate::from_reported(reported))
142        } else {
143            let key = (record.provider.clone(), record.model.clone());
144            if !pricing_cache.contains_key(&key) {
145                match manager.pricing_for(&key.0, &key.1).await {
146                    Ok(pricing) => {
147                        pricing_cache.insert(key.clone(), pricing);
148                    }
149                    Err(error) => {
150                        tracing::error!(provider = %key.0, model = %key.1, %error, "failed to load model pricing");
151                        pricing_cache.insert(key.clone(), Vec::new());
152                    }
153                }
154            }
155            pricing_cache.get(&key).and_then(|versions| {
156                versions
157                    .iter()
158                    .find(|pricing| pricing.applies_to(&record))
159                    .and_then(|pricing| calculate_cost(&record, pricing).ok())
160                    .filter(|cost| cost.status != CostStatus::Unavailable)
161            })
162        };
163
164        let mut item = match serde_json::to_value(&record) {
165            Ok(value) => value,
166            Err(error) => {
167                tracing::error!(%error, "failed to serialize usage record");
168                return HttpResponse::InternalServerError()
169                    .body("could not serialize usage records");
170            }
171        };
172        item["cost"] = serde_json::to_value(cost).unwrap_or(serde_json::Value::Null);
173        response.push(item);
174    }
175
176    HttpResponse::Ok().json(response)
177}
178
179fn estimate_record_cost(record: &UsageRecord, pricing: &[ModelPricing]) -> Option<CostEstimate> {
180    if let Some(reported) = &record.reported_cost {
181        return Some(CostEstimate::from_reported(reported));
182    }
183    pricing
184        .iter()
185        .find(|price| price.applies_to(record))
186        .and_then(|price| calculate_cost(record, price).ok())
187        .filter(|cost| cost.status != CostStatus::Unavailable)
188}
189
190#[get("/{run_id}/usage")]
191async fn get_run_usage(
192    path: Path<String>,
193    request: HttpRequest,
194    auth: Option<Data<crate::auth::TelegramAuth>>,
195    store: Option<Data<Arc<SqliteConversationStore>>>,
196    manager: Data<RunManager>,
197) -> impl Responder {
198    let run_id = match RunId::from_str(&path) {
199        Ok(run_id) => run_id,
200        Err(_) => return HttpResponse::BadRequest().body("invalid run ID"),
201    };
202    let run = manager
203        .list()
204        .await
205        .into_iter()
206        .find(|run| run.id == run_id);
207    let Some(run) = run else {
208        return HttpResponse::NotFound().finish();
209    };
210    if !owns_run(
211        &run,
212        &request,
213        auth.as_deref().map(|value| &**value),
214        store.as_ref().map(|value| value.get_ref().as_ref()),
215    ) {
216        return HttpResponse::Forbidden().finish();
217    }
218
219    let records = match manager.usage_records(Some(run_id)).await {
220        Ok(records) => records,
221        Err(error) => {
222            tracing::error!(%run_id, %error, "failed to load run usage records");
223            return HttpResponse::InternalServerError().body("could not load run usage");
224        }
225    };
226    let pricing = match manager.pricing_catalog().await {
227        Ok(pricing) => pricing,
228        Err(error) => {
229            tracing::error!(%run_id, %error, "failed to load pricing catalogue");
230            return HttpResponse::InternalServerError().body("could not load pricing catalogue");
231        }
232    };
233    let summary = summarize_usage(&records, &pricing);
234    let invocations = records
235        .iter()
236        .map(|record| {
237            let mut item = serde_json::to_value(record).unwrap_or(serde_json::Value::Null);
238            item["cost"] = serde_json::to_value(estimate_record_cost(record, &pricing))
239                .unwrap_or(serde_json::Value::Null);
240            item
241        })
242        .collect::<Vec<_>>();
243
244    HttpResponse::Ok().json(serde_json::json!({
245        "run_id": run_id.to_string(),
246        "summary": summary,
247        "invocations": invocations
248    }))
249}
250
251#[get("/pricing")]
252async fn list_pricing(manager: Data<RunManager>) -> impl Responder {
253    match manager.pricing_catalog().await {
254        Ok(pricing) => HttpResponse::Ok().json(pricing),
255        Err(error) => {
256            tracing::error!(%error, "failed to load pricing catalogue");
257            HttpResponse::InternalServerError().body("could not load pricing catalogue")
258        }
259    }
260}
261
262#[post("/pricing")]
263async fn create_pricing(
264    request: HttpRequest,
265    auth: Option<Data<crate::auth::TelegramAuth>>,
266    manager: Data<RunManager>,
267    pricing: Json<ModelPricing>,
268) -> impl Responder {
269    if auth
270        .as_ref()
271        .and_then(|auth| auth.owner_for_request(&request))
272        .is_none()
273    {
274        return HttpResponse::Unauthorized().finish();
275    }
276    if let Err(error) = pricing.validate() {
277        return HttpResponse::BadRequest().body(error.to_string());
278    }
279    match manager.register_pricing(pricing.into_inner()).await {
280        Ok(()) => HttpResponse::Created().finish(),
281        Err(error) if error.contains("already exists") => HttpResponse::Conflict().body(error),
282        Err(error) => {
283            tracing::error!(%error, "failed to register model pricing");
284            HttpResponse::InternalServerError().body("could not register model pricing")
285        }
286    }
287}
288
289#[post("")]
290async fn submit_run(
291    http_request: HttpRequest,
292    auth: Option<Data<crate::auth::TelegramAuth>>,
293    manager: Data<RunManager>,
294    identities: Option<Data<Arc<FileUserIdentityStore>>>,
295    request: Json<SubmitRunRequest>,
296) -> impl Responder {
297    if request.agent.trim().is_empty() {
298        return HttpResponse::BadRequest().body("agent must not be empty");
299    }
300    if request.input.trim().is_empty() {
301        return HttpResponse::BadRequest().body("input must not be empty");
302    }
303
304    let context = auth
305        .as_ref()
306        .and_then(|auth| auth.owner_for_request(&http_request))
307        .and_then(|owner| owner.strip_prefix("telegram:").map(str::to_owned))
308        .and_then(|subject| {
309            identities
310                .as_ref()?
311                .find_identity("telegram", &subject)
312                .ok()
313                .flatten()
314        })
315        .map(|identity| ToolContext {
316            user_id: Some(identity.user_id.to_string()),
317            telegram_id: Some(identity.subject),
318            ..ToolContext::default()
319        })
320        .unwrap_or_default();
321
322    match manager
323        .submit(
324            request.agent.clone(),
325            request.input.clone(),
326            Vec::new(),
327            context,
328        )
329        .await
330    {
331        Ok(run_id) => {
332            if let Some(auth) = auth.as_ref() {
333                if let Some(owner) = auth.owner_for_request(&http_request) {
334                    auth.register_run(run_id.to_string(), &owner);
335                }
336            }
337            HttpResponse::Accepted().json(SubmitRunResponse {
338                run_id: run_id.to_string(),
339                status: "queued",
340            })
341        }
342        Err(SubmitRunError::QueueFull) => {
343            HttpResponse::ServiceUnavailable().body("run queue is full")
344        }
345        Err(SubmitRunError::Storage(error)) => {
346            tracing::error!(%error, "failed to persist submitted run");
347            HttpResponse::InternalServerError().body("could not persist run")
348        }
349    }
350}
351
352#[get("/{run_id}")]
353async fn get_run(
354    request: HttpRequest,
355    auth: Option<Data<crate::auth::TelegramAuth>>,
356    store: Option<Data<Arc<SqliteConversationStore>>>,
357    manager: Data<RunManager>,
358    run_id: Path<String>,
359) -> impl Responder {
360    let run_id = match RunId::from_str(&run_id) {
361        Ok(run_id) => run_id,
362        Err(_) => return HttpResponse::BadRequest().body("invalid run identifier"),
363    };
364
365    match manager.get(run_id).await {
366        Some(run)
367            if owns_run(
368                &run,
369                &request,
370                auth.as_deref().map(|v| &**v),
371                store.as_ref().map(|store| store.get_ref().as_ref()),
372            ) =>
373        {
374            HttpResponse::Ok().json(GetRunResponse {
375                run_id: run.id.to_string(),
376                conversation_id: run.conversation_id.map(|id| id.to_string()),
377                input: run.input,
378                agent: run.agent,
379                status: status_name(run.status),
380                response: run.response,
381                error: run.error,
382            })
383        }
384        Some(_) | None => HttpResponse::NotFound().finish(),
385    }
386}
387
388#[get("/{run_id}/events")]
389async fn get_run_events(
390    request: HttpRequest,
391    auth: Option<Data<crate::auth::TelegramAuth>>,
392    store: Option<Data<Arc<SqliteConversationStore>>>,
393    manager: Data<RunManager>,
394    run_id: Path<String>,
395) -> impl Responder {
396    let run_id = match RunId::from_str(&run_id) {
397        Ok(run_id) => run_id,
398        Err(_) => return HttpResponse::BadRequest().body("invalid run identifier"),
399    };
400
401    let Some(run) = manager.get(run_id).await else {
402        return HttpResponse::NotFound().finish();
403    };
404    if !owns_run(
405        &run,
406        &request,
407        auth.as_deref().map(|v| &**v),
408        store.as_ref().map(|store| store.get_ref().as_ref()),
409    ) {
410        return HttpResponse::NotFound().finish();
411    }
412    match manager.events(run_id).await {
413        Some(events) => HttpResponse::Ok().json(
414            events
415                .into_iter()
416                .map(RunEventResponse::from)
417                .collect::<Vec<_>>(),
418        ),
419        None => HttpResponse::NotFound().finish(),
420    }
421}
422
423#[get("/{run_id}/events/stream")]
424async fn stream_run_events(
425    request: HttpRequest,
426    auth: Option<Data<crate::auth::TelegramAuth>>,
427    store: Option<Data<Arc<SqliteConversationStore>>>,
428    manager: Data<RunManager>,
429    run_id: Path<String>,
430) -> HttpResponse {
431    let run_id = match RunId::from_str(&run_id) {
432        Ok(run_id) => run_id,
433        Err(_) => return HttpResponse::BadRequest().body("invalid run identifier"),
434    };
435
436    let Some(run) = manager.get(run_id).await else {
437        return HttpResponse::NotFound().finish();
438    };
439    if !owns_run(
440        &run,
441        &request,
442        auth.as_deref().map(|v| &**v),
443        store.as_ref().map(|store| store.get_ref().as_ref()),
444    ) {
445        return HttpResponse::NotFound().finish();
446    }
447
448    // Subscribe before taking the snapshot. Events arriving in between are
449    // represented in both and de-duplicated by their per-run sequence number.
450    let mut live_events = manager.subscribe_events();
451    let replay = manager.events(run_id).await.unwrap_or_default();
452    let last_event_id = request
453        .headers()
454        .get("Last-Event-ID")
455        .and_then(|value| value.to_str().ok())
456        .and_then(|value| value.parse::<u64>().ok());
457    let (sender, receiver) = mpsc::channel::<Bytes>(32);
458    let manager = manager.clone();
459
460    actix_web::rt::spawn(async move {
461        let mut last_sequence = last_event_id;
462        for event in replay {
463            if last_sequence.is_some_and(|last| event.sequence <= last) {
464                continue;
465            }
466            let Some((sequence, terminal)) = send_sse_event(&sender, event).await else {
467                return;
468            };
469            last_sequence = Some(sequence);
470            if terminal {
471                return;
472            }
473        }
474
475        if manager
476            .get(run_id)
477            .await
478            .is_some_and(|run| !matches!(run.status, RunStatus::Queued | RunStatus::Running))
479        {
480            return;
481        }
482
483        let mut heartbeat = tokio::time::interval(Duration::from_secs(15));
484        loop {
485            tokio::select! {
486                received = live_events.recv() => {
487                    match received {
488                        Ok((event_run_id, event)) if event_run_id == run_id => {
489                            if last_sequence.is_some_and(|last| event.sequence <= last) {
490                                continue;
491                            }
492                            let Some((sequence, terminal)) = send_sse_event(&sender, event).await else {
493                                return;
494                            };
495                            last_sequence = Some(sequence);
496                            if terminal {
497                                return;
498                            }
499                        }
500                        Ok(_) => {}
501                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
502                            // Recover from a slow consumer using ordered run history.
503                            for event in manager.events(run_id).await.unwrap_or_default() {
504                                if last_sequence.is_some_and(|last| event.sequence <= last) {
505                                    continue;
506                                }
507                                let Some((sequence, terminal)) = send_sse_event(&sender, event).await else {
508                                    return;
509                                };
510                                last_sequence = Some(sequence);
511                                if terminal {
512                                    return;
513                                }
514                            }
515                        }
516                        Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
517                    }
518                }
519                _ = heartbeat.tick() => {
520                    if sender.send(Bytes::from_static(b": keep-alive\n\n")).await.is_err() {
521                        return;
522                    }
523                }
524            }
525        }
526    });
527
528    HttpResponse::Ok()
529        .insert_header((header::CONTENT_TYPE, "text/event-stream"))
530        .insert_header((header::CACHE_CONTROL, "no-cache"))
531        .insert_header(("X-Accel-Buffering", "no"))
532        .streaming(futures_util::stream::unfold(
533            receiver,
534            |mut receiver| async move {
535                receiver
536                    .recv()
537                    .await
538                    .map(|bytes| (Ok::<Bytes, actix_web::Error>(bytes), receiver))
539            },
540        ))
541}
542
543async fn send_sse_event(
544    sender: &mpsc::Sender<Bytes>,
545    event: agent_service::RunEvent,
546) -> Option<(u64, bool)> {
547    let response = RunEventResponse::from(event);
548    let sequence = response.sequence;
549    let terminal = matches!(
550        response.kind,
551        "completed" | "failed" | "cancelled" | "timed_out" | "max_iterations_reached"
552    );
553    let payload = serde_json::to_string(&response).ok()?;
554    let frame = format!("id: {sequence}\ndata: {payload}\n\n");
555    sender.send(Bytes::from(frame)).await.ok()?;
556    Some((sequence, terminal))
557}
558
559#[post("/{run_id}/cancel")]
560async fn cancel_run(
561    request: HttpRequest,
562    auth: Option<Data<crate::auth::TelegramAuth>>,
563    store: Option<Data<Arc<SqliteConversationStore>>>,
564    manager: Data<RunManager>,
565    run_id: Path<String>,
566) -> impl Responder {
567    let run_id = match RunId::from_str(&run_id) {
568        Ok(run_id) => run_id,
569        Err(_) => return HttpResponse::BadRequest().body("invalid run identifier"),
570    };
571
572    let Some(run) = manager.get(run_id).await else {
573        return HttpResponse::NotFound().finish();
574    };
575    if !owns_run(
576        &run,
577        &request,
578        auth.as_deref().map(|v| &**v),
579        store.as_ref().map(|store| store.get_ref().as_ref()),
580    ) {
581        return HttpResponse::NotFound().finish();
582    }
583    match manager.cancel(run_id).await {
584        Ok(outcome) => {
585            let run = manager
586                .get(run_id)
587                .await
588                .expect("cancelled run remains available");
589            let response = CancelRunResponse {
590                run_id: run.id.to_string(),
591                status: status_name(run.status),
592            };
593
594            match outcome {
595                CancelRunOutcome::Requested | CancelRunOutcome::CancelledBeforeStart => {
596                    HttpResponse::Accepted().json(response)
597                }
598                CancelRunOutcome::AlreadyRequested | CancelRunOutcome::AlreadyFinished => {
599                    HttpResponse::Ok().json(response)
600                }
601            }
602        }
603        Err(CancelRunError::NotFound) => HttpResponse::NotFound().finish(),
604        Err(CancelRunError::Storage(error)) => {
605            tracing::error!(%run_id, %error, "failed to persist run cancellation");
606            HttpResponse::InternalServerError().body("could not cancel run")
607        }
608    }
609}
610
611/// Builds the /runs route scope. Register RunManager as application data
612/// before mounting this scope.
613pub fn runs_api() -> Scope {
614    web::scope("/runs")
615        .service(list_runs)
616        .service(get_usage)
617        .service(list_pricing)
618        .service(create_pricing)
619        .service(get_run_usage)
620        .service(submit_run)
621        .service(get_run)
622        .service(get_run_events)
623        .service(stream_run_events)
624        .service(cancel_run)
625}