ohgo

module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 23, 2026 License: Apache-2.0

README

ohgo

Module: github.com/PizenLabs/ohgo · Status: working product (see CHANGELOG.md)


Install

# From source (static binary, no cgo)
make build
./ohgo --help

# Install into ~/.local/bin (first on PATH, no sudo needed)
make install

# System-wide install instead
sudo make install PREFIX=/usr/local

# Release tarball, once a version is published on GitHub
OHGO_VERSION=v0.1.0 sh install.sh

# Docker
make docker
docker run -it -v "$PWD:/work" ohgo:dev

Requires Go 1.27+ for source builds. No C toolchain: CGO_ENABLED=0 go build ./... succeeds and the dependency graph contains zero C packages.

First run:

ohgo init          # writes ~/.ohgo/settings.json (never overwrites without --force)
ohgo doctor        # every failure names its fix
ohgo               # interactive session

Providers

Provider Auth Protocol Models
Anthropic ANTHROPIC_API_KEY Messages 28 bundled
OpenAI OPENAI_API_KEY Chat Completions 47 bundled (Responses-only lines excluded)
Groq, Together, Fireworks, DeepSeek, Cerebras, Mistral per-provider key Chat Completions bundled
OpenRouter OPENROUTER_API_KEY Chat Completions 7 seeds + live discovery
OpenCode Zen / OpenCode Go OPENCODE_API_KEY (shared) Chat Completions, Messages 71 / 34 seeds + live discovery
Ollama (local) none native chat live discovery only
Ollama Cloud OLLAMA_API_KEY native chat 52 seeds + live discovery

Not yet supported: xAI and Azure/OpenAI Responses-only models (no Responses transport), Google Gemini (no google-generative-ai transport), AWS Bedrock (SigV4 signing), pi-vfs/pi-walker internals, LSP/DAP, and MCP transports other than bounded stdio.

Credentials resolve in order: explicit request key, ~/.ohgo/credentials.json (0600, written only when you save), environment, then parsed shell startup files (read as text, never executed). ohgo doctor and /usage show which source won — values are never printed.

Shell completion and reference docs ship with the binary:

ohgo completion bash > /etc/bash_completion.d/ohgo   # bash|zsh|fish|powershell
ohgo docs --dir ./ohgo-docs                          # man pages + markdown

Run

export ANTHROPIC_API_KEY=sk-...   # or OPENAI_API_KEY, GROQ_API_KEY, ...
ohgo doctor                       # check the setup first; every failure names its fix
ohgo "summarise this repository"  # one-shot via `ohgo run "…"`
ohgo                              # interactive session (full-screen UI on a TTY)
ohgo --no-tui                     # plain REPL instead
ohgo --resume 12                  # continue session 12
ohgo models groq                  # list one provider's models
ohgo sessions show 12             # inspect a saved transcript

First run? ohgo doctor tells you what is missing — usually one environment variable — and nothing else fails silently because of it.

What it does

Reads, edits, and runs code in your repository through a focused tool set (read write edit delete bash wait glob grep ls symbols graph refs webfetch todo task), with session persistence, context compaction, subagent delegation (--max-depth), a wall-clock run budget (--deadline), and per-tool approval prompts.

symbols, graph, and refs share one repository index. refs answers where a symbol is referenced and which functions it directly calls or is called by. It reports ambiguous, truncated, unsupported, and unknown results explicitly; method dispatch, function values, dot imports, and reflection are not guessed.

In-session commands: /help /commands /clear /model [provider/id] /models /sessions /jobs /task [status|cancel|accept] /theme [dark|light] /connect /disconnect [provider] /status /usage /doctor /diff [target] /retry /compact /quit. The REPL and the full-screen UI share the same backend, so every command means the same thing in both; /task manages durable task continuity, which exists only in the full-screen UI, so the plain REPL reports it unavailable. /status reports the workspace and session; /usage opens the usage and provider inspector.

Completion and exit status

Completion is decided from observed evidence, not from the model stopping. ohgo run prints one verdict and exits accordingly:

Verdict Exit Meaning
COMPLETED 0 The requested contract was satisfied by observed evidence
NEEDS_REVIEW 2 The run stopped without enough evidence (missing execution, empty answer, unverified change)
PAUSED 3 A budget, deadline, or turn limit stopped the run before a verdict
FAILED 1 Execution, provider, or authority failure
CANCELLED 130 The process was interrupted

