tea-cli 0.1.0

Interactive and headless Coding CLI 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
use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use tea_coding::{CodingError, CodingErrorCode};
use tea_mcp::{McpError, McpErrorCode, McpServerId};
use tea_policy::WorkspaceId;
use tea_protocol::{
    ApprovalDecision, ApprovalId, BranchId, CommandId, EventEnvelope, MessageId, ModelRef,
    SessionId, SessionSequence,
};

use crate::session_views::{
    McpServerView, SessionListItem, SessionSnapshotPage, SessionStateView, SessionStatsView,
    SessionTreeView,
};

/// Current independent RPC schema version.
pub const RPC_VERSION: &str = "1.0";
const MAX_REQUEST_ID_BYTES: usize = 128;

/// Bounded client-supplied response correlation identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RpcRequestId(String);

impl RpcRequestId {
    /// Creates a bounded, control-free request identity.
    ///
    /// # Errors
    ///
    /// Rejects empty, oversized, or control-containing values.
    pub fn new(value: impl Into<String>) -> Result<Self, RpcError> {
        let value = value.into();
        if value.is_empty()
            || value.len() > MAX_REQUEST_ID_BYTES
            || value.chars().any(char::is_control)
        {
            return Err(RpcError::new(
                RpcErrorCode::InvalidRequest,
                "request id is invalid",
            ));
        }
        Ok(Self(value))
    }

    /// Returns the correlation text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for RpcRequestId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl Serialize for RpcRequestId {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for RpcRequestId {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Self::new(String::deserialize(deserializer)?)
            .map_err(|_| serde::de::Error::custom("request id is invalid"))
    }
}

/// One strict versioned client request.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RpcRequest {
    rpc_version: String,
    #[serde(default)]
    id: Option<RpcRequestId>,
    #[serde(flatten)]
    request: RpcRequestKind,
}

impl RpcRequest {
    /// Returns the optional client correlation identity.
    #[must_use]
    pub const fn id(&self) -> Option<&RpcRequestId> {
        self.id.as_ref()
    }

    /// Splits the request after validating the independent RPC version.
    ///
    /// # Errors
    ///
    /// Returns `unsupported_version` for any schema other than 1.0.
    pub fn into_parts(self) -> Result<(Option<RpcRequestId>, RpcRequestKind), RpcError> {
        if self.rpc_version != RPC_VERSION {
            return Err(RpcError::new(
                RpcErrorCode::UnsupportedVersion,
                "RPC version is unsupported",
            ));
        }
        Ok((self.id, self.request))
    }
}

/// Supported command and host-query request families.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(tag = "type", content = "payload", rename_all = "snake_case")]
pub enum RpcRequestKind {
    /// Create and select a new durable session.
    NewSession {},
    /// Attach and select an existing durable session.
    OpenSession {
        /// Durable session identity.
        #[serde(rename = "sessionId")]
        session_id: SessionId,
    },
    /// Set or clear the selected session display name.
    NameSession {
        /// Optional bounded display name.
        name: Option<String>,
    },
    /// Submit one user prompt as an owned long-running command.
    Prompt {
        /// User text.
        text: String,
    },
    /// Steer the active run.
    Steer {
        /// Bounded steering text.
        text: String,
    },
    /// Queue a user follow-up.
    FollowUp {
        /// Bounded user text.
        text: String,
    },
    /// Cancel the active run.
    Abort {},
    /// Resolve a durable approval.
    ResolveApproval {
        /// Pending approval identity.
        #[serde(rename = "approvalId")]
        approval_id: ApprovalId,
        /// Supported bounded decision.
        decision: ApprovalDecision,
    },
    /// Select a model for future turns.
    SetModel {
        /// Registered provider-qualified model selector.
        model: ModelRef,
    },
    /// Compact the selected session.
    Compact {},
    /// Fork and activate a new branch.
    Fork {
        /// Durable source message.
        #[serde(rename = "fromMessageId")]
        from_message_id: MessageId,
        /// Client-assigned branch identity.
        #[serde(rename = "branchId")]
        branch_id: BranchId,
    },
    /// List durable sessions.
    ListSessions {},
    /// Query compact selected-session state.
    QueryState {},
    /// Query bounded canonical records after a durable cursor.
    QuerySnapshot {
        /// Last durable sequence already held by the client.
        #[serde(default, rename = "afterSequence")]
        after_sequence: Option<SessionSequence>,
        /// Requested record count, clamped to the server maximum.
        #[serde(default = "default_snapshot_limit")]
        limit: usize,
    },
    /// Query transcript statistics.
    QueryStats {},
    /// Query the append-only branch tree.
    QueryTree {},
    /// List registered provider models.
    ListModels {},
    /// List safe MCP health and frozen catalog metadata.
    ListMcpServers {},
    /// Reconnect one MCP server only when discovery matches the frozen catalog.
    ReconnectMcp {
        /// Configured MCP server identity.
        #[serde(rename = "serverId")]
        server_id: McpServerId,
    },
}

