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
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! Consolidated JSON API endpoints for the control panel.
//!
//! All `/ui/api/*` handlers live here. Existing handlers from submodules
//! are re-exported, and new endpoints (auth check, login, logout, session
//! terminate, config save, AWP, integrations) are defined below.

use std::sync::Arc;
use std::time::Instant;

use axum::extract::{Path, State};
use axum::http::{header, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use subtle::ConstantTimeEq;

use super::auth::UiSession;
use super::ControlPanelState;
use crate::config::AuthMode;

/// Cookie name for UI sessions.
const COOKIE_NAME: &str = "adk_ui_session";

// ── Re-exports from existing submodules ────────────────────────────
// These keep backward compatibility — existing JSON handlers stay where
// they are and are wired into routes from here.

pub(crate) use super::agent_setup::agent_get;
pub(crate) use super::agent_setup::agent_save;
pub(crate) use super::agents::{
    api_agents_configure, api_agents_create, api_agents_delete, api_agents_list, api_agents_logs,
    api_agents_start, api_agents_stop,
};
pub(crate) use super::channels::channels_get;
pub(crate) use super::channels::channels_save;
pub(crate) use super::channels::telegram_probe;
pub(crate) use super::config_page::config_json;
pub(crate) use super::dashboard::dashboard_json;
pub(crate) use super::logs::logs_json;
pub(crate) use super::memory::{memory_entities, memory_load, memory_save};
pub(crate) use super::sessions::sessions_json;
pub(crate) use super::settings::session_status;
pub(crate) use super::settings::settings_save;

// ── Auth check ─────────────────────────────────────────────────────

/// GET /ui/api/auth/check — returns current authentication status.
pub async fn auth_check(
    State(state): State<Arc<ControlPanelState>>,
    request: axum::extract::Request,
) -> Json<serde_json::Value> {
    let config = state.config.load();

    let mode = config
        .auth
        .as_ref()
        .map(|a| match a.mode {
            AuthMode::Password => "password",
            AuthMode::Token => "token",
            AuthMode::None => "none",
        })
        .unwrap_or("none");

    let auth_required = config.auth.as_ref().is_some_and(|auth| {
        matches!(auth.mode, AuthMode::Password | AuthMode::Token)
            && (auth.password.is_some() || auth.token.is_some())
    });

    let authenticated = if !auth_required {
        true
    } else {
        let cookie_header = request
            .headers()
            .get(header::COOKIE)
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        extract_cookie(cookie_header, COOKIE_NAME)
            .map(|token| state.ui_sessions.contains_key(token))
            .unwrap_or(false)
    };

    Json(serde_json::json!({
        "authenticated": authenticated,
        "mode": mode,
    }))
}

// ── JSON Login ─────────────────────────────────────────────────────

#[derive(serde::Deserialize)]
pub struct LoginPayload {
    password: String,
}

/// POST /ui/api/login — JSON login, validates password, sets session cookie.
pub async fn api_login(
    State(state): State<Arc<ControlPanelState>>,
    Json(payload): Json<LoginPayload>,
) -> Response {
    let config = state.config.load();

    let expected = config
        .auth
        .as_ref()
        .and_then(|auth| match auth.mode {
            AuthMode::Password => auth.password.as_deref(),
            AuthMode::Token => auth.token.as_deref(),
            AuthMode::None => None,
        })
        .unwrap_or("");

    // Constant-time comparison to prevent timing attacks
    let provided = payload.password.as_bytes();
    let expected_bytes = expected.as_bytes();

    let valid = if provided.len() == expected_bytes.len() {
        provided.ct_eq(expected_bytes).into()
    } else {
        false
    };

    if !valid || expected.is_empty() {
        return (
            StatusCode::UNAUTHORIZED,
            Json(serde_json::json!({
                "ok": false,
                "message": "Invalid credentials"
            })),
        )
            .into_response();
    }

    // Generate session token
    use rand::Rng;
    let token: String = rand::thread_rng()
        .sample_iter(&rand::distributions::Alphanumeric)
        .take(48)
        .map(char::from)
        .collect();

    // Store session
    state.ui_sessions.insert(
        token.clone(),
        UiSession {
            token: token.clone(),
            created_at: Instant::now(),
        },
    );

    // Set cookie and return success JSON
    let cookie = format!(
        "{}={}; HttpOnly; SameSite=Strict; Path=/; Max-Age=86400",
        COOKIE_NAME, token
    );

    let body = serde_json::json!({
        "ok": true,
        "message": "Login successful"
    });

    Response::builder()
        .status(StatusCode::OK)
        .header(header::SET_COOKIE, cookie)
        .header(header::CONTENT_TYPE, "application/json")
        .body(axum::body::Body::from(
            serde_json::to_string(&body).unwrap(),
        ))
        .unwrap()
}

// ── JSON Logout ────────────────────────────────────────────────────

/// POST /ui/api/logout — clears session cookie, removes from ui_sessions.
pub async fn api_logout(
    State(state): State<Arc<ControlPanelState>>,
    request: axum::extract::Request,
) -> Response {
    let cookie_header = request
        .headers()
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    if let Some(token) = extract_cookie(cookie_header, COOKIE_NAME) {
        state.ui_sessions.remove(token);
    }

    let clear_cookie = format!(
        "{}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0",
        COOKIE_NAME
    );

    let body = serde_json::json!({
        "ok": true,
        "message": "Logged out"
    });

    Response::builder()
        .status(StatusCode::OK)
        .header(header::SET_COOKIE, clear_cookie)
        .header(header::CONTENT_TYPE, "application/json")
        .body(axum::body::Body::from(
            serde_json::to_string(&body).unwrap(),
        ))
        .unwrap()
}

// ── Session terminate ──────────────────────────────────────────────

/// POST /ui/api/sessions/{id}/terminate — end a session via session_bridge.
pub async fn session_terminate(
    State(state): State<Arc<ControlPanelState>>,
    Path(session_id): Path<String>,
) -> Json<serde_json::Value> {
    // Try to remove the session from the control panel's session list
    let mut found = false;
    if let Ok(mut sessions) = state.sessions.write() {
        let before = sessions.len();
        sessions.retain(|s| s.session_id != session_id);
        found = sessions.len() < before;
    }

    if found {
        tracing::info!(session_id = %session_id, "session terminated via UI");
        Json(serde_json::json!({
            "ok": true,
            "message": format!("Session '{}' terminated.", session_id)
        }))
    } else {
        Json(serde_json::json!({
            "ok": false,
            "message": format!("Session '{}' not found.", session_id)
        }))
    }
}

// ── Config save ────────────────────────────────────────────────────

#[derive(serde::Deserialize)]
pub struct ConfigSavePayload {
    content: String,
}

/// POST /ui/api/config — validate into GatewayConfig, run semantic validation, then write to disk.
pub async fn config_save(
    State(state): State<Arc<ControlPanelState>>,
    Json(payload): Json<ConfigSavePayload>,
) -> Json<serde_json::Value> {
    let config_path = match &state.config_path {
        Some(p) => p.clone(),
        None => {
            return Json(serde_json::json!({
                "ok": false,
                "message": "Config file path not configured"
            }));
        }
    };

    // Step 1: Parse into GatewayConfig (not just serde_json::Value)
    let new_config: crate::config::GatewayConfig = match serde_json::from_str(&payload.content) {
        Ok(cfg) => cfg,
        Err(_) => {
            // Try JSON5 fallback
            match json5::from_str(&payload.content) {
                Ok(cfg) => cfg,
                Err(e) => {
                    return Json(serde_json::json!({
                        "ok": false,
                        "message": format!("Invalid configuration: {e}")
                    }));
                }
            }
        }
    };

    // Step 2: Semantic validation
    if let Err(e) = crate::config_watcher::validate_config(&new_config) {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Configuration validation failed: {e}")
        }));
    }

    // Step 3: Serialize to normalized JSON for consistent formatting
    let output = match serde_json::to_string_pretty(&new_config) {
        Ok(s) => s,
        Err(e) => {
            return Json(serde_json::json!({
                "ok": false,
                "message": format!("Failed to serialize config: {e}")
            }));
        }
    };

    // Step 4: Write to disk
    if let Err(e) = std::fs::write(&config_path, &output) {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Failed to write config: {e}")
        }));
    }

    // Step 5: Update in-memory config atomically (only after successful write)
    state.config.store(std::sync::Arc::new(new_config));

    tracing::info!("config saved via UI to {}", config_path.display());

    Json(serde_json::json!({
        "ok": true,
        "message": "Configuration validated, saved, and reloaded."
    }))
}

