protectnil/epic-ai-core

GitHub: protectnil/epic-ai-core

面向企业网络安全运营的零上下文泄露 MCP 编排框架,以本地小模型调度工具、云端大模型生成响应,覆盖十大安全域并提供分级自治治理与防篡改审计。

Stars: 0 | Forks: 0

# Epic AI® ## 零 LLM 上下文 MCP 编排器 — 覆盖所有 10 个 (ISC)² 安全域的智能虚拟助手 (IVA) [![npm version](https://img.shields.io/npm/v/@epicai/core.svg?style=flat)](https://www.npmjs.com/package/@epicai/core) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) [![Build](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com/protectnil/epic-ai-core/actions) [![TypeScript](https://img.shields.io/badge/TypeScript-5.3+-blue.svg)](https://www.typescriptlang.org/) [![Node](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg)](https://nodejs.org/) **Epic AI®** 是一个开源 TypeScript SDK,用于构建能够跨多个 Model Context Protocol (MCP) 服务器进行联邦的智能虚拟助手 (IVA),具备分层自治治理、混合检索、持久化内存、角色路由和防篡改审计跟踪功能 — 覆盖所有 10 个 (ISC)² 安全域。该 SDK 的编排器/生成器架构将工具 schema、MCP 服务器拓扑和中间工具结果保留在您的本地 SLM 上 — 只有经过筛选的上下文才会传输到云端 LLM 进行响应合成。 由 [protectNIL Inc.](https://protectnil.com) 构建 — Epic AI® 是注册商标(美国注册号 7,748,019)。 ## 为什么选择 Epic AI® **1. 工具 schema 导致 LLM 上下文膨胀 — 并降低性能。** 发送到云端 LLM 的每个 MCP 工具定义都会消耗 token,增加延迟,并将您的内部工具面泄露给第三方。Epic AI® 使用本地小语言模型 (SLM) 作为编排器来选择和调用工具,将所有工具 schema 保留在云端 LLM 的上下文窗口之外。云端 LLM 仅看到检索到的结果并生成最终响应。 **2. Agent 需要的是治理,而不仅仅是护栏。** 静态系统提示护栏在对抗性输入下会失效。Epic AI® 实现了分层自治引擎:在运行时根据动态策略将操作分类为 `auto`、`escalate` 或 `approve`。高风险操作在执行前需要明确的人工批准 — 而不是之后。 **3. 合规性需要溯源,而不仅仅是日志记录。** 仅追加日志不是审计跟踪。Epic AI® 将每个 agent 操作写入 SHA-256 哈希链记录,使得任何事件序列中的篡改均可被检测,并支持导出为 JSON、CSV 和 syslog 格式。 **4. 安全数据保留您的基础设施上 — 设计如此。** 每个 MCP 工具 schema、每个中间工具结果以及每个路由决策都保留在您的本地 SLM 上。云端 LLM 仅接收经过筛选和清洗的上下文以进行响应合成。您的安全遥测、供应商拓扑和威胁数据永远不会通过第三方 API 传输。 ## 快速开始 ``` npm install @epicai/core npx epic-ai setup ``` ``` import { EpicAI } from '@epicai/core'; const agent = await EpicAI.create({ orchestrator: { provider: 'ollama', model: 'mistral:7b' }, generator: { provider: 'openai', model: 'gpt-4.1', apiKey: process.env.OPENAI_API_KEY }, federation: { servers: [ { name: 'vault', transport: 'stdio', command: 'mcp-vault' }, { name: 'splunk', transport: 'streamable-http', url: 'https://splunk.local/mcp' }, ], }, autonomy: { tiers: { auto: ['read', 'query', 'search'], escalate: ['contain', 'isolate'], approve: ['delete', 'revoke', 'terminate'], }, }, persona: { name: 'praetor', tone: 'commanding', domain: 'cybersecurity', systemPrompt: 'You are the Praetor, a sovereign cybersecurity intelligence officer.', }, audit: { store: 'memory', integrity: 'sha256-chain' }, }); await agent.start(); const result = await agent.run('What threats were detected in the last 24 hours?'); console.log(result.response); await agent.stop(); ``` ## 架构 ``` ┌─────────────────────────────────────────────────────┐ │ EpicAI Agent │ │ (EpicAI.create()) │ └──────────────────────┬──────────────────────────────┘ │ ┌────────────────────────────────┼────────────────────────────────┐ │ │ │ ▼ ▼ ▼ ┌──────────────────┐ ┌───────────────────┐ ┌───────────────────┐ │ Orchestrator │ │ Autonomy Layer │ │ Audit Trail │ │ (Local SLM) │◄──────────►│ TieredAutonomy │ │ SHA-256 chain │ │ Mistral 7B / │ evaluates │ PolicyEngine │ │ append-only log │ │ vLLM / custom │ actions │ ApprovalQueue │ │ tamper-evident │ └────────┬─────────┘ └───────────────────┘ └───────────────────┘ │ selects tools │ (schemas stay local) ▼ ┌──────────────────────────────────────────────────────┐ │ Federation Layer │ │ FederationManager → ConnectionPool → ToolRegistry │ │ Correlator (cross-source entity resolution) │ └────────┬────────┬────────┬────────┬──────────────────┘ │ │ │ │ ┌────┘ ┌────┘ ┌────┘ ┌────┘ ▼ ▼ ▼ ▼ [MCP-1] [MCP-2] [MCP-3] [MCP-N] Splunk CrowdStrike Vault Qualys ... │ │ results returned ▼ ┌──────────────────┐ ┌─────────────────────┐ │ Retrieval Layer │ │ Memory Layer │ │ HybridRetriever │ │ PersistentMemory │ │ dense + sparse │ │ importance-weighted│ │ + BM25 + RRF │ │ Redis + MongoDB │ └────────┬─────────┘ └──────────┬───────────┘ │ │ └──────────┬───────────────┘ ▼ ┌──────────────────┐ │ Persona Layer │ │ PersonaManager │ │ SystemPrompt │ │ Builder │ └────────┬─────────┘ │ composed context ▼ ┌──────────────────┐ │ Generator │ │ (Cloud LLM) │ │ GPT-4.1 / │ │ Claude / custom │ └──────────────────┘ ``` 编排器(本地 SLM)从不将工具 schema 发送到生成器(云端 LLM)。工具定义、MCP 服务器拓扑和中间工具结果完全在本地处理。云端 LLM 仅接收生成响应所需的筛选上下文。 ## 五层架构 ### 第 1 层 — 联邦 在单一接口后连接任意数量的 MCP 服务器。`FederationManager` 管理所有已注册服务器的连接生命周期、健康检查和重试策略。`ToolRegistry` 提供统一的工具发现。`Correlator` 跨来自多个服务器的数据解析同一实体(IP 地址、用户、主机名)。 ``` import { FederationManager } from '@epicai/core'; const federation = new FederationManager({ servers: [ { name: 'crowdstrike', transport: 'streamable-http', url: 'https://cs.local/mcp', auth: { type: 'bearer', token: process.env.CS_TOKEN } }, { name: 'splunk', transport: 'streamable-http', url: 'https://splunk.local/mcp' }, { name: 'vault', transport: 'stdio', command: 'mcp-vault' }, ], retryPolicy: { maxRetries: 3, backoffMs: 500, maxBackoffMs: 10_000 }, healthCheckIntervalMs: 30_000, }); await federation.connectAll(); const tools = federation.listTools(); // unified tool list across all servers const health = await federation.health(); // per-server connection status ``` **传输方式:** `stdio`(本地子进程)和 `streamable-http`(通过 HTTPS 的远程 MCP 服务器)。 **认证方案:** `bearer`、`basic`、`api-key`。 ### 第 2 层 — 自治 编排器请求的每次工具调用在执行前都会通过 `TieredAutonomy` 引擎。操作匹配三个层级: | 层级 | 行为 | |------------|----------------------------------------------------| | `auto` | 立即执行,无需人工审查 | | `escalate` | 执行,但加入队列等待事后人工审查 | | `approve` | 阻塞,直到授权人员明确批准 | 动态 `PolicyEngine` 规则可以根据 payload 内容、时间段、源服务器或任何自定义条件在运行时覆盖层级分配。`ApprovalQueue` 支持内存或 Redis 持久化,具有可配置的 TTL 和过期行为。 ``` import { TieredAutonomy } from '@epicai/core'; const autonomy = new TieredAutonomy( { auto: ['search', 'query', 'read', 'list'], escalate: ['contain', 'isolate', 'block'], approve: ['delete', 'revoke', 'terminate', 'disable'], }, { persistence: 'redis', redis: { host: 'localhost', port: 6379 }, ttlMs: 3_600_000 }, ); autonomy.addPolicy({ name: 'no-prod-deletes-after-hours', condition: (ctx) => ctx.tool === 'delete' && ctx.server === 'prod', override: 'approve', priority: 10, }); const decision = await autonomy.evaluate({ tool: 'delete', server: 'prod', args: {}, persona: 'praetor', timestamp: new Date(), priorActions: [], }); // decision.tier === 'approve' — blocked, pending human approval ``` 批准或拒绝待处理操作: ``` await agent.approve('action-uuid-here', { approver: 'ops@example.com' }); await agent.deny('action-uuid-here', { approver: 'ops@example.com', reason: 'Out of change window' }); ``` ### 第 3 层 — 检索 `HybridRetriever` 针对向量存储运行三条并行搜索路径,并使用 Reciprocal Rank Fusion (RRF) 融合结果: - **Dense** — 语义嵌入相似度(例如 OpenAI `text-embedding-3-small`,本地模型) - **Sparse** — miniCOIL 学习稀疏表示,用于关键词敏感召回 - **BM25** — 经典词频评分,用于精确匹配检索 RRF 融合平衡了所有三个信号,无需手动调整权重。 持久化内存存储带有重要性分数的召回上下文,使 agent 能够突出高信号记忆,同时抑制陈旧噪声。 ``` import { HybridRetriever } from '@epicai/core'; import { QdrantAdapter } from '@epicai/core/retrieval/adapters/qdrant'; const retriever = new HybridRetriever({ dense: { provider: 'qdrant', collection: 'dense-collection', adapter: new QdrantAdapter(client, 'dense-collection') }, sparse: { provider: 'qdrant', collection: 'sparse-collection', adapter: new QdrantAdapter(client, 'sparse-collection') }, bm25: { provider: 'qdrant', collection: 'bm25-collection', adapter: new QdrantAdapter(client, 'bm25-collection') }, maxResults: 10, minScore: 0.0, fusion: 'rrf', }); const results = await retriever.search('lateral movement indicators past 48h'); ``` **向量存储适配器:** `InMemoryAdapter`(内置,零依赖),`QdrantAdapter`(可选 peer 依赖)。 ### 第 4 层 — 角色 `PersonaManager` 和 `SystemPromptBuilder` 组装发送给生成器 LLM 的最终系统提示。角色配置控制名称、语气、领域重点、词汇替换和输出约束 — 无需修改编排逻辑即可构建专用 agent。 ``` import { PersonaManager, SystemPromptBuilder } from '@epicai/core'; const persona = new PersonaManager(); persona.register({ name: 'praetor', tone: 'commanding', domain: 'cybersecurity', systemPrompt: 'You are the Praetor, a sovereign threat intelligence officer.', vocabulary: { 'host': 'endpoint', 'user': 'principal' }, constraints: ['Never speculate beyond available evidence.', 'Cite all source servers.'], }); const prompt = SystemPromptBuilder.build(persona.active(), conversationContext); ``` 可以通过 agent 配置在运行时定义和切换多个角色,从而从单个 SDK 实例进行多角色部署。 ### 第 5 层 — 审计 Agent 采取的每个操作 — 工具调用、自治决策、批准事件 — 都会写入 `AuditTrail`。每条记录分配有一个单调递增的序列号和一个链接到前一条记录的 SHA-256 哈希,使得追溯性篡改可被检测。 ``` import { AuditTrail } from '@epicai/core'; const audit = new AuditTrail({ store: 'append-only-log', path: '/var/log/epic-ai/audit.jsonl', integrity: 'sha256-chain' }); // Query const records = await audit.query({ tool: 'delete', since: new Date('2026-01-01') }); // Verify chain integrity — returns false if any record was modified or deleted const intact = await audit.verify(); // Export const csv = await audit.export('csv'); const json = await audit.export('json'); await audit.export('syslog'); // emits to syslog ``` **审计存储适配器:** `memory`(内置),`append-only-log`(JSONL 文件,内置),`custom`(自带 `AuditStoreAdapter` 实现)。 ## 40 个网络安全 MCP 服务器适配器 Epic AI® 提供覆盖所有 10 个 (ISC)² 安全域的预构建适配器:安全管理、访问控制、电信与网络安全、密码学、安全架构、运维安全、应用安全、物理安全、业务连续性以及法律与道德。 每个适配器实现 `MCPAdapter` 接口,并处理其各自平台的认证、请求格式化和响应规范化。 | 类别 | 适配器 | |-----------------------|----------------------------------------------------------------------------------------------| | **EDR / XDR** | CrowdStrike Falcon, CrowdStrike Identity, Carbon Black, SentinelOne, Cybereason, Sophos, Trend Micro | | **SIEM / Analytics** | Splunk, IBM QRadar, Microsoft Sentinel, Sumo Logic, LogRhythm, Datadog Security | | **Threat Intelligence** | Recorded Future, ThreatConnect, Anomali, Mandiant | | **Network Security** | Palo Alto Networks, Fortinet, Check Point, Cisco Secure, Zscaler, Barracuda, Darktrace | | **Vulnerability Mgmt**| Tenable, Qualys, Rapid7, Orca, Lacework, Wiz, Prisma Cloud | | **Identity & Access** | CyberArk, BeyondTrust, Delinea, Ping Identity | | **GRC / Compliance** | ServiceNow GRC, OneTrust, Drata | | **Email Security** | Proofpoint, Mimecast | ### 示例:Splunk 适配器 ``` import { SplunkMCPServer } from '@epicai/core/mcp-servers/splunk'; const splunk = new SplunkMCPServer({ host: 'splunk.corp.example.com', username: process.env.SPLUNK_USER!, password: process.env.SPLUNK_PASS!, }); // Use directly or connect via FederationManager await federation.connect('splunk', { name: 'splunk', transport: 'streamable-http', url: 'https://splunk.corp.example.com:8089' }); ``` 所有 40 个适配器共享一致的接口 — 无需更改编排逻辑即可切换平台。 ## 企业级功能 ### 可观测性 每个 agent 生命周期事件的事件回调。每次调用的 token 和成本跟踪。通过 `createOTelEventCallback` 和 `createOTelLogCallback` 集成 OpenTelemetry。 ``` import { ObservabilityEmitter, TokenTracker, createOTelEventCallback } from '@epicai/core'; const emitter = new ObservabilityEmitter(); emitter.onEvent(createOTelEventCallback(tracer)); emitter.onEvent((event) => metrics.record(event.type, event.data)); const tracker = new TokenTracker(); tracker.record({ model: 'gpt-4.1', promptTokens: 1200, completionTokens: 340, costUsd: 0.0048 }); const summary = tracker.summary(); // total tokens, total cost, per-model breakdown ``` 要获取单次运行的可读快照,请将 `RunTelemetryCollector` 附加到相同的事件/日志流: ``` import { RunTelemetryCollector } from '@epicai/core'; const telemetry = new RunTelemetryCollector(); const detach = telemetry.attach(emitter); // ... run the agent ... console.log(telemetry.format()); detach(); ``` ### 弹性 - **Rate limiting** — 每个服务器的令牌桶,具有可配置的突发容量 (`RateLimiter`) - **Error classification** — 区分瞬态和致命错误以进行重试逻辑 (`ErrorClassifier`) - **Graceful shutdown** — 有序关闭,强制执行每个任务的超时 (`GracefulShutdown`) - **Crash recovery** — 长时间运行编排器循环的检查点/恢复 (`FileCheckpointStore`) - **Prompt cache** — SHA-256 键控内存缓存,用于重复的提示片段 (`PromptCache`) ``` import { RateLimiter, GracefulShutdown, FileCheckpointStore } from '@epicai/core'; const limiter = new RateLimiter({ requestsPerSecond: 10, burst: 20 }); const shutdown = new GracefulShutdown({ timeoutMs: 15_000 }); const checkpoint = new FileCheckpointStore('/var/lib/epic-ai/checkpoints'); shutdown.register('save-checkpoint', async () => { await checkpoint.save('orchestrator', { step: currentStep, context }); }); ``` ### 流式传输 agent `stream()` 方法随着编排器循环的进展产生 `StreamEvent` 对象 — 计划选择、工具调用、自治决策、叙述生成和完成 — 支持通过 SSE 进行实时 UI 更新。 ``` for await (const event of agent.stream('Identify all endpoints with active C2 beaconing')) { if (event.type === 'action') console.log('Tool:', event.data.tool); if (event.type === 'narrative') process.stdout.write(event.data.text); if (event.type === 'done') console.log(`Completed in ${event.data.durationMs}ms`); } ``` ## 配置参考 ### `EpicAIConfig` | 字段 | 类型 | 必需 | 描述 | |----------------|------------------------|----------|----------------------------------------------------------| | `orchestrator` | `OrchestratorConfig` | 是 | 用于工具选择和编排的本地 SLM | | `generator` | `GeneratorConfig` | 否 | 用于最终响应生成的云端 LLM | | `federation` | `FederationConfig` | 是 | MCP 服务器连接和重试策略 | | `autonomy` | `AutonomyConfig` | 是 | 分层操作治理规则和批准队列 | | `retrieval` | `RetrievalConfig` | 否 | 混合检索器和向量存储配置 | | `persona` | `PersonaConfig` | 是 | Agent 身份、语气、领域和系统提示 | | `audit` | `AuditConfig` | 是 | 审计存储、完整性模式、保留和导出 | | `transport` | `'sse' \| 'json'` | 否 | `stream()` 输出的流式传输 | ### `OrchestratorConfig` | 字段 | 类型 | 描述 | |-----------------|-----------------------------------------------------|------------------------------------------| | `provider` | `'ollama' \| 'vllm' \| 'apple-foundation' \| 'custom'` | 编排器运行时 | | `model` | `string` | 模型名称 (例如 `'mistral:7b'`) | | `baseUrl` | `string` | Ollama 或 vLLM 端点的 Base URL | | `maxIterations` | `number` | 最大编排器循环迭代次数 | | `llm` | `LLMFunction` | 自带 LLM 函数 | ### `GeneratorConfig` | 字段 | 类型 | 描述 | |------------|---------------------------------------------|---------------------------------------------------| | `provider` | `'openai' \| 'anthropic' \| 'ollama' \| 'custom'` | 生成器 LLM 提供商 | | `model` | `string` | 模型名称 (例如 `'gpt-4.1'`, `'claude-opus-4'`)| | `apiKey` | `string` | 提供商的 API key | | `maxTokens`| `number` | 生成的最大 token 数量 | | `llm` | `LLMFunction` | 自带 LLM 函数 | ### `AutonomyConfig` | 字段 | 类型 | 描述 | |----------------|-------------------------|-------------------------------------------------------| | `tiers` | `AutonomyRules` | `auto`、`escalate`、`approve` 的操作关键词列表| | `policies` | `AutonomyPolicy[]` | 动态策略规则(可选) | | `approvalQueue`| `ApprovalQueueConfig` | 批准持久化:`memory` 或 `redis` | ### `AuditConfig` | 字段 | 类型 | 描述 | |-------------|---------------------------------------|-------------------------------------------------| | `store` | `'memory' \| 'append-only-log' \| 'custom'` | 审计存储后端 | | `path` | `string` | `append-only-log` 存储的文件路径 | | `integrity` | `'sha256-chain' \| 'none'` | 哈希链接模式 | | `export` | `Array<'json' \| 'csv' \| 'syslog'>` | 启用的导出格式 | | `retention` | `{ maxAgeDays?, maxSizeBytes? }` | 日志保留策略 | ## API 参考 所有公共类型均从 `@epicai/core` 导出,并附带完整的 JSDoc 文档。该包随所有编译模块一起提供声明文件 (`.d.ts`)请参阅 [开发者指南](DEVELOPER_GUIDE.md) 以获取每一层、配置选项和适配器接口的完整文档。 ### 主要导出 | 导出 | 描述 | |-----------------------|----------------------------------------------------------| | `EpicAI` | 静态工厂 — `EpicAI.create(config)` → `EpicAIAgent` | | `FederationManager` | 多服务器 MCP 连接管理 | | `TieredAutonomy` | 具有层级评估和批准队列的操作治理| | `HybridRetriever` | Dense + sparse + BM25 检索,带 RRF 融合 | | `PersonaManager` | Agent 身份和系统提示组合 | | `AuditTrail` | SHA-256 哈希链仅追加审计日志 | | `ObservabilityEmitter`| 事件回调和 OpenTelemetry 集成 | | `TokenTracker` | 跨模型的 token 和成本跟踪 | | `RateLimiter` | 每个服务器的令牌桶速率限制 | | `GracefulShutdown` | 带超时强制的有序 agent 关闭 | ## 贡献 欢迎贡献。在提交 Pull Request 之前,请阅读[贡献指南](CONTRIBUTING.md)。 **要求:** - Node.js >= 20.0.0 - TypeScript 5.3+ **设置:** ``` git clone https://github.com/protectnil/epic-ai-core.git cd epic-ai-core npm install npm run build npm test ``` **在提交 PR 之前:** 1. 所有现有测试必须通过:`npm test` 2. TypeScript 必须零错误编译:`npm run lint` 3. 新的公共 API 必须包含 JSDoc 文档和 TypeScript 类型 4. 新的 MCP 服务器适配器必须实现 `MCPAdapter` 并包含测试 **报告安全漏洞:** 不要为安全漏洞公开 issue。请发送邮件至 [security@epic-ai.io](mailto:security@epic-ai.io)。 ## 许可证 Copyright 2026 protectNIL Inc. 根据 Apache License, Version 2.0 授权。有关完整许可文本,请参阅 [LICENSE](LICENSE)。 除非遵守许可证,否则您不得使用本软件。许可证副本也可在 [https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) 获取。 ## 商标声明 **Epic AI®** 是 protectNIL Inc. 的注册商标,美国商标注册号 7,748,019。在软件、服务或文档中使用 Epic AI® 名称和标志受 protectNIL Inc. 商标政策的约束。 `@epicai/core` npm 包和本仓库是 Epic AI® 标志在商业中的官方使用样本,用于具有网络安全功能的可下载计算机软件,利用自然语言处理 (NLP)、自然语言理解 (NLU)、机器学习以及生成式和对话式 AI 来访问和处理所有 10 个 (ISC)² 安全域的第三方安全信息源。 本文档中引用的所有其他商标、服务标志和产品名称均是其各自所有者的财产。CrowdStrike、Splunk、Palo Alto Networks、Microsoft Sentinel、IBM QRadar 和所有其他第三方名称仅用于标识兼容集成,与 protectNIL Inc. 没有任何关联或受其认可。 *Epic AI® — 网络安全智能虚拟助手 (IVA) | 零 LLM 上下文 MCP 编排器 | 由 [protectNIL Inc.](https://protectnil.com) 构建*
标签:AI风险缓解, GNU通用公共许可证, ISC2安全域, LLM上下文优化, MITM代理, Node.js, Petitpotam, Spyse API, TypeScript SDK, 人工智能, 企业级AI安全, 多工具联邦, 大语言模型编排, 安全合规, 审计追踪, 工具调用路由, 搜索引擎查询, 敏感数据屏蔽, 数据隐私保护, 智能虚拟助手, 本地SLM, 检索增强生成, 模型上下文协议, 混合云AI, 用户代理, 用户模式Hook绕过, 网络代理, 网络安全助手, 自动化攻击, 自治代理治理, 防御性AI, 隐私优先AI, 零上下文架构