agentty 0.14.0

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
528
//! Foreground-owned session workflow actor and cloneable control handle.
//!
//! [`SessionRuntime`] owns the live [`SessionManager`] plus a bounded command
//! mailbox. The terminal runtime drives accepted commands on the foreground
//! task so reducer-owned render snapshots and session handles remain coherent,
//! while [`SessionRuntimeHandle`] gives background coordinators a cloneable
//! `Send + Sync` capability without sharing all of [`crate::app::App`] behind
//! a mutex.

use std::future::poll_fn;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::task::Poll;

use ag_session::{
    AnswerQuestionsRequest, CoordinatorMessageRequest, CreateSessionRequest, ReviewRequest,
    Session, SessionError, SessionId,
};
use tokio::sync::{mpsc, oneshot, watch};

use crate::app::SessionManager;

/// Maximum number of accepted API commands waiting for foreground execution.
const SESSION_RUNTIME_COMMAND_CAPACITY: usize = 32;
/// Stable error returned after the foreground session runtime has stopped.
const SESSION_RUNTIME_UNAVAILABLE: &str = "Session runtime is unavailable";

/// One command accepted by the session runtime actor.
pub(crate) enum SessionRuntimeCommand {
    /// Creates one session from an explicit API request.
    Create {
        request: CreateSessionRequest,
        response_tx: oneshot::Sender<Result<SessionId, SessionError>>,
    },
    /// Loads one complete session aggregate.
    Get {
        response_tx: oneshot::Sender<Result<Option<Session>, SessionError>>,
        session_id: SessionId,
    },
    /// Sends one user message.
    SendMessage {
        message: String,
        response_tx: oneshot::Sender<Result<(), SessionError>>,
        session_id: SessionId,
    },
    /// Submits one coordinator-owned turn directly on the session worker.
    SubmitCoordinatorMessage {
        request: CoordinatorMessageRequest,
        response_tx: oneshot::Sender<Result<(), SessionError>>,
        session_id: SessionId,
    },
    /// Answers one complete clarification-question set.
    AnswerQuestions {
        request: AnswerQuestionsRequest,
        response_tx: oneshot::Sender<Result<(), SessionError>>,
        session_id: SessionId,
    },
    /// Cancels one session.
    Cancel {
        response_tx: oneshot::Sender<Result<(), SessionError>>,
        session_id: SessionId,
    },
    /// Enqueues one session for merge.
    Merge {
        response_tx: oneshot::Sender<Result<(), SessionError>>,
        session_id: SessionId,
    },
    /// Publishes one session branch and creates or refreshes its review
    /// request.
    CreateReviewRequest {
        response_tx: oneshot::Sender<Result<ReviewRequest, SessionError>>,
        session_id: SessionId,
    },
}

/// Cloneable control capability for the foreground session runtime.
#[derive(Clone)]
pub(crate) struct SessionRuntimeHandle {
    command_tx: mpsc::Sender<SessionRuntimeCommand>,
    consumer_state: Arc<SessionRuntimeConsumerState>,
}

impl SessionRuntimeHandle {
    /// Creates one session through the runtime actor.
    pub(crate) async fn create_session(
        &self,
        request: CreateSessionRequest,
    ) -> Result<SessionId, SessionError> {
        self.request(|response_tx| SessionRuntimeCommand::Create {
            request,
            response_tx,
        })
        .await
    }

    /// Loads one complete session aggregate through the runtime actor.
    pub(crate) async fn get_session(
        &self,
        session_id: &SessionId,
    ) -> Result<Option<Session>, SessionError> {
        let session_id = session_id.clone();

        self.request(|response_tx| SessionRuntimeCommand::Get {
            response_tx,
            session_id,
        })
        .await
    }

    /// Sends one message through the runtime actor.
    pub(crate) async fn send_message(
        &self,
        session_id: &SessionId,
        message: String,
    ) -> Result<(), SessionError> {
        let session_id = session_id.clone();

        self.request(|response_tx| SessionRuntimeCommand::SendMessage {
            message,
            response_tx,
            session_id,
        })
        .await
    }

    /// Submits one coordinator-owned turn through the runtime actor.
    pub(crate) async fn submit_coordinator_message(
        &self,
        session_id: &SessionId,
        request: CoordinatorMessageRequest,
    ) -> Result<(), SessionError> {
        let session_id = session_id.clone();

        self.request(
            |response_tx| SessionRuntimeCommand::SubmitCoordinatorMessage {
                request,
                response_tx,
                session_id,
            },
        )
        .await
    }

    /// Answers one complete clarification-question set through the runtime
    /// actor.
    pub(crate) async fn answer_questions(
        &self,
        session_id: &SessionId,
        request: AnswerQuestionsRequest,
    ) -> Result<(), SessionError> {
        let session_id = session_id.clone();

        self.request(|response_tx| SessionRuntimeCommand::AnswerQuestions {
            request,
            response_tx,
            session_id,
        })
        .await
    }

    /// Cancels one session through the runtime actor.
    pub(crate) async fn cancel_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
        let session_id = session_id.clone();

