freshcrate
Skin:/
Home > Frameworks > opencode-magic-context

opencode-magic-context

OpenCode plugin for Magic Context โ€” cache-aware infinite context, cross-session memory, and background history compression for AI coding agents

Why this rank:Strong adoptionRecent releaseHealthy release cadence

Description

OpenCode plugin for Magic Context โ€” cache-aware infinite context, cross-session memory, and background history compression for AI coding agents

README

Magic Context

Cache-aware infinite context, cross-session memory, and background history compression for AI coding agents.
An OpenCode plugin that keeps your agent's memory intact โ€” no matter how long the session runs.

npmstarslast commitMIT License Magic Context in action

Get Started ยท What is Magic Context? ยท What Your Agent Gets ยท How It Works ยท ๐Ÿ–ฅ๏ธ Desktop App (NEW) ยท Commands ยท Configuration


What is Magic Context?

Your agent should never stop working to manage its own context. Magic Context is an OpenCode plugin that handles context and memory management entirely in the background:

1. Transparent context compaction via a background historian โ€” the main agent keeps working while a separate model compresses older conversation. All operations are cache-aware and deferred to avoid wasting cached prefixes.

2. Cross-session project memory โ€” architecture decisions, constraints, and preferences persist across conversations.

3. Overnight dreamer agent that consolidates, deduplicates, and promotes memories into canonical facts, plus maintains codebase documentation.

4. On-demand sidekick that augments prompts with relevant project context.

5. TUI sidebar with live context breakdown, token usage, historian status, and memory counts โ€” right inside the terminal.

๐Ÿงช New Experimental Features

Compaction Markers โ€” after historian compresses older messages, Magic Context injects a boundary into OpenCode's message table. OpenCode's built-in message loader stops at the boundary, so the transform processes only the live tail instead of the full session history. Dramatically reduces per-turn overhead on long sessions. Enable with experimental.compaction_markers: true.

User Memories โ€” historian extracts behavioral observations about you alongside its normal compartment output (communication style, expertise level, review focus, working patterns). Recurring observations are promoted by the dreamer to stable user memories that appear in all sessions via <user-profile>. Enable with experimental.user_memories.enabled: true (requires dreamer).

Key File Pinning โ€” dreamer analyzes which files your agent reads most frequently across the session. Core orientation files (architecture, config, types) that get re-read after every context drop are pinned into the system prompt as <key-files>, so the agent always has them without needing to re-read from disk. Files are read fresh on each cache-busting pass. Enable with experimental.pin_key_files.enabled: true (requires dreamer).


Get Started

Quick Setup (Recommended)

Run the interactive setup wizard โ€” it detects your models, configures everything, and handles compatibility:

macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/cortexkit/opencode-magic-context/master/scripts/install.sh | bash

Windows (PowerShell):

irm https://raw.githubusercontent.com/cortexkit/opencode-magic-context/master/scripts/install.ps1 | iex

Or run directly (any OS):

bunx @cortexkit/opencode-magic-context@latest setup

The wizard will:

  1. Check your OpenCode installation and available models
  2. Add the plugin and disable built-in compaction
  3. Help you pick models for historian, dreamer, and sidekick
  4. Handle oh-my-opencode compatibility if needed

Manual Setup

Add to your OpenCode config (opencode.json or opencode.jsonc):

{
  "plugin": ["@cortexkit/opencode-magic-context"],
  "compaction": {
    "auto": false,
    "prune": false
  }
}

Why disable compaction? Magic Context manages context itself โ€” built-in compaction interferes with its cache-aware deferred operations and would cause duplicate compression.

Create magic-context.jsonc in your project root, .opencode/, or ~/.config/opencode/:

{
  "$schema": "https://raw.githubusercontent.com/cortexkit/opencode-magic-context/master/assets/magic-context.schema.json",
  "enabled": true,

  // Which model the historian uses for background compression, 
  // Prefer providers that charge by request instead of tokens
  "historian": {
    "model": "github-copilot/gpt-5.4",
    "fallback_models": ["opencode-go/glm-5"]
  }
}

Tip: The $schema key enables autocomplete and validation in VS Code and other editors.

That's it. Everything else has sensible defaults. Project config merges on top of user-wide settings.

Oh-My-OpenCode / Oh-My-OpenAgent Users

If you use oh-my-openagent (formerly oh-my-opencode), disable the hooks that conflict with Magic Context in your oh-my-openagent.json:

{
  "disabled_hooks": [
    "context-window-monitor",
    "preemptive-compaction",
    "anthropic-context-window-limit-recovery"
  ]
}

The setup wizard handles this automatically if it detects an oh-my-openagent or oh-my-opencode config.

Doctor (Troubleshooting)

Already installed but something isn't working? Run the doctor to check and auto-fix configuration issues:

bunx @cortexkit/opencode-magic-context@latest doctor

Doctor checks for conflicts (compaction, DCP, OMO hooks), ensures the TUI sidebar is configured, verifies the plugin is registered, and checks the npm cache โ€” fixing what it can automatically.

Use --force to force-clear the plugin cache even when versions match (fixes broken transitive dependencies):

bunx @cortexkit/opencode-magic-context@latest doctor --force

What Your Agent Gets

Magic Context injects structured context automatically and gives the agent five tools.

ctx_reduce โ€” Shed weight

After tool-heavy turns (large grep results, file reads, bash output), the agent calls ctx_reduce to mark stale content for removal. Drops are queued โ€” not applied immediately โ€” until the cache expires or context pressure forces it.

