kernel

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Overview

Package kernel — civilization primitives.

The 9 technical primitives (sandbox, session, provider, control + 5 syscalls) let the agent talk to a computer. The 4 civilization primitives let the agent talk to humanity: who the user is (identity), what the agent knows across time (recall), how it proves what it did (trust), and how it gets better (learn).

Package kernel defines the minimal, immutable core of the OK agent. Everything outside this package is a plugin — including 54 built-in tools and any number of MCP plugins.

The kernel has exactly 13 components:

4 platform services — sandbox, session, provider, control
5 LLM syscalls     — bash, read_file, write_file, edit_file, grep
4 civilization primitives — identity, recall, trust, learn

These 4 civilization primitives give the agent a concept of personhood (identity), long-term memory (recall), verifiability (trust), and self-evolution (learn). Without them the agent is a tool without context; with them it becomes a civilization-scale infrastructure.

The Kernel struct stores pre-built adapters; create via boot.Build() which wires all 13 components. A zero-value Kernel will not panic on construction but calling methods on nil interface fields will — always use boot.Build().

Design note — adapter location

The concrete adapter implementations (adapters.go, tools.go) live in this package alongside the interfaces. This is a pragmatic choice: Go does not allow same-level subpackages to import their parent, so moving adapters to kernel/adapter/ would require duplicating all interface types and break type identity (kernel.Sandbox ≠ adapter.Sandbox). The adapters depend on 7 internal packages (agent, provider, sandbox, etc.) — those dependencies are compile-time and do not create circular imports because they all flow through the boot package (the composition root). A future Go version with cleaner module-level dependency management may allow a kernel/adapter/ split.

Package kernel — sandbox.go was removed. Plugin sandbox isolation has moved to internal/sandbox/.

Package kernel — sandbox_stub.go was removed. Replaced by internal/sandbox/ package.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewIdentityTool

func NewIdentityTool(inner Identity) tool.Tool

NewIdentityTool wraps a kernel.Identity as a callable tool.Tool.

func NewLearnTool

func NewLearnTool(inner Learn) tool.Tool

NewLearnTool wraps a kernel.Learn as a callable tool.Tool.

func NewRecallTool

func NewRecallTool(inner Recall) tool.Tool

NewRecallTool wraps a kernel.Recall as a callable tool.Tool.

func NewTrustTool

func NewTrustTool(inner Trust) tool.Tool

NewTrustTool wraps a kernel.Trust as a callable tool.Tool.

Types

type Bash

type Bash interface {
	Exec(ctx context.Context, command string, bg bool) BashOut
}

Bash is LLM's universal execution channel.

func NewBash

func NewBash(sb Sandbox) Bash

NewBash creates a kernel Bash backed by the Sandbox primitive.

type BashOut

type BashOut struct {
	Output   string `json:"output"`
	JobID    string `json:"job_id,omitempty"`
	ExitCode int    `json:"exit_code"`
}

type Chunk

type Chunk struct {
	Type   ChunkType       `json:"type"`
	Text   string          `json:"text,omitempty"`
	ToolID string          `json:"tool_id,omitempty"`
	Data   json.RawMessage `json:"data,omitempty"`
}

type ChunkType

type ChunkType int
const (
	ChunkText ChunkType = iota
	ChunkReasoning
	ChunkToolCall
	ChunkToolResult
	ChunkUsage
	ChunkError
)

type Controller

type Controller interface {
	Send(ctx context.Context, input string) error
	Cancel()
	SetPlanMode(bool)
	Events() <-chan Event
}

Controller is the transport-agnostic session driver.

type EditFile

type EditFile interface {
	Edit(ctx context.Context, path, oldString, newString string) error
}

EditFile gives LLM precise string replacement.

func NewEditFile

func NewEditFile(roots []string, workDir string) EditFile

NewEditFile creates a kernel EditFile with optional root confinement.

type Event

type Event struct {
	Kind  EventKind  `json:"kind"`
	Text  string     `json:"text,omitempty"`
	Tool  *ToolEvent `json:"tool,omitempty"`
	Error string     `json:"error,omitempty"`
}

type EventKind

type EventKind int
const (
	EventTurnStarted EventKind = iota
	EventReasoning
	EventText
	EventToolCall
	EventToolResult
	EventTurnDone
)

type Fact

type Fact struct {
	ID        string            `json:"id"`
	Scope     string            `json:"scope"`  // "session" | "project" | "global"
	Key       string            `json:"key"`    // short slug, e.g. "user-prefers-dark-mode"
	Value     string            `json:"value"`  // the remembered content
	Source    string            `json:"source"` // what created it: "user", "agent", "skill"
	CreatedAt time.Time         `json:"createdAt"`
	TTL       time.Duration     `json:"ttl,omitempty"` // 0 = forever
	Tags      map[string]string `json:"tags,omitempty"`
}

