kyma-server 0.0.1

HTTP + gRPC query API, auth stub, health, observability.
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
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
//! HTTP handlers for `POST /v1/agent/ask` (SSE), `GET /v1/agent/runs/:run_id`,
//! and the engine-management surface (`GET/PUT /v1/agent/engine`, etc.).
//!
//! The ask handler drives an ADK-Rust `Runner` and emits a stream of SSE
//! frames. Once the stream completes (naturally, on error, or on budget
//! overrun) we insert one row into `agent_runs` with the full trace as JSONB.

use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

use adk_rust::futures::StreamExt;
use adk_rust::identity::{SessionId, UserId};
use adk_rust::{Content, Part};
use axum::extract::{Extension, Path, State};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::Json;
use chrono::Utc;
use serde::Deserialize;
use serde_json::{json, Value};
use sqlx::types::Json as SqlxJson;
use sqlx::PgPool;
use tracing::{debug, error, info, warn};

use super::engine::{
    build_engine, claude_cli, engine_catalogue, CredentialResolver, EngineConfig, EngineKind,
};
use super::memory_retrieve::{retrieve, RetrieveRequest};
use super::runner::{make_runner, model_id, run_oneshot, ANON_USER};
use super::sessions;
use super::state::AgentState;
use super::tools::{execute_sql, SharedToolCtx};
use super::ui_stream;
use crate::auth::{Principal, Role};

/// Hard cap on tool-call count per run. Above this, the turn is aborted
/// with `run_error{code="tool_loop"}` and persisted as `budget_exceeded`.
const MAX_TOOL_CALLS: u32 = 12;

/// Wall-clock deadline for the whole SSE exchange.
const RUN_WALL_CLOCK: Duration = Duration::from_secs(60);

/// Default number of new turns after which a session's rolling summary is
/// refreshed. Overridable via `KYMA_SESSION_SUMMARY_EVERY`.
const DEFAULT_SUMMARY_EVERY: i32 = 12;

fn summary_every() -> i32 {
    std::env::var("KYMA_SESSION_SUMMARY_EVERY")
        .ok()
        .and_then(|v| v.parse::<i32>().ok())
        .filter(|n| *n > 0)
        .unwrap_or(DEFAULT_SUMMARY_EVERY)
}

pub fn router(state: AgentState) -> axum::Router {
    axum::Router::new()
        .route("/ask", post(ask_handler))
        .route("/runs/:run_id", get(run_lookup_handler))
        .route("/sessions", get(list_sessions_handler))
        .route(
            "/sessions/:session_id",
            get(get_session_handler).delete(delete_session_handler),
        )
        .route("/sessions/:session_id/turns", get(get_session_turns_handler))
        .route("/engines", get(list_engines))
        .route("/engine", get(get_engine).put(put_engine))
        .route("/engine/test", post(test_engine))
        .route("/skills", get(list_skills))
        .route("/skills/enabled", get(get_enabled_skills).put(put_enabled_skills))
        .route("/memory/overview", get(super::memory::overview_handler))
        .route("/memory/query", post(memory_query_handler))
        .route(
            "/memory/settings",
            get(get_memory_settings).put(put_memory_settings),
        )
        .route("/memory/export", get(export_memory_handler))
        .route("/memory/changes", get(changes_memory_handler))
        .route("/memory/import", post(import_memory_handler))
        .with_state(state)
}

#[derive(Debug, Deserialize, Default)]
struct ImportBody {
    #[serde(default)]
    memory_nodes: Vec<Value>,
    #[serde(default)]
    memory_edges: Vec<Value>,
}

/// `POST /v1/agent/memory/import` — apply memory node/edge rows (from another
/// instance's `export`/`changes`) into this store **via the MemoryWriter**, so
/// the canonical memory schema (typed `importance`, the embedding vector, …) and
/// on-demand provisioning are used — unlike generic `/v1/ingest`, which would
/// infer every column as text. Append-only / latest-wins, so re-applying is safe.
/// This is the receive side of memory sync.
async fn import_memory_handler(
    State(state): State<AgentState>,
    Extension(principal): Extension<Principal>,
    Json(body): Json<ImportBody>,
) -> Response {
    // Import is a bulk WRITE of memory nodes/edges from another instance. The
    // surrounding agent router is mounted at `Role::Read`, so gate this one
    // route at `Role::Write` in-handler — a read-only token must not be able to
    // push memory into the store.
    if principal.role < Role::Write {
        return (
            StatusCode::FORBIDDEN,
            Json(json!({ "error": "memory import requires write role" })),
        )
            .into_response();
    }
    let embed = match kyma_memory::shared_embedding().await {
        Ok(e) => e,
        Err(e) => {
            return Json(json!({ "error": format!("embedding backend: {e}") })).into_response()
        }
    };
    let writer =
        kyma_memory::MemoryWriter::new(state.catalog.clone(), state.format.clone(), embed);
    let mut applied_nodes = 0usize;
    let mut applied_edges = 0usize;
    let mut errors: Vec<String> = Vec::new();
    if !body.memory_nodes.is_empty() {
        match writer.append_node_rows(body.memory_nodes.clone()).await {
            Ok(()) => applied_nodes = body.memory_nodes.len(),
            Err(e) => errors.push(format!("nodes: {e}")),
        }
    }
    if !body.memory_edges.is_empty() {
        match writer.append_edge_rows(body.memory_edges.clone()).await {
            Ok(()) => applied_edges = body.memory_edges.len(),
            Err(e) => errors.push(format!("edges: {e}")),
        }
    }
    Json(json!({
        "applied_nodes": applied_nodes,
        "applied_edges": applied_edges,
        "errors": errors,
    }))
    .into_response()
}

#[derive(Debug, Deserialize)]
struct ExportParams {
    /// Restrict the export to one realm. Omit to export all.
    #[serde(default)]
    realm: Option<String>,
}

#[derive(Debug, Deserialize)]
struct ChangesParams {
    /// Return only memories changed strictly after this RFC3339 timestamp.
    /// Omit for the full set (epoch). Pass back the response's `until` next time.
    #[serde(default)]
    since: Option<String>,
    /// Restrict to one realm. Omit for all.
    #[serde(default)]
    realm: Option<String>,
}

