How coder/agentapi works
Project Type and Purpose
• AgentAPI is a full-stack application providing an HTTP API and CLI to control coding agents (Claude Code, Goose, Aider, Codex) via a terminal emulator.
• It includes:
• A Go-based HTTP server and CLI (in cmd/ and main.go)
• Core libraries for terminal handling, message parsing, formatting, logging
• A Next.js/React chat frontend under the chat/ directory
File-Structure Analysis
• Top-level
• cmd/attach: CLI command to attach to a running agent
• cmd/server: HTTP server command to launch and manage an agent process
• lib/httpapi: handlers for /message, /messages, /status, /events; OpenAPI schema
• lib/termexec: spawns agent subprocess in a pseudo-TTY
• lib/screentracker: captures and diffs terminal output into message chunks
• lib/msgfmt: strips user echo and TUI artifacts from agent output
• lib/logctx: structured logging context
• chat/: Next.js frontend—React components for chat UI
• openapi.json: API schema
• No persistent database; conversation stored in memory
README Insights
• Exposes four HTTP endpoints and an SSE stream for event updates
• Translates API calls into terminal keystrokes; parses output back into messages
• CLI “attach” uses the same HTTP API to stream messages and send keystrokes
a. Frontend
• Chat UI (Next.js web app)
• Components: MessageList, MessageInput, ChatInterface
• Connects via HTTP/SSE to the backend
b. Backend HTTP API
• HTTP server (cmd/server → lib/httpapi)
• Endpoints: POST /message, GET /messages, GET /status, GET /events (SSE)
• OpenAPI schema & docs UI
c. Terminal Engine
• lib/termexec: spawns the agent binary in a pseudo-terminal
• Sends keystrokes for user messages
d. Screen Tracker & Parser
• lib/screentracker: takes snapshots of terminal output, diffs to detect new agent messages
• In-memory storage of conversation state
e. Message Formatter
f. CLI “attach”
• cmd/attach: SSE subscription to /events and HTTP calls to send keystrokes
g. External Agent Processes
• Claude Code, Goose, Aider, Codex binaries on the host system
Interactions and Data Flow
1. User enters text in Chat UI → HTTP POST /message
2. HTTPAPI handler invokes lib/termexec to send keystrokes to agent subprocess
3. lib/screentracker snapshots terminal output, diffs against last state → new raw message
4. lib/msgfmt cleans up raw message → structured AgentMessage
5. Backend stores message in memory and:
• Returns 200 to POST /message
• Broadcasts update via SSE on /events
6. Chat UI listens on /events → renders new AgentMessage in MessageList
7. CLI “attach” works similarly: it subscribes to /events and sends keystrokes via /message
Architectural Patterns and Principles
• Layered architecture:
• Presentation (chat/ React)
• API layer (lib/httpapi)
• Domain logic (termexec, screentracker, msgfmt)
• In-memory state management (no external DB)
• Event-driven updates via SSE
• Single-process monolith with pluggable agent backends