Skip to main content

tea_coding/
service.rs

1use std::collections::HashMap;
2use std::future::{Future as _, poll_fn};
3use std::pin::Pin;
4use std::str::FromStr;
5use std::sync::{Arc, Mutex};
6use std::task::Poll;
7
8use tea::{AgentRuntime, RuntimeCommandOutcome, RuntimeSessionState, SessionStats};
9use tea_coding_tools::WorkspaceRoot;
10use tea_mcp::{McpError, McpManager, McpServerHealth, McpServerId};
11use tea_model::{ModelCapabilities, ModelSpec};
12use tea_policy::WorkspaceId;
13use tea_protocol::{
14    AgentCommand, ApprovalDecision, ApprovalId, BranchId, CanonicalMessage, CommandEnvelope,
15    CommandId, CommandText, ContentBlock, MessageId, ModelRef, ProfileId, ProtocolMetadata,
16    ProtocolTimestamp, ReasoningEffort, SessionId,
17};
18use tea_session::{SessionCatalogEntry, SessionName};
19use tea_tools::ToolName;
20
21use crate::config::CodingSettings;
22use crate::mcp::{self, McpServiceSnapshot};
23use crate::resources::ResourceCatalog;
24use crate::{CodingError, CodingErrorCode};
25
26const MAX_OWNED_RUNS: usize = 64;
27
28/// Immediate acknowledgement that a long-running command has an owned task.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct CommandAcceptance {
31    command_id: CommandId,
32    session_id: SessionId,
33}
34
35impl CommandAcceptance {
36    /// Returns the accepted command identity.
37    #[must_use]
38    pub const fn command_id(self) -> CommandId {
39        self.command_id
40    }
41    /// Returns the affected session.
42    #[must_use]
43    pub const fn session_id(self) -> SessionId {
44        self.session_id
45    }
46}
47
48/// One mode-neutral application service over the canonical runtime/session model.
49#[derive(Debug)]
50pub struct CodingAgentService {
51    runtime: Arc<AgentRuntime>,
52    workspace: WorkspaceRoot,
53    resources: ResourceCatalog,
54    settings: CodingSettings,
55    workspace_id: WorkspaceId,
56    runs: Mutex<
57        HashMap<SessionId, tokio::task::JoinHandle<Result<RuntimeCommandOutcome, CodingError>>>,
58    >,
59    mcp_manager: Mutex<Option<Arc<McpManager>>>,
60}
61
62#[allow(clippy::missing_errors_doc)] // All facade errors use the documented `CodingError` boundary.
63impl CodingAgentService {
64    pub(crate) fn new(
65        runtime: AgentRuntime,
66        workspace: WorkspaceRoot,
67        resources: ResourceCatalog,
68        settings: CodingSettings,
69        workspace_id: WorkspaceId,
70        mcp_manager: Option<Arc<McpManager>>,
71    ) -> Self {
72        Self {
73            runtime: Arc::new(runtime),
74            workspace,
75            resources,
76            settings,
77            workspace_id,
78            runs: Mutex::new(HashMap::new()),
79            mcp_manager: Mutex::new(mcp_manager),
80        }
81    }
82
83    /// Returns the validated workspace capability.
84    #[must_use]
85    pub const fn workspace(&self) -> &WorkspaceRoot {
86        &self.workspace
87    }
88    /// Returns the safe canonical workspace identity.
89    #[must_use]
90    pub const fn workspace_id(&self) -> &WorkspaceId {
91        &self.workspace_id
92    }
93    /// Returns the immutable resource catalog.
94    #[must_use]
95    pub const fn resources(&self) -> &ResourceCatalog {
96        &self.resources
97    }
98    /// Returns the resolved secret-free product settings snapshot.
99    #[must_use]
100    pub const fn settings(&self) -> &CodingSettings {
101        &self.settings
102    }
103    /// Returns advertised provider models.
104    #[must_use]
105    pub fn models(&self) -> Vec<ModelRef> {
106        self.runtime
107            .models()
108            .iter()
109            .map(|model| model.model_ref().clone())
110            .collect()
111    }
112    /// Returns capabilities for one model in the frozen provider catalog.
113    #[must_use]
114    pub fn model_capabilities(&self, model_ref: &ModelRef) -> Option<ModelCapabilities> {
115        self.runtime
116            .models()
117            .iter()
118            .find(|model| model.model_ref() == model_ref)
119            .map(tea_model::ModelSpec::capabilities)
120    }
121    /// Returns one advertised model contract from the frozen catalog.
122    #[must_use]
123    pub fn model_spec(&self, model_ref: &ModelRef) -> Option<&ModelSpec> {
124        self.runtime
125            .models()
126            .iter()
127            .find(|model| model.model_ref() == model_ref)
128    }
129
130    /// Returns a safe immutable MCP lifecycle and catalog projection.
131    ///
132    /// The projection excludes server-provided descriptions, annotations,
133    /// process details, environment values, stderr, and result bodies.
134    pub fn mcp_snapshot(&self) -> Result<McpServiceSnapshot, McpError> {
135        let manager = self
136            .mcp_manager
137            .lock()
138            .map_err(|_| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Unavailable))?
139            .clone();
140        mcp::snapshot(manager.as_deref(), now_mcp()?)
141    }
142
143    /// Reconnects one configured MCP server only when its new discovery
144    /// snapshot exactly matches the frozen runtime catalog.
145    ///
146    /// A descriptor or stale-catalog error requires rebuilding this service;
147    /// reconnect never mutates its live tool registry or profile binding.
148    pub async fn reconnect_mcp(
149        &self,
150        server_id: &McpServerId,
151    ) -> Result<McpServerHealth, McpError> {
152        let manager = self
153            .mcp_manager
154            .lock()
155            .map_err(|_| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Unavailable))?
156            .clone()
157            .ok_or_else(|| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Unavailable))?;
158        manager.reconnect(server_id, now_mcp()?).await
159    }
160    /// Subscribes before prompt submission to avoid missing early events.
161    ///
162    /// # Errors
163    ///
164    /// Returns an error when the bounded subscriber registry is full.
165    pub fn subscribe(
166        &self,
167        session_id: SessionId,
168    ) -> Result<tokio::sync::mpsc::Receiver<tea_protocol::EventEnvelope>, CodingError> {
169        self.runtime
170            .subscribe(session_id)
171            .map_err(CodingError::from)
172    }
173    /// Creates a durable coding session.
174    ///
175    /// # Errors
176    ///
177    /// Returns a runtime or canonical command error.
178    pub async fn create_session(&self) -> Result<SessionId, CodingError> {
179        let outcome = self
180            .runtime
181            .send(envelope(
182                None,
183                AgentCommand::CreateSession {
184                    profile_id: ProfileId::from_str("coding-agent").map_err(|_| invalid())?,
185                    metadata: ProtocolMetadata::default(),
186                },
187            )?)
188            .await
189            .map_err(CodingError::from)?;
190        match outcome {
191            RuntimeCommandOutcome::Created { session_id } => Ok(session_id),
192            _ => Err(runtime_error()),
193        }
194    }
195    /// Attaches an existing durable session.
196    pub async fn open_session(
197        &self,
198        session_id: SessionId,
199    ) -> Result<RuntimeSessionState, CodingError> {
200        self.runtime
201            .attach_session(session_id)
202            .await
203            .map_err(CodingError::from)
204    }
205    /// Lists durable sessions.
206    pub async fn list_sessions(&self) -> Result<Vec<SessionCatalogEntry>, CodingError> {
207        self.runtime
208            .list_sessions()
209            .await
210            .map_err(CodingError::from)
211    }
212    /// Sets a durable display name.
213    pub async fn name_session(
214        &self,
215        session_id: SessionId,
216        name: Option<SessionName>,
217    ) -> Result<(), CodingError> {
218        self.runtime
219            .set_session_name(session_id, name)
220            .await
221            .map_err(CodingError::from)
222    }
223    /// Returns a compact mode-neutral state projection.
224    pub async fn snapshot(
225        &self,
226        session_id: SessionId,
227    ) -> Result<RuntimeSessionState, CodingError> {
228        self.runtime
229            .session_state(session_id)
230            .await
231            .map_err(CodingError::from)
232    }
233    /// Returns the complete immutable canonical session snapshot.
234    ///
235    /// Hosts use this after startup, reconnect, or an observed sequence gap to
236    /// rebuild projections instead of treating transient deltas as durable.
237    pub async fn session_snapshot(
238        &self,
239        session_id: SessionId,
240    ) -> Result<tea_session::SessionSnapshot, CodingError> {
241        self.runtime
242            .snapshot(session_id)
243            .await
244            .map_err(CodingError::from)
245    }
246    /// Returns rebuildable session statistics.
247    pub async fn stats(&self, session_id: SessionId) -> Result<SessionStats, CodingError> {
248        self.runtime
249            .session_stats(session_id)
250            .await
251            .map_err(CodingError::from)
252    }
253
254    /// Accepts a prompt into one owned task; completion is observed separately.
255    ///
256    /// # Errors
257    ///
258    /// Rejects duplicate/overflowing owned runs and invalid prompt text.
259    pub fn prompt(
260        &self,
261        session_id: SessionId,
262        text: impl Into<String>,
263    ) -> Result<CommandAcceptance, CodingError> {
264        let content = vec![ContentBlock::text(text.into()).map_err(|_| invalid())?];
265        self.prompt_content(session_id, content)
266    }
267
268    /// Accepts typed user content into one owned task.
269    ///
270    /// # Errors
271    ///
272    /// Rejects duplicate/overflowing owned runs and content that cannot form a
273    /// canonical user message.
274    pub fn prompt_content(
275        &self,
276        session_id: SessionId,
277        content: Vec<ContentBlock>,
278    ) -> Result<CommandAcceptance, CodingError> {
279        let timestamp = now()?;
280        let message = CanonicalMessage::user(new_id::<MessageId>()?, content, timestamp)
281            .map_err(|_| invalid())?;
282        let envelope = envelope_at(
283            Some(session_id),
284            AgentCommand::Prompt { message },
285            timestamp,
286        )?;
287        self.start_owned(session_id, envelope)
288    }
289
290    /// Awaits and removes one owned run.
291    pub async fn wait(&self, session_id: SessionId) -> Result<RuntimeCommandOutcome, CodingError> {
292        poll_fn(|context| {
293            let Ok(mut runs) = self.runs.lock() else {
294                return Poll::Ready(Err(runtime_error()));
295            };
296            let Some(handle) = runs.get_mut(&session_id) else {
297                return Poll::Ready(Err(CodingError::new(
298                    CodingErrorCode::Runtime,
299                    "session has no owned run",
300                )));
301            };
302            match Pin::new(handle).poll(context) {
303                Poll::Pending => Poll::Pending,
304                Poll::Ready(joined) => {
305                    runs.remove(&session_id);
306                    Poll::Ready(
307                        joined
308                            .map_err(|_| runtime_error())
309                            .and_then(|result| result),
310                    )
311                }
312            }
313        })
314        .await
315    }
316
317    /// Sends steering text to an active run.
318    pub async fn steer(
319        &self,
320        session_id: SessionId,
321        text: impl Into<String>,
322    ) -> Result<RuntimeCommandOutcome, CodingError> {
323        self.send(
324            session_id,
325            AgentCommand::Steer {
326                text: CommandText::new(text).map_err(|_| invalid())?,
327            },
328        )
329        .await
330    }
331    /// Queues a follow-up user message.
332    pub async fn follow_up(
333        &self,
334        session_id: SessionId,
335        text: impl Into<String>,
336    ) -> Result<RuntimeCommandOutcome, CodingError> {
337        let timestamp = now()?;
338        let message = CanonicalMessage::user(
339            new_id::<MessageId>()?,
340            vec![ContentBlock::text(text.into()).map_err(|_| invalid())?],
341            timestamp,
342        )
343        .map_err(|_| invalid())?;
344        self.send_at(session_id, AgentCommand::FollowUp { message }, timestamp)
345            .await
346    }
347    /// Cancels an active run.
348    pub async fn abort(&self, session_id: SessionId) -> Result<RuntimeCommandOutcome, CodingError> {
349        self.send(session_id, AgentCommand::Abort {}).await
350    }
351    /// Accepts approval resolution into an owned continuation task.
352    pub fn approve(
353        &self,
354        session_id: SessionId,
355        approval_id: ApprovalId,
356        decision: ApprovalDecision,
357    ) -> Result<CommandAcceptance, CodingError> {
358        let command = envelope(
359            Some(session_id),
360            AgentCommand::ResolveApproval {
361                approval_id,
362                decision,
363            },
364        )?;
365        self.start_owned(session_id, command)
366    }
367    /// Selects a model for future turns.
368    pub async fn set_model(
369        &self,
370        session_id: SessionId,
371        model: ModelRef,
372    ) -> Result<RuntimeCommandOutcome, CodingError> {
373        self.send(session_id, AgentCommand::SetModel { model })
374            .await
375    }
376    /// Selects provider-neutral reasoning effort for future turns.
377    pub async fn set_reasoning_effort(
378        &self,
379        session_id: SessionId,
380        reasoning_effort: ReasoningEffort,
381    ) -> Result<RuntimeCommandOutcome, CodingError> {
382        self.send(
383            session_id,
384            AgentCommand::SetReasoningEffort { reasoning_effort },
385        )
386        .await
387    }
388    /// Selects a registered product profile for future turns.
389    pub async fn set_profile(
390        &self,
391        session_id: SessionId,
392        profile_id: ProfileId,
393    ) -> Result<RuntimeCommandOutcome, CodingError> {
394        self.send(session_id, AgentCommand::SetProfile { profile_id })
395            .await
396    }
397    /// Replaces the active tool set for future runs in this session.
398    pub async fn set_active_tools(
399        &self,
400        session_id: SessionId,
401        names: Vec<ToolName>,
402    ) -> Result<(), CodingError> {
403        self.runtime
404            .set_active_tools(session_id, names)
405            .await
406            .map_err(CodingError::from)
407    }
408    /// Requests manual compaction.
409    pub async fn compact(
410        &self,
411        session_id: SessionId,
412    ) -> Result<RuntimeCommandOutcome, CodingError> {
413        self.send(
414            session_id,
415            AgentCommand::CompactSession { instruction: None },
416        )
417        .await
418    }
419    /// Forks and activates a branch from one message.
420    pub async fn fork(
421        &self,
422        session_id: SessionId,
423        from_message_id: MessageId,
424        branch_id: BranchId,
425    ) -> Result<RuntimeCommandOutcome, CodingError> {
426        self.send(
427            session_id,
428            AgentCommand::ForkSession {
429                from_message_id,
430                branch_id,
431            },
432        )
433        .await
434    }
435
436    /// Cancels active runtime runs, aborts task owners, and awaits shutdown.
437    pub async fn shutdown(&self) {
438        let session_ids = self
439            .runs
440            .lock()
441            .map(|runs| runs.keys().copied().collect::<Vec<_>>())
442            .unwrap_or_default();
443        for session_id in session_ids {
444            if let Ok(command) = envelope(Some(session_id), AgentCommand::Abort {}) {
445                let _ = self.runtime.send(command).await;
446            }
447        }
448        let handles = self
449            .runs
450            .lock()
451            .map(|mut runs| runs.drain().map(|(_, handle)| handle).collect::<Vec<_>>())
452            .unwrap_or_default();
453        for handle in &handles {
454            handle.abort();
455        }
456        for handle in handles {
457            let _ = handle.await;
458        }
459        let manager = self
460            .mcp_manager
461            .lock()
462            .ok()
463            .and_then(|mut manager| manager.take());
464        if let Some(manager) = manager {
465            let _ = manager.shutdown().await;
466        }
467    }
468
469    fn start_owned(
470        &self,
471        session_id: SessionId,
472        command: CommandEnvelope,
473    ) -> Result<CommandAcceptance, CodingError> {
474        let command_id = command.command_id();
475        let runtime = Arc::clone(&self.runtime);
476        let mut runs = self.runs.lock().map_err(|_| runtime_error())?;
477        if runs.contains_key(&session_id) || runs.len() >= MAX_OWNED_RUNS {
478            return Err(CodingError::new(
479                CodingErrorCode::Runtime,
480                "session already has an owned run",
481            ));
482        }
483        let handle =
484            tokio::spawn(async move { runtime.send(command).await.map_err(CodingError::from) });
485        runs.insert(session_id, handle);
486        Ok(CommandAcceptance {
487            command_id,
488            session_id,
489        })
490    }
491
492    async fn send(
493        &self,
494        session_id: SessionId,
495        command: AgentCommand,
496    ) -> Result<RuntimeCommandOutcome, CodingError> {
497        self.runtime
498            .send(envelope(Some(session_id), command)?)
499            .await
500            .map_err(CodingError::from)
501    }
502    async fn send_at(
503        &self,
504        session_id: SessionId,
505        command: AgentCommand,
506        timestamp: ProtocolTimestamp,
507    ) -> Result<RuntimeCommandOutcome, CodingError> {
508        self.runtime
509            .send(envelope_at(Some(session_id), command, timestamp)?)
510            .await
511            .map_err(CodingError::from)
512    }
513}
514
515impl Drop for CodingAgentService {
516    fn drop(&mut self) {
517        if let Ok(runs) = self.runs.get_mut() {
518            for handle in runs.values() {
519                handle.abort();
520            }
521        }
522        let Some(manager) = self.mcp_manager.get_mut().ok().and_then(Option::take) else {
523            return;
524        };
525        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
526            runtime.spawn(async move {
527                let _ = manager.shutdown().await;
528            });
529            return;
530        }
531        if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
532            .enable_all()
533            .build()
534        {
535            let _ = runtime.block_on(manager.shutdown());
536        }
537    }
538}
539
540fn envelope(
541    session_id: Option<SessionId>,
542    command: AgentCommand,
543) -> Result<CommandEnvelope, CodingError> {
544    envelope_at(session_id, command, now()?)
545}
546fn envelope_at(
547    session_id: Option<SessionId>,
548    command: AgentCommand,
549    timestamp: ProtocolTimestamp,
550) -> Result<CommandEnvelope, CodingError> {
551    CommandEnvelope::new(new_id::<CommandId>()?, session_id, timestamp, command)
552        .map_err(|_| invalid())
553}
554fn new_id<T: FromStr>() -> Result<T, CodingError> {
555    UuidString::new().0.parse().map_err(|_| invalid())
556}
557struct UuidString(String);
558impl UuidString {
559    fn new() -> Self {
560        Self(uuid::Uuid::now_v7().hyphenated().to_string())
561    }
562}
563fn now() -> Result<ProtocolTimestamp, CodingError> {
564    chrono::Utc::now()
565        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
566        .parse()
567        .map_err(|_| invalid())
568}
569fn now_mcp() -> Result<ProtocolTimestamp, McpError> {
570    chrono::Utc::now()
571        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
572        .parse()
573        .map_err(|_| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Configuration))
574}
575fn invalid() -> CodingError {
576    CodingError::new(
577        CodingErrorCode::InvalidInput,
578        "canonical coding command is invalid",
579    )
580}
581fn runtime_error() -> CodingError {
582    CodingError::new(CodingErrorCode::Runtime, "coding runtime operation failed")
583}