Skip to content

Architecture of `one`

one.core.temperature defines the named presets and 0.0–1.2 normalization. AgentSession owns and persists effective numeric temperature. Supported adapters receive it as OpenAI temperature, Gemini generationConfig.temperature, or Ollama options.temperature; Anthropic and Codex omit it and emit an additive warning. Child sessions resolve numeric override, named override, then parent inheritance into isolated state.

██████╗ ███╗ ██╗███████╗
██╔═══██╗████╗ ██║██╔════╝
██║ ██║██╔██╗ ██║█████╗
██║ ██║██║╚██╗██║██╔══╝
╚██████╔╝██║ ╚████║███████╗
╚═════╝ ╚═╝ ╚═══╝╚══════╝

Full TUI logo artwork

Internal architecture of the autonomous terminal agent one — components, data flows, contracts, and extension points.

Audience: contributors, reviewers, and agents inspecting the codebase. This document is derived from the source tree at commit HEAD; verify against the code if any detail has drifted.

one is a Python 3.12+ application distributed as one-agent (import and console-script name are one). It provides four user-visible interfaces (TUI, text, JSON, RPC) plus a headless one run subcommand. Explicit TUI mode uses a Textual-owned UI loop and a dedicated agent-runtime worker loop; other modes retain their established session ownership.

one/modes/tui_transcript.py provides the stream widget’s Textual line API. The TUI model owns bounded logical lines and stable line IDs; the widget keeps a row-offset index and wraps Content only when Textual requests a visible row. Rows are cached by line identity and invalidated on a line change, resize, or theme change. This avoids rebuilding one aggregate Content/Static visual for every stream delta while retaining trusted generated @click metadata. Its content property is an inspection compatibility view only, never the paint path. The logo remains a sibling above this virtual transcript in the existing scroll container.

┌──────────────────────────────────────────────────────────┐
│ one/cli/main.py │
│ entry point · arg parsing · provider registry │
│ · session/runtime wiring · mode dispatch │
└──────────┬──────────────────────────────┬────────────────┘
│ │
┌──────▼──────┐ ┌────────▼────────┐
│ one/modes/ │ │ one/modes/run_ │
│ tui_mode.py│ │ mode.py │
│ text mode │ │ (headless) │
│ json mode │ │ │
│ rpc mode │ │ │
└──────┬──────┘ └────────┬────────┘
│ │
┌──────▼──────────────────────────────▼────────┐
│ one/core/agent_session.py │
│ synchronous event-emitting loop · tool │
│ dispatch · compaction · steering queue │
└──────┬──────────────────────────────┬────────┘
│ │
┌──────▼──────┐ ┌────────▼────────┐
│ one/tools/ │ │ one/providers/ │
│ 14 tools │ │ adapters │
└──────┬──────┘ └────────┬────────┘
│ │
┌──────▼──────────────────────────────▼────────┐
│ one/core/session_manager.py · evidence │
│ sidecars · JSONL persistence │
└──────────────────────────────────────────────┘

File: one/cli/main.py

The CLI entry point:

  1. Parses arguments with typer (one/cli/args.py), including --mode (tui, text, json, rpc), --provider, --model, --image, --json, --no-extensions, --no-mcp, and positional task messages.
  2. Builds the provider registry via build_provider_registry() which constructs adapters for every known backend.
  3. Creates AgentSessionRuntime (session factory, switching, forking, model restoration).
  4. Dispatches to the selected mode:
Mode File Characteristics
tui one/modes/tui_mode.py Textual-based TUI with streaming, slash commands, keyboard shortcuts, session history
text one/modes/print_mode.py One-shot positional messages → final assistant text
json one/modes/jsonl.py One-shot positional messages → {"messages": [...]} session dump
rpc one/modes/rpc_mode.py Long-lived JSON-lines stdin/stdout protocol; no startup banner
one run one/modes/run_mode.py Headless autonomy loop; --json emits {"summary":"...","goalSuccess":true,"finished":true}

The default mode (when none is specified) is tui.

