aidaemon-channels 0.29.0

Chat channel contract and the runner that connects channels to aidaemon agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! The ports between chat channels and the agent runtime: what a turn
//! hands the agent ([`InboundMessageRequest`]), what comes back
//! ([`AgentResponseEnvelope`]), the agent administration channel commands use
//! ([`ChannelAgentRuntime`]), and the outbound router the agent and tools
//! reach the chat through ([`OutboundRouter`]). Internal to aidaemon, no
//! stability promise; the public contract is [`crate::channel`].

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;

/// Owned inbound turn delivered by a chat transport.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct InboundMessageTiming {
    /// Timestamp assigned by the source platform, when available.
    pub platform_message_at: Option<chrono::DateTime<chrono::Utc>>,
    /// First instant the daemon transport handler observed the message.
    pub transport_received_at: chrono::DateTime<chrono::Utc>,
    /// Instant the message entered a per-session queue, if it waited.
    pub queue_entered_at: Option<chrono::DateTime<chrono::Utc>>,
    /// Instant the transport handed the turn to the agent runtime.
    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,
    /// The model that wrote the reply, as the runtime recorded it.
    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(),
        }
    }
}

/// The only agent capability chat transports need.
#[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(())
    }
}

/// What a message sent while a run is going is about, as the model read it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MidRunIntent {
    /// A question about the running work: how it is going, what it found,
    /// whether a result is ready. Answered now from the work's typed live
    /// state (never in the model's words); the run goes on undisturbed.
    AboutRunningWork,
    /// It changes or adds to the running work: the run takes it in.
    ChangesWork,
    /// Something else: it runs as its own turn once the current one ends.
    Unrelated,
    /// It asks to stop running work: the items [`MidRunReading::stop`]
    /// names, or, when it names none, what bare `/cancel` would stop.
    StopsWork,
}

/// One helper run of a chat, as the runtime's record of it shows it: the
/// same view every card draws, keyed by the run's id (two attempts with the
/// same label are two runs).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatRun {
    /// The run's id: the key every surface finds it by.
    pub id: String,
    pub view: aidaemon_core::card::HelperView,
    /// How long it has run (to now, or to its end once it ended).
    pub running_for: std::time::Duration,
    pub started_at: chrono::DateTime<chrono::Utc>,
    pub ended_at: Option<chrono::DateTime<chrono::Utc>>,
    /// What a coding agent it launched last said it was doing, in plain
    /// words; `None` for any other run.
    pub activity: Option<String>,
    /// What kind of step [`Self::activity`] is (a wait while it waits):
    /// what a client draws the run's mark by.
    pub activity_kind: Option<aidaemon_core::card::AgentStepKind>,
    /// The coding agent it is ("Claude Code"), when it launched one.
    pub agent: Option<String>,
    /// That agent's mark (its maker's provider id, or its own), when it
    /// has one: what a client draws its logo by.
    pub agent_mark: Option<String>,
    /// The chat turn (its task id) that started it: runs one request
    /// started share it.
    pub group: Option<String>,
    /// The files the coding agent it launched changed.
    pub edited: Vec<String>,
    /// The earlier run it continues: the same coding agent's session,
    /// resumed with the owner's follow-up.
    pub continues: Option<String>,
    /// The first run of its thread: the agent session it is part of (one
    /// participant of the conversation). `None`: it starts its own.
    pub thread: Option<String>,
    /// Its coding agent keeps its session where a follow-up can continue it.
    pub keeps_session: bool,
    /// While running, its live host accepts mid-run notes directly.
    pub accepts_mid_run: bool,
    /// Running but not started yet: it waits its turn behind another run,
    /// for its folder or for a free slot.
    pub queued: bool,
    /// What its coding agent ended with, once it ended ([`crate::turns::RunResult`]).
    pub result: Option<crate::turns::RunResult>,
    /// What it was asked, and by whom.
    pub asked: Option<crate::turns::RunAsk>,
    /// The chat's running turn started it (an earlier turn's helper runs on
    /// in the background).
    pub this_request: bool,
    /// The team of coding agents it is a member of.
    pub team: Option<crate::turns::RunTeam>,
    /// The builds and tests it ran, as seen.
    pub seen_checks: Vec<crate::turns::SeenCheck>,
    /// Tokens its coding agent used so far.
    pub tokens: Option<u64>,
    /// The files it wrote.
    pub wrote: Vec<String>,
    /// How its coding agent's work stands beyond its latest step.
    pub pulse: crate::turns::RunPulse,
}