ctx_reduce(drop="3-5,12")     // Drop tags 3, 4, 5, and 12

Recent tags (last 20 by default) are protected. Drops targeting them stay queued until they age out.

ctx_expand โ€” Decompress history

When the agent needs to recall details from a compressed history range, it can expand specific compartment ranges back to the original conversation transcript.

ctx_expand(start=100, end=200)   // Expand raw messages 100-200

Returns the same compact U:/A: transcript format the historian sees, capped at ~15K tokens per request. Use start/end from compartment attributes visible in <session-history>.

ctx_note โ€” Deferred intentions

Session notes are the agent's scratchpad for things to tackle later โ€” not task tracking (that's what todos are for), but deferred work and reminders that should surface at the right time.

ctx_note(action="write", content="After this fix, check if the compressor budget formula is correct")
ctx_note(action="read")

Notes surface automatically at natural work boundaries: after commits, after historian runs, and after all todos complete.

Smart notes are project-scoped notes with an open-ended surface_condition that the dreamer evaluates nightly. When the condition is met, the note surfaces in the next session:

ctx_note(action="write", content="Implement X because Y", surface_condition="When PR #42 is merged in this repo")
ctx_note(action="dismiss", note_id=1)

Smart notes require dreamer enabled. Pending notes are invisible until the dreamer marks them ready. Use dismiss to clear a surfaced note.

ctx_memory โ€” Persistent cross-session knowledge

Architecture decisions, naming conventions, user preferences โ€” anything that should survive across conversations. Memories are project-scoped and automatically promoted from session facts by the historian.

ctx_memory(action="write", category="ARCHITECTURE_DECISIONS", content="Event sourcing for orders.")
ctx_memory(action="delete", id=42)

ctx_search โ€” Unified search

Search across all data layers with a single query โ€” project memories, session facts, and raw conversation history. Results are ranked by source (memories first, then facts, then message hits).

ctx_search(query="authentication approach")

Message results include ordinal numbers the agent can pass to ctx_expand to retrieve the surrounding conversation context.

Automatic context injection

Every turn, Magic Context injects a <session-history> block containing:

  • Project memories โ€” cross-session decisions, constraints, and preferences
  • Compartments โ€” structured summaries replacing older raw history
  • Session facts โ€” durable categorized facts from the current session

This block is stable between historian runs. Memory writes persist immediately for search but don't change the injected block until the next historian run โ€” so writes never bust the cache mid-conversation.


How It Works

Tagging

Every message, tool output, and file attachment gets a monotonically increasing ยงNยง tag. The agent sees these inline and uses them to reference specific content when calling ctx_reduce. Tags persist in the database and resume across restarts.

Queued reductions

When the agent calls ctx_reduce, drops go into a pending queue โ€” not applied immediately. Two conditions trigger execution:

  • Cache expired โ€” enough time has passed that the cached prefix is likely stale (configurable per model, default 5 minutes)
  • Threshold reached โ€” context usage hits execute_threshold_percentage (default 65%)

Between triggers, the conversation continues unchanged. The agent doesn't need to think about timing.

Background historian

When local drops aren't buying enough headroom, Magic Context starts a historian โ€” a separate lightweight model that reads an eligible prefix of raw history and produces:

  • Compartments โ€” chronological blocks that replace older raw messages
  • Facts โ€” durable decisions, constraints, and preferences (categorized)

The historian runs asynchronously. The main agent never waits for it. When the historian finishes, its output is materialized on the next transform pass.

A separate compressor pass fires when the rendered history block exceeds the configured history budget, merging the oldest compartments to keep the injected context lean.

Nudging

As context usage grows, Magic Context sends rolling reminders suggesting the agent reduce. Cadence tightens as usage approaches the threshold โ€” from gentle reminders to urgent warnings. If the agent recently called ctx_reduce, reminders are suppressed. An emergency nudge at 80% always fires.

Cross-session memory

After each historian run, qualifying facts are promoted to the persistent memory store. On every subsequent turn, active memories are injected in <session-history>. New sessions inherit all project memories from previous sessions.

Memories are searchable via ctx_search alongside session facts and raw conversation history, using semantic embeddings (local by default) with full-text search as fallback.

Dreamer

An optional background agent that maintains memory quality overnight:

  • Consolidate โ€” merge semantically similar memories into canonical facts
  • Verify โ€” check memories against current codebase (configs, paths, code patterns)
  • Archive stale โ€” retire memories referencing removed features or old paths
  • Improve โ€” rewrite verbose memories into terse operational form
  • Maintain docs โ€” update ARCHITECTURE.md and STRUCTURE.md from codebase changes
  • Evaluate smart notes โ€” check pending smart note conditions and surface ready notes
  • Review user memories (experimental) โ€” promote recurring user behavior observations to stable memories

The dreamer runs during a configurable schedule window and creates ephemeral OpenCode child sessions for each task. Since it runs during idle time (typically overnight), it works well with local models โ€” even slower ones like ollama/mlx-qwen3.5-27b-claude-4.6-opus-reasoning-distilled are fine since there's no user waiting.

When dreamer is enabled, ARCHITECTURE.md and STRUCTURE.md are automatically injected into the agent's system prompt (configurable via inject_docs). Content is cached per-session and refreshed on cache-busting passes.

User Memories (Experimental)

When experimental.user_memories.enabled is set, historian extracts behavioral observations about the user alongside its normal compartment output โ€” things like communication style, expertise level, review focus, and working patterns. These go into a candidate pool.