/// `GET /v1/agent/memory/changes?since=<rfc3339>[&realm=]` — the incremental
/// pull side of memory sync: latest node versions whose `updated_at` (and edges
/// whose `created_at`) are strictly after `since`, plus an `until` watermark
/// (server clock) the caller advances to for the next pull. Same row shape as
/// export, so the caller re-applies via `POST /v1/ingest` (X-Database: memory).
async fn changes_memory_handler(
    State(state): State<AgentState>,
    axum::extract::Query(params): axum::extract::Query<ChangesParams>,
) -> Json<Value> {
    let shared = SharedToolCtx {
        catalog: state.catalog.clone(),
        format: state.format.clone(),
        pool: state.pool.clone(),
    };
    let since = params
        .since
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| "1970-01-01T00:00:00Z".to_string());
    let since_esc = since.replace('\'', "''");
    let realm_filter = params
        .realm
        .as_deref()
        .map(|r| format!(" AND realm = '{}'", r.replace('\'', "''")))
        .unwrap_or_default();
    let nodes_sql = format!(
        "WITH latest AS (SELECT *, row_number() OVER (PARTITION BY id ORDER BY updated_at DESC) AS __rn FROM memory_nodes) \
         SELECT id, labels, realm, memory_type, title, content, content_preview, tags, importance, status, \
                source_session_id, source_run_id, embedding, created_at, updated_at, \
                valid_at, invalid_at, superseded_by, provenance, topic_key \
         FROM latest WHERE __rn = 1 AND updated_at > '{since_esc}'{realm_filter}"
    );
    let edges_sql = format!(
        "SELECT id, src, dst, type, realm, target_namespace, props, created_at \
         FROM memory_edges WHERE created_at > '{since_esc}'"
    );
    let db = kyma_memory::DEFAULT_DATABASE;
    let nodes = execute_sql(&shared, db, &nodes_sql, 1_000_000).await;
    let edges = execute_sql(&shared, db, &edges_sql, 1_000_000).await;
    let rows = |v: Value| v.get("rows").cloned().unwrap_or_else(|| json!([]));
    Json(json!({
        "since": since,
        "until": Utc::now().to_rfc3339(),
        "memory_nodes": rows(nodes),
        "memory_edges": rows(edges),
    }))
}

/// `GET /v1/agent/memory/export[?realm=]` — full memory snapshot (latest node
/// versions + edges, including embeddings) as JSON, for backup / portability.
/// Re-import on another instance via the idempotent `POST /v1/ingest`
/// (`X-Database: memory`, `X-Table: memory_nodes|memory_edges`, NDJSON).
async fn export_memory_handler(
    State(state): State<AgentState>,
    axum::extract::Query(params): axum::extract::Query<ExportParams>,
) -> Json<Value> {
    let shared = SharedToolCtx {
        catalog: state.catalog.clone(),
        format: state.format.clone(),
        pool: state.pool.clone(),
    };
    let realm_filter = params
        .realm
        .as_deref()
        .map(|r| format!(" AND realm = '{}'", r.replace('\'', "''")))
        .unwrap_or_default();
    let nodes_sql = format!(
        "WITH latest AS (SELECT *, row_number() OVER (PARTITION BY id ORDER BY updated_at DESC) AS __rn FROM memory_nodes) \
         SELECT id, labels, realm, memory_type, title, content, content_preview, tags, importance, status, \
                source_session_id, source_run_id, embedding, created_at, updated_at, \
                valid_at, invalid_at, superseded_by, provenance, topic_key \
         FROM latest WHERE __rn = 1{realm_filter}"
    );
    let edges_sql = "SELECT id, src, dst, type, realm, target_namespace, props, created_at FROM memory_edges";
    let db = kyma_memory::DEFAULT_DATABASE;
    let nodes = execute_sql(&shared, db, &nodes_sql, 1_000_000).await;
    let edges = execute_sql(&shared, db, edges_sql, 1_000_000).await;
    let rows = |v: Value| v.get("rows").cloned().unwrap_or_else(|| json!([]));
    Json(json!({
        "memory_nodes": rows(nodes),
        "memory_edges": rows(edges),
        "hint": "Re-import on another instance via POST /v1/agent/memory/import \
                 with this same {memory_nodes, memory_edges} body (writes through \
                 the MemoryWriter, preserving the canonical schema + embeddings).",
    }))
}

/// `GET /v1/agent/memory/settings` — current tunable memory settings.
async fn get_memory_settings(State(state): State<AgentState>) -> Json<Value> {
    let s = super::memory_settings::load(state.pool.as_ref(), state.tenant).await;
    Json(serde_json::to_value(s).unwrap_or_else(|_| json!({})))
}

/// `PUT /v1/agent/memory/settings` — persist tunable memory settings.
async fn put_memory_settings(
    State(state): State<AgentState>,
    Json(body): Json<super::memory_settings::MemorySettings>,
) -> Response {
    let Some(pool) = state.pool.as_ref() else {
        // Local mode: settings aren't persisted; accept and report ok.
        return Json(json!({ "ok": true, "persisted": false })).into_response();
    };
    match super::memory_settings::save(pool, state.tenant, &body).await {
        Ok(()) => Json(json!({ "ok": true })).into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({ "error": e.to_string() })),
        )
            .into_response(),
    }
}

/// `POST /v1/agent/memory/query` — near-realtime memory recall for external
/// callers (web UI, Claude Code hooks, coding agents). `mode: "fast"` (default)
/// runs the LLM-free graph-aware hybrid retrieval; `mode: "agentic"` adds a
/// short synthesized `brief` over the retrieved context.
#[derive(Debug, Deserialize)]
struct MemoryQueryRequest {
    #[serde(flatten)]
    retrieve: RetrieveRequest,
    #[serde(default)]
    mode: Option<String>,
}

async fn memory_query_handler(
    State(state): State<AgentState>,
    Json(body): Json<MemoryQueryRequest>,
) -> Json<Value> {
    let shared = SharedToolCtx {
        catalog: state.catalog.clone(),
        format: state.format.clone(),
        pool: state.pool.clone(),
    };
    let result = retrieve(&shared, &body.retrieve).await;
    let mut out = result.to_json();
    if body.mode.as_deref() == Some("agentic") && !result.context.is_empty() {
        let prompt = format!("Question: {}\n\n{}", body.retrieve.query, result.context);
        if let Ok(brief) = run_oneshot(
            &state,
            "kyma-memory-brief",
            "Answers a question from retrieved memory.",
            "Answer the question using ONLY the provided memories. Be concise and cite memory \
             ids. If the memories don't contain the answer, say so plainly.",
            &prompt,
        )
        .await
        {
            if let Value::Object(ref mut m) = out {
                m.insert("brief".into(), Value::String(brief));
            }
        }
    }
    Json(out)
}

