core

package module
v0.4.7 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: EUPL-1.2 Imports: 30 Imported by: 0

README

Core

codecov Go Version License Go Reference

Dependency injection and service lifecycle framework for Go. Zero external dependencies beyond testify for tests.

import "dappco.re/go/core"

Quick Start

c := core.New(core.Options{
    {Key: "name", Value: "myapp"},
})

// Register a service
c.Service("auth", core.Service{
    OnStart:  func() core.Result { return core.Result{OK: true} },
    OnStop:   func() core.Result { return core.Result{OK: true} },
})

// Retrieve it
r := c.Service("auth")
if r.OK { /* use r.Value */ }

// Register and run commands
c.Command("deploy", handler)
c.Cli().Run()

Primitives

Options

Key-value pairs that flow through all subsystems:

opts := core.Options{
    {Key: "name", Value: "brain"},
    {Key: "port", Value: 8080},
}

name := opts.String("name")
port := opts.Int("port")
ok   := opts.Has("debug")
Result

Universal return type replacing (value, error):

r := c.Data().New(core.Options{{Key: "name", Value: "store"}})
if r.OK { use(r.Value) }

// Map from Go conventions
r.Result(file, err)   // OK = err == nil, Value = file
Service

Managed component with optional lifecycle hooks:

core.Service{
    Name:     "cache",
    Options:  opts,
    OnStart:  func() core.Result { /* ... */ },
    OnStop:   func() core.Result { /* ... */ },
    OnReload: func() core.Result { /* ... */ },
}

Subsystems

Accessor Purpose
c.Options() Input configuration
c.App() Application identity
c.Data() Embedded/stored content
c.Drive() Resource handle registry
c.Fs() Local filesystem I/O
c.Config() Configuration + feature flags
c.Cli() CLI surface layer
c.Command("path") Command tree
c.Service("name") Service registry
c.Lock("name") Named mutexes
c.IPC() Message bus

IPC / Message Bus

Fire-and-forget actions, request/response queries, and task dispatch:

// Register a handler
c.IPC().On(func(c *core.Core, msg core.Message) core.Result {
    // handle message
    return core.Result{OK: true}
})

// Dispatch
c.IPC().Action(core.Message{Action: "cache.flush"})

Install

go get dappco.re/go/core@latest

License

EUPL-1.2

Documentation

Overview

Cli is the CLI surface layer for the Core command tree. It reads commands from Core's registry and wires them to terminal I/O.

Run the CLI:

c := core.New(core.Options{{Key: "name", Value: "myapp"}})
c.Command("deploy", handler)
c.Cli().Run()

The Cli resolves os.Args to a command path, parses flags, and calls the command's action with parsed options.

Command is a DTO representing an executable operation. Commands don't know if they're root, child, or nested — the tree structure comes from composition via path-based registration.

Register a command:

c.Command("deploy", func(opts core.Options) core.Result {
    return core.Result{"deployed", true}
})

Register a nested command:

c.Command("deploy/to/homelab", handler)

Description is an i18n key — derived from path if omitted:

"deploy"             → "cmd.deploy.description"
"deploy/to/homelab"  → "cmd.deploy.to.homelab.description"

Data is the embedded/stored content system for core packages. Packages mount their embedded content here and other packages read from it by path.

Mount a package's assets:

c.Data().New(core.Options{
    {Key: "name", Value: "brain"},
    {Key: "source", Value: brainFS},
    {Key: "path", Value: "prompts"},
})

Read from any mounted path:

content := c.Data().ReadString("brain/coding.md")
entries := c.Data().List("agent/flow")

Extract a template directory:

c.Data().Extract("agent/workspace/default", "/tmp/ws", data)

Drive is the resource handle registry for transport connections. Packages register their transport handles (API, MCP, SSH, VPN) and other packages access them by name.

Register a transport:

c.Drive().New(core.Options{
    {Key: "name", Value: "api"},
    {Key: "transport", Value: "https://api.lthn.ai"},
})
c.Drive().New(core.Options{
    {Key: "name", Value: "ssh"},
    {Key: "transport", Value: "ssh://claude@10.69.69.165"},
})
c.Drive().New(core.Options{
    {Key: "name", Value: "mcp"},
    {Key: "transport", Value: "mcp://mcp.lthn.sh"},
})

Retrieve a handle:

api := c.Drive().Get("api")

Embedded assets for the Core framework.

Embed provides scoped filesystem access for go:embed and any fs.FS. Also includes build-time asset packing (AST scanner + compressor) and template-based directory extraction.

Usage (mount):

sub, _ := core.Mount(myFS, "lib/persona")
content, _ := sub.ReadString("secops/developer.md")

Usage (extract):

core.Extract(fsys, "/tmp/workspace", data)

Usage (pack):

refs, _ := core.ScanAssets([]string{"main.go"})
source, _ := core.GeneratePack(refs)

Sandboxed local filesystem I/O for the Core framework.

Structured logging for the Core framework.

core.SetLevel(core.LevelDebug)
core.Info("server started", "port", 8080)
core.Error("failed to connect", "err", err)

Core primitives: Option, Options, Result.

Option is a single key-value pair. Options is a collection. Any function that returns Result can accept Options.

Create options:

opts := core.Options{
    {Key: "name", Value: "brain"},
    {Key: "path", Value: "prompts"},
}

Read options:

name := opts.String("name")
port := opts.Int("port")
ok := opts.Has("debug")

Use with subsystems:

c.Drive().New(core.Options{
    {Key: "name", Value: "brain"},
    {Key: "source", Value: brainFS},
    {Key: "path", Value: "prompts"},
})

Use with New:

c := core.New(core.Options{
    {Key: "name", Value: "myapp"},
})

Index

Constants

This section is empty.

Variables

View Source
var RotationWriterFactory func(RotationLogOptions) goio.WriteCloser

RotationWriterFactory creates a rotating writer from options. Set this to enable log rotation (provided by core/go-io integration).

Functions

func AddAsset

func AddAsset(group, name, data string)

