agent

package
v0.25.1 Latest Latest
Warning

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

Go to latest
Published: Aug 28, 2026 License: MIT Imports: 47 Imported by: 0

Documentation

Overview

Package agent wires the provider, core, tools, auth, and modes into a CLI.

Index

Constants

View Source
const OnDemandSubagentsSystemAddendum = `` /* 1364-byte string literal not displayed */

OnDemandSubagentsSystemAddendum keeps the canonical subagent tools available without enabling proactive delegation.

View Source
const ProactiveSubagentsDelegationUnavailableAddendum = `` /* 192-byte string literal not displayed */
View Source
const ProactiveSubagentsSystemAddendum = `` /* 1350-byte string literal not displayed */

ProactiveSubagentsSystemAddendum keeps the interactive primary agent on the critical path and reserves delegation for genuinely parallel sidecar work.

View Source
const StrictOrchestratorDelegationUnavailableAddendum = `` /* 389-byte string literal not displayed */
View Source
const StrictOrchestratorSystemAddendum = `` /* 1005-byte string literal not displayed */

StrictOrchestratorSystemAddendum is used only by explicit headless orchestration. The parent coordinates workers and never becomes an implementer itself.

Variables

This section is empty.

Functions

func AuthPath

func AuthPath() string

AuthPath returns the path to auth.json.

func AuthStoreFor

func AuthStoreFor() *auth.Store

AuthStoreFor returns the auth.Store backed by AuthPath().

func AutoSubagentsEnabled

func AutoSubagentsEnabled() bool

AutoSubagentsEnabled reads whether the interactive primary agent may delegate proactively. The canonical subagent tools remain available for user-requested delegation and skill-mandated workflows when disabled.

func BuildSystemPrompt

func BuildSystemPrompt(o SystemPromptOpts) string

BuildSystemPrompt constructs the system prompt.

Design note: kept intentionally small. Every byte here is part of the cached prefix on every request, so bloat is cumulatively expensive. We ship only:

  • A one-paragraph identity (who zut is, what the name means, what the TUI expects for output format).
  • Compact handoff and writing-quality guidance that must survive custom identities and appended context.
  • The date + cwd footer so the model has current-context.

Everything else (tool listing, operating guidelines, "don't run sudo", "prefer edit over write", etc.) is left out because the current-generation frontier models already internalise it, and the tool schemas sent alongside the request carry each tool's own description.

Users who want extra biasing can use --system-prompt (replace), --append-system-prompt (additive, repeatable), or drop a SYSTEM.md in $ZUT_HOME that overrides the default identity.

func CheckForUpdateAsync

func CheckForUpdateAsync(zutHome, currentVersion string) <-chan UpdateInfo

CheckForUpdateAsync runs CheckForUpdate in a goroutine, delivers the result to the returned channel, and never blocks startup. The channel is always closed; receivers should `ok`-check.

func ConfigPath

func ConfigPath() string

ConfigPath returns the path to config.json.

func CredentialAvailable

func CredentialAvailable(provider string) bool

CredentialAvailable reports whether a provider has a configured credential without executing an api_key_command.

func FetchChangelogAsync

func FetchChangelogAsync(version string) <-chan ChangelogInfo

FetchChangelogAsync runs FetchChangelog on a goroutine and delivers the result on the returned channel. Channel always closes.

func KimiCLIFallbackDisabledPath

func KimiCLIFallbackDisabledPath() string

KimiCLIFallbackDisabledPath returns a sentinel that disables falling back to the official Kimi Code CLI token after `zut /logout kimi`.

func LoadCachedModels

func LoadCachedModels()

LoadCachedModels loads the cache file and applies it to the provider package so FindModel / ModelsForProvider see live ids immediately. Safe to call before any credentials are known.

func LoadUserModels

func LoadUserModels()

LoadUserModels reads $ZUT_HOME/models.json and merges any user-defined models into the active catalog. User models take highest precedence. Any validation issues (bad provider id, empty model id, malformed JSON, negative widths) are surfaced as one warning per line on stderr; the well-formed entries from the rest of the file are still loaded.

func LogsPath

func LogsPath() string

LogsPath returns the directory holding log files.

func MarkChangelogShown

func MarkChangelogShown(version string) error