const fn default_snapshot_limit() -> usize {
    32
}

/// Stable safe RPC failure classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RpcErrorCode {
    /// A complete LF frame was not valid request JSON.
    ParseError,
    /// Request fields or state were invalid.
    InvalidRequest,
    /// The independent RPC version is unsupported.
    UnsupportedVersion,
    /// A requested session or artifact does not exist.
    NotFound,
    /// The requested session already owns conflicting work.
    Busy,
    /// Policy rejected the operation.
    PolicyDenied,
    /// Durable state could not be read or committed.
    Persistence,
    /// Provider execution or selection failed.
    Provider,
    /// Work was cancelled.
    Cancelled,
    /// An internal boundary failed.
    Internal,
}

/// Bounded path- and secret-independent RPC error.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RpcError {
    code: RpcErrorCode,
    message: String,
}

impl RpcError {
    /// Creates one safe error with bounded text.
    #[must_use]
    pub fn new(code: RpcErrorCode, message: impl Into<String>) -> Self {
        let mut message = message.into();
        if message.is_empty() {
            "RPC request failed".clone_into(&mut message);
        }
        message.retain(|character| !character.is_control() || character == ' ');
        if message.len() > 512 {
            let mut boundary = 512;
            while !message.is_char_boundary(boundary) {
                boundary -= 1;
            }
            message.truncate(boundary);
        }
        Self { code, message }
    }

    /// Returns the stable code.
    #[must_use]
    pub const fn code(&self) -> RpcErrorCode {
        self.code
    }
}

impl From<CodingError> for RpcError {
    fn from(error: CodingError) -> Self {
        let code = match error.code() {
            CodingErrorCode::InvalidInput => RpcErrorCode::InvalidRequest,
            CodingErrorCode::NotFound => RpcErrorCode::NotFound,
            CodingErrorCode::ProjectNotTrusted | CodingErrorCode::PolicyDenied => {
                RpcErrorCode::PolicyDenied
            }
            CodingErrorCode::Persistence => RpcErrorCode::Persistence,
            CodingErrorCode::Credential | CodingErrorCode::Provider => RpcErrorCode::Provider,
            CodingErrorCode::Cancelled => RpcErrorCode::Cancelled,
            CodingErrorCode::Runtime => RpcErrorCode::Internal,
        };
        Self::new(code, error.message())
    }
}

impl From<McpError> for RpcError {
    fn from(error: McpError) -> Self {
        let (code, message) = match error.code() {
            McpErrorCode::Configuration | McpErrorCode::PolicyDeclaration => {
                (RpcErrorCode::InvalidRequest, "MCP configuration is invalid")
            }
            McpErrorCode::Descriptor | McpErrorCode::Identity | McpErrorCode::StaleCatalog => (
                RpcErrorCode::InvalidRequest,
                "MCP catalog changed; close and rebuild the CLI service",
            ),
            McpErrorCode::Unavailable => (RpcErrorCode::Busy, "MCP server is unavailable"),
            McpErrorCode::Cancellation => (RpcErrorCode::Cancelled, "MCP operation was cancelled"),
            _ => (RpcErrorCode::Internal, "MCP service operation failed"),
        };
        Self::new(code, message)
    }
}

/// Successful or failed response payload correlated to one request.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RpcResponse {
    /// An owned prompt/approval command was accepted.
    CommandAccepted {
        /// Server-generated command identity.
        #[serde(rename = "commandId")]
        command_id: CommandId,
        /// Affected session.
        #[serde(rename = "sessionId")]
        session_id: SessionId,
    },
    /// A synchronous canonical mutation completed.
    CommandCompleted {
        /// Affected session.
        #[serde(rename = "sessionId")]
        session_id: SessionId,
    },
    /// The active session changed.
    SessionSelected {
        /// Compact authoritative state.
        state: SessionStateView,
        /// Clients must query a durable snapshot after rebinding.
        #[serde(rename = "resnapshotRequired")]
        resnapshot_required: bool,
    },
    /// Durable session catalog result.
    Sessions {
        /// Stable latest-updated ordering from `SessionCatalog`.
        sessions: Vec<SessionListItem>,
    },
    /// Compact selected-session state.
    State {
        /// Authoritative host state.
        state: SessionStateView,
    },
    /// Bounded canonical replay page.
    Snapshot {
        /// Durable records and tail cursor.
        snapshot: SessionSnapshotPage,
    },
    /// Rebuildable transcript statistics.
    Stats {
        /// Aggregate counts.
        stats: SessionStatsView,
    },
    /// Append-only branch tree.
    Tree {
        /// Stable branch projection.
        tree: SessionTreeView,
    },
    /// Registered models.
    Models {
        /// Provider-advertised model selectors.
        models: Vec<ModelRef>,
    },
    /// Safe MCP lifecycle and frozen-catalog projection.
    McpServers {
        /// Servers in canonical server-ID order.
        servers: Vec<McpServerView>,
    },
    /// Stable safe request failure.
    Error {
        /// Machine-readable error.
        error: RpcError,
    },
}

