basemind 0.6.0

Full AI context layer over MCP — tree-sitter code-map, document RAG (PDF/Office/HTML/email + OCR + reranker), shared agent memory, on-demand web crawl, git history + blame + per-symbol diff. 300+ languages, 8 coding-agent harnesses, content-addressed Fjall + LanceDB.
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
//! A2A HTTP server assembly: the single-listener axum app fronting the
//! JSON-RPC 2.0 binding ([`crate::a2a::jsonrpc::handlers`]) and the tonic gRPC
//! service ([`crate::a2a::grpc::service::BasemindA2aService`]).
//!
//! [`build_router`] wires the routes plus a shared tower middleware stack
//! (request-id, tracing, CORS, load-shed, concurrency limit, timeout). Both
//! transports share one [`tokio::net::TcpListener`]: `axum::serve` auto-negotiates
//! HTTP/1.1 (JSON-RPC) and HTTP/2 h2c (gRPC) per connection, so the gRPC service
//! is mounted as a plain route rather than on a second port.
//!
//! [`serve`] binds the listener and runs the app with graceful shutdown driven
//! by a [`CancellationToken`](tokio_util::sync::CancellationToken). It is mounted
//! by [`crate::a2a::run_server`] (the `basemind a2a serve` CLI). Bearer auth is
//! applied here via [`crate::a2a::auth::require_bearer`].
//!
//! When a TLS pair ([`crate::a2a::TlsPaths`]) is supplied, [`serve`] swaps the
//! plaintext `axum::serve` acceptor for an `axum_server` rustls acceptor whose
//! ALPN list is `["h2", "http/1.1"]`, so gRPC-over-TLS negotiates HTTP/2. The
//! plaintext path is left byte-for-byte unchanged (it depends on axum's HTTP/2
//! h2c upgrade for gRPC). Graceful shutdown for the TLS path is wired through an
//! [`axum_server::Handle`] driven by the same [`CancellationToken`].

use std::net::SocketAddr;
use std::time::Duration;

use axum::Router;
use axum::error_handling::HandleErrorLayer;
use axum::extract::DefaultBodyLimit;
use axum::http::StatusCode;
use axum::middleware::from_fn_with_state;
use axum::routing::{get, post};
use tokio_util::sync::CancellationToken;
use tower::ServiceBuilder;
use tower::limit::ConcurrencyLimitLayer;
use tower::load_shed::LoadShedLayer;
use tower::timeout::TimeoutLayer;
use tower_http::cors::CorsLayer;
use tower_http::request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer};
use tower_http::trace::TraceLayer;

use crate::a2a::auth::require_bearer;
use crate::a2a::jsonrpc::handlers::{agent_card_handler, jsonrpc_handler};
use crate::a2a::state::A2aState;

/// Maximum JSON-RPC request body size (4 MiB). Applied to the JSON-RPC route
/// only so it does not throttle the gRPC streaming path.
const MAX_REQUEST_BODY_BYTES: usize = 4 * 1024 * 1024;

/// Maximum number of in-flight requests admitted concurrently before the
/// load-shed layer rejects new work with `503 Service Unavailable`.
const MAX_CONCURRENT_REQUESTS: usize = 1024;

/// Per-request timeout, in seconds, enforced by the tower [`TimeoutLayer`].
const REQUEST_TIMEOUT_SECS: u64 = 30;

/// Well-known route serving the public agent card. Always reachable without
/// auth so clients can discover the security scheme before holding a token.
pub(crate) const AGENT_CARD_PATH: &str = "/.well-known/agent-card.json";

/// gRPC route template for the A2A service. tonic dispatches on the
/// `/<package>.<Service>/<Method>` path; `:method` captures the RPC name.
const GRPC_SERVICE_PATH: &str = "/lf.a2a.v1.A2AService/:method";

