Note
本文档由 WeHub 基于上游 README 翻译整理,属于社区翻译,非官方中文文档。
English · 原始项目 · 上游 README
原作者、版权与许可证归属以原始项目及本仓库 LICENSE 文件为准。
██╗ ███████╗ █████╗ ███╗ ██╗ ██████╗████████╗██╗ ██╗ ██║ ██╔════╝██╔══██╗████╗ ██║ ██╔════╝╚══██╔══╝╚██╗██╔╝ ██║ █████╗ ███████║██╔██╗ ██║ ██║ ██║ ╚███╔╝ ██║ ██╔══╝ ██╔══██║██║╚██╗██║ ██║ ██║ ██╔██╗ ███████╗███████╗██║ ██║██║ ╚████║ ╚██████╗ ██║ ██╔╝ ██╗ ╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═╝
LeanCTX — 面向 AI 智能体的精简上下文工程(Lean Context Engineering)
LeanCTX — Lean Context 的缩写 — 是面向 AI 智能体的上下文工程层。它以单一本地二进制程序的形式运行在你的智能体与其所接触的一切之间 — 你的代码、Shell、数据以及模型本身:它决定它们读取什么,压缩它们发送的内容(可选的本地代理会缩小每一次请求 — 系统提示、历史记录与工具结果 — 且对 prompt cache 安全),记住它们所学,守护它们所接触的内容 — 并通过带签名的可验证节省账本证明它们节省了什么。结果是:token 减少 60–90%。 零配置。 本地优先(Local-first)。
| 问题 | 使用 LeanCTX |
|---|---|
| 重复读取文件:每次约 2000 tokens | 缓存后重读:约 13 tokens |
原始 git status:约 800 tokens |
压缩后:约 120 tokens |
| 每一轮都重新发送完整历史 | 代理压缩每次请求,对 prompt cache 安全 |
| 每次聊天上下文都会重置 | 会话记忆跨聊天持久保存 |
| 无法洞察上下文使用情况 | 实时仪表盘 + 预算控制 |
Website · Docs · Install · SDKs · Scenarios · Demo · Benchmarks · Cookbook · Security · Changelog
掌控你的 AI 能看到什么。 LeanCTX — Lean Context 的缩写 — 是面向 AI 智能体的上下文工程层:一个本地 Rust 二进制程序,决定你的智能体读取什么、压缩它们发送给模型的内容、记住它们所学、守护它们所接触的内容 — 并证明它们节省了什么。
Token 节省是收据,智能才是产品。可与 Cursor、Claude Code、Copilot、Windsurf、Codex、Gemini 及其他 30+ 智能体配合使用 — 无需配置。
眼见为实:
Read + Shell Map 模式读取 + 压缩后的 CLI 输出 |
Gain (live) 实时 token 与美元节省 |
Benchmark proof 按语言与模式测量压缩效果 |
所有 GIF 均由 demo/ 中可复现的 VHS 录像带生成。
lean-ctx setup 命令,无需更改配置帮你省了 token? 点个 Star — 帮助更多人发现 LeanCTX。
模型正在趋同于商品化。持久的优势不在于你调用哪一个模型 — 而在于你的上下文:智能体读取什么、记住什么,以及你能证明什么。而优化并拥有该上下文的层,不可能来自按 token 计费或将你的记忆锁在黑盒中的厂商 — 它必须站在你这一侧。
这就是「agent entities」浪潮背后的转变:它们活在你的聊天中并记住你的公司(Claude in Slack、ClickUp Brain)— 这是一种上下文登录,而非模型登录 — 你最终是在租回自己的公司知识。LeanCTX 是相反的一层。它让你的护城河归你所有:本地优先、可移植(.ctxpkg)、模型无关 — 切换 OpenAI、Anthropic 或 Gemini 而不丢失上下文或缓存。拥有你的上下文;不要把它租回来。
LeanCTX 将上下文视为受管资源,而非事后补救。一个二进制程序覆盖决定 AI 智能体实际表现优劣的四个维度:
你的 AI 智能体会读取文件并运行命令。LeanCTX 自动压缩两者。
full、map、signatures、diff、lines:N-M、density:X、…)— 缓存后重读仅需约 13 tokensdensity:0.4):SDE 风格预算压缩 — 保留最高熵行直至剩余约原 token 数的 40%,结果确定signatures 携带行跨度并指向 lines:N-M 以按需定向展开 — 先给大纲,正文按需获取ctx_expand、ctx_retrieve、带内标记或 GET /v1/references/{id} 按需取回原始字节。五种恢复路径 →并非每个文件都需要同等深度。LeanCTX 传递信号,过滤噪声。
ModePredictor:根据过往会话为各文件类型学习最优读取模式IntentEngine:对查询复杂度分类,让简单查找保持低成本上下文不再在聊天之间消失。
.ctxpkg 包,可在机器或模型间迁移,而非锁死在厂商黑箱中性能关乎准确性,而非仅速度。你始终掌控上下文窗口。
ctx_proof、ctx_verify):四层验证引擎,附带 CI 漂移门禁ctx_url_read):将公开网页、PDF 或 YouTube 转录稿拉入上下文,形成压缩且带引用的文本 — facts/quotes 返回带置信度评分 + 来源 URL 的断言,按相关性排序的研究压缩可精炼至 token 预算,SSRF 防护(仅 http/https)ctx_refactor):经语言服务器驱动的重命名、引用、跳转定义,支持 rust-analyzer、typescript-language-server、pylsp、goplsctx_agent、ctx_handoff):智能体交接含上下文传输包、日记系统、同步共享状态ctx_expand search_all):FTS5 驱动的跨归档全文搜索,覆盖所有此前归档的工具输出lean-ctx pack --pr 构建 PR 就绪上下文包(变更文件、相关测试、影响、产物)lean-ctx pack create 将 Knowledge + Graph + Session 打包为可移植的 .ctxpkg 文件,SHA-256 完整性校验lean-ctx snapshot create|list|show|verify|restore|publish|import — 以 git 为锚、ed25519 签名的层状态快照(lineage、ledger Φ、ROI、session),存于仅追加时间线;在仪表盘中回放,restore 恢复会话(--git 检出提交),或 publish/import 签名快照以共享(概念 →)lean-ctx gain --live 实时节省,lean-ctx wrapped 周/月摘要(gain --svg/--share 可分享卡片或自托管页面),lean-ctx watch TUI 监控lean-ctx savings 是可审计的逐事件账本(分词器透明、bounce-netting、防篡改 SHA-256 链)— 仅本地,默认开启lean-ctx serve 用于 Streamable HTTP MCP + /v1/tools/call(Cookbook + SDK 使用)你不必在 LeanCTX 与现有其他上下文工具之间二选一。addon 将任意 MCP 服务器封装在精简的 lean-ctx-addon.toml 清单中;LeanCTX 一条命令即在网关后运行它,并将其返回值当作自有读取处理,而非单纯代理。
lean-ctx addon search memory # browse the registry by category
lean-ctx addon add headroom # installs the upstream package + wires the MCP server, on add
lean-ctx addon list # what's wired into your gateway
addon add <name> 通过原生包管理器(uv、pip、cargo、npm、brew、dotnet)安装上游包,并将 MCP 服务器接入网关。无需 fork,无需重新编译。ctx_expand 句柄、索引至 BM25 / graph / knowledge。类型化适配器将特定工具直接路由至 ctx_expand、ctx_callgraph 和 ctx_knowledge。[addons] 策略将单机或集群固定为仅 verified、白名单或完全关闭,单个仓库无法覆盖。注册表涵盖压缩(Headroom、Sophon)、代码智能(Repomix、Serena)、记忆(Mem0、Cognee、Letta)与推理(Sequential Thinking)。参阅 addon 指南 或 浏览全部.
LeanCTX 正从单一上下文层成长为面向整支团队的完整认知上下文层:版本化的上下文策略、统一图谱,以及跨多智能体的治理层。
ctxpkg.com 注册表,用于托管、版本化的上下文历史,以及并排模型视图 | git-diff 回放。时间轴贯穿 LeanCTX 所做一切 — 它决策、记忆、守护、验证并回放。(概念 →)完整路线图见 VISION.md。
LeanCTX 在两个平面上运作 — 智能体读取什么,以及向模型发送什么:
read path: AI tool → (MCP tools + shell) → lean-ctx → your repo + CLI
wire path: AI tool → lean-ctx proxy → model provider (every request, compressed)
ctx_* 工具(读取模式、缓存、增量、搜索、记忆、多智能体)lean-ctx proxy enable 在智能体与模型之间放置本地代理,压缩每个请求 — 系统提示、完整历史与工具结果 — 提示缓存安全,并计量 USD 花费。还可跨 OpenAI、Anthropic 与 Gemini 固定单一推理力度级别(proxy.effort)而不破坏该缓存,通过缓存安全的冗长度引导加计量 holdout 削减输出 token,并将易变字段(日期、UUID、commit SHA)移出可缓存前缀,使稳定的系统提示终于可缓存。每次重写可逆(按内容寻址恢复),按契约字节稳定。与独立请求压缩代理(如 Headroom)同一层 — 无需再叠一层。# 1) Install (pick one)
curl -fsSL https://leanctx.com/install.sh | sh # universal (no Rust needed)
brew tap yvgude/lean-ctx && brew install lean-ctx # macOS / Linux
npm install -g lean-ctx-bin # Node.js
cargo install lean-ctx # Rust
pi install npm:pi-lean-ctx # Pi Coding Agent
# 2) One-command setup for your agent
lean-ctx wrap cursor # or: wrap claude / wrap codex / wrap vscode
# Done. Savings appear after your AI's first lean-ctx call.
lean-ctx gain
lean-ctx wrap 一条命令即可完成:安装 shell hooks、注册 MCP 服务器、配置 agent hooks、启动守护进程并验证连接。随时可用 lean-ctx unwrap cursor 撤销。
lean-ctx onboard # connect all detected AI tools (zero prompts)
lean-ctx setup # interactive wizard with every option
在 Windows 上从源码构建? 克隆仓库并在 PowerShell 中运行 ./install.ps1 —— 它会构建 release 二进制文件并安装到 Cargo 的 bin 目录(传入 -BuildOnly 可仅构建不安装)。
lean-ctx-offlean-ctx -c --raw "git status"~/.config/lean-ctx/config.toml 中设置 shell_activation = "agents-only".lean-ctx.toml(自动与全局配置合并)/workspace 的 Docker 项目:创建 .lean-ctx-id 并使用唯一名称,以避免上下文冲突lean-ctx updatelean-ctx doctor --json除 CLI 外,lean-ctx 还提供已发布的库,可直接从应用中调用。
即插即用的 prompt 压缩 — lean-ctx-sdk (npm). 在对话式 messages 数组到达任何模型之前进行压缩——确定性且对 prompt 缓存友好;图片、tool-calls 和 id 均原样透传。
# pip install lean-ctx-sdk
from lean_ctx import compress
messages = compress(messages, model="claude-sonnet-4")
// npm install lean-ctx-sdk
import { compress } from "lean-ctx-sdk";
messages = await compress(messages, { model: "gpt-4o" });
包含框架适配器(LiteLLM、LangChain、Vercel AI SDK)。→ compress() cookbook
轻量 /v1 契约客户端 — lean-ctx-client (npm · crates.io). 在进程边界上封装完整的 /v1 工具、事件与会话 API——不链接引擎,因此在 lean-ctx 演进时保持稳定。
pip install lean-ctx-client # Python (imports as `leanctx`)
npm install lean-ctx-client # TypeScript / Node
cargo add lean-ctx-client # Rust
使用 lean-ctx serve 启动服务器,然后将客户端指向它。→ API 参考
LeanCTX 会随你一起成长。以下是大多数人实际会经历的路径——每条都链接到 参考文档 中的完整、逐项功能讲解(所有 CLI 命令及全部 79 个 MCP 工具均记录于其中)。
🟢 最初 30 秒「刚装好——接下来做什么?」 一条命令即可安装 hooks、完成 MCP 注册并验证连接。 → 旅程 1 — 安装与入门 |
📖 日常编码「别再反复读同一批文件。」 你的 agent 自动读得更少、搜得更准。 → 旅程 2 — 日常使用 |
🧠 从上次中断处继续「新对话把之前全忘了。」 会话记忆 + 项目知识图谱可在多次对话间持久保存。 → 旅程 3 — 记忆与知识 |
🗺️ 理解新代码库「这个函数会影响到哪里?」 多边属性图(property graph)支撑影响分析 + 排序搜索。 → 旅程 4 — 代码智能 |
🔌 提供方与多仓库「拉取 GitHub issues 和我们的 Postgres schema。」 外部数据经同一整合流水线流入。 → 旅程 5 — 高级功能与集成 |
🛠️ 保持健康运行「更新、修复或干净卸载。」 自愈式诊断;精准卸载,仅移除自身相关块。 → 旅程 6 — 生命周期与故障排查 |
🎛️ 掌控上下文窗口「像高手一样规划上下文预算。」 Phi 评分规划 + 背包(knapsack)编译 + 上下文账本。 → 旅程 7 — 上下文工程 |
🤝 运行 agent 团队「同一仓库上的规划者 + 编码者 + 审查者。」 共享消息总线、日记、知识库及确定性交接。 → 旅程 8 — 多 Agent 协作 |
🏢 团队 / CI 共享「一套共享索引,在流水线中以无头模式运行。」 作用域 token、可选云同步、可验证的上下文门控。 → 旅程 9 — 团队、云与 CI |
🎚️ 调优与治理「让它完全按我们的方式运行。」 压缩级别、工具配置、主题与规则治理。 → 旅程 10 — 自定义与治理 |
📊 证明收益「给我看数据。」 所有分析均在 CLI/仪表板中——绝不消耗 agent token。 → 旅程 11 — 分析与洞察 |
📚 完整参考「我想通读全部内容。」 所有命令及全部 81 个 MCP 工具,按用户旅程组织,并附有 CLI 映射、 MCP 工具 与 路径与配置 附录。 → 参考索引 |
LeanCTX 是标准 MCP 服务器,可与任何兼容 MCP 的客户端配合使用。系统会按 agent 自动选择两种集成模式之一:
| 模式 | 工作原理 | 最适合 |
|---|---|---|
| Hybrid(混合) | MCP 用于缓存读取(约 13 tokens)+ shell hooks 压缩命令 | 具备 shell 访问权限的 agent(Cursor、Claude Code、Codex 等) |
| MCP | 通过 MCP 协议提供全部 80 个工具,无 shell hooks | 仅支持协议的 agent(JetBrains、VS Code、Zed 等) |
| 智能体 | 混合模式 | MCP | 设置 |
|---|---|---|---|
| Cursor | ● | lean-ctx init --agent cursor |
|
| Claude Code | ● | lean-ctx init --agent claude |
|
| CodeBuddy | ● | lean-ctx init --agent codebuddy |
|
| Augment CLI / VS Code | ● | lean-ctx init --agent augment |
|
| Codex CLI | ● | lean-ctx init --agent codex |
|
| Gemini CLI | ● | lean-ctx init --agent gemini |
|
| Windsurf | ● | lean-ctx init --agent windsurf |
|
| GitHub Copilot | ● | lean-ctx init --agent copilot |
|
| CRUSH | ● | lean-ctx init --agent crush |
|
| Hermes | ● | lean-ctx init --agent hermes |
|
| OpenCode | ● | lean-ctx init --agent opencode |
|
| Pi | ● | lean-ctx init --agent pi |
|
| Qoder | ● | lean-ctx init --agent qoder |
|
| Amp | ● | lean-ctx init --agent amp |
|
| Cline | ● | lean-ctx init --agent cline |
|
| Roo Code | ● | lean-ctx init --agent roo |
|
| Kiro | ● | lean-ctx init --agent kiro |
|
| Antigravity | ● | lean-ctx init --agent antigravity |
|
| Amazon Q | ● | lean-ctx init --agent amazonq |
|
| Qwen | ● | lean-ctx init --agent qwen |
|
| Trae | ● | lean-ctx init --agent trae |
|
| Verdent | ● | lean-ctx init --agent verdent |
|
| Aider | ● | lean-ctx init --agent aider |
|
| Continue | ● | lean-ctx init --agent continue |
|
| JetBrains IDEs | ● | lean-ctx init --agent jetbrains |
|
| QoderWork | ● | lean-ctx init --agent qoderwork |
|
| VS Code | ● | lean-ctx init --agent vscode |
|
| Zed | ● | lean-ctx init --agent zed |
|
| Neovim | ● | lean-ctx init --agent neovim |
|
| Emacs | ● | lean-ctx init --agent emacs |
|
| Sublime Text | ● | lean-ctx init --agent sublime |
任何兼容 MCP 的客户端均可开箱即用 — 上表列出的是支持一流自动配置的智能体。
非常适合,如果你……
可以跳过,如果你……
--raw,但投资回报率较低)实话实说的细节:收益取决于三个杠杆 — 覆盖范围(通过代理/引擎掌控窗口,而不仅是 ctx_* 工具层)、上下文生命周期(一个长生命周期会话 vs. 每个阶段一个新进程),以及提供商定价(按 prompt cache 计价 vs. 每轮重新计费)。三者对齐时叠加为明显收益,不对齐时净效果为收支平衡。完整分析与各场景的调优方法见收益 vs. 收支平衡矩阵。
可在任意仓库中尝试:
lean-ctx read rust/src/server/mod.rs -m map
lean-ctx -c "git log -n 5 --oneline"
lean-ctx gain --live
lean-ctx dashboard # Context Manager (browser)
lean-ctx watch # TUI monitor
lean-ctx benchmark report .
demo/vhs demo/leanctx.tape
vhs demo/gain.tape
vhs demo/benchmark.tape
真实、可复现的数据 — 从不估算。在本仓库上使用 GPT-4o 分词器(o200k_base)测量;未安装的工具会如实报告,从不猜测。
| 读取模式 | 压缩率 | Token 数(50 个文件) | 质量 |
|---|---|---|---|
| Raw read | 0% | 533.2K | 100% |
map |
98.1% | 8.0K | 78% |
signatures |
96.7% | 14.0K | 96% |
| Cached re-read | ~99.99% | ~13 tok | 100% |
lean-ctx 自身成本也有测量:其注入的固定每会话占用(公布的工具 schema + MCP 指令)约为 2.1K token,并通过 lean-ctx doctor overhead --gate 进行 CI 门禁,因此只会缩减。长生命周期代理通道还有确定性自验证 — lean-ctx benchmark dual-arm --json 重放 15 轮会话并按模型计价(摘要 f5ed145e61ce3689,在按 cache 计价的通道上输入侧节省 99.4%;方法论:bench/agent-task/r2)。
准确性不是凭感觉:有损阶段均受 CI 门禁约束。无模型的 A/B 门禁证明 JSON crusher 在削减 token 的同时保留每一个黄金答案,且代理重写按合约保持字节稳定,因此 Anthropic(90%)/ OpenAI(50%)的 prompt-cache 折扣在压缩后依然有效。确定性 关闭 vs. 开启测试台(lean-ctx eval testbench)将证明扩展到答案:它在相同 token 预算下,让固定的真实仓库分别经过 raw-dump 基线与 lean-ctx,用 LLM 评判器对自由形式问答评分、用各仓库自有测试对代码评分,并输出 FINDINGS.md(token / 轮次 / 墙钟时间 / 质量)及回归文件 — 其中包含已提交的录制子集,任何回归都会阻断 CI。
lean-ctx benchmark report .update_check_disabled = true 或 LEAN_CTX_NO_UPDATE_CHECK=1)详见 SECURITY.md。
一条命令即可移除一切 — 停止所有进程,然后删除 hooks、编辑器配置、规则、自启动项(LaunchAgent/systemd)、数据目录,以及二进制文件本身:
lean-ctx uninstall # full clean removal
lean-ctx uninstall --dry-run # preview every change, write nothing
lean-ctx uninstall --keep-config # keep MCP configs + rules (for reinstall)
lean-ctx-off # or just disable for the current shell session
PATH 上没有二进制文件(或你使用了 curl 安装器)?从安装器运行相同的移除流程:
curl -fsSL https://leanctx.com/install.sh | sh -s -- --uninstall
若通过包管理器安装,uninstall 会移除其写入的一切,并告知你完成删除二进制文件所需的一条命令:
brew uninstall lean-ctx # Homebrew
cargo uninstall lean-ctx # cargo install
npm uninstall -g lean-ctx-bin # npm
pi uninstall npm:pi-lean-ctx # Pi Coding Agent
请从 CONTRIBUTING.md 开始。适合新手的首个 PR:通过 issue 模板 提议新的 CLI 压缩模式(compression pattern)。
Apache License 2.0 — 详见 LICENSE。