/// A chat's helper runs and its plan card, from the runtime's records.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ChatRuns {
    /// Oldest first.
    pub runs: Vec<ChatRun>,
    /// The running turn's plan card, as the chat shows it.
    pub plan: Option<String>,
}

/// The running work as its typed live state shows it, for answering a
/// question about it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RunningWork {
    /// The request the run is working on.
    pub request: String,
    /// How long it has been running.
    pub elapsed: std::time::Duration,
    /// Its latest step and how long ago it started.
    pub last_step: Option<(String, std::time::Duration)>,
    /// Its plan card (checklist), as shown in chat.
    pub plan: Option<String>,
    /// The chat's helper runs, from their records.
    pub runs: Vec<ChatRun>,
    /// Everything running for the chat, numbered as `/tasks` shows it.
    pub running: Vec<RunningItem>,
}

/// One thing running for a chat, as `/tasks` numbers it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningItem {
    pub number: u64,
    pub title: String,
    pub elapsed: std::time::Duration,
    /// What it is: `None` for a chat turn.
    pub work: Option<ChatWorkKind>,
    /// The helper run it is, when it is one ([`ChatRun::id`]).
    pub run: Option<String>,
}

/// How a message sent mid-run is handled. Built with [`MidRunReading::new`]
/// or [`MidRunReading::stops`], so a field added later is not a breaking
/// change.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct MidRunReading {
    pub intent: MidRunIntent,
    /// For [`MidRunIntent::StopsWork`]: the numbers of the
    /// [`RunningWork::running`] items to stop; empty for what bare `/cancel`
    /// stops.
    pub stop: Vec<u64>,
    /// For [`MidRunIntent::StopsWork`]: the message also asks for something
    /// besides stopping ("stop it and delete the project"), which then runs
    /// as its own turn once the work is stopped.
    pub also_asks: bool,
}

impl MidRunReading {
    /// A reading of `intent` that stops nothing.
    pub fn new(intent: MidRunIntent) -> Self {
        Self {
            intent,
            stop: Vec::new(),
            also_asks: false,
        }
    }

    /// A [`MidRunIntent::StopsWork`] reading: the `stop` items to stop
    /// (empty for what bare `/cancel` stops) and whether the message
    /// `also_asks` for something besides stopping.
    pub fn stops(stop: Vec<u64>, also_asks: bool) -> Self {
        Self {
            intent: MidRunIntent::StopsWork,
            stop,
            also_asks,
        }
    }
}

/// A sub-agent running for a chat, as `/status` and `/tasks` list it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunningChild {
    /// The title its parent gave it (the spawn's mission, first line).
    pub label: String,
    pub started_at: chrono::DateTime<chrono::Utc>,
}

/// What kind of work runs for a chat besides its turns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatWorkKind {
    SubAgent,
    BackgroundJob,
}

/// One piece of work running for a chat outside its turn: a sub-agent or a
/// background command, read from the agent's typed state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatWork {
    /// The agent's handle for it, stable while it runs; never shown.
    pub key: String,
    pub kind: ChatWorkKind,
    /// What it is, in plain words.
    pub title: String,
    pub started_at: chrono::DateTime<chrono::Utc>,
    /// The request (turn) that started it, when known; opaque.
    pub request: Option<String>,
    /// Its latest step, from its record (a sub-agent's).
    pub step: Option<aidaemon_core::card::Step>,
    /// The helper run it is, when it is one ([`ChatRun::id`]).
    pub run: Option<String>,
}

/// Everything running for a chat besides its turns.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ChatWorkView {
    /// The request the chat's running turn is working on, if one runs.
    pub current_request: Option<String>,
    pub items: Vec<ChatWork>,
}

