Engineering Manual
Developer reference and integration guide for running Apical Arbor, Apical Plexus, and Apical Edge in constant O(1) memory with cryptographic zero-retention verification.
-std=c99) for bare-metal Apical Edge firmware. Obtain an API key (apk_live_...) from the Developer Console before running authenticated cloud examples.
Platform Topology & The Constant-Memory Invariant
Upstream frozen encoders (such as DINOv2, CLIP, BGE, Whisper, or causal LLMs) extract an L2-normalized embedding from raw text, audio, or image inputs. Optionally, the client-side OrthogonalPrivacyProjector blinds the vector coordinates using a local secret key before the payload leaves client memory.
Downstream, Apical queries or updates a pre-allocated fixed-byte synaptic container in a single forward pass on CPU (persisted_bytes_delta == 0), zeroes transient RAM input buffers before returning, and emits a signed Ed25519 execution receipt.
+---------------------------------------------------------------------------------------+
| [1. Client Environment] Application, Microservice, or IDE Agent |
| |
| Feature Vector r(t) -> [OrthogonalPrivacyProjector] -> Blinded Vector r'(t) |
| - Optional client-side keyed isometric rotation (secret key never leaves client) |
| - Preserves L2 norms and cosine geometry so downstream routing is unchanged |
+---------------------------------------------------------------------------------------+
|
HTTPS (TLS 1.3) or Local Loopback / UNIX Socket
v
+---------------------------------------------------------------------------------------+
| [2. Authenticated API Gateway] Request Routing, Auth & Quota Control |
| |
| - Bearer API Key Authentication (apk_live_...) |
| - Capability Scope Enforcement: infer, learn, admin |
| - Plan & Product Entitlement Check (Arbor, Plexus) |
| - Per-Tenant Token-Bucket Rate Limiting |
+---------------------------------------------------------------------------------------+
|
Internal Isolated IPC Channel
v
+---------------------------------------------------------------------------------------+
| [3. Zero-Retention Enclave] Isolated Constant-Memory Runtime |
| |
| A. Input Vector Integrity Guard: |
| - Rejects degenerate sparse/zero-padded vectors (ERR_ORACLE_SPARSE_PROBE) |
| - Halts non-stochastic collinear probe sweeps (ERR_ORACLE_SWEEP_DETECTED) |
| |
| B. Fixed-Byte Synaptic Container: |
| - Pre-allocated constant O(1) state: persisted_bytes_delta == 0 |
| - Single-pass online directional update on CPU (< 0.10 to 0.22 ms) |
| |
| C. Zero-Retention Scrubber & Attestation Signer: |
| - Scrubs transient input vector buffers in RAM before returning |
| - Signs canonical JSON receipt with Enclave Ed25519 private key |
+---------------------------------------------------------------------------------------+
Module Quick-Reference
Select the primitive matching your embedding geometry, tool catalog size, or target hardware environment:
| Module Primitive | Family | Primary Production Application | Key Methods | CPU Latency | Memory Invariant |
|---|---|---|---|---|---|
| I. Agent Infrastructure & Tool Routing | |||||
arbor.MemoryRouter |
Arbor | Route dense embeddings to top-K tool IDs or rule partitions online | route(), reinforce() | < 0.05 ms | Constant O(1) (ΔBytes == 0) |
arbor.ModelRouter |
Arbor | Dispatch prompts across configured LLM tiers with online escalation updates | route_prompt(), reinforce_escalation(), calibrate_defaults() | < 0.10 ms | Constant O(1) (ΔBytes == 0) |
plexus.Router |
Plexus | Route complex or non-linear embeddings across 1,000+ dynamic tool IDs | route(top_k=3), reinforce() | < 0.35 ms | Constant O(1) (ΔBytes == 0) |
apical-proxy & apical-mcp |
Plexus | Prune tool schemas via local HTTP proxy or stdio MCP catalog server | plexus_route, plexus_reinforce, plexus_stats | < 0.35 ms | Constant O(1) (ΔBytes == 0) |
DeveloperPreferenceAdapter |
Plexus | Classify prompts and reinforce custom coding directives in a 64-slot container | classify(), learn_correction(), register_directive() | < 0.20 ms | Constant O(1) (ΔBytes == 0) |
| II. Continual Classification & Adaptation | |||||
arbor.Classifier |
Arbor | Classify L2-normalized embeddings online downstream of frozen encoders | predict(), learn(), erase_class() | < 0.10 ms | Constant O(1) (ΔBytes == 0) |
plexus.Network |
Plexus | Adapt non-linearly separable embeddings or LLM hidden-state activations online | predict(), learn(), route(), unlearn() | < 0.22 ms | Constant O(1) (ΔBytes == 0) |
III. Apical Edge (apical_edge.h · ANSI C99 Q15)
|
|||||
arbor_edge_t (Single-Layer Profile) |
Edge (v1) | Run single-layer Q15 classification and unsupervised anomaly calibration in SRAM | arbor_edge_init(), arbor_edge_predict(), arbor_edge_learn(), arbor_edge_calibrate_unsupervised() | 15.7 μs x86 · 119.6 μs M4F | 1.19–49.09 KB SRAM (0 malloc) |
plexus_edge_t (Multi-Layer Profile) |
Edge (v2) | Run multi-layer Q15 sensor adaptation and occluded pattern recall in SRAM | plexus_edge_init(), plexus_edge_predict(), plexus_edge_learn(), plexus_edge_associative_recall() | 30.7 μs x86 · 243.2 μs M4F | 69.52–428.50 KB SRAM (0 malloc) |
| IV. Security, Governance & Compliance | |||||
OrthogonalPrivacyProjector |
Platform | Blind vector coordinates client-side with a local key before network egress | project() | < 0.50 ms | Client RAM (key stays local) |
arbor.Bridge |
Arbor | Realign existing container coordinates to a new encoder using anchor pairs | bridge(source_anchors, target_anchors) | < 20.0 ms | Constant O(1) (ΔBytes == 0) |
arbor.Unlearn |
Arbor | Zero a target class coordinate deterministically for GDPR Article 17 erasure | erase_class(target_class) | < 1.00 ms | Constant O(1) (ΔBytes == 0) |
API Key Authentication & Capability Scopes
Apical API keys (apk_live_...) enforce capability scoping so read-only workers cannot mutate container state or delete containers:
| Capability Scope | Target Role | Permitted Endpoints | Behavior & Security Boundary |
|---|---|---|---|
infer (Inference & Tool Routing) |
Autonomous Agents, IDE Extensions, Read-Only Frontends | POST /api/v1/predict POST /api/v1/route POST /api/v2/predict POST /api/v2/route POST /api/v2/recall |
Read-only classification, routing, and associative recall. Rejected from mutating weights or creating containers. |
learn (Online Plasticity) |
Production Workers, RL Feedback Loops, Human Review Pipelines | POST /api/v1/learn POST /api/v1/reinforce POST /api/v1/unlearn POST /api/v1/bridge POST /api/v2/learn POST /api/v2/unlearn |
Allows single-pass online directional updates, cross-backbone migration, and class erasure with persisted_bytes_delta == 0. |
admin (Container Lifecycle) |
CI/CD Pipelines, DevOps Automation, Provisioning Workers | POST /api/v1/models POST /api/v2/models |
Pre-allocates fixed-byte containers and authorizes container lifecycle management. |
Requests sent with an insufficient scope (for example, calling learn() with an infer-only key) are rejected at the API Gateway with HTTP 403 Forbidden before reaching the enclave.
Installation, Authentication & Client Setup
Install the official thin-client Python SDK (numpy, httpx, cryptography) and export your API key from the Developer Console:
# Install official thin-client SDK
pip install --upgrade apical
# Export API key from the Developer Console
export APICAL_API_KEY="apk_live_..."
# Verify installation and CLI version
python3 -m apical.mcp.server --version
# -> Apical Plexus MCP Daemon v0.5.6
ApicalClient Constructor Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key |
str | Required | Tenant bearer token (apk_live_...) scoped to infer, learn, and/or admin. |
privacy_secret |
Optional[str] | None | Client-side secret passphrase enabling automatic OrthogonalPrivacyProjector blinding on every vector. |
base_url |
str | "https://apical-labs.com" | Gateway base URL. Override when targeting a private VPC or dedicated hardware TEE endpoint. |
timeout |
float | 10.0 | HTTP request timeout in seconds. |
max_retries |
int | 3 | Maximum automatic retry attempts on transient network or gateway errors. |
Three Client Initialization Modes
Initialize ApicalClient for Cloud API Gateway access, direct local Enclave IPC, or dedicated VPC / AWS Nitro TEE deployments with PCR0 attestation pinning:
import os
import apical
# ==============================================================================
# MODE 1: Cloud API Gateway (Standard SaaS)
# Connects over HTTPS TLS 1.3 to https://apical-labs.com.
# ==============================================================================
client_cloud = apical.ApicalClient(
api_key=os.environ["APICAL_API_KEY"],
base_url="https://apical-labs.com",
timeout=10.0,
max_retries=3,
)
# ==============================================================================
# MODE 2: Local Enclave IPC (Self-Hosted / Workstation Daemon)
# Connects directly over UNIX domain socket or loopback TCP (port 8765).
# ==============================================================================
client_local = apical.ApicalClient.local(
tenant_id="default",
socket_path=os.environ.get("APICAL_ENCLAVE_SOCKET", "/var/run/apical/enclave.sock"),
tcp_port=8765,
)
# ==============================================================================
# MODE 3: Dedicated VPC / AWS Nitro TEE (With PCR0 Measurement Pinning)
# Verify every receipt against the audited enclave PCR0 measurement.
# ==============================================================================
client_tee = apical.ApicalClient(
api_key=os.environ["APICAL_API_KEY"],
base_url="https://vpc-enclave.example.internal",
)
# Example after any learn() or predict() call:
# apical.verify_zero_retention_receipt(
# receipt,
# expected_pcr0="000102030405060708090a0b0c0d0e0f...",
# )
Apical Arbor SDK Reference
Use client.arbor when your upstream features come from a frozen embedding backbone (such as all-MiniLM-L6-v2, BAAI/bge-small-en-v1.5, CLIP, or DINOv2) where classes or routes are linearly separable. Each primitive operates in constant O(1) memory and returns signed zero-retention receipts.
Method & Return Signature Reference
| Method Signature | Return Type & Key Fields | Usage |
|---|---|---|
| client.arbor.create_model(model_id, in_features, num_classes, privacy_secret=None) | Classifier | Pre-allocates a fixed-byte classification container and returns a bound Classifier handle. |
| clf.predict(vector, verify_receipt=True) | PredictionResult (prediction / predicted_class, confidence, receipt, ed25519_signature) | Classifies an L2-normalized embedding on CPU and verifies the returned receipt. |
| clf.learn(vector, target_class, verify_receipt=True) | LearnResult (status, target_class, winner_class, confidence, update_count, persisted_bytes_delta, receipt) | Performs a single-pass directional update for target_class in constant memory. |
| clf.erase_class(target_class, verify_receipt=True) | UnlearnResult (status, erased_class_id, persisted_bytes_delta, target_class_weight_norm, receipt) | Zeroes the target class coordinate deterministically for GDPR Article 17 erasure. |
| client.arbor.memory_router(router_id, embedding_dim, num_tools, privacy_secret=None) | MemoryRouter | Returns a MemoryRouter handle. Call router.create(embedding_dim, num_rules) to initialize the container. |
| router.route(embedding, top_k=3, verify_receipt=True) | RouteResult (routes, candidates, top_rule_id, receipt) | Returns top-K RouteItem(rule_id, affinity) candidates (accessible via .tool_id). |
| router.reinforce(embedding, selected_tool_id=..., verify_receipt=True) | ReinforceResult (status, target_rule, confidence, update_count, persisted_bytes_delta, receipt) | Reinforces the winning tool or rule pathway online (accepts target_rule or selected_tool_id). |
| client.arbor.bridge(model_id, source_anchors, target_anchors, verify_receipt=True) | BridgeResult (status, model_id, alignment_score, persisted_bytes_delta, update_count, receipt, latency_ms) | Realigns container coordinates between encoder dimensions using public anchor pairs. |
| client.arbor.model_router(router_id, registry=None, embedding_model="all-MiniLM-L6-v2", default_tier=0) | ModelRouter | Instantiates a semantic LLM tier router over MemoryRouter. |
import apical
import numpy as np
# 1. Initialize client
client = apical.ApicalClient(api_key="apk_live_...")
# 2. Pre-allocate fixed-byte model container
# in_features=384 (e.g. all-MiniLM-L6-v2), num_classes=20
clf = client.arbor.create_model(
model_id="security-incident-classifier",
in_features=384,
num_classes=20,
)
# Generate sample L2-normalized continuous embedding
sample_vector = np.random.randn(384).astype(np.float32)
sample_vector /= np.linalg.norm(sample_vector)
# 3. Run inference (< 0.10 ms on CPU)
pred = clf.predict(sample_vector)
print(f"Predicted Class: {pred.predicted_class} | Confidence: {pred.confidence:.4f}")
# 4. Continual online update (< 0.10 ms)
receipt = clf.learn(sample_vector, target_class=7)
assert receipt.persisted_bytes_delta == 0
print(f"Updated model to Class 7. Ed25519 Sig: {receipt.ed25519_signature[:16]}...")
# 5. Semantic tool shortlisting with MemoryRouter
router = client.arbor.memory_router("agent-tools", embedding_dim=384, num_tools=50)
router.create(embedding_dim=384, num_rules=50)
route_res = router.route(sample_vector, top_k=3)
print(f"Selected Candidate Tools: {[item.tool_id for item in route_res.candidates]}")
# 6. Reinforce successful execution
reinf_receipt = router.reinforce(sample_vector, selected_tool_id=route_res.candidates[0].tool_id)
assert reinf_receipt.persisted_bytes_delta == 0
# 7. GDPR Article 17 class erasure (< 1 ms)
unlearn_receipt = clf.erase_class(target_class=7)
assert unlearn_receipt.persisted_bytes_delta == 0
assert unlearn_receipt.target_class_weight_norm == 0.0
print("Class 7 erased with verifiable Ed25519 receipt.")
Semantic LLM Model Routing & Escalation (ModelRouter)
Use client.arbor.model_router() to dispatch incoming prompts to configured LLM capability tiers in sub-millisecond CPU time:
- Define a registry: Supply a dictionary mapping integer tier indices to
ModelSpecentries (or omitregistryto use the built-in 5-tier defaults). - Seed baseline exemplars: Call
router.calibrate_defaults(exemplars=...)once to initialize tier anchors under zero retention. - Route prompts: Call
router.route_prompt(prompt)to receive aModelRouteDecisioncontainingmodel_name,tier,provider, andreceipt. - Reinforce escalations: Call
router.reinforce_escalation(prompt, fallback_tier=...)whenever downstream validation requires a higher capability tier.
| Data Structure | Module | Fields & Types | Operational Role |
|---|---|---|---|
ModelSpec |
apical.model_router | name: str, provider: str, cost_tier: str, cost_per_m: float, description: str | Defines endpoint attributes for each integer tier. Defaults: Tier 0 (gemini-3.8-flash), 1 (claude-sonnet-5-5), 2 (gemini-4-argon), 3 (gemini-4-carbon), 4 (gemini-4-hydrogen), 5 (gemini-4-neon). |
ModelRouteDecision |
apical.model_router | model_name: str, tier: int, provider: str, confidence: float, latency_ms: float, vector: List[float], receipt: Dict[str, Any] | Routing output containing the selected model identifier, tier, confidence score, CPU routing latency, and enclave receipt. |
EscalationReceipt |
apical.model_router | status: str, target_tier: int, persisted_bytes_delta: int, ed25519_signature: str, timestamp_ns: int | Signed zero-retention attestation returned by reinforce_escalation() confirming persisted_bytes_delta == 0. |
CalibrationResult |
apical.calibrate | router_id: str, exemplars_count: int, tiers_calibrated: List[int], duration_ms: float, persisted_bytes_delta: int, ed25519_signatures_verified: int | Summary of single-pass baseline anchor seeding across configured tiers. |
import apical
# 1. Initialize client
client = apical.ApicalClient(api_key="apk_live_...")
# 2. Instantiate ModelRouter (uses built-in 5-tier defaults when registry=None)
router = client.arbor.model_router(
router_id="enterprise-llm-router",
embedding_model="all-MiniLM-L6-v2",
default_tier=4,
)
# 3. Seed baseline anchors across configured tiers
cal_res = router.calibrate_defaults()
assert cal_res.persisted_bytes_delta == 0
print(f"Calibrated {cal_res.exemplars_count} exemplars. Signatures verified: {cal_res.ed25519_signatures_verified}")
# 4. Route prompt dynamically (< 0.10 ms CPU)
prompt = "Refactor the authentication middleware and run the unit test suite."
decision = router.route_prompt(prompt)
print(f"Routed Model: {decision.model_name} (Tier {decision.tier}) | Latency: {decision.latency_ms:.2f} ms")
# 5. Reinforce escalation when downstream checks require a higher tier
escalation_prompt = "Formally prove that the language L = {a^n b^n c^n | n >= 0} is not context-free."
receipt = router.reinforce_escalation(escalation_prompt, fallback_tier=3)
assert receipt.persisted_bytes_delta == 0
print(f"Reinforced Tier 3. Ed25519 Sig: {receipt.ed25519_signature[:16]}...")
Configuring Custom Model Registries & Local Endpoints
Pass a custom dictionary of ModelSpec objects to bind Ollama, vLLM, private fine-tunes, or any custom tier ladder, and supply domain-specific exemplars to calibrate_defaults(exemplars=...):
import apical
from apical.model_router import ModelSpec
client = apical.ApicalClient(api_key="apk_live_...")
# 1. Define a custom N-tier model registry
CUSTOM_REGISTRY = {
0: ModelSpec(
name="llama-3.2-3b-instruct",
provider="ollama_local",
cost_tier="free",
cost_per_m=0.00,
description="Local model for classification, summarization, and formatting",
),
1: ModelSpec(
name="mistral-large-2411",
provider="mistral",
cost_tier="cloud",
cost_per_m=2.00,
description="General cloud reasoning and multi-turn planning",
),
2: ModelSpec(
name="deepseek-r1",
provider="vllm_cluster",
cost_tier="reasoning",
cost_per_m=0.55,
description="Complex mathematical proofs, algorithmic code synthesis, and formal logic",
),
}
# 2. Instantiate ModelRouter with the custom registry
router = client.arbor.model_router(
router_id="my-custom-enterprise-router",
registry=CUSTOM_REGISTRY,
embedding_model="all-MiniLM-L6-v2",
default_tier=0,
)
# 3. Seed with domain-specific exemplars (persisted_bytes_delta == 0)
custom_exemplars = {
0: [
"Extract the customer phone number from this email.",
"Fix the spelling and grammar in this sentence.",
"Summarize this release note into two sentences.",
],
1: [
"Write an SQL migration adding tenant_id foreign keys with cascade delete.",
"Draft a technical RFC for migrating an OLTP datastore to sharded storage.",
],
2: [
"Formally prove that Byzantine Fault Tolerance requires 3f + 1 nodes.",
"Design a lock-free ring buffer in C++ using atomic load/store memory orders.",
],
}
cal_res = router.calibrate_defaults(exemplars=custom_exemplars)
assert cal_res.persisted_bytes_delta == 0
print(f"Calibrated {cal_res.exemplars_count} custom exemplars across {cal_res.tiers_calibrated}.")
# 4. Route prompt to your custom models
decision = router.route_prompt("Design a lock-free queue with memory fences in Rust")
print(f"Routed Model: {decision.model_name} (Tier {decision.tier})")
Apical Plexus SDK Reference
Use client.plexus(...) when inputs are high-dimensional or non-linearly separable, such as raw causal LLM hidden-state activations, multi-step agent trajectories, or large catalogs exceeding 500 tools. Plexus uses a multi-layer sparse continual container in constant O(1) memory.
Capacity Tier Configuration (tier Parameter)
tier Argument |
Container Footprint | Step Latency | Recommended Workload Scale |
|---|---|---|---|
"standard" (0) |
~ 16.5 MB (9.12 MB on 896-D LLM) | ~ 0.15 ms | Single IDE instances, local MCP daemons, and small agent swarms |
"pro" (1) |
~ 33.1 MB | ~ 0.18 ms | Multi-tenant SaaS continual learning, telemetry streams, 100+ tasks |
"ultra" (2) |
~ 66.3 MB | ~ 0.22 ms | Large-scale agent fleets, sovereign VPC clusters, 1,500+ dynamic tools |
Multi-Seat Team Configuration (infer vs learn Keys on a Shared model_id)
Multiple developer workstations and CI runners can share one centralized Plexus container without syncing local prompt files:
- Provision the shared container: Create one named container (for example,
model_id="team-plexus-router") using anadmin-scoped API key. - Issue role-scoped keys: Distribute
infer+learnkeys to designated CI feedback pipelines or maintainers, andinfer-only keys to read-only agent workstations. - Point all seats to the same
model_id: Acceptedreinforce()orlearn()updates apply immediately in enclave RAM, so subsequentroute()orpredict()queries from any connected seat reflect the updated weights.
Method & Return Type Reference
| Method Signature | Return Type & Key Fields | Usage |
|---|---|---|
| plexus_net.create(in_features=None, out_features=None, verify_receipt=True) | Dict[str, Any] | Pre-allocates the fixed-byte Plexus container via POST /api/v2/models. |
| plexus_net.predict(vector, tier=None, verify_receipt=True) | PlexusPredictionResult (prediction / predicted_class, confidence, probabilities, receipt, latency_ms) | Executes multi-layer inference via POST /api/v2/predict. |
| plexus_net.route(vector, top_k=3, tier=None, verify_receipt=True) | PlexusRouteResult (routed_class, top_k_rules, scores, receipt, latency_ms) | Returns top-K matching rule IDs and affinity scores via POST /api/v2/route. |
| plexus_net.learn(vector, target_class, tier=None, verify_receipt=True) | PlexusLearnResult (status, target_class, winner_class, update_count, persisted_bytes_delta, receipt, latency_ms) | Executes a continual update via POST /api/v2/learn with persisted_bytes_delta == 0. |
| plexus_net.reinforce(vector, target_rule, tier=None, verify_receipt=True) | PlexusLearnResult | Reinforces a target routing rule (alias for learn() matching Router semantics). |
| plexus_net.unlearn(class_id, verify_receipt=True) | PlexusUnlearnResult (status, erased_class_id, persisted_bytes_delta, receipt, latency_ms) | Erases a target class coordinate via POST /api/v2/unlearn. |
import apical
import numpy as np
client = apical.ApicalClient(api_key="apk_live_...")
# 1. Instantiate PlexusNetwork (tier: "standard", "pro", or "ultra")
plexus_net = client.plexus(
model_id="enterprise-agent-router",
in_features=1536,
out_features=150,
tier="standard",
)
# 2. Pre-allocate container in constant memory
plexus_net.create()
# 3. Generate normalized query vector and run inference
query_vec = np.random.randn(1536).astype(np.float32)
query_vec /= np.linalg.norm(query_vec)
pred_result = plexus_net.predict(query_vec)
print(f"Predicted Class: {pred_result.predicted_class} | Confidence: {pred_result.confidence:.4f}")
# 4. Semantic tool routing across 150 tools
route_result = plexus_net.route(query_vec, top_k=3)
print(f"Top-1 Cluster: {route_result.routed_class}")
print(f"Top-3 Rules: {route_result.top_k_rules}")
print(f"Scores: {route_result.scores}")
# 5. Zero-retention online plasticity update and reinforcement
learn_result = plexus_net.learn(query_vec, target_class=14)
assert learn_result.persisted_bytes_delta == 0
reinf_result = plexus_net.reinforce(query_vec, target_rule=14)
assert reinf_result.persisted_bytes_delta == 0
# 6. GDPR Article 17 erasure and offline receipt verification
unlearn_result = plexus_net.unlearn(class_id=14)
assert unlearn_result.persisted_bytes_delta == 0
apical.verify_zero_retention_receipt(learn_result.receipt)
print("Plexus zero-retention receipt cryptographically validated (Ed25519).")
In-Line Proxy & MCP Server Configuration
Apical integrates with agent frameworks and IDE environments through three transport modes: (1) apical-proxy, a local HTTP reverse proxy for OpenAI-, Anthropic-, and Gemini-compatible clients, (2) apical.mcp.server, a stdio Model Context Protocol server for pull-based tool discovery, and (3) PreInvocation lifecycle hooks for Google Antigravity.
| Environment | Integration Mechanism | Interception Model | Execution Trigger |
|---|---|---|---|
| Google Antigravity (AGY) | .agents/hooks.json (PreInvocation) |
IDE engine shell hook before model call | 100% Deterministic |
| Cursor / Continue / Aider | apical-proxy (Reverse Proxy) |
Local HTTP proxy at localhost:8080 |
100% Deterministic |
| Claude Desktop | apical-mcp (Stdio MCP Server) |
Pull-based dynamic catalog meta-tool | Model Discretion |
| LangChain / CrewAI / AutoGen | SDK (MemoryRouter) or Proxy |
Python router or HTTP proxy base URL | 100% Deterministic |
Mode 1: The In-Line Proxy (apical-proxy)
Launch the reverse proxy locally to prune tool schemas and optionally route requests across LLM tiers before forwarding to OpenAI, Anthropic, or Google Gemini upstreams:
pip install --upgrade apical
python3 -m apical.proxy \
--port 8080 \
--top-k 5 \
--enable-model-routing \
--model-router-id enterprise-model-router \
--embedding-model all-MiniLM-L6-v2 \
--openai-upstream https://api.openai.com/v1 \
--anthropic-upstream https://api.anthropic.com/v1 \
--gemini-upstream https://generativelanguage.googleapis.com
# -> Apical Plexus Reverse Proxy running at http://127.0.0.1:8080
# -> OpenAI Base URL: http://127.0.0.1:8080/v1
# -> Anthropic Base URL: http://127.0.0.1:8080
# -> Google Gemini URL: http://127.0.0.1:8080/v1beta
Proxy Request Pipeline
- Tool Signature Extraction: Extracts tool definitions from OpenAI (
tools), Anthropic (tools), or Gemini (function_declarations) payloads. - SHA-256 Tool Caching: Hashes tool schemas in RAM to skip re-embedding unchanged definitions on subsequent turns.
- Dense Ranking: Encodes the incoming query using the configured local embedding model (default
all-MiniLM-L6-v2, or override via--embedding-model) and ranks candidate tools in < 3 ms total round-trip. - Zero-Retention Receipts: Scrubs transient buffers immediately upon ranking (
persisted_bytes_delta == 0) and signs anEd25519receipt.
Proxy CLI Flags
| CLI Flag / Option | Default | Description |
|---|---|---|
--port / --host |
8080 / 127.0.0.1 | Local bind host and TCP port for the proxy HTTP server. |
--top-k / --min-tools |
5 / 6 | Number of shortlisted tools retained per turn and minimum tool count required to trigger pruning. |
--enable-model-routing |
False | Enables automatic model tier routing across all proxied requests. |
--model-router-id |
enterprise-model-router | Identifier of the fixed-byte model router container hosted in the enclave. |
--model-tiers-config |
None | Optional path to a JSON file mapping integer tiers (defaults to Tiers 0–5: gemini-3.8-flash, claude-sonnet-5-5, gemini-4-argon, gemini-4-carbon, gemini-4-hydrogen, gemini-4-neon) to custom model names. |
--enable-preferences |
False | Injects matching DeveloperPreferenceAdapter directives into upstream system prompts (or per request via X-Apical-Preferences: true). |
--preference-threshold |
0.35 | Minimum affinity threshold required before injecting a learned preference directive. |
--enable-trajectory-context / --disable-trajectory-context |
True | Prepends a canonical structural prefix ([trajectory turn=... tools=... err=... retries=... files=...]) during multi-step model routing without persisting raw prompts. |
--enable-auto-escalate |
False | Enables closed-loop retry-and-reinforce escalation on upstream 429/5xx errors, malformed tool calls, or empty completions (also triggerable via X-Apical-Auto-Escalate: 1). |
--auto-escalate-target-tier |
3 | Target model tier index used when autonomous escalation triggers. |
On-Demand Routing Triggers: Even when --enable-model-routing is omitted, the proxy routes a request whenever the body sets model="arbor-auto" or model="auto", the URL targets /models/arbor-auto or /models/auto, or the request includes X-Apical-Model-Routing: 1 or X-Apical-Escalate-Tier: <int>.
| Response Header | Example Value | Semantics |
|---|---|---|
X-Apical-Routed-Model |
gemini-4-hydrogen | Concrete upstream model selected and invoked for this turn. |
X-Apical-Routed-Tier |
4 | Integer capability tier selected for the request. |
X-Apical-Routing-Latency-Ms |
0.08 | CPU time spent classifying the routing query in the enclave. |
X-Apical-Active-Preferences |
CONCRETE_EXECUTION_NO_MOCKS | Comma-separated learned developer preference names injected into this turn. |
X-Apical-Trajectory-State |
turn=4,tools=1,err=1,retries=1 | Structural multi-turn trajectory telemetry extracted deterministically from message history. |
X-Apical-Auto-Escalated |
true | Present when closed-loop escalation intercepted an upstream failure or malformed tool call and retried against the elevated tier. |
X-Apical-Escalated-From |
gemini-4-argon | Initial routed model identifier before autonomous escalation promoted the request. |
Supplying Custom Models & Tiers to apical-proxy
Supply a JSON file mapping integer tiers to your target model identifiers (for example, Ollama, vLLM, or custom endpoints):
{
"0": "llama-3.2-3b-instruct",
"1": "mistral-large-2411",
"2": "deepseek-r1",
"3": "custom-finetuned-coder"
}
# 1. (Optional) Seed container with custom domain exemplars
python3 -m apical.calibrate \
--router-id enterprise-model-router \
--exemplars-file /etc/apical/custom_exemplars.json
# 2. Launch proxy with custom model mapping
python3 -m apical.proxy \
--port 8080 \
--enable-model-routing \
--model-router-id enterprise-model-router \
--model-tiers-config /etc/apical/custom_model_tiers.json
Agent Framework & IDE Base URL Setup
Point existing OpenAI-compatible SDKs or IDE settings at the local proxy URL:
# 1. LangChain / LangGraph with Dynamic Model Routing
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="arbor-auto",
base_url="http://127.0.0.1:8080/v1",
api_key="sk-..."
)
agent_executor = create_react_agent(llm, tools=all_hundred_tools)
# 2. CrewAI
import os
os.environ["OPENAI_API_BASE"] = "http://127.0.0.1:8080/v1"
os.environ["ANTHROPIC_BASE_URL"] = "http://127.0.0.1:8080"
# 3. Microsoft AutoGen / AutoGen Studio
config_list = [{
"model": "auto",
"base_url": "http://127.0.0.1:8080/v1",
"api_key": "sk-..."
}]
assistant = autogen.AssistantAgent("coder", llm_config={"config_list": config_list})
# 4. LlamaIndex
from llama_index.llms.openai import OpenAI
llm = OpenAI(model="auto", api_base="http://127.0.0.1:8080/v1", api_key="sk-...")
# 5. Cursor IDE & Continue.dev (.cursor/settings.json or ~/.continue/config.json)
# "apiBase": "http://127.0.0.1:8080/v1", "model": "arbor-auto"
Choosing Between Arbor and Plexus for Routing
Use arbor.ModelRouter or apical-proxy when routing dense sentence embeddings (such as all-MiniLM-L6-v2 or bge-small) across model tiers. Use plexus.Router when routing raw LLM hidden-state activations or shared multi-seat catalogs exceeding 500 tools; see Blueprint 6 for the full programmatic routing example.
Mode 2: MCP Tool Catalog Server (apical-mcp)
Register apical.mcp.server in Claude Desktop or Cursor when you want the model to pull relevant tool definitions on demand over stdio JSON-RPC:
{
"mcpServers": {
"plexus": {
"command": "python3",
"args": ["-m", "apical.mcp.server"],
"env": {
"APICAL_API_KEY": "apk_live_...",
"APICAL_ENCLAVE_SOCKET": "/var/run/apical/enclave.sock"
}
}
}
}
from apical.mcp.server import PlexusMcpServer
server = PlexusMcpServer()
# 1. Automatic discovery of active environment tools
print(f"Registered tools: {len(server.registry)}")
# 2. Register or update project tools
server.plexus_register_tools([
{"name": "git_commit", "description": "Record changes to the git repository"},
{"name": "docker_build", "description": "Build container image from Dockerfile"},
{"name": "deploy_service", "description": "Trigger rolling service deployment"},
])
# 3. Route across candidate tools
route = server.plexus_route(query="Commit my recent code changes", top_k=2)
# 4. Reinforce accepted tool turn
reinf = server.plexus_reinforce(query="Commit my recent code changes", tool_id=0)
# 5. Verify zero-retention receipt offline
audit = server.plexus_verify_receipt(receipt=route["receipt"])
# 6. Inspect telemetry and p50/p95 latencies
stats = server.plexus_stats()
# 7. Purge local telemetry log (preserving optional .bak copy)
wipe = server.plexus_wipe_telemetry(backup=True)
Mode 3: Google Antigravity (AGY) PreInvocation Hook
Register a PreInvocation hook in .agents/hooks.json (or globally in ~/.gemini/config/hooks.json) to route tools and inject top candidates deterministically before each model invocation:
{
"apical-plexus-router": {
"enabled": true,
"PreInvocation": [
{
"type": "command",
"command": "/path/to/venv/bin/python3 /path/to/apical-sdk/hooks/plexus_pre_invocation.py",
"timeout": 10
}
]
}
}
Continual Developer Preference Adapter
DeveloperPreferenceAdapter maps incoming prompts and review corrections onto a 64-slot constant-memory container (in_features=384, out_features=64) so agents inject only the directives matching the current task. Slots 0..9 ship with built-in coding rules, and slots 10..63 can hold custom team directives registered at runtime.
| Method Signature | Return Value | Behavior |
|---|---|---|
| register_directive(name, directive) | Dict[str, Any] (with dimension_id) |
Registers or updates a custom directive in the persistent JSON catalog and assigns a slot ID (0..63). |
| classify(text, top_k=3) | List[PreferenceMatch] | Scores registered directives using semantic and synaptic affinity and returns the top-K matches (filter against a threshold such as 0.35 in your caller). |
| learn_correction(correction_text, preferred_dimension_id) | Dict[str, Any] | Updates synaptic weights online for the target slot ID or dimension name under zero retention (learn(text, dimension_id=...) is an alias). |
from apical.preference import DeveloperPreferenceAdapter
from apical.enclave_client import EnclaveDirectClient
enclave = EnclaveDirectClient()
adapter = DeveloperPreferenceAdapter(enclave_client=enclave)
# 1. Register a custom team coding directive (auto-allocates next slot in 10..63)
reg = adapter.register_directive(
name="PARAMETERIZED_SQL_QUERIES",
directive="All SQL queries must use bound parameters; never interpolate user strings.",
)
custom_slot_id = reg["dimension_id"]
# 2. Classify an incoming prompt against registered directives
prompt = "Refactor the billing repository query builder and add structured error logs"
matches = [m for m in adapter.classify(prompt, top_k=3) if m.affinity >= 0.35]
for match in matches:
print(f"[{match.dimension_id}] {match.name} (affinity={match.affinity:.3f}): {match.directive}")
# 3. Reinforce a preference slot online after a review correction
update_res = adapter.learn(
text="Use bound SQL parameters in BillingRepository instead of f-strings",
dimension_id=custom_slot_id,
)
assert update_res["persisted_bytes_delta"] == 0
print(f"Reinforced slot {update_res['dimension_id']} ({update_res['dimension_name']}).")
Apical Edge C99 Firmware Integration (apical_edge.h)
apical_edge.h and apical_edge.c provide two dependency-free ANSI C99 (-std=c99 -O3) Q15 fixed-point microkernel profiles that execute inside caller-supplied static SRAM buffers with zero malloc, zero <math.h>, and zero Flash writes during inference or learning (persisted_bytes_delta == 0).
1. Compilation & Build Integration
Include apical_edge.h in your firmware translation units and compile apical_edge.c alongside your target application using only standard C99 headers (<stdint.h>, <stddef.h>, <string.h>):
# Host x86_64 build (unit verification / simulator)
gcc -std=c99 -O3 -Wall -Wextra -Werror -Iinclude src/apical_edge.c firmware/main.c -o edge_sim
# Bare-metal ARM Cortex-M4F firmware build (zero libm / zero heap)
arm-none-eabi-gcc -std=c99 -O3 -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 \
-Iinclude -c src/apical_edge.c -o build/apical_edge.o
2. Profile Sizing & Timing Specifications
| Microkernel Profile | Arena Sizing Macro | Typical Static SRAM | x86_64 p50 (Predict / Learn) | 120 MHz Cortex-M4F (Predict / Learn) |
|---|---|---|---|---|
arbor_edge_t (Single-Layer + Anomaly) |
ARBOR_EDGE_ARENA_BYTES(D, C) | 1.19 KB – 49.09 KB | 15.7 μs / 18.9 μs | 119.6 μs / 123.3 μs |
plexus_edge_t (Multi-Layer + Recall) |
PLEXUS_EDGE_ARENA_BYTES(D, H, C, K) | 69.52 KB – 428.50 KB | 30.7 μs / 78.8 μs | 243.2 μs / 311.8 μs |
3. Q15 Input Scaling & Return Status Codes
Scale normalized float sensor features x in [-1.0, 1.0] to int16_t Q15 integers via (int16_t)(x * 32767.0f) using APICAL_EDGE_Q15_ONE (32767). Threshold parameters such as vigilance_q15 use the same scale (for example, 0.65 * 32767 = 21299). All status-returning functions yield one of the following codes from apical_edge.h:
| Constant | Value | Meaning & Required Caller Action |
|---|---|---|
| APICAL_EDGE_OK | 0 | Operation succeeded; outputs and CRC/update counters are valid. |
| APICAL_EDGE_ERR_ARG | -1 | Null pointer or invalid dimension/configuration argument passed to API. |
| APICAL_EDGE_ERR_ARENA | -2 | Caller-provided arena_bytes or snapshot buffer is smaller than *_ARENA_BYTES(...). |
| APICAL_EDGE_ERR_BOUNDS | -3 | target_class or class_id is greater than or equal to num_classes. |
| APICAL_EDGE_ERR_FROZEN | -4 | Mutation attempted while read-only mode is active (set_readonly(ctx, 1)). |
| APICAL_EDGE_ERR_CORRUPT | -5 | Arena header magic or CRC-32 integrity verification failed on restore. |
#include <stdint.h>
#include "apical_edge.h"
#define FEATURE_DIM 360
#define NUM_CLASSES 16
#define RAW_DIM 768
#define HIDDEN_DIM 128
#define ASSEMBLY_K 16
/* Static SRAM arenas: zero malloc, constant O(1) memory */
static uint8_t s_arbor_arena[ARBOR_EDGE_ARENA_BYTES(FEATURE_DIM, NUM_CLASSES)];
static uint8_t s_plexus_arena[PLEXUS_EDGE_ARENA_BYTES(RAW_DIM, HIDDEN_DIM, 6, ASSEMBLY_K)];
static uint8_t s_snapshot_buf[ARBOR_EDGE_ARENA_BYTES(FEATURE_DIM, NUM_CLASSES)];
static arbor_edge_t s_arbor_ctx;
static plexus_edge_t s_plexus_ctx;
static inline int16_t float_to_q15(float v) {
if (v >= 1.0f) return APICAL_EDGE_Q15_ONE;
if (v <= -1.0f) return (int16_t)-APICAL_EDGE_Q15_ONE;
return (int16_t)(v * (float)APICAL_EDGE_Q15_ONE);
}
int app_sensor_init(void) {
int rc = arbor_edge_init(&s_arbor_ctx, s_arbor_arena, sizeof(s_arbor_arena),
FEATURE_DIM, NUM_CLASSES, 1000u);
if (rc != APICAL_EDGE_OK) return rc;
return plexus_edge_init(&s_plexus_ctx, s_plexus_arena, sizeof(s_plexus_arena),
RAW_DIM, HIDDEN_DIM, 6, ASSEMBLY_K, 1000u);
}
int on_healthy_burn_in_sample(const int16_t *x_q15) {
uint16_t assigned_slot = 0;
/* 0.65 vigilance in Q15: (int16_t)(0.65f * 32767.0f) == 21299 */
return arbor_edge_calibrate_unsupervised(&s_arbor_ctx, x_q15, 21299, &assigned_slot);
}
void on_sensor_interrupt(const int16_t *x_q15, const uint8_t *mask_occluded) {
uint16_t predicted_class = 0;
int16_t confidence_q15 = 0;
int16_t anomaly_q15 = 0;
int16_t reconstructed_q15[RAW_DIM];
/* 1. Inference and anomaly scoring */
arbor_edge_predict(&s_arbor_ctx, x_q15, &predicted_class, &confidence_q15, &anomaly_q15);
plexus_edge_predict(&s_plexus_ctx, x_q15, &predicted_class, &confidence_q15, &anomaly_q15);
/* 2. Associative pattern completion when channels are occluded */
plexus_edge_associative_recall(&s_plexus_ctx, x_q15, mask_occluded,
reconstructed_q15, &predicted_class, &confidence_q15);
/* 3. Online update, class erasure, snapshot/CRC, and read-only lock */
if (gpio_technician_button_pressed()) {
if (arbor_edge_learn(&s_arbor_ctx, x_q15, 3) == APICAL_EDGE_OK) {
arbor_edge_snapshot_save(&s_arbor_ctx, s_snapshot_buf, sizeof(s_snapshot_buf));
}
plexus_edge_learn(&s_plexus_ctx, x_q15, 3);
}
if (gpio_decommission_class_requested()) {
arbor_edge_erase_class(&s_arbor_ctx, 3);
plexus_edge_erase_class(&s_plexus_ctx, 3);
arbor_edge_set_readonly(&s_arbor_ctx, 1);
}
if (gpio_restore_snapshot_requested()) {
if (arbor_edge_snapshot_restore(&s_arbor_ctx, s_snapshot_buf, sizeof(s_snapshot_buf)) == APICAL_EDGE_OK) {
volatile uint32_t crc = arbor_edge_crc32(&s_arbor_ctx);
(void)crc;
}
}
}
client.plexus.edge)
import apical
import numpy as np
client = apical.ApicalClient(api_key="apk_live_...")
# Bind to an edge sensor container via the Plexus namespace
edge = client.plexus.edge(
input_shape=(360,),
num_classes=16,
sram_budget_kb=94,
circuit_id="hydraulic-rig-360d",
)
sensor_window = np.random.randn(360).astype(np.float32)
sensor_window /= np.linalg.norm(sensor_window)
# 1. Edge inference
infer_res = edge.infer(sensor_window)
print(f"Class: {infer_res.prediction} | Confidence: {infer_res.confidence:.4f}")
# 2. Continual edge update (persisted_bytes_delta == 0)
learn_res = edge.learn(sensor_window, target_class=3)
assert learn_res.persisted_bytes_delta == 0
# 3. Associative recall on an occluded sensor patch
recall_res = edge.associative_recall(sensor_window)
print(f"Reconstructed dim={len(recall_res.reconstructed_vector)} | Gain={recall_res.recovery_gain_pct:.2f}%")
Local Enclave IPC & Socket Protocol
In self-hosted VPC or workstation deployments, the Apical Enclave worker communicates over newline-delimited JSON on a local UNIX domain socket (configured via APICAL_ENCLAVE_SOCKET, e.g. /var/run/apical/enclave.sock) or loopback TCP (127.0.0.1:8765) with no public network listener and no database connection.
5-Step Atomic Enclave Execution Sequence
persisted_bytes_delta == 0.
// 1. Client Request over Socket (Line-delimited JSON)
{
"operation": "learn",
"tenant_id": 4,
"model_id": "production-classifier-v1",
"vector": [0.0421, -0.1205, ..., 0.0891], // L2-normalized float32
"target_class": 12,
"tier": 1
}
// 2. Enclave Response over Socket ("predict" / "plexus_predict" also include "anomaly_score")
{
"ok": true,
"data": {
"status": "adapted",
"target_class": 12,
"update_count": 84,
"persisted_bytes_delta": 0,
"receipt": {
"receipt_id": "rcpt_982a1b7c4d3e2f10",
"tenant_id": 4,
"model_id": "production-classifier-v1",
"operation": "learn",
"input_buffer_zeroed": true,
"scrubbed_at_unix_ns": 1792848910442819,
"persisted_bytes_delta": 0,
"state_sha256_before": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"state_sha256_after": "a591a6d40bf420404a011733cfb7b190d62c65bf0bcda32b57b277d9ad9f146e",
"ed25519_signature": "7f8b9c...a1d4"
}
}
}
// 3. Unsupervised Healthy Burn-In Calibration ("calibrate_unsupervised" / "plexus_calibrate_unsupervised")
{
"operation": "calibrate_unsupervised",
"tenant_id": 4,
"model_id": "hydraulic-rig-360d",
"vector": [0.0421, -0.1205, ..., 0.0891],
"vigilance": 0.65,
"tier": 1
}
| JSON-RPC Operation | Key Request Fields | Key Response Fields |
|---|---|---|
| predict / plexus_predict | tenant_id, model_id, vector, tier | prediction, confidence, anomaly_score, persisted_bytes_delta: 0 |
| calibrate_unsupervised / plexus_calibrate_unsupervised | tenant_id, model_id, vector, vigilance (default 0.65), tier | status: "calibrated", assigned_slot, recruited_new_slot, confidence, anomaly_score, receipt |
| learn / plexus_learn / erase_class / plexus_erase_class | tenant_id, model_id, vector / class_id | persisted_bytes_delta: 0, state_sha256, receipt (Ed25519) |
| set_plasticity_mode / create_snapshot / rollback_snapshot | read_only: bool / snapshot_id: str | Frozen drift guard or signed snapshot rollback |
Input Vector Requirements & Error Handling
Prepare input vectors to satisfy all four enclave validation checks before calling predict(), learn(), or route():
- Exact Shape: Supply a 1D
float32array whose length matches the container's configuredin_features. - Finite Values: Ensure no
NaNorInfentries appear in the vector. - L2-Normalized Continuous Embeddings: Use dense embeddings from a continuous encoder (avoid raw one-hot vectors or zero-padded arrays).
- Stochastic Real Streams: Deduplicate repeated identical inputs and avoid synthetic linear interpolation sweeps that trigger the sweep circuit-breaker.
HTTP Status & SDK Exception Reference
SDK Exception (apical.exceptions) |
HTTP / Error Code | Cause & Remediation |
|---|---|---|
| AuthenticationError | HTTP 401 | API key is missing, malformed, or revoked. Verify APICAL_API_KEY in the Developer Console. |
| ProductNotEntitledError | HTTP 403 / ERR_PRODUCT_NOT_ENTITLED | API key lacks the required scope (infer vs learn/admin) or plan lacks Plexus access. |
| ModelNotFoundError | HTTP 404 | Container model_id has not been initialized yet. Call create_model() or create() first. |
| SparseProbeError | HTTP 422 / ERR_ORACLE_SPARSE_PROBE | Vector is zero-padded, one-hot, or degenerate. Pass an L2-normalized continuous encoder embedding. |
| SweepDetectedError | HTTP 422 / 429 / ERR_ORACLE_SWEEP_DETECTED | Repetitive collinear probe sweep tripped the circuit-breaker. Deduplicate and verify natural input variance. |
| RateLimitError | HTTP 429 | Token-bucket rate limit or monthly operation quota exceeded. Back off or upgrade quota tier. |
| VerificationError / FixedByteInvariantError | Client-side | Ed25519 signature mismatch, PCR0 mismatch, or persisted_bytes_delta != 0 in receipt. |
import apical
import numpy as np
from apical.exceptions import (
ApicalError,
AuthenticationError,
ModelNotFoundError,
ProductNotEntitledError,
RateLimitError,
SparseProbeError,
SweepDetectedError,
VerificationError,
)
client = apical.ApicalClient(api_key="apk_live_...")
clf = client.arbor.classifier("my-production-model")
# Prepare a finite, L2-normalized float32 vector
vec = np.asarray(get_encoder_embedding("customer query"), dtype=np.float32)
assert np.all(np.isfinite(vec))
vec /= np.linalg.norm(vec)
try:
pred = clf.predict(vec)
print(f"Prediction: class={pred.predicted_class}, confidence={pred.confidence:.2f}")
except (AuthenticationError, ProductNotEntitledError) as e:
print(f"Auth or scope error: {e}")
except ModelNotFoundError:
clf.create(in_features=vec.size, num_classes=20)
except SparseProbeError as e:
print(f"Degenerate or zero-padded vector rejected: {e}")
except SweepDetectedError as e:
print(f"Collinear sweep circuit-breaker triggered: {e}")
except RateLimitError as e:
print(f"Rate or quota limit exceeded: {e}")
except VerificationError as e:
print(f"Receipt verification failed: {e}")
except ApicalError as e:
print(f"Unhandled Apical SDK error: {e}")
Client-Side Keyed Input Blinding
OrthogonalPrivacyProjector applies a deterministic client-keyed isometric rotation to every input vector before it leaves your process. The rotation secret stays strictly in client memory, while preserving L2 norms and inner products so downstream routing and classification behavior remains unchanged.
Enable blinding globally by passing privacy_secret to ApicalClient, or invoke OrthogonalPrivacyProjector directly before sending vectors over custom pipelines:
import apical
from apical.orthogonal import OrthogonalPrivacyProjector
# Option A: Automatic blinding via ApicalClient(privacy_secret=...)
client = apical.ApicalClient(
api_key="apk_live_...",
privacy_secret="master-vault-secret-passphrase-known-only-to-client-9921",
)
clf = client.arbor.classifier("clinical-diagnostic-model", in_features=512, num_classes=10)
res = clf.predict(raw_patient_embedding)
# Option B: Standalone manual projector
projector = OrthogonalPrivacyProjector(
privacy_secret="client-secret-passphrase",
dimension=512,
)
projected_vector = projector.project(raw_patient_embedding)
Offline Ed25519 Receipt Verification
Every enclave operation returns an Ed25519 receipt proving that transient input buffers were scrubbed in RAM (input_buffer_zeroed == True) and container storage did not grow (persisted_bytes_delta == 0). The enclave signs every key in the receipt except ed25519_signature using sorted keys and compact JSON separators (separators=(",", ":")).
Validate single receipts or contiguous state hash chains with the built-in SDK helpers, or implement the standalone cryptography audit function below with zero SDK dependencies:
import json
import apical
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
# 1. Built-in SDK verification (single receipt and contiguous state hash chain)
apical.verify_zero_retention_receipt(
receipt,
public_key_hex="...", # Optional: overrides receipt["enclave_public_key_hex"]
expected_pcr0=None, # Optional: pins AWS Nitro Enclave PCR0 hex digest
)
chain_summary = apical.verify_receipt_chain([receipt_1, receipt_2])
# 2. Zero-dependency standalone third-party audit function
def verify_apical_receipt(receipt: dict, published_pubkey_hex: str) -> bool:
"""Verify Ed25519 signature and zero-retention invariants offline."""
pubkey = Ed25519PublicKey.from_public_bytes(bytes.fromhex(published_pubkey_hex))
signature = bytes.fromhex(receipt["ed25519_signature"])
# Exact canonical payload: all receipt fields except ed25519_signature, compact JSON
signing_dict = {k: v for k, v in receipt.items() if k != "ed25519_signature"}
canonical_bytes = json.dumps(
signing_dict, sort_keys=True, separators=(",", ":")
).encode("utf-8")
pubkey.verify(signature, canonical_bytes)
assert receipt["persisted_bytes_delta"] == 0, "Non-zero persisted byte delta"
assert receipt["input_buffer_zeroed"] is True, "RAM buffer not scrubbed"
return True
Copy-Paste Integration Recipes
Runnable end-to-end patterns for classification, tool routing, human-in-the-loop escalation, backbone migration, GDPR erasure, and multi-model prompt dispatch:
Blueprint 1: Image Classification & Online Cold-Start Tagging (DINOv2)
Input → Pattern → Output: Normalized 384-D DINOv2 image embeddings → arbor.Classifier.predict() with confidence-gated learn() → predicted category ID plus signed zero-retention update receipt when a new category is encountered.
import apical
import torch
from torchvision import transforms
from PIL import Image
client = apical.ApicalClient(api_key="apk_live_...")
clf = client.arbor.create_model("marketplace-catalog", in_features=384, num_classes=50)
dinov2 = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14").eval()
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
def get_product_embedding(image_path: str) -> list[float]:
img = preprocess(Image.open(image_path).convert("RGB")).unsqueeze(0)
with torch.no_grad():
emb = dinov2(img).squeeze(0)
emb = torch.nn.functional.normalize(emb, dim=0)
return emb.tolist()
emb = get_product_embedding("new_arrival_jacket.jpg")
res = clf.predict(emb)
print(f"Predicted Category: {res.predicted_class} (Confidence: {res.confidence:.3f})")
if res.confidence < 0.65:
receipt = clf.learn(emb, target_class=42)
assert receipt.persisted_bytes_delta == 0
print(f"Category 42 adapted online. Ed25519: {receipt.ed25519_signature[:16]}...")
Blueprint 2: Top-K Tool Shortlisting with arbor.MemoryRouter
Input → Pattern → Output: Normalized 384-D prompt embedding → arbor.MemoryRouter.route(top_k=3) followed by reinforce() → pruned list of 3 tool schemas passed to the LLM and an updated routing pathway.
import apical
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("all-MiniLM-L6-v2")
client = apical.ApicalClient(api_key="apk_live_...")
router = client.arbor.memory_router("enterprise-agent", embedding_dim=384, num_tools=250)
router.create(embedding_dim=384, num_rules=250)
TOOL_REGISTRY = {
14: {"name": "refund_stripe_charge", "params": ["charge_id", "amount"]},
28: {"name": "search_zendesk_tickets", "params": ["query", "status"]},
92: {"name": "create_jira_issue", "params": ["project", "summary"]},
}
def execute_agent_query(user_prompt: str):
query_vector = embedder.encode(user_prompt, normalize_embeddings=True).tolist()
# 1. Shortlist 250 tools down to top-3 candidates
candidates = router.route(query_vector, top_k=3)
pruned_tools = [TOOL_REGISTRY[c.tool_id] for c in candidates if c.tool_id in TOOL_REGISTRY]
print(f"Selected tools: {[t['name'] for t in pruned_tools]}")
# 2. Reinforce winning tool after execution
selected_tool_id = candidates[0].tool_id
receipt = router.reinforce(query_vector, selected_tool_id=selected_tool_id)
assert receipt.persisted_bytes_delta == 0
print(f"Reinforced tool {selected_tool_id} (persisted_bytes_delta={receipt.persisted_bytes_delta})")
Blueprint 3: Confidence-Gated Ticket Triage & Operator Feedback
Input → Pattern → Output: Support ticket embedding → arbor.Classifier.predict() with a 0.82 confidence threshold → automatic queue dispatch above threshold or human review followed by clf.learn().
import apical
client = apical.ApicalClient(api_key="apk_live_...")
clf = client.arbor.create_model("support-desk-triage", in_features=384, num_classes=30)
def triage_ticket(ticket_id: str, ticket_embedding: list[float]):
pred = clf.predict(ticket_embedding)
if pred.confidence >= 0.82:
print(f"Ticket {ticket_id} auto-routed to Queue {pred.predicted_class} (Conf: {pred.confidence:.2f})")
return {"action": "auto_route", "queue": pred.predicted_class}
print(f"Ticket {ticket_id} escalated for human review (Conf: {pred.confidence:.2f})")
return {"action": "escalate", "candidate_queue": pred.predicted_class}
def on_operator_resolution(ticket_embedding: list[float], verified_queue: int):
receipt = clf.learn(ticket_embedding, target_class=verified_queue)
assert receipt.persisted_bytes_delta == 0
print(f"Updated classifier online for Queue {verified_queue}.")
Blueprint 4: Cross-Backbone Coordinate Migration via Public Anchors
Input → Pattern → Output: Paired equal-dimension (M, 384) and (M, 384) anchor embeddings (e.g., migrating all-MiniLM-L6-v2 384-D to BAAI/bge-small-en-v1.5 384-D, or between distinct 512-D encoders) → client.arbor.bridge() → rotates container coordinates in-place across equal-dimension (D → D) encoders so the container byte size stays strictly constant (persisted_bytes_delta == 0).
import apical
import numpy as np
client = apical.ApicalClient(api_key="apk_live_...")
# 1. Paired equal-dimension anchor representations (e.g. MiniLM 384-D -> BGE-Small 384-D)
np.random.seed(42)
source_anchors = np.random.randn(1000, 384).astype(np.float32)
target_anchors = np.random.randn(1000, 384).astype(np.float32)
source_anchors /= np.linalg.norm(source_anchors, axis=1, keepdims=True)
target_anchors /= np.linalg.norm(target_anchors, axis=1, keepdims=True)
# 2. Realign existing container coordinates to the new encoder space
bridge_res = client.arbor.bridge(
model_id="marketplace-catalog",
source_anchors=source_anchors.tolist(),
target_anchors=target_anchors.tolist(),
)
print(f"Migration Status: {bridge_res.status}")
print(f"Alignment Score: {bridge_res.alignment_score:.4f}")
print(f"Execution Latency: {bridge_res.latency_ms:.2f} ms")
assert bridge_res.persisted_bytes_delta == 0
Blueprint 5: GDPR Article 17 Class Erasure Webhook
Input → Pattern → Output: Target user_class_id → clf.erase_class() → zeroed class coordinate and an auditable Ed25519 erasure certificate payload.
import apical
client = apical.ApicalClient(api_key="apk_live_...")
clf = client.arbor.classifier("enterprise-tenant-model")
def handle_gdpr_erasure_request(user_class_id: int) -> dict:
cert = clf.erase_class(target_class=user_class_id)
assert cert.persisted_bytes_delta == 0
assert cert.target_class_weight_norm == 0.0
return {
"status": "erased_compliant",
"class_id": user_class_id,
"pre_hash": cert.state_sha256_before,
"post_hash": cert.state_sha256_after,
"ed25519_sig": cert.ed25519_signature,
"timestamp_ns": cert.timestamp_ns,
}
Blueprint 6: Semantic Multi-Model Prompt Dispatch & Escalation
Input → Pattern → Output: Raw prompt text and custom ModelSpec ladder → arbor.ModelRouter.calibrate_defaults(), route_prompt(), and reinforce_escalation() → selected ModelRouteDecision plus signed escalation receipt.
import apical
from apical.model_router import ModelSpec
client = apical.ApicalClient(api_key="apk_live_...")
TIER_REGISTRY = {
0: ModelSpec(name="gemini-3.8-flash", provider="google", cost_tier="nano", cost_per_m=0.50),
1: ModelSpec(name="claude-sonnet-5-5", provider="anthropic", cost_tier="standard", cost_per_m=3.00),
2: ModelSpec(name="gemini-4-argon", provider="google", cost_tier="advanced", cost_per_m=2.00),
3: ModelSpec(name="gemini-4-carbon", provider="google", cost_tier="frontier", cost_per_m=4.00),
}
router = client.arbor.model_router(
router_id="enterprise-model-router",
registry=TIER_REGISTRY,
embedding_model="all-MiniLM-L6-v2",
default_tier=0,
)
# 1. Calibrate baseline tier anchors
cal_result = router.calibrate_defaults()
assert cal_result.persisted_bytes_delta == 0
# 2. Route prompt to optimal model tier
decision = router.route_prompt("Summarize this 10-line feedback message into two takeaways.")
print(f"Routed to: {decision.model_name} (Tier {decision.tier}) in {decision.latency_ms:.2f} ms")
# 3. Reinforce escalation when higher reasoning capacity is required
receipt = router.reinforce_escalation(
prompt="Formally prove that the square root of 2 is irrational.",
fallback_tier=3,
)
assert receipt.persisted_bytes_delta == 0
print(f"Reinforced Tier 3. Ed25519 Sig: {receipt.ed25519_signature[:16]}...")