During dreamer runs, a dedicated review pass checks candidates for recurring patterns across sessions. Observations that appear at least promotion_threshold times (default 3) are promoted to stable user memories and injected into all sessions via <user-profile> in the system prompt.

Stable user memories are visible and manageable in the dashboard's User Memories page. Requires dreamer to be enabled for the promotion step.

TUI Sidebar

When running in OpenCode's terminal UI, Magic Context shows a live sidebar panel with:

  • Context breakdown bar โ€” visual token split across System Prompt, Compartments, Facts, Memories, and Conversation
  • Historian status โ€” idle, running, or compartment/fact counts
  • Memory counts โ€” total project memories and how many are injected
  • Dreamer status โ€” last run time
  • Queue status โ€” pending operations count

The sidebar updates after every message. Commands (/ctx-status, /ctx-flush, /ctx-aug) also work directly in TUI mode via dialogs and toasts.

The TUI plugin is configured automatically by the setup wizard and the doctor command. If you installed manually, add to your tui.json or tui.jsonc:

{
  "plugin": ["@cortexkit/opencode-magic-context"]
}

Startup conflict detection

On startup, Magic Context checks for common configuration problems โ€” OpenCode's built-in compaction being enabled, DCP plugin being active alongside Magic Context, or conflicting oh-my-openagent hooks. When conflicts are detected, it warns the active session with a fix suggestion pointing to bunx @cortexkit/opencode-magic-context@latest doctor.


Commands

Command Description
/ctx-status Debug view: tags, pending drops, cache TTL, nudge state, historian progress, compartment coverage, history compression budget
/ctx-flush Force all queued operations immediately, bypassing cache TTL
/ctx-recomp Rebuild compartments and facts from raw history โ€” use when stored state seems wrong
/ctx-aug Run sidekick augmentation on a prompt โ€” retrieves relevant memories via a separate model
/ctx-dream Run dreamer maintenance on demand โ€” consolidate, verify, archive, improve memories

Magic Context App

A companion desktop app for browsing and managing Magic Context state outside of OpenCode.

โฌ‡๏ธ Download for macOS ยท Windows ยท Linux

Features:

  • Memory Browser โ€” search, filter, and edit project memories with category and project filtering
  • Session History โ€” browse compartments, facts, and notes for any session with timeline navigation
  • Cache Diagnostics โ€” real-time cache hit/miss timeline, bust cause detection, per-session stats
  • Dreamer Management โ€” view dream run history per project, trigger runs, inspect task results
  • Configuration Editor โ€” form-based editing for all settings including model selection with fallback chains
  • Log Viewer โ€” live-tailing log viewer with search
  • System Tray โ€” quick access to dreamer status and controls

The app reads directly from Magic Context's SQLite database โ€” no additional server or API required. Auto-updates are built in.


Configuration

All settings live in magic-context.jsonc as flat top-level keys. See CONFIGURATION.md for the full reference โ€” cache TTL tuning, per-model execute thresholds, historian model selection, embedding providers, memory settings, sidekick, and dreamer.

Config locations (merged in order, project overrides user):

  1. <project-root>/magic-context.jsonc
  2. <project-root>/.opencode/magic-context.jsonc
  3. ~/.config/opencode/magic-context.jsonc

Storage

All durable states live in a local SQLite database. If the database can't be opened, Magic Context disables itself and notifies the user.

~/.local/share/opencode/storage/plugin/magic-context/context.db
Table Purpose
tags Tag assignments โ€” message ID, tag number, session, status
pending_ops Queued drop operations
source_contents Raw content snapshots for persisted reductions
compartments Historian-produced structured history blocks
session_facts Categorized durable facts from historian runs
notes Unified session notes and project-scoped smart notes
session_meta Per-session state โ€” usage, nudge flags, anchors
memories Cross-session persistent memories
memory_embeddings Embedding vectors for semantic search
dream_state Dreamer lease locking and task progress
dream_queue Queued projects awaiting dream processing
dream_runs Per-project dream run history โ€” task names, durations, memory changes
compression_depth Per-message compression depth for weighted compressor selection
message_history_fts FTS5 index of user/assistant message text for ctx_search
message_history_index Tracks last indexed ordinal per session for incremental FTS population
recomp_compartments Staging for /ctx-recomp partial progress
recomp_facts Staging for /ctx-recomp partial progress
user_memory_candidates User behavior observations from historian (experimental)
user_memories Promoted stable user memories injected into all sessions (experimental)

Star History

Star History Chart

Development

Requirements: Bun โ‰ฅ 1.0

bun install              # Install dependencies
bun run build            # Build the plugin
bun run typecheck        # Type-check without emitting
bun test                 # Run tests
bun run lint             # Lint (Biome)
bun run lint:fix         # Lint with auto-fix
bun run format           # Format (Biome)

Utility scripts:

bun packages/plugin/scripts/tail-view.ts             # Show post-compartment message tail
bun packages/plugin/scripts/context-dump/index.ts     # Dump full context state for a session
bun packages/plugin/scripts/backfill-embeddings.ts   # Backfill missing memory embeddings

Dream execution requires a live OpenCode server โ€” the dreamer creates ephemeral child sessions. Use /ctx-dream inside OpenCode for on-demand maintenance.


Contributing

Bug reports and pull requests are welcome. For larger changes, open an issue first to discuss the approach.

