adk-gateway 1.0.0

Multi-channel AI gateway for adk-rust agents — Telegram, Slack, WhatsApp, Discord, Matrix + control panel
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
//! AWP (Agentic Web Protocol) integration for adk-gateway.
//!
//! Uses `AwpState::builder()` from adk-awp for clean state construction,
//! `FileConsentService` for durable consent records, and `awp_routes()`
//! for the standard 7 AWP endpoints. Adds gateway-specific consent HTTP
//! endpoints and health reporting tied to LLM availability.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use adk_awp::{AwpState, BusinessContextLoader, FileConsentService};

// Re-export so gateway_state.rs can reference the type.
pub use adk_awp::AwpState as AwpGatewayState;

// ── Configuration ──────────────────────────────────────────────────

/// Configuration for AWP protocol support within the gateway.
#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(default)]
pub struct AwpConfig {
    /// Enable AWP protocol endpoints. Default: false (opt-in).
    pub enabled: bool,
    /// Path to business.toml relative to the gateway config file directory.
    pub business_toml: PathBuf,
    /// Whether to watch business.toml for hot-reload changes.
    pub hot_reload: bool,
    /// Path to consent storage file. Default: "data/consent.json".
    pub consent_file: PathBuf,
}

impl Default for AwpConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            business_toml: PathBuf::from("business.toml"),
            hot_reload: true,
            consent_file: PathBuf::from("data/consent.json"),
        }
    }
}

// ── Build ──────────────────────────────────────────────────────────

/// Build the AWP shared state from configuration.
///
/// Returns `None` if AWP is disabled or business.toml is not found.
pub async fn build_awp_state(
    awp_config: &AwpConfig,
    config_dir: &Path,
) -> anyhow::Result<Option<AwpState>> {
    if !awp_config.enabled {
        tracing::info!("AWP protocol disabled");
        return Ok(None);
    }

    let toml_path = if awp_config.business_toml.is_relative() {
        config_dir.join(&awp_config.business_toml)
    } else {
        awp_config.business_toml.clone()
    };

    if !toml_path.exists() {
        tracing::warn!(
            path = %toml_path.display(),
            "business.toml not found — AWP endpoints will not be available"
        );
        return Ok(None);
    }

    let loader = BusinessContextLoader::from_file(&toml_path)
        .map_err(|e| anyhow::anyhow!("failed to load business.toml: {e}"))?;

    tracing::info!(
        path = %toml_path.display(),
        site = %loader.load().site_name,
        capabilities = loader.load().capabilities.len(),
        "AWP business context loaded"
    );

    if awp_config.hot_reload {
        loader
            .watch(toml_path.clone())
            .await
            .map_err(|e| anyhow::anyhow!("failed to start business.toml watcher: {e}"))?;
        tracing::info!("AWP business.toml hot-reload enabled");
    }

    // Use FileConsentService for durable consent records (GDPR/KPA compliance)
    let consent_path = if awp_config.consent_file.is_relative() {
        config_dir.join(&awp_config.consent_file)
    } else {
        awp_config.consent_file.clone()
    };

    let consent_service: Arc<dyn adk_awp::ConsentService> =
        match FileConsentService::new(&consent_path) {
            Ok(svc) => {
                tracing::info!(path = %consent_path.display(), "AWP consent storage initialized");
                Arc::new(svc)
            }
            Err(e) => {
                tracing::warn!(
                    path = %consent_path.display(),
                    error = %e,
                    "failed to initialize file consent service, falling back to in-memory"
                );
                Arc::new(adk_awp::InMemoryConsentService::new())
            }
        };

    let state = AwpState::builder(loader.context_ref())
        .consent_service(consent_service)
        .build();

    tracing::info!("AWP protocol state initialized");
    Ok(Some(state))
}

// ── Route merging ──────────────────────────────────────────────────