/// One server output frame: correlated response or asynchronous canonical event.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RpcOutput {
    /// Initial connection metadata.
    Ready {
        /// Independent RPC schema version.
        #[serde(rename = "rpcVersion")]
        rpc_version: &'static str,
        /// Initially selected session.
        #[serde(rename = "sessionId")]
        session_id: SessionId,
        /// Safe canonical workspace identity.
        #[serde(rename = "workspaceId")]
        workspace_id: WorkspaceId,
    },
    /// Correlated request response.
    Response {
        /// Independent RPC schema version.
        #[serde(rename = "rpcVersion")]
        rpc_version: &'static str,
        /// Optional client correlation identity.
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<RpcRequestId>,
        /// Typed response payload.
        payload: RpcResponse,
    },
    /// Asynchronous canonical event.
    Event {
        /// Independent RPC schema version.
        #[serde(rename = "rpcVersion")]
        rpc_version: &'static str,
        /// Unchanged canonical runtime event envelope.
        payload: EventEnvelope,
    },
    /// Owned command task reached its terminal result.
    CommandFinished {
        /// Independent RPC schema version.
        #[serde(rename = "rpcVersion")]
        rpc_version: &'static str,
        /// Accepted command identity.
        #[serde(rename = "commandId")]
        command_id: CommandId,
        /// Affected session.
        #[serde(rename = "sessionId")]
        session_id: SessionId,
        /// Safe failure when the command did not complete successfully.
        #[serde(skip_serializing_if = "Option::is_none")]
        error: Option<RpcError>,
    },
    /// The event subscription was replaced after a gap or rebind.
    ResnapshotRequired {
        /// Independent RPC schema version.
        #[serde(rename = "rpcVersion")]
        rpc_version: &'static str,
        /// Session requiring canonical replay.
        #[serde(rename = "sessionId")]
        session_id: SessionId,
        /// Current durable tail at notification time.
        #[serde(rename = "tailSequence")]
        tail_sequence: SessionSequence,
    },
}

impl RpcOutput {
    /// Creates initial connection metadata.
    #[must_use]
    pub const fn ready(session_id: SessionId, workspace_id: WorkspaceId) -> Self {
        Self::Ready {
            rpc_version: RPC_VERSION,
            session_id,
            workspace_id,
        }
    }

    /// Creates one correlated response frame.
    #[must_use]
    pub const fn response(id: Option<RpcRequestId>, payload: RpcResponse) -> Self {
        Self::Response {
            rpc_version: RPC_VERSION,
            id,
            payload,
        }
    }

    /// Creates one asynchronous canonical event frame.
    #[must_use]
    pub const fn event(payload: EventEnvelope) -> Self {
        Self::Event {
            rpc_version: RPC_VERSION,
            payload,
        }
    }

    /// Creates one asynchronous owned-command terminal notification.
    #[must_use]
    pub const fn command_finished(
        command_id: CommandId,
        session_id: SessionId,
        error: Option<RpcError>,
    ) -> Self {
        Self::CommandFinished {
            rpc_version: RPC_VERSION,
            command_id,
            session_id,
            error,
        }
    }

    /// Requires the client to rebuild from a durable snapshot page.
    #[must_use]
    pub const fn resnapshot_required(
        session_id: SessionId,
        tail_sequence: SessionSequence,
    ) -> Self {
        Self::ResnapshotRequired {
            rpc_version: RPC_VERSION,
            session_id,
            tail_sequence,
        }
    }

    /// Creates one safe error response.
    #[must_use]
    pub const fn error(id: Option<RpcRequestId>, error: RpcError) -> Self {
        Self::response(id, RpcResponse::Error { error })
    }
}