MarkChangelogShown persists the version whose changelog the user just dismissed. Idempotent; safe to call when the dialog wasn't actually shown (e.g. fetch failed) so we don't keep retrying.

func ModelCachePath

func ModelCachePath() string

ModelCachePath returns the on-disk location of the merged model cache.

func PonytailSystemAddendum

func PonytailSystemAddendum() string

PonytailSystemAddendum returns the compact coding-guidance block included in resolved system prompts when Ponytail mode is enabled.

func PrintHelp

func PrintHelp(version string)

PrintHelp writes the help text to stderr. When stderr is a TTY it uses the same palette as zut's TUI; when redirected it falls back to plain text with no ANSI escapes.

func ProactiveSubagentsSystemAddendumFor added in v0.25.0

func ProactiveSubagentsSystemAddendumFor(spawnToolAllowed, stopToolAllowed, resumeToolAllowed bool) string

ProactiveSubagentsSystemAddendumFor returns the interactive collaboration contract with guidance only for manager actions exposed at launch time.

func RefreshLlamaCPPModels

func RefreshLlamaCPPModels(ctx context.Context) error

RefreshLlamaCPPModels adds the router's currently loaded models to the active catalog. Unloaded models remain in the management UI and cannot be selected for inference until they are loaded.

func RefreshModelsAsync

func RefreshModelsAsync()

RefreshModelsAsync kicks a background discovery for every provider we have credentials for. Refreshed results are merged into the active catalog and persisted to the on-disk cache.

Silent on error: discovery is a nice-to-have. Callers can still use the baked-in catalog if this fails.

func ResolveCredential

func ResolveCredential(provider, explicit string) (cred, method string, err error)

ResolveCredential returns the credential (api key or oauth access token), the method ("apikey"/"oauth"), and an error when no credential is available.

Lookup order:

  1. explicit (e.g. --api-key): treated as API key
  2. provider-specific env var: treated as API key
  3. auth.json: api key OR oauth, whichever is present

func ResolveCredentialContext

func ResolveCredentialContext(ctx context.Context, provider, explicit string) (cred, method string, err error)

ResolveCredentialContext is ResolveCredential with caller cancellation.

func ResolveCredentialFull

func ResolveCredentialFull(provider, explicit string) (cred, method, accountID string, err error)

ResolveCredentialFull is like ResolveCredential but also returns a provider-specific accountID when the credential is an OpenAI OAuth token (the ChatGPT account id extracted from the stored id_token). accountID is "" for API-key auth and for anthropic.

func ResolveCredentialFullContext

func ResolveCredentialFullContext(ctx context.Context, provider, explicit string) (cred, method, accountID string, err error)

ResolveCredentialFullContext is ResolveCredentialFull with caller cancellation.

func ResolveLlamaCPPConfig

func ResolveLlamaCPPConfig() (baseURL, apiKey string, err error)

ResolveLlamaCPPConfig resolves the router URL and optional API key. The environment overrides the credential stored through /login.

func Run

func Run(rawArgs []string, version string) error

Run is the top-level entrypoint for the zut binary.

func SaveConfig

func SaveConfig(c Config) error

SaveConfig writes the config file, creating parent dirs.

func SeedChangelogVersion

func SeedChangelogVersion(version string)

SeedChangelogVersion sets LastChangelogShown if it's currently empty. Called once on first-ever launch so future upgrades correctly trigger the dialog while THIS launch (which is also "first-ever") doesn't.

func SessionsPath

func SessionsPath() string

SessionsPath returns the directory holding session files.

func SetKimiCLIFallbackDisabled

func SetKimiCLIFallbackDisabled(disabled bool) error

func ShouldShowChangelog

func ShouldShowChangelog(currentVersion string, cfg Config) bool

