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 `reqwest::Client` carrying the daemon
76    /// credential (#5439) as a DEFAULT header.
77    ///
78    /// A default header rather than a per-request one because this client
79    /// talks to exactly one target — `daemon_url`, resolved once above — so
80    /// there is no second destination it could reach, and the six request
81    /// sites below cannot individually forget it. The header is marked
82    /// sensitive so `reqwest`'s own `Debug` output redacts it. The
83    /// never-off-loopback rule lives in
84    /// `crate::http_credential::daemon_credential_for`, not here.
85    pub fn with_daemon_url(daemon_url: impl Into<String>) -> Self {
86        let daemon_url = daemon_url.into();
87        Self {
88            http: credentialed_client(&daemon_url),
89            daemon_url,
90        }
91    }
92
93    /// Build a connector presenting an explicitly supplied credential.
94    ///
95    /// Why: an integration test drives a daemon it spawned with its OWN
96    /// isolated data directory (#5439's hermeticity fix), so the credential is
97    /// not the one this process would resolve from disk. Passing it as an
98    /// argument beats exporting `TCODE_DAEMON_TOKEN`, which is process-global
99    /// and races the other tests in the same binary.
100    /// What: identical to [`Self::with_daemon_url`] except the credential comes
101    /// from the caller. The loopback gate still applies — a non-loopback
102    /// `daemon_url` gets no header, whatever is passed here.
103    /// Test: `tests/connector_e2e.rs`'s live-daemon arms.
104    pub fn with_daemon_url_and_credential(daemon_url: impl Into<String>, credential: &str) -> Self {
105        let daemon_url = daemon_url.into();
106        let http = if trusty_common::daemon_token::url_targets_loopback(&daemon_url) {
107            client_presenting(credential)
108        } else {
109            reqwest::Client::new()
110        };
111        Self { http, daemon_url }
112    }
113}
114
115/// A `reqwest::Client` presenting the daemon credential for `daemon_url`.
116///
117/// Why: #5439 put every route behind a credential, so a connector built on a
118/// bare client sees `401` on every call. Resolution is delegated to
119/// `crate::http_credential::daemon_credential_for` so the "never send the
120/// local token off loopback" rule has exactly one implementation.
121/// What: falls back to a plain client when there is no credential to present
122/// or the target is not loopback — the caller then reads the daemon's `401`
123/// as an ordinary `ConnectorError`, which is a clearer failure than a client
124/// that refused to be constructed.
125/// Test: `create_session_full_lifecycle`,
126/// `list_sessions_empty_fleet_returns_empty_vec` (both in
127/// `tests/connector_e2e.rs`) exercise the credentialed path against a live
128/// daemon; the loopback gate is covered by
129/// `credential_is_withheld_from_a_non_loopback_url` in `crate::http_credential`.
130fn credentialed_client(daemon_url: &str) -> reqwest::Client {
131    match crate::http_credential::daemon_credential_for(daemon_url) {
132        Some(token) => client_presenting(&token),
133        None => reqwest::Client::new(),
134    }
135}
136
137/// A client sending `Authorization: Bearer <token>` on every request.
138///
139/// What: the header is marked sensitive so `reqwest`'s own `Debug` output
140/// redacts it. A token that will not fit in a header value yields a plain
141/// client rather than a panic — the caller then reads the daemon's `401`.
142fn client_presenting(token: &str) -> reqwest::Client {
143    let Ok(mut value) = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}")) else {
144        return reqwest::Client::new();
145    };
146    value.set_sensitive(true);
147    let mut headers = reqwest::header::HeaderMap::new();
148    headers.insert(reqwest::header::AUTHORIZATION, value);
149    reqwest::Client::builder()
150        .default_headers(headers)
151        .build()
152        .unwrap_or_else(|_| reqwest::Client::new())
153}
154
155impl Default for TcodeConnector {
156    fn default() -> Self {
157        Self::new()
158    }
159}
160
161/// Map a non-success HTTP response onto a [`ConnectorError`] (shared by the
162/// REST-route methods below).
163///
164/// Why: `rpc_error_to_status` (`crate::serve::rest::rpc_error_to_status`)
165/// already maps every domain error code onto the right HTTP status
166/// (404/400/403/500) before this connector ever sees the response — so
167/// classifying purely by status code, rather than re-parsing the JSON-RPC
168/// error envelope in the body, is sufficient and keeps this connector
169/// decoupled from that internal mapping's exact error-code table.
170/// What: 404 -> `NotFound`, 400 -> `InvalidRequest`, else -> `Backend`.
171async fn map_error_response(resp: reqwest::Response) -> ConnectorError {
172    let status = resp.status();
173    let body = resp.text().await.unwrap_or_default();
174    let message = if body.trim().is_empty() {
175        status.to_string()
176    } else {
177        format!("{status}: {}", body.trim())
178    };
179    if status == reqwest::StatusCode::NOT_FOUND {
180        ConnectorError::NotFound(message)
181    } else if status == reqwest::StatusCode::BAD_REQUEST {
182        ConnectorError::InvalidRequest(message)
183    } else {
184        ConnectorError::Backend(message)
185    }
186}
187
188/// Map a JSON-RPC error OBJECT (the `error` field of a `POST /rpc` envelope)
189/// onto a [`ConnectorError`] — used only by `attach`, since `POST /rpc`
190/// always returns HTTP 200 and carries its error in the envelope (unlike the
191/// REST routes, which get a real HTTP status from `rpc_error_to_status`).
192///
193/// Why: mirrors `crate::serve::rest::rpc_error_to_status`'s code table so
194/// `attach`'s error classification agrees with every REST-routed method's.
195/// What: `-32007`/`-32002` -> `NotFound`; `-32003`/`-32602` ->
196/// `InvalidRequest`; everything else -> `Backend`.
197fn map_rpc_error_object(err: &Value) -> ConnectorError {
198    let code = err.get("code").and_then(Value::as_i64).unwrap_or(0);
199    let message = err
200        .get("message")
201        .and_then(Value::as_str)
202        .unwrap_or("unknown JSON-RPC error")
203        .to_string();
204    match code {
205        -32007 | -32002 => ConnectorError::NotFound(message),
206        -32003 | -32602 => ConnectorError::InvalidRequest(message),
207        _ => ConnectorError::Backend(message),
208    }
209}
210
211/// Map a `reqwest` transport-level failure onto [`ConnectorError::Transport`].
212fn transport_err(e: reqwest::Error) -> ConnectorError {
213    ConnectorError::Transport(e.to_string())
214}
215
216/// Map a JSON-body-decode failure onto [`ConnectorError::Transport`].
217fn decode_err(e: reqwest::Error) -> ConnectorError {
218    ConnectorError::Transport(format!("failed to decode daemon response: {e}"))
219}
220
221/// Map a [`Session`] onto the portable [`SessionInfo`].
222///
223/// Why: tcode's `Session` has no separate display-name field (unlike tm's
224/// tmux session name) — `name` mirrors `task` so callers always have SOME
225/// human-readable label, documented here rather than silently duplicating
226/// the field with no explanation.
227fn session_to_info(session: Session) -> SessionInfo {
228    SessionInfo {
229        id: session.id,
230        name: session.task.clone(),
231        state: session.status.as_str().to_string(),
232        task: Some(session.task),
233    }
234}
235
236#[async_trait]
237impl WorkstreamConnector for TcodeConnector {
238    /// `POST /sessions` -> `session.create` (#2983 Slice 3).
239    ///
240    /// Why: mints a new tcode session bound to an existing local project.
241    /// `req.backend` must be [`BackendParams::Tcode`] — a
242    /// [`BackendParams::Tm`] request is a caller bug (asked the tcode
243    /// connector to provision a tm-shaped worktree session) and is rejected
244    /// with [`ConnectorError::InvalidRequest`] before any HTTP call is made.
245    /// What: `req.name_hint` has no tcode equivalent and is silently
246    /// ignored (see [`CreateSessionReq`]'s docs); `req.agent` maps onto
247    /// `session.create`'s `agent` param. A `400` (empty task, or `project`
248    /// naming no real directory — see `session::protocol::create`'s AC-16.2
249    /// docs) maps to [`ConnectorError::InvalidRequest`].
250    /// Test: `connector_e2e::create_session_full_lifecycle`,
251    /// `connector_e2e::create_session_wrong_backend_params_is_invalid_request`.
252    async fn create_session(&self, req: CreateSessionReq) -> Result<SessionInfo, ConnectorError> {
253        let CreateSessionReq {
254            task,
255            name_hint: _name_hint,
256            agent,
257            backend,
258        } = req;
259        let project = match backend {
260            BackendParams::Tcode { project } => project,
261            BackendParams::Tm { .. } => {
262                return Err(ConnectorError::InvalidRequest(
263                    "tcode connector requires CreateSessionReq::backend = BackendParams::Tcode"
264                        .into(),
265                ));
266            }
267        };
268        let body = json!({
269            "task": task,
270            "agent": agent,
271            "project": project.to_string_lossy(),
272            // #8184: `session.create` now defaults to the SOLO agent for the
273            // interactive TUI. This connector provisions sessions
274            // PROGRAMMATICALLY, with no client attached to answer a permission
275            // prompt, so it keeps the pre-#8184 delegating shape explicitly
276            // rather than inheriting a default aimed at a human at a terminal.
277            "delegate": true,
278        });
279        let url = format!("{}/sessions", self.daemon_url);
280        let resp = self
281            .http
282            .post(&url)
283            .json(&body)
284            .send()
285            .await
286            .map_err(transport_err)?;
287        if !resp.status().is_success() {
288            return Err(map_error_response(resp).await);
289        }
290        let session: Session = resp.json().await.map_err(decode_err)?;
291        Ok(session_to_info(session))
292    }
293
294    /// `GET /sessions` -> `session.list` (#2983 Slice 2).
295    ///
296    /// Why: enumerates every session the daemon currently owns.
297    /// What: unwraps the `{"sessions": [...]}` envelope and maps each
298    /// `Session` onto a portable `SessionInfo`.
299    /// Test: `connector_e2e::list_sessions_empty_fleet_returns_empty_vec`.
300    async fn list_sessions(&self) -> Result<Vec<SessionInfo>, ConnectorError> {
301        #[derive(serde::Deserialize)]
302        struct SessionsEnvelope {
303            sessions: Vec<Session>,
304        }
305        let url = format!("{}/sessions", self.daemon_url);
306        let resp = self.http.get(&url).send().await.map_err(transport_err)?;
307        if !resp.status().is_success() {
308            return Err(map_error_response(resp).await);
309        }
310        let listed: SessionsEnvelope = resp.json().await.map_err(decode_err)?;
311        Ok(listed.sessions.into_iter().map(session_to_info).collect())
312    }
313
314    /// `GET /sessions/{id}` -> `session.status` (#2983 Slice 2).
315    ///
316    /// Why: point lookup for one session's current state.
317    /// What: a `404` (unknown id, `-32007 session_not_found`) maps to
318    /// [`ConnectorError::NotFound`]. `pending_decision` is always `None` —
319    /// tcode has no equivalent concept in this phase (tm's managed-session
320    /// pending-decision surface has no tcode counterpart yet).
321    /// Test: `connector_e2e::session_status_unknown_id_is_not_found`.
322    async fn session_status(&self, session_id: &str) -> Result<SessionStatus, ConnectorError> {
323        let url = format!("{}/sessions/{session_id}", self.daemon_url);
324        let resp = self.http.get(&url).send().await.map_err(transport_err)?;
325        if !resp.status().is_success() {
326            return Err(map_error_response(resp).await);
327        }
328        let session: Session = resp.json().await.map_err(decode_err)?;
329        Ok(SessionStatus {
330            id: session.id,
331            state: session.status.as_str().to_string(),
332            pending_decision: None,
333        })
334    }
335
336    /// `POST /sessions/{id}/messages` -> `session.send` (#2983 Slice 3).
337    ///
338    /// Why: the client -> daemon input path.
339    /// What: a `404` (unknown id) maps to [`ConnectorError::NotFound`];
340    /// success is `()` — the daemon's `{"acknowledged": true}` confirmation
341    /// is not surfaced through this trait.
342    /// Test: `connector_e2e::send_input_unknown_id_is_not_found`.
343    async fn send_input(&self, session_id: &str, input: &str) -> Result<(), ConnectorError> {
344        let url = format!("{}/sessions/{session_id}/messages", self.daemon_url);
345        let resp = self
346            .http
347            .post(&url)
348            .json(&json!({ "input": input }))
349            .send()
350            .await
351            .map_err(transport_err)?;
352        if !resp.status().is_success() {
353            return Err(map_error_response(resp).await);
354        }
355        Ok(())
356    }
357
358    /// `POST /rpc` `session.attach` — ring-buffer replay + SSE stream URL.
359    ///
360    /// Why: there is no REST route for `session.attach` (see module docs) —
361    /// this is the one method that must speak raw JSON-RPC. tcode's attach
362    /// surface is fundamentally different from tm's: it hands back replayed
363    /// history plus a URL a caller GETs (as SSE) for live events, rather
364    /// than a command a human runs — see [`AttachHandle::EventStream`]'s
365    /// docs for why this is NOT forced into tm's shell-command shape.
366    /// What: `POST /rpc` always returns HTTP 200 (errors are carried IN the
367    /// envelope, per `crate::serve::http::rpc_handler`'s docs) — a non-200
368    /// here means transport failure, mapped via [`map_error_response`]; an
369    /// `error` field in the envelope is mapped via
370    /// [`map_rpc_error_object`] (`-32007 session_not_found` ->
371    /// [`ConnectorError::NotFound`]). On success, wraps
372    /// `result.{session_id,stream_url,events}` in
373    /// [`AttachHandle::EventStream`].
374    /// Test: `connector_e2e::create_session_full_lifecycle` (asserts the
375    /// returned handle is an `EventStream` with the expected `stream_url`),
376    /// `connector_e2e::attach_unknown_id_is_not_found`.
377    async fn attach(&self, session_id: &str) -> Result<AttachHandle, ConnectorError> {
378        let rpc_req = json!({
379            "jsonrpc": "2.0",
380            "id": 1,
381            "method": "session.attach",
382            "params": { "session_id": session_id },
383        });
384        let url = format!("{}/rpc", self.daemon_url);
385        let resp = self
386            .http
387            .post(&url)
388            .json(&rpc_req)
389            .send()
390            .await
391            .map_err(transport_err)?;
392        if !resp.status().is_success() {
393            return Err(map_error_response(resp).await);
394        }
395        let envelope: Value = resp.json().await.map_err(decode_err)?;
396        if let Some(err) = envelope.get("error") {
397            return Err(map_rpc_error_object(err));
398        }
399        let result = envelope.get("result").cloned().unwrap_or(Value::Null);
400        let session_id_out = result
401            .get("session_id")
402            .and_then(Value::as_str)
403            .unwrap_or(session_id)
404            .to_string();
405        let stream_url = result
406            .get("stream_url")
407            .and_then(Value::as_str)
408            .unwrap_or_default()
409            .to_string();
410        let replayed_events = result
411            .get("events")
412            .and_then(Value::as_array)
413            .cloned()
414            .unwrap_or_default();
415        Ok(AttachHandle::EventStream {
416            session_id: session_id_out,
417            stream_url,
418            replayed_events,
419        })
420    }
421
422    /// Always [`ConnectorError::NotSupported`] — tcode has no delegate
423    /// surface in this phase (DOC-44 locked decision 3).
424    ///
425    /// Why: tm's `delegate` wraps `agent_delegate`'s gate+record-only MCP
426    /// tool; tcode has no equivalent endpoint, and adding one is explicit
427    /// scope creep for issue #3007 (the issue's locked design calls this out
428    /// by name). Returning a typed `NotSupported` — rather than a generic
429    /// `Backend`/`Transport` failure, and rather than making an HTTP call
430    /// that would 404/`METHOD_NOT_FOUND` against a route that will never
431    /// exist — lets a caller (the future lead agent, or a test) distinguish
432    /// "this backend never does this" from "this particular call failed."
433    /// What: returns `Err(ConnectorError::NotSupported(_))` unconditionally,
434    /// with no network call at all.
435    /// Test: `connector_e2e::delegate_is_not_supported`.
436    async fn delegate(
437        &self,
438        _session_id: &str,
439        _agent_spec: &AgentSpec,
440    ) -> Result<DelegateHandle, ConnectorError> {
441        Err(ConnectorError::NotSupported(
442            "tcode has no delegate surface in this phase (DOC-44 locked decision 3, issue #3007)"
443                .into(),
444        ))
445    }
446}