/// Build the A2A axum [`Router`]: JSON-RPC entrypoint, agent-card route, the
/// mounted gRPC service, and the shared tower middleware stack.
pub(crate) fn build_router(state: A2aState) -> Router {
    // Mount the tonic service as a plain axum route on the shared listener.
    // `axum::serve` upgrades HTTP/2 h2c per connection, so gRPC clients reach
    // this route over the same port as the HTTP/1.1 JSON-RPC binding. The tonic
    // service body is `tonic::body::BoxBody`; `route_service` unifies it with
    // axum's response body directly, so no body adapter is required here.
    let grpc = crate::a2a::A2aServiceServer::new(
        crate::a2a::grpc::service::BasemindA2aService::new(state.clone()),
    );

    // The fallible middleware (timeout / load-shed / concurrency limit) produces
    // a `BoxError`; axum's final service must be `Infallible`, so `HandleErrorLayer`
    // converts those errors into a `StatusCode` response. It must wrap the layers
    // that can error, so it sits outermost inside the fallible segment.
    let middleware = ServiceBuilder::new()
        .layer(SetRequestIdLayer::x_request_id(MakeRequestUuid))
        .layer(TraceLayer::new_for_http())
        // Bearer auth runs immediately after request-id/trace and BEFORE the
        // concurrency-limit/load-shed/timeout layers, so unauthenticated requests
        // are rejected before they consume a concurrency slot. It covers the
        // JSON-RPC and gRPC routes alike (shared listener) and lets the public
        // agent card through; it is a no-op when auth is disabled.
        .layer(from_fn_with_state(state.clone(), require_bearer))
        .layer(CorsLayer::permissive())
        .layer(HandleErrorLayer::new(handle_middleware_error))
        .layer(LoadShedLayer::new())
        .layer(ConcurrencyLimitLayer::new(MAX_CONCURRENT_REQUESTS))
        .layer(TimeoutLayer::new(Duration::from_secs(REQUEST_TIMEOUT_SECS)))
        .layer(PropagateRequestIdLayer::x_request_id());

    Router::new()
        .route(
            "/",
            post(jsonrpc_handler).layer(DefaultBodyLimit::max(MAX_REQUEST_BODY_BYTES)),
        )
        .route(AGENT_CARD_PATH, get(agent_card_handler))
        .route_service(GRPC_SERVICE_PATH, grpc)
        .layer(middleware)
        .with_state(state)
}

/// Map a tower middleware error onto an HTTP status code. Load-shed rejections
/// become `503`, timeouts `408`, anything else `500`.
async fn handle_middleware_error(err: tower::BoxError) -> StatusCode {
    if err.is::<tower::load_shed::error::Overloaded>() {
        StatusCode::SERVICE_UNAVAILABLE
    } else if err.is::<tower::timeout::error::Elapsed>() {
        StatusCode::REQUEST_TIMEOUT
    } else {
        StatusCode::INTERNAL_SERVER_ERROR
    }
}

/// Grace period granted to in-flight connections after shutdown is signalled on
/// the TLS path before they are forcibly dropped.
const TLS_SHUTDOWN_GRACE: Duration = Duration::from_secs(REQUEST_TIMEOUT_SECS);

/// Bind `addr` and serve the A2A app until `cancel` fires, then drain gracefully.
///
/// When `tls` is `None` the plaintext path is used verbatim (`axum::serve`,
/// which auto-negotiates HTTP/1.1 + HTTP/2 h2c — gRPC depends on the h2c
/// upgrade). When `tls` is `Some`, [`serve_tls`] terminates TLS via rustls with
/// ALPN `["h2", "http/1.1"]`.
pub(crate) async fn serve(
    state: A2aState,
    addr: SocketAddr,
    cancel: CancellationToken,
    tls: Option<crate::a2a::TlsPaths>,
) -> std::io::Result<()> {
    // Spawn the outbound webhook delivery worker before serving. It subscribes to
    // the message bus and POSTs task-lifecycle events to registered push-notification
    // webhooks. Tied to the same `cancel` token, so it drains when the server does;
    // no explicit abort is needed. `state` is cloned so it remains usable below.
    let _worker = crate::a2a::core::webhook::spawn_delivery_worker(state.clone(), cancel.clone());

    match tls {
        Some(tls) => serve_tls(state, addr, cancel, tls).await,
        None => {
            let listener = tokio::net::TcpListener::bind(addr).await?;
            let bound = listener.local_addr()?;
            tracing::info!(address = %bound, tls = false, "A2A HTTP server listening");

            axum::serve(listener, build_router(state))
                .with_graceful_shutdown(async move { cancel.cancelled().await })
                .await
        }
    }
}