Run bun run format before submitting โ€” CI rejects unformatted code.


License

MIT

Release History

VersionChangesUrgencyDate
dashboard-v0.5.1# Dashboard v0.5.1 A small patch release. ## What's Fixed - **No more console-window flashes on Windows.** Opening the dashboard spawned a child process for `git` (once per project while resolving identities) plus `opencode`/`pi` probes, each flashing a terminal window โ€” easily a dozen or more on startup. All child spawns now use `CREATE_NO_WINDOW` on Windows (no-op on macOS/Linux). (#115) ## What's New - **NVIDIA NIM support in Test Connection.** The embedding connection test now reads `inHigh6/3/2026
v0.21.8# v0.21.8 โ€” See how much work Magic Context is doing for you ## What's New - **Total tokens metric, per session.** The TUI sidebar and the dashboard's session Meta tab now show a "Total tokens" number: the cumulative prompt size Magic Context has processed for this session over its lifetime, summed across every turn. It's the simplest way to see how much aggregate context Magic Context has been managing without having to read the live percentage on every turn. - **Per-historian-run cost visibHigh5/22/2026
v0.21.0# v0.21.0 โ€” Cache-stable reminders and per-project embeddings ## What's new ### Note nudges and auto-search hints are now cache-stable Both reminder types append a small block to a recent user message. Previously the plugin remembered only the *latest* sticky anchor per session, so the next new reminder rewrote the old anchor's bytes on the wire, busting the prompt cache prefix for everything past it. Auto-search hints were worse: they lived only in process memory and disappeared entirely on High5/17/2026
v0.18.0## What's new ### Synthetic todowrite for todo retention across context cleanup Magic Context aggressively drops old tool calls and results from the conversation prefix to save tokens. Helpful for token economy, harmful for agents that use `todowrite` as a planning scratchpad โ€” once the original `todowrite` tool calls age out, the model effectively forgets its plan even though the real state is still tracked in OpenCode's internal todo registry. This release adds a deterministic, cache-High5/11/2026
v0.16.2## System prompt control + cross-host dreamer fixes This release adds per-agent control over Magic Context's system-prompt injection, fixes a long-standing bug where the dreamer queue could leak across projects, and stops historian/dreamer/sidekick subagent prompts from rendering as huge visible messages in the TUI. ## What's New - **Per-agent opt-out for system-prompt injection** ([#53](https://github.com/cortexkit/magic-context/issues/53), [#42](https://github.com/cortexkit/magic-context/isHigh5/4/2026
v0.15.7## What's Fixed - **Tagger no longer cascades into repeated cache busts** when its internal counter drifts behind the tags table's actual max tag number. Previously, once divergence occurred (from earlier outer-transaction rollback, multi-process race, or non-monotonic counter upsert), every transform pass would propose an already-claimed tag number, hit a UNIQUE collision, abort tagging, and skip the persisted-drop / reasoning-clear / caveman-compression replay โ€” resurrecting tens of thousandsHigh4/28/2026
v0.15.2# v0.15.2 Five focused fixes since v0.15.1 โ€” a malformed-tag-prefix repair, memory hardening, and audit-driven polish. ## ๐Ÿงน Malformed `ยงN">ยง` tag prefixes now self-heal After `experimental.temporal_awareness` shipped in v0.13, some models started emitting garbled tag prefixes at the start of their own assistant text: ``` ยง15298">ยง15298ยง Confirmed โ€” every OpenCode restartโ€ฆ ยง15434">ยง Type mismatch: m.file.as_path() returns ... ``` Root cause was token-level confusion: adding `start-date` andHigh4/24/2026
v0.13.2## ๐Ÿ› Bug Fixes **Compressor โ€” prevent depth cascade on old compartments** The compressor's selection algorithm previously scanned oldestโ†’newest and picked the first contiguous same-depth run it found. This caused the same raw-ordinal range to be re-selected pass after pass, rapidly deepening a small prefix (e.g. seq 0-3) all the way to depth 5 (caveman โ€” title-only collapse with empty content) within hours, while the rest of the history remained at depth 0. The new algorithm iterates distinctHigh4/21/2026
v0.13.1## ๐Ÿ› Bug fix ### `curl | bash` installer: historian model picker frozen The one-line installer (`curl -fsSL ... | bash`) could freeze on the historian model selection screen โ€” arrow keys did nothing, ctrl+c didn't exit โ€” forcing users to kill the terminal and fall back to running `bunx --bun @cortexkit/opencode-magic-context@latest setup` directly. **Root cause:** a regression in `scripts/install.sh` (v0.12.x) added `--bun` to the bunx invocation, which forced the setup CLI to run under Bun High4/21/2026
dashboard-v0.3.0## โœจ Highlights ### Bulk memory management (closes #28) The Memory Browser now handles batch operations properly. - **Per-item checkboxes** on every memory - **Per-category tri-state checkboxes** (all / some / none) to select a whole category at once - **Select-all-visible** sticky control at the top - **Bulk archive** โ€” reversible, archives a batch in one SQL transaction - **Bulk delete** โ€” destructive, requires a native confirm dialog - **Collapsible category groups** with right-side chevroHigh4/21/2026
v0.13.0## โœจ Highlights ### Historian V2 โ€” sharper compartments, better compression The historian prompt has been rewritten from scratch. Compartments are now narrative-first with minimal `U:` line preservation, ban question-form quotes, and drop agreement-prefix noise. Internal testing on a real 22K-message session showed `U:` line counts dropping from 76 โ†’ 24 per run while preserving high-signal user directives. Paired with the new **two-pass mode** that adds an optional editor pass for models withHigh4/21/2026
dashboard-v0.2.8## โœจ Tracks Plugin v0.12.0 This release aligns the dashboard config editor with the new config surfaces and schema changes introduced in [plugin v0.12.0](https://github.com/cortexkit/opencode-magic-context/releases/tag/v0.12.0). ## ๐Ÿš€ New **Absolute-token execute thresholds in the Thresholds section.** A new per-model field lets you configure `execute_threshold_tokens` from the dashboard UI โ€” set a default and optional per-model overrides, all numeric inputs. Mirrors the plugin's new token-baHigh4/19/2026
v0.12.0## ๐Ÿš€ New Feature **Set execute thresholds in absolute tokens, not just percentages.** The new `execute_threshold_tokens` config lets you trigger magic context's execute pass at a specific token count instead of a percentage of the model's context. This is especially useful when you want a hard cap matching your provider's `limit.input` โ€” e.g. stop at exactly 100K tokens regardless of the model's total context window. ```jsonc { // Trigger at absolute token counts (overrides percentage for mHigh4/19/2026
v0.11.1**Full Changelog**: https://github.com/cortexkit/opencode-magic-context/compare/v0.11.0...v0.11.1High4/19/2026
v0.11.0## โœจ Highlights **Accurate token counts in the sidebar.** The TUI sidebar's "Conversation", "System", "Memories", "Compartments", "Tool Calls", and residual "Tool Defs + Overhead" numbers now match what Anthropic actually sees on the wire โ€” validated within 0.1% against a live 340K-input request capture. Sessions will self-heal on the next transform pass without any user action. **New "Tool Calls" sidebar slice.** Tool-invocation tokens (`tool_use`, `tool_result`) are now tracked and displayedHigh4/18/2026
v0.10.1## ๐Ÿ›  Fixes **Embedding crash under concurrent load (#21)** โ€” fully reproduced and fixed on two fronts: - **Native runtime upgrade.** Bumped `@huggingface/transformers` from `~3.7.6` to `^4.1.0`, which pulls in `onnxruntime-node@1.24.3` with native library `libonnxruntime.1.24.3.dylib`. That's a ~2.5-year jump over the old `1.14.0.dylib` (Feb 2023) that shipped with `onnxruntime-node@1.21.0`, whose `ReleaseIoBinding` cleanup path could double-free during concurrent `InferenceSession::LoadModelHigh4/17/2026
v0.10.0## Highlights ### ๐Ÿ›  Anthropic signed-thinking error fix Prevents `messages.N.content: 'thinking' or 'redacted_thinking' blocks in the latest assistant message cannot be modified` errors. When the most recent assistant turn carried signed `thinking` / `reasoning` / `redacted_thinking` parts (Anthropic extended thinking), nudge injection was mutating the text part and invalidating the turn's signature, so the next turn got rejected by the provider. The plugin now detects signed turns andHigh4/17/2026
v0.9.1## Fixes - **Memory injection for new sessions** โ€” Memories and session facts are now injected into `message[0]` even when no compartments exist yet. Previously, brand-new sessions and existing projects where historian hadn't fired yet saw no `<session-history>` block at all, leaving agents without project memories until the first historian run. Now the block injects as soon as any memory or fact is available. ## Notes - 7 new tests cover memory-only, facts-only, combined injection, cache traHigh4/16/2026
dashboard-v0.2.7## Dashboard v0.2.7 - Config editor updated for stable `compaction_markers` top-level setting (moved from experimental) - `bunx --bun` in all user-facing help text and toast messagesHigh4/15/2026
v0.9.0## v0.9.0 ### Config Changes - **`compaction_markers` promoted to stable top-level config** โ€” moved from `experimental.compaction_markers` to top-level `compaction_markers`, default `true`. Doctor auto-migrates old configs. - **Pinned plugin versions respected** โ€” doctor now warns instead of auto-upgrading pinned versions (`@0.8.12` etc). Use `--force` to explicitly upgrade. ### CLI / Install - **`bunx --bun` everywhere** โ€” install scripts, README, and help text now use `bunx --bun` to preveHigh4/15/2026
v0.8.12## Bug Fixes - **Agent switching on ignored messages** โ€” `sendIgnoredMessage` and `promptAsync` calls now preserve the session's active agent name instead of leaving it undefined, which caused OpenCode to default to the "build" agent and switch users away from their current agent (e.g., Prometheus/plan). Closes #15.High4/14/2026
v0.8.11## v0.8.11 ### Bug Fixes - **Custom provider model context limits broken** โ€” JSONC comment stripping regex was destroying URLs inside JSON string values (e.g. `"$schema": "https://..."`) which silently broke OpenCode config parsing. Custom provider models with explicit context limits were never loaded, falling back to the 128K default. Replaced with a string-aware regex that preserves quoted content. (Closes #14) - **Derived model IDs missing from context limit resolution** โ€” OpenCode creates High4/13/2026
dashboard-v0.2.6## Dashboard v0.2.6 ### Bug Fixes - **Windows: "Database not found"** โ€” Dashboard was looking for `context.db` under `%APPDATA%` on Windows, but the plugin stores it at `~/.local/share` on all platforms. Both database path resolvers now use `XDG_DATA_HOME` or `~/.local/share` unconditionally, matching the plugin's behavior. (Closes #10)Medium4/12/2026
v0.8.10## v0.8.10 ### Bug Fixes - **Custom provider model context limits** โ€” Context limit resolution now reads custom model definitions from OpenCode's `opencode.json(c)` config in addition to the `models.dev` cache. Custom/proxy models like `google/antigravity-claude-opus-4-6-thinking` with explicit `limit.context` in the provider config were previously falling back to 128k default, causing incorrect pressure calculations and unnecessary compaction. OpenCode config entries override models.dev entriMedium4/12/2026
v0.8.9## v0.8.9 ### Bug Fixes - **Windows dashboard "Database not found"** โ€” The dashboard was looking for `context.db` under `%APPDATA%` on Windows, but the plugin stores it at `~/.local/share` on all platforms. Both `resolve_db_path` and `resolve_opencode_db_path` now use the same `XDG_DATA_HOME` or `~/.local/share` path unconditionally. (Closes #10) - **Windows embedding model failures** โ€” Set an explicit `cacheDir` for `@huggingface/transformers` at `~/.local/share/opencode/storage/plugin/magic-Medium4/12/2026
v0.8.8## v0.8.8 ### Improvements - **Memory injection reranking** โ€” Injection priority now uses utility-class tiers instead of `seen_count` alone: memories the agent actually retrieved (tier 0) and constraint-guarding memories with "must"/"never"/"always" keywords (tier 1) are packed before generic memories. Within tiers, shorter memories are preferred so more fit in budget. - **Smarter dreamer archive-stale** โ€” The dreamer archive task now uses structured archive/keep criteria validated through locMedium4/12/2026
v0.8.7## Bug Fixes - **Anthropic `redacted_thinking` blocks preserved** โ€” `stripClearedReasoning` no longer drops `redacted_thinking` blocks or thinking-type parts with undefined `thinking`/`text` fields, preventing Anthropic API rejection (`thinking or redacted_thinking blocks in the latest assistant message cannot be modified`). Fixes #8. - **Embedding model retries transient load failures** โ€” ONNX runtime initialization races (e.g., `Protobuf parsing failed`) are now retried up to 3 times with jitHigh4/11/2026
v0.8.6## What's Fixed **OpenCode Desktop plugin load failure** (closes #4) โ€” the bundled Desktop sidecar failed to load the plugin with `ENOENT: no such file or directory, open '.../@huggingface/transformers/utils/devices.js'`. The literal `import(\"@huggingface/transformers\")` specifier was being statically resolved by Bun at plugin load time, which then followed JSDoc-referenced paths in transformers' webpack-bundled dist and tried to open files that only exist as JSDoc `@type` annotations. ReplacMedium4/10/2026
v0.8.5## What's Fixed **Embedding model loading broken since v0.8.0** โ€” reverted the bundling of `@huggingface/transformers`. Bundling broke native binary resolution for `sharp` and `onnxruntime-node`, and corrupted the transformers model cache path resolution. Restored pre-v0.8.0 external dependency behavior. Embeddings now load correctly and proactive/lazy embedding flows work again. **Invalid config silently disabled entire plugin** (closes #4) โ€” if any single field in \`magic-context.jsonc\` faiMedium4/10/2026
v0.8.4## Bug Fix - **Fix: /ctx-status and /ctx-recomp commands no longer register as duplicate TUI slash commands. They use a single server-side registration and route through RPC to show dialog UI in TUI mode, while still falling back to ignored messages in Desktop/Web. Closes #3 High4/9/2026
dashboard-v0.2.4## Dashboard v0.2.4 - **Compartment date ranges** โ€” each compartment card shows the start/end dates resolved from OpenCode's message DB - **Fact editing** โ€” edit or delete session facts inline with Save/Cancel - **Note editing** โ€” edit or delete session notes, dismiss or delete smart notes - **Confirmation dialogs** โ€” all destructive actions (delete, dismiss) use native OS confirmation dialogs - **Experimental config section** โ€” toggle compaction markers, user memories, and key file pinning witMedium4/9/2026
dashboard-v0.2.3## Dashboard v0.2.3 - **Experimental features config** โ€” toggle compaction markers, user memories (with promotion threshold), and key file pinning (with token budget/min reads) directly from the config editor - **App menu** โ€” macOS menu bar with About and Check for Updates - **Auto-updater fix** โ€” endpoint now points to gh-pages, version tracking works correctly - **Tray icon fix** โ€” proper monochrome template icon - **User memory promote** โ€” promote candidates to active from dashboard - **AsseMedium4/8/2026
dashboard-v0.2.2Release dashboard-v0.2.2Medium4/8/2026
v0.8.0## What's New ### Accurate Context Limits Magic Context now reads OpenCode's cached `models.json` for real per-model context limits. Previously, non-Anthropic models defaulted to 200K which caused incorrect usage percentages (e.g., Cerebras 131K models showing 64% when actually at 98%). ### Historian Retry & Fallback Historian now retries transient failures (429, timeout, 5xx) with jittered backoff, and falls back to the primary session's model when the configured historian chain is exhaMedium4/8/2026
v0.8.3## Hotfix - **Bundle @huggingface/transformers** โ€” moved from external runtime dependency to bundled-at-build-time. Eliminates the `ENOENT: utils/devices.js` error permanently, regardless of which version npm resolves. The `devices.js` error was caused by `@huggingface/transformers` shipping broken internal import paths in recent versions. By bundling the library into `dist/index.js`, the plugin no longer depends on npm resolving a working version at install time. Bundle size increased from 1Medium4/8/2026
v0.7.4## Bug Fixes - **Web mode commands** โ€” `/ctx-status` and other `/ctx-*` commands now work in `opencode web` mode. Fixed a bug where undefined `OPENCODE_CLIENT` was treated as TUI mode, which removed server-side command registration and broke notifications for web users. (Fixes #1) Medium4/6/2026
v0.7.3### Bug Fixes - Fixed `/ctx-status` dialog crash on newer `@opentui/solid` โ€” nested `<text>` elements inside `<text>` are no longer allowed by the TUI renderer. Split the title into sibling elements inside a `<box>` container.Medium4/5/2026
v0.7.1## Bug Fixes - **Dreamer re-enqueue loop** โ€” Dreamer's own memory mutations (consolidate, verify, improve, archive) set `updated_at` on modified memories, which made the next scheduler check think there was new user activity and re-enqueue the project. This caused 4+ dream runs per night instead of 1. Fixed with a 12-hour cooldown: `findProjectsNeedingDream` now skips projects whose `last_dream_at` is less than 12 hours old.Medium4/5/2026
v0.7.0## What's New ### Experimental: Key File Pinning Dreamer analyzes which files each session's agent reads most frequently (full reads only, not partial ranges) and pins core orientation files into the system prompt as a `<key-files>` block. Files are read fresh from disk on each cache-busting pass so edits are always reflected. Enable with: ```jsonc "experimental": { "pin_key_files": { "enabled": true, "token_budget": 10000, "min_reads": 4 } } ``` Requires dreamer to be enabledMedium4/5/2026
v0.6.2## v0.6.2 ### Fixes - **FTS full reindex on message removal** โ€” `deleteIndexedMessage` now clears all FTS rows and the tracker to avoid ordinal skipping when messages are added after a removal - **Memory cache invalidation on all mutation paths** โ€” `invalidateAllMemoryBlockCaches` now runs after `update`, `merge`, and `archive` actions (was only `write`/`delete`) - **Stale anchor clearing** โ€” sticky turn reminders and note nudges with missing anchors are now cleared on cache-busting passMedium4/5/2026
v0.6.1## Bug Fixes - **Heuristic tool dedup restored** โ€” `extractToolInfo` was reading tool names from `state.tool` instead of `part.tool`, so the DEDUP_SAFE_TOOLS deduplication path (mcp_grep, mcp_read, etc.) never fired in production. Fixed to match real OpenCode tool part shape. - **Dashboard config path** โ€” `resolve_project_config_path` now checks both `<project>/magic-context.jsonc` and `<project>/.opencode/magic-context.jsonc`, so dashboard edits target the correct active config. - **Message buMedium4/4/2026
v0.6.0## What's New ### ๐Ÿงช New Experimental Features **Compaction Markers** โ€” after historian compresses older messages, Magic Context injects a boundary into OpenCode's message table. OpenCode's `filterCompacted` stops at the boundary, so the transform processes only the live tail instead of the full session history. Dramatically reduces per-turn overhead on long sessions. Enable with `experimental.compaction_markers: true`. **User Memories** โ€” historian extracts behavioral observations about the Medium4/4/2026
v0.5.2## v0.5.2 ### New Features - **TUI Sidebar** โ€” Live context breakdown bar in OpenCode's terminal UI showing token usage split across System Prompt, Compartments, Facts, Memories, and Conversation. Includes historian status, memory counts, dreamer last run, and pending queue count. Updates after every message. - **TUI Commands** โ€” `/ctx-status`, `/ctx-flush`, and `/ctx-aug` work directly in TUI mode via dialogs and toasts. - **Doctor CLI** โ€” `bunx @cortexkit/opencode-magic-context doctoMedium4/3/2026
v0.4.2## Bug Fixes - **`enabled` now defaults to `true`** โ€” installing the plugin activates it without requiring `"enabled": true` in `magic-context.jsonc`. Previously defaulted to `false`, which meant users who installed the plugin without a config file got no functionality. The config-parse failure fallback correctly stays `enabled: false`. SORRY!Medium4/1/2026
v0.4.1## What's New ### Proactive Memory Embedding Memories are now embedded immediately after `ctx_memory write` (fire-and-forget) and swept periodically on the dream timer. The first `ctx_search` after dreamer runs no longer pays bulk embedding latency. The lazy search-time fallback remains as a safety net. ### Smarter Compressor Selection The compressor no longer always picks the oldest compartments for compression. A new **weighted scoring system** (`0.7 ร— age + 0.3 ร— inverse compression depth`)Medium4/1/2026
v0.4.0## What's New ### Configurable Commit Cluster Trigger Historian can now fire based on **commit clusters** โ€” distinct work phases where the agent made git commits, separated by meaningful user turns. This captures natural work-unit boundaries even when context pressure is low. ```jsonc { "commit_cluster_trigger": { "enabled": true, "min_clusters": 3 } } ``` Default changed from 2 to 3 minimum clusters. Can be disabled entirely to rely only on pressure-based triggers. ### Dream RunMedium4/1/2026
v0.3.4## Bug Fixes (Council Audit) 8 fixes from a 13-member council audit of the plugin codebase: ### Critical - **Smart note infinite re-evaluation loop**: `JSON.parse` in smart note evaluation had no try-catch โ€” malformed LLM output caused notes to be re-evaluated on every dream run, silently consuming budget. Now catches parse errors, marks notes as checked, and uses greedy regex for bracket handling. ### High - **Dedup drop() return ignored**: Heuristic deduplication called `drop()` but didn't Medium4/1/2026
v0.3.3## What's New ### Tool-Call Summaries in Historian Chunks Previously, 61% of assistant messages (tool-only turns with no text) were completely invisible to historian โ€” it had no idea what the agent was doing between text blocks. Historian chunks now include compact `TC:` summaries extracted from tool call descriptions and key arguments: - **Bash tools**: `TC: Fix lint errors`, `TC: Run tests` - **File tools**: `TC: read(src/index.ts)`, `TC: edit(src/hooks/transform.ts)` - **Search tools**: `TCMedium4/1/2026
v0.3.2## What's New ### Smarter Compartment Trigger Projection The compartment trigger now projects all three sources of freeable context before deciding whether historian needs to fire: - **Heuristic tool drops** โ€” Old tool outputs outside the protected tail, based on `auto_drop_tool_age` and `protected_tags` - **Reasoning clearing** โ€” Thinking/reasoning bytes that will be cleared on the next cache-busting pass, based on the reasoning watermark and `clear_reasoning_age` - **Pending ctx_reduce dropsMedium3/31/2026
v0.3.1## What's New ### Message Revert Support When users revert messages in OpenCode, magic-context now properly invalidates affected internal state โ€” tags, reasoning watermarks, nudge anchors, note nudge state, stripped placeholder IDs, and FTS index entries. Compartments and facts are preserved since they represent compressed history that should survive reverts. ### ctx_search Prompt Guidance Agent prompts now include "search before asking" guidance with concrete examples. Agents will proactivelyMedium3/31/2026
v0.3.0## What's New ### Smart Notes - `ctx_note` now supports **smart notes** with `surface_condition` โ€” project-scoped conditional reminders that the dreamer evaluates nightly and surfaces when conditions are met - `ctx_note read` shows session notes plus ready smart notes; pending smart notes stay hidden until dreamer promotes them - Smart note guidance appears in agent prompts only when dreamer is enabled ### Dreamer-Maintained Project Docs - When `dreamer.inject_docs` is enabled (default), magicMedium3/30/2026
v0.2.10## Cache Safety Fixes - **Persisted reasoning clearing watermark** โ€” `clearOldReasoning` and `stripInlineThinking` were ephemeral in-memory mutations that reverted on the next defer pass when OpenCode rebuilt messages fresh from its DB. This caused a double cache bust: one from the cleanup, another when the next defer pass sent messages with reasoning blocks restored. A monotonic `cleared_reasoning_through_tag` watermark is now persisted in `session_meta` and replayed on every pass. - **StickyMedium3/30/2026
v0.2.9### Bug Fixes - **Critical**: Zero-config path now returns Zod-parsed defaults instead of empty object - `clearIndexedMessages` wrapped in transaction for consistent FTS/index state on partial failure - `isArrayLikeNumber` type guard strengthened to validate `length` is numeric and sample element is a number - Stale dream queue cleanup now uses configurable `maxRuntimeMinutes + 30min buffer` instead of hardcoded 2h - `deleteMemory` uses surgical single-memory embedding cache invalidation inMedium3/29/2026
v0.2.8## Bug Fixes - **Note nudge state persisted to DB** โ€” trigger and sticky state now survives restarts without cache busts. Previously, restarting would lose deferred triggers and cause delivered nudge text to vanish from user messages (cache bust). - **Note nudge deferred to next user message** โ€” triggers mid-turn (e.g., from todowrite) no longer inject into the current cached user message. The nudge waits for the next user turn. - **Sticky note nudge replay** โ€” delivered nudges re-inject atMedium3/29/2026
v0.2.7## Bug Fixes - **Note nudges now work in all sessions** โ€” delivery was gated by `fullFeatureMode` which is `false` for subagent/orchestrator sessions. Triggers fired but nudges were silently suppressed. Now runs independently of `fullFeatureMode`. - **Note nudge state only clears after successful placement** โ€” previously `triggerPending` was cleared before confirming the append succeeded, causing silent drops when no suitable user message existed. ## Improvements - Added logging for note nudgMedium3/28/2026
v0.2.6**Full Changelog**: https://github.com/cortexkit/opencode-magic-context/compare/v0.2.5...v0.2.6Medium3/28/2026
v0.2.5**Full Changelog**: https://github.com/cortexkit/opencode-magic-context/compare/v0.2.4...v0.2.5Medium3/28/2026

Dependencies & License Audit

Loading dependencies...

Similar Packages

dagengineType-safe DAG execution engine for AI workflowsv0.3.0
agent-knowledge-cycleMemory-centric self-improving harness for AI agents. Six-phase cycle + Security by Absence. ADRs, JSON schemas, and a dependency-free Python reference.v2.2.0
outputThe open-source TypeScript framework for building AI workflows and agents. Designed for Claude Code describe what you want, Claude builds it, with all the best practices already in place.main@2026-06-05
honcho Memory library for building stateful agentsmain@2026-06-02
delight-ai-agentSendbird AI-Agent main@2026-06-02

More in Frameworks

schemathesisProperty-based testing framework for Open API and GraphQL based apps
spec_driven_developSpec-Driven Develop is a platform-agnostic AI agent skill that automates the pre-development workflow for large-scale complex tasks. It is not a framework, not a runtime, not a package manager โ€” it is
DrasilGenerate all the things (focusing on research software)
langchainThe agent engineering platform