omnix

module
v0.1.14 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT

README

omnix

An embeddable Go runtime for stateful, tool-using AI agents.

English · 简体中文

omnix brings the agent loop, tool execution, and replayable session state into your Go process. It combines an append-only event log with derived projections, a four-stage tool pipeline, and a streaming DeepSeek adapter. Planning, persistence, subagents, and workflows are available as separate packages.

The project is under active development. Start with the local examples, then assemble the components your application needs.

What you can build

  • Agents with inspectable history. Record turns, model responses, tool calls, and results as session events; derive current state or replay a stored conversation.
  • Tools with execution policies. Validate arguments and apply approval decisions, restrictions, timeouts, and result processing through middleware.
  • Stateful planning. Track goals, todos, and plan mode alongside the conversation; expose selected planning tools to the model.
  • Go application integrations. Supply an LLM adapter, register tools, choose persistence, and compose subagents or workflows within your application.

Quick start

Requires Go 1.25 or later. SQLite support uses the pure-Go modernc.org/sqlite driver.

git clone https://github.com/herlanai/omnix.git
cd omnix
go run ./examples/agent_loop
go run ./examples/tutorial

These two examples run without a model API key. agent_loop uses a scripted adapter to demonstrate a complete tool-call cycle. The tutorial covers sessions and projections; its goal-tool section currently prints GOAL_NOT_FOUND because no goal has been created.

To add omnix to an existing Go module:

go get github.com/herlanai/omnix
Create a session

Session events are the source of truth. Enable incremental projections when reading state repeatedly as new events arrive.

package main

import (
	"fmt"

	"github.com/herlanai/omnix/pkg/brand"
	"github.com/herlanai/omnix/pkg/session"
)

func main() {
	log := session.NewSessionLog(brand.NewSessionID("hello"))
	log.EnableIncrementalProjection()

	if _, err := log.Append(session.UserMessageData{Content: "Hello, omnix!"}); err != nil {
		panic(err)
	}

	for _, message := range log.Projection().Messages {
		fmt.Printf("%s: %s\n", message.Role, message.Content)
	}
}

Output:

user: Hello, omnix!
Run an agent

The agent-loop example shows the complete wiring: a SessionLog, system prompt, tool Pipeline, and llm.LLMAdapter passed to agent.NewAgent.

The execution lifecycle is asynchronous:

  1. Configure the adapter, tools, and middleware before starting the agent.
  2. Set the execution context with SetRunContext.
  3. Submit input with Run or Followup; their return value reports whether the input was accepted.
  4. Use WhenIdle(ctx) to wait for accepted work to finish. Inspect session events for model/tool errors and turn completion reasons.
  5. Call Cancel to stop active work, and Dispose when the agent is no longer needed.

A timeout on WhenIdle stops waiting. Execution cancellation is controlled by the run context or Cancel. Tool implementations must honor their context.

Try the DeepSeek adapter

The chat example makes live API requests and requires your own credentials:

export DEEPSEEK_API_KEY="your-api-key"
export DEEPSEEK_MODEL="deepseek-chat"
go run ./examples/chat

DEEPSEEK_MODEL is optional; the example defaults to deepseek-chat. This example demonstrates streaming model access directly. Use the agent-loop example to learn tool dispatch and session recording.

How it fits together

Application input
       |
       v
Agent turn / step loop <----> LLM adapter
       |                         |
       |                    Tool requests
       |                         v
       |        pre -> execute -> post -> result
       |                         |
       +------ session events ---+
                    |
                    v
             Append-only log
              /           \
       Projections     Persistence

A turn can contain several model/tool steps. Events preserve what happened, projections expose the current view, and persistence stores history for later loading and replay. Surface replacements let compaction change the visible history while retaining source events.

Packages

Area Packages Purpose
Runtime agent, session, eventbus Execution lifecycle, event history, projections, notifications
Model access llm, provider_deepseek Adapter contract, streaming, usage, failure classification
Tools tools, approval, sandbox Schemas, middleware, access decisions, execution confinement
Planning goal, todo, plan, skills Goal state, task lists, plan mode, skill discovery
Storage persistence, sqlite, storage JSONL, SQLite/FTS5, scoped storage
Composition subagent, workflow, mcp Child-agent interfaces, orchestration, MCP tool bridging
Local execution fs, shell, subprocess, jobs Files, commands, processes, background work
Observability telemetry, tokenmeter Session metrics, token estimates, budgets

Examples

Run each command from the repository root.

Command Demonstrates
go run ./examples/tutorial Events, projections, and goal-tool validation
go run ./examples/agent_loop Model requests, tool execution, and turn completion with a scripted adapter
go run ./examples/usage SDK components and JSONL persistence
go run ./examples/todo Todo writes and derived state
go run ./examples/workflow Sequential and parallel orchestration
go run ./examples/subagent Child-agent backends and lifecycle
go run ./examples/sandbox_approval Sandbox-mode and approval-policy resolution
go run ./examples/mcp MCP tool bridging with an in-memory transport
go run ./examples/chat Live DeepSeek streaming; requires an API key