// ── AWP endpoints ──────────────────────────────────────────────────

/// GET /ui/api/awp — AWP summary: health state, capability count, subscription count, consent count, site info.
pub async fn awp_summary(
    State(state): State<Arc<ControlPanelState>>,
) -> (StatusCode, Json<serde_json::Value>) {
    let awp = match &state.awp_state {
        Some(s) => s,
        None => {
            return (
                StatusCode::OK,
                Json(serde_json::json!({
                    "ok": true,
                    "data": null,
                    "message": "AWP is not enabled"
                })),
            );
        }
    };

    let health_snap = awp.health.snapshot().await;
    let ctx = awp.business_context.load();

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "ok": true,
            "data": {
                "health": {
                    "state": format!("{:?}", health_snap.state),
                    "message": health_snap.message,
                    "timestamp": health_snap.timestamp.to_rfc3339(),
                },
                "site": {
                    "name": ctx.site_name,
                    "description": ctx.site_description,
                    "domain": ctx.domain,
                },
                "capability_count": ctx.capabilities.len(),
            }
        })),
    )
}

/// GET /ui/api/awp/health — AWP health state, message, timestamp.
pub async fn awp_health(
    State(state): State<Arc<ControlPanelState>>,
) -> (StatusCode, Json<serde_json::Value>) {
    let awp = match &state.awp_state {
        Some(s) => s,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "ok": false,
                    "message": "AWP is not enabled"
                })),
            );
        }
    };

    let snap = awp.health.snapshot().await;

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "ok": true,
            "data": {
                "state": format!("{:?}", snap.state),
                "message": snap.message,
                "timestamp": snap.timestamp.to_rfc3339(),
            }
        })),
    )
}

