sol

package module
v0.1.17 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: Apache-2.0 Imports: 32 Imported by: 0

README

sol

Minimal LLM agent loop in Go — embeddable as a library, usable as a CLI utility composable with pipes, jq, and structured JSON output.

The core agent loop is derived from opencode (see NOTICE for attribution), but sol's scope is different: opencode is an interactive coding TUI, sol is a building block — something you call from your own Go code or stitch into shell pipelines.

[!WARNING] Alpha software. Early-stage code with bugs we haven't found yet. We use it ourselves but expect rough edges, especially around uncommon prompts or tool combinations. Please open an issue for anything that breaks.

Install

As a library:

go get github.com/airlockrun/sol

As a CLI:

go install github.com/airlockrun/sol/cmd/sol@latest

Requires Go 1.26+.

CLI

sol "summarize the contents of README.md"
sol --model personal/openai/gpt-4o --agent plan "outline a migration to postgres 17"
sol "Summarize README.md" > summary.txt

Flags:

  • --model — explicit slug/provider/model reference; otherwise the saved default
  • --agent — override the session/configured agent: build, plan, explore, general
  • --sid — existing durable session ID; overrides SOL_SESSION for this invocation
  • --verbose — tool progress on stderr
  • --compact — summarize the selected session's model context
  • --clear — reset the selected session's active context, retaining full history
  • --help, --version — usage and version without configuration or credential access

Administrative commands require --session, --auth, or --config. Positional words always form the prompt: sol session list sends session list to the model. Options are parsed only before the first prompt word; sol request --session list sends request --session list. A leading bare -- ends option parsing: sol -- --help sends the literal prompt --help. A bare -- after the prompt starts is literal too. Unknown options before a prompt fail without model access. Administrative options require double hyphens; operational options such as --model also accept Go's single-hyphen spelling.

Requests are noninteractive batch executions: assistant text goes to stdout, errors and newly created session IDs to stderr. Permissions are auto-approved and questions use the runner's automatic answers. No title-generation request runs.

Default agent and local sessions
sol --config agent plan
sol --config agent                       # read the default
export SOL_SESSION="$(sol --session new)" # create/select this terminal's session
sol 'Inspect the project'
sol 'Continue with the implementation'   # resume the same history
sol --session compact "$SOL_SESSION"     # summarize model context without running tools
sol --compact                            # compact SOL_SESSION
sol --sid OTHER_ID --clear                # reset context; retain the full transcript
sol --session show "$SOL_SESSION"        # JSON record including full history and context
sol --session list
sol --sid OTHER_ID 'Continue that session'
export SOL_SESSION=OTHER_ID              # switch this shell's selection
sol --config agent --clear               # default to build

Each shell selects its own ID explicitly. No global current-session file, terminal guessing, or interactive picker is involved. With no selector, each request creates a new session. Unknown IDs and empty SOL_SESSION fail. New sessions use the saved defaultAgent (otherwise build); existing sessions retain their agent/model unless overridden with flags. Execute from the session's original working directory.

Private session records live under $XDG_STATE_HOME/sol/sessions, or ~/.local/state/sol/sessions. Atomic snapshots retain the full transcript separately from the compacted model context. One cross-process lease protects an entire turn; a concurrent writer to the same session fails busy while unrelated sessions run independently. Interrupted turns retain an explicit unknown-effect marker for the next requested turn; commands are not automatically replayed.

--clear uses the same exclusive session lease as a request or compaction. It atomically empties model context and resets the interruption marker, preserving the session ID, agent, model, working directory and full transcript. Repeating it adds no history entries. The next request starts with fresh instructions and only new messages, while the transcript continues accumulating. Clear works from any directory without model resolution, credentials, tools or configuration writes. It changes only session context, not workspace files, Git state or external processes. --sid ID --compact and --sid ID --clear override the shell's selection locally. --session compact ID also overrides it; combining that ID with --sid fails.

SOL_DEPTH guards nested model executions. An outer Sol passes SOL_DEPTH=1 to launched programs, allowing one child Sol. That child passes SOL_DEPTH=2, which blocks further Sol inference before configuration or model access. Help, version and session inspection require no inference. Inherited SOL_SESSION is removed from launched programs so a child starts independently; a shell command can select a different child session explicitly. This is an operational recursion guard, not a sandbox against programs deliberately replacing environment variables.

