Open Source
Open Source

Context Mode: Taming the Coding-Agent Context Window

mksglu/context-mode (23,324 stars, TypeScript, Elastic License 2.0, created 2026-02-23, last push 2026-09-16, per the 2026-09-18 GitHub API) positions itself as "context window optimization for AI coding agents": an MCP-layer sandbox intercepts and compacts context, backed by a SQLite/FTS5 knowledge base and session-continuity design across 17 clients. The core claim: it hits three real pains, bloated long sessions, diluted key instructions, and token cost that grows with length. But be honest about the license: ELv2 is not OSI-approved open source and carries two red lines, no offering it as a hosted service and no removing the license notice, fine for personal use but a legal review before corporate adoption.

Published September 18, 20268 min read
<!-- context-mode-resource | open-source | Context Mode: Taming the Coding-Agent Context Window -->

The context window is the ignored other half

Over the past year the coding agent became the busiest digital laborer on a developer's desk. It opens terminals, runs commands, edits files, opens pull requests. One person keeping Claude Code, Codex, and Cursor running at once is no longer unusual. Yet few notice that once models got smart, the real bottleneck moved from "is the model strong enough" to "does the context window fit everything."

Context Mode's one-line positioning is "the other half of the context problem." The half it fixes is not making the model write better code. It is stopping the agent from bloating its own context in long sessions, from forgetting everything on compaction, and from burning tokens hauling raw data.

The pain is concrete. The README's numbers come from real runs: one Playwright snapshot eats 56 KB, twenty GitHub issues add 59 KB, a single access log is 45 KB. After thirty minutes, 40% of your window is hauled-in raw data. Worse, when the agent compacts to free space it drops the file it was editing, the task in progress, and your last request. On top of that it spends output tokens on filler, so context burns from both ends.

This is the layer a runtime like herdr never touches. herdr manages terminals and multi-machine scheduling; context-mode manages the agent's in-brain context memory. They are not replacements, only different entrances of the same wave. To use agents well you must solve both context optimization and session orchestration.

What context-mode is: a sandbox at the MCP layer

Context Mode is an MCP server in TypeScript, shipped as the npm package context-mode. Its bet is that context optimization belongs at the data source, not behind a per-seat cloud dashboard. So it runs on your machine: no telemetry, no cloud sync, no account. Your code, prompts, and session data stay local.

It intercepts tool calls at the MCP layer. When the agent reads a huge file, runs a command that spews output, or fetches a page, context-mode does not let that raw data into the window. It drops the data into an isolated subprocess sandbox, processes it there, and returns only the result. The README is plain: raw data stays in the sandbox and never enters your context.

This is not a CLI output filter and not a cloud analysis dashboard. It distills data in place, before the model sees it. That choice also drives the license, covered in the final section.

Four capabilities, broken down

The README splits what context-mode solves into four faces.

First, context saving. Sandbox tools keep raw data out of the window. The README's figure: across a full session 315 KB of raw output compresses to 5.4 KB, a 98% cut. It does not rely on the model thinning things; architecturally the raw data never arrives.

Second, session continuity. Every edit, git op, task, error, and decision is recorded in SQLite. On compaction, context-mode does not dump that data back raw. It indexes it in FTS5 and retrieves only what is relevant via BM25. The model resumes exactly where you left off. The honest boundary: skip --continue and the prior session is deleted at once.

Third, think in code. The LLM should program the analysis, not compute it. Instead of reading 50 files to count functions, the agent writes a script that counts and only logs the result. One script replaces ten calls and saves 100x context. The README calls this mandatory across all 17 supported clients.

Fourth, no prose enforcement. Context-mode keeps raw data out but never dictates the final answer's style. Brevity and format are the model's call, or yours via CLAUDE.md / AGENTS.md. The README cites evidence that overly terse prompts hurt benchmarks, so the routing block governs where data goes, not how the model talks.

Sandbox and knowledge base

Selling points are not enough; the implementation convinces. Two engines: sandbox execution and a SQLite knowledge base.