/// What a chat channel answers, with no turn, when its conversation needs
/// AIDaemon's model and none is connected.
pub const NO_MODEL_LINE: &str = "No model is connected. Connect one in the AIDaemon app.";

/// Agent administration surface used by shared channel commands.
#[async_trait]
pub trait ChannelAgentRuntime: AgentIngress {
    /// Whether a message in `session_id` would need a model and none is
    /// connected: the channel then answers [`NO_MODEL_LINE`] itself and
    /// starts no turn. Default: false.
    async fn needs_missing_model(&self, _session_id: &str) -> bool {
        false
    }

    /// Read a message the owner sent while `work` runs in `session_id`.
    /// `None` (the default, or when the reading failed) hands it to the
    /// running work, as a steering message.
    async fn read_mid_run_message(
        &self,
        _session_id: &str,
        _text: &str,
        _work: &RunningWork,
    ) -> Option<MidRunReading> {
        None
    }

    /// Keep an exchange the channel answered itself (a stop, a status
    /// question) in the conversation: the owner's message and the reply,
    /// as one turn, so the chat shows what they sent and later turns can
    /// refer to it. Default: nothing kept.
    async fn record_control_exchange(
        &self,
        _session_id: &str,
        _owner_text: &str,
        _user_role: aidaemon_tools::semantics::UserRole,
        _channel_ctx: &ChannelContext,
        _reply: &str,
    ) {
    }

    /// The sub-agents running now for `session_id` (waited on by a turn or
    /// in the background), oldest first.
    async fn running_children(&self, _session_id: &str) -> Vec<RunningChild> {
        Vec::new()
    }

    /// The chat's helper runs and its running turn's plan card, from the
    /// runtime's run records and plan store: what every card draws, so a
    /// status reply agrees with the card.
    async fn chat_runs(&self, _session_id: &str) -> ChatRuns {
        ChatRuns::default()
    }

    /// Everything running for `session_id` besides its turns: sub-agents
    /// and background commands.
    async fn chat_work(&self, _session_id: &str) -> ChatWorkView {
        ChatWorkView::default()
    }

    /// Stop the chat's work `key` (from [`Self::chat_work`]) and read its
    /// state back: `true` only once it is verified gone.
    async fn stop_chat_work(&self, _session_id: &str, _key: &str) -> bool {
        false
    }

    /// Cancel the chat's finite goals (task leads and their executors);
    /// returns what was cancelled. Its sub-agents and background commands are
    /// stopped through [`Self::stop_chat_work`].
    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<()>;
}

/// Persistence hook used by outbound delivery without depending on `Agent`.
#[async_trait]
pub trait AssistantNoteSink: Send + Sync {
    async fn record_assistant_note(&self, session_id: &str, note: &str) -> anyhow::Result<()>;

    /// Files delivered to the owner: `note` is for the model, `caption` what
    /// the owner saw with `files`, which the transcript keeps.
    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
    }
}

/// Outbound operations shared by the agent runtime, tools, and heartbeat.
#[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<()>;
    /// Delete a message this daemon sent. `Ok(false)` when the channel
    /// cannot delete it; the default suits routers that never can.
    async fn delete_message(&self, _session_id: &str, _message_id: &str) -> anyhow::Result<bool> {
        Ok(false)
    }
    /// The session's chat shows each background run as its own row
    /// ([`crate::hub::HubChannel::shows_runs`]).
    async fn shows_runs(&self, _session_id: &str) -> bool {
        false
    }
    /// The plan card a turn left in the session's chat, if the channel keeps
    /// one; the default suits routers without plan cards.
    async fn checklist_surface(&self, _session_id: &str) -> Option<String> {
        None
    }
    /// The first card the session's chat kept after card `after` (`None`:
    /// after none), when the channel can tell; a background run's line is
    /// drawn on the card its starting turn kept, never a later turn's. The
    /// default suits routers without a card history: the current card, when
    /// it is a different one.
    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 }
    }
    /// Record a plan card sent outside a turn (see [`Self::checklist_surface`]).
    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);
}

/// Cancellation-safe route lifetime that is independent of the concrete hub.
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;
            });
        }
    }
}