◆ VERSION 3.0.3 PRODUCTION READY PYTHON 3.11+ MIT LICENSE

SHS CODE

Enterprise-Grade Autonomous AI Agent Framework

A production-ready, self-reasoning agent framework with the PAORR loop, DAG-based multi-agent orchestration, defense-in-depth security, 100+ LLM providers (cloud + offline GGUF / HuggingFace / Ollama), 13+ messaging channels, voice, live canvas, SSH, cron and enterprise observability.

0+
LLM Providers
0+
Channels
0+
Tools
0
Tests Passed
SHS Code dashboard running on an ultrawide monitor with live agent workflows, charts and terminals
PAORR · Plan → Act → Observe → Reflect → Retry
DAG Multi-Agent Orchestrator
Security Ensemble · 4 layers
212 tests · SQLite WAL · FTS5
Enterprise Highlights

Built to run anywhere.
Cloud, local, or fully air‑gapped.

SHS Code empowers LLMs to plan, execute code, browse the web, manage files, resolve issues and complete complex multi-step tasks — all autonomously.

PAORR Self-Reasoning Loop

Plan → Act → Observe → Reflect → Retry — a self-correcting execution model at the heart of every agent. The SHS Code agent performs a self-check every 3 steps to verify progress.

PLAN ACT OBSERVE REFLECT RETRY ∞

DAG Multi-Agent Orchestration