Local configuration and provider API keys

Sol stores named provider accounts, inline credentials, and the default model reference in one private user configuration file: filepath.Join(os.UserConfigDir(), "sol", "config.json"). On Linux this is $XDG_CONFIG_HOME/sol/config.json, or ~/.config/sol/config.json when XDG_CONFIG_HOME is unset. The CLI does not discover credentials in project .sol directories or load project .env files.

sol --auth set-key personal/openai              # hidden terminal prompt
secret-manager-command | sol --auth set-key work/anthropic --stdin
sol --auth status personal/openai               # presence only, never the key
sol --auth remove-key personal/openai
sol --config model personal/openai/gpt-4o-mini   # save explicit account/model
sol --config model                             # read the selected default
sol "Summarize README.md"                       # use that default
sol --config model --clear

secret-manager-command represents a command that writes the API key to stdout. --stdin requires piped input: one nonempty key line followed by EOF, limited to 16 KiB. Without --stdin, set-key requires a terminal and disables echo during entry. Ctrl-C cancels the hidden prompt and restores terminal state. Secret command-line arguments are rejected. Status and configuration commands do not print credentials.

The private schema is:

{
  "version": 3,
  "providers": {
    "personal/openai": {"auth": "api-key", "key": "YOUR_API_KEY"},
    "work/openai": {
      "auth": "codex",
      "credentials": {
        "access_token": "ACCESS_TOKEN",
        "refresh_token": "REFRESH_TOKEN",
        "expires_at": "2026-10-10T12:00:00Z",
        "account_id": "ACCOUNT_ID"
      }
    }
  },
  "defaultModel": "personal/openai/gpt-5.4",
  "defaultAgent": "plan"
}

Entry names are case-sensitive slug/provider pairs. Slugs match [A-Za-z0-9][A-Za-z0-9._-]*; provider IDs must be canonical Sol catalog IDs, not aliases. Model references split at the first two slashes and retain the full model suffix, for example work/huggingface/org/model. Each entry has one method: api-key, or codex for OpenAI. Multiple entries can use the same provider and method with independent credentials.

API-key entries contain exactly one of key or explicit keyEnv when connected. For example {"auth":"api-key","keyEnv":"WORK_OPENAI_KEY"} reads only that variable; missing/empty values fail. Global provider environment variables never override inline keys or create accounts. Optional account baseURL selects an API-key endpoint. Disconnected entries retain their method with no credentials.

--model overrides the saved reference, including its account. Without an explicit reference or defaultModel, startup fails with configuration instructions. Missing accounts and disconnected accounts fail without choosing another account, method, or environment key. Login, refresh and logout preserve the default reference. sol --config model --clear clears it. --auth selects account administration.

Sol uses private files/directories (0600/0700 on Unix and protected current-user ACLs on Windows), fsync and atomic replacement. config.json.lock serializes short read-modify-write transactions. Hashed per-entry lock files serialize credential operations across processes while unrelated accounts can refresh concurrently. Keep lock files in place while processes use the store. Unsupported fields, versions and corrupt records fail without overwriting data. CLI status/default output contains no keys or tokens.

localconfig exposes ProviderConfig, ModelRef, ParseModelRef, DefaultPath, NewFileStore, Load, Update, and LockEntry. Store callbacks must not reenter the store. Acquire entry locks before configuration updates. Constructors perform no credential discovery. Hosted Airlock model bindings use their own records and do not read this private configuration.

Configuration import

When config.json is absent, recognized version-1/version-2 auth.json records are automatically imported. Provider API keys become default/PROVIDER entries; OpenAI Codex tokens become codex/openai. A saved model/auth pair maps to that entry's full reference. No saved default means no default is invented. Unsupported methods, corrupt records, and dangling defaults abort the import. The source file is preserved as an inactive backup; config.json is the sole active configuration. When config.json exists, auth.json is not read or reimported, including after logout. Remove the inactive backup manually when it is no longer needed.

Local Codex device authentication

Use a ChatGPT account with access to the selected Codex model:

sol --auth login work/openai --method codex
sol --auth login personal/openai --method codex  # independent account session
sol --auth status work/openai
sol --model work/openai/gpt-5.4 --agent plan "Summarize README.md"
sol --config model work/openai/gpt-5.4
sol --agent plan "Summarize README.md"
sol --auth logout work/openai

