Welcome to Nexmon API Documentation
Manage your autonomous agents, tools, tiered memory backends, HITL governance, and subagent fleet orchestration.
What is Nexmon?
A production-grade, zero-hard-dependency TypeScript AI Agent Runtime Engine designed for deterministic event sourcing, type safety, and backend automation.
Core Definition & Design Goal
Nexmon is a lightweight, high-performance TypeScript agent execution engine. It enables developers to build, orchestrate, and deploy autonomous AI agents with complete execution auditability, risk governance, and context management.
The framework integrates strongly-typed context injection (`AgentConfig
Nexmon 7-Layer Architectural Stack
Core Execution Engine
Event-sourcing log, TContext DI container, parallel tools (Promise.allSettled), token budgets, and onEvent hooks.
Tool Risk Governance
Risk levels (LOW..CRITICAL), dynamic HITL approval predicates (requiresApproval), and parameter self-healing.
Tiered Memory System
WorkingMemory (sliding window), ShortTermMemory (TTL KV), and VectorStore (episodic semantic RAG).
Multi-Agent Fleet
AgentSwarm (peer handoffs), AgentWorkflow (DAG state machine), and AgentConsensus (Debate & Voting).
Security & Sandboxing
PIIRedactor, SecurityGuardrail (prompt injection defense), RBAC scoped tools, and LocalSubprocessSandbox.
Tooling & MCP Integration
MCP Client (Stdio/SSE), MCP Server Exporter (JSON-RPC 2.0), HTTP fetcher, file I/O, SQL, code interpreter, PDF RAG.
Observability & USD Token Cost Engine
Hierarchical OpenTelemetry span tracing (`agent.run`, `llm.generate`, `tool.execute`) and real-time model USD token cost calculation.
Architectural Pillars & Core Capabilities
| Architectural Pillar | What Nexmon Delivers | Production Benefit |
|---|---|---|
| Zero-Hard-Dependency Core | Runs natively on Node.js, Bun, Deno, and Edge runtimes with zero heavy native binaries. | Instant cold starts & universal serverless deployment. |
| Immutable Event Sourcing | Every step, tool call, and human approval emits an append-only AgentEvent. |
100% auditability & time-travel process resumption (resumeFromStore). |
| Typed Context DI Container | Strongly-typed generic context AgentConfig<TContext> passed to all tool handlers. |
Safe access to user sessions, tenant context & DB handles in tools. |
| Parallel Tool Execution | Multi-tool requests run concurrently via Promise.allSettled() by default. |
Latency reduction for multi-search & batch API calls. |
| Token Budget Hard Caps | Native tokenBudget limits (maxPromptTokens, maxCompletionTokens, maxTotalTokens). |
Prevents runaway LLM costs with graceful "budget_exceeded" exit. |
| Dry-Run Simulation Mode | Opt-in dryRun: true and dryRunMocks to preview execution without side-effects. |
Risk-free pre-flight testing & prompt verification in staging. |
| Bi-Directional MCP Protocol | Native MCP Client (Stdio/SSE) + MCP Server Exporter (exportAgentAsMCPServer). |
Seamless integration with Claude Desktop, Cursor & external tools. |
| Declarative Tool Governance | Tool risk levels (LOW..CRITICAL) and HITL predicates (requiresApproval). |
Prevents unauthorized high-risk state mutations (e.g. money transfers). |
| Enterprise Security Suite | Native PIIRedactor, SecurityGuardrail injection defense, RBAC, & process sandbox. |
Enterprise data compliance & prompt-injection safeguards out of the box. |
| Rate Limit Resilience | Exponential backoff with full random jitter and 429/503 error detection. | Prevents thundering herd problems during provider rate limits. |
CLI Scaffolding & Interactive Web Agent Studio
Scaffold, configure, and inspect production-ready Nexmon AI Agent projects locally via terminal CLI runner or interactive ChaibookLM-styled browser studio.
1. Interactive Web Agent Studio
The interactive Web Studio launches a local browser interface for configuring LLM providers, SDK modules, vector memory stores, Zod tools, and MCP servers with live code previews and single-click project generation.
npx nexmon
# Or explicitly launch UI on custom port
npx nexmon ui --port 8080
Visual Configuration Suite
- Provider Base URLs: OpenAI, Ollama, DeepSeek, Groq, OpenRouter, vLLM.
- Core SDK Modules: Stateful Chat, HITL Governance, Event Sourcing, Streaming, Guardrails.
- Tiered Memory Stores: InMemory, Mem0.ai, Qdrant, Pinecone, ChromaDB, PostgreSQL, SQLite.
- Custom Zod Tools: Interactively define low, medium, high, or critical risk tools.
MCP Catalog Explorer & Code Preview
- MCP Server Catalog: Search & inspect 30+ public stdio/sse MCP packages or live GitHub repos.
- Live Drawer Preview: View generated TypeScript source code (
agent.ts,index.ts,.env) before saving. - Local Disk Generator: Direct single-click project scaffolding to your workspace directory.
2. Terminal CLI Scaffolding Wizard
Prefer working directly in your terminal? Use terminal flags or interactive CLI prompts to scaffold project files directly.
npx nexmon create my-agent
# Non-interactive CLI scaffolding with pre-configured flags
npx nexmon create my-agent \
--provider=openai \
--model=gpt-4o \
--memory=mem0 \
--tools=httpFetch,filesystem,pdfRAG \
--pm=npm
CLI Command & Flag Reference
| Command / Flag | Default | Description |
|---|---|---|
| npx nexmon | ui --port 3000 | Launches interactive ChaibookLM Web Studio UI |
| npx nexmon ui --port <port> | 3000 | Starts Web Studio UI server on target port |
| npx nexmon create <dir> | ./my-nexmon-agent | Scaffolds complete TypeScript project structure |
| --provider | openai | LLM provider adapter (openai | ollama | deepseek | groq | vllm) |
| --memory | in-memory | Memory engine backend (in-memory | mem0 | qdrant | pinecone | postgres | sqlite) |
| --pm | npm | Package manager (npm | bun | pnpm) |
API Reference Specification
Comprehensive SDK Module documentation, type definitions, factory functions, classes, and advanced practical usage examples.
Core Runtime Engine
Zero-hard-dependency agent execution loop, multi-turn chat, token streaming, and structured schema outputs.
createAgent<TContext>(config)
Initializes a strongly-typed Agent<TContext> with injected dependency context, provider, tools, token budget, and event listeners.
Agent<TContext>
Core execution engine. Supports run(), chat(), resume(), resumeFromStore(), remember(), and recall() with parallel tool execution.
context: { userId: "u123" }
});
await agent.run("Hello");
TokenBudget & AgentRunResult
Hard token limits (maxPromptTokens, maxCompletionTokens, maxTotalTokens) and run result output with status "budget_exceeded".
maxTotalTokens?: number;
}
Dry-Run & Real-time onEvent
Safely simulate runs with dryRun: true and dryRunMocks. Subscribe to live lifecycle events with onEvent: (event) => void.
dryRun: true,
onEvent: (e) => console.log(e.type)
});
import { createAgent, z } from "nexmon";
// 1. Initialize Agent with instructions and response schema
const agent = createAgent({
name: "CodeReviewAgent",
instructions: "Analyze input code snippet and produce structured JSON audit report.",
responseSchema: z.object({
issueCount: z.number(),
severity: z.enum(["LOW", "MEDIUM", "HIGH"]),
summary: z.string()
})
});
// 2. Multi-turn chat maintains state across turns out of the box!
await agent.chat("Analyzing src/index.ts file...");
const result = await agent.chat("Generate final structured review report");
// Strongly typed validated object parsed automatically
console.log("Structured Output:", result.structuredOutput);
Provider Adapters & Custom Endpoints
Universal LLM provider integration supporting custom baseUrls, headers, and local inference engines (Ollama, vLLM, DeepSeek, Groq).
OpenAICompatProvider
Universal strategy adapter supporting custom baseUrl, custom headers, and model aliases for any OpenAI-compatible endpoint.
BaseProvider
Base strategy interface for implementing custom provider drivers with streaming and tool dispatch.
abstract generate(messages, options): Promise<LLMResponse>;
}
import { createAgent, OpenAICompatProvider } from "nexmon";
// Connect to local Ollama inference engine or custom vLLM gateway
const localProvider = new OpenAICompatProvider({
baseUrl: process.env.NEXMON_BASE_URL || "http://localhost:11434/v1",
apiKey: process.env.NEXMON_API_KEY || "ollama",
model: "llama3.2",
defaultHeaders: { "X-Environment": "Local-Inference" }
});
const agent = createAgent({
name: "LocalLLMAgent",
provider: localProvider,
instructions: "Perform zero-cost local LLM inference!"
});
const response = await agent.run("Summarize key benefits of local LLM deployment.");
console.log("Local Output:", response.text);
Tool Security & HITL Governance
Declarative risk classification, dynamic Human-in-the-Loop authorization predicates, and self-healing schema correction loops.
defineTool(options)
Declares a strongly typed tool with Zod input schema, risk level (LOW | MEDIUM | HIGH | CRITICAL), and approval predicate.
ToolRiskLevel & ApprovalPredicate
Risk safety levels and dynamic boolean evaluation predicate function to intercept high-risk tool calls.
import { createAgent, defineTool, z } from "nexmon";
// 1. Declare high-risk tool requiring human approval for production tables
const deleteDatabaseTool = defineTool({
name: "deleteDatabaseTable",
description: "Deletes a database table irreversibly",
schema: z.object({ tableName: z.string() }),
riskLevel: "CRITICAL",
requiresApproval: ({ tableName }) => tableName.startsWith("prod_"),
handler: async ({ tableName }) => ({ status: "deleted", table: tableName })
});
// 2. Attach approval handler callback to intercept execution safely
const agent = createAgent({
name: "DBAdminAgent",
tools: [deleteDatabaseTool],
onApprovalRequest: async (request) => {
console.log(`⚠️ Approval Requested for tool: ${request.toolName}`, request.input);
// Human reviews request and returns approval decision
return { approved: true };
}
});
await agent.run("Drop table prod_users");
Tiered Memory System
Pluggable memory architecture. Simple multi-turn memory works out-of-the-box via agent.chat(). Plug in sliding window token caps or vector stores for persistent RAG.
ShortTermMemory
Sliding window conversation history buffer keeping context under token limits.
LongTermMemory & VectorStore
Persistent key-value memory store and semantic vector similarity memory for RAG recall.
new VectorMemoryBackend()
createVectorStore(config)
Factory helper instantiating memory stores dynamically from environment variables (Mem0, PGVector, Qdrant, Pinecone, Chroma).
// or via NEXMON_VECTOR_STORE_TYPE
import { createAgent, createVectorStore, ShortTermMemory } from "nexmon";
// 1. Zero-code Env Controlled Setup (driven by .env file):
// NEXMON_VECTOR_STORE_TYPE="mem0"
// NEXMON_MEM0_API_KEY="m0-xxx"
// NEXMON_MEM0_URL="https://api.mem0.ai/v1"
// NEXMON_MEM0_USER_ID="user_101"
const envDrivenStore = createVectorStore(); // Auto-reads NEXMON_VECTOR_STORE_TYPE
// 2. Explicit Factory Setup for Mem0 / PGVector / Qdrant:
const mem0Store = createVectorStore({
type: "mem0",
apiKey: process.env.NEXMON_MEM0_API_KEY,
url: "https://api.mem0.ai/v1"
});
const agent = createAgent({
name: "EnvMemoryAgent",
shortTermMemory: new ShortTermMemory({ maxMessages: 20 }),
vectorStore: envDrivenStore
});
await agent.remember("User preference: Always return JSON format.");
const facts = await agent.recall("User preference");
Third-Party Integration Info & Setup Guides
Mem0 automatically extracts facts and user preferences from user messages. Partitioned by userId, Mem0 retrieves user context even in single stateless runs (e.g., serverless API calls) without needing manual agent.remember() calls or multi-turn chat loops!
NEXMON_MEM0_API_KEY="m0-xxx"
NEXMON_MEM0_USER_ID="user_id"
NEXMON_MEM0_AGENT_ID="agent_id"
pg pool query executor function to PGVectorStore. Automatically creates vector tables and HNSW indexes.query: (text, params) => pgPool.query(text, params),
tableName: "nexmon_vectors"
})
NEXMON_VECTOR_STORE_URL="http://localhost:6333"
NEXMON_VECTOR_COLLECTION="nexmon_vectors"
Event Sourcing & Audit Engine
Immutable event logging, time-travel execution replay, and deterministic state reconstruction from historical event logs.
EventBus & AgentEvent
Decoupled event emitter emitting immutable AgentEvent state transition objects.
bus.on("event", fn);
replayAgentState(events)
Reconstructs exact agent state deterministically up to any step in historical execution logs.
import { createAgent, EventBus, replayAgentState } from "nexmon";
// 1. Subscribe to real-time execution event bus stream
const eventBus = new EventBus();
eventBus.on("event", (evt) => {
console.log(`[EVENT ${evt.timestamp}] Type: ${evt.type}`, evt.payload);
});
const agent = createAgent({ name: "AuditedAgent", eventBus });
const result = await agent.run("Execute financial order #8841");
// 2. Reconstruct deterministic state up to step 2 for audit debugging
const historicalEvents = result.messages; // or agent.getEventLog()
const reconstructedState = replayAgentState(historicalEvents, 2);
console.log("Reconstructed Step 2 State:", reconstructedState);
Fleet Orchestration & Swarm Intelligence
Supervisor-worker delegation, dynamic peer-to-peer agent handoffs, and DAG workflow pipelines.
SubAgentFleet
Supervisor agent orchestrating tasks across specialized worker subagents.
SwarmHandoff & WorkflowDAG
Dynamic agent-to-agent delegation and deterministic graph pipelines.
new WorkflowDAG()
import { createAgent, SubAgentFleet } from "nexmon";
// 1. Initialize specialized worker agents
const researcher = createAgent({ name: "Researcher", instructions: "Gathers raw facts and technical metrics." });
const writer = createAgent({ name: "Writer", instructions: "Synthesizes clear prose reports." });
// 2. Wrap under supervisor agent inside a SubAgentFleet
const fleet = new SubAgentFleet({
supervisor: createAgent({ name: "Editor", instructions: "Coordinates team output." }),
workers: [researcher, writer]
});
// 3. Delegate complex task to fleet
const fleetOutput = await fleet.execute("Write a comprehensive research report on quantum AI.");
console.log("Fleet Final Output:", fleetOutput.text);
PDF RAG Engine
Extract text from PDF documents, chunk content, index vector embeddings, and query context within agent execution loops.
DocumentLoader & PDFParser
Loads and parses PDF files into text chunks with metadata extraction.
const doc = await loader.loadPDF(path);
VectorIndex
Indexes vector similarity embeddings and performs cosine similarity queries over document chunks.
await index.addDocuments(chunks);
import { createAgent, DocumentLoader, VectorIndex } from "nexmon";
// 1. Load and parse PDF document into text chunks
const loader = new DocumentLoader();
const pdfDoc = await loader.loadPDF("./system-manual.pdf");
// 2. Index text chunks into similarity vector store
const vectorIndex = new VectorIndex();
await vectorIndex.addDocuments(pdfDoc.chunks);
// 3. Attach vector store to Agent for document RAG querying
const ragAgent = createAgent({
name: "PDFDocAssistant",
vectorStore: vectorIndex,
instructions: "Answer queries accurately based strictly on loaded document context."
});
const answer = await ragAgent.run("What are the hardware memory prerequisites?");
console.log("RAG Answer:", answer.text);
Telemetry & Security Guardrails
OpenTelemetry span exporter integration, prompt injection filtering, and PII sanitization filters.
TelemetryManager
Exports execution spans, token consumption metrics, and tool latencies to OTel collectors.
SecurityGuardrail
Inspects inputs and outputs for prompt injection attempts, malicious code, and PII exposure.
import { createAgent, TelemetryManager, SecurityGuardrail } from "nexmon";
// 1. Configure OpenTelemetry tracing exporter
const telemetry = new TelemetryManager({
serviceName: "nexmon-production-agent",
exportEndpoint: "http://localhost:4318/v1/traces"
});
// 2. Configure runtime security guardrail (PII redaction + injection filter)
const guardrail = new SecurityGuardrail({
blockPromptInjection: true,
redactPII: true,
customRules: [(input) => !input.includes("DROP DATABASE")]
});
// 3. Instantiate hardened agent
const secureAgent = createAgent({
name: "HardenedEnterpriseAgent",
telemetry,
guardrails: [guardrail]
});
await secureAgent.run("Process inquiry for john.doe@example.com");
Bi-Directional Model Context Protocol (MCP) Integration
Connect external MCP servers (Filesystem, GitHub, Postgres) directly to Nexmon Agents, or export Nexmon Agents as standard JSON-RPC 2.0 MCP servers.
MCPClient & StdioMCPTransport
Connects to external stdio/sse MCP server processes, discovers available tools, and binds them to Nexmon agents.
const tools = await getToolsFromMCPClient(client);
exportAgentAsMCPServer
Exports any Nexmon Agent or tool set as an MCP server over stdio/sse for Claude Desktop or Cursor integration.
await server.startStdio();
import { createAgent, MCPClient, StdioMCPTransport, getToolsFromMCPClient, exportAgentAsMCPServer } from "nexmon";
// 1. Create Stdio transport connecting to external filesystem MCP server
const transport = new StdioMCPTransport({
command: "npx",
args: ["-y", "@modelcontextprotocol/server-filesystem", "./data"]
});
// 2. Connect MCP Client & discover tools automatically
const mcpClient = new MCPClient(transport, { name: "filesystem_mcp" });
await mcpClient.connect();
const mcpTools = await getToolsFromMCPClient(mcpClient);
// 3. Create Agent equipped with external MCP server tools!
const agent = createAgent({
name: "FilesystemAgent",
instructions: "Inspect and update files using external MCP tools.",
tools: mcpTools
});
const result = await agent.run("List files in ./data and check their status.");
console.log(result.text);
await mcpClient.disconnect();
// Optional: Export Nexmon Agent as an MCP Server for Claude Desktop / Cursor
const mcpServer = exportAgentAsMCPServer(agent, { name: "exported_agent", version: "1.0.0" });
await mcpServer.startStdio();
Custom & Standard Tooling Library
Declarative tool creation with Zod schema validation, type-safe context injection (`TContext`), and standard built-in tools (HTTP, Filesystem, Code Interpreter, SQL, PDF RAG).
defineTool<TParams, TOutput, TContext>
Defines a strongly-typed tool with Zod schema validation, risk level, approval predicate, and injected context.
name, description, parameters, riskLevel, requiresApproval, execute
})
Built-in Standard Tools
Ready-to-use tools: httpFetchTool, readFileTool, writeFileTool, codeInterpreterTool, sqlQueryTool, readPdfTool, createRAGTool.
import { createAgent, defineTool, httpFetchTool, codeInterpreterTool, z } from "nexmon";
// 1. Define custom application tool with Zod parameters & context injection
const searchUserDbTool = defineTool({
name: "search_users",
description: "Search user database by status",
parameters: z.object({ status: z.enum(["active", "pending"]) }),
execute: async ({ status }, context) => {
return { status, count: 42, requestedBy: context?.context?.userId };
}
});
// 2. Attach custom & built-in tools to agent
const agent = createAgent({
name: "ToolingAgent",
tools: [searchUserDbTool, httpFetchTool, codeInterpreterTool]
});
const result = await agent.run("Search active users and check HTTP status of api.example.com");
console.log(result.text);
Runnable Examples Gallery
Select any of the 19 verified code examples below to view complete, copyable TypeScript source code.
01. Basic Agent
Basic agent initialization and execution.
Quick Start Guide
Get up and running with Nexmon in under 60 seconds.
1. Installation
2. Set Environment Variables
export NEXMON_BASE_URL="https://api.openai.com/v1" # or http://localhost:11434/v1 for Ollama
export NEXMON_MODEL="gpt-4o-mini"
3. Create Your First Agent
import { createAgent, defineTool, z } from "nexmon";
const agent = createAgent({
name: "MyFirstAgent",
instructions: "You are a helpful AI assistant built with Nexmon."
});
const result = await agent.run({ prompt: "Hello! Introduce yourself.", dryRun: true });
console.log(result.output);
4. Vendor-Agnostic Environment Variables Matrix
All SDK capabilities can be controlled zero-code via .env or .env.local files:
| Category | Environment Variable | Description & Default |
|---|---|---|
| LLM Provider | NEXMON_API_KEY | API key for OpenAI / DeepSeek / Groq / OpenRouter |
| LLM Provider | NEXMON_BASE_URL | Custom endpoint URL (e.g. http://localhost:11434/v1) |
| LLM Provider | NEXMON_MODEL | Model alias (Default: gpt-4o-mini) |
| Memory Store | NEXMON_VECTOR_STORE_TYPE | Memory backend (in-memory | mem0 | pgvector | qdrant | pinecone | chroma) |
| Mem0 Store | NEXMON_MEM0_API_KEY | Mem0 API Key for managed long-term memory |
| Mem0 Store | NEXMON_MEM0_URL | Mem0 Base URL (Default: https://api.mem0.ai/v1) |
| Mem0 Store | NEXMON_MEM0_USER_ID / AGENT_ID | Partition identifiers for user/agent long-term memory |
| Vector DB | NEXMON_VECTOR_STORE_URL | Vector database endpoint (Default: http://localhost:6333) |
| Telemetry | OTEL_SERVICE_NAME / NEXMON_SERVICE_NAME | OpenTelemetry service identifier (Default: nexmon-agent) |
| Telemetry | OTEL_EXPORTER_OTLP_ENDPOINT | OpenTelemetry collector trace endpoint URL |
Interactive Agent Simulator
Configure, execute, and monitor live Agent state transitions, event streams, tool governance checks, and human approvals directly in your browser.
Agent Configuration
dryRun: true)
Immutable Event Stream Log (AgentEvent)
executeShellCommand requires human authorization before execution.