AddAsset registers a packed asset at runtime (called from generated init()).

func AllOperations

func AllOperations(err error) iter.Seq[string]

AllOperations returns an iterator over all operational contexts in the error chain. It traverses the error tree using errors.Unwrap.

func ArgBool

func ArgBool(index int, args ...any) bool

ArgBool extracts a bool at the given index.

debug := core.ArgBool(2, args...)

func ArgInt

func ArgInt(index int, args ...any) int

ArgInt extracts an int at the given index.

port := core.ArgInt(1, args...)

func ArgString

func ArgString(index int, args ...any) string

ArgString extracts a string at the given index.

name := core.ArgString(0, args...)

func As

func As(err error, target any) bool

As finds the first error in err's tree that matches target. Wrapper around errors.As for convenience.

func Concat

func Concat(parts ...string) string

Concat joins variadic string parts into one string. Hook point for validation, sanitisation, and security checks.

core.Concat("cmd.", "deploy.to.homelab", ".description")
core.Concat("https://", host, "/api/v1")

func ConfigGet

func ConfigGet[T any](e *Config, key string) T

ConfigGet retrieves a typed configuration value.

func Contains

func Contains(s, substr string) bool

Contains returns true if s contains substr.

core.Contains("hello world", "world")  // true

func Debug

func Debug(msg string, keyvals ...any)

Debug logs to the default logger.

func E

func E(op, msg string, err error) error

E creates a new Err with operation context. The underlying error can be nil for creating errors without a cause.

Example:

return log.E("user.Save", "failed to save user", err)
return log.E("api.Call", "rate limited", nil)  // No underlying cause

func Error

func Error(msg string, keyvals ...any)

Error logs to the default logger.

func ErrorCode

func ErrorCode(err error) string

ErrorCode extracts the error code from an error. Returns empty string if the error is not an *Err or has no code.

func ErrorJoin

func ErrorJoin(errs ...error) error

ErrorJoin combines multiple errors into one.

core.ErrorJoin(err1, err2, err3)

func ErrorMessage

func ErrorMessage(err error) string

Message extracts the message from an error. Returns the error's Error() string if not an *Err.

func FilterArgs

func FilterArgs(args []string) []string

FilterArgs removes empty strings and Go test runner flags from an argument list.

clean := core.FilterArgs(os.Args[1:])

func FormatStackTrace

func FormatStackTrace(err error) string

FormatStackTrace returns a pretty-printed logical stack trace.

func HasPrefix

func HasPrefix(s, prefix string) bool

HasPrefix returns true if s starts with prefix.

core.HasPrefix("--verbose", "--")  // true

func HasSuffix

func HasSuffix(s, suffix string) bool

HasSuffix returns true if s ends with suffix.

core.HasSuffix("test.go", ".go")  // true

func Info

func Info(msg string, keyvals ...any)

Info logs to the default logger.

func Is

func Is(err, target error) bool

Is reports whether any error in err's tree matches target. Wrapper around errors.Is for convenience.

func IsFlag

func IsFlag(arg string) bool

IsFlag returns true if the argument starts with a dash.

core.IsFlag("--verbose")  // true
core.IsFlag("-v")         // true
core.IsFlag("deploy")    // false

func Join

func Join(sep string, parts ...string) string

Join joins parts with a separator, building via Concat.

core.Join("/", "deploy", "to", "homelab")      // "deploy/to/homelab"
core.Join(".", "cmd", "deploy", "description")  // "cmd.deploy.description"

func JoinPath

func JoinPath(segments ...string) string

JoinPath joins string segments into a path with "/" separator.

core.JoinPath("deploy", "to", "homelab")  // → "deploy/to/homelab"

func Lower

func Lower(s string) string

Lower returns s in lowercase.

core.Lower("HELLO")  // "hello"

func NewBuilder

func NewBuilder() *strings.Builder

NewBuilder returns a new strings.Builder.

b := core.NewBuilder()
b.WriteString("hello")
b.String() // "hello"

func NewCode

func NewCode(code, msg string) error

NewCode creates an error with just code and message (no underlying error). Useful for creating sentinel errors with codes.

Example:

var ErrNotFound = log.NewCode("NOT_FOUND", "resource not found")

func NewError

func NewError(text string) error

NewError creates a simple error with the given text. Wrapper around errors.New for convenience.

func NewReader

func NewReader(s string) *strings.Reader

NewReader returns a strings.NewReader for the given string.

r := core.NewReader("hello world")

func Operation

func Operation(err error) string

Operation extracts the operation name from an error. Returns empty string if the error is not an *Err.

func ParseFlag

func ParseFlag(arg string) (key, value string, valid bool)

ParseFlag parses a single flag argument into key, value, and validity. Single dash (-) requires exactly 1 character (letter, emoji, unicode). Double dash (--) requires 2+ characters.

"-v"           → "v", "", true
"-🔥"          → "🔥", "", true
"--verbose"    → "verbose", "", true
"--port=8080"  → "port", "8080", true
"-verbose"     → "", "", false  (single dash, 2+ chars)
"--v"          → "", "", false  (double dash, 1 char)
"hello"        → "", "", false  (not a flag)

func Print

func Print(w io.Writer, format string, args ...any)

Print writes a formatted line to a writer, defaulting to os.Stdout.

core.Print(nil, "hello %s", "world")     // → stdout
core.Print(w, "port: %d", 8080)          // → w

func Replace

func Replace(s, old, new string) string

Replace replaces all occurrences of old with new in s.

core.Replace("deploy/to/homelab", "/", ".")  // "deploy.to.homelab"

func Root

func Root(err error) error

Root returns the root cause of an error chain. Unwraps until no more wrapped errors are found.

func RuneCount

func RuneCount(s string) int

RuneCount returns the number of runes (unicode characters) in s.

core.RuneCount("hello")  // 5
core.RuneCount("🔥")     // 1

func Security

func Security(msg string, keyvals ...any)

Security logs to the default logger.

func SetDefault

func SetDefault(l *Log)

SetDefault sets the default logger.

func SetLevel