/// Serve the A2A app over TLS, terminating with rustls and negotiating HTTP/2
/// vs HTTP/1.1 via ALPN so gRPC-over-TLS works.
///
/// Graceful shutdown is wired through an [`axum_server::Handle`]: a task awaits
/// `cancel` and then calls [`Handle::graceful_shutdown`] with a bounded grace
/// period, mirroring the plaintext path's `with_graceful_shutdown` semantics.
///
/// Never logs key material — only the bound address and the cert/key *paths*.
async fn serve_tls(
    state: A2aState,
    addr: SocketAddr,
    cancel: CancellationToken,
    tls: crate::a2a::TlsPaths,
) -> std::io::Result<()> {
    // Both the aws-lc-rs and ring rustls providers are present in the dependency
    // tree, so the process-default crypto provider is ambiguous and building a
    // `ServerConfig` would panic. Install aws-lc-rs explicitly (idempotent: a
    // prior install by another component is fine, hence the discarded result).
    let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();

    // `RustlsConfig::from_pem_file` builds a `ServerConfig` whose `alpn_protocols`
    // is `["h2", "http/1.1"]`, which is exactly what gRPC-over-TLS needs.
    let config = axum_server::tls_rustls::RustlsConfig::from_pem_file(&tls.cert, &tls.key)
        .await
        .map_err(|err| std::io::Error::new(err.kind(), format!("loading TLS cert/key: {err}")))?;

    let handle = axum_server::Handle::new();
    // Bridge the CancellationToken to axum_server's graceful shutdown.
    let shutdown_handle = handle.clone();
    let shutdown_cancel = cancel.clone();
    let shutdown_task = tokio::spawn(async move {
        shutdown_cancel.cancelled().await;
        shutdown_handle.graceful_shutdown(Some(TLS_SHUTDOWN_GRACE));
    });

    tracing::info!(
        address = %addr,
        tls = true,
        cert = %tls.cert.display(),
        key = %tls.key.display(),
        "A2A HTTPS server listening",
    );

    let result = axum_server::bind_rustls(addr, config)
        .handle(handle)
        .serve(build_router(state).into_make_service())
        .await;

    // If serve returned for a reason OTHER than cancellation (bind/IO error), the
    // bridge task is still parked on `cancelled()`; abort it so it can't linger
    // until runtime shutdown.
    shutdown_task.abort();
    result
}

#[cfg(test)]
mod tests {
    use super::*;

    use axum::body::{Body, to_bytes};
    use axum::http::Request;
    use serde_json::{Value, json};
    use tower::ServiceExt as _;

    /// Read a response body fully and parse it as JSON.
    async fn json_body(resp: axum::response::Response) -> Value {
        let bytes = to_bytes(resp.into_body(), usize::MAX)
            .await
            .expect("body must read");
        serde_json::from_slice(&bytes).expect("body must be valid JSON")
    }

    /// Build a JSON-RPC POST request against the root route.
    fn jsonrpc_request(payload: Value) -> Request<Body> {
        Request::builder()
            .method("POST")
            .uri("/")
            .header("content-type", "application/json")
            .body(Body::from(payload.to_string()))
            .expect("request must build")
    }

    /// Build a JSON-RPC POST request carrying an `Authorization: Bearer` header.
    fn jsonrpc_request_with_bearer(payload: Value, token: &str) -> Request<Body> {
        Request::builder()
            .method("POST")
            .uri("/")
            .header("content-type", "application/json")
            .header("authorization", format!("Bearer {token}"))
            .body(Body::from(payload.to_string()))
            .expect("request must build")
    }