/// Merge AWP protocol routes into an existing axum router.
///
/// Adds the 7 standard AWP endpoints (discovery, manifest, health, a2a,
/// events) plus gateway-specific consent endpoints. Version negotiation
/// middleware is applied automatically by `awp_routes()`.
pub fn merge_awp_routes(router: axum::Router, awp_state: Option<AwpState>) -> axum::Router {
    let Some(state) = awp_state else {
        return router;
    };

    // Standard AWP endpoints from adk-awp (with version negotiation middleware)
    let awp_router = adk_awp::awp_routes(state.clone());

    // Gateway-specific consent endpoints
    let consent_routes = axum::Router::new()
        .route("/awp/consent", axum::routing::post(handle_consent_capture))
        .route(
            "/awp/consent/check",
            axum::routing::get(handle_consent_check),
        )
        .route(
            "/awp/consent/revoke",
            axum::routing::post(handle_consent_revoke),
        )
        .with_state(state);

    tracing::info!(
        "AWP endpoints registered: /.well-known/awp.json, /awp/manifest, \
         /awp/health, /awp/a2a, /awp/events/*, /awp/consent/*"
    );

    router.merge(awp_router).merge(consent_routes)
}

// ── Health reporting (called from gateway message processing) ──────

/// Report that the LLM backend is degrading (e.g. high latency).
pub async fn report_degrading(state: &AwpState, reason: &str) {
    if let Err(e) = state.health.report_degrading(reason).await {
        tracing::debug!(error = %e, "health transition to degrading rejected");
    }
}

/// Report that the LLM backend has recovered.
pub async fn report_healthy(state: &AwpState) {
    if let Err(e) = state.health.report_healthy().await {
        tracing::debug!(error = %e, "health transition to healthy rejected");
    }
}

// ── Consent handlers ───────────────────────────────────────────────

#[derive(serde::Deserialize)]
struct ConsentBody {
    subject: String,
    purpose: String,
}

async fn handle_consent_capture(
    axum::extract::State(state): axum::extract::State<AwpState>,
    axum::Json(body): axum::Json<ConsentBody>,
) -> (axum::http::StatusCode, axum::Json<serde_json::Value>) {
    if body.subject.is_empty() || body.purpose.is_empty() {
        return (
            axum::http::StatusCode::BAD_REQUEST,
            axum::Json(serde_json::json!({ "error": "subject and purpose are required" })),
        );
    }
    match state
        .consent_service
        .capture_consent(&body.subject, &body.purpose)
        .await
    {
        Ok(()) => (
            axum::http::StatusCode::CREATED,
            axum::Json(serde_json::json!({
                "status": "captured",
                "subject": body.subject,
                "purpose": body.purpose,
            })),
        ),
        Err(e) => (
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            axum::Json(serde_json::json!({ "error": e.to_string() })),
        ),
    }
}

#[derive(serde::Deserialize)]
struct ConsentCheckQuery {
    subject: String,
    purpose: String,
}

async fn handle_consent_check(
    axum::extract::State(state): axum::extract::State<AwpState>,
    axum::extract::Query(params): axum::extract::Query<ConsentCheckQuery>,
) -> axum::Json<serde_json::Value> {
    let consented = state
        .consent_service
        .check_consent(&params.subject, &params.purpose)
        .await
        .unwrap_or(false);
    axum::Json(serde_json::json!({
        "subject": params.subject,
        "purpose": params.purpose,
        "consented": consented,
    }))
}

async fn handle_consent_revoke(
    axum::extract::State(state): axum::extract::State<AwpState>,
    axum::Json(body): axum::Json<ConsentBody>,
) -> (axum::http::StatusCode, axum::Json<serde_json::Value>) {
    match state
        .consent_service
        .revoke_consent(&body.subject, &body.purpose)
        .await
    {
        Ok(()) => (
            axum::http::StatusCode::OK,
            axum::Json(serde_json::json!({
                "status": "revoked",
                "subject": body.subject,
                "purpose": body.purpose,
            })),
        ),
        Err(e) => (
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            axum::Json(serde_json::json!({ "error": e.to_string() })),
        ),
    }
}

// ── Tests ──────────────────────────────────────────────────────────

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

    const SAMPLE_TOML: &str = r#"