Fact is one unit of recall — a thing the agent knows.

type FileContent

type FileContent struct {
	Path      string `json:"path"`
	Content   string `json:"content"`
	Lines     int    `json:"lines"`
	Size      int    `json:"size"`
	Truncated bool   `json:"truncated,omitempty"`
	Binary    bool   `json:"binary,omitempty"`
	Error     string `json:"error,omitempty"`
}

type Grep

type Grep interface {
	Search(ctx context.Context, pattern, path string) ([]Match, error)
}

Grep gives LLM instant regex search.

func NewGrep

func NewGrep(roots []string, workDir string) Grep

NewGrep creates a kernel Grep with optional root confinement.

type Identity

type Identity interface {
	// Whoami returns the current user's identity. The zero value means
	// "anonymous / no identity configured" — the agent runs with defaults.
	Whoami(ctx context.Context) User

	// SetUser switches the active user for this session.
	// An empty id means "log out" (return to anonymous).
	SetUser(ctx context.Context, id string) error

	// ListUsers returns all known user profiles on this device.
	ListUsers(ctx context.Context) ([]User, error)
}

Identity answers "who am I serving?" — the user's identity across devices, their role, preferences, and trust relationships. This is the kernel's concept of "personhood", without which the agent is a tool without context.

func NewIdentity

func NewIdentity() Identity

NewIdentity creates a kernel Identity backed by local config and OS user.

type Kernel

type Kernel struct {
	Sandbox    Sandbox
	Session    Session
	Provider   Provider
	Controller Controller

	Bash      Bash
	ReadFile  ReadFile
	WriteFile WriteFile
	EditFile  EditFile
	Grep      Grep

	// Civilization primitives
	Identity Identity
	Recall   Recall
	Trust    Trust
	Learn    Learn
}

Kernel carries 4 civilization primitive adapters (Identity, Recall, Trust, Learn) that frontends can read for agent metadata. The remaining 9 fields (Sandbox, Session, Provider, Controller, Bash, ReadFile, WriteFile, EditFile, Grep) are architectural declarations — only the civ primitives are populated at boot. Create via boot.Build(); zero-value Kernel will panic on method calls against nil interfaces.

func (*Kernel) IsSyscall

func (k *Kernel) IsSyscall(name string) bool

IsSyscall reports whether name is a kernel syscall.

func (*Kernel) Schema

func (k *Kernel) Schema() []ToolSchema

Schema returns the LLM tool schema for the 5 syscalls. This is the ONLY schema the kernel exposes — plugins add their own.

func (*Kernel) SyscallNames

func (k *Kernel) SyscallNames() []string

SyscallNames returns the 5 built-in syscall tool names.

type Learn

type Learn interface {
	// Extract analyzes a completed task and returns patterns (reusable
	// approaches, anti-patterns, tool combinations).
	Extract(ctx context.Context, task TaskRecord) ([]Pattern, error)

	// Generate creates a candidate skill from successful patterns.
	// The skill is not yet validated — it must pass Validate first.
	Generate(ctx context.Context, patterns []Pattern) (Skill, error)

	// Validate runs the candidate skill in an isolated sandbox to verify
	// correctness. Returns nil when the skill is safe and effective.
	Validate(ctx context.Context, skill Skill) error

	// Publish makes a validated skill available to the agent's skill store.
	Publish(ctx context.Context, skill Skill) error

	// Stats returns learning metrics: how many skills learned, success rate, etc.
	Stats(ctx context.Context) LearnStats
}

Learn is the agent's self-evolution engine — it extracts patterns from completed tasks, generates reusable skills, validates them in a sandbox, and publishes them to the skill store. This is the kernel's "learning to learn" primitive.

Without Learn, the agent is a fixed-capability tool. With Learn, it improves with every task, accumulating skills across sessions and users.

func NewLearn

func NewLearn(skillsDir string) Learn

NewLearn creates a kernel Learn primitive. skillsDir is where generated skills are stored (empty = no persistence).

func NewLearnFromEngine

func NewLearnFromEngine(engine Learn) Learn

NewLearnFromEngine creates a kernel Learn backed by an external engine (typically evolution.Engine). All calls are forwarded to engine.

type LearnStats

type LearnStats struct {
	TotalSkills    int     `json:"totalSkills"`
	ExtractedToday int     `json:"extractedToday"`
	SuccessRate    float64 `json:"successRate"`
	AvgConfidence  float64 `json:"avgConfidence"`
}