#[derive(Debug, Deserialize)]
struct AskRequest {
    question: String,
    #[serde(default)]
    #[allow(dead_code)]
    database: Option<String>,
    #[serde(default)]
    include_thinking: bool,
    /// Optional conversation session. When present, prior turns are replayed
    /// for context and this turn is appended. A new id is minted when absent.
    #[serde(default)]
    session_id: Option<String>,
    /// Marks the session source (e.g. `"claude_code"` for hook-driven asks).
    #[serde(default)]
    source: Option<String>,
}

/// One recorded logical event — we stash both the event name and the JSON
/// body so we can persist the full trace into `agent_runs` after the stream
/// completes. (The persisted format is internal and independent of the wire
/// protocol the client sees.)
#[derive(Debug, Clone)]
struct TraceFrame {
    event: &'static str,
    data: Value,
}

/// Translates the agent's logical events into the AI-SDK **UI Message Stream**
/// the client consumes, while also recording a [`TraceFrame`] of each event for
/// persistence. One `Emitter` drives one assistant message: it opens the
/// message on construction and manages text/reasoning block lifecycles (so the
/// wire always has matching `*-start`/`*-end` parts) and tool-call/result
/// pairing by id.
struct Emitter {
    ui: ui_stream::UiStream,
    trace: Vec<TraceFrame>,
    /// Open text block id, if any.
    text_id: Option<String>,
    /// Open reasoning block id, if any.
    reasoning_id: Option<String>,
    /// Monotonic counter for unique block ids within the message.
    block_seq: u64,
    /// FIFO of synthetic tool-call ids per tool name, so a `tool_result`
    /// (which carries only the tool name) can be paired with its `tool_call`.
    tool_ids: HashMap<String, VecDeque<String>>,
    tool_seq: u64,
}

impl Emitter {
    /// Open the assistant message (`start` + `start-step`) and return the emitter.
    fn new(ui: ui_stream::UiStream, message_id: &str) -> Self {
        ui.start(message_id);
        ui.start_step();
        Self {
            ui,
            trace: Vec::new(),
            text_id: None,
            reasoning_id: None,
            block_seq: 0,
            tool_ids: HashMap::new(),
            tool_seq: 0,
        }
    }

    fn record(&mut self, event: &'static str, data: Value) {
        self.trace.push(TraceFrame { event, data });
    }

    fn next_block(&mut self) -> String {
        let id = format!("blk-{}", self.block_seq);
        self.block_seq += 1;
        id
    }

    fn close_text(&mut self) {
        if let Some(id) = self.text_id.take() {
            self.ui.text_end(&id);
        }
    }
    fn close_reasoning(&mut self) {
        if let Some(id) = self.reasoning_id.take() {
            self.ui.reasoning_end(&id);
        }
    }

    /// Surface the conversation session id so the client can resume.
    fn session(&mut self, session_id: &str) {
        self.record("session", json!({ "session_id": session_id }));
        self.ui.data("session", json!({ "sessionId": session_id }));
    }

    fn run_started(&mut self, run_id: &str, model: &str, question: &str) {
        self.record(
            "run_started",
            json!({ "run_id": run_id, "model": model, "question": question }),
        );
        self.ui.data("model", json!({ "model": model }));
    }

    fn answer_delta(&mut self, text: &str) {
        self.record("answer_delta", json!({ "text": text }));
        self.close_reasoning();
        let id = match &self.text_id {
            Some(id) => id.clone(),
            None => {
                let id = self.next_block();
                self.ui.text_start(&id);
                self.text_id = Some(id.clone());
                id
            }
        };
        self.ui.text_delta(&id, text);
    }

    fn thinking_delta(&mut self, text: &str) {
        self.record("thinking_delta", json!({ "text": text }));
        self.close_text();
        let id = match &self.reasoning_id {
            Some(id) => id.clone(),
            None => {
                let id = self.next_block();
                self.ui.reasoning_start(&id);
                self.reasoning_id = Some(id.clone());
                id
            }
        };
        self.ui.reasoning_delta(&id, text);
    }

    fn tool_call(&mut self, tool: &str, args: Value, call_index: u32) {
        self.record(
            "tool_call",
            json!({ "tool": tool, "args": args, "call_index": call_index }),
        );
        self.close_text();
        self.close_reasoning();
        let id = format!("call-{}", self.tool_seq);
        self.tool_seq += 1;
        self.tool_ids
            .entry(tool.to_string())
            .or_default()
            .push_back(id.clone());
        self.ui.tool_input_available(&id, tool, args);
    }

    fn tool_result(&mut self, tool: &str, result: Value) {
        self.record("tool_result", json!({ "tool": tool, "result": result }));
        let id = self
            .tool_ids
            .get_mut(tool)
            .and_then(|q| q.pop_front())
            .unwrap_or_else(|| format!("call-{tool}"));
        self.ui.tool_output_available(&id, result);
    }

    /// Final answer bookkeeping. The text itself has already streamed via
    /// `answer_delta`, so here we only close the block and surface the SQL/KQL
    /// the run used as data parts.
    fn answer_final(&mut self, text: &str, sql_used: Option<&str>, kql_used: Option<&str>) {
        self.record(
            "answer_final",
            json!({ "text": text, "kql_used": kql_used, "sql_used": sql_used }),
        );
        self.close_text();
        self.close_reasoning();
        if let Some(sql) = sql_used {
            self.ui.data("sql", json!({ "sql": sql }));
        }
        if let Some(kql) = kql_used {
            self.ui.data("kql", json!({ "kql": kql }));
        }
    }

    fn run_error(&mut self, code: &str, message: &str) {
        self.record("run_error", json!({ "code": code, "message": message }));
        self.ui.error(message);
    }

    /// Close the message: flush open blocks, emit run metadata, then the
    /// terminal `finish-step`/`finish`/`[DONE]` parts.
    fn finish(&mut self, usage: Value) {
        self.close_text();
        self.close_reasoning();
        self.ui.data("usage", usage);
        self.ui.finish_step();
        self.ui.finish();
        self.ui.done();
    }

