llm

package
v1.4.0 Latest Latest
Warning

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

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

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

Documentation

Overview

Package llm is the agent adapter layer: one execution contract, a config-assembled registry, and the built-in harnesses. It is the Go counterpart of lib/llm/.

An "agent" is an autonomous harness: we hand it a prompt, a system-context string, and a working directory, and it acts on its own — reads tasks.jsonl, runs `tasks`, edits files. Our code never parses its output for meaning; it streams a transcript to the user and reloads the store when the file changes on disk. There is deliberately no separate "completion" protocol — we reach local models by putting a harness in front of them, never by calling a bare model and coercing its text ourselves.

Backends vary along exactly two axes, and Agent hides both:

  • transport: how the harness is driven. Every adapter here spawns a CLI and reuses this machinery; an SDK-transport adapter would supply a different Harness and keep the same Agent surface.
  • model: which model the harness runs, passed through to Command.

Two entry points share one Command, so there is one source of truth for how a backend is invoked:

  • sync (CLI): RunSync spawns with inherited stdio so output streams straight to the terminal, and reports whether it exited cleanly.
  • async (TUI): Start, then read Output as it fills and wait on Done; Cancel stops the whole process group.

Index

Constants

View Source
const (
	CancelTermGrace = 150 * time.Millisecond
	CancelKillGrace = 150 * time.Millisecond
)

Cancellation grace windows. Some harnesses (or the tool subprocesses they spawn) trap TERM, so cancellation must not block a raw-terminal UI indefinitely: the group gets a short graceful window, then KILL, then the child is detached rather than held onto.

View Source
const (
	DefaultOllamaURL = "http://127.0.0.1:11434"
	// DefaultInferenceProvider is Hermes' conventional local-Ollama provider
	// name; overridable via config, or set empty to fall back to Hermes' default.
	DefaultInferenceProvider = "ollama-launch"
)

Variables

This section is empty.

Functions

func PathFrom

func PathFrom(env determinism.Env) string

PathFrom is the PATH an availability probe should search, taken from the environment the adapter boundary resolved rather than from the process.

Types

type Agent

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

Agent is one constructed backend, ready to RunSync or Start.

func Build

func Build(entry Entry, options BuildOptions, conf Config) (*Agent, error)

Build instantiates the adapter for an entry, ready to RunSync or Start.

func New

func New(harness Harness, options Options) *Agent

New constructs an agent over a harness. An empty Binary takes the harness's default, and an empty System means no system context at all — the same `system.to_s.empty? ? nil : system` normalisation Ruby applies, so a caller cannot accidentally inject a blank block.

func (*Agent) Available

func (a *Agent) Available() bool

Available answers whether the backend is usable right now: the binary is reachable, and the harness's own probe passes. It never returns an error — a dead backend is a false, so a UI can flash rather than crash.

func (*Agent) Binary

func (a *Agent) Binary() string

Binary is the executable this agent spawns.

func (*Agent) Cancel

func (a *Agent) Cancel()

Cancel stops a running agent. The signal goes to the whole process group started in Start — negative pid — so a harness's tool subprocesses go with it.

TERM first, then KILL after a short window, and if even that is not reaped in time the child is left to the drain goroutine rather than blocking the caller. A UI must never be held hostage by a harness that traps signals.

func (*Agent) Cancelled

func (a *Agent) Cancelled() bool

Cancelled reports whether this run was stopped by Cancel. It is deliberately distinct from Success: a cancelled run and a run that failed on its own both end nonzero, and only the flag tells a UI which sentence to show.

func (*Agent) Command

func (a *Agent) Command(prompt, model string, stream bool) []string

Command is the argv for a run. Both entry points funnel through it.

func (*Agent) Done

func (a *Agent) Done() <-chan struct{}

Done closes when the run has exited and its output has been drained. A fresh Agent's channel is already closed, so a caller that selects on it before any run does not block forever.

func (*Agent) ExitStatus

func (a *Agent) ExitStatus() int