    /// A minimal valid `message/send` payload.
    fn message_send_payload() -> Value {
        json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "message/send",
            "params": {
                "message": {
                    "messageId": "",
                    "role": "user",
                    "parts": [{"kind": "text", "text": "hi"}]
                }
            }
        })
    }

    /// State with bearer auth enabled for `token`.
    fn authed_state(token: &str) -> A2aState {
        A2aState::default().with_auth_token(Some(std::sync::Arc::from(token)))
    }

    #[tokio::test]
    async fn agent_card_route_serves_basemind_jsonrpc_card() {
        let app = build_router(A2aState::default());
        let req = Request::builder()
            .method("GET")
            .uri(AGENT_CARD_PATH)
            .body(Body::empty())
            .expect("request must build");

        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);

        let body = json_body(resp).await;
        assert_eq!(body["name"], json!("basemind"));
        assert_eq!(body["preferredTransport"], json!("JSONRPC"));
    }

    #[tokio::test]
    async fn extended_card_method_returns_basemind_result() {
        let app = build_router(A2aState::default());
        let req = jsonrpc_request(json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "agent/getAuthenticatedExtendedCard",
            "params": {}
        }));

        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);

        let body = json_body(resp).await;
        assert_eq!(body["result"]["name"], json!("basemind"));
    }

    #[tokio::test]
    async fn unknown_method_returns_method_not_found() {
        let app = build_router(A2aState::default());
        let req = jsonrpc_request(json!({
            "jsonrpc": "2.0",
            "id": 2,
            "method": "does/not-exist",
            "params": {}
        }));

        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);

        let body = json_body(resp).await;
        assert_eq!(body["error"]["code"], json!(-32601));
    }

    #[tokio::test]
    async fn message_send_returns_task_result() {
        let app = build_router(A2aState::default());
        let req = jsonrpc_request(json!({
            "jsonrpc": "2.0",
            "id": 3,
            "method": "message/send",
            "params": {
                "message": {
                    "messageId": "",
                    "role": "user",
                    "parts": [{"kind": "text", "text": "do something"}]
                }
            }
        }));

        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);

        let body = json_body(resp).await;
        assert_eq!(body["result"]["kind"], json!("task"));
    }

    #[tokio::test]
    async fn auth_rejects_request_without_token() {
        let app = build_router(authed_state("secret-token"));
        let resp = app
            .oneshot(jsonrpc_request(message_send_payload()))
            .await
            .expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        assert_eq!(
            resp.headers()
                .get("www-authenticate")
                .and_then(|v| v.to_str().ok()),
            Some("Bearer"),
        );
    }

    #[tokio::test]
    async fn auth_rejects_request_with_wrong_token() {
        let app = build_router(authed_state("secret-token"));
        let resp = app
            .oneshot(jsonrpc_request_with_bearer(message_send_payload(), "nope"))
            .await
            .expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn auth_allows_request_with_correct_token() {
        let app = build_router(authed_state("secret-token"));
        let resp = app
            .oneshot(jsonrpc_request_with_bearer(
                message_send_payload(),
                "secret-token",
            ))
            .await
            .expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);
        let body = json_body(resp).await;
        assert_eq!(body["result"]["kind"], json!("task"));
    }

    #[tokio::test]
    async fn agent_card_is_public_even_when_auth_enabled() {
        let app = build_router(authed_state("secret-token"));
        let req = Request::builder()
            .method("GET")
            .uri(AGENT_CARD_PATH)
            .body(Body::empty())
            .expect("request must build");
        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);
        let body = json_body(resp).await;
        // Auth-on card advertises the bearer security scheme.
        assert_eq!(body["securitySchemes"]["bearer"]["scheme"], json!("bearer"));
    }

    #[tokio::test]
    async fn malformed_json_returns_parse_error() {
        let app = build_router(A2aState::default());
        let req = Request::builder()
            .method("POST")
            .uri("/")
            .header("content-type", "application/json")
            .body(Body::from("{ not json"))
            .expect("request must build");
        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);
        let body = json_body(resp).await;
        assert_eq!(body["error"]["code"], json!(-32700));
    }

    #[tokio::test]
    async fn wrong_jsonrpc_version_returns_invalid_request() {
        let app = build_router(A2aState::default());
        let req = jsonrpc_request(json!({
            "jsonrpc": "1.0",
            "id": 7,
            "method": "message/send",
            "params": {}
        }));
        let resp = app.oneshot(req).await.expect("oneshot must succeed");
        assert_eq!(resp.status(), StatusCode::OK);
        let body = json_body(resp).await;
        assert_eq!(body["error"]["code"], json!(-32600));
        assert_eq!(body["id"], json!(7));
    }

    // --- TLS path ---------------------------------------------------------

    /// Test-only certificate verifier that trusts any server certificate.
    ///
    /// This lives in `#[cfg(test)]` and is used ONLY by the in-test TLS client so
    /// it can connect to the self-signed server. Production code never weakens
    /// verification; the server side performs no client-cert checks either way.
    #[derive(Debug)]
    struct TrustAnyServerCert;

    impl tokio_rustls::rustls::client::danger::ServerCertVerifier for TrustAnyServerCert {
        fn verify_server_cert(
            &self,
            _end_entity: &tokio_rustls::rustls::pki_types::CertificateDer<'_>,
            _intermediates: &[tokio_rustls::rustls::pki_types::CertificateDer<'_>],
            _server_name: &tokio_rustls::rustls::pki_types::ServerName<'_>,
            _ocsp_response: &[u8],
            _now: tokio_rustls::rustls::pki_types::UnixTime,
        ) -> Result<
            tokio_rustls::rustls::client::danger::ServerCertVerified,
            tokio_rustls::rustls::Error,
        > {
            Ok(tokio_rustls::rustls::client::danger::ServerCertVerified::assertion())
        }

        fn verify_tls12_signature(
            &self,
            _message: &[u8],
            _cert: &tokio_rustls::rustls::pki_types::CertificateDer<'_>,
            _dss: &tokio_rustls::rustls::DigitallySignedStruct,
        ) -> Result<
            tokio_rustls::rustls::client::danger::HandshakeSignatureValid,
            tokio_rustls::rustls::Error,
        > {
            Ok(tokio_rustls::rustls::client::danger::HandshakeSignatureValid::assertion())
        }

        fn verify_tls13_signature(
            &self,
            _message: &[u8],
            _cert: &tokio_rustls::rustls::pki_types::CertificateDer<'_>,
            _dss: &tokio_rustls::rustls::DigitallySignedStruct,
        ) -> Result<
            tokio_rustls::rustls::client::danger::HandshakeSignatureValid,
            tokio_rustls::rustls::Error,
        > {
            Ok(tokio_rustls::rustls::client::danger::HandshakeSignatureValid::assertion())
        }

        fn supported_verify_schemes(&self) -> Vec<tokio_rustls::rustls::SignatureScheme> {
            tokio_rustls::rustls::crypto::aws_lc_rs::default_provider()
                .signature_verification_algorithms
                .supported_schemes()
        }
    }

    /// End-to-end TLS handshake: start `serve_tls` with a self-signed cert,
    /// connect over real TLS with a permissive client, and assert the public
    /// agent card returns `200 OK` over HTTPS. Exercises the full B4.3 path
    /// (cert load + ALPN + bind) that the validation unit tests cannot.
    #[tokio::test]
    async fn serve_tls_serves_agent_card_over_https() {
        use std::io::Write as _;
        use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _};

        // Self-signed cert/key via rcgen (no committed secrets).
        let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()])
            .expect("generate self-signed cert");
        let mut cert_file = tempfile::NamedTempFile::new().expect("cert temp file");
        cert_file
            .write_all(cert.cert.pem().as_bytes())
            .expect("write cert pem");
        cert_file.flush().expect("flush cert");
        let mut key_file = tempfile::NamedTempFile::new().expect("key temp file");
        key_file
            .write_all(cert.key_pair.serialize_pem().as_bytes())
            .expect("write key pem");
        key_file.flush().expect("flush key");

        let tls = crate::a2a::resolve_tls_config(Some(cert_file.path()), Some(key_file.path()))
            .expect("config must validate")
            .expect("both supplied yields Some");

        // Bind an ephemeral loopback port; reuse it for the server.
        let probe = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("probe bind");
        let addr = probe.local_addr().expect("probe addr");
        drop(probe);

        let cancel = CancellationToken::new();
        let server_cancel = cancel.clone();
        let server =
            tokio::spawn(
                async move { serve_tls(A2aState::default(), addr, server_cancel, tls).await },
            );

        // Build a permissive TLS client config with HTTP/1.1 ALPN so the request
        // is a plain HTTP/1.1 GET.
        let _ = tokio_rustls::rustls::crypto::aws_lc_rs::default_provider().install_default();
        let mut client_config = tokio_rustls::rustls::ClientConfig::builder()
            .dangerous()
            .with_custom_certificate_verifier(std::sync::Arc::new(TrustAnyServerCert))
            .with_no_client_auth();
        client_config.alpn_protocols = vec![b"http/1.1".to_vec()];
        let connector = tokio_rustls::TlsConnector::from(std::sync::Arc::new(client_config));
        let server_name = tokio_rustls::rustls::pki_types::ServerName::try_from("localhost")
            .expect("server name");

        // Retry the connect until the server has bound (graceful startup race).
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        let tcp = loop {
            match tokio::net::TcpStream::connect(addr).await {
                Ok(stream) => break stream,
                Err(_) if std::time::Instant::now() < deadline => {
                    tokio::time::sleep(Duration::from_millis(25)).await;
                }
                Err(err) => panic!("server never accepted TLS connections: {err}"),
            }
        };
        let mut tls_stream = connector
            .connect(server_name, tcp)
            .await
            .expect("TLS handshake must succeed");

        let request = format!(
            "GET {AGENT_CARD_PATH} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"
        );
        tls_stream
            .write_all(request.as_bytes())
            .await
            .expect("write request over TLS");
        tls_stream.flush().await.expect("flush TLS request");

        let mut raw = Vec::new();
        tls_stream
            .read_to_end(&mut raw)
            .await
            .expect("read TLS response");
        let text = String::from_utf8_lossy(&raw);
        let (head, body) = text.split_once("\r\n\r\n").unwrap_or((text.as_ref(), ""));
        assert!(
            head.starts_with("HTTP/1.1 200"),
            "agent card must return 200 over TLS, got head: {head}"
        );
        assert!(
            body.contains("\"basemind\""),
            "agent card body must name basemind over TLS: {body}"
        );

        cancel.cancel();
        let _ = server.await;
    }
}