Every ctx_execute spawns an isolated subprocess with its own boundary; scripts cannot touch each other's memory. The subprocess runs your code, captures stdout, and only stdout enters context. Raw logs, API responses, snapshots never leave the sandbox. Twelve runtimes are supported: JavaScript, TypeScript, Python, Shell, Ruby, Go, Rust, PHP, Perl, R, Elixir, C#. Bun makes JS/TS 3 to 5 times faster. Authenticated CLIs (gh, aws, gcloud, kubectl, docker) pass through credentials without exposing them. Past 5 KB with an intent, it switches to intent-driven filtering: index the full output, return only matching sections.

The knowledge base uses a SQLite FTS5 table, backend auto-selected among bun:sqlite, node:sqlite on Node 22.5 plus, and better-sqlite3. Search uses BM25 with Porter stemming, titles weighted 5x. It fuses porter and trigram matching with Reciprocal Rank Fusion, adds proximity reranking, and applies Levenshtein typo correction. Results use smart snippets, not truncation. Two more pieces matter in practice. Indexed content sits in a per-project SQLite store with a 24-hour TTL cache by default, so a re-fetched URL within the window is skipped and the model searches the existing index, and databases older than 14 days are cleaned on startup. And the tool layer applies progressive throttling: early calls return two results per query, later calls drop to one with a warning, and past a threshold it redirects you to ctx_batch_execute. The point is to stop one obsessive search loop from silently draining the window.

The README benchmark table, the project's own reporting and not independently verified:

ScenarioRawInto contextSaved
Playwright snapshot56.2 KB299 B99%
Twenty GitHub issues58.9 KB1.1 KB98%
Access log 500 lines45.1 KB155 B100%
Analytics CSV 500 rows85.5 KB222 B100%
Git log 153 commits11.6 KB107 B99%
Subagent repo research986 KB62 KB94%

At session level 315 KB becomes 5.4 KB and length stretches from about 30 minutes to about 3 hours. Treat these as vendor benchmarks and validate before procurement.

Session continuity

This is the most underestimated piece. When the window fills, the agent compacts to drop old messages. Without tracking it forgets the file it edited, the task in flight, the error resolved, and what you last asked.

Context Mode captures every meaningful event into per-project SQLite. On compaction or --continue / --resume, the state rebuilds and the model continues from your last prompt. Five hook classes cooperate: PreToolUse enforces sandbox routing, PostToolUse captures events, UserPromptSubmit captures decisions, Stop captures turn-end state, PreCompact builds the snapshot, SessionStart restores state.

Events are prioritized from files, tasks, plans, rules, prompts, decisions, git, errors, constraints, blockers down to environment, subagent findings, retries, latency, MCP tools, skills, references. On compaction it builds a 2 KB capped XML snapshot, dropping low priority first but always keeping active files, tasks, rules, decisions. After compaction the model gets a 15-category Session Guide: last request, tasks, plans, decisions, files, errors, constraints, blockers, git, rules, tools, subagents, skills, rejected approaches, references.

The README lists 17 clients, but full continuity, capture plus snapshot plus restore, lands only on Claude Code, Gemini CLI, VS Code Copilot, JetBrains Copilot, OpenCode, KiloCode. Cursor reaches partial coverage because its validator rejects sessionStart. If you are picking an agent, this Claude Code versus Cursor versus Codex comparison makes the tradeoffs concrete.

Getting started

Installs split in two: hook-capable platforms enforce routing automatically, the rest copy a routing file once. For Claude Code the marketplace path is automatic:

bash
/plugin marketplace add mksglu/context-mode
/plugin install context-mode@context-mode

After restart run /context-mode:ctx-doctor; every check shows a mark. It registers all six hooks and eleven tools. Gemini CLI, VS Code and JetBrains Copilot, GitHub Copilot CLI, Cursor use config-plus-hook files; OpenCode and KiloCode use a TypeScript plugin; Codex CLI needs [features].hooks = true.