ExitStatus is the child's exit code, or -1 when it has not exited or died on a signal.

func (*Agent) Output

func (a *Agent) Output() string

Output is the transcript captured so far. It is a snapshot: safe to call while the run is still producing.

func (*Agent) RunSync

func (a *Agent) RunSync(prompt, model string, stream bool) bool

RunSync is the blocking run for the CLI: inherit stdio so the harness streams to the terminal live, and report whether it exited cleanly. It defaults to the non-streaming (final-answer) shape at the call site, since there is no UI to animate.

The boolean is Kernel#system's: true on a clean exit, false on any nonzero status AND on a spawn that never happened. Both mean "the agent did not complete", which is the only distinction the caller acts on.

func (*Agent) Running

func (a *Agent) Running() bool

func (*Agent) Signaled

func (a *Agent) Signaled() (bool, syscall.Signal)

Signaled reports whether the child died on a signal, and which one. This is how a caller distinguishes "the harness refused to stop and we killed it" from "the harness exited".

func (*Agent) Start

func (a *Agent) Start(prompt, model string, stream bool) error

Start spawns the harness asynchronously, capturing its combined output. The child is put in its own process group so Cancel can signal the whole tree: these harnesses spawn tool subprocesses that would otherwise be orphaned when only the leader is killed.

This is the async surface Ruby's Agent#start/#pump/#cancel provides, in the shape Go gives it: a goroutine drains the pipe into Output and closes Done, rather than a caller multiplexing with IO.select. The observable contract — output captured, exit status recorded, cancellation distinct from a nonzero exit, a fresh run resetting the metadata — is the same.

func (*Agent) Success

func (a *Agent) Success() bool

func (*Agent) System

func (a *Agent) System() string

System is the resolved system context, or "".

type BuildOptions

type BuildOptions struct {
	// Root is the working directory the harness runs in.
	Root string
	// System is the resolved system-context string, or "".
	System string
	// Path is the PATH the availability probe searches; see Options.Path.
	Path string
}

BuildOptions is what instantiating an adapter needs beyond the entry. The model is absent on purpose: it rides along at call time.

type ClaudeCLI

type ClaudeCLI struct{}

ClaudeCLI is the local `claude` CLI, run headless with -p.

`claude -p --output-format text` streams the assistant's text the same way whether or not a transcript is wanted, so the `stream` hint is a no-op here — it only matters for harnesses with distinct one-shot and transcript modes (see Hermes).

func (ClaudeCLI) Argv

func (ClaudeCLI) Argv(binary, system, prompt, model string, _ bool) []string

func (ClaudeCLI) DefaultBinary

func (ClaudeCLI) DefaultBinary() string

func (ClaudeCLI) Reachable

func (ClaudeCLI) Reachable() bool

Reachable: nothing beyond the PATH probe. An installed `claude` is a usable `claude`; it reaches its model over the network on its own.

type Config

type Config struct {
	Provider  string
	Model     string
	Providers map[string]Settings
}

Config is the LLM half of the same flat `key = value` file the task paths use (~/.config/tasks/config). Every key is optional and unknown keys are ignored — forward-compatible, so old configs keep working and a headless CLI that never touches the LLM pays nothing. Recognised keys:

llm_provider = hermes                 default harness for `-p` and the TUI
llm_model    = gemma4:e4b             default model within that provider
<provider>_models  = a, b, c          override a provider's model list
<provider>_command = /path/to/binary  override the binary a provider spawns
hermes_provider = ollama-launch       Hermes inference provider (--provider)
ollama_url  = http://127.0.0.1:11434  endpoint for Hermes' availability probe

`<provider>` is any registry key, e.g. `claude-cli_models`, `hermes_models`, or `cursor-cli_models`.

func LoadConfig

func LoadConfig(env determinism.Env, path string) Config

LoadConfig reads the config file. `path` empty resolves it the way every other surface does, through internal/config, so the LLM settings can never end up reading a different file than the task paths did.

func (Config) ProviderSettings

func (c Config) ProviderSettings(name string) Settings