File: one/core/agent_session.py

AgentRuntimeFacade and ThreadedAgentRuntime own the TUI execution loop. TuiRuntimeHost creates providers, MCP clients, extensions, storage, and the current AgentSession on that owner loop. TuiSessionView, on Textual’s loop, holds copied bounded snapshots only and sends commands through the facade. It never owns a live session, provider, future, or approval waiter.

The facade has a bounded event queue and byte budget. It coalesces compatible text deltas, preserves lifecycle barriers, and applies backpressure before moving work to the bounded UI accumulator. Control commands use their own runtime submission path. The UI drains a limited item/time slice and schedules transcript paint at most once per frame; an active assistant block is capped at 8 KiB before wrapping/formatting (full content remains in session history and evidence). Cached sidebar/Git and transcript projections avoid history scans on input/paint paths. The offline R6 report records paint/render p99 and count, the maximum measured event-loop block across key, wheel, input-refresh, paint, drain, and sidebar work, and retains targets of no ordinary stall above 250 ms and reduction-slice p99 at most 8 ms.

The offline profiler exercises the detached TuiSessionView/runtime-facade route under bounded delta floods, child invalidations, slow worker I/O/Git stubs, and CPU contention with an independent 10 ms heartbeat and a real wheel / key at gate 40 (virtual driver — not real llama.cpp, not a physical terminal). Spinner idle ticks = 0; transcript renders; cache entries 490 / 490 / 490 / 492 at delta budgets 10 / 20 / 40 / 80.

Phase p99 UI loop p99 render max loop max render
Before renderer rewrite 232.974 ms 242.624 ms 251.082 ms —
After full geometry / cache / status fixes 24.888 ms 13.705 ms 84.577 ms 32.616 ms

Gate targets (one per trial):

Gate Target Latest Verdict
UI lag p99 ≤ 50 ms 24.888 ms met
Render p99 (strict) ≤ 8 ms 13.705 ms not met

Other trials vary — the strict render p99 ≤ 8 ms target is not claimed solved universally or at comfort.

This is concurrency isolation, not sandboxing: runtime code, extensions, MCP servers, and tools still run with agent permissions. Threads share the process, memory, and Python GIL, so CPU-heavy Python work can still delay UI scheduling; the offline R6 profiler records this as a gate result rather than claiming that threads guarantee latency. Worker shutdown/drain cannot safely kill arbitrary running work. No Textual widget may be touched from the runtime thread.

Lifecycle telemetry uses a dedicated monotonic clock. Durable timing entries record nonnegative integer elapsedMs for whole turns, attempts, provider requests, and tool handling; these correlation-only entries are retained in session history but are never replayed into provider context. turn spans the whole prompt (including approvals, retries, backoff, and compaction), while attempt ends before later retry backoff. Tool timing starts after approval, so rejected calls are zero. Entries accept only the documented scope/outcome enums and a correlation-only metadata whitelist; invalid values are rejected rather than silently reclassified. Outcomes are success, error, timeout, cancelled, rejected, or budget_exceeded.

SessionManager.get_lifecycle_timing_stats() traverses only the active branch, so it retains shared ancestry through compaction but excludes sibling work. It reports independent per-scope aggregates for turn, attempt, provider_request, and tool; no timestamp is inferred for older entries. Malformed measurements and unknown outcomes are ignored to preserve the stable public outcome set. The TUI renders validated completed-tool elapsed values and emits one validated whole-turn summary at agent_end, accumulating uniquely identified, turn-scoped provider requests across retries.

Provider-reported token counters (inputTokens, cachedTokens, outputTokens, reasoningTokens) are stored as typed integers on the same provider_request timing entries; missing counters are omitted, never written as zero. SessionManager.get_provider_cache_stats() summarizes the active branch as providerCache in get_session_stats(), including per-provider and per-purpose groups. Totals sum reported values only; cacheRatio covers requests that reported both input and cached counts, and ratioRequests / usageComplete expose that coverage.