Performance

Recent work reduces allocation in event dispatch, uses merged intervals for visible-history filtering, and removes reflection from incremental preset comparison. Local measurements below are medians of three runs on an Apple M5, macOS arm64, with Go 1.26.2.

Microbenchmark Before After
Dispatch to 16 listeners 34.17 ns/op; 1 alloc/op 13.28 ns/op; 0 allocs/op
Filter 10,000 events with a replacement range 215.73 μs/op 99.27 μs/op
Incrementally process 10,000 events 1.010 ms/op; 21,683 allocs/op 0.493 ms/op; 1,683 allocs/op

Results vary with hardware and workload. Event-bus dispatch avoids allocation by copying the listener list during registration and removal, favoring workloads with frequent dispatch and infrequent listener changes.

Reproduce the current benchmarks:

go test ./pkg/eventbus ./pkg/session -run '^$' \
  -bench 'BenchmarkEmit|BenchmarkEffectiveEvents' -benchmem -count=3
go test ./tests -run '^$' \
  -bench '^BenchmarkIncrementalH04IncrementalPath$' -benchmem -count=3
go test ./tests -run '^$' -bench '^BenchmarkSQLiteSearch$' -benchmem

Development

gofmt -w examples internal pkg tests
go vet ./...
go test ./...
go test -race ./...

Tests include local HTTP/SSE mock servers; the test environment must allow loopback listeners. Keep code comments in English and add regression tests for behavior changes. Measure performance changes with benchmarks separately from functional assertions.

Implementation scope

The built-in model adapter targets DeepSeek. Other providers implement llm.LLMAdapter; the adapter passed to the constructor handles requests, and AgentOptions.Provider does not provide runtime provider routing.

MCP network transports, complete inbox steering, and automatic orchestration of compaction and retry policies still require further integration. Sandbox enforcement varies by backend, and the Windows implementation contains incomplete enforcement paths. Review the relevant package before relying on it in a deployment.

See SDK execution behavior and integration boundaries for details.

Documentation

Start with the English guides or 简体中文文档.

Origins and license

omnix started from dsh-go and draws on the DeepSeek Harness design. This repository develops its own Go implementation and does not claim complete upstream feature parity.

Released under the MIT License. The original copyright notice is preserved.

Directories