/// GET /ui/api/awp/capabilities — array of capabilities from business context.
pub async fn awp_capabilities(
    State(state): State<Arc<ControlPanelState>>,
) -> (StatusCode, Json<serde_json::Value>) {
    let awp = match &state.awp_state {
        Some(s) => s,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "ok": false,
                    "message": "AWP is not enabled"
                })),
            );
        }
    };

    let ctx = awp.business_context.load();
    let capabilities: Vec<serde_json::Value> = ctx
        .capabilities
        .iter()
        .map(|cap| {
            serde_json::json!({
                "name": cap.name,
                "description": cap.description,
                "endpoint": cap.endpoint,
                "method": cap.method,
                "access_level": format!("{:?}", cap.access_level),
            })
        })
        .collect();

    (
        StatusCode::OK,
        Json(serde_json::json!({
            "ok": true,
            "data": capabilities
        })),
    )
}

/// GET /ui/api/awp/subscriptions — array of event subscriptions.
/// Note: Subscriptions are managed through the AWP protocol endpoints (/awp/events/*).
/// This endpoint provides a proxy view.
pub async fn awp_subscriptions(
    State(state): State<Arc<ControlPanelState>>,
) -> (StatusCode, Json<serde_json::Value>) {
    let _awp = match &state.awp_state {
        Some(s) => s,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "ok": false,
                    "message": "AWP is not enabled"
                })),
            );
        }
    };

    // Event subscriptions are managed through the AWP protocol routes.
    // This endpoint confirms AWP is active; clients should use /awp/events/subscriptions
    // for full subscription management.
    (
        StatusCode::OK,
        Json(serde_json::json!({
            "ok": true,
            "data": [],
            "message": "Use /awp/events/subscriptions for full subscription management"
        })),
    )
}

/// DELETE /ui/api/awp/subscriptions/{id} — remove subscription.
/// Proxies to the AWP event service.
pub async fn awp_subscription_delete(
    State(state): State<Arc<ControlPanelState>>,
    Path(_sub_id): Path<String>,
) -> (StatusCode, Json<serde_json::Value>) {
    let _awp = match &state.awp_state {
        Some(s) => s,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "ok": false,
                    "message": "AWP is not enabled"
                })),
            );
        }
    };

    // Subscription deletion is handled through the AWP protocol routes.
    // Use DELETE /awp/events/subscriptions/{id} for direct management.
    (
        StatusCode::OK,
        Json(serde_json::json!({
            "ok": true,
            "message": "Use DELETE /awp/events/subscriptions/{id} for subscription removal"
        })),
    )
}