ShouldShowChangelog reports whether the running binary version differs from the last version whose changelog the user dismissed. Returns false on development builds and on the first-ever launch (no LastChangelogShown stored — we don't dump release notes at someone who just installed).

func StrictOrchestratorSystemAddendumFor added in v0.25.0

func StrictOrchestratorSystemAddendumFor(spawnToolAllowed, stopToolAllowed, resumeToolAllowed bool) string

StrictOrchestratorSystemAddendumFor returns the headless manager-only contract with guidance only for manager actions exposed at launch time.

func UserModelsPath

func UserModelsPath() string

UserModelsPath returns the path to the user's models.json override.

func ValidateAndRepairConfig

func ValidateAndRepairConfig()

ValidateAndRepairConfig checks the persisted config.json's (Provider, Model) pair against the active catalog and repairs any mismatch in-place (and on disk) before any UI renders. Three failure modes are handled:

  • cfg.Provider is empty or unknown -> reset to "anthropic".
  • cfg.Model is empty -> set to the provider's default.
  • cfg.Model belongs to a different provider than cfg.Provider (e.g. provider=anthropic + model=kimi-for-coding from a stale half-applied switch) -> reset model to the provider's default.

Gateway providers are exempt from the cross-provider model check for routed model IDs because those IDs can be valid even when absent from zut's catalog.

Silent on success; one stderr line per repair. Errors loading or saving the file are non-fatal — the caller continues with defaults.

func WriteNewTranscript

func WriteNewTranscript(ag *core.Agent, sess *core.Session, from int) error

WriteNewTranscript appends only messages after index `from` from the agent's transcript to the session. Used by callers that don't hold the persistMu (non-interactive print/json modes which run a single turn under their own goroutine).

func WritingGuidance added in v0.16.0

func WritingGuidance() string

WritingGuidance returns the universal policy kept at the end of resolved prompt context, including after interactive prompt updates.

func ZutHome

func ZutHome() string

ZutHome returns $ZUT_HOME or the OS-default data dir.

All zut state (config.json, auth.json, sessions/, logs/) lives under this directory.

Types

type Args

type Args struct {
	Mode        Mode
	Orchestrate bool
	// ResidentChild marks internal child resolution so primary-only delegation
	// policies and profile metadata are not added to worker prompts.
	ResidentChild bool
	Provider      string
	Model         string
	APIKey        string

	BaseURL            string // override provider base URL (for tests/self-hosted)
	SystemPrompt       string
	AppendSystemPrompt []string
	Reasoning          string
	Temperature        *float32

	// FastMode is an internal resident-child propagation value.
	FastMode bool
	// FastModeSet distinguishes the durable child override from host config.
	FastModeSet bool

	Continue        bool
	Resume          bool
	ResumeSessionID string
	Session         string
	NoSess          bool

	CWD     string
	NoTools bool
	NoLSP   bool
	Tools   []string
	// ToolsSet distinguishes an omitted --tools flag from an explicitly
	// supplied empty list. Other built-in tools intentionally retain their
	// historical empty-list behavior; web search uses this provenance as a
	// capability allowlist.
	ToolsSet bool

	// WebSearchPolicy is an internal capability override. CLI users leave it
	// at Inherit; host runtimes and SDK callers set it explicitly.
	WebSearchPolicy subagents.WebSearchPolicy
	MaxSteps        int

	// Exts is a list of directory paths the user passed via --ext.
	// Each must contain an extension.json. Loaded for one session
	// only; never persisted. Take precedence over installed exts of
	// the same name.
	Exts []string

	// NoExt disables extension discovery + spawn entirely for this
	// run. --ext PATH still works (explicit beats implicit) so you
	// can run "with only this one extension" via --no-ext --ext PATH.
	NoExt bool

	// NoSkill disables ALL skill discovery for this run, including
	// the built-in skills compiled into the binary. The system
	// prompt loses its "Available skills" manifest and the `skill`
	// tool isn't registered. Useful for running zut without any
	// extra context biasing the model.
	NoSkill bool

	// WithSkills controls loading user-installed skills from
	// $ZUT_HOME/skills/, .zut/skills/, .claude/skills/, and
	// .agents/skills/. It defaults to true; --no-skill disables all
	// skill discovery, including built-ins.
	WithSkills bool

	// NoContextFiles disables discovery and loading of AGENTS.md files
	// from $ZUT_HOME and the cwd's ancestor directories.
	NoContextFiles bool

	// InsecureTLS skips TLS verification for custom inference endpoints.
	InsecureTLS bool

	// NoYolo turns on per-tool confirmation. Before each tool
	// invocation the TUI prompts the user with the tool name + args
	// and waits for an explicit yes/no. The user can also pick
	// "always for this tool this session" or "always for anything
	// this session" to stop being prompted again. Defaults off
	// (yolo mode): tools run without asking.
	//
	// No effect in -p / --json / rpc modes, which have no
	// interactive prompt. A warning is printed to stderr on startup
	// so scripts know the flag is ignored, but tools still run
	// freely so automated workflows keep working.
	NoYolo bool

	// Yes accepts zutfile launch consent without an interactive
	// Allow? prompt (zut run -y / --yes). Durable consent receipts
	// are still written for modes other than bash ask.
	Yes bool

	ListModels bool
	Help       bool
	Version    bool
	StatsPath  string // write print-mode generation statistics as JSON

	Prompt string // concatenated positional args

	// StartupPre is an optional zutfile entry.pre value. Interactive
	// mode auto-submits it once at startup before InitialInput handling.
	StartupPre string

	// AgentName/AgentDataDir/PermissionSet are populated by `zut run`
	// for local zutfile agents. They scope sessions and enforce the
	// manifest's declared file/bash permissions.
	AgentName     string
	AgentDataDir  string
	PermissionSet *tools.PermissionSet
}

Args holds parsed command-line options.

func ParseArgs

func ParseArgs(in []string) (Args, error)

ParseArgs parses the process arguments (excluding argv[0]).

type ChangelogInfo

type ChangelogInfo struct {
	Version string
	Body    string
	URL     string
}

ChangelogInfo is what FetchChangelog returns. Body is the markdown from the GitHub release page; URL points back to that page so the dialog can offer "open in browser".

func FetchChangelog

func FetchChangelog(ctx context.Context, version string) (ChangelogInfo, error)

type Config

type Config struct {
	Provider    string   `json:"provider"`
	Model       string   `json:"model"`
	Reasoning   string   `json:"reasoning"`
	Temperature *float32 `json:"temperature,omitempty"`
	Theme       string   `json:"theme"`

	// FastMode requests OpenAI's fast service tier. Off by default;
	// nil/missing means disabled. Other providers reject fast-mode
	// requests at the provider boundary.
	FastMode *bool `json:"fast_mode,omitempty"`

	// ToolRender selects how tool calls are drawn in interactive mode.
	// "box" (default, or empty) wraps each call in a bordered panel;
	// "flat" drops the frame for a quiet header line plus indented,
	// frameless output. The ZUT_FLAT_TOOLS env var overrides this when
	// set ("1"/"true" forces flat, "0"/"false" forces box).
	ToolRender string `json:"tool_render,omitempty"`

	// CompactInput renders sent user messages as a single quiet gutter
	// line instead of a padded, background-tinted bubble. nil/false
	// (the default) keeps the bubble. The ZUT_COMPACT_INPUT env var
	// overrides this when set.
	CompactInput *bool `json:"compact_input,omitempty"`

	// QuickModelShortcuts maps slots 1-9 to provider/model pairs used by
	// Ctrl+1..9. Cmd+1..9 may also work on terminals that forward Super.
	QuickModelShortcuts []QuickModelShortcut `json:"quick_model_shortcuts,omitempty"`

	// InlineImagesEnabled controls whether zut draws screenshots inline
	// when the terminal supports an image protocol. nil/missing means
	// auto (enabled when supported); false disables; true forces the
	// detected protocol when available.
	InlineImagesEnabled *bool `json:"inline_images_enabled,omitempty"`

	// TerminalAlertsEnabled controls interactive terminal alerts from the
	// main agent and extensions. nil/missing means enabled; false disables
	// alerts. Toggle from /settings.
	TerminalAlertsEnabled *bool `json:"terminal_alerts_enabled,omitempty"`

	// TerminalTitleEnabled controls the hidden title request and OSC 0 title
	// updates in interactive mode. nil/missing means enabled; false disables
	// both so no extra provider request is made. Toggle from /settings.
	TerminalTitleEnabled *bool `json:"terminal_title_enabled,omitempty"`

	// Subagents controls manager-owned child lifecycle and resource policy.
	Subagents SubagentsConfig `json:"subagents,omitempty"`

	// Goals configures optional resource limits for autonomous goals. Missing
	// configuration preserves unlimited autonomous execution.
	Goals GoalsConfig `json:"goals,omitempty"`

	// AutoSubagentsEnabled lets the interactive primary proactively delegate
	// independent sidecar work through built-in subagent tools. Off by default;
	// nil/missing means disabled. Toggle from /settings.
	AutoSubagentsEnabled *bool `json:"auto_subagents_enabled,omitempty"`

	// PonytailEnabled controls the compact coding-guidance addendum. On by
	// default; nil/missing means enabled. Toggle from /settings.
	PonytailEnabled *bool `json:"ponytail_enabled,omitempty"`

	// WebSearchEnabled controls the built-in web_search capability for
	// normal CLI sessions. nil/missing means enabled so existing config
	// files retain the default-on behavior.
	WebSearchEnabled *bool `json:"web_search_enabled,omitempty"`

	// LSPEnabled controls the built-in lsp tool and write-time diagnostics
	// for the main session. nil/missing means enabled. Toggle from
	// /settings.
	LSPEnabled *bool `json:"lsp_enabled,omitempty"`

	// SubagentLSPEnabled controls LSP availability in resident child agents.
	// nil/missing means enabled. Toggle from /settings.
	SubagentLSPEnabled *bool `json:"subagent_lsp_enabled,omitempty"`

	// LSPDiagnosticsOnWrite enables bounded diagnostics after a successful
	// write. nil/missing means enabled when LSP itself is enabled.
	LSPDiagnosticsOnWrite *bool `json:"lsp_diagnostics_on_write,omitempty"`

	// LSPDiagnosticsOnEdit enables bounded diagnostics after a successful
	// edit. nil/missing means disabled to keep multi-edit sequences quiet.
	LSPDiagnosticsOnEdit *bool `json:"lsp_diagnostics_on_edit,omitempty"`

	// AutoCompactThreshold is the percentage of the model context window
	// that triggers automatic transcript compaction in interactive mode.
	// nil/missing means 85; valid values are 0, 70, 80, 85, 90, or 95.
	// zero disables percentage-based triggers.
	AutoCompactThreshold *int `json:"auto_compact_threshold,omitempty"`

	// JailByDefault confines tools to the session working directory when
	// a new agent starts. Off by default; nil/missing means disabled.
	// The live session can still override this with /jail or /unjail.
	JailByDefault *bool `json:"jail_by_default,omitempty"`

	// RecursiveFileSuggest controls the @-mention file picker. When true
	// the picker fuzzy-searches the whole project tree below the working
	// directory; nil/missing/false keeps the default directory-by-
	// directory browse. Toggle from /settings.
	RecursiveFileSuggest *bool `json:"recursive_file_suggest,omitempty"`

	// RespectGitignore controls whether the @-mention file picker hides
	// files and directories matched by the project's root .gitignore (in
	// both flat and recursive modes). nil/missing means the default,
	// which is on; false shows ignored entries. Toggle from /settings.
	RespectGitignore *bool `json:"respect_gitignore,omitempty"`

	// CompactMode renders the interactive transcript with less chrome:
	// tool calls use flat headers instead of bordered panels, and sent
	// user messages render without padded background bubbles. Off by
	// default; nil/missing means disabled. Toggle from /settings.
	CompactMode *bool `json:"compact_mode,omitempty"`

	// ShowInstructionsAtStartup lists loaded context files, extensions,
	// and user-installed skills above the transcript. Off by default;
	// nil/missing means disabled. Toggle from /settings.
	ShowInstructionsAtStartup *bool `json:"show_instructions_at_startup,omitempty"`

	// TUIInputStyle controls the main input rendering. Supported values:
	// "plain" (default), "lines", and "block".
	TUIInputStyle string `json:"tui_input_style,omitempty"`

	// TUIStatusPosition controls whether model, usage, and cwd information
	// render above or below the main input. Supported values: "above_input"
	// (default) and "below_input".
	TUIStatusPosition string `json:"tui_status_position,omitempty"`

	// TUIWorkingPosition controls whether the busy/working spinner renders
	// above or below the main input. Supported values: "above_input"
	// (default) and "below_input".
	TUIWorkingPosition string `json:"tui_working_position,omitempty"`

	// Insecure skips TLS verification for custom inference endpoints.
	Insecure bool `json:"insecure,omitempty"`

	// HTTPProxy is a global proxy URL used for HTTP and HTTPS requests when
	// the corresponding standard proxy environment variable is not already set.
	HTTPProxy string `json:"http_proxy,omitempty"`

	// LastChangelogShown is the version whose release-notes
	// dialog the user has already seen. When the running binary's
	// version differs, the next interactive run shows the
	// changelog (fetched from the GitHub release page) once and
	// updates this field. Empty means "never shown".
	LastChangelogShown string `json:"last_changelog_shown,omitempty"`
}

Config is the persisted user configuration.

func LoadConfig

func LoadConfig() (Config, error)

LoadConfig reads the config file, returning defaults if missing.

func (Config) CompactUserInput

func (c Config) CompactUserInput() bool

CompactUserInput reports whether sent user messages should render as a single quiet gutter line instead of a padded, background-tinted bubble. The ZUT_COMPACT_INPUT env var takes precedence over the config when set: "1"/"true"/"yes"/"on" force compact, "0"/"false"/ "no"/"off" force the bubble. Otherwise the config's compact_input is consulted (nil/false means the bubble).

func (Config) FlatToolRender

func (c Config) FlatToolRender() bool

FlatToolRender reports whether tool calls should render flat (no bordered panel). The ZUT_FLAT_TOOLS env var takes precedence over the config when set: "1"/"true"/"yes"/"on" force flat, "0"/"false"/ "no"/"off" force box. Otherwise the config's tool_render is consulted; "flat" is flat, anything else (including empty) is box.

func (Config) LSPDiagnosticsOnEditEnabled

func (c Config) LSPDiagnosticsOnEditEnabled(subagent bool) bool

LSPDiagnosticsOnEditEnabled reports the default-off edit diagnostics preference without requiring a generated config entry.

func (Config) LSPDiagnosticsOnWriteEnabled

func (c Config) LSPDiagnosticsOnWriteEnabled(subagent bool) bool

LSPDiagnosticsOnWriteEnabled reports the default-on write diagnostics preference without requiring a generated config entry.

func (Config) LSPEnabledFor

func (c Config) LSPEnabledFor(subagent bool) bool

LSPEnabledFor reports whether LSP is enabled for a main or subagent sub-agent session. Both settings default to true so new installations get code intelligence without a migration or generated config file.

func (Config) PonytailModeEnabled

func (c Config) PonytailModeEnabled() bool

PonytailModeEnabled reports the default-on coding-guidance preference without requiring a generated config entry.

func (Config) WebSearchEnabledForCLI added in v0.6.0

func (c Config) WebSearchEnabledForCLI() bool

WebSearchEnabledForCLI reports the default-on web-search preference without requiring a generated config entry.

type ContextFile

type ContextFile struct {
	Path    string
	Content string
}

ContextFile is an instruction file loaded into the system prompt.

type ExtensionSkillSource

type ExtensionSkillSource interface {
	Skills() []*skills.Skill
}

ExtensionSkillSource exposes the optional bundled-skill surface without forcing older ExtensionToolSource implementations to add it.

type ExtensionToolInfo

type ExtensionToolInfo struct {
	Extension   string
	Name        string
	Description string
	Schema      []byte
	Deferred    bool
}

ExtensionToolInfo mirrors extensions.ToolInfo so we can declare ExtensionToolSource here without importing the extensions package. The cli wires a tiny adapter to bridge them.

type ExtensionToolSource

type ExtensionToolSource interface {
	Tools() []ExtensionToolInfo
	NewExtensionTool(info ExtensionToolInfo) core.Tool
}

ExtensionToolSource is the slice of the extension manager that MergeExtensionTools needs. Lives here as an interface so the build package doesn't import packages/agent/extensions (which imports core, which imports... avoid the cycle).

type GoalsConfig added in v0.18.0

type GoalsConfig struct {
	MaxTokenBudget *uint64 `json:"max_token_budget,omitempty"`
}

GoalsConfig controls optional resource limits for autonomous goals. A nil MaxTokenBudget leaves goals unlimited; when set, it is the host-configured cap applied to newly created goals.

type Mode

type Mode string

Mode is the CLI run mode.

const (
	ModeInteractive Mode = "interactive"
	ModePrint       Mode = "print"
	ModeStream      Mode = "stream"
	ModeJSON        Mode = "json"
	ModeRPC         Mode = "rpc"
)

type QuickModelShortcut

type QuickModelShortcut struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
}

