kode

package module
v0.13.7 Latest Latest
Warning

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

Go to latest
Published: May 19, 2026 License: MIT Imports: 11 Imported by: 0

README

kode

The fastest, minimal, zero-dependency Go autonomous agent runtime.

One binary. One loop. Zero frameworks. ReAct (Reasoning + Acting) — think, therefore act.

# Install
go install github.com/BackendStack21/kode/cmd/kode@latest

# Use (set DEEPSEEK_API_KEY or OPENAI_API_KEY)
export DEEPSEEK_API_KEY=sk-...
kode run "How many lines in go.mod?"
# → 3 lines

Why kode

kode is not a framework. It's a runtime — the smallest possible surface area between an LLM and your tools.

kode Python agents (LangChain, CrewAI, etc.)
Dependencies Zero. stdlib only 200+ packages
Binary size ~5 MB static 50-200 MB with venv
Startup Instant 2-10s (Python imports)
Sandbox --sandbox flag Requires manual Docker setup
Tool interface One interface, one method Class hierarchies + decorators

Strategic Features

🔒 Sandboxed Execution

kode run --sandbox — every session spawns an isolated Docker container. No network, no host mounts beyond the working directory, zero capabilities, destroyed on exit. Full security model in docs/SANDBOXING.md.

🧩 Sub-Agent Delegation

Parallel OS-process sub-agents via delegate_tasks. True isolation — each sub-agent is a fresh kode subagent process with its own config, tools, and termination timeout. Up to 8 concurrent workers. docs/SUBAGENTS.md

🧠 Skill System (on by default)

Skill-matched SKILL.md files load on-demand. Auto-learns from patterns every session — detects multi-step procedures, error recoveries, repeated actions, and user corrections. LLM-enhanced: each detected pattern is enriched with an LLM-generated name, description, trigger keywords, and structured body with overview, steps, pitfalls, and verification sections. Use --no-learn to disable. Import skills from any URI with automatic LLM risk assessment. docs/CLI.md#skills

💾 Persistent Memory

Three tiers: facts (agent-managed durable entries), session buffer (auto-appended turn summaries), episodes (LLM-extracted knowledge from past sessions). Merge-on-write via go-vector RandomProjections — cosine >0.7 auto-merges, <0.3 auto-adds. Saves ~80% LLM calls. docs/MEMORY.md

🔧 Multi-Turn Sessions

Save, resume, list, trim, and clean up conversations. Sessions persist as JSON in ~/.kode/sessions/. Continue any session with kode continue. docs/SESSIONS.md

🏗️ Layerable Config

Four-layer priority chain: global (~/kode/config.json) → project (./kode.json) → KODE_* env vars → CLI flags. ${VAR} substitution in config files. docs/CONFIG.md

🔌 LLM-Agnostic

Any OpenAI-compatible endpoint: Deepseek, OpenAI, Anthropic, Ollama, vLLM, Groq, Together, Fireworks — anything that speaks /chat/completions. Per-model profiles for thinking depth and context windows. docs/PROVIDERS.md

🌐 Web UI

kode serve — browser-based agent with @ resource completion (@file.go, @sess:abc123), WebSocket streaming, and a full IDE-style console. docs/WEBUI.md

🔗 MCP (Two-Way)

Server (kode mcp) — expose kode's native tools (shell, read/write/search files, patch, browser) to Claude Code, Cursor, and any MCP client. Client (mcp_servers config) — kode connects to external MCP servers (Playwright, Fetch, GitHub, SQLite, etc.) and makes their tools available to the agent as <server>__<tool>. Both directions in one binary. docs/MCP.md

🔍 Native Tools

Built-in read_file, write_file, search_files, patch, shell, and browser tools. All gated by a unified security layer (dangerous config) — classify operations as allow / deny / prompt per risk class. No third-party dependencies. docs/SECURITY.md


Quick Start

# Single-shot task
kode run "List the files"

# With session persistence
kode run --session "Refactor auth module"
kode continue "Add rate limiting"

# Sandboxed (Docker isolation)
kode run --sandbox "npm audit"