/// GET /ui/api/awp/consent — consent records summary.
pub async fn awp_consent(
    State(state): State<Arc<ControlPanelState>>,
) -> (StatusCode, Json<serde_json::Value>) {
    let _awp = match &state.awp_state {
        Some(s) => s,
        None => {
            return (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "ok": false,
                    "message": "AWP is not enabled"
                })),
            );
        }
    };

    // Consent records are managed through the AWP consent endpoints (/awp/consent/*).
    // This endpoint confirms AWP consent service is active.
    (
        StatusCode::OK,
        Json(serde_json::json!({
            "ok": true,
            "data": [],
            "message": "Use /awp/consent/* endpoints for consent management"
        })),
    )
}

// ── Integrations endpoints ─────────────────────────────────────────

/// GET /ui/api/integrations/mcp — MCP server status from config + mcp_manager.
pub async fn integrations_mcp(
    State(state): State<Arc<ControlPanelState>>,
) -> Json<serde_json::Value> {
    let config = state.config.load();
    let servers: Vec<serde_json::Value> = config
        .mcp_servers
        .iter()
        .map(|srv| {
            let (transport_type, transport_detail) = match &srv.transport {
                crate::mcp::McpTransport::Stdio { command, args, env } => {
                    let detail = serde_json::json!({
                        "command": command,
                        "args": args,
                        "env": env,
                    });
                    ("stdio", detail)
                }
                crate::mcp::McpTransport::Sse { url } => {
                    let detail = serde_json::json!({ "url": url });
                    ("sse", detail)
                }
            };

            let status = state
                .mcp_manager
                .as_ref()
                .and_then(|mgr| mgr.get_status(&srv.server_id))
                .map(|s| format!("{:?}", s))
                .unwrap_or_else(|| {
                    if srv.enabled {
                        "Disconnected".to_string()
                    } else {
                        "Disabled".to_string()
                    }
                });

            let tools = state
                .mcp_manager
                .as_ref()
                .map(|mgr| mgr.discovered_tools(&srv.server_id))
                .unwrap_or_default();

            serde_json::json!({
                "server_id": srv.server_id,
                "transport": transport_type,
                "transport_detail": transport_detail,
                "enabled": srv.enabled,
                "status": status,
                "discovered_tools": tools,
            })
        })
        .collect();

    Json(serde_json::json!({
        "ok": true,
        "data": servers
    }))
}

/// GET /ui/api/integrations/cron — cron job list from cron_scheduler.
pub async fn integrations_cron(
    State(state): State<Arc<ControlPanelState>>,
) -> Json<serde_json::Value> {
    // Merge config-defined jobs with runtime status
    let config = state.config.load();
    let config_jobs = &config.cron.jobs;

    let jobs: Vec<serde_json::Value> = match &state.cron_scheduler {
        Some(scheduler) => {
            let guard = scheduler.lock().await;
            match guard.as_ref() {
                Some(sched) => {
                    sched.list_all_jobs().iter().map(|(job, status)| {
                        // Get last error/skip from task log
                        let last_error = state.task_log.as_ref().and_then(|log| {
                            let logs = log.get_logs(&job.id, 5);
                            logs.iter()
                                .find(|l| l.event_type == "skipped" || l.event_type == "failed")
                                .map(|l| serde_json::json!({
                                    "message": l.message,
                                    "timestamp": l.timestamp,
                                }))
                        });

                        serde_json::json!({
                            "id": job.id,
                            "schedule": job.schedule,
                            "message": job.message,
                            "delivery": job.deliver_to.as_ref().map(|d| serde_json::json!({
                                "channel": d.channel,
                                "target": d.target,
                            })),
                            "status": match status {
                                crate::cron::CronJobStatus::Active => "Active",
                                crate::cron::CronJobStatus::Cancelled => "Cancelled",
                            },
                            "last_error": last_error,
                            "suppress_keyword": job.suppress_keyword,
                        })
                    }).collect()
                }
                None => {
                    // No scheduler running — show config jobs as inactive
                    config_jobs.iter().map(|job| {
                        serde_json::json!({
                            "id": job.id,
                            "schedule": job.schedule,
                            "message": job.message,
                            "delivery": job.deliver_to.as_ref().map(|d| serde_json::json!({
                                "channel": d.channel,
                                "target": d.target,
                            })),
                            "status": "Stopped",
                        })
                    }).collect()
                }
            }
        }
        None => {
            // No scheduler at all — show config jobs
            config_jobs.iter().map(|job| {
                serde_json::json!({
                    "id": job.id,
                    "schedule": job.schedule,
                    "message": job.message,
                    "delivery": job.deliver_to.as_ref().map(|d| serde_json::json!({
                        "channel": d.channel,
                        "target": d.target,
                    })),
                    "status": "Stopped",
                })
            }).collect()
        }
    };

    Json(serde_json::json!({
        "ok": true,
        "data": {
            "jobs": jobs,
            "total": jobs.len(),
        }
    }))
}

