Solana Agent Middleware - Production-ready AI agent framework for blockchain operations
Framework for building autonomous AI agents that interact with the Solana blockchain ecosystem
- Overview
- Key Features
- Quick Start
- Tool Ecosystem
- Architecture
- Configuration
- Plugin System
- Security
- Development
- Documentation
SAM Framework provides a production-ready infrastructure for building AI agents that interact with the Solana blockchain ecosystem. The framework implements an event-driven architecture with plugin support, enabling automated trading, portfolio management, market data analysis, and web research capabilities.
| Category | Description | Tools |
|---|---|---|
| Agent Engine | Multi-LLM orchestration with advanced tool calling | OpenAI, Anthropic, xAI, Local |
| Tool Registry | Production-ready integrations with middleware | 26+ tools |
| Event System | Async pub/sub messaging for component communication | Real-time streaming |
| Plugin SDK | Extensible architecture for custom tools | Entry point discovery |
| Memory System | Persistent conversation context with compression | SQLite-based |
| Security Layer | Encrypted key management and validation | Fernet + OS keyring |
- Automated Trading: Execute trades on Pump.fun, Jupiter DEX, and Aster Futures
- Portfolio Management: Monitor balances, positions, and transaction history
- Market Research: Real-time data from DexScreener, Polymarket, and Kalshi analytics
- Prediction Markets: Analyze and trade prediction market opportunities
- Web Intelligence: Search and news aggregation
- Transaction Automation: Safety-controlled blockchain operations
| Feature | Description |
|---|---|
| Multi-LLM Support | OpenAI, Anthropic, xAI, and local models |
| Advanced Tool Calling | Loop prevention and error recovery |
| Event-Driven Design | Async pub/sub messaging system |
| Session Persistence | SQLite-based conversation context |
| Async Optimization | uvloop integration for performance |
| Feature | Description |
|---|---|
| 28+ Production Tools | Complete DeFi ecosystem coverage |
| Plugin Architecture | Extensible with entry point discovery |
| Middleware Pipeline | Configurable logging, rate limiting, retries |
| SDK Integration | Programmatic agent construction |
| Error Handling | Structured error responses and recovery |
| Feature | Description |
|---|---|
| Fernet Encryption | AES-128 encryption for sensitive data |
| OS Keyring Integration | System-level credential storage |
| Transaction Validation | Pre-execution safety checks |
| Rate Limiting | Configurable request throttling |
| Address Validation | Solana address format verification |
git clone https://github.com/prfagit/sam-framework
cd sam-framework
uv syncInteractive Onboarding (Recommended)
uv run sam onboardConfigures:
- LLM provider selection and API key setup
- Wallet private key import (encrypted storage)
- Environment configuration
- Tool enablement preferences
Expose the multi-tenant HTTP API for frontend applications:
uv run sam api --host 0.0.0.0 --port 8000Key environment variables:
SAM_API_AGENT_ROOT– filesystem root for user-scoped agent definitions (.sam/usersby default)SAM_API_CORS_ORIGINS– comma-separated list of allowed origins for CORSSAM_API_USER_HEADER– legacy header override for user resolution (Bearer auth is preferred)SAM_API_TOKEN_SECRET– shared secret for signing API tokens (falls back toSAM_FERNET_KEYif unset)
Create API users from the CLI:
uv run sam api create-user alice --adminAuthenticate and call endpoints using bearer tokens:
# Obtain a token
curl -X POST http://localhost:8000/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username": "alice", "password": "hunter2"}'
# Use the token
curl http://localhost:8000/v1/agents \
-H "Authorization: Bearer <access_token>"
# Stream agent output (Server-Sent Events)
curl -N -X POST http://localhost:8000/v1/agents/sam/stream \
-H "Authorization: Bearer <access_token>" \
-H "Content-Type: application/json" \
-d '{"prompt": "Watch SOL/USDC"}'Manual Configuration
Create .env file:
# Provider Selection
LLM_PROVIDER=openai
# API Keys
OPENAI_API_KEY=sk-your-key-here
ANTHROPIC_API_KEY=sk-ant-your-key-here
XAI_API_KEY=xai-your-key-here
# Security
SAM_FERNET_KEY=your-generated-key
# Optional Services
BRAVE_API_KEY=your-brave-search-keyProvider Management
# List available providers
sam provider list
# Switch providers
sam provider switch anthropic
# Test provider connection
sam provider test# Start interactive agent (CLI)
sam run
# Or with custom session
sam run --session trading_sessionWeb Interface (Streamlit)
# Launch the web interface
uv run streamlit run examples/streamlit_app/app.py
# Access at http://localhost:8501Web Features:
- Real-time chat with streaming responses
- Live tool call visualization and event streaming
- Interactive settings, wallet, and tools pages
- Session management with conversation history
- Responsive design with custom styling
Enhanced Status Display:
- Real-time model and wallet information
- Context usage percentage (auto-compacts at 80%)
- Session statistics and performance metrics
Available Commands:
/help- Show available commands/tools- List available tools/config- Show current configuration/provider- Manage LLM providers/settings- Interactive configuration editor/clear-context- Clear conversation context/compact- Compact conversation history/clear-sessions- Clear all sessions and reset to default- ESC - Interrupt current operation
- Ctrl+C - Exit
Session Management:
- Persistent conversation contexts across runs
- Automatic session creation and management
- Session statistics and performance tracking
- Database-backed session storage with indexing
SAM provides 24+ production-ready tools organized by category:
| Tool | Description | Parameters |
|---|---|---|
get_balance |
Complete wallet overview | address (optional) |
transfer_sol |
Send SOL between addresses | to_address, amount |
get_token_data |
Token metadata and supply | address |
| Tool | Description | Parameters |
|---|---|---|
pump_fun_buy |
Execute token purchases | mint, amount, slippage |
pump_fun_sell |
Sell tokens with percentage | mint, percentage, slippage |
get_pump_token_info |
Detailed token information | mint |
get_token_trades |
View trading activity | mint |
| Tool | Description | Parameters |
|---|---|---|
uranus_open_position |
Open LONG or SHORT positions on Uranus.ag | market_mint, amount_sol, leverage, direction, market_symbol (optional) |
uranus_close_position |
Close an existing Uranus.ag position | position_nonce, position_account (optional), owner (optional) |
uranus_get_positions |
List active Uranus.ag positions | owner or market_mint or ticker, include_closed |
uranus_market_liquidity |
Inspect available market liquidity in SOL | market_mint |
uranus_get_price |
Fetch current Uranus.ag oracle price | symbol |
| Tool | Description | Parameters |
|---|---|---|
smart_buy |
Buy with fallback (Pump.fun → Jupiter) | token, amount |
smart_sell |
Sell with fallback (Pump.fun → Jupiter) | token, percentage |
| Tool | Description | Parameters |
|---|---|---|
get_swap_quote |
Get swap quotes | input_mint, output_mint, amount |
jupiter_swap |
Execute token swaps | Quote parameters |
| Tool | Description | Parameters |
|---|---|---|
aster_account_info |
Account information and trading status | - |
aster_account_balance |
Account balance and margin details | - |
aster_trade_history |
Recent trade history and performance | limit |
aster_open_long |
Open long position with leverage | symbol, quantity, leverage, price |
aster_close_position |
Close existing position | symbol, quantity, position_side |
aster_position_check |
Check current positions and PnL | - |
| Tool | Description | Parameters |
|---|---|---|
search_pairs |
Search trading pairs | query |
get_token_pairs |
Get pairs for token | address |
get_solana_pair |
Detailed pair information | pair_address |
get_trending_pairs |
Trending pairs by volume | chain |
| Tool | Description | Parameters |
|---|---|---|
polymarket_list_markets |
Discover active Polymarket markets | limit, category, tag, series_slug |
polymarket_opportunity_scan |
Rank markets by ROI/liquidity heuristics | limit, min_volume_24h, max_entry_price, tag |
polymarket_strategy_brief |
Generate entry/exit strategy summaries | count, max_entry_price, category, tag |
kalshi_list_markets |
Discover Kalshi markets with pricing, volume, and status filters | limit, status, event_ticker, series_ticker, tickers, min_close_ts, max_close_ts, cursor |
kalshi_market_overview |
Detailed Kalshi market snapshot with ROI heuristics | ticker |
kalshi_opportunity_scan |
Rank Kalshi markets by ROI, liquidity, and volume heuristics | limit, universe_limit, min_volume_24h, min_liquidity, max_yes_ask, event_ticker, category |
kalshi_strategy_brief |
Generate trade ideas with entry/TP/SL strategy suggestions | count, universe_limit, min_volume_24h, min_liquidity, max_yes_ask, event_ticker, category |
kalshi_get_balance |
Get portfolio balance (requires authentication) | - |
kalshi_get_positions |
Get portfolio positions (requires authentication) | limit, cursor, event_ticker, settlement_status |
| Tool | Description | Parameters |
|---|---|---|
aixbt_projects |
Ranked list of trending projects with rationale and momentum data | limit, name, ticker, x_handle, sort_by, min_score |
aixbt_indigo_research |
Narrative deep dives powered by the Indigo research agent | prompt or messages |
Requires the
x402Python package (uv add x402) and an EVM private key configured viaAIXBT_PRIVATE_KEY.
| Tool | Description | Parameters |
|---|---|---|
search_web |
Search internet content | query, count |
search_news |
Search news articles | query, count |
| Tool | Description | Parameters |
|---|---|---|
payai_supported_networks |
List schemes and networks supported by the configured facilitator | - |
payai_discover_resources |
Discover x402-enabled resources advertised by the facilitator Bazaar | resource_type, limit, offset, metadata |
payai_get_payment_requirements |
Fetch payment requirements for a resource, using the default facilitator network | resource |
payai_auto_pay_resource |
End-to-end Solana payment (fetch, sign, verify, settle) via the facilitator | resource, payment_requirements (optional) |
payai_verify_payment |
Validate an x402 payment payload without settling on-chain | payment_payload, payment_requirements |
payai_settle_payment |
Broadcast an x402 settlement via the PayAI facilitator | payment_payload, payment_requirements |
Default Network: Set
PAYAI_FACILITATOR_DEFAULT_NETWORK(defaultsolana) to ensure tools automatically select the right scheme when a resource offers multiple options.
| Tool | Description | Parameters |
|---|---|---|
coinbase_x402_list_resources |
List discovery resources advertised by the Coinbase-operated facilitator | limit, offset, type |
coinbase_x402_verify_payment |
Validate an x402 payment payload against the facilitator | payment_payload, payment_requirements |
coinbase_x402_settle_payment |
Settle an x402 payment and return settlement metadata | payment_payload, payment_requirements |
coinbase_x402_auto_pay |
Fetch a protected resource and automatically fulfill its payment using the configured EVM wallet | url, method, query, headers, json, data |
These tools reuse the same EVM private key configured for AIXBT/x402 payments; set
AIXBT_PRIVATE_KEY(or store it viauv run sam settings) and install thex402Python package.
"Buy 0.01 SOL worth of BONK on pump.fun"
"Sell 50% of my DOGE position"
"Get swap quote for 1 SOL to USDC on Jupiter"
"Check my wallet balance"
"Show trending pairs on DexScreener"
"Find prediction market opportunities on Polymarket"
"Scan Kalshi for high-upside yes contracts"
"Open a long position on BTC futures with 5x leverage"
"Check my account balance on Aster Futures"
"Verify this payment payload with the PayAI facilitator"
"Auto-pay the Echo merchant on Solana"sam/
├── cli.py # Enhanced CLI with interactive features
├── core/
│ ├── agent.py # Main SAMAgent with advanced tool calling
│ ├── builder.py # AgentBuilder for modular construction
│ ├── llm_provider.py # Multi-LLM provider abstraction
│ ├── memory.py # SQLite-based conversation persistence
│ ├── tools.py # Tool registry with middleware support
│ ├── events.py # Event system for pub/sub messaging
│ └── middleware.py # Tool middleware pipeline
├── integrations/ # Blockchain and service integrations
│ ├── solana/ # Native Solana RPC operations
│ ├── pump_fun.py # Pump.fun trading interface
│ ├── jupiter.py # Jupiter aggregator integration
│ ├── dexscreener.py # Market data provider
│ ├── polymarket.py # Prediction market analytics
│ ├── aster_futures.py # Futures trading on Aster DEX
│ ├── aixbt.py # Narrative intelligence + Indigo agent access
│ ├── coinbase_x402.py # Coinbase-operated x402 facilitator helpers
│ ├── smart_trader.py # Smart trading with fallbacks
│ ├── search.py # Web search via Brave API
│ └── payai_facilitator.py # PayAI x402 facilitator integration
├── config/ # Configuration management
│ ├── settings.py # Environment and settings
│ ├── prompts.py # System prompts and templates
│ └── config_loader.py # TOML/JSON configuration loader
├── utils/ # Security and utilities
│ ├── crypto.py # Key encryption with Fernet
│ ├── secure_storage.py # OS keyring integration
│ ├── validators.py # Input validation and safety
│ ├── rate_limiter.py # Request throttling
│ └── connection_pool.py # RPC connection management
├── commands/ # CLI command modules
│ ├── onboard.py # Interactive setup wizard
│ ├── providers.py # LLM provider management
│ ├── health.py # System diagnostics
│ └── maintenance.py # Database maintenance
└── web/ # Web interface components
└── session.py # Web session management
- Event-Driven: Async pub/sub system for component communication
- Plugin Architecture: Entry point discovery for extensibility
- Middleware Pipeline: Configurable tool execution pipeline
- Builder Pattern: Modular agent construction
- Repository Pattern: Data access abstraction
- Connection Pooling: Shared database and HTTP client connections
- Circuit Breaker: API resilience with automatic failure recovery
- Session Management: Persistent conversation contexts with indexing
SAM supports multiple configuration methods with automatic loading priority:
- Environment Variables (highest priority)
- TOML Configuration File (
sam.toml) .envFile (auto-loaded)- Interactive Settings (runtime configuration)
- Sensible Defaults (lowest priority)
| Provider | Environment Variables | Models |
|---|---|---|
| OpenAI | OPENAI_API_KEY, OPENAI_MODEL, OPENAI_BASE_URL |
GPT-4, GPT-3.5 |
| Anthropic | ANTHROPIC_API_KEY, ANTHROPIC_MODEL, ANTHROPIC_BASE_URL |
Claude 3 |
| xAI | XAI_API_KEY, XAI_MODEL, XAI_BASE_URL |
Grok |
| Local | LOCAL_LLM_BASE_URL, LOCAL_LLM_MODEL |
Ollama, LM Studio |
| OpenAI Compat | LOCAL_LLM_BASE_URL, LOCAL_LLM_MODEL |
Custom endpoints |
| Integration | Environment Variables | Description |
|---|---|---|
| Polymarket | - | No API key required (public API) |
| Kalshi | KALSHI_API_KEY_ID, KALSHI_PRIVATE_KEY_PATH, KALSHI_USE_DEMO |
Prediction market trading (see Kalshi Setup) |
| Aster Futures | ASTER_API_KEY, ASTER_API_SECRET, ASTER_BASE_URL, ASTER_DEFAULT_RECV_WINDOW |
Futures trading credentials |
| Brave Search | BRAVE_API_KEY |
Web search and news aggregation |
| AIXBT Intelligence | AIXBT_PRIVATE_KEY* , AIXBT_API_BASE_URL (optional), ENABLE_AIXBT_TOOLS |
Access narrative analytics and Indigo research agent via x402 payments |
| Coinbase x402 Facilitator | COINBASE_X402_FACILITATOR_URL, COINBASE_X402_API_KEY (optional), ENABLE_COINBASE_X402_TOOLS |
Discovery, verification, and auto-pay for Coinbase-operated x402 resources |
| PayAI Facilitator | PAYAI_FACILITATOR_URL (or FACILITATOR_URL), PAYAI_FACILITATOR_API_KEY (optional), PAYAI_FACILITATOR_DEFAULT_NETWORK (default solana) |
x402 verification, settlement, and resource discovery |
*If AIXBT_PRIVATE_KEY is not provided, SAM reuses the stored Hyperliquid EVM wallet key for x402 payments.
Kalshi uses RSA-PSS signature authentication. To enable authenticated endpoints (portfolio, trading):
- Generate API Key: Log in to Kalshi (or demo) → Account Settings → API Keys → Create New API Key
- Save Private Key: Download the
.keyfile to a secure location (e.g.,~/.kalshi/kalshi-key.key) - Configure Environment:
export KALSHI_API_KEY_ID="your-key-id-from-kalshi" export KALSHI_PRIVATE_KEY_PATH="$HOME/.kalshi/kalshi-key.key" # Optional: Use demo environment for testing with fake funds # export KALSHI_USE_DEMO=true
Note: Public endpoints (market data, opportunity scanning) work without authentication. Authentication is only required for portfolio and trading operations.
API Endpoint: Uses production API at api.elections.kalshi.com by default. For demo environment (fake funds), set KALSHI_USE_DEMO=true.
Important: Kalshi uses different units than Polymarket:
- Volume: Measured in contracts (not USD)
- Liquidity: Kalshi-specific metric (typically 50-5000 range)
- Markets: Binary (Yes/No only, not multi-outcome)
- Default thresholds: Lower than Polymarket due to different market structure
# sam.toml
[llm]
provider = "anthropic"
model = "claude-3-5-sonnet-latest"
[safety]
max_transaction_sol = 5.0
default_slippage = 2.0
[tools]
enable_solana_tools = true
enable_pump_fun_tools = true
enable_jupiter_tools = true
enable_dexscreener_tools = true
enable_polymarket_tools = true
enable_aster_futures_tools = false
enable_search_tools = false{
"logging": {
"include_args": false,
"include_result": false,
"only": [],
"exclude": []
},
"rate_limit": {
"enabled": true,
"map": {
"search_web": {"type": "search", "identifier_field": "query"},
"pump_fun_buy": {"type": "pump_fun_buy", "identifier_field": "mint"}
}
},
"retry": [
{"only": ["search_web"], "max_retries": 2, "base_delay": 0.25}
]
}SAM supports external tools via Python entry points:
# setup.py or pyproject.toml
[project.entry-points."sam.plugins"]
my_trading_tools = "my_package.tools:register"
[project.entry-points."sam.llm_providers"]
custom_llm = "my_package.llm:create_provider"
[project.entry-points."sam.memory_backends"]
redis_memory = "my_package.memory:create_backend"# my_trading_tools.py
from sam.core.tools import Tool
async def arbitrage_scanner(args: dict) -> dict:
"""Scan for arbitrage opportunities."""
return {
"success": True,
"opportunities": [],
"timestamp": "2024-01-01T12:00:00Z"
}
def register(registry, agent=None):
registry.register(Tool(
name="arbitrage_scanner",
description="Scan for arbitrage opportunities across DEXs",
input_schema={
"type": "object",
"properties": {
"min_profit_percent": {"type": "number", "default": 1.0}
}
},
handler=arbitrage_scanner
))# Load custom plugins
export SAM_PLUGINS="my_package.tools,vendor.tools"
# Use custom memory backend
export SAM_MEMORY_BACKEND="my_package.memory:create_backend"SAM loads third-party plugins only when they are explicitly trusted.
# Enable plugin loading (disabled by default)
export SAM_ENABLE_PLUGINS=true
# Optional settings
export SAM_PLUGIN_ALLOWLIST_FILE=./sam/config/plugin_allowlist.json
export SAM_PLUGIN_ALLOW_UNVERIFIED=false # keep strict mode
# Record a plugin module fingerprint
uv run sam plugins trust my_package.tools --entry-point my-tools --label "Vendor Tools"- The allowlist stores module SHA-256 digests to prevent supply-chain tampering.
- Run
sam debugto review the trusted set and environment state. - When upgrading a plugin, re-run
sam plugins trust …to refresh the recorded hash.
SAM implements multiple layers of security for key management:
| Method | Description | Use Case |
|---|---|---|
| OS Keyring | System-level credential storage | Production deployments |
| Fernet Encryption | AES-128 encryption for keys | Secure storage |
| Environment Variables | Runtime configuration | Development |
- Transaction Validation: Pre-execution safety checks
- Slippage Protection: Configurable slippage tolerance
- Rate Limiting: Request throttling and abuse prevention
- Address Validation: Solana address format verification
- Audit Logging: Tool execution and error tracking
# Security configuration
RATE_LIMITING_ENABLED=true
MAX_TRANSACTION_SOL=5.0
DEFAULT_SLIPPAGE=2.0
LOG_LEVEL=WARNING
# Key management
sam key import # Secure key import
sam key generate # Generate encryption keys
sam key rotate --yes # Rotate SAM_FERNET_KEY and re-encrypt stored secretsSAM includes comprehensive testing infrastructure with 25+ test files covering all major components:
# Run complete test suite
uv run pytest tests/ -v
# Run with coverage reporting
uv run pytest tests/ --cov=sam --cov-report=html
# Run specific test categories
uv run pytest tests/test_integration.py # Integration tests
uv run pytest tests/test_tools.py # Tool registry tests
uv run pytest tests/test_polymarket.py # Polymarket integration
uv run pytest tests/test_aster_futures.py # Futures trading tests
# Run async tests with proper configuration
uv run pytest tests/ --asyncio-mode=auto- Comprehensive Coverage: Unit, integration, and end-to-end tests
- Async Testing: Full asyncio support with pytest-asyncio
- Mock Frameworks: Extensive mocking for external API dependencies
- Environment Testing: Test-specific configurations and fixtures
- Performance Validation: API resilience and error handling tests
# Format code
uv run ruff format
# Check style and fix issues
uv run ruff check --fix
# Type checking
uv run mypy sam/Run before opening a pull request to ensure quality gates stay green:
uv run ruff check # Static analysis
uv run mypy sam/ # Type safety across the package
uv run pytest -v # Full test suiteAll three commands must pass without warnings for CI parity.
SAM ships a single, consolidated decorator toolkit under sam.utils.decorators. These helpers combine rate limiting, error tracking, retry/backoff, and performance telemetry in one place:
from sam.utils.decorators import (
rate_limit,
retry_with_backoff,
log_execution,
safe_async_operation,
performance_monitor,
)
from sam.utils.error_handling import ErrorSeverity
@safe_async_operation(
"dexscreener",
log_result=True,
max_retries=2,
error_severity=ErrorSeverity.MEDIUM,
)
@performance_monitor("dexscreener", warn_threshold=0.5)
@rate_limit("market_data")
async def fetch_pair(mint: str) -> dict:
...All decorator imports that previously referenced sam.utils.enhanced_decorators should now use sam.utils.decorators.
# Setup and development
uv sync # Install dependencies
make install # Alternative setup via Makefile
# Code quality (via Makefile)
make format # Format code with ruff
make lint # Check style and fix issues
make typecheck # Run mypy type checking
make test # Run complete test suite
# Individual commands
sam debug # Show plugins and middleware
sam provider test # Test LLM provider
sam health # System diagnostics
sam settings # Runtime configuration
sam maintenance # Database maintenance operations- Makefile: Standardized development targets for common operations
- Enhanced Testing: 25+ test files with comprehensive coverage
- Async Optimization: uvloop integration for performance
- Connection Pooling: Shared database and HTTP client connections
- Circuit Breakers: API resilience with automatic recovery
import asyncio
from sam.core.builder import AgentBuilder
async def main():
agent = await AgentBuilder().build()
# Direct tool calls
result = await agent.tools.call("get_balance", {"address": "..."})
print(result)
# Headless agent
response = await agent.run("Check my SOL balance", session_id="sdk")
print(response)
asyncio.run(main())- Architecture Guide - System design and components
- Tools Reference - Complete tool documentation
- Configuration Guide - Setup and configuration options
- CLI Reference - Command-line interface documentation
- Security Guide - Security features and best practices
- Getting Started - Step-by-step setup guide
- API Reference - SDK and API documentation
examples/plugins/- Plugin development examplesexamples/sdk/- SDK integration patternstests/- Comprehensive test suite
MIT License with SAM Framework Additional Terms - See LICENSE for complete licensing details.
- Contact Requirement: Must contact @prfa before releasing tools built on SAM Framework
- $SAM Token Benefits: Tools must provide benefits to $SAM token holders
- Ecosystem Participation: Active participation in the $SAM ecosystem rewards program
- Transparency: Clear disclosure of SAM Framework usage and token holder benefits
Contributions welcome. See CONTRIBUTING.md for guidelines.
@prfa • @prfagit • getsam.xyz
SAM Framework - Production-ready AI agent infrastructure for Solana blockchain operations.
Built for developers who value technical excellence and production reliability.
SAM encrypts sensitive data (wallet keys, API credentials, wallet configs) using Fernet and the OS keyring by default. The storage layer is now pluggable:
- Base interface:
sam.utils.secure_storage.BaseSecretStoredefines the required methods. The built-inSecureStorageimplementation handles keyring/Fernet encryption with an encrypted file fallback. - Plugins: Provide your own secret store by exposing an entry point in the
sam.secure_storagegroup or by callingconfigure_secure_storage(custom_store). Seeexamples/plugins/secure_storage_dummyfor a simple in-memory example. - Key rotation:
SecureStorage.rotate_encryption_key()migrates stored secrets to a new Fernet key; custom stores should implement similar behavior when possible.
Agent and tool events are published via the async event bus. API adapters can import typed payload definitions from sam/core/event_payloads.py to ensure compatibility. Available payload types include:
AgentStatusPayloadLLMUsagePayloadToolCalledPayloadToolResultPayload/ToolFailedPayloadAgentDeltaPayloadAgentMessagePayload
Every payload includes both session_id and user_id, enabling multi-tenant streaming adapters to filter by caller.