    /// Build the JSON trace array persisted into `agent_runs`.
    fn trace_json(&self) -> Value {
        Value::Array(
            self.trace
                .iter()
                .map(|f| json!({ "event": f.event, "data": f.data }))
                .collect(),
        )
    }
}

/// POST /v1/agent/ask — run one agent turn and stream SSE frames.
async fn ask_handler(
    State(state): State<AgentState>,
    headers: axum::http::HeaderMap,
    Json(body): Json<AskRequest>,
) -> Response {
    let question = body.question.trim().to_string();
    if question.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "question must be non-empty"})),
        )
            .into_response();
    }

    // Engine-kind branch: the Claude CLI engine owns its own tool loop, OAuth,
    // skills, and MCPs — adk-rust can't wrap it. Divert here before building
    // the runner.
    if let Ok(cfg) = state.engines.get().await {
        if cfg.kind == EngineKind::ClaudeCli {
            // `session_id` here is Claude's own session id (echoed back from a
            // prior turn's `data-session` part), used to `--resume`. The
            // caller's Authorization header is forwarded so Claude can reach
            // our own MCP endpoint (`mcp_url`) as the same principal.
            let auth_header = headers
                .get(axum::http::header::AUTHORIZATION)
                .and_then(|v| v.to_str().ok())
                .map(str::to_string);
            return ask_via_claude_cli(
                state.pool.clone(),
                &question,
                &cfg,
                body.session_id.clone(),
                state.mcp_url.clone(),
                auth_header,
            )
            .await;
        }
    }

    let run_id = uuid::Uuid::new_v4();
    let include_thinking = body.include_thinking;
    let model = model_id(&state).await;
    let started_at = Utc::now();
    let start = Instant::now();

    // Resolve (or create) the conversation session (A5). Prior turns are
    // replayed into the runner; this turn is appended below.
    let source = body.source.as_deref().unwrap_or("kyma");
    let tenant_uuid = state.tenant.as_uuid();
    let sctx = sessions::load_or_create(
        state.pool.as_ref(),
        body.session_id.as_deref(),
        tenant_uuid,
        ANON_USER,
        source,
    )
    .await;
    let session_uuid = sctx.session_id;
    let session_id_str = session_uuid.to_string();
    let user_turn_index = sctx.next_turn_index;
    let assistant_turn_index = user_turn_index + 1;

    info!(run_id = %run_id, session_id = %session_uuid, question = %question, "agent run starting");

    // Record the user turn up-front so it survives even if the run errors.
    sessions::persist_turn(
        state.pool.as_ref(),
        session_uuid,
        tenant_uuid,
        user_turn_index,
        "user",
        &question,
        None,
    )
    .await;

    // Build runner up-front so we can surface init errors as a single-message
    // UI Message Stream (rather than an HTTP 500).
    let runner = match make_runner(&state, &session_id_str, &sctx.history, sctx.summary.as_deref())
        .await
    {
        Ok(r) => r,
        Err(e) => {
            error!(run_id = %run_id, error = %e, "failed to build agent runner");
            let (ui, rx) = ui_stream::channel();
            let mut em = Emitter::new(ui, &run_id.to_string());
            em.session(&session_id_str);
            em.run_error("init_error", &e.to_string());
            em.finish(json!({ "tool_calls": 0, "elapsed_ms": start.elapsed().as_millis() as u64 }));
            // Best-effort persistence — ignore errors here since the
            // primary surface (SSE) already told the client.
            let _ = persist_run(
                state.pool.as_ref(),
                run_id,
                &question,
                &model,
                tenant_uuid,
                Some(session_uuid),
                started_at,
                Utc::now(),
                "error",
                &Value::Null,
                &em.trace_json(),
            )
            .await;
            return ui_stream::response(rx);
        }
    };

    // Spawn the driver task. The task owns the runner and the event loop and
    // drives the UI Message Stream through an `Emitter`; the response is a
    // `tokio_stream::UnboundedReceiverStream` over the parts it produces.
    let (ui, rx) = ui_stream::channel();
    let pool = state.pool.clone();
    let summary_state = state.clone();
    let summary_every = summary_every();

    tokio::spawn(async move {
        let mut em = Emitter::new(ui, &run_id.to_string());
        let mut tool_calls: u32 = 0;
        let mut last_run_sql: Option<String> = None;
        let mut final_text: String = String::new();

        // Surface the session id first so the client can capture it even if
        // the run errors mid-stream.
        em.session(&session_id_str);
        em.run_started(&run_id.to_string(), &model, &question);

        let content = Content::new("user").with_text(&question);

        let user_id = match UserId::new(ANON_USER) {
            Ok(u) => u,
            Err(e) => {
                em.run_error("internal", &format!("user_id: {e}"));
                finish_and_persist(
                    pool.as_ref(), &mut em, run_id, &question, &model, tenant_uuid, Some(session_uuid),
                    started_at, start, tool_calls, "error",
                )
                .await;
                return;
            }
        };
        let session_id = match SessionId::new(&session_id_str) {
            Ok(s) => s,
            Err(e) => {
                em.run_error("internal", &format!("session_id: {e}"));
                finish_and_persist(
                    pool.as_ref(), &mut em, run_id, &question, &model, tenant_uuid, Some(session_uuid),
                    started_at, start, tool_calls, "error",
                )
                .await;
                return;
            }
        };

        let run_future = async {
            let mut stream = match runner.run(user_id, session_id, content).await {
                Ok(s) => s,
                Err(e) => {
                    return Err(format!("runner.run: {e}"));
                }
            };

            while let Some(ev_result) = stream.next().await {
                let ev = match ev_result {
                    Ok(e) => e,
                    Err(e) => return Err(format!("event: {e}")),
                };

                let partial = ev.llm_response.partial;
                let parts_iter = ev
                    .llm_response
                    .content
                    .iter()
                    .flat_map(|c| c.parts.iter().cloned())
                    .collect::<Vec<Part>>();

                for part in parts_iter {
                    match part {
                        Part::Text { text } => {
                            // Non-partial Text means we have the complete
                            // (possibly aggregated) turn answer — stash it for
                            // the session record. Either way it streams as a
                            // text delta.
                            if !partial {
                                final_text.push_str(&text);
                            }
                            em.answer_delta(&text);
                        }
                        Part::Thinking { thinking, .. } => {
                            if include_thinking {
                                em.thinking_delta(&thinking);
                            }
                        }
                        Part::FunctionCall { name, args, .. } => {
                            tool_calls += 1;
                            if name == "run_sql" {
                                if let Some(s) = args.get("sql").and_then(|v| v.as_str()) {
                                    last_run_sql = Some(s.to_string());
                                }
                            }
                            em.tool_call(&name, args, tool_calls);
                            if tool_calls > MAX_TOOL_CALLS {
                                return Err(format!("tool_loop:{}", tool_calls));
                            }
                        }
                        Part::FunctionResponse {
                            function_response, ..
                        } => {
                            em.tool_result(&function_response.name, function_response.response);
                        }
                        _ => {}
                    }
                }

                if ev.is_final_response() {
                    // Fold in any final text even if it arrived as a
                    // non-partial full text part above. Nothing to do
                    // here — we've already pushed it to `final_text`.
                    debug!(run_id = %run_id, "agent emitted is_final_response");
                }
            }
            Ok::<(), String>(())
        };

        let outcome = tokio::time::timeout(RUN_WALL_CLOCK, run_future).await;

        let (status, status_str): (&str, &str) = match outcome {
            Ok(Ok(())) => ("success", "success"),
            Ok(Err(msg)) if msg.starts_with("tool_loop:") => {
                em.run_error("tool_loop", &msg);
                ("budget_exceeded", "budget_exceeded")
            }
            Ok(Err(msg)) => {
                em.run_error("runner_error", &msg);
                ("error", "error")
            }
            Err(_elapsed) => {
                warn!(run_id = %run_id, "agent run exceeded 60s wall clock");
                em.run_error(
                    "timeout",
                    &format!(
                        "agent run exceeded {}s wall clock budget",
                        RUN_WALL_CLOCK.as_secs()
                    ),
                );
                ("budget_exceeded", "budget_exceeded")
            }
        };

        if status == "success" {
            em.answer_final(&final_text, last_run_sql.as_deref(), None);
            // Record the assistant turn, then refresh the rolling summary.
            sessions::persist_turn(
                pool.as_ref(),
                session_uuid,
                tenant_uuid,
                assistant_turn_index,
                "assistant",
                &final_text,
                None,
            )
            .await;
            sessions::maybe_summarize_detached(summary_state, session_uuid, summary_every);
        }

        finish_and_persist(
            pool.as_ref(), &mut em, run_id, &question, &model, tenant_uuid, Some(session_uuid), started_at,
            start, tool_calls, status_str,
        )
        .await;
    });

    ui_stream::response(rx)
}

