# @munesoft/agent

> Zero-dependency Node.js framework for reliable AI agents. Pipeline: sanitize →
> parse intent → guardrails → ROUTER BRAIN → execute → VERIFY → repair → memory.
> Includes file-safe multi-agent orchestration, searchable session memory, visual
> workflows, and 21 LLM providers + 23 framework bridges.

## Install
npm install @munesoft/agent   (Node >= 16, CommonJS, no runtime dependencies)

## 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. CtxAdapter bridges the `ctx` CLI for real
coding-agent history. 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.

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