# Different model
kode run --model gpt-4o --base-url https://api.openai.com/v1 "Explain this"

# With skill learning (on by default — use --no-learn to disable)
kode run "Set up a Go project with CI"

# Interactive REPL
kode repl

Cheatsheet

Commands
Command What it does
kode run <task> Single-shot task
kode run --session <task> Save conversation as session
kode continue [--id <id>] <task> Resume a saved session
kode repl Interactive multi-turn REPL
kode session list List recent sessions
kode session show [id] View session transcript
kode session delete <id> Delete a session
kode session trim <id> <n> Keep last n messages
kode session cleanup <days> Delete old sessions
kode skill list List available skills
kode skill view <name> View skill content
kode skill delete <name> Delete a skill
kode skill import <uri> Import skill from URL
kode skill curate Audit skill quality/overlap
kode serve [--addr :8080] Start Web UI server
kode subagent --goal <string> Run a focused sub-task
kode init [--global] Create config file
kode mcp [--sandbox] Start MCP server — expose tools to Claude Code
kode version Print version
Key Flags
Flag What it does
--model <name> LLM model (e.g. deepseek-v4-flash, gpt-4o)
--base-url <url> API endpoint URL
--sandbox Run in Docker sandbox
--thinking <level> Reasoning depth (enabled/disabled/low/medium/high)
--learn Enable skill learning mode — on by default
--no-learn Disable skill learning mode
--system <prompt> Override system prompt
--max-iter <n> Max think→act cycles (default 90)
--no-color Disable colored output
--no-agents Skip AGENTS.md project file

Docs

Doc Covers
CLI Reference All commands, subcommands, flags, error codes
Configuration Config files, env vars, priority chain, all sections
Providers & Models Supported providers, thinking config, context windows
Memory Three-tier design, go-vector merge-on-write, memory tool
Sessions Multi-turn conversations, save/resume/trim/cleanup
Sandboxing Docker isolation model, config, security hardening
Security Threat model, prompt injection defense, sandbox model
Sub-Agents Task decomposition, delegation tool, subagent protocol
Web UI kode serve, WebSocket protocol, @ resource resolution
Skills Trigger-matched skills, learning, import, curation
MCP Serve tools to Claude Code + connect to external MCP servers
Development Building, testing, contributing, project structure

Programmatic API

import "github.com/BackendStack21/kode"

agent, err := kode.New(kode.Config{
    Model:          "deepseek-chat",
    APIKey:         os.Getenv("DEEPSEEK_API_KEY"),
    MaxIterations:  30,
    Tools:          []kode.Tool{&myCustomTool{}},
    SystemMessage:  "You are an expert at refactoring Go code.",
})
defer agent.Close()

result, err := agent.Run(context.Background(), "Refactor this module")

The full Config struct supports: BaseURL, Thinking, SandboxCleanup, Renderer, MemoryConfig, MemoryDir, Skills, SkillManager, and NoProjectFile.


Test

go test ./...                  # 888 tests, all pass
go test -race ./...           # race detector clean
go test -cover ./...          # 79%+ average coverage

Everything runs with go test — no Docker, no network, no external services required for unit tests.


License

MIT

Documentation

Overview

Package kode is a minimal, zero-dependency Go agent loop runtime.

kode implements the ReAct (Reasoning + Acting) pattern — the "think, therefore act" loop that powers autonomous AI agents. It is not a framework or an SDK. It is a runtime: one loop, one binary, zero deps.

Design

  • Zero external dependencies. stdlib only.
  • Session isolation via Docker containers (--sandbox).
  • LLM-agnostic. Any OpenAI-compatible endpoint works.
  • Tool-first. Tools are the only extension point.

Security

When running with --sandbox, each session executes in a fresh Docker container. The container has no network access, no host mounts beyond the working directory, and is destroyed on exit. The agent can never access files outside its working directory.

Index

Constants

View Source
const ProjectFileName = "AGENTS.md"

ProjectFileName is the name of the project-level instructions file that kode automatically loads from the working directory.

Variables

