tea-coding 0.1.0

Coding profile, configuration, resources, and session service for tea-rs
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
use std::collections::HashMap;
use std::future::{Future as _, poll_fn};
use std::pin::Pin;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::task::Poll;

use tea::{AgentRuntime, RuntimeCommandOutcome, RuntimeSessionState, SessionStats};
use tea_coding_tools::WorkspaceRoot;
use tea_mcp::{McpError, McpManager, McpServerHealth, McpServerId};
use tea_model::{ModelCapabilities, ModelSpec};
use tea_policy::WorkspaceId;
use tea_protocol::{
    AgentCommand, ApprovalDecision, ApprovalId, BranchId, CanonicalMessage, CommandEnvelope,
    CommandId, CommandText, ContentBlock, MessageId, ModelRef, ProfileId, ProtocolMetadata,
    ProtocolTimestamp, ReasoningEffort, SessionId,
};
use tea_session::{SessionCatalogEntry, SessionName};
use tea_tools::ToolName;

use crate::config::CodingSettings;
use crate::mcp::{self, McpServiceSnapshot};
use crate::resources::ResourceCatalog;
use crate::{CodingError, CodingErrorCode};

const MAX_OWNED_RUNS: usize = 64;

/// Immediate acknowledgement that a long-running command has an owned task.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandAcceptance {
    command_id: CommandId,
    session_id: SessionId,
}

impl CommandAcceptance {
    /// Returns the accepted command identity.
    #[must_use]
    pub const fn command_id(self) -> CommandId {
        self.command_id
    }
    /// Returns the affected session.
    #[must_use]
    pub const fn session_id(self) -> SessionId {
        self.session_id
    }
}

/// One mode-neutral application service over the canonical runtime/session model.
#[derive(Debug)]
pub struct CodingAgentService {
    runtime: Arc<AgentRuntime>,
    workspace: WorkspaceRoot,
    resources: ResourceCatalog,
    settings: CodingSettings,
    workspace_id: WorkspaceId,
    runs: Mutex<
        HashMap<SessionId, tokio::task::JoinHandle<Result<RuntimeCommandOutcome, CodingError>>>,
    >,
    mcp_manager: Mutex<Option<Arc<McpManager>>>,
}

#[allow(clippy::missing_errors_doc)] // All facade errors use the documented `CodingError` boundary.
impl CodingAgentService {
    pub(crate) fn new(
        runtime: AgentRuntime,
        workspace: WorkspaceRoot,
        resources: ResourceCatalog,
        settings: CodingSettings,
        workspace_id: WorkspaceId,
        mcp_manager: Option<Arc<McpManager>>,
    ) -> Self {
        Self {
            runtime: Arc::new(runtime),
            workspace,
            resources,
            settings,
            workspace_id,
            runs: Mutex::new(HashMap::new()),
            mcp_manager: Mutex::new(mcp_manager),
        }
    }

    /// Returns the validated workspace capability.
    #[must_use]
    pub const fn workspace(&self) -> &WorkspaceRoot {
        &self.workspace
    }
    /// Returns the safe canonical workspace identity.
    #[must_use]
    pub const fn workspace_id(&self) -> &WorkspaceId {
        &self.workspace_id
    }
    /// Returns the immutable resource catalog.
    #[must_use]
    pub const fn resources(&self) -> &ResourceCatalog {
        &self.resources
    }
    /// Returns the resolved secret-free product settings snapshot.
    #[must_use]
    pub const fn settings(&self) -> &CodingSettings {
        &self.settings
    }
    /// Returns advertised provider models.
    #[must_use]
    pub fn models(&self) -> Vec<ModelRef> {
        self.runtime
            .models()
            .iter()
            .map(|model| model.model_ref().clone())
            .collect()
    }
    /// Returns capabilities for one model in the frozen provider catalog.
    #[must_use]
    pub fn model_capabilities(&self, model_ref: &ModelRef) -> Option<ModelCapabilities> {
        self.runtime
            .models()
            .iter()
            .find(|model| model.model_ref() == model_ref)
            .map(tea_model::ModelSpec::capabilities)
    }
    /// Returns one advertised model contract from the frozen catalog.
    #[must_use]
    pub fn model_spec(&self, model_ref: &ModelRef) -> Option<&ModelSpec> {
        self.runtime
            .models()
            .iter()
            .find(|model| model.model_ref() == model_ref)
    }

