Skip to content

Axon | Go Agent Runtime

OPEN-SOURCE · GO AGENT RUNTIME

Build the agent.
Don’t rebuild the runtime.

Axon is the execution layer underneath Cortex, a real terminal coding agent. It owns the long-running loop between models, tools, sessions, context, processes, and events — while your product stays in control of behavior and UX.

$go get github.com/atakang7/axon/v2
7 built-in toolsOpenAI-compatible modelsMCP over stdioAppend-only sessionsMIT licensed
cortexaxon · main
›turn 2 · calling model...
✓Both repos build, vet, and test green. Done.
## What changed
axon — runtime wiring stays isolated from the product.
cortex — model, prompt, and terminal behavior stay above the line.
## Verified
•axon: go build · go vet · go test ./...PASS
•cortex: go build · go vet · go test ./...PASS
❯ask for a change, or /help
z-ai/glm-5.2pruner: deepseek/v4-flashturn 2ctx 13,868
REFERENCE PRODUCT Cortex uses Axon as its execution runtime.
01 · REAL PRODUCT PROOF

Cortex is not a demo for Axon.
It is a product built on Axon.

The cleanest way to understand the runtime is to look at what Cortex does not implement. Cortex owns the coding-agent product. Axon owns the generic execution machinery underneath it.

C
github.com/atakang7/cortexthe coding agent
  • 01 Model + provider selection
  • 02 Coding-agent system prompt
  • 03 Bubble Tea terminal UI
  • 04 Slash commands + UX policy
  • 05 Interactive and one-shot modes
BUILT ON↓
A
github.com/atakang7/axonthe runtime
  • 01 Model / tool turn loop
  • 02 Session persistence + undo
  • 03 Context projection + pruning
  • 04 Foreground + background execution
  • 05 Streaming + retries + events
THE ACTUAL SEAM

Cortex wires the runtime once.

Its newAgent function converts product configuration into an axon.Config. The interactive TUI and non-interactive CLI both go through that same constructor, so the product cannot quietly grow a second agent loop.

Read Cortex wiring on GitHub ↗
return axon.New(axon.Config{
    Model:        model,
    SystemPrompt: cfg.SystemPrompt,
    MCPServers:   servers,
    OnEvent:      onEvent,
    Settings:     settings,
    Pruner:       prunerModel,
})
02 · THE BOUNDARY

Three layers. One direction.

Product intent flows down. Runtime events flow back up. Axon is the seam that keeps those concerns from collapsing into one codebase.

PRODUCT
Cortex / your agentwhat makes the agent yours
PromptUIPolicyCustom toolsModel choice
calls Step()receives Events
RUNTIME
Axonthe reusable execution substrate
Turn loopSessionContextTool dispatchRetriesStreamingProcesses
drivesobserves
ENVIRONMENT
Machine + providerswhere work actually happens
LLM APIFilesystemShellripgrepMCP servers
Small public surfaceNew, Step, Run, Interrupt, Reset, Undo, runtime controls.
Config stays frozenSettings are resolved at construction. Axon does not silently reread configuration mid-session.
Two agents can differModel, tools, settings, working directory, pruner, MCP servers, and event sinks are instance-level.
03 · ONE TURN, END TO END

Step() is the engine room.

One user message can become many model calls and many tool executions. Axon owns that continuation until the model finally returns with no more tool calls.

01
Append user inputIncrement turn, persist message, save session.
02
Project contextRecency window + parked breadcrumbs determine what the model sees.
03
Call modelStream content, reasoning, tool-argument fragments, and token usage.
04
Resolve tool callsMatch the tool name, parse args, execute, emit events.
05
Persist tool resultsAppend results to the same session history and continue.
↻
Repeat when tools remainThe runtime goes back to the model with the new evidence.
✓
Return StepResultFinal assistant text, all tool calls, and the turn number.
minimal.go20 lines of product wiring
model, err := settings.NewClient("openrouter", "deepseek/deepseek-v3.2")
if err != nil { log.Fatal(err) }

agent, err := axon.New(axon.Config{
    Model:        model,
    SystemPrompt: "You are a careful coding agent.",
    OnEvent:      render,
})
if err != nil { log.Fatal(err) }
defer agent.Close()

result, err := agent.Step(ctx, "Find and fix the failing test.")
Your UI can call Step itself or hand Axon an input function through Run.
04 · BUILT-IN CAPABILITIES

Seven tools. Replace any of them.

Axon ships the mundane capabilities coding agents repeatedly need. Exclude a built-in to free its name, then supply your own implementation behind the same tool surface.

01readslice · full

Read files or list directories. Binary-aware, byte-capped, line-addressable.

02write4 edit modes

Atomic tmp + rename writes. Every edit is recorded so agent.Undo() can restore it.