QuickModelShortcut is one configured keyboard shortcut slot.

type Resolved

type Resolved struct {
	Provider        string
	Model           string
	Credential      string // api key or oauth access token
	AuthMethod      string // "apikey" | "oauth" | "" (no credential yet)
	AccountID       string // ChatGPT account id (for openai oauth), "" otherwise
	BaseURL         string
	InsecureTLS     bool
	CWD             string
	Reasoning       string
	Temperature     *float32
	FastMode        bool
	WebSearchPolicy subagents.WebSearchPolicy

	ToolRegistry core.Registry
	ToolSummary  []ToolSummary
	SystemPrompt string
	MaxSteps     int
	Sandbox      *tools.Sandbox

	// ContextWindow and MaxOutput retain the effective model metadata,
	// including metadata synthesized for valid open-catalog local and routed
	// models that provider.FindModel cannot rediscover later.
	ContextWindow int

	// MaxOutput is the resolved model's maximum output-token budget
	// (from the catalog). Passed to the agent so each turn requests
	// the model's full output capacity instead of the provider's
	// conservative default (e.g. Bedrock's 4096, which truncates
	// long writes/edits with stopReason=length).
	MaxOutput int

	// SkillTool is the on-demand skill loader registered with the
	// agent's tool registry, or nil if no SKILL.md files were
	// discovered. Exposed so the tui can list / preview skills.
	SkillTool *skills.Tool

	// ContextFiles records the AGENTS.md files appended to SystemPrompt,
	// in effective load order. Interactive mode uses this metadata to make
	// otherwise invisible startup context inspectable without adding fake
	// messages to the provider transcript.
	ContextFiles []ContextFile
	// contains filtered or unexported fields
}

