Documentation
¶
Index ¶
- Constants
- Variables
- func AIMLAPIServiceKey(resolved ResolvedConfig, store APIKeyGetter, getenv func(string) string) (string, error)
- func ClearProviderKeyStored(path, provider string) (cleared bool, err error)
- func DefaultMCPServers() map[string]MCPServerConfig
- func DefaultUserConfigPath() (string, error)
- func ForgetProviderKey(provider string) (bool, error)
- func HasProviderProfile(profile ProviderProfile) bool
- func IsDefaultMCPServer(name string) bool
- func IsDefaultMCPServerDisabled(name string) bool
- func IsUnconfiguredDefault(name string, server MCPServerConfig) bool
- func LoadAIMLAPIServiceKey() (string, error)
- func LockFile(path string) (func() error, error)
- func MarkProviderAPIKeyStored(path string, provider string) (err error)
- func MigratePlaintextProviderKeys(path string, store APIKeySetter) (count int, err error)
- func ProviderKeyStore() (*credstore.Store, error)
- func ProviderKeyStoreAt(dir string) (*credstore.Store, error)
- func ProviderPersisted(path string, name string) (bool, error)
- func SetActiveProviderEnv(name string)
- func SetMaxTurnsEnv(n int)
- func UserConfigDir() (string, error)
- func ValidateBytes(data []byte) (FileConfig, []Issue)
- type APIKeyGetter
- type APIKeySetter
- type EnsuredProvider
- type FileConfig
- func EditProvider(path string, edit ProviderEdit) (result FileConfig, err error)
- func LoadProviderCommand(command string) (FileConfig, error)
- func RemoveProvider(path string, name string) (result FileConfig, err error)
- func RenameProvider(path string, oldName string, newName string) (result FileConfig, err error)
- func SetActiveProvider(path string, name string) (result FileConfig, err error)
- func SetActiveProviderModel(path string, name string, model string) (result FileConfig, err error)
- func SetFavoriteModels(path string, models []string) (result FileConfig, err error)
- func SetPet(path string, pet string) (result FileConfig, err error)
- func SetProviderModel(path string, name string, model string) (result FileConfig, err error)
- func SetRecapsEnabled(path string, enabled bool) (result FileConfig, err error)
- func SetRecentModels(path string, entries []RecentModelEntry) (result FileConfig, err error)
- func SetSTTLocalEngine(path, binary, serverBinary, modelPath string, streaming bool) (result FileConfig, err error)
- func SetSTTModel(path string, provider STTProviderKind, model string) (result FileConfig, err error)
- func SetSTTProvider(path string, provider STTProviderKind) (result FileConfig, err error)
- func SetTheme(path string, theme string) (result FileConfig, err error)
- func UpsertProvider(path string, profile ProviderProfile, setActive bool) (result FileConfig, err error)
- type Issue
- type KeyBindingDef
- type KeyBindingsConfig
- type LocalControlConfig
- func (cfg LocalControlConfig) BrowserEnabled() bool
- func (cfg LocalControlConfig) DesktopEnabled() bool
- func (cfg LocalControlConfig) Disabled() bool
- func (cfg LocalControlConfig) Empty() bool
- func (cfg LocalControlConfig) MarshalJSON() ([]byte, error)
- func (cfg LocalControlConfig) TerminalEnabled() bool
- func (cfg *LocalControlConfig) UnmarshalJSON(data []byte) error
- type LocalControlDriverConfig
- type MCPConfig
- type MCPOAuthConfig
- type MCPServerConfig
- type NotifyConfig
- type Overrides
- type PreferencesConfig
- type ProviderEdit
- type ProviderKind
- type ProviderProfile
- type RecentModelEntry
- type ResolveOptions
- type ResolvedConfig
- type STTConfig
- type STTProviderKind
- type SandboxConfig
- type SessionsConfig
- type SwarmConfig
- type ToolsConfig
Constants ¶
const ActiveProviderEnv = "ZERO_PROVIDER"
ActiveProviderEnv selects the active provider profile by name (read in applyEnv).
const AnthropicBaseURL = "https://api.anthropic.com"
const GoogleBaseURL = "https://generativelanguage.googleapis.com"
const MaxRecentModels = 5
MaxRecentModels caps the persisted/displayed recent-selection history.
const MaxTurnsCeiling = 500
MaxTurnsCeiling caps the per-run tool-turn budget so a stray env value or typo can't set an absurd ceiling. Shared between applyEnv (read site) and the /turns command (write site) so the bound holds even if the env is set by a raw shell.
const MaxTurnsEnv = "ZERO_MAX_TURNS"
MaxTurnsEnv overrides the per-run tool-turn budget by name (read in applyEnv).
const OpenAIBaseURL = "https://api.openai.com/v1"
Variables ¶
var ( // ErrAIMLAPIKeyMissing means no AI/ML API key is configured. ErrAIMLAPIKeyMissing = errors.New("no AI/ML API key is configured; set up aimlapi.com with /provider or set AIMLAPI_API_KEY") // ErrAIMLAPIProxyProfile means the aimlapi profile points at a proxy, so its // key belongs to that proxy and is withheld from aimlapi.com services. ErrAIMLAPIProxyProfile = errors.New("the aimlapi provider points at a proxy base URL; its key is not sent to aimlapi.com services") // ErrAIMLAPIKeyInvalid means the key cannot be sent as a single Bearer token. ErrAIMLAPIKeyInvalid = errors.New("the AI/ML API key contains whitespace, a comma or a control character") )
ErrLockUnavailable reports that the config lock was still held by another process (or goroutine) when configLockTimeout expired. A caller that would otherwise make a SECOND config write after a failed one branches on this: the lock has not been released, so the second attempt can only spend another full timeout to fail the same way, turning one keystroke into two stalls.
var ErrNoActiveProvider = errors.New("no active provider configured")
ErrNoActiveProvider marks a resolve failure caused solely by a missing or unresolvable active provider. The interactive TUI treats this as "needs onboarding" (drop into the setup wizard) rather than a fatal config error.
var ErrProviderRequiresModel = errors.New("provider requires model")
ErrProviderRequiresModel marks a resolve failure caused solely by the active provider missing a model with no catalog default to fall back on (custom openai-/anthropic-compatible endpoints — Zero cannot guess a gateway's model). Like ErrNoActiveProvider, the interactive TUI treats it as "needs onboarding" and drops into the setup wizard so the user can fix it; headless commands (zero config, zero exec) still fail with the actionable message.
Functions ¶
func AIMLAPIServiceKey ¶ added in v0.13.0
func AIMLAPIServiceKey(resolved ResolvedConfig, store APIKeyGetter, getenv func(string) string) (string, error)
AIMLAPIServiceKey returns the AI/ML API key that may be sent to the aimlapi.com Toolbox and MCP server. It is resolved again on every call, so a provider change is seen by the next request.
The key comes from the aimlapi provider profile (the active one when it is aimlapi, otherwise the first), including a key held in the credential store, or from AIMLAPI_API_KEY when no aimlapi profile exists. The key is withheld when that profile, any aimlapi profile, or any profile reading AIMLAPI_API_KEY points at a base URL other than the canonical https://api.aimlapi.com/v1, and when AIMLAPI_INFERENCE_URL is overridden: in those cases the credential may belong to a proxy.
func ClearProviderKeyStored ¶
ClearProviderKeyStored unsets the APIKeyStored marker for a provider in the config at path, so credential checks no longer claim a stored key after one is removed. No-op when path/provider is empty, the config is absent, or the marker is already unset.
func DefaultMCPServers ¶
func DefaultMCPServers() map[string]MCPServerConfig
DefaultMCPServers returns the MCP servers Zero ships built in. Exa is ENABLED by default so web search and page fetching work out of the box with no setup and no API key. They are seeded before user/project config is merged (see ResolveMCP), so a user can override any field — for example add an API-key header to lift Exa's anonymous rate limit — or disable it entirely with `zero mcp disable <name>` (which writes `"disabled": true`).
Exa's hosted MCP server works anonymously with rate limits. Users can add an Exa API key for higher limits.
The AI/ML API server ships DISABLED: its tool runs and generations are billed to the user's AI/ML API balance, so it only connects after `zero mcp enable aimlapi` (which writes `"disabled": false`). The disable is marked as explicitly set so the lower-trust project layer cannot lift it (see mergeMCPServer); only the user and CLI-override scopes can. The key is attached per request by the MCP client and is never part of this config.
func DefaultUserConfigPath ¶
func ForgetProviderKey ¶
ForgetProviderKey removes a provider's stored API key from the credential store, reporting whether one existed. Used by the lifecycle "remove key" / auth logout.
func HasProviderProfile ¶
func HasProviderProfile(profile ProviderProfile) bool
func IsDefaultMCPServer ¶
IsDefaultMCPServer reports whether name is one of Zero's built-in default MCP servers. The config commands use it so a default can be disabled/enabled even though it is not written to the user's config file until overridden.
func IsDefaultMCPServerDisabled ¶ added in v0.13.0
IsDefaultMCPServerDisabled reports whether name is a built-in default that ships disabled, so enabling it has to be written out as `"disabled": false` rather than by dropping the flag.
func IsUnconfiguredDefault ¶
func IsUnconfiguredDefault(name string, server MCPServerConfig) bool
IsUnconfiguredDefault reports whether server is one of Zero's built-in defaults that the user never wrote an entry for in their config — i.e. it is running with whatever Zero ships (e.g. keyless Exa, no credentials).
Both conditions below must hold:
- !server.configured: the user's JSON never declared an object for this server key at all (set by MCPServerConfig.UnmarshalJSON only when it actually ran for this key). Any explicit action — including a disable/enable toggle like `zero mcp enable exa` that leaves the resolved value unchanged — sets configured, so it always counts as user-configured, even though the value comparison below could not tell the difference on its own.
- reflect.DeepEqual(def, server): the value still matches the default. This is the fallback for callers that construct MCPServerConfig directly rather than through the JSON/merge pipeline (server.configured is then always false) — without it, any hand-built config with different field values would be misreported as unconfigured.
Callers use this to tell "server we turned on for the user" apart from "server the user configured themselves," e.g. to avoid warning loudly when an out-of-the-box default that was never given credentials fails to connect.
func LoadAIMLAPIServiceKey ¶ added in v0.13.0
LoadAIMLAPIServiceKey resolves the user configuration, the environment and the user credential store, then applies AIMLAPIServiceKey. Project config is not read: provider keys are user-scoped. A config with no active provider still resolves its profiles (ErrNoActiveProvider), so the key is looked up in that partial config; every other resolve error is returned. Resolve drops a non-active profile it cannot normalize, so the configured profiles are checked as well: such a profile still withholds the key when it carries it.
func LockFile ¶
lockConfigFile serializes a config read-modify-write across processes.
Every mutator in this package loads the whole document, edits independent fields, and publishes a complete replacement by rename. The rename is atomic, so a reader never sees partial JSON — but two processes that both loaded the same revision each write a full document, and the second rename silently discards the first one's acknowledged update (issue #832). Startup work makes this easy to hit: MigratePlaintextProviderKeys rewrites the config on every launch, so it collides with any concurrent mutation from another Zero.
The lock must therefore span load, mutation, validation AND publication: holding it only around the write would still let both processes read the same stale revision first. Callers acquire before their first read, which is what makes the re-read inside the lock authoritative.
The lock file is a sibling of the config, never the config itself. The kernel holds an advisory lock against an inode, and publishing the config by rename installs a NEW inode — locking the config directly would leave each process holding a different one. lockutil keeps the sibling's path stable for the same reason, and never removes it.
The returned release function reports its own failure rather than swallowing it: a failed Release can leave the lock held for the rest of the process, so a mutator that returned success after it would be reporting a state the next mutation cannot reproduce. Callers join it into their result (AGENTS.md: "never report success when cleanup or unlock failed").
This also serializes goroutines within one process: each acquisition opens its own file description, so a second in-process attempt contends exactly as another process would. The lock is NOT reentrant, so an exported mutator that needs another mutator's work calls the unexported *Locked form instead of re-entering through the public function. LockFile exposes lockConfigFile to packages that edit the SAME user config document without going through this package's mutators — internal/cli's MCP editor reads, edits and republishes it with the identical temp-file+rename shape. A writer that skipped this lock would reintroduce the lost update for every field, so the lock has to be one authority across packages rather than a private detail of this one.
func MarkProviderAPIKeyStored ¶
MarkProviderAPIKeyStored records that provider's API key now lives in the credential store. It also clears inline/env key fields so the stored key is the runtime credential; an old apiKeyEnv value must not keep overriding a freshly captured key from `zero auth openrouter` or provider setup.
func MigratePlaintextProviderKeys ¶
func MigratePlaintextProviderKeys(path string, store APIKeySetter) (count int, err error)
MigratePlaintextProviderKeys moves any inline plaintext API key in the config at path into the credential store, marking the profile APIKeyStored and stripping the inline secret — but ONLY after the store write succeeds, so a failed Set leaves the plaintext key in place and never strands a credential. Returns how many keys were migrated; a no-op (0, nil) when path is empty/absent or nothing needs migrating. Safe to run on every startup (idempotent).
func ProviderKeyStore ¶
ProviderKeyStore opens the credential store beside the default user config.
func ProviderKeyStoreAt ¶
ProviderKeyStoreAt opens the encrypted credential store whose file backend lives in dir. The backend resolves keyring-first, then encrypted-file, with a plaintext opt-out via ZERO_CRED_STORAGE. The dir parameter exists so tests can point the file backend at a temp directory; production always uses the user config directory (ProviderKeyStore) because provider API keys are user-scoped by design — they are only ever captured under the user config, never project config (a cloned repo must not carry keys), so runtime lookups deliberately use the user store regardless of where a provider profile was resolved from.
func ProviderPersisted ¶
ProviderPersisted reports whether a provider profile named name actually has a row in the config file at path. A provider can appear in the resolved/ in-memory provider list without ever being written to config.json — e.g. applyProviderEnv synthesizes an "openai" profile purely from an ambient OPENAI_API_KEY environment variable on every Resolve() call, without ever persisting it. RemoveProvider/SetActiveProvider/SetProviderModel only ever look at what's on disk, so a caller offering to mutate a provider by name should check this first: "not on disk" needs different handling (nothing to persist/remove there) than a name that doesn't exist anywhere at all.
func SetActiveProviderEnv ¶
func SetActiveProviderEnv(name string)
SetActiveProviderEnv exports the active provider name to the process environment so a spawned child process (which inherits the environment) resolves the SAME provider profile — and therefore the same credentials (env key / stored key / OAuth) — as its parent. Without this a sub-agent re-resolves config.json's default provider and can land on one whose credentials don't match the parent's live selection, failing auth the instant it spawns. A blank name CLEARS the variable: switching back to an unnamed/default profile must not keep exporting a stale provider to children.
func SetMaxTurnsEnv ¶
func SetMaxTurnsEnv(n int)
SetMaxTurnsEnv exports the per-run tool-turn budget to the process environment so a spawned child (sub-agent / swarm member, which inherits the environment) runs with the SAME budget the user set via /turns. Without it a child re-resolves config.json's default and a large delegated task can exhaust its turns mid-run (exit 4 / max-turns). No-op for n <= 0.
func UserConfigDir ¶
UserConfigDir returns the base directory Zero stores per-user config under. It mirrors os.UserConfigDir everywhere except macOS: there Go defaults to ~/Library/Application Support, but Zero deliberately uses ~/.config (XDG-style, matching Linux and Claude Code) so a single config path works cross-platform. $XDG_CONFIG_HOME still wins on macOS when set.
func ValidateBytes ¶
func ValidateBytes(data []byte) (FileConfig, []Issue)
ValidateBytes parses data as a Zero FileConfig and runs the same semantic provider/model rules as ValidateFile. It returns the parsed config (zero value on parse failure) plus any structured issues. A parse failure yields a single issue whose Message wraps the underlying JSON error (path-less form: "invalid config JSON: <err>") so callers can extract *json.SyntaxError / *json.UnmarshalTypeError offsets via errors.As.
Types ¶
type APIKeyGetter ¶
APIKeyGetter is the read surface of the credential store; *credstore.Store satisfies it. Kept here so callers can inject a fake in tests.
type APIKeySetter ¶
APIKeySetter is the write surface of the credential store.
type EnsuredProvider ¶
EnsuredProvider reports the outcome of EnsureCatalogProvider: the profile name that serves the catalog entry, whether it was newly created, and which provider is active after the call (unchanged unless it was blank).
func EnsureCatalogProvider ¶
func EnsureCatalogProvider(path string, catalogID string) (result EnsuredProvider, err error)
EnsureCatalogProvider guarantees a provider profile exists in the config at path for the given catalog entry. OAuth login flows call this right after storing a token: a login is only reachable from the provider list and `zero providers use` when a profile exists, but a login must never replace or deactivate the user's current active provider — so an existing profile whose Name or CatalogID already matches is left completely untouched (its name, credentials, and model are the user's), and a created profile is NOT marked active unless no provider was active at all.
type FileConfig ¶
type FileConfig struct {
ModelRPM map[string]int `json:"modelRPM,omitempty"`
ActiveProvider string `json:"activeProvider,omitempty"`
Providers []ProviderProfile `json:"providers,omitempty"`
MaxTurns int `json:"maxTurns,omitempty"`
MCP MCPConfig `json:"mcp,omitempty"`
Sandbox SandboxConfig `json:"sandbox,omitempty"`
Notify NotifyConfig `json:"notify,omitempty"`
Tools ToolsConfig `json:"tools,omitempty"`
Swarm SwarmConfig `json:"swarm,omitempty"`
Preferences PreferencesConfig `json:"preferences,omitempty"`
KeyBindings KeyBindingsConfig `json:"keybindings,omitempty"`
LocalControl LocalControlConfig `json:"localControl,omitempty"`
STT STTConfig `json:"stt,omitempty"`
CrossSessionInbound string `json:"crossSessionInbound,omitempty"`
Sessions SessionsConfig `json:"sessions,omitempty"`
// Extra preserves top-level fields written by newer Zero versions or
// extensions so a read-modify-write through this version is non-destructive.
Extra map[string]json.RawMessage `json:"-"`
// contains filtered or unexported fields
}
func EditProvider ¶
func EditProvider(path string, edit ProviderEdit) (result FileConfig, err error)
EditProvider applies a provider edit in ONE read-modify-write: rename (activeProvider follows; a stored key migrates, with a best-effort rollback if the config write fails), field updates, the stored-key marker, and the verbatim description. A single write keeps the operation atomic — the previous rename+upsert+describe sequence could fail halfway and leave config.json renamed while every in-memory consumer still held the old name — and, unlike UpsertProvider's exact-name merge, the case-insensitive match here makes a case-only rename (groq -> Groq) an in-place update instead of an appended duplicate profile.
func LoadProviderCommand ¶
func LoadProviderCommand(command string) (FileConfig, error)
func RemoveProvider ¶
func RemoveProvider(path string, name string) (result FileConfig, err error)
RemoveProvider deletes the named provider profile from the config at path. When the removed profile was active, activeProvider hands off to the first remaining provider (or clears when none remain) so the config never points at a profile that no longer exists. The caller owns cleaning up the credential store entry — config stays pure of secret I/O on the read path, and remove keeps that symmetry by only touching config.json.
func RenameProvider ¶
func RenameProvider(path string, oldName string, newName string) (result FileConfig, err error)
RenameProvider renames a provider profile, keeping everything keyed by the profile name consistent: the activeProvider pointer follows the rename, and a key in the encrypted credential store (APIKeyStored) is migrated to the new name BEFORE the config is rewritten — the store write must succeed first so a failed migration never strands the config pointing at a key that no longer resolves. OAuth tokens are deliberately not migrated: the runtime's login candidates fall back to the profile's CatalogID, which every OAuth-capable catalog profile carries, so a rename keeps the login reachable.
func SetActiveProvider ¶
func SetActiveProvider(path string, name string) (result FileConfig, err error)
func SetActiveProviderModel ¶
func SetActiveProviderModel(path string, name string, model string) (result FileConfig, err error)
SetActiveProviderModel persists a provider selection as one lock-held read-modify-write. The active provider and that provider's model are one UI choice; publishing them separately can leave a partially applied selection if another writer wins the lock between calls.
func SetFavoriteModels ¶
func SetFavoriteModels(path string, models []string) (result FileConfig, err error)
func SetPet ¶
func SetPet(path string, pet string) (result FileConfig, err error)
SetPet persists only the terminal-pet preference while preserving every unrelated user setting through the config writer's atomic replace path.
func SetProviderModel ¶
func SetProviderModel(path string, name string, model string) (result FileConfig, err error)
func SetRecapsEnabled ¶
func SetRecapsEnabled(path string, enabled bool) (result FileConfig, err error)
SetRecapsEnabled persists the idle recap preference, mirroring SetFavoriteModels (read-modify-atomic-write).
func SetRecentModels ¶
func SetRecentModels(path string, entries []RecentModelEntry) (result FileConfig, err error)
SetRecentModels persists the automatic recent-model-switch history, mirroring SetFavoriteModels (read-modify-atomic-write). Unlike favorites, order is preserved (newest first) rather than sorted, since it reflects switch recency, not an alphabetical preference list.
func SetSTTLocalEngine ¶
func SetSTTLocalEngine(path, binary, serverBinary, modelPath string, streaming bool) (result FileConfig, err error)
SetSTTLocalEngine persists the paths of an auto-downloaded local engine + model and switches dictation to the local provider, mirroring SetTheme (read-modify-atomic-write). streaming selects the pipeline matching the downloaded model (a streaming transducer vs a batch model). Called after a download completes.
func SetSTTModel ¶
func SetSTTModel(path string, provider STTProviderKind, model string) (result FileConfig, err error)
SetSTTModel persists the dictation model and its provider, mirroring SetTheme (read-modify-atomic-write). provider must be one of the known STT provider kinds; a local provider stores the model as stt.localModelPath, otherwise as stt.model. A blank model clears the stored value for that slot.
func SetSTTProvider ¶
func SetSTTProvider(path string, provider STTProviderKind) (result FileConfig, err error)
SetSTTProvider persists just the dictation batch provider, mirroring SetTheme.
func SetTheme ¶
func SetTheme(path string, theme string) (result FileConfig, err error)
SetTheme persists the TUI theme preference, mirroring SetFavoriteModels (read-modify-atomic-write). A blank theme clears the stored preference.
func UpsertProvider ¶
func UpsertProvider(path string, profile ProviderProfile, setActive bool) (result FileConfig, err error)
func (FileConfig) MarshalJSON ¶
func (cfg FileConfig) MarshalJSON() ([]byte, error)
func (*FileConfig) UnmarshalJSON ¶
func (cfg *FileConfig) UnmarshalJSON(data []byte) error
type Issue ¶
Issue is a single structured problem found while validating a config file. Message is already routed through the package secret redaction.
type KeyBindingDef ¶
type KeyBindingDef string
KeyBindingDef defines one key binding string (e.g. "ctrl+o") that the TUI can remap. An empty string means "use the built-in default" for that action.
type KeyBindingsConfig ¶
type KeyBindingsConfig struct {
// ToggleDetailed toggles the detailed transcript view (default: ctrl+o).
ToggleDetailed KeyBindingDef `json:"toggleDetailed,omitempty"`
// ToggleMouse toggles mouse capture release (default: ctrl+e).
ToggleMouse KeyBindingDef `json:"toggleMouse,omitempty"`
// CycleReasoning cycles through reasoning effort levels (default: ctrl+t).
CycleReasoning KeyBindingDef `json:"cycleReasoning,omitempty"`
// TogglePlan is retained for configuration compatibility. Plan updates render
// in the transcript and no longer have a persistent panel to toggle.
TogglePlan KeyBindingDef `json:"togglePlan,omitempty"`
// ToggleSidebar toggles the right context sidebar (default: ctrl+b).
ToggleSidebar KeyBindingDef `json:"toggleSidebar,omitempty"`
}
KeyBindingsConfig holds the subset of TUI keybindings that users may remap via config.json. Each field defaults to a sensible built-in when empty.
type LocalControlConfig ¶
type LocalControlConfig struct {
Enabled bool `json:"enabled,omitempty"`
Browser LocalControlDriverConfig `json:"browser,omitempty"`
Desktop LocalControlDriverConfig `json:"desktop,omitempty"`
Terminal LocalControlDriverConfig `json:"terminal,omitempty"`
ArtifactsDir string `json:"artifactsDir,omitempty"`
// contains filtered or unexported fields
}
LocalControlConfig controls local browser/desktop/terminal automation helpers. Helpers are discovered lazily by the tool that needs them; no setup command or background probe is required during startup.
func (LocalControlConfig) BrowserEnabled ¶
func (cfg LocalControlConfig) BrowserEnabled() bool
func (LocalControlConfig) DesktopEnabled ¶
func (cfg LocalControlConfig) DesktopEnabled() bool
func (LocalControlConfig) Disabled ¶
func (cfg LocalControlConfig) Disabled() bool
func (LocalControlConfig) Empty ¶
func (cfg LocalControlConfig) Empty() bool
func (LocalControlConfig) MarshalJSON ¶
func (cfg LocalControlConfig) MarshalJSON() ([]byte, error)
func (LocalControlConfig) TerminalEnabled ¶
func (cfg LocalControlConfig) TerminalEnabled() bool
func (*LocalControlConfig) UnmarshalJSON ¶
func (cfg *LocalControlConfig) UnmarshalJSON(data []byte) error
type LocalControlDriverConfig ¶
type LocalControlDriverConfig struct {
Enabled bool `json:"enabled,omitempty"`
HelperPath string `json:"helperPath,omitempty"`
Driver string `json:"driver,omitempty"`
// contains filtered or unexported fields
}
func (LocalControlDriverConfig) Empty ¶
func (cfg LocalControlDriverConfig) Empty() bool
func (LocalControlDriverConfig) MarshalJSON ¶
func (cfg LocalControlDriverConfig) MarshalJSON() ([]byte, error)
func (*LocalControlDriverConfig) UnmarshalJSON ¶
func (cfg *LocalControlDriverConfig) UnmarshalJSON(data []byte) error
type MCPConfig ¶
type MCPConfig struct {
Servers map[string]MCPServerConfig `json:"servers,omitempty"`
}
func ResolveMCP ¶
func ResolveMCP(options ResolveOptions) (MCPConfig, error)
type MCPOAuthConfig ¶
type MCPOAuthConfig struct {
ClientID string `json:"clientID,omitempty"`
ClientSecret string `json:"clientSecret,omitempty"`
Scopes []string `json:"scopes,omitempty"`
AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`
TokenEndpoint string `json:"tokenEndpoint,omitempty"`
RegistrationEndpoint string `json:"registrationEndpoint,omitempty"`
IssuerURL string `json:"issuerURL,omitempty"`
}
MCPOAuthConfig describes how to authenticate to a remote MCP server using an OAuth 2.0 + PKCE authorization-code flow. Endpoints may be discovered from the authorization server's metadata document; explicit values here override or fill in anything discovery cannot provide. Client credentials are optional when the server supports dynamic client registration.
type MCPServerConfig ¶
type MCPServerConfig struct {
Type string `json:"type,omitempty"`
Command string `json:"command,omitempty"`
Args []string `json:"args,omitempty"`
Env map[string]string `json:"env,omitempty"`
URL string `json:"url,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Auth string `json:"auth,omitempty"`
OAuth *MCPOAuthConfig `json:"oauth,omitempty"`
Disabled bool `json:"disabled,omitempty"`
// ProjectConfigured marks servers touched by project config. It is runtime
// metadata, not persisted config.
ProjectConfigured bool `json:"-"`
// contains filtered or unexported fields
}
func (MCPServerConfig) MarshalJSON ¶ added in v0.13.0
func (server MCPServerConfig) MarshalJSON() ([]byte, error)
MarshalJSON writes "disabled" whenever it was explicitly set, not only when true. A read-modify-write of config.json (SetTheme, SetActiveProvider, ...) would otherwise drop `"disabled": false`, which turns a default that ships disabled (aimlapi) back off and lets project config override a user's explicit enable (see mergeMCPServer).
func (*MCPServerConfig) UnmarshalJSON ¶
func (server *MCPServerConfig) UnmarshalJSON(data []byte) error
type NotifyConfig ¶
type NotifyConfig struct {
Mode string `json:"mode,omitempty"`
FocusMode string `json:"focusMode,omitempty"`
}
func UpdateNotify ¶
func UpdateNotify(path string, merge func(current NotifyConfig) NotifyConfig) (result NotifyConfig, err error)
UpdateNotify runs one SERIALIZED read-modify-write transaction on the user's notify block. merge receives the currently stored block and returns the block to store; it must preserve any field the caller is not explicitly changing. The lock covers reading the stored block, applying merge, and replacing the file, so two concurrent partial updates (for example `--mode off` and `--focus always` from two terminals) cannot interleave their reads and writes and silently undo each other's explicit change (maintainer review, PR #1001 reproduced a 50/50 lost-update without it).
The write replaces ONLY the notify member's bytes (setNotifyJSONObject), preserving every unrelated value and its explicit presence — including explicit zeros/falses like tools.deferThreshold: 0 or an MCP server's disabled: false, which the typed serializer's omitempty cannot round-trip — through the existing temp-file-and-rename atomic publish. Locking only the final write would leave the stale-field merge outside the transaction, so the whole sequence runs under one lock — the SAME lockConfigFileFn authority every other config mutator uses (provider/theme/credential/MCP writes), not a private lock: two authorities over the same file would not contend (maintainer review, PR #1001). The release error is joined into the result like every other writer: a failed unlock would leave the advisory lock held and later updates blocked while the caller is told success.
func UserNotify ¶
func UserNotify(path string) (NotifyConfig, error)
UserNotify returns the notify block stored in the user's own config file at path, trimmed. A missing file or missing/empty block returns the zero value: callers that need to preserve "whatever the user already chose" on a partial update must seed from THIS value, not from the resolved view — the resolver merges project config and the TUI applies its own defaults, so seeding from resolved copies choices the user never made into their global file (a project's mode: off, or a pinned default) and across every other project.
type Overrides ¶
type Overrides struct {
ActiveProvider string
Providers []ProviderProfile
Provider ProviderProfile
MaxTurns int
MCP MCPConfig
Sandbox SandboxConfig
Notify NotifyConfig
Tools ToolsConfig
KeyBindings KeyBindingsConfig
LocalControl LocalControlConfig
STT STTConfig
CrossSessionInbound string
}
type PreferencesConfig ¶
type PreferencesConfig struct {
FavoriteModels []string `json:"favoriteModels,omitempty"`
// RecentModels is the short automatic history of provider+model pairs the
// user has switched to via /model, newest first. Unlike FavoriteModels
// (manual pins), this list is maintained automatically on every switch and
// capped to MaxRecentModels entries. See RecentModelEntry.
RecentModels []RecentModelEntry `json:"recentModels,omitempty"`
// Theme is the persisted TUI palette preference — "auto" or a registered theme
// name (e.g. "dracula"). Applied at startup below the --theme flag and
// ZERO_THEME, so a /theme choice survives restart. Empty = unset (defaults auto).
Theme string `json:"theme,omitempty"`
// Pet is the terminal companion selected through /pets. Empty leaves pets
// off until the user chooses one; "disabled" is the explicit off state.
Pet string `json:"pet,omitempty"`
// Recaps is a tri-state: nil (unset) defaults to ON; an explicit false means
// the user turned idle recaps off. A *bool is its own tri-state, so no
// custom unmarshal is needed (unlike ToolsConfig.DeferThreshold's int).
Recaps *bool `json:"recaps,omitempty"`
// CompactionModel routes compaction summarization calls to this model
// instead of the session's main model (summaries at main-model prices are
// the most expensive recurring event in long runs). Empty = automatic: a
// curated cheap model on official endpoints, the main model elsewhere.
// "main" forces the main model. ZERO_COMPACTION_MODEL overrides.
CompactionModel string `json:"compactionModel,omitempty"`
}
func (PreferencesConfig) RecapsEnabled ¶
func (p PreferencesConfig) RecapsEnabled() bool
RecapsEnabled reports whether idle recaps are on. Unset defaults to ON.
type ProviderEdit ¶
type ProviderEdit struct {
Name string
NewName string
BaseURL string
Model string
APIKey string
APIKeyStored bool
Description string
}
ProviderEdit is a field-level edit of one saved provider, applied by EditProvider in a single atomic write. Name is the CURRENT profile name (matched case-insensitively); NewName renames (case-only renames included). Empty BaseURL/Model/APIKey mean "leave unchanged"; Description is applied VERBATIM (the editor always knows the full desired text, so clearing works).
type ProviderKind ¶
type ProviderKind string
const ( ProviderKindOpenAI ProviderKind = "openai" ProviderKindAnthropic ProviderKind = "anthropic" ProviderKindAnthropicCompat ProviderKind = "anthropic-compatible" ProviderKindGoogle ProviderKind = "google" ProviderKindOpenAICompatible ProviderKind = "openai-compatible" )
type ProviderProfile ¶
type ProviderProfile struct {
Name string `json:"name"`
Provider string `json:"provider,omitempty"`
ProviderKind ProviderKind `json:"provider_kind,omitempty"`
CatalogID string `json:"catalogID,omitempty"`
BaseURL string `json:"baseURL,omitempty"`
APIKey string `json:"apiKey,omitempty"`
APIKeyEnv string `json:"apiKeyEnv,omitempty"`
// APIKeyStored marks that this provider's API key lives in the encrypted
// credential store (internal/credstore), not inline in APIKey. The effective
// key is loaded from the store at provider-build time; config.json holds only
// this marker, never the secret.
APIKeyStored bool `json:"apiKeyStored,omitempty"`
APIFormat string `json:"apiFormat,omitempty"`
AuthHeader string `json:"authHeader,omitempty"`
AuthScheme string `json:"authScheme,omitempty"`
AuthHeaderValue string `json:"authHeaderValue,omitempty"`
CustomHeaders map[string]string `json:"customHeaders,omitempty"`
Model string `json:"model,omitempty"`
ParseThinkTags *bool `json:"parseThinkTags,omitempty"`
Description string `json:"description,omitempty"`
}
func ApplyStoredAPIKey ¶
func ApplyStoredAPIKey(profile ProviderProfile, store APIKeyGetter) ProviderProfile
ApplyStoredAPIKey fills profile.APIKey from the credential store when it is not already resolved — an inline config key or a resolved APIKeyEnv always wins, so this only supplies a key for providers whose secret lives in the store. A nil store, a miss, or a store error leaves the profile unchanged.
func SecureProviderProfile ¶
func SecureProviderProfile(profile ProviderProfile, configPath string) ProviderProfile
SecureProviderProfile moves an inline APIKey on the profile into the credential store co-located with configPath, returning a profile with APIKeyStored set and APIKey cleared so the secret is never written to config.json. On any store error (e.g. no keyring) it returns the profile unchanged — the inline key persists and the startup migration retries later — so capturing a provider never fails on a flaky credential backend.
func (ProviderProfile) HasConfiguredCredential ¶
func (profile ProviderProfile) HasConfiguredCredential() bool
HasConfiguredCredential reports whether the profile is set up to authenticate with its own API key (inline, stored, or a raw auth header). It is the single definition of "this profile is key-authed", shared by OAuthLoginCandidates and the cli/tui setup surfaces so they never disagree about whether a profile is keyed. APIKeyEnv is deliberately NOT included: an env var may be unset at runtime while the profile actually relies on an OAuth login, so an env-configured-but-empty profile must still be allowed to resolve a token.
func (ProviderProfile) MissingCredentialEnv ¶
func (profile ProviderProfile) MissingCredentialEnv() (string, bool)
MissingCredentialEnv reports the environment variable this profile is expected to read an API key from, and whether that expectation is currently unmet. It is the single source of truth for "does this saved provider need a credential it doesn't have" — the CLI (`providers check`, `usableSavedProviders`) and TUI (`/providers` status, provider wizard summary) surfaces all delegate here so they never disagree about a profile's status.
For the catalog's two "bring your own endpoint" descriptors (custom-openai-compatible, custom-anthropic-compatible), RequiresAuth is just a wizard template default, not a fact about the user's actual endpoint: a custom target may need no auth at all. So for those two only, a credential is expected exclusively when this profile carries its own explicit APIKeyEnv that differs from the catalog's guessed default — a value matching that default is indistinguishable from the wizard's old auto-stamp bug (issue #555) and is treated the same as unset, which also self-heals profiles saved before that bug was fixed.
func (ProviderProfile) OAuthLoginCandidates ¶
func (profile ProviderProfile) OAuthLoginCandidates() []string
OAuthLoginCandidates returns the login names to try, in order, when resolving this profile's OAuth token — used by the runtime bearer resolver, the Codex account-header resolver, and the onboarding presence check so all three agree.
It returns NO candidates for a profile that carries its own configured credential: attaching an OAuth resolver to such a profile makes withBearer erase the key the instant a token resolves, silently routing/billing the call through the OAuth account instead of the intended key (the cross-profile override the review caught — and, via the profile name, a same-name login overriding an explicit key). A stored-key profile that reaches this keyless (e.g. a transiently unreadable keyring) is likewise treated as key-auth, so it fails with a clear missing-credential error rather than silently borrowing an unrelated OAuth login. APIKeyEnv is intentionally not part of that gate (an env var may be unset while the profile relies on OAuth).
For a keyless profile the profile name comes first (a login under your own profile name is unambiguously yours), then the catalog ID as a FALLBACK (so a profile renamed away from its catalog ID — e.g. {name:"codex", catalogID:"chatgpt"} — still finds a `zero auth login chatgpt` token). Candidates are trimmed, blank-skipped, and de-duplicated CASE-SENSITIVELY — the OAuth token store is a case-sensitive map, so "ChatGPT" and "chatgpt" are distinct keys and both must survive.
func (*ProviderProfile) UnmarshalJSON ¶
func (profile *ProviderProfile) UnmarshalJSON(data []byte) error
type RecentModelEntry ¶
RecentModelEntry is one provider-qualified model selection recorded in Preferences.RecentModels. Provider is the saved provider profile's Name (not a display label), so a recent entry can be resolved back to a concrete profile the same way the /model picker's cross-provider rows are.
func NormalizeRecentModels ¶
func NormalizeRecentModels(entries []RecentModelEntry) []RecentModelEntry
NormalizeRecentModels trims, drops entries with no model id, de-duplicates by provider+model pair (keeping the first/newest occurrence), and caps the result to MaxRecentModels. Order is preserved — the caller is responsible for passing entries newest-first. Exported so callers outside this package (e.g. the TUI, which keeps its own in-memory copy of recent history) apply the exact same normalization rules as the persisted config, instead of maintaining a second, independently-drifting copy of this logic.
type ResolveOptions ¶
type ResolveOptions struct {
UserConfigPath string
ProjectConfigPath string
ProviderCommand string
Env map[string]string
Overrides Overrides
// ExcludeProject drops the project config layer (ProjectConfigPath) from MCP
// resolution when the workspace is untrusted, so a cloned repo's ./.zero/config.json
// cannot spawn stdio MCP servers. It is fail-closed: only a trusted workspace sets
// it false. Mirrors the ExcludeProject option hooks and plugins already honor.
ExcludeProject bool
}
func DefaultResolveOptions ¶
func DefaultResolveOptions(workspaceRoot string) (ResolveOptions, error)
DefaultResolveOptions builds config resolution inputs from the local process environment and workspace.
type ResolvedConfig ¶
type ResolvedConfig struct {
ModelRPM map[string]int
ActiveProvider string
Providers []ProviderProfile
Provider ProviderProfile
MaxTurns int
// MaxTurnsSet reports whether MaxTurns came from an explicit source (a
// config file, a provider command, ZERO_MAX_TURNS, or CLI overrides) rather
// than the built-in default — callers that need a different default can
// tell the two apart.
MaxTurnsSet bool
MCP MCPConfig
Sandbox SandboxConfig
Notify NotifyConfig
Tools ToolsConfig
Swarm SwarmConfig
Preferences PreferencesConfig
KeyBindings KeyBindingsConfig
LocalControl LocalControlConfig
STT STTConfig
CrossSessionInbound string
}
func Resolve ¶
func Resolve(options ResolveOptions) (ResolvedConfig, error)
type STTConfig ¶
type STTConfig struct {
// Provider is the batch transcription backend: "local" (sherpa-onnx-offline,
// the default), "groq", or "openai". Termux and the fallback everywhere use
// this path.
Provider STTProviderKind `json:"provider,omitempty"`
// StreamProvider is the streaming backend on desktop: "local" (sherpa-onnx
// websocket server, default), "deepgram", or "openai" (Realtime).
StreamProvider STTProviderKind `json:"streamProvider,omitempty"`
// Streaming enables the live-transcript pipeline on platforms that support
// it (desktop). Defaults to on; set false to always use the batch pipeline.
Streaming *bool `json:"streaming,omitempty"`
// Model overrides the cloud batch model (e.g. "whisper-large-v3-turbo" for
// Groq, "whisper-1" for OpenAI). Empty uses the provider default.
Model string `json:"model,omitempty"`
// StreamModel overrides the cloud streaming model (Deepgram/OpenAI Realtime).
StreamModel string `json:"streamModel,omitempty"`
// LocalModelPath is the sherpa-onnx model directory for local transcription
// (batch and streaming). Required to use a local provider.
LocalModelPath string `json:"localModelPath,omitempty"`
// LocalBinary overrides the offline binary name/path (default
// "sherpa-onnx-offline"); LocalServerBinary overrides the streaming server
// (default "sherpa-onnx-online-websocket-server"). Both looked up on PATH.
LocalBinary string `json:"localBinary,omitempty"`
LocalServerBinary string `json:"localServerBinary,omitempty"`
// LocalServerPort is the localhost port for the sherpa-onnx websocket server
// (default 6006).
LocalServerPort int `json:"localServerPort,omitempty"`
// EngineVersion selects the sherpa-onnx release the auto-download fetches
// ("" → a pinned known-good default; "latest" or any release tag also works,
// so a newer engine needs no Zero update). Verified against the release's
// published SHA256 digest either way.
EngineVersion string `json:"engineVersion,omitempty"`
// NumThreads sets the local engine's thread count (0 = engine default).
NumThreads int `json:"numThreads,omitempty"`
// Language optionally constrains recognition (ISO-639-1, e.g. "en"). Empty =
// auto-detect.
Language string `json:"language,omitempty"`
// MaxDurationSeconds is the hard runaway-recording cap on every platform
// (0 = default 300s).
MaxDurationSeconds int `json:"maxDurationSeconds,omitempty"`
// SilenceAutoStop ends a recording ~2s after the signal goes quiet, as a
// backstop for a forgotten manual stop (not VAD-triggered start). Defaults on.
SilenceAutoStop *bool `json:"silenceAutoStop,omitempty"`
// AutoSubmit fires the transcript at the agent instead of inserting it for
// review. Defaults OFF — insert-for-review is the safety net for a misheard
// prompt (§3).
AutoSubmit *bool `json:"autoSubmit,omitempty"`
// WindowsAudioDevice names the dshow capture device (auto-detected when empty).
WindowsAudioDevice string `json:"windowsAudioDevice,omitempty"`
}
STTConfig configures speech-to-text dictation. All fields are optional; empty values take the documented defaults. Booleans that need a real tri-state (distinguishing "unset" from "false") use *bool, matching PreferencesConfig.Recaps.
func (STTConfig) AutoSubmitEnabled ¶
AutoSubmitEnabled reports whether transcripts are auto-fired. Unset defaults OFF.
func (STTConfig) Empty ¶
Empty reports whether the STT config carries no user-set values (so it can be omitted from a marshaled config).
func (STTConfig) STTProvider ¶
func (c STTConfig) STTProvider() STTProviderKind
STTProvider returns the configured batch provider, defaulting to local.
func (STTConfig) STTStreamProvider ¶
func (c STTConfig) STTStreamProvider() STTProviderKind
STTStreamProvider returns the configured streaming provider, defaulting to local.
func (STTConfig) SilenceAutoStopEnabled ¶
SilenceAutoStopEnabled reports whether trailing-silence auto-stop is on. Unset defaults ON.
func (STTConfig) StreamingEnabled ¶
StreamingEnabled reports whether the live pipeline is on. Unset defaults ON.
type STTProviderKind ¶
type STTProviderKind string
STTProviderKind is the batch (or streaming) transcription backend selector. Validated at config load time against the known set, so a typo fails loudly with the valid options rather than silently falling back to a default.
const ( STTProviderLocal STTProviderKind = "local" STTProviderGroq STTProviderKind = "groq" STTProviderOpenAI STTProviderKind = "openai" STTProviderDeepgram STTProviderKind = "deepgram" )
type SandboxConfig ¶
type SandboxConfig struct {
// Enabled turns the sandbox off when set to false (`"sandbox": {"enabled":
// false}`). A pointer distinguishes an explicit false (disable) from an
// omitted key (keep the default: enabled). Honored from the GLOBAL user
// config and CLI only — deliberately NOT project config, so a cloned repo
// cannot disable the sandbox that constrains it. nil / true keep enforcement.
Enabled *bool `json:"enabled,omitempty"`
// Network controls whether shell commands classified as network-touching
// (curl, git push, package installs, …) are allowed: "allow" or "deny".
// Empty keeps the built-in default (deny). Without this knob the engine's
// hard-coded NetworkDeny was unreachable from any config surface.
Network string `json:"network,omitempty"`
// AdditionalWriteRoots lists directories outside the workspace the sandbox
// allows writes in. Each entry must be an existing directory; entries are
// normalized (~-expanded, absolutized, symlink-resolved) at startup and an
// invalid entry fails the run. Honored from the GLOBAL user config and CLI
// flags only — deliberately not project config, so a cloned repo cannot
// grant itself write access. Session-only grants use /add-dir instead.
AdditionalWriteRoots []string `json:"additionalWriteRoots,omitempty"`
// BlockUnixSockets, when true, asks the Linux sandbox helper to install a
// best-effort seccomp filter that denies AF_UNIX socket creation inside the
// sandboxed command. Off by default; ignored on non-Linux backends.
BlockUnixSockets bool `json:"blockUnixSockets,omitempty"`
// MonitorDenials, when true on macOS, tails the unified log for this run's
// sandbox denials and appends them to a command's stderr so blocked operations
// are visible to the agent. Off by default. No-op on platforms/OS versions that
// do not deliver seatbelt denials to the queryable log.
MonitorDenials bool `json:"monitorDenials,omitempty"`
}
type SessionsConfig ¶
type SessionsConfig struct {
// RetentionDays is the cutoff `zero sessions prune` uses when it is given no
// --older-than. Unset (0) means prune needs an explicit cutoff; nothing is
// ever removed without one being asked for.
RetentionDays int `json:"retentionDays,omitempty"`
}
SessionsConfig holds settings for Zero's saved sessions.
READ FROM THE USER'S OWN CONFIG ONLY. It decides what `zero sessions prune` deletes, and sessions belong to the user rather than to a repository, so a project's .zero/config.json has no say: the resolver does not merge it, and the prune command reads it straight from the user config file.
func ReadSessionsConfig ¶
func ReadSessionsConfig(path string) (SessionsConfig, error)
ReadSessionsConfig reads the sessions settings from the config file at path, which callers pass as the user config. A missing file is an empty config. See SessionsConfig for why nothing else supplies these settings.
type SwarmConfig ¶
type SwarmConfig struct {
MaxTeamSize int `json:"maxTeamSize,omitempty"`
}
SwarmConfig tunes the multi-agent swarm. MaxTeamSize caps how many members run concurrently per team; 0 uses the built-in default (8). Spawns past the cap queue and launch as slots free, so lowering it bounds parallelism (and provider load / rate-limit pressure) without dropping work.
type ToolsConfig ¶
type ToolsConfig struct {
DeferThreshold int `json:"deferThreshold,omitempty"`
// contains filtered or unexported fields
}
func (*ToolsConfig) UnmarshalJSON ¶
func (cfg *ToolsConfig) UnmarshalJSON(data []byte) error