OpenCode plugin for coding agent workflow optimization and safeguarding. Most orchestration runs on an OpenAI-compatible embeddings model; a System One decision model is kept for the safety-critical checks: command risk and the confidence tool.
- Safeguard against potentially dangerous shell commands
- Improve token efficiency
- Deliver more reliable solutions to tasks
Most capabilities need an OpenAI-compatible text embeddings endpoint (POST <embeddings.baseURL>/embeddings, { model, input }): llama.cpp, Ollama and LM Studio all serve that shape. The embeddings model drives complexity, tool retrieval, history compaction, skill suggestions, memory, semantic search, loop detection and dispatch.
The System One decision model at <baseURL>/systemone is still required, but it is only asked the safety-critical questions: the shell guardrail, command checks before reflex_run dispatches a shell-like tool, and the on-demand confidence tool. The guardrail asks one noul block question, escalates to a typed choice risk question only when the block score is ambiguous (0.30–0.70), and blocks when either signal clears 0.70; the confidence check grounds a noul circularity question in the user's current request. Every classifier request is fitted to the model's context window before it is sent (see contextWindow below), so a small local model is never sent a prompt larger than it can hold.
OpenCode Go's Jev is opt-in: select provider: "opencode-go" (model jev-1.14) to use it. It needs no separate API key — the plugin reads the credential of the account signed in through the OpenCode integration, and usage is billed to that account's Go subscription. A configured apiKey still takes precedence. The preset is never selected automatically, so existing configurations are unaffected.
To run decision and embeddings models locally, the plugin was tuned for nomic-embed-text-v1.5 for embeddings and Julia-1 for decisions, so it's easily viable on modest hardware. We recommend you use these models, or similar ones.
- Embedding-driven complexity and effort: each request is compared with a small set of simple/medium/high coding-request exemplars. A tier must win by a clear margin, otherwise the request stays medium. The level sets
maxTokensand switches reasoning effort when the agent uses the default effort setting; an explicit model variant or effort option takes precedence. The request dialect is detected per request from the model actually being requested, so multimodel setups — including one gateway proxying many models — never send a foreign field. Wired dialects: Anthropic, llama.cpp, Ollama, OpenAI GPT reasoning models, Z.ai GLM (GLM-5.2 onwards), Xiaomi MiMo (MiMo-V2.5 onwards), Google Gemini (Gemini 3 onwards), Qwen (Qwen3.5 onwards and the qwen-plus/qwen-max aliases), Moonshot Kimi (kimi-k2.7+/kimi-k3), xAI Grok (grok-4.3 onwards) and MiniMax (MiniMax-M3 onwards) - Confidence tool: suggested on the first model call of medium/high tasks,
systemone_check_confidenceasks the decision model whether the current plan is circular or stuck, with the user's request as context, and returns CONTINUE or RESTART at a 75% confidence threshold. Repeated thoughts reuse the cached verdict and at most two actual checks run per user request, so a model cannot turn the tool into a polling loop. Together with the shell guardrail (and itsreflex_runcommand check), it is the only remaining classifier path - Embedding-driven history compaction: when history grows long, the recent messages stay verbatim (keep-window widens with complexity), the older prose closest to the current request is preserved (bounded), and the rest is folded into a compact structured digest. Folding is incremental: each compaction only summarizes the messages that aged out of the keep window since the last fold — batched so short turns stay cheap, folded once per session — and appends their facts to a persistent per-session long-term block, so per-request compaction cost stays roughly flat as the session grows. Tool outputs, tool-call plumbing and thinking/reasoning blocks past the keep window are not scored: they are discarded outright, since the assistant turns that interpreted them are the load-bearing content
- Embedding-driven tool exposure: with
tools: "auto"(implied when embeddings + tool retrieval are configured andtoolsis unset), each tool is represented by its name and description, the prompt is embedded, and only the top-k closest long-tail tools are kept. The common core (read/search/edit/shell/task, plus theexecute/search/skill/questionmeta-tools where the harness routes everything through them) and any tool already used in the session are never removed, so a multi-step task never loses a tool mid-flight. If a needed tool was trimmed,systemone_reveal_toolslists the agent's tool pool and restores all schemas for the current user request. Automatic exposure requires embeddings; without them every tool stays exposed - Embedding-driven skill suggestions: on a conversation's initial prompt, the task and each available skill's description are embedded and the closest matches are suggested for the model to load through the
skilltool. Follow-up prompts are not re-checked, and a skill drops out of the nudge once the model has loaded it. A suggestion is optional help and stays silent when the catalog or embeddings endpoint is unavailable - Project agent-docs nudge: on a conversation's initial prompt the plugin checks the project root for
AGENTS.mdand a non-empty.ai/directory, and, when found, injects a one-line note telling the model to read them before starting. The note is only sent on the opening prompt; the check is a filesystem stat, not a model call (agentDocsoption) - Long-term project memory (with embeddings): in a repository carrying a
.ai/directory,.ai/LONGTERM.mdis created automatically and durable facts — preferences, conventions, decisions, gotchas, environment details — are stored there as embedded chunks. Compaction folds old turns into that file, a background capture pass also summarizes long single-turn tool loops, and thereflex_remembertool appends an explicit fact. On each new user request the prompt is embedded against the most recent 400 chunks and only the closest are injected, so the whole file never rides in context. A stored fact that an explicit remember contradicts is removed whenmemoryPruneis on (embeddings narrow the candidates, and update/negation language confirms the deletion), andreflex_forgetremoves any fact that is no longer applicable — by its stored text, or by showing the closest matches when the wording differs. The feature is inert without a.ai/directory, and the file is plain Markdown that can be edited by hand (memoryoption; retrieval boundsmemoryTopK/memoryMinScore; maintenancememoryPrune) - Cross-project user-preference memory (with embeddings): a
USER_REFLEX.mdfile at a location you choose —USER_REFLEX.mdin your Documents directory by default — keeps standing preferences (communication style, workflow, tools and conventions, environment, personal context, boundaries) and is always active, with or without a.ai/directory and even outside a repository. A background pass reads only your own turns and distills them into preference facts;reflex_remember_userandreflex_forget_usersave and remove one explicitly. Only the chunks closest to the current request are injected, considering the most recent 200 preferences. Repository instructions and project documentation (AGENTS.md, anything under.ai/) always take precedence over user preferences when they conflict. The file is plain Markdown that can be edited, moved, backed up or copied to another machine — updateuserMemoryPathif you move it (userMemory,userMemoryPath,userMemoryTopK/userMemoryMinScore) - Semantic code/docs search (with embeddings): the
semantic_searchtool indexes the project's text files by meaning, with file paths and line ranges, so the model can find the place that handles a concept without a sequence of grep/list/read round-trips. Files are chunked with overlap, the index refreshes incrementally by mtime/size, and generated/vendor directories, lockfiles and credential files are skipped (searchoption). On a conversation's initial prompt the plugin advises the model to reach for it on concept-level lookups - Semantic answer cache (with embeddings, off by default): the opening turn of a conversation is embedded and compared against previously answered opening questions. A lookup skips the embedding entirely when no stored entry belongs to the current scope. A near-duplicate above
cacheThreshold(default 0.95) returns the stored plain-text answer without contacting the provider. The model, system prompt, tool set and sampling options must match, and answers containing tool calls are never cached (cacheoption) - Embedding-driven tool dispatch (
reflex_run): an optional fallback for when the model cannot decide which underlying tool a task needs. It narrows the pool by schema fit, picks the closest tool by meaning, runs it and returns its real output. The shell guardrail still runs before dispatching a shell-like tool - Embedding-driven stuck-loop detection: after each completed tool call the plugin fingerprints the call and its result. Identical arguments with identical output are flagged deterministically; a repeated call whose output varies is first checked with a cheap local token comparison, and only ambiguous outputs are compared by embedding. Near-identical outputs trigger the same "change approach" warning. Detection is conservative, delivered once per loop and repeated only if the loop persists
- Syntax checks: after
edit/write, language parsers check the file (TypeScript/JavaScript, JSON, Bash, Python, Ruby, PHP, Perl, Lua, Go), with one retry and then an ask-the-user stop. No classifier call is involved - Shell guardrail: blocks commands that may damage a repository, remove files without backup or leak secrets. Clearly safe commands — read-only inspection, test/build scripts, package installs, ordinary project edits/moves/cleanup, non-force git writes and public GET fetches — are allowed locally without a decision request; anything touching system/home paths, credentials, globs, recursive permission changes, destructive git subcommands or shell metacharacters goes to the model. The model path asks a
noulpolicy question with the short literal command; an ambiguous score (0.30–0.70) escalates to a typedchoicerisk question, and the guardrail blocks when either signal clears the 0.70 danger threshold. The same check runs beforereflex_rundispatches a shell-like tool. Exact command scores are cached (2,048 entries), so repeated test/build/status commands skip the classifier; a failed classifier trips a 60-second circuit and uses the configured fallback, if any. This is the only hard block in the plugin, and it fails open when no classifier can answer - Classifier context-window safety: every System One request (state plus questions) is fitted to the decision model's context window. The window is read from the
contextWindowoption when set, otherwise discovered once from<baseURL>/modelson local/LAN endpoints, with a conservative fallback. Decision models generate no completion text, so only a small protocol margin is reserved and the state gets all the room the questions do not need; sets are split by the 4-question cap and by serialized request size, and an oversized state or question is truncated instead of overflowing the model
The decision and embeddings endpoints often share one laptop's memory. The plugin keeps a single cross-model inference budget instead of letting every feature open its own requests:
- One shared gate. Both clients go through
sharedInferenceGate. The automatic concurrency is 1 when the embeddings endpoint is local (or only the decision model is configured), 2 when only the decision endpoint is local, and 3 when both are remote. Set the top-levelinferenceConcurrencyoption (1–8) to override it. Decision checks take the next free slot before queued embedding batches, so a shell guardrail check is not stuck behind semantic indexing. - Small local batches. Local embeddings default to 4 texts per request and 2,000 characters per text (
embeddings.batchSize/embeddings.maxInputCharsoverride). Remote endpoints keep 16 / 8,000. If a local server still rejects an oversized input (llama.cpp's default physical batch is 512 tokens), the client retries that text with a smaller slice and keeps the rest of the batch, so one long file cannot disable every semantic feature. - Bounded prefetch and indexing. A request prefetch is skipped above 24 texts, so one prompt never queues the whole tool/memory catalog. A first
semantic_searchindexes at most 48 new chunks per call and continues on the next search; it does not queue the whole repository at once. - Smaller local decision window. An automatically discovered local decision window is capped at 2,048 tokens;
contextWindowraises it explicitly. This keeps the encoder sequence short for commands and plans. - Server flags still matter. The plugin can only limit requests it sends. Start each local server with one slot and a modest context, for example
llama-server ... --parallel 1 -c 2048(or-np 1), and keep--sleep-idle-secondsso an idle model releases memory. Two servers each started with four slots and a large context can exhaust a laptop even when the plugin sends one request at a time. If an OpenVINO GPU build reportsCompute erroron a MoE embedding model, use the standard CPUllama.cppimage (or a model that builds on your GPU) for the embedding server. - OpenVINO compiled-model cache. The OpenVINO backend compiles a graph per input shape and stores it under
GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR. A decision model that receives many different prompt lengths can grow that cache to many gigabytes and keep a large compiled model resident even though the GGUF itself is small. For the small decision model, the standard CPUllama.cppimage avoids that cache; if you keep OpenVINO, clear the decision model's cache directory after changing prompt sizes.
The workflow features above are enabled by adding an embeddings object
pointing at any OpenAI-compatible embeddings endpoint (POST <baseURL>/embeddings
with { model, input }; llama.cpp, Ollama and LM Studio all serve that shape):
baseURL defaults to http://127.0.0.1:1118/v1, and model may be omitted to
auto-discover the first model served at <baseURL>/models (llama.cpp reports
the loaded GGUF path there). apiKey is optional and supports {env:NAME}.
The endpoint sees every text it is asked to embed — prompts, tool descriptions,
memory chunks and code chunks — so keep it on the local machine when the source
must not leave it.
Feature switches and tuning (defaults in parentheses):
| Option | Default | Meaning |
|---|---|---|
toolRetrieval |
true |
Semantic top-k tool exposure. When tools is unset, configuring embeddings also opts into automatic tool exposure; an explicit "tools": "all" still wins |
toolTopK / toolMinScore |
8 / 0.2 |
Long-tail tools kept per request, and the cosine floor for a match |
memory |
true |
Read/write .ai/LONGTERM.md; inert when the repository has no .ai/ directory |
memoryTopK / memoryMinScore |
4 / 0.3 |
Memory chunks injected per request, and the cosine floor |
memoryPrune |
true |
Remove a stored fact when an explicitly remembered fact supersedes it. Background capture and compaction never delete facts on their own; reflex_forget is always available for an explicit removal |
userMemory |
true |
Cross-project USER_REFLEX.md preference memory. Active in every project and task, independent of .ai/; repository agent documentation (AGENTS.md, .ai/) takes precedence on conflicts |
userMemoryPath |
Documents directory | Location of USER_REFLEX.md (top-level option; the installer records it there). A directory gets /USER_REFLEX.md appended; a path ending in .md is used as the file. The plugin creates the file and its folder on first use |
userMemoryTopK / userMemoryMinScore |
4 / 0.3 |
User-preference chunks injected per request, and the cosine floor |
search |
true |
Register the semantic_search tool |
cache |
false |
Semantic answer cache. Opt-in because replaying an answer is a stronger intervention than retrieval |
cacheThreshold / cacheMaxEntries |
0.95 / 200 |
Similarity needed for a cache hit, and the in-memory entry bound |
timeoutMs |
20000 |
Per-request timeout for the embeddings endpoint |
The semantic path fails open: if the endpoint is down, tool exposure keeps
every tool, history is preserved within the cap, complexity stays at medium,
memory injects nothing, semantic_search says so, and the answer cache simply
misses. On a new user request, the query and its stable documents are prefetched
in one shared batch; the individual features then join that in-flight work or
the cache instead of opening competing requests. In a repository with a .ai/ directory, .ai/LONGTERM.md is created
automatically; the cross-project USER_REFLEX.md is created at its configured
location even outside a repository. The semantic answer cache lives in plugin
memory and is cleared when OpenCode restarts.
The decision model no longer receives history excerpts or skill catalogs, so its prompts are small: a command, a thought, or a batch of independent safety checks. They are still fitted to the model's window before every request:
contextWindow(plugin option, tokens) sets the window explicitly.- When omitted, a local/LAN endpoint is probed once at
<baseURL>/modelsforn_ctx,context_length,max_model_lenor similar metadata, then capped at 2048 tokens. A remote endpoint defaults to 8192. - Decision models emit typed answers, not generated text, so the budget keeps only a small protocol margin instead of a 15% output reserve. The state gets the room the questions do not need (no fixed 35/65 split), the request is estimated at 3 characters per token, sets are split by the 4-question cap and by serialized request size, and any single oversized state or question is truncated while keeping both ends of the text.
agent-reflex is built for OpenCode and supports it as the only harness. The shell guardrail is a hard block, post-edit parser checks run inline, compaction is embedding-driven, dynamic effort speaks each model's own dialect, and tool exposure can remove schemas from the request.
Install the skill using npx skills add psygreg/agent-reflex or bun x skills add psygreg/agent-reflex then ask your agent to do it: the skill briefs the agent on the plugin's capabilities and installs or updates it — updates need no answers (bash install.sh </dev/null), fresh installs collect the answers in chat and pipe them in.
Or run the install script provided in this repository. It will also install the skill so future updates can be performed through the agent itself.
./install.shOn a fresh install it asks for the classifier provider (llama.cpp, Ollama, LM Studio, TypeSafe, OpenRouter, Vercel AI Gateway, OpenCode Zen, OpenCode Go or a custom endpoint), whether a local server runs on the same machine or a remote one (with its base URL), the classifier model, an optional API key ({env:NAME} supported), an optional fallback classifier model, an optional debug log path and the folder for the cross-project USER_REFLEX.md (the system Documents directory by default; pick somewhere easy to find, since you may want to move or back up the file later). The user-memory answer is stored as a top-level userMemoryPath option. The embeddings endpoint is not asked by the installer; add the embeddings object to the plugin options as shown above to enable the semantic features. For OpenCode Go, leave the API key blank to use the account already signed in through the OpenCode integration; the installer verifies the endpoint with that account when it can, and otherwise skips the probe with a note. Then it verifies the answers against the server itself before writing anything: the collected endpoint must answer a real System One question at <baseURL>/systemone with the configured model, and every field is checked against the mis-fills that leave the plugin broken silently (the model name in the apiKey field, a bare port as the baseURL, an api key identical to the model) — a plain chat or completion server on the same port is refused with the exact reason. AGENT_REFLEX_SKIP_VERIFY=1 bypasses this probe for environments it cannot reach.
The OpenCode plugin installs through the OpenCode plugin CLI: install.sh runs opencode plugin add github:psygreg/agent-reflex (or opencode plugin <spec> -g on older CLIs), so the plugin lives in the CLI's own package install and the entry lands in the global config the standard way; the classifier options are merged into that entry ({ "package": "github:psygreg/agent-reflex", "options": { ... } }, keeping comments and formatting; a .agent-reflex.bak backup is kept next to the config and the merged file is validated before committing). Older CLIs without the standard plugin command, offline machines, or a missing JS runtime fall back to the legacy local-copy layout (plugins/reflex next to the config + a ./plugins/reflex entry) — re-running the installer on such an installation migrates it to the standard package install. The skill installs through the skills CLI (bunx/npx skills add, into the CLI's own canonical path) when no copy exists yet; existing copies are detected and left untouched, so there is never a second installation path.
Re-running the installer only updates the plugin: an existing installation (standard package, legacy copy or config entry) is detected and the configured options are left untouched — except that a legacy local-copy install migrates to the standard package install, with its options carried over. The OpenCode plugin and its opencode.json(c) entry are written only when the opencode CLI is on PATH; without it, a fresh install stops before the classifier prompts and reports that there is nothing to install. After installing or updating, restart OpenCode (opencode service restart) to load the plugin.
For development, add a "debugLog": key to the plugin's options pointing to a file to write the logs into. Configuration reference examples live in opencode.example.jsonc.
- Add automatic effort changing capabilities for local models running through LM Studio (blocked upstream: its OpenAI-compatible endpoint documents no reasoning field yet)
- Add automatic effort changing capabilities for other providers beyond the wired dialects (Anthropic, GPT, GLM, MiMo, Gemini, Qwen, Kimi, Grok, MiniMax)
{ "package": "github:psygreg/agent-reflex", "options": { "provider": "llamacpp", "baseURL": "http://127.0.0.1:1123/v1", "model": "liquid-d1", "userMemoryPath": "/home/you/Documents/USER_REFLEX.md", "embeddings": { "baseURL": "http://127.0.0.1:1118/v1", "model": "/models/Qwen3-Embedding-0.6B-Q8_0.gguf", "toolRetrieval": true, "memory": true, "search": true, "cache": false } } }