Login prints https://auth.openai.com/codex/device and a code to enter there. It requires no callback listener or local browser. Login expires after ten minutes and can be interrupted with Ctrl-C. Individual auth HTTP requests are bounded to thirty seconds. Status displays the access-token expiration without printing tokens; it does not refresh or verify the remote account. Logout removes the local credential only.

Codex is a method attached to each named OpenAI entry. Each login persists only that entry's tokens after success. Configured Codex entries support sol --auth login ENTRY without repeating the method. Per-entry locks serialize refresh-token rotation across processes, including concurrent runs and subagents. Refresh starts when access expires within one minute; successful refresh is persisted before a model request is sent. Auth failures are reported to the caller; run login again if the account requires reauthorization. Keep the lock file in place while Sol processes use this store.

Codex is selected by referencing a configured Codex entry; a login alone does not change another entry's requests. It does not require OPENAI_API_KEY, and uses the dedicated ChatGPT Codex Responses backend. AIRLOCK_API_URL and OPENAI_BASE_URL must be unset for this mode. Model availability depends on the account's Codex entitlements; an ordinary OpenAI catalog entry does not establish subscription access.

With Codex, --search --search-provider personal/brave selects an independent API-key entry, configured with sol --auth set-key personal/brave. Device credentials never reach API-key search backends. Session titles are deterministic excerpts of the first request.

Explicit Codex models for library and local SDK tests

For an explicitly selected live model, callers can use the configured-model resolver without constructing a provider or credential source:

model, limits, err := provider.ResolveLocalModel(ctx, provider.LocalModelOptions{
    Model: "work/openai/gpt-5.4",
    HTTPClient: http.DefaultClient,
    UserAgent: "my-local-test/1",
    SessionID: "explicit-test-session",
})
if err != nil {
    return err
}
// Inject model and limits into the test runtime's model binding.

ResolveLocalModel returns (stream.Model, session.ModelLimits, error). Model must be an explicit canonical slug/provider/model reference to a configured account. The resolver does not select application model slots or the saved default. Mock models are injected separately; ordinary deterministic tests do not call this resolver. Invalid selections fail before credential discovery. No CLI local-run command is involved.

The resolver loads the OS user store only when explicitly called. Supply Store or an absolute ConfigPath to select a test store instead; providing both is an error. LookupEnv defaults to process environment lookup during resolution and can be replaced for deterministic tests. Only explicit account keyEnv values use that lookup. Codex requires that entry's existing device login; the resolver never starts browser/device login. Expired Codex access is refreshed with durable serialization when the resolved model sends its first request.

Catalog context/input/output maxima are returned unchanged. Limits can supply an explicit *session.ModelLimits override for deployment IDs or other unknown models; missing/invalid budgets fail rather than inventing a context window. BaseURL overrides API-key endpoints. CodexURL and Issuer override Codex endpoints for local protocol tests and otherwise use production endpoints.

Custom HTTP clients are honored for supported language providers, including dedicated GoAI transports. The resolver copies the supplied client and rejects redirects so credentials and request bodies stay on the configured endpoint. No global client is changed. Native provider request formats remain provider-owned. The CLI shares the resolver's API-key precedence helper, provider.ResolveLocalAPIKey(config, providerID, lookupEnv).

auth/codex and provider.NewCodexModel are reusable without the CLI. Callers provide a store, HTTP clients, protocol identity, and session ID explicitly:

shared, err := localconfig.NewFileStore(absoluteConfigPath)
if err != nil {
    return err
}
store, err := codex.NewStore(shared, "work/openai")
if err != nil {
    return err
}
credentials, err := codex.NewClient(codex.ClientOptions{
    Store: store,
    HTTPClient: &http.Client{Timeout: 30 * time.Second},
    Issuer: codex.Issuer,
    ClientID: codex.ClientID,
    UserAgent: "my-local-test/1",
})
if err != nil {
    return err
}
model, err := provider.NewCodexModel("gpt-5.4", provider.CodexOptions{
    Credentials: credentials,
    HTTPClient: &http.Client{}, // Stream lifetime is controlled by context.
    URL: provider.CodexURL,
    UserAgent: "my-local-test/1",
    SessionID: "explicit-test-session",
})
if err != nil {
    return err
}
// Inject model into sol.RunnerOptions.Model or an agentsdk runtime Input.Model.