#[allow(clippy::too_many_arguments)]
async fn finish_and_persist(
    pool: Option<&PgPool>,
    em: &mut Emitter,
    run_id: uuid::Uuid,
    question: &str,
    model: &str,
    tenant: uuid::Uuid,
    session_id: Option<uuid::Uuid>,
    started_at: chrono::DateTime<Utc>,
    start: Instant,
    tool_calls: u32,
    status: &str,
) {
    let elapsed_ms = start.elapsed().as_millis() as u64;
    let usage_json = json!({
        "run_id": run_id.to_string(),
        "tool_calls": tool_calls,
        "elapsed_ms": elapsed_ms,
    });
    // Closes any open blocks and emits the terminal finish/[DONE] parts.
    em.finish(usage_json.clone());

    let trace_json = em.trace_json();

    if let Err(e) = persist_run(
        pool,
        run_id,
        question,
        model,
        tenant,
        session_id,
        started_at,
        Utc::now(),
        status,
        &usage_json,
        &trace_json,
    )
    .await
    {
        error!(run_id = %run_id, error = %e, "failed to persist agent_runs row");
    }
}

#[allow(clippy::too_many_arguments)]
async fn persist_run(
    pool: Option<&PgPool>,
    run_id: uuid::Uuid,
    question: &str,
    model_id: &str,
    tenant: uuid::Uuid,
    session_id: Option<uuid::Uuid>,
    started_at: chrono::DateTime<Utc>,
    finished_at: chrono::DateTime<Utc>,
    status: &str,
    usage_json: &Value,
    trace_json: &Value,
) -> sqlx::Result<()> {
    let Some(pool) = pool else { return Ok(()) }; // local mode: no run persistence
    sqlx::query(
        r#"
        INSERT INTO agent_runs (
            run_id, tenant_id, question, model_id, auth_subject,
            session_id, started_at, finished_at, status,
            usage_json, trace_json, replay_cache_hit
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
        "#,
    )
    .bind(run_id)
    .bind(tenant)
    .bind(question)
    .bind(model_id)
    .bind(ANON_USER)
    .bind(session_id)
    .bind(started_at)
    .bind(finished_at)
    .bind(status)
    .bind(SqlxJson(usage_json.clone()))
    .bind(SqlxJson(trace_json.clone()))
    .bind(false)
    .execute(pool)
    .await
    .map(|_| ())
}

// ---------------------------------------------------------------------------
// GET/DELETE /v1/agent/sessions* — multi-turn session surface (A5)
// ---------------------------------------------------------------------------

fn parse_session_id(raw: &str) -> Result<uuid::Uuid, Response> {
    uuid::Uuid::parse_str(raw).map_err(|_| {
        (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "invalid session_id (expected uuid)"})),
        )
            .into_response()
    })
}

async fn list_sessions_handler(State(state): State<AgentState>) -> Response {
    let Some(pool) = state.pool.as_ref() else {
        return Json(json!({ "sessions": [] })).into_response(); // local: no session history
    };
    let rows: Vec<(
        uuid::Uuid,
        Option<String>,
        chrono::DateTime<Utc>,
        chrono::DateTime<Utc>,
        String,
        i64,
    )> = match sqlx::query_as(
        r#"
        SELECT s.session_id, s.title, s.created_at, s.last_active, s.source,
               COUNT(t.turn_index) AS turn_count
        FROM agent_sessions s
        LEFT JOIN agent_session_turns t ON t.session_id = s.session_id
        GROUP BY s.session_id
        ORDER BY s.last_active DESC
        LIMIT 200
        "#,
    )
    .fetch_all(pool)
    .await
    {
        Ok(r) => r,
        Err(e) => {
            error!(error = %e, "list sessions failed");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": e.to_string()})),
            )
                .into_response();
        }
    };
    let sessions: Vec<Value> = rows
        .into_iter()
        .map(|(id, title, created, last_active, source, turn_count)| {
            json!({
                "session_id": id.to_string(),
                "title": title,
                "created_at": created,
                "last_active": last_active,
                "source": source,
                "turn_count": turn_count,
            })
        })
        .collect();
    Json(json!({ "sessions": sessions })).into_response()
}