ProviderSettings is the overrides for one provider, or the zero value.

type CursorCLI

type CursorCLI struct{}

CursorCLI is Cursor's local `agent` CLI, run headlessly in print mode. The CLI has no system-prompt flag, so the shared TASK_AGENT.md context is prepended to the user's request, as it is for Hermes.

Text output contains the final assistant message rather than structured tool progress, so both the TUI and the synchronous CLI use the same invocation.

Verified against Cursor Agent 2026.07.09-a3815c0. This is an external CLI contract, not a stable API — re-check `agent --help` when upgrading.

func (CursorCLI) Argv

func (CursorCLI) Argv(binary, system, prompt, model string, _ bool) []string

func (CursorCLI) DefaultBinary

func (CursorCLI) DefaultBinary() string

func (CursorCLI) Reachable

func (CursorCLI) Reachable() bool

type Entry

type Entry struct {
	Provider string
	Model    string
}

Entry is a single (provider, model) choice — what the TUI switcher cycles and what the CLI resolves a default for. Because every backend is an agent, there is no kind/transport branch here: an Entry only names which harness and model.

func DefaultEntry

func DefaultEntry(provider, model string, conf Config) (Entry, error)

DefaultEntry is the starting (provider, model).

Explicit arguments (a CLI --provider/--model) win, then config, then the first registered provider and its first model. A model given explicitly is honoured even when it is not in the provider's list, so a user can run any model their harness supports without editing config.

config.Model only applies when the provider was NOT explicitly overridden: it is paired with config.Provider, so `--provider hermes` alone resolves to hermes's own default model rather than to a claude tier left in config.

func Entries

func Entries(conf Config) []Entry

Entries is the flat, ordered (provider, model) list for the switcher. The resolved default is moved to the front so cycling starts there — out of the box that is claude-cli:sonnet, so nothing changes for current users.

func (Entry) String

func (e Entry) String() string

func (Entry) UILabel

func (e Entry) UILabel() string

UILabel is the short spelling a switcher shows. It never becomes the canonical identity: an unknown provider or model passes through verbatim, so a harness added tomorrow is displayable today.

type Harness

type Harness interface {
	// DefaultBinary is the executable this adapter spawns unless config points
	// at another install.
	DefaultBinary() string
	// Argv builds the command line for one run. `system` is the fully resolved
	// system context, or "" when there is none; adapters inject it however their
	// CLI allows. `stream` true means "emit a live transcript including tool
	// activity" (the TUI); false means "final answer only" (the sync CLI).
	Argv(binary, system, prompt, model string, stream bool) []string
	// Reachable is any probe BEYOND "the binary is on PATH" — Hermes pings its
	// model endpoint. An adapter with nothing further to check returns true.
	// Never returns an error: a dead backend is unavailable, not a crash.
	Reachable() bool
}

Harness is the per-backend half of the contract, and the only thing an adapter implements. Everything else — spawning, availability, cancellation, output capture — is Agent's and is identical for every provider, which is what keeps provider-specific branching out of every call site.

type Hermes

type Hermes struct {
	// OllamaURL is the endpoint the availability probe pings.
	OllamaURL string
	// InferenceProvider is Hermes' `--provider`. Empty omits the flag, which
	// falls back to Hermes' own default provider.
	InferenceProvider string
}

The Hermes agent (Nous Research) — an agentic CLI installed locally. It runs tools and edits files autonomously, so it fits the Agent contract as just another spawn: a different binary and flags, the same protocol.