Imports are github.com/airlockrun/sol/localconfig, github.com/airlockrun/sol/auth/codex, and github.com/airlockrun/sol/provider, plus net/http and time. Constructing a client or model does not read credentials or perform network I/O. Calling Stream obtains credentials through codex.Source.Access(ctx). Live local tests must opt in explicitly; deterministic tests supply their own Source implementation and httptest.Server URLs, with no local credential discovery. Inject the resulting stream.Model through the SDK's generic model adapter or existing runtime model inputs.

For programmatic login, call Client.StartDeviceAuth(ctx), present the returned verification URL and user code, then call Client.CompleteDeviceAuth(ctx, device). Completion returns a codex.Credential without persisting it. Commit it explicitly using Store.Update(ctx, func(*codex.Credential) (*codex.Credential, error) { return &credential, nil }). Store.Load returns codex.ErrNotLoggedIn when empty; an Update callback receives nil when empty and deletes the credential by returning nil. This is a minimal record adapter; all durable file mechanics belong to localconfig. Its updates preserve other OAuth methods, the OpenAI API key, other providers, and the default model. Both update interfaces are serialized and must not reenter the store.

The adapter moves text system/developer messages into top-level instructions and requires nonempty instructions. It preserves tool and encrypted-reasoning history, forces store:false, and does not use server-stored continuation. conversation and previousResponseId are rejected. Output limits and sampling controls are omitted, including on compaction/title requests; minimal reasoning effort maps to low. Unsupported Responses options maxToolCalls, metadata, logprobs, truncation, user, safetyIdentifier, and promptCacheRetention are removed. A nonempty promptCacheKey controls session affinity, otherwise the explicit SessionID does. Authentication, account, and compute-residency headers are authoritative; redirects are refused. JWT payloads are decoded only for Codex routing metadata, not for application authentication. A missing OAuth expires_in uses a one-hour expiration fallback.

Local verification (no real login):

go test -race ./localconfig ./auth/codex ./provider ./cmd/sol .
go test ./...
go vet ./...
go build ./...
GOWORK=off go build ./...

Library

The sol package is what airlock embeds for in-process agent execution. Run the agent loop directly, supply your own provider/tools/bus, and stream results into your application.

See cmd/sol/main.go and cmd/toolserver/main.go in this repo for full examples.

Native image reads

The read tool opens PNG, JPEG, GIF, and WebP files as native image attachments. It identifies the format from the file bytes and validates the image header and dimensions. Each image file is limited to 5 MiB (5,242,880 bytes) and is read whole; omit offset and limit when reading images. Either pagination parameter, including an explicit zero, is rejected for images. Resize larger images first. Text files retain their line pagination and 50 KiB output cap. Read accepts regular files and symbolic links to regular files. It checks the target before opening and the opened descriptor before reading any bytes. Pipes and device files are rejected. On Unix, nonblocking opens prevent a replacement pipe from hanging descriptor validation.

The tool returns the original encoded image through tool.Result.Attachments with base64 data and its detected MIME type. A vision-capable model receives the image for visual inspection; OCR is not required. Provider/model capabilities and the configured transport must support image input. Session persistence keeps the structured image result; history retention and compaction can remove old images from model context according to the configured policy.

Scope

We accept contributions that improve sol's library API, scriptability, structured-output handling, and pipe-friendly UX. We don't accept changes that try to make sol re-converge with opencode's interactive TUI experience — that's not what sol is for. Use opencode if that's what you want. See CONTRIBUTING.md for details.

Companion projects

  • airlock (AGPL-3.0) — self-hosted cyborg agent platform that embeds sol
  • agentsdk (Apache-2.0) — Go SDK for building agents on airlock
  • goai (Apache-2.0) — Go port of the Vercel AI SDK

License

Apache-2.0. The opencode-derived portions are MIT and reproduced under NOTICE.

Contributing

See CONTRIBUTING.md and CODE_OF_CONDUCT.md. A CLA Assistant bot will prompt you to sign on your first PR (one signature covers all airlockrun projects).

Security

Email security@airlock.run. Do not open public issues for vulnerabilities.

Documentation

Index

Constants

View Source
const Version = "0.1.17"

Version is the sol library version. It is strictly greater than the latest git tag except while that exact version is being released.

Variables

This section is empty.

Functions

