Command Synthesis, Providers & Safety Verification
The intelligence layer under src/sempropos/intelligence/ separates provider-neutral contracts from lazy-loaded backends, structured JSON prompting, and deterministic command grounding/safety verification.
Contracts#
src/sempropos/intelligence/contracts.py defines:
StructuredPrompt(system, context, query, json_schema=None)— the system instruction, truncatedToolSpeccandidate dicts, user task, and optional JSON schema (COMMAND_JSON_SCHEMA).SynthesisResult(provider, command, raw_output, tool=None, explanation="", alternatives=(), metadata={})— normalized provider output.SynthesisOptions—think,temperature,max_tokens,keep_alive,stop,base_url,api_key,timeout_seconds,n_ctx,n_gpu_layers,threads, andstructured_output.- Exception hierarchy:
IntelligenceError,ProviderUnavailableError,ProviderExecutionError, andProviderConfigurationError. SynthesisProviderBackendandEmbeddingProviderBackendprotocols.
Lazy Facade & Dispatch#
src/sempropos/intelligence/facade.py imports provider modules (_fastembed, _local_gguf, _ollama, _openai_compatible, _tier0) strictly on demand inside the branches that use them so CLI startup and pure-lexical commands never pay ML runtime import overhead.
- Synthesis selection:
detect_synthesis_provider()inspectsconfig.load_config().synthesis.providerand returns(provider_name, SynthesisConfig)forlocal_gguf,ollama,openai_compatible, ortier0if available, raisingProviderUnavailableErrorotherwise (no silent cross-provider fallback). - Embedding selection:
detect_embedding_provider()supportsfastembed_local,ollama, andnone(lexical-only mode). - Dispatch:
synthesize(prompt, backend=None, model=None)honors an explicitbackendoverride while preserving configuredSynthesisConfigoptions, and dispatches to the target provider. - Warm-up & teardown:
warm_synthesis_provider()warmsollamaorlocal_ggufmodels;shutdown_providers()unloads FastEmbed and terminates any in-process orllama-serverGGUF runtime.
Prompt Construction & JSON Output Parsing#
src/sempropos/intelligence/prompt.py enforces structured output with COMMAND_JSON_SCHEMA:
json{
"tool": "<name>",
"command": "<one runnable command>",
"explanation": "<short explanation>",
"alternatives": [],
"none": false
}
| Budget Constant | Value |
|---|---|
MAX_PROMPT_WORDS |
680 |
MAX_TOOLS |
5 |
MAX_SUBCOMMANDS_PER_TOOL |
4 |
MAX_FLAGS_PER_TOOL |
8 |
MAX_EXAMPLES_PER_TOOL |
4 |
build_prompt truncates candidates in stages until total words fit MAX_PROMPT_WORDS (reducing examples 4 -> 1, then flags 8 -> 4, then subcommands 4 -> 2, then tools 5 -> 1).
parse_synthesis_output(raw_output) (and extract_command) first attempts to parse a JSON object (including inside fenced blocks), honoring "none": true as an explicit non-fit. When JSON is absent, it strips language-tagged markdown fences (```bash), leading shell prompts ($, #, >), rejects prose markers and usage/synopsis echoes (du [OPTION]...), and rejects outputs over 500 characters. If synthesis fails to produce a command and did not explicitly return none, SemService._repair_once performs one repair retry.
Providers#
Managed Local GGUF (local_gguf)#
src/sempropos/intelligence/models.py provides a curated catalog of small CLI-tuned GGUF models downloaded atomically into config.models_dir():
| Tier | Model ID | Approx. Size | Min RAM |
|---|---|---|---|
tiny |
qwen2.5-coder-0.5b |
398 MB | 2 GB |
balanced |
qwen2.5-coder-1.5b |
986 MB | 4 GB |
quality |
qwen2.5-coder-3b |
1930 MB | 8 GB |
src/sempropos/intelligence/providers/_local_gguf.py supports two automatic drivers:
- In-process
llama-cpp-python(whensempropos[local-llm]is installed), caching theLlamasingleton and passingresponse_format={"type": "json_object", "schema": COMMAND_JSON_SCHEMA}. - Managed
llama-server(on$PATHordata_dir()/bin/llama-server), spawned on an ephemeral loopback port (127.0.0.1), polled on/health, called via/v1/chat/completionswithjson_schema, and terminated cleanly onunload_model()/atexit.
Pure-HTTP Ollama (ollama)#
src/sempropos/intelligence/providers/_ollama.py uses Python stdlib urllib.request directly (requiring neither the ollama Python SDK nor runtime pip install). It resolves the host from base_url, OLLAMA_HOST, or http://127.0.0.1:11434, checks /api/tags, passes format: COMMAND_JSON_SCHEMA and think to /api/chat (retrying once without think/format if rejected), and calls /api/embed for embeddings.
OpenAI-Compatible (openai_compatible)#
src/sempropos/intelligence/providers/_openai_compatible.py resolves base_url and bearer API keys (options, api_key_env, keyring, plaintext, or SEMPROPOS_OPENAI_API_KEY), sends response_format json_schema to /chat/completions (retrying without response_format on HTTP 400/422), and maps HTTP vs. URL failures cleanly.
FastEmbed (fastembed_local)#
src/sempropos/intelligence/providers/_fastembed.py caches one TextEmbedding ONNX singleton in config.embeddings_cache_dir(), caps threads at min(cpu_count, 4), uses query_embed / passage_embed when available, and exposes is_model_loaded() for confidence-gated semantic execution.
Deterministic Tier-0 (tier0)#
src/sempropos/intelligence/providers/_tier0.py is always available offline. Rather than returning an empty placeholder, it scores retrieved ToolSpec examples by token overlap against the query (with a 0.15 top-candidate bonus) and emits the matching verified command when overlap reaches >= 0.55, falling back cleanly to structured ToolSpec card display otherwise.
Command Grounding & Safety Verification#
Before SemService.ask returns a command, verify_command(command, spec) (src/sempropos/intelligence/safety.py):
- Extracts the primary executable across pipelines/chains (
|,&&,;), skipping leadingKEY=VALenv assignments and wrapper commands (sudo,doas,env,time,nice,nohup) including wrapper value flags (sudo -u root). - Checks whether the executable exists in
$PATH, shell builtins, or the matchedToolSpecname/aliases. - Expands bundled short flags (e.g.
-sh,-xzf) and cross-checks flags against the matchedToolSpecto produce verifiedFlagAnnotationentries for--explainand record anyunverified_flags. - Classifies operational risk as
safe,caution(sudo,rm,sed -i,chmod/chown,systemctl stop|restart|disable,docker|podman rm|prune,kill), ordestructive(rm -rf,find -delete,dd of=/dev/...,mkfs*/wipefs/shred,chmod -R 777,git reset --hard,git push --force,git clean -f,kill -9,curl|wget ... | sh|bash, block-device redirects).