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::measurement::{MeasurementConfidence, MeasurementSource};
17// F3 (0.2.66): the core-internal render type is `InternalRenderedContext`; the SDK-visible
18// name stays `RenderedContext` (API stability — this re-export is the crate's public surface).
19pub use deepstrike_core::context::renderer::InternalRenderedContext as RenderedContext;
20pub use deepstrike_core::governance::permission::PermissionAction;
21pub use deepstrike_core::governance::quota::ResourceQuota;
22// Session entropy (heartbeat watch source): the kernel emits `entropy_sample` /
23// `entropy_alert` observations through the shared JSON ABI; these types are for hosts
24// configuring the watch (`set_entropy_watch` / `configure_run.entropy_watch`) or folding
25// their own samples when driving the kernel manually.
26pub use deepstrike_core::mm::memory::{
27    MemoryAuthor, MemoryKind, MemoryProvenance, MemoryQuery, MemoryRecall, MemoryRecord,
28    MemoryScope, MemoryTrustLevel,
29};
30pub use deepstrike_core::runtime::kernel::wire::MemoryPolicy;
31pub use deepstrike_core::{EntropySample, EntropyTracker, EntropyWatchConfig};
32// Workflow surface (DELIBERATE floor, not a gap): the Rust SDK has no `run_workflow` driver — the
33// node/python/wasm SDKs own async node execution. These re-exports are for MANUAL driving: build a
34// spec with the templates, hold a `WorkflowRun` (a pure state machine), call `ready_batch()` /
35// `spawn_info()` / `record_completion()` from your own executor. Everything the drivers do is
36// reachable this way; a batteries-included Rust driver lands only when a real consumer needs it.
37pub use deepstrike_core::orchestration::workflow::{JudgeMatch, WorkflowRun, WorkflowSpawnInfo};
38pub use deepstrike_core::orchestration::workflow::{
39    WorkflowNode, WorkflowSpec, fanout_synthesize, gen_eval, generate_and_filter, verify_rules,
40};
41pub use deepstrike_core::runtime::verifiable::{
42    CheckVerdict, EvidenceBundle, ForkManifest, ForkPlan, InspectReport, ReplayOptions,
43    ReplayReport, ReplayVerdict, VerifiableOperation, VerifyOptions, VerifyReport,
44};
45pub use governance::{Governance, GovernanceVerdict};
46pub use harness::{Criterion, CriterionResult, Verdict};
47pub use harness_loop::{
48    AttemptBody, AttemptBodyContext, AttemptBodyEvent, AttemptBodyStream, AttemptJudge,
49    AttemptLoop, AttemptLoopEvent, AttemptLoopStream, AttemptOutcome, AttemptOutcomeKind,
50    AttemptRequest, CarryContext, CarryPolicy, ContinueSession, DigestFn, DigestFuture,
51    FreshWithDigest, FreshWithFeedback, HybridJudge, JudgeContext, JudgeResult, LlmEvalJudge,
52    PassHook, PassHookFuture, PreparedAttempt, RuntimeAttemptBody, StopPolicy, VerdictFn,
53    VerdictFnJudge,
54};
55pub use knowledge::KnowledgeSource;
56pub use memory::{
57    DurableMemory, InMemoryMemoryStore, MemorySearchOptions, MemoryStore, WorkingMemory,
58};
59pub use providers::RuntimePolicy;
60pub use providers::anthropic::AnthropicProvider;
61pub use providers::openai::{OpenAIProvider, deepseek, kimi, minimax, ollama, qwen};
62pub use providers::request_plan::{
63    CostObservation, NormalizedProviderUsage, PricingRates, PricingSnapshot,
64    ProviderRequestEndpoint, ProviderRequestPlan, ProviderUsage, RecordedPromptMeasurement,
65    RequestPlanError, UnpricedReason, measurement_for_plan, normalize_provider_usage,
66    price_provider_usage, record_prompt_measurement,
67};
68pub use providers::{
69    LLMProvider, ProviderError, ProviderErrorKind, ProviderRunState, ProviderToolSpec, StreamEvent,
70    TokenUsage,
71};
72pub use run_event::RunEvent;
73pub use runtime::eval::{Criterion as EvalCriterion, Verdict as EvalVerdict};
74pub use runtime::eval::{build_eval_messages, judge, parse_verdict, verdict_output_schema};
75pub use runtime::replay_fixture::{
76    extract_recorded_messages, extract_recorded_messages_from_entries,
77};
78pub use runtime::replay_provider::{ReplayProvider, ReplayProviderOpts};
79pub use runtime::{
80    CanonicalCheckpoint, CanonicalCheckpointCandidate, CanonicalCommit, CanonicalKernel,
81    CanonicalPreparation,
82};
83pub use runtime::{
84    ChainedCredentialVault, CredentialVault, EnvCredentialVault, InMemoryCredentialVault,
85};
86pub use runtime::{
87    DEFAULT_NATIVE_SIGNAL_POLICY, GovernancePolicy, MemoryWriteRateLimit, NativeOsProfile,
88    OsProfile, SchedulerPolicyConfig, SignalPolicy, assert_native_profile,
89    default_native_governance_policy, os_profile,
90};
91pub use runtime::{ExecutionPlane, LocalExecutionPlane};
92pub use runtime::{FilePayloadStore, PayloadStore};
93pub use runtime::{FileSessionLog, InMemorySessionLog, SessionEntry, SessionLog};
94pub use runtime::{
95    KernelReliability, MilestoneEvaluationContext, MilestoneEvaluationHandler, MilestonePolicy,
96    RuntimeOptions, RuntimeRunner, collect_text,
97};
98// Durable transaction capability (Canonical Kernel ABI §9.1). `FileKernelJournal` is the
99// cross-process-atomic reference implementation; `InMemoryKernelJournal` is dev/test only.
100pub use runtime::{
101    CheckpointCandidate, FileKernelJournal, InMemoryKernelJournal, InstalledCheckpoint,
102    JournalAppendReceipt, JournalEntry, JournalError, JournalHead, JournalPruneReceipt,
103    JournalRecordInput, JournalResult, KernelJournal,
104};
105pub use runtime::{McpProxyPlane, McpServerConfig};
106pub use runtime::{
107    PermissionRequest, PermissionRequestHandler, PermissionResponse, RunContext,
108    ToolSuspendHandler, ToolSuspendRequest,
109};
110pub use runtime::{ProcessSandboxPlane, SandboxOptions};
111pub use runtime::{RemoteVpcOptions, RemoteVpcPlane};
112pub use safety::{Permission, PermissionDecision, PermissionManager, PermissionMode};
113pub use signals::{
114    GatewayReceiver, RuntimeSignal, ScheduledPrompt, SignalClaim, SignalDeliveryReceipt,
115    SignalGateway, SignalSource,
116};
117pub use tools::{
118    RegisteredTool, SafeToolResult, TextToolSession, ToolChunk, ToolEnvelope, ToolEnvelopeFail,
119    ToolEnvelopeOk, ToolSession, ToolStep, execute_tools, fail, ok, read_file_tool, safe_tool,
120    tool_fail, validate_tool_arguments,
121};
122
123#[derive(Debug, thiserror::Error)]
124pub enum Error {
125    #[error("provider error: {0}")]
126    Provider(String),
127    #[error(transparent)]
128    ProviderFailure(#[from] providers::ProviderError),
129    #[error("tool error: {0}")]
130    Tool(String),
131    #[error("io error: {0}")]
132    Io(#[from] std::io::Error),
133    #[error("tool execution failed: {output}")]
134    ToolExecutionFailed {
135        output: String,
136        is_fatal: bool,
137        error_kind: Option<deepstrike_core::types::message::ToolErrorKind>,
138    },
139    /// Tool author signalled a structured failure with optional machine-readable `code` and a
140    /// self-correcting `hint`. Parity with the Node/Python `ToolError` + `safe_tool` envelope:
141    /// surfaced to the model as JSON `{message, code?, hint?}` (via `format_tool_error`) so the
142    /// agent can branch on `code` instead of pattern-matching a free-form string.
143    #[error("{output}")]
144    ToolFail {
145        output: String,
146        code: Option<String>,
147        hint: Option<String>,
148        is_fatal: bool,
149        error_kind: Option<deepstrike_core::types::message::ToolErrorKind>,
150    },
151    #[error("{0}")]
152    Other(String),
153}
154
155/// Error-aware serialization for tool-execution error paths. Replaces `e.to_string()` at the
156/// sites that hand the model a failure message:
157///
158/// - `Error::Tool(s)` → `s` (drops the `"tool error: "` prefix from `e.to_string()`).
159/// - `Error::ToolExecutionFailed { output, .. }` → `output` (drops the `"tool execution failed: "` prefix).
160/// - `Error::ToolFail { output, code:None, hint:None, .. }` → `output`.
161/// - `Error::ToolFail { output, code, hint, .. }` (either set) → JSON `{message, code?, hint?}`.
162/// - everything else → `e.to_string()` (the `thiserror`-formatted string).
163pub fn format_tool_error(e: &Error) -> String {
164    match e {
165        Error::Tool(s) => s.clone(),
166        Error::ToolExecutionFailed { output, .. } => output.clone(),
167        Error::ToolFail {
168            output, code, hint, ..
169        } => {
170            if code.is_none() && hint.is_none() {
171                return output.clone();
172            }
173            let mut obj = serde_json::Map::with_capacity(3);
174            obj.insert(
175                "message".to_string(),
176                serde_json::Value::String(output.clone()),
177            );
178            if let Some(c) = code {
179                obj.insert("code".to_string(), serde_json::Value::String(c.clone()));
180            }
181            if let Some(h) = hint {
182                obj.insert("hint".to_string(), serde_json::Value::String(h.clone()));
183            }
184            serde_json::to_string(&serde_json::Value::Object(obj))
185                .unwrap_or_else(|_| output.clone())
186        }
187        _ => e.to_string(),
188    }
189}
190
191pub type Result<T> = std::result::Result<T, Error>;
192
193// Context preparation and verification have one implementation in the Rust core.
194pub use deepstrike_core::context::execution::{
195    ContextCandidate, ContextDispatchPreparation, ContextDispatchRequest, ContextExecutionInput,
196    ContextPlan, ContextPromptMeasurement, ContextState, prepare_context_dispatch,
197    verify_context_dispatch,
198};