Resolved is the effective configuration after merging CLI, config, defaults.

func Resolve

func Resolve(args Args, requireCred bool) (Resolved, error)

Resolve merges args, config, and env into a Resolved set.

Unlike the earlier version, Resolve NEVER returns an error for missing credentials: the TUI can start without them and launch a login flow. requireCred controls whether missing credentials are a hard error (used by print/json modes).

func (Resolved) HasCredential

func (r Resolved) HasCredential() bool

HasCredential reports whether a credential was resolved.

func (*Resolved) MergeExtensionTools

func (r *Resolved) MergeExtensionTools(mgr ExtensionToolSource)

MergeExtensionTools folds every tool registered by an extension into r's ToolRegistry and re-renders the system prompt's tool summary so the model sees both built-in and extension tools.

Idempotent: calling twice with the same manager state has no effect on the second pass (existing names are preserved). Built-in tools always win on conflict.

func (Resolved) NewAgent

func (r Resolved) NewAgent() *core.Agent

NewAgent constructs a core.Agent from r. Requires a credential.

func (Resolved) NewClient

func (r Resolved) NewClient() provider.Client

NewClient returns a provider.Client for r, choosing the auth mode based on r.AuthMethod. Panics if no credential is present; callers must check HasCredential() first.

func (*Resolved) UseSandbox