func SetLevel(level Level)

SetLevel sets the default logger's level.

func SetRedactKeys

func SetRedactKeys(keys ...string)

SetRedactKeys sets the default logger's redaction keys.

func Split

func Split(s, sep string) []string

Split splits s by separator.

core.Split("a/b/c", "/")  // ["a", "b", "c"]

func SplitN

func SplitN(s, sep string, n int) []string

SplitN splits s by separator into at most n parts.

core.SplitN("key=value=extra", "=", 2)  // ["key", "value=extra"]

func Sprint

func Sprint(args ...any) string

Sprint converts any value to its string representation.

core.Sprint(42)       // "42"
core.Sprint(err)      // "connection refused"

func Sprintf

func Sprintf(format string, args ...any) string

Sprintf formats a string with the given arguments.

core.Sprintf("%v=%q", "key", "value")  // `key="value"`

func StackTrace

func StackTrace(err error) []string

StackTrace returns the logical stack trace (chain of operations) from an error. It returns an empty slice if no operational context is found.

func Trim

func Trim(s string) string

Trim removes leading and trailing whitespace.

core.Trim("  hello  ")  // "hello"

func TrimPrefix

func TrimPrefix(s, prefix string) string

TrimPrefix removes prefix from s.

core.TrimPrefix("--verbose", "--")  // "verbose"

func TrimSuffix

func TrimSuffix(s, suffix string) string

TrimSuffix removes suffix from s.

core.TrimSuffix("test.go", ".go")  // "test"

func Upper

func Upper(s string) string

Upper returns s in uppercase.

core.Upper("hello")  // "HELLO"

func Username

func Username() string

Username returns the current system username. It uses os/user for reliability and falls back to environment variables.

func Warn

func Warn(msg string, keyvals ...any)

Warn logs to the default logger.

func Wrap

func Wrap(err error, op, msg string) error

Wrap wraps an error with operation context. Returns nil if err is nil, to support conditional wrapping. Preserves error Code if the wrapped error is an *Err.

Example:

return log.Wrap(err, "db.Query", "database query failed")

func WrapCode

func WrapCode(err error, code, op, msg string) error

WrapCode wraps an error with operation context and error code. Returns nil only if both err is nil AND code is empty. Useful for API errors that need machine-readable codes.

Example:

return log.WrapCode(err, "VALIDATION_ERROR", "user.Validate", "invalid email")

Types

type ActionServiceShutdown

type ActionServiceShutdown struct{}

type ActionServiceStartup

type ActionServiceStartup struct{}

type ActionTaskCompleted

type ActionTaskCompleted struct {
	TaskIdentifier string
	Task           Task
	Result         any
	Error          error
}

type ActionTaskProgress

type ActionTaskProgress struct {
	TaskIdentifier string
	Task           Task
	Progress       float64
	Message        string
}

type ActionTaskStarted

type ActionTaskStarted struct {
	TaskIdentifier string
	Task           Task
}

type App

type App struct {
	// Name is the human-readable application name (e.g., "Core CLI").
	Name string

	// Version is the application version string (e.g., "1.2.3").
	Version string

	// Description is a short description of the application.
	Description string

	// Filename is the executable filename (e.g., "core").
	Filename string

	// Path is the absolute path to the executable.
	Path string

	// Runtime is the GUI runtime (e.g., Wails App).
	// Nil for CLI-only applications.
	Runtime any
}

App holds the application identity and optional GUI runtime.

type Array

type Array[T comparable] struct {
	// contains filtered or unexported fields
}

Array is a typed slice with common operations.

func NewArray

func NewArray[T comparable](items ...T) *Array[T]

NewArray creates an empty Array.

func (*Array[T]) Add

func (s *Array[T]) Add(values ...T)

Add appends values.

func (*Array[T]) AddUnique

func (s *Array[T]) AddUnique(values ...T)

AddUnique appends values only if not already present.

func (*Array[T]) AsSlice

func (s *Array[T]) AsSlice() []T

AsSlice returns a copy of the underlying slice.

func (*Array[T]) Clear

func (s *Array[T]) Clear()

Clear removes all elements.

func (*Array[T]) Contains

func (s *Array[T]) Contains(val T) bool

Contains returns true if the value is in the slice.

func (*Array[T]) Deduplicate

func (s *Array[T]) Deduplicate()

Deduplicate removes duplicate values, preserving order.

func (*Array[T]) Each

func (s *Array[T]) Each(fn func(T))

Each runs a function on every element.

func (*Array[T]) Filter

func (s *Array[T]) Filter(fn func(T) bool) Result

Filter returns a new Array with elements matching the predicate.

func (*Array[T]) Len

func (s *Array[T]) Len() int

Len returns the number of elements.

func (*Array[T]) Remove

func (s *Array[T]) Remove(val T)

Remove removes the first occurrence of a value.

type AssetGroup

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

AssetGroup holds a named collection of packed assets.

type AssetRef

type AssetRef struct {
	Name     string
	Path     string
	Group    string
	FullPath string
}

AssetRef is a reference to an asset found in source code.

type Cli

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

Cli is the CLI surface for the Core command tree.

func (*Cli) Banner

func (cl *Cli) Banner() string

Banner returns the banner string.

func (*Cli) Print

func (cl *Cli) Print(format string, args ...any)

Print writes to the CLI output (defaults to os.Stdout).

c.Cli().Print("hello %s", "world")

func (*Cli) PrintHelp

func (cl *Cli) PrintHelp()

PrintHelp prints available commands.

c.Cli().PrintHelp()

func (*Cli) Run

func (cl *Cli) Run(args ...string) Result

Run resolves os.Args to a command path and executes it.

c.Cli().Run()
c.Cli().Run("deploy", "to", "homelab")

func (*Cli) SetBanner

func (cl *Cli) SetBanner(fn func(*Cli) string)

SetBanner sets the banner function.

c.Cli().SetBanner(func(_ *core.Cli) string { return "My App v1.0" })

func (*Cli) SetOutput

func (cl *Cli) SetOutput(w io.Writer)

