Building an Unattended-Safe Coding Agent Runtime in Bun (oma): Sandboxing, Anti-Injection Classification, Pair-Safe Compaction, and Comparing It to pi
Building an interactive coding agent takes fifty lines of code. Keeping it safe and coherent when running unattended for two hours hits two hard runtime problems immediately:
- Prompts cannot enforce security boundaries. Instructions hidden in a repo README or fetched web page, or a destructive command padded past an 8,000-character truncation limit, routinely slip past naive filters. Even inside a sandbox, a command that edits
.mcp.jsonor.oma/settings.jsoninside the workspace can weaken its own guardrails. - Long sessions bloat KV Cache and break on naive compaction. Dozens of
grepand test logs quickly overflow context windows, and cutting conversation history between anassistant(tool_use)and itstool(tool_result)triggers instant HTTP 400 errors from model APIs.
This post walks through the concrete code I wrote to handle both in oma (@chengchenccc/oh-my-agent, an open-source Bun coding agent that runs standalone or as CrewDesk's ACP worker runtime), followed by an honest comparison with Mario Zechner's pi (pi-coding-agent).
1. Keeping Provider SDKs Out of the Core Loop
oma's core loop has zero dependency on any LLM SDK. The only integration seam is a single streaming contract:
ChatModel.stream(messages, opts?) -> AsyncIterable<AIMessageChunk>
Anthropic, OpenAI-compatible APIs, DeepSeek, Groq, OpenRouter, and ~/.oma/models.yml routing live in packages/ai. The practical payoff is testability: the entire loop, approval gate, plugin pipeline, overflow recovery, and compaction suite runs deterministically in milliseconds against echoModel() with zero network calls.
Plugins are plain objects { name, hooks?, tools?, meta? } checked at startup by validatePlugins() for name and tool collisions.
2. Security: Anti-Injection Classifier + Tamper-Resistant OS Sandbox
Under permissionMode: "ask", sensitive calls pause immediately for approval and fail closed on timeout or channel errors. Under permissionMode: "auto", side-effectful tools (bash, eval, mcp__*, plugin code tools) pass through permission-classifier.ts with two deliberate structural defenses:
- The classifier never sees tool outputs. It receives only the user's messages and the pending tool call — so prompt injections embedded in files or web responses never enter its context window.
- No silent tail truncation. Cutting oversized inputs at
slice(0, 8000)lets an attacker pad the front and hiderm -rfat the end.omakeeps head 4,000 + tail 4,000 chars and injects an explicit[TRUNCATED ...]marker:
const serialized = JSON.stringify(input) ?? "undefined";
const MAX_INPUT_CHARS = 8000;
// Never silently drop the tail: preserve head + tail AND surface a truncation marker
const formattedInput =
serialized.length <= MAX_INPUT_CHARS
? serialized
: `${serialized.slice(0, 4000)}\n... [TRUNCATED ${serialized.length - 8000} chars of ${serialized.length} total] ...\n${serialized.slice(-4000)}`;
Any payload marked [TRUNCATED ...] defaults to block unless obviously benign read-only work, and unparseable responses, timeouts, or stream drops fail closed as block.
At the OS level (bash-sandbox.ts), oma wraps commands in Bubblewrap (bwrap) on Linux and Seatbelt (sandbox-exec) on macOS, with two battle-tested details:
- Mask host homes, then remount policy files read-only. On Linux,
bwrapcovers/root,/home, and/tmpwith--tmpfsbefore binding the workspace (hiding~/.ssh,~/.oma,~/.env), then remounts.mcp.json,.oma/plugins.json,.oma/settings.json, and.oma/settings.local.jsonread-only so a command cannot rewrite MCP endpoints or loosen its own rules. - Strict
/dev/ttyisolation. Background commands spawn withdetached: true(setsid) andstdin: "ignore"sosshorscpcan never hijack the TUI terminal or swallow keystrokes.
3. Long-Session Context Hygiene: Read-Side Pruning + Pair-Safe Compaction
To keep KV Cache healthy and avoid premature summaries, oma manages context in two stages:
- Stage 1: Read-side pruning (
tool-pruning.ts). Scanning backward from the newest message, the most recent 8,000 tokens of tool outputs stay untouched (along with protected tools like loadedSKILL.mdfiles and plans). Older large outputs and images project as compact[pruned: ...]stubs without mutating persisted history. - Stage 2: Pair-safe structured compaction (
compaction.ts). When the window actually fills, deterministic state blocks preserve edited files, executed commands, and Q&A outcomes across summaries — andadjustCutForToolPairs()prevents splitting anytool_use/tool_resultpair:
function adjustCutForToolPairs(messages: readonly CodingSessionEntry[], cutIdx: number): number {
let cut = cutIdx;
while (cut > 0 && cut < messages.length && messages[cut]?.type === "message") {
const first = messages[cut] as { role?: string; message?: { blocks?: Array<{ type?: string; tool_use_id?: string }> } };
if (first.role !== "tool") break;
const toolUseIds = new Set(
(first.message?.blocks ?? [])
.filter((b) => b.type === "tool_result" && typeof b.tool_use_id === "string")
.map((b) => b.tool_use_id!),
);
if (toolUseIds.size === 0) break;
let earliestIdx = -1;
for (let i = 0; i < cut; i++) {
const m = messages[i] as { role?: string; message?: { blocks?: Array<{ type?: string; id?: string }> } };
if (m.role === "assistant" && m.message?.blocks?.some((b) => b.type === "tool_use" && b.id && toolUseIds.has(b.id))) {
earliestIdx = i;
break;
}
}
if (earliestIdx === -1) break;
cut = earliestIdx;
}
return cut;
}
On the interactive side, oma's TUI supports collapsible structured tool cards, mid-turn steering, and native terminal Mermaid rendering:


4. Comparing oma Honestly to pi (pi-coding-agent)
Mario Zechner's pi (pi-mono / pi-coding-agent) is one of the cleanest open-source coding agents around. Its philosophy is unmistakable: ship 4 core tools (read, write, edit, bash), keep the base prompt tiny, and let developers build everything else with hot-reloading (/reload) TypeScript extensions.
oma shares much of that engineering taste (clean TypeScript, unified multi-protocol model layer, auditable loop, branching session trees), but targets a different sweet spot:
| Dimension | pi (pi-coding-agent) | oma (@chengchenccc/oh-my-agent) |
|---|---|---|
| Primary goal | Minimalist personal canvas tailored by the developer | Hardened batteries-included runtime for both local CLI and unattended ACP workers |
| Default tools | 4 tools (read/write/edit/bash); everything else via extensions | Files, search, sandboxed eval, web, browser, todo, two-stage skill_load, native MCP |
| Security | Trusts the developer's local terminal by default | Fail-Closed approvals, anti-injection classifier, Linux bwrap / macOS Seatbelt, read-only policy mounts |
| Compaction | Minimal prompt + tree compaction | Read-side 8k-token pruning window + pair-safe compaction + deterministic file/command state |
| Extensibility | Self-modifying TS extensions + /reload + Pi package ecosystem | Plain-object lifecycle plugins, two-stage SKILL.md, native MCP |
| Runtime | Node.js / npm ecosystem | Native Bun (fast startup, Bun.spawn, SQLite) + terminal Mermaid rendering |
Tradeoffs to keep in mind:
- Choose
piif you want the lightest 4-tool personal canvas and love building hot-reloaded TS extensions in a mature package ecosystem. - Choose
omaif you want Bun startup speed plus built-in OS sandboxing, anti-injection auto-classification, two-stage compaction, and native MCP out of the box — or a clean path into multi-agent orchestration. oma's real limits: it requires Bun, carries a heavier default tool surface thanpi, and Linuxbwrapsandboxing requires user namespaces enabled in restricted container environments.
5. Try oma Standalone in 30 Seconds
No backend or database needed:
bun add -g @chengchenccc/oh-my-agent@rc
export ANTHROPIC_API_KEY=sk-ant-...
oma
Works with Anthropic, OpenAI, DeepSeek, Groq, OpenRouter, or custom endpoints (see Models & Providers). When one terminal stops being enough, oma gateway up boots full CrewDesk on the exact same runtime.
Source Code:
- Classifier & truncation defense: permission-classifier.ts
- Pair-safe compaction & read-side pruning: compaction.ts · tool-pruning.ts