func BuildSwitchPrompt

func BuildSwitchPrompt() string

BuildSwitchPrompt returns the build switch prompt.

func ConnectMCPServers

func ConnectMCPServers(ctx context.Context, servers []MCPServer) (*mcp.Client, tool.Set, error)

ConnectMCPServers connects to the configured MCP servers via HTTP and returns the MCP client and the discovered tools. Tool schemas are normalized to match opencode's behavior. The caller must call client.DisconnectAll() when done.

func EnvironmentInfo

func EnvironmentInfo(workDir string) string

EnvironmentInfo returns environment information for agents with custom prompts.

func GenerateTitleAsync

func GenerateTitleAsync(ctx context.Context, userPrompt string, titleModel, apiKey, baseURL string) <-chan TitleResult

GenerateTitleAsync generates a title for the conversation asynchronously. It returns a channel that will receive the result.

func GenerateTitleWithModelAsync added in v0.1.13

func GenerateTitleWithModelAsync(ctx context.Context, userPrompt string, model stream.Model) <-chan TitleResult

GenerateTitleWithModelAsync uses an explicitly supplied model and credentials.

func GetPromptForModel

func GetPromptForModel(modelID string) string

GetPromptForModel returns the provider-specific prompt name for logging/debugging.

func MaxStepsPrompt

func MaxStepsPrompt() string

MaxStepsPrompt returns the max steps warning prompt.

func PlanPrompt

func PlanPrompt() string

PlanPrompt returns the plan mode prompt.

func PlanReminderAnthropicPrompt

func PlanReminderAnthropicPrompt() string

PlanReminderAnthropicPrompt returns the Anthropic-specific plan reminder.

func SystemPrompt

func SystemPrompt(modelID, workDir string) string

SystemPrompt generates the system prompt for the agent. It selects the appropriate provider-specific prompt and appends environment info. modelID is the model identifier (e.g., "gpt-4o"), workDir is the working directory.

func TitlePrompt

func TitlePrompt() string

TitlePrompt returns the title generation prompt.

Types

type CompactResult

type CompactResult struct {
	// TokensFreed is the estimated delta between pre- and post-compaction
	// context size. Reported to the UI as the divider label.
	TokensFreed int

	// Summary is the text the model produced. Callers may surface it to the
	// user, log it, or ignore it.
	Summary string
}

CompactResult describes the outcome of a user-triggered compaction.

type CompactionState

type CompactionState struct {
	Messages []goai.Message `json:"messages"` // the compacted messages (excluding system prompt)
}

CompactionState captures the compacted messages when context overflow triggers compaction.

type ExitedRunResult

type ExitedRunResult struct {
	*RunResult

	// Exit holds whatever the agent passed to the exit tool. When the run
	// terminated for any other reason (provider error, ctx cancel, max
	// nudges exceeded), Exit.Called() returns false and the result-level
	// Status indicates the actual outcome.
	Exit *tools.ExitState

	// Nudges is the count of "you must call exit" re-drives sent before
	// the run terminated. 0 means the agent called exit (or errored) on
	// the first attempt.
	Nudges int
}

ExitedRunResult bundles the underlying RunResult with the agent-reported exit state and the number of nudges sent. Returned by RunUntilExit.

func (*ExitedRunResult) ExitCode

func (r *ExitedRunResult) ExitCode() int

ExitCode maps an ExitedRunResult onto a stable process exit code, suitable for sol-CLI / CI consumers that pipe sol invocations and want machine-readable outcomes.

0 — success: agent called exit{status:"success"}
1 — error:   agent called exit{status:"error"} (LLM-reported failure)
2 — no-exit: agent stopped without calling exit after all nudges
3 — run-failure: provider error, model panic, validation, etc.
4 — cancelled: ctx cancellation propagated

Stable wire contract — do not renumber.

type InProcessChild added in v0.1.7

type InProcessChild struct {
	AgentName         string             `json:"agentName"`
	Messages          []goai.Message     `json:"messages"`
	SuspensionContext *SuspensionContext `json:"suspensionContext,omitempty"`
	CompactionState   *CompactionState   `json:"compactionState,omitempty"`
}

InProcessChild is the SuspensionContext.Data payload for a Sol Task subagent that suspended. It carries everything the resume dispatcher needs to reconstruct and re-drive the subagent on the parent's resume, so the parent checkpoint is self-contained.