/// POST /ui/api/scheduled-tasks — Create a new scheduled task.
pub async fn scheduled_task_create(
    State(state): State<Arc<ControlPanelState>>,
    Json(payload): Json<serde_json::Value>,
) -> Json<serde_json::Value> {
    let id = payload.get("id").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
    let schedule = payload.get("schedule").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
    let message = payload.get("message").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();

    if id.is_empty() || schedule.is_empty() || message.is_empty() {
        return Json(serde_json::json!({
            "ok": false,
            "message": "Fields 'id', 'schedule', and 'message' are required."
        }));
    }

    let delivery = payload.get("delivery").and_then(|d| {
        let channel = d.get("channel")?.as_str()?.to_string();
        let target = d.get("target")?.as_str()?.to_string();
        if channel.is_empty() { return None; }
        Some(crate::config::CronDelivery { channel, target })
    });

    let suppress_keyword = payload.get("suppress_keyword")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());

    let new_job = crate::config::CronJob {
        id: id.clone(),
        schedule,
        message,
        deliver_to: delivery,
        suppress_keyword,
        target: None,
        workspace: None,
    };

    // Persist to config
    let config_path = match &state.config_path {
        Some(p) => p.clone(),
        None => {
            return Json(serde_json::json!({
                "ok": false,
                "message": "Config file path not configured"
            }));
        }
    };

    let mut cfg = state.config.load().as_ref().clone();

    // Check for duplicate ID (in config AND in scheduler)
    if cfg.cron.jobs.iter().any(|j| j.id == id) {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("A scheduled task with ID '{}' already exists.", id)
        }));
    }
    // Also check runtime-only tasks (like heartbeat)
    if let Some(scheduler) = &state.cron_scheduler {
        let guard = scheduler.lock().await;
        if let Some(sched) = guard.as_ref() {
            if sched.is_active(&id) {
                return Json(serde_json::json!({
                    "ok": false,
                    "message": format!("A scheduled task with ID '{}' is already running.", id)
                }));
            }
        }
    }

    cfg.cron.jobs.push(new_job.clone());

    // Write to disk
    let output = match serde_json::to_string_pretty(&cfg) {
        Ok(s) => s,
        Err(e) => {
            return Json(serde_json::json!({
                "ok": false,
                "message": format!("Failed to serialize config: {e}")
            }));
        }
    };

    if let Err(e) = std::fs::write(&config_path, &output) {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Failed to write config: {e}")
        }));
    }

    // Hot-reload: update in-memory config and schedule the job
    state.config.store(std::sync::Arc::new(cfg.clone()));
    if let Some(scheduler) = &state.cron_scheduler {
        let mut guard = scheduler.lock().await;
        if let Some(sched) = guard.as_mut() {
            sched.reconcile(&cfg.cron.jobs);
        }
    }

    tracing::info!(job_id = %id, "scheduled task created via API");

    Json(serde_json::json!({
        "ok": true,
        "message": format!("Scheduled task '{}' created.", id)
    }))
}

/// POST /ui/api/scheduled-tasks/:id/cancel — Cancel a scheduled task.
pub async fn scheduled_task_cancel(
    State(state): State<Arc<ControlPanelState>>,
    axum::extract::Path(task_id): axum::extract::Path<String>,
) -> Json<serde_json::Value> {
    let mut found = false;
    if let Some(scheduler) = &state.cron_scheduler {
        let mut guard = scheduler.lock().await;
        if let Some(sched) = guard.as_mut() {
            if sched.is_active(&task_id) {
                sched.cancel(&task_id);
                found = true;
            }
        }
    }

    if !found {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Task '{}' not found or already paused.", task_id)
        }));
    }

    tracing::info!(job_id = %task_id, "scheduled task cancelled via API");
    Json(serde_json::json!({
        "ok": true,
        "message": format!("Scheduled task '{}' paused.", task_id)
    }))
}