The plain REPL prints the same verdict and keeps reading. The full-screen UI persists the task contract and its pre-run target evidence; a NEEDS_REVIEW task stays open until a later turn supplies evidence for that persisted contract, or the user explicitly runs /task cancel (abandon) or /task accept (close without claiming completion). Background wait reports a timed-out or non-zero job as an error, and only a successful recognised check is verification evidence. Mid-session /model resolves through the same catalog as ohgo models, so a listed model is always switchable. /commands (or Tab on a /-line) opens a searchable command palette; every row runs the command it names.

/diff opens an interactive diff inspector: a hierarchical changed-file tree with A/M/D badges, a +X -Y stats bar, and per-file hunks with word-level highlighting. It fetches only the file list and counts on open and loads each file's hunks on demand (cached), so a large changeset opens instantly. /diff compares the working tree against HEAD, /diff <target> compares it against a revision, and /diff <base>..<target> compares two revisions. Keys: tab focus · j/k move · enter open · / filter · esc close.

Terminal workspace

The full-screen UI is one adaptive workbench: header (identity, runtime phase, model, connection), conversation, composer, status line (cwd, session, context %, measured usage). Layout follows the terminal size (WindowSizeMsg is a first-class input; a resize re-renders but never starts work or drops history):

  • Wide (≥100 cols): full metadata plus keyboard hints.
  • Medium (70–99): reduced metadata, full conversation.
  • Narrow (<70): conversation first; secondary metadata collapses before readability does. Footers stay one row.
  • Mini (<40 cols or <8 rows): a size notice instead of overlapping regions. Input and history are preserved; enlarge to resume.

On an empty conversation the workspace shows a short welcome — identity, one invitation to describe a task, and at most three examples — as chrome, never as a transcript entry: it cannot enter the session log, it disappears the moment real content arrives, it never reappears over a resumed transcript, and /clear brings it back. Narrow terminals drop the examples and keep the introduction plus a /help pointer. The header owns identity, model, and runtime phase; the status line owns workspace context (cwd, session, context %, measured usage) and never repeats them. Short content is padded below the transcript so the composer stays pinned to the bottom of the screen.

Shortcuts that are shown always work: enter send (queues while busy), alt+enter/ctrl+j insert a break, ↑ recalls history on a single line, pgup/pgdn scroll, home jumps to the transcript top while the composer is idle, end returns to the live edge, esc cancels a turn (never quits), ctrl+c cancels when busy, clears a non-empty draft, or points at the exit chords when idle (never quits), ctrl+d on an empty composer quits. Approval dialogs default to the conservative choice; closing, cancelling, or resizing never approves. Widths are measured in terminal cells (CJK/emoji/ANSI aware), long URLs and tool output wrap and bound rather than overflow.

Transcript, scrolling, and selection

The alternate-screen workspace owns its transcript: blocks keep stable identities, a layout index computes visual rows at the current width, and a virtual viewport slices only the rows on screen. Scrolling never rewrites terminal scrollback and never moves the terminal cursor into history. New output follows the bottom while you are at the live edge; scrolling up detaches and pins the block you are reading, so streaming does not steal the viewport. A ↑ N lines above — end to follow marker counts the hidden rows, and end (or scrolling back down) reattaches. Expanding a block — ctrl+o for the latest activity, or a click in reporting mode — changes presentation only; it never reruns a tool, reads the repository, or changes authority.

Pointer behaviour follows the mouse setting:

  • select (default outside tmux): the terminal keeps drag-select and copy. The wheel arrives through alternate-scroll mode (DEC 1007).
  • report (default inside tmux): the application owns the pointer. Drag selects logical rows; click expands an expandable tool block; alt-click copies that block's canonical content; releasing a drag copies via OSC 52 (ESC ] 52 ; c ; <base64> BEL). Copy payloads are logical text — never ANSI, cursor controls, or padding. A terminal that ignores OSC 52 silently does nothing; OHGO_CLIPBOARD=off disables the transport explicitly.

--live is the separate output-first mode: it writes sealed transcript rows to the terminal's normal buffer, so terminal scrollback, native selection, and pipe behaviour remain the terminal's job. It never requests a mouse mode or attempts historical expansion.

The /model picker lists the merged catalog (bundled plus live-cached rows) with the active model marked, provider scope, result count, and freshness (live, cached, bundled, refreshing…). Search is multiword and case-insensitive across name, id, provider, and metadata (openrouter, free, deepseek v4 free, provider:openrouter); free matches verified zero-price rows, falling back to name text only when pricing is unknown — unknown prices are never rendered as free. Picker keys: printable input including space searches, ↑↓ move, PgUp/PgDn page, Home/End jump, ←→ move the query cursor, enter selects the highlighted canonical id, esc clears the query first and closes second, ctrl+r refreshes the live catalog in the background. A stale snapshot refreshes automatically on open; failures keep cached rows with a reason, and a slower older refresh never overwrites a newer one.

