1use serde_json::Value;
2use std::sync::{Arc, RwLock};
3
4#[cfg(feature = "full")]
5use std::path::{Path, PathBuf};
6
7use crate::{AgentId, AgentProfile, RunRequest, ToolPolicy};
8pub use microclaw_engine::{
9 AgentHandle, ControlRequest, ExecutionContext, ExecutionResult, LocalWorker, RemoteWorker,
10 RemoteWorkerOptions, RunController, RunExecutor, RunHandle, Runtime, RuntimeBuildError,
11 RuntimeBuilder, RuntimeStats, Worker, WorkerConnection, WorkerTransport,
12};
13
14#[cfg(feature = "remote-worker")]
15pub use microclaw_engine::{WebSocketWorkerTransport, WorkerHost};
16
17pub use microclaw_engine::tool_gate::{
19 ToolGate, ToolGateCall, ToolGateDecision, ToolGateOutcome, ToolGateResult,
20};
21
22pub const INTERACTIVE_APPROVALS: &str = microclaw_engine::headless::INTERACTIVE_APPROVALS_KEY;
28
29#[cfg(feature = "full")]
32pub const IMAGE_METADATA: &str = microclaw_engine::headless::IMAGE_KEY;
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct Checkpoint {
37 pub commit: String,
39 pub label: String,
40 pub timestamp: String,
42}
43
44#[cfg(feature = "full")]
45impl From<microclaw_engine::headless::HeadlessCheckpoint> for Checkpoint {
46 fn from(c: microclaw_engine::headless::HeadlessCheckpoint) -> Self {
47 Self {
48 commit: c.commit,
49 label: c.label,
50 timestamp: c.timestamp,
51 }
52 }
53}
54
55#[derive(Debug, Clone, Default, PartialEq, Eq)]
57pub struct SessionUsage {
58 pub requests: i64,
59 pub input_tokens: i64,
60 pub output_tokens: i64,
61 pub by_model: Vec<ModelUsage>,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct SessionCompaction {
67 pub messages_before: usize,
68 pub messages_after: usize,
69 pub tokens_before: usize,
70 pub tokens_after: usize,
71 pub method: String,
73}
74
75#[derive(Debug, Clone, Default, PartialEq, Eq)]
77pub struct ContextUsage {
78 pub model: String,
79 pub window: usize,
81 pub reserved_output: usize,
83 pub auto_compact_threshold: usize,
85 pub used_tokens: usize,
87 pub last_request_tokens: Option<usize>,
89 pub summary_tokens: usize,
90 pub user_tokens: usize,
91 pub assistant_tokens: usize,
92 pub tool_call_tokens: usize,
93 pub tool_result_tokens: usize,
94 pub image_tokens: usize,
95 pub messages: usize,
96 pub prompt_cache_ttl: Option<std::time::Duration>,
99}
100
101impl ContextUsage {
102 pub fn percent_used(&self) -> u8 {
104 let usable = self.window.saturating_sub(self.reserved_output).max(1);
105 ((self.used_tokens * 100) / usable).min(100) as u8
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ModelUsage {
112 pub model: String,
113 pub requests: i64,
114 pub input_tokens: i64,
115 pub output_tokens: i64,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum SessionMessageRole {
121 User,
122 Agent,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct SessionMessage {
128 pub role: SessionMessageRole,
129 pub content: String,
130 pub timestamp: String,
132}
133
134#[derive(Debug, thiserror::Error)]
136pub enum SdkError {
137 #[error("invalid SDK configuration: {0}")]
138 Configuration(String),
139 #[error("could not initialize the Agent Engine: {0}")]
140 Initialization(String),
141 #[error("could not build the runtime: {0}")]
142 Runtime(String),
143 #[error("agent name must not be empty")]
144 EmptyAgentName,
145 #[error("Skill '{0}' is not available in this runtime")]
146 SkillUnavailable(String),
147 #[error("could not manage Skill state: {0}")]
148 SkillManagement(String),
149}
150
151impl From<RuntimeBuildError> for SdkError {
152 fn from(error: RuntimeBuildError) -> Self {
153 Self::Runtime(error.to_string())
154 }
155}
156
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159#[non_exhaustive]
160pub enum SdkErrorCode {
161 Configuration,
162 Initialization,
163 Runtime,
164 InvalidAgent,
165 SkillUnavailable,
166 SkillManagement,
167}
168
169impl SdkError {
170 pub fn code(&self) -> SdkErrorCode {
171 match self {
172 Self::Configuration(_) => SdkErrorCode::Configuration,
173 Self::Initialization(_) => SdkErrorCode::Initialization,
174 Self::Runtime(_) => SdkErrorCode::Runtime,
175 Self::EmptyAgentName => SdkErrorCode::InvalidAgent,
176 Self::SkillUnavailable(_) => SdkErrorCode::SkillUnavailable,
177 Self::SkillManagement(_) => SdkErrorCode::SkillManagement,
178 }
179 }
180
181 pub fn retryable(&self) -> bool {
182 matches!(self, Self::Initialization(_))
183 }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
188pub struct SkillSummary {
189 pub name: String,
190 pub description: String,
191 pub source: String,
192 pub version: Option<String>,
193 pub enabled: bool,
194 pub available: bool,
195 pub unavailable_reason: Option<String>,
196}
197
198#[derive(Debug, Clone, Default)]
200pub struct SkillCatalog {
201 skills: Vec<SkillSummary>,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct DelegatedTask {
207 pub run_id: String,
208 pub parent_run_id: Option<String>,
209 pub depth: u32,
210 pub label: Option<String>,
211 pub task: String,
212 pub status: DelegatedTaskStatus,
213 pub progress: Option<String>,
214 pub result: Option<String>,
215 pub error: Option<String>,
216 pub created_at: String,
217 pub started_at: Option<String>,
218 pub finished_at: Option<String>,
219 pub cancel_requested: bool,
220}
221
222#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub struct SessionMark {
226 messages: usize,
227 fingerprint: u64,
228}
229
230impl SessionMark {
231 pub fn messages(&self) -> usize {
233 self.messages
234 }
235}
236
237#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct BackgroundJob {
241 pub id: String,
242 pub command: String,
243 pub started_at: String,
245 pub exit_code: Option<i32>,
247}
248
249#[derive(Debug, Clone, PartialEq, Eq)]
251#[non_exhaustive]
252pub enum DelegatedTaskStatus {
253 Accepted,
254 Queued,
255 Running,
256 Completed,
257 Failed,
258 Cancelled,
259 BudgetExceeded,
260 Unknown(String),
261}
262
263impl DelegatedTaskStatus {
264 pub fn as_str(&self) -> &str {
265 match self {
266 Self::Accepted => "accepted",
267 Self::Queued => "queued",
268 Self::Running => "running",
269 Self::Completed => "completed",
270 Self::Failed => "failed",
271 Self::Cancelled => "cancelled",
272 Self::BudgetExceeded => "budget_exceeded",
273 Self::Unknown(status) => status,
274 }
275 }
276
277 pub fn is_terminal(&self) -> bool {
278 matches!(
279 self,
280 Self::Completed | Self::Failed | Self::Cancelled | Self::BudgetExceeded
281 )
282 }
283}
284
285impl From<String> for DelegatedTaskStatus {
286 fn from(status: String) -> Self {
287 match status.as_str() {
288 "accepted" => Self::Accepted,
289 "queued" => Self::Queued,
290 "running" => Self::Running,
291 "completed" => Self::Completed,
292 "failed" => Self::Failed,
293 "cancelled" | "canceled" => Self::Cancelled,
294 "budget_exceeded" => Self::BudgetExceeded,
295 _ => Self::Unknown(status),
296 }
297 }
298}
299
300#[cfg(feature = "full")]
302#[derive(Debug, Clone)]
303pub struct SkillInstallResult {
304 pub message: String,
305 pub warnings: Vec<String>,
306 pub skills: SkillCatalog,
307}
308
309#[cfg(feature = "full")]
311#[derive(Debug, Clone)]
312pub struct SkillRemovalResult {
313 pub archived_at: PathBuf,
314 pub skills: SkillCatalog,
315}
316
317impl SkillCatalog {
318 pub fn new(skills: impl IntoIterator<Item = SkillSummary>) -> Self {
319 Self {
320 skills: skills.into_iter().collect(),
321 }
322 }
323
324 pub fn all(&self) -> &[SkillSummary] {
325 &self.skills
326 }
327
328 pub fn available(&self) -> impl Iterator<Item = &SkillSummary> {
329 self.skills.iter().filter(|skill| skill.available)
330 }
331
332 pub fn find(&self, name: &str) -> Option<&SkillSummary> {
333 self.skills.iter().find(|skill| skill.name == name)
334 }
335}
336
337#[cfg(feature = "full")]
338fn skill_catalog(skills: Vec<microclaw_engine::skills::SkillAvailability>) -> SkillCatalog {
339 SkillCatalog::new(skills.into_iter().map(|skill| {
340 let enabled = skill.reason.as_deref() != Some("Skill is disabled for this runtime.");
341 SkillSummary {
342 name: skill.meta.name,
343 description: skill.meta.description,
344 source: skill.meta.source,
345 version: skill.meta.version,
346 enabled,
347 available: skill.available,
348 unavailable_reason: skill.reason,
349 }
350 }))
351}
352
353#[derive(Clone)]
355pub struct MicroClaw {
356 runtime: Runtime,
357 skills: Arc<RwLock<SkillCatalog>>,
358 #[cfg(feature = "full")]
359 engine: Option<microclaw_engine::headless::HeadlessRuntime>,
360 #[cfg(feature = "full")]
362 caller_channel: String,
363}
364
365impl MicroClaw {
366 pub fn from_runtime(runtime: Runtime) -> Self {
369 Self {
370 runtime,
371 skills: Arc::new(RwLock::new(SkillCatalog::default())),
372 #[cfg(feature = "full")]
373 engine: None,
374 #[cfg(feature = "full")]
375 caller_channel: String::new(),
376 }
377 }
378
379 pub fn with_skill_catalog(mut self, skills: SkillCatalog) -> Self {
381 self.skills = Arc::new(RwLock::new(skills));
382 self
383 }
384
385 #[cfg(feature = "full")]
387 pub fn builder(config_path: impl Into<PathBuf>) -> MicroClawBuilder {
388 MicroClawBuilder::from_config_file(config_path)
389 }
390
391 #[cfg(feature = "full")]
393 pub fn builder_from_environment() -> MicroClawBuilder {
394 MicroClawBuilder::from_environment()
395 }
396
397 #[cfg(feature = "full")]
399 pub fn configure(config: FullRuntimeConfig) -> MicroClawBuilder {
400 MicroClawBuilder::from_runtime_config(config)
401 }
402
403 pub fn runtime(&self) -> &Runtime {
404 &self.runtime
405 }
406
407 pub fn skills(&self) -> SkillCatalog {
408 self.skills
409 .read()
410 .unwrap_or_else(|error| error.into_inner())
411 .clone()
412 }
413
414 #[cfg(feature = "full")]
416 pub fn reload_skills(&self) -> Result<SkillCatalog, SdkError> {
417 let engine = self.engine.as_ref().ok_or_else(|| {
418 SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
419 })?;
420 let catalog = skill_catalog(engine.reload_skill_catalog(true));
421 *self
422 .skills
423 .write()
424 .unwrap_or_else(|error| error.into_inner()) = catalog.clone();
425 Ok(catalog)
426 }
427
428 #[cfg(feature = "full")]
430 pub fn set_skill_enabled(
431 &self,
432 name: impl AsRef<str>,
433 enabled: bool,
434 ) -> Result<SkillCatalog, SdkError> {
435 let engine = self.engine.as_ref().ok_or_else(|| {
436 SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
437 })?;
438 engine
439 .set_skill_enabled(name.as_ref(), enabled)
440 .map_err(SdkError::SkillManagement)?;
441 self.reload_skills()
442 }
443
444 #[cfg(feature = "full")]
446 pub async fn install_skill(
447 &self,
448 reference: impl AsRef<str>,
449 ) -> Result<SkillInstallResult, SdkError> {
450 let engine = self.engine.as_ref().ok_or_else(|| {
451 SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
452 })?;
453 let outcome = engine
454 .install_skill(reference.as_ref())
455 .await
456 .map_err(SdkError::SkillManagement)?;
457 Ok(SkillInstallResult {
458 message: outcome.message,
459 warnings: outcome.warnings,
460 skills: self.reload_skills()?,
461 })
462 }
463
464 #[cfg(feature = "full")]
466 pub async fn install_local_skill(
467 &self,
468 path: impl AsRef<Path>,
469 ) -> Result<SkillInstallResult, SdkError> {
470 let reference = path.as_ref().to_string_lossy().into_owned();
471 self.install_skill(reference).await
472 }
473
474 #[cfg(feature = "full")]
476 pub fn remove_skill(&self, name: impl AsRef<str>) -> Result<SkillRemovalResult, SdkError> {
477 let engine = self.engine.as_ref().ok_or_else(|| {
478 SdkError::SkillManagement("this Runtime has no configured Agent Engine".into())
479 })?;
480 let archived_at = engine
481 .archive_skill(name.as_ref())
482 .map_err(SdkError::SkillManagement)?;
483 Ok(SkillRemovalResult {
484 archived_at,
485 skills: self.reload_skills()?,
486 })
487 }
488
489 #[cfg(feature = "full")]
491 pub fn delegated_tasks(
492 &self,
493 session: impl AsRef<str>,
494 limit: usize,
495 ) -> Result<Vec<DelegatedTask>, SdkError> {
496 let engine = self.engine.as_ref().ok_or_else(|| {
497 SdkError::Runtime("this Runtime has no configured Agent Engine".into())
498 })?;
499 engine
500 .subagent_runs(session.as_ref(), limit)
501 .map(|runs| {
502 runs.into_iter()
503 .map(|run| DelegatedTask {
504 run_id: run.run_id,
505 parent_run_id: run.parent_run_id,
506 depth: run.depth,
507 label: run.label,
508 task: run.task,
509 status: run.status.into(),
510 progress: run.progress,
511 result: run.result,
512 error: run.error,
513 created_at: run.created_at,
514 started_at: run.started_at,
515 finished_at: run.finished_at,
516 cancel_requested: run.cancel_requested,
517 })
518 .collect()
519 })
520 .map_err(|error| SdkError::Runtime(error.to_string()))
521 }
522
523 #[cfg(feature = "full")]
528 pub fn session_messages(
529 &self,
530 session: impl AsRef<str>,
531 limit: usize,
532 ) -> Result<Vec<SessionMessage>, SdkError> {
533 let engine = self.engine.as_ref().ok_or_else(|| {
534 SdkError::Runtime("this Runtime has no configured Agent Engine".into())
535 })?;
536 engine
537 .session_messages(session.as_ref(), limit)
538 .map(|messages| {
539 messages
540 .into_iter()
541 .map(|message| SessionMessage {
542 role: if message.from_agent {
543 SessionMessageRole::Agent
544 } else {
545 SessionMessageRole::User
546 },
547 content: message.content,
548 timestamp: message.timestamp,
549 })
550 .collect()
551 })
552 .map_err(|error| SdkError::Runtime(error.to_string()))
553 }
554
555 #[cfg(feature = "full")]
556 fn engine(&self) -> Result<µclaw_engine::headless::HeadlessRuntime, SdkError> {
557 self.engine
558 .as_ref()
559 .ok_or_else(|| SdkError::Runtime("this Runtime has no configured Agent Engine".into()))
560 }
561
562 #[cfg(feature = "full")]
565 pub async fn checkpoint(
566 &self,
567 session: impl AsRef<str>,
568 label: impl AsRef<str>,
569 ) -> Result<Option<Checkpoint>, SdkError> {
570 self.engine()?
571 .checkpoint_session(&self.caller_channel, session.as_ref(), label.as_ref())
572 .await
573 .map(|c| c.map(Checkpoint::from))
574 .map_err(|error| SdkError::Runtime(error.to_string()))
575 }
576
577 #[cfg(feature = "full")]
579 pub async fn checkpoints(
580 &self,
581 session: impl AsRef<str>,
582 limit: usize,
583 ) -> Result<Vec<Checkpoint>, SdkError> {
584 self.engine()?
585 .session_checkpoints(&self.caller_channel, session.as_ref(), limit)
586 .await
587 .map(|list| list.into_iter().map(Checkpoint::from).collect())
588 .map_err(|error| SdkError::Runtime(error.to_string()))
589 }
590
591 #[cfg(feature = "full")]
594 pub async fn session_mark(&self, session: impl AsRef<str>) -> Result<SessionMark, SdkError> {
595 self.engine()?
596 .session_mark(session.as_ref())
597 .await
598 .map(|mark| SessionMark {
599 messages: mark.messages,
600 fingerprint: mark.fingerprint,
601 })
602 .map_err(|error| SdkError::Runtime(error.to_string()))
603 }
604
605 #[cfg(feature = "full")]
609 pub async fn rewind_session(
610 &self,
611 session: impl AsRef<str>,
612 mark: &SessionMark,
613 ) -> Result<usize, SdkError> {
614 self.engine()?
615 .rewind_session_to(
616 &self.caller_channel,
617 session.as_ref(),
618 µclaw_engine::headless::SessionMark {
619 messages: mark.messages,
620 fingerprint: mark.fingerprint,
621 },
622 )
623 .await
624 .map_err(|error| SdkError::Runtime(error.to_string()))
625 }
626
627 #[cfg(feature = "full")]
630 pub async fn restore_checkpoint(
631 &self,
632 session: impl AsRef<str>,
633 commit: impl AsRef<str>,
634 ) -> Result<Option<Checkpoint>, SdkError> {
635 self.engine()?
636 .restore_session_checkpoint(&self.caller_channel, session.as_ref(), commit.as_ref())
637 .await
638 .map(|c| c.map(Checkpoint::from))
639 .map_err(|error| SdkError::Runtime(error.to_string()))
640 }
641
642 #[cfg(feature = "full")]
644 pub async fn session_usage(&self, session: impl AsRef<str>) -> Result<SessionUsage, SdkError> {
645 self.engine()?
646 .session_usage(session.as_ref())
647 .await
648 .map(|usage| SessionUsage {
649 requests: usage.requests,
650 input_tokens: usage.input_tokens,
651 output_tokens: usage.output_tokens,
652 by_model: usage
653 .by_model
654 .into_iter()
655 .map(
656 |(model, requests, input_tokens, output_tokens)| ModelUsage {
657 model,
658 requests,
659 input_tokens,
660 output_tokens,
661 },
662 )
663 .collect(),
664 })
665 .map_err(|error| SdkError::Runtime(error.to_string()))
666 }
667
668 #[cfg(feature = "full")]
670 pub async fn session_model(&self, session: impl AsRef<str>) -> Result<String, SdkError> {
671 self.engine()?
672 .session_model(&self.caller_channel, session.as_ref())
673 .await
674 .map_err(|error| SdkError::Runtime(error.to_string()))
675 }
676
677 #[cfg(feature = "full")]
680 pub async fn set_session_model(
681 &self,
682 session: impl AsRef<str>,
683 model: Option<&str>,
684 ) -> Result<String, SdkError> {
685 self.engine()?
686 .set_session_model(&self.caller_channel, session.as_ref(), model)
687 .await
688 .map_err(|error| SdkError::Runtime(error.to_string()))
689 }
690
691 #[cfg(feature = "full")]
694 pub async fn compact_session(
695 &self,
696 session: impl AsRef<str>,
697 keep_recent: usize,
698 ) -> Result<(usize, usize), SdkError> {
699 self.compact_session_with(session, keep_recent, None)
700 .await
701 .map(|c| (c.messages_before, c.messages_after))
702 }
703
704 #[cfg(feature = "full")]
707 pub async fn compact_session_with(
708 &self,
709 session: impl AsRef<str>,
710 keep_recent: usize,
711 focus: Option<&str>,
712 ) -> Result<SessionCompaction, SdkError> {
713 self.engine()?
714 .compact_session(&self.caller_channel, session.as_ref(), keep_recent, focus)
715 .await
716 .map(|c| SessionCompaction {
717 messages_before: c.messages_before,
718 messages_after: c.messages_after,
719 tokens_before: c.tokens_before,
720 tokens_after: c.tokens_after,
721 method: c.method,
722 })
723 .map_err(|error| SdkError::Runtime(error.to_string()))
724 }
725
726 #[cfg(feature = "full")]
730 pub async fn handoff_session(
731 &self,
732 from: impl AsRef<str>,
733 to: impl AsRef<str>,
734 goal: &str,
735 ) -> Result<usize, SdkError> {
736 self.engine()?
737 .handoff_session(&self.caller_channel, from.as_ref(), to.as_ref(), goal)
738 .await
739 .map_err(|error| SdkError::Runtime(error.to_string()))
740 }
741
742 #[cfg(feature = "full")]
744 pub async fn context_usage(&self, session: impl AsRef<str>) -> Result<ContextUsage, SdkError> {
745 self.engine()?
746 .context_usage(&self.caller_channel, session.as_ref())
747 .await
748 .map(|u| ContextUsage {
749 used_tokens: u.used(),
750 model: u.model,
751 window: u.window,
752 reserved_output: u.reserved_output,
753 auto_compact_threshold: u.auto_compact_threshold,
754 last_request_tokens: u.last_request_tokens,
755 summary_tokens: u.conversation.summary,
756 user_tokens: u.conversation.user_text,
757 assistant_tokens: u.conversation.assistant_text,
758 tool_call_tokens: u.conversation.tool_calls,
759 tool_result_tokens: u.conversation.tool_results,
760 image_tokens: u.conversation.images,
761 messages: u.conversation.messages,
762 prompt_cache_ttl: u.prompt_cache_ttl,
763 })
764 .map_err(|error| SdkError::Runtime(error.to_string()))
765 }
766
767 #[cfg(feature = "full")]
769 pub async fn fork_session(
770 &self,
771 from: impl AsRef<str>,
772 to: impl AsRef<str>,
773 ) -> Result<(), SdkError> {
774 self.engine()?
775 .fork_session(from.as_ref(), to.as_ref())
776 .await
777 .map_err(|error| SdkError::Runtime(error.to_string()))
778 }
779
780 #[cfg(feature = "full")]
782 pub fn background_jobs(
783 &self,
784 session: impl AsRef<str>,
785 ) -> Result<Vec<BackgroundJob>, SdkError> {
786 self.engine()?
787 .background_jobs(&self.caller_channel, session.as_ref())
788 .map(|jobs| {
789 jobs.into_iter()
790 .map(|job| BackgroundJob {
791 id: job.id,
792 command: job.command,
793 started_at: job.started_at.to_rfc3339(),
794 exit_code: job.exit_code,
795 })
796 .collect()
797 })
798 .map_err(|error| SdkError::Runtime(error.to_string()))
799 }
800
801 #[cfg(feature = "full")]
806 pub fn background_running_commands(
807 &self,
808 session: impl AsRef<str>,
809 ) -> Result<Vec<String>, SdkError> {
810 self.engine()?
811 .detach_foreground_commands(&self.caller_channel, session.as_ref())
812 .map_err(|error| SdkError::Runtime(error.to_string()))
813 }
814
815 #[cfg(feature = "full")]
817 pub fn background_job_output(
818 &self,
819 session: impl AsRef<str>,
820 id: impl AsRef<str>,
821 max_bytes: usize,
822 ) -> Result<String, SdkError> {
823 self.engine()?
824 .background_job_output(
825 &self.caller_channel,
826 session.as_ref(),
827 id.as_ref(),
828 max_bytes,
829 )
830 .map_err(|error| SdkError::Runtime(error.to_string()))
831 }
832
833 #[cfg(feature = "full")]
835 pub async fn kill_background_job(
836 &self,
837 session: impl AsRef<str>,
838 id: impl AsRef<str>,
839 ) -> Result<String, SdkError> {
840 self.engine()?
841 .kill_background_job(&self.caller_channel, session.as_ref(), id.as_ref())
842 .await
843 .map_err(|error| SdkError::Runtime(error.to_string()))
844 }
845
846 #[cfg(feature = "full")]
848 pub fn cancel_delegated_task(
849 &self,
850 session: impl AsRef<str>,
851 run_id: impl AsRef<str>,
852 ) -> Result<bool, SdkError> {
853 let engine = self.engine.as_ref().ok_or_else(|| {
854 SdkError::Runtime("this Runtime has no configured Agent Engine".into())
855 })?;
856 engine
857 .cancel_subagent(session.as_ref(), run_id.as_ref())
858 .map_err(|error| SdkError::Runtime(error.to_string()))
859 }
860
861 pub fn agent(&self, name: impl Into<String>) -> AgentBuilder<'_> {
862 AgentBuilder {
863 microclaw: self,
864 profile: AgentProfile {
865 name: name.into(),
866 ..AgentProfile::default()
867 },
868 }
869 }
870}
871
872#[cfg(feature = "full")]
875#[derive(Debug, Clone, PartialEq, Eq)]
876pub struct ModelProvider {
877 pub id: &'static str,
878 pub label: &'static str,
879 pub default_base_url: &'static str,
880 pub models: &'static [&'static str],
881}
882
883#[cfg(feature = "full")]
885pub fn model_providers() -> Vec<ModelProvider> {
886 microclaw_engine::setup::provider_catalog()
887 .map(|entry| ModelProvider {
888 id: entry.id,
889 label: entry.label,
890 default_base_url: entry.default_base_url,
891 models: entry.models,
892 })
893 .collect()
894}
895
896#[cfg(feature = "full")]
899pub fn validate_config_file(path: impl AsRef<Path>) -> Result<(), SdkError> {
900 microclaw_engine::config::Config::load_from_path_for_headless(path.as_ref())
901 .map(|_| ())
902 .map_err(|error| SdkError::Configuration(error.to_string()))
903}
904
905#[cfg(feature = "full")]
907#[derive(Debug, Clone, PartialEq, Eq)]
908pub enum ShellSandbox {
909 Off,
911 WorkspaceWrite {
915 network: bool,
916 writable_roots: Vec<PathBuf>,
917 },
918}
919
920#[cfg(feature = "full")]
923pub fn local_sandbox() -> Option<&'static str> {
924 microclaw_engine::tool_runtime::local_sandbox::detect().map(|kind| kind.name())
925}
926
927#[cfg(feature = "full")]
932fn apply_workspace_context_defaults(config: &mut microclaw_engine::config::Config) {
933 if config.max_session_messages == 40 {
934 config.max_session_messages = 0;
935 }
936 if config.compact_keep_recent_tokens == 0 {
937 config.compact_keep_recent_tokens = 24_000;
938 }
939 config.explore_tool = true;
940 config.context_budget_hint = true;
941 config.detachable_foreground_commands = true;
942 if config.tool_result_truncation_threshold_chars == 4_000 {
943 config.tool_result_truncation_threshold_chars = 60_000;
944 config.tool_result_truncation_head_chars = 40_000;
945 config.tool_result_truncation_tail_chars = 10_000;
946 }
947}
948
949#[cfg(feature = "full")]
951#[derive(Debug, Clone, PartialEq, Eq)]
952pub struct FullRuntimeConfig {
953 pub provider: String,
954 pub model: String,
955 pub api_key: String,
956 pub base_url: Option<String>,
957}
958
959#[cfg(feature = "full")]
960impl FullRuntimeConfig {
961 pub fn new(
962 provider: impl Into<String>,
963 model: impl Into<String>,
964 api_key: impl Into<String>,
965 ) -> Self {
966 Self {
967 provider: provider.into(),
968 model: model.into(),
969 api_key: api_key.into(),
970 base_url: None,
971 }
972 }
973
974 pub fn base_url(mut self, url: impl Into<String>) -> Self {
975 self.base_url = Some(url.into());
976 self
977 }
978}
979
980#[cfg(feature = "full")]
982pub struct MicroClawBuilder {
983 config_path: Option<PathBuf>,
984 runtime_config: Option<FullRuntimeConfig>,
985 data_dir: Option<PathBuf>,
986 skills_dir: Option<PathBuf>,
987 workspace: Option<PathBuf>,
988 caller_channel: String,
989 max_concurrent_runs: usize,
990 shell_sandbox: Option<ShellSandbox>,
991 command_reviewer: Option<Option<String>>,
992 compact_instructions: Option<String>,
993 context_window: Option<usize>,
994 context_tools: bool,
995 project_agents_dir: Option<PathBuf>,
996 plugin_sources: PluginSources,
997 tool_gate: Option<Arc<dyn ToolGate>>,
998 summary_model: Option<String>,
999 subagent_model: Option<String>,
1000}
1001
1002#[cfg(feature = "full")]
1006#[derive(Debug, Clone, Default, PartialEq, Eq)]
1007pub struct PluginSources {
1008 pub agents_dirs: Vec<PathBuf>,
1009 pub skills_dirs: Vec<PathBuf>,
1010 pub mcp_configs: Vec<PathBuf>,
1011}
1012
1013#[cfg(feature = "full")]
1014impl MicroClawBuilder {
1015 pub fn from_config_file(path: impl Into<PathBuf>) -> Self {
1016 Self {
1017 config_path: Some(path.into()),
1018 runtime_config: None,
1019 data_dir: None,
1020 skills_dir: None,
1021 workspace: None,
1022 caller_channel: "embedded-app".into(),
1023 max_concurrent_runs: 4,
1024 shell_sandbox: None,
1025 command_reviewer: None,
1026 compact_instructions: None,
1027 context_window: None,
1028 context_tools: false,
1029 project_agents_dir: None,
1030 plugin_sources: PluginSources::default(),
1031 tool_gate: None,
1032 summary_model: None,
1033 subagent_model: None,
1034 }
1035 }
1036
1037 pub fn from_environment() -> Self {
1038 Self {
1039 config_path: None,
1040 runtime_config: None,
1041 data_dir: None,
1042 skills_dir: None,
1043 workspace: None,
1044 caller_channel: "embedded-app".into(),
1045 max_concurrent_runs: 4,
1046 shell_sandbox: None,
1047 command_reviewer: None,
1048 compact_instructions: None,
1049 context_window: None,
1050 context_tools: false,
1051 project_agents_dir: None,
1052 plugin_sources: PluginSources::default(),
1053 tool_gate: None,
1054 summary_model: None,
1055 subagent_model: None,
1056 }
1057 }
1058
1059 pub fn from_runtime_config(config: FullRuntimeConfig) -> Self {
1060 Self {
1061 config_path: None,
1062 runtime_config: Some(config),
1063 data_dir: None,
1064 skills_dir: None,
1065 workspace: None,
1066 caller_channel: "embedded-app".into(),
1067 max_concurrent_runs: 4,
1068 shell_sandbox: None,
1069 command_reviewer: None,
1070 compact_instructions: None,
1071 context_window: None,
1072 context_tools: false,
1073 project_agents_dir: None,
1074 plugin_sources: PluginSources::default(),
1075 tool_gate: None,
1076 summary_model: None,
1077 subagent_model: None,
1078 }
1079 }
1080
1081 pub fn data_dir(mut self, path: impl Into<PathBuf>) -> Self {
1082 self.data_dir = Some(path.into());
1083 self
1084 }
1085
1086 pub fn skills_dir(mut self, path: impl Into<PathBuf>) -> Self {
1087 self.skills_dir = Some(path.into());
1088 self
1089 }
1090
1091 pub fn workspace(mut self, path: impl Into<PathBuf>) -> Self {
1095 self.workspace = Some(path.into());
1096 self
1097 }
1098
1099 pub fn caller_channel(mut self, channel: impl Into<String>) -> Self {
1100 self.caller_channel = channel.into();
1101 self
1102 }
1103
1104 pub fn max_concurrent_runs(mut self, max: usize) -> Self {
1105 self.max_concurrent_runs = max;
1106 self
1107 }
1108
1109 pub fn shell_sandbox(mut self, sandbox: ShellSandbox) -> Self {
1113 self.shell_sandbox = Some(sandbox);
1114 self
1115 }
1116
1117 pub fn command_reviewer(mut self, model: Option<String>) -> Self {
1121 self.command_reviewer = Some(model);
1122 self
1123 }
1124
1125 pub fn compact_instructions(mut self, instructions: Option<String>) -> Self {
1128 self.compact_instructions = instructions.filter(|i| !i.trim().is_empty());
1129 self
1130 }
1131
1132 pub fn context_window(mut self, tokens: Option<usize>) -> Self {
1135 self.context_window = tokens.filter(|t| *t > 0);
1136 self
1137 }
1138
1139 pub fn context_tools(mut self, enabled: bool) -> Self {
1141 self.context_tools = enabled;
1142 self
1143 }
1144
1145 pub fn project_agents_dir(mut self, dir: Option<PathBuf>) -> Self {
1148 self.project_agents_dir = dir;
1149 self
1150 }
1151
1152 pub fn plugin_sources(mut self, sources: PluginSources) -> Self {
1155 self.plugin_sources = sources;
1156 self
1157 }
1158
1159 pub fn tool_gate(mut self, gate: Arc<dyn ToolGate>) -> Self {
1162 self.tool_gate = Some(gate);
1163 self
1164 }
1165
1166 pub fn subagent_model(mut self, model: Option<String>) -> Self {
1172 self.subagent_model = model.filter(|m| !m.trim().is_empty());
1173 self
1174 }
1175
1176 pub fn summary_model(mut self, model: Option<String>) -> Self {
1177 self.summary_model = model.filter(|m| !m.trim().is_empty());
1178 self
1179 }
1180
1181 pub async fn build(self) -> Result<MicroClaw, SdkError> {
1182 use microclaw_engine::config::Config;
1183 use microclaw_engine::headless::HeadlessRuntime;
1184
1185 let mut config = match (self.runtime_config, self.config_path) {
1186 (Some(config), _) => Config::for_embedded(
1187 config.provider,
1188 config.model,
1189 config.api_key,
1190 config.base_url,
1191 ),
1192 (None, Some(path)) => Config::load_from_path_for_headless(Path::new(&path)),
1193 (None, None) => Config::load(),
1194 }
1195 .map_err(|error| SdkError::Configuration(error.to_string()))?;
1196 if let Some(path) = self.data_dir {
1197 config.data_dir = path.to_string_lossy().into_owned();
1198 }
1199 if let Some(path) = self.skills_dir {
1200 config.skills_dir = Some(path.to_string_lossy().into_owned());
1201 }
1202 if let Some(path) = self.workspace {
1203 config.working_dir = path.to_string_lossy().into_owned();
1204 config.working_dir_isolation = microclaw_engine::config::WorkingDirIsolation::Direct;
1205 config.checkpoints_enabled = true;
1206 apply_workspace_context_defaults(&mut config);
1207 }
1208 if self.compact_instructions.is_some() {
1209 config.compact_instructions = self.compact_instructions;
1210 }
1211 if self.context_tools {
1212 config.context_tools = true;
1213 }
1214 if let Some(dir) = self.project_agents_dir {
1215 config.project_agents_dir = Some(dir.to_string_lossy().into_owned());
1216 }
1217 let lossy = |paths: Vec<PathBuf>| -> Vec<String> {
1218 paths
1219 .into_iter()
1220 .map(|p| p.to_string_lossy().into_owned())
1221 .collect()
1222 };
1223 config.extra_agents_dirs = lossy(self.plugin_sources.agents_dirs);
1224 config.extra_skills_dirs = lossy(self.plugin_sources.skills_dirs);
1225 config.extra_mcp_configs = lossy(self.plugin_sources.mcp_configs);
1226 if let Some(model) = self.subagent_model {
1227 config.aux_models.subagent = Some(model);
1228 }
1229 if let Some(model) = self.summary_model {
1230 config.aux_models.compaction = Some(model);
1231 }
1232 if let Some(gate) = self.tool_gate {
1233 config.tool_gate = microclaw_engine::tool_gate::ToolGateHandle::new(gate);
1234 }
1235 if let Some(window) = self.context_window {
1236 config.model_context_window = window;
1237 let model = config.model.clone();
1238 config.model_context_windows.insert(model, window);
1239 }
1240 if let Some(model) = self.command_reviewer {
1241 config.aux_models.approval_reviewer = Some(
1242 model
1243 .filter(|m| !m.trim().is_empty())
1244 .unwrap_or_else(|| config.model.clone()),
1245 );
1246 }
1247 match self.shell_sandbox {
1248 Some(ShellSandbox::Off) => {
1249 config.sandbox.mode = microclaw_engine::config::SandboxMode::Off;
1250 }
1251 Some(ShellSandbox::WorkspaceWrite {
1252 network,
1253 writable_roots,
1254 }) if local_sandbox().is_some() => {
1255 config.sandbox.mode = microclaw_engine::config::SandboxMode::All;
1256 config.sandbox.backend = microclaw_engine::config::SandboxBackend::Local;
1257 config.sandbox.no_network = !network;
1258 config.sandbox.require_runtime = false;
1259 config.sandbox.writable_roots = writable_roots
1260 .into_iter()
1261 .map(|p| p.to_string_lossy().into_owned())
1262 .collect();
1263 }
1264 Some(ShellSandbox::WorkspaceWrite { .. }) => {
1265 config.sandbox.mode = microclaw_engine::config::SandboxMode::Off;
1266 }
1267 None => {}
1268 }
1269 let engine = HeadlessRuntime::load(config)
1270 .await
1271 .map_err(|error| SdkError::Initialization(error.to_string()))?;
1272 let skills = skill_catalog(engine.skill_catalog(true));
1273 let runtime = engine
1274 .clone()
1275 .into_embedded_runtime(self.caller_channel.clone(), self.max_concurrent_runs)?;
1276 Ok(MicroClaw {
1277 runtime,
1278 skills: Arc::new(RwLock::new(skills)),
1279 engine: Some(engine),
1280 caller_channel: self.caller_channel,
1281 })
1282 }
1283}
1284
1285pub struct AgentBuilder<'a> {
1287 microclaw: &'a MicroClaw,
1288 profile: AgentProfile,
1289}
1290
1291impl AgentBuilder<'_> {
1292 pub fn id(mut self, id: impl Into<AgentId>) -> Self {
1293 self.profile.id = Some(id.into());
1294 self
1295 }
1296
1297 pub fn system_prompt(mut self, prompt: impl Into<String>) -> Self {
1298 self.profile.system_prompt = Some(prompt.into());
1299 self
1300 }
1301
1302 pub fn skill(mut self, name: impl Into<String>) -> Self {
1303 self.profile.skills.push(name.into());
1304 self
1305 }
1306
1307 pub fn skills<I, S>(mut self, names: I) -> Self
1308 where
1309 I: IntoIterator<Item = S>,
1310 S: Into<String>,
1311 {
1312 self.profile
1313 .skills
1314 .extend(names.into_iter().map(Into::into));
1315 self
1316 }
1317
1318 pub fn tool_policy(mut self, policy: ToolPolicy) -> Self {
1319 self.profile.tool_policy = policy;
1320 self
1321 }
1322
1323 pub fn metadata(mut self, key: impl Into<String>, value: Value) -> Self {
1324 self.profile.metadata.insert(key.into(), value);
1325 self
1326 }
1327
1328 pub fn build(mut self) -> Result<Agent, SdkError> {
1329 self.profile.name = self.profile.name.trim().to_owned();
1330 if self.profile.name.is_empty() {
1331 return Err(SdkError::EmptyAgentName);
1332 }
1333 self.profile.skills.sort();
1334 self.profile.skills.dedup();
1335 for name in &self.profile.skills {
1336 let available = self
1337 .microclaw
1338 .skills()
1339 .find(name)
1340 .is_some_and(|skill| skill.available);
1341 if !available {
1342 return Err(SdkError::SkillUnavailable(name.clone()));
1343 }
1344 }
1345 Ok(Agent {
1346 handle: self.microclaw.runtime.agent(self.profile),
1347 })
1348 }
1349}
1350
1351#[derive(Clone)]
1353pub struct Agent {
1354 handle: AgentHandle,
1355}
1356
1357impl Agent {
1358 pub fn profile(&self) -> &AgentProfile {
1359 self.handle.profile()
1360 }
1361
1362 pub fn run(&self, prompt: impl Into<String>) -> RunHandle {
1363 self.handle.run(RunRequest::new(prompt))
1364 }
1365
1366 pub fn run_request(&self, request: RunRequest) -> RunHandle {
1367 self.handle.run(request)
1368 }
1369}
1370
1371#[cfg(test)]
1372mod tests {
1373 use async_trait::async_trait;
1374
1375 use super::*;
1376 use crate::RuntimeError;
1377
1378 struct Echo;
1379
1380 #[async_trait]
1381 impl RunExecutor for Echo {
1382 async fn execute(
1383 &self,
1384 _profile: AgentProfile,
1385 request: RunRequest,
1386 _context: ExecutionContext,
1387 ) -> Result<ExecutionResult, RuntimeError> {
1388 Ok(ExecutionResult::new("sdk-test", request.prompt))
1389 }
1390 }
1391
1392 fn test_sdk(skills: Vec<SkillSummary>) -> MicroClaw {
1393 MicroClaw::from_runtime(Runtime::builder().executor(Echo).build().unwrap())
1394 .with_skill_catalog(SkillCatalog::new(skills))
1395 }
1396
1397 #[tokio::test]
1398 async fn agent_builder_creates_a_reusable_agent() {
1399 let sdk = test_sdk(vec![SkillSummary {
1400 name: "review".into(),
1401 description: "Review code".into(),
1402 source: "test".into(),
1403 version: Some("1".into()),
1404 enabled: true,
1405 available: true,
1406 unavailable_reason: None,
1407 }]);
1408 let agent = sdk
1409 .agent(" reviewer ")
1410 .id("agent-1")
1411 .skill("review")
1412 .skill("review")
1413 .build()
1414 .unwrap();
1415
1416 assert_eq!(agent.profile().name, "reviewer");
1417 assert_eq!(agent.profile().skills, vec!["review"]);
1418 assert_eq!(
1419 agent.run("hello").result().await.unwrap().final_text,
1420 "hello"
1421 );
1422 }
1423
1424 #[test]
1425 fn agent_builder_rejects_unknown_or_unavailable_skills() {
1426 let sdk = test_sdk(Vec::new());
1427 let error = match sdk.agent("reviewer").skill("missing").build() {
1428 Ok(_) => panic!("unknown Skill should be rejected"),
1429 Err(error) => error,
1430 };
1431 assert!(matches!(error, SdkError::SkillUnavailable(name) if name == "missing"));
1432 }
1433
1434 #[test]
1435 fn sdk_errors_have_stable_codes() {
1436 let error = SdkError::EmptyAgentName;
1437 assert_eq!(error.code(), SdkErrorCode::InvalidAgent);
1438 assert!(!error.retryable());
1439 }
1440
1441 #[test]
1442 fn delegated_task_status_is_typed_and_forward_compatible() {
1443 assert!(DelegatedTaskStatus::from("completed".to_string()).is_terminal());
1444 assert!(!DelegatedTaskStatus::from("running".to_string()).is_terminal());
1445 assert_eq!(
1446 DelegatedTaskStatus::from("future_state".to_string()).as_str(),
1447 "future_state"
1448 );
1449 }
1450
1451 #[cfg(feature = "full")]
1452 #[tokio::test]
1453 async fn full_runtime_reloads_and_toggles_skills_without_restart() {
1454 let directory = tempfile::tempdir().unwrap();
1455 let skills_dir = directory.path().join("skills");
1456 let first = skills_dir.join("sdk-first");
1457 std::fs::create_dir_all(&first).unwrap();
1458 std::fs::write(
1459 first.join("SKILL.md"),
1460 "---\nname: sdk-first\ndescription: first SDK skill\n---\nUse the first skill.\n",
1461 )
1462 .unwrap();
1463
1464 let sdk = MicroClaw::configure(FullRuntimeConfig::new("ollama", "local", ""))
1465 .data_dir(directory.path().join("data"))
1466 .skills_dir(&skills_dir)
1467 .build()
1468 .await
1469 .unwrap();
1470 assert!(sdk.skills().find("sdk-first").unwrap().enabled);
1471
1472 let disabled = sdk.set_skill_enabled("sdk-first", false).unwrap();
1473 let first = disabled.find("sdk-first").unwrap();
1474 assert!(!first.enabled);
1475 assert!(!first.available);
1476
1477 let second = directory.path().join("sdk-second");
1478 std::fs::create_dir_all(&second).unwrap();
1479 std::fs::write(
1480 second.join("SKILL.md"),
1481 "---\nname: sdk-second\ndescription: second SDK skill\n---\nUse the second skill.\n",
1482 )
1483 .unwrap();
1484 assert!(sdk.skills().find("sdk-second").is_none());
1485 let installed = sdk.install_local_skill(&second).await.unwrap();
1486 assert!(installed.skills.find("sdk-second").is_some());
1487 let removed = sdk.remove_skill("sdk-second").unwrap();
1488 assert!(removed.archived_at.join("SKILL.md").is_file());
1489 assert!(removed.skills.find("sdk-second").is_none());
1490 }
1491
1492 #[cfg(feature = "full")]
1493 #[test]
1494 fn exposes_provider_catalog_and_config_validation() {
1495 let providers = model_providers();
1496 assert!(providers.iter().any(|p| p.id == "anthropic"));
1497 assert!(providers.iter().any(|p| p.id == "openai"));
1498
1499 let directory = tempfile::tempdir().unwrap();
1500 let path = directory.path().join("config.yaml");
1501 std::fs::write(&path, "llm_provider: ollama\nmodel: local\napi_key: \"\"\n").unwrap();
1502 validate_config_file(&path).unwrap();
1503 std::fs::write(&path, "llm_provider: [not, a, string]\n").unwrap();
1504 assert_eq!(
1505 validate_config_file(&path).unwrap_err().code(),
1506 SdkErrorCode::Configuration
1507 );
1508 }
1509}