site_name = "Test Gateway"
site_description = "Test"
domain = "localhost"

[[capabilities]]
name = "health"
description = "Health check"
endpoint = "/health"
method = "GET"
access_level = "anonymous"

[[policies]]
name = "privacy"
description = "Privacy policy"
policy_type = "privacy"
"#;

    #[test]
    fn test_default_config() {
        let cfg = AwpConfig::default();
        assert!(!cfg.enabled);
        assert_eq!(cfg.business_toml, PathBuf::from("business.toml"));
        assert!(cfg.hot_reload);
        assert_eq!(cfg.consent_file, PathBuf::from("data/consent.json"));
    }

    #[test]
    fn test_config_serde_round_trip() {
        let cfg = AwpConfig {
            enabled: true,
            business_toml: PathBuf::from("custom/path.toml"),
            hot_reload: false,
            consent_file: PathBuf::from("custom/consent.json"),
        };
        let json = serde_json::to_string(&cfg).unwrap();
        let deserialized: AwpConfig = serde_json::from_str(&json).unwrap();
        assert!(deserialized.enabled);
        assert_eq!(
            deserialized.business_toml,
            PathBuf::from("custom/path.toml")
        );
        assert!(!deserialized.hot_reload);
        assert_eq!(
            deserialized.consent_file,
            PathBuf::from("custom/consent.json")
        );
    }

    #[tokio::test]
    async fn test_build_disabled() {
        let cfg = AwpConfig {
            enabled: false,
            ..Default::default()
        };
        assert!(build_awp_state(&cfg, Path::new("."))
            .await
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn test_build_missing_toml() {
        let cfg = AwpConfig {
            enabled: true,
            business_toml: PathBuf::from("nonexistent.toml"),
            ..Default::default()
        };
        assert!(build_awp_state(&cfg, Path::new("."))
            .await
            .unwrap()
            .is_none());
    }

    #[tokio::test]
    async fn test_build_valid_with_file_consent() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("business.toml"), SAMPLE_TOML).unwrap();

        let cfg = AwpConfig {
            enabled: true,
            hot_reload: false,
            consent_file: PathBuf::from("consent.json"),
            ..Default::default()
        };
        let state = build_awp_state(&cfg, dir.path()).await.unwrap().unwrap();
        assert_eq!(state.business_context.load().site_name, "Test Gateway");
    }

    #[tokio::test]
    async fn test_merge_none_is_noop() {
        let router: axum::Router = axum::Router::new();
        let _ = merge_awp_routes(router, None);
    }

    #[tokio::test]
    async fn test_merge_with_state() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("business.toml"), SAMPLE_TOML).unwrap();

        let cfg = AwpConfig {
            enabled: true,
            hot_reload: false,
            consent_file: PathBuf::from("consent.json"),
            ..Default::default()
        };
        let state = build_awp_state(&cfg, dir.path()).await.unwrap();

        let router: axum::Router = axum::Router::new();
        let merged = merge_awp_routes(router, state);

        use axum::body::Body;
        use tower::ServiceExt;
        let req = axum::http::Request::builder()
            .uri("/.well-known/awp.json")
            .body(Body::empty())
            .unwrap();
        let resp = merged.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
    }

    #[tokio::test]
    async fn test_health_reporting() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("business.toml"), SAMPLE_TOML).unwrap();

        let cfg = AwpConfig {
            enabled: true,
            hot_reload: false,
            consent_file: PathBuf::from("consent.json"),
            ..Default::default()
        };
        let state = build_awp_state(&cfg, dir.path()).await.unwrap().unwrap();

        let snap = state.health.snapshot().await;
        assert_eq!(snap.state, adk_awp::HealthState::Healthy);

        report_degrading(&state, "high latency").await;
        let snap = state.health.snapshot().await;
        assert_eq!(snap.state, adk_awp::HealthState::Degrading);

        report_healthy(&state).await;
        let snap = state.health.snapshot().await;
        assert_eq!(snap.state, adk_awp::HealthState::Healthy);
    }
}