The AgentSession class is the central component. It implements a synchronous event-emitting loop that:

  1. Builds context — compacts conversation history if the token budget is exceeded, loads skill metadata, system prompt fragments, and tool definitions.
  2. Invokes the provider — serializes messages into the provider’s expected format and receives streaming text, tool calls, or structured output.
  3. Dispatches tool calls — parses provider output (JSON-in-text format or provider-native structured calls), validates arguments against registered schemas, and executes the matching tool function.
  4. Emits events — tool_call_start, tool_call_end, message_start, message_end, turn_start, turn_end, agent_start, agent_end, etc.
  5. Handles steering — processes queued steering messages at provider boundaries.
  6. Manages compaction — generates rolling summaries when history exceeds the configured threshold.

Key configuration:

  • maxSteps — maximum number of tool steps (0 = unlimited).
  • tools.timeoutSec — default per-tool timeout (30s).
  • compaction settings — threshold for automatic summary generation.

Tools are registered in one/tools/index.py. Each tool has a name, description, and function. Dispatch happens in AgentSession._run_tool_call():

  1. Match the tool name against all_tools.
  2. Validate arguments against the schema in resource_loader.py.
  3. Call tool.execute.before extension hooks (can deny the call).
  4. Execute the tool function with validated arguments.
  5. Call tool.execute.after extension hooks.
  6. Emit tool_call_start and tool_call_end events.
  7. Store results in self.messages (bounded to 12,000 chars) and write complete evidence to the session sidecar.

The event system (one/core/event_bus.py) emits typed events that external consumers (TUI, RPC, diagnostics) rely on. The contract is stable:

  • Events are additive; new events must not change existing payloads.
  • Event sequences are tested via tests/test_event_snapshots.py.
  • Every tool call produces a tool_call_start followed by tool_call_end.
  • Every turn produces turn_start and turn_end.
  • Every agent session produces agent_start and agent_end.

Directory: one/providers/

Provider adapters serialize messages into the expected format and deserialize responses. The registry maps provider names to adapter instances.

Name Adapter Notes
openai OpenAICompatibleAdapter OpenAI-compatible REST API
anthropic AnthropicAdapter Anthropic Messages API; supports cache_control breakpoints
gemini GeminiAdapter Google Gemini API
chatgpt CodexResponsesAdapter ChatGPT/Codex subscription (Responses API)
openrouter OpenAICompatibleAdapter OpenRouter gateway (reasoning_mode="openrouter")
ollama-cloud OllamaCloudAdapter Ollama Cloud API
llama.cpp OpenAICompatibleAdapter Local llama.cpp server (no API key, supports_reasoning_effort=False)
ollama OpenAICompatibleAdapter Local Ollama server (no API key)
xai, deepseek, mistral, groq OpenAICompatibleAdapter Various OpenAI-compatible backends
azure-openai OpenAICompatibleAdapter Azure OpenAI (only when AZURE_OPENAI_BASE_URL is set)

All adapters inherit from ProviderAdapter (one/providers/base.py) and implement:

  • invoke(messages, tools, ...) — send a request and return structured output.
  • is_vision_capable(model) — check if the model supports image input.
  • get_capabilities(model) — return capability metadata (vision, tool calls, etc.).

Native structured tool calls (OpenAI function calling, Anthropic tool use, Gemini tool calls) are absorbed into a normalized {id, name, arguments} shape that the session loop treats identically to JSON-in-text parsed calls.

Image attachments are stored in the blob store (one/core/attachments.py) using content-addressed hashing. Supported formats: PNG, JPEG, WebP. Each adapter serializes images differently:

  • OpenAI-compatible: image_url parts in message content.
  • Anthropic: image content blocks with source (base64).
  • Gemini: inline_data parts with MIME type.
  • Codex Responses: input_image parts with base64 data URI.

Images are rejected before any HTTP request if:

  • The model lacks vision capability.
  • The blob is missing, corrupt, or exceeds size limits.
  • The mode does not support images (e.g., steer/follow-up are text-only).

Directory: one/tools/

There are 14 registered tools:

