Skip to main content

deepstrike_sdk/
lib.rs

1pub mod governance;
2pub mod harness;
3pub mod harness_loop;
4pub mod knowledge;
5pub mod memory;
6pub mod providers;
7pub mod run_event;
8pub mod runtime;
9pub mod safety;
10pub mod signals;
11pub mod tools;
12
13#[cfg(test)]
14mod tests;
15
16pub use deepstrike_core::context::renderer::RenderedContext;
17pub use deepstrike_core::governance::permission::PermissionAction;
18pub use deepstrike_core::governance::quota::ResourceQuota;
19pub use deepstrike_core::mm::memory::{
20    MemoryKind, MemoryMetadata, MemoryPolicy, MemoryQuery, MemoryRetrieval, MemoryWriteRequest,
21};
22// Workflow surface (DELIBERATE floor, not a gap): the Rust SDK has no `run_workflow` driver — the
23// node/python/wasm SDKs own async node execution. These re-exports are for MANUAL driving: build a
24// spec with the templates, hold a `WorkflowRun` (a pure state machine), call `ready_batch()` /
25// `spawn_info()` / `record_completion()` from your own executor. Everything the drivers do is
26// reachable this way; a batteries-included Rust driver lands only when a real consumer needs it.
27pub use deepstrike_core::orchestration::workflow::{
28    fanout_synthesize, gen_eval, generate_and_filter, verify_rules, WorkflowNode, WorkflowSpec,
29};
30pub use deepstrike_core::orchestration::workflow::{JudgeMatch, WorkflowRun, WorkflowSpawnInfo};
31pub use governance::{Governance, GovernanceVerdict};
32pub use harness::{CriterionResult, Harness, HarnessEvent, HarnessOutcome, HarnessRequest, QualityGate};
33pub use harness_loop::{EvalLoopHarness, HarnessLoop, SinglePassHarness, VerdictCtx, VerdictFn};
34pub use knowledge::KnowledgeSource;
35pub use memory::{DreamResult, DreamStore, InMemoryDreamStore, WorkingMemory};
36pub use providers::RuntimePolicy;
37pub use providers::anthropic::AnthropicProvider;
38pub use providers::openai::{OpenAIProvider, deepseek, kimi, minimax, ollama, qwen};
39pub use providers::{LLMProvider, ProviderRunState, ProviderToolSpec, StreamEvent, TokenUsage};
40pub use run_event::RunEvent;
41pub use runtime::{
42    ChainedCredentialVault, CredentialVault, EnvCredentialVault, InMemoryCredentialVault,
43};
44pub use runtime::{ExecutionPlane, LocalExecutionPlane};
45pub use runtime::{FileSessionLog, InMemorySessionLog, SessionEntry, SessionLog};
46pub use runtime::replay_provider::{ReplayProvider, ReplayProviderOpts};
47pub use runtime::replay_fixture::{extract_recorded_messages, extract_recorded_messages_from_entries};
48pub use runtime::eval::{judge, build_eval_messages, parse_verdict, verdict_output_schema, Criterion, Verdict};
49pub use runtime::{McpProxyPlane, McpServerConfig};
50pub use runtime::{
51    AttentionPolicy, GovernancePolicy, MemoryWriteRateLimit, NativeOsProfile, OsProfile,
52    SchedulerBudget, assert_native_profile, default_native_governance_policy, os_profile,
53    DEFAULT_NATIVE_ATTENTION_POLICY,
54};
55pub use runtime::{
56    MilestoneEvaluationContext, MilestoneEvaluationHandler, MilestonePolicy, RuntimeOptions,
57    RuntimeRunner, collect_text,
58};
59pub use runtime::{
60    PermissionRequest, PermissionRequestHandler, PermissionResponse, RunContext,
61    ToolSuspendHandler, ToolSuspendRequest,
62};
63pub use runtime::{ProcessSandboxPlane, SandboxOptions};
64pub use runtime::{RemoteVpcOptions, RemoteVpcPlane};
65pub use safety::{Permission, PermissionDecision, PermissionManager, PermissionMode};
66pub use signals::{GatewayReceiver, RuntimeSignal, ScheduledPrompt, SignalGateway, SignalSource};
67pub use tools::{
68    RegisteredTool, SafeToolResult, TextToolSession, ToolChunk, ToolEnvelope, ToolEnvelopeFail,
69    ToolEnvelopeOk, ToolSession, ToolStep, execute_tools, fail, ok, read_file_tool, safe_tool,
70    tool_fail, validate_tool_arguments,
71};
72
73#[derive(Debug, thiserror::Error)]
74pub enum Error {
75    #[error("provider error: {0}")]
76    Provider(String),
77    #[error("tool error: {0}")]
78    Tool(String),
79    #[error("io error: {0}")]
80    Io(#[from] std::io::Error),
81    #[error("tool execution failed: {output}")]
82    ToolExecutionFailed {
83        output: String,
84        is_fatal: bool,
85        error_kind: Option<deepstrike_core::types::message::ToolErrorKind>,
86    },
87    /// Tool author signalled a structured failure with optional machine-readable `code` and a
88    /// self-correcting `hint`. Parity with the Node/Python `ToolError` + `safe_tool` envelope:
89    /// surfaced to the model as JSON `{message, code?, hint?}` (via `format_tool_error`) so the
90    /// agent can branch on `code` instead of pattern-matching a free-form string.
91    #[error("{output}")]
92    ToolFail {
93        output: String,
94        code: Option<String>,
95        hint: Option<String>,
96        is_fatal: bool,
97        error_kind: Option<deepstrike_core::types::message::ToolErrorKind>,
98    },
99    #[error("{0}")]
100    Other(String),
101}
102
103/// Error-aware serialization for tool-execution error paths. Replaces `e.to_string()` at the
104/// sites that hand the model a failure message:
105///
106/// - `Error::Tool(s)` → `s` (drops the `"tool error: "` prefix from `e.to_string()`).
107/// - `Error::ToolExecutionFailed { output, .. }` → `output` (drops the `"tool execution failed: "` prefix).
108/// - `Error::ToolFail { output, code:None, hint:None, .. }` → `output`.
109/// - `Error::ToolFail { output, code, hint, .. }` (either set) → JSON `{message, code?, hint?}`.
110/// - everything else → `e.to_string()` (the `thiserror`-formatted string).
111pub fn format_tool_error(e: &Error) -> String {
112    match e {
113        Error::Tool(s) => s.clone(),
114        Error::ToolExecutionFailed { output, .. } => output.clone(),
115        Error::ToolFail { output, code, hint, .. } => {
116            if code.is_none() && hint.is_none() {
117                return output.clone();
118            }
119            let mut obj = serde_json::Map::with_capacity(3);
120            obj.insert("message".to_string(), serde_json::Value::String(output.clone()));
121            if let Some(c) = code {
122                obj.insert("code".to_string(), serde_json::Value::String(c.clone()));
123            }
124            if let Some(h) = hint {
125                obj.insert("hint".to_string(), serde_json::Value::String(h.clone()));
126            }
127            serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_else(|_| output.clone())
128        }
129        _ => e.to_string(),
130    }
131}
132
133pub type Result<T> = std::result::Result<T, Error>;