async fn get_session_handler(
    State(state): State<AgentState>,
    Path(session_id): Path<String>,
) -> Response {
    let sid = match parse_session_id(&session_id) {
        Ok(u) => u,
        Err(resp) => return resp,
    };
    let Some(pool) = state.pool.as_ref() else {
        return (StatusCode::NOT_FOUND, Json(json!({"error": "session not found"}))).into_response();
    };
    let row: Option<(
        Option<String>,
        Option<String>,
        chrono::DateTime<Utc>,
        chrono::DateTime<Utc>,
        String,
        i32,
    )> = sqlx::query_as(
        "SELECT title, rolling_summary, created_at, last_active, source, summary_turn_index \
         FROM agent_sessions WHERE session_id = $1",
    )
    .bind(sid)
    .fetch_optional(pool)
    .await
    .unwrap_or(None);
    match row {
        Some((title, summary, created, last_active, source, summary_idx)) => Json(json!({
            "session_id": sid.to_string(),
            "title": title,
            "rolling_summary": summary,
            "created_at": created,
            "last_active": last_active,
            "source": source,
            "summary_turn_index": summary_idx,
        }))
        .into_response(),
        None => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "session not found"})),
        )
            .into_response(),
    }
}

async fn get_session_turns_handler(
    State(state): State<AgentState>,
    Path(session_id): Path<String>,
) -> Response {
    let sid = match parse_session_id(&session_id) {
        Ok(u) => u,
        Err(resp) => return resp,
    };
    let Some(pool) = state.pool.as_ref() else {
        return Json(json!({ "session_id": sid.to_string(), "turns": [] })).into_response();
    };
    let rows: Vec<(
        i32,
        String,
        SqlxJson<Value>,
        Option<uuid::Uuid>,
        chrono::DateTime<Utc>,
    )> = sqlx::query_as(
        "SELECT turn_index, role, content_json, run_id, created_at \
         FROM agent_session_turns WHERE session_id = $1 ORDER BY turn_index ASC",
    )
    .bind(sid)
    .fetch_all(pool)
    .await
    .unwrap_or_default();
    let turns: Vec<Value> = rows
        .into_iter()
        .map(|(idx, role, content, run_id, created)| {
            json!({
                "turn_index": idx,
                "role": role,
                "content": content.0,
                "run_id": run_id.map(|r| r.to_string()),
                "created_at": created,
            })
        })
        .collect();
    Json(json!({ "session_id": sid.to_string(), "turns": turns })).into_response()
}

async fn delete_session_handler(
    State(state): State<AgentState>,
    Path(session_id): Path<String>,
) -> Response {
    let sid = match parse_session_id(&session_id) {
        Ok(u) => u,
        Err(resp) => return resp,
    };
    let Some(pool) = state.pool.as_ref() else {
        return (StatusCode::NOT_FOUND, Json(json!({"error": "session not found"}))).into_response();
    };
    // Turns cascade via FK ON DELETE CASCADE. `agent_runs.session_id` is a plain
    // (non-FK) column, so detach it to avoid dangling references.
    let _ = sqlx::query("UPDATE agent_runs SET session_id = NULL WHERE session_id = $1")
        .bind(sid)
        .execute(pool)
        .await;
    match sqlx::query("DELETE FROM agent_sessions WHERE session_id = $1")
        .bind(sid)
        .execute(pool)
        .await
    {
        Ok(r) if r.rows_affected() > 0 => {
            Json(json!({"deleted": true, "session_id": sid.to_string()})).into_response()
        }
        Ok(_) => (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "session not found"})),
        )
            .into_response(),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({"error": e.to_string()})),
        )
            .into_response(),
    }
}

// ---------------------------------------------------------------------------
// GET /v1/agent/runs/:run_id
// ---------------------------------------------------------------------------

async fn run_lookup_handler(
    State(state): State<AgentState>,
    Path(run_id): Path<String>,
) -> Response {
    let uid = match uuid::Uuid::parse_str(&run_id) {
        Ok(u) => u,
        Err(_) => {
            return (
                StatusCode::BAD_REQUEST,
                Json(json!({"error": "invalid run_id (expected uuid)"})),
            )
                .into_response();
        }
    };
    let Some(pool) = state.pool.as_ref() else {
        return (StatusCode::NOT_FOUND, Json(json!({"error": "run not found"}))).into_response();
    };

    let row: Option<(
        String,
        String,
        String,
        chrono::DateTime<Utc>,
        chrono::DateTime<Utc>,
        SqlxJson<Value>,
        SqlxJson<Value>,
    )> = match sqlx::query_as(
        r#"
        SELECT question, model_id, status, started_at, finished_at,
               usage_json, trace_json
        FROM agent_runs
        WHERE run_id = $1
        "#,
    )
    .bind(uid)
    .fetch_optional(pool)
    .await
    {
        Ok(r) => r,
        Err(e) => {
            error!(run_id = %run_id, error = %e, "agent_runs lookup failed");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": e.to_string()})),
            )
                .into_response();
        }
    };
    let Some((question, model, status, started_at, finished_at, usage, trace)) = row else {
        return (
            StatusCode::NOT_FOUND,
            Json(json!({"error": "run not found", "run_id": run_id})),
        )
            .into_response();
    };
    Json(json!({
        "run_id": run_id,
        "question": question,
        "model_id": model,
        "status": status,
        "started_at": started_at,
        "finished_at": finished_at,
        "usage": usage.0,
        "trace": trace.0,
    }))
    .into_response()
}

// ---------------------------------------------------------------------------
// Engine management routes
// ---------------------------------------------------------------------------