func (r *Resolved) UseSandbox(s *tools.Sandbox)

UseSandbox replaces the sandbox pointer that every tool in r's registry references. Used to keep the /jail state stable across agent rebuilds (e.g. /login, /model switching providers).

type SubagentsConfig

type SubagentsConfig struct {
	MaxConcurrent int      `json:"max_concurrent,omitempty"`
	QueueTimeout  string   `json:"queue_timeout,omitempty"`
	AllowedTools  []string `json:"allowed_tools,omitempty"`
	AllowedRoots  []string `json:"allowed_roots,omitempty"`
}

SubagentsConfig contains the resident manager policy. max_concurrent limits simultaneous turns, queue_timeout bounds admission waits, allowed_tools limits child capabilities, and allowed_roots limits eligible workspaces. Obsolete keys such as tui_subagent_position are ignored.

type SystemPromptOpts

type SystemPromptOpts struct {
	CWD        string
	Tools      []ToolSummary
	Custom     string   // if set, replaces the built-in identity and docs guidance
	Append     []string // extra text appended at the end
	Now        time.Time
	ZutDocsDir string
}

SystemPromptOpts configures BuildSystemPrompt.

type ToolSummary

type ToolSummary struct {
	Name        string
	Description string
}

ToolSummary is a name+one-line description. Kept as part of the public opts type for backwards compatibility with callers that still pass tool summaries in; the default prompt no longer lists them because the provider already advertises tools in the request body's tools[] array, so listing them again in prose is pure duplication.