Pipelines with topological sorting (Kahn's algorithm), event hooks and a global timeout. Role pipeline: ProductManager → Architect → Engineer → QA over a typed RoleMessageBus.

Kahn's algorithmRoleMessageBusper-channel routing

Defense-in-Depth Security

Pattern → Rails → LLM → Ensemble fusion with audit trails, human-in-the-loop confirmation and Fernet-encrypted secrets.

100+ LLM Providers

Cloud + offline GGUF / HuggingFace / Ollama with credential rotation, profile rotation and model failover. Zero vendor lock-in.

13+ Channels · Voice · Canvas

Telegram to Teams, wake-word voice, A2UI live canvas, SSH server, webhooks and cron — one unified messaging gateway.

Enterprise Observability

OpenTelemetry tracing via @observe, Prometheus metrics, K8s liveness /healthz and readiness /ready probes, correlation IDs and JSON structured logging with secret redaction.

OTELPrometheusp50/p95/p99

Persistence That Survives Restarts

SQLite WAL with FTS5 full-text search: sessions, NDJSON event logs and priority task queues with checkpoint / resume. 7 core tables via Alembic migrations.

SQLite WALFTS5Alembic ×7 tables
Live Telemetry

The framework, in numbers.

Why SHS Code

Every enterprise objection, already answered.

Architecture

Six layers. One autonomous core.

From presentation to infrastructure — every layer is modular, thread-safe and crash-proof by default.

The Heart

The PAORR reasoning loop.

A self-correcting cycle that plans, acts, observes, reflects and retries until the task is complete — autonomously.

PAORR
STEP 01 / 05

Plan

Multi-Agent Orchestration

A role pipeline, orchestrated as a DAG.

Topological sorting via Kahn's algorithm, event hooks, global timeout and per-channel / per-account routing with an LRU cache (64 entries, 300s idle TTL).

Multi-Agent Orchestrator DAG-based · Kahn's topological sort · global timeout ProductManagerRoleResult ArchitectRoleResult EngineerRoleResult QARoleResult RoleMessageBus — typed messages between roles
Agent inheritance  BaseAgent → ReActAgent → ToolCallAgent → SHSCode → DataAnalysisAgent
Platform Depth

Enterprise features, layer by layer.

🪝 Hooks System

Lifecycle interception with blocking power. YAML config with class_path imports + Python module auto-discovery from the SHS Code home directory.

SESSION_STARTAgent session begins — non-blocking
USER_PROMPT_SUBMITBefore the prompt enters the loop — can DENY / MODIFY
PRE_TOOL_USEBefore tool execution — can DENY
POST_TOOL_USEAfter a tool returns — non-blocking
STOPAgent about to stop — can DENY
SESSION_ENDSession terminates — non-blocking
Built-insLoggingHook (all events) · SecurityHook (blocks dangerous actions) · AuditHook (JSONL trail with secret sanitization)

🧠 Context Management — View + Condenser

Linear event projection with safe condensation points and structural integrity guarantees.

View Systemmanipulation_indices — safe points for condensation
View PropertiesBatchAtomicity · ObservationUniqueness · ToolCallMatching · ToolLoopAtomicity
LLM Summarizing CondenserDedicated condenser LLM summarizes removed events · triggers: REQUEST (hard) · TOKENS (soft) · EVENTS (soft)
Rolling WindowKeeps the N most recent events, drops the rest
Pipeline CondenserChains condensers with stop_on_first short-circuit + aggregated metrics
Progressive TruncationOn condenser LLM failure: 5 retries, 0.8× scaling per retry · No-op pass-through when disabled

💬 Conversation System

Local in-process or WebSocket-backed remote conversations with reconnection + event buffering.

Local / RemoteEvent log, async, fork / branch, confirmation mode · factory auto-selects by config
StuckDetector5 patterns: repeating action-observation, action-error loops, agent monologue, alternating patterns, context overflow
CancellationTokenThread-safe, raise_if_cancelled(), timeout support, context manager
FIFOLockFair, starvation-free locking (sync + async) guaranteeing FIFO ordering

⚡ Parallel Tool Execution

Readers-writer locking with deadlock prevention via global acquisition ordering.

ResourceLockManagerPer-resource READ / WRITE locks · deadlock-free ordering
Declared Resourcesfile_resource() · terminal_resource() · network_resource()
ParallelToolExecutorThread-pool concurrency with conflict serialization
AsyncParallelToolExecutorasyncio.gather + semaphore concurrency capping
MetricsExecution time · concurrency level · resource conflicts · per-tool timeout

🔐 Secrets + 📦 File Storage

Fernet encryption at rest with key rotation; pluggable storage backends with factory auto-detection.

Cipher (Fernet)FERNET_TOKEN_PREFIX · add_key() seamless rotation
SecretRegistryLazy resolution, namespaces, caching · sources: STATIC · LOOKUP · ENV
File Secrets StoreAtomic writes, 0600 permissions · API router never exposes raw values (masked ***)
Local / In-MemoryAtomic writes + sidecar .meta.json + streaming · full metadata tracking
S3 / GCSPresigned & v4 signed URLs, retry with backoff, async executor · SHSCODE_FILE_STORE_BACKEND

💾 Session & Memory System

Everything persists. Everything survives restarts.

SessionDBSQLite WAL + FTS5 · session branching · compression
Resume / Branch/resume interrupted sessions · /branch for parallel exploration
Long-Term MemoryRAG-like persistent memory, FTS5 + LIKE fallback
Short-Term MemoryConversation buffer with refresh, snapshot, restore
Task QueuePersistent SQLite queue · priority ordering · checkpoint / resume · worker pool · dedup
Alembic Migrations7 core tables: conversations · events · sessions · tasks · credentials · secrets · audit_log

📡 Connectivity & Extensions

Remote control, scheduling, protocol bridging and desktop companions.

SSH ServerFull remote agent control + interactive shell · port / host / auth via config.toml or env
Cron SchedulerYAML persistence + auto-reload · webhook delivery · multi-platform output · auto-cleanup · secrets redacted
MCP Client + Serverstdio / SSE connections · proxy MCP tools as native tools · expose SHS Code tools · auto-discovery in config.toml
Skills Enginecoding · devops · data_analysis · research · mlops · github — auto-injected by relevance
Desktop AppsmacOS Menubar (rumps) · Windows Hub · Mobile Node (iOS / Android canvas nodes)
Defense-in-Depth

Four shields. Zero blind spots.

Multi-layer security analysis combining pattern matching, policy rails, LLM-based analysis and ensemble fusion — with full audit trails.

L1

Pattern Analyzer PatternSecurityAnalyzer

8 regex patterns across 2 corpora (executable + all-field): rm_rf · sudo_rm · eval_call · subprocess · curl_pipe_exec · inject_override · inject_mode_switch · inject_identity

L2

Policy Rails PolicyRailSecurityAnalyzer

3 structural rails — fetch-to-exec · raw-disk-op · catastrophic-delete. Per-segment evaluation prevents cross-field false positives.

L3

LLM Analyzer LLMSecurityAnalyzer

AI-powered semantic analysis for subtle threats, with a configurable call budget.

L4

Ensemble EnsembleSecurityAnalyzer

Max-severity fusion, crash isolation, full audit trail. Confirmation via NeverConfirm / ConfirmRisky for HIGH / UNKNOWN risk.

Cipher Fernet at rest + key rotation redact() masks API keys · tokens · AWS secrets Identity Guard 30+ anti-jailbreak patterns · 9 languages Permission Gate AUTONOMOUS / CONFIRM / RESTRICTED
Event System

17 typed events. One append-only truth.

Discriminated unions with kind literal discriminators for pattern matching. A file-backed NDJSON EventLog with O(1) length queries, lazy loading, atomic writes and temp-file-then-rename crash safety + reindex() recovery.

LLMConvertibleEvent protocol parallel tool-call batching serialize_batch() / deserialize_batch() count file updated post-write
eventlog.ndjson — live append

                    
LLM Ecosystem

100+ providers. Zero lock-in.

Credential pools with multi-key rotation, cross-provider rotation, profile rotators, 8 fallback triggers, token budgets and p50 / p95 / p99 latency metrics.

Cloud Providers
Offline · Local · Air-Gapped
Pre-Configured Provider TOMLs
LLM Infrastructure
Streaming token-level · SSE · backpressure Enhanced Retry 5 backoff strategies · retry budgets Fallback rate_limit · context_window · timeout +5 Token Budget per-session · grace call · cost estimation NonNativeToolCallingMixin prompt-engineered function calling Secret Redaction in prompts & logs Credential Pool OPENAI_API_KEY_2 / _3 · cooldown · health
Air-Gapped by Design

No internet? No problem.

Fully offline inference with zero cloud dependency — GGUF via llama-cpp-python, HuggingFace local, Ollama local.

Air-gapped server room running local GGUF and Ollama inference
● zero cloud dependency · zero telemetry · zero keys
GGUF

GGUF — llama-cpp-python

Any .gguf model, fully offline, GPU support via n_gpu_layers, tool-call parsing from raw text.

provider = "gguf" · model_path = "/path/to/model.gguf"
OLLAMA

Ollama — official SDK

Run ollama serve and go. Local + Ollama Cloud with API key when you want it.

provider = "ollama" · model = "llama3"
HF

HuggingFace — HuggingFaceRouter

Inference API + Spaces + Dedicated Endpoints, or local models.

provider = "huggingface" · model = "meta-llama/Llama-3-8B"
LMStudio · localhost:1234text-gen-webui · localhost:5000Any OpenAI-compat (Groq, Together…)MockLLM · no key needed
Messaging Ecosystem

13+ channels. One gateway.

Multi-adapter routing with agent caching and eviction with cleanup — per-channel and per-account.

Messaging
Gateway
Voice · Canvas

Speak to it. Watch it think.

Voice System

Wake word → STT → agent → TTS, in a continuous Talk Mode conversation loop.

"Hey SHS Code" — Pvporcupine or STT-based wake word
STT OpenAI Whisper · Google · Vosk (offline) TTS OpenAI · ElevenLabs · System (espeak/piper) Talk Mode continuous mic loop

Canvas UI — A2UI Protocol

Real-time WebSocket updates from agent to browser with a typed, composable component model.

 canvas.html — wss:// live render
active_conversations0
token_usage_total128k
Button · A2UI component
Charts: bar · line · scatter · pie · histogram · area · radar Components: Text · Image · Button · Table · Chart · Container Mobile nodes · static canvas.html
17+ Tools · Intelligent Selector

A tool for every act.

🎯 ToolSelector — confidence-based scoring

Heuristic keyword matching + optional LLM scoring produce a 0.0 – 1.0 confidence per tool, with failure penalties, recency diversification and a public stats API. The Permission Gate enforces 3-tier access: AUTONOMOUS / CONFIRM / RESTRICTED with catastrophic pattern blocking.

Bash0.94
StrReplaceEditor0.81
WebSearch0.63
Git Provider Integrations

Five platforms. Full coverage.

A unified GitProviderService interface — sync + async, thread-safe, rate-limited, exponential backoff. URL-based router detects 10+ patterns including self-hosted instances.

Webhooks HMAC-SHA256 · dedup · retry · normalization Suggested tasks OPEN_ISSUE · FAILING_CHECKS · MERGE_CONFLICT · UNRESOLVED_COMMENTS Concurrency semaphore max 5 · per-resolution locking · Jinja2 templates
Project Management
📋 Jira Cloud + DC

OAuth / PAT · create / update / search · JQL · comments · transitions · ADF→text · webhooks

📐 Linear

GraphQL API · OAuth 2.0 · teams · issues · comments · suggested tasks · webhooks

💬 Slack

Socket Mode + API · /shscode /resolve /review · Block Kit · threads · buttons · uploads

Observability

See every token. Trace every call.

SHS Code observability dashboard with live metrics, gauges and log streams
llm_calls_total
48,213
llm_call_duration
p95 412ms
p50 180ms · p99 940ms
token_usage_total
9.4M
cost tracking per conversation
active_conversations
37
error_count_total · 0
/healthz · liveness /ready · readiness DatabaseHealthChecker LLMHealthChecker SandboxHealthChecker
@observe sync/async spans correlation IDs · error_id lookup JSON structured logs · redaction tool_calls_total · conversation_duration_seconds
Docker Deployment

Containerized in seconds.

Build the image

One command to a production image.

docker build -t shscode:latest .

Run the CLI agent

Interactive, or one-shot tasks.

docker compose up
docker compose run --rm shscode "Your task here"

Server mode

FastAPI + WebSocket server on port 8765.

docker compose --profile server up -d

Multi-agent pipeline

Run the full DAG role pipeline in a container.

docker compose --profile multi up

Compose services

ServiceProfileDescription
shscodedefaultInteractive CLI agent
serverserverFastAPI + WebSocket · :8765
multi-agentmultiMulti-agent pipeline runner
health probes

                        
Quick Start

From zero to autonomous in five lines.

Python 3.11+ One LLM API key — or none at all Free: Pollinations / OpenCode, no key needed Offline: GGUF / Ollama / HuggingFace Linux · macOS · Windows · Docker
zsh — shscode
# Clone the repository
                                $ git clone https://github.com/shslab-org/SHS-Code.git
                                $ cd shscode

                                # Install dependencies — or with all enterprise features:
                                $ pip install -e .            # or: pip install -e ".[all-plus]"

                                # Configure your API key
                                $ cp config.toml config.toml.local
                                $ export OPENAI_API_KEY=sk-...

                                # Run your first task
                                $ python main.py "Create a Python script that generates Fibonacci numbers"
config.toml — free providers
# Use Pollinations (free, no key)
                                # Set in config.toml:
                                provider = "pollinations"

                                # Or use OpenCode (free deepseek-v4-flash)
                                provider = "opencode"
config.toml — air-gapped
# GGUF — download any .gguf model, zero internet
                                provider       = "gguf"
                                model_path     = "/path/to/model.gguf"
                                n_gpu_layers   = 0   # set >0 for GPU acceleration

                                # Ollama — run `ollama serve`, then:
                                provider = "ollama"  ·  model = "llama3"

                                # HuggingFace — Inference API, Spaces, or local
                                provider = "huggingface"  ·  model = "meta-llama/Llama-3-8B"
Linux / macOS
# One-Line Install (Linux/macOS)
                                $ curl -fsSL https://raw.githubusercontent.com/shslab-org/SHS-Code/main/install.sh | bash
PowerShell
PS> .\install.ps1
shscode — first run

                
Configuration

One file. Total control.

SHS Code uses config.toml for all configuration. See config.toml for the full reference with every option and default.

config.toml
[llm]
                                model       = "gpt-4o"
                                provider    = "openai"   # openai | anthropic | google | mistral | bedrock | ollama | gguf | huggingface | litellm | openrouter | pollinations | opencode | 7llm | mock
                                api_key     = ""          # Or set OPENAI_API_KEY env var
                                max_tokens  = 4096
                                temperature = 0.7

                                [llm.streaming]
                                enabled     = true
                                buffer_size = 4096

                                [llm.fallback]
                                enabled = false
                                chain   = ["gpt-4o", "claude-3-5-sonnet-20241022", "gemini-2.0-flash"]
config.toml
[agent]
                                max_iterations = 50
                                mode           = "confirm"   # autonomous | confirm | restricted

                                [security]
                                enabled                = true
                                analyzers              = ["pattern", "rails"]   # pattern | rails | llm | ensemble
                                confirmation_threshold = "medium"                # low | medium | high

                                [hooks]
                                enabled   = true  ·  auto_load = true  ·  timeout_s = 30
config.toml
[context]
                                max_events     = 200
                                max_tokens     = 128000
                                condenser_type = "rolling"   # rolling | llm_summarizing | noop

                                [conversation]
                                max_iterations    = 30
                                confirmation_mode = "confirm_risky"   # never_confirm | confirm_risky
                                stuck_detection   = true
config.toml
[observability]
                                tracing       = false  ·  metrics = true  ·  health_probes = true

                                [secrets]
                                backend            = "file"   # file | env
                                encryption_enabled = true

                                [file_store]
                                backend = "local"   # local | s3 | gcs | memory

                                [git_providers]
                                default_provider = "github"   # github | gitlab | azure_devops | bitbucket | forgejo

                                [parallel_executor]
                                max_workers = 4  ·  timeout_s = 300

                                [migrations]
                                enabled = true  ·  auto_run = false
config.toml
[sandbox]
                                backend = "docker"   # docker | ssh | openshell

                                [ssh]
                                host = "0.0.0.0"  ·  port = 2222

                                [voice]
                                wake_word  = "hey shs code"
                                stt_engine = "openai"   # openai | google | vosk (offline)
                                tts_engine = "openai"   # openai | elevenlabs | system

                                [integrations]
                                webhooks_enabled = true
Entry Points

Five binaries. Ten slash commands.

shscode

Interactive CLI agent with slash commands

shscode-server

FastAPI + WebSocket server

shscode-cron

Cron scheduler daemon

shscode-multi

Multi-agent pipeline runner

shscode-sessions

Session management tool

FAQ

Questions, answered.

Ship your first
autonomous agent tonight.

MIT-licensed. Production-ready. 212 tests passed. Runs in the cloud, on your laptop, or in a fully air-gapped rack.

curl -fsSL …/install.sh | bash
Copied to clipboard