LearnStats summarizes the agent's learning progress.

type Match

type Match struct {
	File    string `json:"file"`
	Line    int    `json:"line"`
	Text    string `json:"text"`
	Context string `json:"context,omitempty"`
}

type Message

type Message struct {
	Role    string          `json:"role"` // "user" | "assistant" | "tool"
	Content string          `json:"content"`
	Name    string          `json:"name,omitempty"`
	Meta    json.RawMessage `json:"meta,omitempty"`
}

type Pattern

type Pattern struct {
	ID           string   `json:"id"`
	Description  string   `json:"description"`
	ToolSequence []string `json:"toolSequence"`
	Frequency    int      `json:"frequency"` // how many times this pattern worked
	Confidence   float64  `json:"confidence"`
}

Pattern is a reusable approach extracted from a task.

type PluginIsolation

type PluginIsolation struct {
	Mode       string // "appcontainer" | "landlock" | "seccomp" | "docker"
	Network    bool
	ReadRoots  []string
	WriteRoots []string
}

type ProofEntry

type ProofEntry struct {
	AtomID      string    `json:"atomId"`             // unique claim identifier
	Proposition string    `json:"proposition"`        // what is being claimed
	Evidence    string    `json:"evidence"`           // supporting output
	ParentID    string    `json:"parentId,omitempty"` // parent atom, for nesting
	Path        string    `json:"path,omitempty"`     // file path, if relevant
	Timestamp   time.Time `json:"timestamp"`
	SHA256      string    `json:"sha256"` // hash of (parent + proposition + evidence)
}

ProofEntry is one link in the agent's proof chain.

type Provider

type Provider interface {
	Name() string
	Stream(ctx context.Context, req Request) (<-chan Chunk, error)
}

Provider connects to an LLM. Kernel is model-agnostic.

func NewProvider

func NewProvider(inner provider.Provider) Provider

NewProvider creates a kernel Provider backed by a provider.Provider.

type ReadFile

type ReadFile interface {
	Read(ctx context.Context, path string, offset, limit int) FileContent
}

ReadFile gives LLM precise file reading.

func NewReadFile

func NewReadFile(roots []string, workDir string) ReadFile

NewReadFile creates a kernel ReadFile with optional root confinement.

type Recall

type Recall interface {
	// Save stores a fact. TTL of 0 means "forever".
	Save(ctx context.Context, fact Fact) error

	// Search returns facts matching the query, newest first.
	Search(ctx context.Context, query string, limit int) ([]Fact, error)

	// Forget removes facts matching the query. Empty query is a no-op.
	Forget(ctx context.Context, query string) (int, error)
}

Recall is the agent's long-term memory — facts, patterns, skills that survive session boundaries. Unlike Session (short-term conversation state), Recall persists across reboots, model switches, and user sessions.

The kernel defines three memory tiers:

Ephemeral  — this-session-only (backed by Session)
Persistent — survives reboots (backed by memory.Store)
Procedural — learned skills (backed by skill.Store)

func NewRecall

func NewRecall(store *memory.Store) Recall

NewRecall creates a kernel Recall backed by memory.Store. store may be nil (returns empty results gracefully).

func NewRecallWithSemantic

func NewRecallWithSemantic(store *memory.Store, semantic SemanticSearcher) Recall

NewRecallWithSemantic creates a kernel Recall with an optional semantic search engine. When semantic is nil, falls back to substring matching.

type Request

type Request struct {
	Messages    []Message    `json:"messages"`
	Tools       []ToolSchema `json:"tools,omitempty"`
	Temperature float64      `json:"temperature,omitempty"`
}

type RunOptions

type RunOptions struct {
	WorkDir    string
	TimeoutSec int
	Network    bool
	Env        map[string]string
}

type RunResult

type RunResult struct {
	Output   string
	ExitCode int
	Error    string // non-empty on timeout, OOM, or sandbox denial
}

type Sandbox

type Sandbox interface {
	// Run executes a command confined by the sandbox policy.
	// Returns stdout+stderr combined.
	Run(ctx context.Context, command string, opts RunOptions) RunResult

	// Available reports whether the sandbox is functional on this platform.
	Available() bool

	// PluginSpec returns the isolation spec for a plugin subprocess.
	// nil means no additional isolation beyond the OS default.
	PluginSpec() *PluginIsolation
}

Sandbox isolates command execution. Plugins run inside it.

func NewSandbox

func NewSandbox(spec sandbox.Spec, workDir string) Sandbox

NewSandbox creates a kernel Sandbox backed by a sandbox.Spec.

type ScoredFact

type ScoredFact struct {
	Fact
	Score float64
}

ScoredFact is a search result with a relevance score.