    /// Returns a safe immutable MCP lifecycle and catalog projection.
    ///
    /// The projection excludes server-provided descriptions, annotations,
    /// process details, environment values, stderr, and result bodies.
    pub fn mcp_snapshot(&self) -> Result<McpServiceSnapshot, McpError> {
        let manager = self
            .mcp_manager
            .lock()
            .map_err(|_| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Unavailable))?
            .clone();
        mcp::snapshot(manager.as_deref(), now_mcp()?)
    }

    /// Reconnects one configured MCP server only when its new discovery
    /// snapshot exactly matches the frozen runtime catalog.
    ///
    /// A descriptor or stale-catalog error requires rebuilding this service;
    /// reconnect never mutates its live tool registry or profile binding.
    pub async fn reconnect_mcp(
        &self,
        server_id: &McpServerId,
    ) -> Result<McpServerHealth, McpError> {
        let manager = self
            .mcp_manager
            .lock()
            .map_err(|_| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Unavailable))?
            .clone()
            .ok_or_else(|| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Unavailable))?;
        manager.reconnect(server_id, now_mcp()?).await
    }
    /// Subscribes before prompt submission to avoid missing early events.
    ///
    /// # Errors
    ///
    /// Returns an error when the bounded subscriber registry is full.
    pub fn subscribe(
        &self,
        session_id: SessionId,
    ) -> Result<tokio::sync::mpsc::Receiver<tea_protocol::EventEnvelope>, CodingError> {
        self.runtime
            .subscribe(session_id)
            .map_err(CodingError::from)
    }
    /// Creates a durable coding session.
    ///
    /// # Errors
    ///
    /// Returns a runtime or canonical command error.
    pub async fn create_session(&self) -> Result<SessionId, CodingError> {
        let outcome = self
            .runtime
            .send(envelope(
                None,
                AgentCommand::CreateSession {
                    profile_id: ProfileId::from_str("coding-agent").map_err(|_| invalid())?,
                    metadata: ProtocolMetadata::default(),
                },
            )?)
            .await
            .map_err(CodingError::from)?;
        match outcome {
            RuntimeCommandOutcome::Created { session_id } => Ok(session_id),
            _ => Err(runtime_error()),
        }
    }
    /// Attaches an existing durable session.
    pub async fn open_session(
        &self,
        session_id: SessionId,
    ) -> Result<RuntimeSessionState, CodingError> {
        self.runtime
            .attach_session(session_id)
            .await
            .map_err(CodingError::from)
    }
    /// Lists durable sessions.
    pub async fn list_sessions(&self) -> Result<Vec<SessionCatalogEntry>, CodingError> {
        self.runtime
            .list_sessions()
            .await
            .map_err(CodingError::from)
    }
    /// Sets a durable display name.
    pub async fn name_session(
        &self,
        session_id: SessionId,
        name: Option<SessionName>,
    ) -> Result<(), CodingError> {
        self.runtime
            .set_session_name(session_id, name)
            .await
            .map_err(CodingError::from)
    }
    /// Returns a compact mode-neutral state projection.
    pub async fn snapshot(
        &self,
        session_id: SessionId,
    ) -> Result<RuntimeSessionState, CodingError> {
        self.runtime
            .session_state(session_id)
            .await
            .map_err(CodingError::from)
    }
    /// Returns the complete immutable canonical session snapshot.
    ///
    /// Hosts use this after startup, reconnect, or an observed sequence gap to
    /// rebuild projections instead of treating transient deltas as durable.
    pub async fn session_snapshot(
        &self,
        session_id: SessionId,
    ) -> Result<tea_session::SessionSnapshot, CodingError> {
        self.runtime
            .snapshot(session_id)
            .await
            .map_err(CodingError::from)
    }
    /// Returns rebuildable session statistics.
    pub async fn stats(&self, session_id: SessionId) -> Result<SessionStats, CodingError> {
        self.runtime
            .session_stats(session_id)
            .await
            .map_err(CodingError::from)
    }

    /// Accepts a prompt into one owned task; completion is observed separately.
    ///
    /// # Errors
    ///
    /// Rejects duplicate/overflowing owned runs and invalid prompt text.
    pub fn prompt(
        &self,
        session_id: SessionId,
        text: impl Into<String>,
    ) -> Result<CommandAcceptance, CodingError> {
        let content = vec![ContentBlock::text(text.into()).map_err(|_| invalid())?];
        self.prompt_content(session_id, content)
    }

    /// Accepts typed user content into one owned task.
    ///
    /// # Errors
    ///
    /// Rejects duplicate/overflowing owned runs and content that cannot form a
    /// canonical user message.
    pub fn prompt_content(
        &self,
        session_id: SessionId,
        content: Vec<ContentBlock>,
    ) -> Result<CommandAcceptance, CodingError> {
        let timestamp = now()?;
        let message = CanonicalMessage::user(new_id::<MessageId>()?, content, timestamp)
            .map_err(|_| invalid())?;
        let envelope = envelope_at(
            Some(session_id),
            AgentCommand::Prompt { message },
            timestamp,
        )?;
        self.start_owned(session_id, envelope)
    }

    /// Awaits and removes one owned run.
    pub async fn wait(&self, session_id: SessionId) -> Result<RuntimeCommandOutcome, CodingError> {
        poll_fn(|context| {
            let Ok(mut runs) = self.runs.lock() else {
                return Poll::Ready(Err(runtime_error()));
            };
            let Some(handle) = runs.get_mut(&session_id) else {
                return Poll::Ready(Err(CodingError::new(
                    CodingErrorCode::Runtime,
                    "session has no owned run",
                )));
            };
            match Pin::new(handle).poll(context) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(joined) => {
                    runs.remove(&session_id);
                    Poll::Ready(
                        joined
                            .map_err(|_| runtime_error())
                            .and_then(|result| result),
                    )
                }
            }
        })
        .await
    }

    /// Sends steering text to an active run.
    pub async fn steer(
        &self,
        session_id: SessionId,
        text: impl Into<String>,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(
            session_id,
            AgentCommand::Steer {
                text: CommandText::new(text).map_err(|_| invalid())?,
            },
        )
        .await
    }
    /// Queues a follow-up user message.
    pub async fn follow_up(
        &self,
        session_id: SessionId,
        text: impl Into<String>,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        let timestamp = now()?;
        let message = CanonicalMessage::user(
            new_id::<MessageId>()?,
            vec![ContentBlock::text(text.into()).map_err(|_| invalid())?],
            timestamp,
        )
        .map_err(|_| invalid())?;
        self.send_at(session_id, AgentCommand::FollowUp { message }, timestamp)
            .await
    }
    /// Cancels an active run.
    pub async fn abort(&self, session_id: SessionId) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(session_id, AgentCommand::Abort {}).await
    }
    /// Accepts approval resolution into an owned continuation task.
    pub fn approve(
        &self,
        session_id: SessionId,
        approval_id: ApprovalId,
        decision: ApprovalDecision,
    ) -> Result<CommandAcceptance, CodingError> {
        let command = envelope(
            Some(session_id),
            AgentCommand::ResolveApproval {
                approval_id,
                decision,
            },
        )?;
        self.start_owned(session_id, command)
    }
    /// Selects a model for future turns.
    pub async fn set_model(
        &self,
        session_id: SessionId,
        model: ModelRef,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(session_id, AgentCommand::SetModel { model })
            .await
    }
    /// Selects provider-neutral reasoning effort for future turns.
    pub async fn set_reasoning_effort(
        &self,
        session_id: SessionId,
        reasoning_effort: ReasoningEffort,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(
            session_id,
            AgentCommand::SetReasoningEffort { reasoning_effort },
        )
        .await
    }
    /// Selects a registered product profile for future turns.
    pub async fn set_profile(
        &self,
        session_id: SessionId,
        profile_id: ProfileId,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(session_id, AgentCommand::SetProfile { profile_id })
            .await
    }
    /// Replaces the active tool set for future runs in this session.
    pub async fn set_active_tools(
        &self,
        session_id: SessionId,
        names: Vec<ToolName>,
    ) -> Result<(), CodingError> {
        self.runtime
            .set_active_tools(session_id, names)
            .await
            .map_err(CodingError::from)
    }
    /// Requests manual compaction.
    pub async fn compact(
        &self,
        session_id: SessionId,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(
            session_id,
            AgentCommand::CompactSession { instruction: None },
        )
        .await
    }
    /// Forks and activates a branch from one message.
    pub async fn fork(
        &self,
        session_id: SessionId,
        from_message_id: MessageId,
        branch_id: BranchId,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.send(
            session_id,
            AgentCommand::ForkSession {
                from_message_id,
                branch_id,
            },
        )
        .await
    }

    /// Cancels active runtime runs, aborts task owners, and awaits shutdown.
    pub async fn shutdown(&self) {
        let session_ids = self
            .runs
            .lock()
            .map(|runs| runs.keys().copied().collect::<Vec<_>>())
            .unwrap_or_default();
        for session_id in session_ids {
            if let Ok(command) = envelope(Some(session_id), AgentCommand::Abort {}) {
                let _ = self.runtime.send(command).await;
            }
        }
        let handles = self
            .runs
            .lock()
            .map(|mut runs| runs.drain().map(|(_, handle)| handle).collect::<Vec<_>>())
            .unwrap_or_default();
        for handle in &handles {
            handle.abort();
        }
        for handle in handles {
            let _ = handle.await;
        }
        let manager = self
            .mcp_manager
            .lock()
            .ok()
            .and_then(|mut manager| manager.take());
        if let Some(manager) = manager {
            let _ = manager.shutdown().await;
        }
    }

    fn start_owned(
        &self,
        session_id: SessionId,
        command: CommandEnvelope,
    ) -> Result<CommandAcceptance, CodingError> {
        let command_id = command.command_id();
        let runtime = Arc::clone(&self.runtime);
        let mut runs = self.runs.lock().map_err(|_| runtime_error())?;
        if runs.contains_key(&session_id) || runs.len() >= MAX_OWNED_RUNS {
            return Err(CodingError::new(
                CodingErrorCode::Runtime,
                "session already has an owned run",
            ));
        }
        let handle =
            tokio::spawn(async move { runtime.send(command).await.map_err(CodingError::from) });
        runs.insert(session_id, handle);
        Ok(CommandAcceptance {
            command_id,
            session_id,
        })
    }

    async fn send(
        &self,
        session_id: SessionId,
        command: AgentCommand,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.runtime
            .send(envelope(Some(session_id), command)?)
            .await
            .map_err(CodingError::from)
    }
    async fn send_at(
        &self,
        session_id: SessionId,
        command: AgentCommand,
        timestamp: ProtocolTimestamp,
    ) -> Result<RuntimeCommandOutcome, CodingError> {
        self.runtime
            .send(envelope_at(Some(session_id), command, timestamp)?)
            .await
            .map_err(CodingError::from)
    }
}