        self.request(|response_tx| SessionRuntimeCommand::Cancel {
            response_tx,
            session_id,
        })
        .await
    }

    /// Enqueues one session for merge through the runtime actor.
    pub(crate) async fn merge_session(&self, session_id: &SessionId) -> Result<(), SessionError> {
        let session_id = session_id.clone();

        self.request(|response_tx| SessionRuntimeCommand::Merge {
            response_tx,
            session_id,
        })
        .await
    }

    /// Creates or refreshes one review request through the runtime actor.
    pub(crate) async fn create_review_request(
        &self,
        session_id: &SessionId,
    ) -> Result<ReviewRequest, SessionError> {
        let session_id = session_id.clone();

        self.request(|response_tx| SessionRuntimeCommand::CreateReviewRequest {
            response_tx,
            session_id,
        })
        .await
    }

    /// Enqueues one typed command and waits for its per-command response.
    async fn request<ResultValue>(
        &self,
        command: impl FnOnce(
            oneshot::Sender<Result<ResultValue, SessionError>>,
        ) -> SessionRuntimeCommand,
    ) -> Result<ResultValue, SessionError> {
        let mut consumer_rx = self.consumer_state.subscribe();
        let consumer_is_active = *consumer_rx.borrow_and_update();
        if !consumer_is_active {
            return Err(SessionError::Operation(
                SESSION_RUNTIME_UNAVAILABLE.to_string(),
            ));
        }

        let (response_tx, response_rx) = oneshot::channel();
        tokio::select! {
            biased;
            _ = consumer_rx.wait_for(|consumer_is_active| !*consumer_is_active) => {
                return Err(SessionError::Operation(
                    SESSION_RUNTIME_UNAVAILABLE.to_string(),
                ));
            }
            result = self.command_tx.send(command(response_tx)) => {
                result.map_err(|_| {
                    SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
                })?;
            }
        }

        tokio::select! {
            biased;
            result = response_rx => {
                result.map_err(|_| {
                    SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
                })?
            }
            _ = consumer_rx.wait_for(|consumer_is_active| !*consumer_is_active) => {
                Err(SessionError::Operation(
                    SESSION_RUNTIME_UNAVAILABLE.to_string(),
                ))
            }
        }
    }
}

/// Shared foreground-consumer lifecycle observed by runtime handles.
struct SessionRuntimeConsumerState {
    active_count: AtomicUsize,
    active_tx: watch::Sender<bool>,
}

impl SessionRuntimeConsumerState {
    /// Creates an inactive consumer lifecycle signal.
    fn new() -> Self {
        let (active_tx, _active_rx) = watch::channel(false);

        Self {
            active_count: AtomicUsize::new(0),
            active_tx,
        }
    }

    /// Registers one foreground consumer until the returned guard drops.
    fn enter(self: &Arc<Self>) -> SessionRuntimeConsumerGuard {
        if self.active_count.fetch_add(1, Ordering::AcqRel) == 0 {
            self.active_tx.send_replace(true);
        }

        SessionRuntimeConsumerGuard {
            state: Arc::clone(self),
        }
    }

    /// Subscribes to foreground-consumer availability changes.
    fn subscribe(&self) -> watch::Receiver<bool> {
        self.active_tx.subscribe()
    }
}

/// Registration guard for one foreground session-command consumer.
pub(crate) struct SessionRuntimeConsumerGuard {
    state: Arc<SessionRuntimeConsumerState>,
}

impl Drop for SessionRuntimeConsumerGuard {
    fn drop(&mut self) {
        if self.state.active_count.fetch_sub(1, Ordering::AcqRel) == 1 {
            self.state.active_tx.send_replace(false);
        }
    }
}

/// Session workflow owner and foreground-driven actor mailbox.
pub(crate) struct SessionRuntime {
    command_rx: mpsc::Receiver<SessionRuntimeCommand>,
    command_tx: mpsc::Sender<SessionRuntimeCommand>,
    consumer_state: Arc<SessionRuntimeConsumerState>,
    manager: SessionManager,
}

impl SessionRuntime {
    /// Wraps the loaded session manager and creates its bounded actor mailbox.
    pub(crate) fn new(manager: SessionManager) -> Self {
        let (command_tx, command_rx) = mpsc::channel(SESSION_RUNTIME_COMMAND_CAPACITY);

        Self {
            command_rx,
            command_tx,
            consumer_state: Arc::new(SessionRuntimeConsumerState::new()),
            manager,
        }
    }

    /// Returns a cloneable control handle for background or frontend callers.
    pub(crate) fn handle(&self) -> SessionRuntimeHandle {
        SessionRuntimeHandle {
            command_tx: self.command_tx.clone(),
            consumer_state: Arc::clone(&self.consumer_state),
        }
    }

    /// Registers a foreground command consumer for the guard's lifetime.
    pub(crate) fn foreground_consumer(&self) -> SessionRuntimeConsumerGuard {
        self.consumer_state.enter()
    }

