shared

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2026 License: GPL-3.0 Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// EnvConfig config location
	EnvConfig   = "SECAI_CONFIG"
	EnvNoDotEnv = "SECAI_NO_DOTENV"
)
View Source
const APrefix = "secai"

Variables

View Source
var (
	FromAssistant = From{"assistant"}
	FromSystem    = From{"system"}
	FromUser      = From{"user"}
	FromNarrator  = From{"narrator"}

	FromEnum = enum.New(FromAssistant, FromSystem, FromUser)
)

Functions

func BinaryPath added in v0.5.0

func BinaryPath(cfg *Config) string

TODO config method

func ConfigDbgAddrs added in v0.5.0

func ConfigDbgAddrs(cfg ConfigDebug) (dbgAddr, httpAddr, sshAddr string, err error)

TODO config method

func ConfigLogPath added in v0.5.0

func ConfigLogPath(cfg ConfigAgent) string

TODO config method

func ConfigWebDBAddrs added in v0.5.0

func ConfigWebDBAddrs(cfg ConfigWeb) (base, agent, mach string)

TODO config method

func ConfigWebLogAddr added in v0.5.0

func ConfigWebLogAddr(cfg ConfigWeb) string

TODO config method

func GetSQLiteSchema added in v0.5.0

func GetSQLiteSchema(db *sql.DB) (string, error)

TODO format "github.com/maxrichie5/go-sqlfmt/sqlfmt" config := sqlfmt.NewDefaultConfig() formatted := sqlfmt.Format(rawSQL, config)

func LogArgs added in v0.2.0

func LogArgs(args am.A) map[string]string

LogArgs is an args logger for A and [secai.A].

func MachTelemetry

func MachTelemetry(mach *am.Machine, logArgs am.LogArgsMapperFn)

func Map

func Map[A, B any](vals []A, f func(A) B) []B

Map maps vals through f and returns a list of returned values from f.

func NumRef added in v0.2.0

func NumRef(text string) int

NumRef returns a number reference from the passed text, or -1 if none found.

func OpenURL added in v0.5.0

func OpenURL(url string) error

OpenURL opens the specified URL in the default browser of the user. https://gist.github.com/sevkin/9798d67b2cb9d07cb05f89f14ba682f8

func OptArgs added in v0.5.0

func OptArgs(args []am.A) am.A

OptArgs will read the first A from an optional list.

func P

func P(txt string, args ...any)

P formats and prints the given string after de-denting and trimming it, and returns the number of bytes written and any error.

func ParseRpc added in v0.5.0

func ParseRpc(args am.A) am.A

ParseRpc parses am.A to *ARPC wrapped in am.A. Useful for REPLs.

func PascalCase added in v0.2.0

func PascalCase(in string) string

PascalCase converts the input string to pascal case, matching the naming convention of state names.

func Pass added in v0.2.0

func Pass(args *A) am.A

Pass prepares am.A from A to pass to further mutations.

func PassRPC added in v0.5.0

func PassRPC(args *A) am.A

PassRPC prepares am.A from A to pass over RPC.

func RemoveStyling added in v0.2.0

func RemoveStyling(str string) string

func RevertPascalCase added in v0.2.0

func RevertPascalCase(in string) string

func Sj

func Sj(parts ...string) string

Sj is a string join and will join passed string args with a space.

func Sl

func Sl(txt string, args ...any) string

Sl is a string line - expands txt with args and ends with a newline.

func SlicesWithout added in v0.2.0

func SlicesWithout[S ~[]E, E comparable](coll S, el E) S

func Sp

func Sp(txt string, args ...any) string

Sp formats a de-dented and trimmed string using the provided arguments, similar to fmt.Sprintf.

Types

type A added in v0.2.0