Path Synopsis
examples
agent_loop command
This example demonstrates the in-process omnix Agent turn/step loop.
This example demonstrates the in-process omnix Agent turn/step loop.
chat command
This example calls the real DeepSeek REST and SSE APIs for a multi-turn conversation.
This example calls the real DeepSeek REST and SSE APIs for a multi-turn conversation.
image_agent command
This example lets the model call Ark image generation and return image URLs.
This example lets the model call Ark image generation and return image URLs.
mcp command
MCP client-to-tool bridging tutorial.
MCP client-to-tool bridging tutorial.
sandbox_approval command
Sandbox and approval tutorial.
Sandbox and approval tutorial.
subagent command
Subagent tutorial: spawn child tasks and collect their results.
Subagent tutorial: spawn child tasks and collect their results.
todo command
Todo tutorial: each todo_write replaces the entire list with last-write-wins semantics, matching upstream.
Todo tutorial: each todo_write replaces the entire list with last-write-wins semantics, matching upstream.
tutorial command
Tutorial: understand the omnix Agent kernel through small, independent Go implementations of DeepSeek Harness concepts.
Tutorial: understand the omnix Agent kernel through small, independent Go implementations of DeepSeek Harness concepts.
usage command
This example embeds omnix in a Go service.
This example embeds omnix in a Go service.
web_agent command
This example lets the model choose when to search the web and fetch pages.
This example lets the model choose when to search the web and fetch pages.
workflow command
Workflow tutorial.
Workflow tutorial.
internal
lint
Package lint provides AST-based cache-safety checks (N06).
Package lint provides AST-based cache-safety checks (N06).
telemetry
Package telemetry provides cache-hit metrics for Grafana and OTel integration (N09).
Package telemetry provides cache-hit metrics for Grafana and OTel integration (N09).
pkg
agent
Package agent provides the agent registry and the Turn/Step execution loop.
Package agent provides the agent registry and the Turn/Step execution loop.
approval
Package approval implements approval policies, matching packages/core/approval (M27).
Package approval implements approval policies, matching packages/core/approval (M27).
attachment
Upload admission matches attachment/admission: base64 must round-trip to the identical encoding so alternate representations cannot bypass validation.
Upload admission matches attachment/admission: base64 must round-trip to the identical encoding so alternate representations cannot bypass validation.
brand
Package brand provides branded types to prevent mixing raw strings or bytes across package contracts, matching util/id-brand and util/bytes upstream.
Package brand provides branded types to prevent mixing raw strings or bytes across package contracts, matching util/id-brand and util/bytes upstream.
coderuntime
Package coderuntime defines the code-execution protocol from packages/code-runtime.
Package coderuntime defines the code-execution protocol from packages/code-runtime.
commands
Package commands implements slash commands, matching interaction/commands.
Package commands implements slash commands, matching interaction/commands.
compaction
Package compaction summarizes long conversations using surface replacement (S01), matching compaction/compaction and compaction-engine-basic.
Package compaction summarizes long conversations using surface replacement (S01), matching compaction/compaction and compaction-engine-basic.
eventbus
Package eventbus provides a typed, in-process event bus modeled on Cordis.
Package eventbus provides a typed, in-process event bus modeled on Cordis.
feedback
Package feedback implements message feedback using Storage Domain sidecars and stable failure classes, matching feedback/feedback (S09).
Package feedback implements message feedback using Storage Domain sidecars and stable failure classes, matching feedback/feedback (S09).
fileref
Package fileref implements context/file-reference @ mentions: find the token at the cursor and format selected paths as @path or @"path".
Package fileref implements context/file-reference @ mentions: find the token at the cursor and format selected paths as @path or @"path".
fs
Package fs implements the filesystem interface, matching fs/fs, fs-local, and fs-observation-policy (M35).
Package fs implements the filesystem interface, matching fs/fs, fs-local, and fs-observation-policy (M35).
goal
Goal failure classes and block reasons match upstream goal (review fix R06).
Goal failure classes and block reasons match upstream goal (review fix R06).
homepath
Package homepath resolves the user data root using explicit configuration, then OMNIX_HOME, then ~/.omnix.
Package homepath resolves the user data root using explicit configuration, then OMNIX_HOME, then ~/.omnix.
imagegen/provider_ark
Package provider_ark provides non-streaming Seedream image generation and an Agent-compatible tool.
Package provider_ark provides non-streaming Seedream image generation and an Agent-compatible tool.
instructions
Package instructions implements pure instruction-file discovery logic from context/agent-instructions: project roots, ancestor chains, and per-directory deduplication.
Package instructions implements pure instruction-file discovery logic from context/agent-instructions: project roots, ancestor chains, and per-directory deduplication.
invariant
Package invariant registers invariant checks, matching runtime-diagnostics/invariants.
Package invariant registers invariant checks, matching runtime-diagnostics/invariants.
jobs
Package jobs implements background jobs (S11) and owner binding (M46), matching jobs/jobs.
Package jobs implements background jobs (S11) and owner binding (M46), matching jobs/jobs.
launchenv
Package launchenv freezes environment layers at launch, matching util/launch-environment.
Package launchenv freezes environment layers at launch, matching util/launch-environment.
llm
This file adapts upstream packages/llm/llm/src/assembler.ts to the simplified text/reasoning/tool-call/done protocol.
This file adapts upstream packages/llm/llm/src/assembler.ts to the simplified text/reasoning/tool-call/done protocol.
llm/provider_deepseek
Package provider_deepseek implements the DeepSeek REST and SSE adapter, following upstream packages/llm/providers.
Package provider_deepseek implements the DeepSeek REST and SSE adapter, following upstream packages/llm/providers.
mcp
Package mcp bridges Model Context Protocol clients to tool definitions (S13).
Package mcp bridges Model Context Protocol clients to tool definitions (S13).
persistence
Package persistence provides checkpoint flushing, batched writes, and crash repair, following upstream session persistence and JSONL storage.
Package persistence provides checkpoint flushing, batched writes, and crash repair, following upstream session persistence and JSONL storage.
persistence/sqlite
Package sqlite implements SQLite session persistence and FTS5 indexing (S03), following upstream storage/sqlite-session.
Package sqlite implements SQLite session persistence and FTS5 indexing (S03), following upstream storage/sqlite-session.
plan
Package plan provides plan-mode guidance and approval-gated exit, matching core/plan-mode.
Package plan provides plan-mode guidance and approval-gated exit, matching core/plan-mode.
presets
Package presets implements agent presets, matching core/agent-preset.
Package presets implements agent presets, matching core/agent-preset.
registry
Freezable shared registries (H07) optimize read-heavy post-startup access.
Freezable shared registries (H07) optimize read-heavy post-startup access.
retain
Package retain implements bounded logical-item retention from util/output-retention.
Package retain implements bounded logical-item retention from util/output-retention.
sandbox
This file implements sandbox escalation, following upstream escalation.ts.
This file implements sandbox escalation, following upstream escalation.ts.
schedule
Package schedule implements in-process reminders: after for relative one-shot delays, at for absolute one-shot times, and every for fixed intervals of at least five minutes.
Package schedule implements in-process reminders: after for relative one-shot delays, at for absolute one-shot times, and every for fixed intervals of at least five minutes.
scope
Explicit scope parents supplement layered scopes, matching bindScopeParent, scopeParentOf, and scopeChainOf upstream.
Explicit scope parents supplement layered scopes, matching bindScopeParent, scopeParentOf, and scopeChainOf upstream.
session
This file implements the session/end-seed boundary marker (M20), following upstream session semantics.
This file implements the session/end-seed boundary marker (M20), following upstream session semantics.
sessionquery
Package sessionquery queries sessions and FTS5 search (S04), matching storage/session-query.
Package sessionquery queries sessions and FTS5 search (S04), matching storage/session-query.
sessiontitle
Title normalization matches session-title/normalize: remove escapes, control and directional characters, normalize whitespace, and truncate to a UTF-8 byte budget without splitting characters.
Title normalization matches session-title/normalize: remove escapes, control and directional characters, normalize whitespace, and truncate to a UTF-8 byte budget without splitting characters.
settings
Package settings implements ctx.settings with layered scopes, path operations, CAS revisions, and secret redaction, matching settings/settings and settings-file.
Package settings implements ctx.settings with layered scopes, path operations, CAS revisions, and secret redaction, matching settings/settings and settings-file.
shell
Package shell implements shell execution and tool-bash, matching shell/shell, bash-local, bash-sandbox, and tool-bash (M37).
Package shell implements shell execution and tool-bash, matching shell/shell, bash-local, bash-sandbox, and tool-bash (M37).
skills
Skill grammar matches upstream kebab-case names and skill_content rendering.
Skill grammar matches upstream kebab-case names and skill_content rendering.
spill
Package spill implements large-result storage (M42), matching spill/spill, spill-local, and spill-policy.
Package spill implements large-result storage (M42), matching spill/spill, spill-local, and spill-policy.
storage
Filesystem-backed key-value storage.
Filesystem-backed key-value storage.
subagent
Delegation depth matches subagent/src/depth.ts: roots start at zero and each child adds one.
Delegation depth matches subagent/src/depth.ts: roots start at zero and each child adds one.
subprocess
Local subprocess implementation using os/exec, process-tree termination, environment scrubbing, and spills.
Local subprocess implementation using os/exec, process-tree termination, environment scrubbing, and spills.
sysprompt
PromptContext registration and snapshots (M10), matching context-prompt.
PromptContext registration and snapshots (M10), matching context-prompt.
telemetry
Anonymous identity matches identity/anonymous-user-id: persist one random UUID per Harness home in .anonymous-user-id.
Anonymous identity matches identity/anonymous-user-id: persist one random UUID per Harness home in .anonymous-user-id.
terminal
Terminal sanitization matches terminal-bash: strip ANSI CSI/OSC escape sequences from raw PTY output and normalize line endings into displayable plain text.
Terminal sanitization matches terminal-bash: strip ANSI CSI/OSC escape sequences from raw PTY output and normalize line endings into displayable plain text.
timecontext
Package timecontext renders request-time context matching context/time-context.
Package timecontext renders request-time context matching context/time-context.
todo
Todo normalization enforces constraints beyond schema: nonblank trimmed content, unique content, and at most one in_progress item without parallel mode.
Todo normalization enforces constraints beyond schema: nonblank trimmed content, unique content, and at most one in_progress item without parallel mode.
tokenmeter
Fixed-density token estimation matches token-meter/src/estimate.ts.
Fixed-density token estimation matches token-meter/src/estimate.ts.
tools
Match the upstream session checkpoint policy for cancellation before dispatch.
Match the upstream session checkpoint policy for cancellation before dispatch.
userq
Package userq provides User Questions, matching interaction/user-questions.
Package userq provides User Questions, matching interaction/user-questions.
uuid
Package uuid generates RFC 9562 version-4 UUIDs, matching util/crypto randomUUID.
Package uuid generates RFC 9562 version-4 UUIDs, matching util/crypto randomUUID.
waterfall
Package waterfall provides generic middleware chains matching core/waterfall.
Package waterfall provides generic middleware chains matching core/waterfall.
workflow
Ralph orchestration matches workflow/tool-ralph.
Ralph orchestration matches workflow/tool-ralph.
workspace
Workspace path helpers match util/workspace-path: resolve relative paths against roots, abbreviate home as ~, and derive display titles from final segments.
Workspace path helpers match util/workspace-path: resolve relative paths against roots, abbreviate home as ~, and derive display titles from final segments.
tests
testutil
Package testutil provides mock DeepSeek helpers for N07 cache E2E tests.
Package testutil provides mock DeepSeek helpers for N07 cache E2E tests.

Jump to

Keyboard shortcuts

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