/// POST /ui/api/scheduled-tasks/:id/resume — Resume a cancelled scheduled task.
pub async fn scheduled_task_resume(
    State(state): State<Arc<ControlPanelState>>,
    axum::extract::Path(task_id): axum::extract::Path<String>,
) -> Json<serde_json::Value> {
    // Try to find the job definition: config first, then scheduler, then heartbeat default
    let config = state.config.load();
    let mut job: Option<crate::config::CronJob> = config.cron.jobs.iter().find(|j| j.id == task_id).cloned();

    // If not in config, check the scheduler's tracked jobs
    if job.is_none() {
        if let Some(scheduler) = &state.cron_scheduler {
            let guard = scheduler.lock().await;
            if let Some(sched) = guard.as_ref() {
                job = sched.list_all_jobs().iter()
                    .find(|(j, _)| j.id == task_id)
                    .map(|(j, _)| (*j).clone());
            }
        }
    }

    // If still not found and it's the heartbeat, use the default definition
    if job.is_none() && task_id == "heartbeat" {
        job = Some(crate::config::CronJob {
            id: "heartbeat".to_string(),
            schedule: "@every 1h".to_string(),
            message: "ask:Read HEARTBEAT.md if it exists. Follow it strictly. If nothing needs attention, reply with just HEARTBEAT_OK.".to_string(),
            deliver_to: Some(crate::config::CronDelivery {
                channel: "telegram".to_string(),
                target: "last".to_string(),
            }),
            suppress_keyword: Some("HEARTBEAT_OK".to_string()),
            target: None,
            workspace: None,
        });
    }

    match job {
        Some(job) => {
            if let Some(scheduler) = &state.cron_scheduler {
                let mut guard = scheduler.lock().await;
                if let Some(sched) = guard.as_mut() {
                    if let Err(e) = sched.schedule(job) {
                        return Json(serde_json::json!({
                            "ok": false,
                            "message": format!("Failed to resume: {e}")
                        }));
                    }
                }
            }
            tracing::info!(job_id = %task_id, "scheduled task resumed via API");
            Json(serde_json::json!({
                "ok": true,
                "message": format!("Scheduled task '{}' resumed.", task_id)
            }))
        }
        None => {
            Json(serde_json::json!({
                "ok": false,
                "message": format!("Task '{}' not found.", task_id)
            }))
        }
    }
}

/// DELETE /ui/api/scheduled-tasks/:id — Remove a scheduled task.
/// For config-persisted tasks: removes from config and scheduler.
/// For runtime-only tasks (heartbeat): just cancels from scheduler.
pub async fn scheduled_task_delete(
    State(state): State<Arc<ControlPanelState>>,
    axum::extract::Path(task_id): axum::extract::Path<String>,
) -> Json<serde_json::Value> {
    // Cancel from scheduler first (works for both config and runtime tasks)
    let mut was_in_scheduler = false;
    if let Some(scheduler) = &state.cron_scheduler {
        let mut guard = scheduler.lock().await;
        if let Some(sched) = guard.as_mut() {
            // Check if it exists in the scheduler
            let exists = sched.list_all_jobs().iter().any(|(j, _)| j.id == task_id);
            if exists {
                sched.cancel(&task_id);
                was_in_scheduler = true;
            }
        }
    }

    // Try to remove from config (only for persisted tasks)
    let mut removed_from_config = false;
    if let Some(config_path) = &state.config_path {
        let mut cfg = state.config.load().as_ref().clone();
        let before = cfg.cron.jobs.len();
        cfg.cron.jobs.retain(|j| j.id != task_id);

        if cfg.cron.jobs.len() < before {
            removed_from_config = true;

            // Write to disk
            if let Ok(output) = serde_json::to_string_pretty(&cfg) {
                let _ = std::fs::write(config_path, &output);
            }

            // Hot-reload
            state.config.store(std::sync::Arc::new(cfg.clone()));
            if let Some(scheduler) = &state.cron_scheduler {
                let mut guard = scheduler.lock().await;
                if let Some(sched) = guard.as_mut() {
                    sched.reconcile(&cfg.cron.jobs);
                }
            }
        }
    }

    if !was_in_scheduler && !removed_from_config {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Scheduled task '{}' not found.", task_id)
        }));
    }

    tracing::info!(job_id = %task_id, from_config = removed_from_config, "scheduled task deleted via API");
    Json(serde_json::json!({
        "ok": true,
        "message": format!("Scheduled task '{}' deleted.", task_id)
    }))
}