type MCPServer

type MCPServer struct {
	// Name is a unique identifier for this server (used as tool name prefix).
	Name string

	// URL is the HTTP endpoint for the MCP server.
	URL string

	// Headers are HTTP headers (e.g., Authorization).
	Headers map[string]string
}

MCPServer configures an HTTP MCP server connection.

type PermissionResolution added in v0.1.8

type PermissionResolution struct {
	Messages          []goai.Message
	Results           []stream.ToolResultEvent
	SuspensionContext *SuspensionContext
}

PermissionResolution contains the tool messages and results created while resolving one permission gate. SuspensionContext is non-nil when a later call in the ordered batch reaches another Sol suspension.

type RunResult

type RunResult struct {
	AgentName string        `json:"agentName"`
	TotalText string        `json:"totalText"`
	Steps     []*StepResult `json:"-"`
	Error     error         `json:"-"`

	Status            RunStatus          `json:"status"`
	Messages          []goai.Message     `json:"messages"`
	NewMessages       []goai.Message     `json:"newMessages,omitempty"`
	CompactionState   *CompactionState   `json:"compactionState,omitempty"`
	SuspensionContext *SuspensionContext `json:"suspensionContext,omitempty"`

	// Usage is the sum of every step's LLM usage over the run. InputTotal
	// and OutputTotal reflect total tokens billed for all API calls this
	// run made (tool loops included). Callers publishing billing / display
	// totals should read from here.
	Usage stream.Usage `json:"usage,omitempty"`
}

RunResult contains the results of an agent run.

func (*RunResult) GetTotalText

func (r *RunResult) GetTotalText() string

GetTotalText returns the total text output. This implements tools.SubagentResult interface.

type RunStatus

type RunStatus string

RunStatus represents the outcome of a run.

const (
	RunCompleted RunStatus = "completed"
	RunSuspended RunStatus = "suspended"
	RunFailed    RunStatus = "failed"
	RunCancelled RunStatus = "cancelled"
	// RunStepLimitReached means the step budget ended while work remained.
	// It is not completion and does not trigger RunUntilExit nudges.
	RunStepLimitReached RunStatus = "step_limit_reached"
	// RunInputTokenLimitReached means cumulative model input reached its budget.
	RunInputTokenLimitReached RunStatus = "input_token_limit_reached"
	// RunExited is set when the agent invoked the exit tool. The caller
	// reads RunnerOptions.ExitState to learn the agent-reported status
	// (success/error) and the accompanying message. Only emitted when the
	// runner was constructed with a non-nil ExitState.
	RunExited RunStatus = "exited"
)

type RunUntilExitOptions

type RunUntilExitOptions struct {
	// MaxNudges caps how many times the runner re-drives the agent with
	// a reminder when it stops without calling exit. Default 2 when zero.
	MaxNudges int

	// NudgeMessage is the user message appended on each nudge. A sane
	// default is used when empty.
	NudgeMessage string
}

RunUntilExitOptions configures the auto-nudge loop in RunUntilExit.

type Runner

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

Runner executes an agent session.

func NewRunner

func NewRunner(opts RunnerOptions) *Runner

NewRunner creates a new agent runner.

func (*Runner) AgentName

func (r *Runner) AgentName() string

AgentName returns the name of the current agent. This implements tools.SubagentSpawner interface.

func (*Runner) Bus

func (r *Runner) Bus() *bus.Bus

Bus returns the runner's scoped event bus.

func (*Runner) Compact

func (r *Runner) Compact(ctx context.Context) (*CompactResult, error)

Compact runs LLM-backed summarization without stepping the thinking loop. Used when the user explicitly asks for compaction (e.g. /compact) rather than letting the context-overflow path fire on its own. Requires a SessionStore — in-memory sessions have no one to persist the checkpoint to.

func (*Runner) Continue

func (r *Runner) Continue(ctx context.Context, prompt string) (*RunResult, error)

Continue adds a new prompt and continues the thread. Must be called after Run has been called at least once.

func (*Runner) PermissionManager

func (r *Runner) PermissionManager() *bus.PermissionManager

PermissionManager returns the runner's scoped permission manager.

func (*Runner) QuestionManager

func (r *Runner) QuestionManager() *bus.QuestionManager

QuestionManager returns the runner's scoped question manager.