impl Drop for CodingAgentService {
    fn drop(&mut self) {
        if let Ok(runs) = self.runs.get_mut() {
            for handle in runs.values() {
                handle.abort();
            }
        }
        let Some(manager) = self.mcp_manager.get_mut().ok().and_then(Option::take) else {
            return;
        };
        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
            runtime.spawn(async move {
                let _ = manager.shutdown().await;
            });
            return;
        }
        if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
        {
            let _ = runtime.block_on(manager.shutdown());
        }
    }
}

fn envelope(
    session_id: Option<SessionId>,
    command: AgentCommand,
) -> Result<CommandEnvelope, CodingError> {
    envelope_at(session_id, command, now()?)
}
fn envelope_at(
    session_id: Option<SessionId>,
    command: AgentCommand,
    timestamp: ProtocolTimestamp,
) -> Result<CommandEnvelope, CodingError> {
    CommandEnvelope::new(new_id::<CommandId>()?, session_id, timestamp, command)
        .map_err(|_| invalid())
}
fn new_id<T: FromStr>() -> Result<T, CodingError> {
    UuidString::new().0.parse().map_err(|_| invalid())
}
struct UuidString(String);
impl UuidString {
    fn new() -> Self {
        Self(uuid::Uuid::now_v7().hyphenated().to_string())
    }
}
fn now() -> Result<ProtocolTimestamp, CodingError> {
    chrono::Utc::now()
        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
        .parse()
        .map_err(|_| invalid())
}
fn now_mcp() -> Result<ProtocolTimestamp, McpError> {
    chrono::Utc::now()
        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
        .parse()
        .map_err(|_| tea_mcp::McpError::new(tea_mcp::McpErrorCode::Configuration))
}
fn invalid() -> CodingError {
    CodingError::new(
        CodingErrorCode::InvalidInput,
        "canonical coding command is invalid",
    )
}
fn runtime_error() -> CodingError {
    CodingError::new(CodingErrorCode::Runtime, "coding runtime operation failed")
}