/// `GET /engines` — list available providers + their default models + the active config.
async fn list_engines(
    State(state): State<AgentState>,
) -> Result<axum::Json<serde_json::Value>, (axum::http::StatusCode, String)> {
    let active = state
        .engines
        .get()
        .await
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    // Pass the active Ollama host (if configured) so the catalogue's live
    // `/api/tags` fetch hits the user's actual instance, not the default.
    let ollama_hint = active.host.as_deref();
    let catalogue = engine_catalogue(ollama_hint).await;
    Ok(axum::Json(serde_json::json!({
        "available": catalogue,
        "active": active,
    })))
}

/// `GET /engine` — the persisted EngineConfig (one global row, v1).
async fn get_engine(
    State(state): State<AgentState>,
) -> Result<axum::Json<EngineConfig>, (axum::http::StatusCode, String)> {
    state
        .engines
        .get()
        .await
        .map(axum::Json)
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
}

/// `PUT /engine` — save a new EngineConfig.
async fn put_engine(
    State(state): State<AgentState>,
    axum::Json(cfg): axum::Json<EngineConfig>,
) -> Result<axum::Json<EngineConfig>, (axum::http::StatusCode, String)> {
    state
        .engines
        .put(&cfg)
        .await
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok(axum::Json(cfg))
}

/// `POST /engine/test` — dry-run probe against a candidate config without
/// persisting it. Confirms creds resolve + the provider responds.
async fn test_engine(
    State(state): State<AgentState>,
    axum::Json(cfg): axum::Json<EngineConfig>,
) -> Result<axum::Json<serde_json::Value>, (axum::http::StatusCode, String)> {
    use adk_rust::futures::StreamExt;
    use adk_rust::{GenerateContentConfig, LlmRequest};

    // Claude CLI engine: spawn the binary with a 1-token prompt and confirm
    // it streams *any* text and completes without error. Bypasses build_engine
    // entirely because the CLI doesn't go through adk-rust.
    if cfg.kind == EngineKind::ClaudeCli {
        let probe = tokio::time::timeout(std::time::Duration::from_secs(30), async {
            let mut rx = claude_cli::run_stream("ping", Some(&cfg.model), None, None, None)
                .map_err(|e| format!("spawn: {e}"))?;
            let mut got_output = false;
            let mut err: Option<String> = None;
            while let Some(ev) = rx.recv().await {
                match ev {
                    claude_cli::ClaudeEvent::TextStart { .. }
                    | claude_cli::ClaudeEvent::TextDelta { .. } => got_output = true,
                    claude_cli::ClaudeEvent::Error { message } => err = Some(message),
                    claude_cli::ClaudeEvent::Result { is_error: true, .. } => {
                        err.get_or_insert_with(|| "claude reported an error".to_string());
                    }
                    _ => {}
                }
            }
            if let Some(e) = err {
                return Err(e);
            }
            if !got_output {
                return Err("claude produced no output".to_string());
            }
            Ok::<(), String>(())
        })
        .await;

        return match probe {
            Ok(Ok(())) => Ok(axum::Json(serde_json::json!({
                "ok": true,
                "kind": cfg.kind,
                "model": cfg.model,
            }))),
            Ok(Err(msg)) => Err((axum::http::StatusCode::BAD_GATEWAY, msg)),
            Err(_elapsed) => Err((
                axum::http::StatusCode::GATEWAY_TIMEOUT,
                "claude_cli probe timed out after 30s".into(),
            )),
        };
    }

    // adk-rust path for Anthropic / OpenAI / Ollama.
    let resolver = CredentialResolver::new(state.credentials.clone(), state.tenant);
    let key = resolver
        .resolve(&cfg)
        .await
        .map_err(|e| (axum::http::StatusCode::BAD_REQUEST, format!("credential: {e}")))?;
    let llm = build_engine(&cfg, key)
        .map_err(|e| (axum::http::StatusCode::BAD_REQUEST, format!("init: {e}")))?;

    let req = LlmRequest {
        model: cfg.model.clone(),
        contents: vec![Content::new("user").with_text("ping")],
        config: Some(GenerateContentConfig {
            max_output_tokens: Some(1),
            ..Default::default()
        }),
        tools: Default::default(),
    };

    let probe = tokio::time::timeout(std::time::Duration::from_secs(30), async {
        let mut stream = llm
            .generate_content(req, false)
            .await
            .map_err(|e| format!("provider: {e:?}"))?;
        while let Some(item) = stream.next().await {
            item.map_err(|e| format!("stream: {e:?}"))?;
            break;
        }
        Ok::<(), String>(())
    })
    .await;

    match probe {
        Ok(Ok(())) => Ok(axum::Json(serde_json::json!({
            "ok": true,
            "kind": cfg.kind,
            "model": cfg.model,
        }))),
        Ok(Err(msg)) => Err((axum::http::StatusCode::BAD_GATEWAY, msg)),
        Err(_elapsed) => Err((
            axum::http::StatusCode::GATEWAY_TIMEOUT,
            "probe timed out after 30s".into(),
        )),
    }
}

// ---------------------------------------------------------------------------
// Skill management routes
// ---------------------------------------------------------------------------

#[derive(Debug, serde::Serialize)]
struct SkillRow {
    name: String,
    description: String,
    source: super::skills::SkillSource,
    path: String,
    enabled: bool,
    /// Truncated body preview for the UI tooltip.
    preview: String,
}

/// `GET /skills` — list every discovered skill on the host, plus its enabled
/// state. Discovery is cheap (filesystem walk), so we run it on every request
/// rather than caching.
async fn list_skills(
    State(state): State<AgentState>,
) -> Result<axum::Json<Vec<SkillRow>>, (axum::http::StatusCode, String)> {
    let enabled = state
        .skills
        .get()
        .await
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let enabled_set: std::collections::HashSet<&str> =
        enabled.iter().map(String::as_str).collect();

    let mut rows: Vec<SkillRow> = super::skills::discover_all()
        .into_iter()
        .map(|s| {
            let preview = preview_body(&s.body);
            SkillRow {
                enabled: enabled_set.contains(s.name.as_str()),
                name: s.name,
                description: s.description,
                source: s.source,
                path: s.path,
                preview,
            }
        })
        .collect();
    rows.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(axum::Json(rows))
}

/// `GET /skills/enabled` — just the toggled set, for callers that don't need
/// the full discovery payload.
async fn get_enabled_skills(
    State(state): State<AgentState>,
) -> Result<axum::Json<Vec<String>>, (axum::http::StatusCode, String)> {
    state
        .skills
        .get()
        .await
        .map(axum::Json)
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
}

