# @munesoft/agent

> Node.js framework for reliable AI agents (v3). Pipeline: sanitize → parse intent →
> guardrails → ROUTER BRAIN → execute → VERIFY → repair → memory. Includes file-safe
> multi-agent orchestration, searchable session memory, visual workflows, 21 LLM
> providers + 23 framework bridges, and an opt-in munesoft-stack integration layer.
> The core has ZERO runtime dependencies; stack integrations are optional peer deps.

## Install
npm install @munesoft/agent   (Node >= 16, CommonJS, zero-dependency core)

## Mental model
An Agent turns natural language into a validated tool call, runs it, then checks the
result actually satisfied the task before returning. Every stage is pluggable.

## Core API
const { createAgent } = require("@munesoft/agent");
const agent = createAgent({
  tools:      [{ name, description, schema, handler }],  // handler(args, ctx) => output
  llmProvider: createLLM("openai", { apiKey }),          // OR rules: [{pattern, action, extract}]
  routing:    { threshold, aliases, fallbackTool },      // Router Brain options
  verify:     { checks: [ ... ] },                       // output verification
  maxRepairs: 2,                                          // auto-retry with feedback on failed verify
  guardrails: { redactSecrets, allowedActions, rateLimit },
});
const res = await agent.run("natural language task");
// res: { success, output, tool, decision, verification, repairs, steps, sessionId }

## Router Brain (packages/router)
Resolves intent → tool by scoring across strategies, in order:
1. exact name  2. alias (router- or tool-level)  3. exact tag  4. fuzzy name (Dice bigram)
5. keyword/description overlap. Applies a confidence floor (threshold, default 0.45),
detects ambiguity (ambiguityGap), and can use fallbackTool or an async disambiguate() LLM tie-breaker.
route(intent) => { tool, args, decision:{ strategy, score, candidates } }. Also does schema
coercion + validation (types, enum, min/max, minLength/maxLength, pattern, array items).

## Verification System (packages/verify)
Answers "is the output correct/complete?" (Guardrails answers "is it allowed?").
new Verifier().check(checks.notEmpty()).check(checks.hasKeys(["total"]))
Built-in checks: notEmpty, hasKeys, matches, type, range, jsonShape, custom, llmCheck.
verify(output, ctx) => VerificationReport { passed, score, checks, feedback }.
When wired into an agent with maxRepairs > 0, failed verification re-runs the tool with
the failure feedback injected at ctx._verification until it passes or repairs are exhausted.

## Session Memory (packages/session)
SessionStore = searchable episodic memory (BM25 over an inverted index, append-only JSONL).
record(run) stores intent/decisions/tools/filesTouched/outcome; search(query,{file}) returns
cited snippets + IDs. attachRecorder(agent, store) auto-captures runs from the event bus.
makeRecallTool(store) gives any agent a search_prior_sessions tool. createHistoryResearchAgent
produces a pre-work report of related sessions. NOTE: this differs from MemoryLayer, which is a
per-run KV+history cache.

## File-safe Orchestration (packages/orchestrator, packages/coordination)
Orchestrator.parallel(tasks) is file-aware when tasks declare files:[]; overlapping edits are
rejected (default) or serialized. safeParallel + FileCoordinator expose the primitive.
researchThenEdit({ researcher, task, editors }) runs a history-research subagent first, then
runs editors file-safely with the report injected into their context.

## Execution guarantees (packages/core/execution)
Per-tool timeout, jittered exponential backoff, retry classification (timeouts/aborts/validation
are not retried), optional circuit breaker, and AbortSignal cancellation via ctx.signal.

## Guardrails (packages/guardrails)
Input sanitize + secret/PII redaction (API keys, JWTs, cards, emails), length + rate limits,
intent allow/block lists + confidence floor, output validators + secret-leak blocking.

## Events (packages/events)
EventBus emits: agent.run, intent.parsed, tool.selected, tool.executed, verify.checked,
repair.attempt, memory.updated, agent.error. on/once/off/emit/emitAsync/waitFor + "*" wildcard.

## LLM providers (createLLM(name, opts))
openai, anthropic/claude, gemini/google, vertex, azure, bedrock, mistral, cohere, grok/xai,
perplexity, deepseek, qwen, ernie, huggingface, ollama, together, groq, fireworks, openrouter,
ai21, novita. Any OpenAI-compatible endpoint via OpenAIAdapter({ baseURL }).

## Framework bridges (createBridge(name, opts))
langchain, langgraph, crewai, autogen, openai-agents, swarm, llamaindex, semantic-kernel,
haystack, flowise, dust, agentgpt, opendevin, superagi, metagpt, smolagents, agno, aaif,
mcp, n8n, zapier, make.

## Munesoft Stack Integrations (require("@munesoft/agent/integrations"))
Opt-in adapters wiring the framework to the wider munesoft stack. The core stays zero-dependency:
each adapter lazy-loads its package only when called, so requiring the barrel is always safe and
each package is an OPTIONAL peer dependency (install only what you use). Adapters:
  loadAgentEnv(schema)              -> @munesoft/envx    env validation & typed config
  attachLogx(agent)                 -> @munesoft/logx    structured lifecycle logs
  withRetry(fn) / retryableTool(t)  -> @munesoft/retryx  retryable API calls (backoff, Retry-After)
  boundedParallel(orch,tasks,{concurrency}) -> @munesoft/asyncx  concurrency-capped fan-out
  idFactory() / withStableIds(ctx)  -> @munesoft/idx     stable internal IDs
  mergeSettings() / safeGet()       -> @munesoft/objx    settings merge + safe nested access
  normalizeResponse() / normalizingTool() -> @munesoft/api-normalizer  normalize API/tool output
  createMemoryxStore()              -> @munesoft/memoryx semantic episodic memory (SessionStore-shaped)
  runAgentLoop(agent,input)         -> @munesoft/loopx   multi-step AI loops with stop conditions
stackStatus() reports which stack packages are installed. Missing package => IntegrationError with install hint.

## Errors (all named, instanceof-checkable)
RouterError, ToolNotFoundError, AmbiguousIntentError, SchemaValidationError,
ExecutionTimeoutError, AbortedError, CircuitOpenError, GuardrailError, RateLimitError,
VerifyError, MemoryError, OrchestratorError, WorkflowError, LLMError, IntegrationError.
