microclaw-sdk 0.31.0

Official Rust SDK for embedding MicroClaw agents, Skills, and Workers
Documentation
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
use serde_json::Value;
use std::sync::{Arc, RwLock};

#[cfg(feature = "full")]
use std::path::{Path, PathBuf};

use crate::{AgentId, AgentProfile, RunRequest, ToolPolicy};
pub use microclaw_engine::{
    AgentHandle, ControlRequest, ExecutionContext, ExecutionResult, LocalWorker, RemoteWorker,
    RemoteWorkerOptions, RunController, RunExecutor, RunHandle, Runtime, RuntimeBuildError,
    RuntimeBuilder, RuntimeStats, Worker, WorkerConnection, WorkerTransport,
};

#[cfg(feature = "remote-worker")]
pub use microclaw_engine::{WebSocketWorkerTransport, WorkerHost};

/// Embedder tool gate (permission rules, hooks); see [`MicroClawBuilder::tool_gate`].
pub use microclaw_engine::tool_gate::{
    ToolGate, ToolGateCall, ToolGateDecision, ToolGateOutcome, ToolGateResult,
};

/// `RunRequest::metadata` key. Set it to `true` and a tool call that needs a
/// human pauses the run: the Agent Engine emits `ApprovalRequired` and waits
/// for `RunController::resolve_approval_confirmed(approval_id, "1" | "2" | "3")`
/// (approve once, always allow the tool in this session, deny) instead of
/// ending the run with a text prompt that the next message answers.
pub const INTERACTIVE_APPROVALS: &str = microclaw_engine::headless::INTERACTIVE_APPROVALS_KEY;

/// `RunRequest::metadata` key for an image attached to the prompt:
/// `{"media_type": "image/png", "data": "<base64>"}`.
#[cfg(feature = "full")]
pub const IMAGE_METADATA: &str = microclaw_engine::headless::IMAGE_KEY;

/// A workspace checkpoint (see `MicroClaw::checkpoint`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Checkpoint {
    /// Abbreviated commit id; pass it to `restore_checkpoint`.
    pub commit: String,
    pub label: String,
    /// RFC 3339.
    pub timestamp: String,
}

#[cfg(feature = "full")]
impl From<microclaw_engine::headless::HeadlessCheckpoint> for Checkpoint {
    fn from(c: microclaw_engine::headless::HeadlessCheckpoint) -> Self {
        Self {
            commit: c.commit,
            label: c.label,
            timestamp: c.timestamp,
        }
    }
}

/// Token usage of one session.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SessionUsage {
    pub requests: i64,
    pub input_tokens: i64,
    pub output_tokens: i64,
    pub by_model: Vec<ModelUsage>,
}

/// Result of compacting a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionCompaction {
    pub messages_before: usize,
    pub messages_after: usize,
    pub tokens_before: usize,
    pub tokens_after: usize,
    /// `none`, `pruned`, `summarized` or `fallback`.
    pub method: String,
}

/// How full a session's context is (estimates; see `MicroClaw::context_usage`).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ContextUsage {
    pub model: String,
    /// The model's context window (tokens).
    pub window: usize,
    /// Tokens kept free for the reply.
    pub reserved_output: usize,
    /// Tokens at which automatic compaction starts (0: disabled).
    pub auto_compact_threshold: usize,
    /// Tokens the next request carries (measured when available).
    pub used_tokens: usize,
    /// Input tokens of the last request, as reported by the provider.
    pub last_request_tokens: Option<usize>,
    pub summary_tokens: usize,
    pub user_tokens: usize,
    pub assistant_tokens: usize,
    pub tool_call_tokens: usize,
    pub tool_result_tokens: usize,
    pub image_tokens: usize,
    pub messages: usize,
    /// How long the provider keeps this session's prompt cache, when the
    /// engine marks cache breakpoints for it (Anthropic); `None` otherwise.
    pub prompt_cache_ttl: Option<std::time::Duration>,
}

impl ContextUsage {
    /// Share of the usable window (window minus the output reserve) in use.
    pub fn percent_used(&self) -> u8 {
        let usable = self.window.saturating_sub(self.reserved_output).max(1);
        ((self.used_tokens * 100) / usable).min(100) as u8
    }
}

/// Token usage of one model within a session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelUsage {
    pub model: String,
    pub requests: i64,
    pub input_tokens: i64,
    pub output_tokens: i64,
}

/// Who wrote a [`SessionMessage`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SessionMessageRole {
    User,
    Agent,
}

/// One stored message of a named session (see `MicroClaw::session_messages`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionMessage {
    pub role: SessionMessageRole,
    pub content: String,
    /// RFC 3339.
    pub timestamp: String,
}

/// An SDK-level error that does not expose Server or Agent Engine implementation types.
#[derive(Debug, thiserror::Error)]
pub enum SdkError {
    #[error("invalid SDK configuration: {0}")]
    Configuration(String),
    #[error("could not initialize the Agent Engine: {0}")]
    Initialization(String),
    #[error("could not build the runtime: {0}")]
    Runtime(String),
    #[error("agent name must not be empty")]
    EmptyAgentName,
    #[error("Skill '{0}' is not available in this runtime")]
    SkillUnavailable(String),
    #[error("could not manage Skill state: {0}")]
    SkillManagement(String),
}

impl From<RuntimeBuildError> for SdkError {
    fn from(error: RuntimeBuildError) -> Self {
        Self::Runtime(error.to_string())
    }
}

/// Stable category for handling SDK failures without parsing display strings.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SdkErrorCode {
    Configuration,
    Initialization,
    Runtime,
    InvalidAgent,
    SkillUnavailable,
    SkillManagement,
}