Configuration

~/.ohgo/settings.json (project .ohgo/settings.json merges over it):

{
  "model": "groq/llama-3.1-8b-instant",
  "maxTokens": 32000,
  "theme": "dark",
  "approvals": { "bash": "deny", "write": "allow" }
}

"allow" never asks, "deny" never runs; anything else (or absent) prompts each time. ohgo init writes model and theme; /theme updates theme in place.

Precedence for the model: --model flag, then settings, then OHGO_MODEL, then the catalog default (anthropic/claude-sonnet-4-5). An unknown name is an error everywhere — a silent fallback would send your conversation to a provider you never chose.

OHGO_HISTORY_FILE overrides the plain-REPL history location (~/.ohgo/history by default; empty disables it).

External knowledge

Phase 8 adds three bounded external capabilities. They are disabled until configured: a missing block means the tool is not offered. External content is untrusted data, never authority, verification, or completion evidence.

Search (search) uses an explicit provider list. Credentials are named environment variables; the value never appears in settings, results, or logs.

{
  "search": {
    "defaultProvider": "brave",
    "providers": [
      {
        "name": "brave",
        "kind": "brave",
        "endpoint": "https://api.search.brave.com/res/v1/web/search",
        "apiKeyEnv": "BRAVE_API_KEY",
        "maxResults": 8,
        "maxBytes": 262144,
        "retries": 1
      }
    ]
  }
}

kind is brave or tavily. A query, result page, snippet, and response body are bounded. Each result carries title, source host, URL, retrieval time, provider, and a request identity. A retry is a separate admitted call.

MCP (mcp_list, mcp_read, mcp_call) speaks bounded newline-delimited JSON-RPC to a configured stdio server. Discovery lists advertised capabilities but grants nothing: every tool must be classified in configuration.

{
  "mcp": {
    "servers": [
      {
        "name": "notes",
        "command": "/usr/local/bin/notes-mcp",
        "args": ["--stdio"],
        "env": ["NOTES_TOKEN"],
        "tools": { "search_notes": "read", "create_note": "mutate" },
        "allowMutation": true,
        "maxBytes": 262144,
        "maxItems": 32,
        "maxTextChars": 12000,
        "idleTimeoutSeconds": 120
      }
    ]
  }
}

Classifications are read, interact, mutate, or unknown; a missing tool is unknown and fails closed. mcp_read accepts only read. mcp_call accepts only interact/mutate with allowMutation, and additionally requires the BUILD authority and an approval. The model never chooses the command, arguments, or environment; only the named environment variables are passed to the server. Binary content is never copied into model context.

Browser (browser) is bounded GET read/navigation, not an automation surface: no JavaScript, forms, clicks, or non-GET requests. A session has an exact host policy, navigation and redirect limits, byte/character/link bounds, a session deadline, and a bounded history. Loopback, private, link-local, and metadata addresses are blocked by default.

{
  "browser": {
    "allowedHosts": ["example.com", "docs.example.com"],
    "maxNavigations": 8,
    "maxRedirects": 3,
    "maxBytes": 1048576,
    "maxChars": 20000,
    "maxLinks": 20,
    "maxSessions": 4,
    "sessionTtlSeconds": 300
  }
}

Every external answer is wrapped as [EXTERNAL KNOWLEDGE — UNTRUSTED DATA] with each content line prefixed, so injected text cannot forge a new section. External calls and bytes consume the root run budget (external_calls, external_bytes); providers also enforce per-request bounds. A cancelled call publishes no evidence. The pre-existing web_fetch remains available and now uses the same untrusted envelope with WEB_FETCH provenance; it is a simple legacy read, not a browser session.

Architecture

See ARCHITECTURE.md for the layer map, turn lifecycle, concurrency rules, error taxonomy, storage, transports, and performance notes. Port invariants live in MEMORY.md; the incremental plan in PORT.md; status in PROGRESS.md.

Key properties:

  • The loop never touches HTTP. All transport goes through ai.StreamFn, the seam every test drives.
  • Model facts are data. catalog.Resolve(provider/id) is the only source; no code branches on model id strings.
  • Containment is structural. Tool paths resolve inside the working root in one place, so no call site can forget the check.
  • Isolation is structural. A subagent at the depth cap is built without a task tool, so it cannot delegate however prompted.
  • Budgets are explicit. Completion budget defaults to the model's ceiling; the run is bounded by wall-clock deadline, and expiry returns completed turns rather than an error.