View Source
var KnownProfiles = []struct {
	Prefix  string
	Profile ModelProfile
}{
	{
		Prefix: "deepseek-v4-pro",
		Profile: ModelProfile{
			Label:           "DeepSeek v4 Pro",
			DefaultThinking: "enabled",
			Timeout:         180,
			MaxContext:      1_000_000,
		},
	},
	{
		Prefix: "deepseek-v4-flash",
		Profile: ModelProfile{
			Label:           "DeepSeek v4 Flash",
			DefaultThinking: "",
			Timeout:         90,
			MaxContext:      131_072,
		},
	},
	{
		Prefix: "deepseek-",
		Profile: ModelProfile{
			Label:      "DeepSeek (generic)",
			MaxContext: 131_072,
		},
	},
}

KnownProfiles lists all built-in model profiles. Each entry is matched by longest prefix — "deepseek-v4-flash" matches before "deepseek-" would. Add new profiles here; the rest of kode consumes them automatically.

Functions

func LoadProjectFile

func LoadProjectFile() string

LoadProjectFile reads ProjectFileName from the current working directory. Returns the file content (trimmed) if it exists and is readable. Returns empty string if the file doesn't exist or can't be read. The content is intended to be appended to the system message with a clear header — use it for project conventions, architecture notes, etc.

func ProfileLabel

func ProfileLabel(model string) string

ProfileLabel returns the human-readable label for a model, or the model name itself if no profile matches. Used in CLI headers and status output.

Types

type Agent

type Agent struct {
	// contains filtered or unexported fields
}

Agent is the agent loop runtime.

func New

func New(cfg Config) (*Agent, error)

New creates a new Agent with the given configuration.

If Config.SandboxCleanup is set, the cleanup function is called when Close() is invoked. The caller is responsible for creating the sandbox container and wiring up tool executables to use it before calling New().

func (*Agent) Close

func (a *Agent) Close() error

Close cleans up resources. If a sandbox container was created, it is destroyed. Always call Close() when done with the agent.

func (*Agent) Memory

func (a *Agent) Memory() *memory.MemoryManager

Memory returns the agent's memory manager. Used by the CLI layer to append buffer entries after each turn and signal session end. Returns nil if memory is disabled.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, task string) (string, error)

Run executes the agent loop for the given task and returns the final answer.

func (*Agent) RunWithMessages

func (a *Agent) RunWithMessages(ctx context.Context, messages []llm.Message) (string, []llm.Message, error)

RunWithMessages executes the agent loop starting from a pre-built message history. Use this for multi-turn conversations where the full conversation context (system prompt, prior turns) has been loaded from a session file and the new user message appended.

Returns the final answer plus the complete updated message history. The caller should persist the history (e.g. to a session file) so the conversation can be continued in a future call.

type Config

type Config struct {
	// Model is the LLM model identifier (e.g., "deepseek-v4-flash").
	Model string

	// BaseURL is the OpenAI-compatible API endpoint.
	// Default: "https://api.deepseek.com/v1"
	BaseURL string

	// APIKey authenticates with the LLM provider.
	// Falls back to DEEPSEEK_API_KEY, then OPENAI_API_KEY env vars.
	APIKey string

	// Thinking controls the model's reasoning depth. Provider-specific:
	//
	//   Deepseek: "enabled" or "disabled" → {"type": "enabled"}
	//   OpenAI o-series: "low", "medium", "high" → {"reasoning_effort": "low"}
	//
	// When empty, the model's profile default is used. If the profile also
	// has no default, the field is not sent (provider default behavior).
	Thinking string

	// Tools available to the agent.
	Tools []Tool

	// MaxIterations caps the number of think→act cycles (default: 90).
	MaxIterations int

	// SystemMessage is the system prompt injected at the start of every run.
	// If AGENTS.md exists in the working directory, its content is appended
	// automatically. Set NoProjectFile to true to skip this.
	SystemMessage string

	// NoProjectFile disables automatic loading of AGENTS.md from the
	// working directory. By default, kode reads AGENTS.md and appends
	// its content to the system message with a "Project Instructions" header.
	NoProjectFile bool

	// SandboxCleanup, if set, is called by Agent.Close() to destroy the
	// Docker sandbox container. Set by the CLI when --sandbox is active.
	// Programmatic API users can set this to their own cleanup logic
	// (e.g., remove a container, delete a VM, tear down a network).
	// When nil, Close() is a no-op.
	SandboxCleanup func() error

	// Renderer, if set, produces colored terminal output for each phase
	// of the agent loop. When nil, the agent runs silently (programmatic API).
	Renderer *render.Renderer

	// Skills configures the skill system. When nil, skills are disabled.
	Skills *skills.SkillsConfig

	// SkillManager holds the loaded skill state. Passed by the CLI layer;
	// when nil, New() auto-loads from default directories.
	SkillManager *skills.SkillManager

	// MemoryDir sets the directory for persistent memory storage.
	// Default: ~/.kode/memory/
	MemoryDir string

	// MemoryConfig controls the memory system (facts, buffer, episodes).
	// Default: memory.DefaultMemoryConfig()
	MemoryConfig memory.MemoryConfig
}

