config

package
v0.75.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: MIT Imports: 16 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 config loads the agent's runtime configuration. Settings come from two JSON files merged over safe defaults: a machine-level user config (~/.config/ipsupport-code/config.json — the LM Studio endpoint, written by first-run setup) and a per-workspace config (<workspace>/.agent/config.json — the permission policy). A protective deny floor is unioned in afterwards so a workspace config can never drop the most dangerous-command guards.

Index

Constants

This section is empty.

Variables

View Source
var HasProgram = func(name string) bool {
	_, err := exec.LookPath(name)
	return err == nil
}

HasProgram reports whether a command can be found to run. A variable so tests don't depend on what the machine has installed.

View Source
var ProviderTemplates = map[string]LLM{
	"openai":     {BaseURL: "https://api.openai.com/v1", Model: "gpt-4o-mini"},
	"anthropic":  {BaseURL: "https://api.anthropic.com/v1", Model: "claude-3-5-sonnet-latest"},
	"grok":       {BaseURL: "https://api.x.ai/v1", Model: "grok-2-latest"},
	"groq":       {BaseURL: "https://api.groq.com/openai/v1", Model: "llama-3.3-70b-versatile"},
	"openrouter": {BaseURL: "https://openrouter.ai/api/v1", Model: "openai/gpt-4o-mini"},
	"zai":        {BaseURL: "https://api.z.ai/api/paas/v4", Model: "glm-5.2"},

	"copilot": {BaseURL: "https://api.githubcopilot.com", Model: "gpt-4.1", WireAPI: "auto", APIKeyCmd: []string{"gh", "auth", "token", "--hostname", "github.com"}},
}

ProviderTemplates are built-in OpenAI-compatible providers: base URL (and a sensible default model) are known, so the user only needs to add an API key.

Functions

func ApplyOverride added in v0.44.23

func ApplyOverride(cfg *Config, dotted, raw string) error