Tests

make check   # build + vet + gofmt + full test suite
make race    # same, with the race detector
make bench   # glob/grep/agent/ai benchmarks

cmd/ohgo/integration_test.go drives a full tool call through the real transport and filesystem against an httptest provider; TestWireRequestCarries… tests assert budgets and endpoints on the actual request body, because unit tests once missed a duplicated budget block.

Directories

Path Synopsis
Package agent implements the model/tool loop: it sends a context to a provider, dispatches any tool calls the model requests, appends the results, and repeats until the model stops calling tools or the caller aborts.
Package agent implements the model/tool loop: it sends a context to a provider, dispatches any tool calls the model requests, appends the results, and repeats until the model stops calling tools or the caller aborts.
Package ai defines the provider-agnostic message model and the streaming contract every LLM transport implements.
Package ai defines the provider-agnostic message model and the streaming contract every LLM transport implements.
Package ast finds code structurally.
Package ast finds code structurally.
bench
phase9 command
Command phase9 is the controlled benchmark harness for the cognitive efficiency layer.
Command phase9 is the controlled benchmark harness for the cognitive efficiency layer.
repository command
Package budget owns the resource grant an execution tree may consume.
Package budget owns the resource grant an execution tree may consume.
Package catalog resolves model facts from bundled data.
Package catalog resolves model facts from bundled data.
cmd
ohgo command
Command ohgo is a coding agent CLI.
Command ohgo is a coding agent CLI.
Package cognition owns Ohgo's task-shape, evidence, projection, and sufficiency model.
Package cognition owns Ohgo's task-shape, evidence, projection, and sufficiency model.
Package config loads and saves ohgo settings.
Package config loads and saves ohgo settings.
Package contract defines the bounded completion contract a user request implies.
Package contract defines the bounded completion contract a user request implies.
Package creds resolves provider credentials from ordered sources.
Package creds resolves provider credentials from ordered sources.
Package diff computes Myers line diffs and unified-diff hunks.
Package diff computes Myers line diffs and unified-diff hunks.
Package edit locates and applies edits to file content.
Package edit locates and applies edits to file content.
Package exec runs the user's "!<command>" shell escape.
Package exec runs the user's "!<command>" shell escape.
Package jsonschema validates decoded JSON values against the subset of JSON Schema that tool parameter schemas use.
Package jsonschema validates decoded JSON values against the subset of JSON Schema that tool parameter schemas use.
Package knowledge defines the common boundary for OHGO's external knowledge capabilities.
Package knowledge defines the common boundary for OHGO's external knowledge capabilities.
Package mcp implements a bounded MCP client boundary.
Package mcp implements a bounded MCP client boundary.
Package memory defines OHGO's project-memory trust boundary.
Package memory defines OHGO's project-memory trust boundary.
Package project establishes a stable project identity for OHGO.
Package project establishes a stable project identity for OHGO.
Package prompt builds the system prompt.
Package prompt builds the system prompt.
Package sandbox launches child processes behind an enforceable filesystem boundary.
Package sandbox launches child processes behind an enforceable filesystem boundary.
Package search implements bounded, provenance-preserving external search.
Package search implements bounded, provenance-preserving external search.
Package security owns OHGO's authorization decision.
Package security owns OHGO's authorization decision.
Package session persists and replays agent conversations.
Package session persists and replays agent conversations.
Package shell decodes and minimises the output of subprocesses.
Package shell decodes and minimises the output of subprocesses.
Package startup owns OHGO's startup lifecycle: project discovery, project initialization, Git detection, and project-local metadata.
Package startup owns OHGO's startup lifecycle: project discovery, project initialization, Git detection, and project-local metadata.
Package state is the single owner of OHGO's machine-level state location.
Package state is the single owner of OHGO's machine-level state location.
Package task owns OHGO's durable task continuity state.
Package task owns OHGO's durable task continuity state.
Package tokens estimates token counts for prompt budgeting.
Package tokens estimates token counts for prompt budgeting.
Package tools implements the built-in tool set.
Package tools implements the built-in tool set.
tui
InitWizardModel is the in-canvas onboarding flow for uninitialized projects.
InitWizardModel is the in-canvas onboarding flow for uninitialized projects.
diff
Package diff implements the interactive visual diff and context inspector behind the /diff command.
Package diff implements the interactive visual diff and context inspector behind the /diff command.
Package vcs reads and drives version-control repositories.
Package vcs reads and drives version-control repositories.
Package workspace defines OHGO's execution authorities.
Package workspace defines OHGO's execution authorities.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL