Skip to main content

Crate neomind_extension_sdk

Crate neomind_extension_sdk 

Source
Expand description

NeoMind Extension SDK

A unified SDK for developing NeoMind extensions that can be compiled for both Native and WASM targets.

§Features

  • Unified trait system for Native and WASM
  • Automatic FFI export generation
  • Helper macros for common patterns
  • Type-safe metric and command definitions
  • Single-source IPC boundary types

§Architecture (V2 - Process Isolation)

All extensions run in isolated processes by default:

┌─────────────────────────────────────────────────────────────┐
│                   NeoMind Main Process                       │
│  - UnifiedExtensionService manages all extensions           │
│  - IPC communication via stdin/stdout                       │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  Extension Runner Process                    │
│  - Your extension runs here in isolation                    │
│  - Native: loaded via FFI                                   │
│  - WASM: executed via wasmtime                              │
│  - Crashes don't affect main process                        │
└─────────────────────────────────────────────────────────────┘

§ABI Stability

The IPC boundary types in ipc_types are the stable protocol between extensions and the main process. Extensions compiled against older SDK versions will continue to work because:

  1. Types are serialized as JSON over IPC
  2. Only the JSON format matters, not the implementation
  3. New fields use #[serde(default)] for forward compatibility

§Quick Start

use neomind_extension_sdk::prelude::*;

// Define your extension struct
pub struct MyExtension {
    counter: std::sync::atomic::AtomicI64,
}

impl MyExtension {
    pub fn new() -> Self {
        Self {
            counter: std::sync::atomic::AtomicI64::new(0),
        }
    }
}

// Implement the Extension trait
#[async_trait]
impl Extension for MyExtension {
    fn metadata(&self) -> &ExtensionMetadata {
        static META: ExtensionMetadata = ExtensionMetadata::new(
            "my-extension",
            "My Extension",
            "1.0.0",
        );
        &META
    }

    fn metrics(&self) -> Vec<MetricDescriptor> {
        vec![
            MetricDescriptor::new("counter", "Counter", MetricDataType::Integer)
                .with_unit("count")
        ]
    }

    fn commands(&self) -> Vec<ExtensionCommand> {
        vec![
            CommandBuilder::new("increment")
                .display_name("Increment")
                .param(
                    ParamBuilder::new("amount", MetricDataType::Integer)
                        .display_name("Amount")
                        .default(MetricValue::Integer(1))
                        .build()
                )
                .build()
        ]
    }

    async fn execute_command(&self, command: &str, args: &serde_json::Value) -> Result<serde_json::Value> {
        match command {
            "increment" => {
                let amount = args.get("amount").and_then(|v| v.as_i64()).unwrap_or(1);
                let new_value = self.counter.fetch_add(amount, std::sync::atomic::Ordering::SeqCst) + amount;
                Ok(serde_json::json!({ "counter": new_value }))
            }
            _ => Err(ExtensionError::CommandNotFound(command.to_string())),
        }
    }

    fn produce_metrics(&self) -> Result<Vec<ExtensionMetricValue>> {
        Ok(vec![
            ExtensionMetricValue::new(
                "counter",
                MetricValue::Integer(self.counter.load(std::sync::atomic::Ordering::SeqCst))
            )
        ])
    }
}

// Export FFI functions
neomind_export!(MyExtension);

Modules§

capabilities
Unified Capabilities Module (Native + WASM support)
capability_constants
Capability name constants - re-exported from host module
ipc
Stable IPC boundary types for extension communication.
native
Native-specific extension utilities
prelude
NeoMind Extension SDK Prelude
utils
Utility functions for extension development

Macros§

create_c_metadata
Create a C-compatible metadata structure
define_commands
Define commands for an extension (helper macro)
define_metrics
Define metrics for an extension (helper macro)
define_params
Define parameters for a command (helper macro)
ext_debug
Extension debug log
ext_error
Extension error log
ext_info
Extension info log
ext_log
Helper macro to log a message
ext_warn
Extension warning log
json
Construct a serde_json::Value from a JSON literal.
metric_bool
Helper macro to create a boolean metric value
metric_float
Helper macro to create a float metric value
metric_int
Helper macro to create an integer metric value
metric_string
Helper macro to create a string metric value
metric_value
Helper macro to create a metric value
neomind_export
Export FFI functions for an extension type
neomind_export_with_constructor
Export FFI functions with a custom constructor
neomind_extension
Define an extension with configuration-style syntax
neomind_extension_metric_type
Helper macro to convert type name to MetricDataType
neomind_extension_param_type
Helper macro to convert type name to MetricDataType for parameters
neomind_simple_extension
Simplified extension definition with minimal boilerplate
static_commands
Create a static slice of commands
static_metadata
Create a static ExtensionMetadata
static_metrics
Create a static slice of metrics

Structs§