type A struct {
	// ID is a general string ID param.
	ID string `log:"id"`
	// Addr is a network address.
	Addr string `log:"addr"`
	// Timeout is a generic timeout.
	Timeout time.Duration `log:"timeout"`
	// Prompt is a prompt to be sent to LLM.
	Prompt string `log:"prompt"`
	// IntByTimeout means the interruption was caused by timeout.
	IntByTimeout bool `log:"int_by_timeout"`
	// Msg is a single message with an author and text.
	Msg *Msg `log:"msg"`
	// Perform additional checks via LLM
	CheckLLM bool `log:"check_llm"`
	// List of choices
	Choices []string
	// Actions are a list of buttons to be displayed in the UI.
	Actions    []ActionInfo `log:"actions"`
	Stories    []StoryInfo  `log:"stories"`
	StatesList []string     `log:"states_list"`
	// ActivateList is a list of booleans for StatesList, indicating an active state at the given index.
	ActivateList []bool `log:"activate_list"`
	ConfigAI     *ConfigAI
	ClockDiff    [][]int

	// Result is a buffered channel to be closed by the receiver
	ResultCh chan<- am.Result
	// DBQuery is a function that executes a query on the database.
	DBQuery func(ctx context.Context) error
	// RetStr returns dereferenced user prompts based on the list of offer.
	RetOfferRef chan<- *OfferRef
	SSHServer   *ssh.Server
	SSHSess     ssh.Session
	// Done is a buffered channel to be closed by the receiver
	Done chan<- struct{}
}

A is a struct for node arguments. It's a typesafe alternative to am.A.

func ParseArgs added in v0.2.0

func ParseArgs(args am.A) *A

ParseArgs extracts A from am.Event.ArgsAPrefix.

type ARPC added in v0.5.0

type ARPC struct {
	// ID is a general string ID param.
	ID string `log:"id"`
	// Addr is a network address.
	Addr string `log:"addr"`
	// Timeout is a generic timeout.
	Timeout time.Duration `log:"timeout"`
	// Prompt is a prompt to be sent to LLM.
	Prompt string `log:"prompt"`
	// IntByTimeout means the interruption was caused by timeout.
	IntByTimeout bool `log:"int_by_timeout"`
	// Msg is a single message with an author and text.
	Msg *Msg `log:"msg"`
	// Perform additional checks via LLM
	CheckLLM bool `log:"check_llm"`
	// List of choices
	Choices []string
	// Actions are a list of buttons to be displayed in the UI.
	Actions      []ActionInfo `log:"actions"`
	Stories      []StoryInfo  `log:"stories"`
	StatesList   []string     `log:"states_list"`
	ActivateList []bool       `log:"activate_list"`
	Result       am.Result
	ConfigAI     *ConfigAI
	ClockDiff    [][]int
}

ARPC is a subset of am.A that can be passed over RPC.

type Action added in v0.5.0

type Action struct {
	// random ID
	ID string

	// Current value.
	Value func() int
	// Maximum value.
	ValueEnd func() int

	Label  string
	Desc   string
	Action func()

	StateAdd    string
	StateRemove string

	VisibleAgent amhelp.Cond
	VisibleMem   amhelp.Cond
	IsDisabled   func() bool
	LabelEnd     string

	Pos         int
	PosInferred bool
}

func (Action) String added in v0.5.0

func (s Action) String() string

type ActionInfo added in v0.5.0

type ActionInfo struct {
	// random ID
	ID string

	// Current value.
	Value int
	// Maximum value.
	ValueEnd int

	Label  string
	Desc   string
	Action bool

	StateAdd    string
	StateRemove string

	VisibleAgent bool
	VisibleMem   bool
	IsDisabled   bool
	LabelEnd     string

	Pos         int
	PosInferred bool
}

ActionInfo is a static model for Action.

type AgentAPI added in v0.5.0

type AgentAPI interface {
	AgentBaseAPI

	Msgs() []*Msg
	Splash() string
	MachSchema() (am.Schema, am.S)
	Actions() []ActionInfo
	Stories() []StoryInfo
	Story(state string) *Story
	DBAgent() *sql.DB
	MachMem() *am.Machine
	// Moves return a list of moves and their descriptions for orienting.
	OrientingMoves() map[string]string
	// HistoryStates returns a list of states to track in the history.
	HistoryStates() am.S
}

AgentAPI is the top-level API to be implemented by the final agent.

type AgentBaseAPI added in v0.5.0

type AgentBaseAPI interface {
	// AgentImpl returns the top-level agent implementation.
	AgentImpl() AgentAPI
	// Output outputs text to the user.
	Output(txt string, from From) am.Result

	Mach() *am.Machine
	DBG() *debugger.Debugger
	Hist() (history.MemoryApi, error)

	ConfigBase() *Config
	OpenAI() []*OpenAIClient
	Gemini() []*GeminiClient

	Start() am.Result
	Stop(disposeCtx context.Context) am.Result
	Log(msg string, args ...any)
	LogErr(msg string, err error, args ...any)
	Logger() *slog.Logger
	Store() *AgentStore

	QueriesBase() *sqlc.Queries

	DBBase() *sql.DB
	DBHistory() *sql.DB
}