/// GET /ui/api/scheduled-tasks/:id/logs — Get activity logs for a scheduled task.
pub async fn scheduled_task_logs(
    State(state): State<Arc<ControlPanelState>>,
    axum::extract::Path(task_id): axum::extract::Path<String>,
) -> Json<serde_json::Value> {
    let logs = match &state.task_log {
        Some(store) => store.get_logs(&task_id, 50),
        None => vec![],
    };

    Json(serde_json::json!({
        "ok": true,
        "data": {
            "task_id": task_id,
            "logs": logs,
            "count": logs.len(),
        }
    }))
}

/// GET /ui/api/integrations/tools — registered tools from tool_registry.
pub async fn integrations_tools(
    State(state): State<Arc<ControlPanelState>>,
) -> Json<serde_json::Value> {
    let tools = match &state.tool_registry {
        Some(registry) => registry
            .known_names()
            .iter()
            .map(|name| {
                serde_json::json!({
                    "name": name,
                })
            })
            .collect::<Vec<_>>(),
        None => vec![],
    };

    Json(serde_json::json!({
        "ok": true,
        "data": {
            "tools": tools,
            "total": tools.len(),
        }
    }))
}

// ── Cookie parsing helper ──────────────────────────────────────────

/// Extract a cookie value by name from a Cookie header string.
fn extract_cookie<'a>(cookie_header: &'a str, name: &str) -> Option<&'a str> {
    for pair in cookie_header.split(';') {
        let pair = pair.trim();
        if let Some(value) = pair.strip_prefix(name) {
            if let Some(value) = value.strip_prefix('=') {
                return Some(value);
            }
        }
    }
    None
}

// ── MCP management endpoints ───────────────────────────────────────

/// Request body for adding/updating an MCP server.
#[derive(serde::Deserialize)]
pub struct AddMcpServerPayload {
    pub server_id: String,
    #[serde(default = "default_stdio")]
    pub transport: String,
    pub command: Option<String>,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default)]
    pub env: std::collections::HashMap<String, String>,
    pub url: Option<String>,
    #[serde(default)]
    pub disabled: bool,
}

fn default_stdio() -> String {
    "stdio".to_string()
}

/// POST /ui/api/integrations/mcp — Add or update an MCP server in config.
pub async fn mcp_add(
    State(state): State<Arc<ControlPanelState>>,
    Json(payload): Json<AddMcpServerPayload>,
) -> Json<serde_json::Value> {
    use crate::mcp::{McpServerConfig, McpTransport};

    let transport = match payload.transport.as_str() {
        "stdio" => {
            let command = match payload.command {
                Some(c) => c,
                None => {
                    return Json(serde_json::json!({
                        "ok": false,
                        "message": "command is required for stdio transport"
                    }));
                }
            };
            McpTransport::Stdio {
                command,
                args: payload.args,
                env: payload.env,
            }
        }
        "http" | "sse" => {
            let url = match payload.url {
                Some(u) => u,
                None => {
                    return Json(serde_json::json!({
                        "ok": false,
                        "message": "url is required for http/sse transport"
                    }));
                }
            };
            McpTransport::Sse { url }
        }
        other => {
            return Json(serde_json::json!({
                "ok": false,
                "message": format!("unknown transport type: {other}")
            }));
        }
    };

    let new_server = McpServerConfig {
        server_id: payload.server_id.clone(),
        transport,
        auth: None,
        enabled: !payload.disabled,
    };

    // Update config
    let config_path = match &state.config_path {
        Some(p) => p.clone(),
        None => {
            return Json(serde_json::json!({
                "ok": false,
                "message": "Config file path not configured"
            }));
        }
    };

    let mut cfg = state.config.load().as_ref().clone();
    cfg.mcp_servers.retain(|s| s.server_id != payload.server_id);
    cfg.mcp_servers.push(new_server);

    // Write to disk
    let output = match serde_json::to_string_pretty(&cfg) {
        Ok(s) => s,
        Err(e) => {
            return Json(serde_json::json!({
                "ok": false,
                "message": format!("Failed to serialize config: {e}")
            }));
        }
    };

    if let Err(e) = std::fs::write(&config_path, &output) {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Failed to write config: {e}")
        }));
    }

    // Hot-reload: update in-memory config and reconcile MCP connections
    state.config.store(std::sync::Arc::new(cfg.clone()));
    if let Some(mgr) = &state.mcp_manager {
        mgr.reconcile(&cfg.mcp_servers).await;
    }

    tracing::info!(server_id = %payload.server_id, "MCP server added via API");

    Json(serde_json::json!({
        "ok": true,
        "message": format!("MCP server '{}' added.", payload.server_id)
    }))
}