Tool Description Category
read Read file contents Read-only
read_image Load image for vision inspection Read-only
bash Execute shell commands Mutating (with timeout)
edit Exact-string file replacement Mutating
write Write/overwrite files Mutating
grep Search file contents Read-only
find Find files by pattern Read-only
ls List directory contents Read-only
web_connect Fetch and extract an HTTP(S) URL (GET) Network access; GET may have side effects
evidence_read Read durable evidence by ID Read-only (session-scoped)
finish End the task with summary Terminal
plan Store an execution plan Utility
ask_user Ask the human a question Interactive
spawn_subagent Delegate subtask to subagent Concurrent
apply_patch Apply OpenCode patch format Mutating
  • Coding tools: read, read_image, bash, edit, write, apply_patch.
  • Inspection tools: read, read_image, grep, find, ls, web_connect. web_connect is available in Default and Readonly, but network access is not sandboxed: localhost/private services may be reachable and GET may have side effects. Readonly is not a network sandbox.
  • Mutating tools: subject to cooperation approval when enabled.

Every tool result is stored as a durable evidence record:

  • The bounded preview (≤12,000 chars) goes into self.messages for provider context.
  • The complete raw result is written to a sidecar JSONL file keyed by a session-scoped evidence ID.
  • The model can retrieve the full evidence via evidence_read using the evidence ID from the preview.

File: one/mcp/client.py

MCP clients connect to external tool servers via:

  • stdio transport: spawn a subprocess and communicate via stdin/stdout.
  • Streamable HTTP transport: connect to an HTTP endpoint.

Servers are configured in .one/settings.json under mcpServers. Features:

  • Automatic tool discovery and registration.
  • Server recovery after unexpected exit (stdio) or failed connections (HTTP).
  • restart, restartDelaySec, maxRestartAttempts, restartExhaustion configuration per server.
  • Server tools are removed immediately on failure and restored on reconnect.

Directory: one/resources/

Extensions are Python files that export a register(ctx) -> hooks function. They are discovered from:

  1. <agent_dir>/extensions/ — global extensions (default: ~/.config/one/extensions/).
  2. <cwd>/.one/extensions/ — project-local extensions.
  3. --extension <path> — explicit paths (repeatable).

Hooks include:

  • tool.execute.before — can modify arguments or deny the call.
  • tool.execute.after — observe outcomes.
  • chat.message — intercept user messages.
  • experimental.session.compacting — influence compaction summaries.
  • dispose — cleanup at session end.

Extensions run with full permissions (not sandboxed). Use --no-extensions to disable.

Skills are SKILL.md files with YAML frontmatter. Discovered from:

  1. ~/.config/one/skills/ — global skills.
  2. ~/.agents/skills/ — platform-wide skills.
  3. .one/skills/ — project-local skills.
  4. --skill <path> — explicit path.

Skills use progressive disclosure: only metadata (name, description) appears in the system prompt; full content is loaded on demand via /skill:<name> or RPC.

Named preset definitions are strict Markdown/YAML data under resources/presets and the configured agent directory. Their replacement role is composed before the invariant runtime/project/skill sections; runtime dispatch separately enforces any tool policy. See PRESETS.md.

one/resources/resource_loader.py handles discovery, parsing, validation, and reload of all resource types (extensions, skills, prompts, themes).

File: one/core/session_manager.py

Session management:

  • JSONL format for conversation history.
  • Evidence sidecars for complete tool/MCP results.
  • Atomic writes via tempfile + os.replace.
  • Session metadata (id, name, model, tool usage) stored separately.