SetOutput sets the CLI output writer.

c.Cli().SetOutput(os.Stderr)

type Command

type Command struct {
	Name        string
	Description string           // i18n key — derived from path if empty
	Path        string           // "deploy/to/homelab"
	Action      CommandAction    // business logic
	Lifecycle   CommandLifecycle // optional — provided by go-process
	Flags       Options          // declared flags
	Hidden      bool
	// contains filtered or unexported fields
}

Command is the DTO for an executable operation.

func (*Command) I18nKey

func (cmd *Command) I18nKey() string

I18nKey returns the i18n key for this command's description.

cmd with path "deploy/to/homelab" → "cmd.deploy.to.homelab.description"

func (*Command) Reload

func (cmd *Command) Reload() Result

Reload delegates to the lifecycle implementation.

func (*Command) Restart

func (cmd *Command) Restart() Result

Restart delegates to the lifecycle implementation.

func (*Command) Run

func (cmd *Command) Run(opts Options) Result

Run executes the command's action with the given options.

result := cmd.Run(core.Options{{Key: "target", Value: "homelab"}})

func (*Command) Signal

func (cmd *Command) Signal(sig string) Result

Signal delegates to the lifecycle implementation.

func (*Command) Start

func (cmd *Command) Start(opts Options) Result

Start delegates to the lifecycle implementation if available.

func (*Command) Stop

func (cmd *Command) Stop() Result

Stop delegates to the lifecycle implementation.

type CommandAction

type CommandAction func(Options) Result

CommandAction is the function signature for command handlers.

func(opts core.Options) core.Result

type CommandLifecycle

type CommandLifecycle interface {
	Start(Options) Result
	Stop() Result
	Restart() Result
	Reload() Result
	Signal(string) Result
}

CommandLifecycle is implemented by commands that support managed lifecycle. Basic commands only need an action. Daemon commands implement Start/Stop/Signal via go-process.

type Config

type Config struct {
	*ConfigOptions
	// contains filtered or unexported fields
}

Config holds configuration settings and feature flags.

func (*Config) Bool

func (e *Config) Bool(key string) bool

func (*Config) Disable

func (e *Config) Disable(feature string)

func (*Config) Enable

func (e *Config) Enable(feature string)

func (*Config) Enabled

func (e *Config) Enabled(feature string) bool

func (*Config) EnabledFeatures

func (e *Config) EnabledFeatures() []string

func (*Config) Get

func (e *Config) Get(key string) Result

Get retrieves a configuration value by key.

func (*Config) Int

func (e *Config) Int(key string) int

func (*Config) Set

func (e *Config) Set(key string, val any)

Set stores a configuration value by key.

func (*Config) String

func (e *Config) String(key string) string

type ConfigOptions

type ConfigOptions struct {
	Settings map[string]any
	Features map[string]bool
}

ConfigOptions holds configuration data.

type ConfigVar

type ConfigVar[T any] struct {
	// contains filtered or unexported fields
}

ConfigVar is a variable that can be set, unset, and queried for its state.

func NewConfigVar

func NewConfigVar[T any](val T) ConfigVar[T]

func (*ConfigVar[T]) Get

func (v *ConfigVar[T]) Get() T

func (*ConfigVar[T]) IsSet

func (v *ConfigVar[T]) IsSet() bool

func (*ConfigVar[T]) Set

func (v *ConfigVar[T]) Set(val T)

func (*ConfigVar[T]) Unset

func (v *ConfigVar[T]) Unset()

type Core

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

Core is the central application object that manages services, assets, and communication.

func New

func New(opts ...Options) *Core

New creates a Core instance.

c := core.New(core.Options{
    {Key: "name", Value: "myapp"},
})

func (*Core) ACTION

func (c *Core) ACTION(msg Message) Result

func (*Core) Action

func (c *Core) Action(msg Message) Result

func (*Core) App

func (c *Core) App() *App

func (*Core) Cli

func (c *Core) Cli() *Cli

func (*Core) Command

func (c *Core) Command(path string, command ...Command) Result

Command gets or registers a command by path.

c.Command("deploy", Command{Action: handler})
r := c.Command("deploy")

func (*Core) Commands

func (c *Core) Commands() []string

Commands returns all registered command paths.

paths := c.Commands()

func (*Core) Config

func (c *Core) Config() *Config

func (*Core) Context

func (c *Core) Context() context.Context

func (*Core) Core

func (c *Core) Core() *Core

func (*Core) Data

func (c *Core) Data() *Data

func (*Core) Drive

func (c *Core) Drive() *Drive

func (*Core) Embed

func (c *Core) Embed() Result

func (*Core) Error

func (c *Core) Error() *ErrorPanic

func (*Core) Fs

func (c *Core) Fs() *Fs

func (*Core) I18n

func (c *Core) I18n() *I18n

func (*Core) IPC

func (c *Core) IPC() *Ipc

func (*Core) Lock

func (c *Core) Lock(name string) *Lock

Lock returns a named Lock, creating the mutex if needed.

func (*Core) LockApply

func (c *Core) LockApply(name ...string)

LockApply activates the service lock if it was enabled.

func (*Core) LockEnable

func (c *Core) LockEnable(name ...string)

LockEnable marks that the service lock should be applied after initialisation.

func (*Core) Log

func (c *Core) Log() *ErrorLog

func (*Core) LogError

func (c *Core) LogError(err error, op, msg string) Result

LogError logs an error and returns the Result from ErrorLog.

func (*Core) LogWarn

func (c *Core) LogWarn(err error, op, msg string) Result

LogWarn logs a warning and returns the Result from ErrorLog.

func (*Core) Must

func (c *Core) Must(err error, op, msg string)

Must logs and panics if err is not nil.

func (*Core) Options

func (c *Core) Options() *Options

func (*Core) PERFORM

func (c *Core) PERFORM(t Task) Result

func (*Core) Perform

func (c *Core) Perform(t Task) Result

func (*Core) PerformAsync

func (c *Core) PerformAsync(t Task) Result

