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
//! How long a turn has waited on its owner. A turn's hang limits leave
//! that time out: waiting on a person is not the turn working. Internal to
//! aidaemon, no stability promise.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use tokio::time::Instant;

tokio::task_local! {
    static TURN_OWNER_WAIT: OwnerWaitClock;
}

/// How long a turn has spent waiting for its owner to answer a card. Waiting
/// on a person is not the turn working, so the turn's hang limit leaves it out.
#[derive(Clone, Default)]
pub struct OwnerWaitClock(Arc<Mutex<OwnerWaitState>>, Option<Box<OwnerWaitClock>>);

#[derive(Default)]
struct OwnerWaitState {
    /// Cards open now (a turn's child agents can ask at the same time).
    open: usize,
    /// When the open cards began; overlapping cards count once.
    since: Option<Instant>,
    /// Waits already finished.
    waited: Duration,
    /// When the first step (a tool call) began.
    first_step: Option<chrono::DateTime<chrono::Utc>>,
    /// When the last step to finish ended.
    last_step_end: Option<chrono::DateTime<chrono::Utc>>,
}

/// Marks one step (a tool call) as running until dropped, on this clock
/// and the clocks it is nested in.
pub struct StepRunning {
    clock: OwnerWaitClock,
    _parent: Option<Box<StepRunning>>,
}

/// Ends one card's wait when dropped, however the wait ends.
pub struct OwnerWaiting {
    clock: OwnerWaitClock,
    /// The same wait on the enclosing clock, ended with this one.
    _parent: Option<Box<OwnerWaiting>>,
}

impl OwnerWaitClock {
    /// Total time spent waiting so far, including a wait still open.
    pub fn waited(&self) -> Duration {
        let state = self.0.lock().unwrap_or_else(|e| e.into_inner());
        state.waited + state.since.map_or(Duration::ZERO, |since| since.elapsed())
    }

    /// The clock of the turn running this task, if any (scheduled work has
    /// none, and no turn limit to exempt).
    pub fn current() -> Option<Self> {
        TURN_OWNER_WAIT.try_with(Clone::clone).ok()
    }

    /// Run `future` with `clock` as its turn's clock. Task locals are not
    /// inherited by spawned tasks, so a child agent's task re-enters it here.
    pub async fn within<F: std::future::Future>(clock: Option<Self>, future: F) -> F::Output {
        match clock {
            Some(clock) => TURN_OWNER_WAIT.scope(clock, future).await,
            None => future.await,
        }
    }

    /// A clock of its own for one part of the turn (a sub-agent): its waits
    /// are measured apart from its siblings', and count on this clock too.
    pub fn nested(&self) -> Self {
        Self(Arc::default(), Some(Box::new(self.clone())))
    }

    /// When this part of the turn's steps ran: the start of its first tool
    /// call and the end of its last finished one. `None` before any step
    /// ended. A helper's own work, apart from its start-up and its report.
    pub fn steps(&self) -> Option<(chrono::DateTime<chrono::Utc>, chrono::DateTime<chrono::Utc>)> {
        let state = self.0.lock().unwrap_or_else(|e| e.into_inner());
        Some((state.first_step?, state.last_step_end?))
    }

    /// Mark a step (a tool call) as running in the current turn.
    pub fn begin_step() -> Option<StepRunning> {
        Some(Self::current()?.step())
    }

    fn step(&self) -> StepRunning {
        {
            let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
            state.first_step.get_or_insert_with(chrono::Utc::now);
        }
        StepRunning {
            clock: self.clone(),
            _parent: self.1.as_ref().map(|parent| Box::new(parent.step())),
        }
    }

    /// Mark a card as waiting on the owner in the current turn.
    pub fn begin_waiting() -> Option<OwnerWaiting> {
        Some(Self::current()?.open_wait())
    }

    fn open_wait(&self) -> OwnerWaiting {
        {
            let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
            state.open += 1;
            if state.open == 1 {
                state.since = Some(Instant::now());
            }
        }
        OwnerWaiting {
            clock: self.clone(),
            _parent: self.1.as_ref().map(|parent| Box::new(parent.open_wait())),
        }
    }
}

/// A limit on working time: time spent waiting for the owner does not count.
#[derive(Clone)]
pub struct WorkDeadline {
    started: tokio::time::Instant,
    limit: std::time::Duration,
    owner_wait: OwnerWaitClock,
    /// The clock's total when this deadline started: waits before then do
    /// not extend it.
    waited_at_start: std::time::Duration,
}

impl WorkDeadline {
    pub fn starting_now(limit: std::time::Duration, owner_wait: OwnerWaitClock) -> Self {
        Self {
            started: tokio::time::Instant::now(),
            limit,
            waited_at_start: owner_wait.waited(),
            owner_wait,
        }
    }