03execfg · bg

Run sh -lc commands with timeout control or detach long-lived processes into managed groups.

04bash_outputdelta

Poll only output produced since the previous read, with offset and file-identity tracking.

05kill_shelllifecycle

Terminate a whole process group: SIGTERM, grace period, then SIGKILL when needed.

06searchliteral · regex

Ripgrep-backed workspace search with globs, case control, and bounded results.

07taskplan state

Register, advance, or replan a compact multi-step goal injected into context.

BACKGROUND PROCESS LIFECYCLE

Long-running commands are first-class.

Servers, watchers, network clients, and anything that may hang can leave the foreground turn without leaving Axon’s lifecycle.

execrun_in_background=true
→
bash_1process group + logfile
→
bash_outputread only new bytes
→
kill_shellTERM → grace → KILL
05 · LONG-SESSION CONTEXT

Keep history. Change the view.

Axon does not rewrite the session to make context smaller. The historical log stays intact; ContextMessages() derives a bounded projection for each model call.

IMMUTABLE SESSION LOG
m1 tool resultm2 assistantm3 parkedm4 tool resultm5 userm6 assistantm7 tool result
ContextMessages()→projection, never mutation
WHAT THE MODEL SEES
m5 · full content
m6 · full content
m7 · full content
30default recent blocks kept in full
10kdefault token floor before the pruner is worth firing
+5kdefault growth before another pruning pass
3 modeslow · moderate · extreme
FREE LINE OF DEFENSE

Recency window

Old blocks collapse to one-line breadcrumbs without a model call. Recent active blocks stay complete.

OPTIONAL SECOND LINE

Model-assisted pruner

A cheaper secondary model can park stale blocks. Protected messages and edited-file evidence stay available.

RECOVERABLE BY DESIGN

Full history survives

Parking changes the request projection, not the session record. The runtime can still reason from durable history.

06 · PROVIDER REALITY

200 OK does not always mean “good reply.”

LLM APIs fail in ways ordinary request wrappers do not cover: truncated SSE streams, stalled connections, partial tool-call fragments, retryable statuses, and even tool markup leaked as plain text.

STREAM

SSE is reassembled, not assumed.

delta.contentdelta.reasoning_contentdelta.tool_calls[index]usage[DONE]

Tool-call fragments are accumulated by index and emitted in stable order when the stream finishes.

RETRY POLICY

Transport and HTTP policy are separate.

retry:
  max_attempts: 10
  backoff_cap: 60s
  on_status: [429, 500, 502, 503, 504]

EOFs, resets, DNS failures, and timeouts are transport failures. HTTP statuses follow explicit policy.

UNUSABLE REPLIES

Success responses can still be invalid.

<tool_call>…</tool_call>
↓ detected as leaked tool markup
retry once → real tool call or explicit error

Axon refuses to silently end a turn on provider markup that should have been parsed as a tool call.

07 · UI WITHOUT RUNTIME COUPLING

Everything important becomes an event.

Cortex’s terminal is not inside Axon. It subscribes to ordered runtime events, converts them into UI messages, and owns presentation on its own goroutine.

axon.Eventordered · synchronous on the turn goroutine
session_startturn_startuser_inputapi_calltokenreasoningtool_arg_deltatool_calltool_resultusageprune_startprune_endturn_end
↳Terminal UIBubble Tea bridge
↳Plain CLIstdout / stderr
↳Trace logfull runtime telemetry
↳Your appwebsocket, metrics, audit
render.gopresentation stays yours
switch e.Kind {
case axon.KindToken:
    fmt.Print(e.Text)
case axon.KindToolCall:
    drawTool(e.Tool)
case axon.KindUsage:
    updateTokens(e.Usage)
case axon.KindPruneEnd:
    updateContext(e.Prune)
}
08 · CAPABILITY BOUNDARIES

Tools get capabilities, not the Agent.

Built-ins are constructed with narrow interfaces and flat limits. They do not receive the settings object, model credentials, conversation history, or the registry of other tools.

AGENT CORE
Settingsprovider config · API keys · runtime policy
extract only what is needed
Limitsread bytes · exec timeout · search caps · process limits
→
TOOL CAPABILITIES
WorkspaceDir · ResolvePath · RecordEdit
PlanRegister · Advance · Replan
BackgroundShellsspawn · poll · kill
Limitsflat caps only
NOT HANDED TO BUILT-INS✕ API keys✕ session history✕ provider config✕ tool registry

Important: the working directory is routing, not a sandbox. Axon narrows runtime interfaces; OS-level sandboxing remains an embedder decision.

09 · FALSIFIABLE, NOT VIBES

Cortex proves the architecture.
SWE-rebench tests the performance.