AgentBaseAPI is the base agent API implemented by the framework.

type AgentInit added in v0.5.0

type AgentInit interface {
	Init(
		agentImpl AgentAPI, cfg *Config, logArgs am.LogArgsMapperFn, groups any, states am.States, args any,
	) error
}

AgentInit is an init func for embeddable agent structs (non-top level ones).

type AgentQueries added in v0.5.0

type AgentQueries[TQueries any] interface {
	Queries() *TQueries
}

AgentQueries is a generic SQL API.

type AgentStore added in v0.5.0

type AgentStore struct {
	M         map[string]any
	ClockDiff [][]int
	Web       fs.FS
}

type Config added in v0.4.0

type Config struct {
	// File is the path to the loaded config file.
	File  string `kdl:"-"`
	AI    ConfigAI
	Agent ConfigAgent
	Web   ConfigWeb
	TUI   ConfigTUI
	Tools ConfigTools
	Debug ConfigDebug
}

func ConfigDefault added in v0.4.0

func ConfigDefault() Config

func (*Config) DotEnv added in v0.5.0

func (cfg *Config) DotEnv() string

type ConfigAI added in v0.4.0

type ConfigAI struct {
	OpenAI []ConfigAIOpenAI `kdl:"OpenAI,multiple"`
	Gemini []ConfigAIGemini `kdl:"Gemini,multiple"`
	// Max LLM requests per session.
	ReqLimit int
}

type ConfigAIGemini added in v0.4.0

type ConfigAIGemini struct {
	Key      string
	Disabled bool
	Model    string
	Tags     []string
	Retries  int
}

func ConfigDefaultGemini added in v0.4.0

func ConfigDefaultGemini() ConfigAIGemini

type ConfigAIOpenAI added in v0.4.0

type ConfigAIOpenAI struct {
	Key      string
	Disabled bool
	URL      string
	Model    string
	Tags     []string
	Retries  int `kdl:",omitempty"`
}

func ConfigDefaultOpenAI added in v0.4.0

func ConfigDefaultOpenAI() ConfigAIOpenAI

type ConfigAgent added in v0.4.0

type ConfigAgent struct {
	// bot ID
	ID    string
	Label string
	// // dir for tmp files, defaults to CWD
	Dir       string
	Intro     string
	IntroDash string
	Footer    string
	Log       ConfigAgentLog
	History   ConfigAgentHistory
}

type ConfigAgentHistory added in v0.4.0

type ConfigAgentHistory struct {
	Backend string
	// TODO BackendParsed enum
	Max int
}

type ConfigAgentLog added in v0.4.0

type ConfigAgentLog struct {
	// path to the log file
	File string
	// log prompts
	Prompts bool
	// duplicate log to state-machine log
	MachFwd bool
	// mach log level 0-5
	MachLevel am.LogLevel
	// print machine log
	MachPrint bool
}

type ConfigDebug added in v0.4.0

type ConfigDebug struct {
	// Display extra info about these stories in the machine log
	Story []string
	// Run the mock scenario
	Mock bool
	// Start pprof on addr
	ProfilerAddr string
	// Enable misc debugging modes (SQL history, am-relay, browser RPC)
	// TODO extract SQL
	Verbose bool
	// Create value files for inspection
	ValFiles bool
	// Enable REPL for agent, mem, and tools
	REPL bool
	// Connect and send dbg info to am-dbg
	DBGAddr string

	// Start an embedded debugger on localhost:{DBGEmbed}
	DBGEmbed bool
	// Expose the embedded debugger on http://localhost:{DBGEmbedWeb}
	DBGEmbedWeb int
	// Start a web REPL on http://localhost:{REPLWeb}
	REPLWeb int
}

type ConfigSearXNG added in v0.4.0

type ConfigSearXNG struct {
	// Port to start a local instance on
	Port string
	// URL of an existing instance (disables Port).
	URL string
}

type ConfigTUI added in v0.4.0

type ConfigTUI struct {
	// TODO Addr
	// TODO WebAddr
	// SSH host
	Host string
	// SSH port
	PortSSH int
	// Web host
	WebHost string
	// Web port
	PortWeb int
	// Number of transitions to show on the clock
	ClockRange int
}

type ConfigTools added in v0.4.0