Routing deserves emphasis. Hooks intercept and rewrite calls, redirecting flooding commands into the sandbox before they run. An instruction file only nudges and blocks nothing. The README contrast: hooks save about 98%, instruction-file-only about 60%. Advice: turn hooks on wherever supported.

Daily commands, typed in any session:

bash
ctx stats     # savings, call counts, session report
ctx doctor    # diagnose runtimes, hooks, FTS5, versions
ctx index     # index a local file or directory
ctx search    # search indexed content
ctx upgrade    # pull latest, rebuild, fix hooks
ctx purge     # clear the knowledge base

A minimal example, swapping read-fifty-files for a script:

js
// Before: 47 times Read() = 700 KB. After: 1 time ctx_execute() = 3.6 KB.
ctx_execute("javascript", `
  const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
  files.forEach(f => console.log(f + ': ' + fs.readFileSync('src/'+f,'utf8').split('\\n').length + ' lines'));
`);

For complementary reading on free tiers and which long session burns more context, this AI coding tool free-credit comparison and this Qoder plus Qwen3-8 hotspot breakdown pair well with this piece.

License reality check

The last section must be clear: it is the line between context-mode and genuine open source.

Context Mode uses Elastic License 2.0, ELv2. The README writes "source-available", not "open source". Per GitHub API as of 2026-09-18, mksglu/context-mode has 23,324 stars, is TypeScript, carries ELv2, was created 2026-02-23, last pushed 2026-09-16. A young, fast-rising project.

ELv2 is not OSI-approved open source. It lets you use, fork, modify, distribute, but two red lines hold: you may not offer it as a hosted or managed service, and you may not remove license notices. The README states its reason for ELv2 over MIT: MIT allows repackaging as a competing closed-source SaaS, while ELv2 keeps source available and blocks that.

What it means depends on you. An individual running agents locally, installing the npm package, wiring it into Claude Code, feels almost no difference from MIT: use it, change it, read source, pay nothing, never trip a red line. Inside a company, most internal R and D is also safe, because the line is hosting for outsiders; internal use is not. Watch two moves: if your company sells an AI coding or agent hosting product and ships context-mode as backend to customers, that hits the first red line; and any redistribution must keep the notices.

My judgment: as a tool for individuals and small teams it is fine, the license will not block you. But a commercial hosted product on top of it needs legal sign-off or a commercial license. The project chose ELv2 deliberately, trading the "free for any use" label for a shield against closed-source SaaS clones while keeping the source readable by everyone. Source available but not free, that is the honest ELv2 position to write into your evaluation sheet.

FAQ

question one: how is context-mode different from telling the model to be concise?

A1: It blocks data at the architecture layer instead of nudging with a prompt. Model self-thinning is unreliable, and the README cites evidence that overly terse prompts hurt benchmarks. Context Mode keeps raw data out with a sandbox, retrieves on demand with FTS5 and BM25, and replaces reading data to compute with writing code to analyze. It compresses by mechanism, not by model discipline.

question two: after compaction does my state survive, and what is lost?

A2: On the full tier, Claude Code, Gemini CLI, VS Code and JetBrains Copilot, OpenCode, KiloCode, it captures files, tasks, plans, rules, decisions, git, errors, blockers, builds a 2 KB snapshot before compaction, and rebuilds a 15-category guide after, so the model continues without repetition. Skip --continue and the prior session is deleted at once. Partial platforms like Cursor cannot yet restore after compaction.

question three: do my secrets and security rules still hold?

A3: They hold and extend into the sandbox. The deny and allow rules in Claude Code's settings.json are read by context-mode and applied to execution tools, blocking sudo or rm -rf. The sandbox enforces project-boundary containment, hardens fetches by blocking cloud metadata and reserved addresses, and redacts tokens and secrets in mcp__* inputs before they hit the database. Deny beats allow, and project rules override global.

question four: which agents are supported, including Codex, Cursor, Zed?