type UpdateInfo

type UpdateInfo struct {
	Current   string // e.g. "0.0.4"
	Latest    string // e.g. "0.0.5"
	Available bool   // true when latest > current
	URL       string // release page url for the changelog link
}

UpdateInfo describes the result of an update check. Zero-value means "no update available, no error, don't show anything".

func CheckForUpdate

func CheckForUpdate(ctx context.Context, zutHome, currentVersion string) UpdateInfo

CheckForUpdate returns info about a newer release, using a cached result when one is fresh enough. Designed to be called at tui startup and rendered as a dismissible banner.

Always returns a usable UpdateInfo (zero-value on error). The banner renderer skips the display when Available is false, so a network failure silently no-ops; we never block startup on this.

type ZutfileManifest

type ZutfileManifest struct {
	Zutfile     int    `json:"zutfile"`
	Name        string `json:"name"`
	Version     string `json:"version"`
	Description string `json:"description"`
	License     string `json:"license"`
	Runtime     struct {
		MinZut string `json:"min_zut"`
	} `json:"runtime"`
	Model struct {
		Requires   []string `json:"requires"`
		MinContext int      `json:"min_context"`
		Preferred  []string `json:"preferred"`
		MinTier    string   `json:"min_tier"`
	} `json:"model"`
	Permissions  tools.PermissionSet `json:"permissions"`
	Requirements struct {
		Bin []string `json:"bin"`
		OS  []string `json:"os"`
	} `json:"requirements"`
	Entry struct {
		Greeting      string  `json:"greeting"`
		Pre           string  `json:"pre"`
		DefaultPrompt *string `json:"default_prompt"`
	} `json:"entry"`
	ReplaceSystemPrompt bool `json:"replace_system_prompt"`
}