The first Axon/Cortex benchmark is intentionally boring: the complete frozen February 2026 SWE-rebench split, one deterministic trajectory per task, the same model family, no web, and hidden PASS / FAIL evaluation.

FROZEN BEFORE RUN #1commit SHAmodelreasoningsystem promptsettingsinstance IDslimitsweb=off
SWE-rebench · 2026_02RESULTS PENDING
SYSTEMTASKSTRIALSRESULT
Cortex + Axon + GPT-5.457 / 571×—
Published Codex baselinesame splitexistingpublished
Reference scaffoldsame splitexistingpublished
Resolved@1primary outcome
tokens / taskinference footprint
tokens / resolvedefficiency
median wall timeruntime latency
No cherry-picked 20-task sample. No tuning after seeing failures. No fake dollar comparison without equivalent cache accounting.
10 · START WITH ONE TURN

The runtime is the part you should be able to stop thinking about.

Wire one model and one prompt. Then add the pieces your product actually needs: events, a pruner, MCP, custom tools, or a UI.

SPECIALIZE THE PRODUCT, NOT THE RUNTIME

Cortex is one agent.
Axon is the factory underneath.

A coding agent is only one specialization. Keep Axon’s loop, sessions, context, retries, processes, and events — then change the role, tools, model, and policy to build an expert for a completely different operational domain.

UNCHANGEDAxon runtimeloop · context · sessions · retries · streaming · processes · events
+
SPECIALIZERole + capabilitiessystem prompt · custom tools · MCP · model · product policy
=
YOUR PRODUCTDomain expert agentKubernetes · SRE · cloud · security · data · releases · anything tool-addressable
SEC04

Security analyst

Evidence-driven investigation + remediation

Join scanner findings with repository context, IAM configuration, SBOM data, deployment state, and policy — then turn a finding into a concrete, reviewable change.

CAPABILITIES
Trivy/SBOMIAM APIsgitpolicy engineticketing
find→scope→trace→remediate→prove
EXAMPLE TRAJECTORY

Critical image CVE → locate deployed versions → find owning Dockerfile → update base → test → rescan → open remediation PR

DATA05

Database / data operator

Operational reasoning over live data systems

Inspect schemas, query plans, replication state, jobs, migrations, and backups while keeping destructive actions behind explicit product-level controls.

CAPABILITIES
SQLmigration CLImetricsbackup APIrunbooks
observe→explain→plan→change→measure
EXAMPLE TRAJECTORY

Slow endpoint → inspect query plan → find missing index → generate migration → validate on staging → observe p95 after rollout

REL06

Release engineer

Repository-to-production orchestration

Own the mechanical path from a repository state to a verified release: tests, versioning, changelog, artifacts, deployment, smoke checks, and rollback evidence.

CAPABILITIES
gitGitHubCIregistrydeploy API
prepare→test→package→ship→verify
EXAMPLE TRAJECTORY

Release request → inspect commits → run test matrix → cut version → publish artifact → deploy canary → verify health

EXAMPLE · KUBERNETES ADMINISTRATOR

Give the model cluster capabilities. Keep the runtime generic.

The Kubernetes knowledge lives in the role and tool descriptions. Cluster access lives inside your tool closures or MCP servers. Axon still only sees ordinary tools and ordinary results, which means the same runtime mechanics used by Cortex can drive a completely different expert.

01Observepods · events · metrics · logs
→
02Reasonhistory + live evidence
→
03Actbounded custom tools
→
04Verifyrollout + health checks
kubernetes-agent.gosame Axon constructor
agent, err := axon.New(axon.Config{
    Model:        model,
    SystemPrompt: kubernetesOperatorPrompt,
    Tools: []axon.Tool{
        kubectlTool,
        helmTool,
        prometheusTool,
        approvalTool,
    },
    Pruner:  cheapContextModel,
    OnEvent: audit,
})
Policy stays above Axon.approvalTool is your capability gate — for example, read-only by default and explicit approval before mutations.
WHY THIS SHAPE WORKS

Specialized agents need depth, not a giant framework.

Long-running stateOperational work takes many calls. Sessions and context projection keep the investigation coherent.
Real executionForeground and managed background processes let agents work with CLIs, watchers, servers, and diagnostics.
Domain toolsConfig.Tools and MCP let you expose exactly the capabilities an expert needs — no more.
Observable behaviorThe event stream gives a UI, audit log, approval system, or metrics pipeline every important runtime transition.
Replaceable intelligenceSwap the primary model or pruner without rewriting the product’s execution machinery.
Narrow boundariesTools receive their own closures and capabilities. Provider settings and conversation internals are not handed to built-ins.
RUNTIME ≠ PERMISSION MODEL

Axon gives you the execution substrate. Production authorization, approval gates, credentials, sandboxing, and blast-radius controls remain product/tool decisions — exactly where a specialized agent should make them explicit.