PerformAsync dispatches a task in a background goroutine.

func (*Core) Progress

func (c *Core) Progress(taskID string, progress float64, message string, t Task)

Progress broadcasts a progress update for a background task.

func (*Core) QUERY

func (c *Core) QUERY(q Query) Result

func (*Core) QUERYALL

func (c *Core) QUERYALL(q Query) Result

func (*Core) Query

func (c *Core) Query(q Query) Result

func (*Core) QueryAll

func (c *Core) QueryAll(q Query) Result

func (*Core) RegisterAction

func (c *Core) RegisterAction(handler func(*Core, Message) Result)

func (*Core) RegisterActions

func (c *Core) RegisterActions(handlers ...func(*Core, Message) Result)

func (*Core) RegisterQuery

func (c *Core) RegisterQuery(handler QueryHandler)

func (*Core) RegisterTask

func (c *Core) RegisterTask(handler TaskHandler)

func (*Core) Service

func (c *Core) Service(name string, service ...Service) Result

Service gets or registers a service by name.

c.Service("auth", core.Service{OnStart: startFn})
r := c.Service("auth")

func (*Core) ServiceShutdown

func (c *Core) ServiceShutdown(ctx context.Context) Result

ServiceShutdown drains background tasks, then stops all registered services.

func (*Core) ServiceStartup

func (c *Core) ServiceStartup(ctx context.Context, options any) Result

ServiceStartup runs OnStart for all registered services that have one.

func (*Core) Services

func (c *Core) Services() []string

Services returns all registered service names.

names := c.Services()

func (*Core) Startables

func (c *Core) Startables() Result

Startables returns services that have an OnStart function.

func (*Core) Stoppables

func (c *Core) Stoppables() Result

Stoppables returns services that have an OnStop function.

type CrashReport

type CrashReport struct {
	Timestamp time.Time         `json:"timestamp"`
	Error     string            `json:"error"`
	Stack     string            `json:"stack"`
	System    CrashSystem       `json:"system,omitempty"`
	Meta      map[string]string `json:"meta,omitempty"`
}

CrashReport represents a single crash event.

type CrashSystem

type CrashSystem struct {
	OperatingSystem string `json:"operatingsystem"`
	Architecture    string `json:"architecture"`
	Version         string `json:"go_version"`
}

CrashSystem holds system information at crash time.

type Data

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

Data manages mounted embedded filesystems from core packages.

func (*Data) Extract

func (d *Data) Extract(path, targetDir string, templateData any) Result

Extract copies a template directory to targetDir.

r := c.Data().Extract("agent/workspace/default", "/tmp/ws", templateData)

func (*Data) Get

func (d *Data) Get(name string) Result

Get returns the Embed for a named mount point.

r := c.Data().Get("brain")
if r.OK { emb := r.Value.(*Embed) }

func (*Data) List

func (d *Data) List(path string) Result

List returns directory entries at a path.

r := c.Data().List("agent/persona/code")
if r.OK { entries := r.Value.([]fs.DirEntry) }

func (*Data) ListNames

func (d *Data) ListNames(path string) Result

ListNames returns filenames (without extensions) at a path.

r := c.Data().ListNames("agent/flow")
if r.OK { names := r.Value.([]string) }

func (*Data) Mounts

func (d *Data) Mounts() []string

Mounts returns the names of all mounted content.

names := c.Data().Mounts()

func (*Data) New

func (d *Data) New(opts Options) Result

New registers an embedded filesystem under a named prefix.

c.Data().New(core.Options{
    {Key: "name", Value: "brain"},
    {Key: "source", Value: brainFS},
    {Key: "path", Value: "prompts"},
})

func (*Data) ReadFile

func (d *Data) ReadFile(path string) Result

ReadFile reads a file by full path.

r := c.Data().ReadFile("brain/prompts/coding.md")
if r.OK { data := r.Value.([]byte) }

func (*Data) ReadString

func (d *Data) ReadString(path string) Result

ReadString reads a file as a string.

r := c.Data().ReadString("agent/flow/deploy/to/homelab.yaml")
if r.OK { content := r.Value.(string) }

type Drive

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

Drive manages named transport handles.

func (*Drive) Get

func (d *Drive) Get(name string) Result

Get returns a handle by name.

r := c.Drive().Get("api")
if r.OK { handle := r.Value.(*DriveHandle) }

func (*Drive) Has

func (d *Drive) Has(name string) bool

Has returns true if a handle is registered.

if c.Drive().Has("ssh") { ... }

func (*Drive) Names

func (d *Drive) Names() []string

Names returns all registered handle names.

names := c.Drive().Names()

func (*Drive) New

func (d *Drive) New(opts Options) Result

New registers a transport handle.

c.Drive().New(core.Options{
    {Key: "name", Value: "api"},
    {Key: "transport", Value: "https://api.lthn.ai"},
})

type DriveHandle

type DriveHandle struct {
	Name      string
	Transport string
	Options   Options
}

DriveHandle holds a named transport resource.

type Embed

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

Embed wraps an fs.FS with a basedir for scoped access. All paths are relative to basedir.

func (*Embed) BaseDirectory

func (s *Embed) BaseDirectory() string

BaseDirectory returns the base directory this Embed is anchored at.

func (*Embed) EmbedFS

func (s *Embed) EmbedFS() embed.FS

EmbedFS returns the underlying embed.FS if mounted from one. Returns zero embed.FS if mounted from a non-embed source.

func (*Embed) FS

func (s *Embed) FS() fs.FS

FS returns the underlying fs.FS.

func (*Embed) Open

func (s *Embed) Open(name string) Result

Open opens the named file for reading.

r := emb.Open("test.txt")
if r.OK { file := r.Value.(fs.File) }

func (*Embed) ReadDir

func (s *Embed) ReadDir(name string) Result

ReadDir reads the named directory.

func (*Embed) ReadFile

func (s *Embed) ReadFile(name string) Result

ReadFile reads the named file.

r := emb.ReadFile("test.txt")
if r.OK { data := r.Value.([]byte) }