func (*Runner) ResolvePermissionSuspension added in v0.1.8

func (r *Runner) ResolvePermissionSuspension(ctx context.Context, suspension *SuspensionContext, approved bool) (*PermissionResolution, error)

ResolvePermissionSuspension resolves the current call in a permission suspension without invoking the model. Approval executes the current call with call-scoped permission and then executes later pending calls in order under the runner's normal managers. Denial records the current call as denied and every later call as skipped. Each result is attached or persisted before its stream event is published.

func (*Runner) Run

func (r *Runner) Run(ctx context.Context, prompt string) (*RunResult, error)

Run executes the agent with the given prompt and returns the result.

func (*Runner) RunUntilExit

func (r *Runner) RunUntilExit(ctx context.Context, prompt string, opts RunUntilExitOptions) (*ExitedRunResult, error)

RunUntilExit runs the agent and re-drives it with a reminder if it stops without calling the exit tool. RunnerOptions.ExitState must have been set when constructing the runner. Errors (provider failures, ctx cancellation) surface immediately — only RunCompleted-without-exit triggers a nudge.

Intended for autonomous, non-interactive runs where the caller wants a structured outcome rather than parsing the model's text.

func (*Runner) SpawnSubagent

func (r *Runner) SpawnSubagent(ctx context.Context, agentName string, prompt string) (tools.SubagentResult, error)

SpawnSubagent creates and runs a subagent. This implements tools.SubagentSpawner interface.

type RunnerOptions

type RunnerOptions struct {
	// Agent defines the agent to run (model, tools, prompt, etc.).
	Agent *agent.Agent

	// APIKey is the API key for the provider implied by Agent.Model.
	APIKey string

	// BaseURL overrides OpenAI-compatible endpoints and is required when the
	// provider ID is openai-compatible.
	BaseURL string

	// HTTPClient sends requests for the explicit openai-compatible provider.
	HTTPClient *http.Client

	// SupportsStructuredOutputs controls native json_schema response formats for
	// the explicit openai-compatible provider. Nil defaults to false for that
	// provider.
	SupportsStructuredOutputs *bool

	// IncludeUsage controls stream_options.include_usage for the explicit
	// openai-compatible provider. Nil defaults to false for that provider.
	IncludeUsage *bool

	// WorkDir is the tool execution working directory.
	WorkDir string

	// Executor handles tool execution. When nil, goai falls back to
	// tool.NewLocalExecutor (tools run in-process). Set this to use remote
	// execution via containers.
	Executor tool.Executor

	// ToolCallExecutionMode controls whether calls from one model response run
	// sequentially or concurrently. Empty defaults to async.
	ToolCallExecutionMode stream.ToolCallExecutionMode

	// MaxStreamErrorContinuations allows a Runner to continue from partial
	// output after a retryable provider stream error. Zero disables recovery.
	// This is intended for autonomous in-memory runs; persisted sessions reject
	// it because the internal recovery instruction has no hidden message type.
	MaxStreamErrorContinuations int

	// Bus is a scoped event bus for this runner. If nil, a new bus is created.
	Bus *bus.Bus

	// InitialMessages, when set, replaces the default [system, user] message
	// initialization in Run(). The prompt parameter becomes a new user message
	// appended at the end. If prompt is empty, no user message is appended.
	// Ignored when SessionStore is set.
	InitialMessages []goai.Message

	// SessionStore provides pluggable message persistence. When set, messages
	// are loaded from the store (instead of InitialMessages) and new messages
	// are persisted after each step. The store must be pre-scoped to a single
	// conversation by the caller.
	SessionStore session.SessionStore

	// CompactionConfig overrides the default compaction configuration.
	// Use this to set a custom PrunedMessage callback.
	CompactionConfig *session.CompactionConfig

	// Quiet suppresses logging output.
	Quiet bool

	// Model overrides the model instance. If nil, created from Agent.Model + APIKey.
	// Used for testing with mock models.
	Model stream.Model

	// ModelLimits defines the context budget for automatic compaction. A zero
	// value infers limits from the known provider catalog. If the catalog has
	// no budget, automatic overflow detection is unavailable; manual compaction
	// still works. Nonzero explicit limits are validated before model calls.
	ModelLimits session.ModelLimits

	// ExitState, when set, opts the runner into "agent must call exit"
	// semantics. After every step the runner checks ExitState.Called() and,
	// if true, breaks the loop with RunResult.Status = RunExited. The exit
	// tool itself is auto-injected into the agent's tool set if not
	// already present, so callers only need to set this field.
	//
	// Intended for autonomous/non-interactive runs (CI, builds, sol-CLI).
	// Use RunUntilExit if you also want the runner to nudge the model when
	// it stops without calling exit.
	ExitState *tools.ExitState

	// SafeBoundaryHook lets a persistent host checkpoint external state and
	// admit already-persisted input between model/tool effects. Existing
	// in-memory and ordinary SessionStore consumers leave it nil.
	SafeBoundaryHook SafeBoundaryHook
}