impl SdkError {
    pub fn code(&self) -> SdkErrorCode {
        match self {
            Self::Configuration(_) => SdkErrorCode::Configuration,
            Self::Initialization(_) => SdkErrorCode::Initialization,
            Self::Runtime(_) => SdkErrorCode::Runtime,
            Self::EmptyAgentName => SdkErrorCode::InvalidAgent,
            Self::SkillUnavailable(_) => SdkErrorCode::SkillUnavailable,
            Self::SkillManagement(_) => SdkErrorCode::SkillManagement,
        }
    }

    pub fn retryable(&self) -> bool {
        matches!(self, Self::Initialization(_))
    }
}

/// Stable, UI-neutral metadata for one discovered Skill.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SkillSummary {
    pub name: String,
    pub description: String,
    pub source: String,
    pub version: Option<String>,
    pub enabled: bool,
    pub available: bool,
    pub unavailable_reason: Option<String>,
}

/// A snapshot of Skills discovered while the SDK runtime was initialized.
#[derive(Debug, Clone, Default)]
pub struct SkillCatalog {
    skills: Vec<SkillSummary>,
}

/// Stable SDK projection of a durable task delegated by the Main Agent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DelegatedTask {
    pub run_id: String,
    pub parent_run_id: Option<String>,
    pub depth: u32,
    pub label: Option<String>,
    pub task: String,
    pub status: DelegatedTaskStatus,
    pub progress: Option<String>,
    pub result: Option<String>,
    pub error: Option<String>,
    pub created_at: String,
    pub started_at: Option<String>,
    pub finished_at: Option<String>,
    pub cancel_requested: bool,
}

/// A point in a session's conversation ([`MicroClaw::session_mark`]).
/// Valid within the process that took it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SessionMark {
    messages: usize,
    fingerprint: u64,
}

impl SessionMark {
    /// Messages in the conversation at that point.
    pub fn messages(&self) -> usize {
        self.messages
    }
}

/// A shell command running (or finished) in the background of a session:
/// started with `run_in_background`, or moved there by the user while it ran.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BackgroundJob {
    pub id: String,
    pub command: String,
    /// RFC 3339.
    pub started_at: String,
    /// `None` while the command runs.
    pub exit_code: Option<i32>,
}

/// Lifecycle state for a task delegated by the Main Agent.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum DelegatedTaskStatus {
    Accepted,
    Queued,
    Running,
    Completed,
    Failed,
    Cancelled,
    BudgetExceeded,
    Unknown(String),
}

impl DelegatedTaskStatus {
    pub fn as_str(&self) -> &str {
        match self {
            Self::Accepted => "accepted",
            Self::Queued => "queued",
            Self::Running => "running",
            Self::Completed => "completed",
            Self::Failed => "failed",
            Self::Cancelled => "cancelled",
            Self::BudgetExceeded => "budget_exceeded",
            Self::Unknown(status) => status,
        }
    }

    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            Self::Completed | Self::Failed | Self::Cancelled | Self::BudgetExceeded
        )
    }
}

impl From<String> for DelegatedTaskStatus {
    fn from(status: String) -> Self {
        match status.as_str() {
            "accepted" => Self::Accepted,
            "queued" => Self::Queued,
            "running" => Self::Running,
            "completed" => Self::Completed,
            "failed" => Self::Failed,
            "cancelled" | "canceled" => Self::Cancelled,
            "budget_exceeded" => Self::BudgetExceeded,
            _ => Self::Unknown(status),
        }
    }
}

/// Result of installing or updating a Skill package.
#[cfg(feature = "full")]
#[derive(Debug, Clone)]
pub struct SkillInstallResult {
    pub message: String,
    pub warnings: Vec<String>,
    pub skills: SkillCatalog,
}

/// Result of recoverably removing a Skill package.
#[cfg(feature = "full")]
#[derive(Debug, Clone)]
pub struct SkillRemovalResult {
    pub archived_at: PathBuf,
    pub skills: SkillCatalog,
}

impl SkillCatalog {
    pub fn new(skills: impl IntoIterator<Item = SkillSummary>) -> Self {
        Self {
            skills: skills.into_iter().collect(),
        }
    }

    pub fn all(&self) -> &[SkillSummary] {
        &self.skills
    }

    pub fn available(&self) -> impl Iterator<Item = &SkillSummary> {
        self.skills.iter().filter(|skill| skill.available)
    }

    pub fn find(&self, name: &str) -> Option<&SkillSummary> {
        self.skills.iter().find(|skill| skill.name == name)
    }
}

#[cfg(feature = "full")]
fn skill_catalog(skills: Vec<microclaw_engine::skills::SkillAvailability>) -> SkillCatalog {
    SkillCatalog::new(skills.into_iter().map(|skill| {
        let enabled = skill.reason.as_deref() != Some("Skill is disabled for this runtime.");
        SkillSummary {
            name: skill.meta.name,
            description: skill.meta.description,
            source: skill.meta.source,
            version: skill.meta.version,
            enabled,
            available: skill.available,
            unavailable_reason: skill.reason,
        }
    }))
}

/// A configured, embeddable MicroClaw runtime.
#[derive(Clone)]
pub struct MicroClaw {
    runtime: Runtime,
    skills: Arc<RwLock<SkillCatalog>>,
    #[cfg(feature = "full")]
    engine: Option<microclaw_engine::headless::HeadlessRuntime>,
    /// Caller channel of the engine runtime (policy and override scope).
    #[cfg(feature = "full")]
    caller_channel: String,
}

impl MicroClaw {
    /// Wrap an application-provided Runtime. This is the main entry point for `minimal` and
    /// `standard` consumers that implement their own [`RunExecutor`].
    pub fn from_runtime(runtime: Runtime) -> Self {
        Self {
            runtime,
            skills: Arc::new(RwLock::new(SkillCatalog::default())),
            #[cfg(feature = "full")]
            engine: None,
            #[cfg(feature = "full")]
            caller_channel: String::new(),
        }
    }

    /// Attach a host-provided Skill catalog to a custom Runtime.
    pub fn with_skill_catalog(mut self, skills: SkillCatalog) -> Self {
        self.skills = Arc::new(RwLock::new(skills));
        self
    }