ArgParser
Helper for parsing command arguments
AvailableCapabilities
Available capabilities registry.
BatchCommand
Single command in a batch
BatchResult
Result of a single command execution
BatchResultsVec
Container for batch execution results
CExtensionMetadata
C-compatible extension metadata for FFI.
CapabilityContext
Capability context for invoking capabilities from extensions. Only available on native targets (requires tokio runtime).
CapabilityManifest
Capability manifest for extension capabilities.
ClientInfo
Client information.
CommandBuilder
Helper type for building command definitions
CommandDescriptor
Command definition/descriptor.
ComponentSize
Component size definition
DataChunk
Data chunk for streaming.
EventFilter
Event filter for subscriptions.
EventSubscription
Event subscription configuration.
ExtensionContext
Extension context for capability invocation.
ExtensionContextConfig
Extension context configuration.
ExtensionDescriptor
Complete extension descriptor.
ExtensionMetadata
Extension metadata.
ExtensionMetricValue
Extension metric value with timestamp.
ExtensionRuntimeState
Dynamic runtime state for a loaded extension.
ExtensionStats
Extension runtime statistics.
FlowControl
Flow control configuration.
FrontendComponent
Frontend component definition
FrontendManifest
Frontend component manifest for extensions
FrontendManifestBuilder
Builder for creating frontend manifests
I18nConfig
i18n configuration
IpcFrame
Frame format for IPC communication
MetricBuilder
Helper type for building metric descriptors
MetricDescriptor
Metric definition/descriptor.
ParamBuilder
Helper type for building parameter definitions
ParameterDefinition
Parameter definition for commands.
ParameterGroup
Parameter group for organizing command parameters.
PushOutputData
Push output data (extracted from PushOutput response) Used for forwarding push data to WebSocket clients
PushOutputMessage
Message sent from extension to host for Push mode streaming.
SdkCommandDefinition
Command definition (SDK-specific)
SdkExtensionMetadata
Extension metadata for SDK (SDK-specific fields)
SdkExtensionMetricValue
Extension metric value with name, value and timestamp (SDK-specific)
SdkMetricDefinition
Metric definition (SDK-specific)
SdkParameterDefinition
Parameter definition for commands (SDK-specific)
SdkParameterGroup
Parameter group for organizing command parameters
SessionStats
Session statistics.
StreamCapability
Stream capability descriptor.
StreamClientInfo
Stream client info (for IPC transfer)
StreamDataChunk
Stream data chunk (for IPC transfer)
StreamError
Stream error.
StreamResult
Stream result.
StreamSession
Stream session.
ValidationRule
Validation rule for parameters.

Enums§

CapabilityError
Error type for capability operations.
ErrorKind
Error kind classification for IPC
ExtensionCapability
Extension capabilities for accessing NeoMind platform features.
ExtensionError
Extension error types.
FrontendComponentType
Component type enumeration
IpcMessage
IPC message sent from host to extension process
IpcResponse
IPC response sent from extension process to host
MetricDataType
Metric data type enumeration.
MetricValue
Metric value for parameters and measurements.
SdkExtensionError
Extension error type (SDK-specific)
SdkMetricDataType
Metric data types (SDK-specific)
SdkMetricValue
Metric value (SDK-specific)
StreamDataType
Stream data type.
StreamDirection
Stream direction.
StreamMode
Stream mode.
Value
Represents any valid JSON value.

Constants§

ABI_VERSION
ABI version for dynamic loading. This must be incremented when breaking changes are made to IPC types.
MAX_IPC_FRAME_SIZE
Maximum IPC frame payload size (16 MB) This prevents malicious extensions from sending extremely large messages that could exhaust main process memory.
MIN_NEOMIND_VERSION
Minimum NeoMind core version required
SDK_ABI_VERSION
ABI version for the unified SDK
SDK_VERSION
SDK version

Traits§

Extension
Core extension trait that all NeoMind extensions must implement.
ExtensionCapabilityProvider
Trait for capability providers.

Functions§

current_timestamp_ms
Get current timestamp in milliseconds.
current_timestamp_secs
Get current timestamp in seconds.
send_push_output
Send a push-output message from the extension to the host.
set_native_capability_bridge
Set the native capability bridge for FFI.
set_push_output_writer
Called by the generated FFI registration function to install the push-output writer callback. Returns 0 on success.

Type Aliases§

CommandDefinition
Alias for backward compatibility.
ExtensionCommand
Alias for backward compatibility.
MetricDefinition
NativeCapabilityFreeFn
NativeCapabilityInvokeFn
Native capability function types.
ParamMetricValue
Alias for backward compatibility with existing code.
PushOutputWriterFn
Function pointer type for writing push output from extension → runner. The runner registers this callback so the extension can push data without going through the JSON FFI round-trip.
Result
Result type for extension operations.
SdkResult
Result type for SDK extension operations

Attribute Macros§

async_trait