RunnerOptions configures a new runner.

type SafeBoundary added in v0.1.14

type SafeBoundary string

SafeBoundary identifies a point where all preceding transcript effects are durably complete and the runner may accept host-persisted input.

const (
	BoundaryBeforeModel SafeBoundary = "before_model"
	BoundaryAfterStep   SafeBoundary = "after_step"
	BoundarySuspended   SafeBoundary = "suspended"
)

type SafeBoundaryHook added in v0.1.14

type SafeBoundaryHook func(context.Context, SafeBoundary) ([]session.Message, error)

SafeBoundaryHook is called while the runner owns its transcript. Returned messages must already be persisted by the host; Runner adds them only to its in-memory transcript and session. Hooks must not reenter the Runner. Hook failures stop the run and require a fresh Run to reload the durable transcript.

type StepResult

type StepResult struct {
	Text         string
	ToolCalls    []stream.ToolCall
	ToolResults  []stream.ToolResultEvent
	FinishReason stream.FinishReason
	Usage        stream.Usage
}

StepResult contains the results of a single step.

type SuspensionContext

type SuspensionContext struct {
	Reason           string                   `json:"reason"`
	Data             any                      `json:"data,omitempty"`
	ToolCallID       string                   `json:"toolCallID,omitempty"`
	PendingToolCalls []stream.ToolCall        `json:"pendingToolCalls,omitempty"`
	CompletedResults []stream.ToolResultEvent `json:"completedResults,omitempty"`
}

SuspensionContext captures state when a run is suspended.

type TitleResult

type TitleResult struct {
	Title string
	Error error
}

TitleResult holds the generated title and any error

Directories

Path Synopsis
Package activity turns a tool execution result into a compact, presentation -ready summary: a short structured Action (for a live-actions feed) and a one-line log string (for a curated codegen log).
Package activity turns a tool execution result into a compact, presentation -ready summary: a short structured Action (for a live-actions feed) and a one-line log string (for a curated codegen log).
Package agent provides the agent system for Sol, enabling multiple specialized agents with different capabilities and system prompts.
Package agent provides the agent system for Sol, enabling multiple specialized agents with different capabilities and system prompts.
auth
Package bus provides a typed event bus for inter-component communication.
Package bus provides a typed event bus for inter-component communication.
cmd
sol command
Sol executes a single batch request against an explicitly selected local session.
Sol executes a single batch request against an explicitly selected local session.
toolserver command
Command toolserver runs Sol's tools in a container, serving requests via WebSocket.
Command toolserver runs Sol's tools in a container, serving requests via WebSocket.
Package eventstream forwards typed bus events from a Sol run loop to a caller-supplied Sink.
Package eventstream forwards typed bus events from a Sol run loop to a caller-supplied Sink.
Package executor provides remote tool execution capabilities.
Package executor provides remote tool execution capabilities.
Package localconfig owns Sol's single-user configuration and credentials.
Package localconfig owns Sol's single-user configuration and credentials.
Package provider implements the multi-provider system for sol.
Package provider implements the multi-provider system for sol.
Package session manages the agent session lifecycle including message history, token tracking, and context compaction.
Package session manages the agent session lifecycle including message history, token tracking, and context compaction.
Package tools provides the tool implementations for Sol.
Package tools provides the tool implementations for Sol.
Package toolutil provides utilities used by tools.
Package toolutil provides utilities used by tools.
Package webfetch provides URL fetching with HTML-to-markdown conversion.
Package webfetch provides URL fetching with HTML-to-markdown conversion.
Package websearch provides a web search client with multiple provider backends.
Package websearch provides a web search client with multiple provider backends.

Jump to

Keyboard shortcuts

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