Path Contents Permissions
~/.config/one/auth.json API keys and OAuth tokens 0600
~/.config/one/settings.json Global settings atomic write
~/.config/one/models.json Model registry and capabilities atomic write
~/.config/one/sessions/*.jsonl Session conversation history 0600
~/.config/one/blobs/ Image attachment storage 0700 dir, 0600 files

The agent directory can be overridden via ONE_CODING_AGENT_DIR.

Old state at ~/.one/agent/ is migrated to ~/.config/one/ on first run. Migration tightens permissions but never fails the startup if it encounters errors.

File: one/core/settings_manager.py

Settings are stored in settings.json and include:

  • tools.timeoutSec (default: 30) — per-tool timeout.
  • compaction.thresholdPercent — legacy automatic compaction threshold.
  • compaction.experimentalV2 — opt-in budget-aware checkpoints, retention, constraint ledger and failure-safe commit; defaults to false. Optional bounded file rehydration defaults off. Native production capability is disabled. See compaction for compatibility and recovery.
  • cooperation — enable/disable approval gates.
  • mcp.enabled — enable/disable MCP servers.
  • extensions — enable/disable extensions.
  • toolOutputPruning — optional provider-context optimization.
  • providerProfiles — per-provider overrides; providerProfiles.chatgpt.experimentalStableSessionId (default true) controls stable Codex session-id/thread-id affinity headers.
  • subagents.timeoutSec (default: 1800) — subagent task timeout.
  • retry.mode — off, on, or unlimited.
  • maxSteps — maximum tool steps (0 = unlimited).

File: one/core/auth_storage.py

Auth precedence: runtime input > stored auth.json > environment variable.

Supported providers:

  • API key authentication (OpenAI, Anthropic, Gemini, etc.).
  • OAuth/subscription login (Anthropic, ChatGPT/Codex).
  • Local servers (llama.cpp, Ollama) need no API key.

Tokens are stored in auth.json with mode 0600 and automatically refreshed before expiry for OAuth providers.

File: one/modes/tui_mode.py

The TUI is built on Textual >=0.74.0 and provides:

  • Streaming response rendering.
  • Tool lifecycle status display.
  • Session history and navigation.
  • Slash commands: /help, /agents, /steer, /follow, /abort, /login, /mcp, /skill, /compact, /reload.
  • Keyboard shortcuts (Ctrl+P, Ctrl+C, Ctrl+L, Ctrl+Q, Ctrl+Z, Ctrl+R, etc.).
  • Image input via --image, paste, or read_image tool.
  • Cooperation approval prompts (Ctrl+Z to toggle).
  • /agents is a read-only monitor for direct children of the current session. It provides a bounded response and tool lifecycle/result preview for the selected child, subject to the existing details toggle; generated Inspect agent stream entries open the same view with that child selected. It never switches to a child session or controls child execution.
  • Subagent enablement (Ctrl+S or /subagents on|off) only controls whether subagent tools are available.
  • Version display in sidebar.

The stream buffer is capped at 500 entries; absolute indexes are rebased after trimming. Golden-rendering snapshots are tested via tests/test_tui_snapshots.py.

File: one/modes/rpc_mode.py

RPC mode implements a long-lived JSON-lines protocol:

  • Input: one JSON command per stdin line.
  • Output: one JSON event/response per stdout line.
  • No startup banner (stdout is pure protocol data).

Supported commands:

  • prompt — submit a message.
  • wait_for_idle — wait for work completion.
  • steer — send steering text.
  • follow_up — send follow-up message.
  • abort — abort current turn.
  • answer_question — answer an ask_user question.
  • get_pending_questions — list pending questions.
  • invoke_skill — load and invoke a skill.
  • get_skills — list skill metadata.
  • reload_resources — reload skills, extensions, prompts.

Use an id field to correlate requests and responses.

1. User input (TUI/text/RPC) or queued steering
↓
2. AgentSession._run_turn():
a. Build context (compaction, skill metadata, tool definitions)
b. Check for pending steering → inject into conversation
c. Invoke provider (streaming response)
d. Parse assistant output (text, tool calls, or both)
↓
3. For each tool call:
a. Emit tool_call_start event
b. Validate arguments against schema
c. Call tool.execute.before hooks (can deny)
d. Execute tool function
e. Call tool.execute.after hooks
f. Store bounded preview in self.messages
g. Write complete result to evidence sidecar
h. Emit tool_call_end event
↓
4. Accumulate assistant message and tool results
5. Repeat until: no tool calls, maxSteps reached, or finish called
6. Emit turn_end, agent_end
↓
7. Persist session (JSONL + evidence sidecars)

Compaction maintains a rolling summary plus recent messages:

  • Triggered when history exceeds the configured threshold.
  • The model generates a summary of older messages.
  • The summary is inserted as a system message at the beginning of the context.
  • Older messages are discarded from the provider context.
  • /compact forces manual compaction for non-empty history.
  • Compaction is lossy; factual evidence remains in the sidecar for retrieval.
  • Steering messages (/steer or RPC steer) are queued and consumed at the next provider boundary (after the current provider response, before the next).
  • Follow-up messages (/follow_up or RPC follow_up) are queued for the next turn after the current one completes.
  • Both maintain FIFO ordering.
  • Terminal events (finish, abort, timeout) do not automatically drain queues.

spawn_subagent delegates work to an isolated agent session:

  • Each subagent has its own session ID, model, and tool configuration.
  • Explicit non-empty tool lists and inherited tool sets automatically receive finish when needed, so every child has a terminal path; order is preserved and duplicates are removed.
  • Default timeout: subagents.timeoutSec (1800s / 30 min).
  • On timeout: abort, collect diagnostics, return typed result with session ID.
  • Parent can inspect/resume the subagent session via the session manager.
  • Nested spawning is forbidden (recursion guard).

Directory: tests/

  • ~1000+ tests across 50+ files.
  • Full suite: .venv/bin/python -m pytest -q.
  • Lint: .venv/bin/ruff check ..
  • TUI snapshots: ONE_UPDATE_SNAPSHOTS=1 .venv/bin/python -m pytest -q tests/test_tui_snapshots.py.
  • Focused suites: scripts/test.sh <suite> (quick, mcp, tui, providers, tools, auth, extensions, cli, rpc, core, sessions, failed/last, full/all).
  • Async tests require explicit @pytest.mark.asyncio.
  • All tests use ONE_CODING_AGENT_DIR pointing to a scratch directory.
  • Tests never contact real API servers or MCP servers.
File Focus
tests/test_tui_*.py TUI input, streaming, rendering, commands, cooperation, retry, navigation
tests/test_tui_snapshots.py Golden-rendering regression tests
tests/test_agent_*.py Tool calls, retry/abort, timeouts, steering, parsing
tests/test_event_snapshots.py Event sequence and payload verification
tests/test_provider_*.py Provider adapter payloads and capabilities
tests/test_extension_*.py Extension hooks and UI
tests/test_mcp.py MCP client connectivity
tests/test_session_*.py Session persistence and reload
tests/test_image_*.py Image attachment storage and processing
tests/test_cli_*.py CLI subprocess and argument parsing
  • Single source of truth: one/config.py:VERSION (currently 0.1.45).
  • Drives pyproject.toml dynamic version and one --version output.
  • Bump before tags; tags must equal the VERSION string.
  • User-visible changes require a version bump, CHANGELOG.md Unreleased entry, and regenerated TUI snapshots.
  • Tests-only, refactor-only, and comment-only changes do not bump version.
  • No sandboxing: Extensions, MCP servers, and tools run with full permissions.
  • JSON-in-text tool calls: The primary contract; native function-calling is absorbed but not yet normalized into a common adapter layer.
  • Windows: Best-effort support; no Windows CI. POSIX shell behavior may differ.
  • Compaction is lossy: Factual evidence survives in sidecars but the provider context loses detail after compaction.
  • Provider-native tool calls: Malformed/unknown calls are handled with best-effort recovery; a formal invalid catch-all tool is planned.

See TODO.md for the complete roadmap. Active work includes:

  • Normalized provider-native tool call adapter layer.
  • Windows shell support and CI.
  • Prompt-cache performance optimization (partially complete).
  • Autonomous provider-timeout recovery.
  • Diagnostic runner for long-session testing.
  • Test-suite organization refactor (split large modules).
  • Plan-mode agent and phase system (explicitly deferred).
  • Dependency security audit automation.