Manual de Usuario de openOnyx (openonyx)

🇬🇧 Read the full User Manual in English

Bienvenido al manual oficial de openonyx, el harness de agente de programación determinista (CLI, TUI y Web PWA embebida) construido sobre el microkernel OnYX (onyx-core → onyx-soul-agents → onyx-workspace → open-onyx).

A diferencia de otros asistentes de terminal que mezclan estado en memoria volátil, openonyx registra cada decisión, lectura, edición y comando en un grafo EAV determinista con:

  • Snapshots comprimidos por hitos (snapshots.onyxpack) con verificación FNV-1a y tolerancia a cortes.
  • Time-travel y bifurcación segura (/rewind, /fork, chat --resume --tick, rewind --interactive).
  • Depurador Temporal Interactivo (TimeFreeze, SDD-07): pausa la sesión en cualquier tick (TUI: Alt+←/→, Ctrl+T, /time, /go, /step, /step-llm; Web: #tick-pill → barra ámbar) sobre un anillo RAM de fronteras + hitos en disco; primitivas 0-tokens selladas en ONYXTR2 (0 red, 0 disco: !cmd, /read, /inject, /step) y cirugía segura del grafo congelado con /graph (inspect / drop-mem / edit-mem / set-goal); 100 % efímero hasta confirmar la bifurcación.
  • Subagentes asíncronos en worktrees Git aislados (spawn_subagent / /spawn, fusión 3-way con Scent-Heated Merge, --max-subagents, y harnesses CLI externos como drivers opcionales [[external_drivers]]), y spawn_agent(isolated: true): hijos síncronos en worktrees aislados onyx/sub/agent-* con reconciliación 3-way que nunca toca HEAD ni la raíz hasta el merge.
  • Benchmark multi-modelo (openonyx bench): mismos snapshot/tick, worktrees desechables por candidato (rewind + RAII), candidatos LLM vivos provider:model o replays offline replay:<label>=<file.tr>, --verify sandboxed, tabla Markdown de 9 columnas + informe JSON --out; la raíz queda 100 % intacta.
  • Verify-on-Edit ([verify] / [[verify.rules]] en .onyx/config.toml): tras cada fs_edit/fs_write exitoso, ejecuta las reglas cuya glob empareja el archivo editado (y tests scope:test impactados por Scent) en sandbox y inyecta [verify: PASS|FAIL|BLOCKED] a la observación del tool, sujeto a Workspace Trust y [permissions].deny.
  • Objetivo LLM conmutable en caliente ([[llm_profiles]], /profile / /provider / /model / /effort, cabecera provider/model viva y selector Web sin credenciales) con proveedor nativo Anthropic (Messages API, prompt caching ephemeral y extended thinking acotado con --thinking-budget).
  • Herramientas dinámicas MCP ([mcp.servers.<name>] con transportes stdio y http): cada tool se expone como mcp__<server>__<tool>, siempre con aprobación explícita, Deny en PLAN/EXPLORE, con gate de Workspace Trust, aislamiento de fallos por servidor y auditoría en openonyx doctor.
  • TUI modular F1..F5 (Chat, Agents, Sprout, Plan & Diff, Timeline) con paleta de comandos Ctrl+K y /view.
  • Checkpoints Git reversibles (/undo) sin tocar HEAD ni tu área de staging.
  • Grabación y reproducción 100% offline (ONYXTR2, 0 llamadas de red, 0 escrituras en disco).
  • Seguridad por capas: Workspace Trust con blake3 (openonyx trust / /trust), modos PLAN / BUILD / EXPLORE, reglas .onyx/config.toml (deny > ask > allow), Scent-Heated Approvals, sandbox OS con env_clear(), protección RO del Control Plane y ProcessJob RAII.
  • Interfaz Web / PWA embebida (openonyx serve): servidor HTTP/1.1 + SSE puro en std::net (0 tokio), pensado para navegador local, móvil Android/iOS o despliegue detrás de proxy HTTPS, con autenticación constante por blake3 (Cookie HttpOnly / Bearer) y --cors-origin para clientes externos.
  • Navegación semántica AST Scent 2.0 (onyx-scent: scent_outline + scent_impact + scent_references): 7 lenguajes (Rust, Python, Java, TypeScript, JavaScript, Go, C/C++), tipos EntityKind::{TypeAlias, Component}, caché binaria incremental .onyx/scent.idx (ONYXSCI1, recarga < 20 ms) y CLI scent outline|impact|references; más orquestación local de servicios/contenedores (sprout.toml).

Índice del Manual


Rutas de Lectura Recomendadas


Requisitos Previos

  • Rust 1.85 o superior (el repositorio fija 1.85.1 en rust-toolchain.toml con edition = "2024").
  • Git instalado en el PATH (necesario para checkpoints reversibles /undo, rewind, git_status y git_diff).
  • Acceso a un LLM:
    • Una clave de Google AI Studio (GEMINI_API_KEY), o
    • Una clave de OpenAI / OpenRouter (OPENAI_API_KEY), o
    • Una clave de Anthropic (ANTHROPIC_API_KEY) para el proveedor nativo (--provider anthropic), o
    • Un servidor local compatible con OpenAI (/v1/chat/completions) como Ollama, vLLM o LM Studio (sin API key requerida).
  • Opcional: docker, nerdctl o podman si vas a usar --sandbox strict-container o servicios kind = "container" en sprout.toml; bwrap (Bubblewrap) en Linux para aislamiento de sistema de archivos.

Otros Documentos del Repositorio

01. Primeros Pasos con openOnyx

🇬🇧 Read this chapter in English

En menos de 10 minutos pasarás de compilar openonyx a ejecutar tu primera sesión interactiva con streaming SSE, cambios supervisados con diff en color, modo PLAN/BUILD y reversión instantánea con /undo.


1. Compilar o instalar openonyx

Desde la raíz del repositorio OnYX:

# Compilación optimizada (recomendada para uso diario)
cargo build --release -p open-onyx

# O instalar en ~/.cargo/bin para invocar `openonyx` desde cualquier proyecto
cargo install --path open-onyx

Comprueba que el binario responde y revisa el estado de tu entorno:

openonyx --version
openonyx --help
openonyx doctor

Tip: si no instalaste el binario globalmente, puedes sustituir openonyx por cargo run --release -p open-onyx -- en todos los comandos de este manual, o usar ./target/release/openonyx (Windows: .\target\release\openonyx.exe).


2. Configurar tu proveedor LLM

openonyx soporta de forma nativa Gemini (por defecto) y cualquier API compatible con OpenAI /v1/chat/completions (OpenAI, OpenRouter, Ollama, vLLM, LM Studio).

Opción A — Google Gemini (default)

Windows (PowerShell):

$env:GEMINI_API_KEY = "tu-api-key"
openonyx chat --auto-save

Linux / macOS (bash/zsh):

export GEMINI_API_KEY="tu-api-key"
openonyx chat --auto-save

Para elegir modelo o esfuerzo de razonamiento (low, medium, high):

openonyx chat --model gemini-2.5-pro --effort high --auto-save

Opción B — OpenAI / OpenRouter

Windows (PowerShell):

$env:OPENAI_API_KEY = "sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save

Linux / macOS:

export OPENAI_API_KEY="sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save

Con OpenRouter u otro proxy compatible:

openonyx chat --provider openai --api-base https://openrouter.ai/api/v1 --model anthropic/claude-sonnet-4 --auto-save

Opción C — Modelo local (Ollama, vLLM, LM Studio)

Cuando especificas --api-base (o OPENAI_API_BASE / OPENAI_BASE_URL), no necesitas configurar OPENAI_API_KEY.

Ollama:

openonyx chat --provider openai --api-base http://localhost:11434/v1 --model qwen2.5-coder:14b --effort low --auto-save

vLLM / LM Studio:

openonyx chat --provider openai --api-base http://localhost:8000/v1 --model Qwen/Qwen3-Coder-30B-A3B --auto-save

Consejo: usar --auto-save (o fijar ONYX_AUTO_SAVE=1 en tu entorno) guarda automáticamente los snapshots y la transcripción .tr juntos dentro de .onyx/vault/<fecha>_<modelo>_<rama>/ (ignorado automáticamente por Git) para que nunca ensucies la raíz del repo y siempre puedas usar /rewind o --resume.


3. Tu primera sesión interactiva (openonyx chat)

  1. Abre una terminal dentro de cualquier repositorio Git (o pasa -w /ruta/al/proyecto).
  2. Lanza openonyx chat --snapshot-dir .snaps_demo --record demo.tr.
  3. Verás la TUI con:
    • Cabecera superior: emblema de estado, modo [BUILD] (o [PLAN]), badge de sandbox [SANDBOX:workspace], modelo y esfuerzo, y barra de telemetría (ctx, tokens in/cache/out/think y coste).
    • Panel principal Memory & Trace: conversación, llamadas a herramientas y respuestas streaming [stream] ...▍.
    • Caja de entrada inferior: tu prompt y accesos rápidos.

Paso 1 — Explora sin riesgo en modo [PLAN]

Pulsa Tab para cambiar a [PLAN] (solo lectura; las herramientas mutantes quedan bloqueadas automáticamente). Escribe un objetivo de análisis y pulsa Enter:

Analiza la estructura de este repositorio y propón un plan para añadir una función de saludo en el módulo principal.

Observa cómo el agente usa herramientas de solo lectura (glob_files, scent_outline, code_search, fs_read, plan_update) sin pedirte aprobación. Si tu terminal tiene >= 100 columnas y el agente actualiza su lista de pasos, aparecerá el panel derecho Live Plan.

Paso 2 — Pasa a [BUILD] y aprueba cambios con diff en color

Pulsa Tab de nuevo para pasar a [BUILD] y escribe:

Implementa el cambio en el archivo principal y ejecuta los tests.

Cuando el agente invoque fs_edit, fs_write o shell_exec, la TUI se pausará en WaitingApproval:

  • Verás qué agente pide la acción ([agent #1 ...]).
  • Para ediciones de archivos, verás un diff unificado en color antes de tocar el disco.
  • Puedes desplazarte por el historial mientras revisas con Up/Down/PgUp/PgDn.
  • Pulsa y para aprobar o n para rechazar (si rechazas, el agente recibe la denegación y puede ajustar su propuesta).

Paso 3 — Deshacer el último cambio con /undo

¿No te convenció el último fs_edit o fs_write? Escribe en la caja de entrada:

/undo

openonyx restaura el checkpoint Git ligero capturado justo antes de la edición —sin modificar HEAD ni tu git add— y, si la operación fue un fs_write que creó un archivo nuevo no rastreado, lo elimina limpiamente sin tocar otros archivos tuyos.

Paso 4 — Salir guardando todo

Pulsa Esc o Ctrl+C. openonyx guarda el hito final (exit) en .snaps_demo/snapshots.onyxpack y cierra la transcripción demo.tr.


4. Reanudar, inspeccionar o reproducir después

Una vez cerrada tu primera sesión, prueba estos tres comandos sin gastar tokens extra:

# 1. Ver todos los hitos guardados y sus checkpoints Git
openonyx inspect .snaps_demo --list

# 2. Reproducir la sesión 100% offline (0 HTTP, 0 cambios en disco)
openonyx replay demo.tr

# 3. Reanudar exactamente donde lo dejaste
openonyx chat --resume .snaps_demo

5. Ejecución de un solo turno (headless)

Si prefieres ejecutar una tarea puntual sin TUI (por ejemplo desde un script o CI):

openonyx run "resume los cambios pendientes en git diff" --record run.tr --snapshot-dir .snaps_run

Al terminar, openonyx imprime el resultado final y una línea [openOnyx telemetry] con los tokens y coste de la ejecución.


← Índice del Manual · English Quickstart → · Siguiente: 02. Interfaz TUI y Flujo Diario →

02. Interfaz TUI y Flujo de Trabajo Diario

🇬🇧 Read this chapter in English

Este capítulo detalla cada componente visual de openonyx chat, cómo controlar el esfuerzo de razonamiento (--effort) y cambiar el objetivo LLM en caliente, cómo funciona la memoria multi-turno y el contexto escalonado (/compact), cómo navegar las cinco vistas efímeras F1..F5 (con la paleta Ctrl+K y /view), y cómo supervisar subagentes desde la vista F2 Agents (o el selector /agent).


1. Anatomía de la TUI

Al ejecutar openonyx chat, la pantalla se organiza en cuatro zonas bien definidas:

┌ F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline · Esc:Quit ──────────────┐
│ openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high)              │
│ goal:  Refactoriza el parser… · phase: thinking / streaming… · #1 [root] [subagents:1] │
│ ⠋ Tab: Plan/Build · F2: Agents · /rewind · /fork · /services · Esc: quit               │
└─ ctx: 24% · in: 18.4k (cache 12.1k) · out: 1.9k · think: 0.6k · ~$0.024 ────────────────┘
┌─ Memory & Trace (Agent #1 root) ───────────────────────┐┌─ Live Plan ───────────────────┐
│ [user] Refactoriza el parser...                        ││ [x] Inspeccionar AST          │
│ [call] scent_outline {"path":"src/parser.rs"}          ││ [>] Editar parser.rs          │
│ [obs]  @TOON v1 ...                                    ││ [ ] Ejecutar cargo test       │
│ [stream] Voy a ajustar la validación de rangos...▍     │├───────────────────────────────┤
│                                                        ││ Services (Sprout)             │
│                                                        ││ [READY] postgres (5432)       │
│                                                        ││ [READY] api      (8080)       │
└────────────────────────────────────────────────────────┘└───────────────────────────────┘
┌─ [BUILD] Goal / Command (Enter send · Tab Plan/Build · F2 Agents · /rewind · /fork …) ──┐
│ > _                                                                                     │
└─────────────────────────────────────────────────────────────────────────────────────────┘

Cabecera compacta (pestañas + título + cuerpo + telemetría)

  • Tira de pestañas (fila superior, alineada a la derecha): F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline, con la vista activa en blanco negrita. Al final, la etiqueta Esc:Quit en F1 Chat o Esc:Back en las vistas efímeras; si hay una aprobación pendiente fuera de F1 Chat, se sustituye por el badge rojo [F1 Chat !APPROVAL] (aprobar a ciegas está prohibido: en las demás vistas y/n nunca aprueban ni deniegan).
  • Fila de título: openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high) — badge de modo ([BUILD], [PLAN] o [EXPLORE]), badge de sandbox ([SANDBOX:workspace], [SANDBOX:strict] o [SANDBOX:off]), el tag [UNTRUSTED] si el workspace no está confiado y el objetivo LLM vivo provider/model (effort:...), que se actualiza en caliente con /profile / /provider / /model / /effort (sección 2.1).
  • Filas de cuerpo:
    • Emblema Braille animado (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏, actualizado con throttle de 90 ms) cuando hay actividad en curso (thinking, acting, waiting_children, streaming SSE).
    • Objetivo y fase: goal: del agente enfocado y phase: con la fase en curso, el ID/nombre/rol (#1 openonyx-1 [root]), los tags [subagents:N · bg:M · F2] (o [N/M agents · F2]), [queued:N] y, si el guardado en sesión está activo (--auto-save o --snapshot-dir), la etiqueta viva vault:<sesion> (que se actualiza automáticamente al crear ramas con /fork o /rewind).
    • Atajos rápidos o tira de agentes: recordatorio compacto (Tab: Plan/Build · F2: Agents · /rewind · /fork · /services · Esc: quit) o, con múltiples agentes, la tira compacta de agentes en una línea.
  • Borde inferior (Telemetría en vivo):
    • Ocupación aproximada de ventana de contexto (ctx: <1% o XX%).
    • Contadores acumulados de sesión del proveedor: in, cache (tokens servidos desde prompt cache), out y think (tokens de razonamiento cuando el proveedor los reporta).
    • Coste estimado (~$0.024) para modelos cloud conocidos, o local cuando usas un --api-base personalizado.
    • Esta telemetría vive fuera del grafo EAV para no alterar nunca el determinismo de ticks, snapshots ni replay.

Panel Memory & Trace y navegación por historial

  • Muestra la conversación completa del agente enfocado: prompts de usuario, llamadas a herramientas ([call]), observaciones ([obs]), respuestas del modelo, notas del sistema ([system]) y la vista previa SSE en tiempo real ([stream] ...▍, renderizada en pump_idle sin consumir ticks).
  • Desplazamiento suave: usa Up, Down, PgUp, PgDn, Home, End, Ctrl+U y Ctrl+D incluso mientras hay una aprobación pendiente. Cuando subes en el historial, aparece el indicador [SCROLLED -N lines | End to follow]; pulsar End o enviar un nuevo mensaje devuelve el seguimiento automático al final.

Paneles laterales automáticos (>= 100 columnas)

Cuando tu terminal tiene al menos 100 columnas de ancho, la zona central se divide en 70% (Memory & Trace) y 30% (panel derecho):

  • Live Plan: aparece automáticamente cuando el agente registra pasos con plan_update ([x] completado, [>] en progreso, [ ] pendiente).
  • Services (Sprout): aparece cuando existe un sprout.toml válido en el workspace, mostrando el estado coloreado de cada servicio ([READY], [STARTING], [PENDING], [FAILED], [OFF]).
  • Si ambos están activos a la vez, la columna derecha se divide 50% / 50% verticalmente.

Panel de aprobación con diff unificado (y / n)

Cuando cualquier agente solicita una herramienta mutante (fs_write, fs_edit, shell_exec, service_start, service_stop, service_exec) que requiere confirmación:

  • El panel de aprobación identifica explícitamente al solicitante: [agent #id name] (muy útil cuando delegas trabajo a subagentes).
  • Para fs_write y fs_edit (incluyendo ediciones atómicas multi-hunk), se calcula una vista previa de diff unificado en color antes de escribir nada en disco.
  • Pulsa y para aprobar o n para rechazar.
  • Solo desde F1 Chat: en las vistas efímeras F2..F5 las teclas y/n nunca aprueban ni deniegan; la tira de pestañas muestra el badge [F1 Chat !APPROVAL] para recordarte volver a F1 a revisar el diff y la línea # impact:.

2. Control del Esfuerzo de Razonamiento (--effort)

Puedes modular cuánto tiempo y tokens dedica el modelo a razonar internamente:

ValorGemini (thinkingLevel)OpenAI-compatible (reasoning_effort)Uso recomendado
lowLOWlowTareas rápidas, consultas de lectura, modelos locales ligeros
mediumMEDIUMmediumBalance diario de edición, debugging y refactorizaciones
highHIGHhighDiseño arquitectónico, bugs sutiles, auditorías complejas

Se puede indicar por flag o por variable de entorno (precedencia: --effort > ONYX_EFFORT > GEMINI_THINKING_LEVEL / OPENAI_REASONING_EFFORT):

openonyx chat --effort high
# o mediante variable de entorno:
export ONYX_EFFORT=medium

Para anthropic: el esfuerzo se traduce en un presupuesto de extended thinking (thinking.budget_tokens: low 2048 / medium 8192 / high 16384 tokens) cuando no se fija uno explícito. Puedes acotarlo con --thinking-budget <n> (o ANTHROPIC_THINKING_BUDGET; 0 = off, rango 1024..=60000), que además eleva max_tokens por encima del presupuesto. El proveedor soporta además prompt caching (cache_control: ephemeral en el sistema y la última definición de tool) y reintentos automáticos ante 429/529 (capítulo 06).

2.1 Objetivo LLM en caliente (/profile, /provider, /model, /effort)

Más allá del esfuerzo, el objetivo LLM completo (proveedor, modelo, api_base y esfuerzo) es conmutable en caliente sin reiniciar la sesión:

  • Perfiles: bloques [[llm_profiles]] en .onyx/config.toml (workspace confiado) con id, provider (gemini | openai | anthropic), model, effort, api_base opcional y api_key_env opcional. Nunca se admiten claves literales en el archivo (detalles en el capítulo 03).
  • Comandos slash: /profile [id] lista o aplica un perfil, /provider <gemini|openai|anthropic>, /model <name> y /effort <auto|low|medium|high>. El cambio se aplica en la siguiente frontera de tick y queda sellado en la transcripción ONYXTR2 (replay determinista).
  • Cabecera viva: la fila de título pasa a mostrar provider/model (effort:...) del objetivo actual en lugar del de arranque.
  • Paleta Ctrl+K: alternativa sin teclear — filtras perfiles, proveedores y esfuerzos y ejecutas con Enter (las acciones LLM pasan por el bus determinista, igual que si las tecleas; un perfil sin credenciales se muestra como unavailable con su motivo y no es seleccionable).
  • Web UI (openonyx serve): el botón LLM target (subtítulo de la marca) abre un diálogo modal con perfil/modelo/esfuerzo y botones Apply/Cancel, sin exponer credenciales al navegador.

Las credenciales nunca viven en el config: cada perfil resuelve su clave por api_key_env (o la variable estándar del proveedor → ONYX_API_KEY). Un perfil sin clave o con api_base rechazada se lista como unavailable con su motivo accionable.


3. Conversaciones Multi-Turno, Guardia de Raíz Activa y /new

Continuación automática (continue_agent)

Al terminar un turno (Settled), escribir un nuevo mensaje y pulsar Enter no crea un agente amnésico: openonyx reactiva al mismo agente raíz mediante continue_agent, conservando toda su rel_memory con contador de pasos monótono.

Cola de seguimiento mientras el agente trabaja (queued:N)

Si el agente raíz está ocupado (thinking, acting, waiting_children o waiting_approval), puedes escribir tu siguiente instrucción y pulsar Enter: en lugar de crear un segundo agente raíz que compita por el workspace, la TUI la encola automáticamente (queued:N en cabecera y borde inferior, previsualizada si la entrada está vacía, y limpiable en cualquier momento con Ctrl+X) y la despacha al instante en cuanto el turno termina. Los comandos inmediatos (/agent, /mode, /services, /service, /undo) siguen ejecutándose al momento.

Autocompletado /, @archivo, cursor e historial de entrada

  • Cursor UTF-8 visible: muévete dentro del prompt con Left, Right, Home, End, Backspace y Delete.
  • Historial de prompts: navega tus prompts anteriores con Alt+Up / Alt+Down (o Ctrl+P / Ctrl+N), conservando automáticamente tu borrador si vuelves abajo.
  • Popup /: al empezar con /, aparece un menú flotante con todos los comandos slash y su descripción (↑/↓, Tab/Enter para aceptar, Esc para cerrar).
  • Popup @: al escribir @ al inicio de una palabra (p. ej. revisa @tui), se filtran en tiempo real las rutas del workspace (ignorando .git, target, node_modules y .onyx/vault) y al pulsar Tab/Enter se inserta la ruta relativa limpia.

Empezar una conversación limpia (/new)

  • /new: marca que el siguiente prompt creará un agente raíz limpio desde cero (sin arrastrar historial de la tarea anterior).
  • /new <objetivo>: crea y lanza inmediatamente un nuevo agente raíz con <objetivo> y enfoca la vista automáticamente en él.

4. Contexto Escalonado y /compact [focus]

Para evitar que sesiones largas agoten la ventana de contexto o disparen el coste de tokens, openonyx aplica un motor de contexto escalonado (Tier 0 / Tier 1 / Tier 2) compartido por Gemini y OpenAI:

  • Tier 0 (Completo): las últimas 10 observaciones de herramientas se envían íntegras al modelo.
  • Tier 1 (Resumen con coordenadas): observaciones antiguas de fs_read, scent_outline, scent_impact, code_search, glob_files y shell_exec se comprimen determinísticamente preservando rutas, rangos de líneas y códigos de salida, manteniendo prefijos estables para maximizar el prompt caching.
  • Tier 2 (Compactación /compact y auto-compactación): al llegar al umbral automático (80% de presupuesto de contexto) o al invocar manualmente /compact [focus], CommandSpawnerSystem inserta un límite [session_summary] verificado en la memoria del agente.

Cómo sacar partido a /compact [focus]

/compact
/compact autenticacion jwt y middleware

Cuando proporcionas un [focus]:

  1. openonyx rescata automáticamente files_found y focus_matches relevantes a las palabras clave desde turnos anteriores.
  2. El porcentaje ctx: baja de inmediato en el siguiente turno.
  3. Se guarda el hito cmd:/compact en snapshots.onyxpack.
  4. No se pierde nada: los ticks anteriores al /compact siguen intactos en el grafo y en snapshots.onyxpack para inspect, replay y rewind.

5. Vistas Modulares F1..F5, Paleta Ctrl+K y /view

Además de F1 Chat (traza, paneles laterales, input y aprobaciones), la TUI expone cuatro vistas efímeras a las que saltas con la tecla funcional, /view <nombre> o la paleta Ctrl+K:

VistaTeclaSlashContenido
F1 ChatF1/view chatTraza Memory & Trace, paneles Live Plan / Services (Sprout), input y aprobaciones
F2 AgentsF2/view agentsAgentes del grafo + jobs asíncronos [bg] (con badge → <driver> si el worktree lo corre un harness CLI externo)
F3 SproutF3/view sproutServicios sprout.toml (badges de estado) + logs en vivo del servicio seleccionado
F4 Plan & DiffF4/view planPlan activo (ws.plan.text) arriba + ledger de efectos Git (tick, tool, target, reversibilidad, (undone)) abajo
F5 TimelineF5/view timelineHitos de snapshots.onyxpack (tick, tag, tamaño, checksum) para /rewind / /fork
  • Navegación 100 % efímera: cambiar de vista no escribe en el grafo, no genera eventos de bus ni avanza ticks — es solo un "cristal" distinto sobre el mismo estado determinista.
  • F2 Agents: Up/Down selecciona (el agente enfocado lleva el marcador *), Enter enfoca la traza Memory & Trace del agente y vuelve a F1 Chat, Esc vuelve a F1 Chat.
  • F3 Sprout: Up/Down/PgUp/PgDn navegan servicios; s/x/r/a (start/stop/restart/all) y f (follow de logs) están bajo gate: en modo PLAN/EXPLORE o con workspace [UNTRUSTED] la cabecera de la vista muestra MUTATIONS BLOCKED y la acción se rechaza con un aviso.
  • F4 Plan & Diff: Up/Down desplazan el ledger de efectos Git.
  • F5 Timeline: Up/Down seleccionan hito, Enter lanza /rewind <tick>, f lanza /fork.
  • Esc: cierra popups o la paleta si están abiertos; en F1 Chat sale limpiamente; en F2..F5 vuelve a F1 Chat (la etiqueta de la tira de pestañas dice Esc:Quit o Esc:Back).
  • /view <chat|agents|sprout|plan|timeline> (case-insensitive): se intercepta en Enter a nivel de TUI — 0 eventos de bus, 0 ticks, 0 escrituras al grafo. /view sin argumento muestra el usage; un nombre desconocido muestra un aviso transitorio.
  • Paleta Ctrl+K: popup centrado (Ctrl+K Palette — type to filter) con tres grupos — VIEW (F1..F5), LLM (perfiles [[llm_profiles]], proveedores y esfuerzos) y AGENT (agente por ID/nombre). Escribe para filtrar (todos los caracteres imprimibles filtran — j/k incluidos, nunca navegan), Up/Down (o Ctrl+P/Ctrl+N) eligen, Enter ejecuta y Esc/Ctrl+K cierran. Tiene prioridad máxima (salvo Ctrl+C) y traga todas las teclas mientras está abierta; las acciones LLM se envían por el bus determinista y quedan selladas en ONYXTR2, igual que tecleadas.

6. Flujo Multi-Agente: Subagentes, Vista F2 Agents y /agent

El agente raíz puede delegar subtareas de dos formas: subagentes síncronos del grafo (spawn_agent, que comparten la workspace y a los que el padre espera) y jobs asíncronos en worktrees Git aislados (spawn_subagent / /spawn, capítulo 05).

  • Presupuesto seguro por defecto: los subagentes sincrónos heredan un techo por defecto de 32 pasos (DEFAULT_SUBAGENT_MAX_STEPS, modificable si el padre pasa max_steps explícitamente en los argumentos JSON de spawn_agent), evitando bucles infinitos en modelos locales. Mientras existen hijos activos, el padre pasa a WaitingChildren.
  • Inspección en vivo con la vista F2 Agents: pulsa F2 en cualquier momento para saltar a la vista Agents (a pantalla completa):
    • Lista todos los agentes del grafo (raíz y subagentes) con ID, nombre, rol (root/sub), estado actual y objetivo.
    • También lista los jobs asíncronos [bg] con su estado (running, done, merged, failed), rama de worktree y, si el job lo corre un harness externo, el badge → <driver>.
    • Navega con Up / Down, pulsa Enter para enfocar la traza Memory & Trace del agente (vuelve a F1 Chat) o Esc para volver a F1 Chat.
  • Atajos alternativos:
    • /agent (o /agents): abre el popup Agent Selector centrado (o rota al siguiente agente si solo existe uno).
    • /agent <id|nombre>: salta directamente a un agente concreto (por ejemplo /agent 1 o /agent researcher).
    • Ctrl+K: la paleta también lista los agentes; Enter enfoca y vuelve a F1 Chat.
    • Ctrl+Tab: rota rápidamente al siguiente agente enfocado (alias dependiente del terminal; F2, /agent y la paleta funcionan en todos los terminales).
  • Drivers externos desde la Web UI: en openonyx serve, el selector Subagent driver permite elegir un [[external_drivers]] declarado; al enviar texto libre con un driver no nativo, el navegador emite /spawn --driver <id> <texto> (capítulo 05).

7. Depurador Temporal Interactivo (TimeFreeze, SDD-07)

TimeFreeze permite pausar la sesión en cualquier tick y examinarla paso a paso sin gastar tokens ni tocar disco: las fronteras de tick viven en un anillo RAM (los hitos en disco de --snapshot-dir se superponen como referencias) y todo el estado es 100 % efímero hasta que confirmes una bifurcación (/go con el cursor anclado en el pasado crea el fork; sin confirmación no se escribe nada).

Congelar, scrubear y salir

AcciónCómo
Congelar / descongelar en el cursorCtrl+T o /time (toggle efímero)
Scrubear −1 / +1 sobre ticks disponiblesAlt+← / Alt+→ (mirar el pasado auto-congela)
Volver al presente sin cerrar la appEsc mientras TIME FROZEN (segundo Esc en vivo: sale)
Ir a un tick concreto (hitos [pack:*], [ram], (present))F5 Timeline → Down/Up → Enter

Bajo freeze aparece el banner ámbar (⏸ TIME FROZEN · tick X / present Y + archivos que se revertirían al bifurcar, solo RAM) y el prompt plano se bloquea: un turno desordenado rompería la bit-a-bit del replay. Las vías de escape (/… y !…) siguen funcionando siempre, incluso con el agente ocupado en Thinking (breakpoint pre-LLM): se ejecutan inmediatas, sin colas.

Primitivas 0-tokens y cirugía del grafo congelado

ComandoQué hace
/step [n]Avanza n ticks deterministas con 0 LLM (default 1; funciona congelado)
/step-llmUn solo turno de LLM: gate + bifurcación si aplica + recongelado al responder
/go (alias /unfreeze)Bifurca desde el cursor si mira el pasado y reanuda en el presente
! <cmd>Ejecuta un comando shell determinista en sandbox y sella el resultado (0 red, 0 disco)
/read <ruta> [a..b]Lee un archivo (o rango de líneas) a memoria, 0 tokens, frozen-safe
/inject <texto>Inyecta una memoria user sellada en la línea temporal (0 tokens)
/graph inspect [agent|mem|ws]Informe read-only del grafo congelado (memorias con mem_seq, agentes, workspace)
/graph drop-mem <seq|a..b>Elimina memorias por mem_seq sin avanzar el tiempo
/graph edit-mem <seq> <texto>Edita una memoria existente in-place
/graph set-goal <texto>Cambia el objetivo del agente raíz en el grafo congelado

Estas primitivas se sellan en ONYXTR2 (/__onyx_det_*): el replay offline las reproduce bit-a-bit con 0 I/O y 0 red. En la vista Web/PWA (openonyx serve) hay paridad completa: la pill #tick-pill abre la misma barra ámbar, POST /api/v1/time/scrub aplica scrubs efímeros, los prompts planos bajo freeze reciben 409 Conflict accionable y las memorias del agente raíz exponen botones ✎/× — ver capítulo 04.

Non-goal: los efectos de Sprout (servicios/contenedores) y de los servidores MCP son efectos externos de proceso, no mutaciones del grafo: TimeFreeze no los rebobina (ni los revierte al bifurcar).


8. Resumen de Atajos y Comandos en chat

Tecla / ComandoAcción
EnterEnvía objetivo, seguimiento al agente raíz o comando slash
TabAlterna en caliente entre [BUILD] y [PLAN]
F1..F5Cambia de vista efímera (Chat, Agents, Sprout, Plan & Diff, Timeline)
Ctrl+KAbre la paleta de comandos (vistas + slash LLM + agentes); escribe para filtrar, Enter ejecuta
Ctrl+TabRota rápidamente el agente enfocado (alias opcional de F2 / /agent)
y / nAprueba o rechaza la herramienta mutante pendiente (solo en F1 Chat; en otras vistas la TUI avisa a pulsar F1)
Up/Down/PgUp/PgDn/Home/End/Ctrl+U/Ctrl+DDesplaza el historial Memory & Trace
Alt+← / Alt+→TimeFreeze: scrub del cursor −1/+1 sobre ticks disponibles (auto-congela al mirar el pasado)
Ctrl+TTimeFreeze: toggle de freeze en el cursor / volver al presente (efímero, 0 disco)
EscCierra popup/paleta; bajo TIME FROZEN vuelve al presente sin salir; en F2..F5 vuelve a F1 Chat; en F1 Chat sale limpiamente guardando snapshot y transcripción
Ctrl+CSale limpiamente (snapshot de salida y transcripción, si están configurados)
/view <chat|agents|sprout|plan|timeline>Cambia de vista desde el prompt (efímero: 0 eventos de bus, 0 ticks, 0 grafo)
/agent [id|name]Abre el selector de agentes o enfoca el agente indicado
/mode [plan|build|explore]Cambia de modo o alterna PLAN ↔ BUILD
/undoRevierte el último checkpoint Git reversible (y limpia archivos nuevos de fs_write)
/rewind [tick]Lista hitos o retrocede en caliente a <tick> creando un fork seguro
/fork [name]Crea una rama de snapshots hasta el tick actual en un directorio hermano
/timeTimeFreeze: alterna el freeze en el cursor actual (efímero, 0 disco)
/go (alias /unfreeze)TimeFreeze: bifurca si el cursor mira el pasado y reanuda en el presente
/step [n]TimeFreeze: n ticks deterministas con 0 LLM (default 1; frozen-safe)
/step-llmTimeFreeze: exactamente un turno de LLM (gate + bifurcación + recongelado)
! <cmd>Shell determinista en sandbox con resultado sellado en ONYXTR2 (frozen-safe)
/read <ruta> [a..b]Lee un archivo (o rango) a memoria, 0 tokens (frozen-safe)
/inject <texto>Memoria user sellada en la línea temporal, 0 tokens (frozen-safe)
/graph <inspect|drop-mem|edit-mem|set-goal>Inspección read-only o cirugía del grafo congelado (memorias por mem_seq, objetivo) sin avanzar el tiempo
/compact [focus]Compacta turnos anteriores rescatando archivos y coincidencias del foco
/servicesMuestra estado @TOON v1 de servicios definidos en sprout.toml
/service <start|stop|logs> <id|all> [tail]Controla servicios Sprout directamente desde la TUI
/new [goal]Prepara o lanza un agente raíz limpio
/profile [id], /provider <gemini|openai>, /model <name>, /effort <auto|low|medium|high>Cambian el objetivo LLM en caliente (sección 2.1)
/spawn [--driver <id>] <goal>Lanza un job asíncrono en worktree Git aislado (capítulo 05)
/subagentsLista los jobs asíncronos [bg] (estado, rama, archivos tocados)
/merge <job_id>Fusión 3-way del worktree del job (governance Ask/Deny, capítulo 03)
/discard <job_id>Cancela el job y elimina su worktree y rama temporal

← 01. Primeros Pasos · Índice · Siguiente: 03. Modos, Permisos y Sandbox OS →

03. Modos de Trabajo, Permisos y Sandbox OS

🇬🇧 Read this chapter in English

openonyx aplica defensa en profundidad sobre todo lo que hace el agente: modos de workspace, reglas declarativas .onyx/config.toml, protección del Control Plane, sanitización de entorno (env_clear()), aislamiento a nivel de sistema operativo y supervisión RAII de procesos.


1. Modos de Workspace: PLAN, BUILD y EXPLORE

El modo activo (ws.mode) se almacena dentro del grafo EAV y se graba en las transcripciones ONYXTR2, de modo que rewind y replay lo restauran exactamente.

ModoLectura / Búsqueda / ASTMutaciones (fs_write, fs_edit, shell_exec, service_start/stop/exec)Uso recomendado
BUILD (default)PermitidoPermitido con aprobación (o según reglas .onyx/config.toml). fs_edit exige lectura previa del archivo con fs_read.Implementación, refactorización, ejecución de tests.
PLANPermitidoBloqueado incondicionalmente (incluso con allow en config.toml o --auto-approve).Análisis de arquitectura, diseño de planes, revisión de PRs.
EXPLOREPermitidoBloqueado incondicionalmente.Exploración rápida de solo lectura en repositorios desconocidos.

Tools MCP dinámicas: aunque un tool mcp__<server>__<tool> no mutee el filesystem local, un servidor MCP remoto puede ejecutar procesos o red fuera del control de openonyx; por eso se trata igual que una mutación y queda Deny en PLAN/EXPLORE (capítulo 03, sección 2.8).

Cómo cambiar de modo en chat

  • Pulsa Tab para alternar en caliente entre [BUILD] y [PLAN].
  • O usa el comando slash explícito: /mode plan, /mode build, /mode explore (o /mode sin argumentos para alternar PLAN ↔ BUILD).

2. Permisos Declarativos (.onyx/config.toml)

Puedes definir reglas granulares en dos ubicaciones que se cargan y fusionan automáticamente:

  1. Global de usuario: ~/.onyx/config.toml
  2. Por proyecto: <workspace>/.onyx/config.toml

Regla de seguridad: un proyecto nunca puede eliminar una regla deny definida en tu ~/.onyx/config.toml global.

Precedencia: deny > ask > allow

  • deny: bloquea la herramienta de forma incondicional, incluso si ejecutas openonyx con --auto-approve. Solo puede omitirse pasando explícitamente --ignore-deny.
  • ask: fuerza confirmación interactiva (y/n), prevaleciendo sobre allow a igual o mayor especificidad.
  • allow: auto-aprueba una herramienta/patrón específico sin interrumpirte (siempre que estés en modo BUILD; en PLAN/EXPLORE las mutaciones siguen bloqueadas). Un allow más específico (p. ej. shell_exec(cargo test*)) vence a un comodín genérico ask (shell_exec(*)).

Ejemplo completo de .onyx/config.toml

[permissions]
# Bloqueos absolutos (ni siquiera --auto-approve los salta)
deny = [
  "shell_exec(rm -rf*)",
  "shell_exec(git push*)",
  "shell_exec(curl*)",
  "fs_write(.env*)",
]

# Auto-aprobar comandos de verificación seguros en modo BUILD
allow = [
  "shell_exec(cargo check*)",
  "shell_exec(cargo test*)",
  "shell_exec(cargo clippy*)",
  "shell_exec(cargo fmt --all -- --check)",
]

# Requerir confirmación explícita para cualquier otro shell_exec o escritura
ask = [
  "shell_exec(*)",
  "fs_write(*)",
  "fs_edit(*)",
]

[sandbox]
# "workspace-write" (default) | "strict-container" | "off"
mode = "workspace-write"
# "offline" (default) | "localhost" | "unrestricted"
network = "offline"
# Variables extra permitidas tras env_clear() (nunca pases API keys)
env_passthrough = ["RUST_LOG", "RUST_BACKTRACE"]
# Rutas adicionales de solo lectura fuera del workspace (opcional)
allow_read_paths = []
# Límites de recursos para subprocesos
max_memory_mb = 4096
max_pids = 128
# Imagen OCI cuando mode = "strict-container" (opcional)
# container_image = "rust:1.85-slim"

[impact]
# Scent-Heated Approval: escala Allow -> Ask si un diff toca símbolos públicos con callers
enabled = true
max_hops = 2          # acotado 1..=4
ask_heat_bp = 2500    # umbral para símbolos pub scope:src (basis points 0..=10000)
hard_ask_bp = 8000    # umbral duro para cualquier símbolo con alto fan-out

[verify]
# Verify-on-Edit: tras cada fs_edit/fs_write exitoso ejecuta las reglas cuya glob
# empareja el archivo editado (sección 2.9). Desactivado por defecto.
on_edit = true
max_secs = 20         # timeout por defecto por regla (acotado 1..=120)

[[verify.rules]]
glob = "**/*.rs"
command = "cargo test --workspace"
# max_secs = 60       # timeout propio de la regla (opcional)

Monotonía de Scent-Heated Approval: [impact] solo puede subir una decisión Allow → Ask y mostrar la línea # impact: N callers, H hops, scope:src(pub) [heat Xbp] sobre el diff en TUI/CLI. Nunca anula un deny, nunca baja un ask a allow, y degrada limpiamente a política estática si el archivo no está indexado o enabled = false.


2.5. Workspace Trust (~/.onyx/trusted_workspaces.toml)

Para proteger frente a repositorios clonados o PRs externos con configuraciones maliciosas (Indirect Prompt Injection + allow = ["shell_exec(*)"] o sprout.toml arbitrario), openOnyx fija los hashes blake3 de .onyx/config.toml y sprout.toml por workspace en ~/.onyx/trusted_workspaces.toml:

  • Repositorio limpio (sin .onyx/config.toml ni sprout.toml): sin fricción (no-project-config).
  • Repositorio no confiado o modificado (untrusted / modified, badge [UNTRUSTED] en TUI):
    • .onyx/config.toml del proyecto solo puede restringir (deny/ask, sandbox/impact más estrictos); se ignoran sus reglas allow, env_passthrough, allow_read_paths, container_image y cualquier relajación de [sandbox]/[impact].
    • sprout.toml bloquea la ejecución de servicios (service_start, service_exec, stop_cmd) hasta aprobación explícita.
  • Comandos de confianza: openonyx trust (aprueba el workspace actual), openonyx trust check, openonyx trust list, openonyx trust revoke, flag de sesión --trust-workspace o /trust [status|revoke] en la TUI.

2.6. Perfiles LLM ([[llm_profiles]])

El objetivo LLM (proveedor, modelo, api_base, esfuerzo) puede declararse en .onyx/config.toml como bloques [[llm_profiles]] y conmutarse en caliente con /profile / /provider / /model / /effort (capítulo 02, sección 2.1):

[[llm_profiles]]
id = "local-ollama"
provider = "openai"
model = "llama3.1:70b"
effort = "medium"
api_base = "http://localhost:11434/v1"
# api_key_env = "OLLAMA_API_KEY"
  • Campos: id (único), provider (gemini | openai | anthropic), model, effort (auto | low | medium | high), api_base opcional y api_key_env opcional. Claves desconocidas o duplicadas son error de parse accionable.
  • Nunca claves literales: un api_key literal en el bloque es rechazado por el parser con un error que indica usar api_key_env (y el mensaje no repite el valor de la clave). Las credenciales siempre se resuelven de variables de entorno (api_key_env → variable estándar del proveedor → ONYX_API_KEY).
  • api_base validado al registro: con la misma política que --api-base (http:// solo en loopback; hosts remotos exigen https://; hosts no oficiales requieren --allow-custom-auth-host).
  • Gate de Trust: un workspace no confiado ignora sus bloques [[llm_profiles]] y muestra la advertencia ignored N [[llm_profiles]] block(s); run openonyx trust or /trust to approve. Con workspace confiado, la precedencia es global (~/.onyx/config.toml) < proyecto (fusion replace-by-id).
  • Disponibilidad: un perfil sin clave resuelta o con api_base rechazada se lista como unavailable con motivo accionable (/profile, paleta Ctrl+K y selector Web). La TUI y la Web solo exponen metadatos (public_snapshot): proveedor, modelo, esfuerzo y motivo — nunca claves.

2.7. Harnesses CLI externos ([[external_drivers]])

Los jobs asíncronos spawn_subagent / /spawn (capítulo 05) pueden ejecutarse fuera del motor OnYX, delegando el trabajo a un harness CLI externo declarado en .onyx/config.toml:

[[external_drivers]]
id = "opencode"
bin = "opencode"
args = ["run", "--model", "qwen38-27b"]
# prompt_transport = "stdin"        # "stdin" (default) | "arg" | "temp_file"
# prompt_flag = "--prompt-file"     # para "temp_file" (o placeholder {prompt_file} en args)
timeout_secs = 600
allowed_env = []
# inherit_home = true               # si el CLI necesita config/OAuth del HOME real
# network_allowlist = ["api.ejemplo.com"]
  • Campos: id (charset [a-z0-9_-]), bin (resuelto en PATH/PATHEXT), args (argumentos fijos), prompt_transport (stdin recomendado y default; arg rechazado en Windows si el binario resuelve a un wrapper .cmd/.bat; temp_file para prompts grandes, fuera del índice Git), prompt_flag, timeout_secs, allowed_env (whitelist de variables para el hijo) e inherit_home (default false).
  • Gate de Trust: un workspace no confiado no puede lanzar drivers externos (Deny absoluto: requires a trusted workspace).
  • Aprobación por defecto Ask: spawn_subagent con driver externo nunca auto-aproba: sin reglas ask/allow explícitas la decisión es Ask; puedes fijarla con allow = ["spawn_subagent(opencode)"] o ask/deny con el mismo patrón (un deny spawn_subagent(opencode) bloquea ese driver aunque haya allow).
  • Aislamiento del proceso: el prompt se entrega sin inyección de shell (stdin/argv único/archivo temporal); el entorno del hijo pasa por env_clear() + allowed_env; el proceso queda asignado a un ProcessJob desde el spawn (si timeout_secs vence o se cancela el job, muere el árbol entero; en Windows hay fallback taskkill /F /T /PID); y el log completo se sella en .onyx/vault/subagent-logs/<job_id>.log pasando por scrub_secrets.
  • Red declarativa (network_allowlist): es una gobernanza declarativa: con --sandbox strict-container se enforce en el contenedor; en los demás perfiles es advisory (el doctor lo avisa). Un allowlist vacío equivale a LocalhostOnly; con allowlist, el sandbox no inyecta variables *_OFFLINE (el harness necesita llegar a su API).
  • Merge forzadamente Ask: aunque tus permisos auto-aprobieran, subagent_merge de un job con driver externo exige aprobación explícita (ExternalDriverApprovalPolicy).

2.8. Servidores MCP ([mcp.servers.<name>])

openonyx puede conectar servidores Model Context Protocol (MCP) declarados en config.toml (global ~/.onyx/config.toml y, con workspace confiado, <workspace>/.onyx/config.toml):

[mcp.servers.github]
transport = "stdio"
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
# env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" }   # referencias ${VAR} al lanzar el proceso
timeout_secs = 20            # default 20
# enabled = true             # default true

[mcp.servers.docs]
transport = "http"
url = "https://mcp.ejemplo.com/sse"
# headers = { Authorization = "Bearer ${MCP_DOCS_TOKEN}" }
  • Campos: transport ("stdio" con command/args/env, o "http" con url/headers), timeout_secs (default 20 s por llamada JSON-RPC) y enabled (default true). Los nombres de servidor no pueden contener __ (reservado para el prefijo mcp__<server>__<tool>). Las referencias ${ENV_VAR} se expanden solo al lanzar la request/proceso (nunca se loguean ni persisten) y Authorization/X-Api-Key en headers exigen ${VAR}.
  • Fusión y gate de Trust: fusión replace-by-name con precedencia global < workspace; un workspace no confiado ignora sus [mcp.servers.*] con la advertencia MCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust), mientras que la configuración global siempre aplica.
  • Naming y aprobación: cada tool descubierta (tools/list) se expone al LLM como mcp__<server>__<tool> con requires_approval = true: siempre pide aprobación interactiva en BUILD, salvo que una regla allow más específica diga lo contrario (p. ej. allow = ["mcp__github__search_repos"] o allow = ["mcp__github__*"]); ask/deny con glob también funcionan (deny = ["mcp__*"] bloquea todo MCP).
  • PLAN/EXPLORE = Deny: en esos modos cualquier mcp__* queda bloqueado incondicionalmente (un servidor remoto ejecuta procesos/red fuera del sandbox).
  • Aislamiento de fallos: un servidor caído no aborta la sesión: se reporta [openOnyx mcp] server \` unavailable: ...y el resto de la sesión sigue; cada servidor expone su estado paraopenonyx doctor`.
  • Seguridad de la sesión stdio: JSON-RPC 2.0 con hilo lector dedicado, timeout real por llamada (mpsc::recv_timeout), línea de stdout acotada a 4 MiB y limpieza del árbol de procesos con ProcessJob al fallar (Windows y Unix).
  • Salidas saneadas: los resultados de tools/call y los errores de descubrimiento pasan por truncate_utf8 + scrub_secrets antes de llegar al LLM o a la transcripción.
  • openonyx doctor: audita cada servidor declarado con un handshake acotado a 5 s (min(timeout_secs, 5)): Connected/Disabled → [CHECK], fallo → [ERR] accionable (mensaje ya scrubbeado), workspace no confiado → [WARN] sin descubrimiento de workspace.
  • replay 0-I/O: al reproducir una transcripción ONYXTR2 no se contacta con ningún servidor: los tools mcp__* se reconstruyen desde la propia transcripción (extract_mcp_tools_from_transcript), sin load_mcp_registry.

2.9. Verify-on-Edit ([verify] / [[verify.rules]])

El Verify-on-Edit cierra el bucle edit → verificar dentro del turno del agente: tras cada fs_edit/fs_write exitoso, openonyx ejecuta los comandos cuyas reglas emparejan el archivo editado e inyecta el resultado al final de la observación del tool, para que el modelo corrija el error antes de terminar el turno.

[verify]
on_edit = true        # default false: opt-in explícito, 0 overhead sin configurar
max_secs = 20         # timeout por defecto por regla (acotado 1..=120)

[[verify.rules]]
glob = "**/*.rs"      # glob de ruta relativa (compile_glob_regex)
command = "cargo test --workspace"
# max_secs = 60       # timeout propio de la regla (opcional)

[[verify.rules]]
glob = "src/**"
command = "pnpm test"
  • Alcance de cada regla: la regla se dispara si la glob empareja el archivo editado o (cuando hay índice Scent) un archivo scope:test alcanzable por impacto AST en ≤ 2 hops; si el workspace no está indexado, solo empareja la ruta editada.
  • Ejecución: cada command pasa por la misma tubería de sandbox de shell_exec (prepare_sandboxed_shell_command + configure_process_isolation + ProcessJob RAII + env_clear() + cancelación por timeout + scrub_secrets), con diagnóstico capturado acotado a 4 KiB.
  • Salidas inyectadas en la observación del tool:
    • \n[verify: PASS] <N> rule(s) succeeded (<cmds>) — más impacted_tests: [...] cuando el índice Scent identifica tests scope:test alcanzables;
    • \n[verify: FAIL] <cmd> (exit <code> | timed out after <N>s)\n<diagnóstico>\n(Fix the error before finishing the turn.);
    • \n[verify: BLOCKED] <cmd> (denied by [permissions]) — la regla no se ejecuta.
  • Gobernanza [permissions].deny: cada command se evalúa como shell_exec antes de ejecutarse; un deny bloquea la regla ([verify: BLOCKED]) y detiene el bucle de verificación de esa edición.
  • Workspace Trust Gate: la fusión es global (~/.onyx/config.toml) < workspace (<workspace>/.onyx/config.toml, confiado); un workspace no confiado ignora por completo sus [verify]/[[verify.rules]] (con advertencia accionable en policy.trust_warnings), mientras que la configuración global sí aplica. Las reglas de workspace reemplazan al conjunto global cuando el workspace está confiado.

3. Protección Read-Only del Control Plane

Incluso en modo BUILD y con --auto-approve, onyx-workspace protege como solo lectura los archivos críticos del plano de control del agente y del repositorio:

  • .onyx/config.toml (evita que un agente se auto-conceda permisos o desactive el sandbox).
  • .onyx/vault/** (evita que un agente borre o corrompa los snapshots y transcripciones de la bóveda de sesiones).
  • .git/hooks/** y .git/config (evita inyección de código al ejecutar comandos Git).
  • .env y .env.* (evita exfiltración o corrupción de secretos locales).

Esta protección se aplica tanto en fs_write / fs_edit como en inspecciones de escritura sobre shell_exec.

Gobernanza del delta de subagent_merge (3-way merge)

Cuando un job asíncrono (spawn_subagent / /spawn) se fusiona con subagent_merge / /merge, el delta <root>..<merged_tree> se clasifica antes de tocar disco:

  • Deny — Control Plane: si el delta toca .onyx/config.toml, .onyx/vault/**, .git/hooks/**, .git/config o .env*, el merge se bloquea entero (un solo archivo bloquea todo el delta; nunca se aplica parcialmente).
  • Ask — superficies de gobernanza: si el delta toca sprout.toml o .github/workflows/**, la aprobación del merge debe ser explícita (nunca auto-aprobada), aunque tus reglas allow cubran otras herramientas.
  • Safe: el resto del delta sigue la aprobación estándar por impacto (Scent-Heated Approval).

La fusión es 3-way con git merge-tree sin mover HEAD ni el índice del workspace; el veredicto se aplica sobre el delta completo.


4. Sandbox OS, env_clear() y ProcessJob RAII

Toda ejecución de shell_exec (y los procesos locales de Sprout) pasa por la infraestructura compartida de onyx-workspace/src/sandbox.rs.

Perfiles de sandbox (--sandbox)

ModoBadge TUIComportamiento
workspace-write (default)[SANDBOX:workspace] (Linux bwrap / macOS sandbox-exec), [SANDBOX:env+job] (Windows) o [SANDBOX:env+pgid]env_clear(), aislamiento nativo de escritura (en Linux/macOS), Win32 Job Objects / PGID, límites de memoria/PIDs y red offline por defecto. En Windows, usa strict-container para aislamiento fuerte de FS/red.
strict-container[SANDBOX:strict]Ejecuta el comando dentro de un contenedor OCI (docker, nerdctl o podman) montando el workspace. Ideal para automatización desatendida.
off[SANDBOX:off]Desactiva el wrapper de sandbox OS (siguen activos WorkspacePolicy, timeout, limpieza de procesos y Control Plane RO).

Política de red (--sandbox-net)

PolíticaComportamiento
offline (default)Bloquea tráfico de red saliente y comandos de red antes de lanzar el proceso, e inyecta variables offline (CARGO_NET_OFFLINE, PIP_NO_INDEX, NPM_CONFIG_OFFLINE).
localhostPermite tráfico local (127.0.0.1 / localhost), útil para probar APIs o bases de datos levantadas con sprout.toml.
unrestrictedSin restricción de red saliente (úsalo solo cuando necesites descargar dependencias).

Elevación automática con --auto-approve

Si pasas --auto-approve y tu configuración tenía mode = "off", openonyx eleva automáticamente el sandbox a workspace-write + offline para reducir el radio de impacto, salvo que pases explícitamente --sandbox off en la línea de comandos.

Sanitización de entorno (env_clear())

Antes de arrancar un subproceso:

  1. Se limpia el entorno con env_clear() y se reconstruye solo una lista segura de variables esenciales del sistema (PATH limpio, HOME/USERPROFILE, toolchains estándar).
  2. Se eliminan todas las variables sensibles (*_API_KEY, *_TOKEN, AWS_*, etc.), evitando que un comando en shell_exec pueda leer tu GEMINI_API_KEY o OPENAI_API_KEY.
  3. TMP/TEMP/TMPDIR se redirigen a un directorio temporal propio de la sesión.
  4. Además, toda la salida capturada pasa por scrub_secrets antes de volver al modelo o grabarse en transcripciones.

Comportamiento por sistema operativo y ProcessJob RAII

  • Windows (win32-job): cada comando se envuelve en un Win32 Job Object con JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE y límites de memoria/PIDs. Si vence --shell-timeout o cierras openonyx, el árbol entero de procesos hijos muere al instante sin dejar huérfanos.
  • Linux (bwrap / landlock + PGID): usa Bubblewrap (bwrap) cuando está disponible y pasa una sonda real en vivo (bwrap_is_usable()). En distribuciones como Ubuntu 24.04 donde AppArmor bloquea unprivileged user namespaces, openonyx detecta el bloqueo automáticamente y aplica fallback seguro sin romper shell_exec, manteniendo env_clear(), control offline, Control Plane RO y limpieza de grupos de procesos POSIX (PGID).
  • macOS (sandbox-exec + PGID): utiliza perfiles sandbox-exec junto con env_clear() y limpieza por grupo de procesos POSIX.

Para comprobar qué driver nativo y qué runtime de contenedores (docker/nerdctl/podman) detecta tu máquina, ejecuta:

openonyx doctor

← 02. Interfaz TUI y Flujo Diario · Índice · Siguiente: 04. Time-Travel, Snapshots y Forking →

04. Time-Travel, Snapshots y Forking

🇬🇧 Read this chapter in English

Una de las capacidades diferenciales de openonyx es que el estado completo del agente vive en un grafo EAV determinista que puede guardarse, inspeccionarse, reproducirse sin red, revertirse en disco y bifurcarse sin destruir la rama original.


1. Bóveda de Sesiones (.onyx/vault/) y --auto-save

Para evitar ensuciar la raíz del repositorio con directorios .snaps_*, forks y archivos .tr, openonyx centraliza las sesiones en <workspace>/.onyx/vault/:

<workspace>/.onyx/vault/
├── .gitignore                                  # creado automáticamente con `*`
├── 20261121-103500_qwen3-coder_main/           # generado por --auto-save
│   ├── snapshots.onyxpack
│   └── 20261121-103500_qwen3-coder_main.tr
├── 20261121-103500_qwen3-coder_main.fork-t12/  # rama creada por /fork o /rewind
├── feat-auth/                                  # --snapshot-dir feat-auth --record chat.tr
│   ├── snapshots.onyxpack
│   └── chat.tr
└── unassigned/                                 # solo --record suelta.tr (sin snapshot-dir)
    └── suelta.tr

Reglas de resolución

  • --auto-save (o ONYX_AUTO_SAVE=1): crea automáticamente <workspace>/.onyx/vault/<YYYYMMDD-HHMMSS>_<modelo>[_<rama|goal>]/ con snapshots.onyxpack y <id>.tr juntos, muestra vault:<id> en la cabecera de la TUI y al salir imprime el comando exacto openonyx chat --resume <id>.
  • Nombres cortos sin separador de ruta (/ o \):
    • --snapshot-dir feat-auth → .onyx/vault/feat-auth/
    • --snapshot-dir feat-auth --record chat.tr → el .tr se guarda dentro de .onyx/vault/feat-auth/chat.tr.
    • --record solo.tr (sin --snapshot-dir) → se guarda en .onyx/vault/unassigned/solo.tr.
  • Rutas explícitas intactas: cualquier ruta absoluta o con separador (./mi-dir, C:\tmp\snaps, ../otro) se respeta tal cual.
  • Búsqueda transparente al leer: --resume, inspect, rewind, replay y doctor buscan primero la ruta literal en disco y, si es un nombre corto, la localizan automáticamente dentro de .onyx/vault/ (y .onyx/vault/unassigned/ para .tr).
  • Aislamiento total de Git y herramientas: openonyx crea .onyx/vault/.gitignore (*) automáticamente para que git status y los checkpoints /undo nunca absorban el vault, mientras WorkspacePolicy oculta .onyx/vault/ de fs_list/glob_files/code_search y lo protege como Control Plane de solo lectura.

2. Cómo funcionan snapshots.onyxpack y los hitos

Al pasar --snapshot-dir <dir> en chat, run o replay, MilestoneSnapshotSystem captura snapshots solo en transiciones relevantes en lugar de desperdiciar disco en ticks inactivos:

  • init — estado inicial de la sesión.
  • spawn — creación de agente raíz o subagente.
  • approval:<tool> — solicitud de aprobación de herramienta mutante.
  • tool:<tool> / tool_error:<tool> — resultado o fallo de herramienta.
  • cmd:/agent, cmd:/undo, cmd:/rewind, cmd:/fork, cmd:/compact, cmd:/mode ..., cmd:/new — comandos slash ejecutados.
  • settled, failed, exit — cierre de turno o salida limpia.
  • periodic — hitos periódicos opcionales si indicas --snapshot-every <n>.

Todos los hitos se almacenan en un único contenedor append-only comprimido <dir>/snapshots.onyxpack (ONYXPK1 con compresión zlib, payload canónico ONYXAG\x01\0 y checksum FNV-1a de 64 bits):

  • Tolerancia a cortes: si un crash deja un frame truncado al final del archivo, PackSnapshotStore ignora de forma segura la cola dañada al leer y la repara automáticamente en el siguiente append.
  • Compatibilidad legacy: los directorios antiguos con tick-*.bin siguen siendo legibles automáticamente en inspect, rewind y --resume.
  • Retención opcional: por defecto se conserva todo el historial para poder hacer time-travel a cualquier punto; puedes activar una ventana deslizante con --max-snapshots <n> (conserva init + últimos n - 1 hitos).

3. Inspeccionar una sesión (openonyx inspect)

Sin API key y sin tocar el workspace, puedes auditar cualquier directorio de snapshots:

# Listar todos los hitos: tick, etiqueta, tamaño comprimido/raw, FNV-1a y tree_sha Git
openonyx inspect .snaps_feat --list

# Salida en JSON para automatización o depuración
openonyx inspect .snaps_feat --list --json

# Inspeccionar el último hito o un tick concreto
openonyx inspect .snaps_feat
openonyx inspect .snaps_feat --tick 24
openonyx inspect .snaps_feat --tick 24 --json

4. Deshacer cambios paso a paso (/undo)

Cada vez que fs_write o fs_edit va a modificar el disco en modo BUILD, WorkspaceToolBridge captura automáticamente un checkpoint de árbol Git ligero usando un GIT_INDEX_FILE temporal (git add -A + git write-tree):

  • Nunca toca HEAD ni tus commits.
  • Nunca altera tu staging area (git add).
  • Funciona incluso en repositorios recién inicializados sin primer commit (unborn HEAD).

Cuando escribes /undo dentro de openonyx chat:

  1. Se marca en el grafo el último efecto reversible como deshecho (ws.effect.undone).
  2. Se restaura en disco el tree_sha exacto anterior a esa edición (restore_git_tree_checkpoint_for_targets).
  3. Limpieza segura de archivos nuevos: si la acción deshecha fue un fs_write que creó un archivo nuevo no rastreado por Git, /undo lo elimina limpiamente sin borrar ningún otro archivo untracked tuyo.
  4. Se invalidan automáticamente las cachés de sesión (fs_read y scent_outline) para que el agente vuelva a leer el contenido real del disco.

5. Bifurcar y viajar en el tiempo en vivo (dentro de la TUI)

Si iniciaste chat con --snapshot-dir <dir> (o --resume <dir>), puedes explorar alternativas sin cerrar la TUI y sin sobrescribir el historial original:

/fork [nombre] — Bifurcar desde el tick actual

/fork experimento-parser
# o sin nombre (crea <dir>.fork-t<tick>):
/fork
  • Copia todos los hitos hasta el tick actual a un directorio hermano (<dir>.fork-experimento-parser o <dir>.fork-t42).
  • Cambia en caliente el store activo (SharedPackStore) a la nueva rama.
  • El snapshots.onyxpack original queda 100% intacto.

/rewind [tick] — Retroceder en caliente dentro de la TUI

# 1. Ver lista de hitos disponibles con tick, etiqueta y checkpoint Git
/rewind

# 2. Retroceder al tick 18 (o al hito previo más cercano <= 18)
/rewind 18
  • Guardia de seguridad: si hay un agente trabajando o una petición LLM en vuelo, /rewind rechaza ejecutarse hasta que la sesión esté en reposo para evitar estados corruptos.
  • No destructivo por defecto: crea automáticamente un directorio fork hermano (<dir>.fork-t18), restaura el grafo al tick objetivo, reconcilia los efectos huérfanos en disco (restaurando checkpoints Git y limpiando archivos fs_write posteriores al tick) e informa del resumen directamente en Memory & Trace.

6. Time-Travel y Forking desde la CLI

También puedes retomar, bifurcar o auditar desde la línea de comandos:

Reanudar en el último hito

openonyx chat --resume .snaps_feat

Reanudar desde un tick histórico creando un fork seguro

# Crea .snaps_feat.fork-t12 y abre la TUI en el tick 12 (original intacto)
openonyx chat --resume .snaps_feat --tick 12

# Especificando ruta exacta del fork:
openonyx chat --resume .snaps_feat --tick 12 --fork-dir .snaps_ruta_b

# Atajo equivalente desde el subcomando rewind:
openonyx rewind .snaps_feat 12 --interactive
openonyx rewind .snaps_feat 12 --tui --fork-dir .snaps_ruta_b

Modo destructivo opt-in (--truncate-future)

Si deliberadamente quieres recortar el snapshots.onyxpack original descartando los ticks posteriores a <tick> en lugar de crear un fork hermano, pasa --truncate-future:

openonyx chat --resume .snaps_feat --tick 12 --truncate-future

Rewind headless con previsualización (--dry-run) y replay

# 1. Previsualizar qué efectos huérfanos y checkpoints Git se revertirían (0 cambios en disco)
openonyx rewind .snaps_feat 12 --dry-run

# 2. Retroceder y reproducir determinísticamente desde una transcripción (0 llamadas HTTP)
openonyx rewind .snaps_feat 12 --transcript feat.tr

7. Transcripciones y Replay 100% Offline (ONYXTR2)

Grabando una sesión con --record <archivo.tr> (alias --save-transcript <archivo.tr>), RecordingBridge registra todas las decisiones del LLM, llamadas estructuradas (call_id), comandos slash (Tab, /mode, /undo, /compact, etc.) y metadatos de checkpoints ([checkpoint:<head>:<tree>]). Las primitivas 0-tokens del depurador temporal se sellan en la transcripción como /__onyx_det_* (shell !cmd, /read, /inject, /step, /step-llm y la cirugía /graph): el replay las reproduce bit-a-bit con 0 I/O y 0 red (no se re-ejecuta ningún comando).

# Grabar una sesión
openonyx chat --snapshot-dir .snaps_demo --record demo.tr

# Reproducirla después sin red, sin API key y sin modificar archivos en disco
openonyx replay demo.tr --snapshot-dir .snaps_replay

Esto resulta invaluable para:

  • Depuración determinista: reproducir un fallo exacto del harness o de un prompt sin volver a pagar tokens.
  • Auditoría: verificar qué decisiones tomó el agente en una corrida pasada.
  • Regresión: reconstruir el grafo completo desde una transcripción y compararlo con inspect --json.

8. Auditoría de Salud (openonyx doctor)

Tras un corte de energía, un error de red o antes de un rewind delicado, ejecuta:

openonyx doctor --snapshot-dir .snaps_feat --transcript feat.tr

doctor comprueba en un solo paso:

  1. Estado del repositorio Git y posibles artefactos residuales.
  2. Integridad de snapshots.onyxpack (cabecera ONYXPK1, checksums FNV-1a, payloads ONYXAG, detección de colas truncadas) y snapshots legacy tick-*.bin.
  3. Validez de objetos tree_sha referenciados por el ledger de efectos.
  4. Cabecera y legibilidad de la transcripción (ONYXTR1 / ONYXTR2).
  5. Capacidades de sandbox OS del sistema anfitrión (bwrap/sandbox-exec/win32-job, runtime OCI).
  6. Validación del DAG y puertos ocupados de sprout.toml (si existe en el workspace).

9. Paridad Web: el Time Debugger en openonyx serve

La PWA embebida tiene paridad completa con el depurador temporal de la TUI (SDD-07 Fase 4A): el mismo estado de sesión alimenta ambas superficies, por lo que lo que haces desde el navegador afecta a la sesión en vivo y viceversa.

  • Pill de tick: la cabecera muestra #tick-pill (botonera aria). En vivo dice tick N; bajo freeze o con el cursor anclado en el pasado dice ⏸ X/Y y abre la barra ámbar de Time Debugger automáticamente (puedes cerrarla; se vuelve a abrir sola al congelar).
  • Barra ámbar: estado (⏸ TIME FROZEN · tick X / present Y / LIVE · tick Y), slider que snapea al tick disponible más cercano (rechaza ticks purgados o futuros con aviso accionable), botones ◀/▶, Freeze/Present, Step, Step 1 LLM y Resume — estos tres últimos van por el túnel de comandos sellado (/step 1, /step-llm, /go), no por la API de scrub: la bifurcación se aplica en la sesión con sus gates.
  • API efímera: POST /api/v1/time/scrub (JSON: action: freeze|unfreeze|return_to_present|scrub_to|scrub_delta) muta solo el estado RAM del depurador — 0 disco, 0 eventos en el bus — y responde con el snapshot time_debug actualizado. Hereda la autenticación Bearer y el guard CSRF de todo /api/v1/* (401 sin credenciales, 403 cross-site, 400 accionable para tick futuro o acción desconocida).
  • Prompts planos bajo freeze: POST /api/v1/command responde 409 Conflict con mensaje accionable (Paused in TIME FROZEN: use /go to resume or /inject to stage memory…); /go, /graph …, /inject …, /read …, /step …, /step-llm, /time y !cmd siguen aceptándose.
  • Cirugía de memorias en la UI: con el agente raíz congelado, cada memoria del root muestra ✎ (editar en un diálogo → /graph edit-mem <seq> <texto> plano) y × (eliminar con confirmación → /graph drop-mem <seq>).
  • Preview de proyección y aviso de revert: el snapshot Web incluye time_debug completo (frozen, cursor_tick, present_tick, available_ticks, pending_revert_files desde los efectos del grafo vivo, 0 I/O) y, con --snapshot-dir + objetivo LLM real, el bench_hint: un comando openonyx bench --snapshot-dir … --tick … --models provider:model copiable para comparar el modelo vivo contra un benchmark determinista desde el mismo cursor (sinergia SDD-05 §9.4).

Non-goal: los efectos de Sprout y de los servidores MCP son efectos externos de proceso: el TimeFreeze (TUI o Web) no los rebobina.


← 03. Modos, Permisos y Sandbox OS · Índice · Siguiente: 05. Herramientas, Scent, Sprout y Skills →

05. Herramientas del Agente, Scent, Sprout, Skills y Automatización

🇬🇧 Read this chapter in English

Este capítulo recoge el catálogo completo de las 24 herramientas disponibles para el agente dentro de openonyx (19 base + spawn_agent + 4 asíncronas de subagentes en worktrees Git aislados), cómo aprovechar la navegación AST multilenguaje (onyx-scent 2.0), cómo orquestar procesos y contenedores locales con sprout.toml, cómo personalizar el comportamiento mediante ONYX.md / skills y cómo ejecutar tareas en modo headless (openonyx run) o en benchmark multi-modelo (openonyx bench).


1. Catálogo Completo de las 23 Herramientas

Herramientas de solo lectura y coordinación (sin aprobación)

HerramientaPropósitoNotas clave
fs_readLeer archivos UTF-8 (enteros o por rango 1-based start_line/end_line).Límite 64 KiB. Deduplica lecturas repetidas (unchanged_since_tick) y rangos solapados ya cubiertos (covered_by:start-end). Detecta y da aviso accionable ante artefactos binarios de OnYX (ONYXTR1/2, ONYXPK1, ONYXAG).
fs_listListar árbol de directorio hasta max_depth (default 3).Omite symlinks fuera de raíz, .git, target, node_modules, *.tr, *.onyxpack.
glob_filesLocalizar rutas por patrón glob (*, **, ?, [...], {a,b}).Orden lexicográfico determinista (o sort_by_mtime). Rechaza path traversal.
code_searchBúsqueda de texto literal o regex en el workspace.Soporta case_insensitive, include_glob, exclude_glob y context_lines (0..=5) con scrub_secrets.
scent_outlineMapa AST paginado (@TOON v1) de símbolos, visibilidad y rangos de líneas.Soporta Rust, Python, Java, TypeScript (.ts/.tsx/.mts/.cts), JavaScript (.js/.jsx/.mjs/.cjs), Go y C/C++ (.c/.h/.cc/.cpp/.cxx/.hh/.hpp); caché incremental blake3 + caché binaria persistente .onyx/scent.idx + caché de sesión seen_outlines invalidada automáticamente tras ediciones/shell//undo; filtros public_only, exclude_tests, cursor, max_rows (1..=500).
scent_impactGrafo de impacto semántico (difusión térmica entera 0..=10_000 bp, 1..=6 hops).Indica qué símbolos y archivos se ven afectados antes de refactorizar un símbolo compartido.
scent_referencesResuelve la definición exacta de un símbolo y sus referencias cruzadas directas (callers, callees, implementers, usuarios del tipo) como tuplas @TOON v1.target (nombre de símbolo, Type::method o file::symbol); filtros opcionales public_only, exclude_tests, paginación cursor/max_rows (1..=500).
git_statusEjecuta git status --short --branch de solo lectura.Úsala en lugar de shell_exec para comprobar cambios locales.
git_diffEjecuta git diff --no-color con path, staged y context_lines opcionales.Pasa path estrictamente tras --.
load_skillCarga bajo demanda una guía Markdown/skill por nombre.Busca en .onyx/skills/, skills/, ~/.onyx/skills/ y las integradas scent y rust.
plan_updateActualiza el checklist estructurado de progreso (pending, in_progress, completed).Se persiste en ws.plan.text y se renderiza en el panel derecho Live Plan.
service_statusConsulta el estado @TOON v1 de todos los servicios de sprout.toml.Reflejado también en el panel derecho Services (Sprout).
service_logsLee las últimas líneas del ring-buffer (hasta 2.000 líneas) de un servicio Sprout.Filtrado con scrub_secrets y decodificación UTF-8 lossy.
spawn_agentDelega una subtarea independiente a un subagente hijo (WaitingChildren).Techo por defecto de 32 pasos (ajustable mediante max_steps en los argumentos JSON). Con isolated: true el hijo trabaja en un worktree Git aislado (onyx/sub/agent-*) y la raíz no se toca hasta aplicar el 3-way (ver sección 1.1).

Herramientas mutantes (requieren aprobación en BUILD; bloqueadas en PLAN/EXPLORE)

HerramientaPropósitoNotas clave
fs_writeCrear o sobrescribir un archivo UTF-8.Captura checkpoint Git previo, muestra diff en color antes de aprobar, bloqueado en Control Plane RO.
fs_editReemplazo exacto único (old_text/new_text) o multi-hunk atómico (edits: [...]).Exige lectura previa con fs_read. Aplica fallback por líneas y re-indentado relativo en memoria antes de escribir. Captura checkpoint Git previo.
shell_execEjecutar comando de shell dentro del workspace.Timeout configurable (--shell-timeout, default 30s), env_clear(), sandbox OS, ProcessJob RAII, scrub_secrets, límite 32 KiB e invalidación de cachés fs_read/scent_outline.
service_startArranca un servicio (id) o todo el DAG (all: true) de sprout.toml.Respeta depends_on en orden topológico y espera sondas reales (ready_port, ready_log, ready_cmd).
service_stopDetiene un servicio (id) o todos (all: true).Cierre limpio con stop_cmd / ProcessJob.
service_execEjecuta un comando dentro de un contenedor activo (docker exec / nerdctl exec / podman exec).Aplica env_clear(), timeout y scrub_secrets.

Herramientas asíncronas de subagentes (worktrees Git aislados)

Además de spawn_agent (síncrono, misma workspace), el agente puede lanzar jobs asíncronos que corren en worktrees Git aislados (rama onyx/sub/<job_id>) sin bloquear al agente raíz:

HerramientaPropósitoNotas clave
spawn_subagentLanza un job asíncrono en un worktree Git aislado.goal requerido; max_steps default 32 (máx 128); driver opcional (native por defecto o id de [[external_drivers]] — un driver externo exige aprobación o allow spawn_subagent(<driver>), capítulo 03). Paralelismo limitado por --max-subagents <n> (default 3, o ONYX_MAX_SUBAGENTS).
subagent_statusConsulta el estado de los jobs asíncronos.job_id opcional; muestra estado, rama, archivos tocados y resumen.
subagent_mergeFusiona el worktree del job con la workspace raíz (3-way, Scent-Heated Merge).git merge-tree sin mover HEAD ni el índice. Es la única de las 4 con requires_approval: true. Gobernanza del delta: Deny si toca Control Plane (bloquea el merge entero) y Ask si toca sprout.toml / .github/workflows/** (capítulo 03); driver externo fuerza Ask.
subagent_discardCancela el job y elimina su worktree y rama temporal.Si el job está en marcha, cancela el árbol de procesos del ProcessJob.

Equivalencias slash en la TUI: /spawn [--driver <id>] <objetivo> (lanza), /subagents (lista), /merge <job_id> (fusiona) y /discard <job_id> (descarta). Los logs completos de cada job (stdout/stderr del trabajo, sellados con scrub_secrets) se guardan en .onyx/vault/subagent-logs/<job_id>.log, y la vista F2 Agents (capítulo 02) muestra los jobs [bg] con su estado y badge → <driver>.

Drivers externos: con driver = "opencode" (o cualquier [[external_drivers]] declarado), el job se delega a un harness CLI externo que trabaja en el mismo worktree aislado; el aislamiento de proceso, el gate de Trust y la política de red se documentan en el capítulo 03 (sección 2.7).

1.1. spawn_agent(isolated: true) — hijos sincronos en worktrees aislados

Además de los jobs asíncronos anteriores, spawn_agent admite el argumento isolated: true: el hijo síncrono (el padre queda WaitingChildren) trabaja en su propio worktree Git aislado, de modo que ediciones paralelas de varios hijos nunca tocan el working tree raíz hasta el merge.

  • Creación: al detectar un spawn_agent(isolated: true) pendiente, el bridge crea perezosamente el worktree onyx/sub/agent-<parent>-<child>-<seq> vía WorktreeManager (SDD-09) con WorkspacePolicy::for_worktree y red NativeOffline; la creación usa un checkpoint commit-tree del working tree actual, sin mover HEAD ni el índice de la raíz. Si el workspace no es un repo Git (o Git < 2.38), el padre recibe un error accionable pegajoso (sin tocar root).
  • Finalización: cuando el hijo termina (Done/Failed) o desaparece del grafo, el bridge lo finaliza de forma incondicional: captura el commit efímero del working tree final del hijo, evalúa el 3-way (git merge-tree, raíz intacta) y registra un IsolatedWorktreeResult (Pending/Applied/Discarded/Transferred).
  • Resolución: con 3-way limpio, el resultado se aplica a la raíz (o se descarta) secuencialmente; con conflictos, el worktree queda transferido a SubagentManager y el trabajo pasa al flujo normal de subagent_status / subagent_merge / subagent_discard (misma aprobación y gobernanza que los jobs spawn_subagent). La notificación del resultado sigue la semántica de los jobs asíncronos (last_completed_proposals y, con proactive_notifications, un IngressEvent::Command).
  • Limpieza: el worktree se elimina al aplicarlo/descartarlo, en Drop del bridge y por la poda de worktrees huérfanos en openonyx doctor; la rama temporal onyx/sub/<job_id> se borra siempre.

Herramientas dinámicas MCP (mcp__<server>__<tool>)

Además del catálogo fijo anterior, cada servidor MCP declarado en [mcp.servers.<name>] (capítulo 03, sección 2.8) inyecta sus tools dinámicamente al LLM con el nombre mcp__<server>__<tool>:

  • Descubrimiento en arranque: el handshake initialize → tools/list (paginado, máx. 16 páginas) recupera nombre, descripción e inputSchema de cada tool; los schemas se normalizan antes de declararse al proveedor (Gemini, OpenAI y Anthropic).
  • Siempre aprobables: requires_approval = true en todas las tools mcp__*: piden aprobación interactiva en BUILD (salvo allow más específica) y quedan Deny en PLAN/EXPLORE, igual que las mutaciones.
  • Aislamiento y saneado: un servidor caído no aborta la sesión y los resultados pasan por truncate_utf8 + scrub_secrets.
  • Replay 0-I/O: en openonyx replay los tools mcp__* se reconstruyen de la propia transcripción, sin contactar con ningún servidor.

Los subagentes no reciben tools mcp__*: solo el agente de la sesión principal ve el registro MCP (los jobs de worktree no heredan el registro).


2. Navegación AST con onyx-scent (Scent 2.0)

En lugar de leer archivos de miles de líneas completos, openonyx anima al agente a trabajar en dos fases:

  1. scent_outline: obtiene en pocos tokens todas las funciones, structs, traits, clases, métodos, type aliases y componentes con sus números de línea exactos en formato compacto @TOON v1 (paginado con cursor y next_cursor). Si el agente intenta repetir exactamente el mismo outline sobre un archivo que no ha cambiado, la caché seen_outlines devuelve una respuesta compacta ahorrando tokens y evitando bucles; en cuanto fs_edit, fs_write, shell_exec o /undo modifican el workspace, la caché se invalida automáticamente.
  2. scent_impact / scent_references + fs_read(start_line, end_line): calcula el radio de impacto (o resuelve la definición exacta y las referencias cruzadas directas de un símbolo) antes de tocar una firma pública, y lee únicamente el bloque exacto necesario.

Lenguajes soportados por onyx-scent (Scent 2.0): 7 lenguajes — Rust (.rs), Python (.py), Java (.java), TypeScript (.ts, .tsx, .mts, .cts), JavaScript (.js, .jsx, .mjs, .cjs), Go (.go) y C/C++ (.c, .h, .cc, .cpp, .cxx, .hh, .hpp). En JS/TS se extraen además type aliases (EntityKind::TypeAlias) y componentes (EntityKind::Component: funciones PascalCase con JSX en .tsx/.jsx), y is_callable incluye ambos. En otros lenguajes el agente utiliza glob_files + code_search v2 + fs_read.

Caché incremental binaria .onyx/scent.idx

  • ONYXSCI1: el índice AST del workspace se persiste en .onyx/scent.idx (máquina ONYXSCI1: magic + versión + entradas ordenadas por rel_path + checksum blake3 final) junto con un .onyx/.gitignore de higiene que ignora scent.idx y scent.idx.tmp*; cualquier anomalía (truncado, magic/versión distinta, checksum inválido) se ignora silenciosamente y el índice se reconstruye limpio.
  • Excluido de los artefactos Git: los checkpoints efímeros de subagentes (commit-tree) y la evaluación de impacto de un worktree excluyen .onyx/scent.idx* y su .gitignore, para que el trabajo del hijo no se contamine con artefactos operativos de OnYX.
  • Recarga incremental: en cada refresco se re-analizan únicamente los archivos cuyo mtime/contenido cambiaron (verificación por hash), de modo que repos de miles de archivos se actualizan en decenas de milisegundos; el archivo se escribe atómicamente (scent.idx.tmp.* → rename).
  • CLI scent: el crate onyx-scent (feature cli) expone el binario scent con los subcomandos outline, impact y references (misma salida @TOON v1 que las tools del agente, para uso directo en scripts/CI).

3. Orquestación Local de Procesos y Contenedores (sprout.toml)

Si tu proyecto necesita arrancar servicios locales (bases de datos en Docker/Rancher, APIs, workers, frontends) durante una sesión de desarrollo o testing, crea un archivo sprout.toml en la raíz del workspace.

onyx-workspace incluye un supervisor puro en std (0 tokio) que valida el grafo de dependencias (DAG sin ciclos), arranca servicios en orden topológico, comprueba sondas de disponibilidad reales y cierra todos los procesos limpiamente al salir de openonyx (ProcessJob RAII).

Formato moderno ([runtime] + [services.<id>])

[runtime]
# Opcional: "docker" | "nerdctl" | "podman" (si se omite, se autodetecta)
container_cli = "docker"

[services.db]
name = "Postgres local"
kind = "container"
cmd = "docker compose up -d postgres"
stop_cmd = "docker compose stop postgres"
logs_cmd = "docker compose logs --tail=100 postgres"
container = "myapp-postgres"
# Opcional: fuerza usuario en `service_exec` (ej. "1000:1000" o "app")
# exec_user = "1000:1000"
ready_port = 5432

[services.api]
name = "API Backend"
kind = "process"
cwd = "backend"
cmd = "cargo run --bin api"
depends_on = ["db"]
ready_port = 8080
ready_log = "Listening on 127.0.0.1:8080"

También se admite el formato clásico de Sprout ([global] + [[service]] con env_wrapper, dir, debug_port, depends_on, optional, enabled).

Control interactivo desde la TUI

  • /services: imprime en Memory & Trace la tabla @TOON v1 con estado de cada servicio.
  • /service start <id|all>: arranca un servicio (y sus dependencias) o todo el stack.
  • /service stop <id|all>: detiene un servicio o todos.
  • /service logs <id> [tail]: muestra las últimas [tail] líneas del buffer de logs.
  • Además, con terminal >= 100 columnas verás el estado en tiempo real en el panel derecho Services (Sprout), y openonyx doctor validará tu sprout.toml (sintaxis, ciclos en DAG, runtime de contenedores y puertos ya ocupados).

Nota sobre red, confianza y contenedores: si el agente necesita consultar con shell_exec una API local levantada por Sprout (p. ej. http://127.0.0.1:8080/health), ejecuta openonyx con --sandbox-net localhost (o configúralo en .onyx/config.toml). Además, si el repositorio no está en tu almacén de Workspace Trust (openonyx trust add o /trust), Sprout muestra [UNTRUSTED — run /trust] y bloquea start, stop y exec hasta que confíes en el sprout.toml actual (cualquier cambio de 1 byte revoca la confianza automáticamente). container_cli solo admite docker, nerdctl o podman, y el campo opcional exec_user permite ejecutar service_exec con un usuario concreto.


4. Instrucciones de Proyecto (ONYX.md / AGENTS.md)

En cada inicio (chat, run y rewind vivo), openonyx carga automáticamente instrucciones Markdown en este orden (hasta 16 KiB totales, siempre pasadas por scrub_secrets):

  1. ~/.onyx/AGENTS.md y ~/.onyx/ONYX.md (reglas globales personales)
  2. <workspace>/AGENTS.md y <workspace>/ONYX.md (reglas del repositorio)

Además, inyecta automáticamente una pista del sistema operativo anfitrión (Windows PowerShell vs Unix/POSIX) para evitar comandos incompatibles en shell_exec.

Ejemplo útil de <workspace>/ONYX.md:

# Convenciones del proyecto
- Ejecuta siempre `cargo test --workspace` tras editar código Rust.
- No modifiques archivos generados bajo `dist/`.
- Escribe los mensajes de error orientados al usuario en español.

5. Crear tus Propias Skills (SKILL.md)

En lugar de inflar ONYX.md con manuales largos que se envían en cada turno, crea skills bajo demanda. Al arrancar, openonyx solo inyecta un catálogo compacto (discover_skills_summary), y el agente carga el texto completo con load_skill("<nombre>") únicamente cuando lo necesita.

Orden de búsqueda de skills

  1. <workspace>/.onyx/skills/<nombre>/SKILL.md (recomendado por proyecto) o <nombre>.md
  2. <workspace>/skills/<nombre>/SKILL.md o <nombre>.md
  3. ~/.onyx/skills/<nombre>/SKILL.md o <nombre>.md (globales de usuario)
  4. Skills integradas: scent y rust

Plantilla de una skill personalizada

Crea .onyx/skills/deploy-checks/SKILL.md:

---
name: deploy-checks
description: Checklist de verificación previa a despliegue y migraciones SQL seguras.
---

# Verificación Pre-Despliegue

1. Comprueba con `git_diff` que no haya migraciones destructivas sin plan de rollback.
2. Verifica que `cargo clippy --workspace --all-targets -- -D warnings` pase sin avisos.
3. Revisa que no queden claves ni URLs de staging en archivos de configuración.

Buenas prácticas:

  • Incluye name: y description: en las primeras 20 líneas (el catálogo usa description:).
  • Nunca escribas secretos reales (todo pasa por scrub_secrets).
  • Mantén cada skill muy por debajo de 64 KiB.

6. Automatización Headless y CI (openonyx run)

Para ejecutar una tarea única sin interfaz TUI:

# Auditoría de solo lectura sin coste humano
openonyx run "revisa git_diff y enumera posibles regresiones de seguridad" \
  --effort medium \
  --max-steps 32 \
  --record ci_review.tr \
  --snapshot-dir .snaps_ci

# Ejecución automatizada acotada con sandbox estricto
openonyx run "corrige los avisos de clippy y valida con cargo test" \
  --auto-approve \
  --sandbox workspace-write \
  --sandbox-net offline \
  --shell-timeout 120 \
  --record ci_fix.tr \
  --snapshot-dir .snaps_fix

Recuerda que incluso con --auto-approve, cualquier regla [permissions].deny de .onyx/config.toml y la protección RO del Control Plane siguen bloqueando acciones prohibidas.


← 04. Time-Travel, Snapshots y Forking · Índice · Siguiente: 06. Referencia CLI y Troubleshooting →

06. Referencia CLI Completa y Solución de Problemas

🇬🇧 Read this chapter in English

Referencia rápida de todos los subcomandos, flags, variables de entorno, resiliencia HTTP/SSE y soluciones a incidencias reales en Windows, Linux y macOS.


1. Referencia de Subcomandos

openonyx chat [OPCIONES] [--resume <dir> [--tick <n>] [--fork-dir <dir>] [--truncate-future]]
openonyx run <goal> [OPCIONES]
openonyx replay <transcript> [--workspace <dir>] [--snapshot-dir <dir>] [--snapshot-every <n>] [--max-snapshots <n>]
openonyx inspect <snapshot_dir> [--tick <n>] [--list] [--json]
openonyx rewind <snapshot_dir> <tick> [--transcript <file>] [--interactive | --tui] [--fork-dir <dir>] [--truncate-future] [--dry-run] [OPCIONES]
openonyx bench --snapshot-dir <dir> --tick <n> --models <list> [--goal <text>] [--verify <cmd>] [--out <file.json>] [--max-steps <n>] [OPCIONES]
openonyx doctor [--workspace <dir>] [--snapshot-dir <dir>] [--transcript <file>]
openonyx trust [--workspace <dir>] [add | list | check | revoke] [--list | --check | --revoke]
openonyx serve [--workspace <dir>] [--bind <ip:port>] [--api-key <key>] [--cors-origin <origin>] [OPCIONES]
openonyx [--help | -h | --version | -V]

2. Tabla Completa de Opciones (Flags)

FlagAplica aDescripción / Default
-w, --workspace <dir>TodosDirectorio del proyecto objetivo (default: directorio actual).
--provider <gemini|openai|anthropic>chat, run, rewindBackend LLM (gemini por defecto; openai para OpenAI/OpenRouter/Ollama/vLLM/LM Studio; anthropic para la Messages API nativa).
--model <name>chat, run, rewindNombre del modelo (defaults: gemini-4-hydrogen en Gemini, gpt-4o en OpenAI, claude-sonnet-4-5 en Anthropic).
--effort <low|medium|high>chat, run, rewindEsfuerzo de razonamiento/pensamiento (thinkingLevel / reasoning_effort; en anthropic mapea al presupuesto de thinking 2048/8192/16384 salvo presupuesto explícito).
--thinking-budget <n>chat, run, rewindPresupuesto de extended thinking de Anthropic en tokens (0 = off, o 1024..=60000; o ANTHROPIC_THINKING_BUDGET). Eleva max_tokens por encima del presupuesto.
--api-base <url>chat, run, rewindURL base personalizada (http:// permitido solo en loopback localhost/127.0.0.1/[::1]; hosts remotos exigen https://).
--allow-custom-auth-hostchat, run, rewindOpt-in explícito para enviar API keys a hosts HTTPS remotos no oficiales (o ONYX_ALLOW_CUSTOM_AUTH_HOST=1).
--trust-workspacechat, run, rewind, serveConfía el workspace actual en memoria durante la sesión (sin modificar ~/.onyx/trusted_workspaces.toml).
--bind <ip:port>serveDirección HTTP/SSE (default: 127.0.0.1:8787; direcciones no loopback exigen --api-key explícita >= 16 chars).
--api-key <key>serveAPI key para autenticación (cookie HttpOnly o Authorization: Bearer; en loopback se genera aleatoria si se omite).
--cors-origin <url>serveOrigen explícito permitido para frontales externos (p. ej. SPA Svelte en http://localhost:5173; nunca *).
--sandbox <off|workspace-write|strict-container>chat, run, rewindPerfil de sandbox OS para shell_exec (default: workspace-write).
--sandbox-net <offline|localhost|unrestricted>chat, run, rewindPolítica de red del sandbox (default: offline).
--auto-approvechat, run, rewindOmite confirmaciones interactivas para herramientas mutantes (deny sigue aplicando y eleva sandbox off → workspace-write + offline salvo --sandbox off).
--ignore-denychat, run, rewindDesactiva explícitamente las reglas [permissions].deny de .onyx/config.toml.
--max-steps <n>chat, runLímite de pasos por turno del agente raíz (default: 128 en chat, 64 en run; subagentes 32 por defecto).
--max-subagents <n>chat, run, serve, rewind --interactiveMáximo de worktrees Git en paralelo para subagentes asíncronos (default: 3, o ONYX_MAX_SUBAGENTS).
--shell-timeout <secs>chat, runTimeout en segundos por comando shell_exec (default: 30s).
--auto-savechat, runCrea automáticamente .onyx/vault/<YYYYMMDD-HHMMSS>_<modelo>[_<rama|goal>]/ con snapshots.onyxpack + .tr juntos (o ONYX_AUTO_SAVE=1).
--record <f>, --save-transcript <f>chat, runGuarda transcripción determinista ONYXTR2 (nombres cortos van dentro de --snapshot-dir, o en .onyx/vault/unassigned/ si no hay snapshot dir).
--snapshot-dir <dir>chat, run, replay, doctorDirectorio para snapshots.onyxpack (nombres cortos se resuelven en .onyx/vault/<dir>/).
--snapshot-every <n>chat, run, replayCaptura además un hito periodic cada <n> ticks.
--max-snapshots <n>chat, run, replayRetención opt-in por ventana deslizante (init + últimos n - 1 hitos).
-r, --resume <dir>chatReanuda desde el último hito (o --tick <n>) guardado en <dir>.
--tick <n>inspect, chat --resumeTick específico a inspeccionar o desde el que reanudar/bifurcar.
--fork-dir <dir>chat --resume --tick, rewind --interactiveDirectorio destino del fork de snapshots.
--truncate-futurechat --resume --tick, rewindOpt-in destructivo: trunca el pack origen in-place en lugar de crear un fork hermano.
--interactive, --tuirewindAbre la TUI interactiva en el tick restaurado en lugar de continuar en headless.
-l, --listinspectLista todos los hitos con etiquetas, tamaños, FNV-1a y checkpoints Git.
--jsoninspectEmite salida estructurada en JSON.
--transcript <file>rewind, doctorReproduce transcripción desde el punto de rewind o valida su cabecera en doctor.
--dry-runrewindPrevisualiza efectos huérfanos y plan de rollback sin modificar disco.
--models <list>benchLista de candidatos separada por comas: <provider>:<model> (LLM vivo, p. ej. gemini:gemini-2.5-pro,openai:gpt-4o) y/o replay:<label>=<file.tr> / replay:<file.tr> (transcripción ONYXTR2 offline, determinista).
--verify <cmd>benchComando de verificación ejecutado sandboxed dentro del worktree del candidato tras asentarse (misma tubería de shell_exec); su exit 0 decide passed_verify. Sin --verify, passed_verify = el agente terminó Done y la sesión se asentó.
--out <file.json>benchEscribe el informe JSON completo (metadata + resultados) en pretty-print.
--goal <text>benchObjetivo del agente raíz si en el --tick no hay agente activo (obligatorio en ese caso).
-h, --help / -V, --versionGlobalMuestra ayuda o versión y sale con código 0.

openonyx bench — referencia completa

Benchmark multi-modelo desde un snapshot idéntico: cada candidato se ejecuta en un worktree desechable (bench-<pid>-<idx>-<label>) con rewind a --tick (reconcile_rewind_effects_report), un host de sesión fresco (request_restore + 1 step) y, al terminar, la raíz y HEAD quedan 100 % intactos y el worktree se elimina (guard RAII; también en error o pánico).

# Comparativa en vivo + replay offline, con verificación y informe JSON
openonyx bench \
  --snapshot-dir .onyx/vault/20261125-100000_gpt-4o \
  --tick 12 \
  --models "gemini:gemini-2.5-pro,openai:gpt-4o,replay:baseline=run_baseline.tr" \
  --goal "fix the failing test in src/app.rs" \
  --verify "cargo test --workspace" \
  --out bench_report.json \
  --auto-approve \
  --sandbox workspace-write \
  --sandbox-net offline
  • Candidatos (--models): <provider>:<model> con provider ∈ gemini|openai|anthropic (credenciales vía las variables habituales GEMINI_API_KEY/OPENAI_API_KEY/ANTHROPIC_API_KEY o --api-base); replay:<label>=<path.tr> fija el label; replay:<path.tr> usa el file stem como label. El parse divide primero por : y luego por =, de modo que las rutas con letra de unidad Windows (replay:C:\runs\a.tr) se conservan intactas.
  • Ejecución por candidato (secuencial): rewind del worktree al tick → host fresco restaurado → si no hay agente activo en el tick, se spawnea un agente raíz con --goal → se ejecuta hasta asentarse (tope interno de 256 ticks) con telemetría real (tokens/coste) en candidatos vivos (replay: tokens/coste 0).
  • --auto-approve: para ejecución desatendida en worktrees desechables: cada candidato corre solo en su worktree, la raíz nunca se toca; [permissions].deny sigue aplicando.
  • Salida: tabla Markdown de 9 columnas en stdout — | model | passed_verify | ticks | tool_calls | input_tokens | cached_tokens | output_tokens | estimated_cost_usd | wall_time_ms | — y, con --out, el informe JSON (metadata con snapshot/tick/models/verify + results por candidato con todas las columnas).
  • Flags reutilizados: --workspace <dir>, --sandbox <off|workspace-write|strict-container>, --sandbox-net <offline|localhost|unrestricted>, --shell-timeout <secs>, --trust-workspace, --api-base <url>, --allow-custom-auth-host, --effort <low|medium|high>, --thinking-budget <n> (el candidato vivo determina su propio provider:model).
  • Validación accionable: sin --snapshot-dir/--tick/--models el error indica la flag que falta; proveedor desconocido → unsupported provider ... (expected gemini, openaioranthropic); snapshot ausente → aviso de suelo (floor), no error.

3. Variables de Entorno

VariableProveedorDescripción
ONYX_PROVIDERTodosProveedor por defecto (gemini | openai | anthropic).
GEMINI_API_KEYGeminiAPI key de Google AI Studio (fallback: ONYX_API_KEY).
OPENAI_API_KEYOpenAIAPI key para --provider openai (fallback: ONYX_API_KEY; opcional con --api-base local).
ANTHROPIC_API_KEYAnthropicAPI key para --provider anthropic (fallback: ONYX_API_KEY).
ONYX_API_KEYTodosClave compartida de fallback si no se define la específica del proveedor.
ONYX_MODELTodosModelo por defecto (fallbacks: ONYX_GEMINI_MODEL para Gemini, OPENAI_MODEL para OpenAI, ANTHROPIC_MODEL para Anthropic).
ONYX_EFFORTTodosEsfuerzo por defecto (low | medium | high; fallbacks: GEMINI_THINKING_LEVEL, OPENAI_REASONING_EFFORT; en Anthropic lo gobierna ANTHROPIC_THINKING_BUDGET).
ONYX_AUTO_SAVEAmbosActiva --auto-save por defecto (1 | true | yes | on) guardando en .onyx/vault/.
ONYX_MAX_SUBAGENTSAmbosMáximo de worktrees en paralelo para subagentes asíncronos (usado cuando no se pasa --max-subagents <n>; default: 3).
GEMINI_API_BASEGeminiEndpoint personalizado para Gemini.
OPENAI_API_BASE / OPENAI_BASE_URLOpenAIEndpoint compatible con OpenAI (default: https://api.openai.com/v1).
ANTHROPIC_API_BASEAnthropicEndpoint personalizado de la API de Anthropic (default: https://api.anthropic.com).
ANTHROPIC_THINKING_BUDGETAnthropicPresupuesto de extended thinking en tokens (0 = off, o 1024..=60000); tiene prioridad sobre el presupuesto derivado de --effort.

Configuración LLM, drivers y MCP en config.toml: además de flags y variables, .onyx/config.toml acepta bloques [[llm_profiles]] (capítulo 03, sección 2.6), [[external_drivers]] (capítulo 03, sección 2.7) y [mcp.servers.<name>] (capítulo 03, sección 2.8). Las credenciales de un perfil se resuelven en el orden api_key_env → variable estándar del proveedor → ONYX_API_KEY.


4. Resiliencia HTTP/SSE en Endpoints OpenAI, vLLM y Proxies

En servidores locales o proxies corporativos (vLLM, LiteLLM, nginx, Cloudflare) es frecuente que la conexión chunked SSE se cierre bruscamente tras emitir finish_reason o que devuelva un error transitorio (408, 429, 500, 502, 503, 504 o corte temporal de red).

El adaptador open-onyx/src/openai.rs incorpora dos protecciones automáticas:

  1. Tolerancia a EOF tras respuesta completada: si el stream SSE falla al decodificar el último chunk pero ya se recibió finish_reason / [DONE] con respuesta o tool_calls completos, la respuesta se acepta sin abortar el turno.
  2. Reintentos automáticos con backoff: ante fallos HTTP o de transporte transitorios, reintenta automáticamente hasta 2 veces (400ms, 1200ms) antes de reportar error al agente.

El adaptador nativo open-onyx/src/anthropic.rs aplica la misma política de reintentos (408, 429, 500, 502, 503, 504 y el overloaded_error 529 propio de Anthropic), respetando el header retry-after cuando el servidor lo envía.


5. Solución de Problemas Frecuentes (Troubleshooting)

1. GEMINI_API_KEY environment variable is not set

  • Si quieres usar Gemini: exporta GEMINI_API_KEY (PowerShell: $env:GEMINI_API_KEY="..."; bash/zsh: export GEMINI_API_KEY="...").
  • Si quieres usar Ollama / vLLM / LM Studio: añade --provider openai --api-base http://localhost:11434/v1 --model <tu-modelo> (así no se exige API key).
  • Si solo quieres usar inspect, replay, rewind --dry-run o doctor: ninguno de ellos requiere API key.

2. El agente intenta leer un .tr, .onyxpack o tick-*.bin con fs_read

fs_read detecta automáticamente las cabeceras binarias de OnYX (ONYXTR1, ONYXTR2, ONYXPK1, ONYXAG) y devuelve un error explicativo recomendando usar openonyx inspect o openonyx replay en lugar de leer el binario como texto.

3. shell_exec falla con error de red (offline) al ejecutar cargo build o curl

Por defecto el sandbox usa --sandbox-net offline (inyectando además CARGO_NET_OFFLINE=true).

  • Si necesitas consultar un servicio local de Sprout (127.0.0.1): usa --sandbox-net localhost.
  • Si necesitas descargar crates o paquetes de internet: usa --sandbox-net unrestricted (o añádelo temporalmente en .onyx/config.toml).

4. Linux Ubuntu 24.04+: bwrap no puede crear user namespaces (AppArmor)

Ubuntu 24.04 restringe unprivileged user namespaces vía AppArmor. openonyx ejecuta una sonda real (bwrap_is_usable()) y aplica automáticamente un fallback seguro para que shell_exec no falle. Comprueba el estado exacto en openonyx doctor.

5. Ctrl+Tab no cambia de agente en mi terminal

Algunos emuladores de terminal (especialmente en Windows o a través de tmux/SSH) interceptan o no envían Ctrl+Tab. Usa siempre la tecla F2 (ahora abre la vista Agents, capítulo 02) o el comando /agent [id|name], que funcionan en el 100% de terminales.

6. /rewind dice que no puede ejecutarse mientras hay actividad

Por seguridad, /rewind <tick> en vivo requiere que ningún agente esté thinking, acting, waiting_children ni con una llamada LLM en vuelo. Espera a que el turno termine (emblema detenido / Settled), o sal con Esc y ejecuta openonyx chat --resume <dir> --tick <n>.

7. Windows PowerShell: comillas o redirecciones en shell_exec

openonyx informa al modelo del sistema operativo anfitrión (Windows PowerShell vs Unix/POSIX), pero si un modelo local insiste en usar sintaxis bash (&&, grep, cat), recuérdale en tu ONYX.md del proyecto que use herramientas nativas (code_search, glob_files, fs_read, git_diff) y comandos compatibles con PowerShell.

8. Corte inesperado durante una sesión larga

  1. Ejecuta openonyx doctor --snapshot-dir <dir> para comprobar si quedó una cola truncada en snapshots.onyxpack.
  2. Revisa los hitos intactos con openonyx inspect <dir> --list.
  3. Reanuda con openonyx chat --resume <dir> (la cola truncada se ignora de forma segura al leer y se repara automáticamente al guardar el próximo hito).

9. openonyx doctor avisa o falla en un driver externo ([[external_drivers]])

doctor audita las declaraciones de [[external_drivers]] (capítulo 03, sección 2.7):

  • Preset integrado opencode: [WARN] si el binario opencode no está en PATH (el preset se omite).
  • Driver declarado cuyo bin no existe: [ERR] — /spawn --driver <id> will fail at runtime.
  • bin encontrado pero la sonda --version (deadline 3 s, entorno saneado) se queda a tiempo: [ERR]; si responde con error (p. ej., flags mal puestas): [WARN].
  • prompt_transport = "arg" en Windows: [WARN] si el binario resuelve a un wrapper .cmd/.bat (rechazado en el spawn).
  • network_allowlist sin --sandbox strict-container: [WARN] — la allowlist es advisory fuera de strict-container; un driver declarado sin network_allowlist queda LocalhostOnly salvo que el sandbox lo relaje.

10. Un servidor MCP no se conecta o [mcp.servers.*] queda ignorado

openonyx doctor audita los servidores declarados en [mcp.servers.<name>] (capítulo 03, sección 2.8) con un handshake acotado a 5 s (un servidor caído nunca colga doctor):

  • Connected o Disabled: [CHECK] informativo.
  • Failed(...) (binario ausente, timeout del handshake, error del servidor): [ERR] accionable con el mensaje ya scrubbeado; la sesión sigue funcionando sin ese servidor (aislamiento de fallos).
  • Workspace no confiado con [mcp.servers.*] de proyecto: [WARN] MCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust) — aprueba con openonyx trust o usa --trust-workspace.
  • Tools mcp__* siempre piden aprobación en BUILD y quedan Deny en PLAN/EXPLORE; si quieres auto-aprobarlas, declara allow = ["mcp__<server>__*"] en .onyx/config.toml (workspace confiado).

11. La Web (o la TUI) no acepta mi prompt: 409 Conflict / "Paused in TIME FROZEN"

Es el guard de TimeFreeze (capítulo 04, sección 9): la sesión está congelada (breakpoint temporal activo) y un prompt plano desordenado rompería la bit-a-bit del replay. No es un fallo — son las vías de escape:

  • /go (o /unfreeze): bifurca si el cursor mira el pasado y reanuda en el presente.
  • /inject <texto> / /graph … / /read … / /step [n] / /step-llm / ! <cmd>: siguen funcionando bajo freeze (primitivas 0-tokens selladas).
  • En la Web, la barra ámbar (pulsar #tick-pill) tiene Resume; en la TUI, Esc vuelve al presente sin salir y Ctrl+T alterna el freeze.
  • En POST /api/v1/command el 409 incluye el mensaje accionable completo; un 400 en POST /api/v1/time/scrub significa tick futuro/purgado o acción desconocida (el body lo explica).

← 05. Herramientas, Scent, Sprout y Skills · Volver al Índice del Manual

openOnyx (openonyx) User Manual

🇪🇸 Leer el manual completo en Español

Welcome to the official manual for openonyx, the deterministic coding-agent CLI, TUI, and embedded Web PWA harness built on the OnYX microkernel (onyx-core → onyx-soul-agents → onyx-workspace → open-onyx).

Unlike conventional terminal coding assistants backed by mutable message arrays, openonyx records every decision, read, edit, and command inside a deterministic EAV graph featuring:

  • Compressed milestone snapshots (snapshots.onyxpack) with 64-bit FNV-1a checksums and truncated-tail crash tolerance.
  • Centralized session vault (.onyx/vault/ + --auto-save) auto-ignored by Git so workspace roots stay clean.
  • Non-destructive time-travel & forking (/rewind, /fork, chat --resume --tick, rewind --interactive).
  • Interactive Time Debugger (TimeFreeze, SDD-07): pause the session at any tick (TUI: Alt+←/→, Ctrl+T, /time, /go, /step, /step-llm; Web: #tick-pill → amber bar) over a RAM tick-boundary ring + on-disk milestones; 0-token primitives sealed into ONYXTR2 (0 network, 0 disk: !cmd, /read, /inject, /step) and safe surgery on the frozen graph with /graph (inspect / drop-mem / edit-mem / set-goal); 100 % ephemeral until the branch is confirmed.
  • Asynchronous subagents in isolated Git worktrees (spawn_subagent / /spawn, 3-way merge with Scent-Heated Merge, --max-subagents, and optional external CLI harness drivers via [[external_drivers]]), plus spawn_agent(isolated: true): synchronous children in isolated onyx/sub/agent-* worktrees with 3-way reconciliation that never touches HEAD or the root until merged.
  • Multi-model benchmarking (openonyx bench): identical snapshot/tick, throwaway per-candidate worktrees (rewind + RAII), live provider:model or offline replay:<label>=<file.tr> candidates, sandboxed --verify, 9-column Markdown table + JSON report via --out; the root stays 100 % intact.
  • Verify-on-Edit ([verify] / [[verify.rules]] in .onyx/config.toml): after each successful fs_edit/fs_write, runs the rules whose glob matches the edited file (plus Scent-impacted scope:test files) in the sandbox and injects [verify: PASS|FAIL|BLOCKED] into the tool observation, subject to Workspace Trust and [permissions].deny.
  • Hot-swappable LLM targets ([[llm_profiles]], /profile / /provider / /model / /effort, live provider/model header and credential-free Web selector), including a native Anthropic provider (Messages API, ephemeral prompt caching, and budgeted extended thinking via --thinking-budget).
  • Dynamic MCP tools ([mcp.servers.<name>], stdio and http transports): each tool is exposed as mcp__<server>__<tool>, always approval-gated, Deny in PLAN/EXPLORE, behind the Workspace Trust gate, with per-server failure isolation and openonyx doctor auditing.
  • Modular F1..F5 TUI views (Chat, Agents, Sprout, Plan & Diff, Timeline) with a Ctrl+K command palette and /view.
  • Transactional Git checkpoints (/undo) without mutating HEAD or your staging index.
  • 100% offline deterministic replay (ONYXTR2, 0 network calls, 0 disk writes).
  • Defense-in-depth security: blake3 Workspace Trust (openonyx trust / /trust), PLAN / BUILD / EXPLORE modes, .onyx/config.toml rules (deny > ask > allow), Scent-Heated Approvals, OS sandboxing with env_clear(), Control Plane RO protection, and RAII ProcessJob process-tree teardown.
  • Embedded Web UI / PWA (openonyx serve): pure-std HTTP/1.1 + SSE server (0 tokio) ready for desktop browsers, mobile phones, or HTTPS reverse proxies, with blake3 constant-time auth (HttpOnly cookie / Bearer) and explicit --cors-origin support for external frontends.
  • Semantic AST navigation, Scent 2.0 (onyx-scent: scent_outline + scent_impact + scent_references): 7 languages (Rust, Python, Java, TypeScript, JavaScript, Go, C/C++), EntityKind::{TypeAlias, Component} kinds, incremental binary cache .onyx/scent.idx (ONYXSCI1, sub-20 ms reloads) and the scent outline|impact|references CLI; plus local process/container orchestration (sprout.toml).

Table of Contents

ChapterTopics
01. First Steps (Quickstart)Build/install, configure Gemini / OpenAI / Ollama / vLLM, --auto-save, first interactive TUI session to Settled, diff approvals, Tab Plan/Build, and /undo.
02. TUI & Daily WorkflowCompact 3-row header with live provider/model, Braille emblem, --effort, live vault:<session> badge, live telemetry, Memory & Trace scroll, Live Plan & Services (Sprout) panels, tiered context + /compact [focus], /new, modular F1..F5 views + Ctrl+K palette + /view, multi-agent supervision (spawn_agent, /agent, Ctrl+Tab), and hot-swapping the LLM target (/profile, /provider, /model, /effort).
03. Modes, Permissions & OS SandboxPLAN, BUILD, and EXPLORE modes; declarative .onyx/config.toml ([permissions], [sandbox], and [verify] Verify-on-Edit), deny > ask > allow, --ignore-deny, --auto-approve elevation, MCP servers ([mcp.servers.<name>], mcp__<server>__<tool>, approval gate, Deny in PLAN/EXPLORE), Control Plane RO protection, env_clear(), RAII ProcessJob, and Linux (bwrap + AppArmor fallback) / macOS / Windows drivers.
04. Time-Travel, Snapshots & ForkingSession vault (.onyx/vault/ & --auto-save), snapshots.onyxpack, automatic milestone tags, /undo (including untracked fs_write cleanup), live /rewind [tick] & /fork [name], chat --resume --tick, rewind --interactive, offline replay (ONYXTR2), inspect, and doctor.
05. Tools, Scent, Sprout & SkillsFull 24-tool reference (including the async subagent tools spawn_subagent / subagent_status / subagent_merge / subagent_discard, spawn_agent(isolated: true) isolated worktrees, and external CLI harness drivers) plus dynamic mcp__* tools, Scent 2.0 AST navigation (7 languages, scent_outline + scent_impact + scent_references, .onyx/scent.idx ONYXSCI1 cache, scent CLI), local service & container orchestration (sprout.toml, /services, /service), project instructions (ONYX.md/AGENTS.md), authoring custom skills, and headless automation (openonyx run).
06. CLI Reference & TroubleshootingComplete subcommand, flag, and environment-variable tables (including --thinking-budget, ANTHROPIC_*, and the full openonyx bench reference: --models live/replay candidates, --verify, --out, --goal), OpenAI/vLLM and Anthropic SSE EOF resilience & retries, openonyx doctor checklist (with MCP server audit), and practical Windows/Linux/macOS troubleshooting.


Prerequisites

  • Rust 1.85 or newer (the repository pins 1.85.1 in rust-toolchain.toml with edition = "2024").
  • Git on PATH (required for reversible /undo checkpoints, rewind, git_status, and git_diff).
  • Access to an LLM:
    • A Google AI Studio (GEMINI_API_KEY) key, or
    • An OpenAI / OpenRouter (OPENAI_API_KEY) key, or
    • An Anthropic (ANTHROPIC_API_KEY) key for the native provider (--provider anthropic), or
    • Any local OpenAI-compatible /v1/chat/completions server such as Ollama, vLLM, or LM Studio (no API key required).
  • Optional: docker, nerdctl, or podman for --sandbox strict-container or kind = "container" services in sprout.toml; bwrap (Bubblewrap) on Linux for filesystem sandboxing.

Other Repository Documentation

01. First Steps with openOnyx (Quickstart)

🇪🇸 Ver este capítulo en Español

Go from building openonyx to completing your first supervised coding session — with live SSE streaming, colorized diff approvals, PLAN/BUILD mode toggling, and transactional Git /undo — in under 10 minutes.


1. Build or Install openonyx

From the OnYX repository root:

# Optimized build (recommended for daily use)
cargo build --release -p open-onyx

# Or install into ~/.cargo/bin so `openonyx` is available in any project
cargo install --path open-onyx

Verify the binary and audit your local environment:

openonyx --version
openonyx --help
openonyx doctor

Tip: If you did not install globally, replace openonyx with cargo run --release -p open-onyx -- or ./target/release/openonyx (Windows: .\target\release\openonyx.exe).


2. Configure an LLM Provider

openonyx natively supports Google Gemini (default) and any OpenAI-compatible /v1/chat/completions endpoint (OpenAI, OpenRouter, Ollama, vLLM, LM Studio).

Option A — Google Gemini (default)

Windows (PowerShell):

$env:GEMINI_API_KEY = "your-api-key"
openonyx chat --auto-save

Linux / macOS (bash/zsh):

export GEMINI_API_KEY="your-api-key"
openonyx chat --auto-save

To pick a specific model or reasoning effort (low, medium, high):

openonyx chat --model gemini-2.5-pro --effort high --auto-save

Option B — OpenAI / OpenRouter

Windows (PowerShell):

$env:OPENAI_API_KEY = "sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save

Linux / macOS:

export OPENAI_API_KEY="sk-..."
openonyx chat --provider openai --model gpt-4o --effort medium --auto-save

With OpenRouter or any compatible gateway:

openonyx chat --provider openai --api-base https://openrouter.ai/api/v1 --model anthropic/claude-sonnet-4 --auto-save

Option C — Local Models (Ollama, vLLM, LM Studio)

Whenever --api-base (or OPENAI_API_BASE / OPENAI_BASE_URL) is set, OPENAI_API_KEY is optional.

Ollama:

openonyx chat --provider openai --api-base http://localhost:11434/v1 --model qwen2.5-coder:14b --effort low --auto-save

vLLM / LM Studio:

openonyx chat --provider openai --api-base http://localhost:8000/v1 --model Qwen/Qwen3-Coder-30B-A3B --auto-save

Tip: passing --auto-save (or setting ONYX_AUTO_SAVE=1) automatically stores snapshots and transcripts together under .onyx/vault/<timestamp>_<model>_<branch>/ (auto-ignored by Git), keeping your repository root clean while enabling /rewind and --resume out of the box.


3. Your First Interactive Session (openonyx chat)

  1. Open a terminal inside any Git repository (or pass -w /path/to/repo).
  2. Run openonyx chat --snapshot-dir .snaps_demo --record demo.tr.
  3. The TUI displays:
    • Compact 3-row header: Braille activity emblem, [BUILD] / [PLAN] badge, [SANDBOX:workspace], active model & effort, and live telemetry (ctx, in/cache/out/think tokens, and estimated cost or local).
    • Main Memory & Trace pane: conversation turns, tool calls, observations, and live [stream] ...▍ token previews.
    • Bottom input bar: prompt input and key hints.

Step 1 — Explore Safely in [PLAN] Mode

Press Tab to toggle to [PLAN] (read-only; mutating tools are unconditionally blocked). Type an analysis prompt and press Enter:

Inspect this repository structure and propose a concise plan to add a helper function to the main module.

The agent uses read-only tools (glob_files, scent_outline, code_search, fs_read, plan_update) without interrupting you for approval. When your terminal is at least 100 columns wide and plan_update is used, the Live Plan panel opens automatically on the right.

Step 2 — Switch to [BUILD] and Review Diffs

Press Tab again to switch back to [BUILD] and send a follow-up prompt:

Implement the change and run the test suite.

Whenever the agent proposes fs_edit, fs_write, or shell_exec, the TUI pauses in WaitingApproval:

  • The banner shows which agent requested the action ([agent #1 ...]).
  • File edits show a colorized unified diff preview before writing to disk.
  • You can scroll Memory & Trace freely (Up/Down/PgUp/PgDn) while inspecting the diff.
  • Press y to approve or n to deny (denials are fed back to the agent cleanly).

Step 3 — Revert the Last Edit with /undo

If you want to roll back the latest fs_edit or fs_write, type:

/undo

openonyx restores the lightweight Git tree checkpoint captured right before the edit — without touching HEAD or your staged index — and cleanly removes newly created untracked fs_write files while preserving unrelated untracked files.

Step 4 — Exit Cleanly

Press Esc or Ctrl+C. openonyx flushes the final exit milestone into .snaps_demo/snapshots.onyxpack and writes demo.tr.


4. Resume, Inspect, or Replay Offline

After closing your session, try these zero-token commands:

# 1. List all recorded milestones and Git tree checkpoints
openonyx inspect .snaps_demo --list

# 2. Deterministically replay the session offline (0 HTTP calls, 0 disk writes)
openonyx replay demo.tr

# 3. Resume from the latest milestone
openonyx chat --resume .snaps_demo

# Or branch safely from an earlier tick into a sibling fork directory
openonyx chat --resume .snaps_demo --tick 8

5. Single-Turn Headless Execution (openonyx run)

For scripts or CI pipelines where you don't want a TUI:

openonyx run "summarize the pending git diff" --record run.tr --snapshot-dir .snaps_run

openonyx prints the final agent response along with [openOnyx telemetry] token/cost counters.


← English Index · Versión en Español · Next: 02. TUI & Daily Workflow →

02. TUI & Daily Workflow

🇪🇸 Ver este capítulo en Español

This chapter explains every visual component of openonyx chat, how to tune reasoning effort (--effort) and hot-swap the LLM target, how multi-turn memory and tiered context (/compact) work, how to navigate the five ephemeral F1..F5 views (with the Ctrl+K palette and /view), and how to supervise subagents from the F2 Agents view (or the /agent picker).


1. TUI Anatomy

Running openonyx chat organizes the terminal into four zones:

┌ F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline · Esc:Quit ──────────────┐
│ openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high)               │
│ goal:  Refactor the parser… · phase: thinking / streaming… · #1 [root] [subagents:1]    │
│ ⠋ Tab: Plan/Build · F2: Agents · /rewind · /fork · /services · Esc: quit                 │
└─ ctx: 24% · in: 18.4k (cache 12.1k) · out: 1.9k · think: 0.6k · ~$0.024 ────────────────┘
┌─ Memory & Trace (Up/Down/PgUp/PgDn/Home/End) ──────────┐┌─ Live Plan ───────────────────┐
│ [user] Refactor the parser...                          ││ [x] Inspect AST               │
│ [call] scent_outline {"path":"src/parser.rs"}          ││ [>] Edit parser.rs            │
│ [obs]  @TOON v1 ...                                    ││ [ ] Run cargo test            │
│ [stream] Updating range validation...▍                 │├───────────────────────────────┤
│                                                        ││ Services (Sprout)             │
│                                                        ││ [READY] postgres (5432)       │
│                                                        ││ [READY] api      (8080)       │
└────────────────────────────────────────────────────────┘└───────────────────────────────┘
┌─ [BUILD] Goal / Command (Enter send · Tab Plan/Build · F2 Agents · /rewind · /fork …) ──┐
│ > _                                                                                     │
└─────────────────────────────────────────────────────────────────────────────────────────┘

Compact Header (Tabs + Title + Body + Telemetry)

  • Tab strip (top row, right-aligned): F1 Chat · F2 Agents · F3 Sprout · F4 Plan & Diff · F5 Timeline, with the active view in bold white. It ends with Esc:Quit in F1 Chat or Esc:Back in the ephemeral views; when an approval is pending outside F1 Chat, it is replaced by the red [F1 Chat !APPROVAL] badge (blind approval is forbidden: y/n never approve or deny in the other views).
  • Title row: openOnyx [BUILD] [SANDBOX:workspace] · gemini/gemini-2.5-pro (effort:high) — mode badge ([BUILD] / [PLAN] / [EXPLORE]), sandbox badge ([SANDBOX:workspace|strict|off]), the [UNTRUSTED] tag when the workspace is untrusted, and the live LLM target provider/model (effort:low|medium|high|auto), hot-swapped by /profile / /provider / /model / /effort (section 2.1).
  • Body rows:
    • Animated Braille emblem (6×3 sub-pixel canvas, throttled to 90 ms) rotating smoothly while work is in progress (thinking, acting, waiting_children) and resting when idle or awaiting approval.
    • Goal & phase: the focused agent's goal: and phase: with its ID/name/role (#1 openonyx-1 [root]), the [subagents:N · bg:M · F2] (or [N/M agents · F2]) and [queued:N] tags, and — when session saving is active (--auto-save or --snapshot-dir) — the live vault:<session> badge (automatically updated when branching via /fork or /rewind).
    • Agent strip or quick hints: when multiple agents exist, renders a compact single-line agent strip; otherwise shows quick hints.
  • Bottom border (Live Telemetry):
    • Approximate context window fill (ctx: <1% or XX%, plus [compacted] after /compact).
    • Cumulative provider counters: in, cache (prompt cache hits), out, and think (reasoning tokens when reported).
    • Estimated USD cost (~$0.024) for known cloud models, or local when using a custom --api-base.
    • Telemetry lives outside the EAV graph so it never perturbs deterministic ticks, snapshots, or replay.

Memory & Trace Pane & History Navigation

  • Displays the full trace of the focused agent: user prompts, tool calls ([call]), observations ([obs]), model replies, system notes ([system]), and live SSE previews ([stream] ...▍, rendered in pump_idle without advancing ticks).
  • Smooth scrolling: use Up, Down, PgUp, PgDn, Home, End, Ctrl+U, and Ctrl+D even while an approval box is open. Scrolling up shows [SCROLLED -N lines | End to follow]; pressing End or submitting a prompt snaps back to auto-follow.

Automatic Side Panels (>= 100 Columns)

When terminal width is at least 100 columns, the center area splits 70% (Memory & Trace) / 30% (right side):

  • Live Plan: opens automatically when plan_update records steps ([x] done, [>] in progress, [ ] pending).
  • Services (Sprout): opens when a valid sprout.toml exists in the workspace, showing color-coded service states ([READY], [STARTING], [PENDING], [FAILED], [OFF]).
  • When both are active, the right pane splits vertically 50% / 50%.

Approval Box with Colorized Unified Diff (y / n)

Whenever an agent requests a mutating tool (fs_write, fs_edit, shell_exec, service_start, service_stop, service_exec) requiring confirmation:

  • The banner identifies the requesting agent explicitly: [agent #id name].
  • For fs_write and fs_edit (including atomic multi-hunk edits), a colorized unified diff preview is rendered before anything touches disk.
  • Press y to approve or n to deny.
  • Only from F1 Chat: in the ephemeral F2..F5 views, y/n never approve or deny; the tab strip shows the [F1 Chat !APPROVAL] badge to remind you to return to F1 and review the diff and the # impact: line.

2. Tuning Reasoning Effort (--effort)

Control how much internal reasoning budget the model spends:

ValueGemini (thinkingLevel)OpenAI-compatible (reasoning_effort)Recommended Use
lowLOWlowQuick lookups, read-only tasks, lightweight local models
mediumMEDIUMmediumEveryday editing, debugging, and refactors
highHIGHhighArchitecture design, subtle bugs, deep audits

Set via flag or environment variable (precedence: --effort > ONYX_EFFORT > GEMINI_THINKING_LEVEL / OPENAI_REASONING_EFFORT):

openonyx chat --effort high --auto-save
# or via environment variable:
export ONYX_EFFORT=medium

For anthropic: the effort maps to an extended-thinking budget (thinking.budget_tokens: low 2048 / medium 8192 / high 16384 tokens) when no explicit budget is set. You can pin it with --thinking-budget <n> (or ANTHROPIC_THINKING_BUDGET; 0 = off, range 1024..=60000), which also raises max_tokens above the budget. The provider also supports prompt caching (cache_control: ephemeral on the system block and the last tool definition) and automatic retries on 429/529 (chapter 06).

2.1 Hot-Swapping the LLM Target (/profile, /provider, /model, /effort)

Beyond effort, the full LLM target (provider, model, api_base, and effort) is hot-swappable without restarting the session:

  • Profiles: [[llm_profiles]] blocks in .onyx/config.toml (trusted workspace) with id, provider (gemini | openai | anthropic), model, effort, optional api_base, and optional api_key_env. Never literal keys in the file (details in chapter 03).
  • Slash commands: /profile [id] lists or applies a profile, /provider <gemini|openai|anthropic>, /model <name>, and /effort <auto|low|medium|high>. Changes apply at the next tick boundary and are sealed in the ONYXTR2 transcript (deterministic replay).
  • Live header: the title row switches to showing provider/model (effort:...) of the active target instead of the startup one.
  • Ctrl+K palette: a typing-free alternative — filter profiles, providers, and efforts, then run with Enter (LLM actions go through the deterministic bus exactly as if typed; a profile without credentials is shown as unavailable with its reason and is not selectable).
  • Web UI (openonyx serve): the LLM target button (brand subtitle) opens a modal dialog with profile/model/effort and Apply/Cancel buttons, without exposing credentials to the browser.

Credentials never live in the config: each profile resolves its key via api_key_env (or the provider's standard variable → ONYX_API_KEY). A profile missing its key or with a rejected api_base is listed as unavailable with the actionable reason.


3. Multi-Turn Conversations, Active-Root Guard & /new

Automatic Continuation (continue_agent)

Once a turn finishes (Settled), submitting a follow-up prompt reactivates the same root agent via continue_agent, preserving its entire rel_memory with monotonic step counts rather than spawning an amnesic agent.

Follow-Up Prompt Queue While Busy (queued:N)

While the root agent is actively working (thinking, acting, waiting_children, or waiting_approval), you can type your next follow-up and press Enter: instead of racing a second root agent over the workspace, the TUI queues it automatically (queued:N shown in the header and input border, previewed when the input is empty, and clearable anytime with Ctrl+X) and dispatches it the moment the current turn settles. Immediate commands (/agent, /mode, /services, /service, /undo) still execute right away.

/ & @file Autocomplete, Cursor Editing & Input History

  • Visible UTF-8 cursor: edit anywhere inside the prompt using Left, Right, Home, End, Backspace, and Delete.
  • Prompt history: cycle previous prompts with Alt+Up / Alt+Down (or Ctrl+P / Ctrl+N), restoring your unsent draft when returning to the bottom.
  • / popup: typing / at the start of the line opens a floating command menu with short descriptions (↑/↓, Tab/Enter to accept, Esc to dismiss).
  • @ popup: typing @ at the start of a word (e.g. review @tui) fuzzy-filters cached workspace paths (respecting ignored directories and .onyx/vault) and inserts the clean relative path on Tab/Enter.

Starting Fresh (/new)

  • /new: marks the next prompt to spawn a clean root agent with fresh memory.
  • /new <goal>: immediately spawns a fresh root agent with <goal> and auto-focuses it in the TUI.

4. Tiered Context & /compact [focus]

To prevent long sessions from overflowing context windows or burning unnecessary tokens, openonyx uses a shared Tier 0 / Tier 1 / Tier 2 context engine across both Gemini and OpenAI:

  • Tier 0 (Full): the latest 10 tool observations are kept verbatim.
  • Tier 1 (Coordinate-Preserving Summaries): older outputs from fs_read, scent_outline, scent_impact, code_search, glob_files, and shell_exec are deterministically summarized while keeping paths, line ranges, and exit codes, maintaining cache-stable prefixes for prompt caching.
  • Tier 2 (/compact & Auto-Compaction): upon reaching the auto-compact threshold (80% of context budget) or running /compact [focus], CommandSpawnerSystem inserts a verified [session_summary] boundary.
/compact
/compact jwt authentication and middleware

Providing a [focus]:

  1. Rescues files_found and keyword-matched focus_matches from earlier turns.
  2. Drops active ctx: fill immediately on the next turn.
  3. Records a cmd:/compact milestone in snapshots.onyxpack.
  4. Loses nothing: pre-compact ticks remain intact in the graph and snapshots.onyxpack for inspect, replay, and rewind.

5. Modular F1..F5 Views, Ctrl+K Palette & /view

Besides F1 Chat (trace, side panels, input, approvals), the TUI exposes four ephemeral views you can jump to with the function key, /view <name>, or the Ctrl+K palette:

ViewKeySlashContents
F1 ChatF1/view chatMemory & Trace, Live Plan / Services (Sprout) panels, input and approvals
F2 AgentsF2/view agentsGraph agents + async [bg] jobs (with a → <driver> badge when an external CLI harness runs the worktree)
F3 SproutF3/view sproutsprout.toml services (status badges) + live logs of the selected service
F4 Plan & DiffF4/view planActive plan (ws.plan.text) on top + Git effects ledger (tick, tool, target, reversibility, (undone)) below
F5 TimelineF5/view timelinesnapshots.onyxpack milestones (tick, tag, size, checksum) for /rewind / /fork
  • 100% ephemeral navigation: switching views writes nothing to the graph, emits no bus events, and advances no ticks — it is just a different "lens" over the same deterministic state.
  • F2 Agents: Up/Down select (the focused agent carries the * marker), Enter focuses that agent's Memory & Trace and returns to F1 Chat, Esc returns to F1 Chat.
  • F3 Sprout: Up/Down/PgUp/PgDn navigate services; s/x/r/a (start/stop/restart/all) and f (log follow) are gated: in PLAN/EXPLORE mode or with an [UNTRUSTED] workspace the view header shows MUTATIONS BLOCKED and the action is rejected with a notice.
  • F4 Plan & Diff: Up/Down scroll the Git effects ledger.
  • F5 Timeline: Up/Down select a milestone, Enter runs /rewind <tick>, f runs /fork.
  • Esc: closes popups or the palette if open; in F1 Chat it quits cleanly; in F2..F5 it returns to F1 Chat (the tab strip label reads Esc:Quit or Esc:Back).
  • /view <chat|agents|sprout|plan|timeline> (case-insensitive): intercepted at Enter at the TUI level — 0 bus events, 0 ticks, 0 graph writes. /view with no argument shows usage; an unknown name shows a transient notice.
  • Ctrl+K palette: centered popup (Ctrl+K Palette — type to filter) with three groups — VIEW (F1..F5), LLM ([[llm_profiles]] profiles, providers, and efforts) and AGENT (by ID/name). Type to filter (every printable character filters — j/k included, they never navigate), Up/Down (or Ctrl+P/Ctrl+N) select, Enter executes, Esc/Ctrl+K close. It has top priority (except Ctrl+C) and swallows every key while open; LLM actions are sent through the deterministic bus and sealed in ONYXTR2, exactly as if typed.

6. Multi-Agent Workflow: Subagents, F2 Agents View & /agent

The root agent can delegate subtasks in two ways: synchronous graph subagents (spawn_agent, sharing the workspace and awaited by the parent) and asynchronous jobs in isolated Git worktrees (spawn_subagent / /spawn, chapter 05).

  • Safe default step cap: synchronous subagents inherit a default cap of 32 steps (DEFAULT_SUBAGENT_MAX_STEPS, overridable via max_steps in spawn_agent JSON args) to prevent runaway loops in local models. While children are active, the parent enters WaitingChildren.
  • Live inspection with the F2 Agents view: press F2 anytime to jump to the full-screen Agents view:
    • Lists every graph agent (root and subagents) with ID, name, role (root/sub), current state, and goal.
    • Also lists async [bg] jobs with their status (running, done, merged, failed), worktree branch, and — when an external harness runs the job — a → <driver> badge.
    • Up / Down select, Enter focuses the agent's Memory & Trace (back to F1 Chat), Esc returns to F1 Chat.
  • Alternative shortcuts:
    • /agent (or /agents): opens the centered Agent Selector popup (or cycles to the next agent when only one exists).
    • /agent <id|name>: jumps directly to an agent (e.g. /agent 1 or /agent researcher).
    • Ctrl+K: the palette also lists agents; Enter focuses and returns to F1 Chat.
    • Ctrl+Tab: quick-cycles focused agents (terminal-dependent alias; F2, /agent, and the palette work everywhere).
  • External drivers from the Web UI: in openonyx serve, the Subagent driver selector picks a declared [[external_drivers]]; sending free text with a non-native driver makes the browser emit /spawn --driver <id> <text> (chapter 05).

7. Interactive Time Debugger (TimeFreeze, SDD-07)

TimeFreeze lets you pause the session at any tick and step through it without spending tokens or touching disk: tick boundaries live in a RAM ring (on-disk milestones from --snapshot-dir overlay it as references) and the whole state is 100 % ephemeral until you confirm a branch (/go with the cursor anchored in the past creates the fork; nothing is written before that).

Freezing, scrubbing, and getting out

ActionHow
Freeze / unfreeze at the cursorCtrl+T or /time (ephemeral toggle)
Scrub −1 / +1 over available ticksAlt+← / Alt+→ (looking at the past auto-freezes)
Return to present without quitting the appEsc while TIME FROZEN (a second Esc when live: exit)
Jump to a specific tick (milestones [pack:*], [ram], (present))F5 Timeline → Down/Up → Enter

While frozen, the amber banner appears (⏸ TIME FROZEN · tick X / present Y + the files that would be reverted when branching, RAM-only) and plain prompts are blocked: an out-of-order turn would break the bit-for-bit replay. The escape routes (/… and !…) keep working always, even with the agent busy in Thinking (the pre-LLM breakpoint): they run immediately, never queued.

0-token primitives and frozen-graph surgery

CommandWhat it does
/step [n]Advance n deterministic ticks with 0 LLM calls (default 1; works frozen)
/step-llmExactly one LLM turn: gate + branch if needed + re-freeze when it answers
/go (alias /unfreeze)Branch from the cursor if it looks at the past, then resume at present
! <cmd>Run a deterministic shell command in the sandbox and seal the result (0 network, 0 disk)
/read <path> [a..b]Read a file (or line range) into memory, 0 tokens, frozen-safe
/inject <text>Stage a sealed user memory into the timeline (0 tokens)
/graph inspect [agent|mem|ws]Read-only report of the frozen graph (memories with mem_seq, agents, workspace)
/graph drop-mem <seq|a..b>Drop memories by mem_seq without advancing time
/graph edit-mem <seq> <text>Edit an existing memory in place
/graph set-goal <text>Change the root agent's goal inside the frozen graph

These primitives are sealed into ONYXTR2 (/__onyx_det_*): offline replay reproduces them bit-for-bit with 0 I/O and 0 network. The Web/PWA view (openonyx serve) has full parity: the #tick-pill opens the same amber bar, POST /api/v1/time/scrub applies ephemeral scrubs, plain prompts under freeze get an actionable 409 Conflict, and root memories expose ✎/× buttons — see chapter 04.

Non-goal: Sprout (services/containers) and MCP server effects are external process side effects, not graph mutations: TimeFreeze does not rewind them (nor revert them when branching).


8. Quick Reference of Keys & Slash Commands (chat)

Key / CommandAction
EnterSubmit goal, follow-up prompt, or slash command
TabToggle [BUILD] ↔ [PLAN] in place
F1..F5Switch ephemeral view (Chat, Agents, Sprout, Plan & Diff, Timeline)
Ctrl+KOpen the command palette (views + LLM slash commands + agents); type to filter, Enter executes
Ctrl+TabQuick-cycle focused agent (terminal-dependent alias for F2 / /agent)
y / nApprove or deny a pending mutating tool diff (only in F1 Chat; other views hint to press F1)
Up/Down/PgUp/PgDn/Home/End/Ctrl+U/Ctrl+DScroll Memory & Trace history
Alt+← / Alt+→TimeFreeze: scrub the cursor −1/+1 over available ticks (auto-freezes when looking at the past)
Ctrl+TTimeFreeze: toggle freeze at the cursor / return to present (ephemeral, 0 disk)
EscClose popup/palette; while TIME FROZEN return to present without quitting; in F2..F5 back to F1 Chat; in F1 Chat exit cleanly (flushing snapshot & transcript)
Ctrl+CExit cleanly (flushing exit snapshot & transcript, if configured)
/view <chat|agents|sprout|plan|timeline>Switch views from the prompt (ephemeral: 0 bus events, 0 ticks, 0 graph writes)
/agent [id|name]Open agent selector or focus specific agent
/mode [plan|build|explore]Switch mode explicitly or toggle PLAN ↔ BUILD
/undoRevert latest reversible Git checkpoint (also cleans newly created fs_write files)
/rewind [tick]List milestones or rewind live to <tick> into a safe sibling fork
/fork [name]Branch snapshots up to current tick into a sibling directory
/timeTimeFreeze: toggle freeze at the current cursor (ephemeral, 0 disk)
/go (alias /unfreeze)TimeFreeze: branch if the cursor looks at the past, then resume at present
/step [n]TimeFreeze: n deterministic ticks with 0 LLM (default 1; frozen-safe)
/step-llmTimeFreeze: exactly one LLM turn (gate + branch + re-freeze)
! <cmd>Deterministic sandboxed shell with the result sealed into ONYXTR2 (frozen-safe)
/read <path> [a..b]Read a file (or range) into memory, 0 tokens (frozen-safe)
/inject <text>Sealed user memory staged into the timeline, 0 tokens (frozen-safe)
/graph <inspect|drop-mem|edit-mem|set-goal>Read-only inspection or surgery on the frozen graph (memories by mem_seq, goal) without advancing time
/compact [focus]Compact older turns while rescuing focus matches and discovered files
/servicesPrint @TOON v1 status of services defined in sprout.toml
/service <start|stop|logs> <id|all> [tail]Control Sprout services directly from the TUI
/new [goal]Prepare or immediately launch a fresh root agent
/profile [id], /provider <gemini|openai>, /model <name>, /effort <auto|low|medium|high>Hot-swap the LLM target (section 2.1)
/spawn [--driver <id>] <goal>Launch an async job in an isolated Git worktree (chapter 05)
/subagentsList async [bg] jobs (status, branch, touched files)
/merge <job_id>3-way merge the job's worktree (Ask/Deny governance, chapter 03)
/discard <job_id>Cancel the job and remove its worktree and temp branch

← 01. First Steps · English Index · Next: 03. Modes, Permissions & OS Sandbox →

03. Modes, Permissions & OS Sandbox

🇪🇸 Ver este capítulo en Español

openonyx enforces defense in depth across every agent action: workspace modes, declarative .onyx/config.toml rules, read-only Control Plane protection, strict environment sanitization (env_clear()), OS-level sandboxing, and RAII process-tree supervision.


1. Workspace Modes: PLAN, BUILD & EXPLORE

The active mode (ws.mode) lives inside the EAV graph and is recorded in ONYXTR2 transcripts so rewind and replay reproduce it faithfully.

ModeRead / Search / ASTMutations (fs_write, fs_edit, shell_exec, service_start/stop/exec)Best For
BUILD (default)AllowedAllowed with approval (or per .onyx/config.toml rules). fs_edit requires prior fs_read.Implementation, refactoring, running tests.
PLANAllowedUnconditionally blocked (even with allow rules or --auto-approve).Architecture analysis, design planning, PR reviews.
EXPLOREAllowedUnconditionally blocked.Safe read-only exploration of unfamiliar repositories.

Dynamic MCP tools: even though an mcp__<server>__<tool> call may not mutate the local filesystem, a remote MCP server can execute processes or network traffic outside openonyx's control, so it is treated like a mutation and is Deny in PLAN/EXPLORE (section 2.8).

Switching Modes in chat

  • Press Tab to toggle [BUILD] ↔ [PLAN] in place.
  • Or run /mode plan, /mode build, /mode explore (or /mode with no argument to toggle PLAN ↔ BUILD).

2. Declarative Permissions (.onyx/config.toml)

Granular rules are loaded and merged automatically from two locations:

  1. Global user config: ~/.onyx/config.toml
  2. Project config: <workspace>/.onyx/config.toml

Security invariant: project config can never remove a global deny rule defined in ~/.onyx/config.toml.

Precedence: deny > ask > allow

  • deny: blocks the tool unconditionally — even when --auto-approve is active. Only bypassed if you explicitly pass --ignore-deny.
  • ask: requires interactive confirmation (y/n), prevailing over allow at equal or higher specificity.
  • allow: auto-approves matching calls in BUILD mode without interrupting you (PLAN/EXPLORE still block all mutations). A more specific allow (e.g. shell_exec(cargo test*)) overrides a generic wildcard ask (shell_exec(*)).

Complete .onyx/config.toml Example

[permissions]
# Hard blocks (enforced even with --auto-approve)
deny = [
  "shell_exec(rm -rf*)",
  "shell_exec(git push*)",
  "shell_exec(curl*)",
  "fs_write(.env*)",
]

# Auto-approve safe verification commands in BUILD mode
allow = [
  "shell_exec(cargo check*)",
  "shell_exec(cargo test*)",
  "shell_exec(cargo clippy*)",
  "shell_exec(cargo fmt --all -- --check)",
]

# Prompt for all other shell executions and file writes
ask = [
  "shell_exec(*)",
  "fs_write(*)",
  "fs_edit(*)",
]

[sandbox]
# "workspace-write" (default) | "strict-container" | "off"
mode = "workspace-write"
# "offline" (default) | "localhost" | "unrestricted"
network = "offline"
# Extra env vars allowed after env_clear() (never pass API keys)
env_passthrough = ["RUST_LOG", "RUST_BACKTRACE"]
# Additional read-only paths outside workspace (optional)
allow_read_paths = []
# Resource limits for child processes
max_memory_mb = 4096
max_pids = 128
# OCI image when mode = "strict-container" (optional)
# container_image = "rust:1.85-slim"

[impact]
# Scent-Heated Approval: escalates Allow -> Ask when a diff touches public symbols with callers
enabled = true
max_hops = 2          # clamped 1..=4
ask_heat_bp = 2500    # threshold for public scope:src symbols (basis points 0..=10000)
hard_ask_bp = 8000    # hard threshold for any high-fanout symbol

[verify]
# Verify-on-Edit: after each successful fs_edit/fs_write, run the rules whose glob
# matches the edited file (section 2.9). Off by default.
on_edit = true
max_secs = 20         # default per-rule timeout (clamped 1..=120)

[[verify.rules]]
glob = "**/*.rs"
command = "cargo test --workspace"
# max_secs = 60       # per-rule timeout override (optional)

Monotonicity of Scent-Heated Approval: [impact] can only escalate Allow → Ask and display # impact: N callers, H hops, scope:src(pub) [heat Xbp] above the diff in TUI/CLI. It never overrides deny, never relaxes ask to allow, and degrades gracefully to static rules when unindexed or enabled = false.


2.5. Workspace Trust (~/.onyx/trusted_workspaces.toml)

To defend against malicious cloned repositories or untrusted PRs (Indirect Prompt Injection + allow = ["shell_exec(*)"] or arbitrary sprout.toml commands), openOnyx pins blake3 hashes of .onyx/config.toml and sprout.toml per workspace in ~/.onyx/trusted_workspaces.toml:

  • Clean repository (no .onyx/config.toml or sprout.toml): zero friction (no-project-config).
  • Untrusted or modified repository (untrusted / modified, [UNTRUSTED] badge in TUI):
    • Project .onyx/config.toml can only tighten policy (deny/ask, stricter sandbox/impact); project allow rules, env_passthrough, allow_read_paths, container_image, and any [sandbox]/[impact] relaxations are ignored.
    • sprout.toml blocks service execution (service_start, service_exec, stop_cmd) until explicitly approved.
  • Trust commands: openonyx trust (approve current workspace), openonyx trust check, openonyx trust list, openonyx trust revoke, per-run --trust-workspace, or /trust [status|revoke] inside the TUI.

2.6. LLM Profiles ([[llm_profiles]])

The LLM target (provider, model, api_base, effort) can be declared in .onyx/config.toml as [[llm_profiles]] blocks and hot-swapped with /profile / /provider / /model / /effort (chapter 02, section 2.1):

[[llm_profiles]]
id = "local-ollama"
provider = "openai"
model = "llama3.1:70b"
effort = "medium"
api_base = "http://localhost:11434/v1"
# api_key_env = "OLLAMA_API_KEY"
  • Fields: id (unique), provider (gemini | openai | anthropic), model, effort (auto | low | medium | high), optional api_base, and optional api_key_env. Unknown or duplicate keys are an actionable parse error.
  • Never literal keys: a literal api_key in the block is rejected by the parser with an error pointing to api_key_env (and the message never echoes the key value). Credentials are always resolved from environment variables (api_key_env → the provider's standard variable → ONYX_API_KEY).
  • api_base validated at registration: same policy as --api-base (http:// only on loopback; remote hosts require https://; non-official hosts require --allow-custom-auth-host).
  • Trust gate: an untrusted workspace ignores its [[llm_profiles]] blocks and shows the warning ignored N [[llm_profiles]] block(s); run openonyx trust or /trust to approve. With a trusted workspace, precedence is global (~/.onyx/config.toml) < project (merge replace-by-id).
  • Availability: a profile with no resolved key or a rejected api_base is listed as unavailable with the actionable reason (/profile, Ctrl+K palette, and the Web selector). The TUI and Web only expose metadata (public_snapshot): provider, model, effort, reason — never keys.

2.7. External CLI Harnesses ([[external_drivers]])

Async spawn_subagent / /spawn jobs (chapter 05) can run outside the OnYX engine by delegating the work to an external CLI harness declared in .onyx/config.toml:

[[external_drivers]]
id = "opencode"
bin = "opencode"
args = ["run", "--model", "qwen38-27b"]
# prompt_transport = "stdin"        # "stdin" (default) | "arg" | "temp_file"
# prompt_flag = "--prompt-file"     # for "temp_file" (or {prompt_file} placeholder in args)
timeout_secs = 600
allowed_env = []
# inherit_home = true               # if the CLI needs config/OAuth from the real HOME
# network_allowlist = ["api.example.com"]
  • Fields: id (charset [a-z0-9_-]), bin (resolved on PATH/PATHEXT), args (fixed arguments), prompt_transport (stdin recommended and default; arg is rejected on Windows when the binary resolves to a .cmd/.bat wrapper; temp_file for large prompts, kept out of the Git index), prompt_flag, timeout_secs, allowed_env (env whitelist for the child), and inherit_home (default false).
  • Trust gate: an untrusted workspace cannot launch external drivers (absolute Deny: requires a trusted workspace).
  • Default Ask approval: spawn_subagent with an external driver never auto-approves: without explicit ask/allow rules the decision is Ask; you can pin it with allow = ["spawn_subagent(opencode)"] or ask/deny with the same pattern (a deny spawn_subagent(opencode) blocks that driver even with an allow).
  • Process isolation: the prompt is delivered without shell injection (stdin / single argv / temp file); the child environment goes through env_clear() + allowed_env; the process is bound to a ProcessJob at spawn (if timeout_secs elapses or the job is cancelled, the whole tree dies; on Windows there is a taskkill /F /T /PID fallback); and the full log is sealed in .onyx/vault/subagent-logs/<job_id>.log after passing through scrub_secrets.
  • Declarative network (network_allowlist): this is declarative governance: it is enforced in-container only under --sandbox strict-container; under the other profiles it is advisory (doctor tells you so). An empty allowlist means LocalhostOnly; with an allowlist, the sandbox does not inject *_OFFLINE variables (the harness must reach its API).
  • Merge forced to Ask: even if your permissions would auto-approve, subagent_merge for a job with an external driver requires explicit approval (ExternalDriverApprovalPolicy).

2.8. MCP Servers ([mcp.servers.<name>])

openonyx can connect Model Context Protocol (MCP) servers declared in config.toml (global ~/.onyx/config.toml and, with a trusted workspace, <workspace>/.onyx/config.toml):

[mcp.servers.github]
transport = "stdio"
command = "npx"
args = ["-y", "@modelcontextprotocol/server-github"]
# env = { GITHUB_TOKEN = "${GITHUB_TOKEN}" }   # ${VAR} refs expanded at spawn time
timeout_secs = 20            # default 20
# enabled = true             # default true

[mcp.servers.docs]
transport = "http"
url = "https://mcp.example.com/sse"
# headers = { Authorization = "Bearer ${MCP_DOCS_TOKEN}" }
  • Fields: transport ("stdio" with command/args/env, or "http" with url/headers), timeout_secs (default 20 s per JSON-RPC call), and enabled (default true). Server names cannot contain __ (reserved for the mcp__<server>__<tool> prefix). ${ENV_VAR} references are expanded only when the process/request launches (never logged or persisted), and Authorization/X-Api-Key in headers require ${VAR}.
  • Merge & Trust gate: replace-by-name merge with precedence global < workspace; an untrusted workspace ignores its [mcp.servers.*] with the warning MCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust), while the global config always applies.
  • Naming & approval: every discovered tool (tools/list) is exposed to the LLM as mcp__<server>__<tool> with requires_approval = true: it always asks for interactive approval in BUILD unless a more specific allow rule says otherwise (e.g. allow = ["mcp__github__search_repos"] or allow = ["mcp__github__*"]); ask/deny globs work too (deny = ["mcp__*"] blocks all MCP).
  • PLAN/EXPLORE = Deny: in those modes every mcp__* call is unconditionally blocked (a remote server executes processes/network outside the sandbox).
  • Failure isolation: a dead server never aborts the session: it is reported as [openOnyx mcp] server \` unavailable: ...and the rest of the session continues; each server exposes its status foropenonyx doctor`.
  • stdio session safety: JSON-RPC 2.0 with a dedicated reader thread, a real per-call timeout (mpsc::recv_timeout), a 4 MiB stdout line cap, and ProcessJob process-tree teardown on failure (Windows and Unix).
  • Sanitized output: tools/call results and discovery errors pass through truncate_utf8 + scrub_secrets before reaching the LLM or the transcript.
  • openonyx doctor: audits each declared server with a 5 s-capped handshake (min(timeout_secs, 5)): Connected/Disabled → [CHECK], failure → actionable [ERR] (already scrubbed message), untrusted workspace → [WARN] without workspace discovery.
  • 0-I/O replay: replaying an ONYXTR2 transcript never contacts a server: the mcp__* tools are reconstructed from the transcript itself (extract_mcp_tools_from_transcript), without load_mcp_registry.

2.9. Verify-on-Edit ([verify] / [[verify.rules]])

Verify-on-Edit closes the edit → verify loop inside the agent's turn: after each successful fs_edit/fs_write, openonyx runs the commands whose rules match the edited file and appends the outcome to the tool's observation, so the model can fix the error before the turn ends.

[verify]
on_edit = true        # default false: explicit opt-in, 0 overhead when unset
max_secs = 20         # default per-rule timeout (clamped 1..=120)

[[verify.rules]]
glob = "**/*.rs"      # relative-path glob (compile_glob_regex)
command = "cargo test --workspace"
# max_secs = 60       # per-rule timeout override (optional)

[[verify.rules]]
glob = "src/**"
command = "pnpm test"
  • Rule scope: a rule fires when its glob matches the edited file or (when a Scent index exists) a scope:test file reachable by AST impact within ≤ 2 hops; in an unindexed workspace only the edited path is matched.
  • Execution: every command goes through the same sandbox pipeline as shell_exec (prepare_sandboxed_shell_command + configure_process_isolation + ProcessJob RAII + env_clear() + timeout cancellation + scrub_secrets), with captured diagnostics capped at 4 KiB.
  • Outputs injected into the tool observation:
    • \n[verify: PASS] <N> rule(s) succeeded (<cmds>) — plus impacted_tests: [...] when the Scent index identifies reachable scope:test files;
    • \n[verify: FAIL] <cmd> (exit <code> | timed out after <N>s)\n<diagnostics>\n(Fix the error before finishing the turn.);
    • \n[verify: BLOCKED] <cmd> (denied by [permissions]) — the rule is not executed.
  • [permissions].deny governance: each command is evaluated as shell_exec before running; a deny blocks the rule ([verify: BLOCKED]) and stops the verification loop for that edit.
  • Workspace Trust Gate: merge precedence is global (~/.onyx/config.toml) < workspace (<workspace>/.onyx/config.toml, trusted); an untrusted workspace ignores its [verify]/[[verify.rules]] entirely (with an actionable warning in policy.trust_warnings), while the global config still applies. Trusted workspace rules replace the global set.

3. Read-Only Control Plane Protection

Even in BUILD mode with --auto-approve, onyx-workspace protects sensitive control-plane paths as read-only:

  • .onyx/config.toml (prevents an agent from widening its own permissions or disabling the sandbox).
  • .onyx/vault/** (prevents an agent from deleting or tampering with session snapshots and transcripts).
  • .git/hooks/** and .git/config (prevents arbitrary code injection via Git hooks).
  • .env and .env.* (prevents secret exfiltration or corruption).

This check applies across fs_write, fs_edit, and write inspection on shell_exec.

Governance of the subagent_merge Delta (3-way merge)

When an async job (spawn_subagent / /spawn) is merged with subagent_merge / /merge, the <root>..<merged_tree> delta is classified before anything touches disk:

  • Deny — Control Plane: if the delta touches .onyx/config.toml, .onyx/vault/**, .git/hooks/**, .git/config, or .env*, the entire merge is blocked (a single file blocks the whole delta; it is never applied partially).
  • Ask — governance surfaces: if the delta touches sprout.toml or .github/workflows/**, the merge approval must be explicit (never auto-approved), even if your allow rules cover other tools.
  • Safe: the rest of the delta follows the standard impact-based approval (Scent-Heated Approval).

The merge is 3-way via git merge-tree without moving the workspace's HEAD or index; the verdict is applied to the whole delta.


4. OS Sandbox, env_clear() & RAII ProcessJob

Every shell_exec call (and Sprout local process) runs on top of the shared onyx-workspace/src/sandbox.rs layer.

Sandbox Profiles (--sandbox)

ModeTUI BadgeBehavior
workspace-write (default)[SANDBOX:workspace] (Linux bwrap / macOS sandbox-exec), [SANDBOX:env+job] (Windows), or [SANDBOX:env+pgid]env_clear(), OS write confinement (Linux/macOS), Win32 Job Objects / PGID, memory/PID limits, and offline network by default. On Windows, use strict-container for hard kernel FS/network isolation.
strict-container[SANDBOX:strict]Executes commands inside an OCI container (docker, nerdctl, or podman) mounting the workspace. Ideal for unattended automation.
off[SANDBOX:off]Disables OS sandbox wrapper (WorkspacePolicy, timeout, process cleanup, and Control Plane RO remain active).

Network Policy (--sandbox-net)

PolicyBehavior
offline (default)Blocks outbound network traffic and network commands pre-execution, and sets offline tool hints (CARGO_NET_OFFLINE, PIP_NO_INDEX, NPM_CONFIG_OFFLINE).
localhostAllows loopback traffic (127.0.0.1 / localhost) for testing local APIs or databases started by sprout.toml.
unrestrictedNo outbound network restriction (use only when downloading dependencies).

Automatic Elevation Under --auto-approve

When --auto-approve is passed and config had mode = "off", openonyx automatically elevates the sandbox to workspace-write + offline unless you explicitly pass --sandbox off on the CLI.

Strict Environment Sanitization (env_clear())

Before spawning any child process:

  1. Calls env_clear() and rebuilds a minimal safe allowlist (clean PATH, HOME/USERPROFILE, standard toolchains).
  2. Strips all secret-bearing variables (*_API_KEY, *_TOKEN, AWS_*, etc.), ensuring shell_exec cannot read your GEMINI_API_KEY or OPENAI_API_KEY.
  3. Redirects TMP/TEMP/TMPDIR to a session-scoped temp directory.
  4. Scrubs all captured output through scrub_secrets before returning to the LLM or recording to transcripts.

Platform Drivers & RAII ProcessJob

  • Windows (win32-job): wraps commands in a Win32 Job Object with JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE plus memory/PID limits so timeouts or exiting openonyx cleanly terminate the entire child tree.
  • Linux (bwrap / landlock + PGID): uses Bubblewrap (bwrap) when available and passing a live runtime probe (bwrap_is_usable()). On hosts like Ubuntu 24.04 where AppArmor restricts unprivileged user namespaces, openonyx detects it automatically and falls back safely while keeping env_clear(), offline command blocking, Control Plane RO, and POSIX PGID process-group cleanup.
  • macOS (sandbox-exec + PGID): applies Seatbelt sandbox-exec profiles alongside env_clear() and POSIX process-group cleanup.

Inspect your host's detected sandbox driver and OCI runtime anytime with:

openonyx doctor

← 02. TUI & Daily Workflow · English Index · Next: 04. Time-Travel, Snapshots & Forking →

04. Time-Travel, Snapshots & Forking

🇪🇸 Ver este capítulo en Español

A defining capability of openonyx is that the agent's entire state lives in a deterministic EAV graph that can be snapshotted, inspected, replayed offline, rolled back on disk, and forked without mutating the original timeline.


1. Session Vault (.onyx/vault/) & --auto-save

To keep your repository root free of stray .snaps_* folders, fork siblings, and .tr files, openonyx centralizes session storage inside <workspace>/.onyx/vault/:

<workspace>/.onyx/vault/
├── .gitignore                                  # created automatically with `*`
├── 20261121-103500_qwen3-coder_main/           # created by --auto-save
│   ├── snapshots.onyxpack
│   └── 20261121-103500_qwen3-coder_main.tr
├── 20261121-103500_qwen3-coder_main.fork-t12/  # branch created by /fork or /rewind
├── feat-auth/                                  # --snapshot-dir feat-auth --record chat.tr
│   ├── snapshots.onyxpack
│   └── chat.tr
└── unassigned/                                 # standalone --record solo.tr (no snapshot-dir)
    └── solo.tr

Routing Rules

  • --auto-save (or ONYX_AUTO_SAVE=1): automatically creates <workspace>/.onyx/vault/<YYYYMMDD-HHMMSS>_<model>[_<branch|goal>]/ storing both snapshots.onyxpack and <id>.tr together, shows vault:<id> in the TUI header, and prints the exact openonyx chat --resume <id> command on exit.
  • Short names (no / or \ separators):
    • --snapshot-dir feat-auth → .onyx/vault/feat-auth/
    • --snapshot-dir feat-auth --record chat.tr → places chat.tr inside .onyx/vault/feat-auth/chat.tr.
    • --record solo.tr (without --snapshot-dir) → places it in .onyx/vault/unassigned/solo.tr.
  • Explicit paths preserved verbatim: any absolute path or path containing / or \ (./my-dir, C:\tmp\snaps, ../other) is used as-is.
  • Transparent lookup on read: --resume, inspect, rewind, replay, and doctor check literal paths first and automatically resolve short names inside .onyx/vault/ (and .onyx/vault/unassigned/ for .tr files).
  • Automatic Git & tool isolation: openonyx writes .onyx/vault/.gitignore (*) automatically so git status and /undo Git checkpoints never index vault files, while WorkspacePolicy hides .onyx/vault/ from fs_list/glob_files/code_search and protects it as read-only Control Plane.

2. How snapshots.onyxpack & Milestones Work

Whenever snapshot saving is enabled (--auto-save or --snapshot-dir <dir>), MilestoneSnapshotSystem captures snapshots only at meaningful transitions:

  • init — initial session state.
  • spawn — root agent or subagent creation.
  • approval:<tool> — pending mutating tool approval.
  • tool:<tool> / tool_error:<tool> — tool observation or error.
  • cmd:/agent, cmd:/undo, cmd:/rewind, cmd:/fork, cmd:/compact, cmd:/mode ..., cmd:/new — slash commands.
  • settled, failed, exit — turn completion or clean exit.
  • periodic — optional periodic frames when --snapshot-every <n> is passed.

All milestones are stored in a single append-only compressed container <dir>/snapshots.onyxpack (ONYXPK1 frames with zlib compression, canonical ONYXAG\x01\0 graph payloads, and 64-bit FNV-1a checksums):

  • Crash tolerance: truncated trailing bytes from interrupted writes are safely ignored on read and healed automatically on the next append.
  • Legacy compatibility: older directories containing tick-*.bin files remain readable via transparent fallback.
  • Optional retention: full history is kept by default so every tick stays rewindable; pass --max-snapshots <n> for opt-in sliding-window retention (keeps init + latest n - 1 milestones).

3. Inspecting Sessions (openonyx inspect)

Audit any session with zero API keys and zero disk mutations:

# List all milestones: tick, tag, compressed/raw size, FNV-1a checksum, and Git tree_sha
openonyx inspect feat-auth --list

# Machine-readable JSON output
openonyx inspect feat-auth --list --json

# Inspect the latest milestone or a specific tick
openonyx inspect feat-auth
openonyx inspect feat-auth --tick 24
openonyx inspect feat-auth --tick 24 --json

4. Step-by-Step Rollback (/undo)

Before every fs_write or fs_edit in BUILD mode, WorkspaceToolBridge captures a lightweight Git tree checkpoint using a temporary GIT_INDEX_FILE (git add -A + git write-tree):

  • Never touches HEAD or your commits.
  • Never alters your staging index (git add).
  • Works even in freshly initialized repositories with an unborn HEAD.

Running /undo in openonyx chat:

  1. Marks the latest reversible effect as undone in the EAV graph (ws.effect.undone).
  2. Restores the exact pre-mutation tree_sha on disk (restore_git_tree_checkpoint_for_targets).
  3. Safe cleanup of newly created files: if the undone effect was an fs_write that created a new untracked file, /undo deletes it cleanly without touching unrelated untracked user files.
  4. Invalidates session caches (fs_read and scent_outline) so the agent sees the restored file contents.

5. Live In-Session Forking & Rewind (Inside the TUI)

When running chat with --auto-save, --snapshot-dir, or --resume, you can branch and rewind without leaving the TUI or overwriting the original timeline:

/fork [name] — Branch from Current Tick

/fork parser-experiment
# or omit name (creates <dir>.fork-t<tick>):
/fork
  • Copies all milestones up to the current tick into a sibling directory inside .onyx/vault/.
  • Switches the live SharedPackStore to the new branch and updates the vault:<session> badge in the header.
  • Leaves the original snapshots.onyxpack 100% untouched.

/rewind [tick] — Rewind Live Inside the TUI

# 1. List available milestones with ticks, tags, and Git checkpoints
/rewind

# 2. Rewind to tick 18 (or nearest prior milestone <= 18)
/rewind 18
  • Active-work guard: if any agent is busy or an LLM request is in flight, /rewind refuses to run until settled.
  • Non-destructive by default: automatically forks into <dir>.fork-t18, restores the graph to the target tick, reconciles orphaned disk effects (restoring Git tree + cleaning post-tick fs_write files), and prints a summary in Memory & Trace.

6. CLI Time-Travel & Forking

Resume from Latest Milestone

openonyx chat --resume feat-auth

Resume from a Historical Tick into a Safe Fork

# Creates .onyx/vault/feat-auth.fork-t12 and opens the TUI at tick 12 (original preserved)
openonyx chat --resume feat-auth --tick 12

# Specify a custom fork name inside .onyx/vault/
openonyx chat --resume feat-auth --tick 12 --fork-dir feat-auth-alt

# Equivalent via rewind --interactive / --tui
openonyx rewind feat-auth 12 --interactive
openonyx rewind feat-auth 12 --tui --fork-dir feat-auth-alt

Opt-In In-Place Truncation (--truncate-future)

To intentionally overwrite the original pack discarding ticks after <tick> instead of creating a sibling fork:

openonyx chat --resume feat-auth --tick 12 --truncate-future

Headless Rewind with --dry-run & Transcript Replay

# 1. Preview orphaned effects and Git rollback plan without touching disk
openonyx rewind feat-auth 12 --dry-run

# 2. Rewind and replay deterministically from a transcript (0 HTTP calls)
openonyx rewind feat-auth 12 --transcript chat.tr

7. Transcripts & 100% Offline Replay (ONYXTR2)

Recording with --auto-save or --record <file> writes all LLM decisions, structured tool calls (call_id), slash commands (Tab, /mode, /undo, /compact, etc.), and checkpoint markers ([checkpoint:<head>:<tree>]). The time debugger's 0-token primitives are sealed in the transcript as /__onyx_det_* (shell !cmd, /read, /inject, /step, /step-llm, and /graph surgery): replay reproduces them bit-for-bit with 0 I/O and 0 network (no command is re-executed).

# Record a session in the vault
openonyx chat --auto-save

# Replay offline later (0 network calls, 0 API key, 0 disk writes)
openonyx replay 20261121-103500_qwen3-coder_main.tr --snapshot-dir replay-check

8. Health Audit (openonyx doctor)

After a crash, network interruption, or before a delicate rewind, run:

openonyx doctor --snapshot-dir feat-auth --transcript chat.tr

doctor verifies:

  1. Git worktree health and any stray root *.tr / snaps* artifacts.
  2. Session vault status (.onyx/vault/ sessions, unassigned/ transcripts, and .onyx/vault/.gitignore).
  3. snapshots.onyxpack integrity (ONYXPK1 header, FNV-1a checksums, ONYXAG graph payloads, truncated-tail detection) and legacy tick-*.bin files.
  4. Validity of Git tree_sha objects referenced in the side-effect ledger.
  5. Transcript header and parse integrity (ONYXTR1 / ONYXTR2).
  6. Host OS sandbox driver (bwrap/sandbox-exec/win32-job) and OCI container CLI.
  7. sprout.toml syntax, acyclic DAG, container runtime, and occupied ports (if present).

9. Web Parity: the Time Debugger in openonyx serve

The embedded PWA has full parity with the TUI time debugger (SDD-07 Phase 4A): the same session state feeds both surfaces, so what you do from the browser affects the live session and vice versa.

  • Tick pill: the header shows #tick-pill (an accessible button). Live it reads tick N; under freeze or with the cursor anchored in the past it reads ⏸ X/Y and auto-opens the amber Time Debugger bar (you can close it; it reopens on the next freeze).
  • Amber bar: status (⏸ TIME FROZEN · tick X / present Y / LIVE · tick Y), a slider that snaps to the nearest available tick (purged/future ticks are rejected with an actionable notice), ◀/▶ buttons, Freeze/Present, Step, Step 1 LLM, and Resume — the last three go through the sealed command tunnel (/step 1, /step-llm, /go), not the scrub API: the branch is applied in the session with its gates.
  • Ephemeral API: POST /api/v1/time/scrub (JSON: action: freeze|unfreeze|return_to_present|scrub_to|scrub_delta) mutates only the debugger's RAM state — 0 disk, 0 bus events — and replies with the updated time_debug snapshot. It inherits the Bearer auth and CSRF guard of every /api/v1/* endpoint (401 without credentials, 403 cross-site, actionable 400 for future/purged ticks or unknown actions).
  • Plain prompts under freeze: POST /api/v1/command answers 409 Conflict with an actionable message (Paused in TIME FROZEN: use /go to resume or /inject to stage memory…); /go, /graph …, /inject …, /read …, /step …, /step-llm, /time and !cmd keep working.
  • Memory surgery in the UI: with the root agent frozen, each root memory exposes ✎ (edit via a dialog → flat /graph edit-mem <seq> <text>) and × (delete with confirmation → /graph drop-mem <seq>).
  • Projection preview & revert notice: the Web snapshot carries the full time_debug block (frozen, cursor_tick, present_tick, available_ticks, pending_revert_files from the live graph's effects, 0 I/O) and, with --snapshot-dir + a real LLM target, the bench_hint: a copy-paste openonyx bench --snapshot-dir … --tick … --models provider:model command to compare the live model against a deterministic benchmark from the same cursor (SDD-05 §9.4 synergy).

Non-goal: Sprout and MCP server effects are external process side effects: TimeFreeze (TUI or Web) does not rewind them.


← 03. Modes, Permissions & OS Sandbox · English Index · Next: 05. Tools, Scent, Sprout & Skills →

05. Agent Tools, Scent, Sprout, Skills & Automation

🇪🇸 Ver este capítulo en Español

This chapter catalogs all 24 tools exposed to the agent in openonyx (19 base + spawn_agent + 4 async subagent tools in isolated Git worktrees), explains multi-language AST navigation (onyx-scent 2.0), covers local service & container orchestration (sprout.toml), shows how to customize behavior with ONYX.md / skills, and outlines headless automation (openonyx run) and multi-model benchmarking (openonyx bench).


1. Complete 24-Tool Catalog

Read-Only & Coordination Tools (No Approval Required)

ToolPurposeKey Notes
fs_readRead UTF-8 files (full or 1-based start_line/end_line range).64 KiB limit. Deduplicates unchanged reads (unchanged_since_tick) and overlapping/subset ranges (covered_by:start-end). Emits actionable errors if pointed at binary OnYX artifacts (ONYXTR1/2, ONYXPK1, ONYXAG).
fs_listList workspace directory tree up to max_depth (default 3).Skips external symlinks, .git, target, node_modules, .onyx/vault/, *.tr, *.onyxpack.
glob_filesFind workspace paths matching glob patterns (*, **, ?, [...], {a,b}).Deterministic lexicographical order (or sort_by_mtime). Rejects path traversal.
code_searchLiteral or regex text search across the workspace.Supports case_insensitive, include_glob, exclude_glob, and context_lines (0..=5) with scrub_secrets.
scent_outlinePaginated @TOON v1 AST map of symbols, visibility, and line ranges.Supports Rust, Python, Java, TypeScript (.ts/.tsx/.mts/.cts), JavaScript (.js/.jsx/.mjs/.cjs), Go, and C/C++ (.c/.h/.cc/.cpp/.cxx/.hh/.hpp); incremental blake3 cache + persistent binary .onyx/scent.idx cache + per-session seen_outlines dedup invalidated on edits/shell//undo; filters public_only, exclude_tests, cursor, max_rows (1..=500).
scent_impactSemantic call-impact graph (integer thermal diffusion 0..=10_000 bp, 1..=6 hops).Reveals callers/dependents before refactoring shared symbols.
scent_referencesResolves the exact AST definition of a symbol and its direct cross-references (callers, callees, implementors, type users) as @TOON v1 tuples.target (symbol name, Type::method, or file::symbol); optional public_only, exclude_tests, pagination cursor/max_rows (1..=500).
git_statusRead-only git status --short --branch.Preferred over shell_exec for Git inspection.
git_diffRead-only git diff --no-color with optional path, staged, and context_lines.Passes path strictly after --.
load_skillOn-demand Markdown protocol/guide loader.Searches .onyx/skills/, skills/, ~/.onyx/skills/, plus built-in scent and rust guides.
plan_updateUpdates structured checklist (pending, in_progress, completed).Persisted to ws.plan.text and rendered in the right-hand Live Plan panel.
service_statusReturns @TOON v1 status of all sprout.toml services.Also projected into the Services (Sprout) side panel.
service_logsReads recent lines from a Sprout service ring-buffer (up to 2,000 lines).Lossy UTF-8 decoding + scrub_secrets filtering.
spawn_agentDelegates an independent subtask to a child subagent (WaitingChildren).Default 32-step cap (overridable via max_steps JSON arg). With isolated: true the child works in its own isolated Git worktree (onyx/sub/agent-*) and the root is untouched until the 3-way is applied (section 1.1).

Mutating Tools (Require Approval in BUILD; Blocked in PLAN/EXPLORE)

ToolPurposeKey Notes
fs_writeCreate or overwrite a UTF-8 file.Captures pre-mutation Git checkpoint, shows colorized diff preview, blocked on Control Plane RO.
fs_editUnique exact replacement (old_text/new_text) or atomic multi-hunk edits: [...].Requires prior fs_read. Line-trimmed fallback & relative re-indentation applied in memory before write. Captures Git checkpoint.
shell_execRun a shell command inside the workspace.Configurable --shell-timeout (default 30s), env_clear(), OS sandbox, RAII ProcessJob, scrub_secrets, 32 KiB cap, invalidates fs_read/scent_outline caches.
service_startStart one service (id) or full DAG (all: true) from sprout.toml.Honors depends_on topological order and waits on real probes (ready_port, ready_log, ready_cmd).
service_stopStop one service (id) or all (all: true).Clean teardown via stop_cmd / ProcessJob.
service_execRun a command inside a running container (docker exec / nerdctl exec / podman exec).Applies env_clear(), timeout, and scrub_secrets.

Async Subagent Tools (Isolated Git Worktrees)

Besides spawn_agent (synchronous, same workspace), the agent can launch async jobs that run in isolated Git worktrees (onyx/sub/<job_id> branches) without blocking the root agent:

ToolPurposeKey Notes
spawn_subagentLaunch an async job in an isolated Git worktree.goal required; max_steps default 32 (max 128); optional driver (native by default, or an [[external_drivers]] id — an external driver requires approval or allow spawn_subagent(<driver>), chapter 03). Parallelism capped by --max-subagents <n> (default 3, or ONYX_MAX_SUBAGENTS).
subagent_statusQuery async job status.Optional job_id; shows status, branch, touched files, and summary.
subagent_merge3-way merge the job's worktree into the root workspace (Scent-Heated Merge).git merge-tree without moving HEAD or the index. The only one of the 4 with requires_approval: true. Delta governance: Deny on Control Plane (blocks the whole merge) and Ask on sprout.toml / .github/workflows/** (chapter 03); external drivers force Ask.
subagent_discardCancel the job and remove its worktree and temp branch.If the job is running, cancels the ProcessJob process tree.

TUI slash equivalents: /spawn [--driver <id>] <goal> (launch), /subagents (list), /merge <job_id> (merge), and /discard <job_id> (discard). The full log of each job (job stdout/stderr, sealed through scrub_secrets) is stored in .onyx/vault/subagent-logs/<job_id>.log, and the F2 Agents view (chapter 02) lists the [bg] jobs with their status and → <driver> badge.

External drivers: with driver = "opencode" (or any declared [[external_drivers]]), the job is delegated to an external CLI harness working in the same isolated worktree; process isolation, the Trust gate, and the network policy are documented in chapter 03 (section 2.7).

1.1. spawn_agent(isolated: true) — synchronous children in isolated worktrees

Beyond the async jobs above, spawn_agent accepts the isolated: true argument: the synchronous child (the parent goes WaitingChildren) works in its own isolated Git worktree, so parallel edits by several children never touch the root working tree until merged.

  • Creation: when a pending spawn_agent(isolated: true) is detected, the bridge lazily creates the onyx/sub/agent-<parent>-<child>-<seq> worktree via WorktreeManager (SDD-09) with WorkspacePolicy::for_worktree and NativeOffline networking; creation uses a commit-tree checkpoint of the current working tree, without moving the root HEAD or index. If the workspace is not a Git repo (or Git < 2.38), the parent receives a sticky, actionable error (root untouched).
  • Finalization: when the child terminates (Done/Failed) or vanishes from the graph, the bridge finalizes it unconditionally: it captures the ephemeral commit of the child's final working tree, evaluates the 3-way (git merge-tree, root intact), and records an IsolatedWorktreeResult (Pending/Applied/Discarded/Transferred).
  • Resolution: with a clean 3-way the result is applied to the root (or discarded) sequentially; with conflicts, the worktree is transferred to SubagentManager and the work flows through the normal subagent_status / subagent_merge / subagent_discard path (same approval and governance as spawn_subagent jobs). Result notifications follow the async-job semantics (last_completed_proposals and, with proactive_notifications, an IngressEvent::Command).
  • Cleanup: the worktree is removed on apply/discard, on the bridge Drop, and by the orphaned-worktree pruning in openonyx doctor; the temp branch onyx/sub/<job_id> is always deleted.

Dynamic MCP Tools (mcp__<server>__<tool>)

On top of the fixed catalog above, every MCP server declared in [mcp.servers.<name>] (chapter 03, section 2.8) injects its tools dynamically into the LLM under the name mcp__<server>__<tool>:

  • Discovery at startup: the initialize → tools/list handshake (paginated, max 16 pages) retrieves each tool's name, description, and inputSchema; schemas are normalized before being declared to the provider (Gemini, OpenAI, and Anthropic).
  • Always approval-gated: requires_approval = true on every mcp__* tool: they ask for interactive approval in BUILD (unless a more specific allow rule) and are Deny in PLAN/EXPLORE, exactly like mutations.
  • Isolation & sanitization: a dead server never aborts the session, and results pass through truncate_utf8 + scrub_secrets.
  • 0-I/O replay: under openonyx replay the mcp__* tools are reconstructed from the transcript itself, without contacting any server.

Subagents do not receive mcp__* tools: only the session's root agent sees the MCP registry (worktree jobs do not inherit it).


2. Semantic AST Navigation with onyx-scent (Scent 2.0)

Instead of burning tokens reading entire multi-thousand-line files, openonyx encourages a two-step workflow:

  1. scent_outline: fetches function, struct, trait, class, method, type alias and component signatures, visibility, and exact line ranges in compact @TOON v1 format (paginated via cursor / next_cursor). Repeated calls on unchanged files hit the per-session seen_outlines cache, which invalidates automatically after fs_edit, fs_write, shell_exec, or /undo.
  2. scent_impact / scent_references + fs_read(start_line, end_line): checks the blast radius (or resolves a symbol's exact definition and direct cross-references) before editing public symbols, then reads only the exact lines required.

Languages supported by onyx-scent (Scent 2.0): 7 languages — Rust (.rs), Python (.py), Java (.java), TypeScript (.ts, .tsx, .mts, .cts), JavaScript (.js, .jsx, .mjs, .cjs), Go (.go), and C/C++ (.c, .h, .cc, .cpp, .cxx, .hh, .hpp). In JS/TS it also extracts type aliases (EntityKind::TypeAlias) and components (EntityKind::Component: PascalCase functions with JSX in .tsx/.jsx), and is_callable includes both. For other languages, the agent uses glob_files + code_search v2 + fs_read.

Incremental binary cache .onyx/scent.idx

  • ONYXSCI1: the workspace AST index is persisted to .onyx/scent.idx (machinery ONYXSCI1: magic + version + entries sorted by rel_path + final blake3 checksum) alongside a hygiene .onyx/.gitignore that ignores scent.idx and scent.idx.tmp*; any anomaly (truncated file, wrong magic/version, invalid checksum) is silently ignored and the index is rebuilt clean.
  • Incremental reload: each refresh only re-parses files whose mtime/content changed (hash-verified), so repos with thousands of files update in tens of milliseconds; the file is written atomically (temp file + rename).
  • Excluded from Git artifacts: subagent ephemeral checkpoints (commit-tree) and worktree impact evaluation exclude .onyx/scent.idx* and its .gitignore, so a child's work is never polluted by OnYX's own operational artifacts.
  • scent CLI: the onyx-scent crate (cli feature) exposes the scent binary with outline, impact, and references subcommands (same @TOON v1 output as the agent tools, for direct use in scripts/CI).

3. Local Process & Container Orchestration (sprout.toml)

If your project relies on local services (Docker/Rancher databases, backend APIs, workers, dev servers), add a sprout.toml at the workspace root.

onyx-workspace runs a pure-std supervisor (0 tokio) that validates the dependency DAG (rejecting cycles), starts services in topological order, checks real readiness probes, and tears down all child trees cleanly on exit via RAII ProcessJob.

Modern Format ([runtime] + [services.<id>])

[runtime]
# Optional: "docker" | "nerdctl" | "podman" (auto-detected if omitted)
container_cli = "docker"

[services.db]
name = "Local Postgres"
kind = "container"
cmd = "docker compose up -d postgres"
stop_cmd = "docker compose stop postgres"
logs_cmd = "docker compose logs --tail=100 postgres"
container = "myapp-postgres"
# Optional: run `service_exec` as a specific user (e.g. "1000:1000" or "app")
# exec_user = "1000:1000"
ready_port = 5432

[services.api]
name = "Backend API"
kind = "process"
cwd = "backend"
cmd = "cargo run --bin api"
depends_on = ["db"]
ready_port = 8080
ready_log = "Listening on 127.0.0.1:8080"

The legacy Sprout format ([global] + [[service]] with env_wrapper, dir, debug_port, depends_on, optional, enabled) is also supported.

Interactive TUI Control

  • /services: prints the @TOON v1 service status table into Memory & Trace.
  • /service start <id|all>: starts a service (plus dependencies) or the entire stack.
  • /service stop <id|all>: stops a service or all services.
  • /service logs <id> [tail]: prints recent lines from the service log buffer.
  • On terminals >= 100 columns wide, statuses appear live in the right-hand Services (Sprout) panel, and openonyx doctor audits sprout.toml syntax, DAG cycles, container runtime availability, and occupied ports.

Sandbox network, trust & container note: if the agent needs shell_exec to hit a local Sprout endpoint (e.g. http://127.0.0.1:8080/health), launch with --sandbox-net localhost (or set network = "localhost" in .onyx/config.toml). In addition, when a workspace is not yet trusted (openonyx trust add or /trust), Sprout displays [UNTRUSTED — run /trust] and blocks start, stop, and exec until the current sprout.toml hash is approved (any 1-byte edit revokes trust automatically). container_cli strictly accepts docker, nerdctl, or podman, and optional exec_user runs service_exec as the specified user.


4. Project Instructions (ONYX.md / AGENTS.md)

On startup (chat, run, and live rewind), openonyx automatically loads Markdown rules in order (up to 16 KiB total, filtered through scrub_secrets):

  1. ~/.onyx/AGENTS.md and ~/.onyx/ONYX.md (personal global rules)
  2. <workspace>/AGENTS.md and <workspace>/ONYX.md (project rules)

It also injects a host OS shell hint (Windows PowerShell vs Unix/POSIX) so the model emits valid commands for your machine.

Example <workspace>/ONYX.md:

# Project Conventions
- Always run `cargo test --workspace` after editing Rust code.
- Never edit generated files under `dist/`.
- Keep public API errors concise and actionable.

5. Authoring Custom Skills (SKILL.md)

Rather than bloating ONYX.md on every turn, package domain checklists as on-demand skills. At startup openonyx injects only a compact summary (discover_skills_summary), and the agent loads the full text via load_skill("<name>") only when relevant.

Skill Discovery Priority

  1. <workspace>/.onyx/skills/<name>/SKILL.md (recommended per-project location) or <name>.md
  2. <workspace>/skills/<name>/SKILL.md or <name>.md
  3. ~/.onyx/skills/<name>/SKILL.md or <name>.md (global user skills)
  4. Built-in skills: scent and rust

Example Custom Skill (.onyx/skills/deploy-checks/SKILL.md)

---
name: deploy-checks
description: Pre-deploy verification checklist and safe SQL migration guidelines.
---

# Pre-Deploy Verification

1. Check `git_diff` for destructive migrations lacking a rollback path.
2. Verify `cargo clippy --workspace --all-targets -- -D warnings` passes cleanly.
3. Confirm no staging tokens or internal URLs remain in config files.

Best practices:

  • Include name: and description: within the first 20 lines.
  • Never include real secrets (all content is filtered through scrub_secrets).
  • Keep files well below 64 KiB.

6. Headless Automation & CI (openonyx run)

Run a single goal non-interactively with full vault recording:

# Read-only security/code audit
openonyx run "review git_diff and list potential security regressions" \
  --effort medium \
  --max-steps 32 \
  --auto-save

# Scoped automated fix with offline sandbox
openonyx run "fix clippy warnings and verify with cargo test" \
  --auto-approve \
  --sandbox workspace-write \
  --sandbox-net offline \
  --shell-timeout 120 \
  --auto-save

Even with --auto-approve, [permissions].deny rules in .onyx/config.toml and Control Plane RO protection remain enforced.


← 04. Time-Travel, Snapshots & Forking · English Index · Next: 06. CLI Reference & Troubleshooting →

06. Complete CLI Reference & Troubleshooting

🇪🇸 Ver este capítulo en Español

Quick reference for all CLI subcommands, flags, environment variables, HTTP/SSE resilience, and solutions to common real-world issues on Windows, Linux, and macOS.


1. Subcommand Overview

openonyx chat [OPTIONS] [--resume <dir> [--tick <n>] [--fork-dir <dir>] [--truncate-future]]
openonyx run <goal> [OPTIONS]
openonyx replay <transcript> [--workspace <dir>] [--snapshot-dir <dir>] [--snapshot-every <n>] [--max-snapshots <n>]
openonyx inspect <snapshot_dir> [--tick <n>] [--list] [--json]
openonyx rewind <snapshot_dir> <tick> [--transcript <file>] [--interactive | --tui] [--fork-dir <dir>] [--truncate-future] [--dry-run] [OPTIONS]
openonyx bench --snapshot-dir <dir> --tick <n> --models <list> [--goal <text>] [--verify <cmd>] [--out <file.json>] [--max-steps <n>] [OPTIONS]
openonyx doctor [--workspace <dir>] [--snapshot-dir <dir>] [--transcript <file>]
openonyx trust [--workspace <dir>] [add | list | check | revoke] [--list | --check | --revoke]
openonyx serve [--workspace <dir>] [--bind <ip:port>] [--api-key <key>] [--cors-origin <origin>] [OPTIONS]
openonyx [--help | -h | --version | -V]

2. Complete Flag Table

FlagApplies ToDescription / Default
-w, --workspace <dir>AllTarget workspace directory (default: current working directory).
--provider <gemini|openai|anthropic>chat, run, rewindLLM backend (gemini default; openai for OpenAI/OpenRouter/Ollama/vLLM/LM Studio; anthropic for the native Messages API).
--model <name>chat, run, rewindModel name (defaults: gemini-4-hydrogen on Gemini, gpt-4o on OpenAI, claude-sonnet-4-5 on Anthropic).
--effort <low|medium|high>chat, run, rewindReasoning/thinking effort (thinkingLevel / reasoning_effort; on anthropic it maps to a thinking budget of 2048/8192/16384 unless an explicit budget is set).
--thinking-budget <n>chat, run, rewindAnthropic extended-thinking budget in tokens (0 = off, or 1024..=60000; or ANTHROPIC_THINKING_BUDGET). Raises max_tokens above the budget.
--api-base <url>chat, run, rewindCustom API base URL (http:// allowed only on loopback localhost/127.0.0.1/[::1]; remote hosts require https://).
--allow-custom-auth-hostchat, run, rewindExplicit opt-in to send API keys to non-official remote HTTPS endpoints (or ONYX_ALLOW_CUSTOM_AUTH_HOST=1).
--trust-workspacechat, run, rewind, serveTrust the current workspace in memory for this run (without writing ~/.onyx/trusted_workspaces.toml).
--bind <ip:port>serveHTTP/SSE bind address (default: 127.0.0.1:8787; non-loopback requires explicit --api-key >= 16 chars).
--api-key <key>serveAPI key for authentication (HttpOnly cookie or Authorization: Bearer; randomly generated on loopback if omitted).
--cors-origin <url>serveExplicit allowed browser origin for external SPAs (e.g. Svelte dev server http://localhost:5173; never *).
--sandbox <off|workspace-write|strict-container>chat, run, rewindOS sandbox profile for shell_exec (default: workspace-write).
--sandbox-net <offline|localhost|unrestricted>chat, run, rewindSandbox network policy (default: offline).
--auto-approvechat, run, rewindSkip interactive approvals for mutating tools (deny rules still apply; sandbox elevates off → workspace-write + offline unless --sandbox off).
--ignore-denychat, run, rewindExplicitly bypass [permissions].deny rules from .onyx/config.toml.
--max-steps <n>chat, runMax root agent steps per turn (default: 128 in chat, 64 in run; subagents capped at 32 by default).
--max-subagents <n>chat, run, serve, rewind --interactiveMax parallel async subagent Git worktrees (default: 3, or ONYX_MAX_SUBAGENTS).
--shell-timeout <secs>chat, runTimeout in seconds per shell_exec command (default: 30s).
--auto-savechat, runAuto-create .onyx/vault/<YYYYMMDD-HHMMSS>_<model>[_<branch|goal>]/ storing both snapshots.onyxpack and <id>.tr together (or ONYX_AUTO_SAVE=1).
--record <f>, --save-transcript <f>chat, runSave deterministic ONYXTR2 transcript (short names go inside --snapshot-dir, or .onyx/vault/unassigned/ if no snapshot dir).
--snapshot-dir <dir>chat, run, replay, doctorSnapshot directory for snapshots.onyxpack (short names resolve under .onyx/vault/<dir>/).
--snapshot-every <n>chat, run, replayAlso capture periodic periodic milestones every <n> ticks.
--max-snapshots <n>chat, run, replayOpt-in sliding-window retention (keeps init + latest n - 1 milestones).
-r, --resume <dir>chatResume from latest milestone (or --tick <n>) in <dir> (resolves short names in .onyx/vault/).
--tick <n>inspect, chat --resumeSpecific tick to inspect or resume/fork from.
--fork-dir <dir>chat --resume --tick, rewind --interactiveDestination directory for forked snapshots (short names resolve under .onyx/vault/).
--truncate-futurechat --resume --tick, rewindOpt-in destructive truncation: overwrite source pack in place instead of creating a sibling fork.
--interactive, --tuirewindOpen interactive TUI at the restored tick instead of running headless.
-l, --listinspectList all stored milestones with tags, sizes, FNV-1a checksums, and Git checkpoints.
--jsoninspectEmit machine-readable JSON output.
--transcript <file>rewind, doctorReplay transcript from rewind tick (rewind) or validate transcript (doctor).
--dry-runrewindPreview orphaned effects and Git rollback plan without modifying disk.
--models <list>benchComma-separated candidate list: <provider>:<model> (live LLM, e.g. gemini:gemini-2.5-pro,openai:gpt-4o) and/or replay:<label>=<file.tr> / replay:<file.tr> (offline ONYXTR2 transcript, deterministic).
--verify <cmd>benchVerification command executed sandboxed inside the candidate's worktree after it settles (same pipeline as shell_exec); its exit 0 decides passed_verify. Without --verify, passed_verify = agent finished Done and the session settled.
--out <file.json>benchWrite the full pretty-printed JSON report (metadata + results).
--goal <text>benchRoot agent goal when no agent is active at --tick (required in that case).
-h, --help / -V, --versionGlobalPrint help or version and exit 0.

openonyx bench — full reference

Multi-model benchmark from an identical snapshot: every candidate runs in a throwaway worktree (bench-<pid>-<idx>-<label>) rewound to --tick (reconcile_rewind_effects_report), with a fresh session host (request_restore + 1 step); afterwards the root and HEAD remain 100 % intact and the worktree is removed (RAII guard; also on error or panic).

# Live + offline replay comparison, with verification and a JSON report
openonyx bench \
  --snapshot-dir .onyx/vault/20261125-100000_gpt-4o \
  --tick 12 \
  --models "gemini:gemini-2.5-pro,openai:gpt-4o,replay:baseline=run_baseline.tr" \
  --goal "fix the failing test in src/app.rs" \
  --verify "cargo test --workspace" \
  --out bench_report.json \
  --auto-approve \
  --sandbox workspace-write \
  --sandbox-net offline
  • Candidates (--models): <provider>:<model> with provider ∈ gemini|openai|anthropic (credentials via the usual GEMINI_API_KEY/OPENAI_API_KEY/ANTHROPIC_API_KEY variables or --api-base); replay:<label>=<path.tr> sets the label explicitly; replay:<path.tr> uses the file stem as the label. Parsing splits on : first, then =, so Windows drive-letter paths (replay:C:\runs\a.tr) survive intact.
  • Per candidate (sequential): rewind the worktree to the tick → fresh restored host → if no agent is active at the tick, spawn a root agent from --goal → run until settled (internal 256-tick cap) with real telemetry (tokens/cost) for live candidates (replay: tokens/cost 0).
  • --auto-approve: for unattended runs on disposable worktrees: each candidate runs only inside its own worktree and the root is never touched; [permissions].deny still applies.
  • Output: a 9-column Markdown table on stdout — | model | passed_verify | ticks | tool_calls | input_tokens | cached_tokens | output_tokens | estimated_cost_usd | wall_time_ms | — plus, with --out, the JSON report (metadata with snapshot/tick/models/verify + per-candidate results with every column).
  • Reused flags: --workspace <dir>, --sandbox <off|workspace-write|strict-container>, --sandbox-net <offline|localhost|unrestricted>, --shell-timeout <secs>, --trust-workspace, --api-base <url>, --allow-custom-auth-host, --effort <low|medium|high>, --thinking-budget <n> (a live candidate determines its own provider:model).
  • Actionable validation: missing --snapshot-dir/--tick/--models produces an error naming the missing flag; unknown provider → unsupported provider ... (expected gemini, openaioranthropic); a missing snapshot store → floor warning, not an error.

3. Environment Variables

VariableProviderDescription
ONYX_PROVIDERAllDefault provider (gemini | openai | anthropic).
GEMINI_API_KEYGeminiGoogle AI Studio API key (fallback: ONYX_API_KEY).
OPENAI_API_KEYOpenAIAPI key for --provider openai (fallback: ONYX_API_KEY; optional with local --api-base).
ANTHROPIC_API_KEYAnthropicAPI key for --provider anthropic (fallback: ONYX_API_KEY).
ONYX_API_KEYAllShared fallback key if provider-specific key is unset.
ONYX_MODELAllDefault model override (fallbacks: ONYX_GEMINI_MODEL, OPENAI_MODEL, ANTHROPIC_MODEL).
ONYX_EFFORTAllDefault reasoning effort (low | medium | high; fallbacks: GEMINI_THINKING_LEVEL, OPENAI_REASONING_EFFORT; on Anthropic, ANTHROPIC_THINKING_BUDGET governs thinking).
ONYX_AUTO_SAVEBothEnable --auto-save by default (1 | true | yes | on) storing sessions in .onyx/vault/.
ONYX_MAX_SUBAGENTSBothMax parallel async subagent worktrees (used when --max-subagents <n> is omitted; default: 3).
GEMINI_API_BASEGeminiCustom Gemini API base URL.
OPENAI_API_BASE / OPENAI_BASE_URLOpenAICustom OpenAI-compatible API endpoint (default: https://api.openai.com/v1).
ANTHROPIC_API_BASEAnthropicCustom Anthropic API base URL (default: https://api.anthropic.com).
ANTHROPIC_THINKING_BUDGETAnthropicExtended-thinking budget in tokens (0 = off, or 1024..=60000); takes precedence over the --effort-derived budget.

LLM, driver & MCP config in config.toml: beyond flags and environment variables, .onyx/config.toml accepts [[llm_profiles]] (chapter 03, section 2.6), [[external_drivers]] (chapter 03, section 2.7), and [mcp.servers.<name>] (chapter 03, section 2.8) blocks. A profile's key resolves in the order api_key_env → the provider's standard variable → ONYX_API_KEY.


4. HTTP/SSE Resilience on OpenAI, vLLM & Corporate Proxies

Local inference servers and proxies (vLLM, LiteLLM, nginx, Cloudflare) occasionally close chunked SSE streams abruptly right after emitting finish_reason or return transient errors (408, 429, 500, 502, 503, 504, or brief transport drops).

open-onyx/src/openai.rs builds in two automatic safeguards:

  1. Completed-SSE EOF tolerance: if a chunk decode error happens after finish_reason / [DONE] with complete assistant content or tool_calls, the response is accepted cleanly instead of failing the turn.
  2. Automatic transient retries with backoff: retries transient transport/408/429/5xx/stream errors up to 2 times (400ms, 1200ms) before surfacing an error to the agent.

The native open-onyx/src/anthropic.rs adapter applies the same retry policy (408, 429, 500, 502, 503, 504, and Anthropic's own overloaded_error 529), honoring the retry-after header when the server sends it.


5. Common Troubleshooting

1. GEMINI_API_KEY environment variable is not set

  • For Gemini: set GEMINI_API_KEY (PowerShell: $env:GEMINI_API_KEY="..."; bash/zsh: export GEMINI_API_KEY="...").
  • For Ollama / vLLM / LM Studio: pass --provider openai --api-base http://localhost:11434/v1 --model <model> (no API key needed).
  • For inspect, replay, rewind --dry-run, and doctor: no API key is ever required.

2. Agent attempts to read a .tr, .onyxpack, or tick-*.bin file with fs_read

fs_read detects binary OnYX headers (ONYXTR1, ONYXTR2, ONYXPK1, ONYXAG) and returns an actionable error pointing the agent to openonyx inspect / openonyx replay.

3. shell_exec fails with an offline/network error during cargo build or curl

The default sandbox policy is --sandbox-net offline (also injecting CARGO_NET_OFFLINE=true):

  • To reach local Sprout services (127.0.0.1): pass --sandbox-net localhost.
  • To fetch crates or internet resources: pass --sandbox-net unrestricted.

4. Ubuntu 24.04+: bwrap cannot create unprivileged user namespaces (AppArmor)

Ubuntu 24.04 restricts unprivileged user namespaces via AppArmor. openonyx probes bwrap_is_usable() at runtime and automatically falls back cleanly so shell_exec keeps working. Verify your host driver with openonyx doctor.

5. Ctrl+Tab does not switch agents in my terminal

Some terminal emulators (Windows Terminal, tmux, SSH) swallow Ctrl+Tab. Use the F2 key (which now opens the Agents view, chapter 02) or /agent [id|name], which work across all terminals.

6. /rewind refuses to run while an agent is busy

Live /rewind <tick> requires no active agents (thinking, acting, waiting_children) and no in-flight LLM calls. Wait for Settled, or quit with Esc and run openonyx chat --resume <session> --tick <n>.

7. Windows PowerShell quoting or bash-isms in shell_exec

openonyx tells the model the host OS (Windows PowerShell vs Unix/POSIX), and you can reinforce in <workspace>/ONYX.md to prefer native tools (code_search, glob_files, fs_read, git_diff) over shell commands.

8. Unexpected crash during a long session

  1. Run openonyx doctor --snapshot-dir <session> to check for any truncated tail bytes in snapshots.onyxpack.
  2. Inspect intact milestones with openonyx inspect <session> --list.
  3. Resume with openonyx chat --resume <session> — truncated tail bytes are safely ignored on read and healed automatically on the next append.

9. openonyx doctor warns or errors on an external driver ([[external_drivers]])

doctor audits the [[external_drivers]] declarations (chapter 03, section 2.7):

  • Built-in opencode preset: [WARN] when the opencode binary is not on PATH (the preset is skipped).
  • Declared driver whose bin is missing: [ERR] — /spawn --driver <id> will fail at runtime.
  • bin found but the --version probe (3 s deadline, sanitized environment) times out: [ERR]; if it errors out instead (e.g., wrong flags): [WARN].
  • prompt_transport = "arg" on Windows: [WARN] when the binary resolves to a .cmd/.bat wrapper (rejected at spawn time).
  • network_allowlist without --sandbox strict-container: [WARN] — the allowlist is advisory outside strict-container; a declared driver without network_allowlist is LocalhostOnly unless the sandbox relaxes it.

10. An MCP server does not connect, or [mcp.servers.*] is ignored

openonyx doctor audits the servers declared in [mcp.servers.<name>] (chapter 03, section 2.8) with a 5 s-capped handshake (a dead server can never hang doctor):

  • Connected or Disabled: informational [CHECK].
  • Failed(...) (missing binary, handshake timeout, server error): actionable [ERR] with an already-scrubbed message; the session keeps running without that server (failure isolation).
  • Untrusted workspace with project [mcp.servers.*]: [WARN] MCP config in ... ignored: workspace is not trusted (use --trust-workspace or openonyx trust) — approve with openonyx trust or use --trust-workspace.
  • mcp__* tools always ask for approval in BUILD and are Deny in PLAN/EXPLORE; to auto-approve them, declare allow = ["mcp__<server>__*"] in .onyx/config.toml (trusted workspace).

11. The Web (or the TUI) rejects my prompt: 409 Conflict / "Paused in TIME FROZEN"

That is the TimeFreeze guard (chapter 04, section 9): the session is frozen (an active time breakpoint) and an out-of-order plain prompt would break the bit-for-bit replay. It is not a bug — these are the escape routes:

  • /go (or /unfreeze): branches if the cursor looks at the past, then resumes at present.
  • /inject <text> / /graph … / /read … / /step [n] / /step-llm / ! <cmd>: keep working under freeze (sealed 0-token primitives).
  • In the Web, the amber bar (press #tick-pill) has a Resume button; in the TUI, Esc returns to present without quitting and Ctrl+T toggles the freeze.
  • On POST /api/v1/command the 409 carries the full actionable message; a 400 on POST /api/v1/time/scrub means a future/purged tick or an unknown action (the body explains it).

← 05. Tools, Scent, Sprout & Skills · Back to English Index