[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-mksglu--context-mode":3,"tool-mksglu--context-mode":64},[4,17,25,39,48,56],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":16},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",138956,2,"2026-04-05T11:33:21",[13,14,15],"开发框架","Agent","语言模型","ready",{"id":18,"name":19,"github_repo":20,"description_zh":21,"stars":22,"difficulty_score":10,"last_commit_at":23,"category_tags":24,"status":16},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[13,15],{"id":26,"name":27,"github_repo":28,"description_zh":29,"stars":30,"difficulty_score":10,"last_commit_at":31,"category_tags":32,"status":16},2268,"ML-For-Beginners","microsoft\u002FML-For-Beginners","ML-For-Beginners 是由微软推出的一套系统化机器学习入门课程，旨在帮助零基础用户轻松掌握经典机器学习知识。这套课程将学习路径规划为 12 周，包含 26 节精炼课程和 52 道配套测验，内容涵盖从基础概念到实际应用的完整流程，有效解决了初学者面对庞大知识体系时无从下手、缺乏结构化指导的痛点。\n\n无论是希望转型的开发者、需要补充算法背景的研究人员，还是对人工智能充满好奇的普通爱好者，都能从中受益。课程不仅提供了清晰的理论讲解，还强调动手实践，让用户在循序渐进中建立扎实的技能基础。其独特的亮点在于强大的多语言支持，通过自动化机制提供了包括简体中文在内的 50 多种语言版本，极大地降低了全球不同背景用户的学习门槛。此外，项目采用开源协作模式，社区活跃且内容持续更新，确保学习者能获取前沿且准确的技术资讯。如果你正寻找一条清晰、友好且专业的机器学习入门之路，ML-For-Beginners 将是理想的起点。",84991,"2026-04-05T10:45:23",[33,34,35,36,14,37,15,13,38],"图像","数据工具","视频","插件","其他","音频",{"id":40,"name":41,"github_repo":42,"description_zh":43,"stars":44,"difficulty_score":45,"last_commit_at":46,"category_tags":47,"status":16},3128,"ragflow","infiniflow\u002Fragflow","RAGFlow 是一款领先的开源检索增强生成（RAG）引擎，旨在为大语言模型构建更精准、可靠的上下文层。它巧妙地将前沿的 RAG 技术与智能体（Agent）能力相结合，不仅支持从各类文档中高效提取知识，还能让模型基于这些知识进行逻辑推理和任务执行。\n\n在大模型应用中，幻觉问题和知识滞后是常见痛点。RAGFlow 通过深度解析复杂文档结构（如表格、图表及混合排版），显著提升了信息检索的准确度，从而有效减少模型“胡编乱造”的现象，确保回答既有据可依又具备时效性。其内置的智能体机制更进一步，使系统不仅能回答问题，还能自主规划步骤解决复杂问题。\n\n这款工具特别适合开发者、企业技术团队以及 AI 研究人员使用。无论是希望快速搭建私有知识库问答系统，还是致力于探索大模型在垂直领域落地的创新者，都能从中受益。RAGFlow 提供了可视化的工作流编排界面和灵活的 API 接口，既降低了非算法背景用户的上手门槛，也满足了专业开发者对系统深度定制的需求。作为基于 Apache 2.0 协议开源的项目，它正成为连接通用大模型与行业专有知识之间的重要桥梁。",77062,3,"2026-04-04T04:44:48",[14,33,13,15,37],{"id":49,"name":50,"github_repo":51,"description_zh":52,"stars":53,"difficulty_score":45,"last_commit_at":54,"category_tags":55,"status":16},519,"PaddleOCR","PaddlePaddle\u002FPaddleOCR","PaddleOCR 是一款基于百度飞桨框架开发的高性能开源光学字符识别工具包。它的核心能力是将图片、PDF 等文档中的文字提取出来，转换成计算机可读取的结构化数据，让机器真正“看懂”图文内容。\n\n面对海量纸质或电子文档，PaddleOCR 解决了人工录入效率低、数字化成本高的问题。尤其在人工智能领域，它扮演着连接图像与大型语言模型（LLM）的桥梁角色，能将视觉信息直接转化为文本输入，助力智能问答、文档分析等应用场景落地。\n\nPaddleOCR 适合开发者、算法研究人员以及有文档自动化需求的普通用户。其技术优势十分明显：不仅支持全球 100 多种语言的识别，还能在 Windows、Linux、macOS 等多个系统上运行，并灵活适配 CPU、GPU、NPU 等各类硬件。作为一个轻量级且社区活跃的开源项目，PaddleOCR 既能满足快速集成的需求，也能支撑前沿的视觉语言研究，是处理文字识别任务的理想选择。",74913,"2026-04-05T10:44:17",[15,33,13,37],{"id":57,"name":58,"github_repo":59,"description_zh":60,"stars":61,"difficulty_score":45,"last_commit_at":62,"category_tags":63,"status":16},2181,"OpenHands","OpenHands\u002FOpenHands","OpenHands 是一个专注于 AI 驱动开发的开源平台，旨在让智能体（Agent）像人类开发者一样理解、编写和调试代码。它解决了传统编程中重复性劳动多、环境配置复杂以及人机协作效率低等痛点，通过自动化流程显著提升开发速度。\n\n无论是希望提升编码效率的软件工程师、探索智能体技术的研究人员，还是需要快速原型验证的技术团队，都能从中受益。OpenHands 提供了灵活多样的使用方式：既可以通过命令行（CLI）或本地图形界面在个人电脑上轻松上手，体验类似 Devin 的流畅交互；也能利用其强大的 Python SDK 自定义智能体逻辑，甚至在云端大规模部署上千个智能体并行工作。\n\n其核心技术亮点在于模块化的软件智能体 SDK，这不仅构成了平台的引擎，还支持高度可组合的开发模式。此外，OpenHands 在 SWE-bench 基准测试中取得了 77.6% 的优异成绩，证明了其解决真实世界软件工程问题的能力。平台还具备完善的企业级功能，支持与 Slack、Jira 等工具集成，并提供细粒度的权限管理，适合从个人开发者到大型企业的各类用户场景。",70612,"2026-04-05T11:12:22",[15,14,13,36],{"id":65,"github_repo":66,"name":67,"description_en":68,"description_zh":69,"ai_summary_zh":69,"readme_en":70,"readme_zh":71,"quickstart_zh":72,"use_case_zh":73,"hero_image_url":74,"owner_login":75,"owner_name":76,"owner_avatar_url":77,"owner_bio":78,"owner_company":79,"owner_location":80,"owner_email":81,"owner_twitter":75,"owner_website":82,"owner_url":83,"languages":84,"stars":97,"forks":98,"last_commit_at":99,"license":100,"difficulty_score":10,"env_os":101,"env_gpu":102,"env_ram":102,"env_deps":103,"category_tags":109,"github_topics":110,"view_count":10,"oss_zip_url":79,"oss_zip_packed_at":79,"status":16,"created_at":122,"updated_at":123,"faqs":124,"releases":153},2399,"mksglu\u002Fcontext-mode","context-mode","Privacy-first. MCP is the protocol for tool access. We're the virtualization layer for context.","context-mode 是一款专为 AI 代理设计的隐私优先型上下文管理工具，旨在解决大模型在长对话中因工具调用导致上下文窗口迅速耗尽的痛点。当 AI 频繁调用外部工具（如抓取网页、读取日志）时，原始数据往往占用大量令牌空间，迫使系统在压缩对话时丢失关键任务状态。\n\ncontext-mode 通过两层机制巧妙化解这一难题：一是“沙盒化”工具调用，将原始数据隔离在上下文窗口之外，仅保留极小的摘要信息，可实现高达 98% 的上下文节省；二是利用 SQLite 数据库持续追踪文件编辑、Git 操作及用户决策等会话状态。即使对话历史被压缩，它也能通过全文检索技术精准召回相关信息，确保 AI 能无缝接续之前的工作进度，同时支持会话结束后自动清除数据以保障隐私。\n\n该工具特别适合依赖 MCP 协议进行复杂开发的程序员、需要长时间维持任务状态的 AI 工程师以及重度使用 Claude Code 等智能编码助手的开发者。其独特之处在于不仅大幅降低了 Token 消耗，更通过结构化存储与语义检索的结合，让 AI 代理拥有了真正的“长期记忆”，在保护隐私的前提下显著提升了多轮交互的连贯性与效率。","# Context Mode\n\n**The other half of the context problem.**\n\n[![users](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fcdn.jsdelivr.net%2Fgh%2Fmksglu%2Fcontext-mode%40main%2Fstats.json&query=%24.message&label=users&color=brightgreen)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fcontext-mode) [![npm](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fcdn.jsdelivr.net%2Fgh%2Fmksglu%2Fcontext-mode%40main%2Fstats.json&query=%24.npm&label=npm&color=blue)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fcontext-mode) [![marketplace](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fcdn.jsdelivr.net%2Fgh%2Fmksglu%2Fcontext-mode%40main%2Fstats.json&query=%24.marketplace&label=marketplace&color=blue)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode) [![GitHub stars](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Fstars\u002Fmksglu\u002Fcontext-mode?style=flat&color=yellow)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fstargazers) [![GitHub forks](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Fforks\u002Fmksglu\u002Fcontext-mode?style=flat&color=blue)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fnetwork\u002Fmembers) [![Last commit](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Flast-commit\u002Fmksglu\u002Fcontext-mode?color=green)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fcommits) [![License: ELv2](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-ELv2-blue.svg)](LICENSE)\n[![Discord](https:\u002F\u002Fimg.shields.io\u002Fdiscord\u002F1478479412700909750?label=Discord&logo=discord&color=5865f2)](https:\u002F\u002Fdiscord.gg\u002FDCN9jUgN5v)\n\n## The Problem\n\nEvery MCP tool call dumps raw data into your context window. A Playwright snapshot costs 56 KB. Twenty GitHub issues cost 59 KB. One access log — 45 KB. After 30 minutes, 40% of your context is gone. And when the agent compacts the conversation to free space, it forgets which files it was editing, what tasks are in progress, and what you last asked for.\n\nContext Mode is an MCP server that solves both halves of this problem:\n\n1. **Context Saving** — Sandbox tools keep raw data out of the context window. 315 KB becomes 5.4 KB. 98% reduction.\n2. **Session Continuity** — Every file edit, git operation, task, error, and user decision is tracked in SQLite. When the conversation compacts, context-mode doesn't dump this data back into context — it indexes events into FTS5 and retrieves only what's relevant via BM25 search. The model picks up exactly where you left off. If you don't `--continue`, previous session data is deleted immediately — a fresh session means a clean slate.\n\nhttps:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002F07013dbf-07c0-4ef1-974a-33ea1207637b\n\n## Install\n\nPlatforms are grouped by install complexity. Hook-capable platforms get automatic routing enforcement. Non-hook platforms need a one-time routing file copy.\n\n\u003Cdetails open>\n\u003Csummary>\u003Cstrong>Claude Code\u003C\u002Fstrong> — plugin marketplace, fully automatic\u003C\u002Fsummary>\n\n**Prerequisites:** Claude Code v1.0.33+ (`claude --version`). If `\u002Fplugin` is not recognized, update first: `brew upgrade claude-code` or `npm update -g @anthropic-ai\u002Fclaude-code`.\n\n**Install:**\n\n```bash\n\u002Fplugin marketplace add mksglu\u002Fcontext-mode\n\u002Fplugin install context-mode@context-mode\n```\n\nRestart Claude Code (or run `\u002Freload-plugins`).\n\n**Verify:**\n\n```\n\u002Fcontext-mode:ctx-doctor\n```\n\nAll checks should show `[x]`. The doctor validates runtimes, hooks, FTS5, and plugin registration.\n\n**Routing:** Automatic. The SessionStart hook injects routing instructions at runtime — no file is written to your project. The plugin registers all hooks (PreToolUse, PostToolUse, PreCompact, SessionStart) and 6 sandbox tools (`ctx_batch_execute`, `ctx_execute`, `ctx_execute_file`, `ctx_index`, `ctx_search`, `ctx_fetch_and_index`).\n\n| Slash Command | What it does |\n|---|---|\n| `\u002Fcontext-mode:ctx-stats` | Context savings — per-tool breakdown, tokens consumed, savings ratio. |\n| `\u002Fcontext-mode:ctx-doctor` | Diagnostics — runtimes, hooks, FTS5, plugin registration, versions. |\n| `\u002Fcontext-mode:ctx-upgrade` | Pull latest, rebuild, migrate cache, fix hooks. |\n\n> **Note:** Slash commands are a Claude Code plugin feature. On other platforms, type `ctx stats`, `ctx doctor`, or `ctx upgrade` in the chat — the model calls the MCP tool automatically. See [Utility Commands](#utility-commands).\n\n\u003Cdetails>\n\u003Csummary>Alternative — MCP-only install (no hooks or slash commands)\u003C\u002Fsummary>\n\n```bash\nclaude mcp add context-mode -- npx -y context-mode\n```\n\nThis gives you the 6 sandbox tools without automatic routing. The model can still use them — it just won't be nudged to prefer them over raw Bash\u002FRead\u002FWebFetch. Good for trying it out before committing to the full plugin.\n\n\u003C\u002Fdetails>\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Gemini CLI\u003C\u002Fstrong> — one config file, hooks included\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Gemini CLI installed.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add the following to `~\u002F.gemini\u002Fsettings.json`. This single file registers the MCP server and all four hooks:\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     },\n     \"hooks\": {\n       \"BeforeTool\": [\n         {\n           \"matcher\": \"run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli beforetool\" }]\n         }\n       ],\n       \"AfterTool\": [\n         {\n           \"matcher\": \"\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli aftertool\" }]\n         }\n       ],\n       \"PreCompress\": [\n         {\n           \"matcher\": \"\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli precompress\" }]\n         }\n       ],\n       \"SessionStart\": [\n         {\n           \"matcher\": \"\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli sessionstart\" }]\n         }\n       ]\n     }\n   }\n   ```\n\n3. Restart Gemini CLI.\n\n**Verify:**\n\n```\n\u002Fmcp list\n```\n\nYou should see `context-mode: ... - Connected`.\n\n**Routing:** Automatic. The SessionStart hook injects routing instructions at runtime — no `GEMINI.md` file is written to your project. All four hooks (BeforeTool, AfterTool, PreCompress, SessionStart) handle enforcement programmatically.\n\n> **Why the BeforeTool matcher?** It targets only tools that produce large output (`run_shell_command`, `read_file`, `read_many_files`, `grep_search`, `search_file_content`, `web_fetch`, `activate_skill`) plus context-mode's own tools (`mcp__plugin_context-mode`). This avoids unnecessary hook overhead on lightweight tools while intercepting every tool that could flood your context window.\n\nFull config reference: [`configs\u002Fgemini-cli\u002Fsettings.json`](configs\u002Fgemini-cli\u002Fsettings.json)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>VS Code Copilot\u003C\u002Fstrong> — hooks with SessionStart\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, VS Code with Copilot Chat v0.32+.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Create `.vscode\u002Fmcp.json` in your project root:\n\n   ```json\n   {\n     \"servers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. Create `.github\u002Fhooks\u002Fcontext-mode.json`:\n\n   ```json\n   {\n     \"hooks\": {\n       \"PreToolUse\": [\n         { \"type\": \"command\", \"command\": \"context-mode hook vscode-copilot pretooluse\" }\n       ],\n       \"PostToolUse\": [\n         { \"type\": \"command\", \"command\": \"context-mode hook vscode-copilot posttooluse\" }\n       ],\n       \"SessionStart\": [\n         { \"type\": \"command\", \"command\": \"context-mode hook vscode-copilot sessionstart\" }\n       ]\n     }\n   }\n   ```\n\n4. Restart VS Code.\n\n**Verify:** Open Copilot Chat and type `ctx stats`. Context-mode tools should appear and respond.\n\n**Routing:** Automatic. The SessionStart hook injects routing instructions at runtime — no `copilot-instructions.md` file is written to your project.\n\nFull hook config including PreCompact: [`configs\u002Fvscode-copilot\u002Fhooks.json`](configs\u002Fvscode-copilot\u002Fhooks.json)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Cursor\u003C\u002Fstrong> — hooks with stop support\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Cursor with agent mode.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Create `.cursor\u002Fmcp.json` in your project root (or `~\u002F.cursor\u002Fmcp.json` for global):\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. Create `.cursor\u002Fhooks.json` (or `~\u002F.cursor\u002Fhooks.json` for global):\n\n   ```json\n   {\n     \"version\": 1,\n     \"hooks\": {\n       \"preToolUse\": [\n         {\n           \"command\": \"context-mode hook cursor pretooluse\",\n           \"matcher\": \"Shell|Read|Grep|WebFetch|Task|MCP:ctx_execute|MCP:ctx_execute_file|MCP:ctx_batch_execute\"\n         }\n       ],\n       \"postToolUse\": [\n         {\n           \"command\": \"context-mode hook cursor posttooluse\"\n         }\n       ],\n       \"stop\": [\n         {\n           \"command\": \"context-mode hook cursor stop\"\n         }\n       ]\n     }\n   }\n   ```\n\n   The `preToolUse` matcher is optional — without it, the hook fires on all tools. The `stop` hook fires when the agent turn ends and can send a followup message to continue the loop. `afterAgentResponse` is also available (fire-and-forget, receives full response text).\n\n4. Copy the routing rules file. Cursor lacks a SessionStart hook, so the model needs a rules file for routing awareness:\n\n   ```bash\n   mkdir -p .cursor\u002Frules\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcursor\u002Fcontext-mode.mdc .cursor\u002Frules\u002Fcontext-mode.mdc\n   ```\n\n5. Restart Cursor or open a new agent session.\n\n**Verify:** Open Cursor Settings > MCP and confirm \"context-mode\" shows as connected. In agent chat, type `ctx stats`.\n\n**Routing:** Hooks enforce routing programmatically via `preToolUse`\u002F`postToolUse`\u002F`stop`. The `.cursor\u002Frules\u002Fcontext-mode.mdc` file provides routing instructions at session start since Cursor's `sessionStart` hook is currently rejected by their validator ([forum report](https:\u002F\u002Fforum.cursor.com\u002Ft\u002Funknown-hook-type-sessionstart\u002F149566)). Project `.cursor\u002Fhooks.json` overrides `~\u002F.cursor\u002Fhooks.json`.\n\nFull configs: [`configs\u002Fcursor\u002Fhooks.json`](configs\u002Fcursor\u002Fhooks.json) | [`configs\u002Fcursor\u002Fmcp.json`](configs\u002Fcursor\u002Fmcp.json) | [`configs\u002Fcursor\u002Fcontext-mode.mdc`](configs\u002Fcursor\u002Fcontext-mode.mdc)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>OpenCode\u003C\u002Fstrong> — TypeScript plugin with hooks\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, OpenCode installed.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add to `opencode.json` in your project root (or `~\u002F.config\u002Fopencode\u002Fopencode.json` for global):\n\n   ```json\n   {\n     \"$schema\": \"https:\u002F\u002Fopencode.ai\u002Fconfig.json\",\n     \"mcp\": {\n       \"context-mode\": {\n         \"type\": \"local\",\n         \"command\": [\"context-mode\"]\n       }\n     },\n     \"plugin\": [\"context-mode\"]\n   }\n   ```\n\n   The `mcp` entry registers the 6 sandbox tools. The `plugin` entry enables hooks — OpenCode calls the plugin's TypeScript functions directly before and after each tool execution, blocking dangerous commands and enforcing sandbox routing.\n\n3. *(Optional)* Copy the routing rules file. OpenCode lacks a SessionStart hook, so the model needs an `AGENTS.md` file for routing awareness:\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fopencode\u002FAGENTS.md AGENTS.md\n   ```\n\n   This tells the model which tools to use and which commands are blocked. Without it, hooks still enforce routing — but the model won't know *why* a command was denied.\n\n4. Restart OpenCode.\n\n**Verify:** In the OpenCode session, type `ctx stats`. Context-mode tools should appear and respond.\n\n**Routing:** Hooks enforce routing programmatically via `tool.execute.before` and `tool.execute.after`. The optional [`AGENTS.md`](configs\u002Fopencode\u002FAGENTS.md) file provides routing instructions for model awareness. The `experimental.session.compacting` hook builds resume snapshots when the conversation compacts.\n\n> **Note:** OpenCode's SessionStart hook is not yet available ([#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)), so startup\u002Fresume session restore is not supported. Compaction recovery works fully via the plugin.\n\nFull configs: [`configs\u002Fopencode\u002Fopencode.json`](configs\u002Fopencode\u002Fopencode.json) | [`configs\u002Fopencode\u002FAGENTS.md`](configs\u002Fopencode\u002FAGENTS.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>KiloCode\u003C\u002Fstrong> — TypeScript plugin with hooks\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, KiloCode installed.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add to `kilo.json` in your project root (or `~\u002F.config\u002Fkilo\u002Fkilo.json` for global):\n\n   ```json\n   {\n     \"$schema\": \"https:\u002F\u002Fapp.kilo.ai\u002Fconfig.json\",\n     \"mcp\": {\n       \"context-mode\": {\n         \"type\": \"local\",\n         \"command\": [\"context-mode\"]\n       }\n     },\n     \"plugin\": [\"context-mode\"]\n   }\n   ```\n\n   The `mcp` entry registers the 6 sandbox tools. The `plugin` entry enables hooks — KiloCode calls the plugin's TypeScript functions directly before and after each tool execution, blocking dangerous commands and enforcing sandbox routing.\n\n3. *(Optional)* Copy the routing rules file. KiloCode shares the OpenCode plugin architecture and lacks SessionStart, so the model needs an `AGENTS.md` file for routing awareness:\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fopencode\u002FAGENTS.md AGENTS.md\n   ```\n\n4. Restart KiloCode.\n\n**Verify:** In the KiloCode session, type `ctx stats`. Context-mode tools should appear and respond.\n\n**Routing:** Hooks enforce routing programmatically via `tool.execute.before` and `tool.execute.after`. The optional [`AGENTS.md`](configs\u002Fopencode\u002FAGENTS.md) file provides routing instructions for model awareness. The `experimental.session.compacting` hook builds resume snapshots when the conversation compacts.\n\n> **Note:** KiloCode shares the same plugin architecture as OpenCode, using the OpenCodeAdapter with platform-specific configuration paths (`kilo.json` instead of `opencode.json`, `~\u002F.config\u002Fkilo\u002F` instead of `~\u002F.config\u002Fopencode\u002F`). SessionStart hook availability depends on KiloCode's implementation.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>OpenClaw \u002F Pi Agent\u003C\u002Fstrong> — native gateway plugin\u003C\u002Fsummary>\n\n**Prerequisites:** OpenClaw gateway running ([>2026.1.29](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw\u002Fpull\u002F9761)), Node.js 22+.\n\ncontext-mode runs as a native [OpenClaw](https:\u002F\u002Fgithub.com\u002Fopenclaw) gateway plugin, targeting **Pi Agent** sessions (Read\u002FWrite\u002FEdit\u002FBash tools). Unlike other platforms, there's no separate MCP server — the plugin registers directly into the gateway runtime via OpenClaw's [plugin API](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin).\n\n**Install:**\n\n1. Clone and install:\n\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode.git\n   cd context-mode\n   npm run install:openclaw\n   ```\n\n   The installer uses `$OPENCLAW_STATE_DIR` from your environment (default: `\u002Fopenclaw`). To specify a custom path:\n\n   ```bash\n   npm run install:openclaw -- \u002Fpath\u002Fto\u002Fopenclaw-state\n   ```\n\n   Common locations: **Docker** — `\u002Fopenclaw` (the default). **Local** — `~\u002F.openclaw` or wherever you set `OPENCLAW_STATE_DIR`.\n\n   The installer handles everything: `npm install`, `npm run build`, `better-sqlite3` native rebuild, extension registration in `runtime.json`, and gateway restart via SIGUSR1.\n\n2. Open a Pi Agent session.\n\n**Verify:** The plugin registers 8 hooks via [`api.on()`](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin) (lifecycle) and [`api.registerHook()`](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin) (commands). Type `ctx stats` to confirm tools are loaded.\n\n**Routing:** Automatic. All tool interception, session tracking, and compaction recovery hooks activate automatically — no manual hook configuration or routing file needed.\n\n> **Minimum version:** OpenClaw >2026.1.29 — this includes the `api.on()` lifecycle fix from [PR #9761](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw\u002Fpull\u002F9761). On older versions, lifecycle hooks silently fail. The adapter falls back to DB snapshot reconstruction (less precise but preserves critical state).\n\nFull documentation: [`docs\u002Fadapters\u002Fopenclaw.md`](docs\u002Fadapters\u002Fopenclaw.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Codex CLI\u003C\u002Fstrong> — hooks + MCP\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Codex CLI installed.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add to `~\u002F.codex\u002Fconfig.toml`:\n\n   ```toml\n   [mcp_servers.context-mode]\n   command = \"context-mode\"\n   ```\n\n3. Add hooks for routing enforcement and session tracking. Create `~\u002F.codex\u002Fhooks.json`:\n\n   ```json\n   {\n     \"hooks\": {\n       \"PreToolUse\": [{ \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook codex pretooluse\" }] }],\n       \"PostToolUse\": [{ \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook codex posttooluse\" }] }],\n       \"SessionStart\": [{ \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook codex sessionstart\" }] }]\n     }\n   }\n   ```\n\n   `PreToolUse` enforces sandbox routing (blocks dangerous commands, redirects to MCP tools). `PostToolUse` captures session events. `SessionStart` restores state after compaction.\n\n4. Copy routing instructions (recommended even with hooks for full routing awareness):\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcodex\u002FAGENTS.md .\u002FAGENTS.md\n   ```\n\n   For global use: `cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcodex\u002FAGENTS.md ~\u002F.codex\u002FAGENTS.md`. Global applies to all projects. If both exist, Codex CLI merges them.\n\n5. Restart Codex CLI.\n\n**Verify:** Start a session and type `ctx stats`. Context-mode tools should appear and respond.\n\n**Routing:** Hooks enforce routing programmatically via PreToolUse. PostToolUse tracks session events. SessionStart restores state. The optional AGENTS.md file provides routing instructions for model awareness. Codex CLI's hook system uses the same JSON stdin\u002Fstdout wire protocol as Claude Code but does not support arg or output modification.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Antigravity\u003C\u002Fstrong> — MCP-only, no hooks\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Antigravity installed.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add to `~\u002F.gemini\u002Fantigravity\u002Fmcp_config.json`:\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. Copy routing instructions (Antigravity has no hook support):\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fantigravity\u002FGEMINI.md .\u002FGEMINI.md\n   ```\n\n4. Restart Antigravity.\n\n**Verify:** In an Antigravity session, type `ctx stats`. Context-mode tools should appear and respond.\n\n**Routing:** Manual. The `GEMINI.md` file is the only enforcement method (~60% compliance). There is no programmatic interception. Auto-detected via MCP protocol handshake (`clientInfo.name`) — no manual platform configuration needed.\n\nFull configs: [`configs\u002Fantigravity\u002Fmcp_config.json`](configs\u002Fantigravity\u002Fmcp_config.json) | [`configs\u002Fantigravity\u002FGEMINI.md`](configs\u002Fantigravity\u002FGEMINI.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Kiro\u003C\u002Fstrong> — hooks with steering file\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Kiro with MCP enabled (Settings > search \"MCP\").\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add to `.kiro\u002Fsettings\u002Fmcp.json` in your project (or `~\u002F.kiro\u002Fsettings\u002Fmcp.json` for global):\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. Create `.kiro\u002Fhooks\u002Fcontext-mode.json`:\n\n   ```json\n   {\n     \"name\": \"context-mode\",\n     \"description\": \"Context-mode hooks for context window protection\",\n     \"hooks\": {\n       \"preToolUse\": [\n         { \"matcher\": \"*\", \"command\": \"context-mode hook kiro pretooluse\" }\n       ],\n       \"postToolUse\": [\n         { \"matcher\": \"*\", \"command\": \"context-mode hook kiro posttooluse\" }\n       ]\n     }\n   }\n   ```\n\n4. Copy routing instructions. Kiro's `agentSpawn` (SessionStart) is not yet implemented, so the model needs a routing file at session start:\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fkiro\u002FKIRO.md .\u002FKIRO.md\n   ```\n\n5. Restart Kiro.\n\n**Verify:** Open the Kiro panel > MCP Servers tab and confirm \"context-mode\" shows a green status indicator. In chat, type `ctx stats`.\n\n**Routing:** Hooks enforce routing programmatically via `preToolUse`\u002F`postToolUse`. The `KIRO.md` file provides routing instructions since `agentSpawn` (SessionStart equivalent) is not yet wired. Tool names appear as `@context-mode\u002Fctx_batch_execute`, `@context-mode\u002Fctx_search`, etc. Auto-detected via MCP protocol handshake.\n\nFull configs: [`configs\u002Fkiro\u002Fmcp.json`](configs\u002Fkiro\u002Fmcp.json) | [`configs\u002Fkiro\u002Fagent.json`](configs\u002Fkiro\u002Fagent.json) | [`configs\u002Fkiro\u002FKIRO.md`](configs\u002Fkiro\u002FKIRO.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Zed\u003C\u002Fstrong> — MCP-only, no hooks\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Zed installed.\n\n**Install:**\n\n1. Install context-mode globally:\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. Add to `~\u002F.config\u002Fzed\u002Fsettings.json` (Windows: `%APPDATA%\\Zed\\settings.json`):\n\n   ```json\n   {\n     \"context_servers\": {\n       \"context-mode\": {\n         \"command\": {\n           \"path\": \"context-mode\"\n         }\n       }\n     }\n   }\n   ```\n\n   Note: Zed uses `\"context_servers\"` and `\"command\": { \"path\": \"...\" }` syntax, not `\"mcpServers\"` or `\"command\": \"...\"` like other platforms.\n\n3. Copy routing instructions (Zed has no hook support):\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fzed\u002FAGENTS.md .\u002FAGENTS.md\n   ```\n\n4. Restart Zed (or save `settings.json` — Zed auto-restarts context servers on config change).\n\n**Verify:** Open the Agent Panel (`Cmd+Shift+A`), go to settings, and check the indicator dot next to \"context-mode\" — green means active. Type `ctx stats` in the agent chat.\n\n**Routing:** Manual. The `AGENTS.md` file is the only enforcement method (~60% compliance). There is no programmatic interception. Tool names appear as `mcp:context-mode:ctx_batch_execute`, `mcp:context-mode:ctx_search`, etc. Auto-detected via MCP protocol handshake.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Pi Coding Agent\u003C\u002Fstrong> — extension with full hook support\u003C\u002Fsummary>\n\n**Prerequisites:** Node.js 18+, Pi Coding Agent installed.\n\n**Install:**\n\n1. Clone the extension:\n\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode.git ~\u002F.pi\u002Fextensions\u002Fcontext-mode\n   cd ~\u002F.pi\u002Fextensions\u002Fcontext-mode\n   npm install\n   npm run build\n   ```\n\n2. Add to `~\u002F.pi\u002Fagent\u002Fmcp.json` (or `.pi\u002Fmcp.json` for project-level):\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"node\",\n         \"args\": [\"\u002Fhome\u002Fyouruser\u002F.pi\u002Fextensions\u002Fcontext-mode\u002Fnode_modules\u002Fcontext-mode\u002Fstart.mjs\"]\n       }\n     }\n   }\n   ```\n\n   > **Note:** JSON does not expand `~`. Replace `\u002Fhome\u002Fyouruser` with your actual home directory (run `echo $HOME` to find it).\n\n3. Restart Pi.\n\n**Verify:** In a Pi session, type `ctx stats`. Context-mode tools should appear and respond.\n\n**Routing:** Automatic. The extension registers all key lifecycle events (`tool_call`, `tool_result`, `session_start`, `session_before_compact`), providing full session continuity and routing enforcement.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Build Prerequisites\u003C\u002Fstrong> \u003Csup>(CentOS, RHEL, Alpine)\u003C\u002Fsup>\u003C\u002Fsummary>\n\nContext Mode uses [better-sqlite3](https:\u002F\u002Fgithub.com\u002FWiseLibs\u002Fbetter-sqlite3) on Node.js, which ships prebuilt native binaries for most platforms. On glibc >= 2.31 systems (Ubuntu 20.04+, Debian 11+, Fedora 34+, macOS, Windows), `npm install` works without any build tools.\n\n**Bun users:** No native compilation needed. Context Mode automatically detects Bun and uses the built-in `bun:sqlite` module via a compatibility adapter. `better-sqlite3` and all its build dependencies are skipped entirely.\n\nOn older glibc systems (CentOS 7\u002F8, RHEL 8, Debian 10), prebuilt binaries don't load and better-sqlite3 **automatically falls back to compiling from source** via `prebuild-install || node-gyp rebuild --release`. This requires a C++20 compiler (GCC 10+), Make, and Python with setuptools.\n\n**CentOS 8 \u002F RHEL 8** (glibc 2.28):\n\n```bash\ndnf install -y gcc-toolset-10-gcc gcc-toolset-10-gcc-c++ make python3 python3-setuptools\nscl enable gcc-toolset-10 'npm install -g context-mode'\n```\n\n**CentOS 7 \u002F RHEL 7** (glibc 2.17):\n\n```bash\nyum install -y centos-release-scl\nyum install -y devtoolset-10-gcc devtoolset-10-gcc-c++ make python3\npip3 install setuptools\nscl enable devtoolset-10 'npm install -g context-mode'\n```\n\n**Alpine Linux:**\n\nAlpine prebuilt binaries (musl) are available in better-sqlite3 v12.8.0+. With the `^12.6.2` dependency range, `npm install` resolves to the latest 12.x and works without build tools on Alpine. If you pin an older version:\n\n```bash\napk add build-base python3 py3-setuptools\nnpm install -g context-mode\n```\n\n\u003C\u002Fdetails>\n\n## Tools\n\n| Tool | What it does | Context saved |\n|---|---|---|\n| `ctx_batch_execute` | Run multiple commands + search multiple queries in ONE call. | 986 KB → 62 KB |\n| `ctx_execute` | Run code in 11 languages. Only stdout enters context. | 56 KB → 299 B |\n| `ctx_execute_file` | Process files in sandbox. Raw content never leaves. | 45 KB → 155 B |\n| `ctx_index` | Chunk markdown into FTS5 with BM25 ranking. | 60 KB → 40 B |\n| `ctx_search` | Query indexed content with multiple queries in one call. | On-demand retrieval |\n| `ctx_fetch_and_index` | Fetch URL, chunk and index. 24h TTL cache — repeat calls skip network. `force: true` to bypass. | 60 KB → 40 B |\n| `ctx_stats` | Show context savings, call counts, and session statistics. | — |\n| `ctx_doctor` | Diagnose installation: runtimes, hooks, FTS5, versions. | — |\n| `ctx_upgrade` | Upgrade to latest version from GitHub, rebuild, reconfigure hooks. | — |\n\n## How the Sandbox Works\n\nEach `ctx_execute` call spawns an isolated subprocess with its own process boundary. Scripts can't access each other's memory or state. The subprocess runs your code, captures stdout, and only that stdout enters the conversation context. The raw data — log files, API responses, snapshots — never leaves the sandbox.\n\nEleven language runtimes are available: JavaScript, TypeScript, Python, Shell, Ruby, Go, Rust, PHP, Perl, R, and Elixir. Bun is auto-detected for 3-5x faster JS\u002FTS execution.\n\nAuthenticated CLIs work through credential passthrough — `gh`, `aws`, `gcloud`, `kubectl`, `docker` inherit environment variables and config paths without exposing them to the conversation.\n\nWhen output exceeds 5 KB and an `intent` is provided, Context Mode switches to intent-driven filtering: it indexes the full output into the knowledge base, searches for sections matching your intent, and returns only the relevant matches with a vocabulary of searchable terms for follow-up queries.\n\n## How the Knowledge Base Works\n\nThe `ctx_index` tool chunks markdown content by headings while keeping code blocks intact, then stores them in a **SQLite FTS5** (Full-Text Search 5) virtual table. Search uses **BM25 ranking** — a probabilistic relevance algorithm that scores documents based on term frequency, inverse document frequency, and document length normalization. **Porter stemming** is applied at index time so \"running\", \"runs\", and \"ran\" match the same stem. Titles and headings are weighted **5x** in BM25 scoring for precise navigational queries.\n\nWhen you call `ctx_search`, it returns relevant content snippets focused around matching query terms — not full documents, not approximations, the actual indexed content with smart extraction around what you're looking for. `ctx_fetch_and_index` extends this to URLs: fetch, convert HTML to markdown, chunk, index. The raw page never enters context. Use the `contentType` parameter to filter results by type (e.g. `code` or `prose`).\n\n### Ranking: Reciprocal Rank Fusion\n\nSearch runs two parallel strategies and merges them with **Reciprocal Rank Fusion (RRF)**:\n\n- **Porter stemming** — FTS5 MATCH with porter tokenizer. \"caching\" matches \"cached\", \"caches\", \"cach\".\n- **Trigram substring** — FTS5 trigram tokenizer matches partial strings. \"useEff\" finds \"useEffect\", \"authenticat\" finds \"authentication\".\n\nRRF merges both ranked lists into a single result set, so a document that ranks well in both strategies surfaces higher than one that ranks well in only one. This replaces the old cascading fallback approach where trigram results were only used if porter returned nothing.\n\n### Proximity Reranking\n\nMulti-term queries get an additional reranking pass. Results where query terms appear close together are boosted — `\"session continuity\"` ranks passages with adjacent terms higher than pages where \"session\" and \"continuity\" appear paragraphs apart.\n\n### Fuzzy Correction\n\nLevenshtein distance corrects typos before re-searching. \"kuberntes\" becomes \"kubernetes\", \"autentication\" becomes \"authentication\".\n\n### Smart Snippets\n\nSearch results use intelligent extraction instead of truncation. Instead of returning the first N characters (which might miss the important part), Context Mode finds where your query terms appear in the content and returns windows around those matches.\n\n### TTL Cache\n\nIndexed content persists in a per-project SQLite database at `~\u002F.context-mode\u002Fcontent\u002F`. When `ctx_fetch_and_index` is called for a URL that was already indexed within the last 24 hours, the fetch is skipped entirely. The model searches the existing index directly.\n\n- **Fresh (\u003C24h):** Returns a cache hint (0.3KB) instead of re-fetching (48KB+). Model proceeds to `ctx_search`.\n- **Stale (>24h):** Re-fetches silently. No user action needed.\n- **`force: true`:** Bypasses cache and re-fetches regardless of TTL.\n- **14-day cleanup:** Content databases and sources older than 14 days are removed on startup.\n\nThis means `--continue` sessions preserve indexed docs across restarts. No re-fetching, no wasted context tokens.\n\n`ctx_stats` reports cache performance separately: hits, data avoided, network requests saved, and total context savings including cache.\n\n### Progressive Throttling\n\n- **Calls 1-3:** Normal results (2 per query)\n- **Calls 4-8:** Reduced results (1 per query) + warning\n- **Calls 9+:** Blocked — redirects to `ctx_batch_execute`\n\n## Session Continuity\n\nWhen the context window fills up, the agent compacts the conversation — dropping older messages to make room. Without session tracking, the model forgets which files it was editing, what tasks are in progress, what errors were resolved, and what you last asked for.\n\nContext Mode captures every meaningful event during your session and persists them in a per-project SQLite database. When the conversation compacts (or you resume with `--continue`), your working state is rebuilt automatically — the model continues from your last prompt without asking you to repeat anything.\n\nSession continuity requires 4 hooks working together:\n\n| Hook | Role | Claude Code | Gemini CLI | VS Code Copilot | Cursor | OpenCode | KiloCode | OpenClaw | Codex CLI | Antigravity | Kiro | Zed | Pi |\n|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n| **PreToolUse** | Enforces sandbox routing before tool execution | Yes | -- | -- | Yes | -- | -- | -- | Yes | -- | Yes | -- | ✓ (via tool_call event) |\n| **PostToolUse** | Captures events after each tool call | Yes | Yes | Yes | Yes | Plugin | Plugin | Plugin | Yes | -- | Yes | -- | ✓ (via tool_result event) |\n| **UserPromptSubmit** | Captures user decisions and corrections | Yes | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |\n| **PreCompact** | Builds snapshot before compaction | Yes | Yes | Yes | -- | Plugin | Plugin | Plugin | -- | -- | -- | -- | ✓ (via session_before_compact) |\n| **SessionStart** | Restores state after compaction or resume | Yes | Yes | Yes | -- | -- | -- | Plugin | Yes | -- | -- | -- | ✓ (via session_start event) |\n| | **Session completeness** | **Full** | **High** | **High** | **Partial** | **High** | **High** | **High** | **Partial** | **--** | **Partial** | **--** | **High** |\n\n> **Note:** Full session continuity (capture + snapshot + restore) works on **Claude Code**, **Gemini CLI**, and **VS Code Copilot**. **OpenCode** provides **high** session continuity: it captures tool events and injects compaction snapshots via the plugin, but SessionStart is not yet available ([#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)), so startup\u002Fresume restore is not supported. **KiloCode** shares the same plugin architecture as OpenCode via the OpenCodeAdapter, so its continuity level depends on KiloCode's SessionStart support. **Cursor** captures tool events via `preToolUse`\u002F`postToolUse`, but `sessionStart` is currently rejected by Cursor's validator ([forum report](https:\u002F\u002Fforum.cursor.com\u002Ft\u002Funknown-hook-type-sessionstart\u002F149566)), so session restore after compaction is not available yet. **OpenClaw** uses native gateway plugin hooks (`api.on()`) for full session continuity. **Pi Coding Agent** provides high session continuity via extension hooks (`tool_call`, `tool_result`, `session_start`, `session_before_compact`). **Codex CLI** provides hook-based session tracking via PreToolUse\u002FPostToolUse\u002FSessionStart, using the same JSON stdin\u002Fstdout protocol as Claude Code. **Antigravity**, **Kiro**, and **Zed** have no hook support in the current release, so session tracking is not available.\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>What gets captured\u003C\u002Fstrong>\u003C\u002Fsummary>\n\nEvery tool call passes through hooks that extract structured events:\n\n| Category | Events | Priority | Captured By |\n|---|---|---|---|\n| **Files** | read, edit, write, glob, grep | Critical (P1) | PostToolUse |\n| **Tasks** | create, update, complete | Critical (P1) | PostToolUse |\n| **Rules** | CLAUDE.md \u002F GEMINI.md \u002F AGENTS.md paths + content | Critical (P1) | SessionStart |\n| **Decisions** | User corrections, preferences (\"use X instead\", \"don't do Y\") | High (P2) | UserPromptSubmit |\n| **Git** | checkout, commit, merge, rebase, stash, push, pull, diff, status | High (P2) | PostToolUse |\n| **Errors** | Tool failures, non-zero exit codes | High (P2) | PostToolUse |\n| **Environment** | cwd changes, venv, nvm, conda, package installs | High (P2) | PostToolUse |\n| **MCP Tools** | All `mcp__*` tool calls with usage counts | Normal (P3) | PostToolUse |\n| **Subagents** | Agent tool invocations | Normal (P3) | PostToolUse |\n| **Skills** | Slash command invocations | Normal (P3) | PostToolUse |\n| **Role** | Persona \u002F behavioral directives (\"act as senior engineer\") | Normal (P3) | UserPromptSubmit |\n| **Intent** | Session mode classification (investigate, implement, debug) | Low (P4) | UserPromptSubmit |\n| **Data** | Large user-pasted data references (>1 KB) | Low (P4) | UserPromptSubmit |\n| **User Prompts** | Every user message (for last-prompt restore) | Critical (P1) | UserPromptSubmit |\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>How sessions survive compaction\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n```\nPreCompact fires\n  → Read all session events from SQLite\n  → Build priority-tiered XML snapshot (≤2 KB)\n  → Store snapshot in session_resume table\n\nSessionStart fires (source: \"compact\")\n  → Retrieve stored snapshot\n  → Write structured events file → auto-indexed into FTS5\n  → Build Session Guide with 15 categories\n  → Inject \u003Csession_knowledge> directive into context\n  → Model continues from last user prompt with full working state\n```\n\nThe snapshot is built in priority tiers — if the 2 KB budget is tight, lower-priority events (intent, MCP tool counts) are dropped first while critical state (active files, tasks, rules, decisions) is always preserved.\n\nAfter compaction, the model receives a **Session Guide** — a structured narrative with actionable sections:\n\n- **Last Request** — user's last prompt, so the model continues without asking \"what were we doing?\"\n- **Tasks** — checkbox format with completion status (`[x]` completed, `[ ]` pending)\n- **Key Decisions** — user corrections and preferences (\"use X instead\", \"don't do Y\")\n- **Files Modified** — all files touched during the session\n- **Unresolved Errors** — errors that haven't been fixed\n- **Git** — operations performed (checkout, commit, push, status)\n- **Project Rules** — CLAUDE.md \u002F GEMINI.md \u002F AGENTS.md paths\n- **MCP Tools Used** — tool names with call counts\n- **Subagent Tasks** — delegated work summaries\n- **Skills Used** — slash commands invoked\n- **Environment** — working directory, env variables\n- **Data References** — large data pasted during the session\n- **Session Intent** — mode classification (implement, investigate, review, discuss)\n- **User Role** — behavioral directives set during the session\n\nDetailed event data is also indexed into FTS5 for on-demand retrieval via `search()`.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Per-platform details\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n**Claude Code** — Full session support. All 5 hook types fire, capturing tool events, user decisions, building compaction snapshots, and restoring state after compaction or `--continue`.\n\n**Gemini CLI** — High coverage. PostToolUse (AfterTool), PreCompact (PreCompress), and SessionStart all fire. Missing UserPromptSubmit, so user decisions and corrections aren't captured — but file edits, git ops, errors, and tasks are fully tracked.\n\n**VS Code Copilot** — High coverage. Same as Gemini CLI — PostToolUse, PreCompact, and SessionStart all fire. User decisions aren't captured but all tool-level events are.\n\n**Cursor** — Partial coverage. Native `preToolUse` and `postToolUse` hooks capture tool events. `sessionStart` is documented by Cursor but currently rejected by their validator, so session restore is not available. Routing instructions are delivered via MCP server startup instead.\n\n**OpenCode** — Partial. The TypeScript plugin captures PostToolUse events via `tool.execute.after`, but SessionStart is not yet available ([#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)). Events are stored but not automatically restored after compaction.\n\n**KiloCode** — Partial. Shares the same plugin architecture as OpenCode via the OpenCodeAdapter. The TypeScript plugin captures PostToolUse events via `tool.execute.after`, but SessionStart availability depends on KiloCode's implementation. Events are stored but may not be automatically restored after compaction.\n\n**OpenClaw \u002F Pi Agent** — High coverage. All tool lifecycle hooks (`after_tool_call`, `before_compaction`, `session_start`) fire via the native gateway plugin. User decisions aren't captured but file edits, git ops, errors, and tasks are fully tracked. Falls back to DB snapshot reconstruction if compaction hooks fail on older gateway versions. See [`docs\u002Fadapters\u002Fopenclaw.md`](docs\u002Fadapters\u002Fopenclaw.md).\n\n**Codex CLI** — Hook-based session tracking. PreToolUse enforces routing, PostToolUse captures events, SessionStart restores state after compaction. Same wire protocol as Claude Code. PreCompact and UserPromptSubmit are not yet available, so compaction snapshots rely on DB reconstruction.\n\n**Antigravity** — No session support. Same as Codex CLI — no hooks, no event capture. Requires manually copying `GEMINI.md` to your project root. Auto-detected via MCP protocol handshake (`clientInfo.name`).\n\n**Zed** — No session support. Same as Codex CLI — no hooks, no event capture. Requires manually copying `AGENTS.md` to your project root. Auto-detected via MCP protocol handshake (`clientInfo.name`).\n\n**Kiro** — Partial coverage. Native `preToolUse` and `postToolUse` hooks capture tool events and enforce sandbox routing. `agentSpawn` (the Kiro equivalent of SessionStart) is not yet implemented, so session restore after compaction is not available. Requires manually copying `KIRO.md` to your project root. Auto-detected via MCP protocol handshake (`clientInfo.name`).\n\n**Pi Coding Agent** — High coverage. The extension registers all key lifecycle events: `tool_call` (PreToolUse), `tool_result` (PostToolUse), `session_start` (SessionStart), and `session_before_compact` (PreCompact). File edits, git ops, errors, and tasks are fully tracked. Session restore after compaction works via the extension's event hooks.\n\n\u003C\u002Fdetails>\n\n## Platform Compatibility\n\n| Feature | Claude Code | Gemini CLI | VS Code Copilot | Cursor | OpenCode | KiloCode | OpenClaw | Codex CLI | Antigravity | Kiro | Zed | Pi |\n|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n| MCP Server | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes |\n| PreToolUse Hook | Yes | Yes | Yes | Yes | Plugin | Plugin | Plugin | -- | -- | Yes | -- | Yes (extension) |\n| PostToolUse Hook | Yes | Yes | Yes | Yes | Plugin | Plugin | Plugin | -- | -- | Yes | -- | Yes (extension) |\n| SessionStart Hook | Yes | Yes | Yes | -- | -- | -- | Plugin | -- | -- | -- | -- | Yes (extension) |\n| PreCompact Hook | Yes | Yes | Yes | -- | Plugin | Plugin | Plugin | -- | -- | -- | -- | Yes (extension) |\n| Can Modify Args | Yes | Yes | Yes | Yes | Plugin | Plugin | Plugin | -- | -- | -- | -- | Yes (extension) |\n| Can Block Tools | Yes | Yes | Yes | Yes | Plugin | Plugin | Plugin | -- | -- | Yes | -- | Yes (extension) |\n| Utility Commands (ctx) | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes (\u002Fctx-stats, \u002Fctx-doctor) |\n| Slash Commands | Yes | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |\n| Plugin Marketplace | Yes | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |\n\n> **OpenCode** uses a TypeScript plugin paradigm — hooks run as in-process functions via `tool.execute.before`, `tool.execute.after`, and `experimental.session.compacting`, providing the same routing enforcement and session continuity as shell-based hooks. SessionStart is not yet available ([#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)), but compaction recovery works via the plugin's compacting hook.\n>\n> **KiloCode** shares the same TypeScript plugin architecture as OpenCode via the OpenCodeAdapter, with platform-specific configuration paths (`kilo.json` instead of `opencode.json`, `~\u002F.config\u002Fkilo\u002F` instead of `~\u002F.config\u002Fopencode\u002F`). Hook capabilities depend on KiloCode's implementation of the plugin interface.\n>\n> **OpenClaw** runs context-mode as a native gateway plugin targeting Pi Agent sessions. Hooks register via `api.on()` (tool\u002Flifecycle) and `api.registerHook()` (commands). All tool interception and compaction hooks are supported. See [`docs\u002Fadapters\u002Fopenclaw.md`](docs\u002Fadapters\u002Fopenclaw.md).\n>\n> **Codex CLI**, **Antigravity**, and **Zed** do not support hooks. They rely solely on manually-copied routing instruction files (`AGENTS.md` \u002F `GEMINI.md`) for enforcement (~60% compliance). See each platform's install section for copy instructions. Antigravity and Zed are auto-detected via MCP protocol handshake — no manual platform configuration needed.\n>\n> **Kiro** supports native `preToolUse` and `postToolUse` hooks for routing enforcement and tool event capture. `agentSpawn` (SessionStart equivalent) and `stop` are not yet wired. Requires manually copying `KIRO.md` to your project root. Kiro is auto-detected via MCP protocol handshake (`clientInfo.name`).\n>\n> **Pi Coding Agent** runs context-mode as an extension with full hook support. The extension registers `tool_call`, `tool_result`, `session_start`, and `session_before_compact` events, providing high session continuity coverage. The MCP server provides the 6 sandbox tools.\n\n### Routing Enforcement\n\nHooks intercept tool calls programmatically — they can block dangerous commands and redirect them to the sandbox before execution. Instruction files guide the model via prompt instructions but cannot block anything. **Always enable hooks where supported.**\n\n> **Note:** Routing instruction files were previously auto-written to project directories on first session start. This was disabled to prevent git tree pollution ([#158](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F158), [#164](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F164)). Hook-capable platforms (Claude Code, Gemini CLI, VS Code Copilot, OpenCode, OpenClaw) inject routing via hooks and need no file. Non-hook platforms (Codex, Zed, Cursor, Kiro, Antigravity) require a one-time manual copy — see each platform's install section.\n\n| Platform | Hooks | Instruction File | With Hooks | Without Hooks |\n|---|:---:|---|:---:|:---:|\n| Claude Code | Yes (auto) | [`CLAUDE.md`](configs\u002Fclaude-code\u002FCLAUDE.md) | **~98% saved** | ~60% saved |\n| Gemini CLI | Yes | [`GEMINI.md`](configs\u002Fgemini-cli\u002FGEMINI.md) | **~98% saved** | ~60% saved |\n| VS Code Copilot | Yes | [`copilot-instructions.md`](configs\u002Fvscode-copilot\u002Fcopilot-instructions.md) | **~98% saved** | ~60% saved |\n| Cursor | Yes | [`context-mode.mdc`](configs\u002Fcursor\u002Fcontext-mode.mdc) | **~98% saved** | ~60% saved |\n| OpenCode | Plugin | [`AGENTS.md`](configs\u002Fopencode\u002FAGENTS.md) | **~98% saved** | ~60% saved |\n| OpenClaw | Plugin | [`AGENTS.md`](configs\u002Fopenclaw\u002FAGENTS.md) | **~98% saved** | ~60% saved |\n| Codex CLI | -- | [`AGENTS.md`](configs\u002Fcodex\u002FAGENTS.md) | -- | ~60% saved |\n| Antigravity | -- | [`GEMINI.md`](configs\u002Fantigravity\u002FGEMINI.md) | -- | ~60% saved |\n| Kiro | Yes | [`KIRO.md`](configs\u002Fkiro\u002FKIRO.md) | **~98% saved** | ~60% saved |\n| Zed | -- | [`AGENTS.md`](configs\u002Fzed\u002FAGENTS.md) | -- | ~60% saved |\n| Pi | ✓ | [`AGENTS.md`](configs\u002Fpi\u002FAGENTS.md) | **~98% saved** | ~60% saved |\n\nWithout hooks, one unrouted `curl` or Playwright snapshot can dump 56 KB into context — wiping out an entire session's worth of savings.\n\nSee [`docs\u002Fplatform-support.md`](docs\u002Fplatform-support.md) for the full capability comparison.\n\n## Utility Commands\n\n**Inside any AI session** — just type the command. The LLM calls the MCP tool automatically:\n\n```\nctx stats       → context savings, call counts, session report\nctx doctor      → diagnose runtimes, hooks, FTS5, versions\nctx upgrade     → update from GitHub, rebuild, reconfigure hooks\n```\n\n**From your terminal** — run directly without an AI session:\n\n```bash\ncontext-mode doctor\ncontext-mode upgrade\n```\n\nWorks on **all platforms**. On Claude Code, slash commands (`\u002Fctx-stats`, `\u002Fctx-doctor`, `\u002Fctx-upgrade`) are also available.\n\n## Benchmarks\n\n| Scenario | Raw | Context | Saved |\n|---|---|---|---|\n| Playwright snapshot | 56.2 KB | 299 B | 99% |\n| GitHub Issues (20) | 58.9 KB | 1.1 KB | 98% |\n| Access log (500 requests) | 45.1 KB | 155 B | 100% |\n| Context7 React docs | 5.9 KB | 261 B | 96% |\n| Analytics CSV (500 rows) | 85.5 KB | 222 B | 100% |\n| Git log (153 commits) | 11.6 KB | 107 B | 99% |\n| Test output (30 suites) | 6.0 KB | 337 B | 95% |\n| Repo research (subagent) | 986 KB | 62 KB | 94% |\n\nOver a full session: 315 KB of raw output becomes 5.4 KB. Session time extends from ~30 minutes to ~3 hours.\n\n[Full benchmark data with 21 scenarios →](BENCHMARK.md)\n\n## Try It\n\nThese prompts work out of the box. Run `\u002Fcontext-mode:ctx-stats` after each to see the savings.\n\n**Deep repo research** — 5 calls, 62 KB context (raw: 986 KB, 94% saved)\n```\nResearch https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers — architecture, tech stack,\ntop contributors, open issues, and recent activity. Then run \u002Fcontext-mode:ctx-stats.\n```\n\n**Git history analysis** — 1 call, 5.6 KB context\n```\nClone https:\u002F\u002Fgithub.com\u002Ffacebook\u002Freact and analyze the last 500 commits:\ntop contributors, commit frequency by month, and most changed files.\nThen run \u002Fcontext-mode:ctx-stats.\n```\n\n**Web scraping** — 1 call, 3.2 KB context\n```\nFetch the Hacker News front page, extract all posts with titles, scores,\nand domains. Group by domain. Then run \u002Fcontext-mode:ctx-stats.\n```\n\n**Large JSON API** — 7.5 MB raw → 0.9 KB context (99% saved)\n```\nCreate a local server that returns a 7.5 MB JSON with 20,000 records and a secret\nhidden at index 13000. Fetch the endpoint, find the hidden record, and show me\nexactly what's in it. Then run \u002Fcontext-mode:ctx-stats.\n```\n\n**Documentation search** — 2 calls, 1.8 KB context\n```\nFetch the React useEffect docs, index them, and find the cleanup pattern\nwith code examples. Then run \u002Fcontext-mode:ctx-stats.\n```\n\n**Session continuity** — compaction recovery with full state\n```\nStart a multi-step task: \"Create a REST API with Express — add routes, tests,\nand error handling.\" After 20+ tool calls, type: ctx stats to see the session\nevent count. When context compacts, the model continues from your last prompt\nwith tasks, files, and decisions intact — no re-prompting needed.\n```\n\n## Privacy & Architecture\n\nContext Mode is not a CLI output filter or a cloud analytics dashboard. It operates at the MCP protocol layer — raw data stays in a sandboxed subprocess and never enters your context window. Web pages, API responses, file analysis, Playwright snapshots, log files — everything is processed in complete isolation.\n\n**Nothing leaves your machine.** No telemetry, no cloud sync, no usage tracking, no account required. Your code, your prompts, your session data — all local. The SQLite databases live in your home directory and die when you're done.\n\nThis is a deliberate architectural choice, not a missing feature. Context optimization should happen at the source, not in a dashboard behind a per-seat subscription. Privacy-first is our philosophy — and every design decision follows from it. [License →](#license)\n\n## Security\n\nContext Mode enforces the same permission rules you already use — but extends them to the MCP sandbox. If you block `sudo`, it's also blocked inside `ctx_execute`, `ctx_execute_file`, and `ctx_batch_execute`.\n\n**Zero setup required.** If you haven't configured any permissions, nothing changes. This only activates when you add rules.\n\n```json\n{\n  \"permissions\": {\n    \"deny\": [\n      \"Bash(sudo *)\",\n      \"Bash(rm -rf \u002F*)\",\n      \"Read(.env)\",\n      \"Read(**\u002F.env*)\"\n    ],\n    \"allow\": [\n      \"Bash(git:*)\",\n      \"Bash(npm:*)\"\n    ]\n  }\n}\n```\n\nAdd this to your project's `.claude\u002Fsettings.json` (or `~\u002F.claude\u002Fsettings.json` for global rules). All platforms read security policies from Claude Code's settings format — even on Gemini CLI, VS Code Copilot, and OpenCode. Codex CLI has no hook support, so security enforcement is not available.\n\nThe pattern is `Tool(what to match)` where `*` means \"anything\".\n\nCommands chained with `&&`, `;`, or `|` are split — each part is checked separately. `echo hello && sudo rm -rf \u002Ftmp` is blocked because the `sudo` part matches the deny rule.\n\n**deny** always wins over **allow**. More specific (project-level) rules override global ones.\n\n## Contributing\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow and TDD guidelines.\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode.git\ncd context-mode && npm install && npm test\n```\n\n## License\n\nLicensed under [Elastic License 2.0](LICENSE) (source-available). You can use it, fork it, modify it, and distribute it. Two things you can't do: offer it as a hosted\u002Fmanaged service, or remove the licensing notices. We chose ELv2 over MIT because MIT permits repackaging the code as a competing closed-source SaaS — ELv2 prevents that while keeping the source available to everyone.\n","# 上下文模式\n\n**上下文问题的另一半。**\n\n[![users](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fcdn.jsdelivr.net%2Fgh%2Fmksglu%2Fcontext-mode%40main%2Fstats.json&query=%24.message&label=users&color=brightgreen)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fcontext-mode) [![npm](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fcdn.jsdelivr.net%2Fgh%2Fmksglu%2Fcontext-mode%40main%2Fstats.json&query=%24.npm&label=npm&color=blue)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fcontext-mode) [![marketplace](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fdynamic\u002Fjson?url=https%3A%2F%2Fcdn.jsdelivr.net%2Fgh%2Fmksglu%2Fcontext-mode%40main%2Fstats.json&query=%24.marketplace&label=marketplace&color=blue)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode) [![GitHub stars](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Fstars\u002Fmksglu\u002Fcontext-mode?style=flat&color=yellow)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fstargazers) [![GitHub forks](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Fforks\u002Fmksglu\u002Fcontext-mode?style=flat&color=blue)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fnetwork\u002Fmembers) [![Last commit](https:\u002F\u002Fimg.shields.io\u002Fgithub\u002Flast-commit\u002Fmksglu\u002Fcontext-mode?color=green)](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fcommits) [![License: ELv2](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FLicense-ELv2-blue.svg)](LICENSE)\n[![Discord](https:\u002F\u002Fimg.shields.io\u002Fdiscord\u002F1478479412700909750?label=Discord&logo=discord&color=5865f2)](https:\u002F\u002Fdiscord.gg\u002FDCN9jUgN5v)\n\n## 问题\n\n每次调用MCP工具时，原始数据都会被直接塞进你的上下文窗口。一个Playwright快照就要占用56 KB。二十个GitHub问题则占59 KB。而一份访问日志就有45 KB。仅仅30分钟后，你40%的上下文就消失了。当代理为了腾出空间而压缩对话时，它会忘记你正在编辑哪些文件、有哪些任务正在进行，以及你上次请求了什么。\n\n上下文模式是一个MCP服务器，它解决了这个问题的两个方面：\n\n1. **上下文保存** — 沙盒工具将原始数据隔离在上下文窗口之外。原本315 KB的数据现在只需5.4 KB，减少了98%。\n2. **会话连续性** — 每一次文件编辑、Git操作、任务、错误以及用户决策都会被记录在SQLite数据库中。当对话被压缩时，上下文模式并不会把这些数据重新放回上下文中——而是将这些事件索引到FTS5中，并通过BM25搜索只检索相关的内容。这样模型就能从你上次中断的地方继续工作。如果你没有使用`--continue`选项，之前的会话数据会被立即删除——这意味着新会话将从一张白纸开始。\n\nhttps:\u002F\u002Fgithub.com\u002Fuser-attachments\u002Fassets\u002F07013dbf-07c0-4ef1-974a-33ea1207637b\n\n## 安装\n\n平台按照安装复杂度分组。支持钩子的平台可以自动执行路由规则。而不支持钩子的平台则需要手动复制一次路由配置文件。\n\n\u003Cdetails open>\n\u003Csummary>\u003Cstrong>Claude Code\u003C\u002Fstrong> — 插件市场，全自动\u003C\u002Fsummary>\n\n**先决条件：** Claude Code v1.0.33及以上版本（`claude --version`）。如果系统无法识别`\u002Fplugin`命令，请先更新：`brew upgrade claude-code` 或 `npm update -g @anthropic-ai\u002Fclaude-code`。\n\n**安装：**\n\n```bash\n\u002Fplugin marketplace add mksglu\u002Fcontext-mode\n\u002Fplugin install context-mode@context-mode\n```\n\n重启Claude Code（或运行`\u002Freload-plugins`）。\n\n**验证：**\n\n```\n\u002Fcontext-mode:ctx-doctor\n```\n\n所有检查项都应显示`[x]`。该诊断工具会验证运行时环境、钩子、FTS5以及插件注册情况。\n\n**路由：** 自动。SessionStart钩子会在运行时注入路由指令——无需向你的项目中写入任何文件。该插件会注册所有钩子（PreToolUse、PostToolUse、PreCompact、SessionStart）以及6个沙盒工具（`ctx_batch_execute`、`ctx_execute`、`ctx_execute_file`、`ctx_index`、`ctx_search`、`ctx_fetch_and_index`）。\n\n| 斜杠命令 | 功能 |\n|---|---|\n| `\u002Fcontext-mode:ctx-stats` | 上下文节省情况——按工具细分、消耗的token数量、节省比例。 |\n| `\u002Fcontext-mode:ctx-doctor` | 诊断信息——运行时环境、钩子、FTS5、插件注册情况、版本号。 |\n| `\u002Fcontext-mode:ctx-upgrade` | 拉取最新版本、重建、迁移缓存、修复钩子。 |\n\n> **注意：** 斜杠命令是Claude Code插件的功能。在其他平台上，你可以在聊天中输入`ctx stats`、`ctx doctor`或`ctx upgrade`——模型会自动调用MCP工具。详情请参阅[实用命令](#utility-commands)。\n\n\u003Cdetails>\n\u003Csummary>替代方案——仅MCP安装（无钩子或斜杠命令）\u003C\u002Fsummary>\n\n```bash\nclaude mcp add context-mode -- npx -y context-mode\n```\n\n这将为你提供6个沙盒工具，但不会自动进行路由设置。模型仍然可以使用这些工具，只是不会优先选择它们而不是原始的Bash\u002FRead\u002FWebFetch等工具。这对于在决定是否完整安装插件之前进行试用非常合适。\n\n\u003C\u002Fdetails>\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Gemini CLI\u003C\u002Fstrong> — 一个配置文件，包含钩子\u003C\u002Fsummary>\n\n**先决条件：** Node.js 18+，已安装Gemini CLI。\n\n**安装：**\n\n1. 全局安装context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 将以下内容添加到`~\u002F.gemini\u002Fsettings.json`中。这个单一的配置文件会注册MCP服务器和全部四个钩子：\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     },\n     \"hooks\": {\n       \"BeforeTool\": [\n         {\n           \"matcher\": \"run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli beforetool\" }]\n         }\n       ],\n       \"AfterTool\": [\n         {\n           \"matcher\": \"\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli aftertool\" }]\n         }\n       ],\n       \"PreCompress\": [\n         {\n           \"matcher\": \"\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli precompress\" }]\n         }\n       ],\n       \"SessionStart\": [\n         {\n           \"matcher\": \"\",\n           \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook gemini-cli sessionstart\" }]\n         }\n       ]\n     }\n   }\n   ```\n\n3. 重启Gemini CLI。\n\n**验证：**\n\n```\n\u002Fmcp list\n```\n\n你应该能看到`context-mode: ... - 已连接`。\n\n**路由：** 自动。SessionStart钩子会在运行时注入路由指令——不会向你的项目中写入`GEMINI.md`文件。所有四个钩子（BeforeTool、AfterTool、PreCompress、SessionStart）都会以编程方式处理路由规则的执行。\n\n> **为什么要有BeforeTool匹配器？** 它只针对那些会产生大量输出的工具（`run_shell_command`、`read_file`、`read_many_files`、`grep_search`、`search_file_content`、`web_fetch`、`activate_skill`），再加上context-mode自己的工具（`mcp__plugin_context-mode`）。这样做可以避免对轻量级工具不必要的钩子开销，同时拦截所有可能使你的上下文窗口爆满的工具。\n\n完整配置参考：[`configs\u002Fgemini-cli\u002Fsettings.json`](configs\u002Fgemini-cli\u002Fsettings.json)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>VS Code Copilot\u003C\u002Fstrong> — 带有SessionStart钩子\u003C\u002Fsummary>\n\n**先决条件：** Node.js 18+，安装了Copilot Chat v0.32及更高版本的VS Code。\n\n**安装：**\n\n1. 全局安装context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 在你的项目根目录下创建 `.vscode\u002Fmcp.json` 文件：\n\n   ```json\n   {\n     \"servers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. 创建 `.github\u002Fhooks\u002Fcontext-mode.json` 文件：\n\n   ```json\n   {\n     \"hooks\": {\n       \"PreToolUse\": [\n         { \"type\": \"command\", \"command\": \"context-mode hook vscode-copilot pretooluse\" }\n       ],\n       \"PostToolUse\": [\n         { \"type\": \"command\", \"command\": \"context-mode hook vscode-copilot posttooluse\" }\n       ],\n       \"SessionStart\": [\n         { \"type\": \"command\", \"command\": \"context-mode hook vscode-copilot sessionstart\" }\n       ]\n     }\n   }\n   ```\n\n4. 重启 VS Code。\n\n**验证：** 打开 Copilot Chat，输入 `ctx stats`。Context-mode 工具应该会显示并作出响应。\n\n**路由：** 自动路由。SessionStart 钩子会在运行时注入路由指令——无需在你的项目中生成 `copilot-instructions.md` 文件。\n\n完整的钩子配置（包括 PreCompact）请参阅：[`configs\u002Fvscode-copilot\u002Fhooks.json`](configs\u002Fvscode-copilot\u002Fhooks.json)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Cursor\u003C\u002Fstrong> — 带停止支持的钩子\u003C\u002Fsummary>\n\n**先决条件：** Node.js 18+，启用代理模式的 Cursor。\n\n**安装：**\n\n1. 全局安装 context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 在你的项目根目录下创建 `.cursor\u002Fmcp.json` 文件（或在 `~\u002F.cursor\u002Fmcp.json` 中进行全局配置）：\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. 创建 `.cursor\u002Fhooks.json` 文件（或在 `~\u002F.cursor\u002Fhooks.json` 中进行全局配置）：\n\n   ```json\n   {\n     \"version\": 1,\n     \"hooks\": {\n       \"preToolUse\": [\n         {\n           \"command\": \"context-mode hook cursor pretooluse\",\n           \"matcher\": \"Shell|Read|Grep|WebFetch|Task|MCP:ctx_execute|MCP:ctx_execute_file|MCP:ctx_batch_execute\"\n         }\n       ],\n       \"postToolUse\": [\n         {\n           \"command\": \"context-mode hook cursor posttooluse\"\n         }\n       ],\n       \"stop\": [\n         {\n           \"command\": \"context-mode hook cursor stop\"\n         }\n       ]\n     }\n   }\n   ```\n\n   `preToolUse` 匹配器是可选的——如果没有它，钩子会对所有工具生效。`stop` 钩子会在代理回合结束时触发，并可以发送后续消息以继续循环。此外还提供 `afterAgentResponse` 钩子（一次性调用，接收完整响应文本）。\n\n4. 复制路由规则文件。由于 Cursor 缺少 SessionStart 钩子，模型需要一个规则文件来了解路由信息：\n\n   ```bash\n   mkdir -p .cursor\u002Frules\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcursor\u002Fcontext-mode.mdc .cursor\u002Frules\u002Fcontext-mode.mdc\n   ```\n\n5. 重启 Cursor 或打开一个新的代理会话。\n\n**验证：** 打开 Cursor 设置 > MCP，确认“context-mode”已连接。在代理聊天中输入 `ctx stats`。\n\n**路由：** 钩子通过 `preToolUse`、`postToolUse` 和 `stop` 程序化地强制执行路由。由于 Cursor 的 `sessionStart` 钩子目前被其验证器拒绝（[论坛报告](https:\u002F\u002Fforum.cursor.com\u002Ft\u002Funknown-hook-type-sessionstart\u002F149566)），因此 `.cursor\u002Frules\u002Fcontext-mode.mdc` 文件会在会话开始时提供路由指导。项目级别的 `.cursor\u002Fhooks.json` 会覆盖 `~\u002F.cursor\u002Fhooks.json`。\n\n完整配置：[`configs\u002Fcursor\u002Fhooks.json`](configs\u002Fcursor\u002Fhooks.json) | [`configs\u002Fcursor\u002Fmcp.json`](configs\u002Fcursor\u002Fmcp.json) | [`configs\u002Fcursor\u002Fcontext-mode.mdc`](configs\u002Fcursor\u002Fcontext-mode.mdc)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>OpenCode\u003C\u002Fstrong> — 带钩子的 TypeScript 插件\u003C\u002Fsummary>\n\n**先决条件：** Node.js 18+，已安装 OpenCode。\n\n**安装：**\n\n1. 全局安装 context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 将以下内容添加到你项目根目录下的 `opencode.json` 文件中（或在 `~\u002F.config\u002Fopencode\u002Fopencode.json` 中进行全局配置）：\n\n   ```json\n   {\n     \"$schema\": \"https:\u002F\u002Fopencode.ai\u002Fconfig.json\",\n     \"mcp\": {\n       \"context-mode\": {\n         \"type\": \"local\",\n         \"command\": [\"context-mode\"]\n       }\n     },\n     \"plugin\": [\"context-mode\"]\n   }\n   ```\n\n   `mcp` 条目用于注册 6 个沙盒工具。`plugin` 条目则启用钩子——OpenCode 会在每次工具执行之前和之后直接调用插件的 TypeScript 函数，从而阻止危险命令并强制执行沙盒路由。\n\n3. *(可选)* 复制路由规则文件。由于 OpenCode 缺少 SessionStart 钩子，模型需要一个 `AGENTS.md` 文件来了解路由信息：\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fopencode\u002FAGENTS.md AGENTS.md\n   ```\n\n   这将告诉模型应使用哪些工具以及哪些命令会被阻止。如果没有这个文件，钩子仍然会强制执行路由——但模型将不知道为什么某个命令会被拒绝。\n\n4. 重启 OpenCode。\n\n**验证：** 在 OpenCode 会话中输入 `ctx stats`。Context-mode 工具应该会显示并作出响应。\n\n**路由：** 钩子通过 `tool.execute.before` 和 `tool.execute.after` 程序化地强制执行路由。可选的 [`AGENTS.md`](configs\u002Fopencode\u002FAGENTS.md) 文件为模型提供了路由意识所需的指导。`experimental.session.compacting` 钩子会在对话压缩时构建恢复快照。\n\n> **注意：** OpenCode 的 SessionStart 钩子尚未可用（[#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)），因此不支持启动或恢复会话。不过，通过插件可以完全实现压缩后的恢复功能。\n\n完整配置：[`configs\u002Fopencode\u002Fopencode.json`](configs\u002Fopencode\u002Fopencode.json) | [`configs\u002Fopencode\u002FAGENTS.md`](configs\u002Fopencode\u002FAGENTS.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>KiloCode\u003C\u002Fstrong> — 带钩子的 TypeScript 插件\u003C\u002Fsummary>\n\n**先决条件：** Node.js 18+，已安装 KiloCode。\n\n**安装：**\n\n1. 全局安装 context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 将以下内容添加到你项目根目录下的 `kilo.json` 文件中（或在 `~\u002F.config\u002Fkilo\u002Fkilo.json` 中进行全局配置）：\n\n   ```json\n   {\n     \"$schema\": \"https:\u002F\u002Fapp.kilo.ai\u002Fconfig.json\",\n     \"mcp\": {\n       \"context-mode\": {\n         \"type\": \"local\",\n         \"command\": [\"context-mode\"]\n       }\n     },\n     \"plugin\": [\"context-mode\"]\n   }\n   ```\n\n   `mcp` 条目用于注册 6 个沙盒工具。`plugin` 条目则启用钩子——KiloCode 会在每次工具执行之前和之后直接调用插件的 TypeScript 函数，从而阻止危险命令并强制执行沙盒路由。\n\n3. *(可选)* 复制路由规则文件。由于 KiloCode 采用与 OpenCode 相同的插件架构且同样缺少 SessionStart 钩子，模型需要一个 `AGENTS.md` 文件来了解路由信息：\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fopencode\u002FAGENTS.md AGENTS.md\n   ```\n\n4. 重启 KiloCode。\n\n**验证：** 在 KiloCode 会话中输入 `ctx stats`。Context-mode 工具应该会显示并作出响应。\n\n**路由：** 钩子通过 `tool.execute.before` 和 `tool.execute.after` 程序化地强制执行路由。可选的 [`AGENTS.md`](configs\u002Fopencode\u002FAGENTS.md) 文件为模型提供了路由意识所需的指导。`experimental.session.compacting` 钩子会在对话压缩时构建恢复快照。\n\n> **注意:** KiloCode 与 OpenCode 共享相同的插件架构，使用 OpenCodeAdapter，并采用平台特定的配置路径（`kilo.json` 代替 `opencode.json`，`~\u002F.config\u002Fkilo\u002F` 代替 `~\u002F.config\u002Fopencode\u002F`）。SessionStart 钩子是否可用取决于 KiloCode 的实现。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>OpenClaw \u002F Pi Agent\u003C\u002Fstrong> — 原生网关插件\u003C\u002Fsummary>\n\n**先决条件:** 运行中的 OpenClaw 网关（[>2026.1.29](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw\u002Fpull\u002F9761)），Node.js 22+。\n\ncontext-mode 作为原生 [OpenClaw](https:\u002F\u002Fgithub.com\u002Fopenclaw) 网关插件运行，针对的是 **Pi Agent** 会话（读取\u002F写入\u002F编辑\u002FBash 工具）。与其他平台不同，这里没有单独的 MCP 服务器——该插件直接通过 OpenClaw 的 [插件 API](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin) 注册到网关运行时中。\n\n**安装:**\n\n1. 克隆并安装：\n\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode.git\n   cd context-mode\n   npm run install:openclaw\n   ```\n\n   安装程序会使用您环境中的 `$OPENCLAW_STATE_DIR`（默认：`\u002Fopenclaw`）。若要指定自定义路径：\n\n   ```bash\n   npm run install:openclaw -- \u002Fpath\u002Fto\u002Fopenclaw-state\n   ```\n\n   常见位置：**Docker** — `\u002Fopenclaw`（默认）。**本地** — `~\u002F.openclaw` 或您设置 `OPENCLAW_STATE_DIR` 的任何位置。\n\n   安装程序会完成所有操作：`npm install`、`npm run build`、`better-sqlite3` 原生重建、在 `runtime.json` 中注册扩展，并通过 SIGUSR1 重启网关。\n\n2. 打开一个 Pi Agent 会话。\n\n**验证:** 插件会通过 [`api.on()`](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin)（生命周期）和 [`api.registerHook()`](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin)（命令）注册 8 个钩子。输入 `ctx stats` 确认工具已加载。\n\n**路由:** 自动。所有工具拦截、会话跟踪和压缩恢复钩子都会自动激活——无需手动配置钩子或路由文件。\n\n> **最低版本:** OpenClaw >2026.1.29——此版本包含来自 [PR #9761](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw\u002Fpull\u002F9761) 的 `api.on()` 生命周期修复。在较旧版本上，生命周期钩子会静默失败。适配器会回退到数据库快照重建（精度较低，但能保留关键状态）。\n\n完整文档：[`docs\u002Fadapters\u002Fopenclaw.md`](docs\u002Fadapters\u002Fopenclaw.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Codex CLI\u003C\u002Fstrong> — 钩子 + MCP\u003C\u002Fsummary>\n\n**先决条件:** Node.js 18+，已安装 Codex CLI。\n\n**安装:**\n\n1. 全局安装 context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 添加到 `~\u002F.codex\u002Fconfig.toml`：\n\n   ```toml\n   [mcp_servers.context-mode]\n   command = \"context-mode\"\n   ```\n\n3. 添加用于强制执行路由和会话跟踪的钩子。创建 `~\u002F.codex\u002Fhooks.json`：\n\n   ```json\n   {\n     \"hooks\": {\n       \"PreToolUse\": [{ \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook codex pretooluse\" }] }],\n       \"PostToolUse\": [{ \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook codex posttooluse\" }] }],\n       \"SessionStart\": [{ \"hooks\": [{ \"type\": \"command\", \"command\": \"context-mode hook codex sessionstart\" }] }]\n     }\n   }\n   ```\n\n   `PreToolUse` 强制执行沙箱路由（阻止危险命令，重定向至 MCP 工具）。`PostToolUse` 捕获会话事件。`SessionStart` 在压缩后恢复状态。\n\n4. 复制路由说明（即使使用钩子，也建议复制以获得完整的路由意识）：\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcodex\u002FAGENTS.md .\u002FAGENTS.md\n   ```\n\n   若需全局使用：`cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcodex\u002FAGENTS.md ~\u002F.codex\u002FAGENTS.md`。全局配置适用于所有项目。如果两者都存在，Codex CLI 会将它们合并。\n\n5. 重启 Codex CLI。\n\n**验证:** 启动一个会话并输入 `ctx stats`。Context-mode 工具应显示并响应。\n\n**路由:** 钩子通过 PreToolUse 以编程方式强制执行路由。PostToolUse 跟踪会话事件。SessionStart 恢复状态。可选的 AGENTS.md 文件为模型提供路由说明。Codex CLI 的钩子系统使用与 Claude Code 相同的 JSON stdin\u002Fstdout 通信协议，但不支持参数或输出修改。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Antigravity\u003C\u002Fstrong> — 仅 MCP，无钩子\u003C\u002Fsummary>\n\n**先决条件:** Node.js 18+，已安装 Antigravity。\n\n**安装:**\n\n1. 全局安装 context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 添加到 `~\u002F.gemini\u002Fantigravity\u002Fmcp_config.json`：\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. 复制路由说明（Antigravity 不支持钩子）：\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fantigravity\u002FGEMINI.md .\u002FGEMINI.md\n   ```\n\n4. 重启 Antigravity。\n\n**验证:** 在 Antigravity 会话中，输入 `ctx stats`。Context-mode 工具应显示并响应。\n\n**路由:** 手动。`GEMINI.md` 文件是唯一的强制手段（约 60% 的合规性）。没有程序化拦截。通过 MCP 协议握手自动检测（`clientInfo.name`），无需手动配置平台。\n\n完整配置：[`configs\u002Fantigravity\u002Fmcp_config.json`](configs\u002Fantigravity\u002Fmcp_config.json) | [`configs\u002Fantigravity\u002FGEMINI.md`](configs\u002Fantigravity\u002FGEMINI.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Kiro\u003C\u002Fstrong> — 带转向文件的钩子\u003C\u002Fsummary>\n\n**先决条件:** Node.js 18+，Kiro 已启用 MCP（设置 > 搜索“MCP”）。\n\n**安装:**\n\n1. 全局安装 context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 添加到您项目的 `.kiro\u002Fsettings\u002Fmcp.json`（或 `~\u002F.kiro\u002Fsettings\u002Fmcp.json` 用于全局配置）：\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"context-mode\"\n       }\n     }\n   }\n   ```\n\n3. 创建 `.kiro\u002Fhooks\u002Fcontext-mode.json`：\n\n   ```json\n   {\n     \"name\": \"context-mode\",\n     \"description\": \"用于保护上下文窗口的 Context-mode 钩子\",\n     \"hooks\": {\n       \"preToolUse\": [\n         { \"matcher\": \"*\", \"command\": \"context-mode hook kiro pretooluse\" }\n       ],\n       \"postToolUse\": [\n         { \"matcher\": \"*\", \"command\": \"context-mode hook kiro posttooluse\" }\n       ]\n     }\n   }\n   ```\n\n4. 复制路由说明。由于 Kiro 的 `agentSpawn`（相当于 SessionStart）尚未实现，因此模型在会话开始时需要一份路由文件：\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fkiro\u002FKIRO.md .\u002FKIRO.md\n   ```\n\n5. 重启 Kiro。\n\n**验证:** 打开 Kiro 面板 > MCP 服务器选项卡，确认“context-mode”显示绿色状态指示灯。在聊天中输入 `ctx stats`。\n\n**路由:** 钩子通过 `preToolUse`\u002F`postToolUse` 以编程方式强制执行路由。`KIRO.md` 文件提供了路由说明，因为 `agentSpawn`（SessionStart 的等效物）尚未连接。工具名称显示为 `@context-mode\u002Fctx_batch_execute`、`@context-mode\u002Fctx_search` 等。通过 MCP 协议握手自动检测。\n\n完整配置文件：[`configs\u002Fkiro\u002Fmcp.json`](configs\u002Fkiro\u002Fmcp.json) | [`configs\u002Fkiro\u002Fagent.json`](configs\u002Fkiro\u002Fagent.json) | [`configs\u002Fkiro\u002FKIRO.md`](configs\u002Fkiro\u002FKIRO.md)\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Zed\u003C\u002Fstrong> — 仅支持MCP，无钩子\u003C\u002Fsummary>\n\n**先决条件:** Node.js 18+，已安装Zed。\n\n**安装:**\n\n1. 全局安装context-mode：\n\n   ```bash\n   npm install -g context-mode\n   ```\n\n2. 将以下内容添加到 `~\u002F.config\u002Fzed\u002Fsettings.json`（Windows: `%APPDATA%\\Zed\\settings.json`）：\n\n   ```json\n   {\n     \"context_servers\": {\n       \"context-mode\": {\n         \"command\": {\n           \"path\": \"context-mode\"\n         }\n       }\n     }\n   }\n   ```\n\n   注意：Zed使用 `\"context_servers\"` 和 `\"command\": { \"path\": \"...\" }` 的语法，而不是其他平台使用的 `\"mcpServers\"` 或 `\"command\": \"...\"`。\n\n3. 复制路由指令（Zed不支持钩子）：\n\n   ```bash\n   cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fzed\u002FAGENTS.md .\u002FAGENTS.md\n   ```\n\n4. 重启Zed（或保存 `settings.json` — Zed会在配置更改时自动重启上下文服务器）。\n\n**验证:** 打开代理面板（`Cmd+Shift+A`），进入设置，检查“context-mode”旁边的指示灯——绿色表示已激活。在代理聊天中输入 `ctx stats`。\n\n**路由:** 手动。`AGENTS.md` 文件是唯一的执行手段（约60%的合规率）。没有程序化的拦截机制。工具名称显示为 `mcp:context-mode:ctx_batch_execute`、`mcp:context-mode:ctx_search` 等。通过MCP协议握手自动检测。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Pi Coding Agent\u003C\u002Fstrong> — 具有完整钩子支持的扩展\u003C\u002Fsummary>\n\n**先决条件:** Node.js 18+，已安装Pi Coding Agent。\n\n**安装:**\n\n1. 克隆扩展：\n\n   ```bash\n   git clone https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode.git ~\u002F.pi\u002Fextensions\u002Fcontext-mode\n   cd ~\u002F.pi\u002Fextensions\u002Fcontext-mode\n   npm install\n   npm run build\n   ```\n\n2. 将以下内容添加到 `~\u002F.pi\u002Fagent\u002Fmcp.json`（或项目级别的 `.pi\u002Fmcp.json`）：\n\n   ```json\n   {\n     \"mcpServers\": {\n       \"context-mode\": {\n         \"command\": \"node\",\n         \"args\": [\"\u002Fhome\u002Fyouruser\u002F.pi\u002Fextensions\u002Fcontext-mode\u002Fnode_modules\u002Fcontext-mode\u002Fstart.mjs\"]\n       }\n     }\n   }\n   ```\n\n   > **注意:** JSON不会展开 `~`。请将 `\u002Fhome\u002Fyouruser` 替换为你的真实主目录（运行 `echo $HOME` 查看）。\n\n3. 重启Pi。\n\n**验证:** 在Pi会话中输入 `ctx stats`。Context-mode工具应出现并响应。\n\n**路由:** 自动。该扩展注册了所有关键生命周期事件（`tool_call`、`tool_result`、`session_start`、`session_before_compact`），从而提供完整的会话连续性和路由执行。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>构建先决条件\u003C\u002Fstrong> \u003Csup>(CentOS、RHEL、Alpine)\u003C\u002Fsup>\u003C\u002Fsummary>\n\nContext Mode在Node.js上使用[better-sqlite3](https:\u002F\u002Fgithub.com\u002FWiseLibs\u002Fbetter-sqlite3)，它为大多数平台提供了预编译的原生二进制文件。在glibc >= 2.31的系统上（Ubuntu 20.04+、Debian 11+、Fedora 34+、macOS、Windows），只需运行 `npm install` 即可，无需任何构建工具。\n\n**Bun用户:** 无需进行原生编译。Context Mode会自动检测Bun，并通过兼容性适配器使用内置的 `bun:sqlite` 模块。`better-sqlite3` 及其所有构建依赖项都会被完全跳过。\n\n在较旧的glibc系统上（CentOS 7\u002F8、RHEL 8、Debian 10），预编译的二进制文件无法加载，better-sqlite3会**自动回退到从源代码编译**，即通过 `prebuild-install || node-gyp rebuild --release` 进行编译。这需要C++20编译器（GCC 10+）、Make和带有setuptools的Python。\n\n**CentOS 8 \u002F RHEL 8**（glibc 2.28）：\n\n```bash\ndnf install -y gcc-toolset-10-gcc gcc-toolset-10-gcc-c++ make python3 python3-setuptools\nscl enable gcc-toolset-10 'npm install -g context-mode'\n```\n\n**CentOS 7 \u002F RHEL 7**（glibc 2.17）：\n\n```bash\nyum install -y centos-release-scl\nyum install -y devtoolset-10-gcc devtoolset-10-gcc-c++ make python3\npip3 install setuptools\nscl enable devtoolset-10 'npm install -g context-mode'\n```\n\n**Alpine Linux:**\n\nAlpine的预编译二进制文件（musl）在better-sqlite3 v12.8.0+中可用。如果使用 `^12.6.2` 的依赖范围，`npm install` 会解析到最新的12.x版本，在Alpine上无需构建工具即可正常工作。如果你锁定较旧的版本：\n\n```bash\napk add build-base python3 py3-setuptools\nnpm install -g context-mode\n```\n\n\u003C\u002Fdetails>\n\n\n\n## 工具\n\n| 工具 | 功能 | 保存的上下文 |\n|---|---|---|\n| `ctx_batch_execute` | 在一次调用中执行多个命令并搜索多个查询。 | 986 KB → 62 KB |\n| `ctx_execute` | 以11种语言运行代码。只有标准输出会进入上下文。 | 56 KB → 299 B |\n| `ctx_execute_file` | 在沙箱中处理文件。原始内容永远不会离开。 | 45 KB → 155 B |\n| `ctx_index` | 将Markdown分块并使用BM25排名索引到FTS5中。 | 60 KB → 40 B |\n| `ctx_search` | 在一次调用中使用多个查询检索索引内容。 | 按需检索 |\n| `ctx_fetch_and_index` | 获取URL、分块并索引。24小时TTL缓存——重复调用会跳过网络。使用 `force: true` 可绕过缓存。 | 60 KB → 40 B |\n| `ctx_stats` | 显示上下文节省量、调用次数和会话统计信息。 | — |\n| `ctx_doctor` | 诊断安装情况：运行时、钩子、FTS5、版本等。 | — |\n| `ctx_upgrade` | 从GitHub升级到最新版本，重新构建并重新配置钩子。 | — |\n\n## 沙箱的工作原理\n\n每次调用 `ctx_execute` 都会启动一个独立的子进程，拥有自己的进程边界。脚本之间无法访问彼此的内存或状态。子进程会运行你的代码，捕获标准输出，而只有这部分输出会进入对话上下文。原始数据——日志文件、API响应、快照——永远不会离开沙箱。\n\n目前支持11种语言运行时：JavaScript、TypeScript、Python、Shell、Ruby、Go、Rust、PHP、Perl、R和Elixir。Bun会被自动检测到，使JS\u002FTS的执行速度提升3至5倍。\n\n经过身份验证的CLI可以通过凭据传递工作——`gh`、`aws`、`gcloud`、`kubectl`、`docker` 会继承环境变量和配置路径，而不会将其暴露给对话。当输出超过5 KB且提供了意图时，Context Mode会切换到基于意图的过滤模式：它会将完整输出索引到知识库中，搜索与你的意图匹配的部分，并仅返回相关结果，同时提供可用于后续查询的可搜索术语词汇表。\n\n## 知识库的工作原理\n\n`ctx_index` 工具会按照标题对 Markdown 内容进行分块，同时保持代码块完整，然后将这些内容存储在一个 **SQLite FTS5**（全文搜索 5）虚拟表中。搜索使用 **BM25 排序**——一种基于概率的相关性算法，它根据词频、逆文档频率以及文档长度归一化来为文档打分。在索引时应用了 **Porter 词干提取**，因此“running”、“runs”和“ran”都会匹配到同一个词干。为了精确的导航查询，标题和各级标题在 BM25 打分中会被赋予 **5 倍权重**。\n\n当你调用 `ctx_search` 时，它会返回围绕匹配查询词的相关内容片段——不是完整的文档，也不是近似结果，而是实际被索引的内容，并且会在你所寻找的关键信息周围进行智能提取。`ctx_fetch_and_index` 将这一功能扩展到了 URL：抓取网页、将 HTML 转换为 Markdown、分块并建立索引。原始页面永远不会进入上下文。你可以使用 `contentType` 参数按类型过滤结果（例如 `code` 或 `prose`）。\n\n### 排序：倒数排名融合\n\n搜索会运行两种并行策略，并通过 **倒数排名融合（RRF）** 将它们合并：\n\n- **Porter 词干提取** — 使用 FTS5 MATCH 和 Porter 分词器。“caching”会匹配“cached”、“caches”、“cach”。\n- **三元子串** — FTS5 的三元组分词器可以匹配部分字符串。“useEff”会找到“useEffect”，“authenticat”会找到“authentication”。\n\nRRF 将这两个排序列表合并成一个单一的结果集，因此在两种策略中都排名靠前的文档，会比只在其中一种策略中排名靠前的文档更靠前。这取代了旧的级联回退方法，在该方法中，只有当 Porter 分词器没有返回任何结果时，才会使用三元子串的结果。\n\n### 近邻重新排序\n\n多词查询会进行额外的重新排序。查询词出现得越接近，结果就会被提升——例如，“session continuity”会让那些查询词相邻出现的段落排名高于“session”和“continuity”相隔数段才出现的页面。\n\n### 模糊纠错\n\n在重新搜索之前，Levenshtein 距离会纠正拼写错误。“kuberntes”会被修正为“kubernetes”，“autentication”会被修正为“authentication”。\n\n### 智能片段\n\n搜索结果采用智能提取，而不是简单的截断。与其返回前 N 个字符（可能会错过重要内容），Context Mode 会找到你的查询词在内容中出现的位置，并返回这些匹配点周围的窗口。\n\n### TTL 缓存\n\n索引后的内容会持久化到每个项目的 SQLite 数据库中，路径为 `~\u002F.context-mode\u002Fcontent\u002F`。当调用 `ctx_fetch_and_index` 处理一个在过去 24 小时内已经索引过的 URL 时，抓取过程会被完全跳过。模型会直接从现有的索引中进行搜索。\n\n- **新鲜（\u003C24 小时）：** 返回缓存提示（0.3KB），而不是重新抓取（48KB+）。模型继续执行 `ctx_search`。\n- **过时（>24 小时）：** 会静默地重新抓取。无需用户操作。\n- **`force: true`：** 忽略缓存，无论 TTL 如何都会重新抓取。\n- **14 天清理：** 启动时会删除超过 14 天的内容数据库和来源。\n\n这意味着使用 `--continue` 继续会话时，索引过的文档会在重启后仍然保留。无需重新抓取，也不会浪费上下文 token。\n\n`ctx_stats` 会分别报告缓存性能：命中次数、避免的数据量、节省的网络请求数量，以及包括缓存在内的总上下文节省量。\n\n### 渐进式限流\n\n- **调用 1–3 次：** 正常结果（每次查询 2 条）\n- **调用 4–8 次：** 减少结果（每次查询 1 条）并发出警告\n- **调用 9 次及以上：** 被阻止——重定向到 `ctx_batch_execute`\n\n## 会话连续性\n\n当上下文窗口满载时，代理会压缩对话——丢弃较旧的消息以腾出空间。如果没有会话跟踪，模型就会忘记它正在编辑哪些文件、正在进行哪些任务、解决了哪些错误，以及你上次询问了什么。\n\nContext Mode 会捕获你在会话期间发生的每一个有意义事件，并将其持久化到每个项目的 SQLite 数据库中。当对话被压缩（或你使用 `--continue` 恢复会话）时，你的工作状态会自动重建——模型会从你上次的提示继续，而不需要你重复任何内容。\n\n会话连续性需要 4 个钩子协同工作：\n\n| 钩子 | 作用 | Claude Code | Gemini CLI | VS Code Copilot | Cursor | OpenCode | KiloCode | OpenClaw | Codex CLI | Antigravity | Kiro | Zed | Pi |\n|---|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n| **PreToolUse** | 在工具执行前强制执行沙盒路由 | 是 | -- | -- | 是 | -- | -- | -- | 是 | -- | 是 | -- | ✓（通过 tool_call 事件） |\n| **PostToolUse** | 捕捉每次工具调用后的事件 | 是 | 是 | 是 | 是 | 插件 | 插件 | 插件 | 是 | -- | 是 | -- | ✓（通过 tool_result 事件） |\n| **UserPromptSubmit** | 捕捉用户的决策和修正 | 是 | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- | -- |\n| **PreCompact** | 在压缩前构建快照 | 是 | 是 | 是 | -- | 插件 | 插件 | 插件 | -- | -- | -- | -- | ✓（通过 session_before_compact 事件） |\n| **SessionStart** | 在压缩或恢复后恢复状态 | 是 | 是 | 是 | -- | -- | -- | 插件 | 是 | -- | -- | -- | ✓（通过 session_start 事件） |\n| | **会话完整性** | **完整** | **高** | **高** | **部分** | **高** | **高** | **高** | **部分** | **--** | **部分** | **--** | **高** |\n\n> **注意：** 完整的会话连续性（捕获 + 快照 + 恢复）适用于 **Claude Code**、**Gemini CLI** 和 **VS Code Copilot**。**OpenCode** 提供 **高** 会话连续性：它会捕捉工具事件并通过插件注入压缩快照，但目前尚未提供 SessionStart 功能（[#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)），因此不支持启动或恢复时的状态还原。**KiloCode** 通过 OpenCodeAdapter 共享与 OpenCode 相同的插件架构，因此其连续性水平取决于 KiloCode 是否支持 SessionStart 功能。**Cursor** 通过 `preToolUse`\u002F`postToolUse` 捕捉工具事件，但目前 Cursor 的验证程序拒绝接受 `session_start` 钩子（[论坛报告](https:\u002F\u002Fforum.cursor.com\u002Ft\u002Funknown-hook-type-sessionstart\u002F149566)），因此尚无法实现压缩后的会话恢复。**OpenClaw** 使用原生网关插件钩子（`api.on()`）来实现完整的会话连续性。**Pi Coding Agent** 通过扩展钩子（`tool_call`、`tool_result`、`session_start`、`session_before_compact`）提供高会话连续性。**Codex CLI** 通过 PreToolUse\u002FPostToolUse\u002FSessionStart 提供基于钩子的会话跟踪，使用与 Claude Code 相同的 JSON stdin\u002Fstdout 协议。**Antigravity**、**Kiro** 和 **Zed** 在当前版本中没有钩子支持，因此无法进行会话跟踪。\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>捕获的内容\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n每次工具调用都会经过钩子，从中提取结构化的事件：\n\n| 类别 | 事件 | 优先级 | 捕获时机 |\n|---|---|---|---|\n| **文件** | 读取、编辑、写入、glob、grep | 关键 (P1) | 工具使用后 |\n| **任务** | 创建、更新、完成 | 关键 (P1) | 工具使用后 |\n| **规则** | CLAUDE.md \u002F GEMINI.md \u002F AGENTS.md 的路径 + 内容 | 关键 (P1) | 会话开始时 |\n| **决策** | 用户修正、偏好（“改用 X”、“不要做 Y”） | 高 (P2) | 用户提示提交时 |\n| **Git** | checkout、commit、merge、rebase、stash、push、pull、diff、status | 高 (P2) | 工具使用后 |\n| **错误** | 工具失败、非零退出码 | 高 (P2) | 工具使用后 |\n| **环境** | 当前工作目录变更、venv、nvm、conda、包安装 | 高 (P2) | 工具使用后 |\n| **MCP 工具** | 所有 `mcp__*` 工具调用及其使用次数 | 普通 (P3) | 工具使用后 |\n| **子代理** | 代理工具调用 | 普通 (P3) | 工具使用后 |\n| **技能** | 斜杠命令调用 | 普通 (P3) | 工具使用后 |\n| **角色** | 人物设定\u002F行为指令（“扮演高级工程师”） | 普通 (P3) | 用户提示提交时 |\n| **意图** | 会话模式分类（调查、实现、调试） | 低 (P4) | 用户提示提交时 |\n| **数据** | 大量用户粘贴的数据引用（>1 KB） | 低 (P4) | 用户提示提交时 |\n| **用户提示** | 每条用户消息（用于恢复最后一条提示） | 关键 (P1) | 用户提示提交时 |\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>会话如何在压缩后保持完整\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n```\nPreCompact 触发\n  → 从 SQLite 中读取所有会话事件\n  → 构建按优先级分层的 XML 快照（≤2 KB）\n  → 将快照存储在 session_resume 表中\n\nSessionStart 触发（来源：“compact”）\n  → 检索存储的快照\n  → 写入结构化事件文件 → 自动索引到 FTS5\n  → 构建包含 15 个类别的会话指南\n  → 将 \u003Csession_knowledge> 指令注入上下文\n  → 模型从上次用户提示处继续，保持完整的工作状态\n```\n\n快照按优先级分层构建——如果 2 KB 的预算紧张，低优先级事件（如意图、MCP 工具调用次数）会首先被舍弃，而关键状态（如当前文件、任务、规则、决策）则始终保留。\n\n压缩后，模型会收到一份 **会话指南**——一个结构化的叙述性文档，包含可操作的部分：\n\n- **最后请求**——用户的最后一条提示，这样模型可以继续工作，而无需询问“我们刚才在做什么？”\n- **任务**——以复选框形式列出，标注完成状态（已完成标记为 `[x]`，未完成为 `[ ]`）\n- **关键决策**——用户修正和偏好（“改用 X”、“不要做 Y”）\n- **修改过的文件**——会话期间涉及的所有文件\n- **未解决的错误**——尚未修复的错误\n- **Git**——执行的操作（checkout、commit、push、status）\n- **项目规则**——CLAUDE.md \u002F GEMINI.md \u002F AGENTS.md 的路径\n- **使用的 MCP 工具**——工具名称及调用次数\n- **子代理任务**——委派工作的摘要\n- **使用的技能**——调用的斜杠命令\n- **环境**——工作目录、环境变量\n- **数据引用**——会话期间粘贴的大段数据\n- **会话意图**——模式分类（实现、调查、评审、讨论）\n- **用户角色**——会话期间设定的行为指令\n\n详细的事件数据也会被索引到 FTS5 中，以便通过 `search()` 函数随时检索。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>各平台的具体情况\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n**Claude Code** — 完整会话支持。所有 5 种钩子都会触发，捕获工具事件、用户决策，构建压缩快照，并在压缩或 `--continue` 后恢复状态。\n\n**Gemini CLI** — 覆盖率较高。PostToolUse（工具使用后）、PreCompact（压缩前）和 SessionStart 都会触发。缺少 UserPromptSubmit，因此无法捕获用户决策和修正——但文件编辑、Git 操作、错误和任务都被完整记录。\n\n**VS Code Copilot** — 覆盖率较高。与 Gemini CLI 相同——PostToolUse、PreCompact 和 SessionStart 都会触发。虽然无法捕获用户决策，但所有工具级别的事件都会被记录。\n\n**Cursor** — 部分覆盖。原生的 `preToolUse` 和 `postToolUse` 钩子会捕获工具事件。`sessionStart` 在 Cursor 文档中有所说明，但目前被其验证器拒绝，因此无法实现会话恢复。路由指令改由 MCP 服务器启动时传递。\n\n**OpenCode** — 部分覆盖。TypeScript 插件通过 `tool.execute.after` 捕获 PostToolUse 事件，但 SessionStart 尚未实现（[#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)）。事件会被存储，但在压缩后不会自动恢复。\n\n**KiloCode** — 部分覆盖。与 OpenCode 共享相同的插件架构，通过 OpenCodeAdapter 实现。TypeScript 插件通过 `tool.execute.after` 捕获 PostToolUse 事件，但 SessionStart 是否可用取决于 KiloCode 的实现。事件会被存储，但可能不会在压缩后自动恢复。\n\n**OpenClaw \u002F Pi Agent** — 覆盖率较高。所有工具生命周期钩子（`after_tool_call`、`before_compaction`、`session_start`）都通过原生网关插件触发。虽然无法捕获用户决策，但文件编辑、Git 操作、错误和任务都被完整记录。如果较旧版本的网关不支持压缩钩子，则会回退到数据库快照重建。详情请参阅 [`docs\u002Fadapters\u002Fopenclaw.md`](docs\u002Fadapters\u002Fopenclaw.md)。\n\n**Codex CLI** — 基于钩子的会话跟踪。PreToolUse 强制执行路由，PostToolUse 捕获事件，SessionStart 在压缩后恢复状态。与 Claude Code 使用相同的通信协议。PreCompact 和 UserPromptSubmit 尚未实现，因此压缩快照依赖于数据库重建。\n\n**Antigravity** — 不支持会话功能。与 Codex CLI 相同——没有钩子，无法捕获事件。需要手动将 `GEMINI.md` 复制到项目根目录。可通过 MCP 协议握手（`clientInfo.name`）自动检测。\n\n**Zed** — 不支持会话功能。与 Codex CLI 相同——没有钩子，无法捕获事件。同样需要手动将 `AGENTS.md` 复制到项目根目录。可通过 MCP 协议握手（`clientInfo.name`）自动检测。\n\n**Kiro** — 部分覆盖。原生的 `preToolUse` 和 `postToolUse` 钩子会捕获工具事件并强制执行沙箱路由。`agentSpawn`（Kiro 版本的 SessionStart）尚未实现，因此无法在压缩后恢复会话。需要手动将 `KIRO.md` 复制到项目根目录。可通过 MCP 协议握手（`clientInfo.name`）自动检测。\n\n**Pi 编程代理** — 覆盖率较高。该扩展注册了所有关键生命周期事件：`tool_call`（PreToolUse）、`tool_result`（PostToolUse）、`session_start`（SessionStart）以及 `session_before_compact`（PreCompact）。文件编辑、Git 操作、错误和任务都被完整记录。压缩后的会话恢复可以通过该扩展的事件钩子实现。\n\n\u003C\u002Fdetails>\n\n## 平台兼容性\n\n| 功能 | Claude Code | Gemini CLI | VS Code Copilot | Cursor | OpenCode | KiloCode | OpenClaw | Codex CLI | Antigravity | Kiro | Zed | Pi |\n|---|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|:---:|\n| MCP 服务器 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 |\n| 工具调用前钩子 | 是 | 是 | 是 | 是 | 插件 | 插件 | 插件 | — | — | 是 | — | 是（扩展） |\n| 工具调用后钩子 | 是 | 是 | 是 | 是 | 插件 | 插件 | 插件 | — | — | 是 | — | 是（扩展） |\n| 会话开始钩子 | 是 | 是 | 是 | — | — | — | 插件 | — | — | — | — | 是（扩展） |\n| 压缩前钩子 | 是 | 是 | 是 | — | 插件 | 插件 | 插件 | — | — | — | — | 是（扩展） |\n| 可修改参数 | 是 | 是 | 是 | 是 | 插件 | 插件 | 插件 | — | — | — | — | 是（扩展） |\n| 可阻止工具 | 是 | 是 | 是 | 是 | 插件 | 插件 | 插件 | — | — | 是 | — | 是（扩展） |\n| 实用命令（ctx） | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是（\u002Fctx-stats、\u002Fctx-doctor） |\n| 斜杠命令 | 是 | — | — | — | — | — | — | — | — | — | — | — |\n| 插件市场 | 是 | — | — | — | — | — | — | — | — | — | — | — |\n\n> **OpenCode** 使用 TypeScript 插件范式——钩子通过 `tool.execute.before`、`tool.execute.after` 和 `experimental.session.compacting` 以进程内函数的形式运行，提供与基于 Shell 的钩子相同的路由强制和会话连续性。SessionStart 尚不可用（[#14808](https:\u002F\u002Fgithub.com\u002Fsst\u002Fopencode\u002Fissues\u002F14808)），但压缩恢复可通过插件的压缩钩子实现。\n>\n> **KiloCode** 通过 OpenCodeAdapter 共享与 OpenCode 相同的 TypeScript 插件架构，具有平台特定的配置路径（`kilo.json` 代替 `opencode.json`，`~\u002F.config\u002Fkilo\u002F` 代替 `~\u002F.config\u002Fopencode\u002F`）。钩子功能取决于 KiloCode 对插件接口的实现。\n>\n> **OpenClaw** 以原生网关插件的形式在 Pi Agent 会话中运行上下文模式。钩子通过 `api.on()`（工具\u002F生命周期）和 `api.registerHook()`（命令）注册。所有工具拦截和压缩钩子均受支持。请参阅 [`docs\u002Fadapters\u002Fopenclaw.md`](docs\u002Fadapters\u002Fopenclaw.md)。\n>\n> **Codex CLI**、**Antigravity** 和 **Zed** 不支持钩子。它们仅依赖手动复制的路由指令文件（`AGENTS.md` \u002F `GEMINI.md`）进行强制执行（约 60% 的合规性）。有关复制说明，请参阅各平台的安装部分。Antigravity 和 Zed 通过 MCP 协议握手自动检测——无需手动平台配置。\n>\n> **Kiro** 支持原生的 `preToolUse` 和 `postToolUse` 钩子，用于路由强制和工具事件捕获。`agentSpawn`（相当于 SessionStart）和 `stop` 尚未连接。需要将 `KIRO.md` 手动复制到项目根目录。Kiro 通过 MCP 协议握手（`clientInfo.name`）自动检测。\n>\n> **Pi 编码代理** 以扩展形式运行上下文模式，完全支持钩子。该扩展注册了 `tool_call`、`tool_result`、`session_start` 和 `session_before_compact` 事件，提供了高度的会话连续性覆盖。MCP 服务器提供 6 种沙盒工具。\n\n### 路由强制\n\n钩子以编程方式拦截工具调用——它们可以阻止危险命令，并在执行前将其重定向到沙盒。指令文件通过提示指令引导模型，但无法阻止任何操作。**请务必在支持的情况下启用钩子。**\n\n> **注意：** 路由指令文件此前会在首次会话启动时自动写入项目目录。为防止污染 Git 树，此功能已被禁用（[#158](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F158)、[#164](https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F164)）。支持钩子的平台（Claude Code、Gemini CLI、VS Code Copilot、OpenCode、OpenClaw）通过钩子注入路由，无需文件。不支持钩子的平台（Codex、Zed、Cursor、Kiro、Antigravity）则需要一次性手动复制——请参阅各平台的安装部分。\n\n| 平台 | 钩子 | 指令文件 | 使用钩子 | 不使用钩子 |\n|---|:---:|---|:---:|:---:|\n| Claude Code | 是（自动） | [`CLAUDE.md`](configs\u002Fclaude-code\u002FCLAUDE.md) | **节省约 98%** | 约节省 60% |\n| Gemini CLI | 是 | [`GEMINI.md`](configs\u002Fgemini-cli\u002FGEMINI.md) | **节省约 98%** | 约节省 60% |\n| VS Code Copilot | 是 | [`copilot-instructions.md`](configs\u002Fvscode-copilot\u002Fcopilot-instructions.md) | **节省约 98%** | 约节省 60% |\n| Cursor | 是 | [`context-mode.mdc`](configs\u002Fcursor\u002Fcontext-mode.mdc) | **节省约 98%** | 约节省 60% |\n| OpenCode | 插件 | [`AGENTS.md`](configs\u002Fopencode\u002FAGENTS.md) | **节省约 98%** | 约节省 60% |\n| OpenClaw | 插件 | [`AGENTS.md`](configs\u002Fopenclaw\u002FAGENTS.md) | **节省约 98%** | 约节省 60% |\n| Codex CLI | — | [`AGENTS.md`](configs\u002Fcodex\u002FAGENTS.md) | — | 约节省 60% |\n| Antigravity | — | [`GEMINI.md`](configs\u002Fantigravity\u002FGEMINI.md) | — | 约节省 60% |\n| Kiro | 是 | [`KIRO.md`](configs\u002Fkiro\u002FKIRO.md) | **节省约 98%** | 约节省 60% |\n| Zed | — | [`AGENTS.md`](configs\u002Fzed\u002FAGENTS.md) | — | 约节省 60% |\n| Pi | ✓ | [`AGENTS.md`](configs\u002Fpi\u002FAGENTS.md) | **节省约 98%** | 约节省 60% |\n\n如果没有钩子，一次未被路由的 `curl` 或 Playwright 截图就可能向上下文中注入 56 KB 数据——从而抹去整个会话的节省成果。\n\n有关完整功能对比，请参阅 [`docs\u002Fplatform-support.md`](docs\u002Fplatform-support.md)。\n\n## 实用命令\n\n**在任何 AI 会话中**——只需输入命令即可。LLM 会自动调用 MCP 工具：\n\n```\nctx stats       → 上下文节省量、调用次数、会话报告\nctx doctor      → 诊断运行时、钩子、FTS5、版本\nctx upgrade     → 从 GitHub 更新、重建、重新配置钩子\n```\n\n**在终端中**——无需 AI 会话即可直接运行：\n\n```bash\ncontext-mode doctor\ncontext-mode upgrade\n```\n\n适用于**所有平台**。在 Claude Code 中，还提供斜杠命令（`\u002Fctx-stats`、`\u002Fctx-doctor`、`\u002Fctx-upgrade`）。\n\n## 基准测试\n\n| 场景 | 原始数据 | 上下文 | 节省 |\n|---|---|---|---|\n| Playwright 截图 | 56.2 KB | 299 B | 99% |\n| GitHub Issues（20 条） | 58.9 KB | 1.1 KB | 98% |\n| 访问日志（500 次请求） | 45.1 KB | 155 B | 100% |\n| Context7 React 文档 | 5.9 KB | 261 B | 96% |\n| 分析 CSV（500 行） | 85.5 KB | 222 B | 100% |\n| Git 日志（153 次提交） | 11.6 KB | 107 B | 99% |\n| 测试输出（30 个测试套件） | 6.0 KB | 337 B | 95% |\n| 代码库研究（子代理） | 986 KB | 62 KB | 94% |\n\n在整个会话中：315 KB 的原始输出降至 5.4 KB。会话时间从约 30 分钟延长至约 3 小时。\n\n[包含 21 个场景的完整基准测试数据 →](BENCHMARK.md)\n\n## 试一试\n\n这些提示开箱即用。每执行一个提示后，运行 `\u002Fcontext-mode:ctx-stats` 即可查看上下文节省情况。\n\n**深度代码库研究** — 5 次调用，62 KB 上下文（原始：986 KB，节省 94%）\n```\n研究 https:\u002F\u002Fgithub.com\u002Fmodelcontextprotocol\u002Fservers — 架构、技术栈、主要贡献者、未解决的问题以及最近的活动。然后运行 \u002Fcontext-mode:ctx-stats。\n```\n\n**Git 历史分析** — 1 次调用，5.6 KB 上下文\n```\n克隆 https:\u002F\u002Fgithub.com\u002Ffacebook\u002Freact，并分析最近 500 次提交：主要贡献者、按月统计的提交频率以及更改最多的文件。然后运行 \u002Fcontext-mode:ctx-stats。\n```\n\n**网页抓取** — 1 次调用，3.2 KB 上下文\n```\n获取 Hacker News 首页，提取所有帖子的标题、评分和域名，并按域名分组。然后运行 \u002Fcontext-mode:ctx-stats。\n```\n\n**大型 JSON API** — 原始数据 7.5 MB → 0.9 KB 上下文（节省 99%）\n```\n创建一个本地服务器，返回一个包含 20,000 条记录的 7.5 MB 大小的 JSON 文件，其中在索引 13000 处隐藏着一个秘密。获取该端点，找到隐藏的记录，并准确展示其内容。然后运行 \u002Fcontext-mode:ctx-stats。\n```\n\n**文档搜索** — 2 次调用，1.8 KB 上下文\n```\n获取 React useEffect 的文档，对其进行索引，并查找带有代码示例的清理模式。然后运行 \u002Fcontext-mode:ctx-stats。\n```\n\n**会话连续性** — 全状态下的压缩恢复\n```\n开始一个多步骤任务：“使用 Express 创建一个 REST API — 添加路由、测试和错误处理。” 在进行了 20 多次工具调用后，输入 ctx stats 查看会话事件数量。当上下文被压缩时，模型会从您上次的提示继续执行，任务、文件和决策均保持不变——无需重新提示。\n```\n\n## 隐私与架构\n\nContext Mode 并非 CLI 输出过滤器或云端分析仪表盘。它运行在 MCP 协议层——原始数据始终处于沙盒子进程中，绝不会进入您的上下文窗口。网页、API 响应、文件分析、Playwright 截图、日志文件等，所有内容都在完全隔离的环境中处理。\n\n**没有任何数据离开您的机器。** 无遥测、无云端同步、无使用跟踪、无需注册账号。您的代码、您的提示、您的会话数据——全部本地存储。SQLite 数据库存放在您的主目录中，会话结束后即被销毁。\n\n这是一种刻意的架构选择，而非功能缺失。上下文优化应在源头进行，而不是在需要按用户订阅的仪表盘中完成。隐私优先是我们的理念——每一个设计决策都以此为基础。[许可证 →](#license)\n\n## 安全性\n\nContext Mode 强制执行您已使用的相同权限规则——但将其扩展到 MCP 沙盒中。如果您禁止 `sudo`，那么在 `ctx_execute`、`ctx_execute_file` 和 `ctx_batch_execute` 中同样会被阻止。\n\n**无需任何设置。** 如果您尚未配置任何权限，则一切保持不变。只有在您添加规则时才会生效。\n\n```json\n{\n  \"permissions\": {\n    \"deny\": [\n      \"Bash(sudo *)\",\n      \"Bash(rm -rf \u002F*)\",\n      \"Read(.env)\",\n      \"Read(**\u002F.env*)\"\n    ],\n    \"allow\": [\n      \"Bash(git:*)\",\n      \"Bash(npm:*)\"\n    ]\n  }\n}\n```\n\n将此配置添加到项目的 `.claude\u002Fsettings.json` 文件中（或全局规则则添加到 `~\u002F.claude\u002Fsettings.json`）。所有平台都会读取 Claude Code 的设置格式来加载安全策略——包括 Gemini CLI、VS Code Copilot 和 OpenCode。不过，Codex CLI 不支持钩子，因此无法实施安全控制。\n\n规则的格式为 `Tool(要匹配的内容)`，其中 `*` 表示“任意内容”。\n\n通过 `&&`、`;` 或 `|` 连接的命令会被拆分——每一部分都会单独检查。例如，`echo hello && sudo rm -rf \u002Ftmp` 会被阻止，因为其中的 `sudo` 部分符合拒绝规则。\n\n**deny** 总是优先于 **allow**。更具体的（项目级）规则会覆盖全局规则。\n\n## 贡献\n\n请参阅 [CONTRIBUTING.md](CONTRIBUTING.md)，了解开发流程和 TDD 准则。\n\n```bash\ngit clone https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode.git\ncd context-mode && npm install && npm test\n```\n\n## 许可证\n\n根据 [Elastic License 2.0](LICENSE) 授权（源代码开放）。您可以使用、fork、修改并分发它。但有两点限制：不得将其作为托管\u002F管理服务提供，也不得移除许可声明。我们选择 ELv2 而不是 MIT 许可证，是因为 MIT 允许将代码重新打包成竞争性的闭源 SaaS——而 ELv2 则可以防止这种情况发生，同时仍保持源代码对所有人开放。","# Context Mode 快速上手指南\n\nContext Mode 是一个 MCP（Model Context Protocol）服务器，旨在解决 AI 代理在长对话中上下文窗口被原始数据填满的问题。它通过沙盒工具将大数据量操作隔离在上下文之外，并利用 SQLite 和全文检索（FTS5）保持会话连续性，实现高达 98% 的上下文节省。\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**：macOS, Linux, 或 Windows (WSL2 推荐)\n*   **Node.js**：版本 18 或更高 (`node -v` 检查)\n*   **目标平台**：已安装以下任一 AI 编程助手：\n    *   Claude Code (v1.0.33+)\n    *   Gemini CLI\n    *   VS Code (需安装 Copilot Chat v0.32+)\n    *   Cursor (需开启 Agent 模式)\n    *   OpenCode\n*   **网络环境**：由于依赖 npm 注册表，国内用户建议配置淘宝镜像源以加速安装：\n    ```bash\n    npm config set registry https:\u002F\u002Fregistry.npmmirror.com\n    ```\n\n## 安装步骤\n\n根据您的使用平台选择对应的安装方式。\n\n### 1. Claude Code (推荐，全自动)\n\n适用于已安装 Claude Code 的用户，支持插件市场自动路由。\n\n1.  **更新客户端** (如果 `\u002Fplugin` 命令不可用)：\n    ```bash\n    brew upgrade claude-code\n    # 或\n    npm update -g @anthropic-ai\u002Fclaude-code\n    ```\n\n2.  **安装插件**：\n    ```bash\n    \u002Fplugin marketplace add mksglu\u002Fcontext-mode\n    \u002Fplugin install context-mode@context-mode\n    ```\n\n3.  **重启** Claude Code 或运行 `\u002Freload-plugins`。\n\n### 2. Gemini CLI \u002F VS Code Copilot \u002F Cursor \u002F OpenCode\n\n这些平台需要全局安装并手动配置钩子（Hooks）。\n\n1.  **全局安装**：\n    ```bash\n    npm install -g context-mode\n    ```\n\n2.  **配置文件设置** (根据平台选择其一)：\n\n    *   **Gemini CLI**: 编辑 `~\u002F.gemini\u002Fsettings.json`，添加 MCP 服务器及 `BeforeTool`, `AfterTool`, `PreCompress`, `SessionStart` 钩子配置（参考原文详细 JSON 结构）。\n    *   **VS Code Copilot**: 在项目根目录创建 `.vscode\u002Fmcp.json` 注册服务器，并在 `.github\u002Fhooks\u002F` 下创建钩子配置文件。\n    *   **Cursor**: 在项目根目录创建 `.cursor\u002Fmcp.json` 和 `.cursor\u002Fhooks.json`。**注意**：Cursor 需额外复制路由规则文件：\n        ```bash\n        mkdir -p .cursor\u002Frules\n        cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fcursor\u002Fcontext-mode.mdc .cursor\u002Frules\u002Fcontext-mode.mdc\n        ```\n    *   **OpenCode**: 在 `opencode.json` 中注册 MCP 和插件，并可选复制 `AGENTS.md` 到项目根目录以增强模型感知。\n\n3.  **重启** 对应的编辑器或 CLI 工具。\n\n## 基本使用\n\n安装完成后，Context Mode 会自动拦截高消耗的工具调用（如文件读取、Shell 执行、网页抓取），将其转为沙盒操作并索引化，无需手动切换工具。\n\n### 验证安装\n\n在聊天窗口中输入以下命令检查状态。所有检查项应显示 `[x]` 或正常返回数据。\n\n**Claude Code:**\n```bash\n\u002Fcontext-mode:ctx-doctor\n```\n\n**其他平台 (Gemini, VS Code, Cursor, OpenCode):**\n直接在对话框输入：\n```text\nctx doctor\n```\n\n### 查看上下文节省效果\n\n查看当前会话的上下文节省统计，包括每个工具的 Token 消耗和节省比例：\n\n**Claude Code:**\n```bash\n\u002Fcontext-mode:ctx-stats\n```\n\n**其他平台:**\n```text\nctx stats\n```\n\n### 日常交互示例\n\n您无需改变原有的提问习惯。当您需要让 AI 读取大文件或执行复杂命令时，直接下达指令即可，Context Mode 会在后台自动优化：\n\n*   **用户**: \"读取项目中所有的日志文件并总结错误。\"\n    *   *后台行为*: 自动调用 `ctx_execute_file` 而非原生 `read_file`，避免大量日志涌入上下文。\n*   **用户**: \"搜索代码库中所有包含 'TODO' 的地方。\"\n    *   *后台行为*: 自动调用 `ctx_search` 进行索引检索，仅返回相关片段。\n*   **用户**: \"继续刚才的任务。\"\n    *   *后台行为*: 利用 SQLite 记录的会话历史，模型能准确回忆之前的文件编辑状态和任务进度，即使上下文窗口曾发生过压缩。\n\n> **提示**: 如果需要升级工具或修复钩子，可运行 `ctx upgrade` (或在 Claude Code 中运行 `\u002Fcontext-mode:ctx-upgrade`)。","资深后端工程师正在利用 AI 助手排查一个涉及多个微服务日志和 GitHub Issue 的复杂生产事故，需要频繁调用工具获取大量原始数据。\n\n### 没有 context-mode 时\n- **上下文迅速耗尽**：每次调用 Playwright 截图或拉取数十个 GitHub Issue，都会将几十 KB 的原始数据直接堆入对话窗口，短短半小时就占用了 40% 的上下文额度。\n- **关键记忆丢失**：当系统被迫压缩对话以节省空间时，AI 会“遗忘”之前编辑过哪些文件、哪些任务正在进行中，导致重复劳动或逻辑断层。\n- **隐私与噪音风险**：敏感的访问日志和无关的原始数据明文暴露在上下文中，既增加了隐私泄露风险，又干扰了模型对核心问题的判断。\n- **会话无法延续**：一旦开启新对话，之前的排查进度和决策记录全部清零，无法实现跨会话的知识继承。\n\n### 使用 context-mode 后\n- **极致压缩上下文**：context-mode 将 315 KB 的原始工具数据沙箱化处理，仅保留 5.4 KB 的索引引用，实现了 98% 的上下文节省，让长程任务成为可能。\n- **智能状态回溯**：所有文件修改、Git 操作和用户决策被自动存入 SQLite 索引；即使对话被压缩，AI 也能通过 BM25 搜索精准召回相关片段，无缝接续工作流。\n- **隐私优先架构**：原始敏感数据始终隔离在沙箱中，只有经过筛选的相关信息才会按需呈现，从源头保障了数据安全。\n- **灵活的会话管理**：支持“断点续传”式的深度协作，同时也提供“一键清空”选项，确保新任务能在完全干净的环境中启动，互不干扰。\n\ncontext-mode 通过虚拟化上下文层，彻底解决了 AI 代理在处理海量数据时的记忆丢失与资源瓶颈问题，让长周期复杂开发任务变得连续且高效。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fmksglu_context-mode_126e0fa6.png","mksglu","Mert Köseoğlu","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fmksglu_c89107af.jpg","engineer",null,"London","bm.ksglu@gmail.com","mksg.lu","https:\u002F\u002Fgithub.com\u002Fmksglu",[85,89,93],{"name":86,"color":87,"percentage":88},"TypeScript","#3178c6",50.4,{"name":90,"color":91,"percentage":92},"JavaScript","#f1e05a",48.9,{"name":94,"color":95,"percentage":96},"Shell","#89e051",0.7,6419,420,"2026-04-02T22:24:53","NOASSERTION","Linux, macOS, Windows","未说明",{"notes":104,"python":102,"dependencies":105},"该工具是一个基于 Node.js 的 MCP 服务器，主要依赖 Node.js 18+ 环境。不同平台（Claude Code, Gemini CLI, VS Code Copilot, Cursor, OpenCode）需要安装全局包并配置相应的 hooks 或规则文件以实现自动路由。核心功能依赖 SQLite 数据库进行会话状态跟踪和全文检索。",[106,107,108],"Node.js 18+","npm","SQLite (内置 FTS5)",[15,36],[111,112,113,114,115,116,117,118,119,120,121],"claude","claude-code","claude-code-plugins","mcp","skills","codex","copilot","opencode","antigravity","kiro","openclaw","2026-03-27T02:49:30.150509","2026-04-06T05:32:26.172370",[125,130,135,140,145,149],{"id":126,"question_zh":127,"answer_zh":128,"source_url":129},11037,"如何在 Windows 上安装 context-mode？遇到 '[' is not recognized 错误怎么办？","在 Windows 上运行 `npm install -g context-mode` 时，如果终端报错 `'[' is not recognized` 或 `'true' is not recognized`，这是因为安装脚本中包含了 Linux\u002FMac 专用的 Shell 命令。解决方案是确保使用兼容的终端环境（如 Git Bash 或 WSL），或者等待维护者修复 Windows 安装脚本。如果遇到此类问题，建议检查是否使用了 nvm4w (Node Version Manager for Windows) 并参考最新文档。如果问题依旧，请提交新的 Issue 反馈，以便团队更新 README 中的 Windows 安装指南。","https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F156",{"id":131,"question_zh":132,"answer_zh":133,"source_url":134},11038,"在 Windows 的 Claude Code 中启动插件失败，提示 'stderr: spawn sh ENOENT' 或 'MCP server failed' 如何解决？","此错误通常是因为 Windows 系统默认没有 `sh` (Bash) 命令，而插件尝试调用它。解决方法是确保你的环境中安装了 Git Bash 并将其添加到了系统 PATH 中，或者使用 WSL (Windows Subsystem for Linux)。维护者已发布修复版本（如 v0.9.17），请尝试升级插件到最新版本。如果问题仍然存在，可以通过运行 `\u002Fcontext-mode:stats` 命令来诊断当前会话状态，确认插件是否正确加载。","https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F26",{"id":136,"question_zh":137,"answer_zh":138,"source_url":139},11039,"为什么在启用 context-mode 后无法使用 curl 或 wget 命令？","这是 context-mode 的安全机制。插件会拦截直接的 `curl` 或 `wget` 调用，以防止未经沙箱处理的网络请求。当被拦截时，你会收到提示：'context-mode: curl\u002Fwget blocked'。正确的做法是使用插件提供的专用 MCP 工具：\n1. 获取并索引 URL 内容：使用 `mcp__context-mode__fetch_and_index(url, source)`。\n2. 在沙箱中执行 HTTP 调用：使用 `mcp__context-mode__execute(language, code)`。\n不要重试原始的 curl\u002Fwget 命令，而是改用上述工具函数。","https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F15",{"id":141,"question_zh":142,"answer_zh":143,"source_url":144},11040,"如何正确为 Opencode 或 Kilo Code 安装和配置 context-mode 插件？","目前直接将 bundle 文件放置在 `~\u002F.cache\u002Fopencode` 或 `~\u002F.cache\u002Fkilo` 目录下并不是官方推荐的安装方式，这可能导致插件无法被正确识别。正确的做法是通过 npm 部署专门的 Opencode 插件包。如果你正在开发或贡献代码，请确保：\n1. 针对 `next` 分支提交 PR（这是预发布分支）。\n2. 遵循 TDD 原则编写测试。\n3. 如果修改了配置路径或安装步骤，务必更新 README 文档。\n4. 验证 `\u002Fcontext-mode:ctx-upgrade` 命令在更改后仍能正常工作。\n5. 提交前运行 `npm test` 和 `npm run typecheck`。","https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fissues\u002F163",{"id":146,"question_zh":147,"answer_zh":148,"source_url":134},11041,"如何查看 context-mode 的运行统计信息以诊断问题？","你可以使用内置命令 `\u002Fcontext-mode:stats` 来查看当前会话的详细统计信息。该命令会输出一个表格，包含以下关键指标：\n- Session (会话时长)\n- Tool calls (工具调用次数)\n- Total data processed (处理的数据总量)\n- Kept in sandbox (保留在沙箱中的数据量)\n这些数据有助于判断插件是否正常工作以及资源消耗情况。",{"id":150,"question_zh":151,"answer_zh":152,"source_url":129},11042,"context-mode 支持哪些平台？如果在非标准平台上遇到问题该怎么办？","context-mode 主要支持 VS Code Copilot、Claude Code、Opencode 和 Kilo Code 等平台。对于 Windows 用户，早期版本可能存在兼容性问题（如缺少 bash 环境），但维护者正在持续改进（例如优化 Windows 安装文档和脚本）。如果你在任何平台上遇到未记录的错误或行为异常，强烈建议开设新的 Issue 并提供详细的复现步骤、错误日志和平台版本信息。用户的反馈对于修复特定平台（尤其是 Windows）的边缘情况非常有价值。",[154,159,164,169,174,179,184,189,194,199,204,209,214,219,224,229,234,239,244,249],{"id":155,"version":156,"summary_zh":157,"released_at":158},56731,"v1.0.59","## v1.0.59\n\nv1.0.58 的热修复 — 在 Codex 配置中缺少 `PreToolUse` 钩子，以及在 Cursor 配置中缺少 `stop` 钩子。\n\n### 修复\n\n- **Codex CLI**: 在 `configs\u002Fcodex\u002Fhooks.json` 和 README 安装说明中添加了 `PreToolUse` 钩子。`PreToolUse` 会强制执行沙箱路由（在 v1.0.58 中缺失）。\n- **Codex CLI**: 从 README 的连续性表格和会话描述中移除了所有过时的“不支持钩子”相关引用。\n- **Cursor**: 在 `configs\u002Fcursor\u002Fhooks.json` 中添加了 `stop` 钩子条目。\n\n### 升级\n\n```bash\nnpm install -g context-mode@1.0.59\n```\n\n**完整变更日志**: https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fcompare\u002Fv1.0.58...v1.0.59","2026-04-02T18:15:47",{"id":160,"version":161,"summary_zh":162,"released_at":163},56732,"v1.0.58","## v1.0.58\n\n### 功能特性\n\n- **feat: Codex CLI 全面支持钩子** — 适配器从“仅限 MCP”重写为“json-stdio”。现已支持 5 种钩子事件（PreToolUse、PostToolUse、SessionStart、UserPromptSubmit、Stop）。与 Claude Code 使用相同的通信协议。新增 19 个 TDD 测试。源码证明位于 `codex-rs\u002Fhooks\u002Fschema\u002Fgenerated\u002F`。彻底打破了长期以来“Codex 没有钩子”的误解。\n\n- **feat: Cursor 增加 stop + afterAgentResponse 钩子** — 新增 stop 钩子（传入 conversation_id、status、loop_count、transcript_path，返回 followup_message 以继续循环）以及 afterAgentResponse 钩子（即发即收，捕获完整响应文本）。新增 7 个 TDD 测试。源码证明位于 `cursor\u002Fplugins\u002Fcontinual-learning-stop.ts`。\n\n### Bug 修复\n\n- **fix: SQLite_BUSY 错误及重试逻辑** — 数据库操作现采用指数退避策略进行重试，不再直接崩溃。关闭了 #218 问题。\n- **fix: Windows\u002FLinux 上 CI 测试不稳定** — 解决了测试间歇性失败的问题。\n- **fix: 修正 Pi Agent 的 mcp.json 路径** — 将路径由 `~\u002F.pi\u002Fsettings\u002Fmcp.json` 改为 `~\u002F.pi\u002Fagent\u002Fmcp.json`。并添加注释说明 JSON 不会展开 `~` 符号。PR #220 由 @trader-payne 提交。\n\n### 代码重构\n\n- **refactor(opencode): 设置读取、插件根目录检测、动态平台命名** — PR #210 由 @mikij 提交。配置优先级现偏向已注册 context-mode 插件的文件。为 KiloCode 引入基于缓存的插件根目录检测机制。完成 `.kilocode` → `.kilo` 的迁移。关闭了 #208 问题。\n  \n- **refactor(opencode): 修复全部 7 项代码评审意见** — 移除未使用的导入、替换脆弱的 isGlobalConfig 写法、在插件中去重 getSessionDir\u002FgetDBPath 方法、提取 hasContextModePlugin 辅助函数。\n\n- **refactor(plugin): 在 ContextModePlugin 中直接初始化适配器** — PR #221。\n\n### 文档更新\n\n- **docs: platform-support.md** — Codex CLI 从“仅限 MCP”更新为全面支持钩子；Cursor 更新了 stop 和 afterAgentResponse 钩子。更新了所有对比表格、能力矩阵以及响应格式相关引用。\n- **docs: README.md** — 添加了 Codex hooks.json 的安装步骤。更新了 Cursor 的 stop 钩子配置，并修正了 Pi Agent 的路径。\n\n### 贡献者\n\n- @mikij — PR #210（OpenCode\u002FKiloCode 重构）\n- @trader-payne — PR #220（Pi mcp.json 路径修复）\n\n**完整变更日志**: https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fcompare\u002Fv1.0.57...v1.0.58","2026-04-02T18:04:25",{"id":165,"version":166,"summary_zh":167,"released_at":168},56733,"v1.0.57","## v1.0.57\n\n### 错误修复\n\n- **修复：会话统计和 FTS5 搜索索引现在会在 `\u002Fclear` 命令执行时重置** — 之前，执行 `\u002Fclear` 命令会清除对话内容，但统计信息和已索引的内容仍会保留，因为 MCP 服务器进程会一直运行。现在，SessionStart 钩子会在清空事件发生时写入一个 `.clear-stats` 标记，而 `ctx_stats` 在读取统计信息前会检查该标记。同时，FTS5 内容存储也会被销毁并重新创建。此外，`ctx_stats` 现在还接受 `reset: true` 参数，用于手动重置统计信息。\n\n**完整变更日志**：https:\u002F\u002Fgithub.com\u002Fmksglu\u002Fcontext-mode\u002Fcompare\u002Fv1.0.56...v1.0.57","2026-04-02T00:28:50",{"id":170,"version":171,"summary_zh":172,"released_at":173},56734,"v1.0.56","## v1.0.56\n\n**48 个文件被修改，新增 908 行，删除 3,121 行** — 这是一个以代码清理为主的版本，移除了废弃代码、强化了沙箱环境，并修复了社区报告的真实漏洞。\n\n### 漏洞修复\n\n- **修复：Shell 的 TMPDIR 指向项目根目录** — `os.tmpdir()` 会读取 `TMPDIR` 环境变量，而某些 Shell 会将其设置为项目根目录。这导致 Shell 命令将临时\u002F缓存目录（如 `node-compile-cache\u002F`、`nx-native-file-cache-*\u002F`、`tsx-*\u002F`）写入工作树中。现在通过 `getconf DARWIN_USER_TEMP_DIR`（macOS）、`mktemp`（Linux）或 `TEMP`（Windows）来获取真正的系统临时目录。基于 @vytautas-petrikas 提交的 PR #209。\n\n- **修复：`ctx_execute` 被用作文件写入绕过** — 当用户拒绝 `Bash(python:*)` 时，路由规则的引导会使模型转向 `ctx_execute(python, \"Path(...).write_text(...)\")`，从而绕过拒绝规则。为此，在路由模板中添加了 `\u003Cfile_writing_policy>` 块，并强化了 `\u003Cforbidden_actions>` 和 `\u003Cartifact_policy>`。基于 @shauneccles 提交的 PR #202。关闭了 #201。\n\n- **修复（OpenCode）：移除过时的 AGENTS.md 自动写入** — OpenCode 插件会在每次启动时将 `AGENTS.md` 写入项目根目录，这与文档中“不会写入任何路由文件”的说明相矛盾。路由执行实际上是由 `tool.execute.before` 和 `tool.execute.after` 钩子完成的，因此文件写入是多余的，还会污染项目目录。基于 @rich-jojo 提交的 PR #196。关闭了 #195。\n\n- **修复（Claude Code）：当插件已有 `hooks.json` 时，跳过 `settings.json` 钩子注册** — 防止在插件已提供自身钩子配置的情况下出现重复的钩子条目。（#211）\n\n- **修复：当原生二进制文件缺失时自动重建 `better-sqlite3`** — 在启动时检测到 ABI 不匹配时，会触发自动重建，而不是直接抛出 `MODULE_NOT_FOUND` 错误。关闭了 #206。\n\n- **修复：移除 `CONTEXT_MODE_NODE` 环境变量** — 现在自动的 ABI 兼容性已经足够，手动覆盖已变得多余且复杂。（#203）\n\n### 功能改进\n\n- **功能（OpenCode）：支持 JSONC 配置格式** — OpenCode\u002FKiloCode 的配置现在可以包含注释（`\u002F\u002F`、`\u002F* *\u002F`）和尾随逗号，且无需外部依赖即可解析。基于 @FloSchl8 提交的 PR #205。\n\n- **功能：`CONTEXT_MODE_NODE` 环境变量用于自定义 Node.js 路径** — 允许覆盖钩子脚本使用的 Node.js 可执行文件路径（后来因引入自动 ABI 检测而被移除）。（#214）\n\n### 重构\n\n- **重构：从所有适配器中移除 `writeRoutingInstructions` 方法** — 从 `HookAdapter` 接口及全部 11 个适配器实现中移除了 `writeRoutingInstructions` 方法、`getRoutingInstructionsConfig` 函数以及 `RoutingInstructionsConfig` 类型。同时移除了 `opencode-plugin.ts`、`openclaw-plugin.ts` 和 `server.ts` 中的相关调用点。如果用户需要路由信息，可以手动复制模板：`cp node_modules\u002Fcontext-mode\u002Fconfigs\u002Fopencode\u002FAGENTS.md AGENTS.md`。关闭了 #195 和 #207。\n\n- **重构：通过 `ensure-deps.mjs` 实现钩子的自动 ABI 保护** — 钩子现在能够在 Node.js ABI 版本发生变化时自动检测并重建原生二进制文件，从而不再需要手动重建。","2026-04-01T23:10:26",{"id":175,"version":176,"summary_zh":177,"released_at":178},56735,"v1.0.54","## v1.0.54\n\n重大稳定性版本，包含 12 项 Bug 修复、6 个已合并的 PR 以及 1 个新的平台适配器。重点：压缩安全性、升级可靠性、跨平台兼容性以及贡献者体验。\n\n### Bug 修复\n\n**压缩与会话安全**\n- **fix(openclaw): 停止拥有压缩权以保护思考块** — 将 `ownsCompaction: false` 设置为避免 Anthropic 的 `thinking`\u002F`redacted_thinking` 块在 OpenClaw 压缩过程中被破坏。修复 #191。\n- **fix: 延迟缓存目录清理以避免破坏活跃会话** — 旧插件版本目录不再会在会话进行中被删除。取而代之的是，在下次会话启动时执行基于时间的惰性清理（超过 1 小时）。修复 #181。\n- **fix(hooks): 自我修复更新所有钩子类型，而不仅仅是 PreToolUse** — 市场自动更新后，`settings.json` 中过时的路径现在会对 SessionStart、PostToolUse、PreCompact 和 UserPromptSubmit 钩子进行修正——而不仅是 PreToolUse。修复 #187。\n- **fix(hooks): 升级时清理设置中的过时钩子路径** — `configureAllHooks()` 现在会在注册新钩子之前移除过时的上下文模式条目。PR #188，由 @s-naveenkumar-001 提交。\n\n**升级可靠性**\n- **fix: 在升级路径中用 execFileSync 替换 execSync** — 在 `cli.ts` 和 `server.ts` 中，所有 12 处 `execSync` 调用均被替换为 `execFileSync`，并内嵌回退机制。此举绕过了 Claude Code 沙盒执行环境中会导致卡顿的 `\u002Fbin\u002Fsh`，同时也消除了 Shell 注入的风险。修复 #185。\n- **fix(executor): 对 rustc 编译使用 execFileSync** — 包含空格的路径（例如 Windows 的 `GitHub Actions Runner` 临时目录）不再会导致 Rust 编译失败。此修复最初来自 PR #193，由 @escapeboy 提交。\n\n**跨平台**\n- **fix: 为临时目录添加点前缀以防止 VS Code 自动打开** — 将临时目录前缀从 `ctx-mode-` 改为 `.ctx-mode-`，使 VS Code 的文件监听器忽略这些目录。修复 #186。\n- **fix: 将 AGENTS.md 的写入延迟到 session_start** — `writeRoutingInstructions` 已从插件初始化阶段（网关工作目录）移至会话开始阶段（实际工作空间路径），并在 OpenClaw 适配器中实现。该功能还包括通过正则表达式和容器检查来防止路径遍历。PR #183，由 @DrakoTrogdor 提交。\n- **fix: 使用 process.execPath 并探测 ~\u002F.bun\u002Fbin 以应对 snap\u002FPATH 限制环境** — 现在可以正确检测 Snap Node.js 和非 PATH 安装的 bun。`getRuntimeSummary()` 已修复，能够处理完整的 bun 路径。PR #190，由 @luispabon 提交。\n\n### 新增平台\n\n- **feat: 添加 KiloCode 平台适配器** — 扩展了 OpenCodeAdapter，使其同时支持 OpenCode 和 KiloCode 平台。通过 `KILO`\u002F`KILO_PID` 环境变量以及 `~\u002F.config\u002Fkilo\u002F` 目录进行检测。包含路由指令、工具命名及 9 个测试用例。PR #167，由 @mikij 提交。\n\n### 改进\n\n- **dx: 在 batch_execute 输出中添加跨批次搜索提示** — 每个批次结果现在都会显示一条提示，指导 LLM 使用 `ctx_search` 进行跨源查询。\n- **fix(store): 将 batch_execute 的作用范围限定为精确的来源标签** — `ctx_batch_execute` 不再会因 `LIKE` 部分匹配而泄露上一批次的残留内容。现采用精确的 `sources.label = ?` 匹配方式。增加 sourc","2026-03-28T19:54:11",{"id":180,"version":181,"summary_zh":182,"released_at":183},56736,"v1.0.53","## v1.0.52 以来的更改\n\n- **修复（opencode）**：保留已选择的配置路径——写回原文件（#175，@rich-jojo）\n- **文档**：修正 PR 目标分支——所有 PR 均指向 `main` 分支，而非 `next` 分支（#176）\n- **文档**：在 README 中更新 npm 构建命令（#171）","2026-03-24T22:26:34",{"id":185,"version":186,"summary_zh":187,"released_at":188},56737,"v1.0.52","## 修复：插件缓存中缺少 better-sqlite3 的 SessionStart 钩子 (#172)\n\n钩子作为与 MCP 服务器分离的独立进程运行，无法访问按需安装的 `node_modules\u002F` 目录。因此，每次会话启动时，会话数据库的初始化都会静默失败。\n\n### 修复方案\n新增 `hooks\u002Fensure-deps.mjs`——一个共享的引导模块（与 `suppress-stderr.mjs` 采用相同模式）。该模块作为原生依赖安装的唯一可信来源，同时被 `start.mjs` 以及跨 5 个平台的 13 个会话钩子所使用。\n\n- 快速路径：通过 `existsSync` 检查（每个钩子调用约 0.1 毫秒）\n- 慢速路径：执行 `npm install`（仅首次运行，耗时约 5–30 秒）\n\n覆盖平台：Claude Code、Gemini CLI、VS Code Copilot、Cursor、Kiro","2026-03-24T09:46:10",{"id":190,"version":191,"summary_zh":192,"released_at":193},56738,"v1.0.51","## 修复：npm 打包文件中的过时捆绑包 (#168)\n\n**根本原因：** `prepublishOnly` 脚本仅执行了 `tsc`（TypeScript 编译），但未执行 `esbuild`（捆绑打包）。因此，发布的 npm 打包中包含一个过时的 `server.bundle.mjs` 文件，该文件并未应用 v1.0.50 版本中的提示\u002F资源修复。\n\n**修复方案：** 现在 `build` 脚本会依次执行 `tsc` 和 `npm run bundle`。每次 `npm publish` 都会生成最新的捆绑包。\n\n这意味着，提示\u002F资源空处理程序的修复 (#168) 现已真正包含在发布的包中。","2026-03-23T23:38:31",{"id":195,"version":196,"summary_zh":197,"released_at":198},56739,"v1.0.50","## 修复：MCP 服务器在 OpenCode 上无法工作 (#168)\n\n### 根本原因\nOpenCode 会无条件地在所有 MCP 服务器上调用 `prompts\u002Flist` 和 `resources\u002Flist`，而不管这些服务器声明了哪些能力。我们的服务器没有为这些方法注册处理器，因此 MCP SDK 返回了 `-32601 方法未找到` 错误。这个错误会破坏 SDK 的传输层——后续的 `listTools()` 调用都会失败，客户端会被永久删除，所有 9 个工具也将无法使用。\n\n### 解决方案\n注册空的 `prompts`、`resources` 和 `resourceTemplates` 处理器，分别返回 `{ prompts: [] }`、`{ resources: [] }` 和 `{ resourceTemplates: [] }`。这样就不会再出现 `-32601` 错误，传输层也能保持正常运行。\n\n### 证据\n- OpenCode 源码：`packages\u002Fopencode\u002Fsrc\u002Fmcp\u002Findex.ts` — 在 `.catch()` 中调用了 `listPrompts()`，但 `-32601` 错误破坏了 SDK 的传输层。\n- MCP SDK：当没有注册处理器时，`Protocol._onrequest()` 会返回 `-32601` 错误。\n- 我们的服务器：仅注册了工具（9 个），未注册 `prompts` 和 `resources` 的处理器。","2026-03-23T22:17:32",{"id":200,"version":201,"summary_zh":202,"released_at":203},56740,"v1.0.49","## 允许静默的文件输出式 curl\u002Fwget 下载 (#166)\n\n当输出重定向到文件时，二进制文件下载（如命令行工具、归档文件）不再被阻止。\n\n### 算法\n每个链式命令段会独立评估：\n- **允许**：同时满足以下条件——有文件输出（`-o`\u002F`>`）、静默模式（`-s`）、无详细输出、且未使用标准输出别名。\n- **阻止**：其他情况（存在标准输出泛滥的风险）。\n\n### 示例\n```bash\n# 允许（静默 + 文件输出）\ncurl -sLo \u002Ftmp\u002Fstripe.tar.gz https:\u002F\u002Fgithub.com\u002Fstripe\u002Fstripe-cli\u002Freleases\u002F...\ncurl -s --output \u002Ftmp\u002Fdata.json https:\u002F\u002Fapi.example.com\u002Fdata\nwget -qO \u002Ftmp\u002Fterraform.zip https:\u002F\u002Freleases.hashicorp.com\u002F...\n\n# 仍被阻止\ncurl https:\u002F\u002Fexample.com                    # 标准输出泛滥\ncurl -o file url                            # 缺少 -s，进度条会向标准错误输出大量信息  \ncurl -s -o - url                            # -o - 实际上是标准输出别名\ncurl -sLo file url && curl https:\u002F\u002Fapi.com  # 第二个命令会导致标准输出泛滥\n```\n\n新增 9 个测试用例。由首席工程师进行安全审核，共评估了 10 种对抗性场景。","2026-03-22T09:25:07",{"id":205,"version":206,"summary_zh":207,"released_at":208},56741,"v1.0.47","## Native deps moved to optionalDependencies (#163)\n\n`better-sqlite3`, `turndown`, `turndown-plugin-gfm`, and `@mixmark-io\u002Fdomino` moved from `dependencies` to `optionalDependencies`.\n\n### Why\nBun-powered platforms (OpenCode, Kilo Code) failed to install context-mode because `better-sqlite3`'s native compilation (prebuild-install → node-gyp) crashes under Bun. The entire `bun install` aborted.\n\n### What changes\n- **Bun users**: `bun install` now succeeds. Native deps silently skip. Runtime uses `bun:sqlite` via `BunSQLiteAdapter`.\n- **Node.js users**: Zero change. `optionalDependencies` install identically to `dependencies` when compilation succeeds. If somehow missing, `start.mjs` lazy-installs at server startup.\n\n### Reviewed by\nWindows Engineer, macOS\u002FLinux Engineer, Node.js Runtime Engineer, 11 Adapters Architect — all SAFE, zero risk.","2026-03-22T08:49:08",{"id":210,"version":211,"summary_zh":212,"released_at":213},56742,"v1.0.46","## Simplified SQLite driver selection (#163)\n\nReplaced the try\u002Fcatch + instantiation probe with a clean runtime check:\n\n```js\nif (globalThis.Bun) {\n  \u002F\u002F bun:sqlite via BunSQLiteAdapter\n} else {\n  \u002F\u002F better-sqlite3\n}\n```\n\n`globalThis.Bun` is engine-set and reliable. No more probing, no more false positives. 30 → 18 lines.\n\nSuggested by @mikij.","2026-03-21T12:56:55",{"id":215,"version":216,"summary_zh":217,"released_at":218},56743,"v1.0.45","## Fix: bun:sqlite fallback now actually works (#163)\n\n**Problem:** Bun's `require(\"better-sqlite3\")` returns a function stub that passes `typeof` checks but crashes when instantiated. Our v1.0.44 typeof check wasn't enough.\n\n**Fix:** Now validates better-sqlite3 by actually instantiating `new mod(\":memory:\")`. When this crashes on Bun, the catch block correctly falls through to `bun:sqlite` via `BunSQLiteAdapter`.\n\n**Why this works:** Bun has built-in FTS5 support (enabled via `SQLITE_ENABLE_FTS5` since [Bun v0.6.12](https:\u002F\u002Fgithub.com\u002Foven-sh\u002Fbun\u002Fdiscussions\u002F3468)). Our `BunSQLiteAdapter` provides the full better-sqlite3-compatible API including multi-statement `.exec()`, `.pragma()`, and `.prepare()` — everything needed for FTS5 virtual tables.\n\nThanks to @mikij for the detailed debugging.","2026-03-21T12:41:42",{"id":220,"version":221,"summary_zh":222,"released_at":223},56744,"v1.0.44","## Critical Fix: Bun bun:sqlite fallback (#163)\n\nBun's `require(\"better-sqlite3\")` doesn't throw — it logs an error and returns `undefined`. The `catch` block in `loadDatabase()` never triggered, making the `bun:sqlite` fallback unreachable on Bun-powered platforms (OpenCode, Kilo Code).\n\n**Fix:** Added explicit validation (`typeof mod !== \"function\"`) after `require()`. When Bun returns `undefined`, the check now correctly triggers the fallback to `bun:sqlite`.\n\nThanks to @mikij for the detailed debugging in #163.","2026-03-21T12:19:42",{"id":225,"version":226,"summary_zh":227,"released_at":228},56745,"v1.0.43","## Platform-Specific Config Fixes\n\nTool name prefixes in routing instruction files now match each platform's official convention:\n\n| Platform | Before (wrong) | After (correct) | Source |\n|----------|----------------|-----------------|--------|\n| OpenCode | `mcp__context-mode__ctx_*` | `context-mode_ctx_*` | [OpenCode docs](https:\u002F\u002Fgithub.com\u002Fanomalyco\u002Fopencode\u002Fblob\u002Fdev\u002Fpackages\u002Fweb\u002Fsrc\u002Fcontent\u002Fdocs\u002Ftools.mdx) |\n| Zed | `mcp__context-mode__ctx_*` | `mcp:context-mode:ctx_*` | [Zed docs](https:\u002F\u002Fzed.dev\u002Fdocs\u002Fai\u002Ftool-permissions) |\n| Codex | `mcp__context-mode__ctx_*` | `ctx_*` (bare) | [Codex docs](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fcodex) |\n| OpenClaw\u002FPi | `mcp__context-mode__ctx_*` | `ctx_*` (bare) | [OpenClaw docs](https:\u002F\u002Fdocs.openclaw.ai\u002Ftools\u002Fplugin) |\n\n## Kiro Adapter Fix\n- Renamed `configs\u002Fkiro\u002Fmcp_config.json` → `mcp.json` (matches [official Kiro docs](https:\u002F\u002Fkiro.dev\u002Fdocs\u002Fmcp\u002Fconfiguration\u002F))\n- Updated adapter code + tests (5 references)\n\n## Cursor Rules File\n- New `configs\u002Fcursor\u002Fcontext-mode.mdc` with `alwaysApply: true` — the modern Cursor rules format\n\n## README Rewrite\n- All 12 platform install sections rewritten in consistent book format\n- Every section: Prerequisites → Install → Verify → Routing\n- Correct tool names per platform in all examples\n- No references to auto-created files","2026-03-21T12:12:38",{"id":230,"version":231,"summary_zh":232,"released_at":233},56746,"v1.0.42","## Platform-Aware Tool Naming (11 platforms)\n\nBlock\u002Fredirect messages now use the correct MCP tool naming convention for each platform. Previously, all platforms received Claude Code's naming (`mcp__plugin_context-mode_context-mode__ctx_*`), causing tools to be unfindable on 10 of 11 platforms.\n\nEvidence-based conventions (from official docs):\n| Platform | Pattern |\n|----------|---------|\n| Claude Code (plugin) | `mcp__plugin_context-mode_context-mode__\u003Ctool>` |\n| Gemini CLI \u002F Antigravity | `mcp__\u003Cserver>__\u003Ctool>` |\n| OpenCode \u002F VS Code Copilot | `\u003Cserver>_\u003Ctool>` |\n| Kiro | `@\u003Cserver>\u002F\u003Ctool>` |\n| Zed | `mcp:\u003Cserver>:\u003Ctool>` |\n| Cursor \u002F Codex \u002F OpenClaw \u002F Pi | bare `\u003Ctool>` |\n\nNew `hooks\u002Fcore\u002Ftool-naming.mjs` provides `getToolName(platform, bareTool)` helper. All platform hooks and plugins pass their platform identifier. 32 new tests.\n\n## Routing File Auto-Write Disabled (#158, #164)\n\n**Breaking**: `start.mjs` and `server.ts` no longer auto-write routing instruction files (CLAUDE.md, GEMINI.md, AGENTS.md, etc.) to project directories. This was causing git tree pollution and double context injection.\n\n- **Hook-capable platforms** (Claude Code, Gemini CLI, OpenCode, OpenClaw, VS Code Copilot): No change needed — routing is injected via SessionStart hook in-memory.\n- **Non-hook platforms** (Codex, Zed, Cursor, Kiro, Antigravity): Manual setup required — copy the routing file from `configs\u002F\u003Cplatform>\u002F` to your project root. See README for instructions.\n\n## README Updated\n\nManual routing file setup instructions added for non-hook platforms.","2026-03-21T09:25:04",{"id":235,"version":236,"summary_zh":237,"released_at":238},56747,"v1.0.41","## Hotfix\n\n- **ctx_doctor\u002Fctx_upgrade pluginRoot** — `dirname(dirname(import.meta.url))` resolved one level too high when running from `server.bundle.mjs`. Now uses `__pkg_dir` with `package.json` existence check to resolve correctly in both bundle and `build\u002F` contexts.\n- **npm install timeout** — increased from 60s to 120s for slow networks\u002Fnative rebuilds.","2026-03-21T01:50:49",{"id":240,"version":241,"summary_zh":242,"released_at":243},56748,"v1.0.40","## Fixes\n\n### #158 — start.mjs unconditionally writes routing file\n- Hook-capable platforms (Claude Code, Gemini CLI, OpenCode, OpenClaw) no longer get routing instructions written to disk — the SessionStart hook handles it, keeping your git tree clean.\n\n### #159 — OpenCode hook interface mismatch (BREAKING for OpenCode users)\n- Fixed `opencode-plugin.ts` to use OpenCode's actual two-parameter hook signature `(input, output)`.\n- Field mapping corrected: `tool_name`→`input.tool`, `tool_input`→`output.args`, `tool_output`→`output.output`.\n- Arg mutation now correctly targets `output.args` so OpenCode reads the modified values.\n- **Note**: This was always broken — the old single-param interface meant routing enforcement never triggered for OpenCode\u002FKilo Code users.\n\n### #160 — Marketplace sync: cli.bundle.mjs missing\n- `ctx_doctor` now runs all diagnostics server-side (no CLI file dependency).\n- `ctx_upgrade` falls back to a temp `.mjs` script when CLI files are missing.\n- `start.mjs` self-heals `cli.bundle.mjs` from `build\u002Fcli.js` when the bundle is absent.\n- `session-loaders.mjs` falls back to `build\u002Fsession\u002F*.js` when bundles are missing.\n- Skills (`ctx-doctor`, `ctx-upgrade`) prefer MCP tool, Bash as fallback.\n\n### Additional\n- Replaced fabricated `OPENCLAW_PROJECT_DIR` env var with real `OPENCLAW_CLI` (verified against upstream [openclaw\u002Fopenclaw](https:\u002F\u002Fgithub.com\u002Fopenclaw\u002Fopenclaw) source).\n- `postinstall.mjs`: improved nvm4w shim detection + `isSafeWindowsPath` guard against cmd.exe injection.\n- CLI self-heal shim now gets `chmod +x` on Unix.\n\n## Stats\n- 19 files changed, 601 insertions, 264 deletions\n- 1194 tests passing, TypeScript clean\n- Reviewed by Staff Engineer + Principal Engineer","2026-03-21T01:43:11",{"id":245,"version":246,"summary_zh":247,"released_at":248},56749,"v1.0.39","## Fixes (#156 — Windows\u002Fnvm4w)\n\n- **Replace deprecated `npm bin -g`** with `npm config get prefix` (removed in npm v9+)\n- **Detect ALL shim locations** via `where context-mode.cmd` — creates directory junctions at every stale shim location (e.g., `C:\\nvm4w\\nodejs\\`) so they can resolve the package\n- **Auto-fix stale shims** that reference old `build\\cli.js` → rewrites them to use `cli.bundle.mjs`","2026-03-20T13:57:59",{"id":250,"version":251,"summary_zh":252,"released_at":253},56750,"v1.0.38","## Fixes\n\n- **ctx-upgrade now syncs `scripts\u002F` directory** — fixes `postinstall.mjs not found` error after upgrade (#156)\n- Removed stale `native-abi.mjs` reference from upgrade file sync list","2026-03-20T13:55:34"]