    /// Start configuring a full Agent Engine from a MicroClaw YAML file.
    #[cfg(feature = "full")]
    pub fn builder(config_path: impl Into<PathBuf>) -> MicroClawBuilder {
        MicroClawBuilder::from_config_file(config_path)
    }

    /// Start configuring a full Agent Engine using MicroClaw's normal configuration discovery.
    #[cfg(feature = "full")]
    pub fn builder_from_environment() -> MicroClawBuilder {
        MicroClawBuilder::from_environment()
    }

    /// Configure an embedded Agent Engine entirely in Rust, without a Server YAML file.
    #[cfg(feature = "full")]
    pub fn configure(config: FullRuntimeConfig) -> MicroClawBuilder {
        MicroClawBuilder::from_runtime_config(config)
    }

    pub fn runtime(&self) -> &Runtime {
        &self.runtime
    }

    pub fn skills(&self) -> SkillCatalog {
        self.skills
            .read()
            .unwrap_or_else(|error| error.into_inner())
            .clone()
    }

    /// Reload Skills from disk and return the current catalog.
    #[cfg(feature = "full")]
    pub fn reload_skills(&self) -> Result<SkillCatalog, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
        })?;
        let catalog = skill_catalog(engine.reload_skill_catalog(true));
        *self
            .skills
            .write()
            .unwrap_or_else(|error| error.into_inner()) = catalog.clone();
        Ok(catalog)
    }

    /// Enable or disable one installed Skill for this Runtime.
    #[cfg(feature = "full")]
    pub fn set_skill_enabled(
        &self,
        name: impl AsRef<str>,
        enabled: bool,
    ) -> Result<SkillCatalog, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
        })?;
        engine
            .set_skill_enabled(name.as_ref(), enabled)
            .map_err(SdkError::SkillManagement)?;
        self.reload_skills()
    }

    /// Install or update a local, GitHub, or ClawHub Skill and refresh the catalog.
    #[cfg(feature = "full")]
    pub async fn install_skill(
        &self,
        reference: impl AsRef<str>,
    ) -> Result<SkillInstallResult, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
        })?;
        let outcome = engine
            .install_skill(reference.as_ref())
            .await
            .map_err(SdkError::SkillManagement)?;
        Ok(SkillInstallResult {
            message: outcome.message,
            warnings: outcome.warnings,
            skills: self.reload_skills()?,
        })
    }

    /// Import a Skill from a local directory containing `SKILL.md`.
    #[cfg(feature = "full")]
    pub async fn install_local_skill(
        &self,
        path: impl AsRef<Path>,
    ) -> Result<SkillInstallResult, SdkError> {
        let reference = path.as_ref().to_string_lossy().into_owned();
        self.install_skill(reference).await
    }

    /// Recoverably remove one Skill by moving it into the managed archive directory.
    #[cfg(feature = "full")]
    pub fn remove_skill(&self, name: impl AsRef<str>) -> Result<SkillRemovalResult, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
        })?;
        let archived_at = engine
            .archive_skill(name.as_ref())
            .map_err(SdkError::SkillManagement)?;
        Ok(SkillRemovalResult {
            archived_at,
            skills: self.reload_skills()?,
        })
    }

    /// List Subagent tasks delegated by the Main Agent in one session.
    #[cfg(feature = "full")]
    pub fn delegated_tasks(
        &self,
        session: impl AsRef<str>,
        limit: usize,
    ) -> Result<Vec<DelegatedTask>, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::Runtime("this Runtime has no configured Agent Engine".into())
        })?;
        engine
            .subagent_runs(session.as_ref(), limit)
            .map(|runs| {
                runs.into_iter()
                    .map(|run| DelegatedTask {
                        run_id: run.run_id,
                        parent_run_id: run.parent_run_id,
                        depth: run.depth,
                        label: run.label,
                        task: run.task,
                        status: run.status.into(),
                        progress: run.progress,
                        result: run.result,
                        error: run.error,
                        created_at: run.created_at,
                        started_at: run.started_at,
                        finished_at: run.finished_at,
                        cancel_requested: run.cancel_requested,
                    })
                    .collect()
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// The most recent `limit` messages of a named session, oldest first:
    /// user prompts (including steering) and the agent's final replies. Use
    /// it to show history when resuming a session. Empty when the session
    /// never ran.
    #[cfg(feature = "full")]
    pub fn session_messages(
        &self,
        session: impl AsRef<str>,
        limit: usize,
    ) -> Result<Vec<SessionMessage>, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::Runtime("this Runtime has no configured Agent Engine".into())
        })?;
        engine
            .session_messages(session.as_ref(), limit)
            .map(|messages| {
                messages
                    .into_iter()
                    .map(|message| SessionMessage {
                        role: if message.from_agent {
                            SessionMessageRole::Agent
                        } else {
                            SessionMessageRole::User
                        },
                        content: message.content,
                        timestamp: message.timestamp,
                    })
                    .collect()
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    #[cfg(feature = "full")]
    fn engine(&self) -> Result<&microclaw_engine::headless::HeadlessRuntime, SdkError> {
        self.engine
            .as_ref()
            .ok_or_else(|| SdkError::Runtime("this Runtime has no configured Agent Engine".into()))
    }

    /// Snapshot the session's workspace now (requires a `workspace`) and
    /// return the checkpoint holding its current state.
    #[cfg(feature = "full")]
    pub async fn checkpoint(
        &self,
        session: impl AsRef<str>,
        label: impl AsRef<str>,
    ) -> Result<Option<Checkpoint>, SdkError> {
        self.engine()?
            .checkpoint_session(&self.caller_channel, session.as_ref(), label.as_ref())
            .await
            .map(|c| c.map(Checkpoint::from))
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Recent workspace checkpoints of a session, newest first.
    #[cfg(feature = "full")]
    pub async fn checkpoints(
        &self,
        session: impl AsRef<str>,
        limit: usize,
    ) -> Result<Vec<Checkpoint>, SdkError> {
        self.engine()?
            .session_checkpoints(&self.caller_channel, session.as_ref(), limit)
            .await
            .map(|list| list.into_iter().map(Checkpoint::from).collect())
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// The current end of a session's conversation. Pass it to
    /// [`Self::rewind_session`] later to drop everything said after it.
    #[cfg(feature = "full")]
    pub async fn session_mark(&self, session: impl AsRef<str>) -> Result<SessionMark, SdkError> {
        self.engine()?
            .session_mark(session.as_ref())
            .await
            .map(|mark| SessionMark {
                messages: mark.messages,
                fingerprint: mark.fingerprint,
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Cut a session's conversation back to a [`SessionMark`] (the whole
    /// conversation is archived first). Fails when the conversation was
    /// compacted since the mark. Returns how many messages were removed.
    #[cfg(feature = "full")]
    pub async fn rewind_session(
        &self,
        session: impl AsRef<str>,
        mark: &SessionMark,
    ) -> Result<usize, SdkError> {
        self.engine()?
            .rewind_session_to(
                &self.caller_channel,
                session.as_ref(),
                &microclaw_engine::headless::SessionMark {
                    messages: mark.messages,
                    fingerprint: mark.fingerprint,
                },
            )
            .await
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Restore the workspace to a checkpoint. The current state is
    /// checkpointed first and returned, so the restore can be undone.
    #[cfg(feature = "full")]
    pub async fn restore_checkpoint(
        &self,
        session: impl AsRef<str>,
        commit: impl AsRef<str>,
    ) -> Result<Option<Checkpoint>, SdkError> {
        self.engine()?
            .restore_session_checkpoint(&self.caller_channel, session.as_ref(), commit.as_ref())
            .await
            .map(|c| c.map(Checkpoint::from))
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Token usage recorded for a session.
    #[cfg(feature = "full")]
    pub async fn session_usage(&self, session: impl AsRef<str>) -> Result<SessionUsage, SdkError> {
        self.engine()?
            .session_usage(session.as_ref())
            .await
            .map(|usage| SessionUsage {
                requests: usage.requests,
                input_tokens: usage.input_tokens,
                output_tokens: usage.output_tokens,
                by_model: usage
                    .by_model
                    .into_iter()
                    .map(
                        |(model, requests, input_tokens, output_tokens)| ModelUsage {
                            model,
                            requests,
                            input_tokens,
                            output_tokens,
                        },
                    )
                    .collect(),
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// The model the next run of a session uses.
    #[cfg(feature = "full")]
    pub async fn session_model(&self, session: impl AsRef<str>) -> Result<String, SdkError> {
        self.engine()?
            .session_model(&self.caller_channel, session.as_ref())
            .await
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Use another model for one session (`None` returns to the configured
    /// one). Lives as long as this runtime. Returns the effective model.
    #[cfg(feature = "full")]
    pub async fn set_session_model(
        &self,
        session: impl AsRef<str>,
        model: Option<&str>,
    ) -> Result<String, SdkError> {
        self.engine()?
            .set_session_model(&self.caller_channel, session.as_ref(), model)
            .await
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Summarize a session's older messages now, keeping the last
    /// `keep_recent` verbatim. Returns `(messages_before, messages_after)`.
    #[cfg(feature = "full")]
    pub async fn compact_session(
        &self,
        session: impl AsRef<str>,
        keep_recent: usize,
    ) -> Result<(usize, usize), SdkError> {
        self.compact_session_with(session, keep_recent, None)
            .await
            .map(|c| (c.messages_before, c.messages_after))
    }

    /// Summarize a session's older messages now; `focus` tells the
    /// summarizer what to keep (for example "the parser refactor").
    #[cfg(feature = "full")]
    pub async fn compact_session_with(
        &self,
        session: impl AsRef<str>,
        keep_recent: usize,
        focus: Option<&str>,
    ) -> Result<SessionCompaction, SdkError> {
        self.engine()?
            .compact_session(&self.caller_channel, session.as_ref(), keep_recent, focus)
            .await
            .map(|c| SessionCompaction {
                messages_before: c.messages_before,
                messages_after: c.messages_after,
                tokens_before: c.tokens_before,
                tokens_after: c.tokens_after,
                method: c.method,
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Start session `to` from a summary of session `from` focused on the
    /// next `goal`; `from` is unchanged. Returns the seeded context's
    /// estimated tokens.
    #[cfg(feature = "full")]
    pub async fn handoff_session(
        &self,
        from: impl AsRef<str>,
        to: impl AsRef<str>,
        goal: &str,
    ) -> Result<usize, SdkError> {
        self.engine()?
            .handoff_session(&self.caller_channel, from.as_ref(), to.as_ref(), goal)
            .await
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// How full a session's context is.
    #[cfg(feature = "full")]
    pub async fn context_usage(&self, session: impl AsRef<str>) -> Result<ContextUsage, SdkError> {
        self.engine()?
            .context_usage(&self.caller_channel, session.as_ref())
            .await
            .map(|u| ContextUsage {
                used_tokens: u.used(),
                model: u.model,
                window: u.window,
                reserved_output: u.reserved_output,
                auto_compact_threshold: u.auto_compact_threshold,
                last_request_tokens: u.last_request_tokens,
                summary_tokens: u.conversation.summary,
                user_tokens: u.conversation.user_text,
                assistant_tokens: u.conversation.assistant_text,
                tool_call_tokens: u.conversation.tool_calls,
                tool_result_tokens: u.conversation.tool_results,
                image_tokens: u.conversation.images,
                messages: u.conversation.messages,
                prompt_cache_ttl: u.prompt_cache_ttl,
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Copy a session's conversation into a new session `to`.
    #[cfg(feature = "full")]
    pub async fn fork_session(
        &self,
        from: impl AsRef<str>,
        to: impl AsRef<str>,
    ) -> Result<(), SdkError> {
        self.engine()?
            .fork_session(from.as_ref(), to.as_ref())
            .await
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Background shell commands of a session, oldest first.
    #[cfg(feature = "full")]
    pub fn background_jobs(
        &self,
        session: impl AsRef<str>,
    ) -> Result<Vec<BackgroundJob>, SdkError> {
        self.engine()?
            .background_jobs(&self.caller_channel, session.as_ref())
            .map(|jobs| {
                jobs.into_iter()
                    .map(|job| BackgroundJob {
                        id: job.id,
                        command: job.command,
                        started_at: job.started_at.to_rfc3339(),
                        exit_code: job.exit_code,
                    })
                    .collect()
            })
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Move the shell commands a session is running in the foreground to
    /// the background; the agent gets their ids and carries on. Returns the
    /// ids (empty when no command was running). Works while a run is in
    /// progress; needs a workspace runtime ([`MicroClawBuilder::workspace`]).
    #[cfg(feature = "full")]
    pub fn background_running_commands(
        &self,
        session: impl AsRef<str>,
    ) -> Result<Vec<String>, SdkError> {
        self.engine()?
            .detach_foreground_commands(&self.caller_channel, session.as_ref())
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// The last `max_bytes` of a background command's output.
    #[cfg(feature = "full")]
    pub fn background_job_output(
        &self,
        session: impl AsRef<str>,
        id: impl AsRef<str>,
        max_bytes: usize,
    ) -> Result<String, SdkError> {
        self.engine()?
            .background_job_output(
                &self.caller_channel,
                session.as_ref(),
                id.as_ref(),
                max_bytes,
            )
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Stop a background command. Returns its status line.
    #[cfg(feature = "full")]
    pub async fn kill_background_job(
        &self,
        session: impl AsRef<str>,
        id: impl AsRef<str>,
    ) -> Result<String, SdkError> {
        self.engine()?
            .kill_background_job(&self.caller_channel, session.as_ref(), id.as_ref())
            .await
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    /// Cancel one active Subagent task owned by the named session.
    #[cfg(feature = "full")]
    pub fn cancel_delegated_task(
        &self,
        session: impl AsRef<str>,
        run_id: impl AsRef<str>,
    ) -> Result<bool, SdkError> {
        let engine = self.engine.as_ref().ok_or_else(|| {
            SdkError::Runtime("this Runtime has no configured Agent Engine".into())
        })?;
        engine
            .cancel_subagent(session.as_ref(), run_id.as_ref())
            .map_err(|error| SdkError::Runtime(error.to_string()))
    }

    pub fn agent(&self, name: impl Into<String>) -> AgentBuilder<'_> {
        AgentBuilder {
            microclaw: self,
            profile: AgentProfile {
                name: name.into(),
                ..AgentProfile::default()
            },
        }
    }
}

/// A model provider the Agent Engine can be configured for, with its default
/// endpoint and suggested models (used by setup flows).
#[cfg(feature = "full")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelProvider {
    pub id: &'static str,
    pub label: &'static str,
    pub default_base_url: &'static str,
    pub models: &'static [&'static str],
}

/// The model providers known to this Agent Engine.
#[cfg(feature = "full")]
pub fn model_providers() -> Vec<ModelProvider> {
    microclaw_engine::setup::provider_catalog()
        .map(|entry| ModelProvider {
            id: entry.id,
            label: entry.label,
            default_base_url: entry.default_base_url,
            models: entry.models,
        })
        .collect()
}

/// Validate a MicroClaw configuration file for a channel-free embedded
/// runtime without starting the Agent Engine.
#[cfg(feature = "full")]
pub fn validate_config_file(path: impl AsRef<Path>) -> Result<(), SdkError> {
    microclaw_engine::config::Config::load_from_path_for_headless(path.as_ref())
        .map(|_| ())
        .map_err(|error| SdkError::Configuration(error.to_string()))
}

/// How shell commands are confined (see `MicroClawBuilder::shell_sandbox`).
#[cfg(feature = "full")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ShellSandbox {
    /// Run commands directly on the host.
    Off,
    /// Commands may read the machine (except credential directories such as
    /// `~/.ssh`, `~/.aws`, `~/.microclaw`) but write only the workspace, the
    /// temp directory, common tool caches and `writable_roots`.
    WorkspaceWrite {
        network: bool,
        writable_roots: Vec<PathBuf>,
    },
}

/// The OS sandbox available on this machine: `"bubblewrap"` (Linux) or
/// `"seatbelt"` (macOS), or `None`.
#[cfg(feature = "full")]
pub fn local_sandbox() -> Option<&'static str> {
    microclaw_engine::tool_runtime::local_sandbox::detect().map(|kind| kind.name())
}

/// Context settings for a coding workspace, applied where the configuration
/// still has the chat-oriented defaults: compaction by tokens instead of
/// message count, a larger verbatim tail, and whole source files in tool
/// results (old outputs are pruned instead of truncated up front).
#[cfg(feature = "full")]
fn apply_workspace_context_defaults(config: &mut microclaw_engine::config::Config) {
    if config.max_session_messages == 40 {
        config.max_session_messages = 0;
    }
    if config.compact_keep_recent_tokens == 0 {
        config.compact_keep_recent_tokens = 24_000;
    }
    config.explore_tool = true;
    config.context_budget_hint = true;
    config.detachable_foreground_commands = true;
    if config.tool_result_truncation_threshold_chars == 4_000 {
        config.tool_result_truncation_threshold_chars = 60_000;
        config.tool_result_truncation_head_chars = 40_000;
        config.tool_result_truncation_tail_chars = 10_000;
    }
}

/// Minimal provider configuration for a full embedded Agent Engine.
#[cfg(feature = "full")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FullRuntimeConfig {
    pub provider: String,
    pub model: String,
    pub api_key: String,
    pub base_url: Option<String>,
}

#[cfg(feature = "full")]
impl FullRuntimeConfig {
    pub fn new(
        provider: impl Into<String>,
        model: impl Into<String>,
        api_key: impl Into<String>,
    ) -> Self {
        Self {
            provider: provider.into(),
            model: model.into(),
            api_key: api_key.into(),
            base_url: None,
        }
    }

    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }
}

/// Builder for the configured Agent Engine exposed by the `full` SDK preset.
#[cfg(feature = "full")]
pub struct MicroClawBuilder {
    config_path: Option<PathBuf>,
    runtime_config: Option<FullRuntimeConfig>,
    data_dir: Option<PathBuf>,
    skills_dir: Option<PathBuf>,
    workspace: Option<PathBuf>,
    caller_channel: String,
    max_concurrent_runs: usize,
    shell_sandbox: Option<ShellSandbox>,
    command_reviewer: Option<Option<String>>,
    compact_instructions: Option<String>,
    context_window: Option<usize>,
    context_tools: bool,
    project_agents_dir: Option<PathBuf>,
    plugin_sources: PluginSources,
    tool_gate: Option<Arc<dyn ToolGate>>,
    summary_model: Option<String>,
    subagent_model: Option<String>,
}

/// What embedder plugins add to an engine: agent and skill directories and
/// MCP configuration files (engine `mcp.json` format). Earlier sources win
/// on a name clash, and the engine's own agents and skills win over all.
#[cfg(feature = "full")]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PluginSources {
    pub agents_dirs: Vec<PathBuf>,
    pub skills_dirs: Vec<PathBuf>,
    pub mcp_configs: Vec<PathBuf>,
}

#[cfg(feature = "full")]
impl MicroClawBuilder {
    pub fn from_config_file(path: impl Into<PathBuf>) -> Self {
        Self {
            config_path: Some(path.into()),
            runtime_config: None,
            data_dir: None,
            skills_dir: None,
            workspace: None,
            caller_channel: "embedded-app".into(),
            max_concurrent_runs: 4,
            shell_sandbox: None,
            command_reviewer: None,
            compact_instructions: None,
            context_window: None,
            context_tools: false,
            project_agents_dir: None,
            plugin_sources: PluginSources::default(),
            tool_gate: None,
            summary_model: None,
            subagent_model: None,
        }
    }

    pub fn from_environment() -> Self {
        Self {
            config_path: None,
            runtime_config: None,
            data_dir: None,
            skills_dir: None,
            workspace: None,
            caller_channel: "embedded-app".into(),
            max_concurrent_runs: 4,
            shell_sandbox: None,
            command_reviewer: None,
            compact_instructions: None,
            context_window: None,
            context_tools: false,
            project_agents_dir: None,
            plugin_sources: PluginSources::default(),
            tool_gate: None,
            summary_model: None,
            subagent_model: None,
        }
    }

    pub fn from_runtime_config(config: FullRuntimeConfig) -> Self {
        Self {
            config_path: None,
            runtime_config: Some(config),
            data_dir: None,
            skills_dir: None,
            workspace: None,
            caller_channel: "embedded-app".into(),
            max_concurrent_runs: 4,
            shell_sandbox: None,
            command_reviewer: None,
            compact_instructions: None,
            context_window: None,
            context_tools: false,
            project_agents_dir: None,
            plugin_sources: PluginSources::default(),
            tool_gate: None,
            summary_model: None,
            subagent_model: None,
        }
    }

    pub fn data_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.data_dir = Some(path.into());
        self
    }

    pub fn skills_dir(mut self, path: impl Into<PathBuf>) -> Self {
        self.skills_dir = Some(path.into());
        self
    }

    /// Select the direct working directory for an embedded foreground Agent.
    ///
    /// This enables checkpoints and keeps file tools rooted in the selected workspace.
    pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
        self.workspace = Some(path.into());
        self
    }

    pub fn caller_channel(mut self, channel: impl Into<String>) -> Self {
        self.caller_channel = channel.into();
        self
    }

    pub fn max_concurrent_runs(mut self, max: usize) -> Self {
        self.max_concurrent_runs = max;
        self
    }

    /// Run shell commands under the operating system's sandbox (overrides
    /// the configuration's `sandbox` section). When this machine has no
    /// working OS sandbox (see [`local_sandbox`]) commands run unsandboxed.
    pub fn shell_sandbox(mut self, sandbox: ShellSandbox) -> Self {
        self.shell_sandbox = Some(sandbox);
        self
    }

    /// Have a model annotate every approval request with a one-line verdict
    /// (`SAFE` / `CAUTION` / `DANGEROUS …`, the `advisory` of
    /// `ApprovalRequired`). `None` uses the configured main model.
    pub fn command_reviewer(mut self, model: Option<String>) -> Self {
        self.command_reviewer = Some(model);
        self
    }

    /// Extra instructions for compaction summaries: what a summary of this
    /// workspace's sessions must keep.
    pub fn compact_instructions(mut self, instructions: Option<String>) -> Self {
        self.compact_instructions = instructions.filter(|i| !i.trim().is_empty());
        self
    }

    /// Treat the model's context window as this many tokens (overrides the
    /// configured and built-in sizes; `None` keeps them).
    pub fn context_window(mut self, tokens: Option<usize>) -> Self {
        self.context_window = tokens.filter(|t| *t > 0);
        self
    }

    /// Offer the model `context_note` / `rewind_context` (experimental).
    pub fn context_tools(mut self, enabled: bool) -> Self {
        self.context_tools = enabled;
        self
    }

    /// Directory of project agent definitions (`<name>.md`) for the
    /// `explore` tool. Only pass directories you trust.
    pub fn project_agents_dir(mut self, dir: Option<PathBuf>) -> Self {
        self.project_agents_dir = dir;
        self
    }

    /// Agents, skills and MCP servers from embedder plugins. Only pass
    /// sources you trust: their MCP servers run as commands.
    pub fn plugin_sources(mut self, sources: PluginSources) -> Self {
        self.plugin_sources = sources;
        self
    }

    /// Consult `gate` before and after every tool call (main agent and
    /// sub-agents): permission rules, user hooks. See [`ToolGate`].
    pub fn tool_gate(mut self, gate: Arc<dyn ToolGate>) -> Self {
        self.tool_gate = Some(gate);
        self
    }

    /// Model for compaction summaries and handoffs (`None` keeps the
    /// configured one, which defaults to the main model).
    /// Model for sub-agents (`sessions_spawn` runs and `explore`) on the
    /// same provider; `None` uses the main model. A project agent's own
    /// `model` still wins.
    pub fn subagent_model(mut self, model: Option<String>) -> Self {
        self.subagent_model = model.filter(|m| !m.trim().is_empty());
        self
    }

    pub fn summary_model(mut self, model: Option<String>) -> Self {
        self.summary_model = model.filter(|m| !m.trim().is_empty());
        self
    }

    pub async fn build(self) -> Result<MicroClaw, SdkError> {
        use microclaw_engine::config::Config;
        use microclaw_engine::headless::HeadlessRuntime;

        let mut config = match (self.runtime_config, self.config_path) {
            (Some(config), _) => Config::for_embedded(
                config.provider,
                config.model,
                config.api_key,
                config.base_url,
            ),
            (None, Some(path)) => Config::load_from_path_for_headless(Path::new(&path)),
            (None, None) => Config::load(),
        }
        .map_err(|error| SdkError::Configuration(error.to_string()))?;
        if let Some(path) = self.data_dir {
            config.data_dir = path.to_string_lossy().into_owned();
        }
        if let Some(path) = self.skills_dir {
            config.skills_dir = Some(path.to_string_lossy().into_owned());
        }
        if let Some(path) = self.workspace {
            config.working_dir = path.to_string_lossy().into_owned();
            config.working_dir_isolation = microclaw_engine::config::WorkingDirIsolation::Direct;
            config.checkpoints_enabled = true;
            apply_workspace_context_defaults(&mut config);
        }
        if self.compact_instructions.is_some() {
            config.compact_instructions = self.compact_instructions;
        }
        if self.context_tools {
            config.context_tools = true;
        }
        if let Some(dir) = self.project_agents_dir {
            config.project_agents_dir = Some(dir.to_string_lossy().into_owned());
        }
        let lossy = |paths: Vec<PathBuf>| -> Vec<String> {
            paths
                .into_iter()
                .map(|p| p.to_string_lossy().into_owned())
                .collect()
        };
        config.extra_agents_dirs = lossy(self.plugin_sources.agents_dirs);
        config.extra_skills_dirs = lossy(self.plugin_sources.skills_dirs);
        config.extra_mcp_configs = lossy(self.plugin_sources.mcp_configs);
        if let Some(model) = self.subagent_model {
            config.aux_models.subagent = Some(model);
        }
        if let Some(model) = self.summary_model {
            config.aux_models.compaction = Some(model);
        }
        if let Some(gate) = self.tool_gate {
            config.tool_gate = microclaw_engine::tool_gate::ToolGateHandle::new(gate);
        }
        if let Some(window) = self.context_window {
            config.model_context_window = window;
            let model = config.model.clone();
            config.model_context_windows.insert(model, window);
        }
        if let Some(model) = self.command_reviewer {
            config.aux_models.approval_reviewer = Some(
                model
                    .filter(|m| !m.trim().is_empty())
                    .unwrap_or_else(|| config.model.clone()),
            );
        }
        match self.shell_sandbox {
            Some(ShellSandbox::Off) => {
                config.sandbox.mode = microclaw_engine::config::SandboxMode::Off;
            }
            Some(ShellSandbox::WorkspaceWrite {
                network,
                writable_roots,
            }) if local_sandbox().is_some() => {
                config.sandbox.mode = microclaw_engine::config::SandboxMode::All;
                config.sandbox.backend = microclaw_engine::config::SandboxBackend::Local;
                config.sandbox.no_network = !network;
                config.sandbox.require_runtime = false;
                config.sandbox.writable_roots = writable_roots
                    .into_iter()
                    .map(|p| p.to_string_lossy().into_owned())
                    .collect();
            }
            Some(ShellSandbox::WorkspaceWrite { .. }) => {
                config.sandbox.mode = microclaw_engine::config::SandboxMode::Off;
            }
            None => {}
        }
        let engine = HeadlessRuntime::load(config)
            .await
            .map_err(|error| SdkError::Initialization(error.to_string()))?;
        let skills = skill_catalog(engine.skill_catalog(true));
        let runtime = engine
            .clone()
            .into_embedded_runtime(self.caller_channel.clone(), self.max_concurrent_runs)?;
        Ok(MicroClaw {
            runtime,
            skills: Arc::new(RwLock::new(skills)),
            engine: Some(engine),
            caller_channel: self.caller_channel,
        })
    }
}

/// Builder for an Agent identity and its selected Skills.
pub struct AgentBuilder<'a> {
    microclaw: &'a MicroClaw,
    profile: AgentProfile,
}

impl AgentBuilder<'_> {
    pub fn id(mut self, id: impl Into<AgentId>) -> Self {
        self.profile.id = Some(id.into());
        self
    }

    pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.profile.system_prompt = Some(prompt.into());
        self
    }

    pub fn skill(mut self, name: impl Into<String>) -> Self {
        self.profile.skills.push(name.into());
        self
    }

    pub fn skills<I, S>(mut self, names: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.profile
            .skills
            .extend(names.into_iter().map(Into::into));
        self
    }

    pub fn tool_policy(mut self, policy: ToolPolicy) -> Self {
        self.profile.tool_policy = policy;
        self
    }

    pub fn metadata(mut self, key: impl Into<String>, value: Value) -> Self {
        self.profile.metadata.insert(key.into(), value);
        self
    }

    pub fn build(mut self) -> Result<Agent, SdkError> {
        self.profile.name = self.profile.name.trim().to_owned();
        if self.profile.name.is_empty() {
            return Err(SdkError::EmptyAgentName);
        }
        self.profile.skills.sort();
        self.profile.skills.dedup();
        for name in &self.profile.skills {
            let available = self
                .microclaw
                .skills()
                .find(name)
                .is_some_and(|skill| skill.available);
            if !available {
                return Err(SdkError::SkillUnavailable(name.clone()));
            }
        }
        Ok(Agent {
            handle: self.microclaw.runtime.agent(self.profile),
        })
    }
}

/// A reusable Agent handle with a fixed identity, prompt, Skills, and tool policy.
#[derive(Clone)]
pub struct Agent {
    handle: AgentHandle,
}

impl Agent {
    pub fn profile(&self) -> &AgentProfile {
        self.handle.profile()
    }

    pub fn run(&self, prompt: impl Into<String>) -> RunHandle {
        self.handle.run(RunRequest::new(prompt))
    }

    pub fn run_request(&self, request: RunRequest) -> RunHandle {
        self.handle.run(request)
    }
}

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

    use super::*;
    use crate::RuntimeError;

    struct Echo;

    #[async_trait]
    impl RunExecutor for Echo {
        async fn execute(
            &self,
            _profile: AgentProfile,
            request: RunRequest,
            _context: ExecutionContext,
        ) -> Result<ExecutionResult, RuntimeError> {
            Ok(ExecutionResult::new("sdk-test", request.prompt))
        }
    }

    fn test_sdk(skills: Vec<SkillSummary>) -> MicroClaw {
        MicroClaw::from_runtime(Runtime::builder().executor(Echo).build().unwrap())
            .with_skill_catalog(SkillCatalog::new(skills))
    }

    #[tokio::test]
    async fn agent_builder_creates_a_reusable_agent() {
        let sdk = test_sdk(vec![SkillSummary {
            name: "review".into(),
            description: "Review code".into(),
            source: "test".into(),
            version: Some("1".into()),
            enabled: true,
            available: true,
            unavailable_reason: None,
        }]);
        let agent = sdk
            .agent(" reviewer ")
            .id("agent-1")
            .skill("review")
            .skill("review")
            .build()
            .unwrap();

        assert_eq!(agent.profile().name, "reviewer");
        assert_eq!(agent.profile().skills, vec!["review"]);
        assert_eq!(
            agent.run("hello").result().await.unwrap().final_text,
            "hello"
        );
    }

    #[test]
    fn agent_builder_rejects_unknown_or_unavailable_skills() {
        let sdk = test_sdk(Vec::new());
        let error = match sdk.agent("reviewer").skill("missing").build() {
            Ok(_) => panic!("unknown Skill should be rejected"),
            Err(error) => error,
        };
        assert!(matches!(error, SdkError::SkillUnavailable(name) if name == "missing"));
    }

    #[test]
    fn sdk_errors_have_stable_codes() {
        let error = SdkError::EmptyAgentName;
        assert_eq!(error.code(), SdkErrorCode::InvalidAgent);
        assert!(!error.retryable());
    }

    #[test]
    fn delegated_task_status_is_typed_and_forward_compatible() {
        assert!(DelegatedTaskStatus::from("completed".to_string()).is_terminal());
        assert!(!DelegatedTaskStatus::from("running".to_string()).is_terminal());
        assert_eq!(
            DelegatedTaskStatus::from("future_state".to_string()).as_str(),
            "future_state"
        );
    }

    #[cfg(feature = "full")]
    #[tokio::test]
    async fn full_runtime_reloads_and_toggles_skills_without_restart() {
        let directory = tempfile::tempdir().unwrap();
        let skills_dir = directory.path().join("skills");
        let first = skills_dir.join("sdk-first");
        std::fs::create_dir_all(&first).unwrap();
        std::fs::write(
            first.join("SKILL.md"),
            "---\nname: sdk-first\ndescription: first SDK skill\n---\nUse the first skill.\n",
        )
        .unwrap();

        let sdk = MicroClaw::configure(FullRuntimeConfig::new("ollama", "local", ""))
            .data_dir(directory.path().join("data"))
            .skills_dir(&skills_dir)
            .build()
            .await
            .unwrap();
        assert!(sdk.skills().find("sdk-first").unwrap().enabled);

        let disabled = sdk.set_skill_enabled("sdk-first", false).unwrap();
        let first = disabled.find("sdk-first").unwrap();
        assert!(!first.enabled);
        assert!(!first.available);

        let second = directory.path().join("sdk-second");
        std::fs::create_dir_all(&second).unwrap();
        std::fs::write(
            second.join("SKILL.md"),
            "---\nname: sdk-second\ndescription: second SDK skill\n---\nUse the second skill.\n",
        )
        .unwrap();
        assert!(sdk.skills().find("sdk-second").is_none());
        let installed = sdk.install_local_skill(&second).await.unwrap();
        assert!(installed.skills.find("sdk-second").is_some());
        let removed = sdk.remove_skill("sdk-second").unwrap();
        assert!(removed.archived_at.join("SKILL.md").is_file());
        assert!(removed.skills.find("sdk-second").is_none());
    }

    #[cfg(feature = "full")]
    #[test]
    fn exposes_provider_catalog_and_config_validation() {
        let providers = model_providers();
        assert!(providers.iter().any(|p| p.id == "anthropic"));
        assert!(providers.iter().any(|p| p.id == "openai"));

        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("config.yaml");
        std::fs::write(&path, "llm_provider: ollama\nmodel: local\napi_key: \"\"\n").unwrap();
        validate_config_file(&path).unwrap();
        std::fs::write(&path, "llm_provider: [not, a, string]\n").unwrap();
        assert_eq!(
            validate_config_file(&path).unwrap_err().code(),
            SdkErrorCode::Configuration
        );
    }
}