    pub fn limit(&self) -> std::time::Duration {
        self.limit
    }

    /// Working time left: time since the start, less the owner waits since
    /// the start.
    pub fn remaining(&self) -> std::time::Duration {
        let waited_since_start = self
            .owner_wait
            .waited()
            .saturating_sub(self.waited_at_start);
        let worked = self.started.elapsed().saturating_sub(waited_since_start);
        self.limit.saturating_sub(worked)
    }

    /// Resolves once the limit has been worked, checking every `check`.
    pub async fn reached(&self, check: std::time::Duration) {
        loop {
            let left = self.remaining();
            if left.is_zero() {
                return;
            }
            tokio::time::sleep(left.min(check)).await;
        }
    }
}

/// When a run last made progress: the end of a model or tool call, or any
/// event of its own. A call in flight is progress being made (each call has
/// its own bound: the model call timeout, a tool's timeout or stall
/// watchdog), and time spent waiting for the owner never counts as idle. A
/// child agent is stopped only after it has been idle for its limit, never
/// for how long it has been running: long legitimate work (an install that
/// takes minutes) keeps making calls.
#[derive(Clone)]
pub struct ProgressClock(Arc<Mutex<ProgressState>>, OwnerWaitClock);

struct ProgressState {
    /// The last progress: a call began or ended, or the run sent an event.
    last: Instant,
    /// The owner clock's total at `last`: waits after it are not idle.
    waited_at_last: Duration,
    /// Calls running now.
    in_flight: usize,
}

/// Marks one call as running until dropped, however the call ends.
pub struct InFlight(ProgressClock);

impl ProgressClock {
    pub fn starting_now(owner_wait: OwnerWaitClock) -> Self {
        Self(
            Arc::new(Mutex::new(ProgressState {
                last: Instant::now(),
                waited_at_last: owner_wait.waited(),
                in_flight: 0,
            })),
            owner_wait,
        )
    }

    /// Record progress now.
    pub fn touch(&self) {
        let waited = self.1.waited();
        let mut state = self.0.lock().unwrap_or_else(|e| e.into_inner());
        state.last = Instant::now();
        state.waited_at_last = waited;
    }

    /// A call begins; it is progress until the returned guard drops.
    pub fn begin(&self) -> InFlight {
        self.touch();
        self.0.lock().unwrap_or_else(|e| e.into_inner()).in_flight += 1;
        InFlight(self.clone())
    }

    /// How long the run has made no progress: zero while a call runs, else
    /// the time since the last progress less the owner waits since then.
    pub fn idle(&self) -> Duration {
        let waited = self.1.waited();
        let state = self.0.lock().unwrap_or_else(|e| e.into_inner());
        if state.in_flight > 0 {
            return Duration::ZERO;
        }
        state
            .last
            .elapsed()
            .saturating_sub(waited.saturating_sub(state.waited_at_last))
    }

    /// Resolves once the run has been idle for `limit`, checking every
    /// `check`.
    pub async fn idle_for(&self, limit: Duration, check: Duration) {
        loop {
            let idle = self.idle();
            if idle >= limit {
                return;
            }
            tokio::time::sleep((limit - idle).min(check)).await;
        }
    }
}

impl Drop for InFlight {
    fn drop(&mut self) {
        {
            let mut state = self.0.0.lock().unwrap_or_else(|e| e.into_inner());
            state.in_flight = state.in_flight.saturating_sub(1);
        }
        self.0.touch();
    }
}

impl Drop for StepRunning {
    fn drop(&mut self) {
        let now = chrono::Utc::now();
        let mut state = self.clock.0.lock().unwrap_or_else(|e| e.into_inner());
        if state.last_step_end.is_none_or(|end| end < now) {
            state.last_step_end = Some(now);
        }
    }
}

impl Drop for OwnerWaiting {
    fn drop(&mut self) {
        let mut state = self.clock.0.lock().unwrap_or_else(|e| e.into_inner());
        state.open = state.open.saturating_sub(1);
        if state.open == 0
            && let Some(since) = state.since.take()
        {
            state.waited += since.elapsed();
        }
    }
}

#[cfg(test)]
mod progress_tests {
    use super::*;

    const STEP: Duration = Duration::from_millis(60);