Config configures an Agent instance.

type ModelProfile

type ModelProfile struct {
	// Label is a human-readable name for the model family.
	Label string

	// DefaultThinking is the thinking value applied when Config.Thinking
	// is empty. Empty string means don't send the field (provider default).
	DefaultThinking string

	// Timeout is the default request timeout in seconds.
	// Zero means use the global default (120s). Increased for
	// models that take longer to reason (e.g. deepseek-v4-pro).
	Timeout int

	// MaxContext is the model's maximum context window in tokens.
	// The loop engine automatically trims conversation history when
	// estimated tokens approach this limit. Zero means no limit
	// enforcement (unknown or effectively unlimited models).
	MaxContext int
}

ModelProfile holds per-model defaults applied when the user hasn't explicitly provided a value. Zero values leave the system default.

func LookupProfile

func LookupProfile(model string) *ModelProfile

LookupProfile returns the best-matching ModelProfile for a model name, or nil if no profile matches. Matching uses longest prefix — a model named "deepseek-v4-flash-custom" would match "deepseek-v4-flash".

type Tool

type Tool interface {
	Name() string
	Description() string
	Schema() any // JSON Schema for the tool's parameters
	Call(args string) (string, error)
}

Tool represents a single capability the agent can invoke.

Directories

Path Synopsis
cmd
kode command
internal
config
Package config loads and merges kode configuration from multiple sources.
Package config loads and merges kode configuration from multiple sources.
danger
Package danger classifies shell commands by risk level and provides a configurable approval system for dangerous operations.
Package danger classifies shell commands by risk level and provides a configurable approval system for dangerous operations.
llm
Package llm provides an OpenAI-compatible HTTP client using only stdlib.
Package llm provides an OpenAI-compatible HTTP client using only stdlib.
loop
Package loop implements the ReAct (Reasoning + Acting) agent loop.
Package loop implements the ReAct (Reasoning + Acting) agent loop.
mcp
Package mcp implements a Model Context Protocol server over stdio.
Package mcp implements a Model Context Protocol server over stdio.
mcpclient
Package mcpclient implements an MCP client that connects to external MCP servers over stdio.
Package mcpclient implements an MCP client that connects to external MCP servers over stdio.
memory
Package memory provides persistent, agent-managed memory across sessions.
Package memory provides persistent, agent-managed memory across sessions.
render
Package render provides emoji-driven terminal rendering for the kode agent loop.
Package render provides emoji-driven terminal rendering for the kode agent loop.
resource
Package resource implements @-prefixed resource discovery and inline resolution.
Package resource implements @-prefixed resource discovery and inline resolution.
session
Package session persists agent conversation history across runs.
Package session persists agent conversation history across runs.
skills
Package skills implements kode's skill system — just-in-time agent specialization.
Package skills implements kode's skill system — just-in-time agent specialization.
tool
Package tool defines the Tool interface and a thread-safe registry.
Package tool defines the Tool interface and a thread-safe registry.
ws
Package ws implements RFC 6455 WebSocket framing with zero external dependencies.
Package ws implements RFC 6455 WebSocket framing with zero external dependencies.

Jump to

Keyboard shortcuts

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