func (*Embed) ReadString

func (s *Embed) ReadString(name string) Result

ReadString reads the named file as a string.

r := emb.ReadString("test.txt")
if r.OK { content := r.Value.(string) }

func (*Embed) Sub

func (s *Embed) Sub(subDir string) Result

Sub returns a new Embed anchored at a subdirectory within this mount.

r := emb.Sub("testdata")
if r.OK { sub := r.Value.(*Embed) }

type Err

type Err struct {
	Operation string // Operation being performed (e.g., "user.Save")
	Message   string // Human-readable message
	Cause     error  // Underlying error (optional)
	Code      string // Error code (optional, e.g., "VALIDATION_FAILED")
}

Err represents a structured error with operational context. It implements the error interface and supports unwrapping.

func (*Err) Error

func (e *Err) Error() string

Error implements the error interface.

func (*Err) Unwrap

func (e *Err) Unwrap() error

Unwrap returns the underlying error for use with errors.Is and errors.As.

type ErrorLog

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

ErrorLog combines error creation with logging. Primary action: return an error. Secondary: log it.

func (*ErrorLog) Error

func (el *ErrorLog) Error(err error, op, msg string) Result

Error logs at Error level and returns a Result with the wrapped error.

func (*ErrorLog) Must

func (el *ErrorLog) Must(err error, op, msg string)

Must logs and panics if err is not nil.

func (*ErrorLog) Warn

func (el *ErrorLog) Warn(err error, op, msg string) Result

Warn logs at Warn level and returns a Result with the wrapped error.

type ErrorPanic

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

ErrorPanic manages panic recovery and crash reporting.

func (*ErrorPanic) Recover

func (h *ErrorPanic) Recover()

Recover captures a panic and creates a crash report. Use as: defer c.Error().Recover()

func (*ErrorPanic) Reports

func (h *ErrorPanic) Reports(n int) Result

Reports returns the last n crash reports from the file.

func (*ErrorPanic) SafeGo

func (h *ErrorPanic) SafeGo(fn func())

SafeGo runs a function in a goroutine with panic recovery.

type ErrorSink

type ErrorSink interface {
	Error(msg string, keyvals ...any)
	Warn(msg string, keyvals ...any)
}

ErrorSink is the shared interface for error reporting. Implemented by ErrorLog (structured logging) and ErrorPanic (panic recovery).

type ExtractOptions

type ExtractOptions struct {
	// TemplateFilters identifies template files by substring match.
	// Default: [".tmpl"]
	TemplateFilters []string

	// IgnoreFiles is a set of filenames to skip during extraction.
	IgnoreFiles map[string]struct{}

	// RenameFiles maps original filenames to new names.
	RenameFiles map[string]string
}

ExtractOptions configures template extraction.

type Fs

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

Fs is a sandboxed local filesystem backend.

func (*Fs) Append

func (m *Fs) Append(p string) Result

Append opens the named file for appending, creating it if it doesn't exist.

func (*Fs) Create

func (m *Fs) Create(p string) Result

Create creates or truncates the named file.

func (*Fs) Delete

func (m *Fs) Delete(p string) Result

Delete removes a file or empty directory.

func (*Fs) DeleteAll

func (m *Fs) DeleteAll(p string) Result

DeleteAll removes a file or directory recursively.

func (*Fs) EnsureDir

func (m *Fs) EnsureDir(p string) Result

EnsureDir creates directory if it doesn't exist.

func (*Fs) Exists

func (m *Fs) Exists(p string) bool

Exists returns true if path exists.

func (*Fs) IsDir

func (m *Fs) IsDir(p string) bool

IsDir returns true if path is a directory.

func (*Fs) IsFile

func (m *Fs) IsFile(p string) bool

IsFile returns true if path is a regular file.

func (*Fs) List

func (m *Fs) List(p string) Result

List returns directory entries.

func (*Fs) Open

func (m *Fs) Open(p string) Result

Open opens the named file for reading.

func (*Fs) Read

func (m *Fs) Read(p string) Result

Read returns file contents as string.

func (*Fs) ReadStream

func (m *Fs) ReadStream(path string) Result

ReadStream returns a reader for the file content.

func (*Fs) Rename

func (m *Fs) Rename(oldPath, newPath string) Result

Rename moves a file or directory.

func (*Fs) Stat

func (m *Fs) Stat(p string) Result

Stat returns file info.

func (*Fs) Write

func (m *Fs) Write(p, content string) Result

Write saves content to file, creating parent directories as needed. Files are created with mode 0644. For sensitive files (keys, secrets), use WriteMode with 0600.

func (*Fs) WriteMode

func (m *Fs) WriteMode(p, content string, mode os.FileMode) Result

WriteMode saves content to file with explicit permissions. Use 0600 for sensitive files (encryption output, private keys, auth hashes).

func (*Fs) WriteStream

func (m *Fs) WriteStream(path string) Result

WriteStream returns a writer for the file content.

type I18n

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

I18n manages locale collection and translation dispatch.

func (*I18n) AddLocales

func (i *I18n) AddLocales(mounts ...*Embed)

AddLocales adds locale mounts (called during service registration).

func (*I18n) AvailableLanguages

func (i *I18n) AvailableLanguages() []string

AvailableLanguages returns all loaded language codes.

func (*I18n) Language

func (i *I18n) Language() string

Language returns the current language code, or "en" if not set.

func (*I18n) Locales

func (i *I18n) Locales() Result

Locales returns all collected locale mounts.

func (*I18n) SetLanguage

func (i *I18n) SetLanguage(lang string) Result

SetLanguage sets the active language and forwards to the translator if registered.

func (*I18n) SetTranslator

func (i *I18n) SetTranslator(t Translator)

SetTranslator registers the translation implementation. Called by go-i18n's Srv during startup.

func (*I18n) Translate

func (i *I18n) Translate(messageID string, args ...any) Result

Translate translates a message. Returns the key as-is if no translator is registered.

func (*I18n) Translator

func (i *I18n) Translator() Result