type SemanticEngineAdapter

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

SemanticEngineAdapter wraps semantic.Engine to implement SemanticSearcher. This bridges the code-search-oriented semantic.Engine into the memory-oriented SemanticSearcher interface so Recall can use vector search.

func (*SemanticEngineAdapter) Search

func (a *SemanticEngineAdapter) Search(ctx context.Context, query string, limit int) ([]ScoredFact, error)

type SemanticSearcher

type SemanticSearcher interface {
	Search(ctx context.Context, query string, limit int) ([]ScoredFact, error)
}

SemanticSearcher provides semantic search over memory. nil means semantic search is unavailable; fall back to substring match.

func NewSemanticEngineAdapter

func NewSemanticEngineAdapter(eng *semantic.Engine) SemanticSearcher

NewSemanticEngineAdapter creates an adapter from a semantic engine.

type Session

type Session interface {
	Add(msg Message)
	Snapshot() []Message
	Compact(ctx context.Context) error
}

Session manages conversation state. All plugins share it.

func NewSession

func NewSession(inner *agent.Session) Session

NewSession creates a kernel Session backed by an agent.Session.

type Skill

type Skill struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Body        string `json:"body"`   // the skill prompt / playbook
	Source      string `json:"source"` // "extracted" | "authored"
	Version     int    `json:"version"`
}

Skill is a learnable capability the agent can execute.

type TaskRecord

type TaskRecord struct {
	Goal       string        `json:"goal"`
	Turns      int           `json:"turns"`
	ToolCalls  []ToolCallRec `json:"toolCalls"`
	Result     string        `json:"result"`
	DurationMs int64         `json:"durationMs"`
	Success    bool          `json:"success"`
}

TaskRecord captures what happened in one task for learning analysis.

type ToolCallRec

type ToolCallRec struct {
	Name   string `json:"name"`
	Args   string `json:"args"`
	Result string `json:"result"`
	Order  int    `json:"order"`
}

ToolCallRec records one tool invocation for learning.

type ToolEvent

type ToolEvent struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	Input    string `json:"input"`
	Output   string `json:"output,omitempty"`
	Error    string `json:"error,omitempty"`
	ReadOnly bool   `json:"read_only"`
}

type ToolSchema

type ToolSchema struct {
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Schema      json.RawMessage `json:"schema"`
}

type Trust

type Trust interface {
	// Record logs an action with supporting evidence. Returns a chain entry.
	Record(ctx context.Context, entry ProofEntry) error

	// Verify checks whether an atom ID's evidence chain is intact.
	// Returns nil when the chain is valid from root to tip.
	Verify(ctx context.Context, atomID string) error

	// Export returns the full proof chain for audit/debug.
	Export(ctx context.Context) ([]ProofEntry, error)

	// Summary returns a terse overview of what's been proven this session.
	Summary(ctx context.Context) TrustSummary
}

Trust is the agent's integrity layer — a tamper-evident record of what it did, what it found, and how it reached conclusions. Without Trust, the agent is a black box. With Trust, every output can be traced to evidence.

func NewTrust

func NewTrust(pc *core.ProofChain, ac *core.AuditChain) Trust

NewTrust creates a kernel Trust backed by proof and audit chains.

type TrustSummary

type TrustSummary struct {
	EntryCount int    `json:"entryCount"`
	LastAction string `json:"lastAction"` // most recent proposition
	Healthy    bool   `json:"healthy"`    // all chains verify
}

TrustSummary is a lightweight overview for the LLM's context window.

type User

type User struct {
	ID        string            `json:"id"`             // stable identifier across sessions/devices
	Label     string            `json:"label"`          // human-readable name
	Roles     []string          `json:"roles"`          // "admin", "developer", "child", …
	Locale    string            `json:"locale"`         // "zh-CN", "en-US", …
	ModelPref string            `json:"modelPref"`      // preferred model name
	Meta      map[string]string `json:"meta,omitempty"` // extensible
}

User is a person the agent serves. The kernel treats this as opaque metadata — it never interprets fields, it just carries them so the agent knows who it's talking to.

func (User) IsZero

func (u User) IsZero() bool

IsZero reports whether the User is the zero value (anonymous).

type WriteFile

type WriteFile interface {
	Write(ctx context.Context, path, content string) error
}

WriteFile gives LLM precise file writing.

func NewWriteFile

func NewWriteFile(roots []string, workDir string) WriteFile

NewWriteFile creates a kernel WriteFile with optional root confinement.

Directories

Path Synopsis
Package adapter provides concrete implementations of the kernel interfaces.
Package adapter provides concrete implementations of the kernel interfaces.

Jump to

Keyboard shortcuts

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