/// DELETE /ui/api/integrations/mcp/:id — Remove an MCP server from config.
pub async fn mcp_remove(
    State(state): State<Arc<ControlPanelState>>,
    Path(server_id): Path<String>,
) -> Json<serde_json::Value> {
    let config_path = match &state.config_path {
        Some(p) => p.clone(),
        None => {
            return Json(serde_json::json!({
                "ok": false,
                "message": "Config file path not configured"
            }));
        }
    };

    let mut cfg = state.config.load().as_ref().clone();
    let before = cfg.mcp_servers.len();
    cfg.mcp_servers.retain(|s| s.server_id != server_id);

    if cfg.mcp_servers.len() == before {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("MCP server '{}' not found.", server_id)
        }));
    }

    let output = match serde_json::to_string_pretty(&cfg) {
        Ok(s) => s,
        Err(e) => {
            return Json(serde_json::json!({
                "ok": false,
                "message": format!("Failed to serialize config: {e}")
            }));
        }
    };

    if let Err(e) = std::fs::write(&config_path, &output) {
        return Json(serde_json::json!({
            "ok": false,
            "message": format!("Failed to write config: {e}")
        }));
    }

    state.config.store(std::sync::Arc::new(cfg.clone()));
    if let Some(mgr) = &state.mcp_manager {
        mgr.reconcile(&cfg.mcp_servers).await;
    }

    tracing::info!(server_id = %server_id, "MCP server removed via API");

    Json(serde_json::json!({
        "ok": true,
        "message": format!("MCP server '{}' removed.", server_id)
    }))
}

/// POST /ui/api/integrations/mcp/:id/toggle — Enable/disable an MCP server.
pub async fn mcp_toggle(
    State(state): State<Arc<ControlPanelState>>,
    Path(server_id): Path<String>,
) -> Json<serde_json::Value> {
    let config_path = match &state.config_path {
        Some(p) => p.clone(),
        None => {
            return Json(serde_json::json!({
                "ok": false,
                "message": "Config file path not configured"
            }));
        }
    };

    let mut cfg = state.config.load().as_ref().clone();
    let server = cfg.mcp_servers.iter_mut().find(|s| s.server_id == server_id);

    match server {
        Some(srv) => {
            srv.enabled = !srv.enabled;
            let new_state = if srv.enabled { "enabled" } else { "disabled" };

            let output = match serde_json::to_string_pretty(&cfg) {
                Ok(s) => s,
                Err(e) => {
                    return Json(serde_json::json!({
                        "ok": false,
                        "message": format!("Failed to serialize config: {e}")
                    }));
                }
            };

            if let Err(e) = std::fs::write(&config_path, &output) {
                return Json(serde_json::json!({
                    "ok": false,
                    "message": format!("Failed to write config: {e}")
                }));
            }

            state.config.store(std::sync::Arc::new(cfg.clone()));
            if let Some(mgr) = &state.mcp_manager {
                mgr.reconcile(&cfg.mcp_servers).await;
            }

            tracing::info!(server_id = %server_id, state = %new_state, "MCP server toggled via API");

            Json(serde_json::json!({
                "ok": true,
                "message": format!("MCP server '{}' {}.", server_id, new_state)
            }))
        }
        None => Json(serde_json::json!({
            "ok": false,
            "message": format!("MCP server '{}' not found.", server_id)
        })),
    }
}