    /// Waits for the next accepted actor command.
    ///
    /// The receiver cannot close while the runtime is alive because the
    /// runtime retains its own sender alongside the public handles.
    pub(crate) async fn next_command(&mut self) -> SessionRuntimeCommand {
        poll_fn(|context| match self.command_rx.poll_recv(context) {
            Poll::Ready(Some(command)) => Poll::Ready(command),
            Poll::Ready(None) | Poll::Pending => Poll::Pending,
        })
        .await
    }
}

impl From<SessionManager> for SessionRuntime {
    fn from(manager: SessionManager) -> Self {
        Self::new(manager)
    }
}

impl Deref for SessionRuntime {
    type Target = SessionManager;

    fn deref(&self) -> &Self::Target {
        &self.manager
    }
}

impl DerefMut for SessionRuntime {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.manager
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;

    fn assert_clone_send_sync<T: Clone + Send + Sync>() {}

    #[test]
    fn runtime_handle_is_cloneable_send_and_sync() {
        // Arrange / Act / Assert
        assert_clone_send_sync::<SessionRuntimeHandle>();
    }

    #[tokio::test]
    async fn handle_reports_unavailable_after_runtime_drops() {
        // Arrange
        let runtime = SessionRuntime::new(crate::test_support::session_manager_with_handles(
            Vec::new(),
            std::collections::HashMap::new(),
        ));
        let handle = runtime.handle();
        let _consumer = runtime.foreground_consumer();
        drop(runtime);

        // Act
        let error = handle
            .get_session(&SessionId::from("session-id"))
            .await
            .expect_err("closed runtime should reject commands");

        // Assert
        assert_eq!(
            error,
            SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
        );
    }

    #[tokio::test]
    async fn handle_reports_unavailable_when_command_response_drops() {
        // Arrange
        let mut runtime = SessionRuntime::new(crate::test_support::session_manager_with_handles(
            Vec::new(),
            std::collections::HashMap::new(),
        ));
        let handle = runtime.handle();
        let _consumer = runtime.foreground_consumer();
        let request =
            tokio::spawn(async move { handle.get_session(&SessionId::from("session-id")).await });
        let command = runtime.next_command().await;
        drop(command);

        // Act
        let error = request
            .await
            .expect("request task should complete")
            .expect_err("dropped response should fail");

        // Assert
        assert_eq!(
            error,
            SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
        );
    }

    #[tokio::test]
    async fn live_undriven_runtime_rejects_requests_without_waiting() {
        // Arrange
        let runtime = SessionRuntime::new(crate::test_support::session_manager_with_handles(
            Vec::new(),
            std::collections::HashMap::new(),
        ));
        let handle = runtime.handle();

        // Act
        let error = tokio::time::timeout(
            Duration::from_secs(1),
            handle.get_session(&SessionId::from("session-id")),
        )
        .await
        .expect("undriven runtime request should not hang")
        .expect_err("undriven runtime should reject requests");

        // Assert
        assert_eq!(
            error,
            SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
        );
    }

    #[tokio::test]
    async fn pending_response_stops_waiting_when_consumer_stops() {
        // Arrange
        let mut runtime = SessionRuntime::new(crate::test_support::session_manager_with_handles(
            Vec::new(),
            std::collections::HashMap::new(),
        ));
        let handle = runtime.handle();
        let consumer = runtime.foreground_consumer();
        let request =
            tokio::spawn(async move { handle.get_session(&SessionId::from("session-id")).await });
        let command = runtime.next_command().await;

        // Act
        drop(consumer);
        let error = request
            .await
            .expect("request task should complete")
            .expect_err("stopped consumer should fail the pending response");
        drop(command);

        // Assert
        assert_eq!(
            error,
            SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
        );
    }

    #[tokio::test]
    async fn pending_send_stops_waiting_when_consumer_stops() {
        // Arrange
        let runtime = SessionRuntime::new(crate::test_support::session_manager_with_handles(
            Vec::new(),
            std::collections::HashMap::new(),
        ));
        let consumer = runtime.foreground_consumer();
        let mut queued_requests = Vec::new();
        for request_index in 0..SESSION_RUNTIME_COMMAND_CAPACITY {
            let handle = runtime.handle();
            queued_requests.push(tokio::spawn(async move {
                handle
                    .get_session(&SessionId::from(format!("session-{request_index}")))
                    .await
            }));
        }
        tokio::time::timeout(Duration::from_secs(1), async {
            while runtime.command_rx.len() < SESSION_RUNTIME_COMMAND_CAPACITY {
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("runtime mailbox should fill");
        let blocked_handle = runtime.handle();
        let blocked_request = tokio::spawn(async move {
            blocked_handle
                .get_session(&SessionId::from("blocked-session"))
                .await
        });
        tokio::task::yield_now().await;
        assert!(!blocked_request.is_finished());

        // Act
        drop(consumer);
        let blocked_error = blocked_request
            .await
            .expect("blocked request task should complete")
            .expect_err("stopped consumer should fail the pending send");
        for queued_request in queued_requests {
            queued_request
                .await
                .expect("queued request task should complete")
                .expect_err("stopped consumer should fail queued responses");
        }

        // Assert
        assert_eq!(
            blocked_error,
            SessionError::Operation(SESSION_RUNTIME_UNAVAILABLE.to_string())
        );
    }
}