Translator returns the registered translation implementation, or nil.

type Ipc

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

Ipc holds IPC dispatch data.

type Level

type Level int

Level defines logging verbosity.

const (
	// LevelQuiet suppresses all log output.
	LevelQuiet Level = iota
	// LevelError shows only error messages.
	LevelError
	// LevelWarn shows warnings and errors.
	LevelWarn
	// LevelInfo shows informational messages, warnings, and errors.
	LevelInfo
	// LevelDebug shows all messages including debug details.
	LevelDebug
)

Logging level constants ordered by increasing verbosity.

func (Level) String

func (l Level) String() string

String returns the level name.

type LocaleProvider

type LocaleProvider interface {
	Locales() *Embed
}

LocaleProvider is implemented by services that ship their own translation files. Core discovers this interface during service registration and collects the locale mounts. The i18n service loads them during startup.

Usage in a service package:

//go:embed locales
var localeFS embed.FS

func (s *MyService) Locales() *Embed {
    m, _ := Mount(localeFS, "locales")
    return m
}

type Lock

type Lock struct {
	Name  string
	Mutex *sync.RWMutex
}

Lock is the DTO for a named mutex.

type Log

type Log struct {

	// Style functions for formatting (can be overridden)
	StyleTimestamp func(string) string
	StyleDebug     func(string) string
	StyleInfo      func(string) string
	StyleWarn      func(string) string
	StyleError     func(string) string
	StyleSecurity  func(string) string
	// contains filtered or unexported fields
}

Log provides structured logging.

func Default

func Default() *Log

Default returns the default logger.

func NewLog

func NewLog(opts LogOptions) *Log

New creates a new Log with the given options.

func (*Log) Debug

func (l *Log) Debug(msg string, keyvals ...any)

Debug logs a debug message with optional key-value pairs.

func (*Log) Error

func (l *Log) Error(msg string, keyvals ...any)

Error logs an error message with optional key-value pairs.

func (*Log) Info

func (l *Log) Info(msg string, keyvals ...any)

Info logs an info message with optional key-value pairs.

func (*Log) Level

func (l *Log) Level() Level

Level returns the current log level.

func (*Log) Security

func (l *Log) Security(msg string, keyvals ...any)

Security logs a security event with optional key-value pairs. It uses LevelError to ensure security events are visible even in restrictive log configurations.

func (*Log) SetLevel

func (l *Log) SetLevel(level Level)

SetLevel changes the log level.

func (*Log) SetOutput

func (l *Log) SetOutput(w goio.Writer)

SetOutput changes the output writer.

func (*Log) SetRedactKeys

func (l *Log) SetRedactKeys(keys ...string)

SetRedactKeys sets the keys to be redacted.

func (*Log) Warn

func (l *Log) Warn(msg string, keyvals ...any)

Warn logs a warning message with optional key-value pairs.

type LogErr

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

LogErr logs structured information extracted from errors. Primary action: log. Secondary: extract error context.

func NewLogErr

func NewLogErr(log *Log) *LogErr

NewLogErr creates a LogErr bound to the given logger.

func (*LogErr) Log

func (le *LogErr) Log(err error)

Log extracts context from an Err and logs it at Error level.

type LogOptions

type LogOptions struct {
	Level Level
	// Output is the destination for log messages. If Rotation is provided,
	// Output is ignored and logs are written to the rotating file instead.
	Output goio.Writer
	// Rotation enables log rotation to file. If provided, Filename must be set.
	Rotation *RotationLogOptions
	// RedactKeys is a list of keys whose values should be masked in logs.
	RedactKeys []string
}

LogOptions configures a Log.

type LogPanic

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

LogPanic logs panic context without crash file management. Primary action: log. Secondary: recover panics.

func NewLogPanic

func NewLogPanic(log *Log) *LogPanic

NewLogPanic creates a LogPanic bound to the given logger.

func (*LogPanic) Recover

func (lp *LogPanic) Recover()

Recover captures a panic and logs it. Does not write crash files. Use as: defer core.NewLogPanic(logger).Recover()

type Message

type Message any

Message is the type for IPC broadcasts (fire-and-forget).

type Option

type Option struct {
	Key   string
	Value any
}

Option is a single key-value configuration pair.

core.Option{Key: "name", Value: "brain"}
core.Option{Key: "port", Value: 8080}

type Options

type Options []Option

Options is a collection of Option items. The universal input type for Core operations.

opts := core.Options{{Key: "name", Value: "myapp"}}
name := opts.String("name")

func (Options) Bool

func (o Options) Bool(key string) bool

Bool retrieves a bool value, false if missing.

debug := opts.Bool("debug")

func (Options) Get

func (o Options) Get(key string) Result

Get retrieves a value by key.

r := opts.Get("name")
if r.OK { name := r.Value.(string) }

func (Options) Has

func (o Options) Has(key string) bool

Has returns true if a key exists.

if opts.Has("debug") { ... }

func (Options) Int

func (o Options) Int(key string) int

Int retrieves an int value, 0 if missing.

port := opts.Int("port")

func (Options) String

func (o Options) String(key string) string

String retrieves a string value, empty string if missing.

name := opts.String("name")

type Query

type Query any

Query is the type for read-only IPC requests.

type QueryHandler

type QueryHandler func(*Core, Query) Result

QueryHandler handles Query requests. Returns Result{Value, OK}.

type Result

type Result struct {
	Value any
	OK    bool
}

Result is the universal return type for Core operations. Replaces the (value, error) pattern — errors flow through Core internally.

r := c.Data().New(core.Options{{Key: "name", Value: "brain"}})
if r.OK { use(r.Result()) }

func Arg

func Arg(index int, args ...any) Result

Arg extracts a value from variadic args at the given index. Type-checks and delegates to the appropriate typed extractor. Returns Result — OK is false if index is out of bounds.

r := core.Arg(0, args...)
if r.OK { path = r.Value.(string) }

func Extract

func Extract(fsys fs.FS, targetDir string, data any, opts ...ExtractOptions) Result