#[derive(Debug, serde::Deserialize)]
struct PutEnabledSkillsBody {
    skills: Vec<String>,
}

/// `PUT /skills/enabled` — replace the toggled set wholesale.
async fn put_enabled_skills(
    State(state): State<AgentState>,
    axum::Json(body): axum::Json<PutEnabledSkillsBody>,
) -> Result<axum::Json<Vec<String>>, (axum::http::StatusCode, String)> {
    state
        .skills
        .put(&body.skills)
        .await
        .map_err(|e| (axum::http::StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    Ok(axum::Json(body.skills))
}

fn preview_body(body: &str) -> String {
    let trimmed = body.trim();
    if trimmed.chars().count() <= 200 {
        return trimmed.to_string();
    }
    let mut out: String = trimmed.chars().take(200).collect();
    out.push('…');
    out
}

// ---------------------------------------------------------------------------
// Claude CLI engine — drives the Claude Code agent loop via the
// claude-code-agent-sdk and translates its events into the UI Message Stream.
// Bypasses adk-rust entirely (Claude Code owns its own tool loop). Multi-turn
// context is preserved by resuming Claude's own session (`--resume`).
// ---------------------------------------------------------------------------

async fn ask_via_claude_cli(
    pool: Option<PgPool>,
    question: &str,
    cfg: &EngineConfig,
    resume_session_id: Option<String>,
    mcp_url: Option<String>,
    auth_header: Option<String>,
) -> Response {
    let run_id = uuid::Uuid::new_v4();
    let started_at = Utc::now();
    let start = Instant::now();
    let model = format!("claude_cli/{}", cfg.model);

    info!(run_id = %run_id, model = %model, resume = ?resume_session_id, mcp = mcp_url.is_some(), "claude_cli ask starting");

    let (ui, rx) = ui_stream::channel();
    ui.start(&run_id.to_string());
    ui.start_step();
    ui.data("model", json!({ "model": model }));

    let question_owned = question.to_string();
    let model_label = cfg.model.clone();
    tokio::spawn(async move {
        let mut answer = String::new();
        let mut errored: Option<String> = None;
        // Claude's own session id, echoed to the client so the next turn can
        // resume this conversation.
        let mut claude_session = String::new();
        let mut total_cost_usd: Option<f64> = None;
        let mut num_turns: u32 = 0;

        // Point the agent at our own MCP server so it can query the user's data.
        let mcp = mcp_url.map(|url| claude_cli::McpConfig { url, auth_header });

        let mut events = match claude_cli::run_stream(
            &question_owned,
            Some(&model_label),
            resume_session_id.as_deref(),
            None,
            mcp.as_ref(),
        ) {
            Ok(rx) => rx,
            Err(e) => {
                ui.error(&e.to_string());
                ui.data("usage", json!({ "run_id": run_id.to_string(), "elapsed_ms": start.elapsed().as_millis() as u64 }));
                ui.finish_step();
                ui.finish();
                ui.done();
                let _ = persist_run(
                    pool.as_ref(),
                    run_id,
                    &question_owned,
                    &model,
                    kyma_core::tenant::DEFAULT_TENANT.as_uuid(),
                    None,
                    started_at,
                    Utc::now(),
                    "error",
                    &Value::Null,
                    &json!([{ "event": "run_error", "data": { "message": e.to_string() } }]),
                )
                .await;
                return;
            }
        };

        while let Some(ev) = events.recv().await {
            match ev {
                claude_cli::ClaudeEvent::Init { session_id } => {
                    claude_session = session_id.clone();
                    ui.data("session", json!({ "sessionId": session_id }));
                }
                claude_cli::ClaudeEvent::TextStart { block_id } => ui.text_start(&block_id),
                claude_cli::ClaudeEvent::TextDelta { block_id, text } => {
                    answer.push_str(&text);
                    ui.text_delta(&block_id, &text);
                }
                claude_cli::ClaudeEvent::TextEnd { block_id } => ui.text_end(&block_id),
                claude_cli::ClaudeEvent::ThinkingStart { block_id } => ui.reasoning_start(&block_id),
                claude_cli::ClaudeEvent::ThinkingDelta { block_id, text } => {
                    ui.reasoning_delta(&block_id, &text)
                }
                claude_cli::ClaudeEvent::ThinkingEnd { block_id } => ui.reasoning_end(&block_id),
                claude_cli::ClaudeEvent::ToolUse { id, name, input } => {
                    ui.tool_input_available(&id, &name, input)
                }
                claude_cli::ClaudeEvent::ToolResult {
                    id,
                    output,
                    is_error,
                } => {
                    if is_error {
                        let txt = output
                            .as_str()
                            .map(str::to_string)
                            .unwrap_or_else(|| output.to_string());
                        ui.tool_output_error(&id, &txt);
                    } else {
                        ui.tool_output_available(&id, output);
                    }
                }
                claude_cli::ClaudeEvent::Result {
                    session_id,
                    total_cost_usd: cost,
                    num_turns: turns,
                    is_error,
                    ..
                } => {
                    if claude_session.is_empty() {
                        claude_session = session_id;
                    }
                    total_cost_usd = cost;
                    num_turns = turns;
                    if is_error {
                        errored.get_or_insert_with(|| "claude reported an error".to_string());
                    }
                }
                claude_cli::ClaudeEvent::Error { message } => {
                    warn!(run_id = %run_id, message = %message, "claude_cli error");
                    ui.error(&message);
                    errored = Some(message);
                }
            }
        }

        ui.data(
            "usage",
            json!({
                "run_id": run_id.to_string(),
                "elapsed_ms": start.elapsed().as_millis() as u64,
                "total_cost_usd": total_cost_usd,
                "num_turns": num_turns,
                "session_id": claude_session,
            }),
        );
        ui.finish_step();
        ui.finish();
        ui.done();

        let _ = persist_run(
            pool.as_ref(),
            run_id,
            &question_owned,
            &model,
            kyma_core::tenant::DEFAULT_TENANT.as_uuid(),
            None,
            started_at,
            Utc::now(),
            if errored.is_some() { "error" } else { "success" },
            &Value::String(answer.clone()),
            &json!([{ "event": "answer_final", "data": { "text": answer } }]),
        )
        .await;
    });

    ui_stream::response(rx)
}