ai

package
v0.0.44 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// SystemRulesFile is the legacy rules file that Claude's Prepare hook cleans up.
	SystemRulesFile = ".openbee.md"
	// ImportLine is the legacy reference line that Claude's Prepare hook removes from CLAUDE.md.
	ImportLine = "@" + SystemRulesFile
)
View Source
const (
	EngineClaude = "claude"
	EngineCodex  = "codex"
	EnginePi     = "pi"
)

Engine name constants used for registration and configuration.

Variables

View Source
var DefaultRegistry = NewRegistry()

DefaultRegistry is the process-wide registry populated by engine init() functions.

View Source
var ErrSessionDataNotFound = errors.New("ai: session data not found")

ErrSessionDataNotFound is returned by CollectTokenUsage when no session data exists.

View Source
var ErrUnknownEngine = fmt.Errorf("unknown engine")

ErrUnknownEngine is returned when New is called with an unregistered engine name.

Functions

func AllEngines added in v0.0.26

func AllEngines() []string

AllEngines returns a snapshot of the canonical engine name list in registration order.

func AppendExtraEnv added in v0.0.26

func AppendExtraEnv(base []string, extraEnv map[string]string) []string

AppendExtraEnv appends non-empty entries from extraEnv to base and returns the result re-clipped to its length, preventing concurrent Run() appends from sharing the backing array with other goroutines.

func BuildBaseEnv

func BuildBaseEnv() []string

BuildBaseEnv constructs the base environment for engine subprocesses. It prepends the current executable's directory to PATH. OPENBEE_URL is inherited from the server process environment (set via os.Setenv at startup).

func BuildBeeSessionPrefix added in v0.0.36

func BuildBeeSessionPrefix() string

BuildBeeSessionPrefix returns the Step 1 + Step 2 header for a new bee session.

func BuildRunEnv added in v0.0.24

func BuildRunEnv(baseEnv, extraEnv []string, apiKey string) []string

BuildRunEnv assembles the final env slice for a subprocess run. Entries are ordered baseEnv → extraEnv → apiKey; for duplicate keys the last value wins (standard subprocess env resolution on Linux/macOS), so extraEnv overrides baseEnv and apiKey overrides both.

func BuildWorkerSessionPrefix added in v0.0.36

func BuildWorkerSessionPrefix(persona string) string

BuildWorkerSessionPrefix returns the Step 1 + Step 2 header for a new worker session. When persona is non-empty it is embedded inside <worker_persona>.

func ConfigureCmd added in v0.0.33

func ConfigureCmd(cmd *exec.Cmd)

ConfigureCmd puts the engine subprocess in its own process group so Stop() can kill the entire group, including child processes the engine spawns (e.g. bash tool subprocesses).

func Register

func Register(name string, f Factory)

Register adds a factory to the DefaultRegistry.

func ScanJSONLines

func ScanJSONLines(r io.Reader, fn func(line string) bool)

ScanJSONLines reads r line by line and calls fn for each line that starts with '{'. fn returns true to keep scanning or false to stop early.

func WorkerPersona

func WorkerPersona(name, description, constraints string) string

WorkerPersona returns the persona-only content injected into new worker session prompts.

Types

type CmdProcess

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

CmdProcess implements Process for an os/exec.Cmd.

func NewCmdProcess

func NewCmdProcess(cmd *exec.Cmd) *CmdProcess

NewCmdProcess wraps an exec.Cmd as a Process.

func (*CmdProcess) PID

func (p *CmdProcess) PID() int

func (*CmdProcess) Stop

func (p *CmdProcess) Stop() error

Requires that ConfigureCmd was called on the underlying cmd before Start.

type DynamicAdapter added in v0.0.26

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

DynamicAdapter wraps multiple EngineAdapters and routes each Run call to whichever engine cfg.Get() returns at call time. The RunResult's ExtractResult closes over the engine that was actually picked, so callers processing results asynchronously are immune to later /engine switches.

func NewDynamicAdapter added in v0.0.26

func NewDynamicAdapter(engines map[string]EngineAdapter, cfg *enginecfg.Store) *DynamicAdapter

NewDynamicAdapter constructs a DynamicAdapter routing through cfg.

func (*DynamicAdapter) CollectTokenUsage added in v0.0.32

func (d *DynamicAdapter) CollectTokenUsage(ctx context.Context, sessionID string) ([]TokenUsage, error)

func (*DynamicAdapter) Prepare added in v0.0.26

func (d *DynamicAdapter) Prepare(workDir string, opts PrepareOptions) error

