use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Weak};
use aidaemon_events::conversation::MessageAttachment;
use aidaemon_tools::semantics::{ApprovalResponse, PermissionMode, RiskLevel, UserRole};
use aidaemon_tools::status::StatusUpdate;
use async_trait::async_trait;
use tokio::sync::mpsc;
use crate::context::ChannelContext;
use crate::hub::MediaMessage;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InboundMessageTiming {
pub platform_message_at: Option<chrono::DateTime<chrono::Utc>>,
pub transport_received_at: chrono::DateTime<chrono::Utc>,
pub queue_entered_at: Option<chrono::DateTime<chrono::Utc>>,
pub agent_dispatched_at: chrono::DateTime<chrono::Utc>,
}
impl InboundMessageTiming {
pub fn new(
platform_message_at: Option<chrono::DateTime<chrono::Utc>>,
transport_received_at: chrono::DateTime<chrono::Utc>,
) -> Self {
Self {
platform_message_at,
transport_received_at,
queue_entered_at: None,
agent_dispatched_at: transport_received_at,
}
}
pub fn mark_queued(&mut self, at: chrono::DateTime<chrono::Utc>) {
self.queue_entered_at = Some(at);
}
pub fn mark_dispatched_now(&mut self) {
self.agent_dispatched_at = chrono::Utc::now();
}
}
pub struct InboundMessageRequest {
pub session_id: String,
pub user_text: String,
pub attachments: Vec<MessageAttachment>,
pub status_tx: Option<mpsc::Sender<StatusUpdate>>,
pub user_role: UserRole,
pub channel_ctx: ChannelContext,
pub heartbeat: Option<Arc<AtomicU64>>,
pub ingress_timing: Option<InboundMessageTiming>,
}
#[derive(Debug, Clone)]
pub struct AgentResponseEnvelope {
pub response_id: String,
pub task_id: String,
pub turn_id: Option<String>,
pub text: String,
pub referenced_receipts: Vec<aidaemon_events::CompletionProofReference>,
pub disposition: aidaemon_events::AssistantResponseDisposition,
pub model: Option<String>,
}
impl AgentResponseEnvelope {
pub fn delivery(
&self,
platform: &str,
state: aidaemon_events::ResponseDeliveryState,
platform_message_ids: Vec<String>,
error_code: Option<String>,
) -> aidaemon_events::ResponseDeliveryData {
debug_assert!(
self.referenced_receipts
.iter()
.all(|reference| !reference.receipt_id.trim().is_empty())
);
aidaemon_events::ResponseDeliveryData {
response_id: self.response_id.clone(),
task_id: self.task_id.clone(),
turn_id: self.turn_id.clone(),
platform: platform.to_string(),
state,
platform_message_ids,
error_code,
occurred_at: chrono::Utc::now().to_rfc3339(),
}
}
}
#[async_trait]
pub trait AgentIngress: Send + Sync {
async fn handle_inbound_message(
&self,
request: InboundMessageRequest,
) -> anyhow::Result<AgentResponseEnvelope>;
async fn record_response_delivery(
&self,
_session_id: &str,
_delivery: aidaemon_events::ResponseDeliveryData,
) -> anyhow::Result<()> {
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MidRunIntent {
AboutRunningWork,
ChangesWork,
Unrelated,
StopsWork,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatRun {
pub id: String,
pub view: aidaemon_core::card::HelperView,
pub running_for: std::time::Duration,
pub started_at: chrono::DateTime<chrono::Utc>,
pub ended_at: Option<chrono::DateTime<chrono::Utc>>,
pub activity: Option<String>,
pub activity_kind: Option<aidaemon_core::card::AgentStepKind>,
pub agent: Option<String>,
pub agent_mark: Option<String>,
pub group: Option<String>,
pub edited: Vec<String>,
pub continues: Option<String>,
pub thread: Option<String>,
pub keeps_session: bool,
pub accepts_mid_run: bool,
pub queued: bool,
pub result: Option<crate::turns::RunResult>,
pub asked: Option<crate::turns::RunAsk>,
pub this_request: bool,
pub team: Option<crate::turns::RunTeam>,
pub seen_checks: Vec<crate::turns::SeenCheck>,
pub tokens: Option<u64>,
pub wrote: Vec<String>,
pub pulse: crate::turns::RunPulse,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ChatRuns {
pub runs: Vec<ChatRun>,
pub plan: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunningWork {
pub request: String,
pub elapsed: std::time::Duration,
pub last_step: Option<(String, std::time::Duration)>,
pub plan: Option<String>,
pub runs: Vec<ChatRun>,
pub running: Vec<RunningItem>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningItem {
pub number: u64,
pub title: String,
pub elapsed: std::time::Duration,
pub work: Option<ChatWorkKind>,
pub run: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MidRunReading {
pub intent: MidRunIntent,
pub stop: Vec<u64>,
pub also_asks: bool,
}
impl MidRunReading {
pub fn new(intent: MidRunIntent) -> Self {
Self {
intent,
stop: Vec::new(),
also_asks: false,
}
}
pub fn stops(stop: Vec<u64>, also_asks: bool) -> Self {
Self {
intent: MidRunIntent::StopsWork,
stop,
also_asks,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningChild {
pub label: String,
pub started_at: chrono::DateTime<chrono::Utc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatWorkKind {
SubAgent,
BackgroundJob,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatWork {
pub key: String,
pub kind: ChatWorkKind,
pub title: String,
pub started_at: chrono::DateTime<chrono::Utc>,
pub request: Option<String>,
pub step: Option<aidaemon_core::card::Step>,
pub run: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ChatWorkView {
pub current_request: Option<String>,
pub items: Vec<ChatWork>,
}
pub const NO_MODEL_LINE: &str = "No model is connected. Connect one in the AIDaemon app.";
#[async_trait]
pub trait ChannelAgentRuntime: AgentIngress {
async fn needs_missing_model(&self, _session_id: &str) -> bool {
false
}
async fn read_mid_run_message(
&self,
_session_id: &str,
_text: &str,
_work: &RunningWork,
) -> Option<MidRunReading> {
None
}
async fn record_control_exchange(
&self,
_session_id: &str,
_owner_text: &str,
_user_role: aidaemon_tools::semantics::UserRole,
_channel_ctx: &ChannelContext,
_reply: &str,
) {
}
async fn running_children(&self, _session_id: &str) -> Vec<RunningChild> {
Vec::new()
}
async fn chat_runs(&self, _session_id: &str) -> ChatRuns {
ChatRuns::default()
}
async fn chat_work(&self, _session_id: &str) -> ChatWorkView {
ChatWorkView::default()
}
async fn stop_chat_work(&self, _session_id: &str, _key: &str) -> bool {
false
}
async fn cancel_finite_goals_for_session(&self, session_id: &str) -> Vec<String> {
self.cancel_active_finite_work_for_session(session_id).await
}
async fn terminalize_supervised_task(
&self,
session_id: &str,
status: aidaemon_events::TaskStatus,
error: String,
) -> anyhow::Result<Option<String>>;
async fn cancel_active_finite_work_for_session(&self, session_id: &str) -> Vec<String>;
async fn current_model(&self) -> String;
async fn context_debug_settings(
&self,
session_id: &str,
model: &str,
) -> (bool, usize, usize, usize, Option<i64>);
async fn set_model(&self, model: String);
async fn list_models(&self) -> anyhow::Result<Vec<String>>;
async fn clear_model_override(&self);
async fn clear_session_context(&self, session_id: &str) -> anyhow::Result<()>;
async fn clear_session(&self, session_id: &str) -> anyhow::Result<()>;
}
#[async_trait]
pub trait AssistantNoteSink: Send + Sync {
async fn record_assistant_note(&self, session_id: &str, note: &str) -> anyhow::Result<()>;
async fn record_delivered_files(
&self,
session_id: &str,
note: &str,
_caption: &str,
_files: Vec<aidaemon_tools::semantics::MessageAttachment>,
) -> anyhow::Result<()> {
self.record_assistant_note(session_id, note).await
}
}
#[async_trait]
pub trait OutboundRouter: Send + Sync {
async fn send_text(&self, session_id: &str, text: &str) -> anyhow::Result<()>;
async fn send_text_tracked(
&self,
session_id: &str,
text: &str,
) -> anyhow::Result<Option<String>>;
async fn edit_text(
&self,
session_id: &str,
message_id: &str,
text: &str,
) -> anyhow::Result<bool>;
async fn send_media(&self, session_id: &str, media: &MediaMessage) -> anyhow::Result<()>;
async fn send_media_strict(&self, session_id: &str, media: &MediaMessage)
-> anyhow::Result<()>;
async fn delete_message(&self, _session_id: &str, _message_id: &str) -> anyhow::Result<bool> {
Ok(false)
}
async fn shows_runs(&self, _session_id: &str) -> bool {
false
}
async fn checklist_surface(&self, _session_id: &str) -> Option<String> {
None
}
async fn checklist_surface_after(
&self,
session_id: &str,
after: Option<&str>,
) -> Option<String> {
let now = self.checklist_surface(session_id).await;
if now.as_deref() == after { None } else { now }
}
async fn register_checklist_surface(&self, _session_id: &str, _message_id: &str) {}
async fn request_inline_approval(
&self,
session_id: &str,
description: &str,
risk_level: RiskLevel,
warnings: &[String],
permission_mode: PermissionMode,
) -> anyhow::Result<ApprovalResponse>;
async fn register_session_route(&self, child_session: &str, parent_session: &str) -> bool;
async fn unregister_session_route(&self, child_session: &str, parent_session: &str);
}
pub struct SessionRouteLease {
router: Weak<dyn OutboundRouter>,
child_session: String,
parent_session: String,
}
impl SessionRouteLease {
pub async fn register(
router: &Arc<dyn OutboundRouter>,
child_session: &str,
parent_session: &str,
) -> Option<Self> {
if !router
.register_session_route(child_session, parent_session)
.await
{
return None;
}
Some(Self {
router: Arc::downgrade(router),
child_session: child_session.to_string(),
parent_session: parent_session.to_string(),
})
}
}
impl Drop for SessionRouteLease {
fn drop(&mut self) {
let Some(router) = self.router.upgrade() else {
return;
};
let child_session = self.child_session.clone();
let parent_session = self.parent_session.clone();
if let Ok(runtime) = tokio::runtime::Handle::try_current() {
runtime.spawn(async move {
router
.unregister_session_route(&child_session, &parent_session)
.await;
});
}
}
}