Hermes reads its model and endpoint from ~/.hermes/config.yaml. We pass -m and --provider per invocation so the selected model wins without mutating the user's global Hermes config. Point it at a local Ollama model via Hermes' own config (an "ollama-launch"/custom provider whose base_url is http://127.0.0.1:11434/v1); this adapter only names the model and provider.

Verified against Hermes v0.17.0 (2026-06). The CLI is an external contract, not a stable API — re-check `hermes --help` when upgrading. Notably:

-z / --oneshot PROMPT     one-shot, prints ONLY the final answer (sync CLI)
chat -q / --query PROMPT  single non-interactive query, streams the
                          transcript including tool previews (TUI); add -Q
                          to silence it, which we deliberately do NOT.
-m / --model, --provider  model and inference-provider overrides
--yolo                    bypass approval prompts — required headless, the
                          analogue of claude's --dangerously-skip-permissions
--accept-hooks            auto-approve config.yaml shell hooks (no TTY)

func NewHermes

func NewHermes(ollamaURL string, inferenceProvider *string) Hermes

NewHermes applies the two defaults. A nil inferenceProvider means "unset", and takes the conventional name; a non-nil empty string means "deliberately none", and drops the --provider flag.

func (Hermes) Argv

func (h Hermes) Argv(binary, system, prompt, model string, stream bool) []string

Argv: Hermes has no --append-system-prompt, so the context (TASK_AGENT.md plus the file locations) is prepended to the prompt text. Hermes may also auto-inject any AGENTS.md it finds in cwd; the data directory should not carry one — our injected copy is authoritative about the contract and the absolute file locations.

func (Hermes) DefaultBinary

func (Hermes) DefaultBinary() string

func (Hermes) Reachable

func (h Hermes) Reachable() bool

Reachable pings the model endpoint: an installed Hermes pointed at a dead Ollama is still a dead end, so it surfaces as unavailable rather than as a run that fails after the user has waited for it.

Short timeouts, because this runs synchronously from a submit path — a dead endpoint must fail fast rather than stall the event loop. /api/tags answers instantly when Ollama is up; it only lists local models.

type Options

type Options struct {
	// Root is the working directory the harness runs in — where tasks.jsonl
	// lives, not where this binary lives.
	Root string
	// System is the resolved system-context string (TASK_AGENT.md + the file
	// locations + task-set memory), or "" for none.
	System string
	// Binary overrides the harness's default executable.
	Binary string
	// Path is the PATH the availability probe searches. It is passed in rather
	// than read from the process, because this layer must honour whatever
	// environment the adapter boundary resolved. Empty means "nothing is on
	// PATH", which is Ruby's ENV.fetch("PATH", "") exactly.
	Path string

	// OllamaURL and InferenceProvider are Hermes' settings; other adapters
	// ignore them. InferenceProvider is a pointer so that "set to empty" (drop
	// the --provider flag) is expressible and distinct from "unset" (use the
	// conventional local-Ollama provider name).
	OllamaURL         string
	InferenceProvider *string
}

Options are what constructing an adapter needs. The model is not here: it rides along at call time, because one constructed agent can serve several models.

type Registry

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

Registry is the provider table in DECLARATION order. Order is contract, not convenience: `reg.keys.first` is the overall default provider, the switcher cycles in this order, and the unknown-provider refusal lists the known names in it. A Go map would permute all three between runs.

func BuildRegistry

func BuildRegistry(conf Config) Registry

BuildRegistry overlays the user's config onto the built-in defaults.

func (Registry) Get

func (r Registry) Get(name string) (Spec, bool)

func (Registry) Has

func (r Registry) Has(name string) bool

func (Registry) Keys

func (r Registry) Keys() []string

type Settings

type Settings struct {
	Models  []string
	Command string
	// InferenceProvider is a pointer because "unset" and "set to empty" are
	// different answers: unset takes Hermes' conventional local-Ollama provider,
	// and empty deliberately drops the --provider flag.
	InferenceProvider *string
	OllamaURL         string
}

Settings are one provider's overrides. They become the adapter's constructor arguments, which is what lets config tune a harness without any code change — the growth path as the harness/model landscape shifts.

type Spec

type Spec struct {
	Provider  string
	Models    []string
	Transport string
	Settings  Settings
	// contains filtered or unexported fields
}

Spec maps a provider name to its adapter and model list, assembled from the built-in defaults overlaid with the user's config.

Transport is informational (for optional-dependency handling), never a call-site branch.

Jump to

Keyboard shortcuts

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