Prepare initialises every engine adapter for the given workDir. Most engines have a no-op Prepare; the only meaningful work (Claude's legacy file cleanup) is a single os.Remove, so a sequential loop is sufficient.

func (*DynamicAdapter) Run added in v0.0.26

func (d *DynamicAdapter) Run(ctx context.Context, workDir, prompt string, opts RunOptions, logPath string) (RunResult, error)

type EngineAdapter

type EngineAdapter interface {
	// Prepare is an engine-specific initialisation hook called before each Run.
	// It must be idempotent. Claude uses it to clean up legacy config files;
	// other engines return nil.
	Prepare(workDir string, opts PrepareOptions) error

	// Run executes a task and returns a RunResult carrying the process handle,
	// event channel, and an engine-bound result extractor. The event channel
	// is closed after the process exits.
	Run(ctx context.Context, workDir, prompt string,
		opts RunOptions, logPath string) (RunResult, error)

	// CollectTokenUsage reads per-turn token usage for the given session from
	// engine-specific storage. Returns ErrSessionDataNotFound when no data is
	// available for the session.
	CollectTokenUsage(ctx context.Context, sessionID string) ([]TokenUsage, error)
}

EngineAdapter is the complete plugin contract for an AI engine. Implementations must be safe for concurrent use.

func New

func New(name string, cfg EngineConfig) (EngineAdapter, error)

New constructs an engine from the DefaultRegistry.

type EngineArgsMap added in v0.0.32

type EngineArgsMap map[string][]string

func MergeEngineArgs added in v0.0.32

func MergeEngineArgs(base, override EngineArgsMap) EngineArgsMap

MergeEngineArgs merges base and override by appending override args after base args, so later flags can override earlier ones while preserving the original CLI ordering.

func ParseEngineArgs added in v0.0.32

func ParseEngineArgs(raw map[string]string) (EngineArgsMap, error)

ParseEngineArgs tokenizes raw CLI strings per engine while preserving order, duplicates, and quoted values.

func ParseEngineArgsJSON added in v0.0.32

func ParseEngineArgsJSON(value string) EngineArgsMap

ParseEngineArgsJSON returns nil for empty/unset values.

type EngineConfig

type EngineConfig struct {
	// Raw holds engine-specific configuration (parsed from config.yaml).
	Raw map[string]any
}

EngineConfig holds the configuration passed to a Factory when constructing an engine.

func (EngineConfig) ExtraEnv added in v0.0.26

func (c EngineConfig) ExtraEnv() map[string]string

ExtraEnv returns Raw["env"] as a map[string]string, or nil if absent / mistyped.

func (EngineConfig) PathOrDefault added in v0.0.26

func (c EngineConfig) PathOrDefault(def string) string

PathOrDefault returns Raw["path"] when it's a non-empty string, else def.

type Factory

type Factory func(cfg EngineConfig) (EngineAdapter, error)

Factory creates an EngineAdapter from the supplied config.

type Output

type Output struct {
	Type    OutputType `json:"type"`
	Content string     `json:"content"`
}

Output is a single lifecycle event.

type OutputType

type OutputType string

OutputType classifies a lifecycle event from a running process.

const (
	OutputDone  OutputType = "done"
	OutputError OutputType = "error"
)

type PrepareOptions

type PrepareOptions struct {
	Role Role
}

PrepareOptions carries parameters for the engine-specific Prepare hook. Add future fields here without changing the Prepare method signature.

type Process

type Process interface {
	PID() int
	Stop() error
}

Process is the handle for a running engine process.

type Registry

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

Registry maps engine names to their factories.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates an empty Registry.

func (*Registry) New

func (r *Registry) New(name string, cfg EngineConfig) (EngineAdapter, error)

New constructs the engine registered under name.

func (*Registry) Register

func (r *Registry) Register(name string, f Factory)

Register adds a factory under name. Panics if name is already registered.

type Role

type Role string

Role identifies the openbee agent role.

const (
	RoleBee    Role = "bee"
	RoleWorker Role = "worker"
)

type RunOptions

type RunOptions struct {
	SessionID string
	Resume    bool
	APIKey    string
	ExtraEnv  []string // additional KEY=VALUE env vars to inject
	ExtraArgs []string // additional CLI args to pass to the engine
}

RunOptions controls session behaviour for an engine invocation.

type RunResult added in v0.0.26

type RunResult struct {
	Process       Process
	Output        <-chan Output
	ExtractResult func(logPath string) string
}

RunResult is the handle returned from EngineAdapter.Run. ExtractResult is bound to the engine that handled this Run, so it remains correct even if the active engine later changes.

func NewRunResult added in v0.0.26

func NewRunResult(proc Process, out <-chan Output, err error, extract func(logPath string) string) (RunResult, error)

NewRunResult wraps the (process, output, error) tuple returned by an engine invoker into a RunResult, attaching the engine's result extractor on success.

type TokenUsage added in v0.0.32

type TokenUsage struct {
	Model               string
	InputTokens         int64
	OutputTokens        int64
	CacheCreationTokens int64
	CacheReadTokens     int64
}

TokenUsage holds per-model token consumption for a single session turn.

func DrainUsageMap added in v0.0.32

func DrainUsageMap(agg map[string]*TokenUsage) []TokenUsage

DrainUsageMap converts a model→*TokenUsage aggregation map into a flat slice.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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