A4: The README lists 17 clients: Claude Code, Qwen Code, Gemini CLI, VS Code and JetBrains Copilot, GitHub Copilot CLI, Cursor, OpenCode, KiloCode, OpenClaw, Codex CLI, Kimi Code, Antigravity, Kiro, Zed, Pi, OMP. You can use it, but tiers differ: hook platforms save about 98%, instruction-only about 60%. Zed and Antigravity have no hooks, need a copied routing file, and cannot restore after compaction. Prefer the hook tier.

question five: ELv2 is not open source, is it risky for my company or personal use?

A5: For most, no. ELv2 lets you use, fork, modify, distribute, with two red lines: no hosted service to others, no removing notices. Local runs and internal R and D do not cross them. The careful case is a commercial AI coding hosting product shipping context-mode as backend to customers, which triggers the first red line and needs legal or a commercial license. Source available but not free, write that truthfully into your evaluation.

This article is AI-assisted and human-edited. Last updated: 2026-09-18

FAQ

how is context-mode different from telling the model to be concise?
It blocks data at the architecture layer instead of nudging with a prompt. Model self-thinning is unreliable, and the README cites evidence that overly terse prompts hurt benchmarks. Context Mode keeps raw data out with a sandbox, retrieves on demand with FTS5 and BM25, and replaces reading data to compute with writing code to analyze. It compresses by mechanism, not by model discipline.
after compaction does my state survive, and what is lost?
On the full tier, Claude Code, Gemini CLI, VS Code and JetBrains Copilot, OpenCode, KiloCode, it captures files, tasks, plans, rules, decisions, git, errors, blockers, builds a 2 KB snapshot before compaction, and rebuilds a 15-category guide after, so the model continues without repetition. Skip `--continue` and the prior session is deleted at once. Partial platforms like Cursor cannot yet restore after compaction.
do my secrets and security rules still hold?
They hold and extend into the sandbox. The deny and allow rules in Claude Code's `settings.json` are read by context-mode and applied to execution tools, blocking `sudo` or `rm -rf`. The sandbox enforces project-boundary containment, hardens fetches by blocking cloud metadata and reserved addresses, and redacts tokens and secrets in `mcp__*` inputs before they hit the database. Deny beats allow, and project rules override global.
which agents are supported, including Codex, Cursor, Zed?
The README lists 17 clients: Claude Code, Qwen Code, Gemini CLI, VS Code and JetBrains Copilot, GitHub Copilot CLI, Cursor, OpenCode, KiloCode, OpenClaw, Codex CLI, Kimi Code, Antigravity, Kiro, Zed, Pi, OMP. You can use it, but tiers differ: hook platforms save about 98%, instruction-only about 60%. Zed and Antigravity have no hooks, need a copied routing file, and cannot restore after compaction. Prefer the hook tier.
ELv2 is not open source, is it risky for my company or personal use?
For most, no. ELv2 lets you use, fork, modify, distribute, with two red lines: no hosted service to others, no removing notices. Local runs and internal R and D do not cross them. The careful case is a commercial AI coding hosting product shipping context-mode as backend to customers, which triggers the first red line and needs legal or a commercial license. Source available but not free, write that truthfully into your evaluation.

Related

Open Source

herdr Deep Dive: The Runtime Layer Your Coding Agents Live On

herdrdev/herdr (39,133 stars, Rust, Apache-2.0, created 2026-03-27, ranked No.8 on the OpenGithubs 20260914 weekly with 2,458 stars added) positions itself as "the runtime your coding agents live on": work detaches but keeps running, multiple machines share one window, every pane is marked working, blocked or idle, agents drive it through the CLI and socket API, and it ships as one Rust binary with no Electron. The core claim: it claims the seat tmux would occupy in the AI era, and the agent-native socket API is what separates it from a tmux wrapper. But the project is under half a year old with unsettled APIs and storage formats, so manage your dev machine and experimental agents first, not your production-critical path.

Sep 17, 20268 min read