type ConfigTools struct {
	SearXNG ConfigSearXNG
}

type ConfigWeb added in v0.5.0

type ConfigWeb struct {
	// Base address for HTTP services:
	// - main HTTP server
	// - +1 WebSocket addr of the agent's RPC server (dashboard)
	// - +2 WebSocket addr of the agent's RPC server (agent UI)
	// - +3 TCP addr of the dashboard REPL server (WS tunnel)
	// - +4 TCP addr of the agent UI REPL server (WS tunnel)
	Addr string
	// Start a DBPort web UI on http://localhost:{DBPort[0-2]}
	DBPort int
	// Start a log web UI on http://localhost:{LogPort}
	LogPort int
}

func (*ConfigWeb) AgentURL added in v0.5.0

func (c *ConfigWeb) AgentURL() string

func (*ConfigWeb) AgentWSAddrDash added in v0.5.0

func (c *ConfigWeb) AgentWSAddrDash() string

func (*ConfigWeb) AgentWSAddrRemoteUI added in v0.5.0

func (c *ConfigWeb) AgentWSAddrRemoteUI() string

TODO remove when dialing via relay lands

func (*ConfigWeb) DashURL added in v0.5.0

func (c *ConfigWeb) DashURL() string

func (*ConfigWeb) REPLAddrAgentUI added in v0.5.0

func (c *ConfigWeb) REPLAddrAgentUI() string

func (*ConfigWeb) REPLAddrDash added in v0.5.0

func (c *ConfigWeb) REPLAddrDash() string

type From

type From enum.Member[string]

type GeminiClient added in v0.5.0

type GeminiClient struct {
	Cfg *ConfigAIGemini
	C   *instructor.InstructorGoogle
}

type Msg added in v0.2.0

type Msg struct {
	From      From
	Text      string
	CreatedAt time.Time
}

func NewMsg added in v0.2.0

func NewMsg(text string, from From) *Msg

func (*Msg) String added in v0.2.0

func (m *Msg) String() string

type OfferRef added in v0.2.0

type OfferRef struct {
	// Index from 0
	Index int
	Text  string
}

type OpenAIClient added in v0.5.0

type OpenAIClient struct {
	Cfg *ConfigAIOpenAI
	C   *instructor.InstructorOpenAI
}

type Story added in v0.2.0

type Story struct {
	StoryInfo

	Agent  StoryActor
	Memory StoryActor

	// If is an optional function used to confirm that this story can activate. It has access to the whole story struct,
	// so all the involved state machines and their historical snapshots (relative to activation and deactivation of
	// this story).
	CanActivate func(instance *Story) bool
	Actions     []Action
}

Story is the basis for all stories.

func (*Story) Check added in v0.2.0

func (s *Story) Check() bool

func (*Story) New added in v0.5.0

func (s *Story) New(actions []Action) *Story

New returns a copy of the story with the actions bound. Used to create new instances.

func (*Story) String added in v0.2.0

func (s *Story) String() string

type StoryActionsByIdx added in v0.4.0

type StoryActionsByIdx []Action

func (StoryActionsByIdx) Len added in v0.4.0

func (s StoryActionsByIdx) Len() int

func (StoryActionsByIdx) Less added in v0.4.0

func (s StoryActionsByIdx) Less(i, j int) bool

func (StoryActionsByIdx) Swap added in v0.4.0

func (s StoryActionsByIdx) Swap(i, j int)

type StoryActor added in v0.2.0

type StoryActor struct {
	Mach *am.Machine

	// actor's time when the story activated
	TimeActivated   am.Time
	TimeDeactivated am.Time

	// When these conditions are met, the story will activate itself.
	Trigger amhelp.Cond
}

StoryActor is a binding between a Story and an actor (state machine).

type StoryInfo added in v0.2.0

type StoryInfo struct {
	// Name of the bound state (eg StoryFoo).
	State string
	// Tick is the current tick of the bound state.
	Tick uint64
	// Epoch is the sum of all previous memories, before a replacement.
	Epoch uint64

	// Title of this story.
	Title string
	// Description of this story.
	Desc string

	// The story was last deactivated at this human time.
	DeactivatedAt time.Time
	// The story was last active for this many ticks of the AgentLLM machine.
	LastActiveTicks uint64
}

StoryInfo is a static model for Story.

func (StoryInfo) String added in v0.2.0

func (s StoryInfo) String() string

Jump to

Keyboard shortcuts

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