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;
19// Session entropy (heartbeat watch source): the kernel emits `entropy_sample` /
20// `entropy_alert` observations through the shared JSON ABI; these types are for hosts
21// configuring the watch (`set_entropy_watch` / `configure_run.entropy_watch`) or folding
22// their own samples when driving the kernel manually.
23pub use deepstrike_core::{EntropySample, EntropyTracker, EntropyWatchConfig};
24pub use deepstrike_core::mm::memory::{
25    MemoryAuthor, MemoryKind, MemoryPolicy, MemoryProvenance, MemoryQuery, MemoryRecall,
26    MemoryRecord, MemoryScope, MemoryTrustLevel,
27};
28// Workflow surface (DELIBERATE floor, not a gap): the Rust SDK has no `run_workflow` driver — the
29// node/python/wasm SDKs own async node execution. These re-exports are for MANUAL driving: build a
30// spec with the templates, hold a `WorkflowRun` (a pure state machine), call `ready_batch()` /
31// `spawn_info()` / `record_completion()` from your own executor. Everything the drivers do is
32// reachable this way; a batteries-included Rust driver lands only when a real consumer needs it.
33pub use deepstrike_core::orchestration::workflow::{
34    fanout_synthesize, gen_eval, generate_and_filter, verify_rules, WorkflowNode, WorkflowSpec,
35};
36pub use deepstrike_core::orchestration::workflow::{JudgeMatch, WorkflowRun, WorkflowSpawnInfo};
37pub use governance::{Governance, GovernanceVerdict};
38pub use harness::{Criterion, CriterionResult, Verdict};
39pub use harness_loop::{
40    AttemptBody, AttemptBodyContext, AttemptBodyEvent, AttemptBodyStream, AttemptJudge,
41    AttemptLoop, AttemptLoopEvent, AttemptLoopStream, AttemptOutcome, AttemptOutcomeKind,
42    AttemptRequest, CarryContext, CarryPolicy, ContinueSession, DigestFn, DigestFuture,
43    FreshWithDigest, FreshWithFeedback, HybridJudge, JudgeContext, JudgeResult, LlmEvalJudge,
44    PassHook, PassHookFuture, PreparedAttempt, RuntimeAttemptBody, StopPolicy, VerdictFn,
45    VerdictFnJudge,
46};
47pub use knowledge::KnowledgeSource;
48pub use memory::{DreamStore, InMemoryDreamStore, WorkingMemory};
49pub use providers::RuntimePolicy;
50pub use providers::anthropic::AnthropicProvider;
51pub use providers::openai::{OpenAIProvider, deepseek, kimi, minimax, ollama, qwen};
52pub use providers::{LLMProvider, ProviderRunState, ProviderToolSpec, StreamEvent, TokenUsage};
53pub use run_event::RunEvent;
54pub use runtime::eval::{build_eval_messages, judge, parse_verdict, verdict_output_schema};
55pub use runtime::eval::{Criterion as EvalCriterion, Verdict as EvalVerdict};
56pub use runtime::replay_provider::{ReplayProvider, ReplayProviderOpts};
57pub use runtime::replay_fixture::{extract_recorded_messages, extract_recorded_messages_from_entries};
58pub use runtime::{
59    assert_native_profile, default_native_governance_policy, os_profile, GovernancePolicy,
60    MemoryWriteRateLimit, NativeOsProfile, OsProfile, SchedulerPolicyConfig, SignalPolicy,
61    DEFAULT_NATIVE_SIGNAL_POLICY,
62};
63pub use runtime::{
64    collect_text, MilestoneEvaluationContext, MilestoneEvaluationHandler, MilestonePolicy,
65    RuntimeOptions, RuntimeRunner,
66};
67pub use runtime::{
68    ChainedCredentialVault, CredentialVault, EnvCredentialVault, InMemoryCredentialVault,
69};
70pub use runtime::{ExecutionPlane, LocalExecutionPlane};
71pub use runtime::{FileSessionLog, InMemorySessionLog, SessionEntry, SessionLog};
72pub use runtime::{McpProxyPlane, McpServerConfig};
73pub use runtime::{
74    PermissionRequest, PermissionRequestHandler, PermissionResponse, RunContext,
75    ToolSuspendHandler, ToolSuspendRequest,
76};
77pub use runtime::{ProcessSandboxPlane, SandboxOptions};
78pub use runtime::{RemoteVpcOptions, RemoteVpcPlane};
79pub use safety::{Permission, PermissionDecision, PermissionManager, PermissionMode};
80pub use signals::{
81    GatewayReceiver, RuntimeSignal, ScheduledPrompt, SignalClaim, SignalDeliveryReceipt,
82    SignalGateway, SignalSource,
83};
84pub use tools::{
85    RegisteredTool, SafeToolResult, TextToolSession, ToolChunk, ToolEnvelope, ToolEnvelopeFail,
86    ToolEnvelopeOk, ToolSession, ToolStep, execute_tools, fail, ok, read_file_tool, safe_tool,
87    tool_fail, validate_tool_arguments,
88};
89
90#[derive(Debug, thiserror::Error)]
91pub enum Error {
92    #[error("provider error: {0}")]
93    Provider(String),
94    #[error("tool error: {0}")]
95    Tool(String),
96    #[error("io error: {0}")]
97    Io(#[from] std::io::Error),
98    #[error("tool execution failed: {output}")]
99    ToolExecutionFailed {
100        output: String,
101        is_fatal: bool,
102        error_kind: Option<deepstrike_core::types::message::ToolErrorKind>,
103    },
104    /// Tool author signalled a structured failure with optional machine-readable `code` and a
105    /// self-correcting `hint`. Parity with the Node/Python `ToolError` + `safe_tool` envelope:
106    /// surfaced to the model as JSON `{message, code?, hint?}` (via `format_tool_error`) so the
107    /// agent can branch on `code` instead of pattern-matching a free-form string.
108    #[error("{output}")]
109    ToolFail {
110        output: String,
111        code: Option<String>,
112        hint: Option<String>,
113        is_fatal: bool,
114        error_kind: Option<deepstrike_core::types::message::ToolErrorKind>,
115    },
116    #[error("{0}")]
117    Other(String),
118}
119
120/// Error-aware serialization for tool-execution error paths. Replaces `e.to_string()` at the
121/// sites that hand the model a failure message:
122///
123/// - `Error::Tool(s)` → `s` (drops the `"tool error: "` prefix from `e.to_string()`).
124/// - `Error::ToolExecutionFailed { output, .. }` → `output` (drops the `"tool execution failed: "` prefix).
125/// - `Error::ToolFail { output, code:None, hint:None, .. }` → `output`.
126/// - `Error::ToolFail { output, code, hint, .. }` (either set) → JSON `{message, code?, hint?}`.
127/// - everything else → `e.to_string()` (the `thiserror`-formatted string).
128pub fn format_tool_error(e: &Error) -> String {
129    match e {
130        Error::Tool(s) => s.clone(),
131        Error::ToolExecutionFailed { output, .. } => output.clone(),
132        Error::ToolFail { output, code, hint, .. } => {
133            if code.is_none() && hint.is_none() {
134                return output.clone();
135            }
136            let mut obj = serde_json::Map::with_capacity(3);
137            obj.insert("message".to_string(), serde_json::Value::String(output.clone()));
138            if let Some(c) = code {
139                obj.insert("code".to_string(), serde_json::Value::String(c.clone()));
140            }
141            if let Some(h) = hint {
142                obj.insert("hint".to_string(), serde_json::Value::String(h.clone()));
143            }
144            serde_json::to_string(&serde_json::Value::Object(obj)).unwrap_or_else(|_| output.clone())
145        }
146        _ => e.to_string(),
147    }
148}
149
150pub type Result<T> = std::result::Result<T, Error>;