    #[tokio::test]
    async fn a_call_in_flight_is_never_idle_and_its_end_restarts_the_clock() {
        let clock = ProgressClock::starting_now(OwnerWaitClock::default());
        tokio::time::sleep(STEP).await;
        assert!(clock.idle() >= STEP);
        let call = clock.begin();
        tokio::time::sleep(STEP * 3).await;
        assert_eq!(clock.idle(), Duration::ZERO, "a long call is progress");
        drop(call);
        assert!(clock.idle() < STEP);
        tokio::time::sleep(STEP).await;
        assert!(clock.idle() >= STEP);
        clock.touch();
        assert!(clock.idle() < STEP);
    }

    /// A sub-agent's own clock measures only its waits, and they still
    /// count for the turn it belongs to.
    #[tokio::test]
    async fn a_nested_clock_measures_its_own_waits_and_counts_for_the_turn() {
        let turn = OwnerWaitClock::default();
        let helper = turn.nested();
        let sibling = turn.nested();
        OwnerWaitClock::within(Some(helper.clone()), async {
            let card = OwnerWaitClock::begin_waiting();
            tokio::time::sleep(STEP * 2).await;
            drop(card);
        })
        .await;
        assert!(helper.waited() >= STEP * 2, "{:?}", helper.waited());
        assert!(turn.waited() >= STEP * 2, "{:?}", turn.waited());
        assert_eq!(sibling.waited(), Duration::ZERO);
    }

    /// A helper's steps are timed on its own clock: from its first tool
    /// call's start to its last one's end, apart from its start-up and its
    /// report, and they count on the turn's clock too.
    #[tokio::test]
    async fn a_nested_clock_times_its_own_steps() {
        let turn = OwnerWaitClock::default();
        let helper = turn.nested();
        assert!(helper.steps().is_none());
        let before = chrono::Utc::now();
        OwnerWaitClock::within(Some(helper.clone()), async {
            tokio::time::sleep(STEP).await; // start-up: not a step
            let first = OwnerWaitClock::begin_step();
            tokio::time::sleep(STEP).await;
            drop(first);
            let second = OwnerWaitClock::begin_step();
            tokio::time::sleep(STEP).await;
            drop(second);
            tokio::time::sleep(STEP).await; // the report: not a step
        })
        .await;
        let (first, last) = helper.steps().expect("timed steps");
        let ran = (last - first).to_std().unwrap();
        assert!(ran >= STEP * 2 && ran < STEP * 4, "{ran:?}");
        assert!(first - before >= chrono::Duration::from_std(STEP).unwrap());
        assert!(turn.steps().is_some());
    }

    #[tokio::test]
    async fn waiting_on_the_owner_is_not_idle() {
        let owner = OwnerWaitClock::default();
        let clock = ProgressClock::starting_now(owner.clone());
        OwnerWaitClock::within(Some(owner), async {
            let card = OwnerWaitClock::begin_waiting();
            tokio::time::sleep(STEP * 4).await;
            drop(card);
        })
        .await;
        assert!(clock.idle() < STEP * 2, "{:?}", clock.idle());
    }
}

/// Conversations with an approval card open now, by session id: while one
/// is, the running work cannot read anything new, so a message sent then
/// waits for the answer. The hub counts each card from when it is shown
/// until it is answered or dropped ([`ApprovalOpen`]).
fn open_approvals() -> &'static std::sync::Mutex<std::collections::HashMap<String, usize>> {
    static OPEN: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, usize>>> =
        std::sync::OnceLock::new();
    OPEN.get_or_init(Default::default)
}

/// One approval card open for a session, until dropped.
pub struct ApprovalOpen(String);

impl ApprovalOpen {
    pub fn begin(session_id: &str) -> Self {
        if let Ok(mut open) = open_approvals().lock() {
            *open.entry(session_id.to_owned()).or_default() += 1;
        }
        Self(session_id.to_owned())
    }
}

impl Drop for ApprovalOpen {
    fn drop(&mut self) {
        if let Ok(mut open) = open_approvals().lock()
            && let Some(n) = open.get_mut(&self.0)
        {
            *n = n.saturating_sub(1);
            if *n == 0 {
                open.remove(&self.0);
            }
        }
    }
}

/// Whether `session_id` has an approval card waiting for the owner.
pub fn approval_open(session_id: &str) -> bool {
    open_approvals()
        .lock()
        .is_ok_and(|open| open.get(session_id).is_some_and(|n| *n > 0))
}

#[cfg(test)]
mod approval_open_tests {
    use super::{ApprovalOpen, approval_open};

    #[test]
    fn a_card_is_open_until_dropped() {
        let session = "telegram:synthetic-approval-open";
        assert!(!approval_open(session));
        let first = ApprovalOpen::begin(session);
        let second = ApprovalOpen::begin(session);
        drop(first);
        assert!(approval_open(session));
        drop(second);
        assert!(!approval_open(session));
    }
}