ApplyOverride sets one dotted-path key on cfg IN MEMORY ONLY — no file I/O, nothing persisted. Same key/value semantics and validation as SetFileValue (a value that parses as JSON keeps its type, else it's the literal string; an unknown key or a type mismatch is rejected) — but for a per-invocation CLI override (e.g. -override run.default=allow, or the -skip-permissions shorthand), which must leave zero trace in config.json: a later plain launch, with no override flags, must see exactly the settings from before.

func ClearRunOnlyModel added in v0.74.0

func ClearRunOnlyModel()

ClearRunOnlyModel forgets -m (for tests).

func CompactPromptPath added in v0.46.0

func CompactPromptPath() string

CompactPromptPath is the global standing instruction for session compaction — what a recap must always keep. Mirrors SystemPromptPath (a workspace .agent/compact.md wins over it), because the instruction is prose the user writes and re-reads, not a value to cycle through in a settings panel, and because it has to reach the AUTOMATIC compaction too: that one fires on its own at the context threshold and decides what survives, where a one-shot "/compact <steer>" can never reach.

func DefaultKBPath

func DefaultKBPath(workspace string) string

DefaultKBPath is the learned-lessons store for one workspace.

Deliberately PER WORKSPACE, alongside the learned facts it is the twin of, and no longer a single global file. Reported live, from a real debug log: a lesson distilled in one project surfaced in an unrelated one and pointed the model at the wrong cause, which it then quoted back in its own reasoning and kept acting on. A store shared by every project on the machine turns one bad lesson into a machine-wide problem; scoped this way the blast radius is the project it was learned in, and /clear can wipe it like any other per-workspace state. An explicit kb_path in config still overrides this (a deliberately shared store is a choice, not the default).

func DefaultSkillsPath

func DefaultSkillsPath() string

DefaultSkillsPath is the global skills directory.

func DefaultTracePath

func DefaultTracePath() string

DefaultTracePath is the global decision-trace (training dataset) location.

func DefaultUsagePath added in v0.4.5

func DefaultUsagePath() string

DefaultUsagePath is the global token-usage ledger location.

func Flatten added in v0.26.0

func Flatten(cfg Config) []string

Flatten returns the effective config as sorted "dotted.path\tvalue" lines (value as compact JSON), for `config list`.

func GlobalExists

func GlobalExists() bool

GlobalExists reports whether the user config file is present.

func GlobalPath

func GlobalPath() string

GlobalPath is the machine-level user config file.

func GlobalTelemetry added in v0.62.0

func GlobalTelemetry() (*bool, error)

GlobalTelemetry reads the usage-statistics setting from the global file alone (nil: never decided). The setting is global-only, so nothing else can change it — and an opt-out must not depend on a workspace file parsing.

func IsCustomProvider added in v0.14.0

func IsCustomProvider(cfg Config, name string) bool

IsCustomProvider reports whether name is a user-defined provider (present in the config's providers map) rather than a built-in template. A custom provider is self-describing (the user supplied base_url) and may be keyless — e.g. a local Ollama/vLLM/second-LM-Studio endpoint — so the UI shouldn't demand an API key.

func JudgePromptPath added in v0.50.0

func JudgePromptPath() string

JudgePromptPath is the global acceptance criteria for the goal judge — what counts as done in addition to the goal itself. Mirrors CompactPromptPath (a workspace .agent/judge.md wins over it): it is prose the user writes and refines as a project's standards settle, not a value to cycle through in a panel, and it must be able to grow without ever touching the goal.

func KnownProviders added in v0.4.0

func KnownProviders() []string

KnownProviders lists the built-in template names (sorted), for help/listing.

func LegacyStateDir added in v0.54.0

func LegacyStateDir(workspace string) string

LegacyStateDir is the in-workspace directory state USED to live in. Read once per path, to move an existing installation's state out; never written to.

func LogPathFor added in v0.58.0

func LogPathFor(workspace, session string) string

LogPathFor is where a run's logs go while the TUI owns the screen (writing them to stderr would corrupt the alt-screen). Tail it to watch retries and warnings live.

Both parts of the name matter, and neither used to be there. The WORKSPACE, because a single agent.log served every checkout on the machine: two runs pointed at different directories — which is exactly what a pair of test scripts does — interleaved into one file line by line, and with IPS_LOG=debug neither was readable. The SESSION, because two named sessions on ONE checkout have the same problem.

Named by the workspace's basename alone, no path digest: this is a file you tail by hand, so "agent-test.log" beats "agent-test-137747f9.log". Two checkouts sharing a basename (~/gh/romashka and ~/work/romashka) therefore share a log — a deliberate trade, unlike StateDir, where a collision would mix two projects' memory rather than two logs.

func LookupPath added in v0.26.0

func LookupPath(cfg Config, dotted string) (any, bool)

LookupPath returns the effective value at a dotted path in cfg (its marshaled view), and whether that path exists.

func LookupPathInFile added in v0.40.5

func LookupPathInFile(path, dotted string) (any, bool)

LookupPathInFile returns the value at a dotted path in the raw JSON object at path — no defaults, no merge with the other config layer. Used to check whether ONE specific file defines a key, independent of what's effective (e.g. so `config set` can warn when the OTHER layer — global vs workspace — also defines it and would win the merge, making the write have no visible effect). A missing/unreadable file just means "no keys", not an error.

func RunOnlyModel added in v0.74.0

func RunOnlyModel() bool

RunOnlyModel reports whether this process was started with -m: model and provider choices are then for the session only.

func SaveAgents added in v0.8.0

func SaveAgents(agents map[string]AgentProfile) error

SaveAgents persists the sub-agent profile map globally.

func SaveChannel added in v0.2.0

func SaveChannel(channel string) error

SaveChannel persists the update channel (stable|nightly).

func SaveColor added in v0.43.3

func SaveColor(color string) error

SaveColor persists the TUI accent color (an ANSI code or /color name).

func SaveCompactThreshold added in v0.40.2

func SaveCompactThreshold(t float64) error

SaveCompactThreshold persists the auto-compact fill-level override globally (see Config.CompactThreshold).

func SaveGlobal

func SaveGlobal(name string, l LLM) error

SaveGlobal writes the machine-level settings (display name + LLM connection) to the user config file, creating its directory.

func SaveGoalMaxReturns added in v0.13.0

func SaveGoalMaxReturns(n int) error

SaveGoalMaxReturns persists the goal-pursuit return TTL globally.

func SaveGoalMaxSteps added in v0.44.0

func SaveGoalMaxSteps(n int) error

SaveGoalMaxSteps persists the per-goal tool-call-round cap globally. 0 clears the override, letting it auto-scale from the context window again.

func SaveGoalNudge added in v0.52.0

func SaveGoalNudge(on bool) error

SaveGoalNudge persists the idle-nudge flag globally.

func SaveJudgeMaxOutput added in v0.48.0

func SaveJudgeMaxOutput(n int) error

SaveJudgeMaxOutput persists the goal judge's own max_tokens globally.

func SaveKnowledgeRetention added in v0.9.3

func SaveKnowledgeRetention(days int) error

SaveKnowledgeRetention persists the lesson-retention window (days) globally.

func SaveLocalModel added in v0.42.29

func SaveLocalModel(name string, l LLM) error

SaveLocalModel is SaveGlobal plus marking "local" as the active provider. Use this (not SaveGlobal) wherever choosing the local connection must ALSO make it the active one — the setup wizard's local-model path, which needs to flip Provider away from any previously configured cloud provider (see SaveProviders, the cloud path's equivalent). Plain SaveGlobal callers (/rename, /model on local, …) must NOT touch Provider: they run regardless of which provider is currently active, and forcing it to "local" there would silently switch a cloud-provider user back to local.

func SaveMaxHistory added in v0.44.0

func SaveMaxHistory(n int) error

SaveMaxHistory persists the cross-task session-memory message cap globally. 0 clears the override, letting it auto-scale from the context window again.

func SaveMaxStuckTurns added in v0.44.25

func SaveMaxStuckTurns(n int) error

SaveMaxStuckTurns persists the stuck/repeat-turn tolerance globally. 0 clears the override, falling back to internal/agent's own default.

func SaveMemory added in v0.40.2

func SaveMemory(mode string) error

SaveMemory persists the cross-task memory strategy globally ("" = summary default, "raw" = never auto-compact — see Config.Memory).

func SaveOffline added in v0.9.2

func SaveOffline(off bool) error

SaveOffline persists the offline-mode flag globally.

func SaveProviders added in v0.4.0

func SaveProviders(provider string, providers map[string]LLM) error

SaveProviders persists the active provider name and the external provider presets (which may include API keys — the file is written 0600).

func SaveReasoning added in v0.11.0

func SaveReasoning(m map[string]json.RawMessage) error

SaveReasoning persists the per-model reasoning params map globally.

func SaveReflectCfg added in v0.11.0

func SaveReflectCfg(disabled bool, profile string) error

SaveReflectCfg persists the reflection flag + profile globally.

func SaveRiskCheck added in v0.64.0

func SaveRiskCheck(on bool) error

SaveRiskCheck persists risk_check globally.

func SaveSessionBudget added in v0.20.0

func SaveSessionBudget(usd float64) error

SaveSessionBudget persists the per-session spend cap (USD) globally.

func SaveSpawn added in v0.8.0

func SaveSpawn(s SpawnPolicy) error

SaveSpawn persists the sub-agent spawn policy (approval mode + exec) globally.

func SaveTelemetry added in v0.62.0

func SaveTelemetry(on bool) error

SaveTelemetry persists the usage-statistics setting globally.

func SaveUsageRetention added in v0.5.0

func SaveUsageRetention(days int) error

SaveUsageRetention persists the usage-ledger retention window (days; 0 = keep forever).

func SaveWorkspacePolicy

func SaveWorkspacePolicy(workspace string, run RunPolicy, file FilePolicy) error

SaveWorkspacePolicy persists the run/file permission policy to the workspace config (<workspace>/.agent/config.json) so /permissions changes survive a restart. Any other keys already in that file are preserved.

func SetFileValue added in v0.26.0

func SetFileValue(path string, perm os.FileMode, dotted, raw string) error

SetFileValue sets the dotted-path key in the JSON config file at path to the value parsed from raw (valid JSON becomes its typed form — false→bool, 8→int, [..]/{..}→array/object; anything else is the literal string), preserving every other key. It refuses to write if the existing file is unparseable, and validates that the result is a well-formed Config with no unknown keys (so a typo like `goal_max_retunrs` is rejected rather than silently persisted). The read-merge-write cycle is locked (see mergeJSONFile) against concurrent callers racing on the same file.

func SetRunOnlyModel added in v0.74.0

func SetRunOnlyModel(before, after Config)

SetRunOnlyModel records the connection before -m turned it into after.

func SnippetsPath added in v0.28.0

func SnippetsPath() string

SnippetsPath is the global prompt-snippets store (/snip save+recall).

func StateDir added in v0.54.0

func StateDir(workspace string) string

StateDir is where the agent keeps its own runtime state for one workspace — the standing goal, learned facts and lessons, prompt history and saved sessions.

Deliberately OUTSIDE the workspace. It used to live in the project's own .agent/ directory, which put the agent's private state on the very filesystem the agent reads: observed live, a model listing the project found .agent/goal.json, read it, and began echoing the goal text back until the transport's repetition detector killed the run. State the agent writes for itself is not project content and must not be discoverable as project content — quite apart from it cluttering someone's repository.

Keyed by the workspace's absolute path, so two checkouts of the same project keep separate state and a moved directory starts clean rather than silently inheriting another tree's goal.

func SystemPromptPath added in v0.3.0

func SystemPromptPath() string

SystemPromptPath is the optional global system-prompt override file; if it (or a workspace .agent/system.md) exists, it replaces the built-in base prompt.

func UnsetFileValue added in v0.26.0

func UnsetFileValue(path string, perm os.FileMode, dotted string) error

UnsetFileValue removes the dotted-path key from the config file at path. A key that isn't present is a no-op (not an error). The read-merge-write cycle is locked (see mergeJSONFile) against concurrent callers racing on the same file.

func WorkspaceKeys added in v0.62.18

func WorkspaceKeys(workspace string) map[string]bool

WorkspaceKeys names the top-level settings this workspace's own config file sets — the ones that win over the global file on every load. The panel says so on those rows: a change saved globally there is undone at the next start. The connection (llm, providers) and telemetry are not among them: Load pins those to the global file whatever the workspace says.

func WorkspaceName added in v0.58.0

func WorkspaceName(workspace string) string

WorkspaceName is a workspace's readable basename, lowercased and reduced to filename-safe characters. It is the recognizable half of workspaceSlug, used on its own where a name a human reads and types matters more than uniqueness — a log file you tail by hand.

Types

type AgentProfile added in v0.6.0

type AgentProfile struct {
	Provider string `json:"provider,omitempty"`
	Model    string `json:"model,omitempty"`
	Prompt   string `json:"prompt,omitempty"`

	// External CLI agent fields (Kind "external"): run Command with Args in the
	// target dir as an autonomous local coding agent (codex, claude, aider…).
	// {task} in an arg is replaced by the task text (appended if no placeholder).
	// An empty Kind is a normal LLM profile, so old configs keep working.
	Kind    string   `json:"kind,omitempty"`
	Command string   `json:"command,omitempty"`
	Args    []string `json:"args,omitempty"`
	Timeout int      `json:"timeout,omitempty"` // seconds per launch; 0 = default (15 min)
}

AgentProfile is a named sub-agent target for the `agent` tool: which provider and model to run the sub-agent on. The task always comes from the delegating assistant; Prompt is an optional, persistent role note for that model.

type Config

type Config struct {
	Name      string         `json:"name,omitempty"`      // display name (renameable)
	Channel   string         `json:"channel,omitempty"`   // update channel: stable | nightly
	Color     string         `json:"color,omitempty"`     // TUI accent (ANSI code or /color name) — "" = default
	Provider  string         `json:"provider,omitempty"`  // active provider ("" / "local" = LLM below)
	LLM       LLM            `json:"llm"`                 // the local connection (the "local" provider)
	Providers map[string]LLM `json:"providers,omitempty"` // external provider presets
	Run       RunPolicy      `json:"run"`
	File      FilePolicy     `json:"file"`
	KBPath    string         `json:"kb_path,omitempty"`
	TracePath string         `json:"trace_path,omitempty"`
	UsagePath string         `json:"usage_path,omitempty"`
	// UsageRetentionDays auto-drops usage-ledger entries older than N days on
	// startup. 0 keeps history forever.
	UsageRetentionDays int `json:"usage_retention_days,omitempty"`
	// KnowledgeRetentionDays auto-drops learned lessons last seen over N days ago
	// on startup. 0 keeps them forever.
	KnowledgeRetentionDays int `json:"knowledge_retention_days,omitempty"`
	// GoalMaxReturns is the TTL for goal pursuit: if the model finalizes but the
	// goal isn't done (a plan still has open items), it's re-fed the goal and tries
	// again, up to this many returns. 0 disables (one run). Default 6.
	GoalMaxReturns int `json:"goal_max_returns,omitempty"`
	// GoalMaxSteps is the hard tool-call-round backstop for one goal pursuit. 0
	// (the default) auto-scales from the active connection's context window —
	// see cmd/agent's autoStepBudget — instead of a flat number oblivious to
	// how much room a big window actually affords a complex task.
	GoalMaxSteps int `json:"goal_max_steps,omitempty"`
	// MaxHistory caps how many cross-task session-memory messages
	// Agent.remember keeps before silently dropping the oldest (no summary —
	// Compact, not this, is the summarizing backstop). 0 (the default)
	// auto-scales from the active context window — see cmd/agent's
	// autoMaxHistory.
	MaxHistory int `json:"max_history,omitempty"`
	// MaxStuckTurns is how many consecutive unproductive turns (every tool call
	// failed, or the exact same call(s) repeated) earn ONE rethink nudge before
	// the run gives up; a still-unproductive turn right after the nudge stops
	// it. 0 (the default) uses internal/agent's own default. Reported live: a
	// model that hit the workspace jail from several different angles (an
	// absolute path, then a couple of cwd variants) got cut off before it had
	// room to actually work through the problem — this raises the ceiling for
	// anyone who wants their model to keep grinding longer before giving up
	// (a genuinely looping model still stops, just later; the outer step
	// budget is the real backstop against a truly runaway task).
	MaxStuckTurns int `json:"max_stuck_turns,omitempty"`
	// GoalNudge, when true (default), gives the model ONE push if it re-reads the
	// goal after a re-feed but then finishes without doing any work — instead of
	// silently giving up. Set false to accept a no-progress finish immediately.
	GoalNudge bool `json:"goal_nudge"`
	// RiskCheck, when true (default), stops a call the risk scorer flags for a
	// person even where the policy would run it without asking. Off, the scorer
	// only logs. No omitempty: false must round-trip.
	RiskCheck bool `json:"risk_check"`
	// SessionBudgetUSD caps estimated spend for one run of the process: once this
	// session's estimated cost reaches it, new tasks are refused until it's raised.
	// 0 disables the guard.
	SessionBudgetUSD float64 `json:"session_budget_usd,omitempty"`
	// Prices overrides the built-in per-model price estimates for /usage cost:
	// model-id substring → [input, output] USD per 1M tokens.
	Prices map[string][2]float64 `json:"prices,omitempty"`
	// Reasoning holds per-model reasoning controls, merged as raw params into the
	// chat request body. Keyed by "<provider>" (default for all its models) or
	// "<provider>/<model>" (overrides the provider default). The value is the
	// provider's own shape — e.g. {"reasoning_effort":"low"} (openai),
	// {"reasoning":{"effort":"low"}} (openrouter),
	// {"chat_template_kwargs":{"enable_thinking":false}} (qwen/lmstudio).
	Reasoning map[string]json.RawMessage `json:"reasoning,omitempty"`
	// Agents are named sub-agent profiles for the `agent` tool (delegate a task to
	// another model/provider): name → {provider, model, optional role prompt}.
	Agents map[string]AgentProfile `json:"agents,omitempty"`
	// Spawn gates the `agent` tool: approval mode before a sub-agent runs, and
	// whether sub-agents may run shell commands.
	Spawn SpawnPolicy `json:"spawn"`
	// Offline disables all internet egress (web tool, startup update check) and
	// makes anything that would reach the net fail fast with a clear message.
	// Local model calls (e.g. LM Studio on localhost) are unaffected.
	Offline bool `json:"offline,omitempty"`
	// Sandbox selects an OS-level containment layer for shell (`run`) commands,
	// UNDER the policy engine: off (default) | seatbelt (macOS) | landlock (Linux)
	// | auto (the platform's mechanism). It confines writes to the workspace even
	// for an allowed command; unsupported platforms run unconfined.
	Sandbox string `json:"sandbox,omitempty"`
	// UpdateCheck controls the best-effort startup "newer build available" notice.
	// On by default; set it false to silence the check WITHOUT going fully Offline
	// (which also disables the web tool) — for pinned or package-managed installs
	// that own their own upgrades. No omitempty: false must round-trip and show in
	// `config list`.
	UpdateCheck bool `json:"update_check"`
	// Telemetry is the anonymous daily usage report (adr/0016): nil means never
	// decided, which is off. First-run setup writes it on for a new install; a
	// build that finds an install without it writes it off — an update never
	// turns it on. Global only: a workspace can't turn it on, or off, for the
	// user (restored after the workspace merge in Load).
	Telemetry *bool `json:"telemetry,omitempty"`
	// ReflectDisabled skips the post-task reflection pass (lesson distillation).
	// Reflection is on by default; turn it off when a weak model loops there.
	ReflectDisabled bool `json:"reflect_disabled,omitempty"`
	// ReflectProfile, when set, runs the reflection pass on this agent profile
	// (a capable model) instead of the current one. Empty = the current model.
	ReflectProfile string `json:"reflect_profile,omitempty"`
	// McpServers are MCP servers the `mcp` proxy tool can use: name → stdio launch
	// spec. Empty = the mcp tool isn't offered.
	McpServers map[string]mcp.Server `json:"mcp_servers,omitempty"`
	SkillsPath string                `json:"skills_path,omitempty"`
	// Memory selects the cross-task session-memory strategy: "" / "summary"
	// (default) folds older turns into an LLM-written recap once the context
	// window passes CompactThreshold; "raw" never summarizes — turns stay
	// verbatim, and only the oldest ones are dropped outright (no paraphrase)
	// once there are too many to keep. An unrecognized value falls back to
	// "summary".
	Memory string `json:"memory,omitempty"`
	// CompactThreshold overrides the fraction of the context window at which
	// "summary" memory folds history into a recap. 0 = built-in default (0.75).
	CompactThreshold float64 `json:"compact_threshold,omitempty"`
	// JudgeMaxOutputTokens is the goal judge's OWN request max_tokens, 0 = the
	// same as the task model's. Reported live, with the log to prove it: nine
	// judge calls in one run, every one "finish_reason=length" — the judge was
	// reasoning sensibly about the evidence and being cut off before it ever
	// wrote a verdict. It inherits the task model's budget, which is sized for
	// producing code and tool calls, not for a check that thinks before
	// answering in one word.
	JudgeMaxOutputTokens int    `json:"judge_max_output_tokens,omitempty"`
	Workspace            string `json:"-"` // resolved absolute workspace root
}

Config is the merged runtime configuration.

func Default

func Default() Config

Default returns the baseline configuration: LM Studio on localhost, ask-by- default policies, a jail at the workspace root, and the protective deny floor.

func Load

func Load(workspace string) (Config, error)

Load merges the user config then the workspace config over Default(), unions the deny floor, and fills in default paths. Absent files are not errors.

type FilePolicy

type FilePolicy struct {
	Default    string   `json:"default"`
	Jail       string   `json:"jail"`
	AllowWrite []string `json:"allow_write"`
	DenyWrite  []string `json:"deny_write"`
}

FilePolicy gates file writes and confines all file ops to Jail (empty = no jail). AllowWrite/DenyWrite are globs applied to writes; reads are jail-checked only.

type LLM

type LLM struct {
	BaseURL     string  `json:"base_url"`
	Model       string  `json:"model"`
	Temperature float64 `json:"temperature"`
	// TopP is nucleus-sampling top_p (0 = unset — the server's own default; the
	// client omits the field below that, same convention as Temperature).
	TopP float64 `json:"top_p,omitempty"`
	// MaxOutputTokens caps how many tokens the SERVER is told it may generate
	// for one reply (the request's max_tokens) — 0 (the default) omits the
	// field entirely, leaving the server's own default in charge. That default
	// is often too small for a reasoning model's own thinking phase: observed
	// live, a local server cut a reply off (finish_reason=length) mid-reasoning
	// well before it ever reached an answer, at a context size nowhere near
	// the window limit — nothing to do with auto-compact, purely the server's
	// own conservative output cap. This is a request-visible knob, unlike
	// MaxSteps/MaxHistory (our own client-side bookkeeping) — the client
	// itself never limits generation length except via the (much larger)
	// runaway-abort cap in internal/llm's maxResponseTokens.
	MaxOutputTokens int `json:"max_output_tokens,omitempty"`
	// MaxSteps caps tool-call rounds per goal pursuit for THIS connection. 0
	// (the default) auto-scales from ContextWindow — see cmd/agent's
	// stepBudget/autoStepBudget — a flat number here would be oblivious to how
	// much room a much bigger (or smaller) window actually affords.
	MaxSteps int    `json:"max_steps"`
	APIKey   string `json:"api_key,omitempty"`
	// APIKeyCmd is a command whose trimmed stdout is the API key, for
	// endpoints that only issue short-lived keys. It runs on first use, again
	// after APIKeyTTL seconds (0: only when needed), and again once when the
	// server answers 401. The key it prints is never saved. When set it wins
	// over APIKey and the provider's environment variable. Machine-level only,
	// like the rest of the connection: a workspace config can't set it.
	APIKeyCmd []string `json:"api_key_cmd,omitempty"`
	APIKeyTTL int      `json:"api_key_ttl,omitempty"`
	// Type selects extra capabilities: "lmstudio" uses LM Studio's native API
	// (rich model list, context detection); anything else is plain OpenAI-compat.
	Type string `json:"type,omitempty"`
	// WireAPI picks the request format: "" or "chat" sends /chat/completions,
	// "responses" sends /responses (models served only there, e.g. newer GPTs
	// behind some gateways), "auto" reads the server's model list once and uses
	// /responses for a model listed as served only there.
	WireAPI WireAPI `json:"wire_api,omitempty"`
	// ContextWindow is the model's context size in tokens; auto-compact triggers
	// as the prompt approaches it. 0 disables auto-compact.
	// No omitempty: Default() sets this to a nonzero 8192, so an explicit 0
	// (clear the override, let auto-detect decide) must round-trip as a real
	// "context_window":0 in the file — omitempty would drop the key entirely,
	// and mergeFile's merge-over-Default() would then silently refill 8192.
	ContextWindow int `json:"context_window"`
	// ContextWindowManual marks ContextWindow as a deliberate user override (set
	// via the /config panel) rather than an auto-detected value, so a fresh
	// process (where the in-memory "already detected" flag always starts false)
	// knows not to let the next best-effort auto-detect pass silently overwrite
	// it. false is the correct zero-value default (an ordinary config predating
	// this field, or one that never had a manual override, should auto-detect
	// normally) — unlike ContextWindow, omitempty here doesn't need Default()'s
	// workaround.
	ContextWindowManual bool `json:"context_window_manual,omitempty"`
	// IdleTimeoutSeconds bounds how long a request waits with NO response/stream
	// data before it's aborted and retried. 0 uses the default (90s). Raise it for a
	// hosted reasoning model that can think silently (no streamed deltas) for longer.
	IdleTimeoutSeconds int `json:"idle_timeout_seconds,omitempty"`
	// RetryAttempts is how many times a TRANSIENT request failure (a 5xx, a
	// network error, a local server still reloading a model) is retried with
	// exponential backoff before the task gives up. 0 uses the default (8,
	// roughly half a minute of trying). Raise it for a server that reloads
	// slowly; lower it to fail fast when the endpoint is simply not there — a
	// dead server is not the model failing, and waiting out eight backoffs to
	// learn that is its own kind of wrong.
	RetryAttempts int `json:"retry_attempts,omitempty"`
	// DisableLoopDetection turns off the degenerate-repetition detectors (a
	// single character, or a whole phrase, repeating back to back) for this
	// connection. Enabled by default everywhere — a capable hosted model
	// essentially never trips these thresholds — but a weak local model prone
	// to this failure mode is exactly what it exists for, so a strong provider
	// (e.g. a hosted Claude/OpenAI connection) can opt out per-connection.
	DisableLoopDetection bool `json:"disable_loop_detection,omitempty"`
	// Extra is resolved per request (NOT persisted here): extra top-level body
	// params merged into the chat request — used for per-model reasoning controls
	// (see Config.Reasoning), whose shape varies by provider.
	Extra map[string]any `json:"-"`
}

LLM describes the OpenAI-compatible endpoint (LM Studio by default). The same shape points at OpenAI or a LiteLLM proxy by changing BaseURL/APIKey.

func ResolveProvider added in v0.4.0

func ResolveProvider(cfg Config, name string) (LLM, bool)

ResolveProvider returns the connection for an external provider name, merging a user preset over the built-in template and falling back to the env var for the key. Not for "local" (that's cfg.LLM). false if the name is unknown.

func (LLM) HasKey added in v0.69.0

func (l LLM) HasKey() bool

HasKey reports whether the connection has a way to authenticate: a key, or a command that prints one.

func (LLM) LMStudio added in v0.4.1

func (l LLM) LMStudio() bool

LMStudio reports whether this connection speaks LM Studio's native API.

type RunPolicy

type RunPolicy struct {
	Default string   `json:"default"`
	Allow   []string `json:"allow"`
	Deny    []string `json:"deny"`
	// TimeoutSeconds is the default wall-clock limit for a shell command. 0 uses
	// the built-in default (60s). A command may pass a larger per-call `timeout`.
	TimeoutSeconds int `json:"timeout_seconds,omitempty"`
	// Shell is the shell commands run in on Windows: "" (pwsh if installed,
	// else Windows PowerShell), "pwsh", "powershell" or "cmd". Ignored
	// elsewhere, where it is always sh.
	Shell string `json:"shell,omitempty"`
}

RunPolicy gates shell execution. Resolution per command: a Deny glob (matched anywhere) blocks, an Allow glob (whole command) auto-runs, otherwise Default.

type SpawnPolicy added in v0.8.0

type SpawnPolicy struct {
	Default string `json:"default"` // ask (default) | allow
	Exec    bool   `json:"exec"`    // give sub-agents the run (shell) tool
}

SpawnPolicy gates the `agent` tool. Default is the approval mode before a sub-agent runs (ask | allow — ask guards against runaway spawns, even local ones that still cost compute); Exec controls whether sub-agents get the run (shell) tool — off by default, the sharpest capability to hand an autonomous sub-agent.

type WireAPI added in v0.75.0

type WireAPI string

WireAPI is a connection's request format — see LLM.WireAPI.

Jump to

Keyboard shortcuts

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