Directories

Path Synopsis
Package ext is the Go SDK for writing zut extensions.
Package ext is the Go SDK for writing zut extensions.
Package extensions implements the host side of zut's subprocess extension protocol.
Package extensions implements the host side of zut's subprocess extension protocol.
Package extproto defines the JSON-over-stdin/stdout wire format spoken between zut and its extension subprocesses.
Package extproto defines the JSON-over-stdin/stdout wire format spoken between zut and its extension subprocesses.
internal
orchestration
Package orchestration owns the deterministic policy between manager turns and delegated worker lifecycles.
Package orchestration owns the deterministic policy between manager turns and delegated worker lifecycles.
Package lsp implements a small, dependency-free LSP and linter backend.
Package lsp implements a small, dependency-free LSP and linter backend.
Package modes implements zut's three run modes: print, json, interactive.
Package modes implements zut's three run modes: print, json, interactive.
bot
Package bot provides a protocol-agnostic runner for long-running bot modes.
Package bot provides a protocol-agnostic runner for long-running bot modes.
telegram
Package telegram implements zut's Telegram bot bridge.
Package telegram implements zut's Telegram bot bridge.
Package scheduler provides portable, in-process calendar scheduling.
Package scheduler provides portable, in-process calendar scheduling.
Package sdk is the public Go SDK for embedding the zut agent runtime in third-party programs.
Package sdk is the public Go SDK for embedding the zut agent runtime in third-party programs.
Package skills implements zut's reusable-instruction system.
Package skills implements zut's reusable-instruction system.
Package subagents discovers named agent profiles that can be selected by zut's resident subagent runtime.
Package subagents discovers named agent profiles that can be selected by zut's resident subagent runtime.
Package tools implements zut's built-in tools: read, write, edit, bash, create_worktree, grep, lsp, web search, and autonomous goal updates.
Package tools implements zut's built-in tools: read, write, edit, bash, create_worktree, grep, lsp, web search, and autonomous goal updates.

Jump to

Keyboard shortcuts

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