Skip to main content

trusty_code/session/
connector.rs

1//! [`TcodeConnector`] — tcode's [`WorkstreamConnector`] implementation
2//! (DOC-44 twin Phase 1, issue #3007).
3//!
4//! Why: DOC-44 §5.2 assigns tcode's connector to wrap the #2983 REST bridge
5//! (`crate::serve::rest`) rather than reimplementing `session.*` business
6//! logic — every REST route already just forwards to the identical
7//! JSON-RPC method (`crate::session::protocol`) both `serve --stdio` and
8//! `serve --http POST /rpc` dispatch through (see `crate::serve::rest`
9//! module docs), so this connector calling REST is provably the SAME code
10//! path a `POST /rpc` caller would hit. `attach` is the one exception —
11//! there is no `GET`/`POST` REST route for `session.attach` (the vision spec
12//! §4.4 SSE route, `GET /sessions/{id}/events`, is the real HTTP
13//! live-streaming mechanism; `session.attach` itself only returns the
14//! ring-buffer replay + that stream's URL) — so `attach` goes over
15//! `POST /rpc` directly, exactly as `tests/session_e2e.rs`'s HTTP scenario
16//! already does.
17//! What: [`TcodeConnector::new`] targets the default `tcode serve --http`
18//! port ([`crate::serve::DEFAULT_HTTP_PORT`], `7882`);
19//! [`TcodeConnector::with_daemon_url`] targets an explicit daemon (every test
20//! in `tests/connector_e2e.rs` uses this against a `--port 0` instance). Every
21//! trait method's doc comment states the exact route/method it maps onto.
22//! `delegate` is NOT implemented — see that method's docs (DOC-44 locked
23//! decision 3).
24//! Test: `tests/connector_e2e.rs` (a top-level integration test — trusty-code
25//! has no `tests/support`-reachable unit-test seam for driving the REAL
26//! `tcode` binary, so this mirrors `tests/session_e2e.rs`'s own placement)
27//! drives every method against a real `tcode serve --http --port 0` process
28//! via `support::spawn_http_daemon`.
29
30use async_trait::async_trait;
31use serde_json::{Value, json};
32use trusty_agents_common::connectors::{
33    AgentSpec, AttachHandle, BackendParams, ConnectorError, CreateSessionReq, DelegateHandle,
34    SessionInfo, SessionStatus, WorkstreamConnector,
35};
36
37use super::model::Session;
38
39/// tcode's [`WorkstreamConnector`] implementation over the #2983 REST bridge
40/// (+ `POST /rpc` for `attach`).
41///
42/// Why/What: see module docs.
43pub struct TcodeConnector {
44    http: reqwest::Client,
45    daemon_url: String,
46}
47
48impl TcodeConnector {
49    /// Build a connector targeting `http://127.0.0.1:<DEFAULT_HTTP_PORT>`.
50    ///
51    /// Why: the common case for a caller that just wants "the local tcode
52    /// daemon on its documented default port." Unlike tm, tcode has no
53    /// lock-file/gateway discovery chain yet (DOC-44 §7.1 lists that as a
54    /// tcode operational prerequisite, out of scope here) — this is a fixed
55    /// default, matching how the CLI itself defaults `--port`.
56    /// What: delegates to [`Self::with_daemon_url`] with
57    /// `http://127.0.0.1:{DEFAULT_HTTP_PORT}`.
58    /// Test: exercised indirectly — every `connector_e2e.rs` test builds via
59    /// [`Self::with_daemon_url`] instead (an ephemeral `--port 0` instance),
60    /// since asserting on this constructor's exact URL would require either
61    /// binding the real default port (risking a collision with a developer's
62    /// already-running `tcode serve`) or exposing `daemon_url` for
63    /// inspection, which would leak an implementation detail no caller needs.
64    pub fn new() -> Self {
65        Self::with_daemon_url(format!(
66            "http://127.0.0.1:{}",
67            crate::serve::DEFAULT_HTTP_PORT
68        ))
69    }
70
71    /// Build a connector targeting an explicit daemon URL.
72    ///
73    /// Why: tests need to target a `--port 0` ephemeral instance rather than
74    /// the fixed default.
75    /// What: stores `daemon_url` and a plain `reqwest::Client`.
76    pub fn with_daemon_url(daemon_url: impl Into<String>) -> Self {
77        Self {
78            http: reqwest::Client::new(),
79            daemon_url: daemon_url.into(),
80        }
81    }
82}
83
84impl Default for TcodeConnector {
85    fn default() -> Self {
86        Self::new()
87    }
88}
89
90/// Map a non-success HTTP response onto a [`ConnectorError`] (shared by the
91/// REST-route methods below).
92///
93/// Why: `rpc_error_to_status` (`crate::serve::rest::rpc_error_to_status`)
94/// already maps every domain error code onto the right HTTP status
95/// (404/400/403/500) before this connector ever sees the response — so
96/// classifying purely by status code, rather than re-parsing the JSON-RPC
97/// error envelope in the body, is sufficient and keeps this connector
98/// decoupled from that internal mapping's exact error-code table.
99/// What: 404 -> `NotFound`, 400 -> `InvalidRequest`, else -> `Backend`.
100async fn map_error_response(resp: reqwest::Response) -> ConnectorError {
101    let status = resp.status();
102    let body = resp.text().await.unwrap_or_default();
103    let message = if body.trim().is_empty() {
104        status.to_string()
105    } else {
106        format!("{status}: {}", body.trim())
107    };
108    if status == reqwest::StatusCode::NOT_FOUND {
109        ConnectorError::NotFound(message)
110    } else if status == reqwest::StatusCode::BAD_REQUEST {
111        ConnectorError::InvalidRequest(message)
112    } else {
113        ConnectorError::Backend(message)
114    }
115}
116
117/// Map a JSON-RPC error OBJECT (the `error` field of a `POST /rpc` envelope)
118/// onto a [`ConnectorError`] — used only by `attach`, since `POST /rpc`
119/// always returns HTTP 200 and carries its error in the envelope (unlike the
120/// REST routes, which get a real HTTP status from `rpc_error_to_status`).
121///
122/// Why: mirrors `crate::serve::rest::rpc_error_to_status`'s code table so
123/// `attach`'s error classification agrees with every REST-routed method's.
124/// What: `-32007`/`-32002` -> `NotFound`; `-32003`/`-32602` ->
125/// `InvalidRequest`; everything else -> `Backend`.
126fn map_rpc_error_object(err: &Value) -> ConnectorError {
127    let code = err.get("code").and_then(Value::as_i64).unwrap_or(0);
128    let message = err
129        .get("message")
130        .and_then(Value::as_str)
131        .unwrap_or("unknown JSON-RPC error")
132        .to_string();
133    match code {
134        -32007 | -32002 => ConnectorError::NotFound(message),
135        -32003 | -32602 => ConnectorError::InvalidRequest(message),
136        _ => ConnectorError::Backend(message),
137    }
138}
139
140/// Map a `reqwest` transport-level failure onto [`ConnectorError::Transport`].
141fn transport_err(e: reqwest::Error) -> ConnectorError {
142    ConnectorError::Transport(e.to_string())
143}
144
145/// Map a JSON-body-decode failure onto [`ConnectorError::Transport`].
146fn decode_err(e: reqwest::Error) -> ConnectorError {
147    ConnectorError::Transport(format!("failed to decode daemon response: {e}"))
148}
149
150/// Map a [`Session`] onto the portable [`SessionInfo`].
151///
152/// Why: tcode's `Session` has no separate display-name field (unlike tm's
153/// tmux session name) — `name` mirrors `task` so callers always have SOME
154/// human-readable label, documented here rather than silently duplicating
155/// the field with no explanation.
156fn session_to_info(session: Session) -> SessionInfo {
157    SessionInfo {
158        id: session.id,
159        name: session.task.clone(),
160        state: session.status.as_str().to_string(),
161        task: Some(session.task),
162    }
163}
164
165#[async_trait]
166impl WorkstreamConnector for TcodeConnector {
167    /// `POST /sessions` -> `session.create` (#2983 Slice 3).
168    ///
169    /// Why: mints a new tcode session bound to an existing local project.
170    /// `req.backend` must be [`BackendParams::Tcode`] — a
171    /// [`BackendParams::Tm`] request is a caller bug (asked the tcode
172    /// connector to provision a tm-shaped worktree session) and is rejected
173    /// with [`ConnectorError::InvalidRequest`] before any HTTP call is made.
174    /// What: `req.name_hint` has no tcode equivalent and is silently
175    /// ignored (see [`CreateSessionReq`]'s docs); `req.agent` maps onto
176    /// `session.create`'s `agent` param. A `400` (empty task, or `project`
177    /// naming no real directory — see `session::protocol::create`'s AC-16.2
178    /// docs) maps to [`ConnectorError::InvalidRequest`].
179    /// Test: `connector_e2e::create_session_full_lifecycle`,
180    /// `connector_e2e::create_session_wrong_backend_params_is_invalid_request`.
181    async fn create_session(&self, req: CreateSessionReq) -> Result<SessionInfo, ConnectorError> {
182        let CreateSessionReq {
183            task,
184            name_hint: _name_hint,
185            agent,
186            backend,
187        } = req;
188        let project = match backend {
189            BackendParams::Tcode { project } => project,
190            BackendParams::Tm { .. } => {
191                return Err(ConnectorError::InvalidRequest(
192                    "tcode connector requires CreateSessionReq::backend = BackendParams::Tcode"
193                        .into(),
194                ));
195            }
196        };
197        let body = json!({
198            "task": task,
199            "agent": agent,
200            "project": project.to_string_lossy(),
201        });
202        let url = format!("{}/sessions", self.daemon_url);
203        let resp = self
204            .http
205            .post(&url)
206            .json(&body)
207            .send()
208            .await
209            .map_err(transport_err)?;
210        if !resp.status().is_success() {
211            return Err(map_error_response(resp).await);
212        }
213        let session: Session = resp.json().await.map_err(decode_err)?;
214        Ok(session_to_info(session))
215    }
216
217    /// `GET /sessions` -> `session.list` (#2983 Slice 2).
218    ///
219    /// Why: enumerates every session the daemon currently owns.
220    /// What: unwraps the `{"sessions": [...]}` envelope and maps each
221    /// `Session` onto a portable `SessionInfo`.
222    /// Test: `connector_e2e::list_sessions_empty_fleet_returns_empty_vec`.
223    async fn list_sessions(&self) -> Result<Vec<SessionInfo>, ConnectorError> {
224        #[derive(serde::Deserialize)]
225        struct SessionsEnvelope {
226            sessions: Vec<Session>,
227        }
228        let url = format!("{}/sessions", self.daemon_url);
229        let resp = self.http.get(&url).send().await.map_err(transport_err)?;
230        if !resp.status().is_success() {
231            return Err(map_error_response(resp).await);
232        }
233        let listed: SessionsEnvelope = resp.json().await.map_err(decode_err)?;
234        Ok(listed.sessions.into_iter().map(session_to_info).collect())
235    }
236
237    /// `GET /sessions/{id}` -> `session.status` (#2983 Slice 2).
238    ///
239    /// Why: point lookup for one session's current state.
240    /// What: a `404` (unknown id, `-32007 session_not_found`) maps to
241    /// [`ConnectorError::NotFound`]. `pending_decision` is always `None` —
242    /// tcode has no equivalent concept in this phase (tm's managed-session
243    /// pending-decision surface has no tcode counterpart yet).
244    /// Test: `connector_e2e::session_status_unknown_id_is_not_found`.
245    async fn session_status(&self, session_id: &str) -> Result<SessionStatus, ConnectorError> {
246        let url = format!("{}/sessions/{session_id}", self.daemon_url);
247        let resp = self.http.get(&url).send().await.map_err(transport_err)?;
248        if !resp.status().is_success() {
249            return Err(map_error_response(resp).await);
250        }
251        let session: Session = resp.json().await.map_err(decode_err)?;
252        Ok(SessionStatus {
253            id: session.id,
254            state: session.status.as_str().to_string(),
255            pending_decision: None,
256        })
257    }
258
259    /// `POST /sessions/{id}/messages` -> `session.send` (#2983 Slice 3).
260    ///
261    /// Why: the client -> daemon input path.
262    /// What: a `404` (unknown id) maps to [`ConnectorError::NotFound`];
263    /// success is `()` — the daemon's `{"acknowledged": true}` confirmation
264    /// is not surfaced through this trait.
265    /// Test: `connector_e2e::send_input_unknown_id_is_not_found`.
266    async fn send_input(&self, session_id: &str, input: &str) -> Result<(), ConnectorError> {
267        let url = format!("{}/sessions/{session_id}/messages", self.daemon_url);
268        let resp = self
269            .http
270            .post(&url)
271            .json(&json!({ "input": input }))
272            .send()
273            .await
274            .map_err(transport_err)?;
275        if !resp.status().is_success() {
276            return Err(map_error_response(resp).await);
277        }
278        Ok(())
279    }
280
281    /// `POST /rpc` `session.attach` — ring-buffer replay + SSE stream URL.
282    ///
283    /// Why: there is no REST route for `session.attach` (see module docs) —
284    /// this is the one method that must speak raw JSON-RPC. tcode's attach
285    /// surface is fundamentally different from tm's: it hands back replayed
286    /// history plus a URL a caller GETs (as SSE) for live events, rather
287    /// than a command a human runs — see [`AttachHandle::EventStream`]'s
288    /// docs for why this is NOT forced into tm's shell-command shape.
289    /// What: `POST /rpc` always returns HTTP 200 (errors are carried IN the
290    /// envelope, per `crate::serve::http::rpc_handler`'s docs) — a non-200
291    /// here means transport failure, mapped via [`map_error_response`]; an
292    /// `error` field in the envelope is mapped via
293    /// [`map_rpc_error_object`] (`-32007 session_not_found` ->
294    /// [`ConnectorError::NotFound`]). On success, wraps
295    /// `result.{session_id,stream_url,events}` in
296    /// [`AttachHandle::EventStream`].
297    /// Test: `connector_e2e::create_session_full_lifecycle` (asserts the
298    /// returned handle is an `EventStream` with the expected `stream_url`),
299    /// `connector_e2e::attach_unknown_id_is_not_found`.
300    async fn attach(&self, session_id: &str) -> Result<AttachHandle, ConnectorError> {
301        let rpc_req = json!({
302            "jsonrpc": "2.0",
303            "id": 1,
304            "method": "session.attach",
305            "params": { "session_id": session_id },
306        });
307        let url = format!("{}/rpc", self.daemon_url);
308        let resp = self
309            .http
310            .post(&url)
311            .json(&rpc_req)
312            .send()
313            .await
314            .map_err(transport_err)?;
315        if !resp.status().is_success() {
316            return Err(map_error_response(resp).await);
317        }
318        let envelope: Value = resp.json().await.map_err(decode_err)?;
319        if let Some(err) = envelope.get("error") {
320            return Err(map_rpc_error_object(err));
321        }
322        let result = envelope.get("result").cloned().unwrap_or(Value::Null);
323        let session_id_out = result
324            .get("session_id")
325            .and_then(Value::as_str)
326            .unwrap_or(session_id)
327            .to_string();
328        let stream_url = result
329            .get("stream_url")
330            .and_then(Value::as_str)
331            .unwrap_or_default()
332            .to_string();
333        let replayed_events = result
334            .get("events")
335            .and_then(Value::as_array)
336            .cloned()
337            .unwrap_or_default();
338        Ok(AttachHandle::EventStream {
339            session_id: session_id_out,
340            stream_url,
341            replayed_events,
342        })
343    }
344
345    /// Always [`ConnectorError::NotSupported`] — tcode has no delegate
346    /// surface in this phase (DOC-44 locked decision 3).
347    ///
348    /// Why: tm's `delegate` wraps `agent_delegate`'s gate+record-only MCP
349    /// tool; tcode has no equivalent endpoint, and adding one is explicit
350    /// scope creep for issue #3007 (the issue's locked design calls this out
351    /// by name). Returning a typed `NotSupported` — rather than a generic
352    /// `Backend`/`Transport` failure, and rather than making an HTTP call
353    /// that would 404/`METHOD_NOT_FOUND` against a route that will never
354    /// exist — lets a caller (the future lead agent, or a test) distinguish
355    /// "this backend never does this" from "this particular call failed."
356    /// What: returns `Err(ConnectorError::NotSupported(_))` unconditionally,
357    /// with no network call at all.
358    /// Test: `connector_e2e::delegate_is_not_supported`.
359    async fn delegate(
360        &self,
361        _session_id: &str,
362        _agent_spec: &AgentSpec,
363    ) -> Result<DelegateHandle, ConnectorError> {
364        Err(ConnectorError::NotSupported(
365            "tcode has no delegate surface in this phase (DOC-44 locked decision 3, issue #3007)"
366                .into(),
367        ))
368    }
369}