← All posts

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:

  1. 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.json or .oma/settings.json inside the workspace can weaken its own guardrails.
  2. Long sessions bloat KV Cache and break on naive compaction. Dozens of grep and test logs quickly overflow context windows, and cutting conversation history between an assistant(tool_use) and its tool(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 hide rm -rf at the end. oma keeps 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, bwrap covers /root, /home, and /tmp with --tmpfs before binding the workspace (hiding ~/.ssh, ~/.oma, ~/.env), then remounts .mcp.json, .oma/plugins.json, .oma/settings.json, and .oma/settings.local.json read-only so a command cannot rewrite MCP endpoints or loosen its own rules.
  • Strict /dev/tty isolation. Background commands spawn with detached: true (setsid) and stdin: "ignore" so ssh or scp can 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:

  1. 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 loaded SKILL.md files and plans). Older large outputs and images project as compact [pruned: ...] stubs without mutating persisted history.
  2. 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 — and adjustCutForToolPairs() prevents splitting any tool_use / tool_result pair:
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:

oma TUI rendering Mermaid architecture diagrams directly in the terminal

oma TUI live coding session with structured tool panels

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:

Dimensionpi (pi-coding-agent)oma (@chengchenccc/oh-my-agent)
Primary goalMinimalist personal canvas tailored by the developerHardened batteries-included runtime for both local CLI and unattended ACP workers
Default tools4 tools (read/write/edit/bash); everything else via extensionsFiles, search, sandboxed eval, web, browser, todo, two-stage skill_load, native MCP
SecurityTrusts the developer's local terminal by defaultFail-Closed approvals, anti-injection classifier, Linux bwrap / macOS Seatbelt, read-only policy mounts
CompactionMinimal prompt + tree compactionRead-side 8k-token pruning window + pair-safe compaction + deterministic file/command state
ExtensibilitySelf-modifying TS extensions + /reload + Pi package ecosystemPlain-object lifecycle plugins, two-stage SKILL.md, native MCP
RuntimeNode.js / npm ecosystemNative Bun (fast startup, Bun.spawn, SQLite) + terminal Mermaid rendering

Tradeoffs to keep in mind:

  • Choose pi if you want the lightest 4-tool personal canvas and love building hot-reloaded TS extensions in a mature package ecosystem.
  • Choose oma if 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 than pi, and Linux bwrap sandboxing 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:

Want to try it on your own machine?

Both CrewDesk and oma are MIT open source — run locally on Bun + SQLite in two commands.