Extract copies a template directory from an fs.FS to targetDir, processing Go text/template in filenames and file contents.

Files containing a template filter substring (default: ".tmpl") have their contents processed through text/template with the given data. The filter is stripped from the output filename.

Directory and file names can contain Go template expressions: {{.Name}}/main.go → myproject/main.go

Data can be any struct or map[string]string for template substitution.

func Find

func Find(filename, name string) Result

Find locates a program on PATH and returns a Result containing the App.

r := core.Find("node", "Node.js")
if r.OK { app := r.Value.(*App) }

func GeneratePack

func GeneratePack(pkg ScannedPackage) Result

GeneratePack creates Go source code that embeds the scanned assets.

func GetAsset

func GetAsset(group, name string) Result

GetAsset retrieves and decompresses a packed asset.

r := core.GetAsset("mygroup", "greeting")
if r.OK { content := r.Value.(string) }

func GetAssetBytes

func GetAssetBytes(group, name string) Result

GetAssetBytes retrieves a packed asset as bytes.

r := core.GetAssetBytes("mygroup", "file")
if r.OK { data := r.Value.([]byte) }

func Mount

func Mount(fsys fs.FS, basedir string) Result

Mount creates a scoped view of an fs.FS anchored at basedir.

r := core.Mount(myFS, "lib/prompts")
if r.OK { emb := r.Value.(*Embed) }

func MountEmbed

func MountEmbed(efs embed.FS, basedir string) Result

MountEmbed creates a scoped view of an embed.FS.

r := core.MountEmbed(myFS, "testdata")

func NewRuntime

func NewRuntime(app any) Result

NewRuntime creates a Runtime with no custom services.

func NewWithFactories

func NewWithFactories(app any, factories map[string]ServiceFactory) Result

NewWithFactories creates a Runtime with the provided service factories.

func ScanAssets

func ScanAssets(filenames []string) Result

ScanAssets parses Go source files and finds asset references. Looks for calls to: core.GetAsset("group", "name"), core.AddAsset, etc.

func (Result) Result

func (r Result) Result(args ...any) Result

Result gets or sets the value. Zero args returns Value. With args, maps Go (value, error) pairs to Result and returns self.

r.Result(file, err)     // OK = err == nil, Value = file
r.Result(value)         // OK = true, Value = value
r.Result()              // after set — returns the value

type RotationLogOptions

type RotationLogOptions struct {
	// Filename is the log file path. If empty, rotation is disabled.
	Filename string

	// MaxSize is the maximum size of the log file in megabytes before it gets rotated.
	// It defaults to 100 megabytes.
	MaxSize int

	// MaxAge is the maximum number of days to retain old log files based on their
	// file modification time. It defaults to 28 days.
	// Note: set to a negative value to disable age-based retention.
	MaxAge int

	// MaxBackups is the maximum number of old log files to retain.
	// It defaults to 5 backups.
	MaxBackups int

	// Compress determines if the rotated log files should be compressed using gzip.
	// It defaults to true.
	Compress bool
}

RotationLogOptions defines the log rotation and retention policy.

type Runtime

type Runtime struct {
	Core *Core
	// contains filtered or unexported fields
}

Runtime is the container for GUI runtimes (e.g., Wails).

func (*Runtime) ServiceName

func (r *Runtime) ServiceName() string

func (*Runtime) ServiceShutdown

func (r *Runtime) ServiceShutdown(ctx context.Context) Result

func (*Runtime) ServiceStartup

func (r *Runtime) ServiceStartup(ctx context.Context, options any) Result

type ScannedPackage

type ScannedPackage struct {
	PackageName   string
	BaseDirectory string
	Groups        []string
	Assets        []AssetRef
}

ScannedPackage holds all asset references from a set of source files.

type Service

type Service struct {
	Name     string
	Options  Options
	OnStart  func() Result
	OnStop   func() Result
	OnReload func() Result
}

Service is a managed component with optional lifecycle.

type ServiceFactory

type ServiceFactory func() Result

ServiceFactory defines a function that creates a Service.

type ServiceRuntime

type ServiceRuntime[T any] struct {
	// contains filtered or unexported fields
}

ServiceRuntime is embedded in services to provide access to the Core and typed options.

func NewServiceRuntime

func NewServiceRuntime[T any](c *Core, opts T) *ServiceRuntime[T]

NewServiceRuntime creates a ServiceRuntime for a service constructor.

func (*ServiceRuntime[T]) Config

func (r *ServiceRuntime[T]) Config() *Config

func (*ServiceRuntime[T]) Core

func (r *ServiceRuntime[T]) Core() *Core

func (*ServiceRuntime[T]) Options

func (r *ServiceRuntime[T]) Options() T

type Startable

type Startable interface {
	OnStartup(ctx context.Context) error
}

Startable is implemented by services that need startup initialisation.

type Stoppable

type Stoppable interface {
	OnShutdown(ctx context.Context) error
}

Stoppable is implemented by services that need shutdown cleanup.

type Task

type Task any

Task is the type for IPC requests that perform side effects.

type TaskHandler

type TaskHandler func(*Core, Task) Result

TaskHandler handles Task requests. Returns Result{Value, OK}.

type TaskState

type TaskState struct {
	Identifier string
	Task       Task
	Result     any
	Error      error
}

TaskState holds background task state.

type TaskWithIdentifier

type TaskWithIdentifier interface {
	Task
	SetTaskIdentifier(id string)
	GetTaskIdentifier() string
}

TaskWithIdentifier is an optional interface for tasks that need to know their assigned identifier.

type Translator

type Translator interface {
	// Translate translates a message by its ID with optional arguments.
	Translate(messageID string, args ...any) Result
	// SetLanguage sets the active language (BCP47 tag, e.g., "en-GB", "de").
	SetLanguage(lang string) error
	// Language returns the current language code.
	Language() string
	// AvailableLanguages returns all loaded language codes.
	AvailableLanguages() []string
}

Translator defines the interface for translation services. Implemented by go-i18n's Srv.

Jump to

Keyboard shortcuts

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